08 Database query functions

8.1. defquery

Macro

(defquery name [params*] query-map) → name

Defines a named function that queries the database snapshot attached to its evaluation. A result contract may follow the parameter list. Calling the function returns a list of maps unless the query requests positional tuples.

A host can subscribe to an exported query. The subscription delivers the query's result, then a new result after each commit that changes a field that the query reads. The ABI's queries/subscribe request and the generated SDK's SubscribeTo methods do this. An evaluation returns one value, so DUST code cannot subscribe.

To evaluate a file against an existing database, name the database in a configuration file such as {plugins {stdlib true database {path "app.db"}}}:

stardust eval --config app.dust query.dust

Top-level locals persist between the file's forms. Each evaluation reads a fresh snapshot. Plugin selection enables the same services as ordinary evaluation. Returned values remain usable after the database closes. Without database storage, a query returns #err <database no>. Open the database with the database plugin and its path or temporary setting.

The query executor chooses a default clause order. The optional planner plugin may choose a different order as it learns. Row order is defined only by order-by. Queries with one field pattern, a limit or offset without order-by, a window call, an each expansion, or a schema clause are not reordered. The ABI's plans/explain request reports the chosen order without running the query.

The examples below read the illustrative Dune database.

8.1.1. Example database

These illustrative records use Dune characters; ages, assignments and transactions are sample data. The id identifies an entity, tags describe membership, and #link refers to another entity. The steps lists contain patrol steps in execution order.

