Native API

Plan IR and the executor

The plan data structure that both JSON filters and SQL compile to, how the batched executor runs it, and the ordering rules used by ORDER BY.

The raftdb-exec crate depends only on raftdb-doc and forbids unsafe code. A filter, in JSON or SQL, becomes a Plan: plain data that can be cached, compared and printed.

Structure#

Plan { nodes: Vec<Node>, root: u32 }
Node = True
     | Cmp { path, op: Eq|Lt|Le|Gt|Ge, lit }
     | In { path, lits } | Exists { path, yes }
     | And(a, b) | Or(a, b) | Not(a)            (children are indexes into nodes)
Path { first: u32, rest: [u32] }                (dictionary ids; rest = nested fields)
Lit  = Null | Bool | Int | F64 | Str

A path holds dictionary ids, not names: documents do not store field names (Documents and schemas). Compiling needs the table's field-name dictionary. $ne, $nin and $not become Not nodes over Cmp, In or Exists.

Example#

The filter {"age":{"$gt":30},"active":true} is two leaves under an And: Cmp{path: age, op: Gt, lit: Int 30} and Cmp{path: active, op: Eq, lit: Bool true}.

Execution#

Documents are processed 1,024 at a time. A mask has one bit per document. A leaf visits only the candidate bits (a word of 64 with no candidates is skipped). And(a,b) evaluates b on the survivors of a; Or(a,b) evaluates b on the documents a rejected; Not flips within the candidates. count(lo, hi) and select(lo, hi, &mut Vec<u32>) run over any range, so shards and threads can split the corpus freely. Both are generic over a Docs trait (len(), doc(i)), so there is no dynamic dispatch; a DocSet (documents back to back plus offsets) and a store snapshot implement it.

Measured: 67 M documents/s on 6 threads over 223 MB; a plan cache hit takes 0.03 us.

In the server, each shard compiles the filter against the table's dictionary, scans its documents, and the connection merges the results. A count scan inside a shard can use worker threads (scan_threads). Measured over TCP (raftdb-bench server, 1 M documents, 4 shards x 3 scan threads): 57.2 M documents/s.

required_leaves and indexes#

Plan::required_leaves lists the Cmp and In nodes a document must satisfy, found by walking And nodes from the root. A leaf under Or or Not is not listed. The query planner uses these to fetch candidate keys from an index.

SQL path#

raftdb_exec::sql::parse turns SELECT * | COUNT(*) FROM <table> [WHERE ...] [ORDER BY ...] [LIMIT n [OFFSET m]] into a Plan plus order, limit and offset, so SQL and JSON share one executor, one set of typing rules and the same indexes. Errors have a message and a byte position; line_col(text, pos) maps it to line and column (this is what position in HTTP errors is). The raftdb-exec parser refuses GROUP BY, LIKE, other functions and writes; column lists are handled by the server.

Ordering#

ORDER BY uses a total order, ascending: missing, null, false, true, numbers (integers and doubles together by value), timestamps, text (bytewise), bytes (bytewise), arrays and objects (all equal). DESC reverses it, so missing and null come last. Rows that tie are ordered by primary key, so paging is stable while the data does not change. Note that in the order integers and doubles of equal value tie, while in a filter they are different types.

JSON to documents#

json::encode writes a parsed JSON value in the binary document form, with a function that maps a field name to its dictionary id (allocating if needed). Integers written without . or exponent are Int, other numbers F64; an object with the same field twice is an error. The reverse is raftdb_doc::to_json.

Not exposed#

The plan is not yet sent over the wire as a pre-compiled handle: it is listed as a design idea; today a client sends the filter text. The explain endpoint that would return the plan is only in the design draft of the API.

Tests#

Four unit tests (12 filters against a plain Rust model over 5,000 documents, range edges, 11 bad filters, plan cache identity), the shared conformance file, JSON round trips, and five SQL tests (29 SQL/JSON pairs, NULL rules, 17 error messages with positions, 30,000 random token strings never panic).

See also#

Filter language, HTTP: queries