05 Requests and responses

Submit an array of request Documents. Each Document holds a map with a UUID message-id, a string method and, when needed, a params map. The caller assigns each request a unique message ID. An optional UUID correlation-id identifies the wider operation. When omitted, the request's message ID is the correlation ID. The Go SDK assigns message IDs and returns them from Submit. Quote metadata such as method names in DUST.

A method refuses a params member that it does not read. The result is an error with the invalid_params code, and the message names the member:

{method "query" params {query {find [?n] where [[?e name ?n]]} as_of 3}}
; result #err {code <invalid params> message "query params have an unknown member as_of"}

Submit waits when the request queue is full and splits batches at the configured batch-size. Poll concurrently whenever a submission can exceed capacity: a worker can wait for response capacity before it can accept more work. On failure, accepted reports how many requests from the start of the array were accepted.

Method Purpose
"eval" Evaluate native code with optional bindings, session, forms, namespace and discard
"sessions/open", "sessions/reset", "sessions/close" Create, clear or release persistent evaluation state; run a script (Scripts in sessions)
"lookup" Read a named value from a session
"query" Read database rows in pages
"queries/prepare", "queries/run", "queries/release" Prepare a query once and run it many times
"queries/subscribe" Receive a query's result after each commit that changes it
"plans/explain" Describe a query plan without executing it
"transact" Apply one atomic mutation and its reactors, or report its changes with dry-run true
"imports/begin", "imports/add", "imports/finish", "imports/abort" Load patches into an empty database in one commit
"namespaces/read", "namespaces/list" Read saved source and namespace metadata
"namespaces/save", "namespaces/load" Publish source changes or load a namespace into a session
"namespaces/check" Validate source changes as a save does, and save nothing
"schemas/valid?" Check a value against a schema or a saved schema name
"programs/signature" Describe the inputs and results of a program's functions without running it
"programs/names" List the functions, values, special forms, macros and namespaces that code can use, with optional prefix and limit; without limit, every matching name
"entities/read", "entities/backlinks", "entities/history" Read an entity's fields, the entities that link to it, or the stored versions of its fields (Entity navigation)
"skills/status", "skills/sync" Report or force the writing of agent skills (skills plugin)
"retention/status" Report what history removal did (retention plugin)
"fuse/status" Report the filesystem mount (fuse plugin)
"blackholes/preview", "blackholes/execute" Plan, then apply an erasure of selected history (blackholes plugin)
"blackholes/audit", "blackholes/status" List erasure audits and describe the blackholes plugin
"objects/uploads/begin", "objects/uploads/get", "objects/uploads/append", "objects/uploads/finish", "objects/uploads/abort" Send a payload in parts (objects plugin)
"objects/payloads/open", "objects/payloads/manifest" Read a published payload (objects plugin)
"objects/create", "objects/get", "objects/lookup", "objects/children", "objects/path", "objects/files", "objects/update", "objects/move", "objects/remove" Read and change the file tree (objects plugin)
"events/publish", "events/subscribe", "events/accept", "events/call", "events/send", "events/finish", "events/cancel", "events/status" Publish and subscribe, and exchange messages between requests (Events, events plugin)
"reactors/status" List the saved reactors and their work since the database opened; with a scheduler, also the scheduled member (Scheduled reactor status)
"backups/status", "backups/sync", "backups/verify" Report, wait for and check backup copies (backups plugin)
"cancel" Request cancellation with params {message-id #uuid "..."} and an optional signal

A transact request with dry-run true runs its mutation in the write transaction and then rolls back. It reports the changes that the mutation would make, and it gives the same errors as a real run. It publishes nothing, and no subscription receives an event. See Database requests for the result.

A namespaces/save error with outcome "committed" means that the namespace publication succeeded but a plugin's post-commit update failed.

A transact request and each mutation call in eval run the reactors of the saved namespaces before the write commits. The facts that the reactors write share the transaction of the write. A reactor failure rejects the whole write, and its error message names the reactor.

The on handlers of mutations, reactors and transact requests (Run code after a write) run after their write commits or rolls back, before the request responds. When a handler fails, the response has an on member beside result: a list with one map for each failed handler. The map has key, "commit" or "rollback", and error, the handler's #err value. It also has name when the handler belongs to a definition, and namespace only for a reactor; a defmutation's entry has no namespace. result is the request's normal result. When the failures do not fit the request's memory, the list ends with one entry {count n error #err {code <exhausted> …}} that counts the failures it leaves out. The Go SDK's Call and CallAs return that result with a *HandlerError that lists the failures; when the call itself fails, its error also matches the *HandlerError.

A successful submit admits the batch; it does not mean that the evaluations have succeeded. Every response has its own UUID message-id, the operation's correlation-id and a causation-id equal to the request's message-id. An ordinary response has result and ends that request. A failed request carries an #err value in result, even when the submit and poll calls themselves return STARDUST_OK. Inspect the result, not only the C return status.

Poll takes a wait in 100 ns units: 0 tries without waiting, a positive value sets a timeout, and a negative value waits indefinitely. A timeout or an empty nonblocking poll returns STARDUST_OK with a zero count; it does not mean that outstanding work has finished. Poll fills a caller-owned array with up to capacity owned response Documents and writes the number returned to count. The configured batch-size may reduce the number returned. Release every returned Document, including any returned with an error.

Query pages contain page, more true and a result List, followed by an ordinary terminal response containing the row and page totals. Match responses by causation-id; independent requests can finish in a different order from submission. Keep polling until each outstanding request has its terminal response. One unconsumed page per worker can hold up further work; outstanding-request capacity is released when the request finishes execution.

queries/prepare accepts params containing a query map, the map that query takes. It checks and compiles the query, then returns prepared, an integer ID. queries/run accepts prepared and optional bindings, session and as-of, as query does. It streams the same pages and terminal response as query with the same query. Preparing can take longer than one query request; each run then skips that work. IDs belong to the database, so every worker and session can run them. queries/release with prepared frees an ID; closing the database frees every ID. An unknown or released ID fails with the unknown_prepared code.

queries/subscribe accepts params containing a query map and optional bindings, as query does. Instead of a query map, namespace, name and optional args name an exported defquery and its arguments. Each run calls the query's current definition, as a generated SDK does. When the namespace is saved again, the next event comes from the new definition. The request delivers events until it ends. Each event contains event, tx, more true and a result List that holds the complete current result. The first event, event 0, is the result when the request starts. After a commit that changes a field that the query reads, the next event holds the new result; tx is the last transaction that the result includes. Commits to other fields send no event. A query with a schema clause, or with no field or tag pattern that requires a field, can match any entity. Each commit that writes facts runs such a query again.

For example, with dune/people exporting (defquery older [minimum] {find [?name] where [[?e name ?name] [?e age ?age] (> ?age minimum)] order-by [?name]})=, this request subscribes to older with the minimum age 18:

{message-id #uuid "00000000-0000-4000-8000-000000000003" method "queries/subscribe"
 params {namespace "dune/people" name "older" args [18]}}

The first event holds the current result:

{message-id #uuid "10000000-0000-4000-8000-000000000003" correlation-id #uuid "00000000-0000-4000-8000-000000000003" causation-id #uuid "00000000-0000-4000-8000-000000000003" event 0 tx 9 more true result [{name "Leto"}]}

After a transaction adds Jessica, aged 35, the next event holds the new result:

{message-id #uuid "10000000-0000-4000-8000-000000000005" correlation-id #uuid "00000000-0000-4000-8000-000000000003" causation-id #uuid "00000000-0000-4000-8000-000000000003" event 1 tx 11 more true result [{name "Jessica"} {name "Leto"}]}

Only one event per subscription waits for a poll. Commits that occur before the poll go into the next event, so a slow host sees the newest result, not each intermediate result. Between events, a subscription uses no worker and no read snapshot. The request ends with one ordinary response: cancel ends it with the cancelled code, a failed run ends it with that failure, and close ends it without a response. A subscription always reads the newest snapshot: as-of in params or in the query map, and session, fail with the invalid_params code. Each subscription holds one outstanding request until it ends.

A bulk import loads many patches into a database that holds no facts, much faster than one transact request per patch. imports/begin returns import, an integer ID. imports/add accepts import and patches, a List of patch maps, the maps a transact patch takes. Each patch is one transaction; the result lists {tx ids} for each patch, as transact reports them. imports/finish with import commits every patch at once and returns transactions, facts and entities. The database then holds what the same patches committed one by one with transact would leave, with the same IDs.

An import only creates entities: a patch whose target is an existing ID, or that has an if condition, is refused, and so is the import of a database with facts (not_empty). A refused patch aborts the whole import. The import writes the rows of the last patches of an imports/add after its result, so a storage failure in those rows aborts the import at the next imports/add or at imports/finish. Until imports/finish, the import keeps the rows of its value indexes in a temporary file beside the database; imports/finish then builds one field's index at a time, so its memory depends on the largest field rather than on the whole import. The file has no name while the import runs, so the system removes it when the import ends, or when the process does. imports/abort with import discards it, and so does closing the database. One import runs at a time (import_active); it holds the database's write transaction until it finishes. Meanwhile transact and namespaces/save fail with the import_active code instead of waiting, a mutation in eval raises an error saying that an import holds the write transaction, and reads see the database as it was before the import. An unknown ID fails with the unknown_import code.

The plans/explain method accepts params containing a query map and optional in and as-of values. It reports plannable, source, version, reason, kind, order, steps and run-cap. For a query that cannot be reordered, refused gives the reason. The order and each step's clause are indexes into the mandatory field patterns. Each step also gives the rendered pattern, its kind, hash-start, presence method and estimated rows, when available. hash-start reports whether the chosen order explicitly marks that position as a hash-group start, including adjacent marked groups. The executor can also infer a hash group where hash-start is false. If a planner is installed, planner reports its state and counters when they exist for that query. This request is read-only and never runs the query.

source is "default", "planned", "learned" or "stored"; kind is "latest" or "historical". Step kinds are "start", "point", "refs" and "hash", with presence methods "auto", "never" or "force". estimate is null when no estimate is available. run-cap is a nanosecond limit, or zero when no cap applies. Refusal reasons are "one field pattern", "limit or offset without order-by", "window call", "each expansion" and "schema clause".

The planner map contains installed true. When the query has planner state, it also contains runs, accepted, median-ns, previous-median-ns, guard, trial-pending, stored and counters. A median is null until measured. The counters report runs, replans, adoptions, reversions, persistence, trial outcomes and capped runs.

Sessions keep locals and compiled state on worker zero; stateless requests are distributed across workers. Submission order is preserved for session operations, namespace publications and host transactions on worker zero. A persistent database belongs to the open handle; closing it does not remove its file. With temporary true, closing removes the temporary store.

eval with discard true returns null instead of each value that is not an #err. A returned #err value and a failure are the result as usual. A script that prints only its own output uses this, so the runtime does not convert values that it discards.

For request parameters and examples, see Namespace files, Database requests, Errors and positions, and Schemas and contracts.

5.1. Scripts in sessions

A session can run a script as stardust eval does (Script runner). sessions/open accepts these optional script settings:

Parameter Meaning
script String that scripts/path returns; default ""
args List of strings that cli/args returns; default []

Another value fails with invalid_params, and no session opens.

{method "sessions/open" params {script "/srv/dune/report.dust" args ["--count" "10"]}}

In that session, (cli/args) is ["--count" "10"].

When evaluation calls processes/exit, the response also has a top-level script-exit integer from 0 through 255. This control field records an actual runtime exit; a returned #err value never sets it. The CLI uses this field to select its exit status and still reports authored error values as errors.

sessions/close and sessions/reset first run the hooks that processes/on-exit registered in the session, once, as a script's exit does: with the capabilities of the database, including its queries and mutations, and at most one second of wall time and CPU. If a hook fails, the result is that #err, and the session closes or resets all the same. A release of the database closes its sessions without their hooks.

The session's child processes stop when the session closes or resets, and the processes that a request started stop when the request fails. cancel and sessions/close accept a signal from 1 through 64. The process group of each such child receives that signal first. The close waits until the child exits; a group whose child has not exited after 2 seconds receives SIGKILL. A host that receives SIGINT sends cancel with signal 2 for the running request, then sessions/close with signal 2, as the CLI does. Another signal value fails with invalid_params.