surrealdb/surrealdb

A scalable, distributed, collaborative, document-graph database, for the realtime web

31,903 stars Rust 9 components

13 hidden assumptions · 6-stage pipeline · 9 components

Like any codebase, this fullstack makes assumptions it never checks — most are routine. The ones worth your attention are below.

Multi-model database server that processes SurrealQL queries on distributed document-graph data

SurrealQL queries enter as text, flow through lexical analysis to become tokens, then recursive descent parsing builds an AST which the core engine executes against distributed storage, returning serialized values through the network server. The Surrealism system runs in parallel, compiling annotated Rust functions to WASM plugins that can be invoked during query execution.

Under the hood, the system uses 3 feedback loops, 4 data pools, 4 control points to manage its runtime behavior.

A 9-component fullstack. 1510 files analyzed. Data flows through 6 distinct pipeline stages.

Hidden Assumptions

Most of what this code assumes is routine. These 3 are the ones most likely to cause trouble here. The rest are minor; they're under "Show everything".

Worth your attention first

If the extras field contains corrupted data or wrong type, the whitespace detection silently fails and tokens may be joined incorrectly, leading to parse errors that don't point to the real issue

Worth your attention first

If a Parse implementation calls parser.push() before the parsed object is complete, the AST contains half-initialized nodes that cause crashes during query execution

Worth your attention first

When invalid UTF-8 appears mid-stream, the lookahead buffer fills with None values, causing the parser to make wrong decisions based on phantom end-of-input, potentially accepting malformed queries

Show everything (10 more)
Temporal

The FlatBufferBuilder::finish() call assumes the Value tree contains no cycles and will always terminate, but Value can contain Object/Array types that could reference each other

If this fails: If a Value contains circular references (Object A contains Array B which contains Object A), the serialization enters infinite recursion and crashes with stack overflow

surrealdb/types/src/flatbuffers/mod.rs:encode
Resource

WASM function execution assumes the host can always interrupt guest code via epoch timeout, but some WASM operations (like large memory allocations) are atomic and cannot be interrupted

If this fails: A malicious or buggy WASM function could perform a massive memory allocation that blocks the epoch interrupt, causing the server to hang indefinitely despite timeout configuration

surrealism/runtime/src/lib.rs:epoch-based timeouts
Domain

The default endpoint 'ws://localhost:8000' assumes WebSocket protocol and port 8000 is available, but there's no runtime verification that this protocol/port combination actually works

If this fails: If port 8000 is blocked or the server only supports HTTP, connections fail with cryptic WebSocket errors instead of clear protocol mismatch messages

surrealdb/server/src/cli/abstraction/mod.rs:DatabaseConnectionArguments
Scale

Parser speculation assumes backtracking depth is bounded, but complex grammar ambiguities could cause exponential backtrack explosion without any limits

If this fails: Pathological input queries with deep ambiguity cause the parser to backtrack exponentially, consuming CPU and memory until the server becomes unresponsive

surrealdb/parser/src/parse/mod.rs:speculating mode
Environment

Export name validation assumes ASCII alphanumeric and underscore are the only valid characters, but doesn't account for Unicode identifier rules that Rust itself supports

If this fails: Valid Rust function names with Unicode characters get rejected during macro processing, preventing legitimate non-English codebases from using Surrealism

surrealism/macros/src/attr.rs:validate_export_name
Contract

The execute! macro assumes block_on() can safely nest and that no other async runtime is already running on the current thread

If this fails: If called from within an existing async context, block_on() panics with 'Cannot start a runtime from within a runtime', breaking benchmark execution

surrealdb/core/benches/common/mod.rs:execute macro
Shape

The decode function assumes the input byte slice contains a valid FlatBuffers root table of type Value, but doesn't validate the FlatBuffers magic number or schema version

If this fails: Passing random binary data or FlatBuffers with wrong schema causes undefined behavior in flatbuffers::root(), potentially reading garbage memory as valid data

surrealdb/types/src/flatbuffers/mod.rs:decode
Temporal

The SDK_VERSION constant assumes CARGO_PKG_VERSION is always available and correctly formatted as a semver string at compile time

