Minigraf
v3.0.0 (unreleased)

Error Reference

On this page

This document covers every user-facing error produced by the core Minigraf Rust library. Errors surface as MinigrafError values returned from db.execute(), db.prepare(), and related API methods.

Reference codes (e.g. PRS-001) appear in runtime error output as [CODE] message, and programmatically via MinigrafError::code() / MinigrafError::category(). As of #277, every bail!/anyhow! call site in the crate has been migrated to a specific structured code — INT-000 is now reserved for the rare case of a raw, non-anyhow error (e.g. an io::Error) reaching the public API boundary with no CodedError anywhere in its chain.

Out of scope: FFI/binding errors from minigraf-python, minigraf-node, and minigraf-wasm are handled in those repos.


Quick Reference Table#

CodeError (prefix)Category
PRS-001Unexpected end of inputParser
PRS-002Unexpected characterParser
PRS-003Unexpected tokenParser
PRS-004Unclosed vectorParser
PRS-005Unclosed listParser
PRS-006Unterminated mapParser
PRS-007String exceeds maximum lengthParser
PRS-008Keyword exceeds maximum lengthParser
PRS-009Tagged literal exceeds maximum lengthParser
PRS-010Expected command symbolParser
PRS-011Unknown commandParser
PRS-012Expected a list starting with commandParser
PRS-013Query requires a map argumentParser
PRS-014:as-of requires a valueParser
PRS-015:as-of counter must be non-negativeParser
PRS-016:as-of must be integer or ISO 8601Parser
PRS-017:valid-at requires a valueParser
PRS-018:valid-at must be ISO 8601 or :any-valid-timeParser
PRS-019:valid-from must be ISO 8601Parser
PRS-020:valid-to must be ISO 8601Parser
PRS-021:with requires aggregate in :findParser
PRS-022:with variable not bound in :whereParser
PRS-023Aggregate variable not bound in :whereParser
PRS-024Aggregate expression must have 2 elementsParser
PRS-025Aggregate function name must be a symbolParser
PRS-026Aggregate argument must be a variableParser
PRS-027Window function requires :over clauseParser
PRS-028Window expression cannot be emptyParser
PRS-029Window function name must be a symbolParser
PRS-030lag/lead not supported (deprecated)Parser
PRS-031Function is not window-compatibleParser
PRS-032Function requires variable before :overParser
PRS-033Function requires :over after variableParser
PRS-034Function requires :over after function nameParser
PRS-035:over must be followed by a listParser
PRS-036Unexpected tokens after :over clauseParser
PRS-037:partition-by requires a variableParser
PRS-038:order-by requires a variableParser
PRS-039Unknown option in :over clauseParser
PRS-040Unexpected element in :over clauseParser
PRS-041Transact requires a vector of factsParser
PRS-042Transact argument must be a vectorParser
PRS-043Retract requires a vector of factsParser
PRS-044Retract argument must be a vectorParser
PRS-045Each fact must be a vector [e a v]Parser
PRS-046Fact must have at least 3 elementsParser
PRS-047Optional 4th fact element must be a mapParser
PRS-048Transact with options requires facts vectorParser
PRS-049Unexpected end of fact vectorParser
PRS-050Empty list in :where clauseParser
PRS-051(not) cannot appear inside another (not)Parser
PRS-052(not) requires at least one clauseParser
PRS-053(or) requires at least one branchParser
PRS-054(or-join) requires join-vars and branchParser
PRS-055(or-join) first argument must be a vectorParser
PRS-056(or-join) join variables must be logic variablesParser
PRS-057(or) branches must introduce same variablesParser
PRS-058(and) requires at least one clauseParser
PRS-059(not-join) requires join-vars and clauseParser
PRS-060Expected pattern or rule in :where clauseParser
PRS-061Unexpected element in queryParser
PRS-062Expression list cannot be emptyParser
PRS-063Expression head must be a symbolParser
PRS-064Function takes exactly 1 argumentParser
PRS-065Function takes exactly 2 argumentsParser
PRS-066matches? second argument must be string literalParser
PRS-067Unknown expression operatorParser
PRS-068Expression clause must be [(expr)] or [(expr) ?out]Parser
PRS-069Expression output must be a ?variableParser
PRS-070Unsupported expression argumentParser
PRS-071Expected UUID string after #uuidParser
PRS-072Invalid UUIDParser
PRS-073Unknown tagged literalParser
PRS-074Bind slot name exceeds maximum lengthParser
PRS-075Transact rejects unexpected trailing argument(s)Parser
PRS-076Retract rejects unexpected trailing argument(s)Parser
PRS-077Unexpected trailing input after a complete formParser
PRS-078Query rejects unexpected trailing argument(s)Parser
PRS-079Rule rejects unexpected trailing argument(s)Parser
PRS-080:find variable not bound in :whereParser
PRS-081Pseudo-attribute has no source patternParser
PRS-082Window reads a non-grouping variableParser
PRS-083Bind slot without a nameParser
PRS-084Window without :order-byParser
PRS-085Query argument is not a vectorParser
PRS-086:with holds a non-variableParser
PRS-087:find element is not a variable or aggregateParser
PRS-088Unknown key in valid-time mapParser
PRS-089Retract fact is not a vectorParser
PRS-090Retract fact must have 3 elementsParser
PRS-091Invalid regex patternParser
PRS-092Item inside (not) is not a clauseParser
PRS-093not-join inside not or not-joinParser
PRS-094not-join without a join-variable vectorParser
PRS-095not-join join variable is not a variableParser
PRS-096Item inside (not-join) is not a clauseParser
PRS-097Rule invocation without a predicate nameParser
PRS-098Pattern must have 3 elementsParser
PRS-099Item inside or branch is not a clauseParser
PRS-100Rule without a bodyParser
PRS-101Rule body is not a vectorParser
PRS-102Rule body is emptyParser
PRS-103Rule head is not a listParser
PRS-104Rule head is emptyParser
PRS-105Rule head without a predicate nameParser
PRS-106Rule body clause is not a vector or listParser
PRS-107Rule body has no clauseParser
PRS-108Fact has more than 4 elementsParser
PRS-109Unterminated string literalParser
PRS-110Keyword without a nameParser
PRS-111Empty query vectorParser
PRS-112Empty query sectionParser
PRS-113Unknown query keywordParser
PRS-114Rule head argument is not a variableParser
PRS-115Query option is not a non-negative integerParser
PRS-116:offset without :order-byParser
PRS-117:order-by entry is not a :find elementParser
PRS-118Malformed :order-byParser
PRS-119Set literal inside a set literalParser
PRS-120Set literal element is not a scalar literalParser
PRS-121Unterminated set literalParser
PRS-122collect-set without a bindingParser
PRS-123collect-set operand is not a variable and an attributeParser
PRS-124Malformed :rows frameParser
PRS-125Position function with an explicit :rows frameParser
QRY-001Invalid entityQuery Execution
QRY-002Attribute must be a keywordQuery Execution
QRY-003Cannot transact a pseudo-attributeQuery Execution
QRY-004Invalid valueQuery Execution
QRY-005Transaction failedQuery Execution
QRY-006Retraction failedQuery Execution
QRY-007Unknown predicateQuery Execution
QRY-008Functions lock poisonedQuery Execution
QRY-009Rules lock poisonedQuery Execution
QRY-010Unknown aggregate functionQuery Execution
QRY-011Unknown window functionQuery Execution
QRY-012Query memory limit exceededQuery Execution
QRY-013Rule head entity is not an entityQuery Execution
QRY-014User function failedQuery Execution
QRY-015collect-set found a set valueQuery Execution
STG-001Invalid header: too shortStorage
STG-002Invalid magic number: not a .graph fileStorage
STG-003Invalid v4/v5/v6 header too short (deprecated)Storage
STG-004Invalid v6 header too short (deprecated)Storage
STG-005Invalid header too shortStorage
STG-006Unsupported format versionStorage
STG-007page_count must be greater than 0Storage
STG-008eavt_root_page must be less than page_countStorage
STG-009fact_page_count cannot exceed page_countStorage
STG-010Failed to read header from existing fileStorage
STG-011Internal page has no childrenStorage
STG-012Expected index page at page NStorage
STG-013range_scan expected leafStorage
STG-014Expected packed page typeStorage
STG-015Record extends beyond page boundaryStorage
STG-016Backend mutex poisonedStorage
STG-017Page count overflow: index_startStorage
STG-018Page count overflow: next_freeStorage
STG-019Page count overflow: new_fact_startStorage
STG-020Fact index exceeds u16::MAXStorage
STG-021Page id overflow in checksum computationStorage
STG-022Page id overflow writing fact pagesStorage
STG-023Page index exceeds u64::MAXStorage
STG-024Pending fact count exceeds u64::MAXStorage
STG-025Database already open in this processStorage
STG-026Database locked by another processStorage
STG-027Filesystem does not support file lockingStorage
STG-028Format version no longer supportedStorage
STG-029Page checksum mismatchStorage
STG-030Page id mismatchStorage
STG-031Page generation ahead of metaStorage
STG-032No valid meta pageStorage
STG-033Meta page damaged after commitStorage
STG-034Unsupported file featureStorage
STG-035Free-list inconsistencyStorage
STG-036Dictionary entry missingStorage
STG-037Transaction with two timestampsStorage
STG-038Index disagrees with the committed factsStorage
STG-039Malformed treeStorage
STG-040Dictionary inconsistencyStorage
STG-041Cannot rebuild indexesStorage
STG-042Database file not found (read-only open)Storage
STG-043Log writer target already existsStorage
STG-044File shorter than its meta page countStorage
STG-045File shorter than one page and not a new databaseStorage
STG-046Earlier checkpoint failed on this handleStorage
STG-047WAL is from a later checkpointStorage
STG-048Browser storage operation failedStorage
WAL-001Invalid WAL magic numberWAL
WAL-002Unsupported WAL versionWAL
WAL-003Value size exceeds maximumWAL
WAL-004Fact serialised size exceeds u32 rangeWAL
WAL-005WAL num_facts exceeds platform usizeWAL
WAL-006Failed to delete WAL fileWAL
WAL-007Earlier WAL write failed on this handleWAL
API-001Write lock poisonedDatabase API
API-002Unexpected command variant in write pathDatabase API
API-003Attribute must be a keywordDatabase API
API-004Cannot transact a pseudo-attributeDatabase API
API-005Only query commands can be prepared (transact)Database API
API-006Only query commands can be prepared (retract)Database API
API-007Only query commands can be prepared (rule)Database API
API-008Function registry lock poisonedDatabase API
API-009WAL not initializedDatabase API
API-010Query with bind slots passed to execute()Database API
API-011Two valid-time windows for one fact in one transactDatabase API
API-012Non-query command passed to query()Database API
API-013Checkpoint while a fact log is open (deprecated)Database API
API-014Write on a read-only handleDatabase API
API-015Log writer record out of transaction orderDatabase API
API-016Log writer record with a second tx_id for one transactionDatabase API
API-017Invalid argument passed through a language bindingDatabase API
API-018Call on a closed binding objectDatabase API
API-019Empty or inverted valid-time windowDatabase API
API-020Assertion and retraction of one fact in one log-writer transactionDatabase API
API-021Set value holds a setDatabase API
API-022Missing bind value for slotDatabase API
API-023Bind slot not permitted in attribute positionDatabase API
API-024Bind slot type mismatchDatabase API
API-025Query option override not allowedDatabase API
API-026OPFS mode is not available hereDatabase API
API-027Database is busyDatabase API
INT-000Unclassified internal errorInternal
INT-001Write transaction already in progress on this threadInternal
INT-002Invalid entity (API layer)Internal
INT-003Invalid value (API layer)Internal
INT-004Invalid timestampInternal
INT-005Millisecond value outside supported datetime rangeInternal
INT-006Internal parser error: expected tokenInternal
INT-007Float literal out of rangeInternal
INT-008Integer literal out of rangeInternal
INT-009Symbol exceeds maximum lengthInternal
INT-010Exceeded maximum recursion depthInternal
INT-011Unexpected end of clauseInternal
INT-012Duplicate query optionInternal
INT-013Query option requires a valueInternal
INT-014Query option must be >= 1Internal
INT-015Query option must be a non-negative integerInternal
INT-016(or)/(or-join) nested inside (not)/(not-join)Internal
INT-017Pseudo-attribute not valid in this positionInternal
INT-018Variable not bound by any outer/earlier clauseInternal
INT-019Datalog parser internal errorInternal
INT-020Evaluator iteration/derived-fact limit exceededInternal
INT-021Evaluator: unsupported where-clause in evaluate_ruleInternal
INT-022Datalog evaluator internal errorInternal
INT-023Packed page: fact exceeds slot capacityInternal
INT-024Packed page: malformed page dataInternal
INT-025Unsubstituted :valid-at bind slot reached executorInternal
INT-026Temporal pseudo-attributes require :any-valid-timeInternal
INT-027Query has no :where clause, rules, or aggregatesInternal
INT-028Rule invocation argument count mismatchInternal
INT-029Unknown aggregate functionInternal
INT-030Unknown window functionInternal
INT-031or-join variable not bound in incoming scopeInternal
INT-032Query executor internal errorInternal
INT-033Missing bind value for slot (deprecated)Internal
INT-034Bind slot not permitted in attribute position (deprecated)Internal
INT-035Bind slot type mismatch (deprecated)Internal
INT-036Header too short: need N..M bytesInternal
INT-037Header slice not the exact expected byte lengthInternal
INT-038Header too short for a specific fieldInternal
INT-039Invalid magic numberInternal
INT-040Function/predicate name already registeredInternal
INT-041sum: unsupported value type (deprecated)Internal
INT-042min/max: no non-null values in groupInternal
INT-043Cannot compare values of different types (deprecated)Internal
INT-044Aggregate: unsupported value type (deprecated)Internal
INT-045Pending fact index out of boundsInternal
INT-046Missing CommittedFactReader for a committed FactRefInternal
INT-047into_backend: backend Arc has multiple ownersInternal
INT-048Storage: arithmetic overflowInternal
INT-049Storage: internal invariant violationInternal
INT-050Internal lock poisonedInternal
INT-051Invalid page sizeInternal
INT-052Page not foundInternal
INT-053Header checksum mismatch: possible file corruptionInternal
INT-054Unstratifiable negative recursion cycleInternal
INT-055Rule predicate disappeared during rollbackInternal
INT-056Write to a read-only storage backendInternal

Deprecated codes: STG-003 and STG-004 (pre-v7 header sizes) are deprecated as of v3.0.0 and are no longer emitted, because formats v1–v6 are rejected with STG-028 before any header-size check. API-013 (checkpoint while a fact log is open) is deprecated as of v3.0.0 and is no longer emitted, because checkpoints run while fact logs are open. PRS-030 (lag/lead unsupported) is deprecated as of v3.0.0 because those functions are supported. INT-033, INT-034 and INT-035 (bind-value mistakes) are deprecated as of v3.0.0 and are no longer emitted: the same mistakes are API-022, API-023 and API-024, since they are the caller's. They stay registered and documented, and error codes are never removed or reused.


PRS — Parser Errors#

Parser errors occur when Minigraf cannot parse the Datalog/EDN input string. They are returned immediately from db.execute() before any fact is read or written.

See the Datalog Reference for syntax guidance.

PRS-001 Unexpected end of input#

Error text: Unexpected end of input

