M3-S1 — The expression engine
Section titled “M3-S1 — The expression engine”| Module | M3 — The read side |
| After this session you can | Predict what an expression returns on the server, the web and the phone, when it is recomputed, and how its result is checked and stored. |
| Time | Facilitated: 50 min · On your own: 50 min |
| Before you start | M2-S3: fields, storage types and casters. Larkspur Dev and Larkspur Lab as Rami Aziz; the Osos mobile app signed in to Larkspur Dev as maya.idris (your training provider supplies the account). |
| Go deeper | Engine: field expression · Criteria dialects · Field configuration: calculated values |
◆ Orientation (1 min) — A formula has three readers
Section titled “◆ Orientation (1 min) — A formula has three readers”In ACE you wrote expressions in six places in the designer and learned to lock a calculated field and choose its triggers (ACE M3-S2). A builder can stop there. A master cannot, because the questions that reach you are of another kind: “the overdue flag is wrong on half the work orders”, “the phone shows an empty date the browser fills in”, “this formula worked yesterday”. Each answer depends on how the engine evaluates an expression, when it decides to recompute one, and the fact that three different runtimes read the same formula. This session opens all three. M3-S5 uses the cross-runtime part for its parity audit.
▤ Concept (10 min) — Evaluate, check, store, recompute
Section titled “▤ Concept (10 min) — Evaluate, check, store, recompute”What an expression is to the engine
Section titled “What an expression is to the engine”An expression is stored as a string on the field’s definition (or on a reaction action, a step’s timing, a query parameter). The server’s engine, inside the data service, evaluates it as a JavaScript expression. Before it runs, the engine builds a small environment:
valueis the current record’svalueobject (M2-S3), sovalue.planned_dateis the stored planned date. In a query condition there is no record, andvalueis empty.scopeholds the built-in helpers: who is asking (scope.me(),scope.myGroups(),scope.myOrgUnit(),scope.currentSpace()), and when (scope.now(),scope.today(),scope.StartOfMonth()and their relatives). The date helpers take an offset such as'-1d','+3w'or'+2M': a sign, an amount and a unit (ddays,wweeks,Mmonths,yyears,h,m,s). A string with no sign leaves the date unchanged, and an unknown unit counts as days.- A few global objects a browser or Node.js program would have are deliberately hidden.
The string may be a plain expression (value.hours * 1.5), a function the engine then calls, or a
promise it waits for. If evaluation throws, the engine logs the expression and raises an expression
error (QUERY_EXPRESSION_ERROR); for a calculated field the error is not fatal to the save, the field
simply gets no value.
The design rule that follows. An expression runs as trusted code, with the authority of the
service that evaluates it. The platform is designed on the assumption that only builders, who
already hold Developer access to the entity, author expressions. So never build an expression from
text a user typed: not by concatenating a form value into a formula, not by letting a request field
choose the formula. If a business rule depends on user input, the expression reads the input as
value.<field>, it does not become part of the formula. You will apply this rule to every extension
you review in M5-S4 and M10.
Pointers: named values, parsed not evaluated
Section titled “Pointers: named values, parsed not evaluated”A pointer is a short name that starts with @ and stands for a value computed at the moment of
use: @me, @current_user, @myGroups, @today('-7d'), @StartOfMonth. Builders type them in
filters and defaults (ACD and ACE taught their use). On the 1.10
line a pointer is parsed, not evaluated: it must have the form @name, @name() or
@name('<amount>'), and the name must be one of the scope’s own helpers, which the engine then calls
directly. Anything else (a misspelling such as @Today, trailing text, an unknown name) is refused
with 400 INVALID_POINTER. That makes pointers a closed vocabulary: a filter can only name values
the platform defines.
Looking across a relation: resolveValue
Section titled “Looking across a relation: resolveValue”An expression often needs a value from a related record: the asset class of the asset a work order
points at. The engine does not fetch records in the middle of evaluation. Instead, a pre-processor
runs first: it finds each resolveValue('…') in the string, walks the path from the current record,
fetching the related record at each .:relation. hop, and writes the value it finds into the
expression as a literal before evaluation starts. So
resolveValue('value.asset.:relation.value.asset_class.:relation.value.class_name')becomes "Centrifugal pumps" in the text the engine evaluates. Fetched records are cached for five
minutes. If a hop is missing, that one look-up is skipped and the rest of the expression still runs.
Two consequences: a look-up costs one read per hop per evaluation (cached), and because the value is
pasted in before evaluation, the related value is part of the code that runs, which is one more
reason the rule above matters.
Checking and storing the result
Section titled “Checking and storing the result”When the result is for a field, the engine checks it against the field’s storage type: a Number field
needs a number, a Text field a string, a Date field something a date can be parsed from, a Reference a
{dataEntity, dataEntry} object. A result of the wrong type, or no result at all, is refused with
EXPRESSION_INVALID_RETURN_TYPE. A date result is formatted in the user’s time zone before it is
stored.
That check is not the same as the coercion applied to values people submit. Submitted values go
through the field type’s caster (M2-S3), which converts without refusing: a Number caster turns
"abc" into NaN and stores it; a Date caster stores an invalid date. So the same garbage is
refused when an expression produces it and stored when a person or an integration sends it.
When you see NaN in a stored record, look for a submitted value, not a formula.
| Path | Applies to | On a bad value |
|---|---|---|
| Expression result check | Calculated fields, defaults, reaction values | Refused (EXPRESSION_INVALID_RETURN_TYPE) |
| Caster | Values submitted by forms, the API, imports | Converted silently, possibly to NaN or an invalid date |
When a calculated field is recomputed
Section titled “When a calculated field is recomputed”The engine evaluates; it never decides when. That decision is made per field, on each save, from the field’s calculated-value options that ACE taught you to set: the triggers (On page load, On save, On entry change, On field change with its watched fields) and the Execution Scope (new, existing or all records). On the server, for each calculated field on each save:
- If it has an On field change trigger, it is recomputed only if one of its watched fields actually changed in this save (compared deeply, empty and missing counted as equal).
- Otherwise, if it has no trigger that applies on save (only On page load, for example), the server does not recompute it at all.
- Otherwise the scope decides: new records only, existing records only, or all.
flowchart TD
S["a record is saved"] --> F{"On field change<br/>trigger?"}
F -->|"yes"| W{"a watched field<br/>changed?"}
W -->|"no"| K["keep the stored value"]
W -->|"yes"| E["evaluate and store"]
F -->|"no"| T{"a save-time<br/>trigger?"}
T -->|"no"| K
T -->|"yes"| SC{"scope matches<br/>new or existing?"}
SC -->|"yes"| E
SC -->|"no"| K
What to notice: nothing recomputes a stored value because time passed or because another record changed. A value that depends on “today” or on a related record is only as fresh as the last save that recomputed it.
There is no dependency graph. The engine does not work out that one calculated field reads another and order them; a calculated field that reads another calculated field sees whatever value that field has at the moment it is processed. Keep calculated fields independent of each other, or make the dependency explicit with watched fields and test it.
Three runtimes, one formula
Section titled “Three runtimes, one formula”The same stored expression is evaluated in three places: the server’s engine (above), the web portal (to show values live in a form), and the mobile app (a JavaScript engine inside the Flutter app). They share the string and the storage types, but each implements its own scope, casting and checks:
| Runtime | Role | Known difference |
|---|---|---|
| Server | The source of truth: re-evaluates on save | Formats date results in the user’s time zone |
| Web portal | A live preview while the form is open | Refuses a bad number that the server’s caster would store as NaN |
| Mobile app | A live preview on the phone | The identity and date helpers of scope are not defined, so scope.now() or scope.me() give nothing |
One more runtime hides inside the platform: the workflow service has its own expression evaluator for conditional targets and expression-based step owners (M4-S3, M4-S4). It overlaps with the data service’s engine but is separate, so a formula that works as a field default can behave differently as a routing condition. Test a routing expression where it runs.
The contract is simple and you can rely on it: what the server stores on save is the value; anything a client shows before that is a preview. Your designs should never depend on a client-side result being right.
▶ Guided demo (7 min) — Read three formulas the way the engine does
Section titled “▶ Guided demo (7 min) — Read three formulas the way the engine does”In Larkspur Lab, with the API window open.
-
Read the calculated-value options of the three calculated fields on Work Orders:
Terminal window curl -s -H "x-app-token: $TOKEN" "$BASE/api/v1/entities/work_orders" | jq '.result.fields[]| select(.options.calculatedValueOptions or .options.defaultValue)| {name: .normalizedName, type: .dataType, calc: .options.calculatedValueOptions,default: .options.defaultValue}' -
Overdue (
overdue, Boolean):value.planned_date ? value.planned_date < scope.today() : false, trigger On save, scope All entries. Say aloud (or write) when the server recomputes it: on every save of any work order, and never otherwise. -
Asset Class (
asset_class_name, Text):resolveValue('value.asset.:relation.value.asset_class.:relation.value.class_name'), trigger On field change watchingasset, scope All entries. It is recomputed only when a save changes the asset, and it costs two look-ups when it is. -
Target Finish (
target_finish, Date): an Advanced default valuescope.today('+2d'), trigger On page load, scope New entries. The server never recomputes it on save; whatever the form sends is stored.Screenshot pending The Work Orders entity designer with the Asset Class field's settings open: Lock Field on, an Advanced expression, the On field change trigger watching Asset, and All entries What to notice: the watched field is written here, by the builder. The engine does not read the expression to find out what it depends on.
⛏ Lab (23 min) — Predict, then verify, on three runtimes
Section titled “⛏ Lab (23 min) — Predict, then verify, on three runtimes”Goal. For each of the three formulas, a written prediction of what the server, the web portal and the phone will show and store, then the evidence that confirms or corrects it.
Before you start. Larkspur Dev in a browser as Rami Aziz; the mobile app as maya.idris on Larkspur
Dev; Larkspur Lab’s record store for the stored values (the seed is the same in both, and Part C uses
the Lab). A file m3-s1-predictions.md with a table: formula × (server on save, web form, phone form).
Part A: predict
- Fill the table for all three formulas before touching anything. For Target Finish, predict what is shown when a new work order form opens, and what is stored if the work order is created on the phone.
Part B: verify on the web and the phone
- In Larkspur Dev’s portal, open Asset Maintenance › Work Orders and start a new work order. Note what Target Finish shows. Cancel.
- On the phone, start a new work order in the same module. Note what Target Finish shows.
- On the phone, create Check coupling alignment on P-102 with asset P-102, leaving Target Finish as it is, and save.
- In the browser, open it and note the stored Target Finish, Asset Class and Overdue.
Part C: verify recomputation on the server
- In Larkspur Lab’s portal, open Replace mechanical seal on P-101. Its Planned Date is in the past (the seed set it to yesterday) and nobody has saved it since. Note Overdue.
- Read its stored value:
db.work_orders.findOne({"value.title": /P-101/}, {"value.overdue": 1, "value.planned_date": 1, updateInfo: 1}). - Change only its Description and save. Read the stored value again.
- Change its Asset to P-102 and save. Read Asset Class before and after in the record store.
- Change its Description again and save. Did Asset Class change this time?
Part D: conclude
- Mark each prediction right or wrong, and for each wrong one write the Concept section that explains it.
- Write one rule for Larkspur’s builders about Overdue: when is the stored value trustworthy, and what would make it so for a dashboard that reads it?
Check.
- All nine predictions were written before Part B.
- Part B records what the web and the phone showed for Target Finish, and what was stored for the phone-created work order.
- Part C shows Overdue stale before the save in step 8 and recomputed after it.
- Part C shows Asset Class recomputed by the asset change and left alone by the description change.
- Your rule for Overdue names the cause (recomputed only on save) and a remedy.
Pass condition. All five checks hold.
If something goes wrong
| What you see | What to do |
|---|---|
| The mobile app cannot reach Larkspur Dev | Check the app’s address and the account with your training provider. Without a phone, do Parts A, C and D, and mark the phone column “not verified”. |
Overdue is already true before step 8 | Someone saved the work order after its planned date passed (perhaps you, in M2-S1). Use another work order whose Planned Date is past and that you have not touched, or reset the seed. |
| Asset Class stays empty after step 9 | The asset or its class has no Class Name in your seed; read the path’s two records in the record store to find the missing value. |
| The save in step 8 is refused | The work order is obsolete from M2-S3’s Part C; upgrade it first, or reset the seed. |
Model answer
Target Finish. Web: today plus two days, filled when the form opens (the web defines scope.today).
Phone: empty, because the mobile runtime does not define the date helpers of scope. Stored for the
phone-created work order: empty, because the field’s only trigger is On page load and the server
does not recompute a field without a save-time trigger; it stores what the phone sent.
Asset Class. Web and phone show it after the asset is chosen, as a preview (the phone shows it only if
its runtime resolves the look-up; treat the stored value as the answer). Stored: Centrifugal pumps for
P-102’s class, written by the server on save because the watched field asset changed. In Part C, the
asset change recomputed it; the description change left it as it was.
Overdue. Before step 8 the stored value is false although the planned date is past: nothing
recomputes a stored value because a day passed. After step 8’s save (any save, with scope All
entries), it is true.
Rule. “Overdue is only as fresh as the work order’s last save. A dashboard must not read it
directly: filter on Planned Date before @today instead, which is evaluated when the dashboard is
read (M3-S3), or keep Overdue current with a nightly scheduled job that saves each open work order
(M4-S1).”
◇ Worked scenario (2 min) — “The formula worked yesterday”
Section titled “◇ Worked scenario (2 min) — “The formula worked yesterday””Sara Qasim’s team reports that Approval Deadline on purchase requests, a calculated Date field with
the formula scope.today('+5d'), “randomly” shows the wrong day: some requests created in the
afternoon get a deadline one day earlier than expected. Reason it through before reading each step.
Step 1: where does it run, and when? The field is locked, with trigger On save and scope New entries. So the stored value is computed once, by the server, when the request is first saved. Web and phone previews do not matter: only the server’s result is stored.
Step 2: what is “today” on the server? The date helpers compute the day on the server, and the
engine’s today() and StartOf… helpers do not apply the user’s time-zone offset to the day they
compute; only the final formatting of a date result uses it. Larkspur works in a time zone ahead of
the server’s. For a request saved late in the local afternoon, the server’s “today” can still be the
previous day.
Step 3: confirm before you report. You save two test requests in Larkspur Dev, one in the morning and one late in the afternoon, and read both stored values in Larkspur Lab’s record store. The afternoon one is a day earlier. Evidence, not a guess.
Step 4: the fix. Not a different formula alone. Either compute the deadline from a value that is already in the user’s terms (the request’s own submitted date, stored by the platform), or move the rule to the workflow step’s Timing, which counts in Larkspur’s working calendar (M4-S4). You record the time-zone behaviour as a known limit in the program’s standard (M10-S1), because every date formula built on “today” shares it.
✓ Practice (6 min) — Predict the engine
Section titled “✓ Practice (6 min) — Predict the engine”A calculated Number field Total Hours has the trigger On field change watching Hours and Overtime. A reaction updates only Rate on a record. What happens to Total Hours?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
An integration posts "Quantity": "twelve" to a Number field. A calculated Number field elsewhere
returns "twelve" from its formula. What is stored in each case?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
A saved filter uses @Today('-7d'). On the 1.10 line, what does the server do with it?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
A builder proposes a “custom rule” field where a planner types a formula, which a reaction then uses as the expression for a work order’s priority. What do you say?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
A formula shows the right value in the browser and on the phone, but a different one is stored after saving. Which runtime do you trust, and why?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
↺ Recap (1 min) — Formulas as the engine sees them
Section titled “↺ Recap (1 min) — Formulas as the engine sees them”You can now explain how the server evaluates an expression and what it can see, how pointers and relation look-ups are resolved first, how results are checked differently from submitted values, when a calculated field is and is not recomputed, and why the phone and the browser may disagree with what is stored.
Next. M3-S2 opens the query engine: how a filter, including the pointers you met here, becomes a database query, and in what order a list read does its work.