If this fails: If built outside Cargo context or with malformed version metadata, the constant contains invalid version data, breaking module compatibility checks

surrealism/runtime/src/lib.rs:SDK_VERSION
Environment

Environment variable parsing assumes SURREAL_* variables contain UTF-8 strings, but environment variables can contain arbitrary bytes on Unix systems

If this fails: Invalid UTF-8 in environment variables causes clap to panic during argument parsing instead of showing user-friendly error messages

surrealdb/server/src/cli/abstraction/mod.rs:AuthArguments
Ordering

The Token struct assumes Span contains valid byte offsets into the original source text that remain valid throughout the token's lifetime

If this fails: If the source text is modified or freed while tokens still reference it, Span offsets point to garbage memory, causing crashes when generating error messages

surrealdb/token/src/lib.rs:Token struct

Open the standalone hidden-assumptions report for surrealdb →

How Data Flows Through the System

SurrealQL queries enter as text, flow through lexical analysis to become tokens, then recursive descent parsing builds an AST which the core engine executes against distributed storage, returning serialized values through the network server. The Surrealism system runs in parallel, compiling annotated Rust functions to WASM plugins that can be invoked during query execution.

  1. Tokenize SurrealQL — The logos-generated Lexer in BaseTokenKind scans input text character-by-character using finite automaton rules to produce Token structs with kind, span, and whitespace separation info
  2. Parse to AST — The recursive descent Parser uses PeekableLexer to consume tokens with up to 3-token lookahead, building an Ast<Library> through NodeId insertions that represent the query structure [Token → Ast]
  3. Execute Query — The Datastore traverses the AST nodes to execute operations against distributed storage backends, using Session for authentication context and transaction management [Ast → Value]
  4. Serialize Response — Values are converted to FlatBuffers binary format via ToFlatbuffers trait implementations, then transmitted over WebSocket/HTTP connections to clients [Value]
  5. Compile WASM Plugins — Rust functions annotated with #[surrealism] macros are parsed by SurrealismAttrs, then compiled to WASM bytecode that can be loaded by the runtime host
  6. Execute WASM Functions — The Surrealism runtime host loads compiled WASM modules and executes guest functions with epoch-based timeouts and capability sandboxing during query processing [Value → Value]

Data Models

The data structures that flow between stages — the contracts that hold the system together.

Token surrealdb/token/src/lib.rs
struct with kind: BaseTokenKind, span: Span, joined: Joined enum indicating whitespace separation
Created by logos lexer from source text, consumed by recursive descent parser to build AST nodes
Ast<L: NodeLibrary> surrealdb/ast/src/types/mod.rs
generic container with typed node collections (Vec<T> for regular nodes, IdSet<u32, T> for unique nodes)
Built incrementally by parser through NodeId insertions, then traversed by core execution engine
Error surrealdb/common/src/error/mod.rs
pointer-sized wrapper around RawError containing type-erased ErrorTrait implementations with error codes
Created when parsing fails or execution encounters errors, propagated up call stack with source diagnostics
Diagnostic surrealdb/common/src/error/source/mod.rs
struct with groups: Vec<Group> containing source code snippets and annotations with spans
Built when errors need source context, rendered for user-facing error messages
Kind surrealdb/types/src/kind/mod.rs
enum representing SurrealDB type system: Any, Bool, String, Number, Object, Array(Box<Kind>, Option<u64>), Record(Vec<Table>), etc.
Inferred during query planning, used for runtime type validation and optimization
Value surrealdb/types/src/flatbuffers/mod.rs
enum representing actual data values, serializable via FlatBuffers with ToFlatbuffers/FromFlatbuffers traits
Created from user data input, transformed during query operations, persisted to storage or returned to client

System Behavior

How the system operates at runtime — where data accumulates, what loops, what waits, and what controls what.

Data Pools

AST Node Collections (in-memory)
Typed vectors and hash-consed sets storing parsed AST nodes indexed by NodeId, supporting efficient lookup and deduplication
Token Buffer (buffer)
Circular buffer in PeekableLexer storing upcoming tokens for multi-token lookahead during parsing
Error Diagnostics Store (in-memory)
Accumulates source code snippets and span annotations for rich error reporting
WASM Module Cache (registry)
Compiled WASM bytecode modules indexed by function name for plugin execution