Cause: Input cut off before parser completed an expression. Happens when (, [, or { opened but never closed, or empty string passed to execute().

Resolution:

  • Ensure every ( → ), [ → ], { → }.
  • Use REPL multi-line mode for long queries.

Example:

(query {:find [?e]
        :where [[?e :name "alice"]

(missing closing ] and })

PRS-002 Unexpected character#

Error text: Unexpected character: {}

Cause: Tokeniser encountered a character not valid in Datalog/EDN. Common culprits: @, # outside a tagged literal, \, smart quotes.

Resolution:

  • Use only plain ASCII in attribute names and keywords.
  • String values may contain any UTF-8.
  • For UUIDs use #uuid "..." tagged literal form.

Example:

(transact [[@entity :name "alice"]])

@ is not a valid EDN character; use a UUID or string entity ID instead

PRS-003 Unexpected token#

Error text: Unexpected token: {}

Cause: Parser encountered a token in a position where it cannot appear. Often caused by missing/misplaced delimiter, or keyword where symbol/value expected.

Resolution:

  • Check surrounding delimiters for balance.
  • Consult the Datalog Reference for expected syntax at that position.

Example:

(query :find [?e] :where [[?e :name "alice"]])

:find must be inside a map {}; use (query {:find [?e] :where [...]})

PRS-004 Unclosed vector#

Error text: Unclosed vector

Cause: A [ was opened but never closed with ]. Check fact vectors in transact and pattern vectors in :where.

Resolution:

  • Ensure every [ is matched with ].

Example:

(transact [[:alice :name "Alice"]

(missing closing ] for the outer vector)

PRS-005 Unclosed list#

Error text: Unclosed list

Cause: A ( was opened but never closed with ). Check command forms and not/or clauses.

Resolution:

  • Ensure every ( is matched with ).

Example:

(query {:find [?e]
        :where [(not [?e :deleted true])

(missing closing ) for the not clause and })

PRS-006 Unterminated map#

Error text: Unterminated map: missing '}'

Cause: A { was opened but never closed with }. Check query maps and fact option maps.

Resolution:

  • Ensure every { is matched with }.

Example:

(query {:find [?e]
        :where [[?e :name "alice"]]

(missing closing })

PRS-007 String exceeds maximum length#

Error text: String exceeds maximum length of {} bytes

Cause: A string value in the input exceeds 4096 bytes. Minigraf limits string lengths to keep the parser bounded.

Resolution:

  • Store large strings externally and reference them with a path or URL string attribute.
  • Use Value::Ref to point to a dedicated entity.

Example:

(transact [[#uuid "..." :doc/content "<string longer than 4096 bytes>"]])

Truncate or externalise the value

PRS-008 Keyword exceeds maximum length#

Error text: Keyword exceeds maximum length of {} bytes

Cause: An attribute keyword in the input exceeds 4096 bytes.

Resolution:

  • Shorten the attribute name.
  • Attribute names should be brief and namespaced, e.g. :namespace/attr.

Example:

(transact [[#uuid "..." :<4097-character-keyword> "value"]])

Shorten the attribute keyword

PRS-009 Tagged literal exceeds maximum length#

Error text: Tagged literal exceeds maximum length of {} bytes

Cause: The string inside a #uuid "..." or other tagged literal exceeds 4096 bytes. UUIDs are 36 characters; anything longer indicates a malformed input.

Resolution:

  • UUIDs must be 36 ASCII characters in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  • Check for accidental concatenation or copy-paste errors.

Example:

#uuid "<string longer than 4096 characters>"

A valid UUID is exactly 36 characters

PRS-010 Expected command symbol#

Error text: Expected command symbol

Cause: The top-level form must start with transact, retract, query, or rule. The form was empty or started with a non-symbol token.

Resolution:

  • Ensure the input is a list beginning with a valid command symbol.

Example:

(:transact [[:alice :name "Alice"]])

:transact is a keyword, not a symbol; use transact (no colon)

PRS-011 Unknown command#

Error text: Unknown command: {}

Cause: The opening symbol is not a recognised command. Check spelling.

Resolution:

  • Valid commands are transact, retract, query, rule.
  • Check for typos.

Example:

(upsert [[:alice :name "Alice"]])

upsert is not a command; use transact

PRS-012 Expected a list starting with a command symbol#

Error text: Expected a list starting with a command symbol

Cause: The input is not a list form at all — a bare keyword, integer, map, or vector was passed to execute().

Resolution:

  • Wrap the command in a list: (transact [...]), (query {...}), etc.

Example:

{:find [?e] :where [[?e :name "alice"]]}

A bare map is not a valid command; use (query {:find [?e] :where [...]})

PRS-013 Query requires a map argument#

Error text: Query requires a map argument

Cause: The query command expects its sole argument to be a map {:find [...] :where [...]}. A vector, symbol, or other form was passed instead.

Resolution:

  • Wrap the query clauses in {}: (query {:find [?e] :where [[?e :name "alice"]]}).

Example:

(query [:find ?e :where [?e :name "alice"]])

The argument is a vector [...]; it must be a map {...}

PRS-014 :as-of requires a value#

Error text: :as-of requires a value

Cause: The :as-of keyword appeared in the query map with no value following it.

Resolution:

Example:

(query {:find [?e] :where [[?e :name ?n]] :as-of})

:as-of must be followed by an integer or ISO 8601 string

PRS-015 :as-of counter must be non-negative#

Error text: :as-of counter must be non-negative, got {}

Cause: Transaction counters start at 1. A negative integer was passed to :as-of.

Resolution:

  • Use a non-negative integer.
  • :as-of 0 returns the database before any transaction; :as-of 1 returns the state after the first transaction.
  • See the Datalog Reference — Time Travel.

Example:

(query {:find [?e] :where [[?e :name ?n]] :as-of -1})

:as-of accepts non-negative integers (transaction count) or ISO 8601 strings

PRS-016 :as-of must be integer or ISO 8601 string#

Error text: :as-of must be an integer (counter) or ISO 8601 string, got {}

Cause: :as-of value is neither an integer transaction count nor an ISO 8601 timestamp string.

Resolution:

Example:

(query {:find [?e] :where [[?e :name ?n]] :as-of :now})

:now is not a valid value; use an integer or ISO 8601 string

PRS-017 :valid-at requires a value#

Error text: :valid-at requires a value

Cause: The :valid-at keyword appeared with no value following it.

Resolution:

Example:

(query {:find [?e] :where [[?e :name ?n]] :valid-at})

:valid-at requires an ISO 8601 timestamp string or :any-valid-time

PRS-018 :valid-at must be ISO 8601 or :any-valid-time#

Error text: :valid-at must be an ISO 8601 string or :any-valid-time, got {}

Cause: :valid-at value is not an ISO 8601 string or the special keyword :any-valid-time.

Resolution:

Example:

(query {:find [?e] :where [[?e :name ?n]] :valid-at 42})

Use a string: :valid-at "2024-06-01T00:00:00Z"

PRS-019 :valid-from must be ISO 8601#

Error text: :valid-from must be an ISO 8601 string, got {}

Cause: The :valid-from key in a fact's option map must be an ISO 8601 string, not an integer or keyword.

Resolution:

Example:

(transact [[#uuid "..." :name "Alice" {:valid-from 1704067200000}]])

Use :valid-from "2024-01-01T00:00:00Z" (ISO 8601), not a Unix timestamp integer

PRS-020 :valid-to must be ISO 8601#

Error text: :valid-to must be an ISO 8601 string, got {}

Cause: The :valid-to key in a fact's option map must be an ISO 8601 string.

Resolution:

Example:

(transact [[#uuid "..." :name "Alice" {:valid-to :forever}]])

Omit :valid-to for open-ended validity, or use an ISO 8601 string

PRS-021 :with requires aggregate in :find#

Error text: ':with' clause requires at least one aggregate in :find

Cause: :with is used to group result rows before aggregation, so it requires at least one aggregate function (count, sum, avg, etc.) in :find.

Resolution:

Example:

(query {:find [?e ?name]
        :with [?order]
        :where [[?e :name ?name] [?e :order ?order]]})

:with needs an aggregate in :find, e.g. (count ?order)

PRS-022 :with variable not bound in :where#

Error text: ':with' variable {} not bound in :where

Cause: A variable listed in :with does not appear in any :where pattern.

Resolution:

Example:

(query {:find [(count ?e)]
        :with [?unbound]
        :where [[?e :name ?n]]})

?unbound must be bound by a :where pattern

PRS-023 Aggregate variable not bound in :where#

Error text: Aggregate variable {} not bound in :where

Cause: An aggregate's input variable (e.g. (sum ?amount)) is not bound by any :where pattern.

Resolution:

Example:

(query {:find [(sum ?amount)]
        :where [[?e :name ?n]]})

?amount must be bound: add [?e :payment/amount ?amount] to :where

PRS-024 Aggregate expression must have exactly 2 elements#

Error text: Aggregate expression must have exactly 2 elements (func ?var), got {}

Cause: An aggregate expression in :find must be (function ?variable) — exactly two elements.

Resolution:

Example:

(query {:find [(sum ?amount :distinct)]
        :where [[?e :payment/amount ?amount]]})

:distinct is not part of the aggregate syntax; use (sum ?amount) alone

PRS-025 Aggregate function name must be a symbol#

Error text: Aggregate function name must be a symbol, got {}

Cause: The aggregate function name must be an unqualified symbol, not a keyword or a variable. Through v2.0.x a variable, (?f ?x), was read as a function named ?f and failed when the query ran (#651).

Resolution:

Example:

(query {:find [(:sum ?amount)]
        :where [[?e :payment/amount ?amount]]})

Use (sum ?amount) not (:sum ?amount)

PRS-026 Aggregate argument must be a variable#

Error text: Aggregate argument must be a variable (starting with ?)

Cause: The argument to an aggregate function must be a logic variable beginning with ?.

Resolution:

Example:

(query {:find [(sum 42)]
        :where [[?e :payment/amount ?amount]]})

Use (sum ?amount) with a variable, not a literal

PRS-027 Window function requires :over clause#

Error text: '{}' is a window function and requires an ':over (...)' clause

Cause: Window functions rank and row-number must be accompanied by an :over clause specifying ordering and/or partitioning.

Resolution:

  • Add an :over clause: (rank :over (:order-by ?score)).
  • Since v3.0.0, avg also works as an ordinary aggregate without :over (#777); v2 requires the window form.
  • See the Datalog Reference — Window Functions.

Example:

(query [:find ?e (rank ?score)
        :where [?e :score ?score]])

Missing :over; use (rank :over (:order-by ?score))

PRS-028 Window expression cannot be empty#

Error text: window expression cannot be empty

Cause: An :over () clause was provided with no options inside it.

Resolution:

Example:

(query {:find [?e (rank :over ())]
        :where [[?e :score ?score]]})

Add :order-by: (rank :over (:order-by ?score))

PRS-029 Window function name must be a symbol#

Error text: window function name must be a symbol

Cause: The window function name token is not a symbol (e.g. a keyword was used), or is a variable. Through v2.0.x a variable was read as a function named after it and failed when the query ran (#651).

Resolution:

Example:

(query {:find [?e (:rank :over (:order-by ?score))]
        :where [[?e :score ?score]]})

Use (rank :over ...) not (:rank :over ...)

PRS-030 lag/lead not supported (deprecated)#

Deprecated in v3.0.0. No longer emitted: lag and lead work as window functions. Kept for reference; this code will not be reused.

Error text: '{}' is not supported in this version; lag/lead are planned for a future release

Cause: A v2.x query used lag or lead in a window expression; v2.x did not implement them.

Resolution:

  • Use v3.0.0 or later for lag/lead window expressions.

Example:

(query {:find [?e (lag ?score :over (:order-by ?ts))]
        :where [[?e :score ?score] [?e :ts ?ts]]})

On v2.x this returned PRS-030; on v3.0.0 and later it is accepted.

PRS-031 Function is not window-compatible#

Error text: '{}' is not window-compatible and cannot be used with ':over'

Cause: The named function is a plain aggregate, not a window function. Only rank, row-number, dense-rank, ntile, percent-rank, and cume-dist support :over.

Resolution:

Example:

(query {:find [(sum ?amount :over (:order-by ?ts))]
        :where [[?e :amount ?amount] [?e :ts ?ts]]})

sum is an aggregate; use (sum ?amount) without :over

PRS-032 Function requires variable argument before :over#

Error text: '{}' requires a variable argument (starting with ?) before ':over'

Cause: ntile requires a variable and then an :over clause: (ntile ?bucket :over (:order-by ?score)).

Resolution:

Example:

(query {:find [(ntile :over (:order-by ?score))]
        :where [[?e :score ?score]]})

Use (ntile ?bucket :over (:order-by ?score))

PRS-033 Function requires :over after variable argument#

Error text: '{}' requires ':over' after the variable argument

Cause: ntile was given a variable but no :over clause followed.

Resolution:

Example:

(query {:find [(ntile ?bucket)]
        :where [[?e :score ?score]]})

Add :over: (ntile ?bucket :over (:order-by ?score))

PRS-034 Function requires :over immediately after function name#

Error text: '{}' requires ':over' immediately after the function name (no variable argument)

Cause: rank, row-number, dense-rank, percent-rank, and cume-dist take no variable — they take :over directly. A variable was placed between the function name and :over.

Resolution:

Example:

(query {:find [(rank ?score :over (:order-by ?score))]
        :where [[?e :score ?score]]})

Use (rank :over (:order-by ?score)) — no variable argument

PRS-035 :over must be followed by a list#

Error text: ':over' must be followed by a list, e.g., (:order-by ?var)

Cause: :over was not followed by a list (...).

Resolution:

Example:

(query {:find [(rank :over :order-by)]
        :where [[?e :score ?score]]})

Use (rank :over (:order-by ?score))

PRS-036 Unexpected tokens after :over clause#

Error text: unexpected tokens after ':over' clause in window expression

Cause: Extra tokens appear after the :over (...) clause inside a window expression.

Resolution:

Example:

(query {:find [(rank :over (:order-by ?score) :extra)]
        :where [[?e :score ?score]]})

Remove :extra; the expression must end after (:order-by ?score)

PRS-037 :partition-by requires a variable#

Error text: ':partition-by' requires a variable (starting with ?)

Cause: The value supplied to :partition-by inside an :over clause is not a logic variable.

Resolution:

Example:

(query {:find [(rank :over (:partition-by :dept :order-by ?score))]
        :where [[?e :dept ?d] [?e :score ?score]]})

Use ?dept not :dept

PRS-038 :order-by requires a variable#

Error text: ':order-by' requires a variable (starting with ?)

Cause: The value supplied to :order-by inside an :over clause is not a logic variable.

Resolution:

Example:

(query {:find [(rank :over (:order-by "score"))]
        :where [[?e :score ?score]]})

Use ?score not the string "score"

PRS-039 Unknown option in :over clause#

Error text: unknown option in ':over' clause: '{}'

Cause: An unrecognised keyword appeared inside the :over list. Valid options are :order-by, :partition-by, :asc, :desc, and (from v3.0.0) :rows N preceding.

Resolution:

Example:

(query {:find [(rank :over (:order-by ?score :ascending))]
        :where [[?e :score ?score]]})

:ascending is not a valid option; ordering direction is not yet configurable

PRS-040 Unexpected element in :over clause#

Error text: unexpected element in ':over' clause: {}

Cause: A non-keyword, non-variable element appeared inside the :over list.

Resolution:

Example:

(query {:find [(rank :over (:order-by ?score 5))]
        :where [[?e :score ?score]]})

Remove 5; :over options take only variables

PRS-041 Transact requires a vector of facts#

Error text: Transact requires a vector of facts

Cause: The transact command was called with no argument or with a non-vector argument.

Resolution:

  • Wrap facts in a vector: (transact [[#uuid "..." :name "Alice"]]).

Example:

(transact)

Missing the facts vector

PRS-042 Transact argument must be a vector of facts#

Error text: Transact argument must be a vector of facts

Cause: The argument to transact is present but is not a vector (e.g. a map or keyword was passed). PRS-041 covers the case where no argument is provided at all.

Resolution:

  • Use (transact [[#uuid "..." :attr value]]).

Example:

(transact {:entity #uuid "..." :name "Alice"})

Pass a vector [...], not a map

PRS-043 Retract requires a vector of facts#

Error text: Retract requires a vector of facts

Cause: The retract command was called with no argument or with a non-vector argument.

Resolution:

  • Wrap facts in a vector: (retract [[#uuid "..." :name "Alice"]]).

Example:

(retract)

Missing the facts vector

PRS-044 Retract argument must be a vector of facts#

Error text: Retract argument must be a vector of facts

Cause: The argument to retract is present but is not a vector (e.g. a map or keyword was passed). PRS-043 covers the case where no argument is provided at all.

Resolution:

  • Use (retract [[#uuid "..." :attr value]]).

Example:

(retract {:entity #uuid "..." :name "Alice"})

Pass a vector [...], not a map

PRS-045 Each fact must be a vector [e a v]#

Error text: Each fact must be a vector [e a v] or [e a v {opts}]

Cause: A non-vector element appeared inside the facts vector (e.g. a keyword or integer instead of a [...] fact).

Resolution:

  • Every element of the outer facts vector must itself be a vector [entity :attribute value].

Example:

(transact [:alice :name "Alice"])

Outer [...] must contain inner [...] facts: (transact [[:alice :name "Alice"]])

PRS-046 Fact must have at least 3 elements (E A V)#

Error text: Fact must have at least 3 elements (E A V), got {}

Cause: Each fact must supply at minimum an entity, an attribute, and a value.

Resolution:

  • Ensure every fact has the form [entity :attribute value].
  • Optionally add a 4th map for temporal options: [entity :attribute value {:valid-from "..."}].

Example:

(transact [[:alice :name]])

Only 2 elements; add the value: [:alice :name "Alice"]

PRS-047 Optional 4th fact element must be a map#

Error text: Optional 4th element of a fact must be a map {:valid-from ... :valid-to ...}, got {}

Cause: The 4th element of a fact vector is not a map.

Resolution:

  • The 4th element must be a map: {:valid-from "ISO" :valid-to "ISO"}.
  • Omit it entirely if no temporal options are needed.

Example:

(transact [[#uuid "..." :name "Alice" "2024-01-01"]])

Use a map: {:valid-from "2024-01-01T00:00:00Z"}

PRS-048 Transact with options requires facts vector after the map#

Error text: Transact with options requires a facts vector after the map

Cause: The (transact {opts} [...]) form was used but the facts vector is missing after the options map.

Resolution:

  • Provide the facts vector after the options map: (transact {:tx-time "..."} [[...]]).

Example:

(transact {:tx-time "2024-01-01T00:00:00Z"})

Add the facts vector: (transact {:tx-time "2024-01-01T00:00:00Z"} [[...]])

PRS-049 Unexpected end of fact vector#

Error text: unexpected end of fact vector

Cause: The parser ran out of tokens while reading a fact vector; a closing ] is missing.

Resolution:

  • Ensure every [ in the facts vector is closed with ].

Example:

(transact [[:alice :name "Alice"

(missing closing ] for the inner fact and outer vector)

PRS-050 Empty list in :where clause#

Error text: Empty list in :where clause

Cause: An empty () appears in :where. Every list in :where must be a pattern vector, not, not-join, or, or-join, or an expression clause.

Resolution:

  • Remove the empty list or replace it with a valid clause.
  • See the Datalog Reference.

Example:

(query {:find [?e]
        :where [() [?e :name "alice"]]})

Remove ()

PRS-051 (not) cannot be nested inside another (not)#

Error text: (not ...) cannot appear inside another (not ...)

Cause: Minigraf's Datalog does not support double-negation via nested not clauses.

Resolution:

  • Double negation is logically equivalent to the positive pattern; use the pattern directly.
  • For complex negation use not-join with explicit join variables.
  • See the Datalog Reference — Negation.

Example:

(query {:find [?e]
        :where [(not (not [?e :active true]))]})

Remove the outer (not ...); match [?e :active true] directly

PRS-052 (not) requires at least one clause#

Error text: (not) requires at least one clause

Cause: (not) has no clauses inside it.

Resolution:

Example:

(query {:find [?e]
        :where [[?e :name ?n] (not)]})

Add a pattern: (not [?e :deleted true])

PRS-053 (or) requires at least one branch#

Error text: (or) requires at least one branch

Cause: (or) has no branches inside it.

Resolution:

Example:

(query {:find [?e]
        :where [(or)]})

Add a branch: (or [?e :type :admin] [?e :type :superuser])

PRS-054 (or-join) requires join-vars vector and at least one branch#

Error text: (or-join) requires a join-vars vector and at least one branch

Cause: (or-join) must have a [join-vars] vector followed by at least one branch.

Resolution:

Example:

(query {:find [?e]
        :where [(or-join)]})

Add join vars and branches: (or-join [?e] [[?e :type :a]] [[?e :type :b]])

PRS-055 (or-join) first argument must be a vector of join variables#

Error text: (or-join) first argument must be a vector of join variables

Cause: The first argument to (or-join) is not a vector.

Resolution:

Example:

(query {:find [?e]
        :where [(or-join ?e [[?e :type :a]])]})

Wrap join vars in a vector: (or-join [?e] ...)

PRS-056 (or-join) join variables must be logic variables#

Error text: (or-join) join variables must be logic variables, got {}

Cause: Join variables in (or-join [?e ...]) must start with ?.

Resolution:

Example:

(query {:find [?e]
        :where [(or-join [:e] [[?e :type :a]])]})

Use [?e] not [:e]

PRS-057 (or) branches must introduce the same set of new variables#

Error text: all branches of (or ...) must introduce the same set of new variables

Cause: Each branch of (or ...) must bind the same set of new logic variables. If one branch binds ?status and another doesn't, the result is undefined.

Resolution:

  • Restructure branches so they all bind the same new variables.
  • Or use or-join to specify exactly which variables to share.
  • See the Datalog Reference.

Example:

(query {:find [?e ?status]
        :where [(or [?e :active true]
                    [?e :status ?status])]})

Both branches must bind ?status or neither should

PRS-058 (and) inside or/or-join requires at least one clause#

Error text: (and) inside or/or-join requires at least one clause

Cause: An (and ...) inside or/or-join has no clauses.

Resolution:

Example:

(query {:find [?e]
        :where [(or (and) [?e :name "alice"])]})

Add a clause: (and [?e :active true] [?e :name "alice"])

PRS-059 (not-join) requires join-vars vector and at least one clause#

Error text: (not-join) requires a join-vars vector and at least one clause

Cause: (not-join) must have a [join-vars] vector followed by at least one clause.

Resolution:

Example:

(query {:find [?e]
        :where [(not-join)]})

Add join vars and clause: (not-join [?e] [?e :deleted true])

PRS-060 Expected pattern vector or rule invocation in :where clause#

Error text: Expected pattern vector or rule invocation in :where clause, got {}

Cause: Something other than a pattern vector [...] or a list-form clause appeared directly in :where.

Resolution:

  • Each :where element must be a vector [e a v], a (not ...), (not-join ...), (or ...), (or-join ...), or expression [(expr) ?out].
  • See the Datalog Reference.

Example:

(query {:find [?e]
        :where [:name [?e :name ?n]]})

:name is not a clause; use [?e :name ?n]

PRS-061 Unexpected element in query#

Error text: Unexpected element in query: {}

Cause: A value in the query vector belongs to no section: it comes before the first keyword, or after an option and its argument (:as-of N, :valid-at "…", :max-derived-facts N, :max-results N, :limit N, :offset N, :order-by […]), or after a bare flag (:any-valid-time, :distinct). Through v2.0.x a value after an option joined the section before the option, so [:find ?a :any-valid-time ?b :where …] returned ?b as a second column (#651).

Resolution:

  • Put every :find spec after :find and every clause after :where, before or after the options.
  • :distinct is a bare flag: omit the argument in :distinct true, :distinct 1 or :distinct $d (#493).
  • See the Datalog Reference.

Example:

(query [:find ?a :any-valid-time ?b :where [?a :edge ?b]])

Write [:find ?a ?b :any-valid-time :where [?a :edge ?b]]

PRS-062 Expression list cannot be empty#

Error text: expression list cannot be empty

Cause: An expression clause [()] contains an empty list.

Resolution:

Example:

(query {:find [?e]
        :where [[?e :a ?a] [()]]})

Add a function: [(> ?a 0)]

PRS-063 Expression head must be a symbol#

Error text: expression head must be a symbol, got {}

Cause: The first element of an expression must be a symbol naming a function, not a keyword or a variable. Through v2.0.x a variable, [(?f ?x) ?y], was read as a function named ?f and failed when the query ran (#651).

Resolution:

Example:

(query {:find [?e]
        :where [[?e :amount ?a] [(:+ ?a 10) ?total]]})

Use (+ ?a 10) not (:+ ?a 10)

PRS-064 Function takes exactly 1 argument#

Error text: {} takes exactly 1 argument

Cause: A built-in operator that takes 1 argument was given a different number.

Resolution:

Example:

(query {:find [?e]
        :where [[?e :amount ?a] [(abs ?a ?a) ?pos]]})

Use [(abs ?a) ?pos] — one argument only

PRS-065 Function takes exactly 2 arguments#

Error text: {} takes exactly 2 arguments

Cause: A built-in operator that takes 2 arguments was given a different number.

Resolution:

  • Check the argument count.
  • Two-argument operators: +, -, *, /, mod, quot, =, !=, <, <=, >, >=, starts-with?, ends-with?, contains?, matches?.
  • See the Datalog Reference — Expressions.

Example:

(query {:find [?e]
        :where [[?e :a ?a] [?e :b ?b] [(+ ?a ?b ?c) ?sum]]})

Use [(+ ?a ?b) ?sum] — two arguments only

PRS-066 matches? second argument must be a string literal#

Error text: matches? second argument must be a string literal

Cause: The second argument to matches? must be a string literal (the regex pattern), not a variable.

Resolution:

Example:

(query {:find [?e]
        :where [[?e :name ?n] [(matches? ?n ?pattern)]]})

The pattern must be a literal: [(matches? ?n "alice.*")]

PRS-067 Unknown expression operator#

Error text: unknown expression operator: {}

Cause: An expression clause used a function name that Minigraf does not recognise. Built-in operators include: +, -, *, /, mod, quot, abs, min, max, str, not, =, !=, <, <=, >, >=, matches?, starts-with?, ends-with?, contains?.

Resolution:

  • Check spelling against the supported operator list above.
  • For missing operators, register a custom predicate via db.register_predicate().
  • See the Datalog Reference — Expressions.

Example:

(query {:find [?e]
        :where [[?e :amount ?a] [(floor-div ?a 100) ?bucket]]})

floor-div is not built-in; use (quot ?a 100) instead

PRS-068 Expression clause must be [(expr)] or [(expr) ?out]#

Error text: expression clause must be [(expr)] or [(expr) ?out], got {} elements

Cause: An expression clause in :where must be a 1- or 2-element outer vector: [(predicate)] or [(expr) ?out]. A 3+ element outer vector is invalid.

Resolution:

Example:

(query {:find [?e]
        :where [[?e :a ?a] [(+ ?a 1) ?b :extra]]})

Remove :extra; the form must be [(+ ?a 1) ?b]

PRS-069 Expression output must be a ?variable#

Error text: expression output must be a ?variable, got {}

Cause: The output binding in [(expr) ?out] is not a logic variable starting with ?.

Resolution:

Example:

(query {:find [?e]
        :where [[?e :a ?a] [(+ ?a 1) :result]]})

Use ?result not :result

PRS-070 Unsupported expression argument#

Error text: unsupported expression argument: {}

Cause: An argument inside an expression is of a type that the expression engine cannot accept (e.g. a nested map or list).

Resolution:

  • Expressions accept variables (?x), integers, floats, strings, booleans, and keywords.
  • Restructure to avoid passing complex types.
  • See the Datalog Reference — Expressions.

Example:

(query {:find [?e]
        :where [[?e :a ?a] [(+ ?a {:x 1}) ?b]]})

Maps are not valid expression arguments

PRS-071 Expected UUID string after #uuid tag#

Error text: Expected UUID string after #uuid tag

Cause: #uuid was used but not followed by a string token.

Resolution:

  • Use the form #uuid "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".

Example:

(transact [[#uuid :some-id :name "Alice"]])

#uuid must be followed by a string: #uuid "550e8400-e29b-41d4-a716-446655440000"

PRS-072 Invalid UUID#

Error text: Invalid UUID

Cause: The string after #uuid is not a valid UUID. UUIDs must match xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (32 hex digits in 5 groups).

Resolution:

  • Verify the UUID format.
  • All 32 characters must be hex digits (0–9, a–f).
  • The groups must be separated by hyphens at the correct positions.

Example:

(transact [[#uuid "not-a-valid-uuid" :name "Alice"]])

Use a properly formatted UUID: #uuid "550e8400-e29b-41d4-a716-446655440000"

PRS-073 Unknown tagged literal#

Error text: Unknown tagged literal: #{}

Cause: A #tag "..." form used an unrecognised tag. Only #uuid is supported.

Resolution:

  • Remove the unrecognised tagged literal.
  • If you need to store binary data, encode it as a string attribute value.

Example:

(transact [[#uuid "..." :data #base64 "SGVsbG8="]])

#base64 is not supported; store the string value directly

PRS-074 Bind slot name exceeds maximum length#

Error text: Bind slot name exceeds maximum length of {} bytes

Cause: A prepared-query bind slot name $name in a prepare() call exceeds 4096 bytes.

Resolution:

  • Use shorter bind slot names.
  • Bind slot names should be brief and descriptive, e.g. $name, $entity-id.

Example:

$<4097-char-slot-name>

Shorten the bind slot name; $name is sufficient for most use cases

PRS-075 Transact rejects unexpected trailing argument(s)#

Error text: transact takes (transact [facts]) or (transact {opts} [facts]); found {} unexpected trailing argument(s) — the valid-time options map must come BEFORE the facts vector, not after

Cause: (transact ...) was called with more top-level arguments than it accepts — either extra tokens after the facts vector, or the valid-time options map placed after the facts vector instead of before it. Earlier parser versions silently dropped these extra arguments (and any :valid-from/:valid-to in a misplaced map); this is now a hard error.

Resolution:

  • Use exactly one of (transact [facts]) or (transact {:valid-from "..." :valid-to "..."} [facts]).
  • If you meant to set valid-time options, move the map before the facts vector.
  • Remove any stray trailing tokens.

Example:

(transact [[:alice :employment/status :active]] {:valid-from "2023-01-01"})

The options map comes after the facts vector; move it before: (transact {:valid-from "2023-01-01"} [[:alice :employment/status :active]])

PRS-076 Retract rejects unexpected trailing argument(s)#

Error text: retract takes (retract [facts]); found {} unexpected trailing argument(s)

Cause: (retract ...) was called with more than one top-level argument. retract only accepts a single facts vector — unlike transact, it does not accept a leading options map.

Resolution:

  • Use exactly (retract [facts]).
  • Remove any trailing tokens after the facts vector.

Example:

(retract [[:alice :employment/status :active]] {:valid-from "2023-01-01"})

retract takes only a facts vector; drop the trailing map

PRS-077 Unexpected trailing input after a complete form#

Error text: unexpected trailing input after a complete form: {}

Cause: The top-level input contains a syntactically complete EDN form (e.g. a fully closed list or vector) followed by additional tokens. Earlier parser versions silently stopped after the first complete form instead of rejecting the extra input.

Resolution:

  • Ensure the input contains exactly one top-level form.
  • Remove any text, delimiters, or extra forms following the first complete form.

Example:

(query [:find ?e :where [?e :entity-type :type/commit]]) garbage-trailing-tokens

Only one top-level form is allowed; remove everything after the closing )

PRS-078 Query rejects unexpected trailing argument(s)#

Error text: query takes (query [...]); found {} unexpected trailing argument(s)

Cause: (query ...) was called with more than one top-level argument. All query options (:find, :where, :as-of, :max-results, etc.) must appear as keywords inside the query vector, not as sibling arguments after it. Earlier parser versions silently dropped these trailing arguments.

Resolution:

  • Put every query option inside the single query vector: (query [:find ?e :where [...] :max-results 5]).
  • Remove any arguments after the closing ] of the query vector.

Example:

(query [:find ?e :where [?e :a :b]] :max-results 5)

:max-results 5 must be inside the vector: (query [:find ?e :where [?e :a :b] :max-results 5])

PRS-079 Rule rejects unexpected trailing argument(s)#

Error text: rule takes (rule [...]); found {} unexpected trailing argument(s)

Cause: (rule ...) was called with more than one top-level argument. A rule definition is a single vector containing the rule head and body patterns; nothing may follow it.

Resolution:

  • Keep the rule head and all body patterns inside one vector: (rule [(reachable ?a ?b) [?a :edge ?b]]).
  • Remove any arguments after the closing ] of the rule vector.

Example:

(rule [(reachable ?a ?b) [?a :edge ?b]] :unexpected-extra)

Nothing may follow the rule vector; remove :unexpected-extra

PRS-080 :find variable not bound in :where#

Error text: :find variable {} not bound in :where

Cause: A variable in :find — a plain variable, or the argument, :partition-by or :order-by variable of a window function — is not bound by any :where clause. Variables count as bound when they appear in a pattern, a rule call, an expression binding ([(+ ?a 1) ?b]), an or-join join vector, or every branch of an or. Variables that appear only inside not/not-join, and ?_ wildcards, are not bound. Before v3.0.0 such a query returned no results, so a typo in :find looked the same as "no matching data".

Resolution:

  • Check the variable name for typos against the :where clauses.
  • Add a clause that binds the variable, or remove it from :find.

Example:

(query [:find ?n :where [?e :person/name ?name]])

?n is never bound; use ?name

PRS-081 Pseudo-attribute has no source pattern#

Error text: {} on {} has no pattern before it, with the same entity, that reads a stored attribute; add one (e.g. [{} ?a _]) before it

Cause: A per-fact pseudo-attribute pattern (:db/valid-from, :db/valid-to, :db/tx-count, :db/tx-id) reads the metadata of one fact: the fact matched by its source, the nearest pattern before it in the query text with the same entity term and a stored attribute (a keyword, or a variable such as [?e ?a ?v]). The search starts in the pseudo-attribute's own clause list and continues outwards, before each enclosing not, or, not-join or or-join; it crosses a not-join or or-join only for an entity variable listed in its join variables, and it stops at a rule body, which never reads its caller's patterns. A pattern after the pseudo-attribute never counts, a sibling or branch is never searched, and a _ entity never has a source. Entity terms are the same when they are the same variable, the same $slot, or constants naming the same entity (:alice and its UUID). Before v3.0.0 such a pattern matched every visible fact of the entity instead, and which fact a pseudo-attribute read could depend on the plan.

Resolution:

  • Put a pattern with the same entity term before the pseudo-attribute pattern.
  • To read the metadata of every fact of an entity, write [?e ?a _] before it.

Example:

(query [:find ?t :any-valid-time :where [?e :db/tx-count ?t] [?e :person/name "Alice"]])

Move [?e :person/name "Alice"] before [?e :db/tx-count ?t]

PRS-082 Window reads a non-grouping variable#

Error text: {} in {} must be a plain :find variable when the query has aggregates

Cause: In a query whose :find holds an aggregate, window functions run over the groups the aggregation produces, after it. Each group row holds only the plain :find variables and the aggregate results, so a window's argument, :partition-by and :order-by must each be a plain :find variable. :with variables do not count: they do not group when :find holds a window. Before v3.0.0 such a variable read nil on every group row, so the window ordered or summed nothing.

Resolution:

  • Add the variable to :find as a plain variable, so it groups.
  • Or run the window in a query without aggregates.

Example:

(query [:find ?dept (sum ?salary) (rank :over (:order-by ?salary)) :where [?e :dept ?dept] [?e :salary ?salary]])

?salary is aggregated, not a group: order by ?dept, or drop (sum ?salary)

PRS-083 Bind slot without a name#

Error text: Bind slot '$' must be followed by an identifier (e.g. $entity)

Cause: A $ in a query is not followed by an identifier. Bind slots name the value supplied at execution time, as $entity or $min-age. Before v3.0.0 this was INT-019.

Resolution:

  • Name the slot: $name, then pass a value for name when executing the prepared query.

Example:

(query [:find ?e :where [?e :name $]])

Write $name and bind name

PRS-084 Window without :order-by#

Error text: ':order-by' is required in the ':over' clause

Cause: A window function's :over clause has no :order-by. Every window orders its rows; :partition-by is optional, :order-by is not. Before v3.0.0 this was INT-019.

Resolution:

  • Add (:order-by ?var) to the :over clause.

Example:

(query [:find ?e (rank :over (:partition-by ?d)) :where [?e :dept ?d]])

Add :order-by, e.g. (:partition-by ?d :order-by ?e)

PRS-085 Query argument is not a vector#

Error text: Query argument must be a vector

Cause: The argument of (query ...) is not a vector. A query is one vector holding :find, optional :with, :where and the temporal keywords. Before v3.0.0 this was INT-019.

Resolution:

  • Wrap the query in square brackets: (query [:find ... :where ...]).

Example:

(query (:find ?e :where [?e :a ?v]))

Use [ ], not ( )

PRS-086 :with holds a non-variable#

Error text: ':with' clause accepts only variables, got {}

Cause: An element of :with is not a logic variable. :with lists variables that keep otherwise identical rows apart before aggregation. Before v3.0.0 this was INT-019.

Resolution:

  • List only ?variables after :with.

Example:

(query [:find (count ?e) :with 7 :where [?e :a ?v]])

7 is not a variable; write :with ?v

PRS-087 :find element is not a variable or aggregate#

Error text: Expected variable or aggregate expression in :find clause, got {}

Cause: An element of :find is neither a logic variable nor an aggregate or window expression such as (count ?e). Before v3.0.0 this was INT-019.

Resolution:

  • Return variables bound in :where, or aggregate them.

Example:

(query [:find 7 :where [?e :a ?v]])

7 is a constant; return a variable

PRS-088 Unknown key in valid-time map#

Error text: Unknown key in valid-time map: {}; expected :valid-from or :valid-to

Cause: The map before a transact's facts, or the fourth element of a fact, holds a key other than :valid-from or :valid-to. Before v3.0.0 this was INT-019.

Resolution:

  • Use only :valid-from and :valid-to; both are optional.

Example:

(transact {:valid-at "2024-01-01"} [[:alice :name "Alice"]])

Write :valid-from

PRS-089 Retract fact is not a vector#

Error text: Each fact must be a vector [e a v]

Cause: An element of the (retract [...]) vector is not a fact vector. Each fact to retract is a vector [entity attribute value]. Before v3.0.0 this was INT-019.

Resolution:

  • Wrap each fact in its own vector: (retract [[:alice :name "Alice"]]).

Example:

(retract [:alice])

Write [[:alice :name "Alice"]]

PRS-090 Retract fact must have 3 elements#

Error text: Retract fact must have exactly 3 elements (E A V), got {}

Cause: A fact in (retract [...]) does not have exactly three elements. A retraction names one fact by entity, attribute and value; it takes no valid-time map. Before v3.0.0 this was INT-000.

Resolution:

  • Give entity, attribute and value: [:alice :name "Alice"].

Example:

(retract [[:alice :name]])

The value is missing

PRS-091 Invalid regex pattern#

Error text: invalid regex pattern {}: {}

Cause: The pattern given to matches? is not a valid regular expression. The error shows the pattern and the regex error. Before v3.0.0 this was INT-019.

Resolution:

  • Fix the pattern; escape regex metacharacters such as (, [ and . with \\ inside the string.

Example:

(query [:find ?e :where [?e :name ?n] [(matches? ?n "(")]])

( opens a group that never closes; write "\\("

PRS-092 Item inside (not) is not a clause#

Error text: expected pattern or rule invocation inside (not), got {}

Cause: An item inside (not ...) is neither a vector (a pattern or an expression clause) nor a list (a rule invocation or another clause form). Before v3.0.0 this was INT-019.

Resolution:

  • Put patterns [?e :attr ?v] or rule calls (rule-name ?x) inside not.

Example:

(query [:find ?e :where [?e :a ?v] (not 7)])

7 is not a clause

PRS-093 not-join inside not or not-join#

Error text: (not-join ...) cannot appear inside another (not ...) or (not-join ...)

Cause: A (not-join ...) appears inside another (not ...) or (not-join ...). Negations do not nest. Before v3.0.0 this was INT-019.

Resolution:

  • Move the inner negation out, or express it as a rule and call the rule inside the outer not.

Example:

(query [:find ?e :where [?e :a ?v] (not (not-join [?e] [?e :b 1]))])

Write the inner not-join as a rule, or move it to the top level

PRS-094 not-join without a join-variable vector#

Error text: (not-join) first argument must be a vector of join variables

Cause: The first argument of (not-join ...) is not a vector. not-join takes the variables it shares with the outer query as a vector, then its clauses. Before v3.0.0 this was INT-019.

Resolution:

  • Write the join variables in square brackets: (not-join [?e] ...).

Example:

(query [:find ?e :where [?e :a ?v] (not-join ?e [?e :b 1])])

Write [?e]

PRS-095 not-join join variable is not a variable#

Error text: (not-join) join variables must be logic variables, got {}

Cause: An element of not-join's join-variable vector is not a logic variable. Before v3.0.0 this was INT-019.

Resolution:

  • List only ?variables in the vector.

Example:

(query [:find ?e :where [?e :a ?v] (not-join [7] [?e :b 1])])

7 is not a variable

PRS-096 Item inside (not-join) is not a clause#

Error text: expected pattern or rule invocation inside (not-join), got {}

Cause: An item after not-join's join variables is neither a vector (a pattern or an expression clause) nor a list (a rule invocation or another clause form). Before v3.0.0 this was INT-019.

Resolution:

  • Put patterns [?e :attr ?v] or rule calls (rule-name ?x) after the join variables.

Example:

(query [:find ?e :where [?e :a ?v] (not-join [?e] 7)])

7 is not a clause

PRS-097 Rule invocation without a predicate name#

Error text: Rule invocation must start with predicate name (symbol), got {}

Cause: A list in :where or a rule body does not start with a rule name, so it is not a rule invocation (nor not, or or another clause form). A rule name is a symbol that is not a variable or an operator. Before v3.0.0 this was INT-019, and a list headed by a variable or an operator, such as (< ?a ?b), was a call of a rule of that name, which matched nothing: the query returned no rows (#651).

Resolution:

  • Start the list with the rule's name: (reachable ?a ?b).
  • Write a comparison as an expression clause, in a vector: [(< ?a ?b)].

Example:

(query [:find ?e :where [?e :a ?v] (7 ?e)])

7 is not a rule name

PRS-098 Pattern must have 3 elements#

Error text: Pattern must have exactly 3 elements (E A V), got {}

Cause: A pattern vector in :where, a rule body, or a not/or body does not have exactly three elements: entity, attribute and value. Use _ for a position you do not care about. Before v3.0.0 this was INT-019.

Resolution:

  • Give all three positions: [?e :attr ?v] or [?e :attr _].

Example:

(query [:find ?e :where [?e :a ?v] [?e :b]])

Write [?e :b _]

PRS-099 Item inside or branch is not a clause#

Error text: expected clause inside or branch, got {}

Cause: An item inside (or ...), (or-join ...) or (and ...) is neither a vector (a pattern or an expression clause) nor a list (a rule invocation or another clause form). Before v3.0.0 this was INT-019.

Resolution:

  • Make each branch a pattern, a rule call, or an (and ...) of clauses.

Example:

(query [:find ?e :where [?e :a ?v] (or 7)])

7 is not a clause

PRS-100 Rule without a body#

Error text: Rule must have a body

Cause: (rule) has no argument. A rule is one vector: a head list, then one or more body clauses. Before v3.0.0 this was INT-019.

Resolution:

  • Write (rule [(name ?args) clause ...]).

Example:

(rule)

Add the rule vector

PRS-101 Rule body is not a vector#

Error text: Rule body must be a vector

Cause: The argument of (rule ...) is not a vector. The head and body go inside one vector. Before v3.0.0 this was INT-019.

Resolution:

  • Wrap head and body in square brackets: (rule [(reachable ?a ?b) [?a :edge ?b]]).

Example:

(rule (reachable ?a ?b))

Put the head and its clauses in [ ]

PRS-102 Rule body is empty#

Error text: Rule body cannot be empty

Cause: The rule vector is empty: it has no head and no clauses. Before v3.0.0 this was INT-019.

Resolution:

  • Write the head list, then at least one clause.

Example:

(rule [])

Add (name ?args) and a clause

PRS-103 Rule head is not a list#

Error text: Rule head must be a list: (predicate ?args)

Cause: The first element of the rule vector is not a list. The head names the rule and its arguments: (predicate ?args). Before v3.0.0 this was INT-019.

Resolution:

  • Write the head as a list: (reachable ?a ?b).

Example:

(rule [reachable [?a :edge ?b]])

Write (reachable ?a ?b)

PRS-104 Rule head is empty#

Error text: Rule head cannot be empty

Cause: The rule head is (): it has no predicate name. Before v3.0.0 this was INT-019.

Resolution:

  • Name the rule and its arguments: (reachable ?a ?b).

Example:

(rule [() [?a :edge ?b]])

Write (reachable ?a ?b)

PRS-105 Rule head without a predicate name#

Error text: Rule head must start with a symbol (predicate name)

Cause: The rule head does not start with a rule name: a symbol that is not a variable or an operator. Before v3.0.0 this was INT-019, and a variable or an operator such as (?r ?a) or (< ?a) was accepted as a name (#651).

Resolution:

  • Start the head with the rule's name: (reachable ?a ?b).

Example:

(rule [(7 ?a) [?a :edge ?b]])

7 is not a name

PRS-106 Rule body clause is not a vector or list#

Error text: Rule body clause must be a vector (pattern) or list (rule invocation / not), got {}

Cause: An element after the rule head is neither a vector (a pattern or an expression clause) nor a list (a rule invocation, not, or or another clause form). Before v3.0.0 this was INT-019.

Resolution:

  • Write each body clause as [?e :attr ?v] or (name ?args).

Example:

(rule [(reachable ?a) 7])

7 is not a clause

PRS-107 Rule body has no clause#

Error text: Rule must have at least one pattern or rule invocation in body

Cause: The rule vector holds a head and nothing else. A rule derives its head from at least one body clause. Before v3.0.0 this was INT-019.

Resolution:

  • Add a pattern or rule invocation after the head.

Example:

(rule [(reachable ?a)])

Add a clause, e.g. [?a :edge ?b]

PRS-108 Fact has more than 4 elements#

Error text: Fact must have at most 4 elements (E A V and an optional map), got {}

Cause: A fact vector in transact has more than four elements. A fact is [E A V] or [E A V {:valid-from ... :valid-to ...}]. Through v2.0.8, a fact whose 4th element was a map had every element after the map dropped without an error (#649), and one whose 4th element was not a map was rejected with PRS-047.

Resolution:

  • Check the brackets: two facts run together, (transact [[e a v {} e2 a2 v2]]), are two vectors in the facts vector, (transact [[e a v {}] [e2 a2 v2]]).

Example:

(transact [[:alice :person/age 1 {} 99 :junk]])

Remove 99 :junk, or make it its own fact

PRS-109 Unterminated string literal#

Error text: Unterminated string literal

Cause: A string has no closing ". Through v2.0.x the string ran to the end of the input, and the command was read without its closing brackets (#651).

Resolution:

  • Close the string. A " inside a string is written \".

Example:

(transact [[:alice :person/name "Alice]])

Write "Alice"

PRS-110 Keyword without a name#

Error text: Keyword has no name after ':'

Cause: A : is not followed by a letter, digit or one of - _ / ?, so the keyword has no name. Through v2.0.x this was the keyword : (#651).

Resolution:

  • Write the keyword's name right after the colon: :person/name, not : person/name.
  • An operator in an expression is a symbol: (+ ?a 1), not (:+ ?a 1).

Example:

(transact [[:alice : "Alice"]])

: alone is not a keyword

PRS-111 Empty query vector#

Error text: Query vector is empty

Cause: The query is (query []). Through v2.0.x it was accepted (#651).

Resolution:

  • Add a :find and a :where section: (query [:find ?e :where [?e :person/name ?n]]).

Example:

(query [])

PRS-112 Empty query section#

Error text: Query section {} is empty

Cause: :find, :where or :with is followed by another keyword or by the end of the query vector. Through v2.0.x an empty :find returned one empty row and an empty :where or :with was ignored (#651).

Resolution:

  • Add what the section is for: variables or aggregates after :find, clauses after :where, variables after :with; or remove the keyword.

Example:

(query [:find :where [?e :person/name ?n]])

Write [:find ?e :where …]

PRS-113 Unknown query keyword#

Error text: Unknown query keyword {}

Cause: The query vector holds a keyword it does not know. The query keywords are :find, :where, :with, :as-of, :valid-at, :any-valid-time, :max-derived-facts, :max-results, :limit, :offset, :order-by and :distinct. Through v2.0.x an unknown keyword followed by another keyword was ignored, and one followed by a value raised PRS-061 (#651).

Resolution:

  • Check the spelling.
  • :in is not supported: pass inputs through bind slots ($name) of a prepared query.

Example:

(query [:find ?e :foo 10 :where [?e :person/name ?n]])

:foo is not a query keyword

PRS-114 Rule head argument is not a variable#

Error text: Rule head argument must be a variable, got {}

Cause: An argument in a rule head is not a variable. Through v2.0.x a constant was accepted, (r ?a :c), and a call (r ?a ?x) bound ?x to it (#651).

Resolution:

  • Use a variable in the head and bind it in the body, e.g. with a pattern or an expression clause: (rule [(r ?a ?x) [?a :edge ?x] [(= ?x :c)]]).

Example:

(rule [(reachable-5 ?a ?b 0) [?a :edge ?b]])

0 is not a variable

PRS-115 Query option is not a non-negative integer#

Error text: {} must be a non-negative integer or a bind slot, got {}

Cause: The value after :limit or :offset is not an integer >= 0 or a $slot, or a prepared query's :limit or :offset slot was bound to a negative integer (#306).

Resolution:

  • Give :limit or :offset a whole number of rows, 0 or more, or a bind slot filled with BindValue::Val(Value::Integer(n)).

Example:

(query [:find ?e :where [?e :person/name ?n] :limit -1])

-1 is negative


PRS-116 :offset without :order-by#

Error text: :offset requires :order-by

Cause: The query has :offset but no :order-by (#306). Without an order, which rows an offset skips is unspecified: pages could overlap or miss rows between plans and between writes.

Resolution:

  • Add :order-by naming the :find elements to page by.
  • To read a whole answer in pieces, use a cursor (Minigraf::query) instead of pages.

Example:

(query [:find ?e :where [?e :person/name ?n] :offset 20 :limit 10])

No :order-by


PRS-117 :order-by entry is not a :find element#

Error text: :order-by entry {} is not a :find element

Cause: An :order-by entry does not equal any :find element (#306). Entries name :find elements: plain variables, or aggregate and window elements written as they appear in :find. A variable bound in :where but not in :find, a :with variable, or a value that is neither a variable nor a list is rejected.

Resolution:

  • Add the variable or aggregate to :find, or order by an element already there.
  • Write an aggregate entry exactly as in :find, e.g. (count ?e).

Example:

(query [:find ?e :where [?e :person/age ?age] :order-by [?age]])

?age is not in :find


PRS-118 Malformed :order-by#

Error text: :order-by takes a non-empty vector of :find elements, each optionally followed by :asc or :desc; {}

Cause: The value after :order-by is not a vector, or is empty, or names the same element twice, or has :asc/:desc with no element before it (or two directions for one element), or holds another keyword (#306). The fault is named after the semicolon.

Resolution:

  • Write :order-by [?a :desc ?b]: each :find element once, each optionally followed by one direction (default :asc).

Example:

(query [:find ?n :where [?e :person/name ?n] :order-by [:desc ?n]])

:desc before its element


PRS-119 Set literal inside a set literal#

Error text: a set literal cannot hold a set

Cause: A set literal #{...} has another set literal among its elements. Sets hold scalar values only (#316).

Resolution:

  • Flatten the elements into one set, or store each inner set as its own attribute value.

Example:

(transact [[:alice :user/scopes #{#{:scope/read}}]])

#{:scope/read} is a set inside a set


PRS-120 Set literal element is not a scalar literal#

Error text: a set literal holds only strings, numbers, booleans, keywords, #uuid literals and nil; got {}

Cause: An element of a set literal is a variable, a bind slot, a symbol, a vector, a list or a map. A set literal is a constant: its elements are literals (#316).

Resolution:

  • Write the elements as literals, or pass the whole set through a bind slot: $scopes bound to BindValue::Val(Value::Set(..)).

Example:

(query [:find ?e :where [?e :user/scopes #{?x}]])

?x is a variable


PRS-121 Unterminated set literal#

Error text: Unterminated set: missing '}'

Cause: The input ends inside a set literal #{...}.

Resolution:

  • Close the set with }.

Example:

(transact [[:alice :user/scopes #{:scope/read

PRS-122 collect-set without a binding#

Error text: collect-set produces a value; bind it to a variable: [(collect-set ?e :attr) ?out]

Cause: A collect-set clause has no output variable. collect-set builds a set value and is not a filter.

Resolution:

  • Bind its result: [(collect-set ?e :user/scope) ?scopes], then test it with in?, any-in? or another predicate.

Example:

(query [:find ?e :where [?e :user/name _] [(collect-set ?e :user/scope)]])

PRS-123 collect-set operand is not a variable and an attribute#

Error text: collect-set takes a ?variable and an attribute keyword; got {}

Cause: The first operand of collect-set must be a logic variable bound to an entity by an earlier clause, and the second an attribute keyword written in the query. A constant entity, a string or a variable attribute, and a $slot in either position are rejected. The message names the operand given.

Resolution:

  • Bind the entity with a pattern first: [?e :user/name "alice"] [(collect-set ?e :user/scope) ?s].
  • Write the attribute as a keyword: :user/scope, not "user/scope" or ?a.

Example:

(query [:find ?s :where [?e :user/name _] [(collect-set ?e "user/scope") ?s]])

"user/scope" is a string, not a keyword


PRS-124 Malformed :rows frame#

Error text: :rows requires one non-negative integer followed by preceding, and may appear only once

Cause: :rows inside :over lacks a literal non-negative integer or the lowercase plain symbol preceding, or appears twice. A logic variable and a prepared bind slot cannot supply the frame width.

Resolution:

  • Write :rows 2 preceding for the current row and up to two earlier rows.
  • Use :rows 0 preceding for only the current row.

PRS-125 Position function with an explicit :rows frame#

Error text: {} does not accept an explicit :rows frame

Cause: rank, row-number, lag, and lead operate on row positions or peers rather than an aggregate frame.

Resolution:

  • Remove :rows from these functions' :over list. Use :rows with sum, count, min, max, avg, or a registered aggregate.

QRY — Query Execution Errors#

Query execution errors occur after parsing succeeds, during pattern matching, predicate evaluation, or fact transacting.

QRY-001 Invalid entity#

Error text: Invalid entity: {}

Cause: An entity ID in a transact fact could not be resolved. Entity IDs must be UUIDs (as #uuid "..." tagged literals), existing entity symbols, or values that can be resolved to a UUID at execution time.

Resolution:

  • Use a #uuid "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" literal for a specific entity.
  • Use a new unique symbol if creating a new entity and let Minigraf assign a UUID.

Example:

(transact [["my-entity" :name "Alice"]])

"my-entity" is a plain string, not a UUID; use #uuid "..." or an entity variable

QRY-002 Attribute must be a keyword#

Error text: Attribute must be a keyword

Cause: An attribute in a transact fact is not a keyword (does not start with :). Attributes must always be namespaced keywords.

Resolution:

  • Use the :namespace/attr form, e.g. :person/name, :app/status.

Example:

(transact [[#uuid "..." name "Alice"]])

name is a symbol, not a keyword; use :name or :person/name

QRY-003 Cannot transact a pseudo-attribute#

Error text: Cannot transact a pseudo-attribute

Cause: A pseudo-attribute (an internal Minigraf metadata attribute used for system bookkeeping) was used as a fact attribute in transact. Pseudo-attributes are reserved and cannot be written by user code.

Resolution:

  • Use only user-defined attributes (e.g. :person/name, :app/status).
  • Avoid attribute names that begin with db/ or other system namespaces.

Example:

(transact [[#uuid "..." :db/id #uuid "..."]])

:db/id is a pseudo-attribute; use only user-defined attributes

QRY-004 Invalid value#

Error text: Invalid value: {}

Cause: A value in a fact is of a type that Minigraf cannot store. Supported value types are: string, integer (i64), float (f64), boolean, UUID ref (Value::Ref), and keyword.

Resolution:

  • Convert the value to a supported type.
  • For lists or maps, serialise to a string or model them as separate entities with :ref attributes.

Example:

(transact [[#uuid "..." :tags ["a" "b" "c"]]])

Vectors are not a valid value type; represent tags as separate facts or a comma-joined string

QRY-005 Transaction failed#

Error text: Transaction failed: {}

Cause: The batch of facts could not be committed. This is a wrapper error — the nested reason message identifies the root cause, which is typically a storage error, lock poisoning, or WAL write failure.

Resolution:

  • Check the nested error message.
  • Common sub-causes are covered by API-001 (lock poisoned) and STG/WAL errors.
  • Restart the process if the database is in an inconsistent state.

Scenario: A transact call fails because an earlier operation panicked while holding the write lock. The nested message reads "write lock is poisoned".

QRY-006 Retraction failed#

Error text: Retraction failed: {}

Cause: A retraction could not be applied. The nested reason message identifies the specific cause — the fact may not exist at the given transaction time, or a storage error occurred.

Resolution:

  • Check the nested error message.
  • Verify the entity, attribute, and value exactly match an asserted fact before retracting.
  • A retraction of a non-existent fact is not a no-op — it is an error.

Scenario: (retract [[#uuid "..." :name "alice"]]) fails because no fact [:name "alice"] was ever asserted for that entity.

QRY-007 Unknown predicate#

Error text: unknown predicate: '{}'

Cause: A :where clause invoked a predicate (expression function) that is not built-in and has not been registered via db.register_predicate().

Resolution:

  • Check spelling against built-in predicates: =, !=, <, <=, >, >=, matches?, starts-with?, ends-with?, contains?.
  • Register a custom predicate: db.register_predicate("between?", |args| { ... })?;.

Example:

(query {:find [?e]
        :where [[?e :age ?a]
                [(between? ?a 18 65)]]})

between? is not built-in; register it or use [(>= ?a 18)] [(<= ?a 65)]

QRY-008 Functions lock poisoned#

Error text: functions lock poisoned

Cause: The lock guarding the custom function registry was poisoned: a thread panicked while it held the lock. A query takes the lock only to copy the registry's handle when it opens. Since v3.0.0 no user code runs under it, so a custom function that panics does not poison it.

Resolution:

  • Restart the process. This indicates a bug in Minigraf; file an issue.

Scenario: A panic while a function was being registered left the registry lock poisoned; every later query returns this error.

QRY-009 Rules lock poisoned#

Error text: rules lock poisoned

Cause: An internal Rust mutex guarding the Datalog rule registry was poisoned — a previous operation panicked while adding or evaluating rules.

Resolution:

  • Restart the process.
  • If panics recur when using (rule ...) forms, investigate whether the rule input is triggering a bug.
  • File a bug with the rule text if the input appears valid.

Scenario: db.execute("(rule ...)") panics; subsequent queries that reference rules return this error.

QRY-010 Unknown aggregate function#

Error text: unknown aggregate function: '{}'

Cause: A :find aggregate names a function that is neither built-in (count, count-distinct, sum, sum-distinct, avg, min, max) nor registered with db.register_aggregate(). The name is resolved before the query runs, so the error does not depend on whether any row matches. Before v3.0.0 a query with no matching rows returned an empty result instead (see INT-029).

Resolution:

  • Check the function name for typos.
  • Register a custom aggregate first: db.register_aggregate("frob", init, step, finalise)?;.

Example:

(query [:find (frob ?b) :where [?a :x ?b]])

frob is not built-in; register it with register_aggregate() before querying

QRY-011 Unknown window function#

Error text: unknown window function '{}' — register it with register_aggregate() before querying

Cause: A :find window expression (... :over (...)) names a function that is neither a window built-in (sum, count, min, max, avg, rank, row-number) nor registered with db.register_aggregate(). The name is resolved before the query runs, so the error does not depend on whether any row matches. Before v3.0.0 a query with no matching rows returned an empty result instead (see INT-030).

Resolution:

  • Check the function name for typos.
  • Register the function with db.register_aggregate() before using it in an :over clause.

Example:

(query [:find ?b (frob ?b :over (:order-by ?b)) :where [?a :x ?b]])

frob is not a window built-in; register it first

QRY-012 Query memory limit exceeded#

Error text: query memory limit exceeded: {}

The text after the colon takes one of two forms:

  • {op} needs {n} more bytes and the query already holds {used} of its {limit}-byte limit
  • the allocator refused {n} bytes for {op}

Cause: A query held more state than OpenOptions::query_memory_limit allows, or the allocator refused memory one of its operators asked for. {op} names the operator that would have held the bytes: HashJoin, AntiJoin, Union, Distinct, Aggregate, Window, Relations or Recursive (a rule query's derived facts), or IdSpace (the query's entity and ident ids). Each operator counts an estimate of what it holds, per entry, so the count is the same on every platform. The limit is off by default (usize::MAX), so the first form only comes when a limit is set. The second form can come without one: it replaces the abort the process would otherwise suffer. A query inside a write transaction that has staged writes is not counted yet.

After the error the query's state is freed. The database, other queries and other cursors are unaffected. Through a cursor, the rows already returned stay returned and the error comes on the next call. A rule query can fail when it is opened, while its rules are evaluated.

Resolution:

  • Raise OpenOptions::query_memory_limit, or leave it at the default.
  • Narrow the query: bind a constant, add a join variable between patterns that share none (a cartesian product holds one side in full), or group by fewer variables.
  • Read a large answer through Minigraf::query instead of execute, which holds every row.

Example:

let db = Minigraf::open_with_options("app.graph", OpenOptions::new().query_memory_limit(64))?;
db.execute("(query [:find ?g (count ?e) :where [?e :g ?g]])")?;

Aggregate needs more than 64 bytes for its first group

QRY-013 Rule head entity is not an entity#

Error text: rule head entity is not an entity: rule '{}' gives a {} where a ref or a keyword is needed

Cause: A rule produced a head whose first argument, the entity of the fact it derives, is not an entity: a string, a number, a boolean or nil. Only a ref, or a keyword (which names the entity uuidv5(keyword)), is an entity. The head's second argument, the value, may be any value. The query that invoked the rule fails, whether the rule has not/not-join/or/or-join clauses or not. Before v3.0.0 a positive rule failed with INT-022 and a rule with not/or clauses silently dropped the row.

Resolution:

  • Put an entity variable first in the head: (owner ?item ?person), not (owner ?name ?item) where ?name binds a string.
  • To derive a fact about a value, keep the entity first and the value second.

Example:

(rule [(named ?n ?e) [?e :name ?n]])
(query [:find ?e :where (named ?n ?e)])

?n binds a string, so rule named gives a String as its entity

QRY-014 User function failed#

Error text: user function {} failed: {}

Cause: A user-defined predicate or aggregate registered with try_register_predicate or try_register_aggregate returned Err(UdfError), or a language binding's callback threw. The first argument is the function's name and the second is the UdfError's message. The query stops at the failing call: no later call of any user function is made for it. A cursor treats it as any other read error: it returns the rows of the batches the query finished before the failure first, then this error, then no more rows. Rows of the batch the failure happens in are not returned. A query inside a WriteTransaction that fails this way leaves the transaction open. Functions registered with register_predicate or register_aggregate never fail this way.

Resolution:

  • Read the message: it is the one the function gave.
  • Fix the input the function rejected, or make the function handle it (return Ok(false) for a predicate that should not match).

Example:

db.try_register_predicate("email?", |v| match v {
    Value::String(s) => Ok(s.contains('@')),
    _ => Err(UdfError::new("not a string")),
})?;
db.execute("(query [:find ?e :where [?e :mail ?m] [(email? ?m)]])")?;

An entity's :mail is an integer, so email? fails with not a string


QRY-015 collect-set found a set value#

Error text: collect-set over {} found a set value; bind a set-valued attribute with a pattern instead

Cause: collect-set gathers the values of an attribute into a set, and a set cannot hold a set. One of the values it found for the attribute is itself a set. The query fails rather than skip or flatten that value.

Resolution:

  • Read a set-valued attribute with a pattern: [?e :user/scopes ?scopes] binds the stored set.
  • Keep collect-set for attributes with one scalar value per fact.

Example:

(transact [[:alice :user/scopes #{:scope/read}]])
(query [:find ?s :where [?e :user/scopes _] [(collect-set ?e :user/scopes) ?s]])

STG — Storage Errors#

Storage errors relate to reading or writing the .graph file. They typically indicate a corrupted, truncated, or incompatible database file.

See the file format section in README for version history.

STG-001 Invalid header: too short#

Error text: Invalid header: too short (got {} bytes, need 64)

Cause: The .graph file is truncated — shorter than the minimum header size. Happens if the file was partially written (e.g. a crash during the initial save()) or if a non-Minigraf file was passed by mistake.

Resolution:

  • Restore the file from a backup. If no backup exists and the file was newly created, delete it and let Minigraf create a fresh one. See the file format section in README.

Scenario: Opening a .graph file that was truncated by a disk-full condition during the first db.save() or db.checkpoint() call.

STG-002 Invalid magic number: not a .graph file#

Error text: Invalid magic number: not a .graph file

Cause: The first 4 bytes of the file are not the Minigraf magic bytes MGRF. The path points to a non-Minigraf file, or the file header was overwritten by another process.

Resolution:

  • Verify the file path is correct and points to a .graph file created by Minigraf. Do not open SQLite databases, JSON files, or other formats with Minigraf.

Scenario: Minigraf::open("config.json") — a wrong file path was passed.

STG-003 Invalid v4/v5/v6 header too short#

Deprecated in v3.0.0. No longer emitted: files in formats v1–v6 are rejected with STG-028 before any header-size check. Kept for reference; this code will not be reused.

Error text: Invalid v4/v5/v6 header: expected at least 72 bytes, got {}

Cause: A file identified as format version 4, 5, or 6 is too short to hold a valid header of that version. The file is truncated at the header.

Resolution:

Scenario: A v5-format .graph file was corrupted by a partial write and is missing the latter part of its header.

STG-004 Invalid v6 header too short#

Deprecated in v3.0.0. No longer emitted: files in formats v1–v6 are rejected with STG-028 before any header-size check. Kept for reference; this code will not be reused.

Error text: Invalid v6 header: expected 80 bytes, got {}

Cause: A file identified as format version 6 is shorter than the required 80-byte v6 header. The file is truncated.

Resolution:

Scenario: A v6-format .graph file was written by an older pre-release version and its header is incomplete.

STG-005 Invalid header too short#

Error text: Invalid header: expected 84 bytes, got {}

Cause: The file declares a supported format version (7 or later) but is shorter than the 84-byte header. The file is truncated.

Resolution:

STG-006 Unsupported format version#

Error text: Unsupported format version: {} (supported: 7-{})

Cause: The file was written by a newer version of Minigraf than is currently installed. The format version number in the header is outside the range this library can read.

Resolution:

  • Upgrade the Minigraf library to a version that supports the file's format. Do not downgrade a database file to an older format — upgrade the library instead. See the file format section in README.

Scenario: A .graph file created with a future version of Minigraf is opened with the current library.

STG-007 page_count must be greater than 0#

Error text: page_count must be greater than 0

Cause: The page_count field in the file header is zero, which is invalid for any non-empty database.

Resolution:

Scenario: The header page of a .graph file was zeroed out by a storage hardware error.

STG-008 eavt_root_page must be less than page_count#

Error text: eavt_root_page ({}) must be less than page_count ({})

Cause: The EAVT B+tree root page index in the header points beyond the file's page count. The header is internally inconsistent — a sign of file corruption.

Resolution:

Scenario: Partial overwrite of the header during an interrupted checkpoint() left the root page pointer pointing past the end of the file.

STG-009 fact_page_count cannot exceed page_count#

Error text: fact_page_count ({}) cannot exceed page_count ({})

Cause: The fact page count in the header is larger than the total page count. The header is internally inconsistent.

Resolution:

Scenario: Bit-flip corruption in the header fact_page_count field produced an out-of-range value.

STG-010 Failed to read header from existing file#

Error text: Failed to read header from existing file: {}

Cause: A low-level I/O error prevented reading the file header. Common causes: file permissions, file moved or deleted between open and read, disk I/O error.

Resolution:

  • Check file system permissions (the process must have read access). Verify the file path still exists. Check for disk errors with your OS's filesystem check tool.

Scenario: Minigraf::open("/data/app.graph") fails because the process does not have read permission on the file.

STG-011 Internal page has no children#

Error text: internal page has no children

Cause: An internal B+tree page was found with an empty children list, which violates B+tree invariants. This indicates index corruption.

Resolution:

  • Stop writing to the database and copy both the .graph file and its .wal sidecar before trying anything else.
  • Restore from backup. Do not delete the .graph file: the WAL holds only the transactions written since the last checkpoint, so it cannot rebuild the database on its own. If you restore an older .graph file, you can keep the matching .wal only if it was written after that file's last checkpoint.
  • Index integrity checking and rebuilding from fact pages are tracked in #373.

Scenario: A crash mid-checkpoint left an internal B+tree page in an inconsistent state.

STG-012 Expected index page at page N#

Error text: Expected index page at page {}

Cause: The B+tree traversal expected an index page at a specific page number, but the page found has a different type tag. This indicates index corruption or file truncation.

Resolution:

Scenario: A packed-fact page and an index page were written to overlapping positions due to a page allocation bug in a pre-release version.

STG-013 range_scan expected leaf#

Error text: range_scan: expected leaf at page_id={}

Cause: A range scan of the B+tree expected a leaf page at a given position but found a non-leaf page. Indicates corruption of the B+tree structure.

Resolution:

Scenario: A partial checkpoint left the B+tree leaf and internal pages inconsistent.

STG-014 Expected packed page type#

Error text: Expected packed page (0x02), got 0x{}

Cause: A page expected to contain packed facts has a different page type tag. Indicates that the page layout in the file does not match the header's page allocation records. Opening a format v7 file (written by v2.x) checks every page in its fact-page range: a v2.x writer puts only fact pages there, so another type byte means the page is damaged. The open fails, read-write and read-only, and the v7 file is not modified or upgraded (#496).

Resolution:

  • Restore from backup. See the file format section in README.
  • For a v7 file, the other v7 pages are unchanged: opening a copy with Minigraf v2.x, which skips the damaged page, reads the facts the other pages hold.

Scenario: A v7 file copied with a bad sector has a fact page whose first byte is no longer 0x02. Before v3.0.0, the open skipped that page and the v7 → v8 upgrade freed it, losing its facts.

STG-015 Record extends beyond page boundary#

Error text: Record at slot {} extends beyond page boundary

Cause: A fact record at the given slot in a packed-facts page extends past the 4KB page boundary. This indicates corruption of the page's internal offset table.

Resolution:

Scenario: A disk write was interrupted, leaving a partial fact page with a corrupt slot table.

STG-016 Backend mutex poisoned#

Error text: backend mutex poisoned

Cause: An internal Rust mutex guarding the storage backend was poisoned — a previous operation panicked while holding it.

Resolution:

  • Restart the process. The WAL will be replayed on the next Minigraf::open() to recover committed facts. If panics recur, investigate the application code for panics occurring inside write operations.

Scenario: A write closure panics mid-transaction, poisoning the backend mutex and preventing all subsequent reads and writes.

STG-017 Page count overflow: index_start#

Error text: page count overflow computing index_start

Cause: Computing the starting page of the index section caused an integer overflow in the page count. This occurs only if the database has grown to an extreme size (billions of pages) or if the page count field in the header is corrupted.

Resolution:

  • If the database file size is normal (under several terabytes), the header is likely corrupted — restore from backup. If the file is genuinely enormous, file a bug with the database size.

Scenario: The page_count header field was corrupted to u64::MAX, causing an overflow when computing derived positions.

STG-018 Page count overflow: next_free#

Error text: page count overflow computing next_free

Cause: Computing the next free page position caused an integer overflow. Same root cause as STG-017 — extreme database size or corrupted header.

Resolution:

  • Same as STG-017. Restore from backup if the database size is normal.

Scenario: Same as STG-017.

STG-019 Page count overflow: new_fact_start#

Error text: page count overflow computing new_fact_start

Cause: Computing the starting position for new fact pages caused an integer overflow. Same root cause as STG-017.

Resolution:

  • Same as STG-017. Restore from backup if the database size is normal.

Scenario: Same as STG-017.

STG-020 Fact index exceeds u16::MAX#

Error text: fact index {} exceeds u16::MAX

Cause: The number of facts on a single packed page exceeded 65535 (u16::MAX). This is a theoretical limit that should not be reached in practice — a single 4KB page holds roughly 20–30 facts.

Resolution:

  • This should not occur under normal operation. If it does, file a bug with the fact serialisation size of the triggering fact.

Scenario: A bug in the page packer caused more facts to be written to a single page than the slot index can represent.

STG-021 Page id overflow in checksum computation#

Error text: page id overflow in checksum computation

Cause: A page ID exceeded the range that can be represented during checksum computation. Indicates an extremely large database or a corrupted page count.

Resolution:

  • If the database file is unexpectedly large, file a bug. Otherwise restore from backup.

Scenario: Same as STG-017 — corrupted page_count triggers overflow during the checksum phase.

STG-022 Page id overflow writing fact pages#

Error text: page id overflow writing fact pages

Cause: A page ID exceeded the representable range when writing fact pages during a checkpoint. Indicates an extremely large database or corrupted header state.

Resolution:

  • Same as STG-021. Restore from backup if the database size is normal.

Scenario: Same as STG-017.

STG-023 Page index exceeds u64::MAX#

Error text: page index {} exceeds u64::MAX

Cause: A page index computation produced a value larger than u64::MAX. This is practically unreachable — would require a database with more pages than u64 can represent.

Resolution:

  • This should never occur under normal operation. File a bug.

Scenario: An extreme edge case in page count arithmetic triggered an overflow that wrapped past u64::MAX.

STG-024 Pending fact count exceeds u64::MAX#

Error text: pending fact count exceeds u64::MAX

Cause: The number of pending (unflushed) facts in the WAL exceeded u64::MAX. Practically unreachable.

Resolution:

  • This should never occur under normal operation. File a bug.

Scenario: An extremely long-running write session accumulated more unflushed facts than u64 can count.


STG-025 Database already open in this process#

Error text: Database is already open in this process ({}). A second handle on one file would give each its own page table and corrupt both — reuse the existing handle instead. Minigraf is cheap to clone and all clones share the same database.

Cause: This process already holds an open handle on this file. Two FileBackend instances on one file each cache their own header.page_count, allocate new pages from that count, and bounds-check reads against it, so the two page tables diverge and produce intermittent Page N out of bounds errors.

Resolution:

  • Reuse the handle you already have. Minigraf is cheap to clone and all clones share one database.
  • If you cannot find the other handle, it is usually held by a longer-lived object than you expect — a cache, a registry, or a background task.

Read-only handles (OpenOptions::read_only) share a file with each other, but not with a read-write handle: either kind refuses the other with this error.

Scenario: A request handler calls Minigraf::open per request while a connection pool already holds the same path open.


STG-026 Database locked by another process#

Error text: Database is locked by another process ({}). The lock is held on the file itself and is released automatically when the holding process exits, so there is no lock file to clean up.

Cause: Another process holds the kernel file lock on this .graph file. Minigraf is single-writer: one process at a time. This is reported only after a bounded retry (up to ~375ms) rules out a transient fork-related false positive — see the v2.0.0 CHANGELOG entry on the bounded retry.

In browser OPFS mode, the same code means another tab or worker (or another handle in this worker) holds the file's exclusive sync access handle. The browser reports NoModificationAllowedError (Safari: InvalidStateError); close() or worker termination releases it. There is no retry on acquisition and no fallback to IndexedDB.

Resolution:

  • Wait for the other process to exit; the kernel releases the lock automatically, including when the process is killed.
  • There is no lock file to delete. If you find a stale .graph.lock, it is a leftover from a version before 2.0 and has no effect — it is not read or deleted, and should not be removed by hand in case an old process still depends on it.
  • If two services genuinely need the same file, put one in front of the other. Minigraf is embedded, not a server.

A read-only handle (OpenOptions::read_only) in another process also refuses a read-write open, and a read-write handle refuses a read-only one. Read-only handles do not refuse each other.

Scenario: A rolling deployment starts the new pod before the old one has exited, and both mount the same volume.


STG-027 Filesystem does not support file locking#

Error text: Failed to lock database at {}: {}. This filesystem does not support file locking (common on NFSv3 without lockd, and on some FUSE mounts). Set allow_unlockedinOpenOptions to open anyway — that accepts the risk that concurrent writers corrupt the file.

Cause: The underlying filesystem rejected the lock outright. Common on NFSv3 mounts with no lockd running, and on some FUSE filesystems. Because the file must exist before it can be locked, this refusal can leave a 0-byte .graph file behind; the next open sees is_new and initialises normally.

Resolution:

  • Prefer moving the database to a filesystem that supports locking — this is the safe fix.
  • On NFS, ensure NFSv4, or start lockd for NFSv3.
  • If you are certain there is exactly one writer, set OpenOptions::allow_unlocked(true). This accepts the risk that concurrent writers corrupt the file; Minigraf cannot detect them without a working lock.

Scenario: A .graph file placed on an NFSv3 export whose lockd is not running.

NFSv3 nolock is not covered by this error — it is a silent, undetectable gap (#334). An export explicitly mounted with -o nolock behaves differently from plain "no lockd": the Linux NFS client serves flock/OFD locks out of its own local, in-kernel lock table instead of going over NLM to the server. try_lock sees an ordinary local success, classify takes the same branch it would on a filesystem where locking genuinely works, and this error is never raised — allow_unlocked is never consulted because the code never learns the mount can't really lock. Two separate client hosts writing the same nolock export each get a false Ok(()) from their own kernel with zero cross-host coordination, and can silently corrupt the file. There is no way to detect this from inside try_lock's result, so nolock NFSv3 exports are an unsupported deployment for multi-writer use, the same way running mixed Minigraf versions against one file is unsupported (see the kernel-locking CHANGELOG entry) — avoid nolock exports rather than relying on this check to catch them.

STG-028 Format version no longer supported#

Error text: Format version {} is no longer supported (oldest supported: {}). Open the file once with Minigraf v2.x to upgrade it to format v7, then open it with this version.

Cause: The file was last written by Minigraf v1.x or earlier in a format older than v7. Minigraf v3.0.0 and later read only format v7 (written by v2.x) and v8.

Resolution:

  • Open the file once with Minigraf v2.x, which upgrades it to format v7, then open it with this version. The file is not modified by the failed open.

Scenario: A .graph file created with Minigraf v1.x and never opened with v2.x.

STG-029 Page checksum mismatch#

Error text: Page {} checksum mismatch: the page is torn or corrupted

Cause: A page's stored CRC32 does not match its contents. The page was partly written (a torn write) or its bytes changed on disk after it was written.

Resolution:

  • Restore from backup. If the damaged page belongs only to an unfinished checkpoint, the file opens at the previous checkpoint and the WAL replays the rest; this error means a page reachable from the committed meta page is damaged.

Scenario: A disk sector holding a B+tree leaf is corrupted by the storage device.

STG-030 Page id mismatch#

Error text: Page id mismatch: requested page {} but the page records id {}

Cause: A page's header records a different page id from the one that was read. The storage layer wrote the page to the wrong offset (a misdirected write), or the file was edited.

Resolution:

  • Restore from backup. Check the storage device and filesystem for faults.

Scenario: A faulty controller writes page 812's contents at the offset of page 640.

STG-031 Page generation ahead of meta#

Error text: Page {} has generation {}, newer than the committed generation {}

Cause: A page reachable from the committed meta page records a checkpoint generation newer than the meta page itself. Pages are only written by the checkpoint that commits them, so this means a stale meta page, or a page from a later checkpoint written where an older page should be.

Resolution:

  • Restore from backup.

Scenario: A meta page restored from an old copy of the file, next to data pages from a newer one.

STG-032 No valid meta page#

Error text: No valid meta page: the file is not a Minigraf v7 or v8 database, or both meta pages are damaged

Cause: Neither meta page (page 0 or page 1) passes its checksum, page 0 is not a valid format v7 header, and no migration backup meta page can be used. Pre-release v8 files written during v3.0.0 development are also rejected this way: those with a single 84-byte header, and those with meta pages but no dictionary tree (written before covering keys).

Resolution:

  • Check that the path points to a Minigraf database.
  • Restore from backup. The file is not modified by the failed open.

Scenario: Opening a file whose first two pages were overwritten, or a file from a v3.0.0 development build.

STG-033 Meta page damaged after commit#

Error text: Meta page damaged after commit: generation {} is valid but a later commit existed ({}). Opening would silently drop that checkpoint

Cause: One meta page is valid and the other is damaged, and there is evidence that the damaged one held a newer, completed checkpoint: the WAL records a newer base generation, or there is no WAL and data pages from the newer generation exist. Opening at the older generation would lose the facts of the newest checkpoint, whose WAL is already deleted.

OPFS mode has no WAL and deliberately opens at the sole valid meta instead of raising this error, even with later-generation data pages. That recovers an interrupted commit, but can silently lose the latest acknowledged checkpoint if its meta later rots. Native recovery keeps this refusal unchanged.

Resolution:

  • Restore from backup. The file is not modified by the failed open.

Scenario: A storage fault corrupts the most recent meta page after a successful checkpoint.

STG-034 Unsupported file feature#

Error text: Unsupported file feature bits {}: the file was written by a newer Minigraf version

Cause: The meta page's required_features bitmask has bits this version does not know. A newer Minigraf v3.x release wrote structures this version cannot read.

Resolution:

  • Open the file with the Minigraf version that wrote it, or a newer one. The file is not modified by the failed open.

Scenario: A file written by a later v3.x release that enabled an optional on-disk structure, opened with v3.0.0.

STG-035 Free-list inconsistency#

Error text: Free list is inconsistent: {}

Cause: The chain of free-list pages loops, or holds a page id that is reserved or past the end of the file. Minigraf::verify() also reports here a free-list count that disagrees with the meta page, a page listed twice, a free page that is still in use, a page used twice, and pages that are neither free nor in use (leaked).

Resolution:

  • Run Minigraf::rebuild_indexes(): it derives a new free list from the pages the rebuilt file uses.
  • Restore from backup if the rebuild fails.

Scenario: A corrupted free-list page whose next pointer points back at itself.


STG-036 Dictionary entry missing#

Error text: Dictionary entry missing: {}

Cause: An index entry refers to an entity id, ident id, transaction or long value that has no entry in the file's dictionary (DICT tree). The file is damaged.

Resolution:

  • Restore from backup.

Scenario: A DICT leaf lost to a bad sector while the index trees that refer to its ids are intact.


STG-037 Transaction with two timestamps#

Error text: Transaction {} has two timestamps: {} and {}

Cause: A checkpoint or a v7 migration found facts with the same tx_count but different tx_id values. Format v8 records one timestamp per transaction, and Minigraf refuses to change a stored timestamp. Every write path stamps one tx_id per tx_count, so this means the facts were written outside those paths or the file is damaged.

Resolution:

  • Keep using the release that wrote the file and report the issue, with the transaction number from the message.

Scenario: A v7 file whose facts were edited by an external tool so that two transactions share one tx_count.


STG-038 Index disagrees with the committed facts#

Error text: Index {} disagrees with the committed facts: {}

Cause: Minigraf::verify() found an index whose pages are intact (every checksum passes) but whose contents are wrong: it holds a different number of entries or different facts than EAVT, EAVT's entry count differs from the meta page's fact count, an entry belongs to a transaction newer than the last checkpoint, or a key's long value does not match the stored value. Queries that use that index can return wrong or missing results.

Resolution:

  • Run Minigraf::rebuild_indexes(), which rebuilds all four indexes from an index that agrees with another one.
  • Restore from backup if the rebuild fails with STG-041.

Scenario: A bug or a lost write leaves AVET without some entries that EAVT and AEVT hold.


STG-039 Malformed tree#

Error text: Tree {} is malformed: {}

Cause: Minigraf::verify() found a B+tree whose pages pass their checksums but whose structure is wrong: keys out of order, a key outside its parent's separator range, a page reached twice (from the same tree or from two trees), a tree deeper than any real tree can be, a node or an index key that does not decode.

Resolution:

  • If the tree is EAVT, AEVT, AVET or VAET, run Minigraf::rebuild_indexes().
  • If the tree is DICT, restore from backup: the dictionary holds the only copy of entity UUIDs and attribute names.

Scenario: A misdirected write leaves an older, valid leaf where a newer one belonged, so two leaves of the tree overlap.


STG-040 Dictionary inconsistency#

Error text: Dictionary is inconsistent: {}

Cause: Minigraf::verify() found DICT entries that disagree with each other or with the meta page: the UUID → entity-id and entity-id → UUID maps (or the ident maps) are not inverse, an id is not below the meta page's next id, an entry has the wrong shape or an unknown tag, or a long value does not match its hash.

Resolution:

  • Restore from backup. The dictionary cannot be rebuilt from the indexes.

Scenario: A DICT leaf is replaced by an older valid copy, so an entity id maps to a UUID that maps to another id.


STG-041 Cannot rebuild indexes#

Error text: Cannot rebuild indexes: {}

Cause: Minigraf::rebuild_indexes() found no index to rebuild from. A source must be an intact index (EAVT, AEVT or AVET) that agrees with another intact index, or the only intact one. This error also means the dictionary is damaged. The file is not modified.

Resolution:

  • Restore from backup.

Scenario: EAVT, AEVT and AVET are all intact but each holds a different set of facts.


STG-042 Database file not found (read-only open)#

Error text: database file not found ({}); a read-only open does not create one

Cause: The database was opened with OpenOptions::read_only and no file exists at the path. A read-write open creates a new, empty database; a read-only open never creates or writes anything.

Resolution:

  • Check the path. The {} is the path as given.
  • To create the database, open it once without read_only.

Scenario: A migration tool is pointed at memory.graph from the wrong working directory.

STG-043 Log writer target already exists#

Error text: {} already exists; a log writer only creates a new database

Cause: LogWriter::create was given a path where a file, or that path's WAL (<path>.wal), already exists; or LogWriter::finish found that a file appeared at the path while the build ran. A log writer never overwrites or extends a database, and a stale WAL beside the new file would be replayed onto it. The {} is the path that exists. At finish, the existing file is left untouched and the build (<path>.partial) is deleted.

Resolution:

  • Write to a new path, then replace the old database yourself once the new one is checked (verify(), your own audit).
  • If the old file and WAL are no longer needed, delete them first.
  • Do not create the target while a build runs.
let mut out = LogWriter::create("memory.v2.graph", OpenOptions::new())?;
// ... append, then out.finish()?; then swap files

Scenario: A migration is re-run after a successful first run, with the same output path.

STG-044 File shorter than its meta page count#

Error text: File is shorter than its meta page: the meta counts {} pages but the file holds {} (truncated?)

Cause: The meta page chosen on open records a page_count larger than the file. Every checkpoint writes and syncs its pages before its meta page, so a file that ends before that count lost its tail after the commit: an interrupted copy, a partial download, a full disk while copying, or an edit of the file. Opening it would fail later on a missing page, and writes would go to the WAL with no way to checkpoint them. Opening at the other meta page would silently drop the newest checkpoint, so the open is refused. The file is not modified.

Resolution:

  • Copy the database again from its source, or restore it from backup.
  • Check the file size: a .graph file is a whole number of 4 KiB pages, at least as many as the first {}.

Scenario: A .graph file is copied to another machine and the copy stops partway.

STG-045 File shorter than one page and not a new database#

Error text: File is {} bytes, shorter than one page, and is not a new Minigraf database

Cause: The file is longer than zero bytes but shorter than one 4 KiB page, and its bytes are not a torn first write of a new database. Creating a database writes its first meta page in one go, so a crash during that write can leave only a prefix of that page (or zeros); such a file is opened as a new, empty database. Any other short file is something else: a different file at the path, a database cut short by an interrupted copy, or a damaged file. Earlier versions opened it as a new database and a read-write open overwrote it. The file is not modified, read-write or read-only.

Resolution:

  • Check that the path points at the intended .graph file.
  • Copy the database again from its source, or restore it from backup.
  • If the file is not needed, delete it and open the path again to create a new database.

Scenario: A copy of a .graph file stops after its first kilobyte, and the copy is opened.


STG-046 Earlier checkpoint or IndexedDB flush failed on this handle#

Error text: an earlier checkpoint or IndexedDB flush failed on this handle and is not retried; reopen the database

Cause: A checkpoint (automatic, checkpoint(), rebuild_indexes(), or the one on close) failed with an I/O error after it may have written pages: a failed write, a full disk, or a failed fsync. After a failed fsync the operating system may have dropped the written pages while marking them clean, so a second fsync can report success for data that never reached the disk (the PostgreSQL "fsyncgate" problem). The checkpoint's meta page may also have reached the disk although the call failed; a retry would then overwrite pages that page references. So the handle never retries: every later write, checkpoint and index rebuild through it fails with STG-046.

Nothing committed is lost. Every committed transaction is still in the WAL, and the .graph file holds either the previous checkpoint or the failed one complete. Queries through the handle keep working. The close-time checkpoint is skipped.

In OPFS mode a failed write, short write or flush has the same failed-handle rule: later writes/checkpoints fail with STG-046 while reads and close() keep working. There is no WAL. Close and reopen to select the complete previous or new generation; the rejected transaction may be wholly present. Closing does not retry the failed commit.

In IndexedDB mode, a failed flush rejects with STG-048 (naming the IndexedDB write and DOM exception); failure to prepare its pages keeps its engine code. The handle then refuses newly admitted transact/retract, commit (even empty), checkpoint and import with STG-046, changing nothing. Reads, cursors, prepared queries, rules, transaction staging, exportGraph() and close() still work. Memory includes the failed operation and overlapping work applied before the failure became known. Export reflects that memory, not an acknowledgement of durability. Later flushes wait for earlier ones and send nothing if an earlier flush failed. Close and reopen recovers the state before the failed flush; a rejected IndexedDB write is never stored. A failed import stays visible in memory but its puts and deletes leave IndexedDB unchanged. Closing does not retry anything.

Resolution:

  • Fix the cause (free disk space, check the device and the kernel log), then drop every clone of the handle and open the database again. Opening picks the newest complete checkpoint and replays the WAL.
  • Do not copy the .graph file without its .wal while the handle is in this state.

Scenario: The disk fills during an automatic checkpoint, so the transact that triggered it fails with the I/O error (its transaction is already in the WAL and applied). The next transact fails with STG-046 until the database is reopened.


STG-047 WAL is from a later checkpoint#

Error text: WAL is from a later checkpoint: it was created at generation {} but the file is at generation {}. Replaying it would leave a gap in the history (was an older .graph restored next to a newer .wal?)

Cause: The .wal file's header records the generation of the checkpoint that was current when the WAL was created. A WAL is deleted after the next checkpoint commits, so it is never newer than the .graph file it belongs to. This WAL is newer than every meta page in the file: the .graph is an older copy of the database, such as a restored backup, and the WAL beside it came from the live database. Its entries start after a checkpoint this file does not have, so replaying them would apply the later transactions and silently skip the ones in between. Earlier versions did that. Neither file is modified, read-write or read-only. v2.x WALs record no generation, so v2.x cannot detect this.

Resolution:

  • If you are restoring a backup: move the .wal aside and open again. The database opens at the backup.
  • If the .graph was replaced by mistake: put back the .graph that the WAL belongs to.

Scenario: An operator copies last night's app.graph over the current one and leaves the current app.graph.wal in the directory.


STG-048 Browser storage operation failed#

Error text: browser storage operation failed: {} ({})

Cause: An IndexedDB write (transaction creation, request queueing, error or abort), or an OPFS operation failed: opening an entry, acquiring its sync access handle, reading, writing, flushing, checking size, truncating, or staging an import. The message names the operation and the browser exception (for example QuotaExceededError), or a short read/write. Short transfers are never accepted as complete pages. Lock contention uses STG-026; an unavailable OPFS context uses API-026.

Resolution:

  • Check the operation and exception name, available origin quota and browser permissions.
  • In OPFS mode, after a commit may have written, later writes fail with STG-046. Call close() and reopen. Reads may still include the unconfirmed transaction; a rejected commit does not prove it is absent on disk.
  • An OPFS import failure at publication closes the database; reopen to recover the complete old or new image.
  • After an IndexedDB flush fails, later durable operations fail with STG-046. Close and reopen to recover the successful prefix before the failed flush. The rejected write, including all its page deletes, is absent from IndexedDB.

Scenario: Origin quota is exhausted while a worker writes a data page; execute() rejects with STG-048 naming the write and QuotaExceededError.


WAL — Write-Ahead Log Errors#

WAL errors relate to the sidecar .wal file written alongside the .graph file. The WAL is replayed on open and deleted on checkpoint.

WAL-001 Invalid WAL magic number#

Error text: Invalid WAL magic number: not a .wal file

Cause: The sidecar .wal file does not start with the expected WAL magic bytes. The file may have been replaced, corrupted, or created by an incompatible tool.

Resolution:

  • Copy both the .graph file and the .wal file before changing anything.
  • Deleting <dbname>.wal makes the database open, but every transaction committed since the last checkpoint is lost, because those transactions exist only in the WAL. Do this only if you have a backup or accept that loss.
  • Do not manually create or edit .wal files.

Scenario: my-db.wal was accidentally replaced with an empty file before Minigraf::open("my-db.graph") was called.

WAL-002 Unsupported WAL version#

Error text: Unsupported WAL version: {} (expected {})

Cause: The .wal file was written by a version of Minigraf with a different WAL format. This can occur when downgrading the library after a WAL was written by a newer version.

Resolution:

  • Open the database with the Minigraf version that wrote the WAL and call checkpoint(). This moves the WAL's transactions into the .graph file and removes the WAL. Then open it with the new version.
  • Deleting the .wal file instead loses every transaction committed since the last checkpoint, because those transactions exist only in the WAL. Do this only if you have a backup or accept that loss.

Scenario: A .wal file written by a pre-release version of Minigraf is opened with the stable release, which uses a different WAL version number — e.g. Unsupported WAL version: 3 (expected 2).

WAL-003 Value size exceeds maximum#

Error text: Value of {} bytes exceeds the maximum of {} bytes. Store large payloads externally and reference them with a Value::String URL/path or Value::Ref entity ID.

Cause: A string value is longer than MAX_VALUE_BYTES (4,068 bytes, one value page), a set value's stored form may be longer than that, or an attribute name or keyword value (a keyword in a set included) is longer than 1,024 bytes. A set's size counts each string element's bytes plus three (and one per zero byte), each keyword element as 6 bytes and each ref element as 10, each integer as up to 10 and each float as 9. This typically means a Value::String contains very large content such as raw document text, a base64-encoded image, or binary data. LogWriter::append checks the same limits. In-memory databases have no WAL and no limit.

Resolution:

  • Store large payloads in an external file or object store.
  • Store the file path or URL as a Value::String attribute on the entity.
  • Or create a dedicated entity for the content and reference it with Value::Ref.
  • See the Datalog Reference — Constraints and Limits for the size limit.

Example:

(transact [[#uuid "..." :document/body "<50000-word essay...>"]])

The :document/body value is too large; store it in a file and use :document/path instead

WAL-004 Fact serialised size exceeds u32 range#

Error text: fact serialised size {} exceeds u32 range

Cause: The serialised size of a single fact exceeds u32::MAX (~4 GB). This is practically unreachable: WAL-003's value limits fire first.

Resolution:

  • This should not occur under normal operation.
  • If it does, file a bug.

Scenario: An extreme edge case where the fact serialisation path bypassed the WAL-003 limit check, producing an impossibly large entry — e.g. fact serialised size 4294967297 exceeds u32 range.

WAL-005 WAL num_facts exceeds platform usize#

Error text: WAL num_facts exceeds platform usize

Cause: The number of facts recorded in the WAL header exceeds the platform's usize maximum. Practically unreachable on 64-bit platforms.

Resolution:

  • This should not occur under normal operation.
  • File a bug.

Scenario: A corrupted WAL header field contains a fact count larger than usize::MAX, triggering an overflow during replay.

WAL-006 Failed to delete WAL file#

Error text: failed to delete WAL file {}: {}

Cause: After a successful checkpoint(), Minigraf could not delete the sidecar .wal file. This is typically a file system permissions issue.

Resolution:

  • Check that the process has write access to the directory containing the .graph file (WAL deletion requires directory write permission, not just file write permission).
  • The .wal file is safe to delete manually — Minigraf will create a new one on the next write.

Scenario: db.checkpoint() succeeds but the process lacks directory write permission, preventing deletion of my-db.wal — e.g. failed to delete WAL file my-db.wal: permission denied.


WAL-007 Earlier WAL write failed on this handle#

Error text: an earlier write to the WAL failed on this handle; reopen the database or call checkpoint() before writing again

Cause: A write or fsync of the .wal file failed earlier on this handle (for example a full disk or an I/O error), and that write returned its own error. The WAL may now end in a partial entry. Recovery stops at the first partial entry, so anything appended after it would be lost after a crash. Every later write through this WAL fails with WAL-007 instead.

The transaction whose write failed was not applied in memory. Whether it is durable is unknown: if its entry reached the disk whole, it is replayed when the database is next opened; otherwise it is lost. It is never applied in part.

Resolution:

  • Fix the cause (free disk space, check the device), then reopen the database. Opening cuts off a partial entry at the end of the WAL.
  • Or call checkpoint(). A successful checkpoint writes the committed facts to the .graph file and deletes the WAL; the next write starts a new one. The failed transaction is then gone for good.
  • If the failed transaction matters, check after reopening whether it is there, and write it again if it is not.

Scenario: The disk fills during db.execute("(transact ...)"), which fails with an I/O error. The next transact fails with WAL-007 until the database is reopened or checkpoint() succeeds.


API — Database API Errors#

API errors indicate a violated contract in how the public Minigraf or WriteTransaction API is used.

API-001 Write lock poisoned#

Error text: write lock is poisoned; database may be in an inconsistent state

Cause: A previous WriteTransaction panicked while holding the write lock. Rust's mutex poisoning mechanism prevents further writes to protect data integrity.

Resolution:

  • Restart the process — the WAL will be replayed on the next Minigraf::open() call to recover any committed facts. If panics are occurring regularly, investigate the root cause in your application code before retrying writes.

Scenario: db.begin_write() is called after a previous write closure panicked mid-transaction, poisoning the lock.

API-002 Unexpected command variant in write path#

Error text: unexpected command variant in write path

Cause: An internal routing error — a command type not expected in the write path was dispatched there. This indicates a bug in the Minigraf library, not a user mistake.

Resolution:

  • File a bug report with the exact input string that triggered this error.

Scenario: A newly added command type was not handled in the write path dispatcher, causing an unexpected variant to arrive.

API-003 Attribute must be a keyword (API layer)#

Error text: attribute must be a keyword

Cause: An attribute validation check in the database API layer (mirroring QRY-002) found a non-keyword attribute. This fires for facts that pass parsing but fail validation at execution time.

Resolution:

  • Ensure all attribute names are keywords starting with :, e.g. :person/name, :app/status.

Example:

// Wrong — attribute is a plain string
db.execute("(transact [[#uuid \"...\" \"name\" \"Alice\"]])")?;

// Right
db.execute("(transact [[#uuid \"...\" :name \"Alice\"]])")?;

API-004 Cannot transact a pseudo-attribute (API layer)#

Error text: cannot transact a pseudo-attribute

Cause: A pseudo-attribute (reserved internal attribute) was used in a transact call. This mirrors QRY-003 but fires at the API layer.

Resolution:

  • Use only user-defined attributes. Avoid attribute names in system-reserved namespaces such as db/.

Example:

// Wrong
db.execute("(transact [[#uuid \"...\" :db/id #uuid \"...\"]])")?;

// Right — use user-defined attributes
db.execute("(transact [[#uuid \"...\" :person/name \"Alice\"]])")?;

API-005 Only query commands can be prepared (got transact)#

Error text: only (query ...) commands can be prepared; got transact

Cause: db.prepare() only accepts (query ...) forms. Passing a (transact ...) command to prepare() is not supported.

Resolution:

  • Use db.execute() for transact commands. Only use db.prepare() for (query ...) commands that will be executed repeatedly with different bind slot values.

Example:

// Wrong
let pq = db.prepare("(transact [[#uuid \"...\" :name \"Alice\"]])")?;

// Right — use execute() for transact
db.execute("(transact [[#uuid \"...\" :name \"Alice\"]])")?;

// Right — prepare() is for repeated queries
let pq = db.prepare("(query {:find [?e] :where [[?e :name $name]]})")?;

API-006 Only query commands can be prepared (got retract)#

Error text: only (query ...) commands can be prepared; got retract

Cause: db.prepare() does not accept (retract ...) commands.

Resolution:

  • Use db.execute() for retract commands.

Example:

// Wrong
let pq = db.prepare("(retract [[#uuid \"...\" :name \"Alice\"]])")?;

// Right
db.execute("(retract [[#uuid \"...\" :name \"Alice\"]])")?;

API-007 Only query commands can be prepared (got rule)#

Error text: only (query ...) commands can be prepared; got rule

Cause: db.prepare() does not accept (rule ...) commands.

Resolution:

  • Use db.execute() for rule commands. Rules are registered once and then available in all subsequent queries — they do not need to be prepared.

Example:

// Wrong
let pq = db.prepare("(rule [(ancestor ?x ?y) [?x :parent ?y]])")?;

// Right
db.execute("(rule [(ancestor ?x ?y) [?x :parent ?y]])")?;

API-008 Function registry lock poisoned#

Error text: function registry lock poisoned: PoisonError { .. }

Cause: The lock guarding the custom function/predicate registry was poisoned: a thread panicked while it held the lock. The lock is held only while a query copies the registry's handle at open and while a function is registered. No user code runs under it: since v3.0.0 a query holds no registry lock while a custom function runs, so a function that panics does not poison it.

Resolution:

  • Restart the process. This indicates a bug in Minigraf; file an issue.

Scenario: A panic inside db.register_predicate(), db.register_aggregate() or their try_ forms while the registry lock is held; the next registration returns this error.

API-009 WAL not initialized#

Error text: WAL not initialized

Cause: db.execute() or db.checkpoint() was called in a state where the WAL subsystem has not been initialised. This indicates an internal sequencing bug in the library.

Resolution:

  • File a bug report with the sequence of API calls that produced this error.

Scenario: A code path in the library called a write operation before the WAL was set up during Minigraf::open().

API-010 Query with bind slots passed to execute()#

Error text: query contains bind slots ({}); use prepare() and execute the prepared query with bind values

Cause: The query contains one or more $name bind slots, but it was run with db.execute() (or WriteTransaction::execute(), or the REPL). Bind slots are placeholders for db.prepare(); execute() has no values to put in them. The {} lists the slots found, sorted by name.

Resolution:

  • Prepare the query and supply a value for every slot:
let alice_id = minigraf::EntityId::new_v5(&minigraf::EntityId::NAMESPACE_OID, b":alice");
let pq = db.prepare("(query [:find ?status :as-of $tx :valid-at $date \
                     :where [$entity :employment/status ?status]])")?;
let result = pq.execute(&[
    ("tx", BindValue::TxCount(5)),
    ("date", BindValue::Timestamp(1_704_067_200_000)),
    ("entity", BindValue::Entity(alice_id)),
])?;
  • Or replace each $name with a literal value and keep using execute().

Scenario: A query copied from the prepared-query docs is pasted into the REPL or passed to db.execute() unchanged.

API-011 Two valid-time windows for one fact in one transact#

Error text: one (transact ...) asserts the same value of {} with two valid-time windows; assert it once with its final window

Cause: One (transact ...) asserts the same entity, attribute and value twice with different :valid-from/:valid-to bounds. At any transaction time a fact has exactly one current valid-time window. Within one statement neither window comes later, so the statement is rejected and nothing is written. The {} is the attribute. Identical repeats are allowed and stored once. Inside a WriteTransaction, tx.execute() rejects the statement and stages nothing; the transaction stays usable. Across several statements of one WriteTransaction there is no error: the last statement that writes a fact decides it (#477). LogWriter::append returns this code for a record that asserts a fact the open transaction already asserts with another window; that record alone is rejected.

Resolution:

  • Assert the fact once per transaction, with the window it should have.
  • To change a window later (close it, extend it, reopen it), transact the same fact again with the new bounds. The earlier window stays visible through :as-of.
  • A fact that was true over two separate periods cannot have both windows live at once. Model each period as its own entity (for example an :employment entity with :employment/salary), or keep the latest period current and read earlier ones with :as-of.
;; Rejected: two windows for [:alice :salary 100000] in one transact
(transact [[:alice :salary 100000 {:valid-from "2020-01-01" :valid-to "2022-01-01"}]
           [:alice :salary 100000 {:valid-from "2024-01-01"}]])

;; Accepted: close the open window in a later transaction
(transact {:valid-from "2020-01-01"} [[:alice :salary 100000]])
(transact {:valid-from "2020-01-01" :valid-to "2022-01-01"} [[:alice :salary 100000]])

Scenario: A batch import writes the same fact once per period it was true, all in one transaction.

API-012 Non-query command passed to query()#

Error text: only (query ...) commands can be opened as a cursor; got {}

Cause: db.query() returns a Cursor over the rows of a query. It was given a transact, retract or rule command, which has no rows. The {} names the command. Nothing is written or registered.

Resolution:

  • Run writes and rule definitions with db.execute() (or inside a WriteTransaction), and open cursors only for (query ...) commands.
db.execute(r#"(transact [[:alice :person/name "Alice"]])"#)?;
let mut cursor = db.query("(query [:find ?name :where [?e :person/name ?name]])")?;
while let Some(batch) = cursor.next_batch(1000)? {
    for row in batch.rows() { /* ... */ }
}

Scenario: Code that dispatches every command string through one function switches from execute() to query() for all of them.

API-013 Checkpoint while a fact log is open#

Deprecated in v3.0.0. No longer emitted: a fact log pins the committed generation it opened on, and checkpoints run while it is open without reusing the pages it reads. Kept for reference; this code will not be reused.

Error text: checkpoint deferred while {} fact log(s) are open; close them and checkpoint again

Cause: db.fact_log() returns a FactLog that reads the committed pages as they were when it opened. A checkpoint frees pages that a later checkpoint reuses, so while any fact log is open, checkpoints are deferred. Writes still succeed and stay in the WAL, and automatic checkpoints wait. checkpoint() or rebuild_indexes() with uncheckpointed writes, or rebuild_indexes() on a file database, returns this error. The {} is the number of open logs. Nothing is written.

Resolution:

  • Finish reading, or call close() on the log (dropping it is the same), then checkpoint again.
  • Keep fact logs short-lived on a database that takes writes, because the WAL grows until they close.
let mut log = db.fact_log(&FactFilter::new())?;
while let Some(batch) = log.next_batch(1000)? { /* ... */ }
log.close();
db.checkpoint()?;

Scenario: A backup job streams the fact log on a thread while the application calls checkpoint() on a timer.

API-014 Write on a read-only handle#

Error text: database is open read-only; {} is not allowed

Cause: The database was opened with OpenOptions::read_only, and the call would write to the file or its WAL. The {} names the call: transact, retract, begin_write, checkpoint or rebuild_indexes. Nothing is written and no transaction number is used.

Resolution:

  • Open the database without read_only to write. A read-write open waits for no one: it fails with STG-025 or STG-026 while any read-only handle holds the file, so close those first.
  • Queries, cursors, fact_log(), verify() and rule registration work on a read-only handle.
let src = Minigraf::open_with_options("old.graph", OpenOptions::new().read_only(true))?;
let mut log = src.fact_log(&FactFilter::new())?;
// ... copy the records elsewhere; src.execute("(transact ...)") would be API-014

Scenario: An offline migration tool opens its source read-only and, by mistake, runs a cleanup retract against it instead of against the destination.

API-015 Log writer record out of transaction order#

Error text: tx_count {} is out of order: the log writer is at {}, and a record must open a later transaction or join the open one

Cause: LogWriter::append received a record whose tx_count is 0, lower than the writer's current tx_count, or equal to it after that transaction was closed (by advance_tx_count, or by a record of a later transaction). The same code is returned by advance_tx_count with a value below the writer's. Records must come in non-decreasing tx_count order, each transaction's records together. The record is not written and the writer stays usable.

Resolution:

  • Read the source with fact_log() in the default FactOrder::Tx, which returns records in non-decreasing tx_count with each transaction's records together. FactOrder::Storage does not, so sort its records by tx_count first.
  • Gaps are allowed: skip a transaction's records to purge it.
  • Call advance_tx_count only after the last record, or with a value above every record still to come.

Scenario: A transform step merges two sources and appends their records one source after the other.

API-016 Log writer record with a second tx_id for one transaction#

Error text: transaction {} has tx_id {}; a record with tx_id {} cannot join it

Cause: LogWriter::append received a record with the open transaction's tx_count but a different tx_id. A transaction has one wall-clock time, which :as-of with a timestamp compares against. The record is not written and the writer stays usable.

Resolution:

  • Keep each record's tx_id as the source gave it. If a transform rewrites timestamps, give every record of one transaction the same new tx_id.

Scenario: A transform sets tx_id from a per-record field instead of from the transaction.

API-017 Invalid argument passed through a language binding#

Error text: invalid argument: {}

Cause: A language binding (Python, Java, Swift, Node.js, C and the others) received an argument it could not convert to the Rust type, such as an entity id or Ref value that is not a UUID string, or a negative or out-of-range number. The {} names the argument and the problem. The Rust API takes typed arguments and never returns this code. Nothing was changed.

Resolution:

  • Pass entity ids and Ref values as the UUID strings that fact_log records and query results carry.
  • Check the binding's documentation for the argument's type and range.

Scenario: A migration script builds a FactRecord with entity="alice" instead of the entity's UUID.

API-018 Call on a closed binding object#

Error text: {} is closed

Cause: A language binding object was used after it was closed or finished, for example append or finish on a log writer after finish or close, or execute or commit on a write transaction after it committed (or failed to), rolled back, or its database was closed (#824). A finished transaction's rollback does nothing instead. Rust consumes these objects, so the Rust API never returns this code. Bindings cannot consume an object a caller still holds, so they return this error instead. A cursor or fact log reports the end (no more batches) after close, not this error. The {} names the object.

BrowserDb.close() in every mode also closes its cursors, prepared queries and transactions logically, even while those objects are still referenced. A successful OPFS importGraph() invalidates earlier cursors and prepared queries. A failure at import publication closes the OPFS database itself. Disposal (free(), cursor close(), transaction rollback(), repeated database close()) remains permitted. API-018 takes precedence over busy (API-027) and an open transaction (INT-001).

Resolution:

  • Create a new object instead of reusing a finished one.
  • In Python, use the writer as a context manager so it is finished once, on exit.

Scenario: A loader calls finish() in a finally block after it already called it on success.

API-019 Empty or inverted valid-time window#

Error text: the valid-time window of {} ends at or before it starts; :valid-to must be later than :valid-from (the transaction time when :valid-from is omitted)

Cause: A transact gives a fact a valid-time window whose end is at or before its start, so the fact could never match a :valid-at query. The check uses the effective window, after defaults: the fact's own bound, else the transaction's, else :valid-from is the transaction time and :valid-to is forever. A :valid-to in the past with no :valid-from is therefore rejected too. The whole transaction is rejected, nothing is written and no transaction number is used. The {} is the attribute. Inside a WriteTransaction, tx.execute() checks each statement. commit() checks again with the commit time, so a :valid-to that passed while staging can still fail at commit. LogWriter::append rejects such a record the same way; that record alone is rejected. Files written before this check are read as they are.

Resolution:

  • Give :valid-to a later instant than :valid-from.
  • To record a fact that is no longer true, give it a :valid-from before its :valid-to, or retract it.
  • Check that a per-fact :valid-from/:valid-to does not invert the transaction-level window it overrides.
;; Rejected: ends before it starts, and an empty window
(transact {:valid-from "2026-08-21" :valid-to "2026-08-20"} [[:d/c :description "r"]])
(transact {:valid-from "2026-08-21" :valid-to "2026-08-21"} [[:d/c :description "r"]])
;; Rejected: valid-from defaults to now, which is after valid-to
(transact {:valid-to "2020-01-01"} [[:d/c :description "r"]])

;; Accepted
(transact {:valid-from "2019-01-01" :valid-to "2020-01-01"} [[:d/c :description "r"]])

Scenario: An import sets :valid-to from a source's end date but leaves out :valid-from, so past end dates produce windows that end before the transaction time.

API-020 Assertion and retraction of one fact in one log-writer transaction#

Error text: one transaction both asserts and retracts the same value of {}; keep only the record that decides it

Cause: LogWriter::append was given a record that asserts an entity, attribute and value the open transaction retracts, or retracts one it asserts. Records of one transaction carry one tx_id and have no order, so the pair does not say which write came last. A normal write never produces such a transaction: in a WriteTransaction the last statement that writes a fact decides it (#477). The record alone is rejected, and the writer stays usable. The {} is the attribute. A source written by Minigraf 2.x, or by v3 builds before #477, can hold such transactions; copying one fails at the first such record.

Resolution:

  • Keep only the record that decides the fact. Readers of the source hide the fact when its newest transaction holds a retraction, so dropping the transaction's assertions of that fact keeps every query result the same.
  • Repair the source's other old records the same way before appending them: a fact with two windows in one transaction (API-011) keeps the window it should have, and an assertion whose window ends before it starts (API-019) is dropped.

Scenario: An offline purge copies a database migrated from v2.x through fact_log() and LogWriter, and one of its transactions retracted and re-asserted a fact.

API-021 Set value holds a set#

Error text: a set cannot hold a set; its elements must be strings, numbers, booleans, refs, keywords or nil

Cause: ValueSet::new was given a Value::Set among its elements. Sets hold scalar values only (#316).

Resolution:

  • Build the set from scalar values. To relate several sets, store each one as its own attribute value.

Example:

let inner = Value::Set(ValueSet::default());
ValueSet::new(vec![inner]) // API-021

API-022 Missing bind value for slot#

Error text: missing bind value for slot '${}'

Cause: A prepared query was executed (PreparedQuery::execute or query, or a binding's prepared handle) without a bind value for one of its $slots. The {} names the slot. Nothing was read. Before v3.0.0 this was INT-033.

Resolution:

  • Pass a bind value for every $slot in the query. Bindings for names the query does not use are ignored, so a misspelt name shows up as this error.

Scenario: A query is prepared with $min-age and executed with a binding named min_age.

API-023 Bind slot not permitted in attribute position#

Error text: bind slot '${}' is not permitted in attribute position; the query optimizer selects an index based on the attribute at prepare time and cannot handle a parameterised attribute

Cause: prepare was given a query with a $slot as the attribute of a pattern, at the top level or inside not, not-join, or or or-join. The plan depends on the attribute, so it cannot be a parameter. Before v3.0.0 this was INT-034.

Resolution:

  • Write the attribute as a keyword. Use bind slots for entities, values, expressions, rule arguments, :as-of and :valid-at.
  • To choose between a few attributes at run time, prepare one query per attribute.

Scenario: A search screen prepares [?e $field ?v] to search whichever field the user picked.

API-024 Bind slot type mismatch#

Error text: slot '${}' in {} position requires {}, got {}

Cause: A bind value was of the wrong kind for the position of its slot: an entity position takes Entity or Val(Ref); a value, expression or rule-argument position takes Val or Entity; :as-of takes TxCount or Timestamp; :valid-at takes Timestamp or AnyValidTime. The message names the slot, its position, the kinds it takes and the kind it got. Before v3.0.0 this was INT-035.

Resolution:

  • Pass the kind the position takes. TxCount and Timestamp are only for :as-of/:valid-at; a number compared in a pattern or expression is a Val.

Scenario: :as-of $tx is bound to Val(Integer(5)) instead of TxCount(5).

API-025 Query option override not allowed#

Error text: query option {} is not allowed on this database; OpenOptions::allow_overrides does not list Overridable::{}

Cause: The query used a keyword that overrides one of the database's settings, such as :max-derived-facts or :max-results, and the embedder's OpenOptions::allow_overrides list leaves that keyword out. The query is refused before it runs, by execute, query, prepare and WriteTransaction::execute; a refused statement in a WriteTransaction leaves the transaction usable. When a query uses several refused keywords, the message names the first in the order :max-derived-facts, :max-results. The list is not stored in the file: each open sets it, and the default (Overridable::DEFAULTS) allows both keywords.

Resolution:

  • Remove the keyword from the query and rely on the database's own setting.
  • Or, if the embedder means to let queries override it, add the Overridable variant to OpenOptions::allow_overrides. The list replaces the defaults; chain Overridable::DEFAULTS to add to them.

Scenario: An application opens its database with OpenOptions::new().allow_overrides([]) so that query text from its users cannot raise max_derived_facts; a user query ending in :max-derived-facts 100000000 is refused with API-025.


API-026 OPFS mode is not available here#

Error text: OPFS mode is not available here: {}

Cause: BrowserDb.openOpfs(name) requires a secure context and a dedicated Web Worker with OPFS and sync access handles. It is unavailable on the main thread, in shared/service workers, when the APIs are absent, or when the browser denies access to the origin directory (for example SecurityError). It never falls back to IndexedDB.

Resolution:

  • Run the call in a dedicated worker served over HTTPS or localhost.
  • Check browser support and origin access policy. Choose BrowserDb.open(name) explicitly if IndexedDB suits the application.

Scenario: A page calls BrowserDb.openOpfs('memory') on its main thread.

API-027 Database is busy#

Error text: the database is busy: {}

Cause: A call starts work while an OPFS import is in progress, or BrowserDb.close() is called reentrantly while a database operation is running. Busy calls change nothing. Closed objects (API-018) take precedence over busy; busy takes precedence over an open transaction (INT-001). Disposal operations remain permitted.

Resolution:

  • Await importGraph() before making other calls, including close() or another import.
  • Call close() after the current operation returns, rather than inside its UDF.

Scenario: A worker calls query() while importGraph() is awaiting staging I/O.


INT — Internal Errors#

Internal errors are invariant violations or edge cases that are not expected to occur through normal use of the public API, or (for a handful of codes inherited from before every call site was audited — see #277) genuine user-reachable mistakes that were never given a category-specific PRS-/ QRY-/API- code of their own. If you see one of these in practice and cannot explain it from your own input, it likely indicates a bug in Minigraf itself; please file an issue with the full error message and the input that triggered it.

Many INT- codes below are intentionally shared by several call sites in the same subsystem (mirroring how, e.g., QRY-005/QRY-006 already wrap an arbitrary underlying failure) — the {} placeholder in the "Error text" carries the specific underlying detail. This keeps the registry a manageable size while still giving every call site a real, matchable code instead of falling through to the generic INT-000 fallback.

INT-000 Unclassified internal error#

Error text: unclassified internal error: {}

Cause: A raw, non-anyhow error (e.g. io::Error, a panic caught at a FFI boundary) reached the public API boundary with no CodedError anywhere in its anyhow::Error chain. As of #277 every bail!/anyhow! call site in the crate has been migrated to a specific code, so this should now be rare.

Resolution:

  • Read the wrapped message text (the {} above) for the underlying cause.
  • If you see this in practice, please file an issue — it likely means a new call site was added without going through bail_coded!/err_coded!.

Scenario: An I/O error from the underlying filesystem propagates through ? without ever being wrapped in a CodedError.

INT-001 Write transaction already in progress on this thread#

Error text: a write transaction is already in progress on this thread; use tx.execute() instead

Cause: on the same thread that already holds an active WriteTransaction, one of these was called: the Minigraf methods execute(), query(), fact_log(), begin_write(), begin_write_owned(), checkpoint(), verify(), rebuild_indexes() or prepare(), or a PreparedQuery's execute() or query(). Acquiring the write lock again on that thread would deadlock, so this is detected and rejected instead. (Before v3.0.0, checkpoint(), verify() and rebuild_indexes() did not check and deadlocked, #734.)

The same calls are refused on the thread that began an open OwnedWriteTransaction of that database (#824), whichever thread uses the transaction meanwhile, and on the thread running one of its statements (a user function calling back into the database); other threads' writes and begins wait for it instead, and other databases are not affected. A binding transaction is an owned one, so the same rule applies to every language binding. In the browser, every BrowserDb call that reads or writes (execute, query, prepare, checkpoint, importGraph, a second beginWrite, and a prepared query's execute/query) is refused while a BrowserWriteTransaction is open, since other asynchronous code could otherwise mistake the database for the transaction.

Resolution:

  • Use the existing transaction's tx.execute() for further writes instead of calling db.execute() again on the same thread.
  • End the transaction (commit() or rollback()) before using the database directly again.

Scenario: Code inside a WriteTransaction write closure calls db.execute("(transact ...)") on the outer db handle instead of tx.execute(...).

INT-002 Invalid entity (API layer)#

Error text: invalid entity: {}

Cause: Minigraf::materialize_transaction/materialize_retraction (the API-layer write path used by db.execute() and WriteTransaction) could not resolve an entity ID in a fact. This mirrors QRY-001 but fires at the API layer's own materialization step, which runs before the WAL write for correct WAL-first ordering.

Resolution:

  • Ensure entity IDs are UUIDs (#uuid "..." tagged literals) or values resolvable to a UUID.

INT-003 Invalid value (API layer)#

Error text: invalid value: {}

Cause: Minigraf::materialize_transaction/materialize_retraction found a fact value of a type Minigraf cannot store. This mirrors QRY-004 but fires at the API layer's own materialization step.

Resolution:

  • Use only supported value types: string, integer, float, boolean, UUID ref, or keyword.

INT-004 Invalid timestamp#

Error text: invalid timestamp: {}

Cause: parse_timestamp (used for :as-of, :valid-at, :valid-from, and :valid-to date strings) rejected the input — either a timezone offset was present (only UTC Z timestamps are supported, to avoid chrono's local timezone handling, GHSA-wcg3-cvx6-7396), or the string did not parse as an RFC 3339 datetime or YYYY-MM-DD date.

Resolution:

  • Use a UTC timestamp like "2024-01-15T10:00:00Z" or a bare date like "2024-01-15". Do not include a timezone offset such as +05:30.

INT-005 Millisecond value outside supported datetime range#

Error text: millisecond value {} is outside the supported datetime range

Cause: millis_to_timestamp_string was given a millisecond value outside the range chrono can represent as a UTC datetime. i64::MAX (VALID_TIME_FOREVER) must never be passed to this function directly — callers should check for the sentinel before formatting.

Resolution:

  • Check for VALID_TIME_FOREVER before formatting a valid_to value.

INT-006 Internal parser error: expected token#

Error text: internal parser error: expected {} token

Cause: The Datalog/EDN parser's second pass expected a specific lexer-token kind (keyword, symbol, string, integer, float, boolean, tagged literal, or bind slot) at a position the first pass had already validated would hold that kind. This indicates the parser's two passes have gone out of sync — a bug in Minigraf, not a user mistake.

Resolution:

  • File a bug report with the exact input string that triggered this error.

INT-007 Float literal out of range#

Error text: Float literal out of range: {}

Cause: A numeric literal in the input parsed as a float token but overflowed Rust's f64 range during conversion.

Resolution:

  • Use a value within f64's representable range.

INT-008 Integer literal out of range#

Error text: Integer literal out of range: {}

Cause: A numeric literal in the input parsed as an integer token but overflowed Rust's i64 range during conversion.

Resolution:

  • Use a value within i64's representable range (roughly ±9.2×10¹⁸).

INT-009 Symbol exceeds maximum length#

Error text: Symbol exceeds maximum length of {} bytes

Cause: A Datalog symbol (variable name, predicate name, etc.) exceeded the parser's maximum symbol length.

Resolution:

  • Shorten the symbol name.

INT-010 Exceeded maximum recursion depth#

Error text: Exceeded maximum recursion depth of {}

Cause: The input's nested list/vector structure exceeded the parser's maximum recursion depth — a guard against stack overflow on deeply nested or adversarial input.

Resolution:

  • Flatten the query structure; deeply nested (and ...)/(or ...) forms are rarely necessary.

INT-011 Unexpected end of clause#

Error text: unexpected end of {}

Cause: The parser reached the end of the input while still expecting more elements inside a clause (e.g. :over, a query vector, an expression clause, not/not-join/or/or-join, a rule invocation, or and). The {} names which clause was left incomplete.

Resolution:

  • Check the input for a missing closing ]/) or a truncated clause.

INT-012 Duplicate query option#

Error text: duplicate {}

Cause: A query specified :max-derived-facts, :max-results, :query-memory-limit, :max-iterations, :limit, :offset, :order-by or :distinct more than once.

Resolution:

  • Specify each query option at most once.

INT-013 Query option requires a value#

Error text: {} requires a value

Cause: A query option keyword (:max-derived-facts, :max-results, :query-memory-limit or :max-iterations) was present with no following value.

Resolution:

  • Supply an integer value or a $slot after the option keyword.

INT-014 Query option must be >= 1#

Error text: {} must be >= 1

Cause: :max-derived-facts, :max-results or :max-iterations (#861) was given a value less than 1, as a literal or as a prepared query's bind value.

Resolution:

  • Use a value of 1 or greater.

INT-015 Query option must be a non-negative integer#

Error text: {} must be a non-negative integer

Cause: :max-derived-facts, :max-results or :max-iterations was given a non-integer value, or :query-memory-limit was given a negative or non-integer value, as a literal or as a prepared query's bind value. (Before #870 the text said "positive integer".)

Resolution:

  • Supply an integer literal or a $slot: at least 1 for :max-derived-facts, :max-results and :max-iterations, at least 0 for :query-memory-limit.

INT-016 (or)/(or-join) nested inside (not)/(not-join)#

Error text: (or)/(or-join) cannot appear inside (not)/(not-join)

Cause: A (not ...) or (not-join ...) clause's body contained a nested (or ...)/(or-join ...), which is not supported.

Resolution:

  • Restructure the query to avoid nesting or/or-join inside negation.

INT-017 Pseudo-attribute not valid in this position#

Error text: pseudo-attribute {} is not valid in {} position

Cause: A pseudo-attribute (e.g. :db/valid-from) was used in the entity or value position of a pattern, where only real attributes and plain values are permitted.

Resolution:

  • Use pseudo-attributes only in the attribute position of a pattern.

INT-018 Variable not bound by any outer/earlier clause#

Error text: {} {} in {} is not bound by any {} clause

Cause: A variable referenced inside (not ...), (not-join ...), an expression clause, or (or-join ...) was never bound by an outer or earlier clause in the query.

Resolution:

  • Ensure every variable used inside negation, expressions, or or-join also appears in a preceding pattern that binds it.

INT-019 Datalog parser internal error#

Error text: datalog parser: {}

Cause: An invariant inside the parser does not hold. No input is known to reach it; if you see it, please report it with the input.

Before v3.0.0 this code was also the parser's catch-all for long-tail syntax and structural errors. From v3.0.0 those carry their own codes: PRS-083 to PRS-107 (PRS-090 replaced INT-000 for the retract arity). Code that matches on INT-019 for those errors must match the new codes.

Resolution:

  • Report the input that raised it as a bug.

INT-020 Evaluator iteration/derived-fact limit exceeded#

Error text: evaluator: iteration or derived-fact limit exceeded: {}

Cause: A stratum of the query's rules was still deriving new facts after its round limit (OpenOptions::max_iterations or :max-iterations, default 1,000,000, counted per stratum; 1,000 and fixed before v3.0.0, #861), or its rules derived more facts in total than max_derived_facts allows (OpenOptions::max_derived_facts or :max-derived-facts, default 1,000,000; the database's own facts do not count) — guards against infinite recursion/cycles or runaway-generating rules. max_results / :max-results are deprecated aliases of that limit; when both are given, the lower applies. Neither limits the rows a query returns.

Before v3.0.0, max_derived_facts limited the facts derived in one iteration, max_results limited the total, and the text read iteration or result limit exceeded. From v3.0.0 there is one limit, on the total (#553).

Resolution:

  • Check the rule for an unintended cycle (e.g. (ancestor ?x ?y) [?x :parent ?y] combined with a cyclic :parent graph). Raise max_derived_facts (or :max-derived-facts on the query), or for the round message max_iterations (or :max-iterations), if the workload is legitimately large. Before #861 the round message read Possible infinite recursion or cycle in rules.

INT-021 Evaluator: unsupported where-clause in evaluate_rule#

Error text: evaluator: unsupported where-clause in evaluate_rule: {}

Cause: A rule body contained a not, not-join, or, or or-join clause, but was evaluated through the non-stratified RecursiveEvaluator instead of StratifiedEvaluator, which is required for rules with negation/disjunction. This indicates an internal dispatch bug — the executor should route negation-containing rules to the stratified evaluator.

Resolution:

  • File a bug report with the rule definition that triggered this error.

INT-022 Datalog evaluator internal error#

Error text: datalog evaluator: {}

Cause: A shared catch-all for the recursive rule evaluator's remaining internal invariant checks around rule invocation/head parsing (e.g. a rule invocation or head with an unexpected shape, an unbound variable in a rule head, or a window-function row-index bound check). These conditions should already be rejected by the parser and are not expected to reach the evaluator through normal use.

Resolution:

  • File a bug report with the rule/query that triggered this error.

INT-023 Packed page: fact exceeds slot capacity#

Error text: packed page: fact record exceeds slot capacity: {}

Cause: A fact's postcard-encoded size exceeds the maximum a packed fact page slot can hold.

Resolution:

  • Store large payloads externally and reference them with a Value::String URL/path or Value::Ref entity ID, the same guidance as WAL-003.

INT-024 Packed page: malformed page data#

Error text: packed page: malformed page data: {}

Cause: A shared catch-all for packed-fact-page invariant violations — a page shorter than expected, a directory entry or record slice out of bounds, or an offset/length computation that would overflow. These indicate on-disk corruption or a bug in the packed-page encoder, not a user mistake.

Resolution:

  • If this occurs on a database file that was not modified outside Minigraf, please file a bug report with the file (or a minimal reproduction) attached.

INT-025 Unsubstituted :valid-at bind slot reached executor#

Error text: internal: unsubstituted :valid-at bind slot reached the executor

Cause: A prepared query's :valid-at clause still contained an unresolved $slot bind placeholder when it reached the query executor. PreparedQuery::execute is expected to substitute all bind slots before handing the query to the executor.

Resolution:

  • File a bug report — this indicates a gap in PreparedQuery's bind-slot substitution.

INT-026 Temporal pseudo-attributes require :any-valid-time#

Error text: temporal pseudo-attributes :db/valid-from, :db/valid-to, :db/tx-count, and :db/tx-id require :any-valid-time; add :any-valid-time to your query

Cause: A query referenced a temporal pseudo-attribute (:db/valid-from, :db/valid-to, :db/tx-count, :db/tx-id) without also specifying :valid-at :any-valid-time. These pseudo-attributes expose per-fact temporal metadata that only makes sense when the query is not filtering to a single point in valid time.

Resolution:

  • Add :valid-at :any-valid-time to the query.

INT-027 Query has no :where clause, rules, or aggregates#

Error text: query has no :where clause, rules, or aggregates — nothing binds the variables. Add a :where clause (e.g., [:find ?e ?a ?v :where [?e ?a ?v]]) or use an aggregate.

Cause: A (query ...) command's :find variables have nothing to bind them — no :where clause, no rule invocation, and no aggregate.

Resolution:

  • Add a :where clause that binds every variable in :find.

INT-028 Rule invocation argument count mismatch#

Error text: Rule invocation '{}' must have 1 or 2 arguments, got {}

Cause: A rule was invoked with an argument count other than 1 (entity only) or 2 (entity and value). Minigraf's rule invocations only support these two arities.

Resolution:

  • Invoke the rule with 1 or 2 arguments, matching its definition.

INT-029 Unknown aggregate function#

Error text: unknown aggregate function: '{}'

Cause: A :find or :with clause referenced an aggregate function name that is neither a built-in (count, count-distinct, sum, sum-distinct, avg, min, max) nor a user-defined function registered via db.register_aggregate().

Resolution:

  • Check the function name for typos, or register it first with db.register_aggregate().

Since v3.0.0, :find aggregates are resolved before the query runs and an unknown name is reported as QRY-010. INT-029 now only signals an internal inconsistency (a name that passed that check but is missing at aggregation).

INT-030 Unknown window function#

Error text: unknown window function '{}' — register it with register_aggregate() before querying

Cause: An :over (window) clause referenced a function name that is not a recognized window-compatible built-in and has not been registered.

Resolution:

  • Register the function with db.register_aggregate() before using it in an :over clause.

Since v3.0.0, window functions are resolved before the query runs and an unknown name is reported as QRY-011. INT-030 now only signals an internal inconsistency (a name that passed that check but is missing at evaluation).

INT-031 or-join variable not bound in incoming scope#

Error text: or-join variable {} is not bound in the incoming scope

Cause: An (or-join [vars] ...) clause's declared join variable was not actually bound in the scope the or-join was evaluated in.

Resolution:

  • Ensure every variable listed in or-join's join-vars vector is bound by a clause preceding it in the query.

INT-032 Query executor internal error#

Error text: query executor: {}

Cause: A shared catch-all for a handful of query executor invariant checks that are not expected to be user-reachable (an empty rule head reaching execution, a rule head not starting with a predicate symbol, or a window function's row-number position overflowing).

Resolution:

  • File a bug report with the query that triggered this error.

INT-033 Missing bind value for slot#

Error text: missing bind value for slot '${}'

Cause: Deprecated since v3.0.0, and no longer emitted: the same mistake is API-022. PreparedQuery::execute() was called without supplying a bind value for every $slot the prepared query declared.

Resolution:

  • Supply a BindValue for every named slot before calling execute().

INT-034 Bind slot not permitted in attribute position#

Error text: bind slot '${}' is not permitted in attribute position; the query optimizer selects an index based on the attribute at prepare time and cannot handle a parameterised attribute

Cause: Deprecated since v3.0.0, and no longer emitted: the same mistake is API-023. A $slot bind placeholder appeared in the attribute position of a pattern in a prepared query. The query optimizer picks an index (EAVT, AEVT, AVET, VAET) based on the attribute at prepare() time, which is not possible if the attribute itself is a runtime-bound parameter.

Resolution:

  • Use a literal attribute keyword in patterns; reserve bind slots for the entity or value position.

INT-035 Bind slot type mismatch#

Error text: slot '${}' in {} position requires {}, got {}

Cause: Deprecated since v3.0.0, and no longer emitted: the same mistake is API-024. A bind value supplied to PreparedQuery::execute() was of the wrong BindValue variant for the position its slot appears in (entity position requires Entity, value/expression position requires Val, :as-of position requires TxCount or Timestamp, :valid-at position requires Timestamp or AnyValidTime).

Resolution:

  • Supply a BindValue of the variant the slot's position requires.

INT-036 Header too short: need N..M bytes#

Error text: header too short: need {}..{}, got {} bytes

Cause: A file-header field read (a 4-byte or 8-byte fixed-width field) extended past the end of the available header bytes.

Resolution:

  • The file is likely truncated or corrupted. Restore from a backup.

INT-037 Header slice not the exact expected byte length#

Error text: header: slice at {} not exactly {} bytes

Cause: An internal invariant check found a header field slice that was not exactly the expected width (4 or 8 bytes) after a bounds check that should have guaranteed it. Indicates a bug in the header-parsing slicing logic.

Resolution:

  • File a bug report with the file header bytes attached.

INT-038 Header too short for a specific field#

Error text: header too short for {}

Cause: The v7 header parser ran out of bytes while reading a specific field (the magic bytes, fact_page_format, or one of the reserved padding bytes).

Resolution:

  • The file is likely truncated or corrupted. Restore from a backup.

INT-039 Invalid magic number#

Error text: Invalid magic number

Cause: A legacy-format header parsing path found a magic number that does not match "MGRF". This mirrors STG-002 but fires on a different internal parsing path.

Resolution:

  • The file is not a Minigraf .graph file, or is corrupted.

INT-040 Function/predicate name already registered#

Error text: {} '{}' is already registered

Cause: db.register_aggregate() or db.register_predicate() was called with a name that is already registered — either a built-in or a previously registered user-defined function.

Resolution:

  • Choose a unique name, or only register the function once.

INT-041 sum: unsupported value type#

Error text: sum: expected Integer, Float, or Null, got {}

Deprecated in v3.0.0 (#789). Ordinary sum and sum-distinct skip nil and all nonnumeric values. An existing group without numbers returns Integer(0); a query with no matching rows returns no rows. This code and its message remain reserved for compatibility; these built-in paths no longer emit it. In v2, the type restriction still applies.

INT-042 min/max: no non-null values in group#

Error text: min/max: no non-null values in group

Behavior: An ordinary min/max group containing only nil values has no extremum and is omitted. On v3 this is an internal group-drop condition, not an error returned by the query. A window instead emits nil for each affected source row. Queries with no matching rows do not create a min/max group. The code and message remain reserved; #789 preserves this behavior.

INT-043 Cannot compare values of different types#

Error text: {}: cannot compare {} and {} values

Deprecated in v3.0.0 (#789). Ordinary min/max accept mixed types, including Integer/Float, using the same total value order as their window forms. This code and its message remain reserved for compatibility; these built-in paths no longer emit it. In v2, the type restriction still applies.

INT-044 Aggregate: unsupported value type#

Error text: {}: expected Integer, Float, String, or Null, got {}

Deprecated in v3.0.0 (#789). Ordinary min/max accept every non-nil Value variant, including Boolean, Ref, Keyword and Set. They use the window total order. This code and its message remain reserved for compatibility; these built-in paths no longer emit it. In v2, the type restriction still applies.

INT-045 Pending fact index out of bounds#

Error text: pending fact index {} out of bounds

Cause: A FactRef pointed at a pending (not-yet-committed) fact slot index that no longer exists in the pending fact buffer.

Resolution:

  • File a bug report — this indicates a lifecycle bug between fact materialization and lookup.

INT-046 Missing CommittedFactReader for a committed FactRef#

Error text: no CommittedFactReader but got committed FactRef (page_id={})

Cause: A FactRef pointing at a committed (on-disk) fact was resolved without a CommittedFactReader configured to read it.

Resolution:

  • File a bug report — this indicates the storage backend was constructed without the reader it needs for the facts it is indexing.

INT-047 into_backend: backend Arc has multiple owners#

Error text: into_backend: backend Arc has multiple owners

Cause: PersistentFactStorage::into_backend() requires exclusive ownership of its internal Arc<Mutex<Backend>> to unwrap it, but another clone of the Arc was still alive when it was called.

Resolution:

  • Ensure no other handle (e.g. a second Minigraf clone) is holding a reference to the same backend when converting it back into a raw backend.

INT-048 Storage: arithmetic overflow#

Error text: storage: arithmetic overflow: {}

Cause: A shared catch-all for arithmetic-overflow guards throughout the storage layer (B+tree page/entry-length computations, page-count/page-id arithmetic, packed-page offset arithmetic) — a checked or saturating_* computation would have overflowed its target integer width. Only reachable on databases far larger than any realistic deployment.

Resolution:

  • File a bug report if this occurs on a database of reasonable size — it likely indicates a corrupt page count or index in the file header.

INT-049 Storage: internal invariant violation#

Error text: storage: internal invariant violation: {}

Cause: A shared catch-all for storage-layer invariant violations — malformed or corrupted B+tree/packed-fact page bytes, an out-of-bounds page/entry index, an unexpected page type where a specific type was required, or an "impossible" empty internal structure (e.g. BUG: cur_first_key empty when writing leaf page). These indicate either on-disk corruption or a bug in Minigraf's B+tree/page-encoding logic.

Resolution:

  • If this occurs on a database file that was not modified outside Minigraf, please file a bug report with the file (or a minimal reproduction) attached.

INT-050 Internal lock poisoned#

Error text: {} lock poisoned

Cause: One of Minigraf's internal Mutex/RwLock guards (the shared fact-storage data lock, the page cache lock, the in-memory backend's page table lock, or the on-disk MutexStorageBackend's lock) was poisoned by a previous operation panicking while holding it.

Resolution:

  • Restart the process. If panics recur, investigate the root cause before retrying — a poisoned lock is permanent for the life of the process.

INT-051 Invalid page size#

Error text: Invalid page size: {} bytes (expected {})

Cause: A page passed to a storage backend's write_page was not exactly PAGE_SIZE (4096) bytes.

Resolution:

  • This is an internal contract violation between the storage layer and its backend, not a user mistake. File a bug report.

INT-052 Page not found#

Error text: Page {} not found

Cause: A storage backend was asked to read a page ID that does not exist in its page table (in-memory or browser IndexedDB-backed backends).

Resolution:

  • File a bug report — this indicates a page was referenced (e.g. by a B+tree pointer) without having first been written.

INT-053 Header checksum mismatch: possible file corruption#

Error text: Header checksum mismatch: possible file corruption. Database may be damaged.

Cause: The v7 file header's stored checksum does not match a freshly computed checksum of the header bytes — the header was modified outside Minigraf, corrupted by a partial write, or damaged by the underlying storage medium.

Resolution:

  • Restore the database file from a backup. If the file was open at the time of a crash, check for a .wal sidecar next to it — replaying it on the last-known-good copy may recover recent writes.

INT-054 Unstratifiable negative recursion cycle#

Error text: unstratifiable: predicate '{}' is involved in a negative cycle through '{}'

Cause: A set of rules contains a predicate that depends negatively (through not/not-join) on itself, directly or transitively — this has no well-defined semantics under stratified negation and cannot be evaluated.

Resolution:

  • Restructure the rules so that no predicate's definition negatively depends on itself, even indirectly through other rules.

INT-055 Rule predicate disappeared during rollback#

Error text: rule predicate '{}' disappeared during rollback

Cause: WriteTransaction::rollback() (or an implicit rollback on drop) attempted to remove a rule that had been staged for registration in this transaction, but the rule registry no longer contained it.

Resolution:

  • File a bug report — this indicates a lifecycle bug in WriteTransaction's rule-staging/rollback logic.

INT-056 Write to a read-only storage backend#

Error text: write to a read-only storage backend: {}

Cause: A page write or sync reached the file backend of a handle opened with OpenOptions::read_only. The public API refuses every write on such a handle first (API-014), so this is a missed check, not a usage error. The {} is the page or sync. Nothing was written.

Resolution:

  • File a bug report with the call that returned it.
How this page was assembled

This page is 287 fragments. Minigraf picked them from docs.graph with this query, where the version is a point on the valid-time axis:

(query [:find ?order ?blob ?added :valid-at "2003-01-01T00:00:00Z" :where [?f :frag/page "error-reference"] [?f :frag/order ?order] [?f :frag/blob ?blob] [?f :frag/added-in ?added]])

Run it in the query console