[
 {<atreides mentor> id 1 name "Duncan Idaho" age 37 station "Arrakeen" commander #link 2 steps ["scout" "patrol" "report"]}
 {<atreides> id 2 name "Leto Atreides" age 45 station "Arrakeen" steps ["patrol" "report"]}
 {<fremen> id 3 name "Stilgar" age 29 station "Sietch Tabr" steps ["travel" "watch"]}
]

Unless stated otherwise, the examples read this initial snapshot. Every input and result below is checked by the query conformance tests.

8.1.2. Select fields

Return the name, age and commander of each Atreides member. [?e <atreides>] binds ?e to each matching entity. project {?e <name age commander>} selects those fields from the entity bound to ?e. The map key names the query binding; its value describes the result.

(defquery example [] {where [[?e <atreides>]]
           project {?e <name age commander>}})
(example)

Result:

[{name "Duncan Idaho" age 37 commander #link 2}
 {name "Leto Atreides" age 45 commander null}]

Leto Atreides has no commander, so the projected commander field is null.

8.1.3. Match tags

Return the names of Atreides members:

(defquery example [] {where [[?e <atreides>]]
           project {?e <name>}})
(example)

Result:

[{name "Duncan Idaho"} {name "Leto Atreides"}]

Require both atreides and mentor membership:

(defquery example [] {where [[?e <atreides mentor>]]
           project {?e <name>}})
(example)

Result:

[{name "Duncan Idaho"}]

Require atreides membership and the absence of the mentor tag:

(defquery example [] {where [[?e <atreides !mentor>]]
           project {?e <name>}})
(example)

Result:

[{name "Leto Atreides"}]

Select everyone without a mentor tag:

(defquery example [] {where [[?e <!mentor>]]
           project {?e <name>}})
(example)

Result:

[{name "Leto Atreides"} {name "Stilgar"}]

Negated tags test absence, not a stored false value. A tag that has never been assigned is absent from every entity:

(defquery example [] {where [[?e <!unassigned>]]
           project {?e <name>}})
(example)

Result:

[{name "Duncan Idaho"} {name "Leto Atreides"} {name "Stilgar"}]

Requiring that same tag selects no entities:

(defquery example [] {where [[?e <unassigned>]]
           project {?e <name>}})
(example)

Result:

[]

8.1.4. Match field values

Return the names of people stationed in Arrakeen. A field pattern is [?entity field value]:

(defquery example [] {where [[?e station "Arrakeen"]]
           project {?e <name>}})
(example)

Result:

[{name "Duncan Idaho"} {name "Leto Atreides"}]

The middle slot always names a literal field: station and "station" select the same field. It does not read a local named station. Strings in the value slot must be quoted. A symbol such as ?name is a query variable; "?name" is literal text.

To select people aged at least 40, bind the stored age and compare it:

(defquery example [] {where [[?e age ?age] (>= ?age 40)]
           project {?e <name age>}})
(example)

Result:

[{name "Leto Atreides" age 45}]

The repeated ?e makes both clauses refer to the same entity. Numeric comparisons require operands of the same numeric kind.

A where item that is not a field pattern, negated pattern, optional, schema or each clause is a predicate. It can call pure functions with query variables, declared inputs, literals and captured locals. A predicate cannot call a host-effect function. A row is kept when the result is truthy; an #err result fails the query. Two-operand = and comparisons/not= inside predicates return false and true, respectively, when operand kinds differ. Only a simple first predicate can use an index.

8.1.5. Select complete entities with a schema

Use [schema schema-value ?entity] to check each complete entity document. The clause can enumerate entities or check an entity bound by another clause. Each schema target listed in in is restricted to its supplied entity, including queries with several targets. For example, ?a and ?b are both bound here:

{find [?a ?b] <tuples>
 in [?schema ?a ?b]
 where [[?a active ?state] [?b active ?state]
        [schema ?schema ?a] [schema ?schema ?b]]
 order-by [?a ?b]}

Open shapes permit fields that the schema does not name.

(defquery example [] {where [[schema {name string? age int?} ?e]]
           project {?e <name>}})
(example)

Result:

[{name "Duncan Idaho"} {name "Leto Atreides"} {name "Stilgar"}]

Grouping, ordering, and paging run after the schema filter. A missing schema value is an error, including when another clause selects no rows. A schema value that is an error, such as an invalid schema, is the query's error: [schema {name <nope>} ?e] fails with #err <invalid schema> and the message "<nope> has no nope? predicate".

8.1.6. Follow a link

Return each Atreides member's name and their commander's name. The nested commander <name> selection follows the commander link:

(defquery example [] {where [[?e <atreides>]]
           project {?e {<name> commander <name>}}})
(example)

Result:

[{name "Duncan Idaho" commander {name "Leto Atreides"}}
 {name "Leto Atreides" commander {name null}}]

When the link is absent, the nested name is null. Nested pointers are relative to that linked entity: commander {label /name} names its field label.

8.1.7. Rename a returned field

Return the mentor's commander name under commander-name. A JSON Pointer supplies the source path:

(defquery example [] {where [[?e <mentor>]]
           project {?e {commander-name /commander/name}}})
(example)

Result:

[{commander-name "Leto Atreides"}]

The JSON Pointer /commander/name follows the link. A quoted "/commander/name" would return that literal string. Selection tags can be mixed with aliases: project {?e {<name> commander-name /commander/name}}.

8.1.8. Read an ordered list

Return the first patrol step for the mentor. JSON Pointer list indexes start at zero:

(defquery example [] {where [[?e <mentor>]]
           project {?e {first-step /steps/0}}})
(example)

Result:

[{first-step "scout"}]

To return every step as a separate row, use [each ?step] in the value slot. It binds ?step to each element of the stored list. The each symbol marks list expansion in this pattern slot. find returns the matched variables; their names become result keys. Sorting by person name retains each person's step order:

(defquery example [] {find [?name ?step]
           where [[?e name ?name] [?e steps [each ?step]]]
           order-by [?name]})
(example)

Result:

[{name "Duncan Idaho" step "scout"}
 {name "Duncan Idaho" step "patrol"}
 {name "Duncan Idaho" step "report"}
 {name "Leto Atreides" step "patrol"}
 {name "Leto Atreides" step "report"}
 {name "Stilgar" step "travel"}
 {name "Stilgar" step "watch"}]

Each step contributes a row, including repeated steps.

8.1.9. Sort and paginate

Return all names in alphabetical order. The field pattern binds the name so order-by can sort on it:

(defquery example [] {where [[?e name ?name]]
           order-by [?name]
           project {?e <name>}})
(example)

Result:

[{name "Duncan Idaho"} {name "Leto Atreides"} {name "Stilgar"}]

To sort from highest to lowest, tag the order term with #desc: order-by [#desc ?value]. For example, return the oldest person first:

(defquery example [] {where [[?e age ?age]]
           order-by [#desc ?age]
           project {?e <name age>}})
(example)

Result:

[{name "Leto Atreides" age 45}
 {name "Duncan Idaho" age 37}
 {name "Stilgar" age 29}]

To request the second name only, skip one row and return one row. Use the entity ID to break ties between equal names:

(defquery example [] {where [[?e name ?name]]
           order-by [?name ?e]
           offset 1 limit 1
           project {?e <name>}})
(example)

Result:

[{name "Leto Atreides"}]

offset and limit apply before projection. Use order-by when the result order matters.

8.1.10. Supply a threshold

Use a lexical local when the surrounding expression supplies the minimum age. minimum is that local; ?age is the matched database value:

(defquery example [minimum]
  {where [[?e age ?age] (>= ?age minimum)]
             project {?e <name age>}})
(example 40)

Result:

[{name "Leto Atreides" age 45}]

When the caller supplies the threshold as an evaluation binding, use :minimum. With these bindings:

{minimum 40}
(defquery example [] {where [[?e age ?age] (>= ?age :minimum)]
           project {?e <name age>}})
(example)

Result:

[{name "Leto Atreides" age 45}]

8.1.11. Count matching entities

Count people who are both Atreides members and mentors:

(defquery example [] {find [(count ?e)]
           where [[?e <atreides mentor>]]})
(example)

Result:

[{count 1}]

(count ?e) produces the result key count. Without grouping, an empty match returns [{count 0}].

8.1.12. Count by station

Return a count for each station. Including ?station alongside the aggregate makes it the group key:

(defquery example [] {find [?station (count ?e)]
           where [[?e station ?station]]
           order-by [?station]})
(example)

Result:

[{station "Arrakeen" count 2} {station "Sietch Tabr" count 1}]

To keep only stations with more than one person, filter the completed counts with having:

(defquery example [] {find [?station (count ?e)]
           where [[?e station ?station]]
           having [(> ?count 1)]})
(example)

Result:

[{station "Arrakeen" count 2}]

The aggregate result is available to having as ?count.

8.1.13. Count people with and without a commander

Count people by commander, including those who have none. Here the commander participates in grouping before projection. optional preserves people whose commander field is absent and binds their commander to null:

(defquery example [] {find [?commander (count ?e)]
           where [[?e name ?name] (optional [?e commander ?commander])]})
(example)

Result:

[{commander #link 2 count 1} {commander null count 2}]

Without optional, the commander pattern would exclude Leto Atreides and Stilgar before they could be counted. To return fields without grouping or filtering on them, use project as in the first example.

8.1.14. Rank rows inside a group

A window call in find computes one value per row from the rows around it. It is a function call whose last argument is an options map: (rank {partition-by [?station] order-by [#desc ?age]}). A known function name with a trailing map is a window call only when the map is empty or holds only as, partition-by, order-by and frame. Any other map leaves an ordinary call: (first {a 1}) calls first on the map, and the misspelled (rank {partiton-by [?t]}) reports rank as a call to a function that does not exist. partition-by groups the rows; order-by sorts each group; the result key is the function name. Return each person's age rank within their station, oldest first:

(defquery example [] {find [?name ?station (rank {partition-by [?station] order-by [#desc ?age]})]
           where [[?e name ?name] [?e station ?station] [?e age ?age]]
           order-by [?station ?name]})
(example)

Result:

[{name "Duncan Idaho" station "Arrakeen" rank 2}
 {name "Leto Atreides" station "Arrakeen" rank 1}
 {name "Stilgar" station "Sietch Tabr" rank 1}]

Without partition-by, one partition holds every row. An order term is ?age (ascending) or #desc ?age; no other spelling is accepted, here or in the query's order-by. Equal order values share a rank; dense-rank numbers distinct values; row-number numbers every row. A frame bounds the rows a fold reads. With order-by, the default frame runs from the partition's start to the current row. Without order-by, the frame is the whole partition. Return a running total of ages in name order:

(defquery example [] {find [?name ?age (sum ?age {order-by [?name]})]
           where [[?e name ?name] [?e age ?age]]
           order-by [?name]})
(example)

Result:

[{name "Duncan Idaho" age 37 sum 37}
 {name "Leto Atreides" age 45 sum 82}
 {name "Stilgar" age 29 sum 111}]

frame {rows {from unbounded-preceding to unbounded-following}} reads the whole partition despite an order-by; frame {rows {from unbounded-preceding to current-row}} spells the running frame. lag and lead read a value from an earlier or later row of the partition. The second argument is the row distance (default 1); the third is the value for rows that have no such neighbor (default null):

(defquery example [] {find [?name ?age (lag ?age 1 0 {order-by [?name]})]
           where [[?e name ?name] [?e age ?age]]
           order-by [?name]})
(example)

Result:

[{name "Duncan Idaho" age 37 lag 0}
 {name "Leto Atreides" age 45 lag 37}
 {name "Stilgar" age 29 lag 45}]

Folds without order-by read their whole partition. Return the size and mean age of each person's station beside the person:

(defquery example [] {find [?name (count ?e {partition-by [?station]}) (mean ?age {partition-by [?station]})]
           where [[?e name ?name] [?e station ?station] [?e age ?age]]
           order-by [?name]})
(example)

Result:

[{name "Duncan Idaho" count 2 mean 41.0}
 {name "Leto Atreides" count 2 mean 41.0}
 {name "Stilgar" count 1 mean 29.0}]

The window functions:

Function Value per row
(row-number {...}) Position in the partition, from 1.
(rank {...}) Position of the first row with equal order values.
(dense-rank {...}) Count of distinct order values up to this row.
(percent-rank {...}) (rank - 1) / (rows - 1); 0.0 for one row.
(cume-dist {...}) Rows with order values at or before this one, divided by the partition size.
(lag ?v [n [default]] {...}) ?v from n rows earlier.
(lead ?v [n [default]] {...}) ?v from n rows later.
(first ?v {...}), (last ?v {...}) ?v from the frame's first or last row.
(nth ?v n {...}) ?v from the frame's n-th row, or null.
(count ?v {...}) Rows in the frame.
(sum ?v {...}), (mean ?v {...}), (min ?v {...}), (max ?v {...}) Folds over the frame, with the aggregate rules.

The rank family, lag, lead, first, last and nth require order-by; so does the running frame. Rows with equal order values keep entity order. Arguments are bound variables, inputs or expressions over them: (sum (* ?age 2) {order-by [?name]}). Use as ?age-rank in the options to name a window result. It sets the result key to age-rank and binds ?age-rank for later stages. Without as, a unique call keeps its function name: (rank {...}) binds ?rank. Repeated implicit names require <tuples> and do not introduce a binding. Use distinct as names to reuse those values. A window name cannot shadow a row binding, aggregate alias or input.

where selects input rows before ranking. having filters completed window results without renumbering them. Return the two oldest people, with reusable ranks:

(defquery example [] {find [?name (rank {as ?age-rank order-by [#desc ?age]})]
           where [[?e name ?name] [?e age ?age]]
           having [(<= ?age-rank 2)]
           order-by [?age-rank]})
(example)

Result:

[{name "Leto Atreides" age-rank 1} {name "Duncan Idaho" age-rank 2}]

Other result expressions and query order-by can read these bindings, for example, (+ ?age-rank 10) and order-by [?age-rank]. Window calls run in find order. A later window can read an earlier result, for example (lag ?age-rank {as ?previous-rank order-by [?name]}). Self-references and forward references are errors. All windows run before having, including when its predicates read only aggregate values.

With aggregates, windows read the grouped rows. Count the people at each station, then rank those counts:

(defquery example [] {find [?station (count ?e) (rank {as ?size-rank order-by [#desc ?count]})]
           where [[?e station ?station]]
           order-by [?size-rank]})
(example)

Result:

[{station "Arrakeen" count 2 size-rank 1} {station "Sietch Tabr" count 1 size-rank 2}]

Only grouping variables and aggregate aliases remain available after aggregation. Windows also compose with project. Projection determines the entire result shape. Include window bindings explicitly among its fields:

(defquery example [] {find [(rank {as ?age-rank order-by [#desc ?age]})]
           where [[?e name ?name] [?e age ?age]]
           order-by [?age-rank]
           project {?e {<name> commander <name> age-rank ?age-rank}}})
(example)

Result:

[{name "Leto Atreides" commander {name null} age-rank 1}
 {name "Duncan Idaho" commander {name "Leto Atreides"} age-rank 2}
 {name "Stilgar" commander {name null} age-rank 3}]

Windows over a join see every matched pair. Count how many people share each person's station, including that person:

(defquery example [] {find [?name (count ?b {as ?neighbors partition-by [?name]})]
           <distinct>
           where [[?a name ?name] [?a station ?station] [?b station ?station]]
           order-by [?name]})
(example)

Result:

[{name "Duncan Idaho" neighbors 2} {name "Leto Atreides" neighbors 2} {name "Stilgar" neighbors 1}]

The query runs where, aggregation when present, windows, having, final ordering, distinct/offset/limit and projection in that order. Window calls, partition variables and order variables have no fixed count. The evaluation's CPU and memory budget bounds their cost. A query too large to compile fails with #err <invalid program> and the message query is too large to compile; a query with 500 window calls is one example, and 260 runs.

8.1.15. Match an optional group

Use one optional form when related fields must match together. This query binds both the commander link and the commander's name, or neither:

(defquery example [] {find [?name ?commander ?commander-name]
           where [[?e name ?name]
                  (optional [?e commander ?commander]
                            [?commander name ?commander-name])]
           order-by [?name]})
(example)

Result:

[{name "Duncan Idaho" commander #link 2 commander-name "Leto Atreides"}
 {name "Leto Atreides" commander null commander-name null}
 {name "Stilgar" commander null commander-name null}]

optional accepts one or more field patterns. Each pattern's entity must already be bound by a required pattern or an earlier optional field. Optional patterns cannot yet depend on bindings introduced by [each ?item]. If any pattern fails, the incoming row remains and all bindings introduced by that group become null. Bindings from outside the group retain their values.

For example, require both a commander and that commander's superior:

(defquery example [] {find [?name ?commander ?superior]
           where [[?e name ?name]
                  (optional [?e commander ?commander]
                            [?commander commander ?superior])]
           order-by [?name]})
(example)

Result:

[{name "Duncan Idaho" commander null superior null}
 {name "Leto Atreides" commander null superior null}
 {name "Stilgar" commander null superior null}]

Duncan has a commander, but Leto has no commander field. The second pattern fails, so neither link is returned for Duncan.

Separate optional forms preserve partial matches:

(defquery example [] {find [?name ?commander ?superior]
           where [[?e name ?name]
                  (optional [?e commander ?commander])
                  (optional [?commander commander ?superior])]
           order-by [?name]})
(example)

Result:

[{name "Duncan Idaho" commander #link 2 superior null}
 {name "Leto Atreides" commander null superior null}
 {name "Stilgar" commander null superior null}]

Here Duncan's first optional group succeeds. Failure in the second group leaves his commander link intact. Use this distinction when these bindings participate in filtering, grouping or ordering. To only return nested fields, use project.

8.1.16. Select either of two tags

Return the names of people with the Atreides or Fremen tag. This form tests two possibly absent tag fields. The optional reads retain people who have only one tag, and or requires at least one:

(defquery example [] {find [?name]
           where [[?e name ?name]
                  (optional [?e atreides ?atreides])
                  (optional [?e fremen ?fremen])
                  (or ?atreides ?fremen)]
           order-by [?name]})
(example)

Result:

[{name "Duncan Idaho"}
 {name "Leto Atreides"}
 {name "Stilgar"}]

Two required tag patterns would instead require both tags.

8.1.17. Select an absent field

Return the names of people without a commander field. not rejects an entity when its enclosed field pattern matches:

(defquery example [] {where [[?e name ?name] (not [?e commander ?commander])]
           project {?e <name>}})
(example)

Result:

[{name "Leto Atreides"} {name "Stilgar"}]

Use negated tags for tag membership and not for an arbitrary field pattern.

8.1.18. Read an earlier snapshot

The initial data is transaction 1, recorded at #utc "2026-01-01T00:00:00Z". Transaction 2, recorded one day later, changes Duncan Idaho's age, removes his mentor tag and creates Chani:

[{<!mentor> id 1 age 38} {id 4 name "Chani"}]

Writing a false tag retracts it, just as writing null retracts a field.

Read Duncan Idaho's age at transaction 1 with as-of:

(defquery example [] {where [[?e name "Duncan Idaho"]]
           as-of 1
           project {?e <age>}})
(example)

Result:

[{age 37}]

Read it at the second commit's UTC time:

(defquery example [] {where [[?e name "Duncan Idaho"]]
           as-of #utc "2026-01-02T00:00:00Z"
           project {?e <age>}})
(example)

Result:

[{age 38}]

The tag removal changes which Atreides members are not mentors:

(defquery example [] {where [[?e <atreides !mentor>]]
           as-of 2
           project {?e <name>}})
(example)

Result:

[{name "Duncan Idaho"} {name "Leto Atreides"}]

A projection reads the same snapshot. A retracted tag projects as null, the same as a tag that was never written:

(defquery example [] {where [[?e <atreides>]]
           as-of 2
           project {?e <name mentor>}})
(example)

Result:

[{name "Duncan Idaho" mentor null} {name "Leto Atreides" mentor null}]

Before the removal, Duncan Idaho's projection has the tag:

(defquery example [] {where [[?e <atreides>]]
           as-of 1
           project {?e <name mentor>}})
(example)

Result:

[{<mentor> name "Duncan Idaho"} {name "Leto Atreides" mentor null}]

At transaction 2, the absence-only query also includes Chani:

(defquery example [] {where [[?e <!mentor>]]
           as-of 2
           project {?e <name>}})
(example)

Result:

[{name "Duncan Idaho"} {name "Leto Atreides"} {name "Stilgar"} {name "Chani"}]

All linked projection reads use the same snapshot. A time before the first commit sees an empty database. With the retention plugin, the database removes old versions, and a read before the oldest kept version of a fact reads that version (History retention).

8.1.19. Several versions of a fact

Every write adds a version of a fact. A query reads the version current at its snapshot. A retraction hides the fact until the next write. Exact-value patterns match current values only.

This database has five transactions, recorded one day apart from #utc "2026-02-01T00:00:00Z". Transaction 1 creates three people:

[
 {id 1 name "Duncan Idaho" status "active" rank "swordmaster"}
 {id 2 name "Gurney Halleck" status "active" rank "troubadour"}
 {id 3 name "Thufir Hawat" status "active" rank "mentat"}
]

Transaction 2 changes two statuses:

[{id 1 status "missing"} {id 2 status "exiled"}]

Transaction 3 retracts Duncan Idaho's status, captures Thufir Hawat and creates Chani:

[{id 1 status null} {id 3 status "captured"} {id 4 name "Chani" status "active" rank "sayyadina"}]

Transaction 4 writes Duncan Idaho's status again and returns Gurney Halleck to active:

[{id 1 status "ghola"} {id 2 status "active"}]

Transaction 5 retracts Thufir Hawat's status:

[{id 3 status null}]

Gurney Halleck's status has three versions. A query without as-of reads the latest one:

(defquery example [] {where [[?e name "Gurney Halleck"]]
           project {?e <status>}})
(example)

Result:

[{status "active"}]

A transaction ID between two versions reads the earlier one:

(defquery example [] {where [[?e name "Gurney Halleck"]]
           as-of 2
           project {?e <status>}})
(example)

Result:

[{status "exiled"}]

A UTC time between two commits reads the version current at that time:

(defquery example [] {where [[?e name "Gurney Halleck"]]
           as-of #utc "2026-02-03T12:00:00Z"
           project {?e <status>}})
(example)

Result:

[{status "exiled"}]

At transaction 3, Duncan Idaho's status is retracted. The field pattern does not match him:

(defquery example [] {where [[?e name ?name] [?e status ?status]]
           as-of 3
           order-by [?name]
           project {?e <name status>}})
(example)

Result:

[{name "Chani" status "active"} {name "Gurney Halleck" status "exiled"} {name "Thufir Hawat" status "captured"}]

A projection does not filter rows. It reads a retracted field as null:

(defquery example [] {where [[?e name ?name]]
           as-of 3
           order-by [?name]
           project {?e <name status>}})
(example)

Result:

[{name "Chani" status "active"} {name "Duncan Idaho" status null} {name "Gurney Halleck" status "exiled"} {name "Thufir Hawat" status "captured"}]

At transaction 2, before the retraction, the projection has his status:

(defquery example [] {where [[?e name ?name]]
           as-of 2
           order-by [?name]
           project {?e <name status>}})
(example)

Result:

[{name "Duncan Idaho" status "missing"} {name "Gurney Halleck" status "exiled"} {name "Thufir Hawat" status "active"}]

Transaction 4 writes his status again, and the fact is visible:

(defquery example [] {where [[?e name "Duncan Idaho"]]
           as-of 4
           project {?e <status>}})
(example)

Result:

[{status "ghola"}]

At the latest snapshot, Duncan Idaho has a status again and Thufir Hawat's status is retracted:

(defquery example [] {where [[?e name ?name]]
           order-by [?name]
           project {?e <name status>}})
(example)

Result:

[{name "Chani" status "active"} {name "Duncan Idaho" status "ghola"} {name "Gurney Halleck" status "active"} {name "Thufir Hawat" status null}]

An exact-value pattern matches entities whose current value is that value. Duncan Idaho and Gurney Halleck were active at transaction 1, and are not at transaction 3:

(defquery example [] {where [[?e status "active"] [?e name ?name]]
           as-of 3
           order-by [?name]
           project {?e <name>}})
(example)

Result:

[{name "Chani"}]

At the latest snapshot, Gurney Halleck is active again and Thufir Hawat has no status:

(defquery example [] {where [[?e status "active"] [?e name ?name]]
           order-by [?name]
           project {?e <name>}})
(example)

Result:

[{name "Chani"} {name "Gurney Halleck"}]

Two field patterns on one entity read the same snapshot. At transaction 2, every rank is still its first version and two statuses have changed:

(defquery example [] {where [[?e rank ?rank] [?e status ?status]]
           as-of 2
           order-by [?rank]
           project {?e <rank status>}})
(example)

Result:

[{rank "mentat" status "active"} {rank "swordmaster" status "missing"} {rank "troubadour" status "exiled"}]

Aggregates count current values only. Superseded and retracted versions are not counted:

(defquery example [] {find [?status (count ?e)]
           where [[?e status ?status]]
           order-by [?status]})
(example)

Result:

[{status "active" count 2} {status "ghola" count 1}]

A time before the first commit sees no versions:

(defquery example [] {where [[?e name ?name]]
           as-of #utc "2026-01-31T00:00:00Z"
           project {?e <name>}})
(example)

Result:

[]

8.1.20. Return positional tuples

Use <tuples> when the consumer needs positional values instead of named fields. find determines their positions:

(defquery example [] {<tuples>
           find [?name]
           where [[?e name ?name]]
           order-by [?name]})
(example)

Result:

[["Duncan Idaho"] ["Leto Atreides"] ["Stilgar"]]

8.1.21. Compute a value in find

A function call in find computes one value per row. Without <tuples>, the result key is the called function's name:

(defquery example [] {find [?name (+ ?age 1) (strings/case "upper" ?name)]
           where [[?e name ?name] [?e age ?age]]
           order-by [?name]})
(example)

Result:

[{name "Duncan Idaho" + 38 strings/case "DUNCAN IDAHO"}
 {name "Leto Atreides" + 46 strings/case "LETO ATREIDES"}
 {name "Stilgar" + 30 strings/case "STILGAR"}]

Two terms that would produce one key are refused with duplicate result key in find; <tuples> allows them. A term without a function name, such as [?age 1], needs a call around it: (list ?age 1). A term that fails ends the query with its #err. A computed term cannot be combined with aggregates, group-by or having. Queries with project reject computed terms and window calls. Aggregate projections can use grouping variables and aggregate aliases. A call whose head is a variable, such as (?s ?v), is refused with a find call needs a function name.

8.1.22. Store a query as data

A query definition can take a query map as a parameter. Quote a query when storing it in a local, so its contents are preserved:

(defquery example [q] q)
(let [q `{where [[?e <atreides>]]
          project {?e <name>}}]
  (example q))

Result:

[{name "Duncan Idaho"} {name "Leto Atreides"}]

8.1.23. Query members and limits

Member Purpose
where Match field patterns and predicates.
project Select fields and nested linked entities.
find Return matched variables, computed values, aggregates or window calls.
order-by Sort results; #desc ?value sorts descending.
offset / limit Skip rows and cap the returned count.
<tuples> Return positional lists instead of maps.
group-by Set explicit aggregate group keys.
having Filter completed groups.
<distinct> Remove repeated selected rows.
in Declare caller-supplied query inputs.
as-of Select a transaction ID or UTC snapshot.

project requires exactly one query-binding entry. When find is omitted, it is inferred from that binding. Negated projection tags such as <!name> are unsupported. Queries use the evaluator's CPU and memory budgets and cancellation signal. There are no separate query row or cost quotas. Unsupported query shapes and incompatible value kinds return errors. limit 0 returns no rows.

8.2. Transactions

A transaction is a mutation value with a patch member. It can also have if, query, schema and on members. The database request transact runs one mutation value from params.code and publishes it as one transaction; see database requests. The examples below run in order against a new database. Every request and response is checked by the transaction conformance tests.

8.2.1. defmutation

Macro

(defmutation name [params*] mutation-map) → name

Define a mutation with defmutation and call it with an open database. The result contains tx and ids. These examples run in order against a separate new database.

(defmutation example [] {patch {_paul {name "Paul" spice 100}}})
(example)

This returns {tx 4 ids {_paul #link 1}}. A mutation can use local values and compute a patch for each selected row:

(defmutation example [extra]
  {query {find [?e ?spice] where [[?e name "Paul"] [?e spice ?spice]]}
                patch {?e {spice (+ ?spice extra)}}})
(example 25)

This returns {tx 5 ids {}}. A subsequent query sees the committed value:

(defquery example [] {<tuples> find [?spice] where [[?e name "Paul"] [?e spice ?spice]]})
(example)

The result is [[125]]. Writing the same value publishes nothing:

(defmutation example [] {patch {1 {spice 125}}})
(example)

The result is {tx null ids {}}. A failed condition or conflicting proposals returns an error and writes nothing for that call.

A mutation without a query can name its target with a parameter. In (defmutation touch [e] {patch {?e {seen true}}}), the key ?e reads the parameter e, which holds an entity ID such as 2 or a link such as #link 2. A ?name key or value reads a parameter or a local of that name: a let, fn or for binding, or a top-level def. In code that eval runs, when no local has that name, it reads the binding of that name that the host supplies. Code in a saved namespace does not read host bindings. When no value is found, the call returns an unbound name error and writes nothing. A map key is always a string, so {e {seen true}} does not name an entity: it is an invalid patch target. With a query, ?e is a variable of the query.

Add schema beside patch to check every addressed entity:

(defmutation example [] {schema {name string? spice int?}
              patch {1 {spice 130}}})
(example)

The check uses each complete post-patch entity. Every call of the mutation checks it: a call in eval, a saved namespace function, a defreactor called by name and a transact request. A schema that contains a name, such as {name string?}, is evaluated where the mutation runs, so a bare kind name is its builtin and a user predicate or a closure applies as written. A call in eval checks with the functions that the evaluation holds. Temporary links use their final entity IDs during checking, including links inside lists. The transaction stages all proposals before validation. One failed entity rejects all facts, identifiers, and log entries. An entirely unchanged patch resolves its schema but skips candidate validation. Unscoped patches remain available when the mutation has no schema member.

A query schema clause also constrains its corresponding mutation target. The constraint remains attached through grouping, ordering, and paging. Different selected rows can carry different schemas.

Add on to run code after the call's write commits or rolls back; see Run code after a write.

8.2.2. Save a mutation function

Save this source as shipments.dust:

(defmutation record-shipment [amount]
  {patch {_shipment {amount amount}}})
(export record-shipment)

Install it in the database:

stardust namespace save arrakis/shipments shipments.dust --config arrakis.dust

Saving validates the definition without running its body. Import it in run.dust and call it:

(import <arrakis/shipments>)
(shipments/record-shipment 50)
(shipments/record-shipment 75)
(defquery shipment-amounts []
  {<tuples> find [?amount] where [[?e amount ?amount]] order-by [?amount]})
(shipment-amounts)

Run stardust eval run.dust --config arrakis.dust. Each call allocates its own shipment; the final query returns [[50] [75]]. Loading the namespace after reopening the database preserves this behavior. A top-level initializer that calls a mutation is refused.

8.2.3. Transaction boundaries

Each mutation call is atomic. An evaluation with several calls can commit several transactions. A later error does not undo an earlier call: its error reports outcome "committed" and transaction {tx … ids …}, with the original failure under cause when available. Read the data before retrying an evaluation that has already committed.

Selection and expressions use a consistent snapshot. If a selected field changes before publication, the call recomputes within its original CPU and memory limits. A changed loaded namespace reports a conflict; invoke it again to use the new definition. Mutation expressions cannot perform external effects or change captured shared values. Use built-ins or saved namespace helpers in mutation expressions; other captured functions can be refused with script denied. Historical contexts cannot write. Cancellation or exhaustion before commit leaves that call unpublished. A storage error with outcome "unknown" requires reopening and reading the data before retrying.

8.2.4. Run code after a write

Some work must wait until a write is final. A program can publish an event, call another service or record a failure, but it must not do so for a write that rolls back. The on member of a mutation map holds this work. It is a map with an optional commit body and an optional rollback body, and each body is ordinary DUST:

(defmutation pay [invoice]
  {if {?invoice {status "open"}}
   patch {?invoice {status "paid"}}
   on {commit (record (str "paid " invoice " in " tx))
       rollback (record (str "not paid " invoice ": " (errors/message error)))}})

defmutation, defreactor and the code map of a transact request accept on. The commit body runs after the transaction commits, and the rollback body runs after it rolls back. Each body runs once for each run of its mutation, reactor or request, and it sees these names:

Name Value
the parameters The mutation's parameters, or the bindings of a transact request
rows The rows that the query selected, as a list of maps from each variable's name to its value; one empty map without a query
tx The transaction ID, in commit
error The #err value that the call returns, in rollback

A literal mutation map in defmutation accepts ordinary handler bodies. The bodies see the definition's parameters and captured local bindings.

The bodies run after the write releases the write lock and before the request responds. Within one request they run in the order of the commits and rollbacks that queued them: a request that calls a and then b runs a's body, then b's, then the bodies of the writes that a's body made. Requests that run at the same time run their bodies independently, with no order between them. A body can run any DUST, also mutations. The handlers of those writes run after it, so a chain of writes runs one handler at a time. A chain has no limit on its length. The request's CPU and memory limits apply to it, and a cancel of the request stops it. When a body is cancelled or runs out of CPU or memory, the bodies after it do not run. Nothing that a body does changes the commit or the rollback.

A mutation map computed as a value, including a map bound with def, holds its handlers as functions. The commit handler takes rows and tx. The rollback handler takes rows and a map whose error member holds the #err value. A function called with an #err argument returns that argument without running. The runtime returns #err <invalid program> if a computed map's handler value is not a function:

(def finish {patch {_d {done true}}
             on {commit (fn [rows tx] (record (str "done in " tx)))}})
(defmutation close [] finish)

A write that publishes nothing, such as a patch that changes no value, runs neither body. A dry run runs no body. When a storage error leaves the outcome unknown, no body runs.

This namespace records each payment, and flags large invoices for review:

{id 1 method "namespaces/save"
 params {changes [{path "billing/payments"
                   forms [(defmutation record [text] {patch {_entry {log text}}})
                          (defmutation pay [invoice]
                            {if {?invoice {status "open"}}
                             patch {?invoice {status "paid"}}
                             on {commit (record (str "paid " invoice " in " tx))
                                 rollback (record (str "not paid " invoice ": "
                                                       (errors/message error)))}})
                          (defmutation settle [invoice]
                            {patch {?invoice {settled true}}
                             on {commit (pay invoice)}})
                          (defreactor flag-large
                            {query {find [?invoice] where [[?invoice amount ?a] (> ?a 1000)]}
                             patch {?invoice {review true}}
                             on {commit (record (str "review " rows))}})
                          (export pay settle)]}]}}
[{id 1 result {tx 4 namespaces [{path "billing/payments" entity #link 1 revision 4 deleted false}]}}]

The next write adds two invoices. flag-large reviews the large one in the same transaction, and its commit body runs after that transaction commits:

{id 2 method "transact"
 params {code {patch {_small {amount 40 status "open"}
                      _large {amount 5000 status "open"}}}}}
[{id 2 result {tx 11 ids {_large #link 5 _small #link 6}}}]

pay closes the small invoice, and its commit body records the payment:

{id 3 method "eval"
 params {forms true code [(import <billing/payments>) (payments/pay 6)]}}
[{id 3 result [null {tx 15 ids {}}]}]

settle marks the invoice settled. Its commit body calls pay again, and that call fails, because the invoice is no longer open. pay rolls back, so its rollback body records the failure. The commit body of settle returns the #err value of pay. The response reports that failure in its on member: one entry for each failed body, with the definition's name, the key of the body and its error. The request returns its normal result, and the other bodies still run:

{id 4 method "eval"
 params {forms true code [(import <billing/payments>) (payments/settle 6)]}}
[{id 4 result [null {tx 19 ids {}}]
  on [{name "settle" key "commit"
       error #err {code <conflict> message "patch proposals or conditions conflict"}}]}]

The log shows each body's work in commit order:

{id 5 method "query"
 params {query {find [?text] <tuples> where [[?entry log ?text]]}}}
[{<more> id 5 page 0 result [["review [{invoice 5}]"]
                             ["paid 6 in 15"]
                             ["not paid 6: patch proposals or conditions conflict"]]}]

An entry has name when its body belongs to a defmutation or a defreactor. Only a reactor's entry also has namespace: the entry of a defmutation, even one in a saved namespace, has no namespace, and the entry of a transact request has neither. A failure is the #err value that the body returns, or the error that stopped it: when the request is cancelled or runs out of CPU, each body that did not run is reported with that error.

Some functions have effects that must not escape a rollback. Such a function refuses to run while a write transaction is open, for example in a computed patch value or in a reactor, and points to on {commit …}. In an on body and outside a transaction it runs normally.

8.2.5. Create entities

patch maps each entity to its changed fields. A key that starts with _ is a temporary name for a new entity. Inside the patch, _paul and #link _paul refer to that entity, so partner stores a link to it. Ordinary strings stay strings.

{id 1 method "transact"
 params {code {patch {_paul {name "Paul" spice 100}
                      _chani {name "Chani" partner _paul}}}}}

Response:

[{id 1 result {tx 6 ids {_chani #link 1 _paul #link 2}}}]

tx is the transaction ID, which is a valid as-of bound for queries. ids maps each temporary name to the entity allocated for it. Names are allocated in name order; new fields follow, and the transaction ID comes last.

8.2.6. Change an entity

A key spelled as a decimal ID names an existing entity. A nested map merges into the entity the field links to, or into a new entity when the field is empty. A list replaces the whole value. A tag asserts membership.

{id 2 method "transact"
 params {code {patch {2 {<fremen> home {city "Arrakeen"} steps ["scout" "patrol"]}}}}}

Response:

[{id 2 result {tx 12 ids {}}}]

8.2.7. Write one patch per query row

A query selects rows, and the patch is filled once for each row. Each row has its own scope, so _note names a new entity for every row, and #link "_note" reaches the entity of that row. ids then maps each name to the list of its entities in row order.

{id 3 method "transact"
 params {code {query {find [?e ?n] where [[?e name ?n]] order-by [?e]}
               patch {_note {about #link ?e text ?n}
                      ?e {note #link "_note"}}}}}

Response:

[{id 3 result {tx 18 ids {_note [#link 13 #link 14]}}}]

Expressions in a patch, such as (+ ?v 10), are computed from the row. A row whose filled body for a name holds no fact allocates no entity for that name and adds nothing to its list; a transaction in which every row is empty publishes nothing. Here only Paul's row gets a badge:

{id 8 method "transact"
 params {code {query {find [?e ?n] where [[?e name ?n]] order-by [?e]}
               patch {_badge (if (= ?n "Paul") {<fremen> who #link ?e} {})}}}}

Response:

[{id 8 result {tx 21 ids {_badge [#link 19]}}}]

A link to a name that allocated nothing in its row names no entity, and the transaction is refused. A quoted form or a function is refused: a patch holds data. A refused form reports its position in the request, as an evaluation error does, with a span when the request was decoded with spans.

8.2.8. Check a condition

An if map compares current values before anything is written. The whole transaction publishes only when every condition holds.

{id 4 method "transact"
 params {code {if {2 {spice 100}} patch {2 {spice 80}}}}}

Response:

[{id 4 result {tx 22 ids {}}}]

A condition that does not hold is #err {code <conflict> …}, and nothing is written. Two rows that propose different values for one field conflict in the same way.

{id 5 method "transact"
 params {code {if {2 {spice 100}} patch {2 {spice 60}}}}}

Response:

[{id 5 result #err {code <conflict> message "patch proposals or conditions conflict"}}]

8.2.9. Unchanged values and retractions

A patch that changes nothing publishes no transaction:

{id 6 method "transact" params {code {patch {2 {spice 80}}}}}

Response:

[{id 6 result {tx null ids {}}}]

A negative tag, null or false at a field retracts it. Inside a list or a nested value, null and false stay data.

{id 7 method "transact" params {code {patch {2 {<!fremen> steps null}}}}}

Response:

[{id 7 result {tx 23 ids {}}}]

null as the value of an entity retracts the entity: the patch retracts each field that the entity has before the transaction. Entity 13 is Chani's note from the rows example:

{id 10 method "transact" params {code {patch {13 null}}}}

Response:

[{id 10 result {tx 24 ids {}}}]

The result is the same as null at each field of the entity. History keeps the old values, so a query with as-of 23 still finds the note. Links from other entities do not change: Chani's note field still links to entity 13, and a query through that link finds no fields. In a mutation, a key such as ?e can also take null, and so can a computed value. The value of ?e is an ID or a #link. A mutation parameter supplies that target too: (defmutation drop [e] {patch {?e null}}) accepts (drop 2) or (drop #link 2). A lexical local can supply the target as well; when there is no local, the target reads its host binding.

The proposals of the retraction are the same as other proposals. A different value for one of the fields at the same priority is a conflict. A field that the entity does not have can get a value in the same transaction. A reactor sees the retraction as it sees other writes, and a dry run shows each field with the action "retract". A schema checks the empty entity. Each plugin claim applies to each field, so a patch cannot retract an objects tree node.

null for an entity that has no fields, for example an entity that is retracted already, changes nothing. A reactor that retracts the entities it finds through a link thus finds them again in its next round, and the rounds end.

These patches are refused, and nothing is written:

  • null for an ID that is not an entity, and for a namespace entity. The error is #err {code <invalid value>}.
  • null for a temporary name such as _x, because a new entity has no fields. The error is #err {code <invalid program>}.
  • false as the value of an entity, and null in an if condition.

Transactions run under the request's CPU and memory limits. A transaction that is cancelled or runs out of budget before it commits writes nothing.

8.2.10. Dry run

Add dry-run true to the transact parameters to see the changes of a mutation before you commit it. The dry run does all the steps of a real run, and then it rolls back the transaction. It writes nothing and gives the same errors as a real run. Its result has tx null, the ids that a real run would allocate, and a changes list. Each item of the list is an entity that the mutation would change, with the before and after values of each changed field. Here entity 2 would get a new spice value, and _leto would be a new entity:

{id 9 method "transact"
 params {dry-run true
         code {patch {2 {spice 60} _leto {name "Leto"}}}}}

Response:

[{id 9 result {tx null ids {_leto #link 24} dry-run true
               changes [{entity #link 2 created false
                         fields {spice {action "assert" before 80 after 60}}}
                        {entity #link 24 created true name "_leto"
                         fields {name {action "assert" after "Leto"}}}]}}]

The action of a field is "assert", "retract" or "merge". A merge is a map at a field that merges into the linked entity. The changes of that entity are in its own item. Named mutation calls in eval have no dry run. A dry run runs no on body.

8.2.11. Keep less history of an entity

With the retention plugin, a patch can give an entity a history policy in the stardust/history field. The plugin removes the older history in the background (History retention). The patch of this request keeps the newest 5 transactions that wrote a field of the order:

{method "transact"
 params {code {patch {_order {status "placed" stardust/history {retain 5}}}}}}

retain is one of these values:

retain Kept history of each field of the entity
An integer N, 1 or more The facts of the newest N transactions of the entity, and the value before them
A positive #dur The facts written within that time before now, and the value before them
A #utc The facts written at or after that time, and the value before them

With cascade true, the policy also applies to the descendants of the entity through stardust/path/parent, such as the files and directories of an objects tree. A descendant with a policy of its own uses its own policy. An own policy without cascade applies to that entity only, so its children still use the cascading policy above it:

{method "transact"
 params {code {patch {7 {stardust/history {retain #dur "P30D" cascade true}}}}}}

A policy has retain and an optional boolean cascade, and no other key. Other values are refused with #err {code <invalid value>}. The policy map merges into an entity that stardust/history links to, as each map in a patch does. Thus a later patch that gives only retain keeps the earlier cascade. null removes the policy. Without the retention plugin, a patch that writes stardust/history fails with #err {code <plugin required>}. If a direct edit makes the linked policy invalid, pruning stops and retention/status reports last-error until the policy is repaired.

A fact can have a field setting of the plugin and an entity policy. Then the one that keeps more history applies. For example, with the field setting {fields {status {retain 3}}} and the entity policy {retain 1}, the status of the entity keeps its newest 3 values and the value before them. The other fields of the entity keep only its newest transaction and the values before it.

Another plugin can hold history back with a history floor. Then a removal keeps every fact that a read at or after the floor needs, and it removes the rest after the floor moves.

8.2.12. defreactor

Macro

(defreactor name doc? options? mutation-map) → name

A reactor is a mutation that the database runs. Save it in a namespace. Each later write that changes a field that the reactor reads or writes then runs the reactor before the write commits. The facts that the reactor writes commit in the same transaction as the facts that caused them, so a query at that transaction sees both.

This namespace flags the invoices of customers on hold and gives each user an access level:

{id 1 method "namespaces/save"
 params {changes [{path "billing/review"
                   forms [(defreactor flag-held
                            "Flag the invoices of customers on hold."
                            {query {find [?invoice]
                                    where [[?invoice customer ?customer]
                                           [?customer hold true]]}
                             patch {?invoice {review true}}})
                          (defreactor grant-admins {priority 10}
                            {query {find [?user] where [[?user admin true]]}
                             patch {?user {access "all"}}})
                          (defreactor default-access
                            {query {find [?user] where [[?user member true]]}
                             patch {?user {access "none"}}})]}]}}

The write below adds a customer on hold, an invoice and two users. It does not write review or access:

{id 2 method "transact"
 params {code {patch {_acme {name "Acme" hold true}
                      _invoice {amount 100 customer #link _acme}
                      _ada {name "Ada" member true admin true}
                      _bob {name "Bob" member true}}}}}

Response:

[{id 2 result {tx 18 ids {_acme #link 5 _ada #link 6 _bob #link 7 _invoice #link 8}}}]

The reactors wrote both fields in that transaction. The invoice has a review flag:

{id 3 method "query"
 params {query {find [?amount ?review] <tuples>
                where [[?invoice amount ?amount] [?invoice review ?review]]}}}
[{id 3 page 0 more true result [[100 true]]}]

Ada is an admin and a member, so grant-admins and default-access both propose her access. The database keeps the priority 10 value. Bob is only a member:

{id 4 method "query"
 params {query {find [?name ?access] <tuples>
                where [[?user name ?name] [?user access ?access]]
                order-by [?name]}}}
[{id 4 page 0 more true result [["Ada" "all"] ["Bob" "none"]]}]

8.2.12.1. Rounds

Reactors run in rounds inside the write transaction:

  1. A round selects each reactor whose query reads a changed field or whose patch writes one. Reactors that can write the same field run together, so a lower priority value can replace a value that a higher priority reactor no longer proposes. A reactor with a computed patch value can write any field, so a change of any field runs it.
  2. All selected reactors read the same state: the write and the earlier rounds. A reactor does not see the proposals of its own round.
  3. The proposals of the round merge. Identical values agree. For different values at one field, the database keeps the value of the higher priority. The default priority is 0.
  4. The merged patch joins the transaction. The next round uses the fields it changed. The transaction commits after a round that changes nothing.

A later round can replace a value that the write or an earlier round wrote. The transaction then records only the final value.

The transaction ID is higher than every ID that the write and its reactors create. When a round creates a field or an entity, the transaction takes its ID after the last round. The ID that the write took before the rounds is then not used.

These conditions reject the whole write, and nothing commits:

  • Two reactors of equal priority propose different values for one field.
  • A reactor fails, for example on a schema. Each schema of a reactor applies to the final state of its entity.
  • Each of 64 rounds changes a value.

The error message names the reactor when one reactor causes the failure.

8.2.12.2. Reactor rules

  • A reactor takes no parameters. Its query selects the entities to change, so a reactor has no if member.
  • The options map accepts priority, an integer.
  • Saving a namespace checks each reactor and refuses an invalid one. A saved reactor applies to later writes. Saving it does not run it on the current facts.
  • The transact request and mutation calls in eval run reactors. A saved namespace is stored as facts, and a bulk import needs a database without facts, so a bulk import never runs a reactor.
  • defreactor also defines a function without parameters that runs the reactor as a mutation, for example to apply it to existing facts.
  • A reactor can have an on member (Run code after a write). Its commit body runs only when a value that the reactor proposed changed the state that the write commits. A reactor that a higher priority fully overrides does not run it, and neither does a reactor that only proposes values its fields already have. Its rows are the rows whose values made such a change. Its rollback body runs when the write rolls back after the reactor's rounds, with the rows of those rounds. The bodies run in the reactor's namespace, after the handlers of the write itself, in the order of the definitions.

8.2.13. db/reactors

Function

(db/reactors) → map

(db/reactors) returns the saved reactors and their work since the database opened. Each entry has these members:

Member Value
namespace, name The namespace path and the reactor name
priority The priority of the reactor's values
writes The fields that the patch writes
any-write true when a computed value can write other fields
runs The rounds that evaluated the reactor
changes The fields of entities that its values changed in writes whose reactors all succeeded
last-tx The last transaction that it changed, or null
failures The writes that it caused to fail
last-failure The message of the last failure, or null

The counters start at zero when the database opens. Without database storage, (db/reactors) returns #err <database no>. The reactors/status request of the ABI returns the same map. After the example above, each reactor ran in two rounds, and the second round changed nothing. The grant-admins reactor changed Ada's access, and default-access changed Bob's:

{id 5 method "reactors/status"}
[{id 5
  result {reactors [{namespace "billing/review" name "flag-held" priority 0
                     writes ["review"] any-write false runs 2 changes 1
                     last-tx 18 failures 0 last-failure null}
                    {namespace "billing/review" name "grant-admins" priority 10
                     writes ["access"] any-write false runs 2 changes 1
                     last-tx 18 failures 0 last-failure null}
                    {namespace "billing/review" name "default-access" priority 0
                     writes ["access"] any-write false runs 2 changes 1
                     last-tx 18 failures 0 last-failure null}]}}]

When the database has saved defcron forms or runs a scheduler, the map also has a scheduled member (Scheduled reactor status).

8.2.14. defcron

Macro

(defcron name doc? map) → name

A scheduled reactor is a mutation that the database runs at UTC times. Save it in a namespace. When the root configuration has the tag <scheduled-reactors>, the database runs the mutation at each minute that its schedule selects. Each run is a separate write transaction.

The map has one schedule member. Its value is a cron expression string (Cron expressions). The other members are a mutation map, as in defmutation. The mutation can use the name scheduled-at. Its value is the minute that the schedule selected, as a #utc value. A run that starts at 09:00:20 receives 09:00:00. The mutation members, such as query, patch and schema, cannot bind the name scheduled-at again.

This configuration enables scheduled reactors. No evaluation can read the clock or the filesystem:

{plugins {<stdlib> database <temporary> io <!clock>}
 <scheduled-reactors>
 capabilities <!filesystem>}

This namespace queues the expired sessions at 09:00 UTC on each weekday:

{id 1 method "namespaces/save"
 params {changes [{path "app/sessions"
                   forms [(defcron queue-expired-sessions
                            "Queue expired sessions for cleanup."
                            {schedule "0 9 * * MON-FRI"
                             query {find [?session]
                                    where [[?session session-status "expired"]]}
                             patch {?session {session-status "cleanup-pending"
                                              queued-at scheduled-at}}})]}]}}

This write adds an expired session and an active session:

{id 2 method "transact"
 params {code {patch {_old {session-status "expired"}
                      _new {session-status "active"}}}}}

At 09:00 UTC on Monday 7 January 2030, the database runs the reactor. The expired session now waits for cleanup, and queued-at has the minute of the run:

{id 3 method "query"
 params {query {find [?status ?queued] <tuples>
                where [[?session session-status ?status]
                       [?session queued-at ?queued]]}}}
[{id 3 page 0 <more> result [["cleanup-pending" #utc "2030-01-07T09:00:00Z"]]}]

8.2.14.1. Settings

Setting Tags Default Effect
scheduled-reactors, in the root configuration <scheduled-reactors> Absent Runs the saved defcron forms. It requires the database plugin.
clock, in the settings of the io plugin <clock> or <!clock> Absent Controls the calls to time/now, as the next table shows.

Without <scheduled-reactors>, the database starts no scheduler. It still checks and saves defcron forms. A database without storage has no saved forms and starts no scheduler. The scheduler operates without the io plugin. It reads the host clock itself and gives no access to the evaluations that it starts.

io settings time/now in other evaluations time/now in a scheduled reactor
No clock tag Returns the time Returns #err <clock denied>
<clock> Returns the time Returns the time
<!clock> Returns #err <clock denied> Returns #err <clock denied>

The clock setting does not change the time functions that do not read the clock, such as time/parts.

The body of a scheduled reactor cannot call time/now, also with <clock>. Mutation expressions have no host effects, in every mutation. namespaces/save accepts such a body, but each run of it fails, and the status shows last-failure <script denied> namespace initialization attempted an effect. Use scheduled-at in the body. Read the clock in an on handler, which runs after the write, or in a reactor that the write runs:

(defmutation record-run [clock] {patch {_run {clock clock}}})

(defcron stamp {schedule "* * * * *"
                patch {_t {at scheduled-at}}
                on {commit (record-run (time/now))}})

With <clock>, the handler records the time. Without it, (time/now) returns #err <clock denied>, and record-run returns that error without a write. A handler body is code of its own: it can bind scheduled-at as its own local name.

8.2.14.2. Cron expressions

A cron expression has five fields. Whitespace, such as spaces, tabs or line ends, separates the fields. The fields are in this order:

Field Values
Minute 0 through 59
Hour 0 through 23
Day of month 1 through 31
Month 1 through 12, or JAN through DEC
Day of week 0 through 7, or SUN through SAT. 0 and 7 are both Sunday.

Each field is a list of one or more items. These operators make an item:

Operator Meaning Example Example meaning
* Each value of the field * * * * * Each minute
, A list of items 0,30 * * * * At minutes 0 and 30 of each hour
- A range that includes its two ends 0 9-17 * * * At the start of each hour from 09:00 through 17:00
/ A step after * or after a range */15 * * * * At minutes 0, 15, 30 and 45 of each hour

A step starts at the first value of its field or range. It does not continue into the next hour, day or month. Thus */40 * * * * selects minutes 0 and 40 of each hour. The names of months and days of the week can have uppercase or lowercase letters.

A minute matches when its minute, hour and month match. For the day, the two day fields operate together:

  • When both day fields are *, each day matches.
  • When one day field is *, the other field selects the days.
  • When neither day field is *, a day matches when either field matches it. Thus 0 9 1 * MON selects 09:00 on each Monday and on the first day of each month.

A day field such as 1-31 or */1 is not *, so the other day field can also select days.

UTC schedule Expression
Every 15 minutes */15 * * * *
At the start of every hour 0 * * * *
At 02:30 each day 30 2 * * *
At 09:00 on weekdays 0 9 * * MON-FRI
At midnight on the first day of each month 0 0 1 * *
At 09:00 on Mondays and on the first day of each month 0 9 1 * MON

The database refuses these expressions:

  • An expression with fewer or more than five fields, and a name such as @daily in place of the fields.
  • A time zone, such as CRON_TZ=UTC. The fields are always in UTC.
  • An empty list item, or a range without an end.
  • A range that ends before it starts, such as SAT-SUN.
  • A value outside its field, or a name that is not a month or a day of the week.
  • A step that is 0, that is not a number, or that follows a single value, such as 5/10.
  • The extensions ?, L, W and #, such as L in the day of month, 15W or MON#2.

8.2.14.3. Run rules

  • Only saved namespaces have scheduled reactors. A form in an evaluation, a namespaces/check request, an unsaved session source and a historical read do not schedule a run. A write of data does not run a scheduled reactor.
  • namespaces/check and namespaces/save refuse an invalid form, also without <scheduled-reactors>. The diagnostic gives the namespace path and the form index. A refused save keeps the current schedule.
  • No other form of the namespace can define the name of a scheduled reactor. A run calls the definition by that name.
  • When the database opens, the first minute is the first minute after the open. After a save, the first minute is the first minute after the save commits.
  • The database examines each UTC minute one time. When the host stops or the clock moves forward, the database does not run the minutes that it did not examine. After the clock moves forward, it examines only the current minute. After the clock moves back, it does not examine a minute again.
  • A reactor has a maximum of one run that waits or runs. When its next minute comes before that run ends, the database does not run the reactor for that minute. The status counts that minute as skipped.
  • When a save changes or deletes the namespace that holds the definition, a run that waits does nothing. The next minute of the reactor is the first minute after that save commits. A run that started continues as a normal write.
  • A run uses the mutation path of the database: its limits, schemas, reactors, on handlers and subscriptions. A failed run rolls back. The status records the failure, and the next matching minute runs again.
  • A run gets no access to the host. The filesystem and the other host capabilities are off for the run and its on handlers, also when the configuration gives them to other evaluations.
  • When the database closes, it starts no new run. It waits until each active run ends or stops before it closes the storage.
  • defcron also defines a function with one parameter, scheduled-at. The function runs the mutation. A call to the function is an ordinary evaluation with the access of the database:
(queue-expired-sessions #utc "2030-01-07T09:00:00Z")

8.2.14.4. Scheduled reactor status

(db/reactors) and the reactors/status request also return a scheduled member: a list with an entry for each saved defcron form, in the order of the definitions. When the database runs a scheduler, the status map always has this member. Without a scheduler, as without <scheduled-reactors>, the status map has the member only when the namespaces have saved defcron forms. Each of those entries has the tag <disabled>.

Member Value
<disabled> The tag of an entry that no scheduler runs; absent otherwise
namespace, name The namespace path and the reactor name
schedule The cron expression
runs The runs that committed
failures The runs that failed, including runs that the database could not start
skipped The minutes that came while a run waited or ran
last-scheduled The last minute that the schedule selected, as a #utc value, or null
next-scheduled The next minute that the schedule selects and the scheduler can still consider, as a #utc value, or null
last-tx The transaction of the last run that committed, or null
last-failure The message of the last failure, or null
last-failure-at The minute that the schedule selected for the last failed run, as a #utc value, or null

next-scheduled is the first minute at or after the current minute that the schedule selects, and that the scheduler did not consider for the reactor before. After the clock moves back, it stays after the newest minute considered. A run that still waits or runs at that minute makes the minute a skip. next-scheduled is null for a disabled entry, and for a schedule that selects no day, such as 0 0 30 2 *.

The counters start at zero when the database opens. A disabled entry has zero counters and null minutes. After the run above:

{id 4 method "reactors/status"}
[{id 4
  result {reactors []
          scheduled [{namespace "app/sessions" name "queue-expired-sessions"
                      schedule "0 9 * * MON-FRI" runs 1 failures 0 skipped 0
                      last-scheduled #utc "2030-01-07T09:00:00Z"
                      next-scheduled #utc "2030-01-08T09:00:00Z" last-tx 10
                      last-failure null last-failure-at null}]}}]

A check of an invalid expression gives the namespace and the form index:

{id 5 method "namespaces/check"
 params {changes [{path "app/sessions"
                   forms [(defcron queue-expired-sessions
                            {schedule "0 9 * * MON-FRY"
                             query {find [?session]
                                    where [[?session session-status "expired"]]}
                             patch {?session {session-status "cleanup-pending"}}})]}]}}
[{id 5
  result {<!valid>
          diagnostics [{code "invalid_source" path "app/sessions"
                        message "scheduled reactor app/sessions/queue-expired-sessions: the day-of-week field accepts 0 through 7 or SUN through SAT"
                        position {form-index 0}}]}}]