Embedding and ABI
Use the C ABI to run DUST, work with a database, or convert documents inside
another process. Hosts link a shared library and call six functions from
stardust.h. The boundary uses C calling conventions, opaque handles and
signed 64-bit status and length values. C++ callers use the same header.
Other languages need bindings for these C types and calls.
Start with Installation and first use for the command-line tool. This manual describes the shared library and its host lifecycle; it does not require running a separate Stardust server.
01 Build and link
The release archive contains abi/include/stardust.h and the native libraries
in abi/lib. Set STARDUST_RELEASE to the absolute path of the extracted
release. Save the example below as evaluate.c. On Linux x86-64, build and
run it with:
cc -std=c11 -Wall -Wextra -Werror \
-I"$STARDUST_RELEASE/abi/include" evaluate.c \
-L"$STARDUST_RELEASE/abi/lib" -l:libstardust-linux-amd64.so \
-Wl,-rpath,"$STARDUST_RELEASE/abi/lib" -o abi-evaluate
./abi-evaluate
The runtime search path points to the release library directory. Choose the library for your target platform when using a different release target.
02 First evaluation
The example decodes a configuration, opens a database without storage, submits
one evaluation, waits for its response and prints it. The request contains the
native DUST expression (+ 20 22) in params.code. A string containing that
expression would remain a string; the engine does not parse code strings in
requests.
#include "stardust.h"
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
static int64_t decode(const char *text, stardust_document **out,
stardust_document **error) {
stardust_bytes input = {(const uint8_t *)text, (int64_t)strlen(text)};
return stardust_decode(input, NULL, out, error);
}
static void diagnostic(int64_t status, stardust_document *error) {
fprintf(stderr, "Stardust status: %" PRId64 "\n", status);
if (error != NULL) {
stardust_buffer text = {0};
if (stardust_encode(error, NULL, &text, NULL) == STARDUST_OK) {
fwrite(text.data, 1, (size_t)text.length, stderr);
fputc('\n', stderr);
stardust_release(text.owner, NULL);
}
}
}
int main(void) {
stardust_document *config = NULL, *requests = NULL, *response = NULL;
stardust_document *error = NULL;
stardust_database *database = NULL;
stardust_buffer encoded = {0};
int result = 1;
int64_t status = decode("{workers 1 plugins <stdlib>}",
&config, &error);
if (status != STARDUST_OK) goto failed;
status = stardust_open(config, &database, &error);
if (status != STARDUST_OK) goto failed;
stardust_release(config, NULL);
config = NULL;
status = decode("{message-id #uuid \"7b3dd174-0be3-47ad-b4fa-933c297b1760\" method \"eval\" params {code (+ 20 22)}}",
&requests, &error);
if (status != STARDUST_OK) goto failed;
int64_t accepted = 0;
status = stardust_submit(database, &requests, 1, &accepted, &error);
if (status != STARDUST_OK || accepted != 1) goto failed;
stardust_release(requests, NULL);
requests = NULL;
/* This one scalar evaluation has one terminal response. */
int64_t count = 0;
status = stardust_poll(database, -1, &response, 1, &count, &error);
if (status != STARDUST_OK || count != 1) goto failed;
status = stardust_encode(response, NULL, &encoded, &error);
if (status != STARDUST_OK) goto failed;
if (fwrite(encoded.data, 1, (size_t)encoded.length, stdout) !=
(size_t)encoded.length || fputc('\n', stdout) == EOF) goto cleanup;
result = 0;
goto cleanup;
failed:
diagnostic(status, error);
cleanup:
stardust_release(encoded.owner, NULL);
stardust_release(response, NULL);
stardust_release(requests, NULL);
stardust_release(config, NULL);
stardust_release(error, NULL);
stardust_release(database, NULL);
return result;
}
It prints a response containing result 42 and three UUIDs. This example has one scalar request and one
terminal response. A general client must continue polling and match response
IDs, as described in Requests and responses.
03 Calls and ownership
| Call | Purpose |
|---|---|
stardust_decode(input, options, output, error) |
Copy notation bytes into an owned immutable Document |
stardust_open(config, output, error) |
Open a database and its worker runtimes |
stardust_submit(database, requests, count, accepted, error) |
Copy and accept request Documents |
stardust_poll(database, wait_ticks, output, capacity, count, error) |
Transfer up to capacity owned response Documents to the host |
stardust_encode(document, options, output, error) |
Return notation bytes and their owner |
stardust_release(handle, error) |
Release a Document, database or encoded-byte owner |
A stardust_bytes input contains data and length. Its bytes need not end
with a zero byte. A stardust_buffer output contains data, length and
owner. Read exactly length bytes, then release owner. Do not free or
release data.
Each returned Document, database and encoded-byte owner has one release
obligation. stardust_release(NULL, NULL) is permitted. Copying a handle
pointer makes an alias to the same object; it does not retain it or create
another ownership reference. There is no retain or clone call. Release an
existing owned value before reusing its output variable.
Decode copies its input. Submit copies each accepted request. The host can
release its request Documents after submit returns, including on failure.
accepted reports the accepted prefix when a batch is only partly accepted.
Documents returned by poll and buffers returned by encode remain valid after
the database closes. Releasing a Document does not release an encoded buffer
made from it; the buffer has its own owner.
A text, bytes or Bitset value in a Document holds at most 4,294,967,295 bytes,
and a container at most 4,294,967,295 items: a cell stores its length in 32
bits. A longer text or a container with more items is refused, not shortened:
stardust_decode reports it as an invalid value. Keep larger payloads in the
objects plugin, which reads a payload by byte range.
A value that crosses into or out of a runtime (bindings, a result, one page of query results) holds at most 2,147,483,647 cells, 2,147,483,647 bytes of text and 2,147,483,647 facts. This runtime bound comes from the runtime's 32-bit counts. Past it, the request fails with a resource limit error that names the bound.
Documents are immutable value snapshots. They do not contain live sessions, cursors, subscriptions or callable handles. Links and pointers are inert data, not native pointers or automatic database lookups. Encoding and decoding do not execute a request. Copy a value independently by encoding and decoding it; TRON preserves native value and floating-point kinds.
Document reads can overlap. Submit supports multiple submitting threads, but
only one poll call can be active for a database: overlapping polls return
STARDUST_BUSY. A release must not overlap a call using the same handle.
Database release cancels outstanding work, joins workers, closes sessions and
releases undelivered responses. The library does not call back into host code.
3.1. Raw bytes
A host can send and receive bytes without a notation and without base64.
Both calls name a value with a path: the map member names from the root of
the Document, joined by /. An empty path names the root.
stardust_bytes_get writes the bytes of the Bytes or UUID value at a path to
its output. The bytes belong to the Document until you release it, so a host
reads a response page without a copy. For example, the path "result"
names the bytes of an objects/payloads/open page.
stardust_bytes_with writes a new Document to its output: a copy of a
Document whose Bytes value at a path holds the given bytes. The input
Document does not change. Decode a request once with a placeholder, such as
bytes #b64 "" in the params of objects/uploads/append, and make each
request with the path "params/bytes". If the value at the path is not
Bytes, the call returns STARDUST_WRONG_KIND.
In Go, Database.UploadPayload reads an io.Reader and publishes its bytes
with the objects plugin, and Database.WritePayload writes a published
payload to an io.Writer. Both use these calls, so the payload bytes are
never in a notation. The Go binding also reads the identity of each response
with stardust_bytes_get, so it does not encode a response to route it.
04 Configuration and codecs
4.1. Database configuration
Configuration is a Document containing a map. An empty map selects no plugins and opens no storage. The settings are:
| Field | Meaning |
|---|---|
workers |
Worker count: at least 1; default 1 |
requests |
Request capacity: 1–1,073,741,823; default 16 |
sessions |
Session capacity: at least 1; default 16 |
batch-size |
Maximum requests taken by a worker and responses returned by one poll: at least 1; default 16 |
limits |
Per-runtime memory-bytes and cpu-ticks limits |
plugins |
Set of plugin names or map of plugins to settings; omitted to select no plugins |
capabilities |
Explicit grants for host effects |
scheduled-reactors |
The tag <scheduled-reactors> runs the saved defcron forms (defcron); it requires the database plugin. Absent by default |
imports |
Import roots of the host that reads imported files, such as the CLI; the database ignores it |
The open allocates every worker, request slot and session that the
configuration names, so a larger capacity takes more memory from the start;
the open fails with STARDUST_EXHAUSTED when that allocation fails. The
request capacity's maximum is a representation bound: the response queue holds
every request, rounded up to a power of two, and its free count must stay below
231.
The memory limit is at least 1 MiB and has no maximum; the default is 256 MiB. CPU ticks are 100 ns units, at least 1, with no maximum below the 92,233,720,368,547,758 ticks whose nanoseconds fit in an int64 (about 292 years); the default is 50,000,000 ticks (5 seconds). Unknown top-level settings are rejected.
Plugins are stdlib, io, database, planner, sdks, skills,
retention, fulltext, embeddings, blackholes, events, backups,
objects, lsp and fuse. The io plugin requires
stdlib; planner requires database, because it saves plans in the database
storage, and so do retention, because it removes history from that storage,
fulltext and embeddings, because they keep their indexes in that storage,
blackholes, because it rewrites that history, backups, because it copies
history from that storage, objects, because it keeps its tree and
payloads in that storage, and fuse, because it shows that storage as files.
backups cannot be selected with retention. lsp requires io. No plugins are selected by default. Selecting plugins controls
which functions are available. Capability grants separately control whether a
runtime may access filesystem, secure random, processes, streams, network or
terminal services. Omitted grants are off. These grants are not an operating
system sandbox. Native process, stream, TCP and PTY operations currently
support Linux.
Each plugins map key selects a plugin. Use a true tag, such as
<stdlib>, for a plugin without settings, or a map for its settings. An
unknown plugin, an invalid value, or an unsupported setting refuses the open
with invalid_plugins.
The database plugin settings select the storage:
| Setting | Meaning |
|---|---|
path |
Persistent database file |
temporary |
true opens a private temporary file that release deletes |
Give path or temporary true, not both. Without either setting, or without
the database plugin, no storage opens. Evaluation and sessions work. Each
database operation fails with the no_database code: query, queries/prepare,
queries/run, queries/subscribe, transact, the imports/ methods,
plans/explain, reactors/status, the namespaces/ methods, the backups/
methods, any request with as-of (eval, sessions/open, schemas/valid? and
programs/signature), and
a query, mutation, (db/reactors) call or saved-namespace import in eval. A top-level path or temporary
is refused with invalid_config; the message names the key as a database
plugin setting.
The planner plugin accepts the following integer
settings. The sdks plugin accepts go {directory "..."} to generate Go
SDK files in that directory when the database opens and after a namespace
publication commits. Without a language configuration, it generates nothing.
The skills plugin takes the settings in Agent skills,
the retention plugin the settings in History retention,
the backups plugin the settings in Backups,
the objects plugin the settings in Object store,
the lsp plugin the settings in Editor integration,
the fuse plugin the settings in Filesystem mount,
and the io plugin the tags <clock> and <!clock> in
Scheduled reactor settings.
The other plugins take no settings. Blackholes describes
the blackholes plugin, and Events the events plugin.
| Setting | Default | Inclusive range |
|---|---|---|
queries |
256 | 1–65536 |
query-bytes |
4194304 | 65536–1073741824 |
stored-plans |
1024 | 0–1048576 |
stored-bytes |
1048576 | 0–268435456 |
The planner plugin saves proven query plans in its database storage and can
reuse them after the database reopens. stored-plans limits the number of saved
plans; stored-bytes limits their combined key and value size. Set either to
zero to disable loading and saving plans. Pending plan trials can use one third
of query-bytes. With the default, 17 trials can wait at a time; at least one
trial can always wait. If the database opens without the
planner plugin, queries use the default planner and do not use saved plans.
For example, this configuration opens a persistent file and permits filesystem operations in evaluations:
{plugins {<stdlib io> database {path "app.db"}}
capabilities <filesystem>}
4.2. Editor integration
While a database that selects the lsp plugin is open, the plugin listens on
a TCP port. It serves the Language Server Protocol 3.17: JSON-RPC messages
with a Content-Length header, without compression. An editor or an agent
connects to the port. There is no server program.
| Setting | Default | Meaning |
|---|---|---|
port |
1980 | TCP port, 0 to 65535. Without port, the first free port from 1980 up. A configured port that is in use refuses the open. With 0, the system selects a free port. |
host |
"127.0.0.1" |
IP address to bind |
port-file |
none | File that receives the bound port. The plugin removes the file at close if it still contains that port. |
{plugins {<stdlib io> database {path "arrakis.db"} lsp {port 0 port-file ".stardust-lsp-port"}}}
The socket has no authentication. A peer that connects can evaluate code and
write the database with the access of the process that opened it. For this
reason, the plugin requires io, and the database writes a warning to
standard error when it opens. Bind to a loopback address if the network is not trusted. If a
different process uses the port, the open fails with invalid_plugins. The
plugin reads its settings when the database opens.
The plugin sends each database operation as an ordinary request. These
requests use the same workers, sessions and request capacity as the host.
When every request slot is busy, an editor request waits in the plugin and
runs when a slot becomes free. Waiting database operations start in the
order that they were queued, and their number has no limit. Each ready
operation of a multi-step command joins the end of that queue. A request can wait for as long as
every slot stays busy, for example while live queries hold all the slots.
$/cancelRequest or the end of the connection removes a waiting request.
When the database closes, it first closes the connections of the plugin and
ends their requests. The stardust/status request reports the port and the
number of connections, sessions and subscriptions. stardust/capabilities
reports the command registry and its SHA-256 digest. An agent can compare the
digest to find a server with different commands.
4.3. Entity navigation
The entities/ requests read one entity. Each request takes entity, a #link value
or an integer entity ID. An optional as-of gives a transaction or a UTC
time. Without as-of, the requests read the head. They run on any worker.
| Method | Parameters | Result |
|---|---|---|
entities/read |
entity, optional as-of |
{entity fields}: the entity's fields, with links as #link values |
entities/backlinks |
entity, optional as-of |
A list of {entity field tx nested}: each entity whose current field value links to it. nested is true for a link in a list or map. |
entities/history |
entity, optional field, limit and as-of |
A list of {field tx value}, newest first. A retracted value has retracted true instead of value. |
{method "entities/read" params {entity #link 2}}
; result {entity #link 2 fields {house #link 1 name "Paul"}}
{method "entities/backlinks" params {entity #link 1}}
; result [{entity #link 2 field "house" tx 5 nested false}]
An entity that does not exist at the selected transaction reports
entity_not_found. The lsp plugin uses these requests for #link
navigation.
4.4. Agent skills
The skills plugin writes agent skills that describe the database: one
directory with a SKILL.md file for each topic, in the Agent Skills format
that coding agents read. The stardust skill is the starting point. The
other skills cover namespaces, queries, mutations and reactors, schemas,
functions, entities, subscriptions, imports, objects and operations. Each
skill tells an agent how to send the requests of its topic. Text about an
optional plugin appears only when the database selects that plugin.
Generated reference pages describe the saved definitions: a page for each
namespace, schema, query, mutation, reactor and blackhole, with its source,
its parameters and the call or request that runs it. With the Go SDK of the
sdks plugin, a page also names the Go method. A page for each namespace of
the function index lists the documented builtin functions with their
signatures.
| Setting | Default | Meaning |
|---|---|---|
dir |
none | Output directory; a relative path is relative to the working directory at open. Without dir, the plugin writes nothing. |
site |
"https://www.stardustdb.com" |
Website origin for links to the reference manuals: http or https, without a path |
debounce |
#dur "PT0.25S" |
Time without namespace saves before the plugin writes the skills |
max-wait |
#dur "PT2S" |
Longest time after a save before the plugin writes the skills |
{plugins {database {path "app.db"} skills {dir ".claude/skills"}}}
The plugin writes the skills when the database opens and after namespace
saves, in the background. It owns the skill directories that it writes below
dir, such as stardust and stardust-query: each write removes the other
files in them, such as the page of a deleted definition. It does not change
other files in dir. A render failure changes no files. Each file is
replaced atomically; a later publication failure can leave some files
updated. A failure sets last-error; the next save or skills/sync tries
again.
The skills/status request reports the writes since the database opened. It
takes no params and starts no write. The result has runs, last-run (a
#utc, or null before the first write), files (the files of the last
successful write), directory (null without dir), pending (true while a
write waits for debounce or max-wait) and last-error (null when the last
write succeeded). The skills/sync request writes the skills at once and
returns the same result. Without dir, it builds the files and writes
nothing.
4.5. History retention
Each write adds a version of a fact, and the database keeps every version.
The retention plugin removes old versions of the fields that its settings
name, and of the entities that have a policy. Its fields map gives each
field one retain value:
retain |
Kept history |
|---|---|
| An integer N, 1 or more | The newest N values of each fact, and the value before them |
A positive #dur |
The values written within that time before now, and the value before them |
A #utc |
The values written at or after that time, and the value before them |
For example, this configuration keeps the newest 10 values of status, 30
days of audit and the history of log from 2026:
{plugins {database {path "arrakis.db"}
retention {fields {status {retain 10}
audit {retain #dur "P30D"}
log {retain #utc "2026-01-01T00:00:00Z"}}}}}
An entity can also have its own policy in the stardust/history field, for
example {stardust/history {retain 5 cascade true}}. An integer retain
keeps the newest N transactions that wrote a field of the entity, and the
value before them. A #dur or #utc keeps history as in a field setting.
With cascade true, the policy also applies to the descendants of the entity
through stardust/path/parent
(Keep less history of an entity). When a
field setting and an entity policy apply to the same fact, the one that keeps
more history applies.
A plugin that reads old snapshots can hold history back with
Spec.history_floor. No removal step removes what a read at or after the
lowest floor needs. A pass that a floor held back sets held-back and runs
again after recheck.
Native plugins that plan a removal from a Facts read use Facts.snapshot
as the snapshot of Prune or Entity_Prune. The host checks this revision
under the write lock. An intervening write returns Stale without changing
history or progress, unless the optional read-only validate callback proves
the plan still valid in that same write transaction. The callback must not
call host operations or write. Read failures return Failed. A committed
guarded step advances snapshot to its new revision. Zero disables the guard.
The retention plugin checks field revisions and linked policy values, so
ordinary unrelated commits preserve the cursor of a yielded removal pass.
Facts.field_revision reads those field stamps in the callback's snapshot.
The per-open Facts.history_revision marker invalidates cached count bounds
when a rewrite, restore or other removal changes older history.
The plugin removes old versions in the background, in small steps that each
commit on their own. A commit that writes facts starts a removal pass after
debounce (default #dur PT2S) without more commits, and not later than
max-wait (default #dur PT30S) after that commit. A #dur or #utc value
also starts a pass every recheck (default #dur PT1M) without commits, and
so does a pass that failed or that a floor held back. A database that opens
starts a pass after debounce, so removal continues after a restart.
Removal never changes the current value of a fact. An as-of read before the
oldest kept value reads the oldest kept value, and no read fails. Removal
never waits for readers, and readers never see it: each request reads one
snapshot, and a session opened with as-of reads one snapshot until it closes
or resets. While such a session is open, the database cannot reuse the pages
of its snapshot, and the file can grow. List values release their storage
chunks, and the database deletes the chunks that no kept value uses.
The retention/status request reports what removal did since the database
opened. It takes no params and starts no pass. The result has runs,
last-run (a #utc, or null before the first pass), entities (the distinct
entities whose versions the last pass changed; when memory ran out while
counting them, an upper bound, and last-error says so), deleted, rewritten
(versions that took the oldest kept value), removed-pairs (facts with no
versions left), freed-chunks, held-back (a history floor held the last
pass back), last-error (null when the last pass did not fail) and pending
(a commit waits for a pass, or a pass runs). A pass that fails on a field or
an entity records last-error, continues with the other work and runs again
after recheck.
4.6. Blackholes
A retraction hides a value from current reads, but as-of reads still return
it. The blackholes plugin erases or replaces selected values in every
version, current values included. Use it for erasure requests and for leaked
secrets. It takes no settings, and it requires database storage:
{plugins {database {path "app.db"} blackholes {}}}.
A defblackhole form in a saved namespace defines a blackhole (see the DUST
reference). Its query selects rows. Each patch key is a query variable that
binds an entity. A null value erases every field of that entity. A map gives
each field null (erase) or an expression that computes a replacement for
each version. links {incoming remove} removes the links to an erased entity
from other fields. Without it, such a link refuses the blackhole.
Operate in two steps. First send blackholes/preview with
{namespace "<path>" name "<name>" args [...]}. The result has these members:
| Member | Meaning |
|---|---|
digest |
The approval digest, a #hash #sha256 value |
targets |
The number of (entity, field) pairs |
matched |
The versions that change |
replacements, removals |
The versions that get a value, and the versions that become retractions |
confirm |
The text PERMANENTLY REWRITE HISTORY AND BACKUPS |
affected |
{entities [...] fields {field [...]}}, the changed entities; absent when empty |
samples |
Up to 10 replacements {entity field transaction replacement}; absent when there are none |
Then send blackholes/execute with the same members and digest, confirm,
actor and reason. actor and reason are nonblank strings. Execute takes
the database's write lock, selects and plans again with a new seed, and
compares the digest. Any commit since the preview, a changed definition or
other arguments give conflict, and nothing changes. Otherwise one write
transaction changes every version and writes the audit. Each selected
version becomes a removal or its replacement. Then a version that equals the
one before it goes, as if it was never written: an erased field that never
had another value has no versions left, and a replacement that gives several
versions the same value keeps the first of them. A read at any transaction
gives the same result as with every version, and entities/history lists
fewer versions. A database that the backups plugin restores has the same
history. The result is
{stage transaction cutoff targets matched replacements removals request-digest
effect-digest}. stage is "complete", or "recovering" when a backup
target did not take the change yet.
With the backups plugin, execute waits until the backup worker is idle and,
before it takes the write lock, requires each target to hold exactly the local
history; otherwise it refuses with unavailable_backup and changes nothing.
After the commit, each target replaces its copy of the changed history. A
record in the plugin's storage keeps every target dirty until then. When a
replacement fails, the result has stage "recovering", and the backups
plugin finishes the replacement in the background or when the database opens
again, and then deletes the record. Until then, a new execute refuses with
backups_pending. Execute does not wait for the write admission of the
backups plugin. A database restored from a target has the rewritten history
and lists its audits. Without the backups plugin, execute changes the local
database only, and the audit has backups false. A recovery record from an
earlier open with backups remains until that plugin finishes it; new executes
refuse with backups_pending even while the backups plugin is absent.
An execute never waits for reads. A session opened with as-of reads one
snapshot until it closes. Thus a session that opened before an execute reads
the old values until it closes. The database reclaims their storage after
those sessions close. A replacement expression can read ?value, ?entity,
?field, ?transaction, ?seed (64 hexadecimal digits, new for each
operation), the variables of its row and the parameters. When a row does not bind a
variable that an expression reads, preview and execute fail with
unbound_variable and nothing changes. Only an optional group that does not
match leaves a variable unbound. A null that the row binds, such as the
default of lag, is a value. A null or false
result is a removal. A map, code and the other values that a field cannot hold
refuse the operation.
Each execute adds one transaction with one stardust/blackhole fact on a new
entity, the audit. It names the definition and its namespace revision, the
actor, the reason, the counts, the digests and affected. It holds no erased
value, no argument and no seed. No other write can write this field.
blackholes/audit lists the audits in transaction order and takes optional
after and limit. Without limit, it lists every audit after after.
limit is a positive integer. blackholes/status returns enabled,
audits, recovering and backups. Without database storage, preview,
execute and audit refuse with no_database, and status reports no audits.
Refusals have these codes: invalid_params, invalid_confirmation,
invalid_args, unknown_blackhole, invalid_definition, invalid_query,
invalid_expression, target_not_entity, unbound_variable,
conflicting_targets, incoming_links, invalid_target,
invalid_replacement, no_match, expression_failed, work_limit,
exhausted, conflict, cancelled, closing, import_active,
unavailable_backup, backups_pending, no_database and
storage_failed. Messages never contain values.
Limits of removal:
- Freed storage pages are not zeroed, and the file does not shrink.
- A session opened with
as-ofbefore the execute reads the old values until it closes. - Copies outside the database stay: file copies, snapshots, and backups when
the
backupsplugin is not selected. - Field names stay in the field dictionary.
- A list chunk that another kept fact holds stays.
- A later write can store the value again.
- Values that reactors or applications copied to other fields stay. Select those fields in the same definition.
4.7. Events
The events plugin carries temporary messages between the requests of one
open database. A publication tells every matching subscription that
something happened. An exchange connects one caller with one worker. Nothing
is stored, acknowledged, retried or replayed: a message reaches only the
requests that are open when it is sent. Record facts first when an event must
survive, and publish in an on {commit …} body after the write. The plugin
takes no settings: {plugins {database {path "app.db"} events {}}}.
A subject is non-empty UTF-8 of slash-separated segments, such as
orders/created. A pattern is a regular expression, as the DUST regex
functions use it, that must match the whole subject: orders/.* matches
orders/created, and created does not.
events/subscribe, events/accept and events/call are long-lived requests.
Each delivers its notices as pages with more true, one page at a time, and
holds no request worker between pages. The request owns what it opened: a
cancel request for it, or the database closing, ends its subscription,
worker or exchange, frees its queue and cancels its exchanges. A cancelled
request ends with cancelled. Resident queues use the plugin allocator and
have no configured size or count limit. They do not count against a runtime's
limits.memory-bytes allowance. If queue allocation fails for a publication,
that subscription drops the delivery and counts it in its next event's
dropped. Failure to queue an exchange notice cancels that exchange with
delivery_failed.
The CPU limit covers a publication and its complete chain of saved handlers. Stopping the chain does not undo earlier deliveries or committed writes. Each handler expression has its own runtime memory limit.
An exchange has a mode. The caller of request and pull sends one request
as the call's data; the caller of push and duplex sends a stream with
events/send and ends it with events/finish. The worker of request and
push answers with one events/send, a push worker after the caller
finished; the worker of pull and duplex sends a stream and finishes it.
The earliest open worker whose mode and pattern match takes the call; with
none, the call fails with no_worker. events/cancel ends an exchange from
either side, and the other side reads cancel. A saved responder answers a
request call before any worker.
| Method | Params | Responses |
|---|---|---|
events/status |
none | {subscriptions registrations rpcs queued runs failures} |
events/publish |
subject, data |
{delivered dropped}, with failures when a saved subscription failed |
events/subscribe |
pattern |
Pages {subject sequence dropped data}; ends when cancelled |
events/accept |
mode, pattern |
Pages {kind handle rpc …} for each exchange's open, message, finish and cancel; ends when cancelled |
events/call |
mode, subject, data for request and pull |
Page {handle rpc}, pages {kind data?}, then {kind "complete"}; a saved responder answers {kind "message" data} at once |
events/send |
handle, data |
{} |
events/finish |
handle |
{} |
events/cancel |
handle |
{} |
A request exchange with a worker:
[{id 1 method "events/accept" params {mode "request" pattern "math/.*"}}]
[{id 2 method "events/call" params {mode "request" subject "math/add" data {a 1 b 2}}}]
; {id 2 page 0 more true result {handle 5 rpc 4}}
; {id 1 page 0 more true result {kind "open" handle 6 rpc 4 mode "request" subject "math/add" data {a 1 b 2}}}
[{id 3 method "events/send" params {handle 6 data 3}}]
; {id 3 result {}}
; {id 2 page 1 more true result {kind "message" data 3}}
; {id 2 result {kind "complete"}}
(defsubscription name pattern fn) and (defresponder name pattern fn) in a
saved namespace are handlers that the database runs itself (see the DUST
reference). events/publish runs the matching saved subscriptions before it
returns, in publish order, and lists a failed body in failures as
{namespace name subject error}, together with the failed on handlers of
the body's writes. A failure never undoes the publication. A request call
on a subject that one saved responder matches gets the responder's value at
once. A save or namespaces/check that defines a responder whose pattern is
written the same as another saved responder's is refused with name_conflict
("math/add already answered by app/math/add"). A subject that two
different patterns match fails the call with conflict. events/status counts the saved handler runs and failures since
the database opened. The exchange
and handler conformance
fixtures show every request with its complete responses.
4.8. Backups
The backups plugin copies every committed transaction to one or more
targets. A target is a directory. The copy is continuous: a plugin thread
copies new transactions soon after each commit. Each target holds the full
history, so a restored database has the same transactions, the same
transaction IDs and the same as-of results. The backups plugin cannot be
selected with the retention plugin, because a removal changes history that
the targets already hold.
The backups plugin requires database. Without storage there is no history
to copy: the open reads no target, and each backups/ request fails with
no_database.
The file target is not available on Windows. On Windows, a configuration
with a file target refuses the open with invalid_plugins and the message
backups: the file target is not supported on Windows. The target's
durability rests on POSIX file operations: a link that never replaces another
file, a flush of each directory after a rename or a removal, and a private
creation file that the user owns with mode 0600. On Windows, a file that is
open cannot be renamed or removed, and ownership and access are access-control
lists, not modes. The backups plugin with no targets opens on Windows.
{plugins {<stdlib>
database {path "app.db"}
backups {targets {local {file {path "/srv/backups/app"}
maximum-lag {transactions 100}}
archive {file {path "/mnt/archive/app"}
compression {algorithm "zstd" level 3}
encryption-key "<64 hexadecimal digits>"
maximum-lag {duration #dur "PT5M"}}}}}}
| Setting | Default | Meaning |
|---|---|---|
targets |
no targets | A map of target names to target maps |
bypass-unreachable |
false |
When true, a target that the plugin cannot reach does not hold writes, unless it restores or is not compared yet |
restore-through |
none | Restore a new database from the targets, up to and including this transaction ID |
A target name is not empty, is not . or .., and has no /, \ or NUL.
A target map has the file member and these optional members:
| Member | Default | Meaning |
|---|---|---|
file |
required | {path "<directory>"}. A relative path starts at the working directory of the process |
compression |
{algorithm "none"} |
{algorithm "zstd" level N} compresses the runs; level 0 is the zstd default |
encryption-key |
none | 64 hexadecimal digits: an AES-256 key that encrypts runs and chunks |
maximum-lag |
no limit | Limits that hold writes, see below |
The configuration holds the encryption key. The host gets the key from its own secret store and puts it in the configuration. The plugin does not keep the key in the database, and status and errors never show it. Two targets with the same directory refuse the open.
4.8.1. Targets
A target directory holds manifest.json, the runs in runs/ and the list
chunks in chunks/. A run holds the records of consecutive transactions. A
SHA-256 chain links the records, so each manifest names exactly one history.
A chunk is stored once, under the SHA-256 of its content. The manifest lists
the SHA-256 of every chunk that its runs use, in ascending order. The plugin
writes a run and its chunks before the manifest names them, and replaces the
manifest last. After a manifest change, the plugin deletes the runs that the
manifest no longer names. Each full check of a target, at open, after a retry
and for backups/verify, also deletes every run and every chunk that the
manifest does not name. Each target has one writer. The plugin locks
.writer.lock in the directory.
A target also holds the object payloads that the history names (the objects
plugin). Each payload is stored once: its chunks are chunk objects in
chunks/, so a chunk that payloads or lists share is stored once, and its
chunk list, in byte order, is in binaries/ under the payload's SHA-256. The
plugin stores a payload before the first run whose records name it, one
chunk in memory at a time, and skips the chunks that the target already
holds. The manifest lists the payloads and their chunks, and counts the
payload references of each run. With encryption-key, chunk lists are
encrypted as chunks are. When the objects plugin is not selected, a target
whose next run would name a payload fails with backup_objects_required.
At each open the plugin reads every run of each target and checks the
digests, the order and the chain. Each record must use only chunks and
payloads that the manifest lists, and each run must count its payload
references. The plugin then reads every chunk that the manifest lists and
checks its digest, and reads the chunk list of every payload that the
manifest lists. Each chunk of a list must be in the manifest. A target that
fails these checks fails with backup_corrupted. The full check also
deletes every chunk list that the manifest does not name.
After a blackhole changes history, the plugin replaces the history of each target and deletes the chunks and payloads that only the removed data used. The target holds writes until these deletions are complete.
When creating a directory target, the plugin first records pending creation in a private file in the nearest existing ancestor directory. That file stays until the new directories are durable, even if cleanup after a failure cannot remove them. Retry the same target path to complete creation. An existing root without pending creation needs only traversal permission on its ancestors. A read-only restore source refuses pending creation without repairing it.
4.8.2. Write holds and lag
A target holds new writes in these conditions:
- until it first holds the newest transaction after the open;
- while it restores, or until the plugin compares it with the database;
- while the plugin cannot reach it, unless
bypass-unreachableis true; - when it failed, until the database opens again with changed settings;
- when its lag passes a
maximum-laglimit.
maximum-lag member |
Holds writes when |
|---|---|
transactions |
more transactions than this are not on the target |
logical-bytes |
the records of those transactions have more bytes than this; the payloads that the records name are not counted |
binary-bytes |
distinct list and object payload chunk records still needing a readable copy have more bytes than this (kind byte plus payload, before compression/encryption); shared or repeated chunks count once |
duration |
the oldest of those transactions committed earlier than this #dur before now |
For a binary-bytes limit, the worker measures chunks outside the commit and
admission paths. A new commit holds the next write until that measurement is
current. Payload chunk-list metadata and encryption/compression overhead do not
count. A chunk already readable on the target counts zero, including a plaintext
copy that an encrypted target can still read. The status reports lag.binary-bytes
only when this limit is configured and measured; it never reports an unmeasured zero.
A held write waits. It continues when the hold ends, and it ends with
cancelled when the request is cancelled and with closed when the database
closes. Held writes are transact, a mutation in eval, namespaces/save,
imports/begin and imports/finish. Reads are never held. A transact with
dry-run true is held as a real run is, but it commits nothing: it adds no lag,
and nothing of it reaches a target.
4.8.3. Restore
To restore, open an empty database with the same backups settings. The
open compares each target with the database and then returns. The plugin
thread replays the records of the target with the newest history through the
ordinary write path. It restores each run of the target in one write
transaction. A run is restored completely or not at all. If the restore
stops, the next open continues after the last run that it restored. Records
go from the target to the database in pieces, so a record of any size
restores: the restore holds one batch of facts and one value at a time.
Writes are held until the restore ends.
backups/sync waits for the end of the restore.
Before the plugin restores a run, it publishes each payload that the
restored records name and that the database does not hold. It sends the
payload's chunks from the target to the objects plugin in byte order,
one at a time; the objects plugin checks the payload's SHA-256 and size,
as for an upload. The restored facts then hold the payload, and the
objects plugin brings its path index up to date in the restore's write
transaction. A restore whose history names payloads needs the objects
plugin: without it, the open fails with the reason
backup_objects_required.
restore-through restores into a new database. Open a database path that
does not exist yet, or temporary true, with the backups settings of the
targets and restore-through set to a transaction ID. The plugin replays the transactions up to and
including that ID. It only reads the targets. It does not write to them,
clean them or attach to them. When the restore ends, the plugin stops using
the targets. Their phase becomes "restored", and the database admits
writes. The database is then an ordinary database.
The targets can hold transactions after restore-through. Thus they cannot
be the targets of the restored database. To back up the restored database,
open it again without restore-through and with new targets. If an open
names an old target again after the database wrote new transactions, the
open fails with backup_history_divergent.
An open with restore-through fails with backup_restore_target_exists when
the database path exists or the database holds transactions.
An open refuses a database in these conditions. The error is
invalid_plugins, and its reason member names the condition:
reason |
Condition |
|---|---|
backup_history_divergent |
Two copies hold different histories. first and second name them; local is the database |
backup_target_unreadable |
The target with the newest history cannot be read |
backup_targets_unreachable |
The database is empty and the plugin can reach no target |
backup_blackhole_recovery |
A blackhole changed history and the plugin cannot replace a target's copy |
backup_restore_target_exists |
restore-through is set, and the database path exists or the database holds transactions |
backup_objects_required |
The history to restore names object payloads, and the objects plugin is not selected. first names the copy |
The open writes nothing when it refuses.
4.8.4. Requests
backups/status takes no params. It does not read targets. The result has
enabled, head (the newest local transaction), writes-admitted,
bypass-unreachable, restore-through and targets, one map for each
target:
| Member | Meaning |
|---|---|
name |
The target name |
provider |
"file" |
source |
True when restore-through is set. The target is then a restore source and not a target of this database |
phase |
"starting", "validating", "reconciling", "synchronizing", "synchronized", "retrying", "failed", "stopped" or "restored". "restored" tells that the restore from this source is complete and the plugin does not use it again |
cursor |
The newest transaction on the target, or null |
synchronized |
True when the target holds head |
restoring, comparison-pending |
The restore and comparison states |
dirty |
A blackhole changed history that the target still holds |
verified |
The last full check of the target passed |
compression, encrypted |
The settings in use; the key never shows |
code |
The last failure code, such as backup_target_unreachable, or an empty string |
lag |
{transactions N logical-bytes N} when the plugin knows the lag; with a binary-bytes limit, also binary-bytes N |
backups/sync waits until every target holds the newest transaction as of
the request. params {max-wait #dur "PT30S"} sets the longest wait; without
it the request checks once. The result is {}, or one of these errors:
backup_target_failed (the message names the target),
backup_sync_timeout, cancelled or closed.
backups/verify makes the plugin read and check every target again now. With
max-wait, it waits for the checks and returns {targets [{name ok code}]}.
Without max-wait, it starts the checks and returns the current state. A
restore source is not checked again. Its code is backup_restore_source.
4.9. Object store
The objects plugin keeps large binary payloads, such as images and
documents, and gives them names in a tree of files and directories. It
requires the database plugin, as in
{plugins {database {path "arrakis.db"} objects {timeout #dur "PT10M"}}}.
When the database plugin opens no storage, each objects/ request fails
with the no_database code. Its timeout setting, a positive #dur
(default #dur PT1H), is how long an upload can wait for its next request and how long a published payload can
wait for a fact that names it. The sum of the current time and timeout must be at most 9223372036854775807
ticks after the Unix epoch. Each tick is 100 ns.
A payload is a sequence of bytes. Its name is its SHA-256 digest, a
#hash #sha256 value. The plugin cuts a payload into chunks of 256 KiB to
4 MiB at positions that the content selects. Thus an edit in a large payload
changes only the chunks near the edit. The database keeps one copy of each
chunk and of each payload. A published payload does not change.
To send a payload, use these requests:
objects/uploads/beginreturnsupload, an integer ID.objects/uploads/appendwithupload,offsetandbytes(a#b64value) adds bytes and returnssize, the number of bytes that the upload has.offsetmust be equal to that size before the request. If not, the request fails with theconflictcode and adds nothing. After a failure,objects/uploads/getwithuploadreturnssize, the accepted offset. Send the remaining bytes again from that offset.objects/uploads/finishwithuploadpublishes the payload and returnsdigest,sizeanddeduplicated(the payload was already published). Optionaldigestandsizegive the payload that you expect. If the payload is different, the request fails with theconflictcode and publishes nothing. The upload continues until you finish or abort it.objects/uploads/abortwithuploaddeletes an upload that is not finished.
The number of uploads has no limit. Each active upload uses 4 MiB of memory
for the chunk that it cuts. An upload that gets no request for timeout is
deleted. Uploads that are not finished when the database closes are deleted
when the database opens again.
objects/payloads/open with digest sends the payload in pages, one chunk
per page, in byte order. Each page has page, more true and a result
that holds the bytes of one chunk. The last response has digest, size
and chunks, the number of pages. objects/payloads/manifest with digest
returns digest, size and chunks, a list of {digest size} in byte
order.
The tree is entity facts, so queries can read it. A directory has the fields
stardust/path/name, stardust/path/parent and
stardust/path/container true. A file has stardust/object/digest instead
of stardust/path/container. The root directory is entity 0 in requests.
A name is UTF-8 of any length other than . and .., without / or NUL. A
name occurs once in a directory. A path is the names from the root, joined
by /, and has no length limit. Only the tree requests write the
stardust/path/ fields. Other patches can write stardust/object/digest,
but only with the #hash #sha256 digest of a published payload. A tree file
must keep its digest, and a directory cannot have one. A patch that
retracts a whole entity with null retracts these fields too, so it cannot
retract a tree node. A patch
that writes these fields fails with the plugin_required code when the
database does not select the objects plugin. Patches cannot write other
fields whose names start with stardust/. You can add your own fields to a
file or directory entity.
A payload lives as long as something holds it. Until a fact names it, the
upload that published it holds it, for at most timeout after the upload
finished; then the database frees it. Every version of a fact that holds its
digest then holds it, so a removed file's payload stays while history names
it. When the retention plugin removes the last version that names a
payload, the database frees the payload and its chunks, also when the
database does not select the objects plugin. The plugin frees expired
payloads in the background and when the database opens, so this continues
after a crash.
A node record is {entity parent name kind revision}, with size and
digest for a file. kind is "file" or "directory". revision is the
last transaction that changed the node. The tree requests are:
| Method | Params | Result |
|---|---|---|
"objects/create" |
nodes, a list of {name parent digest} or {name under digest} |
The records |
"objects/get" |
entity |
The record |
"objects/lookup" |
path, or parent and name |
The record |
"objects/children" |
parent |
The records in name order |
"objects/path" |
entity |
The names from the root |
"objects/files" |
digest |
The files with that payload, in entity order |
"objects/update" |
entity, digest, optional expected-revision |
The record |
"objects/move" |
entity, parent, name, optional expected-revision and replace |
The record |
"objects/remove" |
entity, optional expected-revision |
{} |
objects/create creates all of its nodes in one transaction. A node with
digest is a file, and a node without it is a directory. parent is the
entity of a directory (default 0). under is the position, from 1, of a
directory earlier in the same list. The payload of a file must be published.
objects/lookup reads a path index, so a lookup is one read for each path.
objects/update changes the payload of a file. objects/move renames a node
or moves it to a different directory. A directory cannot move into itself.
If the new name is in use, the request fails with the conflict code, unless
replace true is given. Then the move replaces a node of the same kind; a
directory must be empty. objects/remove removes a file or an empty
directory. The payload stays published. With expected-revision, a change
fails with the conflict code when the node has a different revision.
Tree changes go through the database's commit queue. Each change checks its node, its names and its expected revision in the queue's write transaction, so no other write can come between the check and the change.
Other error codes are invalid_params, not_found, corrupted,
storage_failed and import_active.
4.10. Filesystem mount
The fuse plugin shows an open database as a directory tree. Usual file
tools, such as ls, cat, cp, mv and text editors, can then read and
change the data. The plugin requires the database plugin. It loads libfuse 3
on Linux, or FUSE-T on macOS, when it mounts. Windows has no mount: a mount
setting there refuses the open. On Windows, use the Linux build in WSL2.
{plugins {database {path "shop.db"} fuse {mount "/mnt/shop" read-only false}}}
| Setting | Default | Meaning |
|---|---|---|
mount |
none | Existing directory where the tree appears. A relative path starts at the working directory. Without it, nothing is mounted. |
read-only |
false |
true refuses every change through the mount |
The plugin mounts when the database opens and unmounts first when the
database closes. If the mount fails, the open fails with invalid_plugins,
and nothing stays mounted. If the process stops without a close, the system
removes the mount. Only the user that opened the database can use the mount.
The tree shows the data in each format that the codecs write: <f> is
dust, json, edn, ron or tron. Each file holds one value. A text
file ends with a line break.
The log files show retained history, not an immutable audit log. History
pruning can omit writes and coalesce older values. A committed transaction
can therefore have an empty retained patch. A transaction ID that never
committed has no file.
| Path | Content | Change |
|---|---|---|
format/<f>/data/entities/<id>.<f> |
The fields of one entity | Save, rm retracts every field |
format/<f>/log/<tx>.<f> |
Retained history for one transaction, as a patch map | None |
format/<f>/patch.<f> |
Reads empty | Write a patch or a mutation map |
format/<f>/data/objects/file-to-hash/<path>.<f> |
The digest of an object file | None |
format/<f>/data/objects/hash-to-files/<hex>.<f> |
The paths of the object files with that digest | None |
format/<f>/data/schemas/<path>/<Schema>/<id>.<f> |
The entities that an exported defschema accepts |
As the entity's file |
namespaces/<path>.dust |
A saved namespace's source | Save, create, rm, mv; mkdir and rmdir for directories |
objects/<path> |
The bytes of an object file | None |
The objects directories are present when the database selects the
objects plugin. A namespace file shows the source as stardust namespace
read prints it. A namespace's entity is not in data/entities.
A file that you write is saved when you close it or synchronize it. An entity
file is saved with one transact: the save writes the fields that the
document has, and it retracts the other fields of the entity. A namespace file
is saved with one namespaces/save. A new file in a namespace directory
creates the namespace. A file that holds nothing saves nothing. Write a patch
map, or a mutation map with patch and an optional if, to patch.<f> to
create entities and to change them.
A save fails with ESTALE when the entity or the namespace changed after you
opened the file. The change that came first stays. Read the file again,
then save again.
Editors often write a temporary file and rename it over the document. A name
that is not a document, such as .notes.dust.swp, is a scratch file. The
plugin keeps a scratch file in memory and stores nothing. When you rename a
scratch file over a document, the plugin saves its content. This save fails
with ESTALE when the document changed after the scratch file was made. The
plugin discards scratch files when the database closes. After a scratch
file is saved by renaming it, reopen the destination before writing again.
Writes or truncation through the old descriptor fail with ESTALE; its
reads keep the saved scratch bytes, and its close repeats a refused write.
A removed namespace directory inode stays retired when the same name is
created again. Mutations through its old descriptor fail with ESTALE.
Linux can instead report ENOENT when it rejects a removed directory
before the request reaches FUSE.
A scratch file keeps its directory and ancestor directories present until
the scratch file is removed.
A namespace directory move includes its saved namespaces and empty
subdirectories. Replacing a nonempty directory fails with ENOTEMPTY.
A directory with unsaved namespace files or scratch files fails with
EAGAIN before anything moves. Save and close the namespace files, and
remove scratch files before trying again.
A namespace hook can fail after the save has committed. In that case the
filesystem save succeeds, and fuse/status records the hook failure.
Other changes fail with EPERM. Every change fails with EROFS when
read-only is true. The kernel error tells only the type of a failure. The
fuse/status request gives the reason:
| Member | Meaning |
|---|---|
mounted |
true while the mount serves requests |
mountpoint |
The mount directory, or null |
read-only |
The read-only setting |
backend |
"fuse3" or "fuse-t" |
open-files |
The files open through the mount |
failures |
The changes that failed since the database opened |
last-failure |
null, or {status code message path} of the last failed change |
| Error | Cause |
|---|---|
ESTALE |
The document changed after it was read (conflict) |
EINVAL |
The document is not one value of its format, or the database refused it |
EAGAIN |
An import holds the write transaction |
ENOMEM |
Memory ran out |
ENOTCONN |
The database is closing |
4.11. Notation settings
A null options handle selects DUST with comments enabled. Decode reads one
value, not a source file containing several top-level forms. To select another
format, first decode an options Document such as {format "json"} using the
default DUST decoder, then pass that handle to decode or encode.
Formats are "dust", "ron", "json", "edn" and "tron".
Decode accepts spans true to retain byte positions for diagnostics and
comments false to discard comments. Positions are 32-bit: with spans, an
input past 4 GiB is refused (Spans_Too_Large); without spans, input has no
size limit. Encode also accepts the comment setting.
DUST and RON encode accept width from 1 to 65,535 (default 100) and order
of "sorted" (default) or "source". EDN accepts width.
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.
06 Errors and status codes
Every ABI function returns an int64_t status. Output slots are cleared on
entry. On failure, a non-null error output receives an independently owned
Document when allocation permits. It contains an #err map with code,
message when available, and diagnostic members such as position or offset.
Release it after inspection. The status remains authoritative when no diagnostic
can be allocated.
| Status | Value | Meaning |
|---|---|---|
STARDUST_OK |
0 | The ABI call succeeded; inspect any request results separately |
STARDUST_INVALID_ARGUMENT |
1 | Invalid arguments, options or request data |
STARDUST_WRONG_KIND |
2 | A live handle has the wrong kind |
STARDUST_INVALID_INPUT |
4 | Notation input cannot be decoded |
STARDUST_EXHAUSTED |
5 | Memory or an internal sequence is exhausted |
STARDUST_BUSY |
6 | A file is locked or another poll is active |
STARDUST_UNSUPPORTED |
7 | An operation or format is unsupported |
STARDUST_CLOSED |
8 | The database is closing |
Use valid, live handles of the declared types. Arbitrary pointers, double
release, use after release and overlapping input/output slots are caller errors.
The STARDUST_WRONG_KIND check does not make arbitrary native pointers safe.