Feedback Loops

Delays

Control Points

Technology Stack

logos (library)
Generates finite automaton lexers from regex patterns and token definitions for SurrealQL tokenization
syn (library)
Parses Rust syntax trees for procedural macro processing in Surrealism compilation
flatbuffers (serialization)
Provides zero-copy binary serialization format for efficient Value transport over network
clap (library)
Parses CLI arguments with environment variable support for server configuration
tokio (runtime)
Async runtime powering database operations, network server, and concurrent query processing
reblessive (library)
Provides stack-safe recursion for deep AST traversal without stack overflow
logos (build)
Token lexer generation for SurrealQL language processing
anyhow (library)
Error handling in application code with context and chaining

Key Components

Package Structure

common (shared)
Shared error handling, diagnostics, and span tracking utilities used across all SurrealDB packages.
ast (library)
Abstract syntax tree definitions for SurrealQL language constructs with node management.
token (library)
Lexical tokenizer for SurrealQL using logos, converts source text into typed tokens.
parser (library)
Recursive descent parser that transforms token streams into AST structures.
core (library)
Main database engine handling query execution, transactions, and distributed storage operations.
server (app)
Network server providing HTTP, WebSocket, and CLI interfaces to the core database engine.
types (library)
Type system definitions, serialization formats, and value representations for SurrealDB data.
derive (library)
Procedural macros for automatically deriving type system traits on user-defined structs.
demo (app)
Example functions demonstrating the Surrealism WASM plugin system for extending SurrealDB.
macros (library)
Procedural macros for annotating Rust functions to be compiled into SurrealDB WASM plugins.
runtime (library)
WASM runtime host for loading and executing Surrealism plugins with sandboxing and timeouts.
types (library)
Type definitions and error handling for the Surrealism WASM plugin interface.

Explore the interactive analysis

See the full architecture map, data flow, and code patterns visualization.

Analyze on CodeSea

Related Fullstack Repositories

Frequently Asked Questions

What is surrealdb used for?

Multi-model database server that processes SurrealQL queries on distributed document-graph data surrealdb/surrealdb is a 9-component fullstack written in Rust. Data flows through 6 distinct pipeline stages. The codebase contains 1510 files.

How is surrealdb architected?

surrealdb is organized into 5 architecture layers: Language Frontend, Database Engine, Network Interface, Type System, and 1 more. Data flows through 6 distinct pipeline stages. This layered structure keeps concerns separated and modules independent.

How does data flow through surrealdb?

Data moves through 6 stages: Tokenize SurrealQL → Parse to AST → Execute Query → Serialize Response → Compile WASM Plugins → .... SurrealQL queries enter as text, flow through lexical analysis to become tokens, then recursive descent parsing builds an AST which the core engine executes against distributed storage, returning serialized values through the network server. The Surrealism system runs in parallel, compiling annotated Rust functions to WASM plugins that can be invoked during query execution. This pipeline design reflects a complex multi-stage processing system.

What technologies does surrealdb use?

The core stack includes logos (Generates finite automaton lexers from regex patterns and token definitions for SurrealQL tokenization), syn (Parses Rust syntax trees for procedural macro processing in Surrealism compilation), flatbuffers (Provides zero-copy binary serialization format for efficient Value transport over network), clap (Parses CLI arguments with environment variable support for server configuration), tokio (Async runtime powering database operations, network server, and concurrent query processing), reblessive (Provides stack-safe recursion for deep AST traversal without stack overflow), and 2 more. A focused set of dependencies that keeps the build manageable.

What system dynamics does surrealdb have?

surrealdb exhibits 4 data pools (AST Node Collections, Token Buffer), 3 feedback loops, 4 control points, 3 delays. The feedback loops handle self-correction and convergence. These runtime behaviors shape how the system responds to load, failures, and configuration changes.

What design patterns does surrealdb use?

5 design patterns detected: Hash-Consed AST Nodes, Type-Erased Error Propagation, Logos-Generated Lexer, Recursive Descent with Backtracking, Procedural Macro Attributes.

Analyzed on April 20, 2026 by CodeSea. Written by .