Introduction

Graphersal is an in-memory graph database and traversal engine written in Rust. You ask it questions in plain language or in Gremlin. In the AI chat you simply write what you want to know, and the model of your choice turns it into queries, runs them and answers. Gremlin is the query language of Apache TinkerPop™: start somewhere in a graph, walk along its edges, filter, group and count. Read queries may also be written in GQL, the ISO graph query language (Cypher-like patterns; experimental).

Try it now in the live playground: the real engine in your browser, nothing to install. The source code, releases and issues are on GitHub.

Why Graphersal

AI moves faster than the tools around it. We built Graphersal so you don't have to wait for them: a lightweight, embeddable graph engine you can turn into whatever your AI solution needs — a library inside your application, a tool for your agents, or a full server with your own features on top.

It works out of the box: a browser UI, an MCP endpoint for AI agents, an AI chat where you simply ask about your graph in plain language and it writes and runs the queries for you, durable storage and transactions, and the safety to run queries you did not write — permissions, read-only access, resource limits and timeouts. You start with a working system, not with a list of components to wire together.

A first look

// who created software together with marko?
g.v().has("name", "marko").as("me")
  .out("created").in("created")
  .where(P.neq("me"))
  .path().by("name")

The web playground: a query, its results and the graph

What you get

  • Gremlin, two ways. Build traversals in Rust (g.v(None).has_label("person").out("knows")) or write them as text in the Gremlin DSL, TinkerPop's steps in snake_case or in Gremlin's own camelCase (hasLabel, outE). The text runs the same everywhere: in the browser, in the command line, from Python and through an AI agent.
  • GQL patterns (experimental). g.gql(..) runs ISO GQL queries (MATCH (p:person)-[:knows]->(f) RETURN f.name, INSERT, SET, DELETE, Cypher spellings as aliases) on the same engine, and Gremlin steps may follow. Its subset and answers may still change between versions.
  • A playground in the browser. The real engine, compiled to WebAssembly: write a query, see a table, the graph drawing, the schema and the optimized plan. Nothing to install.
  • A command line tool. One-shot queries for shell scripts, an interactive REPL with completion and help, and a local server that brings the playground UI to a graph on your disk.
  • AI agents on your graph. The server speaks the Model Context Protocol (MCP), so Claude Code or another MCP client can query the graph you are looking at. In the playground's AI Chat tab you ask about your graph in plain language, and the model of your choice writes and runs the queries (experimental).
  • Values with real types. Besides numbers, strings, UUIDs and nested JSON: five date and time types modelled on PostgreSQL (time zones from the IANA database, calendar-correct arithmetic, TinkerPop's date steps), and vectors for embeddings with exact similarity search and quantization (Embeddings and Vector Search is the hands-on tour).
  • Safe by construction. Every traversal is atomic: it commits completely or leaves nothing behind. Schemas (a subset of JSON Schema) are enforced on write and fill create-time defaults. Limits, timeouts and permissions make it safe to run queries you did not write.
  • Durable when you need it. A graph lives in memory, and the Store keeps it on disk: every commit is in a write-ahead log, you can go back to any point in time, fork, roll back, back up and repair. The file format is a public specification.
  • Fast and observable. A rule-based optimizer rewrites each query and answers has() filters from declared property indexes; profile() shows the optimized plan with timings, traverser counts and memory per step.
  • Open for integration. Rust and Python APIs, saved (named, parameterized) queries stored in the graph, change capture with commit hooks, GraphSON and GraphML files, and a storage trait to run the whole engine on a storage of your own.

Where to go next

You want to ...Read
try it right nowthe live playground (nothing to install); a guided tour: Try It in the Browser
read the source, download a release or report an issuethe GitHub repository
install the command-line tool, the Python package or the crateInstallation
run queries from a terminal or a scriptThe Command Line
let an AI agent work with your graphDev Server, MCP and AI Chat
search by meaning with embeddings (semantic search, GraphRAG)Embeddings and Vector Search
understand graphs and Gremlin firstWhy a Graph?
use it from codeRust Quick Start, Python Quick Start
look up a step or a ruleThe Gremlin DSL, Step Reference
query with GQL or Cypher-like patterns (experimental)GQL Queries
find a commandCommand Cheat Sheet

Graphersal is not a complete copy of TinkerPop. It follows the TinkerPop specification for every step it implements and checks that with TinkerPop's own test suite, but some steps are not implemented yet and a few behave differently on purpose. Each difference is documented where the feature is described and collected in TinkerPop Deviations; see Graphersal and TinkerPop.

Installation

The command-line tool graphersal (the one-shot query runner, the REPL, the dev server and the graphersal store commands) comes as a prebuilt binary for Linux, macOS and Windows, or builds from source with Cargo. The engine is also a Python package and a Rust crate. To only try it, nothing has to be installed: the playground runs in the browser.

Prebuilt binaries

Every release on the releases page has one archive per platform:

PlatformArchive
Linux x86_64 (any distribution, also Alpine and WSL2)graphersal-v<version>-linux-x86_64.tar.gz
Linux aarch64 (ARM64)graphersal-v<version>-linux-aarch64.tar.gz
macOS on Apple silicongraphersal-v<version>-macos-arm64.tar.gz
Windows x86_64graphersal-v<version>-windows-x86_64.zip

There is no prebuilt binary for macOS on Intel after 0.4.0 (its runner made every release much slower): build it from source with Cargo (below), or open an issue if you need one. The Python package installs there from the sdist, which needs a Rust toolchain.

Each archive holds one directory of its own name with the graphersal binary (graphersal.exe on Windows), the licence files, the third-party licences and README.md. The Linux binaries are statically linked, so they run on every distribution; see Performance of the prebuilt Linux binaries before you benchmark with them.

On Linux and macOS (pick the archive of your platform):

VERSION=0.2.0
NAME=graphersal-v$VERSION-linux-x86_64
ARCHIVE=$NAME.tar.gz
curl -LO https://github.com/graphersal/graphersal/releases/download/v$VERSION/$ARCHIVE
tar -xzf $ARCHIVE                  # unpacks into the directory $NAME
mkdir -p ~/.local/bin && mv $NAME/graphersal ~/.local/bin/    # or: sudo mv $NAME/graphersal /usr/local/bin/

~/.local/bin must be on your PATH; if it is not, add export PATH="$HOME/.local/bin:$PATH" to your shell's start file (~/.bashrc, ~/.zshrc).

On Windows, in PowerShell:

$Version = "0.2.0"
$Name = "graphersal-v$Version-windows-x86_64"
$Archive = "$Name.zip"
Invoke-WebRequest "https://github.com/graphersal/graphersal/releases/download/v$Version/$Archive" -OutFile $Archive
# the archive holds one directory $Name with graphersal.exe
Expand-Archive $Archive -DestinationPath "$env:LOCALAPPDATA\graphersal"
$Dir = "$env:LOCALAPPDATA\graphersal\$Name"
# put the directory on the PATH of your user (takes effect in a new terminal)
[Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";$Dir", "User")

Check the download

Each release also has a file SHA256SUMS with the checksum of every archive. Download it next to the archive and check:

curl -LO https://github.com/graphersal/graphersal/releases/download/v$VERSION/SHA256SUMS
sha256sum -c --ignore-missing SHA256SUMS      # Linux
shasum -a 256 -c --ignore-missing SHA256SUMS  # macOS

In PowerShell, compare (Get-FileHash $Archive -Algorithm SHA256).Hash with the archive's line in SHA256SUMS (the case of the letters does not matter).

The archives are built on GitHub Actions and carry a GitHub build-provenance attestation, which proves that a file was built from this repository by its release workflow. With the GitHub CLI:

gh attestation verify $ARCHIVE --repo graphersal/graphersal

cargo binstall

With cargo-binstall, Cargo downloads the prebuilt archive of your platform instead of compiling:

cargo binstall graphersal-cli

From source

With a Rust toolchain (1.88 or newer, rustup):

cargo install graphersal-cli      # the binary is `graphersal`

On Linux this build uses the system's C library (glibc) and its allocator, so it is the one for benchmarks and heavy workloads (see the next section). From a clone of the repository, cargo build -p graphersal-cli --release writes target/release/graphersal.

Performance of the prebuilt Linux binaries

The prebuilt Linux binaries are statically linked with musl, which makes them run on any distribution, including Alpine and WSL2. musl's memory allocator is noticeably slower than glibc's on allocation-heavy queries (large group(), path() or to_list() results, imports): measured on the large sample graph, the same queries took 1.07 to 1.39 times as long as with a glibc build of the same source (the most for group() and write-heavy scripts). For benchmarks and heavy workloads, build from source with cargo install graphersal-cli, which uses the system's glibc. The figures in this book come from source builds. The macOS and Windows binaries have no such penalty.

Windows Subsystem for Linux

Under WSL, use the Linux binary: linux-x86_64, or linux-aarch64 on ARM Windows. WSL1 is not supported.

  • WSL2 forwards localhost to Windows, so a graphersal --server started in WSL is reachable from the Windows browser at http://localhost:<port>/ (port 8080 unless you give --port).
  • Keep a Store in the Linux file system (~/...), not under /mnt/c: the Windows drives are mounted over 9p, where fsync is slow, and the store's LOCK file does not protect against a native Windows graphersal.exe opening the same files. Never open one store from both at once.

macOS and Windows security prompts

The binaries are not code-signed.

  • macOS: Gatekeeper blocks a binary downloaded with a browser ("cannot be opened because the developer cannot be verified"). Remove the quarantine flag once: xattr -d com.apple.quarantine ./graphersal. A download with curl or cargo binstall is not quarantined.
  • Windows: SmartScreen may warn when you first start graphersal.exe; choose More info, then Run anyway.

Verify

graphersal --version                      # graphersal 0.2.0
graphersal -e 'g.v().count().next()'      # 6: the vertices of the TinkerPop "modern" sample

The Command Line goes on from here. The dev server (graphersal --server) is a demo and development mode, not for production: see Dev Server and MCP.

Python

The Python package (wheels for Python 3.10 and newer):

pip install graphersal

See the Python Quick Start.

Rust library

cargo add graphersal --features script,io,display

script is the Gremlin DSL as text, io GraphSON and GraphML files, display results as tables; add persist to keep a graph on disk. Library Features lists every feature, and the Rust Quick Start is the first program.

Try It in the Browser

The playground is the quickest way to see what Graphersal does. It is a web page that runs the real engine, compiled to WebAssembly, inside your browser: no server, no account, and your data never leaves the machine.

Start it

rustup target add wasm32-unknown-unknown                      # one-time
cargo install --locked wasm-bindgen-cli --version 0.2.129     # one-time
playground/build.sh                                           # builds playground/pkg/
python3 playground/serve.py 8000                              # open http://localhost:8000/

The start page offers sample graphs, or a GraphSON or GraphML file of your own:

The start page: choose a sample graph or load a file

Pick Modern (TinkerPop): four people, two pieces of software, and who knows and created what. Most examples in this book run on it.

Run a query

Type a traversal into the Query panel and press Ctrl/⌘+Enter. The results appear as a table (also as JSON and as the raw text the command line prints), and the Graph panel draws the graph. Typing . offers every step with its description and a runnable example.

A query, its results and the graph

A few queries to start with; Run in the playground under each one opens it there:

g.v().has_label("person").values("name")                       // all people
g.v().has("name", "marko").out("knows").values("name")         // whom marko knows
g.v().has_label("person").has("age", P.gt(30)).values("name")  // people older than 30
g.v().has_label("person").group().by("name").by(__.out("created").count())   // software per person

The Examples menu holds about thirty more, grouped by graph and topic.

See how it ran

With Profile on, every run also shows the plan the optimizer made of your query: each step with its calls, traversers in and out and its time, plus the optimizer rules that changed the plan. Here has_label("person") was folded into the start step (v(labels: ["person"])):

The Profile panel: the optimized plan with timings

Look at the schema

The Schema panel infers the structure of the data: the labels, their properties and types, and which edges connect which labels. You can edit it, and Freeze as open or Freeze as closed turns it into a schema the engine enforces on every write.

The Schema panel: labels, properties and types

Walk a bigger graph

The File tree sample is a small directory tree: good for recursive traversals with repeat().

A recursive traversal over the file tree sample

What else is in there

  • several query tabs side by side, a history and saved scripts;
  • a graph editor (add, change and delete vertices and edges by clicking);
  • a fast WebGL drawing for large graphs, label graphs and neighbourhood views;
  • saved queries, compression rules and property indexes in the Catalog menu;
  • a Store in memory with commits, marks, point-in-time views, forks and rollback (the Store menu);
  • downloads of the graph (GraphSON, GraphML, snapshot), the schema and the catalog.
  • vector search over embeddings: the Examples group "Embeddings (vectors)" and Embeddings and Vector Search.
  • the green Share link button in the top bar: a link that opens your query together with a small graph, for example in a bug report (Share a query with its graph).

Every feature is described in Web Playground. The same UI also runs against a graph on your disk, served by the command line tool: Dev Server, MCP and AI Chat.

The Command Line

The graphersal binary runs Gremlin queries from a terminal. It has three modes: a one-shot query runner for shell scripts, an interactive REPL, and a local server (next chapter).

Install it from a prebuilt binary or with cargo install graphersal-cli (Installation), or build it in a clone of the repository:

cargo build -p graphersal-cli --release      # target/release/graphersal

One-shot queries

Pass a query with -e; the result goes to stdout and nothing else does:

$ graphersal -e 'g.v().has("name", "marko").out("knows").values("name")'
╭───────╮
│ value │
├───────┤
│ josh  │
│ vadas │
╰───────╯

Without --graph it runs on the TinkerPop "modern" sample. --graph also takes empty, large (about 110,000 elements), tree, a GraphSON or GraphML file, a snapshot or a Store directory:

graphersal --graph people.json -e 'g.v().count()'
echo 'g.v().values("age").max().next()' | graphersal --graph modern     # the query from stdin
graphersal -e 'g.v().has_label("person").values("name")' --format json  # also markdown, mermaid, ...

A query that fails prints its diagnostic on stderr and exits with 1, so a shell script or a CI job can check a graph:

# fails (exit 1) when a server has no owner
graphersal --graph export.json -e 'g.v().has_label("server").has_not("owner").fail("a server without an owner")'

The REPL

Without a query, graphersal starts an interactive shell with history, Tab completion of steps and tokens, and the documentation of every function:

$ graphersal
graphersal> g.v().has_label("person").values("name").limit(2);
╭───────╮
│ value │
├───────┤
│ marko │
│ vadas │
╰───────╯
graphersal> let n = g.v().count().next();
graphersal> n * 10;
60
graphersal> /help values
values  (step, terminal or source method of a traversal)
  values()
  values(arg1: any)
  ...
Yields the values of the given (or all) properties; a jpath() key reads a nested value.

Example: `g.v(1).values("name", "age").to_list()` returns `["marko", 29]`

Variables live across lines: a script is ordinary Rhai code around Gremlin traversals, so loops, functions and maps work as well.

See the plan

profile() prints the plan the optimizer made, with timings and traverser counts:

$ graphersal -e 'g.v().has_label("person").out("created").count().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(labels: ["person"])                                           1       0       4    5.667µs     8.66
out("created")                                                  1       4       4    5.125µs     7.83
count()                                                         1       4       1      125ns     0.19
                                                      TOTAL:             execute:   65.417µs    16.69
=====================================================================================================
Optimizer rules applied: source_filter_pushdown

Keep a graph on disk

graphersal store creates and manages a Store, a graph on disk with a write-ahead log, and every mode opens one with --graph <dir>:

graphersal store create data --from people.json    # a new store from a graph file
graphersal --graph data -e 'g.add_v("person").property("name", "ann").iterate()'   # durable
graphersal store info data

More: The graphersal store Command.

Embedding models

embed() computes vectors from text with an embedder; built in is hash-ngram/1 (lexical only). A real model serves a database only once it is imported into it: graphersal embed-model download <repo> fetches a Model2Vec model from Hugging Face once into the download cache (the only network access of the tool), and graphersal embed-model import <repo> --into <store> puts it into a store (--default makes it the model embed() uses without a name):

graphersal embed-model download minishlab/potion-base-8M     # into ~/.cache/graphersal/embed-models
graphersal embed-model download minishlab/potion-multilingual-128M   # 101 languages (about 510 MB)
graphersal embed-model list                                  # repository, size, model identity
graphersal store create data
graphersal embed-model import minishlab/potion-base-8M --into data --default
graphersal --graph data \
  -e 'g.add_v("person").property("name", "Marco").iterate();
      g.add_v("person").property("name", "Mary").iterate();
      g.patch_schema(#{vertices: #{person: #{schema: #{type: "object", properties: #{emb: #{type: "array",
        format: "vector", embedder: "minishlab/potion-base-8M", from: "name"}}}}}});
      g.v().has_label("person").nearest("emb", "Marco", 2).values("name").to_list()'

The vector rule (from: "name") fills person.emb with the store's model at every write (Vector Rules); embed(text) and g.v().embed("name", #{embedder: "minishlab/potion-base-8M"}) name a model by its repository; g.embedders() lists the built-in and the database's models with their full identity, model2vec/minishlab/potion-base-8M@fac4fa854e68, the one embed-model list shows. A .gsnap file carries its models too: --graph file.gsnap serves them without a store.

Changed in 0.5.0: the flags --embedder NAME=... and --default-embedder are removed (a command line that still passes them stops with exit code 2 and the import command); a model is imported into the database instead.

The download cache is $GRAPHERSAL_EMBED_MODELS (or --dir), else the user cache. A model that does not load stops the command and gives the reason. More: Embeddings and Vector Search.

Every option of the tool is in graphersal --help and on the Command Cheat Sheet.

Dev Server, MCP and AI Chat

graphersal --server brings the playground UI to a graph on your disk. The browser talks to the native engine in this process instead of WebAssembly, and the same process can open the graph to AI agents.

DEV mode. The server is for local work: it listens on the loopback interface (inside a container on every interface, or where --host says), has no user accounts, and its HTTP API changes without notice. See Listening address and Docker.

The playground over your own graph

graphersal --graph people.json --server --port 8080      # open http://127.0.0.1:8080/

--graph takes everything the command line takes: a sample, a GraphSON or GraphML file (Save to file writes it back), a snapshot, or a Store directory, whose commits are durable and whose history (marks, points in time, forks, rollback, backups) is in the Store menu.

An AI agent on the same graph (MCP)

With --mcp the server also offers a Model Context Protocol endpoint. An agent such as Claude Code then works with the same graph you see in the browser: it runs queries, adds data and evolves the schema through MCP tools, and the page reloads by itself when the agent changed something.

graphersal --graph modern --server --port 9000 --mcp
claude mcp add --transport http graphersal http://127.0.0.1:9000/mcp   # then start a new `claude`

The dev server: the MCP badge in the top bar, a query and its plan

Ask the agent, for example:

  • "Use the graphersal tools: who does marko know?"
  • "Add a person ada, 36 years old, who knows marko." (the browser shows the new commit)
  • "Infer the schema, store it in mode open and add an optional string property email to person."

The agent gets the tools query, the schema tools (get_schema, infer_schema, set_schema, patch_schema, validate_schema, diff_schema, ...), statistics, graph_info, the saved queries, the compression rules and the property indexes, plus the DSL reference as a resource. --mcp-read-only lets it only read, --mcp-token requires a bearer token, and --mcp-query-tools offers every saved query as a tool of its own.

AI Chat in the playground

EXPERIMENTAL. The configuration and the tab change without notice.

With --ai FILE the agent loop runs inside the server itself: the Query panel's + opens an AI Chat tab where you ask questions in plain language. The server sends them to the LLM you configured (Anthropic, OpenAI or an OpenAI-compatible endpoint such as Ollama), runs the tool calls the model asks for on your graph and shows each step: the queries the agent ran, their results, and its answer with tables and runnable queries.

An AI Chat tab: the question, the tool calls behind the answer, the query and the table

export ANTHROPIC_API_KEY=...                  # the key stays in the server process
graphersal --graph modern --server --ai crates/graphersal-cli/examples/ai-anthropic.json

What the agent queries is sent to the provider you chose; the key never reaches the browser.

Every option, the configuration keys, the safety notes and what data leaves the machine are in Dev Server and MCP.

Embeddings and Vector Search

An embedding is a list of numbers that a machine-learning model computes for a piece of data: a sentence, a document, an image, a product. The model places similar things close together, so "how do I feed my cat?" and "Feeding your cat" get vectors that point in almost the same direction, while "Rust for beginners" points elsewhere. Searching by embedding finds what is meant, not only what is spelled the same. Graphersal stores embeddings as a vector value, searches them exactly with nearest() and similarity(), and combines the hits with everything a graph does well: filters, edges, paths.

Graphersal never calls a model on its own. A semantic model runs in your host program (Python, a server, an MCP tool), which writes the result as an ordinary property value, or registers the model as an embedder that the embed step calls. Built in is one small embedder, hash-ngram/1: no model, lexical similarity only (typos and word forms, not meaning), enough for fuzzy lookup and for trying the steps; the reference page has the details and the reasoning. The graphersal command line registers a real semantic model for you: a downloaded Model2Vec model, run locally.

This page is the practical tour. Every detail (element kinds, metrics, schema rules, formats) is on the reference page Vectors.

Keep vectors filled: a vector rule

The way to fill a vector property is a vector rule in the schema: "from": "text" beside "embedder" on the vector property. Every write of text embeds it into the vector in the same unit, a text removed removes the vector, and adding the rule fills every existing element (the whole database is locked while that runs: the schema preview says how long first).

// one query: the rule
g.set_schema(#{mode: "open", vertices: #{doc: #{schema: #{type: "object", properties: #{
    text: #{type: "string"},
    emb: #{type: "array", format: "vector", embedder: "hash-ngram/1", from: "text"}}}}}})
// the next query: a write of the text (its vector is written when the query's unit ends)
g.add_v("doc").property("text", "vector search in a graph").next()
// and later: a text query
g.v().has_label("doc").nearest("emb", "graph search", 1).values("text").next()

Try it in the playground, without a model

Real embeddings have hundreds of dimensions. To see how the steps behave you can make up toy embeddings with three dimensions whose meaning you pick yourself:

AxisMeaning
1animals
2food
3technology

"Training a puppy" is mostly animals: [0.8, 0.1, 0.2]. "Robot chefs" is food and technology: [0.1, 0.6, 0.8]. A question about pets becomes [1.0, 0.0, 0.0].

Every block below is a complete script that starts on the empty graph, so each one runs on its own: the button in the margin opens it in the playground and runs it. The first lines are the same in most blocks: a schema that declares emb as a 3-dimensional f32 vector, and seven documents.

The schema declares the property emb with the format vector. In mode open a list of numbers written to it becomes a vector, so the host can send plain lists (or JSON arrays). nearest(key, q, k) then keeps the k documents closest to the query vector q, best first:

// Toy embeddings with three axes: [animals, food, technology].
g.set_schema(#{mode: "open", vertices: #{doc: #{schema: #{type: "object", properties: #{
  emb: #{type: "array", format: "vector", element: "f32", dimension: 3}}}}}});
for d in [
  ["Cats and dogs",        2024, [0.9, 0.1, 0.0]],
  ["Training a puppy",     2026, [0.8, 0.1, 0.2]],
  ["Feeding your cat",     2025, [0.6, 0.7, 0.0]],
  ["Pasta at home",        2025, [0.0, 0.9, 0.1]],
  ["Robot chefs",          2026, [0.1, 0.6, 0.8]],
  ["Rust for beginners",   2024, [0.0, 0.0, 1.0]],
  ["GPS collars for dogs", 2026, [0.7, 0.0, 0.6]],
] {
  g.add_v("doc").property("title", d[0]).property("year", d[1]).property("emb", d[2]).iterate();
}

// The list was stored as a vector: vector([0.9, 0.1, 0.0])
g.v().has("title", "Cats and dogs").values("emb").next();

// The three documents closest to "animals":
// ["Cats and dogs", "Training a puppy", "GPS collars for dogs"]
g.v().has_label("doc").nearest("emb", [1.0, 0.0, 0.0], 3).values("title").to_list()

nearest() is an exact search: it scores every document it receives (cosine similarity unless a metric is named or the schema declares one) and keeps the best k. The dimension is checked: a query with 2 or 4 numbers against these 3-dimensional vectors is an error, never truncated.

Ranking with scores

To see how close each document is, score it with similarity() and order by the score. project() builds one row per document; anonymous steps take the __. prefix and the order token is written out (Order.desc):

g.set_schema(#{mode: "open", vertices: #{doc: #{schema: #{type: "object", properties: #{
  emb: #{type: "array", format: "vector", element: "f32", dimension: 3}}}}}});
for d in [
  ["Cats and dogs",        [0.9, 0.1, 0.0]],
  ["Training a puppy",     [0.8, 0.1, 0.2]],
  ["Feeding your cat",     [0.6, 0.7, 0.0]],
  ["Pasta at home",        [0.0, 0.9, 0.1]],
  ["Robot chefs",          [0.1, 0.6, 0.8]],
  ["Rust for beginners",   [0.0, 0.0, 1.0]],
  ["GPS collars for dogs", [0.7, 0.0, 0.6]],
] {
  g.add_v("doc").property("title", d[0]).property("emb", d[1]).iterate();
}

// A question about "animals and technology":
let q = vector([0.5, 0.0, 0.5]);
g.v().has_label("doc")
 .project("title", "score")
   .by("title")
   .by(__.similarity("emb", q))
 .order().by(__.select("score"), Order.desc)
 .limit(4)
 .to_list()
// GPS collars for dogs 0.997, Training a puppy 0.851,
// Rust for beginners 0.707, Cats and dogs 0.703

nearest("emb", q, 4) gives the same four documents in the same order without the scores; to have both, search first and project after it: nearest("emb", q, 4).project("title", "score").by("title").by(__.similarity("emb", q)).

Put ordinary filters before nearest(): it then ranks only what passes them. Here only the documents from 2025 on:

g.set_schema(#{mode: "open", vertices: #{doc: #{schema: #{type: "object", properties: #{
  emb: #{type: "array", format: "vector", element: "f32", dimension: 3}}}}}});
for d in [
  ["Cats and dogs",        2024, [0.9, 0.1, 0.0]],
  ["Training a puppy",     2026, [0.8, 0.1, 0.2]],
  ["Feeding your cat",     2025, [0.6, 0.7, 0.0]],
  ["Pasta at home",        2025, [0.0, 0.9, 0.1]],
  ["Robot chefs",          2026, [0.1, 0.6, 0.8]],
  ["Rust for beginners",   2024, [0.0, 0.0, 1.0]],
  ["GPS collars for dogs", 2026, [0.7, 0.0, 0.6]],
] {
  g.add_v("doc").property("title", d[0]).property("year", d[1]).property("emb", d[2]).iterate();
}

// "Cats and dogs" (2024) is left out:
// ["Training a puppy", "GPS collars for dogs", "Feeding your cat"]
g.v().has_label("doc")
 .has("year", P.gte(2025))
 .nearest("emb", [1.0, 0.0, 0.0], 3)
 .values("title").to_list()

A filter is exact: unlike an approximate vector index, a filtered search never returns fewer than k hits when k documents pass the filter. A where(__.out(..)...) filters by the graph around each document the same way.

GraphRAG: a vector hit, then the graph

Retrieval-augmented generation (RAG) gives a language model the passages that answer a question. GraphRAG starts the same way, with the documents nearest to the question, and then follows the edges: who wrote them, what they are about, which other documents share the topic. Here each document has an author (wrote) and a topic (about). This block has no schema, so the lists are wrapped in vector(..):

// Documents with toy embeddings [animals, food, technology], their authors and topics.
for d in [
  ["Cats and dogs",      "Ada",  "pets",        [0.9, 0.1, 0.0]],
  ["Feeding your cat",   "Ada",  "pets",        [0.6, 0.7, 0.0]],
  ["Pasta at home",      "Ben",  "cooking",     [0.0, 0.9, 0.1]],
  ["Robot chefs",        "Cleo", "cooking",     [0.1, 0.6, 0.8]],
  ["Rust for beginners", "Cleo", "programming", [0.0, 0.0, 1.0]],
] {
  g.merge_v(#{"T.label": "person", name: d[1]}).as("a")
   .merge_v(#{"T.label": "topic", name: d[2]}).as("t")
   .add_v("doc").property("title", d[0]).property("emb", vector(d[3])).as("d")
   .add_e("about").to("t")
   .add_e("wrote").from("a").to("d")
   .iterate();
}

// "What should I cook for my cat?" ~ [0.5, 0.8, 0.0]: the two best hits with their context.
// [#{"author": "Ada", "title": "Feeding your cat", "topic": "pets"},
//  #{"author": "Ben", "title": "Pasta at home", "topic": "cooking"}]
g.v().has_label("doc").nearest("emb", [0.5, 0.8, 0.0], 2)
 .project("title", "author", "topic")
   .by("title")
   .by(__.in("wrote").values("name"))
   .by(__.out("about").values("name"))
 .to_list()

One more hop finds documents that a vector search alone would rank low, but that share the best hit's topic:

for d in [
  ["Cats and dogs",      "pets",        [0.9, 0.1, 0.0]],
  ["Feeding your cat",   "pets",        [0.6, 0.7, 0.0]],
  ["Pasta at home",      "cooking",     [0.0, 0.9, 0.1]],
  ["Rust for beginners", "programming", [0.0, 0.0, 1.0]],
] {
  g.merge_v(#{"T.label": "topic", name: d[1]}).as("t")
   .add_v("doc").property("title", d[0]).property("emb", vector(d[2]))
   .add_e("about").to("t")
   .iterate();
}

// The best hit for [0.5, 0.8, 0.0] is "Feeding your cat"; its topic "pets" brings in:
// ["Cats and dogs"]
g.v().has_label("doc").nearest("emb", [0.5, 0.8, 0.0], 1).as("hit")
 .out("about").in("about").where(P.neq("hit"))
 .values("title").to_list()

The host then turns the rows into the prompt for its language model. In Python this is a few lines (below).

GraphRAG with text: a vector rule and a text query

The same flow without making up any vector: a vector rule in the schema embeds every document's title with a model (here the built-in hash-ngram/1, which compares spelling, not meaning; a model the Store keeps works the same way) and records which model produced the vectors. A query then passes the question as text: nearest() embeds it once, with that same model, so the question and the documents are always comparable. The rule is the from beside the embedder of the vector property:

g.set_schema(#{mode: "open", vertices: #{doc: #{schema: #{type: "object", properties: #{
  title: #{type: "string"},
  emb: #{type: "array", format: "vector", embedder: "hash-ngram/1", from: "title"}}}}}});
for d in [
  ["Cats and dogs",      "Ada",  "pets"],
  ["Feeding your cat",   "Ada",  "pets"],
  ["Pasta at home",      "Ben",  "cooking"],
  ["Cooking for robots", "Cleo", "cooking"],
  ["Rust for beginners", "Cleo", "programming"],
] {
  // Each write of a title embeds it into "emb" when its unit ends.
  g.merge_v(#{"T.label": "person", name: d[1]}).as("a")
   .merge_v(#{"T.label": "topic", name: d[2]}).as("t")
   .add_v("doc").property("title", d[0]).as("d")
   .add_e("about").to("t")
   .add_e("wrote").from("a").to("d")
   .iterate();
}

// [#{"author": "Ada", "title": "Feeding your cat", "topic": "pets"},
//  #{"author": "Ada", "title": "Cats and dogs", "topic": "pets"}]
g.v().has_label("doc").nearest("emb", "feeding cats", 2)
 .project("title", "author", "topic")
   .by("title")
   .by(__.in("wrote").values("name"))
   .by(__.out("about").values("name"))
 .to_list()

The rule writes the vectors when the unit that wrote the titles ends. The command line runs every traversal as its own unit, so the script runs as it is (graphersal --graph empty -e '..'); the playground runs a whole script as one unit, so run the text query there as a second run. A document added or retitled later is embedded by the same rule, in the unit that writes it (Vector Rules). One more hop works as before:

g.set_schema(#{mode: "open", vertices: #{doc: #{schema: #{type: "object", properties: #{
  emb: #{type: "array", format: "vector", embedder: "hash-ngram/1", from: "title"}}}}}});
for d in [["Pasta at home", "cooking"], ["Cooking for robots", "cooking"], ["Cats and dogs", "pets"]] {
  g.merge_v(#{"T.label": "topic", name: d[1]}).as("t")
   .add_v("doc").property("title", d[0])
   .add_e("about").to("t")
   .iterate();
}
// The best hit for "cooking pasta" shares its topic with: ["Pasta at home"]
g.v().has_label("doc").nearest("emb", "cooking pasta", 1).as("hit")
 .out("about").in("about").where(P.neq("hit"))
 .values("title").to_list()

More like this

The query vector can come from the graph: take a document's own embedding, label it with as("q") and search with __.select("q"), leaving the document itself out:

g.set_schema(#{mode: "open", vertices: #{doc: #{schema: #{type: "object", properties: #{
  emb: #{type: "array", format: "vector", element: "f32", dimension: 3}}}}}});
for d in [
  ["Cats and dogs",        [0.9, 0.1, 0.0]],
  ["Training a puppy",     [0.8, 0.1, 0.2]],
  ["Feeding your cat",     [0.6, 0.7, 0.0]],
  ["Pasta at home",        [0.0, 0.9, 0.1]],
  ["Robot chefs",          [0.1, 0.6, 0.8]],
  ["Rust for beginners",   [0.0, 0.0, 1.0]],
  ["GPS collars for dogs", [0.7, 0.0, 0.6]],
] {
  g.add_v("doc").property("title", d[0]).property("emb", d[1]).iterate();
}

// Like "Feeding your cat" (animals and food): ["Pasta at home", "Cats and dogs"]
g.v().has("title", "Feeding your cat").as("me").values("emb").as("q")
 .v().has_label("doc").where(P.neq("me"))
 .nearest("emb", __.select("q"), 2)
 .values("title").to_list()

Recommendations with vector_mean()

vector_mean() averages vectors, component by component. The mean of the documents a user liked is a "taste" vector; search with it among the documents the user has not liked yet:

g.set_schema(#{mode: "open", vertices: #{doc: #{schema: #{type: "object", properties: #{
  emb: #{type: "array", format: "vector", element: "f32", dimension: 3}}}}}});
for d in [
  ["Cats and dogs",        [0.9, 0.1, 0.0]],
  ["Training a puppy",     [0.8, 0.1, 0.2]],
  ["Feeding your cat",     [0.6, 0.7, 0.0]],
  ["Pasta at home",        [0.0, 0.9, 0.1]],
  ["Robot chefs",          [0.1, 0.6, 0.8]],
  ["Rust for beginners",   [0.0, 0.0, 1.0]],
  ["GPS collars for dogs", [0.7, 0.0, 0.6]],
] {
  g.add_v("doc").property("title", d[0]).property("emb", d[1]).iterate();
}
g.add_v("user").property("name", "sam").iterate();
for title in ["Cats and dogs", "Training a puppy"] {
  g.v().has("user", "name", "sam").as("u")
   .v().has("doc", "title", title).add_e("liked").from("u").iterate();
}

// Sam's taste: vector([0.85, 0.1, 0.1])
g.v().has("name", "sam").out("liked").values("emb").vector_mean().next();

// Recommended: ["GPS collars for dogs", "Feeding your cat"]
g.v().has("name", "sam").out("liked").values("emb").vector_mean().as("taste")
 .v().has_label("doc")
 .where(__.in("liked").has("name", "sam").count().is(0))
 .nearest("emb", __.select("taste"), 2)
 .values("title").to_list()

Quantization: smaller vectors

An f32 vector takes 4 bytes per component: 1.5 KiB for a 384-dimensional embedding. Declared with element: "i8" it takes 1 byte per component (plus 4 bytes for a scale), with almost the same search results (measured on the reference page). The schema's element wins on write: a list or an f32 vector written to an i8 property is quantized as it is stored, so the host keeps sending what its model gives it:

g.set_schema(#{mode: "open", vertices: #{doc: #{schema: #{type: "object", properties: #{
  emb: #{type: "array", format: "vector", element: "i8", dimension: 3}}}}}});
for d in [
  ["Cats and dogs",      [0.9, 0.1, 0.0]],
  ["Pasta at home",      [0.0, 0.9, 0.1]],
  ["Rust for beginners", [0.0, 0.0, 1.0]],
] {
  g.add_v("doc").property("title", d[0]).property("emb", d[1]).iterate();
}

// Stored as i8: vector([0.9, 0.0992126, 0.0], "i8"); an f32 query searches it.
g.v().has("title", "Cats and dogs").values("emb").next();
g.v().has_label("doc").nearest("emb", [1.0, 0.2, 0.0], 1).values("title").next()   // "Cats and dogs"

The same rule works against you when you quantize a property that is already declared as f32: set_schema/patch_schema to element: "i8" is refused while the stored vectors are still f32 (the schema would not fit the data), and a rewrite with quantize("i8") under the f32 declaration is turned straight back into an f32 vector. Switch the checks off for the migration, rewrite the values, then declare the new element:

g.set_schema(#{mode: "open", vertices: #{doc: #{schema: #{type: "object", properties: #{
  emb: #{type: "array", format: "vector", element: "f32", dimension: 3}}}}}});
g.add_v("doc").property("title", "Cats and dogs").property("emb", [0.9, 0.1, 0.0]).iterate();
g.add_v("doc").property("title", "Pasta at home").property("emb", [0.0, 0.9, 0.1]).iterate();

// 1. Mode "none": no checks, no conversion on write.
g.patch_schema(#{mode: "none"});
// 2. Rewrite every vector quantized.
g.v().has_label("doc").property("emb", __.values("emb").quantize("i8")).iterate();
// 3. Declare i8 and switch the checks on again: the data fits now.
g.patch_schema(#{mode: "open", vertices: #{doc: #{schema: #{properties: #{emb: #{element: "i8"}}}}}});

g.v().has_label("doc").values("emb").to_list().map(|v| v.element)   // ["i8", "i8"]

The playground runs a whole script as one unit, so a failure on the way leaves the graph as it was; from Python pass atomic=True to execute() for the same.

Real models: Model2Vec

A database can run a real, semantic text model itself: a Model2Vec static embedding model. Such a model keeps one vector per token and averages them for a text, so it needs no GPU and no neural network at run time: a small model like minishlab/potion-base-8M (256 dimensions, about 30 MB) embeds thousands of sentences per second on a laptop CPU, and it captures meaning, not only spelling ("car" and "automobile" come out close). It is less precise than a large transformer model, and much faster.

1. Download a model once. This is the only step that uses the network:

graphersal embed-model download minishlab/potion-base-8M               # English, small
graphersal embed-model download minishlab/potion-multilingual-128M     # 101 languages

It fetches config.json, tokenizer.json and model.safetensors from Hugging Face into the download cache ($GRAPHERSAL_EMBED_MODELS, else ~/.cache/graphersal/embed-models, on Windows %LOCALAPPDATA%\graphersal\embed-models; --dir overrides it), checks the SHA-256 Hugging Face states for the large file and the git blob id of the small ones, and writes a manifest graphersal-embed-model.json (repository, revision, the commit it resolved to, the files with their sizes and SHA-256). A failed or interrupted download leaves no model behind. --revision <branch|tag|commit> pins a version; HF_TOKEN is sent for gated or private repositories. graphersal embed-model list shows what is there:

── Downloaded model ──────────────────────────────────────────────────────────
  model:     minishlab/potion-base-8M
  full name: model2vec/minishlab/potion-base-8M@fac4fa854e68
  size:      29.5 MiB
  licence:   mit

Which model. All three below are MIT licensed Model2Vec models of 256 dimensions from MinishLab; copy the repository name into the command above.

RepositorySizeTrained forUse it when
minishlab/potion-base-8Mabout 30 MBEnglish texttexts and questions are in English, and size or start time matters
minishlab/potion-multilingual-128Mabout 510 MB101 languages (distilled from BAAI/bge-m3)texts or questions come in several languages, for example English documentation searched with questions in Russian or German
minishlab/potion-code-16M-v2about 32 MBEnglish questions against source code (Python, Java, JavaScript, Go, PHP, Ruby)questions are English and the texts are code itself, not prose about it

For a knowledge base about software (documentation, decisions, descriptions of code) queried in more than one language, take potion-multilingual-128M: a model trained on English only places a question in another language far from every document, so it finds nothing useful, while a multilingual model maps the same meaning in different languages close together. A static model is less precise across languages than within one; combining the vector search with a word match on names (has with TextP.containing) covers exact identifiers. The larger model costs memory for as long as it is loaded (about its file size).

2. Import it into the database. A model serves a database only once it is imported into it: the import puts the model's files into the store as one blob with a catalog entry, so the store carries its model wherever it is copied. --default makes it the model embed() uses without #{embedder: ..}:

graphersal store create kb
graphersal embed-model import minishlab/potion-base-8M --into kb --default
graphersal --graph kb \
  -e 'g.patch_schema(#{vertices: #{doc: #{schema: #{type: "object", properties: #{emb: #{type: "array",
        format: "vector", embedder: "minishlab/potion-base-8M", from: "text"}}}}}});
      g.add_v("doc").property("text", "a graph database stores vertices and edges")
        .add_v("doc").property("text", "banana bread recipe with walnuts")
        .add_v("doc").property("text", "traversal queries over a network of nodes").iterate()'
graphersal --graph kb \
  -e 'g.v().has_label("doc").nearest("emb", "how do I query connected data?", 2).values("text").to_list()'

The vector rule (from: "text") fills and refreshes doc.emb with the store's model at every write; the schema records the model's identity for doc.emb, so the text query needs no embedder: it uses that model.

"traversal queries over a network of nodes"
"a graph database stores vertices and edges"

The import takes the model from the download cache (or a model directory given as a path) and loads it once as a check; the store loads it again when a query or a vector rule first needs it (a model the schema needs loads when the store opens). The built-in hash-ngram/1 stays beside it. g.embedders() lists both by repository, GET /api/info of the dev server too. embed("text", #{embedder: "minishlab/potion-base-8M"}) names a model of the database.

What leaves the machine. Only the explicit embed-model download: it connects to https://huggingface.co (or the mirror in $GRAPHERSAL_HF_ENDPOINT). Loading and running a model is local: no text is sent anywhere.

Model identity. Each embedder reports a model identity (g.embedders(), field model): model2vec/<repo>@<12 hex digits>, the start of a SHA-256 over the model's three files (without a manifest model2vec@<12 hex digits>). It names the model, never a path: a copied or moved model directory keeps it, a changed file gets another one. Vectors are comparable only between embedders of the same identity, so embed documents and questions with the same model. A vector rule naming a model of the Store by its repository stores the identity in the schema itself. To declare a vector property by hand, copy the full identity, hash included, from graphersal embed-model list or g.embedders(): a schema naming a model without its hash matches no embedder (the error shows the full identity of the one you tried), so a changed model file can never quietly mix its vectors with the old ones.

Licences. A model's licence is the model's own, set by whoever published it (see its Hugging Face page); Graphersal downloads and runs it but does not license it. potion-base-8M is MIT licensed. A download keeps the model card (README.md), the repository's licence files and the licence id beside the model, and warns about an unknown or non-commercial licence or a gated repository; embed-model list shows the licences.

A model inside a store. graphersal embed-model download minishlab/potion-base-8M --into data/ downloads and imports in one step. Every copy of the store (backup, fork, export to a .gsnap) carries its models with their licences; a .gsnap file serves them even without a store (--graph file.gsnap). From Python: store.import_model("minishlab/potion-base-8M") (see Embedding Models in a Store).

Changed in 0.5.0: the command line flags --embedder/--default-embedder, the Python graphersal.Embedder/graphersal.Model2Vec and the Rust embedder registry (graphersal::vector::Embedders, Model2Vec, with_embedders) are removed: the models a database uses are imported into it. A host with a model of its own computes the vectors itself and writes them as values (below).

With real embeddings (Python)

With a real model the steps stay the same; only the vectors get longer. This example uses sentence-transformers and the small model all-MiniLM-L6-v2, which gives 384 numbers per text and runs on a laptop CPU (pip install graphersal sentence-transformers):

import graphersal
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")      # 384 dimensions

graph = graphersal.Graph()
graph.set_schema({
    "mode": "open",
    "vertices": {
        "chunk": {"schema": {"type": "object", "properties": {
            "text": {"type": "string"},
            "emb": {"type": "array", "format": "vector", "element": "f32",
                    "dimension": 384, "metric": "cosine"},
        }}},
    },
})

# The host's data: documents cut into chunks, plus the topics each document mentions.
docs = [
    {"title": "Cat care", "topics": ["pets", "health"], "chunks": [
        "Cats need fresh water every day.",
        "Most adult cats do well on two meals a day.",
    ]},
    {"title": "Weeknight pasta", "topics": ["cooking"], "chunks": [
        "Salt the pasta water generously.",
    ]},
]

for doc in docs:
    graph.execute('g.add_v("doc").property("title", title).iterate()', params={"title": doc["title"]})
    for topic in doc["topics"]:
        graph.execute(
            'g.merge_v(#{"T.label": "topic", name: topic}).as("t")'
            '.v().has("doc", "title", title).add_e("mentions").to("t").iterate()',
            params={"title": doc["title"], "topic": topic},
        )
    embs = model.encode(doc["chunks"])               # numpy float32, shape (n, 384)
    for text, emb in zip(doc["chunks"], embs):
        graph.execute(
            'g.v().has("doc", "title", title).as("d")'
            '.add_v("chunk").property("text", text).property("emb", emb)'
            '.add_e("part_of").to("d").iterate()',
            params={"title": doc["title"], "text": text, "emb": emb},
        )

A one-dimensional float32 numpy array passed in params arrives in the script as an f32 vector (so does a graphersal.Vector(values), built from a list or a buffer); the extension reads it through memoryview and does not depend on numpy. A list in params is not supported: wrap it in graphersal.Vector(..).

The search embeds the question with the same model and passes it as a parameter:

question = "How often should I feed my cat?"
q = model.encode(question)

hits = graph.query("""
    g.v().has_label("chunk").nearest("emb", q, 3)
     .project("text", "score")
       .by("text")
       .by(__.similarity("emb", q))
     .to_list()
""", params={"q": q})
# a list of dicts, best first: [{'text': '...', 'score': ...}, ...]

GraphRAG from Python

The context for the language model is the hits plus what the graph knows about them, in one query:

rows = graph.query("""
    g.v().has_label("chunk").nearest("emb", q, 3)
     .project("text", "doc", "topics")
       .by("text")
       .by(__.out("part_of").values("title"))
       .by(__.out("part_of").out("mentions").values("name").fold())
     .to_list()
""", params={"q": q})

context = "\n".join(f"[{r['doc']}; topics: {', '.join(r['topics'])}] {r['text']}" for r in rows)
prompt = f"Answer from this context only.\n\n{context}\n\nQuestion: {question}"
# send `prompt` to the language model of your choice

To let an AI agent (an MCP client or the playground's AI Chat on the dev server) run the search itself, store it as a saved query whose parameter is the vector; the agent still needs the question's embedding from a tool of the host:

graph.define_query({
    "name": "semantic_search",
    "params": {
        "q": {"schema": {"type": "array", "format": "vector", "dimension": 384}},
        "k": {"schema": {"type": "integer"}, "default": 5},
    },
    "body": 'fn semantic_search(q, k) { g.v().has_label("chunk").nearest("emb", q, k).values("text") }',
})
graph.call_query("semantic_search", {"q": graphersal.Vector(q), "k": 2})

With a Model2Vec model imported into a store and declared in the schema for the documents' vectors (its embedder, best as a vector rule), the parameter can be the question itself: nearest("emb", question, k) with params: {"question": "string"} embeds it with that model, so the agent needs no embedding tool at all (Embedding Models in a Store). A model the database does not keep, like the sentence-transformers model above, stays with the host: it computes the vectors and passes them in.

Any model works. OpenAI, Cohere, Ollama or a model of your own: an embedding is just a list of numbers. Keep the schema's dimension equal to the model's, embed documents and questions with the same model, and pick the metric the model is meant for (most text models: cosine).

Sizing and performance

nearest() scores every element it receives, with no index to build or keep up to date, so its time grows with the number of vectors times the dimension. The measured numbers (10 000 vectors of 384 dimensions) show that this is fast enough for most in-memory graphs; a filter before the search scores fewer, and an i8 property takes a quarter of the memory. There is no approximate (ANN) index yet (Current Limitations).

Where to go next

  • Vectors: the reference: element kinds, metrics, similarity(), nearest(), vector_mean(), quantization, formats.
  • Schema Enforcement: declaring properties, modes and migrations.
  • Python Quick Start: the Python API.
  • Saved Queries: searches that hosts, MCP clients and the AI Chat call by name.
  • The playground's Examples ▾ menu has a group "Embeddings (vectors)" with these queries.

Library Features

This page is about the Rust crate; the command-line tool and the Python package are on Installation.

Library

Graphersal is primarily provided as a library and can be easily incorporated into your Rust project by adding it as a dependency.

To include Graphersal as a dependency in your Rust project's Cargo.toml file, refer to the following example:

[dependencies]
graphersal = "0.8"

Supported Features

Graphersal comes with the several key features.

FeatureDescription
ioReads and writes graph files: GraphSON 3.0 (TinkerPop's format; values keep their types, dates and other types Graphersal cannot hold are skipped with a report) and GraphML. GraphML values are written as their plain text (a UUID as its canonical string, arrays and objects as JSON text); logical types (uuid, array, object) are restored on import only from the schema stored in the target graph, so set the schema first. GraphML never carries the schema; it travels as its own JSON.
serdeConverts between plain JSON and Graphersal values (a UUID is written as its canonical string), and reads/writes schema files.
scriptGraphersal also supports a Domain Specific Language (DSL) for scripting based on the Rhai library. The math() step does not need it: its equations run on Graphersal's own expression engine in every build (see Math Expressions).
gqlGQL queries (experimental): GraphTraversalSource::gql / gql_with run ISO GQL queries (MATCH ... WHERE ... RETURN ..., INSERT, SET, REMOVE, DELETE, Cypher's MERGE, Cypher spellings as aliases) as ordinary traversals; with script also g.gql(..) in the DSL. No dependencies.
persistGraphersal's own lossless binary format: packed snapshots (.gsnap), a write-ahead journal with recovery, and the Store (one directory or one .gstore file = one graph, durable commits, point in time, fork, rollback, backups, repair). See Persistence.
persist-zstdzstd-compressed snapshot chunks on top of persist (pure Rust).
persist-zipZIP backup archives of a Store on top of persist.
model2vecThe engine can run the Model2Vec embedding models kept in a database (imported into a Store or carried by a .gsnap), through model2vec-rs and tokenizers (pure Rust); no public item. Native targets only; the graphersal CLI and the Python wheel have it on. Without it a store keeps and copies its models but cannot run them.

CLI Application and Python

The command-line tool graphersal (prebuilt binaries, cargo binstall, cargo install graphersal-cli) and the Python package are on Installation. Every command of the tool is on the Command Cheat Sheet.

WEB Playground

Graphersal also runs in the browser: the web playground is a static page with the engine compiled to WebAssembly, so there is nothing to install on a server. Build it from the repository with playground/build.sh and serve the playground/ directory, as described in the WEB Playground chapter.

Command Cheat Sheet

Every command you need to build, run and operate Graphersal, ready to copy, each with one line of explanation. Run them from the root of a checkout of the repository. Every command on this page was run against the built binary; when the binary says something else, the binary is right and this page is wrong.

The examples write graphersal for the binary. After a debug build it is target/debug/graphersal, after a release build target/release/graphersal; put one of them on your PATH or type the path.

Build

cargo build -p graphersal-cli                 # debug build: target/debug/graphersal
cargo build -p graphersal-cli --release       # optimized build: target/release/graphersal
target/debug/graphersal --version             # check what you built
playground/build.sh                           # the WebAssembly playground into playground/pkg/

playground/build.sh needs two one-time installs: rustup target add wasm32-unknown-unknown and cargo install --locked wasm-bindgen-cli --version 0.2.129 (it must equal the wasm-bindgen crate version). wasm-opt (binaryen) is optional and makes the module smaller.

The web playground (WebAssembly, in the browser)

python3 playground/serve.py 8000              # open http://localhost:8000/

serve.py is a static file server that sends Cache-Control: no-store. Plain python3 -m http.server sends no cache headers, so after a rebuild the browser keeps running the old JavaScript modules and the old engine worker. If the page hangs after a reload, open http://localhost:8000/reset/ (it clears the playground's saved state). See WEB Playground.

One-shot queries and the REPL

graphersal                                                       # the REPL on the modern graph
graphersal --graph empty                                         # the REPL on an empty graph
graphersal -e 'g.v().has_label("person").values("name").to_list()'   # run, print, exit
graphersal -e 'let xs = g.v().to_list()' -e 'xs.len()'           # -e repeats and shares one scope
echo 'g.v().values("age").max().next()' | graphersal --in --graph modern   # the script from stdin
printf '/help has_label\n' | graphersal --repl                   # the REPL on a piped stdin (scripted sessions)

Embedding models (Model2Vec; the download is the only network access, a model runs locally):

graphersal embed-model download minishlab/potion-base-8M          # into $GRAPHERSAL_EMBED_MODELS or ~/.cache/graphersal/embed-models
graphersal embed-model download minishlab/potion-multilingual-128M   # 101 languages: questions in another language than the texts
graphersal embed-model download minishlab/potion-base-8M --revision v1.0 --dir ./models   # a pinned revision, another directory
graphersal embed-model list                                        # repository, size, licence, model identity
graphersal embed-model download minishlab/potion-base-8M --into data/   # download and import into the Store data/
graphersal embed-model import minishlab/potion-base-8M --into data/ --default   # from the download cache (no network), the default model
graphersal embed-model import ./my-model --into data/ --repo acme/my-model   # a local model directory into a Store
graphersal embed-model import minishlab/potion-base-8M --into data/ --replace   # a new revision replaces the old one
graphersal store models default data/ minishlab/potion-base-8M     # the model embed() uses without a name (--none clears it)
graphersal --graph data/ -e 'embed("graph databases")'              # the store's default model
graphersal --graph data/ -e 'g.v().embed("name", #{embedder: "acme/my-model"}).to_list()'   # a model by its repository
graphersal --graph export.gsnap -e 'g.embedders()'                  # a .gsnap serves the models it carries

In the REPL a script runs when its input ends with ;. Commands start with / (an input starting with : gets a pointer to its / form); Tab completes steps, token values (P., Order., T., ...), commands and their arguments, in the session spelling. Completion and help read the same catalogue as the playground's query editor: the engine's own function docs.

CommandWhat it does
/helpthe commands, grouped
/help <name>the doc of a step, function, token class or command in either spelling, with its overloads and an example with its result (/help has_label, /help hasLabel, /help P.eq, /help Order)
/help steps, /help tokensevery step and terminal; the token classes with their values
/set format <fmt>the default visualizer
/set max-rows <n>, /set max-items <n>, /set no-limitthe display limits
/set spelling <snake|camel>the spelling of completion, help, .profile() and errors
/set max-operations <n>, ..., /set safe-limitsthe script limits (/help set lists them)
/memory [delta] [max_elements]the process memory bar (used of the ceiling, its source, the percentage, the segments), then the graph's memory report per label and property (with delta: only a layer's own elements, the base counted as shared; with a number: sampled)
/schema [label ...]the schema summary: labels with counts, keys with types, edge from->to pairs, indexes, schema mode; with labels: those labels in detail
/exit (or Ctrl-D)close the graph and leave

--graph takes:

SourceWhat it is
modernTinkerPop's "modern" sample graph (the default)
emptyan empty graph
largea generated graph of about 110k vertices and 110k edges
treea file-tree sample (37 vertices) for glob_path
g.json, g.jsonl, g.graphsona GraphSON file (GraphSON)
g.xml, g.graphmla GraphML file
g.gsnapa packed snapshot
data/, g.gstorea Store: opened read-write, every commit is durable
graphersal -e 'g.export_snapshot("m.gsnap")'                    # save the graph as a packed snapshot
graphersal --graph m.gsnap -e 'g.v().count().next()'             # and load it
graphersal -e 'g.export_graphson("m.json")'                      # GraphSON (TinkerPop's g.io() format)

A graph file carries no schema; --schema brings one (the schema format):

graphersal --graph g.graphml --schema schema.json -e 'g.v().count().next()'   # schema first, then the file imported against it
graphersal --graph g.json --schema schema.json --schema-mode closed           # --schema-mode overrides the file's "mode"
graphersal --graph modern --schema schema.json                                # a sample graph: the schema is applied (validated)

The schema is set on the new empty graph first and the file is imported as one unit, so declared logical types (uuid, array, object) come back and an open/closed mode is enforced. Data that violates the schema stops the start with exit code 1 and the violation report; an unreadable or invalid schema file, an unknown --schema-mode, and --schema with a Store or a .gsnap (both carry their own schema) are exit code 2.

Saved queries (stored in the database, called by name; a query whose body writes data writes as one transaction; see Saved Queries):

graphersal -e 'g.define_query(#{name: "people", body: "fn people() { g.v().has_label(\"person\") }"})' \
           -e 'g.query("people").values("name").to_list()'    # define, then call and continue
graphersal -e 'g.queries()'                                       # list (also g.queries("folder"), g.get_query(name))

Display (a result without a data terminal is rendered; to_list()/next() are never cut; iterate() runs for the side effects and shows nothing):

graphersal -e 'g.v().has_label("person").values("name")' --format json   # auto, table, markdown, json, jsonschema, mermaid, plantuml, tree
graphersal -e 'g.v()' --max-rows 2            # at most 2 rows (default 100); --max-items N for nested items
graphersal -e 'g.v().values("name")' --no-limit
graphersal --spelling camel -e 'g.v().has_label("person").count().profile()'   # Gremlin spelling in profiles and errors

Limits (scripts run without limits by default; see Resource Limits):

graphersal --graph large --timeout 50 -e 'g.v().out().out().out().out().count().next()'  # 50 ms per traversal and script
graphersal --memory-limit 2000000000 -e 'g.v().count().next()'  # process memory ceiling in bytes (default auto: cgroup limit minus headroom, else 80 % of RAM)
graphersal --memory-limit none -e 'g.v().count().next()'        # no process memory ceiling
graphersal --safe-limits -e 'g.v().count().next()'               # the library's SAFE script limits
graphersal --max-operations 1000 -e 'let n = 0; loop { n += 1; }' # stops with "Resource limit 'script.max_operations'"
graphersal --max-traversers 1000000 --max-value-depth 64 -e 'g.v().count().next()'  # also --max-string-size, --max-array-size, --max-map-size, --max-materialized-bytes

Exit codes: 0 ok, 1 the script failed (diagnostic on stderr), the --graph data violates the --schema, or a --graph <store> cannot be opened (in use by another writer, ...), 2 invalid invocation (unknown option, a graph or schema file that cannot be loaded), 141 stdout was closed before every result was written (graphersal -e '..' | head -1: the run stops quietly; a failing script keeps its own code; the same for graphersal store). A closed stdout or stderr is never a crash: the dev server keeps serving when its log reader goes away. graphersal --help lists every option.

The dev server

DEV mode, unstable, local only (127.0.0.1 unless --host or a container says otherwise, no authentication). It serves the playground UI with this process as the engine. Details: Dev Server and MCP.

graphersal --graph modern --server                       # http://127.0.0.1:8080/
graphersal --graph ./mygraph.json --server --port 9000   # any --graph source; "Save to file" writes it back
graphersal --graph large --server --port 0               # 0 picks a free port (the address is printed on stdout)
graphersal --graph modern --server --host 0.0.0.0        # every interface: reachable from the network, NO authentication
graphersal --graph data/ --server                        # a Store: every commit is durable, the Store menu appears
graphersal --graph new/ --create-store --server          # create the store when it does not exist
graphersal --graph g.graphml --schema schema.json --server   # a graph file loaded against its schema
graphersal --graph large --server --timeout 5000 --memory-limit auto   # limits apply to every query
graphersal --graph modern --server --ui-dir ~/src/graphersal/playground # its files win over the embedded UI
graphersal --graph modern --server --ui-profile demo   # the pages show another UI profile (EXPERIMENTAL)
graphersal --graph export.gsnap --server                  # a .gsnap: the models it carries serve every query (in memory)
graphersal --graph db.gstore --read-only --server --mcp --mcp-read-only   # every write refused; the store is not written
graphersal health                                        # exit 0 when http://127.0.0.1:8080/healthz answers 200
graphersal health --ready --port 9000                    # /readyz: 503 while loading or stopping
curl -s http://127.0.0.1:8080/healthz                    # {"status":"ok"} (any Host header, no lock)
docker build -t graphersal . && docker run --rm -p 127.0.0.1:8080:8080 -v "$PWD/db.gstore:/data/graph.gstore:ro" graphersal

Stop it with Ctrl+C or SIGTERM (docker stop, also as PID 1): a running query is cancelled and an open store is closed cleanly (exit code 0). A second Ctrl+C exits at once. The display options (--format, --max-rows, ...) and -e/--in are refused with --server (exit 2).

MCP: an AI agent on the same graph

graphersal --graph modern --server --port 9000 --mcp                    # MCP endpoint http://127.0.0.1:9000/mcp
graphersal --graph modern --server --port 9000 --mcp --mcp-read-only    # the agent may only read
graphersal --graph modern --server --port 9000 --mcp --mcp-token my-secret-token   # the agent must send the token
graphersal --graph data/ --server --port 9000 --mcp --mcp-query-tools  # also every saved query as a tool of its own
graphersal --graph data/ --server --mcp --mcp-instructions notes.md      # operator notes in the MCP instructions
graphersal --graph data/ --server --mcp --mcp-max-chars 30000           # the largest MCP tool answer (default 60000)
graphersal --args-file args.json                                         # the flags from a JSON file (also @args.json)

Connect Claude Code (the server must be running; then start a NEW claude session):

claude mcp add --transport http graphersal http://127.0.0.1:9000/mcp
claude mcp add --transport http graphersal http://127.0.0.1:9000/mcp --header "Authorization: Bearer my-secret-token"
claude mcp list                    # graphersal: http://127.0.0.1:9000/mcp (HTTP) - Connected
claude mcp remove graphersal       # when you are done, or before adding it again on another port

AI Chat in the playground (EXPERIMENTAL)

export ANTHROPIC_API_KEY=...                                   # the variable the file names; the key stays in the server
graphersal --graph modern --server --ai ai.json                # "+" in the Query panel -> AI Chat
graphersal --graph modern --server --ai crates/graphersal-cli/examples/ai-ollama.json   # a local model: no data leaves the machine
GEMINI_API_KEY=... graphersal --graph modern --server --ai crates/graphersal-cli/examples/ai-google.json   # Google Gemini (OpenAI-compatible endpoint)

ai.json: {"provider": "anthropic"|"openai", "model": "<id>", "api_key_env": "<VARIABLE>", "base_url": null, "read_only": false, "max_tool_calls_per_turn": 20, "max_tokens": 4096}. Details: AI Chat.

The Store

A Store is one directory (or one .gstore file) that keeps one graph durable. Reference: The graphersal store Command. TARGET below is one of --at-commit N, --at-time 2026-10-08T02:43:00Z (RFC 3339 with a zone, or microseconds since the epoch) or --at-mark NAME.

graphersal store create data/ --from modern          # a new store (or: --from empty|large|tree|FILE|FILE.gsnap)
graphersal store create graph.gstore --from modern   # a single-file store (or: --single-file)
graphersal store create data/ --on-damage continue   # keep committing when damage is found while open (fixed at creation)
graphersal --graph data/ -e 'g.add_v("person").property("name", "zoe").to_list()'   # a durable commit
graphersal --graph data/                             # the REPL on the store (--server: the dev server)
graphersal store mark data/ before-import            # name the current position
graphersal --graph data/ -e 'g.add_v("person").property("name", "ada").to_list()'
graphersal store info data/                          # identity, position, snapshots, marks, WAL size
graphersal store list data/                          # the snapshots
graphersal store marks data/                         # the marks
graphersal store checkpoint data/ --name nightly     # write a snapshot now
graphersal store verify data/                        # scrub every checksum (exit 1 on damage)
graphersal store journal data/ --level warn          # the system journal: what the store did
graphersal store fork data/ branch/ --at-mark before-import          # a past state as a new store
graphersal store fork data/ branch2/ --at-time 2026-10-08T02:43:00Z  # or --at-commit N
graphersal store backup data/ /mnt/backup/data       # full the first time, incremental afterwards
graphersal store backup data/ weekly/ --full         # always full (the directory must be empty)
graphersal store backup data/ data.zip --zip         # a full backup as one ZIP archive
graphersal store backup data/ data.zip --zip --without-models   # ... without the embedding models
# every backup checks every checksum in the store and in the copy; damage stops it (repair the STORE)
# a damaged store open in the dev server: Store menu > Back up from memory (POST /api/store/backup {"from_memory": true})
graphersal store export data/ data.gsnap             # the latest snapshot as a .gsnap (--commit N: another)
graphersal store export data/ data.gsnap --without-models   # ... without the store's embedding models
graphersal store models data/                        # the embedding models the store keeps, with licences
graphersal store models default data/ <repo>         # the default model (--none clears it; a commit)
graphersal store models remove data/ <repo>          # remove one (a commit)
graphersal store rollback data/ --at-mark before-import   # back IN PLACE; the rest goes to the attic
graphersal store attic data/                         # the attic entries (rolled-back history), with their <ID>
graphersal store attic data/ changes <ID>            # the commits of an entry
graphersal store attic data/ fork <ID> rolled-back/  # keep the rolled-back history as a new store
graphersal store attic data/ restore <ID>            # undo the rollback
graphersal store attic data/ remove <ID>             # or: delete an entry for good
graphersal store rollback data/ --at-commit 0 --delete    # back in place, deleting the rest (no undo)
graphersal store restore /mnt/backup/data            # make a backup the live store (same graph id)
graphersal store restore data.zip restored/          # unpack a ZIP backup as the live store
graphersal store prune data/ --up-to 1200            # remove history only needed before commit 1200
graphersal store compact-advice data/                # is compact worth it now? (cheap)
graphersal store compact data/                       # prune to now; a single file gives its free space back
graphersal store compact data/ --drop-marks          # ... also when marks become unreachable (refused without)
graphersal store convert data/ data.gstore           # a closed store into one file (or back)
graphersal store upgrade old/ new/                   # a store of Graphersal 0.1.x-0.4.x into the current format (or: old/ --in-place)
graphersal store repair damaged/ --to repaired/      # a damaged store, repaired into a new directory
graphersal store restore-blobs data/ --from /mnt/backup/data  # missing or damaged blobs (models) back from a copy
graphersal store repair data/ --to repaired/ --drop-damaged-blobs  # a copy without what references lost blobs
graphersal store rollback --help                     # the usage of one command (or: store help rollback)

Migrate a store from an older format

A store written by an older Graphersal is refused with The store ... has the older format version N (nothing is changed); the error's help names the command. A store of a released version (2: Graphersal 0.1.x) is upgraded by THIS binary, no older one needed, with everything carried (graph, schema, catalog, history, marks, attic, identity):

cp -R old_store/ old_store.bak/                       # optional: keep the older store as it is
graphersal store upgrade old_store/ new_store/       # into a new store (old_store/ unchanged), verified
graphersal store upgrade old_store/ --in-place       # or the store itself
graphersal store upgrade old_backup/ new_backup/     # a backup directory stays a backup
graphersal store restore old_backup.zip new_store/   # a ZIP backup is upgraded as it is restored
graphersal store repair damaged_old/ --to new_store/ # a DAMAGED older store: repaired into the current format

A store of store format version 1 (a pre-release, before the store id) moves through a packed snapshot instead: export it with the OLD binary (the store closed), create a new store from the file with the new one:

old/graphersal --graph old_store/ -e 'g.export_snapshot("graph.gsnap")'   # the OLD binary: the current state
graphersal store create new_store/ --from graph.gsnap                     # this binary (or new.gstore: one file)
graphersal store verify new_store/                                        # then back it up

The new store has the graph, its schema and its catalog (saved queries, compression rules), with the same element ids and commit position, but it is a new store: the marks, the attic (rolled-back history) and the backups of the old store are not carried. old/graphersal store export old_store/ graph.gsnap exports the latest stored SNAPSHOT only (run old/graphersal store checkpoint old_store/ first to include the WAL). Keep the old store until the new one is verified and backed up. A .gsnap written by 0.1.x loads in this build as it is.

Python

import graphersal
graph = graphersal.Graph.tinkerpop_modern()
graph.save("g.gsnap")                                   # a packed snapshot
graph = graphersal.Graph.load("g.gsnap")
with graphersal.Store.create("data") as store:          # or Store.open("data"); "g.gstore": one file
    store.graph.execute('g.addV("person").property("name", "ann").next()')   # durable
    store.mark("after-ann"); store.checkpoint("nightly"); store.backup("bk")

More: Python and bindings/py-graphersal/README.md.

Tests and checks (contributors)

The full list of build, test, lint, coverage, fuzzing and wasm commands, with the acceptance feature set, is in CLAUDE.md (section "Commands") at the root of the repository; the Python binding's in bindings/py-graphersal/README.md, the playground's in playground/README.md.

Why a Graph?

Many questions are about connections: who knows whom, what depends on what, which path leads from here to there. A graph stores the connections themselves, so such a question is answered by walking along them instead of reconstructing them.

Questions a graph answers well

  • Networks of people and things. Friends of friends, colleagues who worked on the same project, customers who bought what similar customers bought.
  • Dependencies and impact. Which services break when this database goes down? Which packages pull in this library, directly or through ten others? Which documents cite this one?
  • Infrastructure and inventory. Servers, networks, accounts and owners, and how they are wired together: "which public endpoints can reach this host?".
  • Hierarchies and trees. Directories, organisational charts, bills of materials: every part below this one, at any depth.
  • Paths. The shortest or every route between two things; cycles that should not exist.
  • Knowledge. Facts as connected entities, the context an AI agent retrieves before answering (the graph behind "GraphRAG").

Connections as data

Take a small social graph: people are friends with people and like movies.

People, friendships and movies

Which people have a friend of a friend who likes "Terminator"? In Gremlin the question reads like a walk through the picture:

g.v().has_label("person").as("person")   // start at every person, remember it
  .repeat(__.out("friends")).times(2)    // follow "friends" twice
  .out("likes").has("title", "Terminator")
  .select("person")                      // back to the person we started from
  .dedup()
  .values("name")

In a relational database the same question needs a self-join of the friendship table for every hop, and the number of hops is fixed in the SQL text:

SELECT DISTINCT p.name
FROM person p
JOIN friends f1 ON f1.from_id = p.id
JOIN friends f2 ON f2.from_id = f1.to_id
JOIN likes   l  ON l.person_id = f2.to_id
JOIN movie   m  ON m.id = l.movie_id
WHERE m.title = 'Terminator';

"Up to five hops" or "any depth" makes the SQL much harder (recursive common table expressions), while the traversal only changes times(2) into times(5) or into an until(...) condition.

Why it is fast

A graph engine keeps, with every vertex, the list of its edges. Following an edge is a direct step to the neighbour, not a lookup in an index of the whole table, so the cost of a traversal grows with the part of the graph it actually touches, not with the size of the data set. That is why deep or recursive questions stay cheap on a graph and become expensive as joins.

The reverse holds too: a graph is not the best tool for everything. Aggregations over millions of rows of the same shape ("total revenue per month") are what relational and columnar databases are built for. Graphersal is an in-memory engine, so a graph has to fit into memory; see Current Limitations.

Next

The Property Graph Model introduces vertices, edges, labels and properties, and Gremlin in Ten Minutes the steps of a traversal.

The Property Graph Model

Graphersal stores a property graph, the model of Apache TinkerPop and most graph databases.

The TinkerPop "modern" graph

This is the "modern" sample graph that ships with TinkerPop and with Graphersal (--graph modern, GraphSource::tinkerpop_modern()). It has the four building blocks of the model:

  • Vertices are the things: here four people and two pieces of software. Every vertex has an id ("1" is marko).
  • Edges are the connections. An edge has a direction, from its out vertex to its in vertex: marko knows josh, josh created ripple. An edge has an id too.
  • Labels say what kind of thing a vertex or an edge is: person, software, knows, created. Queries usually start by label.
  • Properties are key-value pairs on vertices and on edges: a person has a name and an age, a piece of software a name and a lang, an edge a weight.
$ graphersal -e 'g.v("1").element_map()'
╭─────┬────┬────────┬───────╮
│ age │ id │ label  │ name  │
├─────┼────┼────────┼───────┤
│ 29  │ 1  │ person │ marko │
╰─────┴────┴────────┴───────╯

Values

A property value is a string, a 64-bit integer, a 64-bit float, a boolean, null, a UUID, a date or time (Dates and Times), a vector (Vectors), an array or an object (a nested map). Arrays and objects can be nested, and steps reach inside them with path keys such as jpath("address.city") (Path Keys). Values keep their type: a string that looks like a number or a date stays a string unless a schema declares otherwise.

Graphersal additions

  • A vertex can carry several labels (person and employee); the first one is its primary label, which label() returns as TinkerPop does (Multi-Label Vertices).
  • A graph can have a schema: the labels, their properties and types, and which edges may connect which labels, enforced on every write (Schemas).
  • A graph keeps a catalog of named definitions next to the data, such as saved queries (Saved Queries).

No database server

A Graphersal graph lives in the memory of the process that uses it: your Rust program, the Python interpreter, the browser tab or the graphersal command line tool. There is no separate database server to run. When the graph must survive the process, the Store keeps it on disk (Persistence Overview).

Gremlin in Ten Minutes

Gremlin describes a query as a traversal: a chain of steps that traversers flow through. Each traverser sits on a vertex, an edge or a value; a step moves it, filters it out, turns it into something else or combines many of them. All examples run on the "modern" graph (The Property Graph Model): Run in the playground under a block opens it in the playground, or pass it to graphersal -e.

Start, filter, walk

g is the graph. v() starts one traverser on every vertex, has_label and has keep the ones that match, values turns each into a property value:

g.v().has_label("person").values("name")          // marko, vadas, josh, peter
g.v().has_label("person").has("age", P.gt(30)).values("name")   // josh, peter

out(label) walks along outgoing edges, in(label) along incoming ones, both(label) along either:

g.v().has("name", "marko").out("knows").values("name")                  // josh, vadas
g.v().has("name", "marko").out("knows").out("created").values("name")   // ripple, lop

Edges are elements too: out_e steps onto the edges, in_v to their far end, and an edge can be filtered by its properties on the way:

g.v().has_label("person").out_e("created").has("weight", P.gte(0.5)).in_v().values("name")   // ripple

Remember and come back

as("x") names a position of the walk; select, where and path read it later:

// who created software together with marko?
g.v().has("name", "marko").as("me")
  .out("created").in("created")
  .where(P.neq("me"))
  .values("name")                                  // peter, josh
g.v().has("name", "marko").out("created").in("created").path().by("name")
// [marko, lop, peter], [marko, lop, josh], [marko, lop, marko]

Group, count, order

Some steps need the whole stream before they answer: count, group, order, dedup. by(...) modulates the step before it, and __. starts an anonymous traversal that runs for each element:

g.v().count()                                                           // 6
g.v().has_label("person").order().by("age", Order.desc).values("name")  // peter, josh, marko, vadas
g.v().has_label("person").group().by("name").by(__.out("created").count())
// {josh: 2, marko: 1, peter: 1, vadas: 0}

Loops

repeat runs a traversal again and again, times(n) or until(condition) stops it, and emit() also yields the steps in between:

// a path from peter to vadas, in either direction along the edges
g.v().has("name", "peter")
  .repeat(__.both().simple_path()).until(__.has("name", "vadas"))
  .path().by("name").limit(1)                      // [peter, lop, marko, vadas]

Results

A traversal without a final step is displayed (a table in the command line and the playground). In code, a terminal step returns the data: to_list() all results, next() the first one, iterate() runs it for its side effects only.

let names = g.v().has_label("person").values("name").to_list();   // a list
let marko = g.v().has("name", "marko").next();                     // one vertex
names.len()                                                        // 4

Changing the graph

add_v, add_e, property and drop write. Every traversal is one unit: when any step fails, nothing it wrote stays.

g.add_v("person").property("name", "ann").property("age", 41).as("a")
  .v().has("name", "marko").add_e("knows").to("a")
  .iterate();
g.v().has("name", "marko").out("knows").values("name")   // ann, josh, vadas

Two spellings

Every TinkerPop step has a snake_case name and its Gremlin camelCase twin, so a query copied from TinkerPop documentation runs as it is (with double quotes for strings); Graphersal's own extensions are snake_case only:

g.V().hasLabel("person").outE("created").has("weight", P.gte(0.5)).inV().values("name")

Next

Graphersal and TinkerPop

Apache TinkerPop™ defines the property graph model and the Gremlin language that many graph databases implement. Graphersal is an independent implementation in Rust: it does not use TinkerPop's Java code, and it is not a Gremlin Server, so a TinkerPop driver does not connect to it. What it shares with TinkerPop is the language and its meaning.

Same meaning, checked by TinkerPop's own tests

The rule is simple: a step that Graphersal implements behaves as the TinkerPop specification says, unless a difference is documented. The specification is TinkerPop's own test suite, a set of Gherkin scenarios (TinkerPop 3.8.2) that runs with every cargo test of Graphersal. A scenario that passes once is protected from regressing, and the number of supported steps whose results are wrong is kept at zero. The current numbers are on TinkerPop Compliance.

Not every step exists yet. An unimplemented step is an error that names it, never a silently different result; the gaps are listed in Current Limitations.

Deliberate differences

A few behaviours differ on purpose, each for a reason that is written down. The most visible ones:

  • Every traversal is a transaction. A failing traversal leaves nothing behind (Transactions).
  • Ids are strings, so they sort as text (Predicates).
  • One integer and one float type (int64, float64) instead of Java's number tower.
  • A removed element stays removed: reading it through an old reference finds nothing, and writing to it is an error (Dropping Elements).
  • No match(), io() or graph-computer algorithms; files are read and written by the API and the command line instead.

Every difference, with its page, is in TinkerPop Deviations.

The query text

TinkerPop's reference language is Gremlin embedded in Groovy or Java. Graphersal's text form is Gremlin embedded in Rhai, a small scripting language for Rust. A Groovy line usually pastes as it is; the differences are small:

Gremlin GroovyGraphersal
'single quotes'"double quotes"
order().by('age', desc)order().by("age", Order.desc) (token classes are written out)
out() inside where(...), repeat(...)__.out() (anonymous traversals always start with __.)
[name: 'ann'] (a map)#{name: "ann"}
def x = ...let x = ...;

The full copy-paste table is in Repeated Labels: select with Pop. Every TinkerPop step also has a snake_case name (has_label, out_e) next to its camelCase one (hasLabel, outE), and the Rust API uses the snake_case names. Graphersal's own additions below are snake_case only.

Additions

Graphersal adds what an embedded engine needs: schemas, saved queries in the graph, path keys into nested values (jpath), multi-label vertices, change capture, permissions and resource limits, a durable Store, and profile() with memory figures. These are extensions: they do not change what a TinkerPop query means.

TinkerPop Deviations

This page lists every place where Graphersal knowingly differs from Apache TinkerPop 3.8.2, and every known gap that is deliberately not fixed (yet). Pass/fail numbers are on TinkerPop Compliance. Each row links to the page that explains the behaviour for users.

The scenarios of the rows select() of an undeclared label, order() of property elements, multi-properties and meta-properties, property(k, null), and asString() of a map, and the families excluded for good (match(), the extra number types, io(), the graph algorithms), are excluded from the compatibility numbers: see Deliberate incompatibilities.

Excluded for good

These TinkerPop features are not planned. Their scenarios are listed by id in INCOMPATIBILITIES (crates/graphersal/tests/tinkerpop/harness/scope.rs) and are outside the compatibility scope.

CodeFeatureWhy
match-stepmatch()declarative pattern matching is the start step gql() instead: ISO GQL queries on the same engine: reads (MATCH ... WHERE ... RETURN ...) and INSERT / CREATE, SET, REMOVE, DELETE and MERGE writes; match is also a reserved Rhai word
extra-number-typesGType.BYTE/SHORT/BIGINT/BIGDECIMAL/CHAR/BINARY, BigInteger literalsthe number model is int64/float64; see Number widths
io-stepio(), read(), write(), the IO tokensGraphSON and GraphML import and export is Graphersal's own API (GraphSource::from_graphson, from_graphml, import_graphson, import_graphml, the CLI's --graph), not a traversal step (GraphSON)
graph-algorithmspageRank(), shortestPath(), connectedComponent(), peerPressure() and their token classesGraphComputer vertex programs, not planned for the traversal language (the scenarios are @GraphComputerOnly as well)

Dates (asDate, dateAdd, dateDiff, DT, GType.DATETIME) are implemented as TinkerPop specifies them, with no deviation; Graphersal's additions are listed in Dates and Times: TinkerPop Compatibility.

Deliberate differences

AreaTinkerPopGraphersalDetails
negate() / P.not(p)Compare.negate() flips the operatorplain complement of the resultPredicates
Element idsnumeric ids order numericallyids are strings, "10" sorts before "9"; hasId(P.gt(3)) (an order predicate on a number) is an error whose help shows hasId(P.gt("3")); equality predicates (eq, neq, within, without) take numbers and compare their textPredicates
hasId(id, ids...)a later list stays one idthe same; a list flattens in first position only, null is an id that matches nothingId Arguments
length()counts UTF-16 code unitscounts Unicode scalar values; an emoji is 1, TinkerPop gives 2Type Conversion
asNumber(GType.INT|LONG) of a floatNaN, infinity or out of range wraps or narrows to the target widthtruncates toward zero; NaN, infinity and out of int64 range are errors (one int64 width)Type Conversion
asBool() of a stringtrue/false in any letter casethe same; no other text converts ("1", "yes" are errors)Type Conversion
trim()/lTrim()/rTrim()Java String.trim() strips characters up to U+0020strips Unicode White_Space (U+00A0, U+3000 too)Type Conversion
choose()/branch() with Pick.anyruns for a produced valuealso runs when the selector yields nothingOption Keys
Branch children of union/choose/branchone traverser at a timestateful children run once over the whole stream; output is branch-majorBranch Children
where(traversal) labelsstart/end label rules of configureStartAndEndStepsthe same rules; an unresolved label filters outwhere() Labels
filter(traversal)TraversalFilterStep: a plain existence test, as() in the child is an ordinary labelthe same (no deviation); it is not an alias of where(traversal), which reads a leading/trailing as() as a scope label and accepts a predicatefilter() and where()
Second by()accepted by some stepsInvalidModulator for aggregate, store, groupCount, valueMap, dedupThe by() Modulator
select() of an undeclared labelselect("a") and select(Pop.x, "a") where no as("a") or side-effect key exists silently filter the traverseran error before execution that names the label and shows how to declare it (a label declared but only sometimes set still filters); a silent filter hides typos (a map-producing step upstream, such as valueMap() or inject(), disables the check, so valueMap().select(Pop.first, "a") filters as in TinkerPop)Select with Pop, Deliberate incompatibilities, help() of the error
order() of properties() elementsProperty elements have their own total order (key, then value) and property idsordered by value only; no property idsProperty Elements
by(T.id) / by(T.key) / by(T.value) over properties() elementsT.id is the opaque property id; T.key/T.value are Property tokensby(T.label) orders by key (as in TinkerPop); by(T.id) is an error (no property ids); by(T.key)/by(T.value) read the key and the value as in TinkerPop (both also read a map entry, a Graphersal extension; any other value is a cast error, as in TinkerPop)Property Elements
Paths::g_V_shortestpaththe expected 24 rows depend on PathRetractionStrategy dropping the repeat-loop v labels in the second iteration, which filters every distance-3 candidatethe full shortest-path set, 30 rows: the six extra rows are the true distance-3 shortest paths (vadas-peter, vadas-ripple, ripple-peter, both directions). Verified on TinkerPop: the scenario's query returns 24, the same query with a no-op filter(__.path()) at the start of the repeat body (which disables the strategy) returns 30. An upstream TinkerPop issue is being preparedDeliberate incompatibilities
Property null@AllowNullPropertyValues / @DisallowNullPropertyValues flavoursnull is a real stored value; writing it never removes a property; use remove_property() to removeUpserts, Removing Properties
Multi-properties, meta-propertiesCardinality.list/set, properties on propertiesone value per key; list/set writes fail with UnsupportedCardinalityUpserts, Property Elements
has(key, ..) / hasNot(key) on a property elementtests the property's meta-properties (an edge property has none)tests the key inside the property's object value (properties("meta").has("a", P.eq(1)) reads meta.a, never the owning element's a); a non-object value is a cast errorProperty Elements
asString() of a mapJava Map.toString ({name=[marko]})the JSON-like physical textProperty Elements
Set side effectsa real Set value typeno set value type: cap() returns an array in first-seen order, members compare by valueSet Side Effects
tree("a")progressive tree, bulk countsthe tree grows with the stream, bulk is ignored (see the gaps below for local())tree() Side Effect
repeat.order = dfsdoes not exista Graphersal addition; a limit() in the body then counts per traverserRecursive Traversals
Map keys 0.0 / -0.0different keys (Double.equals)the same key (-0.0 is canonicalized when a number is built)Maps With Non-String Keys
Map with a non-string key as a property valueTinkerGraph stores any valuenever storable (InvalidPropertyValue); a string-keyed map is storableMaps With Non-String Keys
group()/groupCount()/tree() vertex or edge keythe live element, compared by ida snapshot (element map) materialized once per result; equal within one resultMaps With Non-String Keys
sideEffect(traversal) and bulkthe child runs once per traverserthe child runs once per unit of a bulk-n traverser (the engine-wide bulk rule); the stream passes through unchangedBulk and Barriers
profile() metricsTraversalMetrics with camelCase keys (traverserCount, elementCount, percentDur, dur) and internal step idssnake_case keys (traverser_count, element_count, percent_duration, duration_ns) plus our fields (calls, count_in, optional timing/loops/memory), ids are static plan positions <step>.<child>.<step> shared with error locations; step names are the canonical DSL rendering of the step (has_label("person"), v(labels: ["person"]).count(); g.with("render.spelling", "camel") gives hasLabel("person")), not the step class names (HasStep([~label.eq(person)])); a failing profile() is an error, execute() (ours) returns results, error and metrics of one runProfiling and execute()
limit()/count() in a repeat() bodycounts across the whole loopcounts per iteration (BFS) or per traverser (DFS); only dedup() has loop-wide stateRecursive Traversals
cap() of subgraph()a graph valuea graph value (a TraversalGraph snapshot, empty when nothing was collected): selected edges, both endpoint vertices, ids, vertex label sets and all properties at full depth; the stored schema is copied. In the Rust API next()/to_list() list it as {"vertices", "edges"} (use to_graph() for the graph)Set Side Effects
to_graph()not in TinkerPopa Graphersal terminal: subgraph("sg").cap("sg") without a label; a stream of anything but edges is an errorSet Side Effects
hasLabel() without argumentsnot in TinkerPop (hasLabel takes at least one label or a predicate)a Graphersal extension: keeps the elements that have a label (a vertex with a non-empty label set, an edge with a label); not(__.has_label()) selects the unlabeled ones; hasLabel(null) and an empty list still match nothingLabel Steps
subgraph() over non-edges, subgraph() without a labelnot specified here (vanilla fails with a cast error on a vertex; unverified, no network)an explicit error with a help naming outE()/inE()/bothE(), and for the missing label subgraph("sg")/to_graph()Set Side Effects
withSideEffect("sg", graph) as the subgraph() targetany grapha graph value of this engine, a TraversalGraph (a host graph of another storage fails with Unsupported; not the traversed graph: it fails instead of deadlocking); an existing vertex id is reused, an existing edge id skipped, the target's own schema keptSet Side Effects
Script expression depththe JVM stack decidesa Rhai expression-depth limit (128 expressions, 64 in a function); a chain of about 124 steps is rejected cleanlyQuery Limits
Number widthsbyte, short, int, long, BigInteger, BigDecimalint64, float64 onlybelow
conjoin() of a list holding a list or a mapwrites Java's toString ([a, b], {k=v}) for the elementa cast error: Graphersal writes no Java formats as data text (the rule of asString() of a map); conjoin() or unfold the inner list first; no suite scenario covers itconjoin
format() of a list or map valuewrites Java's toString for the valuea cast error, as for conjoin(); no suite scenario covers itformat
TextP.regex()/notRegex() dialectjava.util.regexthe Rust regex crate's own dialect (syntax); the individual differences are not listedPredicates
Random draws (coin(), sample(), Order.shuffle)SeedStrategy seeds Java's Randomg.with("random.seed", n) seeds the execution's own generator (Rust rand): reproducible per Graphersal version, but not the same draws as TinkerPop for the same seed; the SeedStrategy scenarios stay out of scope with withStrategies()sample, Execution Options
sample(n).by(weight)weights any number; with only zero weights left the sampling loop does not endthe weight must be a number of at least 0 (ValueError::SampleWeight otherwise); a zero-weight traverser is never drawn, so fewer than n can come back; each draw is exactly proportional to the remaining weightsample
P.typeOf(name)any type name registered in TinkerPop's type cache (custom types included)a fixed list of names: String, Integer, Long, Double, Float, Boolean, UUID, OffsetDateTime, Duration, Number, List, Map, Vertex, Edge, Path, Graph (every Java simple class name TinkerPop registers for a GType Graphersal has), plus LocalDate, LocalDateTime, LocalTime for Graphersal's own date and time types; Integer is int64 and Float is float64 (one width each)Predicates
min()/max() over incomparable valuesa ClassCastException for mixed kinds; vertices and edges order by ida mix of kinds (number and string, boolean and number) fails with a cast-style error naming both kinds; elements, paths and collections are not ordered by min/max and fail the same wayLocal Scope
int + float in sum/min/maxNumberHelper widens to doublethe same: the result is a float even when the extremum came from an integer; integers beyond 2^53 lose precision when widened; integer-only streams stay exact and overflow raisesLocal Scope
path()/simplePath()/cyclicPath() from()/to()Path.subPath(from, to): last carrier of each labelthe same; an unknown label or a to() before the from() is an error (TinkerPop raises too, text differs); a label list is an InvalidModulatorPath Windows
by() of path()/simplePath()/cyclicPath() yielding nothingdrops the traverser (without ProductiveByStrategy)the same, for all three stepsPath Windows
where(P.gt("a")) with by(); ring order of a composite predicatelabel operands take ring entries in the order TinkerPop's connective handling visits them (not verified)textual order of the predicate, independent of short-circuiting; an unproductive by() drops the traverser, also under not()where() Start and End Labels
group("a")/groupCount("a") on a key that holds another side effectthe map is merged into whatever a holds (withSideEffect("a", [:]) seeds it)an error naming the key: only group steps that reduce a key the same way may share a side-effect key; a reducing value traversal is re-run over all members of a grown key at the end of each step execution, so readers in the same traversal see reduced valuesgroup
dedup("a", "b") with a label that is not on the pathgetSafeScopeValue raises an errorthe traverser is filtered out, like an unproductive by()dedup
addE() endpoint that is no path label and no side-effect keythe select(key) lookup failsthe name is looked up as a vertex id (to("2"))addE() Endpoints
addE().to(["2", "3"])one endpoint per from()/to()one edge per name (or vertex)addE() Endpoints
addE() endpoint idsvertex id of the graph's id typecompared as strings (2 is "2")addE() Endpoints
id()/label() of an element removed earlier in the same query (as("a"), aggregate(), a path, a lazy values()/id() read after the drop)TinkerGraph still returns the id and label it keeps on the removed element object; properties and edges are goneproperties and edges are gone too, but id(), label(), materialization and writes fail with GraphError::ElementRemoved: a generational handle no longer has any data (the freed slot may hold another element), and it never resolves to that other elementDropping Elements
A traversal that fails after it changed the graph (a failing step, a schema violation, a resource limit, evaluationTimeout)TinkerGraph without transactions keeps the changes made before the errorevery traversal is one unit (implicit auto-commit): the failure rolls back all its changes, so nothing of it is applied; in a script the unit is one traversal (a host may make the whole script one unit, and the Rust API has explicit transactions and dry runs)Transactions
outV()/inV()/bothV()/otherV() of an edge removed earlier in the same queryTinkerGraph's removed edge object still references its endpoint verticesempty, like every other adjacency of a removed element (the generational handle has no data left)Dropping Elements
Explicit transactionsg.tx() with commit()/rollback() on a transactional graph (TinkerGraph itself is not transactional)no tx() in the DSL; the Rust API has Transactional::transaction(|g| ..) for every storage (a closure: Ok commits, Err rolls back, every traversal inside is a savepoint), transaction_with (commit metadata) and dry_run (always rolled back, returns the ChangeSet); a host can make a whole Rhai script one unit (eval_value_atomic); automatic ids of rolled-back elements are never handed out againTransactions
Mutation eventsEventStrategy with MutationListeners, called per mutation after it happenedper committed unit: CommitHook::before_commit (may veto, the unit is rolled back), after_commit, after_rollback, each with the whole ChangeSet (before and after values); no per-mutation eventsTransactions
id() of a property element (properties().id())an opaque property idan error, Graphersal has no property ids (key() and element().id() work); Orderability::g_V_properties_order_id stays failingProperty Elements
label()/hasLabel() of a propertya vertex property's label is its key; an edge Property is no elementthe same for properties() elements of vertices; edge properties and values() handles are cast errorsProperty Elements
A vertex or an edge in untyped JSONGraphSON: vertex "properties" map each key to a list of vertex-property objects ([{"id": .., "value": ..}])"properties" holds each value directly (one value per key, no property ids); a multi-label vertex adds "labels"Vertices and Edges as Values
select(T.id), select(T.label), select(Direction.OUT|IN)not TinkerPop steps (select() takes no token)Graphersal extension: reads that token entry of an elementMap()/valueMap(true) map; the keys "id"/"label" name propertiesProperties Named id or label
remove_property(keys...)not a TinkerPop step (removal is properties(k).drop())Graphersal extension: removes keys (none = all) of vertices/edges and emits the same element; rejected for a property in its label's required list in open/closed schemasRemoving Properties
add_label(..), drop_label(..), set_label(..)not TinkerPop steps (labels are immutable)Graphersal extensions: change the label set of a vertex or the label of an edge and emit the same element; checked by an open/closed schemaadd_label, drop_label, set_label
valueMap(null)ambiguous single-null varargsa null key is dropped, so a lone null means all keysProperty Elements
Operator integer overflowsum/minus/mult promote int to long and long to BigIntegerint64 only: overflow is an OperatorFailed errorSack and Operators
Operator.sumLong overflowwraps around (two's complement)an OperatorFailed errorSack and Operators
Operator.addAll of a list and a scalar3.7.2 throws, 3.8.2 appendsappends the scalar (the 3.8.2 feature files decide)Sack and Operators
Operator null operandNumberHelper: sum(null, x) is null, sum(x, null) is xthe same (kept deliberately); min/max/and/or take the other operandSack and Operators
Sack value is a vertex or an edgeany object is a valid sacka cast error (help names by(T.id)); use an id or a propertySack and Operators
Sack split and Supplier initial valueswithSack(Supplier) clones per traverser, a UnaryOperator splitsnot supported; a container sack is shared by handle and never modified in placeSack and Operators
Merging traversers that carry a sacka sacked traverser never merges without a merge operatorequal-sack traversers merge (invisible after bulk expansion); different sacks never doSack and Operators
sack(Operator) arithmetic wideninga sack of 127b plus 1b becomes a long, Long.MAX_VALUE + 1 a BigIntegerint64/float64 only: the result is an int64, and an overflow is an OperatorFailed error naming sackSack and Operators
sack(Operator) with a vertex or edge operandany objectOperatorFailed or a cast error (a sack never holds an element); by(T.id) gives the idSack and Operators
sack(BiFunction), barrier(Consumer) lambdasacceptednot supported: sack(Operator.sum) and barrier(Barrier.normSack) onlySack and Operators
by() of sack(Operator)the first result of the child (TraversalUtil.produce)the same; one by() only (a second is InvalidModulator)Sack and Operators
normSack numeratorsack * bulk / totalwith a merge operator the same; without one sack / total with total = sum(sack * bulk): equal sacks merge invisibly here, TinkerPop's bulk is 1 without a merge operator, so the answers agreeSack and Operators
Merge points with a sack merge operator or withBulk(false)LazyBarrierStrategy inserts barriers that merge sacks, so the result depends on where they landonly an explicit barrier() merges; the repeat() frontier and lazy_barrier() pass through (context.auto_merge); write repeat(__.out().barrier())Sack and Operators
bulk.merge=false with a merge operatornot an optiondisables every merge including the explicit barrier, so the sack result changes (diagnostic switch)Sack and Operators
withBulk(false)requirement ONE_BULKthe option bulk.one; same effect at an explicit barrier; additionally turns the automatic merge points offSack and Operators
Containers and Full paths under a merge operatorarrays and maps with equal content merge; path equality is by contentnever merge (containers have no key, paths compare by handle), so the operator does not combine thereSack and Operators
withSack(init, UnaryOperator), three-argument withSacksplit operatorsnot supported (error naming the merge Operator)Sack and Operators
aggregate()/store() into withSideEffect(key, init, Operator)3.7.2 gives the reducer one BulkSet per step execution (sum(1, BulkSet) throws); 3.8.2 behaviour is only visible in the feature filesone uniform rule per step execution: assign/addAll receive the collected values as one list, every other operator folds them one by one; inferred from the 24 sideEffect/Aggregate Operator scenarios (all pass)Sack and Operators
fold(seed, Operator), withSideEffect(key, init, Operator) lambdasfold(seed, BiFunction), withSideEffect(key, init, BinaryOperator) acceptedonly an Operator token (an error names the form); a bulk-n traverser applies the operator n times, no shortcutSack and Operators
select(Pop.x, ..) path recordingthe path keeps every labelled positionevery pop except Pop.last, and every select(.., traversal) (the key is only known at run time), records full paths and so skips bulk merging upstream (a cost difference only; results are the same)Select with Pop
select(Pop.mixed, "a"), oldest occurrence is a listPath.get(label) appends the later occurrences to the stored list in placethe same result on a copy; the stored value never changesSelect with Pop
math() of a trigonometric functionJava Math.sinthe platform libm; the last digit of a result can differ (sin(4.0) is -0.7568024953079283 here, ...282 in Java: map/Math::g_withSackX1X_injectX1X_repeatXsackXsumX_byXconstantX1XXX_timesX5X_emit_mathXsin__X_byXsackX passes in the harness because float results compare within 1 ulp, see 1 ulp float tolerance)Math

GraphSON

GraphSON 3.0 import and export is Graphersal's own API, not the io() step (which stays excluded). Where it differs from TinkerPop's GraphSONReader/GraphSONWriter (details and the full type table on GraphSON):

AreaTinkerPopGraphersal
Element idsany type (g:Int32 1)strings: an imported g:Int32 1 is "1"; export writes string ids, so TinkerGraph answers g.V("1"); with its LONG id managers also g.V(1) (recipe)
Multi- and meta-propertieslist cardinality, properties on propertiesseveral entries become one array, meta-properties the reserved _meta object property; export restores them from _meta only
Multi-label verticesno label setswritten as "A::B", one opaque label in TinkerGraph
Unlabeled vertex/edgealways labeledexported with the default labels vertex/edge, read back with them
Date and time valuesread into java.time valuesread into the temporal types (a gx:ZonedDateTime keeps its offset and a zone id of the bundled database, any other zone id is dropped and reported; one whose offset is not its zone's offset at that instant keeps the offset of the text and drops the name, reported, where java.time would recompute the offset from the zone (user decision: an offset is kept as written); up to nine fraction digits are kept); gx:Year, gx:YearMonth, gx:MonthDay, gx:ZoneOffset are skipped and reported; a duration with both months or days and a time part is exported as graphersal:Interval, which TinkerPop cannot read
BigDecimal, Class, enum tokens, vendor typesread into Java valuesskipped and listed in the import report, never converted
Edge to a vertex that is not in the filereadGraph failsskipped and reported (or connected to the target graph's vertex of that id)
Duplicate vertex idan errorthe first vertex wins, the second is skipped and reported
Vertex-property idskeptnot kept; export writes a file-wide g:Int64 sequence
g:Int32, g:Floatkept as suchint64/float64; export writes g:Int64/g:Double

jpath(..) keys wherever a property name is taken

Extension, not a deviation of an existing TinkerPop behaviour. values, properties, has (every form with a key), hasNot, valueMap, elementMap, every property by(), property and remove_property also accept jpath("a.b[1]"), a singular RFC 9535 path into a nested property value (Path Keys). A plain string is always a literal property name, exactly as in TinkerPop, and is never parsed as a path. A missing path is an absent property, not an error. In maps (valueMap, elementMap) the key of a path entry is the canonical path text ($.a.b[1]). json_path("a.b[1]") stays the standalone string-argument step with the same grammar. A side effect of the key conversion: has(null, v) reads the null key as the name "" and matches nothing, which is what the TinkerPop scenario g_V_hasXnull_testnullkeyX expects.

properties(jpath(..)) yields a path property element

Extension, not a deviation of an existing TinkerPop behaviour: properties("name") is exactly as in TinkerPop. properties(jpath("a.b[1]")) (a Graphersal path key, see Path Keys) yields TraverserValue::PathProperty, a materialized property element: key() is the canonical path text ($.a.b[1]), value() the leaf, label()/hasKey() see the path text, id() is the same deliberate error as for any property element, and a terminal materializes the leaf. Reason: a path has no stored property a lazy handle could point at. It is only produced by a path key, never by a plain string.

property(jpath(..), value) writes below a stored property

TinkerPop has no nested property write. Graphersal's property(jpath("a.b[1]"), v) (Path Keys) sets a value inside the stored property a: missing object keys are created, [n] replaces, [len] appends, anything else out of range or of the wrong type is an error (GraphError::InvalidPropertyPath) and never an overwrite. property(Cardinality, jpath(..), v) is an explicit error in v1. With a schema, the written leaf is coerced at its declared nested type and the resulting property is validated, Closed rejecting undeclared nested keys (Schemas and nested paths). A plain string key behaves exactly as in TinkerPop. A traversal as the key (property(select("a"), v)) is still not implemented.

remove_property(jpath(..)) removes below a stored property

TinkerPop removes a property with properties(k).drop(); Graphersal's remove_property(..) is an extension that keeps the element in the stream, and it now also takes a jpath(..) key (user's guide page "Path keys (jpath)"): an object key is removed, an array element is removed with shift, and a missing path or a type mismatch on the way is a no-op, never an error (more lenient than the write side, where a mismatch is an error). properties(jpath(..)).drop() is an error, because a path property element holds no reference to its owner; use remove_property(jpath(..)).

Known gaps, not fixed yet

Counts are in-scope scenarios (missing unless noted; the current numbers are in target/tinkerpop-report.md after a suite run); a scenario can wait on more than one gap.

GapEffectScenarios
repeat.order = dfs body limit()counts per traverser, not per iteration (a Graphersal addition, see above)none
local(tree("a")) needs a streaming executora step after the local() child sees the finished tree, not the progressive onenone known to fail
literal types the harness cannot express (set)translate; a {..} set literal is not mapped to Set.of(..) because Graphersal has no set value (only a set side-effect seed), so GType.SET would have nothing to matcha few, two of them Orderability scenarios that also hold dates (byte/short/bigint/bigdecimal are excluded for good)
GType.SET, GType.TREE, GType.VPROPERTYmissing; no set, tree or vertex-property value type7
call() service steptranslate (call is a Rhai built-in function, so a future step needs a DSL name of its own); no service model (registry, tinkerpop.dc, list, search) yet; may come with the server20
@DisallowNullPropertyValues, multi-/meta-properties, valueMap().asString()deliberate, outside the compatibility scopesee Deliberate incompatibilities
subgraph() capnone: cap() is a graph value, the harness compares its {"vertices", "edges"} listing with the scenario's edge and vertex tables, and GType.GRAPH exists. The 4 Subgraph and 3 TypeOfGraph scenarios passnone

Why @DisallowNullPropertyValues stays unfixed: the 3 scenarios expect a write of null to remove the property, the 4 @AllowNullPropertyValues scenarios that pass expect it to be stored. Both cannot hold in one mode; the answer would be a graph-level null mode (not scheduled).

Number-width literals in the test surface

The harness maps 1b/1s/1n to an integer and 1m to a float, so these scenarios pass by value equality only. They do not show byte, short, BigInteger or BigDecimal support:

  • map/AsNumber.feature: g_injectX5bX_asNumber, g_injectX5sX_asNumber, g_injectX5nX_asNumber.
  • map/Sum.feature (12): g_V_injectX127b_1bX_sumXX, g_V_injectX_128b__1bX_sumXX, g_V_injectX32767s_1sX_sumXX, g_V_injectX_32768s__1sX_sumXX, g_V_age_injectX1000nX_sum, g_injectX1b_2b_3bX_sum, g_injectX1b_2b_3sX_sum, g_injectX1b_26b_3iX_sum, g_V_age_injectX1000nX_fold_sumXlocalX, g_injectX1b_2b_3bX_fold_sumXlocalX, g_injectX1b_2b_3sX_fold_sumXlocalX, g_injectX1b_26b_3iX_fold_sumXlocalX.
  • sideEffect/Inject.feature::g_injectXbigintBoundaryValuesX.

That is 16 scenarios. The 8 semantics/Equality.feature Primitives_Number_* scenarios pass the same way (byte, short, bigint and bigdecimal included); Sum of byte values that overflow a byte is the case where TinkerPop and Graphersal would differ without the collapse.

1 ulp float tolerance in the test surface

The harness compares two float64 result values as equal when they are equal or at most 1 ulp apart (NaN equals NaN, infinities exact, +0 equals -0, other signs must agree). The cause is that Rust's libm and Java's Math differ in the last digit of some results (sin(4.0)); Graphersal's arithmetic does not deviate from TinkerPop. The tolerance applies only to float vs. float result values, never to integers, ids, orderings or error cases. It lets the one map/Math sin scenario pass, which is a pass by tolerance, not proof of bit-identical trigonometry.

Which scenarios could expose negate()

Compare.negate() and a plain complement differ only for incomparable operands (NaN, a string against a number). The P.not/negate() scenarios of the suite (filter/TypeOf, filter/Where, filter/HasLabel, integrated/Recommendation) negate typeOf, within or comparisons of numbers, where both agree. The NaN scenarios of semantics/Comparability.feature (not(is(P.gt(NaN)))) use the not() traversal step, which negates the filter result, not the predicate. No vendored scenario exposes the difference.

Current Limitations

What Graphersal 0.2.0 does not do, in one place. Each item links to the page with the details; the deliberate differences from Apache TinkerPop are listed one by one in TinkerPop Deviations, and the steps and scenarios that are not implemented yet in TinkerPop Compliance.

Data model

  • Dates keep an offset, not a zone. A datetime stores its UTC offset; a time zone is an argument of the operations that need one, never part of a value, and the zone database is the one bundled with the release (Time Zones). GraphSON's gx:Year, gx:YearMonth, gx:MonthDay, gx:OffsetTime and gx:ZoneOffset are skipped on import (GraphSON).
  • One value per property key. Only Cardinality.single is written; store several values as one array (Upserts). There are no meta-properties: a GraphSON import folds them into the _meta property.
  • Ids are strings. A numeric id becomes its text, and ids order as strings ("10" before "9"; see Id Arguments and Predicates).
  • Edges have one label; vertices have a label set (Multi-Label Vertices).
  • Property indexes are declared, top-level and per label. A has() on a property reads an index only when one is declared with g.create_index(..) for the start step's label and the key (Property Indexes); nested values (jpath keys), has() without has_label() and order() scan.
  • Vector search is exact, without an index. nearest() scores every incoming element (about 13 ms per 100 000 vectors of 384 f32 components); there is no approximate (ANN, HNSW) vector index yet. Filter before the search to score fewer (Vectors).
  • The graph lives in memory. A Store makes it durable, but the whole graph is loaded into memory when the store is opened.

Query language

  • The DSL is Rhai, not Groovy. Queries read like Gremlin in either spelling (hasLabel or has_label), but maps are written #{..}, child traversals need __. (where(__.out())) and tokens need their class (Order.desc, Scope.local). A Gremlin text query is not parsed as it is.
  • No withStrategies() / withoutStrategies(). Execution options are set with g.with(key, value) (Execution Options Reference).
  • No g.tx(). Every traversal is one unit of work; a host can run a whole script as one unit (Transactions).
  • GQL is experimental. g.gql() runs ISO GQL queries with the write clauses INSERT (Cypher CREATE), SET, REMOVE, DELETE and Cypher's MERGE (Cypher spellings as aliases, Cypher's map projections, comprehensions, COUNT { } / COLLECT { } and list predicates, UNION / NEXT and CALL { } subqueries, quantified path patterns) as a start step; its subset and answers may still change between versions. EXCEPT / INTERSECT, shortest paths and a quantifier nested in a quantified path pattern are not supported yet, an uncorrelated CALL body runs once per row (no caching), and Cypher's FOREACH is not supported yet (use FOR x IN list before the write).
  • Saved queries only read and are called at the start of a traversal (g.query(..)), not on incoming traversers (Saved Queries).

Schema

  • No map type (additionalProperties with a schema), no oneOf/allOf/not, no tuples, and no format other than uuid, the date and time formats (date-time, date, local-date-time, time, duration) and vector (Schemas).
  • default/defaultFunction fill only a label's top-level properties, only when an element is created, and only in mode open/closed; defaultFunction knows uuidv4, uuidv7, now and today; see Defaults on create.

Security and serving

  • Read security per element or label does not exist yet; an authorizer decides per request kind and label as the plan states it (Permissions).
  • The dev server (graphersal --server, also MCP and AI Chat) is a local development tool: unstable, bound to the loopback, without authentication (Dev Server and MCP).
  • Not a Gremlin Server. There is no network protocol for remote Gremlin drivers (gremlin-python, the Java driver); Graphersal is embedded as a library, the CLI or the Python package (Graphersal and TinkerPop).

Concurrency and packaging

  • Readers wait for the writer. A graph has one writer at a time and reads wait while a unit writes; a layered storage with snapshot reads is planned (Transactions).
  • No npm package. The WebAssembly engine runs the web playground; its JavaScript API is internal to it, and a published npm package is planned.

Other

Rust Quick Start

Add the crate with the features you need (Library Features lists them all):

[dependencies]
graphersal = { version = "0.8", features = ["script", "io", "display"] }
  • script: the Gremlin DSL as text, the same language as the CLI, the playground and Python;
  • io: GraphSON and GraphML files;
  • display: results rendered as tables;
  • persist: snapshots, the journal and the Store on disk.

The code on this page is the example crates/graphersal/examples/quick_start.rs; run it with cargo run -p graphersal --example quick_start --features script,io,display.

Read

use graphersal::prelude::* brings everything a query needs. A graph is shared behind a lock: a read lock gives a traversal source, the steps are methods, and a terminal (to_list, next, iterate) runs the traversal.

    // The TinkerPop "modern" sample graph: 4 people, 2 pieces of software, 6 edges.
    let graph = GraphSource::tinkerpop_modern();

    // A read lock gives a traversal source `g`; the traversal is built step by step and run by
    // its terminal (`to_list`, `next`, `iterate`).
    let lock = graph.read();
    let friends = lock
        .traversal()
        .v(None)
        .has("name", "marko")
        .out("knows")
        .values("name")
        .to_list()?;
    println!("marko knows {friends:?}"); // marko knows ["josh", "vadas"]
    drop(lock);

v(None) starts at every vertex; v("1") or v(vec!["1", "2"]) at given ids. The Rust names are the snake_case names of the DSL, with a trailing underscore where Rust needs one (as_, in_).

Write

Writes take the write lock and traversal_mut(). A traversal is one unit: it commits when it succeeds and is rolled back completely when any step fails. Anonymous traversals start with __::.

    // Writes take the write lock. Every traversal is one unit: it commits when it succeeds and
    // leaves nothing behind when it fails.
    graph
        .write()
        .traversal_mut()
        .v(None)
        .has("name", "marko")
        .add_e("knows")
        .to_by(__::add_v("person").property("name", "ann"))
        .iterate()?;
    let people = graph
        .read()
        .traversal()
        .v(None)
        .has_label("person")
        .count()
        .next()?;
    println!("people: {people:?}"); // people: Some(5)

Several traversals become one unit with Transactional::transaction; a dry run shows the changes a closure would make without keeping them (Transactions).

The DSL from Rust

With the script feature a query can also be text, for example one a user typed. eval_value returns the result as a script value, eval renders it for display:

    // The same queries as text, in the Gremlin DSL (feature `script`): what the CLI, the
    // playground and Python run. Both spellings work: `has_label` and `hasLabel`.
    let graph = Arc::new(graph);
    let names = graphersal::script::eval_value(
        graph.clone(),
        r#"g.V().has("name", "marko").out("knows").values("name").order().toList()"#,
    )?;
    println!("{names}"); // ["ann", "josh", "vadas"]

    // `eval` renders the result for display: JSON lines, a table with feature `display`.
    let table = graphersal::script::eval(
        graph,
        r#"g.V().hasLabel("software").valueMap("name", "lang")"#,
    )?;
    println!("{table}");

These two helpers allow everything. For a query you did not write, use script::eval_value_with_limits with an Authorizer such as AccessPolicy::read_only() and ScriptLimits (Permissions, Resource Limits).

Files and samples

With the io feature:

        let modern = GraphSource::tinkerpop_modern(); // the samples: also file_tree(), large_110k()
        modern.read().traversal().export_graphson(path)?; // GraphSON 3.0, TinkerPop's format
        let copy = GraphSource::from_graphson(path)?; // also from_graphml, from_file
        let two = copy
            .read()
            .traversal()
            .v(vec!["1", "2"])
            .values("name")
            .to_list()?;
        println!("{two:?}"); // ["marko", "vadas"]

Where to go from here

  • the API reference on docs.rs: prelude for queries, the topic modules (schema, changes, auth, catalog, exec, profile, storage, persist) for integration;
  • Transactions: units, dry runs, change capture and commit hooks;
  • Schemas;
  • Persistence Overview: a graph on disk;
  • Custom Storages: run the engine on your own storage.

Python Quick Start

The Python package graphersal embeds the engine into the Python process. Queries are Gremlin text, the same DSL as everywhere else, and results come back as plain Python values (list, dict, int, float, str, bool, None, uuid.UUID, and the datetime types for dates and times, see Dates and Times: From Python); a vertex or an edge comes back as a graphersal.Vertex / graphersal.Edge (see Vertices and Edges as Values).

Install

Build the extension from the repository (Python 3.10 or newer, one wheel covers every later version):

cd bindings/py-graphersal
python3.12 -m venv .venv && .venv/bin/pip install maturin
VIRTUAL_ENV=$PWD/.venv .venv/bin/maturin develop --release     # installs `graphersal` into .venv

maturin build --release writes a wheel to install elsewhere; details are in bindings/py-graphersal/README.md.

Query

import graphersal

graph = graphersal.Graph.tinkerpop_modern()      # or graphersal.Graph() for an empty graph

graph.query('g.V().has("name", "marko").out("knows").values("name")')
# ['josh', 'vadas']

graph.query('g.V().hasLabel("person").group().by("name").by("age").next()')
# {'josh': [32], 'marko': [29], 'peter': [35], 'vadas': [27]}

A traversal the script returns is run for you; inside a longer script, end each traversal with a terminal (.next(), .to_list(), .iterate()).

Parameters

Pass values as parameters instead of pasting them into the text; they arrive as script variables:

graph.query('g.V().has_label("person").has("age", P.gt(min_age)).values("name")',
            params={"min_age": 30})
# ['josh', 'peter']

Write

Every query is one unit: when it fails, nothing it wrote stays, and the error is a graphersal.GraphersalError with the diagnostic and its help text.

graph.execute('g.addV("person").property("name", "ann").property("age", 41).iterate()')

try:
    graph.execute('g.V().has("name", "ann").property("age", 42).fail("stop").iterate()')
except graphersal.GraphersalError as err:
    print(err)                                   # the failing step and how to fix it

graph.query('g.V().has("name", "ann").values("age").next()')
# 41: the failed query changed nothing

Files and persistence

graph.export_graphson("people.json")             # GraphSON 3.0; TinkerGraph reads it
graph = graphersal.Graph.from_graphson("people.json")

with graphersal.Store.create("data") as store:   # a graph on disk, every commit durable
    store.graph.execute('g.addV("person").property("name", "bob").iterate()')

Embedding models

The step embed(), the function embed(text) and text queries (nearest("emb", "a question", 5)) compute vectors with the built-in hash-ngram/1 or with a model kept in the graph's database (Vectors: Embeddings). A model serves a database only once it is imported into it:

import graphersal

with graphersal.Store.create("kb") as store:
    # A repository downloaded before (`graphersal embed-model download minishlab/potion-base-8M`)
    # is found in the download cache; a model directory works as well.
    report = store.import_model("minishlab/potion-base-8M", default=True)
    report["identity"]      # 'model2vec/minishlab/potion-base-8M@<12 hex digits>'
    store.graph.embedders() # hash-ngram/1 and the store's model, the default first

store.import_model(source, *, repo=None, license=None, replace=False, default=False) takes a repository name found in the download cache ($GRAPHERSAL_EMBED_MODELS, else $XDG_CACHE_HOME/graphersal/embed-models, else ~/.cache/graphersal/embed-models) or a directory holding a Model2Vec model; repo=/license= fill what the directory does not say, replace=True replaces another revision of the same repository (vector rules naming it are re-embedded in the same commit), default=True makes it the default model. It returns the report as a dict and releases the GIL while it runs. graphersal.Store.import_model_into(path, source, ..) does the same for a CLOSED store without loading its graph. The wheel has no download client: fill the cache with the graphersal command line (graphersal embed-model download <repo>), once for any number of databases.

A store opens with its models: the ones the schema needs are loaded at the open, the others at the first query that uses them. Graph.load("file.gsnap") serves the models the file carries (a UserWarning names what an earlier release left, such as vectors without a rule). graph.embedders() lists the embedders of the graph by repository, with their model identity.

Filling a property and searching by text. A vector rule ("from") fills and refreshes the vectors by itself with hash-ngram/1 or a model of the store; the schema records the model, which is what a text query embeds the question with:

store.graph.patch_schema({"vertices": {"chunk": {"schema": {"type": "object", "properties": {
    "emb": {"type": "array", "format": "vector", "embedder": "minishlab/potion-base-8M",
            "from": "text"}}}}}})
store.graph.execute("""
    for t in ["Cats need fresh water every day.", "Salt the pasta water generously."] {
        g.add_v("chunk").property("text", t).iterate();
    }
""")
store.graph.query('g.v().has_label("chunk").nearest("emb", question, 5).values("text").to_list()',
                  params={"question": "How often should I feed my cat?"})

A model of your own (sentence-transformers, a remote API) stays in your program: compute the vectors there and write them as values (a 1-D float32 numpy array or a graphersal.Vector in params), and pass the question's vector to nearest (Embeddings and Vector Search).

Changed in 0.5.0: graphersal.Embedder, graphersal.Model2Vec, the embedders=/ default_embedder= keywords of every constructor, loader and Store opener, and graph.register_embedder are removed (a removed keyword raises Python's TypeError); the job embed_property was removed as well (vector rules replace it).

Threads of Model2Vec. The tokenizer (tokenizers, through rayon) starts a thread pool of one thread per CPU core on the first batch it encodes. TOKENIZERS_PARALLELISM=false in the environment (set before the first embedding) keeps it on the calling thread, for example in a program that forks worker processes after embedding or that limits its CPU use.

Vector rules

A vector rule in the schema keeps a vector property embedded from a text property. graph.set_schema(..) and graph.patch_schema(..) issue graphersal.VectorFillWarning (a UserWarning) with the preview's text BEFORE a change that fills vectors, because the whole graph is locked while the fill runs; graph.validate_schema(..) ["fill"] lists the planned fills. Turn the warning into an error to stop such a change:

import warnings
import graphersal

with warnings.catch_warnings():
    warnings.simplefilter("error", graphersal.VectorFillWarning)
    graph.set_schema(schema)   # raises before anything is applied when it would fill vectors

Where to go from here

Web Playground

The playground is a single-page web app that runs Graphersal in the browser: the real engine, compiled to WebAssembly (crates/graphersal-wasm), in a Web Worker. There is no server-side part; any static file server can host it. Its source is playground/ in the repository; the developer details (engine boundary, file layout, libraries) are in playground/README.md.

Build and run

rustup target add wasm32-unknown-unknown                      # one-time
cargo install --locked wasm-bindgen-cli --version 0.2.129     # one-time; must match the wasm-bindgen crate
playground/build.sh                                           # builds playground/pkg/
python3 playground/serve.py 8000                              # open http://localhost:8000/ (no browser caching)

wasm-opt (from binaryen) is optional; when it is installed, build.sh uses it to make the module smaller. Without the build output the page explains how to build it.

The same UI also runs against the CLI as a local engine, without WebAssembly: graphersal --graph <src> --server (DEV mode, unstable, local only; see Dev Server and MCP). There the Query panel can also open an AI Chat tab (EXPERIMENTAL, --ai FILE): an LLM agent that answers questions by querying the served graph. In the WebAssembly playground that tab is read-only.

What it does

  • Graphs: the empty graph, the TinkerPop "modern" graph, the generated ~110k element graph (the CLI's --graph large), a file tree sample, or a GraphSON (.json, TinkerPop's g.io() format) or GraphML file from your disk (it stays in the browser). What a GraphSON import skips (dates, unsupported types) is shown in a notice.
  • Queries: the full DSL, both spellings, with completion from the engine's own function list (each entry's tooltip shows its overloads, a one-line description and a runnable example). A traversal without a terminal runs as execute(), so one run gives the results and, with Profile on, the metrics; Memory adds the exact per-step memory figures (the module installs the counting allocator, so the source is tracked). Results are shown as a table, JSON and the raw text the CLI prints, within the CLI's display limits (see Displaying Results).
  • Examples: the Query panel's Examples button (a click, or resting the pointer on it) opens a panel over the editor with every example, in collapsible groups (GQL split by topic). Its search field finds a plain text in titles and scripts, case-insensitive (.order( lists every example that uses it, with the matching line); Up/Down move, Enter opens, Esc clears the search and then closes. Reopening returns to where you were and marks the example opened last, so the next one is right below it. The Modern graph group has subgraph() examples (the edges of one kind, the edges walked by repeat(), the result as a graph, traversing the extracted graph).
  • Query tabs: the Query panel holds several queries side by side. Each tab has its own text, Profile/Memory toggles, last result and last profile; switching tabs shows that tab's results without running anything. The graph is shared: when a run in one tab changes it, the other tabs' results are marked "possibly stale" until they run again. An example from the Examples menu goes into the active tab only when that tab is empty or still holds an unchanged example; otherwise it opens in a new tab, so your own text is never overwritten. The tab menu also offers Duplicate tab, Close other tabs and Run all tabs. The tabs (not their results) are kept in the browser; the query history records every run with its tab's name. Shortcuts: Ctrl/⌘+Enter runs the active tab (or its selection, see Run below), Ctrl/⌘+Shift+Enter runs all tabs, Alt+N opens and Alt+W closes a tab, Alt+[ / Alt+] switch to the previous / next tab and Alt+Shift+1…9 to tab 1…8 or the last one (the browser keeps Ctrl/⌘+T, W and 1…9 for its own tabs).
  • GQL query tabs: a query tab is in Rhai (the Gremlin DSL, the default) or in GQL. Open one with + ▸ GQL query (marked GQL in the tab strip), or switch the tab with the Rhai / GQL switch in the Query panel's header; nothing is detected from the text. In a GQL tab you write the query itself, MATCH (p:person) WHERE p.age > $min RETURN p.name, with GQL highlighting and completion: the keywords that fit the position (after MATCH a pattern's WHERE, RETURN and the next clauses, after RETURN AS, ORDER BY, LIMIT, ...), the GQL functions with a short description, the graph's labels after : (edge types inside [..]), the property keys after n. (those of n's labels), the variables the query binds, the parameters after $, and after CALL the saved queries written in GQL as folder.name (Calling saved queries from GQL). Under the editor the Parameters field holds the parameter map as JSON, {"min": 30} (checked as you type; a fault names its line and column); + Add $parameters adds every $name the query reads that the map lacks. Run, Run selection, Stop, Profile, the history and the results work as in a Rhai tab: the tab runs g.gql("<query>", #{min: 30}), and an error's GQLSTATUS stays in its message while the part of the query it names is underlined in the editor (Go to line jumps there). Switching a tab that holds exactly one g.gql(`...`, #{..}) call to GQL takes its query and its literal parameters out of it; switching back writes them as that call again; any other text is kept as it is. GQL examples of the Examples menu open as GQL tabs. Save as query… of a GQL tab saves a GQL query with its $parameters, typed and defaulted by the Parameters field.
  • Statistics, a tab of the Profile panel (next to Steps and Text), shows two sources side by side: the graph's data (g.statistics(): vertex and edge totals, the counts per vertex label, also as primary label, and per edge label; at most 50 labels per kind, largest first) with its memory footprint (g.memory_usage()), and the limits a query runs under: the host's presets (none in the playground; the dev server's --timeout, --max-*, ...) and the engine's defaults for the rest (see Resource Limits; g.with(..) changes them per query). While open it reloads after every run that changed the data. A Process memory section (hidden when empty) lists what the process holds: the resident set size (RSS, with its peak) and the live heap on the dev server (RSS on Linux and macOS only), every loaded embedding model with its size (measured at its load; marked "estimate" where no tracking allocator counted it) and, on the dev server with --ai, the AI Chat history (conversations and an estimate of their bytes). The WebAssembly playground has no loaded models, no chat and no RSS; it shows the live heap and the size of its WebAssembly memory. Above the Memory section, the process memory bar shows how full the process is against its memory ceiling: used of the ceiling, where the ceiling comes from (configured, cgroup limit, 80 % of RAM, WebAssembly default), and the percentage (normal below 70 %, amber from 70 to 90 %, red above). One coloured segment per place the memory goes: structure (vertex and edge slots, ids and labels: the Memory row's Structure), properties (plain values), compressed (compressed and deduplicated values with their dictionaries), indexes (the id and label indexes plus the property indexes: the Memory row's Indexes and Property indexes), models (embedding models in memory), live_graph (a store's live graph, held beside the read-only view of a past state you are looking at), store (the store's buffers and, for a database kept in memory, its files), engine (the script engine, the workload statistics, the session's layouts, the dev server's MCP and AI Chat state) and other (the rest of the heap no segment explains: query buffers, caches, allocator overhead). A segment's tooltip lists the parts it sums. The legend lists every segment with its size, also a tiny one, and a line says what compression saves. Without a tracking allocator only the known segments are shown, marked "process total not tracked"; without a ceiling there is no percentage. The same bar opens the Memory tab of Optimize; the Statistics tab's Components and memory report… button opens that tab, whose Process memory table lists every component with its bytes (the memory report's walk, so it is not repeated in the Statistics tab). With Profile on, a line under the step tree, Peak memory, shows the most memory the run held at once against the per-query limit traversal.max_materialized_bytes (amber and red by the same thresholds): a different figure from the process bar, against a different limit.
  • Errors show the message, the step path of a runtime error (the same step ids as the profile), the help() advice, a "Go to line" for script errors, and the full diagnostic.
  • Graph, Schema, Profile panels draw the graph (capped), show and edit the schema (see The schema editor below; the drawings, a label graph and a Mermaid diagram, show at most 300 labels), and the optimized plan with timings, traverser counts, loop statistics, path recording and memory. The Graph panel draws the whole graph when it has at most 10 000 vertices and 20 000 edges (Settings), else its labels; it also draws the neighbourhood of a vertex and the last query result. Clicking a vertex or an edge shows its properties, fetched from the engine at that moment (the drawing itself carries only ids, labels and names; long texts and vectors are collapsed with an expand button, see Long values); double-clicking a vertex in the neighbourhood or the query result expands it by one hop from the engine (in the whole graph: selects it with its neighbours, again for one hop more), double-clicking empty space fits the drawing. The toolbar keeps Layout, Edit, Fit and Export; the ⚙ Display menu holds the drawing tier, vertex and edge IDs, edge labels and a short mouse help (a narrow panel moves Layout and Edit there too). Above 200 vertices the engine lays the drawing out (with progress and Stop) instead of the browser. See The graph drawing below for what the panel shows and its two drawing tiers.
  • Run (or Ctrl/⌘+Enter) runs the selected text when the editor has a selection, else the whole tab, so a script can be tried piece by piece. The button then reads Run selection, and the status bar and the Results header say "selection (N lines)". A selection of only whitespace runs the whole tab; with several selections (Alt+drag) only the main one runs. Everything else is a normal run: one unit (committed only when it succeeds), the history records the text that ran, Profile and Memory apply, and an error's "Go to line" points into the full text of the tab. Run all tabs always runs whole tabs.
  • Stop (next to Run) ends a long query: the engine is restarted and the graph restored as it was last loaded (sample or file) or last saved. Changes made after that point are lost, and so is the history of the store in memory (it starts over from that state). While no query runs but the graph drawing is being laid out, Stop ends only the layout: the drawing keeps the positions reached so far and nothing is restarted.
  • Save ▾ (top bar; the start page has the same entries as buttons) downloads ONE file per entry: the graph data as GraphSON 3.0 (graphersal-graph-YYYYMMDD-HHMMSS.json) or GraphML (.graphml), the schema (graphersal-schema-YYYYMMDD-HHMMSS.json; neither data format carries it, see UUID Values), the saved queries, or a snapshot (.gsnap) with data, schema and saved queries in one file. One file per click, because browsers block or drop a second download started by the same click. To load both back, choose both in Load from file on the start page: the graph file and, in the dialog's optional second field, the schema file (JSON). The schema is set on the new, empty graph first and the data is imported against it as one unit, so the elements, ids, labels, properties and the schema come back; in mode open or closed a violation fails the load with the error and nothing changes. Load from file always starts without the previous graph's schema: a graph file loaded without a schema file has no schema (a previous graph's schema has nothing to do with an unrelated file). Dropping ONE file on the card loads it without a schema; dropping a graph file together with its .json schema pairs them when that is unambiguous (the graph file is GraphML, .jsonl or .graphson; two .json files are refused, choose them in the dialog). A snapshot (.gsnap) brings its own schema and takes no schema file. GraphSON keeps every value type (uuid, lists, maps) by itself; GraphML gets them back from the schema's declarations, and Save warns about values that come back as strings without one (an undeclared uuid, lists and maps, a property with different types on different labels).
  • Load schema applies a JSON file in the schema format (set_schema) to the current graph. In mode open or closed the existing data is validated first; on violations nothing changes and the error is shown. It changes only the current graph: a graph loaded from a file afterwards does not keep it (give the schema file in Load from file instead).

Scripts run without Rhai resource limits and without a default timeout, as in the CLI: the page is your own local front end, and Stop ends a runaway query or loop. Every run starts with a fresh script scope; the graph keeps the changes queries make until you load another one.

A run is all-or-nothing: the whole script is one unit of work, and a run that shows an error leaves the graph as it was before the run (see Transactions). Scripts may do everything except file access, which the browser does not have (see Permissions).

A link can open the playground with a query in the editor, and run it, on a sample graph or on a small graph the link carries itself:

https://play.graphersal.dev/#/play?graph=modern&q=g.v().has_label(%22person%22).values(%22name%22)&run=1
https://play.graphersal.dev/#/play?v=1&data=xZWxboMwEIb3PoZnFIFtSMOUoR36Al...&q=g.v().count()&run=1
https://play.graphersal.dev/#/play?graph=modern&q=MATCH%20(p%3Aperson)%20WHERE%20p.age%20%3E%20%24min%20RETURN%20p.name&lang=gql&params=%7B%22min%22%3A30%7D&run=1
ParameterMeaning
graphthe sample graph: modern (the default), empty, large, tree
datainstead of graph: the graph itself, as GraphSON 3.0 compressed with deflate and written as base64url
schemawith data only: the graph's schema (the schema format), encoded the same way
vthe format of data and schema; 1 (the default) is the only one so far
qthe query, percent-encoded (encodeURIComponent; a literal + must be %2B)
langgql: q is a plain GQL query and opens in a GQL tab (absent: a Rhai script)
paramswith lang=gql: the GQL tab's Parameters field, a JSON map, percent-encoded (optional)
titlethe name of the query tab (optional)
run1 runs the query once it is in the editor

The parameters are in the fragment (after #), so the browser never sends them to a server: a graph in a link goes only where you paste the link. The query goes into a new tab when the current one holds your own text. When a graph is already open in the page, the playground asks before it replaces it; declined, the query is only put into the editor. The address then goes back to #/play, so a reload does not apply the link again. With the dev server a link only opens the query: the served graph is your own data, so nothing is replaced and nothing runs. Parameters the playground does not know are ignored, so later additions keep older links working.

Share a query with its graph

The green Share link button in the top bar (also Share as link… in the Query panel's tab menu) makes such a link for the active tab: its query and the graph. A sample graph that has not changed goes into the link by its name; any other graph goes into the link itself, with its schema. Saved queries and compression rules are not included. Copy the link into a bug report or a message; whoever opens it gets the same graph and query in their own browser.

The playground over the dev server has no Share button: its graph lives on the server, and a link to the public playground could not carry it.

Only small graphs fit into a link. A link is at most 60,000 characters, so that it fits into the text of an issue: roughly a graph of a thousand elements, fewer with long property values. For a bug report, reduce the graph to the few vertices and edges that reproduce the problem and leave out everything else; a minimal graph is also the fastest to understand. For a larger graph, save it with Save ▸ Data (GraphSON) and attach the file instead.

The book uses these links: every example that runs on a sample graph has a ▶ run button next to each of its queries (or a Run in the playground link under a block with one query).

UI profiles

EXPERIMENTAL. UI profiles and the profile API may change in any release, like the dev server's hosting core.

One playground code base serves several pages: a UI profile says what the page shows. The playground as described on this page is the built-in profile full, and it is what you get unless something asks for another one. A profile names:

KeyMeaning
namelowercase letters, digits and -
titlethe page title and the top bar's name
versionoptional: the version of the product the profile belongs to ("0.1.0"); the top bar shows it (v0.1.0) beside the name instead of the engine's version, which moves into its tooltip
tabsthe tabs: {"id", "title", "builtin": "workspace"} (the workspace of this page, at most once) or {"id", "title", "module": "<path>.js"} (a tab of the profile's own); with more than one tab the page shows a tab row under the top bar
startTabthe tab the page opens on
headeroptional: {"module": "<path>.js"}, a module of the profile shown in the top bar on every tab; see "The top-bar module" below
canwhat the user can reach: true, false, "wasm" (only in the browser playground) or "server" (only with the dev server) per key; a key left out is false
cardscard templates per label for the profile's tabs (may be empty; see Cards)
graphstyles of the profile's graph views per label, classes and legend entries (may be empty; see Graph views)
stylesoptional (EXPERIMENTAL): ["<path>.css", ...], one to eight style sheets of the profile, relative paths below files like the modules; the page links each one once it has the profile, so a host need not change index.html
fileswhere the module files are: "" (next to the page) or a path ending in / on the same origin

The can keys: the top bar's devBadge, mcp, share, view, catalog, optimize, store, save, saveToFile, changeGraph, settings, theme, help, layerDiff (a layer's badge and Layer changes dialog, Start / Drop layer in the browser); the panels panel.editor, panel.results, panel.graph, panel.schema, panel.profile; the Query panel's examples and its tab kinds tab.query, tab.gql, tab.ai. What the engine cannot do stays off whatever the profile says (the Store menu needs a store, the MCP badge an MCP endpoint, Save to file a graph file on the server). full sets every key; Share, Examples and Change graph only in the browser playground, the DEV SERVER badge, the MCP badge and Save to file only with the dev server: exactly the page as it was before profiles.

Choosing a profile. The browser playground takes a built-in profile from its address: #/play?profile=demo (the parameter stays in the address, so a reload keeps it; a link that names no profile opens full). The dev server takes it from graphersal --server --ui-profile NAME|FILE (a built-in name or a JSON file with a profile object) and tells the page through GET /api/info (uiProfile); a host built on the server's core sets it with ContextBuilder::ui_profile. A host that is not the dev server can deliver a profile too (EXPERIMENTAL): the page talks to any Graphersal host, recognized by "protocol": "graphersal/1" in its GET /api/info (every host built on the server's core answers it); server only names the host (ContextBuilder::server_name, for example "graphersal-server"), and an answer without protocol (a static file server, an older host) leaves the page in the browser playground. The DEV SERVER badge shows only when the host says it is a development server ("dev": true, ContextBuilder::dev; the dev server does). A profile name the page does not know, or an object that breaks a rule above, is shown as an error naming every problem, never replaced by another profile. The built-in demo profile is a small example: a tab of its own that lists the people of the modern graph through a saved query as cards (it shows the script that defines the query when the graph has none), a Graph tab that draws them as a graph view, and the workspace without the catalog, the optimizer, the store and the examples.

A profile's own tabs. A module tab is an ES module (files + module, loaded when the tab is first shown) whose default export is a Vue component. It gets two props: params, the tab's parameters from the address (#/play?tab=<id>&key=value), and api, the profile API:

MemberWhat it does
query(name, params)calls the saved query name with named arguments through the page's engine (the dev server's POST /api/query, the browser engine's worker), under the engine's rules (read-only mode, access policy); the caller passes every parameter; resolves to its results, rejects with {message, help}
markdown(text)the text through the playground's safe Markdown renderer (never HTML)
card(label, row, options)a card of row by the profile's card template for label (see Cards)
graph(data, options)a graph view of {nodes, edges}, styled by the profile's graph key (see Graph views)
mergeGraph(base, addition)the union of two graph datas without duplicates, with the ids it added
toast(kind, text)a notification: info, success, warn or error
navigate(tab, params)shows another tab of the profile (and puts it into the address)
thememode, dark and token(name), the value of a colour token such as accent
infothe profile's name and title, whether the engine is the dev server, its version and read-only flag; info.host (EXPERIMENTAL) is the server's GET /api/info answer as the host sent it, with fields of the host's own (for example an upload limit), null in the browser playground

A module that cannot be loaded, has no default export or fails while rendering shows an error card in its tab; the other tabs keep working.

A host's home page. A server that serves the playground for several graphs, each under its own prefix such as /db/<name>/ (GET /api/info mountPath), shows the graph's name in the top bar. When its GET /api/info also has home (EXPERIMENTAL), the name links there: home is a path from the server root that starts with / ("/" is the root itself, "/admin/" a page below it). The page turns it into a link relative to itself, climbing one level per segment of mountPath, so home: "/" under /db/acme/ links to ../../, and a proxy that puts the whole server under a prefix of its own keeps working. A home that does not start with a single /, or has ./.. segments, a query or a fragment, gives no link. The home page itself is usually the host's own UI profile.

The top-bar module. A choice that affects every tab (a project filter, a status text) belongs in the top bar, not inside each tab: the profile key header: {"module": "<path>.js"} names a module (loaded from files like a tab's) whose default export the page renders in the top bar, right of the free space and left of the bar's buttons, on every tab. It gets the same api prop as a module tab and no params. Keep it small: the bar lets it shrink and never grows wider than the window, so hide parts of it on narrow screens with media queries of its own (or the playground's hide-narrow class, hidden below 760 px). A header module that cannot be loaded or fails shows a small "Header module failed" marker in the bar (its tooltip names the module and the error); the tabs keep working. The demo profile has one: the engine's kind and a button that opens its Graph tab. The profile's files are served like the rest of the page: with the dev server, put them into the --ui-dir directory (an overlay over the embedded playground). The details of the API are in the playground's js/profile-api.js.

Cards

api.card(label, row, options) shows one row of a saved query (an element, a map such as value_map() returns, or a single value) by the profile's card template for label. A label without a template gets a plain card: the label and every field of the row. The full profile defines no cards; the demo profile's Hello tab shows the people of the modern graph as cards.

A template says which fields go where; every key is optional and an unknown key is an error:

KeyWhat it shows
titlethe heading: a field (or a list of fields, the first present wins); without one, the label
subtitleone muted line of parts joined with ·
badgessmall pills after the title; a badge shows when its field (or its when) is present and true
bodya field holding Markdown: rendered by the playground's safe renderer in the full card (never HTML), a one-line plain-text excerpt in the compact card
excerptthe characters of that excerpt (default 160, 0: none)
fieldsa key/value list in the full card; long values collapse like everywhere else (setting Collapse values above); left out, every field the other parts do not show; [], none
actionsdefault buttons {id, text, kind, when, unless, title} (kind default, primary or danger)

A field is a dot-separated path (name, author.name, tags.0); on an element it is looked up in the properties first, then on the element (id, label). A one-item list, as value_map() returns every property, is shown as its item. A part is a field or an object {field, title, text, prefix, format, tone, when, unless}: title names the field in fields, text replaces the value by a fixed text, prefix comes before the value, format is text (the default; lists joined with commas), date, datetime (an ISO text or milliseconds since 1970, shown in UTC), count (a list's length) or markdown (fields only), tone colours a badge (neutral, accent, ok, warn, danger, or a map from the value to a tone), and when/unless show the part only when another field is (or is not) present and true. A field that is absent, null, empty text or an empty list renders nothing.

"cards": {
  "memory": {
    "title": ["title", "slug"],
    "subtitle": ["kind", "scope", "source", {"field": "updated", "format": "date"}],
    "badges": [
      {"field": "pinned", "text": "pinned", "tone": "accent"},
      {"field": "superseded_by", "text": "replaced", "tone": "warn"},
      {"field": "conflicts", "text": "conflict", "tone": "danger"}
    ],
    "body": "body",
    "fields": [{"field": "why", "title": "Why", "format": "markdown"}, {"field": "links", "title": "Links"}],
    "actions": [
      {"id": "pin", "text": "Pin", "unless": "pinned"},
      {"id": "forget", "text": "Forget", "kind": "danger", "unless": "imported_at"}
    ]
  }
}

The module chooses how a card is shown with options (all optional):

OptionMeaning
variant"full" (the default: body and fields) or "compact" (a list row: title, subtitle, badges, excerpt)
selectedtrue marks the card as the current one
onOpen(row)the title becomes a button and a click on the card calls it (to open the full card of a list row)
actionsthe buttons, in place of the template's
onAction(id, row)called when a button is clicked; without it the card shows no buttons. While the promise it returns is pending, the card's buttons are disabled; a failure shows as an error notification

Actions are the module's: the template only names the buttons, and the module decides what a click does (call a saved query, navigate, show a notification). Cards take their colours from the page's theme, so they follow light and dark mode, and they wrap on a narrow screen.

Graph views

api.graph(data, options) draws a graph that the module builds, typically from saved queries, with the same drawing code as the Graph panel: Cytoscape for ordinary sizes, the Fast tier (WebGL) for large views. The data is

{
  "nodes": [{"id": "a", "label": "memory", "caption": "Graph first", "data": {"kind": "feedback"}, "classes": ["pinned"]}],
  "edges": [{"id": "e1", "source": "a", "target": "b", "label": "supersedes", "data": {}}]
}

id is a text or a number (unique per kind), label chooses the style and the card template, caption is the text under the node (else the style's caption field of data, else the label), data holds the element's fields (what its card shows), classes names style classes. Every edge's source and target must be nodes of the data. Data that breaks a rule is not drawn: the view shows every problem instead (nodes[1].id "a" is used twice, edges[0].target "zz" is not a node of the data, ...).

The profile's graph key styles the views per label ("*" applies to every label; the label's own entry on top of it):

"graph": {
  "nodes": {
    "memory": {"color": "--accent", "shape": "ellipse", "size": 24, "caption": "slug"},
    "session": {"shape": "round-rectangle", "color": "#8a93a3"}
  },
  "edges": {
    "supersedes": {"arrow": true, "width": 2},
    "conflicts_with": {"color": "--danger", "arrow": false},
    "relates_to": {"color": "--text-faint", "width": 0.8}
  },
  "classes": {"pinned": {"border": {"width": 4}}},
  "legend": [{"text": "loaded at every session start", "node": {"border": {"width": 4}}}]
}
KeyValues
color#rgb, #rrggbb or a colour token of the page (--accent, --danger, ...: follows light and dark mode); a node without one takes its label's colour from the Graph panel's palette
shape (node)ellipse, round-rectangle, rectangle, diamond, triangle, hexagon, star
size (node)6 to 96 pixels (default 24)
border (node){width: 0..12, color, style}
style (edge), border.stylesolid, dashed, dotted
arrow (edge)true (default) or false
width (edge)0.5 to 12 pixels (default 1.6)
opacity0.05 to 1
captiona field path of data (as in Cards)

A class carries the same keys (node and edge keys together). Three are built in: faded (opacity 0.3), bold (a thick border, a wide edge) and dashed; a profile class of the same name replaces one, and an unknown name changes nothing. The module can also style each element itself with styleOf(element, kind), which returns {classes, ...keys} or null. Later wins: the defaults, "*", the label's entry, the element's classes, the classes styleOf returns, then the keys styleOf returns. The legend under the drawing lists the labels drawn (the key legendLabels: true by default, "nodes" or "edges" for only those, false for none: a profile that colours by classes lists its own entries), then the profile's legend entries, then the module's.

OptionMeaning
styleOf(element, kind)per-element style (above)
onSelect(selection)a click chose {kind, id, label, data, element}, or empty space (null)
onExpand(node)a double click on a node, or the side card's Expand button: the module reads the node's neighbours and merges them in with api.mergeGraph
selected{kind, id} or null: the selection set from outside (for example a tab parameter)
cardtrue or {actions, onAction(id, selection), expand}: a side card of the selected element through api.card(label, element.data, ...); expand names the Expand button (false: none; a function (selection) => text or false decides per node)
legendtrue (default), false, or extra entries [{text, node}] / [{text, edge}]
layoutcose (default), circle, concentric, breadthfirst or grid
heightthe drawing's CSS height (default 520px)
highlightwhat a selection highlights: neighbours (default: the element with its neighbours), element, none
emptyTextthe text of a view without nodes

A click selects (the rest fades), a double click on empty space or Fit fits the drawing, Esc clears the selection; the toolbar zooms, picks the layout and lays the drawing out again. When the module replaces the data (an expansion merged in, new styles), the nodes it had keep their positions and the new ones appear next to their neighbours, without a new layout. The view itself never writes: a module changes the graph through query from its card's buttons. The Fast tier draws every node as a circle and every line solid. On a server in allow-list mode the engine's force layout is not available: the browser's force layout runs up to 1,500 nodes, a larger view is drawn as a grid.

Allow-list mode

A host built on the dev server's core can serve such a profile in allow-list mode (GET /api/info apiMode: "allow-list"): the server answers only the saved queries the host selected, so only a profile whose tabs are all modules can be shown there (a profile with the workspace is an error naming the reason). See the HTTP API.

Request headers of a host

EXPERIMENTAL, like UI profiles.

A host whose server wants more on every request than the playground sends (for example a token, Authorization: Bearer <token>) tells the playground before it starts: a classic script that runs before the playground's modules sets

<script>
  window.GRAPHERSAL_ENGINE = { headers: { Authorization: 'Bearer ' + token } };
</script>

The page reads it once, when it finds the server, and every request it sends to the server's /api/ carries these headers (the API calls of the workspace and of the profile API alike; the page's own Accept, Content-Type and X-Graphersal-Client cannot be replaced). A header with an invalid name or a value that is not a single line of text is left out with a warning in the browser console that names the header, never its value. The values never go into an address or a log. A plain link cannot carry a header, so with host headers the Store menu shows no download links of stored snapshots (Download current state still works). Without the setting the page sends exactly what it always sent. Requests a profile's modules send themselves, to endpoints of the host's own, add the header themselves.

Login of a host

EXPERIMENTAL, like UI profiles.

A host that requires a login (for example a multi-database server serving the playground under /db/<name>/) answers an API request of a visitor who is not logged in with 401 and names its login page in the JSON body:

{ "error": "log in to open this database", "login": "/" }

The page then goes to that login page with the way back: login plus ?next= and the page's path and query (/?next=%2Fdb%2Facme%2F; &next= when login has a query of its own), so the login page can return there afterwards. This happens when the page starts (instead of falling back to the WebAssembly playground) and on every later request. Only a path of the page's own origin counts: it starts with / but not // and has no backslash, space or control character; any other login (another site, a relative path) is ignored and the error shows as usual. The page never redirects to the page it is on (no loop). A 401 without login (for example a host's own token check) is an error as before, and the dev server and the WebAssembly playground never send one.

The graph drawing

What the panel shows

Drawing "the first 1000 vertices" of a large graph shows an arbitrary slice of it. The Graph panel's tabs choose a meaningful part instead:

  • Whole graph: the graph itself when it has at most the vertex and edge limits of the settings (10 000 vertices and 20 000 edges by default). A larger graph shows its labels (below) with a note saying how large it is; Draw the first N vertices anyway draws that slice (said to be one), Double the limits raises them.
  • Labels: the label overview. Each vertex label is a node sized by its number of vertices, each edge is a label pair (person –created→ software) with its number of edges. The 40 largest labels are drawn, the others form one "other labels" node; the 200 largest pairs are drawn and the note counts the rest. The counts come from the graph's statistics and one pass over the edges, so they are exact (for graphs with more than five million edges, the pairs are counted over the first five million and the note says so). Double-click a label to draw a sample of its vertices with the edges between them, double-click an edge for a sample of that label pair. A sample is the first matching elements in storage order (at most 1000 vertices), not a random choice, and its note says how many of how many it shows.
  • Neighbourhood: a vertex and its neighbours, fetched from the engine. Type a vertex id (or click Neighbourhood in a vertex's properties, or the ⌖ button of a vertex row in the Results table) and choose the Depth (1 = the direct neighbours, 2 = their neighbours too, up to 5) and the direction: both, out → (the vertices it points to) or ← in (the vertices pointing to it); changing either redraws from the same vertex. Double-click a vertex to expand it by one hop (along the chosen direction): its neighbours are added, everything already drawn stays where it is and the new vertices are placed around it. The note says how many edges still lead out of the drawing, and when the limits (Settings) cut the neighbourhood, how many vertices and edges within that depth were left out.
  • Query result: the vertices, edges and paths the last query returned, with the edges between them. At most 50 000 vertices + edges by default (Result graph in the settings, up to 200 000; the result's data itself is never cut); the note says when a result has more. Double-click a vertex of the result to expand it by one hop from the engine, like in a neighbourhood: the drawing continues as a neighbourhood ("the query result, expanded"), the result's vertices stay in place, and further double clicks keep expanding. A result with more vertices than the drawing limit is not expanded (the note says so; open a vertex's neighbourhood instead).

Result highlight. In the Whole graph tab the elements the active tab's last query result refers to are highlighted and everything else is faded (Highlight result in the toolbar's ⚙ Display menu turns this off for good). ✕ Clear highlight in the toolbar, shown while a highlight is active, or Esc on the drawing (click it first) shows the graph normally again; Esc also clears a double-click selection. Clearing applies to that result only: the next query result highlights again, and switching to another query tab shows that tab's result highlighted, while the tab you cleared stays cleared. Both tiers behave the same.

Vertex details. Clicking a vertex shows its id and label, then edges: in 3 · out 5: the number of incoming and outgoing edges of the vertex in the whole graph, also when its neighbours are not in the drawing (the engine counts them from the graph, not from the visible subgraph).

Long values. In an element's details (click a vertex or an edge) and in the Results table, a text longer than 200 characters or with more than 3 lines is cut to its start and "…", and a vector (a list of 16 or more numbers) shows as vector[384] [0.12, -0.03, 0.5, 1, …]. expand shows the full value, collapse the short form again; the copy button next to it in the element's details copies the full value. Collapse values above in the Settings sets the number of characters (20 to 100 000), 0 shows every value in full. A vector in the Results table keeps its own disclosure (vector[768 f32], the JSON tab has every value).

Vertex size. Vertex size in the toolbar's ⚙ Display menu sizes each vertex by its number of edges in the whole graph: Degree (incoming + outgoing), In or Out; Off (the default) draws every vertex the same size. The size grows with the logarithm of the degree, relative to the largest degree among the drawn vertices, so a few hubs do not shrink everything else to dots. The choice is kept in the browser; while it is Off the engine counts no degrees. A query result run before the option was switched on is sized by its edges within the drawing until it runs again.

Filtering the drawing

⚲ Filter in the Graph panel's toolbar opens a popover under the button, at the left of the drawing, that decides what is drawn; it stays open while you click the drawing, does not cover the details of the selected element on the right, and Esc closes it. It lists the graph's vertex and edge labels with their counts; a dot before each vertex label shows its colour in the drawing (a ring while the label is hidden, a dashed outline while the label has not been drawn yet). Uncheck a label to hide it (all / none check or uncheck every label of that side). + condition under a label adds a condition on one of its properties, such as age > 30 or name contains "an"; several conditions of one label must all hold, and an element is drawn when its label is checked and its conditions hold. Every label you do not touch stays visible, including labels the drawer does not list (on a graph with very many labels it lists only the largest ones). A vertex with several labels is drawn when none of its labels is unchecked and the conditions of each of its labels hold. A hidden vertex hides its edges; Hide vertices without visible edges hides vertices left alone as well.

  • The operators depend on the property's type, which comes from the schema (the stored one, or the schema inferred from the data when the drawer opens): numbers and dates offer =, ≠, <, ≤, >, ≥ and between (from inclusive, to exclusive), text offers =, ≠, contains, starts with, ends with and regex, and every key offers exists and missing. A number key sends a number; every other value is sent as text and, when the schema declares the key's type, converted like a write (2024-01-01 compares as a date). The value text never decides a type.
  • Changes apply 300 ms after the last edit. On a graph with more than 100 000 vertices and edges the drawer says Large graph: Apply to use and changes apply with Apply.
  • A condition the engine refuses (a bad regular expression, a value the schema cannot convert) is marked in red at that condition; the drawing keeps showing the last filter that worked.
  • While a filter is on, a strip above the drawing says what passes, for example Filtered: 3 of 6 vertices, 1 of 6 edges (for a neighbourhood: of the vertices and edges it holds without the filter). Clear there, and the switch next to the Filter button or in the popover's header, turn the filter off without deleting it (the button then shows · off); the same switch turns it on again. Reset in the drawer deletes it.
  • Open as query opens a new query tab with the query that selects what the filter shows.
  • The filter applies to the Whole graph (the engine filters first and then draws up to the limits, so a filter makes a large graph drawable) and to the Neighbourhood. A Query result and a label sample carry no properties, so they are filtered by label only, and the Labels overview draws hidden labels faded. A neighbourhood keeps every vertex you expanded into when the filter changes: vertices it hid come back when they pass the new filter, and the count of edges leading out of the drawing counts only edges to vertices the filter shows.
  • The filter, including whether it is on, is kept per graph in the browser.
  • A graph with very many labels lists the largest ones (the drawer says so); while a label is hidden or has a condition, the labels not listed are hidden too.

Editing properties

Click a vertex or an edge for its properties, then the pencil next to the close button: a dialog edits them. Each property is one line with its name, its type (string, int64, float64, boolean, uuid, array, object, null), its value and its buttons, in columns aligned across the rows (in a narrow window a property takes two lines); a changed or invalid property is marked at its left edge. The last line adds a property: name, type and value, then + Add or Enter. Remove (with undo) and rename properties. Arrays and objects are edited as a tree below their line (expand, collapse, add and remove items and keys); the { } button edits any value as JSON, Edit as JSON (next to Save) the whole element. A string always stays a string, whatever it looks like, until you pick another type. Long or multi-line strings, and every string a compression rule covers, get a large text box below their line (⤢ opens one for any string).

When the graph has a schema, the dialog follows it: the properties of the element's label(s) are listed (also the ones not set yet), required ones are marked with *, the type, bounds and description are shown under each line, and an enum is a menu. Every change is checked by the engine before you save; its errors appear next to their fields and Save stays disabled until they are fixed. Saving writes all changes as one commit: if the engine still refuses (for example the schema changed meanwhile), nothing is applied and the dialog stays open with the error. Ids and labels are shown but not edited. The pencil is disabled, with the reason as its tooltip, while a query runs and when the graph cannot be written: a read-only view of a past state (Store menu), a backup, or a store in maintenance mode.

Edit mode

The ✎ Edit switch in the Graph panel's toolbar (in the ⚙ Display menu when the panel is narrow) turns the mouse into an editor of the graph:

  • Add a vertex: double-click empty space. A dialog asks for the label (a menu of the labels the schema declares and the graph already has; any label can be typed unless the schema is closed), an optional id (empty: automatic) and the properties, laid out by the label's schema (required ones are already there, *). The vertex appears where you double-clicked.
  • Add an edge: drag from one vertex to another (a dashed line follows the pointer; back onto the start vertex after leaving it makes a loop). The label menu offers the schema's edge labels whose connections allow the two vertices (* matches any label, any label of a multi-label vertex counts), then the graph's other edge labels; with a closed schema only the allowed ones.
  • Delete: select a vertex or an edge (click it) and press Delete, or use the bin in its card. A confirmation says how many edges go with a vertex.
  • Edit properties: double-click an element (or use the pencil), as above.

Every draft is checked by the engine with a dry run, its errors shown at their fields; each change is one commit. The drawing changes in place: the other vertices keep their positions and no layout runs. In edit mode vertices cannot be dragged around (a drag draws an edge). The Fast tier edits and deletes but adds nothing with the mouse (switch to Detailed to add). Edit mode is off, with the reason as its tooltip, in the Labels overview and when the graph cannot be written (a read-only view of a past state, a backup, a store in maintenance mode or frozen by damage).

A small cloud inventory (58 vertices, 91 edges) in the three views:

Whole graph: every vertex and edge, coloured by label

Labels: one node per vertex label, sized by its count, and the label pairs with their edge counts

Neighbourhood: the vertices within two hops of one service

Tiers

The Graph panel draws in one of two tiers:

DetailedFast
EngineCytoscape.js (Canvas 2D)sigma.js + graphology (WebGL)
Chosen by Autobelow 2000 vertices + edgesfrom 2000 (back to Detailed below 1600)
Vertex labelsalways (from 2000 elements only when large enough to read)as you zoom in
Edge labelsyesonly on hover: hovering a vertex highlights its neighbours and labels its edges
Edgescurved, loops, arrowsstraight, arrows, no loops
LayoutsForce, Circle, Concentric, Tree, GridForce (the engine's), Circle, Grid
ExportPNGPNG
Pans smoothly up toabout 2000 elements100 000 elements (the largest measured)

The switch Auto / Detailed / Fast in the toolbar's ⚙ Display menu (also in Settings) chooses the tier; Auto decides by size, with a margin so a drawing does not flip back and forth around the threshold. Switching keeps the drawing's positions. In the Fast tier a banner says what it lacks, and the controls it cannot honour (edge labels, the Concentric and Tree layouts) are disabled with the reason as tooltip. The schema drawing and the label overview always use the Detailed tier.

Drill down: in the Fast tier, click a vertex (or double-click it to select its neighbours, again for one hop more) and choose Open in Detailed: that neighbourhood is drawn in the Detailed tier, with every label and style; Back to the whole drawing returns.

A drawing waits for an explicit Draw it only where it can still make the page slow: Detailed forced above 5000 vertices + edges, the Fast tier above 200 000. A browser without WebGL (or where the Fast tier's scripts cannot load) draws in the Detailed tier, at most 10 000 vertices + edges, and says so. The Fast tier's scripts are loaded only the first time a drawing needs them.

The Fast tier draws the first 10 000 vertices of the generated 110k-element graph:

10 000 vertices drawn by the Fast (WebGL) tier

Saved queries

Saved queries are named, parameterized queries stored in the graph. The top bar's Catalog ▾ ▸ Saved queries manager lists them by folder (the description and the signature) with a badge each: R/O (it only reads), R/W (it changes data; the tooltip lists what, as inferred from its body), R/O ⚠ (read-only, its writing steps are denied until it is saved again) or unavailable (it cannot run; the tooltip says why), and its language, Rhai or GQL (the tooltip names the dialect). It manages them on the WebAssembly playground and on the dev server alike:

  • New saved query… / ✎ opens the editor: name, folder, description, the language, the parameter list and the body. Each parameter has a name, a type (string, integer, number, boolean, uuid, array of one of these, object, or a schema written as JSON), constraints (minimum and maximum, length, pattern, allowed values), a default (empty: the parameter is required) and a description; ↑/↓ reorder and ✕ removes one. The body is what goes inside the function, in the code editor with the DSL completion; the line fn name(a, b) { above it follows the parameter list, so a parameter is added or renamed in one place. Save stores it (a rename replaces the old name in the same commit); what the engine refuses is shown next to its field (a bad name or folder, a parameter whose default breaks its schema, a body that does not compile). Moving a query to another folder is changing its folder here. Delete… asks first.
  • The Rhai / GQL switch picks the language. A GQL query is the whole query text, highlighted as GQL, with no function line around it; every $name it reads must be a declared parameter and every parameter must be read (+ Add $parameters of the query declares the missing ones as strings). Switching a g.gql(`...`) body to GQL keeps its query; switching a GQL query to Rhai wraps it into g.gql(`...`, #{p: p}).
  • Save as query… in a query tab's ⋯ menu opens the editor on the tab's text. A GQL tab becomes a GQL query with every $name as a parameter, typed and defaulted by its Parameters field. A Rhai tab holding exactly one g.gql(`...`) call (as Wrap as GQL writes it) becomes a GQL query of the inner text the same way, typed by the values the tab passes in its #{..} map; any other tab becomes a Rhai query whose body is the tab's text.
  • The body editor completes the declared parameters: in a Rhai body their names (the function's arguments), shown with their type above the DSL's own names; in a GQL query $name after $. A parameter added, renamed or removed in the list is offered at once.
  • Clicking a query opens its run form, built from the parameter schemas: a number field with its minimum and maximum, a list for allowed values, a checkbox for a boolean, UUID text that is checked, one line per item for a list; defaults are prefilled and required fields marked with *, the descriptions are hints. Run writes the call, for example g.query("older_than", #{age: 29, label: "person"}), into a query tab and runs it there: it is visible, editable and in the history like any other query. The form remembers the last values per query (in the browser). An empty field takes the parameter's default.
  • In the editor, g.query(" completes the names of the saved queries, grouped by folder.
  • Saved queries travel in the catalog file, like the schema: Catalog ▾ ▸ Save catalog (.json) (graphersal-catalog-YYYYMMDD-HHMMSS.json, also Save catalog on the start page) holds the whole catalog, saved queries, compression rules and property indexes; Catalog ▾ ▸ Load catalog… (or Load catalog on the start page) adds the file's definitions to the current graph (one of the same kind and name is replaced; a compression rule compresses its values at once). A graph loaded from a GraphSON or GraphML file afterwards keeps them; a sample graph starts without any, a snapshot (.gsnap) brings its own. Stop keeps the catalog the page loaded or edited (like the schema); definitions a script made since the last load or save are gone with the rest of the run's changes.

The Catalog

The top bar's Catalog ▾ lists what the graph stores besides its data and schema, each kind with its count, and opens its manager:

  • Saved queries: the queries by folder with Run…, Edit…, Delete and New saved query… (the editor and run form described above).
  • Compression: the compression rules with their stats (compressed values, plain and stored size, ratio, saving, dictionary size), Edit…, Recompress and Drop, and New rule…: a form with name, element (vertex or edge), label (the graph's labels are suggested), path, minimum size and dictionary; the engine's errors show next to their field. Saving re-encodes the label's values at once.
  • Property indexes: the property indexes with their stats (entries, distinct values, elements per value, memory; not served on a storage that keeps the definition but serves no index) and Drop (after a confirmation), and New index…: a form with element (vertex or edge), label (the graph's labels are suggested), key and an optional name (the default <label>_<key> is shown as you type); the engine's errors show next to their field. Creating builds the index from the data at once.

The same dropdown holds Save catalog (.json) and Load catalog…. The Statistics tab of the Profile panel shows the compressed strings and the dictionaries, and the property indexes' memory, in its memory part when there are any.

A catalog change is a commit: in the store in memory it is part of the history, and on the dev server another browser tab or an AI agent sees it through the change feed.

System journal

Catalog ▾ ▸ System journal… (in the section Kept by this instance: the journal is not part of the catalog and no catalog file carries it) shows the system journal of the served graph: what the instance did, such as the store opened or closed, checkpoints, backups, damage found and permissions denied. The newest record is at the top; each row shows the time in the browser's time zone (the exact UTC time with microseconds in its tooltip), the level, the source, the kind, the message with its fields, and the record's sequence number.

  • Level shows that level and the more severe ones (error > warn > notice > info); Source shows a source and the ones below it (store shows store.backup too; the sources seen so far are suggested).
  • It opens on the newest 300 records: a long journal on disk is read from its end, never from its start.
  • While the dialog is open it shows the records written since its last read as they come (every five seconds on the dev server, every two in the WebAssembly playground; switch it off with follow new records, or press Refresh); it never reads the whole journal again. It keeps the newest 2000 records it follows.
  • Show more shows 300 more rows, reading the next older page from the journal when all held rows are shown; the line under the table says how many loaded rows are not shown and whether older records exist.

Notifications. A new journal record also pops up as a small notification in the top-right corner, without blocking anything: red for error, amber for warn, blue for notice, grey for info. warn and error stay until you close them; the others close after 30 seconds, and not while the pointer is on them. The close button (×) shows when the pointer is on a notification or it has keyboard focus (always on touch screens). At most three are shown; more become one +N more journal records notification, and repeats of the same kind and message merge into one with a counter (×3). A click opens the System journal at that record, highlighted. Only records written while the page is open pop up, never older ones. Settings ▸ Notifications ▸ Journal records sets the least severe level shown: notice and above (the default), warn and above, error only or Off; it is kept in the browser with the other settings. The playground reads the journal for them every five seconds on the dev server and every two in the WebAssembly playground, only while the page is visible; the open System journal dialog shares these reads.

In the WebAssembly playground the journal is the one of the graph's store in memory, gone with a page reload like the store. On the dev server it is the served graph's (GET /api/journal): the store's journal on disk for a --graph <store>, else the graph's journal in memory.

The store in memory

Every graph you load is kept as a Store in memory: every run that changes the graph is a commit, and the Store menu in the top bar checkpoints, marks, opens past states read-only, forks and rolls back. Everything in memory is lost on page reload: download a .gsnap to keep a state. The details are on the page The Store in the Playground.

Store ▸ Start a layer over this graph freezes the loaded graph as the base of a layer: writes go to the layer, a top-bar badge shows the changes, and the drawing outlines added and modified elements. See Layered graphs: In the playground.

The schema editor

The Schema panel's Tables tab shows the schema (the stored one, or, without one, the schema inferred from the data; the badge says which) as nested tables on one page: a table per vertex and edge label, one row per property with its type, required, nullable and a compact constraint column (0..150, length 1..80, ^\d{5}$, <= 10, one of a, b). A nested object is a table inside its row; arrays show as array of T (an array of objects gets the item table); objects deeper than the first level start collapsed as object {n fields}. The format is described in Schemas.

Everything is edited in place, and every edit changes a draft, never the stored schema:

  • the type (a dropdown; uuid is string + format: "uuid", any is {}; a union of several kinds is edited in the JSON tab), required, nullable, the property name, a + property row in every table, and a detail form per property (open it from the constraint column) with the constraints of its type, enum, const, additionalProperties for objects, and the annotations title, description, default, examples, $comment, deprecated;
  • labels: add, rename (a renamed vertex label is renamed in the edge connections too), remove; the connections of an edge label with from/to dropdowns (* is any label; no connection allows every pair); additionalProperties per label;
  • the mode (toolbar) and meta (free JSON);
  • the JSON tab is the same draft as text, synchronised both ways: text that parses becomes the draft, invalid JSON is shown inline while the tables keep the last valid state;
  • Infer from data starts a draft from infer_schema(); Load… reads a schema.json into the draft; Download saves what the editor shows as schema.json;
  • Freeze as open / Freeze as closed (offered while the graph stores no enforcing schema and no draft is being edited) store the inferred schema with that mode in one step, set_schema(infer_schema(), mode): see Freeze the structure you have. It always applies, except closed with vertices or edges without a label: then nothing changes and the report is shown.

A property's default is stored when a vertex or edge is created without it (see Defaults on create), never filled into existing elements; the editor's backfill script uses it as the value it writes into those.

With a draft, the toolbar offers the review and the apply:

  1. What changes lists the changes from the stored schema (diff_schema), each marked backward compatible or not (compatible: it only adds or relaxes, so data and clients written against the old schema keep working; adding an optional property is compatible, removing one is not; see the rule set). Existing data that conflicts is what the next step finds.
  2. Check against data validates the existing data against the draft (validate_schema_patch; nothing changes) and lists the violations grouped by rule. A click on a group opens a new query tab that runs a query showing the offending elements (g.V().hasLabel("person").not(__.has("email")) for a missing required key, the sample ids for a constraint violation).
  3. Apply stores the draft with patch_schema (a JSON Merge Patch computed from the stored schema; one unit, all or nothing). It checks first and is blocked while the data violates the draft. To make a key required on existing data, Open a backfill script writes the recipe as one run: the draft with mode none, a property(key, value) for every element that lacks the key (the draft's default, or a placeholder to edit), then the draft itself; a playground run is one unit, so nothing is kept unless all of it succeeds.

Discard drops the draft. A draft that sets a member to null ("default": null) cannot be a merge patch; Apply then uses set_schema with the whole draft. The editor talks to the engine only through the seven schema methods, the same as in Rust, the DSL and Python. The Graph and Mermaid tabs draw the stored (or inferred) schema, not the draft.

When the panel infers. Inferring a schema reads the whole graph, so the panel does it only when it is first shown (expanded) and when you press its refresh button, never after every change of the graph. A stored schema is read again after every change (a schema set or changed by a query shows at once). Without one, a change (a query that writes, the property editor, a change made in another tab or by an AI agent) keeps the schema inferred last on screen and adds the badge may be outdated - refresh next to the refresh button; press refresh to infer it again. The same badge appears when the stored schema is dropped. Loading another graph, opening a read-only view of the Store, going back to the live graph, rolling back or switching databases replaces the graph: the panel infers once for it, right away if it is shown, else when you open it. The WebAssembly playground and the dev server behave the same.

If the playground freezes

Open the playground's address with /reset added (for example http://localhost:8000/reset/). That page loads nothing of the playground itself: it removes the playground's saved state from the browser (settings, panel layout, theme, query tabs, view choices; the query history is kept) and then opens the playground with the Modern sample graph. Use it when a saved state makes the page hang again after every reload, for example a huge drawing that is restored on start.

Dev Server and MCP

DEV mode, unstable, local only, temporary. Not for production. The dev server is a way to try Graphersal "as a small server" and watch how it behaves. Its HTTP API is internal to the playground and changes without notice; it has no authentication and by default serves only the loopback (127.0.0.1, and [::1] when the system has IPv6; inside a container 0.0.0.0, see Listening address and Docker). Do not expose it to a network you do not trust.

graphersal --server serves the Web Playground UI over HTTP, with the CLI process itself as the engine instead of the WebAssembly worker. It is the same single-page app: the page asks the serving origin GET /api/info at start, and when a Graphersal host answers (its answer names the protocol, "protocol": "graphersal/1"), every engine call goes to it over HTTP. Served from GitHub Pages or any static file server, the page stays the WebAssembly playground.

Start it

cargo run -p graphersal-cli -- --graph modern --server            # or: graphersal --graph ... --server
# Graphersal dev server: http://127.0.0.1:8080/
graphersal --graph ./mygraph.json --server --port 9000            # a GraphSON or GraphML file
graphersal --graph large --server --port 0                        # 0 picks a free port
graphersal --graph data/ --server                                 # a Store: every commit is durable
graphersal --graph new/ --create-store --server                   # create the store when missing
graphersal --graph g.graphml --schema schema.json --server        # a graph file loaded against its schema
  • --graph takes the same sources as the CLI: modern (default), empty, large, tree, a GraphSON (.json, .jsonl, .graphson) or GraphML (.xml, .graphml) file, a packed snapshot (.gsnap), or a Store (a directory or a .gstore file; see On a Store).

  • --port (default 8080; 0 picks a free one). The address is the only line on stdout; the "dev mode, unstable, local only" banner goes to stderr.

  • --host <ADDR> (default 127.0.0.1, inside a container 0.0.0.0): the address to listen on, see Listening address and Docker.

  • --read-only: every write is refused (queries, schema, catalog, "Save to file"; MCP offers only its reading tools) and a Store is loaded without its lock and without writing anything, so a read-only file or file system works (Running in Docker). A Store the process may not write is served that way anyway, with a note.

  • GET /healthz (liveness) and GET /readyz (readiness: 503 while the graph loads or the server stops) answer without a lock and under any Host, for container health checks; graphersal health [--ready] probes them (Health checks). The server listens before the graph loads and answers every other request with 503 until then.

  • Ctrl+C or SIGTERM stops the server: the running query is cancelled, a Store is closed cleanly, the exit code is 0 (Stopping).

  • The playground UI is embedded in the binary (its static files: index.html, css/, js/, assets/, reset/), so graphersal serves it on its own, from any working directory. --ui-dir <DIR> names a directory whose files win over the embedded copy (for working on the UI); a file missing there comes from the embedded copy. Without --ui-dir, ./playground is used that way when it exists (a repository checkout), else the embedded UI alone. An explicit --ui-dir that does not exist is a usage error. The stderr banner says where the UI comes from: UI: embedded or UI: <dir> (embedded fallback) (in its Server section). A path leaving the UI root (..) is a 404.

  • --ui-profile <NAME|FILE> (EXPERIMENTAL) chooses the UI profile the pages show: a built-in name (full, the default: the whole playground; demo) or a JSON file holding a profile object. GET /api/info names it as uiProfile; a profile's tab modules are files of the UI, so put them into the --ui-dir directory. An unknown name or an invalid object is not refused at start: the page shows it as an error (never another profile).

  • After the graph is in memory, stderr shows what was loaded and how the server runs, in sections under the warning box, one key: value row per fact (long values wrap under their column; the claude mcp add command never wraps, so it copies in one piece):

    • Store (a Store only): its path, the commit and the number of snapshots, its state (durable, a read-only backup, or maintenance mode), and the load time (snapshot load + WAL replay, with the number of WAL commits replayed);
    • Graph: for a sample or a file its source and load time; the vertex and edge totals, the ten largest vertex and edge labels (+N more for the rest), the graph's memory (structure, indexes, properties, and the property indexes when there are any), the memory of its workload statistics (0 B until queries ran, unless a Store brought its saved ones), the loaded embedding models (when there are any) and the process heap, and the compressed and deduplicated values when there are any (the same data as the playground's Profile -> Statistics tab);
    • Embedding models (when there are any): every model of the database besides the built-in hash-ngram/1 (imported into the Store, or carried by a .gsnap file), by its repository (the name queries call it by) with its licence and whether it is the default, a note when the database holds models but none is the default, and every model the schema names that the database lacks (Embedding Models in a Store); a note keeps the layout of the CLI's notes (its headline in the row, one detail per line below it, each command on a line of its own under its # comment, never wrapped);
    • Server: the limits of every query, where the UI comes from, the MCP endpoint and the command that connects Claude Code, the AI Chat, and the addresses it listens on.
    ── Store ─────────────────────────────────────────────────────────────────────
      path:      data
      commit:    7021, 1 snapshot
      state:     durable: every commit is in the write-ahead log before the query
                 answers; Ctrl+C stops the server and closes the store cleanly
      loaded:    2.02 s (snapshot, no WAL commits to replay)
    
    ── Graph ─────────────────────────────────────────────────────────────────────
      size:      193,947 vertices, 923,752 edges
      vertices:  45 labels: Method 91,098, Field 39,155, Type 16,306, DocChunk
                 13,018, File 12,814, Bean 3,293, LogMessage 3,129, ConfigKey 2,989,
                 Package 2,602, ExternalArtifact 1,278, +35 more
      edges:     78 labels: CALLS 251,991, USES_TYPE 142,362, DECLARES 122,073, ...
      memory:    graph 703.2 MiB (structure 144.7 MiB, indexes 64.0 MiB, properties
                 486.8 MiB, property indexes 7.6 MiB)
                 workload statistics 182.4 KiB
                 model 506.4 MiB (minishlab/potion-multilingual-128M 506.4 MiB)
                 process heap 1.6 GiB
                 process 47 % of 3.4 GiB (cgroup)
    
    ── Embedding models ──────────────────────────────────────────────────────────
      model:     minishlab/potion-multilingual-128M (the default), licence MIT
                 stored in data; loaded at its first use
                 model2vec/minishlab/potion-multilingual-128M@<12 hex>
    
    ── Server ────────────────────────────────────────────────────────────────────
      limits:    none (start with --timeout, --safe-limits, --max-* to bound
                 queries; the process memory ceiling applies, --memory-limit)
      UI:        embedded
      MCP:       http://127.0.0.1:9010/mcp
      connect:   claude mcp add --transport http graphersal http://127.0.0.1:9010/mcp
      listening: http://127.0.0.1:9010/ and http://[::1]:9010/ (IPv6 loopback)
    
  • The limit options of the CLI apply to every query of the server (see Limits). The display options (--format, --max-rows, --max-items, --no-limit, --spelling) are refused with a usage error, because the UI sets the display per query; -e/--in cannot be combined with --server either.

  • Stop the server with Ctrl+C (SIGINT) or SIGTERM: a running query is cancelled (it rolls back) and an open store is closed cleanly; the exit code is 0. A second Ctrl+C exits at once.

The server needs no WebAssembly build: playground/pkg/ is not used in this mode.

Arguments from a file

--args-file FILE (or @FILE) reads arguments from a JSON file, so a server with many flags starts with one. The keys are the long flag names without dashes:

{
  "_comment": "keys starting with _ are comments",
  "graph": "data/",
  "server": true,
  "port": 8080,
  "mcp": true,
  "mcp-read-only": true,
  "mcp-instructions": "operator-notes.md",
  "timeout": 30000
}
graphersal --args-file args.json                 # everything from the file
graphersal @args.json --port 9000                # the command line wins: port 9000
graphersal --args-file args.json -e 'g.v().count()'   # a repeatable flag adds to the file's
  • A switch (server, mcp, no-limit, ...) is true; false is the same as leaving it out. A number is written as a number ("port": 8080), a string as a string. eval repeats: a string or an array of strings. Every flag of graphersal --help is a key except help, version and args-file.
  • Relative paths (graph, schema, ui-dir, ui-profile, ai, mcp-instructions, mcp-config) resolve against the directory of the args file, not the working directory. The sample names (modern, empty, large, tree) and a ui-profile name (full, demo) stay as written.
  • The command line wins. The file's arguments come first, as if typed before the others: a flag given on the command line replaces the file's, a repeatable flag (--eval) adds to it. The usual validation runs on the merged arguments, so a file with "server": true plus -e on the command line fails as --server -e does.
  • A file may not name another args file, and --args-file may appear once. An unreadable file, invalid JSON, a value of the wrong type or an unknown key is a usage error (exit code 2) that names the key; values are never echoed. Unlike the --ai file, where an unknown key only warns, an unknown key here is an error (a near-typo adds did you mean "server"?): a flag that is silently dropped could switch off mcp-read-only or mcp-token. Only a key starting with _ is a silent comment. The keys embedder and default-embedder of earlier releases are refused with the import command (0.5.0 removed the flags).

The file holds no secrets by design (give --mcp-token on the command line or keep the file private); the repository has an example, crates/graphersal-cli/examples/args-dev-server.json.

Limits

The limit options become session presets: every query sent to the server runs under them, as every script of the one-shot runner does (the resource limits page explains each limit).

OptionWhat every query gets
--timeout <MS>evaluationTimeout on every traversal, and the budget of a query as a whole (a loop {} between traversals stops too, with "Script exceeded evaluationTimeout of N ms")
--memory-limit <BYTES|auto|none>, --memory-headroom <BYTES>the process memory ceiling (memory.limit, on by default: the cgroup limit minus the headroom, else 80 % of RAM): a query, import or write that would take the server's live heap over it fails with "Resource limit 'memory.limit'" and rolls back, instead of the process being killed; a --graph store or file whose graph does not fit refuses to load (exit 1, the error names the minimum). One setting for the whole server process, not a session preset
--max-traversers <N>traversal.max_traversers
--max-materialized-bytes <N>traversal.max_materialized_bytes, the per-query memory limit (0 is unlimited)
--max-string-size <N>the script's string limit and traversal.max_string_bytes
--max-value-depth <N>the script's value depth and traversal.max_value_depth
--max-operations, --max-array-size, --max-map-sizethe Rhai limits of the server's script engine
--safe-limitsthe library's SAFE script limits and the engine's traversal defaults

A query overrides a traversal option with g.with(..) (for example g.with("evaluationTimeout", 0)), as in the CLI. The values in force are listed on stderr at start (the limits row of the Server section: "of every query: ...", or "none (...)" without limit options) and in GET /api/info (presets). Without limit options the server runs like the playground: no script limits, the engine's traversal defaults, no time budget; Stop is the way to end a runaway query.

graphersal --graph large --server --timeout 5000 --memory-limit 4000000000

Read-only serving mode

--server --read-only is the read-only serving mode: the data cannot change, so the server runs the queries of many browser pages and MCP clients in parallel instead of one after the other. It is meant for a knowledge base served to many agents and readers (a Docker image, a shared machine).

The server has no authentication. Whoever reaches its port can read the whole graph and run any reading query. What protects it is that nothing can be written (every write is refused, the database file is never touched) and the limits below; keep the port on a network you trust or behind a reverse proxy that authenticates.

graphersal --graph kb.gstore --read-only --server --host 0.0.0.0 --port 8080 \
  --mcp --mcp-read-only --workers 8

How it works:

  • Workers: --workers N threads (default: the machine's available parallelism) each own a session over the SAME graph in memory (one copy of the data, one copy of each embedding model). Every query of a page, of an MCP client and of the AI Chat goes to them through one queue.
  • Bounded queue: at most --queue N jobs wait for a worker (default 4 x workers). A request that finds the queue full, or that waited longer than --queue-timeout S seconds (default 10) for a worker, is answered 503 with Retry-After: 1, so the client retries it a moment later (the playground shows the error; run the query again).
  • Fairness: one client (an MCP session, a browser page) has at most --max-inflight-per-client N queries running or waiting (default 4). A further one waits for a slot of its own client, up to the queue timeout, then gets 503: one looping agent cannot take every worker.
  • Connections: at most --max-connections N requests are handled at once (default 512, a thread each); beyond it the server answers 503 at once. The health probes /healthz and /readyz are always answered.
  • Stop: the Stop button of a page cancels only that page's query, never another page's or an agent's, also while the query still waits in the queue.
  • Graceful stop: on SIGTERM (docker stop, Kubernetes) /readyz turns 503, no new query is taken, the running ones get --drain-timeout S seconds (default 20) to finish, then the waiting ones are refused, every query is cancelled (also an AI Chat turn's) and the process exits with code 0. A query that has not stopped 2 s later is named in a warning on stderr.
  • Safe defaults: unlike the read-write server (which runs like the playground, without limits), every query runs under the SAFE script limits (--safe-limits), a 30 s timeout (--timeout 30000) and a 500 MiB per-query memory limit (--max-materialized-bytes 524288000). Each flag still overrides its own default (--timeout 0 turns the timeout off, --max-operations 0 lifts the operation limit).
  • MCP sessions are stateless: the session id initialize answers is signed (HMAC-SHA256) instead of being kept in a table, so any number of agents stay connected and none evicts another. The key is random per process (after a restart the agents initialize again), or the value of the environment variable GRAPHERSAL_MCP_SESSION_KEY (at least 32 characters, never printed): several replicas behind a load balancer with the same key accept each other's session ids.

What is not available in this mode: the Store panel, views of past states, rollbacks and history (a Store is opened read-only, as a graph); "Save to file"; scheduled jobs (defining, switching or running one answers 409); and every write (queries, schema, saved queries, indexes, compression rules), which the graph refuses as with --read-only alone. The change feed stays empty: nothing changes. Force layouts of the Graph panel work; their jobs are shared by all pages.

GET /api/info adds serving: the pool's settings, the queries running and waiting, and the requests refused so far (refused.queueFull, expired, clientBusy, stopping). The start banner's serving row shows the settings. How agents use the MCP endpoint (tools, saved queries, clients, refusals of MCP requests) is in MCP usage statistics.

The new flags need --server --read-only (--max-connections only --server: on a read-write server it caps the requests too, without a default); like every flag they can be keys of an arguments file ("workers": 8).

Embedding models

The server serves the embedding models of its database: the models imported into the --graph Store, or carried by a --graph .gsnap file; every query of the server, the MCP query tool and the AI Chat's tools use them (embed(), the embed step, text queries, vector rules, g.embedders()). GET /api/info lists them as embedders. The models the schema needs are loaded when the store opens, the others at their first use. Running a model is local; only graphersal embed-model download connects to Hugging Face (Embeddings).

graphersal embed-model download minishlab/potion-base-8M
graphersal embed-model import minishlab/potion-base-8M --into data/ --default   # the store closed
graphersal --graph data/ --server --mcp

The import into a closed store appends one commit without loading the graph; while the server has the store open the import is refused (Locked): stop the server first. Changed in 0.5.0: --embedder and --default-embedder are removed (Embedding Models in a Store).

What the UI does in this mode

  • A red DEV SERVER · unstable badge in the top bar (the server says "dev": true in GET /api/info). There is no start page and no graph choice: the server serves the one graph it was started with. To use another graph, restart the server.
  • Queries, results, profiles, the graph drawing, the schema views and the schema editor work as in the WebAssembly playground: both run the same session code (the internal crate graphersal-session), so the answers are the same structures. The Examples menu is not shown: its queries are written for the sample graphs, and the server serves its own.
  • The Statistics tab of the Profile panel shows the limits the server applies (its presets, from the options above) beside the engine's defaults for the rest, next to the graph's counts and memory footprint.
  • Several browser tabs share the one graph. Queries run one after the other. A change made in another tab (or by an AI agent, see MCP and AI Chat) reloads the page by itself within about 2 seconds and shows "changed: commit N". While the graph changes fast (a bulk load: changes from elsewhere in three polls within 10 seconds), the page reloads at most every 30 seconds instead and a banner says so, with Refresh now and Pause auto refresh (no automatic reloads until Resume); 10 seconds after the last change it reloads once more and goes back to normal.
  • Stop cancels the query this tab started on the server: it stops at its next check (where evaluationTimeout is checked, plus the script loop), fails with "cancelled", and everything it changed is rolled back; a query that still waits for the server (behind another tab's query) runs nothing. The graph stays as it was before the query; nothing restarts. Stop never cancels another tab's query, an agent's query over MCP or an AI Chat turn's query (the chat has its own Stop).
  • Save ▾ downloads the graph data (GraphSON or GraphML), the schema (JSON) or a snapshot, one file per entry, as in the playground. Save to file appears when the server was started with a graph file: it writes the graph back to that file in its format (GraphSON, GraphML or a packed snapshot), atomically (a temporary file next to it, then a rename). The stored schema is not part of a GraphSON or GraphML file: with --schema FILE Save to file writes the schema back to that file too (atomically, both temporary files are written before either is renamed; a cleared schema is written as {}). Without --schema, saving a graph that has a schema shows a warning (the schema is not part of a GraphML/GraphSON file: download it with Save schema, or start the server with --schema FILE); no file is ever written beside the graph implicitly. A snapshot (.gsnap) is lossless: schema and saved queries included.
  • Without a Store directory nothing is saved automatically, and nothing survives a restart of the server. On a Store directory every commit is persisted (below).

Listening address and Docker

Without --host the server binds the loopback, 127.0.0.1 and, when the system has IPv6, [::1] on the same port (the listening row on stderr then names both addresses; if that bind fails the server stays on IPv4, silently). Only programs on the same machine reach it.

Inside a container the loopback is useless: a published port (docker run -p 8080:8080) arrives on the container's network interface. So when the server finds /.dockerenv (Docker), /run/.containerenv (Podman) or the variable KUBERNETES_SERVICE_HOST (a Kubernetes pod), its default is 0.0.0.0, every interface of the container, and docker run -p works without flags. The repository's Dockerfile, health checks, read-only serving, SIGTERM and Kubernetes probes: Running in Docker.

# an image that has the graphersal binary; the Store lives in a volume
docker run --rm -p 8080:8080 -v "$PWD/data:/data" my-graphersal-image \
  graphersal --graph /data --create-store --server --port 8080
# the same with the address spelled out (it also works where the container is not detected)
docker run --rm -p 8080:8080 my-graphersal-image \
  graphersal --graph modern --server --port 8080 --host 0.0.0.0
# then open http://localhost:8080/ on the host

docker run -p 127.0.0.1:8080:8080 ... publishes the port on the host's loopback only, which keeps the server private to the host machine.

--host <ADDR> names the address explicitly, on any machine: an IP address (0.0.0.0 every IPv4 interface, :: every IPv6 interface, 192.168.1.5 one interface, 127.0.0.1 the loopback, which also overrides the container default) or a host name that resolves on the machine (localhost is the loopback default). An address that is not valid or does not resolve is an invocation error (exit code 2). For a wildcard address the URL on stdout is http://127.0.0.1:<port>/ (http://[::1]:<port>/ for ::), the one a browser on the same machine opens, and the listening row adds (all interfaces: 0.0.0.0:<port>); otherwise it is the address or name given.

Warning. On any address other than a loopback one the server is reachable from the network and has no authentication: whoever reaches the port can read and change the graph, write Store checkpoints and backups, and, with --ai, spend the AI provider key. The banner says so, and a one-line warning on stderr names the address. Publish the port only to networks you trust, and use --mcp-token for the MCP endpoint.

Safety

The server is a local development tool: it binds the loopback unless --host or a container says otherwise (above). It has no authentication, and checks the Host and Origin headers of every request against DNS rebinding and cross-site requests:

  • On the loopback, Host must name the server itself (127.0.0.1, localhost or [::1], or the --host name, with the server's port), and an Origin must be one of them.
  • On any other address the port of Host is not checked (a container's port mapping changes it) and its name must be an IP address, localhost (or a *.localhost name), a name without a dot (a machine name, a Docker Compose service name such as http://graphersal:8080), or the --host name. Any other fully qualified name is refused (403): a DNS rebinding attack sends the attacker's domain. To open the server by a domain name, start it with --host <that name>. An Origin must be the request's own origin (http:// followed by its Host), so a page of another site is refused even when it names an IP address.
  • --allowed-host <NAME> (repeatable; also the variable GRAPHERSAL_ALLOWED_HOSTS, names separated by commas) admits further names on either address: a Host naming one of them is served on any port, and an Origin of http:// or https:// one of them is accepted whatever the Host. They are the public names of the server behind a reverse proxy that ends TLS (https://kb.example.com); the listening banner lists them under allowed hosts. A value with a scheme, port or path is an invocation error (exit code 2). See Behind a reverse proxy.

Beyond the headers, every write needs Content-Type: application/json, which a page of another site cannot send without a CORS preflight that the server never answers. Scripts cannot read or write files (as in the playground: file access is denied), so a file is written only by the explicit Save to file. Request bodies are limited to 16 MiB; a malformed request gets a 4xx answer with a JSON error. A request that declares a body larger than 64 MiB (Content-Length) is ignored without an answer: the HTTP library would otherwise reserve memory for the whole declared size.

Run administration

--admin-runs (EXPERIMENTAL, off by default) lets whoever runs the server see and stop every query of every client: browser pages, MCP agents and AI Chat turns. A page's Stop button (POST /api/cancel) reaches only that page's own runs; the run administration reaches all of them.

graphersal --graph data.gstore --server --admin-runs --admin-runs-token my-admin-secret
  • GET /api/admin/runs lists every run that waits for the session or runs now, oldest first: {runs: [{id, client, alias, kind, state, cancelled, startedAtMs, durationMs, text, identity, mount}], textHeadChars}. client is page:<id> (a browser tab's X-Graphersal-Client), mcp:<MCP session> or ai:<conversation>; kind is query, layout, tool (an MCP or AI Chat tool call) or other; state is queued or running; text is the first 200 characters of the query (textHeadChars).
  • POST /api/admin/runs/cancel {"id": 12} cancels the run 12 whatever its client: a waiting run runs nothing, a running one stops at its next check, and what it changed is rolled back (the client gets its usual "Script cancelled" answer). {cancelled} says whether the run was there (an ended run answers false).
  • With --admin-runs-token <SECRET> every admin request must send the header X-Graphersal-Admin-Token: <SECRET> (403 without it or with another value). Without a token only the Host/Origin checks protect it, so anyone who can reach the server sees the other users' query texts.
  • Without --admin-runs both endpoints answer 404 ("the run administration is off: start the server with --admin-runs") and GET /api/info has no adminRuns field. With it, GET /api/info answers adminRuns: {"tokenRequired": true|false} and the playground shows a Runs button in its top bar: a list that reloads every 2 seconds while it is open, with a Kill button per run (it asks for the token when the server needs one; the token stays in the page's memory).

The MCP endpoint offers no tool for it: stopping other clients' work is an operator's act, not an agent's. A host built on the server's core (graphersal-serve) turns it on per graph with ContextBuilder::admin_runs(token); a graph served under a mount path (/db/<name>/) lists and stops only its own runs, and the host's own cross-graph view calls Runs::list / Runs::cancel_run.

On a Store

graphersal store create data/ --from modern      # once (or: --graph data/ --create-store --server)
graphersal --graph data/ --server                # then open http://127.0.0.1:8080/
graphersal --graph new/ --create-store --on-damage continue --server   # a new store, its damage policy

The server opens the Store read-write (its lock is held while it runs) and serves its graph: every commit is written to the store's write-ahead log before the query answers, so writes survive a restart of the server, also a crash or kill -9 (the next start replays the WAL; stderr then notes that the store was not closed cleanly, which is harmless). Stopping the server with Ctrl+C is such a stop: everything committed is already on disk.

The store's warnings go to stderr as WARN graphersal::persist::store: ... lines: a failed automatic checkpoint, damage found while it runs, a read-only open (also when the store is used with -e, --in or the REPL); an open that rewrote a damaged GRAPH copy notes it on stderr before the start banner. GRAPHERSAL_LOG sets the level (off, error, warn = the default, info, debug, trace; info also notes a checkpoint that encodes the loaded graph because the WAL since the last snapshot exceeds the merge bound). A whole script is ONE commit here: a large one is written to the WAL in parts of 64 MiB, and the process memory ceiling bounds it (the unit's changes are held while it commits); a script that drops and re-creates a huge graph can still be refused as a whole: run the drop on its own and load in several runs (The size of one commit).

The UI shows a Store menu in the top bar (its ↻ button in the top right corner reloads it): the position (commit number and last commit time), the WAL size, Checkpoint (write a snapshot now, optionally named) and Mark (name the current position), and the history:

  • Marks: "a name for a position in the history; any commit can be restored, not only snapshots". Snapshots: "a full copy of the graph at a commit (fast start)", each with a .gsnap download. The menu lists the newest five of each; Calendar… (See all… when there are more) opens the history calendar below. The table in Snapshots and marks compares them.

  • Every snapshot and mark has three actions, and Go to commit... / Go to time... (a date and time in your browser's time zone) offer the same for any other point:

    • Open read-only here (View): the server serves the state at that point instead of the live graph. A banner says "Read-only view of commit N (mark X)" and offers Back to the live graph. Queries, the graph drawing, the schema and the statistics show that state; every write is refused ("the served state is a read-only view at commit N ...: writes are refused"; its help points to Back to the live graph and to a fork), and so are Checkpoint and Mark. The live graph is not changed; Download current state saves the view.
    • Fork to a new directory...: asks for a directory (empty: <store>-fork-<target> next to the store; a relative path is next to the store; it must not exist) and makes a new store there. The answer says where it is and how to open it (graphersal --graph <new> --server --port 0, another server). This store is not changed; to undo, delete the new directory.
    • Roll back here...: a confirmation explains the effect: everything after commit N moves to the attic (restorable as long as nothing new is committed or marked), the live graph switches to commit N. The option "delete instead of keeping in the attic" (off by default) deletes it for good. The server waits for a running query (it never cancels another client's query: use that tab's Stop), rolls the store back in place and serves the result; the Graph, Schema and Statistics panels reload and every tab's result is marked as possibly stale.
  • Attic: one entry per rollback (when, commit range, size) with Show changes (per commit: time, author, counts by kind, examples), Restore (undo the rollback; disabled with the reason once something was committed or marked since, then use Fork), Fork... (the rolled-back history as a new store) and Remove... (delete it for good, asks first).

  • Disk space: the compaction advice, refreshed with the menu (cheap, nothing is read): "Compact recommended" or "No compaction needed" with the reason (which threshold decided), the file's size, live and free-inside bytes for a single-file store, what a prune would free first, and the free disk space a compaction needs. Compact (always enabled, except in a read-only view, in maintenance mode or on a store frozen by damage; when the advice does not recommend it, it asks first, showing what it would free and the reason; when marks would become unreachable it ALWAYS asks first, recommended or not, naming them and saying they cannot be opened afterwards) prunes up to the current commit and, for a single file, rewrites it without its free space; queries wait while it runs. On a directory store Compact is the prune.

  • Backup: a directory (empty: <store>-backup next to the store, which takes increments from then on; a relative path is next to the store) and full; Back up copies the store while queries and commits go on, reading every checksum in the store and again in the copy. The answer says how much was copied and how to restore it.

  • The store's creation parameters: when it was created and its damage policy ("on damage: maintenance (turns read-only; fixed at creation)").

  • Damage found on disk while the server runs (a Back up, a Checkpoint, Verify, the automatic checkpoint found it): a red block with what found it, every problem, and what the policy did (with maintenance the store is READ-ONLY now: Checkpoint and Mark are gone, writes are refused); Back up from memory writes the intact graph in memory into a new directory without touching the damaged store, then repair the store with graphersal store repair. A banner at the top says the same in every tab (through the change feed), and MCP's graph_info carries it (damageFound), so an agent learns why writes fail.

The server runs on a single-file store the same way (graphersal --graph graph.gstore --server, --create-store creates it); a fork of it becomes a .gstore file next to it (graph-fork-<target>.gstore).

Opening a view, going back to live, a rollback and an attic restore change the graph the session serves, so they cancel a running query first (it rolls back). Several browser tabs share the one server: a view opened in one tab is the view of all (the other tabs follow through the change feed within two seconds: banner, graph, Schema and Statistics; an MCP agent's graph_info says so too and its writes are refused). The CLI's graphersal store commands that only read (list, fork, verify, ...) work while the server runs; rollback and attic restore from the CLI report "in use" then, use the menu.

On a backup directory (graphersal --graph backup/ --server) the server serves the backup read-only: a banner says "Backup: read-only" with its position and the command that makes it the live store (graphersal store restore backup/, after stopping the server); the Store menu shows the backup's snapshots and marks with View and Fork only (no Checkpoint, Mark or Roll back), and every write is refused. See Backup and Restore.

The history calendar

A store keeps hundreds or thousands of snapshots and marks; the Store menu shows only the newest five of each. Calendar… opens a dialog with a month calendar of all of them: each day shows two badges, the number of marks (M) and of snapshots (S) on that day in your browser's time zone (a snapshot counts on the day of the commit it holds), their colour deeper the more there are. ‹ › and the month and year selectors (each month with its counts) move through the history; Today, Newest and Oldest jump. A click on a day (or Enter) lists all its marks and snapshots with time and commit and the same actions as the menu (View, Fork…, Roll back…, .gsnap). The filter keeps marks and/or snapshots and matches a name or #commit. Keyboard: the arrows move between days (across months), PageUp/PageDown change the month, Home/End go to the start or end of the week, Esc closes. The WebAssembly playground's store in memory has the same calendar.

MCP: an AI agent on the same graph

With --mcp the server also offers a Model Context Protocol endpoint at http://127.0.0.1:<port>/mcp. An AI agent such as Claude Code then works with the same graph and session as the browser: you watch and query in the playground while the agent queries, changes the graph or evolves the schema through MCP tools, and the page reloads by itself when the agent changed something. MCP works with the graph only: persistence (checkpoints, marks, views of past states, rollback, the attic, backups, compaction) stays in the browser's Store menu, so the agent's tool list stays short.

Start the server with MCP

graphersal --graph modern --server --port 9000 --mcp
# Graphersal dev server: http://127.0.0.1:9000/        (stdout)
#   MCP:       http://127.0.0.1:9000/mcp               (stderr, Server section; the next row,
#   connect:   claude mcp add --transport http ...      is the command that connects Claude Code)

Any --graph source works, a Store directory too (the agent gets the same graph tools; the commits it makes are journaled like the browser's):

graphersal --graph data/ --server --port 9000 --mcp

Read-only for the agent (only the reading tools are offered, and a query that would create, change or delete data, the schema or a catalog definition (a saved query, a compression rule, a property index) is refused; the browser can still write):

graphersal --graph modern --server --port 9000 --mcp --mcp-read-only

With a token (every MCP request must send Authorization: Bearer <token>, otherwise 401):

graphersal --graph modern --server --port 9000 --mcp --mcp-token my-secret-token

With every saved query as a tool of its own (besides list_saved_queries and run_saved_query, which are always there), for a small, curated catalog:

graphersal --graph data/ --server --port 9000 --mcp --mcp-query-tools

With a note of the operator that every connecting agent reads in the instructions of initialize (what the graph holds, which queries to prefer, house rules):

graphersal --graph data/ --server --mcp --mcp-instructions operator-notes.md

The file is UTF-8 text of at most 20000 characters; it is appended under the line "Notes from the operator of this server about this graph:" after the built-in instructions (and the read-only note). It is trusted text of the operator. A missing, non-UTF-8 or empty file, or the option without --mcp, is a usage error. The AI Chat does not use it (its system prompt has the built-in MCP instructions, but not these notes): give the chat its own text with system_prompt or system_prompt_file, so nothing is added twice.

The largest tool answer is 60000 characters by default; --mcp-max-chars N (at least 1000) sets another limit (see Answer size and paging):

graphersal --graph data/ --server --mcp --mcp-max-chars 30000

The options combine (--mcp --mcp-read-only --mcp-token ... --mcp-query-tools), and the limit options apply to the agent's queries as to the browser's.

The MCP configuration file: --mcp-config

Every tool, its description and the instructions take room in the agent's context before its first call: about 6.7 K tokens for the read-write endpoint, 4.6 K read-only, and more with every saved query as a tool. Each built-in tool's description is a sentence or two with an example where it helps; the gql description names element ids, anchoring variable-length patterns and (on a server that allows writes) the write clauses, and points to the resource graphersal://gql-reference for the whole supported subset. --mcp-config FILE lets the operator choose what the agent sees:

graphersal --graph kb.gstore --read-only --server --mcp --mcp-config mcp-kb-readonly.json
{
  "_comment": "a key starting with _ is a comment",
  "server_name": "project-kb",
  "instructions": { "mode": "replace", "text": "A read-only knowledge graph of this project. ..." },
  "tools": {
    "include": ["gql", "get_schema", "run_saved_query"],
    "overrides": { "gql": { "description": "Read-only GQL over the project graph. ..." } }
  },
  "saved_query_tools": { "folders": ["kb"], "paging_params": false },
  "resources": ["schema", "saved-queries", "gql-reference"],
  "answer_limit_chars": 30000
}
KeyMeaningDefault
server_nameThe serverInfo.name of initialize (1 to 100 characters)graphersal-dev
server_titleThe serverInfo.title of initialize (1 to 100 characters), the name a client showsGraphersal dev server
instructions{"mode": "builtin" | "append" | "replace", "text": ".."} or {"mode": .., "file": "notes.md"} (UTF-8, 1 to 20000 characters): builtin the built-in text (+ the read-only note), append the built-in text with the operator's text under "Notes from the operator of this server about this graph:" (what --mcp-instructions does), replace the operator's text onlybuiltin
descriptionsKept so that older files still load: short, the only style, changes nothing. full (the long descriptions of 0.5.2 and before) was removed: an A/B test of Claude Code with Sonnet on read and write tasks measured the same accuracy, fewer failed calls (above all fewer calls of a tool by its bare name) and about 20 to 27 K fewer input tokens per task with the short texts; a file that still says full is refused at start with a message (remove the key)short
tools.includeThe built-in tools offered (in their usual order); a tool not offered is not callable eitherevery tool of the mode but usage_statistics (offered only when named here)
tools.excludeBuilt-in tools left outnone
tools.overrides{"<tool>": {"description": ".."}}: the operator's description instead of the built-in one (the input schema never changes)none
saved_query_toolsSaved queries as tools of their own: {} = every saved query (what --mcp-query-tools does), folders (each with its subfolders), names, exclude (names); paging_params: true lists offset/max_rows/max_items in their schemas (by default they are left out: the defaults apply and a call may still pass them). The description is the query's own text; a query that writes adds a note with what it changes, which write_note sets: "default" (the built-in note: "Saved query that CHANGES DATA (...); run it only when the user asked for that change. The same as run_saved_query."), "none" (no note; the tool's readOnlyHint/destructiveHint annotations still say it writes), or the operator's text (1 to 1000 characters, {effects} stands for what the query changes). run_saved_query still reaches every saved queryno saved-query tools
resourcesThe resources listed by resources/list, by name: schema, statistics, dsl-reference, examples, saved-queries, gql-reference. Every resource stays readableall six
answer_limit_charsThe largest tool answer in characters (at least 1000), like --mcp-max-chars60000

The file is checked at start (exit 2 with the reason): JSON, an unknown key is an error with a did-you-mean (a key starting with _ is a comment at every level), an unknown tool or resource name is an error, a relative instructions file resolves against the configuration file, and read-only always wins: a writing tool named in tools.include or tools.overrides of a read-only server (--mcp-read-only, --read-only, or a Store that could only be opened read-only) is an error rather than a silently missing tool. The flags --mcp-instructions, --mcp-query-tools and --mcp-max-chars stay as shorthands; the same setting given by a flag and in the file is an error (there is no precedence to remember). In an args file the key is mcp-config. Nothing in the file is a built-in profile: without it the endpoint offers every tool of its mode with its built-in description. Two examples ship in crates/graphersal-cli/examples/: mcp-kb-readonly.json (a read-only knowledge graph: gql, get_schema, run_saved_query, the saved queries of the folder kb as tools, short instructions) and mcp-short.json (the data tools, the storage administration tools left out, the operator's notes appended).

The AI Chat does not read --mcp-config: it keeps the full tool set of its mode, the built-in descriptions and instructions; it cannot read resources, so its prompt carries the DSL and GQL references instead.

What a configuration costs: graphersal mcp-cost

graphersal mcp-cost prints what the prompt of an endpoint costs, without starting a server: the characters of the instructions and of every tools/list entry, and a rough token estimate (characters / 4; a real tokenizer counts differently). It takes --graph (default modern; the saved queries of a store become tools with --mcp-query-tools or saved_query_tools), --mcp-config, --read-only (measure the read-only endpoint), --mcp-query-tools and --mcp-instructions. The graph is always opened read-only (nothing is written, a Store's lock is not taken), so a store a running server holds can be measured.

graphersal mcp-cost --graph kb.gstore --read-only --mcp-config mcp-kb-readonly.json
MCP prompt cost of kb.gstore (read-only, with --mcp-config)
  instructions: 427 chars, ~107 tokens
  tools: 17: 12774 chars, ~3194 tokens
  total: 13201 chars, ~3301 tokens
  estimate: tokens = characters / 4, a rough estimate (a real tokenizer counts differently)

Tools (characters of each tools/list entry, largest first)
  gql:                1546 chars  ~387 tokens
  references_to:      1275 chars  ~319 tokens
  run_saved_query:    1181 chars  ~296 tokens
  ...

The same knowledge graph without the file (--read-only --mcp-query-tools) costs about 7 K tokens.

Schema changes that fill vectors: confirm_lock

set_schema and patch_schema run the schema preview first when the schema names a vector rule. A fill whose estimate is 1 s or more (or, without an estimate, of 10,000 elements or more) locks the whole database while it runs, so the tool answers a tool error (isError: true) with the preview's warning text plus "Repeat with confirm_lock: true" and applies NOTHING; the agent repeats the call with "confirm_lock": true once the user agreed. A smaller fill is applied, with the warning text before the answer.

Connect Claude Code

claude mcp add --transport http graphersal http://127.0.0.1:9000/mcp

With a token:

claude mcp add --transport http graphersal http://127.0.0.1:9000/mcp \
  --header "Authorization: Bearer my-secret-token"

Check the connection, and remove the entry when you are done:

claude mcp list                  # graphersal: http://127.0.0.1:9000/mcp (HTTP) - ✔ Connected
claude mcp remove graphersal

claude mcp add stores the server for the current project directory (-s user makes it available everywhere). A newly added MCP server is picked up by a NEW Claude Code session: start claude again (or start it after adding). Use the same port as the running server; when you restart the server on another port, remove and add the entry again. The server must be running when Claude Code starts, or claude mcp list shows it as failed (start the server, then a new session).

Try it

  1. graphersal --graph modern --server --port 9000 --mcp, and open http://127.0.0.1:9000/ in the browser: the top bar shows an MCP badge.
  2. claude mcp add --transport http graphersal http://127.0.0.1:9000/mcp, then start claude.
  3. Ask: "Use the graphersal tools: who does marko know?". The agent calls query with a traversal such as g.v().has("name", "marko").out("knows").values("name"). The badge's tooltip now names the agent (claude-code).
  4. Ask: "Add a person ada, 36 years old, who knows marko." The browser reloads its graph by itself and shows "changed: commit N"; results you ran before are marked "possibly stale".
  5. Ask: "Infer the schema, store it in mode open and add an optional string property email to person." (infer_schema, set_schema, patch_schema); the Schema panel follows.

What the agent gets

The server introduces itself as graphersal-dev with instructions that explain the query language. Tools (each one queues on the server's session like a browser call; read-only tools are marked readOnlyHint, query, set_schema, drop_compression and drop_index destructiveHint). The list is the same on every --graph source; there are no persistence tools:

ToolWhat it does
query {script, profile?, offset?, max_rows?, max_items?}Runs a script (Gremlin in Rhai syntax) as one transaction: the results as compact JSON, paged (100 results after the first offset, 100 items of every nested list by default, with a note when something was cut and the next page's offset), whether it changed the graph and the new commit number, the per-step profile with profile: true; a failing script is a tool error carrying the diagnostic and its Help: line, and changes nothing
gql {query, params?, profile?, offset?, max_rows?, max_items?}Runs a GQL query, the text as it is ($name values from params): one JSON object per row, paged like query; a write (INSERT, SET, REMOVE, MERGE, DELETE) is one transaction and the answer names the net changes; refused in read-only mode. Its description is short; the resource graphersal://gql-reference lists the whole supported subset
get_schema, infer_schema {labels?, format?, descriptions?}The schema summary by default (both tools, the same text): labels with counts, their keys with types and how often they occur, edge labels with their from->to label pairs, property indexes, the schema mode, the stored schema's enums and declared labels and keys laid over it; labels details some labels (every key, a vertex label's edges out and in). The stored schema's descriptions are left out by default (they make up about a third of a large graph's summary: 24.2 K characters with them, 15.5 K without on a knowledge graph of 45 vertex and 79 edge labels, and the answer is written to the agent's prompt cache in every conversation); descriptions: true adds them (label descriptions, and in the details every key's description), and the resource graphersal://schema-summary is the summary with them. format: "json": the stored schema (or null) / the schema the data satisfies, as JSON, narrowed to labels when given (the JSON of a large graph exceeds the answer limit; the summary of a graph of 124 labels takes about 20 KB)
validate_schema {schema, mode?}, validate_schema_patch {patch}, diff_schema {schema}Check a proposed schema or a JSON Merge Patch against the data, without applying
set_schema {schema, mode?}, patch_schema {patch}Store a schema, patch the stored one (validated against the data)
list_compressionsThe compression rules with their stats (also in read-only mode)
estimate_compression {label, path, element?, codec?, minBytes?, dictionary?}Estimates what rules for that label and path would save on the current data, without changing the graph (also in read-only mode)
define_compression {name, label, path, element?, minBytes?, dictionary?, replaces?}, drop_compression {name}, recompress {name}Define, drop or re-run a compression rule (refused in read-only mode); a refused rule answers its field errors
list_indexesThe property indexes with their type and stats (entries, distinctValues, bytes; served: false with a reason when the storage serves none or the index type is unknown to this version) (also in read-only mode)
create_index {label, key, element?, name?, type?}, drop_index {name}Create (built from the data in the same commit) or drop a property index; type is an enum of the known index types (memory-ordered, the default); refused in read-only mode, where query also refuses g.create_index/g.drop_index; a refused index answers its field errors (an unknown type, a key the schema declares as a vector, a list or a map)
list_saved_queries {folder?, search?}The saved queries stored in the graph: name, folder, description, parameters (JSON Schema, default, required, description), status (error with the reason when it cannot run), writes and effects (true and what it changes, for a query that writes); folder keeps a folder and those below it, search a text in the name or description (case-insensitive). With --mcp-read-only the queries that write are left out
run_saved_query {name, params?, offset?, max_rows?, max_items?}Runs g.query(name, #{..}) like query (paged answer, the call text on its first line): the arguments are checked against the parameter schemas, omitted ones take their default, a wrong one is a tool error with its Help: line. A query that writes changes only its effects, as one transaction; with --mcp-read-only it is refused
workload_statisticsThe workload statistics of a Store's graph: queries by normalized plan, property uses, lock times and jobs per channel (max_rows per list, default 50; history: minutes, hours or days adds every row's buckets; also in read-only mode)
list_jobsThe scheduled jobs of a Store's graph: system jobs and jobs of users with schedule, switch, next time, last run, run counts, a user job's action and effects (reading; also in read-only mode; defining and changing jobs stays the user's)
advise {everything?}The storage advisor's recommendations, each with its command, and their groups (dedup: 74 keys, total -400.1 MiB with the ids); changes nothing (also in read-only mode)
apply_recommendations {ids, everything?}Applies the recommendations the user picked (ids from advise) in ONE commit, all new compression rules in one pass over the data; all or nothing (an id no longer advised or a refused change applies nothing); refused in read-only mode
usage_statistics {max_rows?}Opt-in (only when tools.include of the configuration names it): the endpoint's usage statistics since the server started (memory only)
statistics, graph_infoCounts per label, memory and limits; what the server serves (name, counts, schema mode, source file or Store directory, view and a note while a read-only view is open, damageFound, mcpReadOnly, answerLimitChars, and on a layered graph layer: base name and baseRef, added/modified/removed counts, ownBytes, sharedBytes)

Answer size and paging

Tool answers are compact JSON (no indentation), on one line after the status lines (call: ... of a saved query, ok: 443 results (2.1 ms)), followed by notes. query, gql, run_saved_query and the tools of --mcp-query-tools take three paging arguments:

  • offset (default 0): the first offset top-level results are skipped. The query itself is not changed and computes every result again; only the answer shows a later page.
  • max_rows (default 100): the most top-level results of one page.
  • max_items (default 100): the most items of every nested list or map; a cut list ends with the item "… N more", a cut map with the key "…", and a note says so.

On top of that the whole answer stays within the server's answer limit (--mcp-max-chars, default 60000 characters; graph_info shows it as answerLimitChars). The limit never cuts inside a result, so the JSON stays valid:

  • A list of results keeps its leading whole results that fit, and the note names what is shown and where to go on: note: shown results 101-160 of 443, cut at a whole result to fit the answer limit of 60000 characters (...); more results follow: next page offset 160. A page cut by max_rows alone says ... (max_rows sets the page size); more results follow: next page offset 200; the last page says no more results, an offset past the end says so too.
  • A result that alone is longer than the limit is left out with a note that names the offset that skips it.
  • A single value (such as a map from .next()) that is too long keeps its leading whole entries with a note; offset pages only a list of results (GQL rows are one).
  • Every other tool keeps the leading whole items of its JSON (a note says how many of how many), or the leading whole lines of a text answer.

Clients limit tool output as well: Claude Code caps one MCP tool answer at about 25000 tokens by default (the environment variable MAX_MCP_OUTPUT_TOKENS changes it). Raising --mcp-max-chars alone may not help; bound large answers in the query (LIMIT, values(..)) or page them.

A read-only view opened in the browser is server-wide: the agent's queries read that past state too. graph_info then carries a note ("the served state is a read-only view at commit N ..."), and every tool error carries it as a last line, so a refused write says why. The agent cannot close the view; the user does (Back to the live graph).

Resources (read with resources/read): graphersal://gql-reference (the GQL subset the gql tool supports, its write semantics and examples, about 13 KB; the gql description points to it), graphersal://schema (the stored schema JSON: get_schema with format: "json"), graphersal://schema-summary (the schema summary text with the stored schema's descriptions: get_schema with descriptions: true), graphersal://statistics, graphersal://dsl-reference (every step and function of the language with its signatures, both spellings, a one-line description and a runnable example with its result, generated from the engine's function docs, about 55 KB), graphersal://examples (the playground's examples, about 8 KB) and graphersal://saved-queries (the list of list_saved_queries).

Saved queries first. The server's instructions and the list_saved_queries description tell the agent to look for a saved query (list_saved_queries) before it writes a new query, and to run it with run_saved_query: the queries a user stored for recurring questions are reused instead of rewritten. A query listed with writes: true changes data (its effects say what), and the instructions tell the agent to run one only when the user asked for that change. Both tools are offered with --mcp-read-only too, which lists only the queries that do not write and refuses a call of one that does. With --mcp-query-tools, tools/list also lists every saved query as a tool named like the query, with its own description (a query that writes says so and names its effects), an inputSchema built from its parameter schemas (defaults included, required parameters in required, no other properties; the paging parameters only with saved_query_tools.paging_params: true) and annotations from its effects (readOnlyHint false for a query that writes, destructiveHint when it updates or deletes); calling it is run_saved_query with those arguments. A program that embeds the endpoint (the graphersal-mcp crate) can bind parameters per connection (Profile::with_bound_params, for example the project a connection serves): a bound parameter is left out of every saved-query tool's inputSchema, and every call of a saved query that declares it, through its own tool or run_saved_query, runs with the bound value whatever the client sent (the answer's call: line leaves it out). tools/list reflects the catalog at the time of the call; the endpoint has no event stream, so it announces tools.listChanged: false and a client lists the tools again to see a changed catalog. A saved query named like a built-in tool (statistics, ...) is not listed as a tool of its own; run_saved_query reaches it.

The agent's queries share everything with the browser: one query runs at a time, a read-only view opened by either side is what both see, and the limits apply. Stop in the browser cancels only that page's own query, never the agent's. The agent cancels its own request with the MCP notification notifications/cancelled ({"requestId": <id of the tools/call>}, sent with its Mcp-Session-Id): the query stops and rolls back, also while it still waits for the session, and the request answers a "cancelled" tool error. A notification for another session's request, for a request that has ended, or sent without a session id is ignored.

MCP usage statistics

The endpoint counts how it is used since the server process started, in both run modes (the read-write session thread and the read-only serving mode's workers). The counters are kept in the server's memory only: nothing is written to the database or to any file (the process may run with a read-only root filesystem and no volume), and a restart starts from zero. The workload statistics of a Store are a different thing (per query plan, kept in the Store; off in read-only mode).

GET /api/mcp/stats (404 without --mcp) answers:

KeyWhat it counts
startedAtMs, uptimeSWhen the counting started (milliseconds since the Unix epoch) and for how long
requeststotal JSON-RPC messages of a known (or no) session, withoutSession, busy503 (answered 503 because the pool was busy)
methodsRequests per JSON-RPC method (initialize, tools/call, ...; (notification), (other))
sessionsinitialized, and activeLast5Min: the distinct session ids seen in about the last five minutes (an estimate, activeIsEstimate: true; within a few percent)
refusalsqueueFull, queueTimeout, clientLimit (the pool's limits for MCP requests), tooManyConnections (--max-connections, requests to /mcp), stopping, unknownSession (404), unauthorized (--mcp-token), invalidRequest (a wrong Accept, Content-Type, protocol version, size or JSON)
tools, savedQueriesOne row per tool and per saved query (run by run_saved_query or by its own tool): calls, errors (tool errors and refused calls), totalMs, meanMs, maxMs, histogram (calls below each bound of latencyBucketsMs, 1 ms to 10 s, the last entry the slower ones) and answerChars; most calls first. At most 1024 names each, further ones count as (other); an unknown tool counts as (unknown)
clientsOne row per client name and version (the clientInfo of initialize): initialized, requests, toolCalls; the 4096 most recently initialized names are kept (clientsKept, clientsMax)
readOnly, statelessSessionsThe endpoint's mode

The playground shows the same in a dialog: click the MCP badge in the top bar (Refresh reads it again).

The agent can read them too with the tool usage_statistics {max_rows?} (reading; at most 50 rows per list unless max_rows says otherwise, <list>_omitted counts the rest). It is opt-in: it is never in the default tool list (nor the AI Chat's), and an endpoint offers it only when its configuration names it in tools.include:

{ "tools": { "include": ["gql", "get_schema", "run_saved_query", "usage_statistics"] } }

Live refresh in the browser

Every page polls GET /api/changes every 2 seconds while it is visible (it pauses in a hidden tab and checks at once when it becomes visible again). When the graph changed because of something this page did not do (an agent over MCP, or another browser tab on the same server), the page reloads the graph info, the Graph, Schema and Statistics panels and the Store menu, marks every tab's result as possibly stale and shows "changed: commit N". Its own queries do not trigger the notice.

Protocol details

The endpoint implements MCP's Streamable HTTP transport of the protocol revisions 2025-11-25, 2025-06-18 and 2025-03-26 (the initialize-based ones; initialize negotiates one of them) with JSON answers and no server-sent event stream: POST /mcp with one JSON-RPC message (initialize, ping, tools/list, tools/call, resources/list, resources/read; a notification is answered 202 Accepted), GET /mcp is 405, DELETE /mcp ends the session. initialize returns an Mcp-Session-Id (an opaque value for the client; a server that embeds the endpoint and serves several graphs may prefix it with a route tag, <route>~<id>, that keeps the session on the graph it started on); a request that names an unknown session (after a restart of the server) is 404, so the client initializes again. A request whose MCP-Protocol-Version header names another revision is 400, which tells a client that also speaks newer, stateless revisions to fall back to initialize. The Host/Origin checks of the Safety section apply (another site's Origin is 403). On the loopback --mcp-token protects against other local users and programs; on a network address (--host, or a container) it is the only thing that keeps other machines from the MCP tools. The printed MCP URL uses the host of the stdout URL (127.0.0.1 for a wildcard address); a client on another machine uses the server's address instead.

AI Chat

EXPERIMENTAL, like the dev server. The configuration file, the endpoints and the tab change without notice.

With --ai FILE the playground's Query panel can open an AI Chat tab: you ask questions in plain language and an LLM agent answers them by working on the served graph. The agent uses the same tools as an MCP client (query, the schema tools, saved queries, compression rules, statistics, graph_info), but the agent loop runs inside the dev server process: the server calls the LLM provider, runs the tool calls the model asks for on the session (they queue like every browser and MCP call), sends the results back and repeats until the model answers. The browser only shows the conversation; the API key never reaches the page. --ai does not need --mcp (both may be on).

export ANTHROPIC_API_KEY=...                           # the key stays in the server process
graphersal --graph modern --server --ai ai.json
# Graphersal dev server: http://127.0.0.1:8080/                              (stdout)
# AI Chat (EXPERIMENTAL): model ... over the Anthropic API; data the agent queries is sent to api.anthropic.com   (stderr)

Open the page, click + in the Query panel's tab strip and choose AI Chat (the tab has its own colour). Ask, for example, "Who does marko know?" or "Which software was created by more than one person?". The transcript shows:

  • your messages and the agent's answers (Markdown: tables, lists, code);
  • per question, the steps that led to the answer in ONE collapsed group above it, with the time the turn took (e.g. "Worked for 34 s: 2 tool calls (list_saved_queries, query)", "Working for 12 s: running query" while the turn runs, counting up every second, "Stopped after 5 s and 1 tool call: list_saved_queries" when it failed; a turn without tool calls shows "Working for 3 s…" at the bottom instead); opened, it lists the agent's interim texts and every tool call in order, each collapsible with its arguments, a result summary and the result text; a query call has Open in a query tab and Run;
  • a query the agent proposes in its answer (a fenced block) with Copy and Run (Run opens a new query tab and runs it there);
  • errors with their help text (a refused key, an unknown model, the provider's rate limit, ...).

A saved query that writes (writes: true) runs only after you confirmed it: the agent's first run_saved_query of it in a turn is not run but answered "ask the user first", so the agent asks you in the chat what it is about to change; when it calls the query again in the turn of your next message, it runs (once).

Stop ends the agent's turn: the pending provider call is abandoned (the client is synchronous, so the answer is dropped when it arrives) and the query the agent runs is cancelled and rolled back. It stops only this chat; another chat tab, the browser's own query and an MCP client keep running (and the browser's query Stop does not stop the agent's query). /clear (the whole message) starts over: it stops a running turn and deletes the conversation on the server; /help lists the commands. Each chat tab is its own conversation, and a conversation belongs to the page that created it: after a reload the transcript stays as history and the next message starts a new conversation. Conversations live in the server's memory only (at most 64; a restart ends them).

Export ▾ in the chat's header downloads the transcript of this chat tab as a file named after the tab and the time (graphersal-chat-2-20261027-090507.md): Markdown (.md) (a title, the export time, model, server and graph, then per turn your question, the final answer as the model wrote it, errors with their help and one line with the time the turn took and its number of tool calls, e.g. _Answered in 34 s · 5 tool calls_; the steps, i.e. the interim texts and the tool calls with their arguments and results, are left out, the time when the server did not report it) or JSON (.json) ({"format": "graphersal-ai-chat", "version": 1, "exportedAt", "meta": {chat, provider, model, readOnly, server, graph}, "preamble": [...], "turns": [{question, state, steps, answer, tail, done, timing}]}, where steps are {type: "text", text} and {type: "tool", id, name, args, ok, summary, result, resultTruncated}, tail holds error {message, help}, notice {text}, text {text} and stopped, and done the turn's figures elapsedMs, toolMs, llmCalls, inputTokens, outputTokens, cachedTokens, toolCalls, limitReached, stopped). It holds what the page holds: a transcript restored after a reload keeps the newest 300 items and each tool result text shortened to 2000 characters (resultTruncated in JSON).

When the agent changes the graph, the page reloads it like after an MCP change: the change feed names the client ai (with the conversation id), and the other tabs' results are marked "possibly stale".

In the WebAssembly playground (no server), an AI Chat tab can be opened but is read-only: it says "AI Chat is available when you run Graphersal locally: graphersal --server --ai ai.json".

The configuration file

--ai FILE names a JSON object. It is read once, at the start of the server. A value of the wrong type or a missing environment variable stops the start with a message that names the key. Unknown keys are lenient: a key starting with _ (for example "_comment") is ignored silently; any other unknown key is ignored with a startup warning that lists the keys; but an unknown key that is within two edits of a known one ("readonly", "max_token") stops the start with a did you mean "read_only"? hint, so a typo cannot silently drop a safety setting.

KeyDefaultMeaning
providerrequired"anthropic" (the Messages API with tool use; the static system prompt is cached by the provider) or "openai" (Chat Completions with tools: OpenAI, and every compatible server through base_url: Google Gemini, Azure OpenAI, OpenRouter, Groq, Ollama, LM Studio, vLLM, ...)
modelrequiredThe model id, passed to the provider as is. There is no default model: the file names it. Choose a model that supports tool calls
base_urlthe provider's (https://api.anthropic.com, https://api.openai.com/v1)An http:// or https:// URL; the adapter appends /v1/messages (anthropic) or /chat/completions (openai), so an OpenAI-compatible URL ends in /v1 (Ollama: http://localhost:11434/v1)
api_key_envnoneThe name of the environment variable that holds the API key ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", ...). The variable must be set and not empty when the server starts
api_keynoneThe key inline. Accepted with a startup warning (the file may end up shared or committed); prefer api_key_env. Not together with api_key_env
read_onlyfalsetrue: the agent may only read (see below)
max_tool_calls_per_turn20The most tool calls one turn (one question) may make. The prompt states this budget, and the last results before the limit tell the model how many calls are left. At the limit the calls beyond it are not run, and the model is asked once more, without tools (tool_choice "none"), to answer from what it has; the answer is marked "tool-call limit reached". A provider that ignores tool_choice and keeps asking for tools ends the turn with a message that says so. "go on" continues it either way
max_tokens4096The answer length bound of one provider call; an answer cut there ends with an error that says so
system_promptnoneYour own text for the agent's system prompt (at most 20 000 characters), see Custom system prompt. Not together with system_prompt_file
system_prompt_filenoneThe same text from a UTF-8 file; a relative path is relative to the directory of the config file. An unreadable or non-UTF-8 file, or too long a text, stops the start

A key is required, except for an openai provider with a custom base_url (a local server such as Ollama needs none). The key is never logged, never written to a file by the server and never sent to the page (GET /api/info shows provider, model, read-only and the host data is sent to, never the key). A key sent over plain http:// to a host that is not this machine gets a startup warning.

Examples (the repository holds them as crates/graphersal-cli/examples/ai-*.json; the model ids are examples, use a current model of your provider):

Anthropic:

{
  "provider": "anthropic",
  "model": "claude-sonnet-4-5",
  "base_url": null,
  "api_key_env": "ANTHROPIC_API_KEY",
  "read_only": false,
  "max_tool_calls_per_turn": 20,
  "max_tokens": 4096
}

OpenAI (and, with another base_url and key variable, OpenRouter, Groq, Azure, ...):

{
  "provider": "openai",
  "model": "gpt-4.1-mini",
  "api_key_env": "OPENAI_API_KEY"
}

Google Gemini, through Google's OpenAI-compatible endpoint (a key from Google AI Studio in GEMINI_API_KEY; the adapter appends /chat/completions to the base_url):

{
  "provider": "openai",
  "model": "gemini-3.8-flash",
  "base_url": "https://generativelanguage.googleapis.com/v1beta/openai",
  "api_key_env": "GEMINI_API_KEY"
}

Thinking models (Gemini 3) work too: the thought signatures Gemini attaches to its tool calls (extra_content) are sent back unchanged with the next request, as Google requires.

Ollama on this machine (ollama pull qwen2.5:7b first; no key, no data leaves the machine):

{
  "provider": "openai",
  "model": "qwen2.5:7b",
  "base_url": "http://localhost:11434/v1"
}

Custom system prompt

system_prompt (inline) or system_prompt_file tells the agent what it cannot read from the graph: units, the meaning of labels, house rules, the language to answer in.

{
  "provider": "anthropic",
  "model": "claude-sonnet-4-5",
  "api_key_env": "ANTHROPIC_API_KEY",
  "_comment": "ages are years; the notes live next to this file",
  "system_prompt_file": "graph-notes.md"
}

The text is placed in the system prompt after the agent's rules and before the DSL reference, under the line "Notes from the operator of this server about this graph:". It is trusted text of the operator, but it comes after the rules and does not lift them: tool results stay data, never instructions. It applies to the AI Chat only; the MCP instructions are unchanged (and the --mcp-instructions notes are not added; the chat does not read --mcp-config either: it keeps the full tool set and the built-in instructions, and its prompt carries the GQL reference after the DSL reference). The prompt prefix stays fixed for the conversation, so the provider's prompt cache still works.

What data leaves the machine

Everything the agent sees goes to the provider: your messages, the system prompt (the MCP instructions, the agent's rules, your custom system prompt text if any, the DSL and GQL references and a short summary of the graph taken at the first question: counts, labels, schema mode, number of saved queries), and every tool result: query results, schemas, statistics, saved queries. The tab's header says so: "Data you query is sent to api.anthropic.com (Anthropic API)"; with provider: "openai" it names the OpenAI-compatible API, whoever runs it (Gemini's host, for example). When base_url points at this machine (localhost, 127.*, [::1]), nothing leaves it and the header says "The model runs on this machine". Use a local provider for data that must not leave it.

Graph data is untrusted input: a property value can contain text that looks like an instruction. The agent's system prompt says that tool results are data, never instructions, and only your own messages instruct it; that lowers the risk, it does not remove it. Use read_only when the agent should not change anything.

Read-only

With "read_only": true the agent gets only the reading tools, and its query runs under the same read-only rule as --mcp-read-only: a query that would create, change or delete data, the schema or a catalog definition is refused. The tab shows a read-only badge. The browser can still write.

Limits

  • max_tool_calls_per_turn bounds the tool calls of one question; max_tokens the length of one answer.
  • The server's limit options (--timeout, --memory-limit, --max-traversers, ...) apply to every query the agent runs, as to the browser's and MCP's; a query result is cut at the display limits (100 rows and 100 nested items) before it goes to the model, with a note.
  • A message is at most 100 000 characters. One turn runs at a time per conversation; several conversations run at the same time.
  • The provider's own limits (rate, context length, cost) are yours: a long conversation sends the whole history with every call. The line under an answer shows the tokens the turn's provider calls read (every request token, the cached ones included, with the cached part named) and wrote, summed over the turn, beside its time.
  • The server keeps the conversations in memory only, each finished turn compressed (LZ4); a restart forgets them.

The HTTP API (EXPERIMENTAL)

The API follows the playground's engine boundary (playground/js/engine/engine.js) and is EXPERIMENTAL: it may change in any release, minor or patch. Answers are JSON; errors are {"error": "..."} with a 4xx status (422 for a failing schema operation).

An OpenAPI 3.1 description of every endpoint below is part of each release: crates/graphersal-serve/openapi.json in the repository, and a running server answers it at GET /openapi.json (also GET /api/openapi.json; GET /api/info names it as openapi), with the server's own version in info.version. Generate a client from it, or open it in any OpenAPI viewer; pin the Graphersal version you read it from. The schemas in it are deliberately loose (objects with the documented keys); the table below and the linked pages describe every answer.

Allow-list mode (EXPERIMENTAL, for hosts built on the server's core, graphersal-serve; the graphersal CLI never turns it on): a host that serves a UI profile to a page it does not fully trust with the graph builds its context with ContextBuilder::api_allow_list(selection, policy). The server then answers only GET /api/info (with apiMode: "allow-list"), GET /api/changes and POST /api/query for the saved queries the selection names (folders with their subfolders, names, excluded names: graphersal_session::queries::SavedQuerySelection), each run under the access policy (graphersal::auth::AccessPolicy: a write the policy does not allow is refused by the engine before the query runs, as an answer with ok: false). Every other /api/ endpoint (the host's own extra routes too) and /mcp answer 403 "<METHOD> <path> is not offered by this server: it answers only GET /api/info, GET /api/changes and POST /api/query (allow-list mode)"; a saved query outside the selection, or one that does not exist, answers 403 "the saved query "<name>" is not offered by this server". The Host/Origin checks and the host's request filter still run first; the static files of the page and /openapi.json stay served. The page then shows only a profile whose tabs are its own modules: a profile with the built-in workspace (which reads the whole graph) is shown as an error.

EndpointEngine method
GET /api/infoinfo() (protocol: "graphersal/1": the protocol id of this API, by which the page recognizes a Graphersal host; a breaking change of the API bumps the number; server: "graphersal-dev": only the host's name; dev: true: a development server, the page shows its DEV SERVER badge; version, saveable, source, presets: the limits in force, mcp: {endpoint, readOnly, client} or null, ai: {provider, model, readOnly, sendsDataTo, maxToolCallsPerTurn} or null (never the key; sendsDataTo is the provider's host, null for one on this machine), damageFound: {text, frozen, foundBy, policy, problems} or null, embedders: [{name, model, dimension, default}], the built-in hash-ngram/1 and every model of the database, adminRuns: {tokenRequired} only with --admin-runs)
GET /api/changeschanges(): the change feed {version, commitSeq, recent: [{version, by, commitSeq, detail?}], view, mcp, damageFound, readOnly} (readOnly as in GET /api/info: it changes while the server runs when its host turns read-only on or off); by is the page's X-Graphersal-Client header (every request of the page sends it), mcp, or ai (an AI Chat conversation, its id in detail)
POST /mcpthe MCP endpoint (with --mcp, above)
POST /api/ai/conversationswith --ai (EXPERIMENTAL): a new AI Chat conversation {id} (random, 128 bits) owned by the page's X-Graphersal-Client (required); every other client gets 403 for it, an unknown id is 404, and without --ai every /api/ai/* is 404
POST /api/ai/conversations/<id>/messages {text}starts a turn on the server ({turn}; 409 while one runs): the provider is called, the tools it asks for run on the session like MCP tool calls (commits in the change feed as ai), until it answers without a tool call or reaches max_tool_calls_per_turn
GET /api/ai/conversations/<id>/events?after=N{events, running, last}: the events after N, each with seq: user {text}, assistant {text}, tool_call {id, name, args}, tool_result {id, name, ok, summary, text}, error {message, help}, done {stopped, toolCalls, elapsedMs, toolMs, llmCalls, inputTokens, outputTokens, cachedTokens, limitReached} (the turn's wall time and the part of it spent in tool calls, in milliseconds; its answered provider calls and their tokens summed: inputTokens counts every request token, the cached ones included, cachedTokens the part read from the prompt cache; whether the turn reached max_tool_calls_per_turn; the page shows them under the answer, e.g. "12.4 s · tools 3.1 s · tokens 15.2k in (12k cached) / 830 out")
POST /api/ai/conversations/<id>/stop{stopped}: ends this conversation's turn only: its pending provider call is abandoned, the query it runs is cancelled and rolled back; other conversations are not affected (and POST /api/cancel does not stop the agent's query)
DELETE /api/ai/conversations/<id>drops the conversation (history, pending call, running query)
GET /api/graphgraphInfo(); on a layer (--layer, --layer-store) it carries layer: {base, baseRef: {graphId, commitSeq, committedAt} | null, added: {vertices, edges}, modified: {..}, removed: {..}, ownBytes, sharedBytes} (counts from the layer's own bookkeeping, no diff walk), absent on any other graph
POST /api/execute {script, options}execute(script, options)
POST /api/query {name, params?, runId?}runSavedQuery(name, params), the profile API's query: one run of the saved query name with the named arguments params (the caller passes every parameter; the server binds none), without the display: {ok: true, results, mutated, changes} (every result, never cut) or {ok: false, error: {message, help?}, mutated, changes} (an unknown query, a parameter its schema refuses, a denied write; status 200). A malformed call is a 400
POST /api/cancelstop(runId): cancels the page's run runId (body {"runId": ".."}, the id given to POST /api/execute), or without a body every run of the page (queries, layout slices); never another client's: {cancelled}
GET /api/admin/runswith --admin-runs (EXPERIMENTAL; Run administration): every client's queued and running runs {runs: [{id, client, alias, kind, state, cancelled, startedAtMs, durationMs, text, identity, mount}], textHeadChars}; the header X-Graphersal-Admin-Token with --admin-runs-token; 404 without the flag
POST /api/admin/runs/cancel {id}with --admin-runs: cancels the run id whatever its client: {cancelled}
GET /api/schemaschema() (the schema views)
GET /api/schema/stored, GET /api/schema/infergetSchema(), inferSchema()
POST /api/schema/view (body: a schema)schemaViewOf(schema): the schema views of that schema (the editor's draft) with the graph's label counts, source: "given"; nothing stored
POST /api/schema/set, /patch, /validate, /validate-patch, /diffthe schema methods (body: the schema or patch; schema/set?mode=open|closed|none replaces the schema's mode)
GET /api/graph-view?maxNodes=&maxEdges=graphView(): the drawing as columns (ids, label indices, captions, edge endpoints as indices), no properties
POST /api/graph-view {maxNodes?, maxEdges?, degrees?, filter?}graphView(limits, filter): the same columns with the Graph panel's filter applied BEFORE the limits (filter: {vertices?: {label: [{key, op, value?}]}, edges?: {..}, hideIsolated?}; op eq, neq, lt, lte, gt, gte, between (low inclusive, high exclusive), contains, starts_with, ends_with, regex, exists, missing; values of keys the schema declares are coerced like a write) plus matchedNodes/matchedEdges (everything that passes, counted exactly); degrees: true adds vertexInDegree/vertexOutDegree (edges in the whole graph). On a layer every drawing (also a neighbourhood, a sample and a result's subgraph) has vertexOrigin/edgeOrigin ("base", "added", "modified" per element) and GET /api/element an origin; absent on any other graph. An invalid filter is a 422 naming the label, key and operator. POST /api/neighbourhood and /api/sample take degrees too, the neighbourhood also filter (a display filter: the neighbourhood is computed as without it, then what it hides is dropped)
POST /api/graph-filter-query (body: a filter)graphFilterQuery(filter): {query}, the Rhai query selecting the same vertices and edges (#{vertices: g.v()..., edges: g.e()...})
POST /api/neighbourhoodneighbourhood(request): the vertices within hops (the depth, 1-5) along direction (both, out, in) of the centre ids, plus the vertices keep (a drawing being expanded), and the edges between them, bounded by maxNodes/maxEdges: the drawing's columns plus seeds, missing, hiddenEdges and, when the limits cut it, leftOut: {vertices, edges, complete}; 422 for an unknown id or a depth above 5
POST /api/samplelabelSample(request): the first vertices of some primary labels ({vertices: {labels, exclude?}}) or the first edges of one label pair ({edge: {label, from?, to?}}), with sample: {kind, shown, total, complete}
GET /api/meta-graphmetaGraph(): vertex labels with their vertex counts (the 40 largest, the rest as other) and label pairs with their edge counts (the 200 largest)
GET /api/element?kind=vertex|edge&id=element(kind, id): one element with its properties (the inspector), null when it no longer exists
GET /api/element/edit?kind=vertex|edge&id=elementForEdit(kind, id): the element for the property editor, its values in the typed form ({type, value}: int64 as decimal text, uuid, object as [key, value] pairs, ...): {kind, id, label, labels, source?, target?, properties: [[key, typed]], readOnly} (readOnly: why the graph cannot be written now, e.g. a read-only view or a store in maintenance mode, else null)
POST /api/element/update {kind, id, set: [[key, typed]], remove: [key], validateOnly?}updateElement(request): writes the changed and removed top-level properties as ONE commit, validated by the engine (schema, required properties); any failing key refuses the whole update: {ok: true, changed, element} or {ok: false, errors: [{field, message, help?}]} (field the key, or general; always 200). validateOnly runs it as a dry run (no commit)
POST /api/element/labels {kind: "vertex"} or {kind: "edge", from, to}labelChoices(request): the labels the Graph panel's edit mode offers for a new element: {kind, mode, free, labels: [{label, declared, count, connects}], readOnly}. Vertices: the schema's declared labels, then the graph's other labels by count. An edge between the vertices from and to: the declared edge labels whose connections allow the pair (any label of an endpoint matches, * matches all, no connections allow every pair), then the graph's other edge labels, then (outside mode closed, where topology is not enforced) the declared labels that connect other labels (connects: false). In mode closed only declared, connecting labels and free: false (no label typed by hand). A missing endpoint is a 422
POST /api/element/create {kind: "vertex", labels, id?, properties: [[key, typed]], validateOnly?} or {kind: "edge", label, from, to, id?, properties, validateOnly?}createElement(request): creates the element as ONE commit, validated by the engine (labels, connections, required properties, types); every property is tried, so all bad values come back at once: {ok: true, created, element, drawn: {kind, id, label, caption, source?, target?}} or {ok: false, errors: [{field, message, help?}]} (field a property key, label, id, from/to or general; always 200). validateOnly runs it as a dry run (no commit, no automatic id used up)
POST /api/element/delete {kind, id, validateOnly?}deleteElement(request): deletes a vertex with its edges, or an edge, as ONE commit: {ok: true, deleted, edges} (edges: the edges removed with the vertex; with validateOnly they are counted and nothing is deleted) or {ok: false, errors}. Creating and deleting are refused, like element/update, while the graph is read-only (a past state's view, a backup, maintenance mode)
POST /api/layoutlayoutStart(input, options): starts the engine's force layout of a drawing ({vertexCount, edgeSource, edgeTarget, seed?, iterations?, budgetMs?}) and runs its first slice; answers the job's status {job, state, iterations, totalIterations, progress, elapsedMs, vertexCount, cached}, with positions (x, y per vertex) once state is done or cancelled. A drawing laid out recently comes from the cache at once
POST /api/layout/steplayoutStep(job, budgetMs): the next slice ({job, budgetMs?}, default 100 ms, at most 500); Stop (POST /api/cancel without a runId) ends a running or waiting slice as cancelled
POST /api/layout/cancellayoutCancel(job): ends the job, keeping the positions reached so far
GET /api/completions, GET /api/token-values, GET /api/memorycompletions(), tokenValues(), memoryUsage()
GET /api/statisticsstatistics(): {statistics, memory, process, limits: {presets, defaults}}. process is the memory the process holds beside the graph (GraphStatistics stays data counts): memory is the whole process (liveHeapBytes: the bytes the Rust allocator holds, from the CLI's tracking allocator; rssBytes and peakRssBytes: the resident set size, from /proc/self/status VmRSS/VmHWM on Linux and from ps -o rss= on macOS, where the peak is the highest value any report of this server has seen; no RSS on Windows or other platforms; each member is left out when unknown; source is proc, ps, allocator or none; the WebAssembly playground adds wasmMemoryBytes, the linear memory size, source wasm; beside them the process memory bar: usedBytes (the tracked live heap, else the sum of the known segments with usedTracked false), limitBytes and usedPercent (the process ceiling and the share used; absent with --memory-limit none), limitSource (configured, cgroup, physical, wasm, none, unknown), segments ([{name, bytes}]: structure, properties, compressed, indexes, models, then other when tracked), compression {plainBytes, storedBytes} when values are compressed or deduplicated, estimateAboveHeap: true when the graph's estimate exceeds the live heap, or limitError when the ceiling cannot be read; see Seeing how full the process is), models lists every loaded embedding model that reports its size (name, model, dimension, bytes, default; an estimate of the weights and the tokenizer), and aiChat {conversations, historyBytes, historyUncompressedBytes} (the bytes the stored chat history takes, compressed per finished turn, and the bytes it would take uncompressed) is added when the server runs with --ai. The MCP statistics tool returns the same
GET /api/mcp/statsThe MCP endpoint's usage statistics (memory only, since the start; 404 without --mcp)
GET /api/workload[?history=minutes|hours|days]workloadReport(history): the workload statistics of the served graph ({level, queries, properties, locks, jobs}; level off outside a Store); with history every row's buckets of that tier (chart data; an unknown tier is a 422). Only the queries a page or an agent runs count (under playground / mcp); the page's drawing and panels are not counted
GET /api/journal?after=N&level=..&since=..&until=..&source=..&kind=..&limit=..journal(spec): one page of the served graph's system journal ({records, next_after, next_before?, truncated, more, notes}; page with after = the previous next_after; newest_first=true answers the newest records first, page backwards with before = the previous next_before; a bad parameter is a 422). Reading it is Read on the resource Journal. The MCP tool journal (reading) answers the same, at most 100 records unless limit says otherwise
GET /api/jobs, POST /api/jobs/define|drop|enable|schedule|run, GET /api/jobs/history?name=..&tier=..jobs(), defineJob(spec), dropJob(name), setJobEnabled(name, on), setJobSchedule(name, cron), runJobNow(name), jobHistory(name, tier): the scheduled jobs (list, define with field errors, switch, a system job's schedule, run now, the runs per minute/hour/day); a backup job may name any directory here, never in the browser
GET /api/export?format=graphson|graphmlsaveGraph(format) (download)
GET /api/export?format=gsnap[&models=without]saveGraph('snapshot', {withModels}): the current state as a packed snapshot (binary download), with the embedding models of the store unless models=without
POST /api/saveSave to file: {path, format, bytes, warnings}, plus schemaPath when the schema was written to the --schema file, or warning when a stored schema could not be saved (GraphML/GraphSON without --schema)
GET /api/storestoreInfo(): {store: null} without a Store, else position, snapshots, marks, WAL, the creation parameters (storeId, damagePolicy, createdText, chunkBytes), damageFound ([{foundBy, atText, problems}]), frozenByDamage, damageText, backupFromMemory, models (the embedding models with their licences and usedBySchema) and missingModels
GET /api/store/summary, GET /api/store/detailsstoreSummary(), storeDetails(): the Store menu's two calls. The summary is GET /api/store with compaction, compactionError, storeBytes(Text) and graphBytes(Text) null and detailsPending: true: it reads only names, lengths and the store's small metadata files, never the WAL, an attic entry's WAL, a model blob or the graph's elements, so the menu opens at once however long the history is. The details {details: {commitSeq, compaction, compactionError, storeBytes, storeBytesText, graphBytes, graphBytesText}} follow (the graph's size is walked once per commit; the advice's prune estimate reads an attic entry's WAL only for a blob nothing else references, once per open store)
POST /api/store/checkpoint {name}, POST /api/store/mark {name}checkpoint(name), mark(name) (422 with the diagnostic on failure; 409 without a Store)
GET /api/store/snapshot?commit=N[&models=without]a stored snapshot as .gsnap (no commit: the latest), with the store's embedding models unless models=without
POST /api/store/view {target}openView(target): serve the state at the target read-only: {view: {commitSeq, label, timeText, target}, graph}; GET /api/info and GET /api/store report view
POST /api/store/livecloseView(): back to the live graph
POST /api/store/fork {target, dir}fork(target, dir): {fork: {dir, commitSeq, graphId, open, undo}} (409: the directory exists)
POST /api/store/rollback {target, delete}rollback(target, delete): {rollback: {target, previousCommitSeq, attic, undo, ...}, graph, store}
GET /api/store/attic/changes?id=&offset=&limit=atticChanges(id, offset, limit): one page of commits (limit default 100, at most 500) and the totals over all of them: {commitCount, mutationCount, totals, offset, limit, commits: [{commitSeq, timeText, principal, counts, samples}], hasMore}
POST /api/store/verifyverifyStore(): {verify: {ok, problems, notes, snapshotsChecked, segmentsChecked, recordsChecked}}
POST /api/store/backup {dir, full, from_memory}backupStore(body): a backup into dir (default <store>-backup next to the store; a relative path is next to it; an existing backup of the store takes an increment): {backup: {dir, incremental, fromMemory, commitSeq, bytesText, warnings, restore}, store}; 422 with the report on damage (nothing kept; the store's damage policy applies) and for a refused backup; from_memory only after damage was found
GET /api/store/compactioncompactionAdvice(): {compaction: {recommended, reason, decidedBy, compactable, totalBytes, liveBytes, garbageBytes, pruneBytes, pruneFirst, reclaimableBytes, spaceNeeded, freeSpace, policy, ...}} (also in GET /api/store as compaction, with kind and space)
POST /api/store/compactcompactStore({dropMarks}), optional body {"dropMarks": true} (an empty body is {}): {compact: {keptFrom, snapshotsRemoved, segmentsRemoved, marksUnreachable, compacted, bytesBefore, bytesAfter, bytesFreed}, compaction}; 409 in a read-only view; 409 {"error", "marksUnreachable": [...]} with nothing changed when the prune would make marks unreachable and dropMarks is not true (the playground sends it after the user confirmed)
POST /api/store/attic/restore, /fork ({id, dir}), /remove ({id})atticRestore(id), atticFork(id, dir), atticRemove(id)
GET /api/queries?folder=listQueries(folder): the saved queries [{name, folder, description, params, status, error?, writes, effects, denied_writes}] (an effect {action, element, label, text})
GET /api/queries/get?name=getQuery(name): one with its body, dialect, meta; null when there is none
POST /api/queries/define {name, folder?, description?, params?: [{name, schema, default?}], body, replaces?}defineQuery(spec): {ok: true, query} or {ok: false, errors: [{field, message, help?}]} (always 200); replaces renames in the same commit
POST /api/queries/drop {name}, POST /api/queries/move {name, folder}dropQuery(name): {dropped}; moveQuery(name, folder): the entry
POST /api/queries/call-text {name, args}queryCallText(name, args): {text}, the call g.query("name", #{..}) with the arguments as Rhai literals
POST /api/queries/preview {name, args}previewQuery(name, args): the call run as a dry run and rolled back, {ok: true, changes: {vertices_added, vertices_dropped, edges_added, edges_dropped, properties_set, properties_removed, labels_changed, other}} or {ok: false, error}; the run form shows it before it runs a query that writes
GET /api/catalog/export, POST /api/catalog/load?replace=truesaveCatalog(): the catalog file ({"definitions": [..]}: saved queries, compression rules, every kind); loadCatalog(file): stores a catalog file in one commit (replace=true: drops what the file does not have; a compression rule compresses its values), {loaded, graph}
GET /api/compressionlistCompressions(): the compression rules [{name, element, label, path, codec, minBytes, dictionary, stats: {compressedValues, plainBytes, storedBytes, dictionaryBytes}}]
POST /api/compression/define {name, label, path, element?, codec?, minBytes?, dictionary?, replaces?}defineCompression(spec): {ok: true, rule} or {ok: false, errors: [{field, message, help?}]} (always 200); replaces renames in the same commit
POST /api/compression/drop-many {names: [..]}dropCompressions: drops the rules in one commit, answers {dropped} (how many; a name not stored is skipped)
POST /api/compression/drop {name}, POST /api/compression/recompress {name}dropCompression(name): {dropped}; recompress(name): the rule's entry (422 when there is none)
POST /api/compression/estimate {label, path, element?, codec?, minBytes?, dictionary?}estimateCompression(spec): {ok: true, estimate} or {ok: false, errors: [{field, message, help?}]} (always 200); changes nothing
GET /api/indexeslistIndexes(): the property indexes [{name, element, label, key, type, transform, served, reason, stats: {entries, distinctValues, skipped, bytes} | null}] (transform is null or "to_lower"; stats is null, served false and reason a text when the storage keeps the definition but serves no index, or the index type or transform is unknown to this version; reason is null otherwise)
POST /api/indexes/create {label, key, element?, name?, type?, transform?}createIndex(spec): {ok: true, index} or {ok: false, errors: [{field, message, help?}]} (always 200; field is name, element, label, key, type, transform or general; an unknown type is an error of type, an unknown transform of transform, a key the schema declares as values the index cannot hold one of key); name defaults to <label>_<key> (<label>_<key>_edge for an edge index, then _to_lower with that transform), type to memory-ordered, transform to none ("to_lower": case-insensitive search with has(key, __.to_lower().is(..))); an existing name is refused (drop it first)
POST /api/indexes/drop {name}dropIndex(name): {dropped}
POST /api/memory/report (a spec {sample_every?, max_elements?, limit?, max_rows?, max_labels?, scope?}, {}: a full walk, at most 500 rows per list; scope: "delta": a layer's own elements only)memoryReport(spec): the memory report, {ok, report} or {ok: false, error}
POST /api/layer/diff (a spec {kinds?, labels?, limit?} as g.layer_diff(#{..}) takes it, {}: the whole diff)layerDiff(spec): what the layer changed against its base, {ok: true, diff: {added, removed, modified, truncated}} (the form of g.layer_diff()) or {ok: false, error}; an empty diff on a graph without layers. The browser playground (no server) starts a layer over its loaded graph itself (startLayer(), dropLayer())
POST /api/advise (thresholds, {}: the defaults), POST /api/advise/apply {id, spec} or {ids, spec} (several in one commit), POST /api/advise/dismiss {id, days?}, POST /api/advise/restore {id}advise(spec), applyRecommendation(id, spec), applyRecommendations(ids, spec), dismissRecommendation(id, days), restoreRecommendation(id): the storage advisor
GET /openapi.json, GET /api/openapi.jsonthe OpenAPI description of this API, with this server's version

A target is {"commit": N}, {"mark": "name"} or {"time": T} with T an RFC 3339 date-time (as the CLI's --at-time) or microseconds. GET /api/store lists every attic entry with bytes, restorable and restoreBlocked (the reason a restore is refused now). A change of the catalog (a saved query or a compression rule defined, replaced or dropped, a property index created or dropped) is a commit like any other: the change feed records it, and on a Store it is journaled. A recompress changes no data and commits nothing. Any other path is a static file of the UI (--ui-dir first, then the embedded copy).

Running in Docker

The dev server has no authentication. Whoever reaches its port can run every query the server allows (all of them without --read-only), and with --ai spend the AI provider key. Keep the port on a private network, publish it on the host's loopback only (-p 127.0.0.1:8080:8080), or put it behind a reverse proxy that authenticates. It is a dev server: its HTTP API is EXPERIMENTAL.

The repository has a Dockerfile that builds the graphersal command line into a small image: the static Linux binary (the same build as the release binaries: default features, so the dev server, MCP, the AI Chat and embedding models are in) on gcr.io/distroless/static, running as a non-root user (uid 65532), with a HEALTHCHECK, STOPSIGNAL SIGTERM and port 8080. No image is published; build it from a checkout. To ship a knowledge base as one image without compiling anything, see A knowledge base image.

Serve a single-file database read-only with MCP

The default command of the image serves the single-file Store /data/graph.gstore read-only, with a read-only MCP endpoint for an AI agent:

graphersal --graph /data/graph.gstore --read-only --server --host 0.0.0.0 --port 8080 --mcp --mcp-read-only

Build the image, then either mount the file or bake it into an image of your own:

docker build -t graphersal .                       # in the repository checkout

# (1) the file mounted read-only from the host
docker run --rm -p 127.0.0.1:8080:8080 \
  -v "$PWD/my.gstore:/data/graph.gstore:ro" graphersal

# (2) the file inside an image of your own
cat > Dockerfile.mygraph <<'EOF'
FROM graphersal
COPY my.gstore /data/graph.gstore
EOF
docker build -f Dockerfile.mygraph -t mygraph .
docker run --rm -p 127.0.0.1:8080:8080 mygraph

Then http://localhost:8080/ is the playground and http://localhost:8080/mcp the MCP endpoint (claude mcp add --transport http graphersal http://localhost:8080/mcp). An embedding model kept in the store (Embedding Models in a Store) is loaded from the file, so text queries (nearest("emb", "some text", 5)) work without a network. Make the store with the command line first, for example:

graphersal --graph my.gstore --create-store -e 'g.add_v("doc").property("text", "a cat on the mat").iterate()'
graphersal embed-model download minishlab/potion-base-8M --into my.gstore
graphersal --graph my.gstore -e 'g.set_schema(g.infer_schema(), SchemaMode.open); g.patch_schema(#{vertices: #{doc: #{schema: #{properties: #{emb: #{type: "array", format: "vector", embedder: "minishlab/potion-base-8M", from: "text"}}}}}})'

Pass other arguments after the image name to replace the command (docker run ... graphersal --graph /data/graph.gstore --server --host 0.0.0.0 --port 8080); the entry point is the graphersal binary.

Read-only

With --read-only the served graph refuses every write: queries, schema changes, saved queries, indexes and compression rules, "Save to file", and the MCP endpoint offers only its reading tools. A Store is loaded without its lock and nothing in it is written: no recovery cut of an interrupted last write (it is ignored), no checkpoint, no workload statistics file, no temporary file beside it. So all of these work:

  • a :ro bind mount or volume;
  • a read-only root file system (docker run --read-only);
  • a file the container's user may not write (the image runs as uid 65532, a file copied into an image belongs to root).

The server shows no Store panel and no history then (it serves the latest state as a graph).

--server --read-only is the read-only serving mode, made for many readers: the queries of all browser pages and MCP agents run in parallel on a pool of workers (--workers, default the container's CPUs), behind a bounded queue (--queue, --queue-timeout; a full queue answers 503 with Retry-After: 1), at most --max-inflight-per-client queries per agent or page and --max-connections requests at once, under safe default limits (SAFE script limits, a 30 s timeout, 500 MiB per query). MCP session ids are stateless. It has no authentication: the server is protected only by being read-only and by these limits, so publish the port where you trust who can reach it (or put an authenticating reverse proxy in front). Not available in this mode: the Store panel, history, scheduled jobs, saving and every write. Without --read-only, a Store that cannot be opened for writing (no permission, a read-only file system) is served read-only anyway, with a note on stderr saying so.

A knowledge base image

A knowledge base for AI agents ships best as ONE image: the binary, the Store and the MCP configuration baked in, served read-only, so an agent connects with a URL and nothing else. docker/prebuilt/ builds such an image without compiling anything. Copy the folder into your own repository, put your store (and, if the build may not download from GitHub, a release archive of the binary) next to it, and run one command. Its README.md is the full guide; build.py needs Python 3.9+ (standard library only) and Docker with buildx or Podman (--engine, default: Docker if present), on Linux, macOS or Windows.

No authentication. Whoever reaches the port reads the whole knowledge base, through MCP and through the playground, without a token. The server is protected only by being read-only and by the limits of the read-only serving mode. Run it on a private network or behind a reverse proxy.

Build

docker/prebuilt/
  build.py  Dockerfile  README.md  .gitignore
  my-kb.gstore                                  the store (exactly one *.gstore)
  graphersal-v0.7.1-linux-x86_64.tar.gz         the binary, a release archive (or --version)
  mcp-config.json                               optional: the MCP configuration
  instructions.md                               optional: instructions for agents (Markdown)
python docker/prebuilt/build.py -t my-kb:1                                    # this platform, local Docker
python docker/prebuilt/build.py --version 0.7.1 -t registry.example.com/my-kb:1 --push   # both platforms
python docker/prebuilt/build.py --store data/kb.gstore --binary tools/graphersal -t my-kb:1

The binary comes from the repository (release archives graphersal-v<version>-linux-*.tar.gz, checked against a SHA256SUMS beside them, or plain Linux binaries whose architecture is read from the file) or from a GitHub Release (--version 0.7.1 or latest, checked against the release's SHA256SUMS and cached in ${GRAPHERSAL_CACHE:-~/.cache/graphersal}/bin/, so later builds work offline; --version run:<run-id> takes the binaries of a run of the "CLI binaries" workflow, with the GitHub CLI). Without --push the image is built for the Docker engine's platform and loaded; with --push for every platform with a binary.

build.py writes the build context .context/ (hard links where possible) and runs docker buildx build, or podman build --format docker (the OCI format would drop the health check; a pushed multi-platform image is a manifest list pushed to every tag). The Dockerfile then prepares the store with the image's own binary: an older binary need not open a store written by a newer one, so the image always opens what it carries. In a first stage, without network, it runs graphersal store fork, which writes the latest state as one snapshot (no write-ahead log history, no attic, no marks, no free space, a new store id) with the store's embedding models, then store verify, then mcp-cost with the configuration, so a broken store or a typo in a tool or folder name fails the build, not the container start. A store of 2.2 GiB (1.7 GiB live: 61 WAL segments of history, a 506 MiB model, 560 MiB free space inside the file) became 565 MiB. The stage runs on the building engine's platform and its result serves every platform of the image. The source store is only read; do not build from a store a running server is writing (fork it first).

The image is three layers on gcr.io/distroless/static (non-root user 65532, everything read-only for it): the binary, the configuration, the store. A new version of the knowledge base rebuilds and ships only the last layer. The labels dev.graphersal.binary.version and dev.graphersal.binary.source name the binary; tag the image with the version of the knowledge base.

A configuration for a knowledge base offers GQL, the schema and the saved queries of one folder as tools of their own (the repository's crates/graphersal-cli/examples/mcp-kb-readonly.json; keys: The MCP configuration file). Without one the server offers every reading tool. The instructions come from the file the configuration names (relative to it), or from --instructions FILE (or an instructions.md next to build.py), appended to the built-in text (--instructions-mode replace: instead of it).

{
  "server_name": "project-kb",
  "instructions": { "mode": "replace", "file": "kb-instructions.md" },
  "tools": { "include": ["gql", "get_schema", "run_saved_query"] },
  "saved_query_tools": { "folders": ["kb"], "paging_params": false },
  "resources": ["schema", "saved-queries", "gql-reference"],
  "answer_limit_chars": 30000
}

With 14 saved queries in the folder kb this prompt (instructions and tool list) costs an agent about 3.3 K tokens, against about 4.6 K for every reading tool without a configuration; after a local build build.py prints this figure.

The command of the image is the read-only serving mode with read-only MCP:

graphersal --graph /kb/graph.gstore --read-only --server --host 0.0.0.0 --port 8080 \
  --mcp --mcp-read-only --mcp-config /kb/mcp-config.json

The health check is graphersal health --ready: the container turns healthy once the store and its models are loaded. Its start period is 60 s; the store above (565 MiB, a 506 MiB model) is ready in about 4 s on a laptop (also under amd64 emulation on an arm64 Mac; the model itself is loaded at its first use), so raise it only for a much larger knowledge base (docker run --health-start-period 5m, or the probes of your orchestrator).

Run and connect

docker run --rm --read-only -p 127.0.0.1:8080:8080 my-kb:1
curl -s http://localhost:8080/readyz          # {"status":"ready"}

--read-only (a read-only root file system) is the intended way: the server writes no file at all, its usage statistics stay in memory (GET /api/mcp/stats), diagnostics go to stderr. Pass more options by repeating the whole command after the image name (the entry point is the binary), or set GRAPHERSAL_ALLOWED_HOSTS and GRAPHERSAL_LOG with -e. The limits of the read-only serving mode (--workers, --queue, --timeout, ...) are the defaults; --memory-limit auto follows the container's memory limit (docker run --memory).

Connect an agent with the URL alone:

claude mcp add --transport http kb http://localhost:8080/mcp          # Claude Code
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": { "kb": { "type": "remote", "url": "http://localhost:8080/mcp" } }
}

(the second is opencode.json for opencode). Behind a proxy the URL is https://kb.example.com/mcp. The playground is at http://localhost:8080/.

Update the knowledge base

Replace the store and run build.py again with a new tag: the binary and configuration layers come from the cache, only the store layer is new. Replace the running container by the new image (docker stop -t 30 lets running queries finish; see Stopping). A new binary is a new archive or --version; the store is prepared again by it automatically.

Behind a reverse proxy

The server speaks plain HTTP. On a network, put a reverse proxy in front of it that:

  • ends TLS (the server has none);
  • closes idle connections and caps the connections to the server: the server keeps a thread per open connection without an idle timeout of its own, and refuses requests beyond --max-connections (512) with 503;
  • absorbs bursts of new connections (the server's listen backlog is 128).

Name the proxy's public host names with --allowed-host or GRAPHERSAL_ALLOWED_HOSTS (comma-separated): the server refuses a fully qualified Host it does not know with 403 (protection against DNS rebinding), and accepts an https:// Origin of an allowed name, so the playground works through the proxy (Safety).

docker run -d --read-only --name kb -p 127.0.0.1:8080:8080 \
  -e GRAPHERSAL_ALLOWED_HOSTS=kb.example.com my-kb:2026-11-06

Caddy (Caddyfile; certificates automatic):

{
    servers {
        timeouts {
            idle 2m
        }
    }
}

kb.example.com {
    reverse_proxy 127.0.0.1:8080 {
        transport http {
            max_conns_per_host 256
            keepalive 60s
        }
        flush_interval -1
    }
}

nginx:

upstream graphersal {
    server 127.0.0.1:8080 max_conns=256;
    keepalive 32;
    keepalive_timeout 60s;
}
limit_conn_zone $binary_remote_addr zone=kb_per_ip:10m;

server {
    listen 443 ssl;
    server_name kb.example.com;
    ssl_certificate     /etc/ssl/kb.example.com.crt;
    ssl_certificate_key /etc/ssl/kb.example.com.key;
    keepalive_timeout 65s;
    client_body_timeout 30s;
    limit_conn kb_per_ip 64;

    location / {
        proxy_pass http://graphersal;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_read_timeout 60s;
        proxy_buffering off;
    }
}

max_conns/max_conns_per_host bound the connections to the server (keep them below --max-connections); limit_conn stops one client from taking them all. The proxy adds no authentication here; add one in the proxy if you need it (MCP clients then must send its credentials).

Health checks

EndpointAnswerUse
GET /healthz200 {"status":"ok"} while the process answers HTTP: also while the graph loads, a long query runs or the server stopsliveness
GET /readyz200 {"status":"ready"} once the graph is loaded; 503 {"status":"loading"} before, 503 {"status":"stopping"} after SIGTERMreadiness

Both also answer HEAD. They take no lock, never wait for a running query (a long write never fails liveness), reveal nothing of the graph and are exempt from the Host/Origin checks, so a Kubernetes probe (Host: <pod IP>:8080) and a Docker health check work in every bind mode. The server listens before it loads its graph: while a large Store opens, /healthz answers 200 and /readyz and every other endpoint 503. Probe requests are not logged.

The image has no curl or wget; the binary is its own probe:

graphersal health                 # GET /healthz on 127.0.0.1:8080; exit 0 when it answers 200
graphersal health --ready         # GET /readyz
graphersal health --host 10.0.0.5 --port 9000 --timeout 1000

It prints nothing on success and the reason on stderr otherwise (exit code 1; 2 for an invalid invocation). The image's health check:

HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=3 \
    CMD ["/usr/local/bin/graphersal", "health"]

Kubernetes

apiVersion: apps/v1
kind: Deployment
metadata: { name: graphersal }
spec:
  replicas: 1
  selector: { matchLabels: { app: graphersal } }
  template:
    metadata: { labels: { app: graphersal } }
    spec:
      terminationGracePeriodSeconds: 30
      securityContext: { runAsNonRoot: true, runAsUser: 65532, fsGroup: 65532 }
      containers:
        - name: graphersal
          image: mygraph:0.4.0            # an image of your own (see above)
          ports: [{ containerPort: 8080 }]
          securityContext: { readOnlyRootFilesystem: true, allowPrivilegeEscalation: false }
          livenessProbe:
            httpGet: { path: /healthz, port: 8080 }
            periodSeconds: 10
          readinessProbe:
            httpGet: { path: /readyz, port: 8080 }
            periodSeconds: 5
          startupProbe:                   # a large Store takes time to load
            httpGet: { path: /readyz, port: 8080 }
            periodSeconds: 2
            failureThreshold: 150
          resources:
            limits: { memory: 2Gi }

Every pod serves its own copy of the graph in memory; with --read-only replicas are independent and can scale. Give them the same GRAPHERSAL_MCP_SESSION_KEY (a secret of at least 32 characters, e.g. from a Kubernetes Secret; never printed) so an agent's MCP session id from one replica is accepted by every other one behind the Service; without it each process signs with a random key of its own and an agent switched to another replica initializes again. A read-write Store belongs to one pod (replicas: 1, a ReadWriteOnce volume): its lock refuses a second writer.

The server counts a Kubernetes pod (KUBERNETES_SERVICE_HOST set) as a container and listens on 0.0.0.0; the image passes --host 0.0.0.0 anyway. Requests must name the server by an IP address, localhost, a name without a dot (a Service name such as graphersal) or the --host name: a fully qualified name such as graphersal.default.svc.cluster.local or an Ingress host is refused with 403 (DNS-rebinding protection, see Listening address and Docker) unless it is named with --allowed-host or GRAPHERSAL_ALLOWED_HOSTS (an env entry of the container): name the Ingress host there, and the https:// origin of the playground behind it is accepted too (Behind a reverse proxy). The process memory ceiling is on by default and follows the container's memory limit minus a headroom (--memory-limit auto, the default; --memory-headroom changes the headroom): a query that would exceed it fails and is rolled back instead of the pod being OOM-killed (Resource Limits). A store whose graph does not fit into the container refuses the OPEN instead (exit 1, nothing opened or changed, never maintenance mode); the error names the minimum --memory-limit (or container memory) it needs.

Stopping

docker stop and Kubernetes send SIGTERM. The server is PID 1 in the container, where a process without a signal handler ignores SIGTERM (and is killed after the grace period); the server handles it:

  • --read-only (the read-only serving mode): /readyz turns 503 and no new query is taken; the running queries get --drain-timeout seconds (default 20) to finish, then they are cancelled and the process exits with code 0 (give the container a grace period above the drain timeout: docker stop -t 30, terminationGracePeriodSeconds: 30);
  • without a Store otherwise: the running query is cancelled, /readyz turns 503, and the process exits at once with exit code 0;
  • with a read-write Store: the same, then the store is closed cleanly (its write-ahead log synced, marked closed) before the exit; a second signal exits at once (code 130).

docker stop returns in well under a second. Give a large read-write Store a grace period that covers its close (docker stop -t 30, terminationGracePeriodSeconds). A one-shot script or the REPL running as PID 1 exits with 130 on SIGINT/SIGTERM.

A read-write Store in a volume

docker volume create graphdata
docker run --rm -p 127.0.0.1:8080:8080 -v graphdata:/data graphersal \
  --graph /data/graph.gstore --create-store --server --host 0.0.0.0 --port 8080
  • A named volume mounted at /data takes the ownership of the image's /data (uid 65532), so the non-root server can write it. A bind mount of a host directory keeps the host's ownership: make it writable for uid 65532 (chown 65532:65532 dir) or run with --user $(id -u):$(id -g).
  • Put the store inside the mounted directory (/data/graph.gstore, or /data/graph/ for a directory store), not as the mount point itself: a fork of the store (Store panel) is written next to it, in the same directory.
  • The writer lock is an OS file lock (flock on Linux). It works on local volumes and bind mounts; Docker Desktop's file sharing (macOS, Windows) and network file systems may not honour it between machines. Open a store from one container at a time.
  • Without --read-only the server writes only into the store (and a --graph file on "Save to file"): there are no temporary files elsewhere, so docker run --read-only works with the volume as the one writable place. A tmpfs (--tmpfs /tmp) is not needed.

Logs and configuration

Everything goes to stdout and stderr, nothing to log files: the address line on stdout (written and flushed once the server serves, so docker logs shows it at once), the start banner, warnings and store messages on stderr. GRAPHERSAL_LOG=off|error|warn|info|debug|trace sets the level of the library's messages (default warn): docker run -e GRAPHERSAL_LOG=info .... TZ sets the time zone of scheduled jobs (distroless has no /etc/localtime, so they run in UTC without it).

Options come from the command line, or from a JSON file with --args-file FILE (or @FILE; Arguments from a file), which fits a ConfigMap or a mounted file:

docker run --rm -p 127.0.0.1:8080:8080 -v "$PWD/my.gstore:/data/graph.gstore:ro" \
  -v "$PWD/server.json:/config/server.json:ro" graphersal @/config/server.json
{"graph": "/data/graph.gstore", "read-only": true, "server": true, "host": "0.0.0.0",
 "port": 8080, "mcp": true, "mcp-read-only": true, "timeout": 30000, "memory-limit": "auto"}

Building the image

docker build -t graphersal .
docker build --build-arg RUST_VERSION=1.91 -t graphersal .     # another toolchain

The build stage is rust:<RUST_VERSION>-alpine (musl, a static binary; profile dist, symbols stripped). It links with thin LTO by default: the fat LTO of the release binaries needs more memory than the 8 GB of a default Docker Desktop VM (the linker is killed); --build-arg LTO=fat builds exactly the release binary where the builder has the memory. Dependencies and the target directory live in BuildKit cache mounts, so a source change rebuilds only the workspace crates. The base image tags in the Dockerfile are examples: bump them when you build. docker builder prune removes the build cache.

GraphSON

GraphSON 3.0 is TinkerPop's JSON graph format and Graphersal's primary exchange format for Gremlin users: TinkerGraph, Gremlin Server and JanusGraph write it with g.io("graph.json").write(), and TinkerGraph reads Graphersal's export with g.io("graph.json").read(). GraphML stays available as the second format. Both need the io feature, and neither carries the schema (see Schema).

Reading and writing

Front endImportExport
Rust, new graphGraphSource::from_graphson(path), from_graphson_reader(reader), GraphSource::from_file(path) for .json/.jsonl/.graphson; GraphSONImport::new().load(reader) / load_file(path) also return the reportgraph.export_graphson(path), export_graphson_writer(writer) (GraphExport), GraphSONExport::new().export_writer(&storage, writer)
Rust, live graphgraph.import_graphson(path) / import_graphson_reader(reader) (GraphImport): one unit, returns the report
Rhaig.import_graphson(path): returns the report as text; GraphSource::file("graph.json")g.export_graphson(path)
CLIgraphersal --graph graph.json (also .jsonl, .graphson); skipped data is listed in a note: on stderr-e 'g.export_graphson("out.json")'
PythonGraph.from_graphson(path, schema=None, mode=None) (a schema is set on the new graph first, then the file is imported as one unit); graph.import_graphson(path) into a live graph, one unit; skipped data is one UserWarninggraph.export_graphson(path)
PlaygroundLoad from file with a .json/.jsonl/.graphson file; skipped data is a noticeSave ▾ › Data as GraphSON (also Data as GraphML, Schema)

The file operations ask the authorizer like GraphML's: Read on the File and Create on Data for an import, Read on Data and Create on the File for an export (see Permissions).

use graphersal::io::{GraphExport, GraphImport, GraphSONImport};

let graph = GraphSource::from_graphson("tinkerpop-modern.json")?;
graph.export_graphson("copy.json")?;

let (graph, report) = GraphSONImport::new().load_file("export-from-janusgraph.json")?;
if report.has_skips() {
    eprintln!("{report}");
}

Accepted input

  • Line form: one vertex object per line, TinkerPop's default and the only form io() reads. Blank lines, a UTF-8 byte order mark and \r\n line ends are accepted.
  • Wrapped form: one document {"vertices": [...]} (TinkerPop's wrapAdjacencyList), compact or pretty-printed. Other top-level keys are ignored and reported.
  • Versions: GraphSON 3.0 typed (the default), 3.0 types=false, 2.0 typed and untyped 1.0 and 2.0 are read by one decoder: an {"@type": .., "@value": ..} object is a typed value, anything else is plain JSON. Typed GraphSON 1.0 (@class) and the TinkerPop 2 (Blueprints) format are rejected with IOError::UnsupportedGraphSON.
  • A vertex object is read from id, label, properties, outE and inE. Other keys (Cosmos DB's type, _partition) are ignored and reported. A vertex-property entry needs only value (its id is not kept); an edge entry needs inV/outV.

Type mapping

GraphSONGraphersalExport writes
string, boolean, nullstring, boolean, nullthe same
g:Int32, g:Int64, gx:Int16, gx:Byte, gx:BigInteger (within int64), a plain integerint64g:Int64
g:Double, g:Float, a plain decimal; the payloads "NaN", "Infinity", "-Infinity"float64g:Double (non-finite values as those strings)
g:UUIDuuidg:UUID
g:List, g:Set, a plain arrayarrayg:List
g:Map with string keys, a plain objectobjectg:Map
gx:Charstringa string
g:Date, g:Timestamp (epoch milliseconds)datetime in UTCgx:OffsetDateTime
gx:Instant, gx:OffsetDateTimedatetime with the offset of the text (a text without an offset is malformed and skipped, never read as UTC)gx:OffsetDateTime
gx:ZonedDateTime (2007-12-03T10:15:30+01:00[Europe/Paris])datetime with the offset and the zone id of the text; a zone id the bundled database does not know (GMT+02:00), or whose offset at that instant is not the text's (2024-01-01T10:00+05:00[Europe/Berlin]), is dropped and reported, and the text's offset is keptgx:ZonedDateTime for a datetime with a zone name, else gx:OffsetDateTime
gx:LocalDate, gx:LocalDateTime, gx:LocalTime, gx:OffsetTime (10:15:30+01:00)date, localdatetime, time, offsettimethe same tags
gx:Duration (a fixed length; P2DT3H reads a day as 24 hours; java.time's signed fields PT-1H-30M too)duration of a time part only, up to the java.time.Duration range (a 64-bit count of seconds plus nanoseconds)gx:Duration for a duration of a time part only (PT26H); a negative one as java.time writes it, each field signed (PT-1H-30M, PT-0.5S)
gx:Period (P1Y2M3D, weeks as 7 days)duration of months and daysgx:Period for a duration of months and days only
graphersal:Interval (Graphersal's own tag)durationgraphersal:Interval for a duration with both months or days and a time part (P1MT2H): no java.time type holds it, so TinkerGraph cannot load such a value
g:List of numbers, read as a list; a vector where the target graph's schema declares one (mode open or closed, coerced on write); graphersal:Vector (Graphersal's own exact tag, as a serialized ChangeSet writes it)vector (book page Vectors)g:List of g:Float, which TinkerGraph loads; an i8 or bit vector as its dequantized values
gx:Year, gx:YearMonth, gx:MonthDay, gx:ZoneOffset, g:Calendar, g:TimeZoneskipped
gx:BigDecimal, g:Class, the enum tokens, g:Vertex/g:Edge/g:Path/... as a value, vendor types (janusgraph:Geoshape)skipped

Nothing is guessed: a string stays a string whatever it looks like (a date-like text without a type tag, as in GraphSON 1.0 or types=false, stays a string; declare the property in the schema to store it as a date), and a value whose type Graphersal cannot hold is skipped, never converted to a string or a number. The java.time types map to the date and time types by their tag (both the gx: and the g: prefix are read; the types are described in Dates and Times); their text is read as java.time writes it (seconds may be missing, up to nine fraction digits), and kept to the nanosecond, Graphersal's resolution. A date outside the years -9999 to 9999, or text that is not of the tag's type, is skipped as malformed. The export writes each value's canonical text, which java.time's parsers read, with all nine fraction digits where the value has them; a negative gx:Duration is written in java.time's own form, because Duration.parse sums the fields before it applies a leading sign and so cannot read -PT2562047788015215H30M8S, the canonical text of the shortest duration. TinkerGraph's g.io(file).read() loads every value (except graphersal:Interval). A skipped value inside a container skips the whole property value. A value nested deeper than 128 levels, a g:Map with an odd number of items or a non-string key, and a payload that does not fit its type ({"@type": "g:Int32", "@value": "7"}) are skipped as malformed.

A number outside int64/float64 (a plain integer above i64::MAX, 1e999) makes its line fail to parse; the import stops with IOError::GraphSONParse.

Structure mapping

GraphSONGraphersal
element id of any typea string: g:Int32 1 becomes "1", a g:UUID its canonical text, JanusGraph's {"relationId": "x"} becomes "x", any other id its JSON text
vertex without an idthe graph assigns one (reported)
label "A::B"the label set [A, B] (Multi-Label Vertices)
properties.k with one entrythe entry's value
properties.k with several entries (list cardinality)one array of the values (reported)
meta-properties of an entrythe reserved object property _meta: _meta.k = {..} for one entry, an array of objects aligned with the values for several (reported)
outE and inEedges. outE is the source of truth; an inE copy with the same id is matched with it (a disagreement is reported, the outE copy wins); an edge found only in inE (a file written with Direction.IN) is added. Without an id, an inE entry is taken only when its tail vertex has no outE
an edge whose other endpoint is not in the fileconnected to the target graph's vertex of that id if one exists, else skipped (reported)
a vertex id used twicethe first vertex wins, the second and its edges are skipped (reported)

Export does the reverse: every vertex is one line with id, label, inE, outE and properties; ids are JSON strings; a label set is joined with "::"; vertex-property ids are a file-wide g:Int64 sequence. _meta is written back as meta-properties when it has exactly the shape an import produces (an object per key, or an array aligned with an array value of two or more items: then the array becomes that many entries); any other _meta is written as an ordinary property, so a round trip never loses it.

A graph exported by Graphersal and imported again is the same graph: ids, label sets, every property with its exact logical type (int64, float64 including NaN and infinities, uuid, nested array/object, every date and time type with a datetime's offset), edge ids, labels and properties. Only the iteration order of edges may differ, because GraphSON groups them by vertex and label. Two Graphersal elements have no TinkerPop counterpart and come back changed: a vertex without labels is written with TinkerPop's default label vertex, an edge without a label with edge, and both are read back with that label.

The import report

ImportReport (graphersal::io) holds the counts of imported vertices and edges and one ImportNote per kind of event, with a count and up to five sample locations (line 3: vertex "1", property "born"; vertices[2]: ... in the wrapped form). ImportNoteKind says what happened; its Skipped* kinds lost data (is_skip()), the others only changed the representation:

KindMeaning
SkippedDateTime { type_tag }a date/time value of a type Graphersal cannot hold (gx:Year, gx:MonthDay, ...)
SkippedUnsupportedType { type_tag }a value of a type Graphersal cannot hold
SkippedMalformedValuea value whose payload does not fit its type, or nested too deeply
SkippedMalformedEntrya vertex-property or edge entry without the expected shape
SkippedDuplicateVertexa vertex whose id came earlier in the file
SkippedDanglingEdgean edge to a vertex that does not exist
SkippedDuplicateEdgean edge whose id a different edge of the file already has
SkippedReservedMetaa _meta property of a vertex that also has meta-properties
MultiValuedToArray, MetaPropertiesToMeta, LabelSplit, VertexWithoutId, EdgeCopiesDisagree, IgnoredKey { key }representation changes
ZoneDropped { type_tag }a gx:ZonedDateTime imported as a datetime with the offset of its text; its zone id is not a zone of the bundled database, or that zone's offset at that instant is not the text's, so the name is not kept (the offset is never recomputed from it)
SubMicrosecondsCut { type_tag }deprecated since 0.3.0 and never reported: values keep nanoseconds (kept so code that matches it compiles)

Its Display is the text the CLI, Rhai and Python show: a first line with the counts and one line per note.

Limits and errors

One line (line form) or the whole document (wrapped form) is read only up to GraphSONImport::max_text_bytes (512 MiB natively, 64 MiB on wasm32); a longer one fails with IOError::InputTooLarge before it is held in memory (GraphSONImport::new().with_max_text_bytes(n) changes it). Use the line form for large graphs: it is read line by line, and only the edges are buffered until every vertex is known. JSON nesting is bounded, so no input can exhaust the stack.

Fatal errors stop the import, and on a live graph roll it back as a whole: invalid JSON or a line that is not an object (IOError::GraphSONParse with the line), an unsupported variant (IOError::UnsupportedGraphSON), an oversized line, and every graph error, such as a schema violation or a vertex id that already exists in the target graph (IOError::Graph).

Schema

GraphSON carries no schema. Typed values keep their own types, so a GraphSON file needs no schema to come back exactly. When the target graph stores a schema, the import goes through it like any other write: open/closed coerce declared fields (an untyped canonical UUID string becomes a declared string with format: uuid) and reject what violates it, which fails the import. Save the schema separately (g.get_schema(), its JSON in the schema format) and set it on the target with g.set_schema(..) before importing. The front ends do both steps in that order for you: graphersal --graph graph.json --schema schema.json [--schema-mode closed], Python Graph.from_graphson(path, schema=.., mode=..) and the playground's Load from file with its optional schema file.

Loading an export into TinkerGraph

Element ids are strings in Graphersal, the same model as Amazon Neptune and Azure Cosmos DB, and the export writes them as JSON strings ("id":"1"). A TinkerGraph opened with its default id manager keeps them as Strings, so it answers g.V("1"), and g.V(1) finds nothing. When the ids are numeric, open the TinkerGraph with the LONG id managers: they convert every id they read (and every id a query passes, 1, 1L or "1") to a Long, so g.V(1) works as on TinkerPop's own sample graphs:

import org.apache.commons.configuration2.BaseConfiguration
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph

conf = new BaseConfiguration()
conf.setProperty("gremlin.tinkergraph.vertexIdManager", "LONG")
conf.setProperty("gremlin.tinkergraph.edgeIdManager", "LONG")
// keeps every value of an array that came from a multi-property (see below)
conf.setProperty("gremlin.tinkergraph.defaultVertexPropertyCardinality", "list")
graph = TinkerGraph.open(conf)
g = graph.traversal()
g.io("modern.json").read().iterate()
g.V(1).out("knows").values("name")   // ==> vadas, josh

The same keys go into a Gremlin Server's TinkerGraph .properties file (gremlin.tinkergraph.vertexIdManager=LONG, ...). The LONG managers need ids that parse as numbers: a graph with ids such as "V_0_0" fails to load with them (Expected an id that is convertible to class java.lang.Long); load it with the default managers and query it by its string ids.

Verified with TinkerGraph 3.8.2 (Gremlin Console, g.io(file).read()) on the exports of modern, large (111 110 vertices, 111 100 edges) and a graph with every value type:

WhatDefault id managersLONG id managers
vertex and edge countsexactexact (large: fails, its ids are not numbers)
id typeStringLong
g.V(1) / g.V(1L)nothingthe vertex
g.V("1")the vertexthe vertex
valuesint64 -> Long, float64 -> Double (also NaN), uuid -> UUID, array -> List, object -> Map, string, booleanthe same
_metameta-properties on the vertex propertiesthe same
multi-label vertexone label "A::B"the same

TinkerGraph's default vertex-property cardinality is single: an array exported as several entries with meta-properties (a former multi-property, _meta aligned with it) keeps only its last entry unless the graph is opened with defaultVertexPropertyCardinality list. With list, the file TinkerGraph writes back (g.io(file).write()) imports into Graphersal as the same graph: values with their types, the array, _meta, and the label set from "A::B".

Deviations from TinkerPop

Listed in TinkerPop Deviations as well:

  • Ids are strings. Imported numeric ids become strings, and export writes string ids, so a TinkerGraph that loads the export answers g.V("1"), not g.V(1), unless it is opened with the LONG id managers (recipe).
  • Multi- and meta-properties are folded into an array and the _meta property, because Graphersal stores one value per key; export restores them only from _meta, otherwise an array is one vertex property holding a g:List.
  • Multi-labels are written as "A::B", which TinkerGraph treats as one opaque label (Neptune's convention, see Multi-Label Vertices).
  • Unlabeled elements are written with the default labels vertex/edge and read back with them.
  • Skipped values: the types listed above as skipped (gx:Year, gx:BigDecimal, ...) are skipped and reported where TinkerPop reads them.
  • Dates: a gx:ZonedDateTime whose zone id the bundled database does not know keeps its offset but not its zone id (reported). One whose offset is not its zone's offset at that instant (written with another time zone database) keeps the offset of the text and drops the name (reported), where java.time keeps the instant and the zone and recomputes the offset (user decision: the stored offset is kept as written, never recomputed from a zone name, as in the store). A duration with both months or days and a time part is exported as graphersal:Interval, which TinkerPop cannot read.
  • Lenient structure: an edge to a missing vertex is skipped (TinkerPop's readGraph fails), a duplicate vertex id keeps the first vertex, and vertex-property ids are not kept.
  • Widening: g:Int32 and g:Float come back as g:Int64 and g:Double on export.

Generating Test Data

Fake(seed) is a generator of test data for scripts: English names, e-mail addresses, job titles, addresses, companies and words, plus the random numbers a script needs to build a graph's shape (how many reports a manager has, who knows whom). It is part of the Rhai DSL (feature script), so it works in the CLI, the playground, the dev server and Python alike.

let f = Fake(42);
f.full_name()             // "Lawrence Young"
f.int(1, 6)               // 2: a die roll
f.email("Ada Lovelace")   // "ada.lovelace35@example.com"

Reproducible by design

The same seed and the same sequence of calls give the same values, on every platform (native and WebAssembly) and in every run. A graph generated from a seed can be rebuilt exactly, to reproduce a bug, to compare two versions of a query, or to benchmark on the same data.

  • Fake() without a seed picks a random one; f.seed() tells which, so a run you liked can be repeated with Fake(that_seed).
  • The generator is Graphersal's own (SplitMix64), not the rand crate's, whose algorithms may change between versions. The word lists and the way each method draws are part of the contract as well: a change to them changes what every seed produces, so it is treated as a breaking change (a test pins the values of seed 42).
  • random.seed (g.with("random.seed", n)) seeds the random steps of one traversal (coin(), sample(), order().by(Order.shuffle)); Fake is independent of it.

Copies share one stream

A Fake value is a handle. A copy (let b = a;, a function argument) draws from the same stream, so a helper function advances the caller's generator and every call gets new values:

fn person(f) { #{ name: f.full_name(), age: f.int(18, 90) } }
let f = Fake(1);
[person(f), person(f)]   // two different people

Forks: independent streams

f.fork(name) returns a generator for the stream name of the same seed. A fork depends only on the seed and its name (and the names of the forks above it), never on what was drawn before. Give each part of a generator its own fork, and drawing one more value in one part does not shift the values of all the others:

let f = Fake(42);
let people = f.fork("people");
let social = f.fork("social");   // unchanged when the people part draws more values

Methods

MethodResult
seed()The seed (of the root, for a fork)
fork(name)An independent generator for the named stream
int(lo, hi)An integer from lo to hi, both included
float(), float(lo, hi)A float in [0, 1) or [lo, hi)
chance(p)true with probability p (0.0 to 1.0)
pick(array)A random element of a non-empty array
shuffle(array)A copy of the array in random order
sample(array, n)n distinct elements of the array, in random order
uuid()A version 4 UUID value (the Uuid type, see UUID Values)
first_name(), last_name(), full_name()Common US given names and surnames
username()victoriav971
email(), email(name)An address at example.com/.org/.net (RFC 2606); with a name, made from it
phone()A US number in the fictional 555-01xx range
job_title()Senior Data Analyst
street_name(), street_address()Lakeview Circle, 5666 Broad Trail
city(), state(), state_abbr(), zip_code(), country()Real US cities and states, countries
address()One line; its city and state belong together
company(), domain_name()Vargas & Ryan, vasquezsalt.info
word(), sentence()English words; a sentence of 4 to 12 of them
lorem(lo, hi)Lorem ipsum text of a random length from lo to hi bytes (both included, at most 16 MiB): paragraphs separated by an empty line, starting with "Lorem ipsum dolor sit amet", ending with a period; for large text fields, e.g. to try compressed properties
lorem_sentence(), lorem_paragraph()a Lorem ipsum sentence of 6 to 14 words; a paragraph of 3 to 7 sentences

Methods of two words are snake_case only (full_name, zip_code, ...), like every Graphersal extension. A wrong argument (int(5, 1), chance(1.5), pick([]), sample([1], 2)) is a script error that names the method.

Only English data exists for now. Fake has no date method; build a random date from a number: date("2024-01-01") + duration("P" + f.int(0, 365) + "D") (Dates and Times).

Building a graph

The playground's Examples menu has a complete generator under Generated test data (Fake): its parameters (seed, number of companies, depth and fan-out of the management trees, number of knows edges, number of cities) are Rhai variables at the top of the script. Its core:

let f = Fake(42);
let people = f.fork("people");
let ids = [];
for i in 0..100 {
    let name = people.full_name();
    ids.push(g.add_v("person").property("name", name)
        .property("email", people.email(name)).property("age", people.int(21, 67))
        .id().next());
}
let social = f.fork("social");
for k in 0..300 {
    let a = ids[social.int(0, ids.len() - 1)];
    let b = ids[social.int(0, ids.len() - 1)];
    if a != b { g.v(a).add_e("knows").to(g.v(b)).to_list(); }
}

Pick from a large array by index, as above: pick(), shuffle() and sample() receive a copy of the array they are given, which costs one copy per call. The example's largest setting (3 companies, depth 6, fan-out 4: 16 383 people, 50 000 knows edges) takes about a second in a native release build.

Running Queries Safely

By default the library trusts its caller: the Rust API and the plain script::eval* helpers allow everything and run without limits beyond the safe script defaults. A host that runs queries it did not write (a web service, a plugin system, an AI agent) restricts them on three levels:

  • Permissions decide what a query may do: read or write data, change the schema, read files, set administrative options. A ready-made AccessPolicy (for example read_only()) or your own Authorizer checks the plan once, before it runs.
  • Limits decide how much it may use: script operations, traversers, materialized bytes, string sizes, nesting depth, a memory budget.
  • Time bounds how long it may run: evaluationTimeout, loop limits, and a cancel token that stops a running query from another thread.

A host sets the defaults and can lock them, so a query cannot raise its own limits with g.with(...). Every refused or stopped query is rolled back.

PageWhat it covers
Permissionsrequests, AccessPolicy, writing an authorizer, file roots
Resource Limitsscript and traversal limits, the memory budget, the defaults of each front end
Query Limitstimeouts and loop limits
Execution Options Referenceevery g.with() key and how a host locks it

Permissions

Graphersal is an in-process, in-memory library: the program that holds the graph usually also writes the queries. Everything is therefore allowed by default, in the Rust API and in the Rhai script entry alike. A host that runs input it does not trust (a web form, a multi-tenant query service, a pasted snippet, an LLM) plugs in an authorizer: a graphersal::auth::Authorizer that is asked for every request a query makes, before the query runs.

Resource use is a separate concern, bounded by Resource Limits and Query Limits.

Requests: an action on a resource

Every step and every file or schema operation of a query makes one or more AccessRequests, an Action on a Resource:

Action
Readread data, the schema, a catalog definition or a file
Createcreate elements, write a file
Updatechange elements (properties, labels), the schema or an option
Deletedrop elements or properties
Executerun code: Rhai's import "module", calling a saved query, running an embedder
Custom(name)an action of an embedding server, never produced by the library
Resource
Data { element, label }graph data; element (Vertex/Edge) and label are set when the step knows them statically from the plan, None otherwise
Schemathe graph's schema
Definition { kind, name }a definition of the graph's catalog (a saved query, ...); kind and name are None for a request about all of them (listing)
File { path }a file, with the path as the script wrote it
Option { key }an administrative g.with() option (below)
Embedder { name }an embedder of the graph: the built-in "hash-ngram/1" or a model of its database, by its repository (Vectors)
Journalthe system journal: Read to query or follow it, asked by the session, the dev server (GET /api/journal) and MCP (the Rust API itself asks nothing); a denial of any request is recorded there as auth.denied (action, resource kind and channel only)
Custom { kind, name }a resource of an embedding server (a database, a tenant, ...), never produced by the library

What each step requests is decided in one place in the engine (GraphStep::for_each_access):

QueryRequests
V() / out_v(), in_v(), both_v(), other_v()Read on Data(vertex)
E() / out_e(), in_e(), both_e()Read on Data(edge)
out(), in(), both()Read on Data(edge) and on Data(vertex)
subgraph("sg")Read on Data(vertex) (it copies the endpoints of the edges it receives)
inject(v) of a vertex / an edge valueRead on Data(vertex) / Data(edge) (it emits the stored element of that id)
every other step (has(), values(), limit(), count(), inject() of plain values, constant(), math(), as(), by(), ...)nothing
addV("person"), addV(["a", "b"])Create on Data(vertex "person"), one request per label (Data(vertex) without a static label)
addE("knows")Create on Data(edge "knows")
g.gql("INSERT (:person {name: 'ann'})-[:knows]->(:person)")Create on Data(vertex "person") per new node and label, Create on Data(edge "knows") per new edge, and nothing for the properties (addV("person").property(..) also asks Update, see Writing with GQL); the MATCH before an INSERT asks its reads like its Gremlin twin
g.gql("MATCH (a)-[e:knows]->(b) SET e.seen = true, b:known"), REMOVE ..Update on Data(vertex) for a node target (any label, as for add_label()), on Data(edge "knows") for an edge whose pattern names its labels, on Data when the kind is known only at run time (a FOR item); the same as the Gremlin twins property(), remove_property(), add_label(), drop_label()
g.gql("MATCH ()-[e:knows]->() DELETE e"), DETACH DELETE nDelete on Data(vertex) for a node, on Data(edge "knows") for an edge whose pattern names its labels, on Data for a path, a list or a value known only at run time; DETACH asks nothing more; the same as drop()
g.gql("MERGE (p:person {name: 'ann'}) ON MATCH SET p.seen = true")Create per label of every element the pattern can create (as its INSERT), Update only for ON CREATE SET / ON MATCH SET items (as SET), checked first, then the Reads of the search (as a MATCH of the pattern), whether a row finds or creates (Writing with GQL)
mergeV(..) / mergeE(..)Read on what the merge searches (Data(vertex) for mergeV(); Data(edge) and Data(vertex), the endpoints its ids name, for mergeE()), then Create and Update on Data(vertex) / Data(edge): a policy denying reads cannot probe existence through a merge
property(..), remove_property(..)Update on the Data the steps before it state (see below), Data when they state nothing
add_label(..), drop_label(..) / set_label(..)Update on Data(vertex) / Data(edge), with the edge label the steps before it state
drop()Delete on the Data the steps before it state, Data when they state nothing
infer_schema(), g.get_schema(), g.infer_schema(), g.diff_schema(..), g.validate_schema(..), g.validate_schema_patch(..)Read on Schema
g.statistics(), g.memory_usage()Read on Data
embed(..) (the step) and embed(text) (the function)Execute on Embedder("name"), the embedder that runs (the default resolved to its name), for every embedder including the built-in hash-ngram/1
a vector rulesetting the schema asks Update on the schema; the vectors it writes at the end of a unit ask nothing of their own (like create-time defaults), and its model runs without Execute on the embedder
g.embedders()nothing (it lists the embedders of the database and runs none of them)
nearest(key, "text", k), similarity(key, "text") (a text query)Execute on the embedder of the model the schema declares for the property (on each one when labels declare different models)
g.set_schema(..), g.patch_schema(..)Update on Schema (a schema is never read from a file)
list_definitions(kind) (Rust)Read on Definition(kind) (Definition for every kind)
get_definition(kind, name) (Rust)Read on Definition(kind "name")
set_definition(..), define_query(..) (Rust)Create on Definition(kind "name") for a new definition, Update when it replaces one
move_query(..), describe_query(..) (Rust)Update on Definition(query "name")
remove_definition(kind, name) (Rust)Delete on Definition(kind "name")
g.query("name", ..)Execute on Definition(query "name") before the body runs; for a query that writes, then each of its inferred effects (Create Data(vertex "person"), ...); the body's own requests then go through the host's authorizer under the saved query's restriction (a read-only query: every write denied; a query that writes: every write outside its effects denied; see Saved Queries)
GQL CALL folder.name(..)Execute on Definition(query "name") for each call step, then the called query's own reads and writes as part of the calling query, asked of the caller's authorizer (Calling saved queries from GQL)
g.queries(), g.queries(folder)Read on Definition(query)
g.get_query("name")Read on Definition(query "name")
g.define_query(..), g.define_queries(..)Create on Definition(query "name") per query, Update when it replaces one
g.move_query(..), g.describe_query(..)Update on Definition(query "name")
g.drop_query("name")Delete on Definition(query "name")
g.define_compression(..)Create on Definition(compression "name"), Update when it replaces one
g.compressions()Read on Definition(compression)
g.recompress("name") / g.drop_compression("name")Update / Delete on Definition(compression "name")
g.mark("name")Update on Data
g.export_snapshot(path)Read on Data, Create on File(path)
g.export_graphml(path)Read on Data, Create on File(path)
g.import_graphml(path)Create on Data, Read on File(path)
g.export_graphson(path) / exportGraphsonRead on Data, Create on File(path)
g.import_graphson(path) / importGraphsonCreate on Data, Read on File(path)
GraphSource::file(path)Read on File(path)
import "module" (Rhai)Execute on File("module.rhai")
an administrative g.with(key, ..)Update on Option(key)

A write of the elements a step receives (property, removeProperty, drop(), the label steps) names what the steps before it in the same traversal state, so a policy can tell g.E().hasLabel("knows").drop() (Delete on Data(edge "knows")) from g.E().drop() (Delete on Data(edge)): V(), out(), the endpoint steps and mergeV() give vertices, E(), outE("knows") and mergeE() edges (with the labels given), addV("person") / addE("knows") their new element, and hasLabel(..) the labels of edges; filters, side effects, modulators and the ordering and windowing steps (limit, order, dedup, ...) keep what is stated, every other step ends it, and a child traversal starts from nothing. A vertex has a label SET, so a vertex label is stated only where the plan gives all of them (addV(labels)): g.V().hasLabel("person").drop() asks Delete on Data(vertex), because a vertex labelled {person, secret} passes that filter.

Only steps that reach graph data ask for a read: the sources (V(), E(), also in the middle of a traversal) and the adjacency steps. A value-only step works on what earlier steps produced, so it asks nothing: g.V().has("age", P.gt(30)).values("name").limit(2) asks exactly once, for Read on Data(vertex), and g.inject(1, 2).sum() runs under AccessPolicy::deny_all(). No live element handle survives a run: let v = g.V().next() is a detached copy of the vertex (see Vertices and Edges as Values), and reading the copy (v.name, v["age"]) asks nothing. Passing it back (g.inject(v), also an edge's endpoint e.out_v) reaches the stored element of its id, so it asks Read on Data(vertex) (Data(edge) for an edge) like V(): a copy cannot open a way to data the policy hides.

Labels of reads are not reported: a request reports what the plan states, and a plan cannot say statically which labels a read reaches. Element- and label-level read security is a later storage decorator (Later). A policy that restricts one element kind or label must treat None as "possibly that one".

The ready-made policy: AccessPolicy

AccessPolicy allows or denies by action kind and resource kind, plus an optional file root. It covers what the shipped front ends need without a trait implementation of their own:

use graphersal::prelude::*;
use graphersal::auth::{AccessPolicy, ActionKind, ResourceKind};
use graphersal::catalog::Definition;

let query_service = AccessPolicy::read_only();             // Read on Data, Schema, Definition;
                                                           // Execute on Definition (saved queries)
                                                           // and on Embedder; Read on Journal
let editor = AccessPolicy::read_only()
    .allow(ActionKind::Create, ResourceKind::Data)
    .allow(ActionKind::Update, ResourceKind::Data)
    .allow(ActionKind::Delete, ResourceKind::Data);
let server = AccessPolicy::allow_all().deny_resource(ResourceKind::File);
let nothing = AccessPolicy::deny_all();                    // a script can only compute
let _ = (query_service, editor, server, nothing);

Restricting a script

graphersal::script::engine(), graph_scope(g) and the eval_* functions without limits allow everything. The entries that take explicit limits take the authorizer too:

use std::sync::Arc;
use graphersal::prelude::*;
use graphersal::auth::{AccessPolicy, Authorizer};
use graphersal::script::ScriptLimits;

let graph = Arc::new(GraphSource::tinkerpop_modern());
let read_only: Arc<dyn Authorizer> = Arc::new(AccessPolicy::read_only());
let names = graphersal::script::eval_value_with_limits(
    graph.clone(),
    r#"g.V().hasLabel("person").values("name").toList()"#,
    Default::default(),
    &ScriptLimits::default(),
    read_only.clone(),
);
assert!(names.is_ok());
let denied = graphersal::script::eval_value_with_limits(
    graph,
    r#"g.addV("x").next()"#,
    Default::default(),
    &ScriptLimits::default(),
    read_only,
);
assert!(denied
    .unwrap_err()
    .to_string()
    .contains(r#"Permission denied for 'add_v' (Create Data(vertex "x"))"#));

A host that drives its own engine passes the same authorizer to both halves of the entry: the engine (Rhai's import, and the graphs a script creates with GraphSource::empty() and friends) and the scope (the session's g):

use std::sync::Arc;
use graphersal::prelude::*;
use graphersal::auth::{AccessPolicy, Authorizer};
use graphersal::script::{engine_with_limits, graph_scope_with_options, ScriptLimits};

let graph = Arc::new(GraphSource::tinkerpop_modern());
let authorizer: Arc<dyn Authorizer> = Arc::new(AccessPolicy::read_only());
let engine = engine_with_limits(&ScriptLimits::default(), authorizer.clone());
let mut scope = graph_scope_with_options(graph, &[], authorizer);

A Rust-built traversal is checked the same way with GraphTraversalSource::with_authorizer(authorizer).

The front ends this project ships:

Front endPolicy
graphersal CLIeverything (AllowAll): a local tool over your own graph and files
Web playground and the dev server (graphersal --server)everything but files (AccessPolicy::allow_all().deny_resource(ResourceKind::File)): the browser has no file system; graphs are loaded and saved through the page
MCP endpoint of the dev serverthe same as the page; with --mcp-read-only, read_only_authorizer() of graphersal-session: no files, and no Create/Update/Delete on Data, Schema or Definition
Python binding (Graph.execute, query, dry_run)everything when the call names no policy=: a Python program is a trusted local host. Pass policy=graphersal.AccessPolicy.read_only() (or another AccessPolicy) per call for scripts you did not write

Writing an authorizer: roles from a token

The subject (who asks) is not part of the request. It lives inside the authorizer instance, so a server builds one authorizer per connection or session, for example from the roles in a JWT it has already verified, and maps them to actions and resources. Roles are not a library concept:

use std::sync::Arc;
use graphersal::prelude::*;
use graphersal::auth::{AccessRequest, Action, Authorizer, Denied, Resource};

/// Built per connection from the verified token's claims.
struct Session {
    roles: Vec<String>,
}

impl Session {
    fn has(&self, role: &str) -> bool {
        self.roles.iter().any(|r| r == role)
    }
}

impl Authorizer for Session {
    fn authorize(&self, request: &AccessRequest<'_>) -> Result<(), Denied> {
        let allowed = match (request.action, request.resource) {
            (_, _) if self.has("admin") => true,
            // Everybody reads data and the schema.
            (Action::Read, Resource::Data { .. } | Resource::Schema) => true,
            // Editors change data, except elements labelled `salary`.
            (Action::Create | Action::Update | Action::Delete, Resource::Data { label, .. }) => {
                self.has("editor") && label != Some("salary")
            }
            // Server-owned resources go through the same policy.
            (Action::Custom("open"), Resource::Custom { kind: "database", name }) => {
                name == Some("shared") || self.has("dba")
            }
            _ => false,
        };
        if allowed {
            Ok(())
        } else {
            Err(Denied::new(format!("{request} needs another role")))
        }
    }
}

let session = Arc::new(Session { roles: vec!["editor".into()] });
// The server checks its own resources at its own boundary ...
let open = AccessRequest::new(
    Action::Custom("open"),
    Resource::Custom { kind: "database", name: Some("shared") },
);
assert!(session.authorize(&open).is_ok());
// ... and hands the same authorizer to the script entry.
let graph = Arc::new(GraphSource::tinkerpop_modern());
let denied = graphersal::script::eval_value_with_limits(
    graph,
    r#"g.addV("salary").property("amount", 1).next()"#,
    Default::default(),
    &graphersal::script::ScriptLimits::default(),
    session,
);
assert!(denied.unwrap_err().to_string().contains("needs another role"));

Resource::Custom and Action::Custom are never produced by the library: they exist so that an embedding server can put its own resources (databases, tenants, endpoints) under the same policy and call authorize itself.

The check

The check runs once per execution, before anything runs, on the plan as written: before the optimizer, so no rule can hide a step by fusing it (add_property_fold folds property() into addV, count_pushdown folds count() into V(); the check still sees each of them). It recurses into every child traversal (union, where, by, repeat, sideEffect, ...), and it costs one pass over the steps. Each distinct request is asked once per execution: g.V().out().in() asks Read on Data(vertex) and on Data(edge), once each. There are no per-element checks. A denial is TraverserError::PermissionDenied { step, request, reason } naming the first step (in plan order) whose request was denied, the request (AccessRequestBuf, as_request() gives the action and the resource) and the authorizer's reason; nothing of the traversal has run. A denied step is located like a failing one: the error is the TraverserError::StepFailed chain of that step (at #1: v().add_v("x"), step_location(); step ids are positions of the plan as written) and the denial is its root_cause(). A denied with("key") option or a source method (file, schema) has no step and stays the bare denial. execute() returns the denial in its error instead of throwing.

"Once per execution" means once per traversal that runs. A script, and a saved query's body, may run several traversals: each one is checked when it runs, so a denial in a later one comes after the earlier ones have run (in the playground the whole script is one unit and is rolled back; a saved query that writes runs as one unit too). A saved query is checked in layers. g.query("name", ..) asks Execute on the query before its body runs; a query that writes then asks its whole effect set, so a denial comes before its first write. The body's traversals then go through the same check with the host's authorizer plus the saved query's restriction: a step the host denies is denied inside the body too (the error carries a line in saved query: "name"); in a read-only query every write is denied whatever the host allows, in a query that writes every write outside its effects. A traversal any query returns is read-only, so g.query("name").drop() is denied as well. Nothing in a saved query can do more than its caller may.

Functions are never hidden: a denied step is still registered, listed by help() and completed by the playground. Only running it is denied.

Administrative g.with() options

A query may set the semantic options freely; setting an administrative one is an Update on Option(key):

OptionRequest
evaluationTimeout, repeat.max_loops, bulk.max_expansion, traversal.max_traversers, traversal.max_value_depth, traversal.max_materialized_bytes, traversal.max_string_bytes (resource ceilings); memory.limit, memory.headroom (the process memory ceiling: always refused as options, this check comes first)Update on Option(key)
optimizer.disabled, optimizer.enabled, path.analysis, bulk.merge (engine switches)Update on Option(key)
repeat.order, bulk.one (withBulk(false)), random.seed, render.spelling, the display options (render.max_rows, ...), unknown keys (ignored by the engine)none

An option the host preset (graph_scope_with_options(graph, &[("evaluationTimeout", ..)], ..), or set on a Rust source before with_authorizer) is not the query's setting and asks nothing; a query that sets such a key to another value does. The presets apply to every source of the session: g, _g and __, and, when the engine is built with engine_with_options(&limits, authorizer, &options) and the same options, the sources a script creates itself (GraphSource::empty(), ...), so a script cannot escape a preset by starting a traversal elsewhere.

With graph_scope_with_ceilings / engine_with_ceilings (a session's SessionPresets::with_ceilings(true)) the preset resource ceilings become caps: a query's value at or below the preset asks nothing, a larger one (or no limit) is refused with OptionAboveCeiling whatever the authorizer allows (Resource Limits).

ExecutionPolicy is the complementary control on the storage: it fixes the value of an option (locked keys, defaults) for every entry, Rust included. Both apply; the authorization check runs first.

File access and the file root

An authorizer decides each file request; Authorizer::resolve_file(path) then maps the path to the file actually accessed (the default returns it unchanged). AccessPolicy::with_file_root(dir) confines every file access to dir:

  • a relative path is resolved under dir (g.export_graphml("out.graphml") writes dir/out.graphml);
  • a path that leaves dir is denied: .. past the root, an absolute path elsewhere, a symbolic link inside the root that points out of it;
  • Rhai's import "helpers" loads dir/helpers.rhai the same way;
  • the root must exist; on wasm32 (no file system) every rooted access is denied, never a panic.

The root does not allow file access by itself: the policy must also allow the action on ResourceKind::File. A host that reads files on behalf of a script calls policy.resolve_file(path) itself.

Graphs the script builds itself

A graph the script built itself is private to it: GraphSource::empty(), GraphSource::tinkerpop_modern(), GraphSource::file(path), schema.to_graph(), the scratch sources __ and _g, and the results of subgraph()/cap() and to_graph(). Changing it is not a change of the host graph, so a request that writes data or the schema of it (Create/Update/Delete on Data, Schema or Definition, AccessRequest::writes_graph) is allowed without asking the authorizer:

let sg = g.E().hasLabel("knows").subgraph("sg").cap("sg").next();
sg.addV("note").property("text", "mine").next();   // allowed with AccessPolicy::read_only()

Reading a private graph still asks for Read, and its file and option requests are asked as usual. Naming the host graph as the explicit target of a subgraph (GraphSource::tinkerpop_modern().withSideEffect("sg", g).E().subgraph("sg")) writes into the host graph: it asks for Create on Data (operation with_side_effect) and gets no relaxation. Such a target must be a TraversalGraph: a host graph of another storage is refused with GraphError::Unsupported (Set Side Effects).

A whole script as one unit

eval_value_atomic(graph, script, params, &limits, authorizer) (Transactions) checks every traversal the same way. While it runs, the script works on a private copy of the graph's lock, so it must not return a closure or function pointer (also inside an array or a map): a closure that captured g would point at an empty graph once the script ends. Such a script fails with ScriptError::ReturnedClosure and everything it changed is rolled back; return data or a traversal instead.

Later

Element- and label-level read security (a Filtered<S, Policy> storage decorator) and a ReadOnly<S> decorator are additive follow-ups. g.gql() uses the same authorizer: a GQL query is lowered into ordinary steps before the check, so it is allowed or denied like its Gremlin equivalent. Its writes (INSERT) ask Create like addV() / addE(), but nothing for the new element's properties, where addV(..).property(..) also asks Update (Writing with GQL); SET and REMOVE ask Update like property() and add_label(), DELETE asks Delete like drop(); a read-only policy refuses them before anything runs.

Resource Limits

A script is untrusted input as soon as a front end faces a user. loop {}, a string that doubles forever, a huge array or unbounded recursion would hang or exhaust the process. Graphersal bounds all of them with two kinds of limit, both reported as one error, TraverserError::ResourceLimitExceeded { limit, max, observed }:

KindLimitDefaultBounds
Script (ScriptLimits)script.max_operations10 000 000Rhai operations of one script (loop {})
script.max_string_size16 MiBthe longest string a script builds
script.max_array_size100 000the largest array a script builds
script.max_map_size100 000the largest object map a script builds
script.max_call_levels32nested script function calls (recursion)
script.max_value_depth128nesting of arrays/maps in a value the script hands to the engine
Traversal (g.with())traversal.max_traversers10 000 000traversers one step may leave alive
traversal.max_value_depth128nesting of arrays/maps/paths in a value the traversal builds or writes
traversal.max_materialized_bytes1 GiB (256 MiB on wasm32)the memory one execution holds at once (live bytes: its buffers and values; freed memory is given back)
traversal.max_string_bytes16 MiBthe longest string a step builds (replace(), concat(), format(), ...)
evaluationTimeoutnonewall-clock budget, see Query Limits
repeat.max_loops10 000iterations of a repeat() without times(), also of an unbounded GQL quantifier ({m,}, *, +, Cypher [*]) on an edge or a path pattern
bulk.max_expansion10 000 000values one bulk expansion may materialize
Process (exec::set_memory_limit)memory.limiton: cgroup limit minus headroom, else 80 % of RAM (3.5 GiB on wasm32)memory in use by the whole process (live heap, or the estimate) during a traversal, an import into a live graph, an applied change set, at every outermost commit, and before every allocation proportional to data (loads, store opens, recovery, checkpoints, backup verifies; see what the ceiling covers); NOT a g.with() option, see the process memory ceiling

A 0 for any of the four script counters means unlimited; the call depth and the value depth are never unlimited because they protect the native stack of the thread (0 reads as the default for them, and ScriptLimits::unlimited() keeps both defaults).

A graph with a journal (a Store, or a journal attached by hand) writes a large unit in parts and has no practical commit size limit (the size of one commit); the process memory ceiling bounds it.

Script limits

graphersal::script::engine() and the eval_* functions use the SAFE defaults above. To change them, build the engine yourself (it also takes the script's authorizer):

use std::sync::Arc;
use graphersal::auth::{AccessPolicy, AllowAll};
use graphersal::script::{engine_with_limits, ScriptLimits};

let limits = ScriptLimits::default().with_max_operations(50_000_000);
let engine = engine_with_limits(&limits, Arc::new(AccessPolicy::read_only()));
// or, for a trusted local front end only:
let engine = engine_with_limits(&ScriptLimits::unlimited(), Arc::new(AllowAll));

eval_value_with_limits(graph, script, params, &limits, authorizer) does the same for a one-shot evaluation. Raising a traversal limit with the query's own g.with(..) is an Update on Resource::Option (Permissions). A host that drives its own engine turns a Rhai limit error into the structured error with resource_limit_from_rhai(&err, &limits); the eval_* functions do this themselves and return the formatted diagnostic.

The defaults were sized so every example of this book, every doctest and the TinkerPop scenarios run unchanged. The array and map caps are deliberately modest: Rhai re-measures an array on each method call that touches it, so a loop pushing items is quadratic and a large cap is also a CPU budget (measured: a loop filling a one-million-item cap ran about half an hour in a debug build). Assigning to a map by index (m[k] = v) is not size-checked by Rhai at all; only the operation limit bounds it.

Traversal limits

traversal.max_traversers is an ordinary g.with() option, checked once per step boundary (a counter comparison, no per-item work). A single step can overshoot the cap by one expansion, since the check runs when the step has produced its output. A cross product (a v() in the middle of a traversal, as in g.v().v() or the GQL MATCH (a), (b)) is checked before it is built: its size is known up front, so a product over the cap fails at once instead of allocating it first.

A count that comes from the query (a bulk, a row count, the size of a product) never becomes an unchecked up-front reservation. Where the engine reserves an exact size it asks the allocator fallibly: when the system cannot provide that block (the limit raised to "unlimited" and a product of trillions of rows), the run fails with ResourceLimitExceeded of memory.allocation and is rolled back instead of the process aborting. memory.allocation is not an option: narrow the query, or bound the run with the process memory ceiling.

g.with("traversal.max_traversers", 50000000).v().out().out().count()

A host sets a default and locks it with an ExecutionPolicy, exactly like evaluationTimeout:

let policy = ExecutionPolicy::permissive()
    .with_default("traversal.max_traversers", 1_000_000)
    .with_locked("traversal.max_traversers");

Every traversal limit is an administrative option: a script's own g.with(..) of it asks the host's authorizer for Update on Option(key), while a host's preset (graph_scope_with_options) or policy default asks nothing. The presets of graph_scope_with_options reach every traversal source of the session: g, _g and __ (also a traversal started from __, such as __.inject(1).repeat(..)). Build the engine with engine_with_options(&limits, authorizer, &options) and the same options, so the sources a script creates itself (GraphSource::empty(), GraphSource::tinkerpop_modern(), schema.to_graph(), ...) get them too; otherwise a script could escape a preset evaluationTimeout by building its own source.

Presets as ceilings

A preset of graph_scope_with_options is a default: the query's own g.with(..) replaces it (if the authorizer allows Update on the option), raising it as well as lowering it. Denying that Update keeps the preset, but then a query cannot tighten it either. A host that wants its limits to be ceilings builds the scope with graph_scope_with_ceilings and the engine with engine_with_ceilings (same arguments; a graphersal-session host sets SessionPresets::with_ceilings(true)). Then, for every preset limit (evaluationTimeout, repeat.max_loops, bulk.max_expansion, traversal.max_traversers, traversal.max_value_depth, traversal.max_materialized_bytes, traversal.max_string_bytes):

  • a value at or below the preset runs, without asking the authorizer (tightening a limit is not an administrative change);
  • a larger value, or no limit at all (evaluationTimeout 0), fails before anything runs with OptionAboveCeiling ("Option 'evaluationTimeout' is capped at 30000 by the host; the query asked for 0 (no limit), and a query may only lower this limit"), whatever the authorizer allows. A raise is refused, never clamped, so a query never runs under a limit other than the one it asked for without being told.

The rule covers every source the script reaches (g, _g, __, the sources it creates) and the bodies of the saved queries it calls. A limit the host does not preset is no ceiling (the engine default is not one): preset every limit a query must not raise. The other preset options (optimizer.*, path.analysis, bulk.merge, display options) behave as without ceilings. An ExecutionPolicy lock still refuses every value, lower ones included. The Rhai limits (ScriptLimits) and a session's script budget (script_timeout_ms) belong to the engine, so no query can change them in either mode. The CLI dev server does not use ceilings.

A gql() query is bounded by the same options. An unbounded quantified edge (-[:knows]->{1,}, *, +, Cypher [*]) or quantified path pattern (((x)-[:knows]->(y)-[:created]->(z))+) has no limit of its own: trail matching ends it on a finite graph, and repeat.max_loops (counting iterations of the whole body) and traversal.max_traversers turn a walk that grows too far into an error, never into a shortened result. The help of that error names the quantified edge or path pattern, suggests an upper bound and shows g.with(..).gql(..) with a raised limit (GQL Semantics):

g.with("repeat.max_loops", 1).gql("MATCH (a {name: 'marko'})-[:knows|created]->*(b) RETURN b.name AS b")   // error: repeat() exceeded the loop limit of 1 iterations
g.with("repeat.max_loops", 5).gql("MATCH (a {name: 'marko'})-[:knows|created]->*(b) RETURN count(*) AS n").to_list()   // #{"n": 6}
g.with("repeat.max_loops", 1).gql("MATCH (a {name: 'marko'}) ((x:person)-[:knows]->(m)-[:created]->(y))+ (b) RETURN b.name AS b")   // error: repeat() exceeded the loop limit of 1 iterations

The same holds for a quantified edge or path pattern inside a subquery (EXISTS, COUNT { }, COLLECT { }, a pattern comprehension, a CALL body), whose help names it. The list a pattern comprehension ([(p)-->(f) | f.name]) collects expands the bulk of its matches under bulk.max_expansion and is checked against traversal.max_materialized_bytes and the memory budget before it is built, like collect_list() (GQL Errors). Besides the options, gql() bounds the size of the query itself with fixed limits (no option changes them), each a 54001 error before the run (GQL Errors):

LimitBounds
128 levelsnesting of parentheses, brackets and subqueries; an expression at most 512 high
64 edge patternsper MATCH clause, over all its comma-separated paths (also per clause inside a subquery); an edge in the body of a quantified path pattern counts once, however often the body repeats
64 subqueries (MAX_SUBQUERIES)EXISTS, pattern predicates, pattern comprehensions, COUNT { } and COLLECT { } written in one query, nested ones included (not CALL bodies)
16 body levels (MAX_BODY_DEPTH)CALL bodies and whole-query subquery bodies (EXISTS / COUNT / COLLECT with clauses other than MATCH) nested in each other; it keeps the deepest query within a 2 MiB thread stack (the wasm32 worker's 1 MiB)
1024 subquery bodies (MAX_LOWERED_SUBQUERIES)bodies the query runs once its LET / WITH variables are substituted: a variable holding a subquery counts once for every place that reads it

Memory: materialized bytes and expansions

Equal traversers are merged into one record with a multiplicity (bulk), so a query like g.v().repeat(__.both()).times(17) stays cheap while it only counts. A step that needs every value as its own item (fold(), aggregate(), store(), group() value lists, a terminal list) expands the bulk, and that is where memory is spent. Two limits bound it:

  • traversal.max_materialized_bytes (default 1 GiB natively, 256 MiB on wasm32): the memory ONE execution holds AT ONCE (changed in 0.5.0; before, it bounded the size of one value or buffer). It counts live bytes: memory a step frees is given back, so only what is held at the same time counts. A query that builds a list, drops it and builds the next (fold().unfold().fold().unfold()) holds one list at a time; a query that keeps two lists (two labelled folds, a project() of two folds) holds both. What is measured:

    • tracked (a tracking allocator is installed, as in the graphersal command line, the playground and the Python binding): the live heap of the query's thread minus what it held when the query started. What the query adds to the GRAPH (a write) does not count here: in a query that writes it is estimated at every step boundary (the elements added, at the graph's average element size) and subtracted; the process ceiling below bounds the graph's growth;
    • estimated (otherwise): the engine's count of what the query holds: the stream between two steps (by capacity, 80 bytes per traverser), the values it sizes anyway (bulk expansions and bucket copies, fold() lists, GQL lists and function results, product(), step-built strings), the repeat() frontier with its values and sacks, and the values the path records keep (repeat(__.path()) doubles its value on every iteration and keeps each earlier one). A value is charged when a step builds it and released when a later step replaces the stream (a map, flat-map or barrier step; filters, labels and side effects pass it on) or when the child traversal that built it returns; side-effect buckets are held to the end of the query. The figures come from what the engine computes anyway, never from a walk over every element, so the estimate is coarse: a value built inside a child traversal (project().by(__.fold())) counts while the child runs, not afterwards, and most element properties read on the way are not counted.

    It is checked at every step boundary, before a bulk expansion, a bucket push of copies or a sized value is built, and for every traverser of a new repeat() frontier WHILE the frontier is built, so a loop that multiplies its traversers stops within the iteration that crosses the limit. The error's observed figure (reached N) is what the query held plus what the failing check was about to allocate. Profiles report the PEAK of the measure (TraversalMetrics::memory()); the peak is sampled at these checks, not exact, so a short spike between two checks can be missed.

  • bulk.max_expansion (default 10 000 000 values): the number of values one expansion may produce, a second line behind the byte budget (BulkExpansionLimit).

g.with("traversal.max_materialized_bytes", 2147483648).v().repeat(__.both()).times(8).fold()

Prefer a step that works on the multiplicity directly (count(), groupCount(), dedup(), limit(n)) over raising either limit.

The process memory ceiling

There are exactly two memory limits, never mixed:

  • the process memory ceiling memory.limit: what the whole PROCESS may hold. One setting of the process, set by the host, on by default;
  • the per-query limit traversal.max_materialized_bytes (above): the memory one query holds at once (live bytes, the query's own working memory without what it adds to the graph), an ordinary g.with() option. Profiles report its peak against this limit, never against the process ceiling.

The ceiling exists so that a query (or an import, or a write) which would exhaust the memory of the process fails with ResourceLimitExceeded and is rolled back, like every failing traversal, instead of the operating system killing the process (a Kubernetes or cgroup OOM kill).

It is on by default. Unless the host sets it, the ceiling is resolved once, in this order, and the result carries its source (graphersal::exec::memory_limit(), MemoryLimitSource):

SourceCeiling
configuredthe bytes the host set
nonethe host turned it off (MemoryLimit::Unlimited, CLI --memory-limit none)
cgroupthe cgroup memory limit of the process minus the headroom: Graphersal reads /sys/fs/cgroup/memory.max (cgroup v2) or, failing that, /sys/fs/cgroup/memory/memory.limit_in_bytes (cgroup v1), once per process; max or the v1 "unlimited" value is no cgroup limit. The headroom (memory.headroom) stays free for the stack, the code, allocator overhead and what the engine does not count: by default a tenth of the limit, at least 64 MiB and at most half of it (a 512 MiB container gets 448 MiB)
physical80 % of the machine's physical memory (Linux /proc/meminfo, macOS hw.memsize, Windows GlobalMemoryStatusEx), read once per process
wasm3.5 GiB on wasm32 (a 32-bit linear memory ends at 4 GiB; a browser may grant less)
unknowna platform where none of the above can be read: no ceiling

A host sets it once, for the whole process (every graph, every session of a server):

use graphersal::exec::{self, MemoryLimit, MemoryLimitSource};

exec::set_memory_limit(MemoryLimit::Bytes(4 << 30)).unwrap(); // 4 GiB
let limit = exec::memory_limit().unwrap();
assert_eq!(limit.bytes(), Some(4 << 30));
assert_eq!(limit.source(), MemoryLimitSource::Configured);

exec::set_memory_limit("auto".parse().unwrap()).unwrap();    // back to the default
exec::set_memory_headroom(Some(256 << 20)).unwrap();          // for a cgroup limit

MemoryLimit reads and prints the text forms the front ends accept: a positive number of bytes, auto or none. It is not an execution option: a query's g.with("memory.limit", ..) (or memory.headroom), an ExecutionPolicy default or a session preset of these keys fails with InvalidOption, whose help() names the process setting (changed in 0.5.0; before, the budget was an opt-in option per execution). A scheduled job's memory_limit does not touch the ceiling: it is the per-query limit traversal.max_materialized_bytes of every traversal the job's run executes, with the same measure (live bytes held at once; the smaller of the two values; see Scheduled jobs).

What is compared with the ceiling (the error's help() says which one applied):

  • tracked: with a tracking allocator (the alloc-tracking feature and graphersal::alloc_tracking::TrackingAllocator installed as the binary's global allocator, as the graphersal command line, the playground and the Python binding do; in Python it counts the extension's Rust heap only, not Python objects), the process's exact live heap bytes, plus what a check is about to allocate;
  • estimated: otherwise (a library host with the system allocator), the engine's estimate: the graph's footprint (g.memory_usage()) when the traversal starts, plus what the traversal holds by the same count as the per-query limit (its buffers, the values it sizes, the repeat() frontier, the path records), the elements the traversal added (at the graph's average element size) and what a check is about to allocate. Property values written to existing elements are not counted, and the count of what a query holds is coarse, so the real process can hold more. Because the ceiling is on by default, the start of a run never walks the graph while the graph is far from the ceiling: it takes the footprint of the last walk, adjusted by the elements added or removed since. The graph is walked (time proportional to its size, cached by its commit position) only on the first run, once its element count has doubled or halved since the last walk, and on every run after a committed change while the figure is at least half of the ceiling. All of these happen only between units: inside a script, a saved-query call or a transaction that has already changed data, the graph is never walked; the figure is the last walk extrapolated by the elements added or removed in it, so its traversals do not walk the graph one after the other. This is an edge case of the estimate: after large changes in that unit (many rewritten property values, elements much larger or smaller than the graph's average) the figure can be off until the unit ends. With a tracking allocator no traversal walks the graph and the figures are exact. g.memory_usage() walks the graph too and keeps its figure for the next runs: call it after rewriting many property values to refresh the estimate. For large graphs that change often near the ceiling, prefer the tracking allocator.

The ceiling is cooperative (an allocator cannot fail softly): it is checked at every step boundary and at the places that check traversal.max_materialized_bytes, before a bulk expansion allocates, before a bucket push of copies and on every repeat() iteration. A single step can overshoot it by what it builds before the next check. Writes are checked the same way: a traversal that grows the graph past the ceiling fails and leaves nothing behind. When the graph alone is over the ceiling, every traversal fails at its first step; a trusted host raises the ceiling for a moment, drops what it does not need (g.v().has_label("tmp").drop()) and lowers it again.

Units that are not traversals are checked against the same ceiling:

  • a GraphML or GraphSON import into a live graph (import_graphml*, import_graphson*, GraphMLImport::import_reader, GraphSONImport::import_reader) and apply_change_set every 4096 elements (imported vertices and edges, applied mutations) and at their end;
  • every outermost unit at its commit: a transaction(|g| ..) closure, an applied change set, an import, a traversal (whose steps already checked their own).

Over the ceiling the whole unit is rolled back and fails with GraphError::ResourceLimitExceeded (wrapped in IOError::Graph for an import), whose message names the operation: Resource limit 'memory.limit' exceeded by the GraphML import (limit N, reached M); the help() gives the same host advice as a traversal's. The measure is the one above: the live heap with a tracking allocator, else the footprint when the unit started plus the elements it added. Only a unit that grew that measure is stopped, so a unit that only removes or rewrites data commits even on a graph that is already over the ceiling. With the ceiling turned off (none) nothing is paid: no footprint, no check.

What the ceiling covers

Every allocation whose size is proportional to data checks the ceiling, BEFORE it allocates when the size is known up front, otherwise every 4096 elements and at the end. Nothing is half-written: a refused open changes nothing on disk, a refused load drops the half-built graph, a refused checkpoint leaves the store as it was.

Operation (the error's operation)Check
traversalsstep boundaries, bulk expansions, materializing steps (above)
product()its estimated size against traversal.max_materialized_bytes and the ceiling before the pairs are built; the evaluationTimeout is checked while they are
imports, apply_change_set, commitsevery 4096 elements and at the end, rolled back (above)
snapshot load (read_snapshot*, Python Graph.load)the snapshot header's estimate of the graph (plus the live heap when tracked) BEFORE anything is read: PersistError::MemoryBudget; while the graph is built every 4096 elements, each segment and its decoded chunks before they are read
store open (Store::open, CLI --graph <store>, dev server, Python Store.open)the same, plus the replay of the WAL after the snapshot: a graph that does not fit refuses the open, naming the minimum to raise to. Never maintenance mode, never read-only instead
recovery (Recovery, past states, read-only views)every WAL record before it is read, the replay every 4096 mutations
commit encodingthe encoded body of a commit while the journal builds it (each time it doubles, from 1 MiB on): a unit that does not fit is rolled back
reading a commit in partsthe assembled body of a commit written in parts before each growth (recovery, checkpoints, backups, verify, salvage)
store reada whole store file or range read into memory (an io::Error of kind OutOfMemory inside PersistError::Io)
checkpoint, snapshot writethe encoder's id index (24 bytes per element) and one chunk before they are allocated; a merged checkpoint's chunks and its delta graph
maintenance copythe copy of a salvaged graph (twice the graph)
backup verifyevery metadata entry of a ZIP backup read back whole
GraphSON load, GraphML load (GraphSource::from_graphson*, from_graphml*, GraphSONImport::load)every 4096 elements and at the end; without a tracking allocator the size is estimated by the bytes of text read so far

Two errors tell when a persisted graph was refused: PersistError::MemoryBudget (the estimate did not fit: refused before reading; its setting is memory.limit, or ReadOptions::with_memory_limit when that stricter per-read bound was lower) and PersistError::Graph(GraphError::ResourceLimitExceeded { .. }) (the estimate passed, but the data grew past the ceiling while it was read). Both name the operation and the setting to raise; ResourceLimitExceeded carries needed (the bytes a check before an allocation asked for) and observed (what was in use plus that: the smallest ceiling that would have passed). The manifest's estimate is the graph's footprint when it was written, so a graph just at the ceiling can be refused (or pass and then stop while loading).

A host that allocates data-proportional memory itself (a model it loads, a buffer it fills) asks first:

use graphersal::exec;

exec::check_memory_for("model load", 64 << 20).unwrap(); // 64 MiB more: fits?
let room = exec::memory_room().unwrap();                  // ceiling, source, live heap, room left
println!("{:?} bytes left", room.available());

check_memory_for compares the live heap plus the bytes with a tracking allocator, else only the bytes (the rest of the process is not seen).

Embedding models of a store (book page Embedding Models in a Store) load under the ceiling too: before a load the blob's length times 1.6 (potion-multilingual-128M takes about 1.01 times its blob loaded and 1.14 times at the load's peak, plus a reserve; the definition's stored load_bytes is not read) is checked against what is in use (the live heap with a tracking allocator, else the models already loaded), so nothing is read when it does not fit (operation "model load"). A model the schema NEEDS is loaded when the store opens: one that does not fit refuses the open with StoreFailure::ModelDoesNotFit, whose message names the smallest ceiling that fits. Other models are loaded at the first query that embeds with them; a refusal there fails that query. Loaded models count in the estimated memory of every run (without a tracking allocator) and in g.memory_usage() as model_bytes.

Seeing how full the process is

Every front end shows the process against its ceiling with the same figures (computed once, in the session layer):

  • Playground: the process memory bar in the Profile panel's Statistics tab and in Optimize -> Memory (The Web Playground): used of the ceiling, its source, the percentage, and the segments structure, properties, compressed, indexes, models, live_graph, store, engine and other (the heap no segment explains). The graph's segments use the figures of g.memory_usage(): structure is structure_bytes, indexes is index_bytes (the id and label indexes) plus property_index_bytes. The others are the process's components of the memory report, read without its walk: models are the embedding_model components (every model loaded in the process, once), live_graph is store_graph (a store's live graph beside a view of a past state), store is store + store_files, engine is the graph's workload_bytes plus every other component (script_engine, session, mcp, ai_chat, a host's own); each is left out at 0.

  • REPL: /memory prints the bar as text before the memory report:

    Memory   1.6 GiB of 3.4 GiB (cgroup)                                        47 %
             [################################....................................]
             structure 150.0 MiB  properties 420.0 MiB  compressed 95.0 MiB
             indexes 90.0 MiB  models 506.0 MiB  other 340.0 MiB
             compression saves 285.0 MiB (plain 380.0 MiB -> 95.0 MiB, -75 %)
    
  • Dev server: GET /api/statistics (and the MCP statistics tool) carries process.memory.usedBytes, usedTracked, limitBytes, limitSource, usedPercent, segments (each {name, bytes}, the component segments with parts: [{name, detail?, bytes}]) and compression; the start banner's memory row ends with process 47 % of 3.4 GiB (cgroup).

Without a tracking allocator (a host that did not install it) the used figure is the sum of the known segments, marked "process total not tracked"; with the ceiling turned off (memory.limit none) there is no percentage. This is the process ceiling only: a query's own peak against the per-query limit traversal.max_materialized_bytes is the PROFILE's query_memory ("Peak memory" in the playground's Profile panel).

Strings built by steps

script.max_string_size bounds the strings a script builds; traversal.max_string_bytes (default 16 MiB, the SAFE script.max_string_size) bounds the strings the engine builds: replace(), concat(), conjoin(), format(), as_string(), to_upper()/to_lower(), substring(), reverse(), the trims and the elements of split(). The steps that can multiply the length of their input (replace() at every match, concat()/conjoin() of many parts) compute the length first and fail before the string is allocated; the others check their result.

g.with("traversal.max_string_bytes", 67108864).v().values("name").replace("a", "aa")

Time inside a step

evaluationTimeout is checked between steps, every 1024 traversers a step consumes or produces, and every 1024 values a step materializes: the copies of a bulk expansion (fold(), a terminal list, aggregate(), group() value lists), the members group() and tree() collect, the sort keys order() computes (and once after the sort) and every repeat() iteration. The timeout is reported at the step that was running (Step #2 'fold()'), not at the next step boundary.

Value depth

Almost everything that reads a value walks it recursively: the conversion to a script value, hashing in dedup(), schema inference, rendering. A value nested thousands of levels deep would overflow the native stack and abort the whole process, so Graphersal bounds the depth where a value enters the engine; no deeper value can exist afterwards, and every reader stays bounded. A scalar has depth 0 and every array, object, map or path around it adds one level: [1] is 1, [[1]] and {"a": [1]} are 2.

  • script.max_value_depth (ScriptLimits::with_max_value_depth, default 128, the recursion limit serde_json applies to JSON input): a value a script hands to the engine (a step argument such as inject(x), property("k", x), has("k", x), a token argument), a host parameter (eval_*_with_params), and the result of a whole-script unit (eval_value_atomic, eval_value_dry_run, materialize_traversals). The conversion stops at the limit; nothing recurses deeper.
  • traversal.max_value_depth (a g.with() option, default 128, administrative, lockable with an ExecutionPolicy like every option): what the engine builds itself. A repeat() whose body wraps its value again on every iteration (repeat(__.fold()), repeat(__.path()), repeat(__.group()), a sack folded into itself) is checked once per traverser per iteration; a property write is checked for the depth it leaves behind, so property(jpath("a.b.c"), v) counts two levels for the path plus the depth of v.
  • jpath: a path has at most 256 segments (a parse error beyond), so even a direct GraphStorage::set_vertex_property_path call cannot build an unbounded value.
  • Imports: GraphML values are scalars (containers cannot be imported), and schema and change-set JSON is parsed by serde_json, whose own recursion limit (128) applies. A GraphSON import skips a property value nested deeper than 128 levels (reported) and bounds the JSON nesting of a line, so no file can exhaust the stack.
  • GraphSON input size: one line (line form) or the whole document (wrapped form) is read only up to GraphSONImport::max_text_bytes (512 MiB natively, 64 MiB on wasm32), checked before the text is held in memory (IOError::InputTooLarge, whose help() names with_max_text_bytes(n)).
g.with("traversal.max_value_depth", 256).inject(1).repeat(__.fold()).times(200).count()

Raise the limits only moderately: a few hundred levels are fine on every thread stack, thousands are not. The display of a script value the script never handed to the engine (a deeply nested Rhai array returned as the result) is cut with […] after 128 levels; the data itself is not changed.

Front ends

  • graphersal (CLI): a trusted local tool, so no script limits by default. --safe-limits applies the SAFE defaults; --max-operations, --max-string-size, --max-array-size, --max-map-size and --max-traversers set one limit (0 is unlimited; --max-string-size also sets traversal.max_string_bytes, which follows the script's string limit and is unlimited by default). --max-value-depth <n> sets script.max_value_depth and traversal.max_value_depth (0 is the default, 128). --max-materialized-bytes <n> sets the default of the per-query memory limit traversal.max_materialized_bytes (0 is unlimited; without it the library default, 1 GiB, applies); a query's own g.with(..) overrides it. --memory-limit <bytes|auto|none> (and --memory-headroom <bytes>) sets the process memory ceiling, measured on the live heap (the CLI installs the tracking allocator); no flag keeps the default (auto), none or 0 turns it off. With --server it covers every session of the server. In the REPL, /set max-operations <n> (and the other script limits, max-value-depth included) and /set safe-limits. The presets reach every source a script creates. The session runs on a thread with a 64 MiB stack.
  • Web playground: no script limits and no default timeout, like the CLI (it runs in your own browser); the process memory ceiling is the wasm32 default, 3.5 GiB of tracked heap. Its Stop button restarts the engine to end a runaway query.
  • Python: SAFE defaults; graph.set_limits(max_operations=..., max_value_depth=..., max_materialized_bytes=..., unlimited=True, ...); max_materialized_bytes is the default of the per-query memory limit traversal.max_materialized_bytes for every traversal of that graph's scripts (a query's own g.with(..) overrides it). The process memory ceiling is not a keyword of a graph: it is set with graphersal.set_memory_limit(bytes | "auto" | "none", headroom=...) and read with graphersal.memory_limit(), one value for the whole process; Graph.load also refuses a snapshot whose size estimate exceeds it. It is measured on the live Rust heap of the extension (the binding installs the tracking allocator); Python objects are not counted, so leave room for the Python side of the process. Scripts run on a worker thread with a 64 MiB stack (one per calling Python thread).

The large stack is a mitigation for the scripting engine itself: Rhai copies a nested map value recursively (x = #{a: x} in a loop), and a few thousand levels overflowed the 8 MiB stack of a debug build before any Graphersal code ran, which no depth limit of Graphersal can catch. A host that embeds the engine on a thread of its own should give that thread a large stack too (std::thread::Builder::stack_size; not available on wasm32).

wasm32

The script limits are counters Rhai checks itself, so they work on wasm32-unknown-unknown. evaluationTimeout works there too: the engine reads the clock through web_time::Instant (performance.now() in the browser). The operation counter stays the portable, deterministic bound; the playground additionally has a Stop button that restarts the engine.

Mutating traversals

A limit abort in the middle of a mutating traversal rolls back every write the traversal made before the abort: an aborted write traversal is all-or-nothing (see Transactions). A Rhai limit that stops a script (operations, call depth, string or collection size) stops it in the script code around the traversals; the traversals that already finished stay applied (the unit is one traversal, not the script), unless the host runs the script as one unit with eval_value_atomic (Transactions), where a limit abort rolls back the whole script.

The size of one commit (journal)

A journal (the write-ahead log of a Store, or a persist::Journal) writes every committed unit as one commit. Its body holds every change of the unit with its before and after values, so dropping an element writes its full properties too: dropping 300 000 vertices with long texts and creating them again in the same unit writes both. A body of more than 64 MiB before compression is written in parts of 64 MiB (format spec 9.3.1), so since 0.5.0 a commit has no practical size limit (up to 2^20 parts, 64 TiB; before 0.5.0 one commit was at most 1 GiB). What bounds it is memory: the unit's changes and its encoded body are held while it commits (operation commit encoding of the process memory ceiling), and a recovery holds one commit's body while it replays it. Plan for several times the commit's size: while a unit commits, the data it added to the graph, its undo log (every before image) and the whole encoded body are in memory at once. A single commit of a little over 1 GiB peaked between 4.4 and 5.7 GB of process memory in our measurements; more, smaller units (below) keep the peak at the size of one of them.

A commit beyond 2^20 parts, or one whose encoding does not fit under the ceiling, is refused by the journal's commit hook: the whole unit is rolled back, nothing is written, and the journal keeps working. The error is CommitTooLarge (or ResourceLimitExceeded) inside

The commit was rejected by the commit hook 'journal': ...

and its help says how to split the work. The limit applies per unit, so the fix is more, smaller units:

  • Web playground and dev server: a whole script is one unit. Drop the old data in a run of its own (g.v().drop().iterate()) and create the new data over several runs (a part of the input per run).
  • CLI, Python, Rust: each traversal is already its own unit; only a single huge traversal (one drop() of everything, one load of millions of elements) can reach the limit. Split it into batches. In Rust, transaction(..) blocks and whole-script units (script::eval_value_atomic) commit as one, so keep each below the limit.

A graph without a journal (in memory only) has no such limit; the process memory ceiling bounds it instead.

Query Limits

See the Execution Options Reference for the full table of every g.with() key, including how a host embedding this engine can lock evaluationTimeout and repeat.max_loops so a query cannot override them.

Nothing bounds the running time of a traversal by default. A Cartesian fan-out such as v().out().out().out() on a large graph can hold the graph lock and a CPU for as long as it takes. When queries come from users, as in the web playground, set a budget. Only repeat() loops have a default bound, repeat.max_loops.

evaluationTimeout

evaluationTimeout is the TinkerPop per-request option of the same name (Tokens.ARGS_EVAL_TIMEOUT). It sets the wall-clock budget of one traversal execution, in milliseconds:

let count = graph
    .traversal()
    .with("evaluationTimeout", 5000)
    .v(None)
    .out(None)
    .out(None)
    .count()
    .next()?;

In the script DSL:

g.with("evaluationTimeout", 5000).V().out().out().count().next()
  • The value is a non-negative integer number of milliseconds. 0 means no timeout, which is also the default when the key is absent.
  • The budget covers the whole execution, nested traversals included: a where(), not(), union() or by() child traversal spends the same budget as its parent.
  • .profile() executes the traversal, so it honours the budget too. A profile that times out returns the error; no partial profile is produced.
  • An invalid value (negative, fractional, or not a number) is reported as InvalidOption when the traversal is executed, because with() itself cannot fail.
  • Setting the key again replaces the previous value.

When the budget runs out, the traversal stops with a Timeout error, for example:

Error: Step #3 'out()' execution failed
  at #3: v().out().out().out().count()
                   ^^^^^
  plan:  v().out().lazy_barrier().out().lazy_barrier().out().count()
                                  ^^^^^
Caused by: Traversal exceeded evaluationTimeout of 50 ms (ran 50 ms)
Help: The traversal ran longer than its evaluationTimeout budget of 50 ms. ...

The diagnostic names the step that was running, in the query as written and, when the optimizer changed it, in the executed plan (plan:). Its help rewrites the failing query: narrow the start set with has_label()/has_id(), cap the stream with limit(), or raise the budget.

repeat.max_loops

A repeat() loop on a graph with cycles, such as g.V().repeat(__.both()), never runs out of traversers. Graphersal stops every repeat() that is not bounded by times() after a number of iterations, instead of letting it run until the timeout or forever:

g.with("repeat.max_loops", 100).V("1").repeat(__.out()).until(__.has("name", "ripple"))
  • The default is 10 000 iterations. The value must be an integer from 1 to 4 294 967 295; anything else is reported as InvalidOption when the traversal is executed.
  • A loop with times(n) is never limited: it already ends after n iterations, so repeat(__.out()).times(50000) runs all of them.
  • The limit applies to each repeat() separately, nested loops included.
  • When a loop exceeds it, the traversal fails with RepeatLimitExceeded. The help suggests times(), until(), simple_path() in the body, and a raised limit, written on the failing loop.

The limit is deterministic: the same query on the same graph always fails after the same iteration. evaluationTimeout bounds wall-clock time instead, including the time a bounded loop spends. The two complement each other. See Recursive Traversals.

Granularity

The timeout is cooperative. The engine checks the clock:

  • between steps,
  • every 1024 traversers a step consumes or produces, and
  • every 1024 values a step materializes (the copies of a bulk expansion in fold(), a terminal list, aggregate(), group() value lists; the members group() and tree() collect; the sort keys of order(), and once after its sort), so the timeout is reported at the step that spent the time.

A single storage call, such as one full index scan, is not interrupted, so a query can overrun its budget by the time one such call takes; so can one sort, or one step that copies a single large value (a repeat(__.path()) iteration copies the whole growing path once).

Mutating traversals

A mutating step (property(), add_v(), add_e(), drop(), ...) is never interrupted: the budget is checked only at its step boundaries.

A traversal that times out is rolled back as a whole, also the mutations of the steps before the timed-out one: a failing traversal leaves nothing behind (see Transactions).

Script expression depth

A script is rejected with Expression exceeds maximum complexity when its expressions nest deeper than 128 levels (64 inside a script-defined function). Every call of a method chain counts as one level, so a chain of about 120 steps or 30 nested union(..) levels is accepted; a 150-step chain is not.

The limit is the same in debug and release builds. Rhai's own default is 64 in release but only 32 in debug builds, which made the same query run in a release graphersal and fail in cargo test. It is not higher because the parser recurses: on a 2 MiB thread stack (the default of spawned threads) a debug build overflowed the stack at 160/80. Split a very long query into several statements with a variable (let people = g.V().hasLabel("person")).

Script hosts

  • graphersal --timeout <ms> sets a default evaluationTimeout for every traversal of the session. Without the flag there is no timeout. A query overrides the default with its own g.with("evaluationTimeout", ms), where 0 disables it.
  • The CLI also stops a script whose own Rhai code (a loop {}) runs past the same budget, because such code is not a traversal and would otherwise bypass the timeout.
  • The web playground sets no default timeout: it runs in your own browser, and its Stop button ends any query or script loop by restarting the engine (the graph comes back as last loaded or saved).
  • An embedder builds the same defaults with graphersal::script::graph_scope_with_options(graph, &[("evaluationTimeout", 5000.into())], authorizer). A preset option is the host's; a script that changes evaluationTimeout itself asks the host's authorizer for Update on Option("evaluationTimeout") (Permissions).

Execution Options Reference

This page is the single, canonical list of every g.with(key, value) option Graphersal recognises. Query authors: this is where to find every key that exists. Hosts embedding this engine (a CLI, a web playground, a multi-tenant backend): this is where to find every key an ExecutionPolicy can lock down.

KeyTypeEngine defaultHost-lockableWhat it does
evaluationTimeoutnon-negative integer milliseconds0 (no timeout)yesWall-clock budget of the whole execution, nested traversals included. See Query Limits.
repeat.order"bfs" | "dfs" (case-insensitive)"bfs"yesThe order a repeat() loop walks its frontier in. See Recursive Traversals.
repeat.max_loopsinteger, 1 to 4 294 967 29510 000yesIteration limit of a repeat() without times(), so an unbounded loop on a cyclic graph fails instead of running forever. See Query Limits and Recursive Traversals.
optimizer.disabledarray of rule-name strings[] (every rule on by default runs)yesNames of on-by-default optimizer rules to leave out of this execution's plan, or ["all"] to disable every rule at once. See Query Optimizer.
optimizer.enabledarray of rule-name strings[]yesNames of off-by-default optimizer rules to force into this execution's plan (a no-op today; no shipped rule defaults to off). See Query Optimizer.
path.analysisbooleantrueyestrue records only the path positions a step actually reads; false records every position unconditionally. See Path Requirement Analysis.
bulk.onebooleanfalseyestrue is g.withBulk(false) (TinkerPop ONE_BULK): a merge at an explicit barrier() keeps bulk 1, so duplicates are emitted once; a traverser with a sack and no merge operator never merges; the automatic merge points (repeat() frontier, lazy_barrier()) pass through. withBulk(true) sets it back to false. Any other value fails with InvalidOption. See Sack and Operators.
bulk.mergebooleantrueyestrue lets merge points (barrier(), the repeat() frontier, lazy_barrier()) merge equal traversers into one with a bulk; false turns them into pass-throughs. Never changes the result multiset. Merging is also off when the plan mutates. See Bulk and Barriers.
bulk.max_expansioninteger, at least 110 000 000yesThe most values a step (fold(), aggregate(), store(), group() value lists, a terminal list) may produce when it expands merged traversers into single items; more fails with BulkExpansionLimit. A second line behind traversal.max_materialized_bytes. See Bulk and Barriers.
traversal.max_materialized_bytesinteger, at least 11 073 741 824 (1 GiB; 268 435 456 on wasm32)yesThe memory, in bytes, one execution holds at once (since 0.5.0; before, the size of one value or buffer): live bytes, so memory a step frees is given back. Tracked (tracking allocator): the live heap of the query's thread since it started, without what it adds to the graph; estimated: the engine's count of its step buffers, sized values (bulk expansions, fold() lists, GQL lists), the repeat() frontier and the path records. Checked at every step boundary, before an expansion allocates and per traverser of a new repeat() frontier; profiles report its peak (TraversalMetrics::memory()). A scheduled job's memory_limit caps it. Exceeding it fails with ResourceLimitExceeded. Administrative. See Resource Limits.
traversal.max_string_bytesinteger, at least 116 777 216 (16 MiB)yesThe longest string, in bytes, a step builds: replace(), concat(), conjoin(), format(), as_string(), to_upper()/to_lower(), substring(), reverse(), the trims and the elements of split(). replace(), concat() and conjoin() check before they allocate. Exceeding it fails with ResourceLimitExceeded. Administrative. See Resource Limits.
memory.limit(not an option)Since 0.5.0 the process memory ceiling, ONE setting of the whole process (graphersal::exec::set_memory_limit, CLI --memory-limit, Python graphersal.set_memory_limit), on by default. Setting it here, as an ExecutionPolicy default or a session preset fails with InvalidOption. Limit one query with traversal.max_materialized_bytes. See Resource Limits.
memory.headroom(not an option)Part of the process memory ceiling (graphersal::exec::set_memory_headroom, CLI --memory-headroom); refused here like memory.limit.
traversal.max_traversersinteger, at least 110 000 000yesThe most traversers one step may leave alive (the stream between two steps, which is also what a terminal list materializes). Exceeding it fails with ResourceLimitExceeded. Pass 9223372036854775807 for no limit. See Resource Limits.
random.seedinteger (int64)none (seeded from the operating system's entropy)yesThe seed of the execution's random number generator, which coin(), sample() and order().by(Order.shuffle) draw from (child traversals included, in plan order). The same seed gives the same draws on every run of the same query with the same Graphersal version, also in the browser. Graphersal's counterpart of TinkerPop's SeedStrategy, whose scenarios stay out of scope with withStrategies(); the draws are not those of TinkerPop's Java Random. A non-integer fails with InvalidOption. See sample.
traversal.max_value_depthinteger, at least 1128yesThe deepest nesting of arrays, maps and paths one value may reach inside the engine: checked once per traverser per repeat() iteration (a body that wraps its value again, such as repeat(__.fold())) and on every property write (a jpath(..) path counts one level per segment below the property). Exceeding it fails with ResourceLimitExceeded. Deeply nested values are read recursively, so keep it in the hundreds. See Resource Limits.
render.max_rowspositive integernone (unlimited)noScript DSL only: how many top-level results a displayed result shows. graphersal and the playground set it to 100 for the session. Never affects data terminals. See Displaying Results.
render.max_itemspositive integernone (unlimited)noScript DSL only: how many items of each nested collection a displayed result shows. graphersal and the playground set it to 100. See Displaying Results.
render.spelling"snake" | "camel" (case-insensitive)"snake"yesThe spelling of step names in diagnostics: .profile() step names, error step locations and the help() rewrites of the failing query. "snake" renders has_label("person"), group_count(); "camel" renders the Gremlin spelling hasLabel("person"), groupCount(). Never affects results. graphersal --spelling camel, the REPL /set spelling camel and the playground setting set it for the session. Any other value fails with InvalidOption. See Profiling and execute().

Every key above changes a query's behavior, its safety bound, or its plan — never its result, except evaluationTimeout/repeat.max_loops themselves failing the query when a bound is hit. Setting a key again replaces its previous value; an unrecognised key is silently ignored.

An invalid value for a recognised key (wrong shape, out of range, an unknown rule name) fails with TraverserError::InvalidOption when the traversal is executed — with() itself has no error channel and always returns Self.

Host-Controlled Execution Policy

evaluationTimeout and repeat.max_loops exist specifically to bound a runaway query's resource use. But by themselves, both are just ordinary options: a query is free to set g.with("evaluationTimeout", 999999999).with("repeat.max_loops", 999999999) and defeat them. A host that runs untrusted queries against a shared graph — a public web playground, a multi-tenant backend — needs a way to fix a ceiling on any option above, outside the query's reach.

ExecutionPolicy is that ceiling. It is built once, by the trusted host, and attached to a TraversalGraph at construction time — before the graph is ever wrapped for sharing (Graph/Arc<TraversalGraph>) and handed to code that might run an untrusted query against it:

use graphersal::prelude::*;
use graphersal::exec::ExecutionPolicy;

let policy = ExecutionPolicy::permissive()
    // A query can no longer touch evaluationTimeout at all; every execution gets 2000 ms.
    .with_default("evaluationTimeout", 2000)
    .with_locked("evaluationTimeout")
    // Same for repeat.max_loops: no query-supplied value is ever honored.
    .with_default("repeat.max_loops", 500)
    .with_locked("repeat.max_loops");

let graph = TraversalGraph::tinkerpop_modern().with_execution_policy(policy);
let g = Graph::new(graph);

There is no setter after this point — not &mut self, not one gated behind a write lock. Once a TraversalGraph is constructed, its policy cannot change for the rest of its life; a host that wants different limits for a different session constructs a different graph instance.

Two independent knobs, settable per key:

  • with_default(key, value) — applied when the query's own g.with() doesn't set key. Takes precedence over the engine's own hardcoded default, but the query can still override it unless the key is also locked.
  • with_locked(key) — a query's own g.with(key, ..) attempt fails immediately with TraverserError::LockedOption, regardless of the value it tried to set. The policy's default (or, absent one, the engine's hardcoded default) always applies instead.

ExecutionPolicy::permissive() — no key locked, no default overridden — is the implicit policy of any TraversalGraph built without with_execution_policy(..): every option takes its engine default unless the query sets it.

Every key in the table above is checked against the policy the same, generic way, so a future option automatically participates in locking and defaulting without special-cased code.

Persistence

Graphersal keeps the graph in memory. The persist feature keeps it on disk too: in Graphersal's own binary format, losslessly, with every committed change made durable before the commit returns, so nothing committed is lost on a restart or a crash.

Looking for a command? The Command Cheat Sheet has every one of them, ready to copy.

What to choose

You wantUseAPIPage
save a graph now and load it later (a script, the browser, a download)a packed snapshot: the whole graph in one file or stream (.gsnap)graph.write_snapshot(w), TraversalGraph::read_snapshot(r); DSL g.export_snapshot(path); CLI --graph g.gsnapPacked Snapshots
durability over streams you manage yourself (a socket, an upload, any Write), also in WebAssemblya snapshot plus a journal (write-ahead log) and recoverypersist::Journal, persist::recoverJournal and Recovery
an application that simply keeps its graph ("SQLite for graphs")the Store: one directory (or one file) = one graph; recovery on open, checkpoints, marks, point-in-time views, fork, rollback, backups, verify, repairpersist::Store; CLI graphersal store ..., --graph data/The Store

GraphML and GraphSON stay the exchange formats. The snapshot is the lossless one: every value type (uuid, nested arrays and objects, NaN payloads, property order), multi-label and unlabeled vertices, unlabeled edges, the schema, the catalog of definitions (saved queries), and the graph's position (commit sequence number, commit time, auto-id sequences).

graphersal = { version = "0.8", features = ["persist"] }        # LZ4 chunks, the Store, journals
graphersal = { version = "0.8", features = ["persist-zstd"] }   # also zstd chunks (pure Rust)
graphersal = { version = "0.8", features = ["persist-zip"] }    # also ZIP backups of a Store

Where it runs:

Packed snapshotJournal and recoveryStore
Rust, nativeyesyesdirectory, single file, memory
Rust, WebAssemblyyesyes (no fsync)in memory (MemDir)
CLI--graph g.gsnap, g.export_snapshotgraphersal store ..., --graph data/
Dev server.gsnap download--graph data/ --server, the Store menu
Web playgroundSave as snapshot, load .gsnapevery loaded graph is a store in memory
Pythongraph.save, Graph.loadgraph.start_journal, Graph.recovergraphersal.Store

Concepts

TermMeaning
commitone committed unit of change. Every traversal is one (see Transactions); so is an explicit transaction(..), a whole playground script, an import
commit sequence number (commit_seq)the number of a commit: 1, 2, 3, ... per graph, never reused. The position of a graph is the number of its last commit (0 = nothing committed yet)
commit timethe time of a commit (UTC, microseconds); monotonic within a history
snapshotthe whole graph at one position. In a Store it is a directory under snapshots/, packed it is one .gsnap file
WAL (journal)the write-ahead log: one record per commit with every change, its before and after values, in order; one record per mark
checkpointwriting a new snapshot of the current state, so the next open replays less WAL
marka name for a position ("before-import"); costs a few bytes
targeta point to go back to: a commit, a time, or a mark
lineage (graph_id)a UUID that names one history. A fork, an in-place rollback and a repair start a new lineage that records its parent
atticwhere an in-place rollback keeps the history it rolled back, so the rollback can be undone
backupa consistent copy of a store; marked, so it opens read-only until it is restored
donoran intact older copy (an older snapshot plus the WAL) that damaged data can be rebuilt from
maintenance modehow a damaged store opens: read-only, with a damage report

Guarantees

  • Durable commits. A Store commit (and a journal commit with Durability::EveryCommit, the default) is written and fsynced before it returns. A failed write or sync rolls the commit back: the caller never gets "ok" for a commit that is not on disk, and the WAL never holds a commit that did not happen.
  • Crash safety. Opening a store after a crash (or kill -9) brings back exactly the last committed state: an interrupted last write is cut off, an interrupted multi-file operation is completed.
  • Damage is found, never silently lost. Every header, chunk and record carries a CRC-32C; the small critical metadata exists twice. A damaged store opens read-only in maintenance mode with a report, and repair writes a new store elsewhere, never in place.
  • Nothing is deleted implicitly. History goes away only through an explicit prune, a rollback with --delete, or removing an attic entry.
  • Point in time. Every commit, time and mark that the retained history covers can be viewed read-only, forked into a new store, or rolled back to.
  • Portable bytes. Little-endian, the same bytes on every platform and in WebAssembly; no file holds an absolute path, so a store can be moved or copied anywhere. The format is a public specification.
  • One writer. A store has at most one writer (an operating-system lock); readers, backups and forks work while it runs.

This part of the book

Quick Start

Command line

cargo build -p graphersal-cli                        # target/debug/graphersal
graphersal store create data/ --from modern          # a store with the modern graph, at commit 0
graphersal --graph data/ -e 'g.add_v("person").property("name", "zoe").to_list()'
graphersal store mark data/ before-import            # name this position
graphersal --graph data/ -e 'g.add_v("person").property("name", "ada").to_list()'
graphersal store info data/                          # commit 2, 1 snapshot, 1 mark
graphersal store fork data/ branch/ --at-mark before-import   # the state at the mark, as a new store
graphersal store backup data/ backup/                # a consistent copy, also while in use
graphersal --graph data/ --server                    # the playground UI on the store: http://127.0.0.1:8080/

Every commit to data/ is durable before the command returns; the REPL (graphersal --graph data/) and the dev server keep it open and commit every query. Ctrl+C closes the store cleanly; a crash or kill -9 loses nothing committed either.

Without a store, a packed snapshot saves and loads the whole graph:

graphersal -e 'g.export_snapshot("m.gsnap")'          # Exported a snapshot to m.gsnap (6 vertices, 6 edges, commit 0)
graphersal --graph m.gsnap -e 'g.v().count().next()'  # 6

Rust

graphersal = { version = "0.8", features = ["persist"] }
use graphersal::persist::{RecoveryTarget, Store, StoreOptions};

let store = Store::create("data", StoreOptions::new())?;      // later: Store::open("data", ..)
store.graph().write().traversal_mut().add_v("person").property("name", "ann").to_list()?;
store.mark("after-ann")?;                                      // a point-in-time target
store.checkpoint(Some("nightly"))?;                            // a snapshot of the current state
store.close()?;                                                // a clean close (Drop does it too)

let store = Store::open("data", StoreOptions::new())?;        // recovery: snapshot + WAL replay
assert_eq!(store.graph().read().vertex_count(), 1);
let past = Store::open_read_only("data", RecoveryTarget::Mark("after-ann".into()))?;
assert_eq!(past.graph.vertex_count(), 1);
Ok::<(), Box<dyn std::error::Error>>(())

store.graph() is the shared graph (Graph, a TraversalGraph behind a read-write lock); every commit of it is written to the store's write-ahead log and synced before it returns.

A packed snapshot over any Write / Read:

use graphersal::prelude::*;

let graph = TraversalGraph::tinkerpop_modern();
let mut bytes = Vec::new();
graph.write_snapshot(&mut bytes).unwrap();
let loaded = TraversalGraph::read_snapshot(bytes.as_slice()).unwrap();
assert_eq!(loaded.vertex_count(), 6);

Python

import graphersal

graph = graphersal.Graph.tinkerpop_modern()
graph.save("g.gsnap")                                    # {"commit_seq", "vertex_count", "edge_count"}
graph = graphersal.Graph.load("g.gsnap")

with graphersal.Store.create("data") as store:           # later: graphersal.Store.open("data")
    store.graph.execute('g.addV("person").property("name", "ann").next()')
    store.mark("after-ann")
    store.checkpoint("nightly")

Web playground

Every graph you load in the playground is a Store in memory: the Store menu in the top bar checkpoints, marks, opens past states read-only, forks and rolls back, exactly as the dev server does on a directory (The Store in the Playground). Everything in memory is lost on a page reload: Download current state (.gsnap) keeps a state, and the start page loads it back.

Packed Snapshots

A packed snapshot is the whole graph in one file or stream, conventionally named *.gsnap. It works over any std::io::Write / Read, so it runs in WebAssembly and on any stream a host has (a file, a socket, an upload). There is no journal and no directory: the application decides when to save. For durability between saves, add a journal or use the Store.

use graphersal::prelude::*;
use graphersal::persist::{self, ReadOptions, WriteOptions};
use graphersal::storage::PersistentStorage; // graph_id()

let graph = TraversalGraph::tinkerpop_modern();
let mut bytes = Vec::new();
let info = persist::write_snapshot(&graph, &mut bytes, &WriteOptions::new().with_name("nightly"))
    .unwrap();
assert_eq!(info.vertex_count, 6);

let header = persist::read_snapshot_info(bytes.as_slice()).unwrap();   // the manifest only
assert_eq!(header.name, "nightly");

let loaded = persist::read_snapshot(bytes.as_slice(), &ReadOptions::new()).unwrap();
assert_eq!(loaded.vertex_count(), 6);
assert_eq!(loaded.graph_id(), graph.graph_id());

graph.write_snapshot(w) and TraversalGraph::read_snapshot(r) are the same with default options.

Your own storage (EXPERIMENTAL): persist::write_snapshot takes any storage that implements graphersal::storage::PersistentStorage (for a shared graph pass &*graph.read()), and persist::read_snapshot_into(reader, &options, MyStorage::default()) loads a snapshot into an empty one through the trait's load sink. The same graph gives the same bytes in every storage. A shared Graph<MyStorage> built with Graph::new_persistent can also be written by the DSL's g.export_snapshot(path); built with plain Graph::new it cannot (Unsupported), except a Graph<TraversalGraph>, which is written either way. Recovery::new_in(MyStorage::default()) recovers a snapshot plus journals into it.

What a snapshot holds

  • Every vertex (id, label set, properties in insertion order) and edge (id, optional label, endpoints, properties); every value type losslessly (uuid, nested arrays and objects, NaN payloads).
  • The stored schema (its mode and declarations).
  • The catalog of definitions (saved queries, ...). A definition of a kind this version does not know (written by a newer Graphersal) is kept byte for byte and written back unchanged (format spec 6.3, 16).
  • The graph's identity and position: the lineage id (graph_id), the commit position (last_commit_seq), the time of the last commit, and the auto-id sequences, so the next automatic id never repeats one handed out before the snapshot.
  • Counts and an estimate of the in-memory size (for a memory check before loading), a name and free-form meta text (WriteOptions::with_name, with_meta).

Indexes and statistics are not stored: they are rebuilt during the load.

Writing

  • Writing holds the graph's read access for the whole write, so the snapshot is consistent; its position is graph.last_commit_seq().
  • Elements are written sorted by id, in compressed, self-contained chunks (1 MiB uncompressed by default, with_chunk_bytes) grouped into segments (256 MiB by default, with_segment_bytes). Chunks are LZ4 (with_codec(Codec::Zstd) with the persist-zstd feature); a chunk below 4 KiB, or one compression does not shrink, is stored as is.
  • The writer streams: the manifest at the start lists every segment's size and checksum, so a first pass encodes every chunk to plan them and keeps only those figures; the second pass encodes each chunk again and writes it straight to the writer. Memory: the sorted id index (about 24 bytes per element) and one chunk, never the encoded snapshot; the writer need not seek (a pipe, a socket, a download). The price is encoding the graph twice.
  • A store imports a packed snapshot (Store::create_from_packed, graphersal store create --from x.gsnap) by copying it section by section into its snapshot directory, and exports one (export_packed) by streaming the files: neither holds the snapshot in memory.

Reading

  • Reading loads vertices, then edges, rebuilds indexes and statistics, and restores the schema, the lineage id, the position, the commit time and the auto-id sequences.
  • The schema is not re-validated: the data was valid when it was committed. Integrity comes from CRC-32C checksums on every header, chunk and section. Damage is a PersistError::Corrupt naming the section and the byte offset, never a panic or a silently wrong graph.
  • Every load is checked against the process memory ceiling (memory.limit, on by default): a snapshot whose recorded size estimate does not fit is refused before anything is loaded (PersistError::MemoryBudget, naming the operation and the minimum to raise the ceiling to), and a graph that grows past the ceiling while it is read stops with PersistError::Graph(GraphError::ResourceLimitExceeded) (see What the ceiling covers). ReadOptions::with_memory_limit(bytes) adds a stricter bound for one read (the lower of both refuses); with_max_value_depth(n) bounds value nesting (default 128, like traversal.max_value_depth).
  • persist::read_snapshot_info(r) reads only the manifest: name, meta, identity, position, counts. It is how graphersal store list lists snapshots without loading them.
  • A non-seekable stream is fine: the sections come in the order they are needed.

From the DSL, the CLI, Python and the playground

graphersal -e 'g.export_snapshot("m.gsnap")'          # Exported a snapshot to m.gsnap (6 vertices, 6 edges, commit 0)
graphersal --graph m.gsnap -e 'g.v().count().next()'  # 6
graphersal store export data/ data.gsnap              # a Store's latest snapshot as a .gsnap
graphersal store create data2/ --from data.gsnap      # a new Store from a .gsnap
  • DSL: g.export_snapshot(path) (or g.export_snapshot(..)) writes one; GraphSource::file("m.gsnap") loads one. Both need file access (Permissions).
  • Python: graph.save(path) and graphersal.Graph.load(path) (Python).
  • Playground: Save as snapshot on the start page, and a .gsnap file loads like any graph file; the Store menu downloads any stored snapshot as .gsnap.
  • Dev server: GET /api/export?format=gsnap downloads the current state, with the store's embedding models unless &models=without.
  • Embedding models: a shared graph's writers (g.export_snapshot, AnyGraph::write_snapshot, persist::write_graph_snapshot, Python graph.save, the dev server's Save to file) carry the models it serves, from its store or the .gsnap it was loaded from; write_snapshot_with(.., ModelCopy::Exclude) leaves them out. A blob the graph does not hold is named in SnapshotInfo::blobs_not_carried, a damaged one fails the write. The storage-level persist::write_snapshot and TraversalGraph::write_snapshot have no source for the blobs: they write only the catalog's references.

The byte layout is section 8 of the format specification: a packed file holds exactly the files of a Store's snapshot directory, so the Store imports and exports .gsnap files by copying (Store::create_from_packed, store.export_packed).

Journal and Recovery

The stream-level durability API: a packed snapshot as the base, a journal (write-ahead log) that records every commit after it, and recovery that replays the journals onto the snapshot, up to the end or to a target. Everything works over std::io::Write / Read, also in WebAssembly. The Store does all of this for you on a directory, a file or memory; use the journal directly when you manage the streams yourself.

use graphersal::prelude::*;
use graphersal::persist::{self, Durability, Journal, RecoveryTarget, SharedBuffer};

// A graph, its base snapshot, and a journal from then on.
let mut graph = TraversalGraph::tinkerpop_modern();
let mut snapshot = Vec::new();
graph.write_snapshot(&mut snapshot).unwrap();
let wal = SharedBuffer::new();                        // an in-memory Write; a File in practice
Journal::new(wal.clone(), Durability::EveryCommit).attach(&mut graph).unwrap();

graph.traversal_mut().add_v("person").property("name", "ann").to_list().unwrap();
graph.mark("after-ann").unwrap();
graph.traversal_mut().v("1").drop().to_list().unwrap();

// Recovery to the mark: ann is there, vertex 1 is not dropped yet.
let recovered = persist::recover(
    snapshot.as_slice(),
    [wal.contents().as_slice()],
    RecoveryTarget::Mark("after-ann".into()),
)
.unwrap();
assert_eq!(recovered.graph.vertex_count(), 7);
assert_eq!(recovered.report.commit_seq, 1);

The journal

Not every commit of a Store comes from an open graph: a catalog change of a CLOSED store (graphersal embed-model import --into, store models remove) appends one commit to its WAL without loading the graph (format spec 12.12). Recovery replays it like any other.

A Journal is a commit hook that writes each committed unit (a lossless ChangeSet: every mutation with its before and after values, the commit time, the commit metadata, the auto-id sequences) to its writer before the commit becomes final.

use graphersal::prelude::*;
use graphersal::persist::{Durability, Journal};

let mut graph = TraversalGraph::new();
let file = std::fs::File::create("graph.wal").unwrap();
Journal::for_file(file, Durability::EveryCommit)       // fsync per commit
    .attach(&mut graph)
    .unwrap();
graph.traversal_mut().add_v("person").to_list().unwrap(); // written and synced, then committed
  • Write-ahead, with a veto. A failed write or sync rolls the unit back and the caller gets GraphError::CommitRejected: memory and journal never diverge, and nobody gets "ok" for a commit that is not on disk.
  • Always last. The journal has its own slot after every other commit hook, whatever the registration order, and the commit sequence number is assigned before it writes. Once its record is written nothing can veto the unit any more, so a journal never holds a commit that did not happen.
  • Refused records are cut off. When a write or sync fails, the record is cut off the stream again (with the truncate function: Journal::for_file sets set_len + fsync, with_truncate(f) sets one for any writer), so a later recovery never replays a commit the caller was told failed. A writer without a truncate function cannot do this.
  • Poisoning. After a failed write or sync the state of the stream is unknown; the journal then rejects every later commit and mark (PersistError::Poisoned). Recover the graph and attach a new journal.
  • Durability (Durability): EveryCommit (the default: sync per commit and mark), Interval(duration) (sync at most that often; a crash of the machine may lose the last interval, never a commit in the middle), Os (flush only; the operating system writes; a crash of the process loses nothing, a crash of the machine may). Journal::new(writer, ..) syncs with flush; with_sync(f) or Journal::for_file give it a real fsync.
  • Durable end. attach returns a DurableEnd: the byte offset after the last synced record and its commit number, readable without any lock (a backup copies a journal up to it).
  • One journal per graph. attach writes the stream header (the lineage id and the next commit number) and fails when the graph already has one or a unit is open.
  • Large records (from 4 KiB) are LZ4-compressed (with_codec).
  • A large commit is written in parts. A commit of more than 64 MiB of uncompressed record body (every change with its before and after values) is written as several records of 64 MiB, one after the other in the same segment, synced once after the last one (format spec 9.3.1); readers see one commit. Beyond 2^20 parts (64 TiB) the unit is vetoed with PersistError::CommitTooLarge (inside GraphError::CommitRejected from the hook journal): it rolls back, nothing is written, and the journal stays usable (Resource Limits).
  • A user hook that panics in before_commit rolls the unit back before the journal runs, so the journal never holds it (Transactions).
  • A panic inside the journal (in its own write path: an engine bug, or a writer, sync or store backend that panics) is handled like a failed write: the record is cut off again, the journal poisons itself, and the panic continues; the unit is rolled back on the way out. See Failures while committing.

Failures while committing

A commit asks the user hooks first (in registration order), then the journal. Whatever goes wrong there, the promise is the same: the unit is either committed in memory AND in the journal, or in neither. What you see, and what a reopen (a recovery, Store::open) gives:

What failsThe unitThe journal afterwardsWhat the caller seesA reopen gives
A user hook's before_commit returns Err (a veto)rolled back; every hook gets after_rollbackuntouched (it never ran) and usableGraphError::CommitRejected { hook, source }the state before the unit
A user hook's before_commit panicsrolled back; every hook gets after_rollback (RollbackReason::Failed)untouched (it never ran) and usablethe panic continues (a bug: it is not turned into an error)the state before the unit
The journal's write or sync fails (Err: a full disk, an I/O error)rolled backthe refused record is cut off again and synced; the journal is poisonedCommitRejected from the hook journal, its source PersistError::Poisoned ("... (the refused record was cut off again)")the state before the unit
The journal's write or sync fails and the cut fails toorolled backpoisoned; a Store records the valid end of the WAL in GRAPH (wal_cut), a bare Journal cannot (the record may stay)as above, the reason says the position was recordeda Store: the state before the unit (the next open cuts the record off, OpenReport::refused_cut; every reader stops there meanwhile)
The journal panics in its write path (after part of the record, or after all of it, e.g. in the sync)rolled back on the way out; every hook gets after_rollbacktreated like a failed write: the record is cut off again (or, when that cut fails or panics too, its position recorded as above); the journal is poisoned with the reason a panic while writing a commit record: <message>the panic continuesthe state before the unit
The write or sync of a commit in parts fails at any of its partsrolled backevery part written is cut off again (the cut starts at the first part) and synced; the journal is poisonedas for a failed writethe state before the unit
The commit needs more than 2^20 parts (CommitTooLarge), or encoding it does not fit under the process memory ceiling (ResourceLimitExceeded, operation commit encoding)rolled backnothing written; usableCommitRejected from the hook journalthe state before the unit
A hook's after_commit panicsstays committed (it is final and durable)holds the unitthe panic continuesthe state with the unit

A poisoned journal refuses every later commit and mark with PersistError::Poisoned (inside CommitRejected from the hook journal; its help says what to do), also once the disk works again: after a failure in the middle of a record the state of the stream is unknown, so nothing may follow it. A Store's close() then fails with StoreFailure::JournalSyncFailed and does not mark the store as closed cleanly. What to do: check the disk (or report the panic: it is a bug), then reopen the store (or restart the server): the recovery continues from the last durable commit and the store accepts commits again. With a bare Journal, recover the graph (persist::recover) and attach a new journal.

The same applies to a mark (graph.mark(..)) and to the Store's own records (a checkpoint record, the sync at close()): a panic poisons the journal and continues.

Marks

A mark names a point in the journal: the state right after the last commit.

graph.mark("before-import")?;   // Rhai: g.mark("before-import"); Python: graph.mark(..)

Names are unique within a journal (pass the names of earlier journals with Journal::with_known_marks, e.g. from RecoveryReport::marks). A graph without a journal, or a mark inside an open transaction, is an error (GraphError::MarkUnavailable). In the DSL g.mark needs the Update permission on data. The Store keeps mark names unique along its whole history.

Commit times

Commit, mark and checkpoint times come from one clock per instance (CommitClock, microseconds since the Unix epoch, UTC): every time is max(system clock, the latest time the instance handed out), so a mark is never earlier than the commit it names and a commit never earlier than a record written before it. Equal times are allowed. The clock's floor is not stored: a recovery and a Store's open raise it again to the latest time the files hold (the last commit, every mark and checkpoint record read, the snapshot's creation time), and a rollback in place keeps it. When the system clock steps back by more than one second behind the floor (a resumed virtual machine, a manual change), times stay at the floor until the system clock catches up and Graphersal writes a warning; it is never an error.

Recovery

use graphersal::persist::{self, Recovery, RecoveryTarget};

let recovered = persist::recover(snapshot_reader, [journal_1, journal_2], RecoveryTarget::Latest)?;
let graph = recovered.graph;              // unpublished, no hooks: attach a new journal
println!("{:?}", recovered.report);       // position, commits replayed, marks, torn tail

// The builder: no snapshot (start from an empty graph), read options, a target.
let recovered = Recovery::new()
    .journal(journal_reader)
    .target(RecoveryTarget::CommitSeq(12))
    .run()?;
TargetStops
Latestat the end of the journals
CommitSeq(n)right after commit n (an error if the journals end before it)
Time(t)after the last commit with a time at or before t (µs since the epoch, UTC)
Mark(name)at the mark (an error if there is no such mark: PersistError::TargetNotReached)
  • Journals are replayed with TraversalGraph::replay: outside units, without hooks and without schema validation. Commits already in the snapshot are skipped; the first one after it must be the next number, and so on (a missing journal is PersistError::Gap). A journal of another lineage is refused (PersistError::LineageMismatch). Without a snapshot the replay starts from an empty graph and the first journal must start at commit 1.
  • The report (RecoveryReport): the snapshot's position, the position reached and its time, the number of commits replayed, the marks seen, whether the end was reached, and a torn tail.
  • Torn tail vs damage. Only an incomplete record at the very end of the last journal (an interrupted write) is a torn tail: it is ignored and reported. A complete record whose checksum fails, anywhere, is damage and fails the recovery with its location (PersistError::Corrupt). Every record header (sync marker, length, commit number, type) has its own checksum, separate from the payload's, so a damaged length is damage too, never taken for an interrupted write; zeros after the last complete record (space the file system allocated but the write never filled) are a torn tail.
  • A past target is a past state. Attach a journal to a graph recovered to a target before the end only as a new history (a new lineage: give it a new id with PersistentStorage::set_graph_id first), never to continue the old journal.
  • Reading a journal without replaying it: persist::read_journal(r) iterates its records (JournalRecord: commits as ChangeSets, marks, checkpoints) and reports a torn tail.

Lineage

PersistentStorage::graph_id() (implemented by TraversalGraph; import the trait from graphersal::storage) is a UUID (version 7) created on first use and carried by every snapshot and journal; read_snapshot restores it. Recovery replays a journal only onto a snapshot of the same lineage. In a Store, a fork, an in-place rollback and a repair start a new lineage that records its parent and the commit it branched at; recovery follows that chain.

Python

graph.save("g.gsnap")                                       # the base
graph.start_journal("g.wal", durability="every_commit")     # or "os", or seconds (an interval)
graph.execute('g.addV("person").property("name", "ann").next()')
graph.mark("after-ann")
graph, report = graphersal.Graph.recover("g.gsnap", ["g.wal"], mark="after-ann")   # or commit_seq=, time=

The byte layouts of journal records are section 9 of the format specification.

The Store

For an application that keeps its graph, the Store does everything of the previous pages for you: one directory holds the graph's snapshots and its write-ahead log, every commit is durable before it returns, and opening the directory brings the graph back exactly as the last commit left it, also after a crash. One directory = one graph, one writer: "SQLite for graphs".

The directory is usually a path on disk. It can also be one single file (graph.gstore, for embedded use) or live in memory (every target, the browser included).

use graphersal::persist::{RecoveryTarget, Store, StoreOptions};

let store = Store::create("data", StoreOptions::new())?;      // or Store::open("data", ..)
store.graph().write().traversal_mut().add_v("person").property("name", "ann").to_list()?;
store.mark("after-ann")?;                                      // a point-in-time target
store.checkpoint(Some("nightly"))?;                            // a snapshot of the current state
store.close()?;                                                // a clean close (Drop does it too)

let past = Store::open_read_only("data", RecoveryTarget::Mark("after-ann".into()))?;
assert_eq!(past.graph.vertex_count(), 1);
Ok::<(), Box<dyn std::error::Error>>(())
graphersal store create data/ --from modern     # the same from the command line
graphersal --graph data/ -e 'g.add_v("person").property("name", "ann").to_list()'
graphersal store info data/

The files

data/
├── GRAPH, GRAPH.copy        identity, lineage, state (two copies of the same small file)
├── LOCK                     held by the one writer (an operating-system lock)
├── BACKUP                   the backup pin: shared while a backup, verify, fork or export reads
├── INTENT                   only while a multi-file operation runs (rollback, prune, ...)
├── marks                    the marks, rebuilt from the WAL when lost
├── snapshots/
│   └── 00000000000000000003/      one snapshot, named by its commit (20 digits)
│       ├── manifest               identity, position, counts, the segment list, every chunk's checksum
│       ├── schema.json            the stored schema
│       ├── v-000000.seg           vertices, sorted by id, in compressed chunks
│       └── e-000000.seg           edges
├── wal/
│   └── 00000000000000000004.wal   write-ahead log segments, named by their first commit (16 MiB each)
└── attic/
    └── 20261008T070510Z-00000000000000000002/   history a rollback moved aside
FileWhat it isWhen it changes
GRAPH, GRAPH.copythe store's identity (graph_id, the lineage chain of forks and rollbacks it descends from), its state (closed cleanly or open), the chunk size, and a few recovery facts (the newest WAL segment, the commit of the last clean close, a backup marker)rarely: open, close, a new WAL segment, a rollback; always both copies, each written atomically
LOCKthe writer's operating-system lock (flock / LockFileEx), released when the process endscreated empty by the first writer, never written
BACKUPa lock file: backups hold it shared while they copy, prune takes it exclusivelycreated empty by the first backup or prune, never written
INTENTthe plan of a multi-file operation in progress; an interrupted one is completed at the next openduring a rollback, an attic restore, a prune, a backup increment (in the backup)
marksthe list of marks, so listing them reads no WALafter every mark
snapshots/<commit>/full copies of the graph; immutable once writtena checkpoint adds one, prune removes old ones
wal/<first commit>.walevery commit since the oldest snapshot, in order; append-onlyevery commit and mark appends a record
attic/<time>-<commit>/snapshots and WAL that an in-place rollback moved aside, with an ATTIC descriptiona rollback adds an entry; restore and remove take it away

Every name is relative to the store's root, and no file records a path: move or copy the whole directory and open it there. The exact byte layouts are the Storage Format Specification.

The pages of the Store

Page
Opening and Closingcreate, open, recovery on open, the lock, read-only opens, clean close and Ctrl+C
Commits and Durabilityfsync per commit, Durability, refused records, the durable end, change data capture
Checkpoints and Snapshotsmanual and automatic checkpoints, the chunk size, .gsnap export and import
Marksnaming a position; snapshots vs marks
Point in Timetargets (commit, time, mark), the time format, read-only views
Forka past state as a new, writable store
Rollback and the Atticgoing back in place, and undoing it
Backup and Restorefull, incremental and ZIP backups, restore
Prune, Compact and Retentionremoving old history explicitly; giving disk space back
Verifythe scrub
Damage, Maintenance and Repairwhat happens when the disk rots; the runbook
Format Versions and Upgrade
Directory BackendsFsDir, MemDir, your own StoreDir; relocation and split stores
Single-File Storethe whole store in one .gstore file
Your Own StorageStore<S> over a host's PersistentStorage: open_in, create_in
Creation Parameterswhat is fixed when a store is created (store id, damage policy, chunk size, backend, format version) and the per-open options

What works while the store is open elsewhere (a dev server, a REPL, another program):

While another process writes
info, list, marks, verify, fork, backup, export, repair, compact-advice, attic (list, changes, fork); Store::open_read_only, Store::inspectwork (no lock taken)
mark, checkpoint, prune, compact, rollback, attic restore/remove, convert; Store::openrefused: "in use" (PersistError::Locked); use the dev server's Store menu, or stop the writer

Opening and Closing

Create

use graphersal::prelude::*;
use graphersal::persist::{Store, StoreOptions};

let empty = Store::create("data", StoreOptions::new())?;                  // an empty graph
let modern = Store::create_with("modern-data", TraversalGraph::tinkerpop_modern(), StoreOptions::new())?;
let file = std::io::BufReader::new(std::fs::File::open("m.gsnap")?);
let restored = Store::create_from_packed("from-gsnap", file, StoreOptions::new())?;  // from a .gsnap
Ok::<(), Box<dyn std::error::Error>>(())

The directory must be missing or empty. A new store has one snapshot (commit 0, the initial graph) and an empty WAL, and is open read-write when create returns. A path ending in .gstore (or Store::create_file) makes a single-file store. StoreOptions::with_chunk_bytes sets the snapshot chunk size, which is fixed for the store's life (Checkpoints).

graphersal store create data/ --from modern       # --from: modern, empty, large, tree, a GraphSON/GraphML file, a .gsnap
graphersal store create small-chunks/ --chunk-size 262144   # 256 KiB chunks
graphersal --graph new/ --create-store -e 'g.add_v("person").to_list()'   # create when missing ("note: created the store new/", then "damage policy: maintenance")

Open: recovery on open

Store::open(dir, options) opens a store read-write and always runs its recovery:

  1. takes the writer lock (a second writer, in this or another process, gets PersistError::Locked: "the store ... is in use");
  2. completes an interrupted multi-file operation (an INTENT file: a rollback, an attic restore, a prune) and removes temporary files of an interrupted checkpoint;
  3. checks the set of WAL segments against GRAPH (a lost, emptied or replaced newest segment is damage, never a shorter history);
  4. loads the latest snapshot and replays the WAL after it;
  5. cuts an interrupted last write of the WAL (a torn tail) and rebuilds a lost marks file;
  6. marks the store as open and attaches the journal: from now on every commit is durable.

store.open_report() says what happened: whether the last close was clean (clean_close), the snapshot it started from and the commits replayed, a cut torn tail, a completed intent, removed temporary files, a repaired GRAPH copy, warnings. A store that was not closed cleanly (a crash, kill -9, a power cut) is not damaged: the WAL replay brings back every commit; the CLI then notes "not closed cleanly", which is harmless.

$ graphersal --graph data/ -e 'g.v().count().next()'
9

Damage never fails the open and is never skipped silently: the store opens read-only in maintenance mode with a damage report. A backup directory is refused by Store::open (PersistError::IsBackup): it opens read-only through Store::open_backup until it is restored. A store that holds something critical this build does not know (a critical definition of an unknown kind, written by a newer Graphersal) opens read-only too: Store::read_only_reason() says why, OpenReport::read_only records it, and every write is refused with PersistError::ReadOnly (Format Versions).

In the CLI, --graph <path> opens a Store when the path is a directory, ends in /, is a missing path without an extension, ends in .gstore, or is an existing single-file store. --create-store creates it when it does not exist yet (missing or empty directory).

Read without opening

None of these take the writer lock; all work while a writer has the store open:

Store::inspect(dir)the StoreInfo: identity, lineage, position, snapshots, marks, WAL size, attic, state (graphersal store info)
Store::snapshots_dir(dir), Store::marks_dir(dir)the listings (store list, store marks)
Store::open_read_only(dir, target)the graph at any point in time, as an unpublished TraversalGraph
Store::verify_dir(dir)the scrub
Store::is_store(dir)whether dir holds a store (Ok(false) for nothing there; a directory that cannot be read is an error)

Close

store.close() (and Drop) closes cleanly: it syncs, records the last commit and marks the store "closed cleanly" in GRAPH, and releases the lock. After close() the shared graph refuses commits (another holder of the Arc<Graph> gets an error, not a silent loss). store.shutdown() does the same through a shared reference. With StoreOptions::with_checkpoint_on_close(true) a checkpoint is written first, so the next open replays nothing.

Ctrl+C (SIGINT, SIGTERM) in the CLI, its REPL and the dev server closes an open store cleanly: the running query is cancelled first (it rolls back), then the store is closed. A second Ctrl+C exits at once (harmless too: every commit is already durable). The dev server exits with 0, the REPL and -e runs with 130.

Stopping: closing the store data/ (Ctrl+C again to exit at once)...
The store data/ was closed cleanly.

Locking

One store has at most one writer: an operating-system lock on LOCK (on a single file, the lock on the file itself; in memory, an in-process flag), released by the operating system when the process ends, so a crashed writer never leaves a stale lock. Readers (inspect, listings, open_read_only, verify, fork, backups, export) take no lock. Two Store values of the same directory in one process are two writers: the second gets PersistError::Locked too.

Commits and Durability

Every commit of store.graph() (every traversal, every transaction(..), every import; see Transactions) is written to the store's write-ahead log as one record and made durable before it returns. A commit that changes nothing writes nothing.

use std::time::Duration;
use graphersal::persist::{Durability, Store, StoreOptions};

let store = Store::open("data", StoreOptions::new())?;                    // fsync per commit
let fast = Store::open(
    "other",
    StoreOptions::new().with_durability(Durability::Interval(Duration::from_millis(200))),
)?;
store.graph().write().traversal_mut().add_v("person").to_list()?;          // on disk when it returns
Ok::<(), Box<dyn std::error::Error>>(())

Durability

DurabilityA commit returns afterA crash of the processA crash of the machine (power)
EveryCommit (default)the record is written and fsyncedloses nothingloses nothing
Interval(d)the record is written; fsync at most every dloses nothingmay lose the commits of the last interval, never one in the middle
Osthe record is handed to the operating systemloses nothingmay lose what the OS had not written yet

The write-ahead guarantees

  • The journal runs last. The store's journal is a commit hook in its own slot after every other hook (your own hooks, schema checks, a veto), and the commit's sequence number is assigned before it writes. Once the record is written nothing can veto the commit any more: the WAL never holds a commit that did not happen.
  • A failed write or fsync vetoes the commit: it rolls back and the caller gets GraphError::CommitRejected with the reason. Memory and disk never diverge, and nobody gets "ok" for a commit that is not on disk.
  • Refused records are cut off. Before the store gives up, the refused record is cut off the WAL again (and synced), so a commit the caller was told failed is never replayed. If even that cut fails, its position is recorded in GRAPH, and the next open cuts there (every reader stops there meanwhile).
  • A panicking hook rolls back. A commit hook of your own that panics in before_commit rolls the unit back (the panic then continues to the caller); the journal runs after it and never writes that unit (Transactions). A panic inside the journal itself (a bug, or a store backend that panics while the WAL is written) cuts the record off again, poisons the journal and rolls the unit back too. Every case, with what a reopen gives, is in the table Failures while committing.
  • Poisoning. After a failed fsync the state of the file is unknown, so the store refuses every later commit and mark (PersistError::Poisoned) until it is reopened. Reopening runs the recovery and continues from the last durable commit.
  • After close() the graph refuses commits.

The durable end

store.durable_end() is the position after the last record whose sync completed (its WAL segment, byte offset and commit). It is readable without any lock: a backup copies the WAL only up to it, because a record after it may still be vetoed.

WAL segments

The WAL is a sequence of segment files wal/<first commit>.wal, 16 MiB each by default (StoreOptions::with_wal_segment_bytes; a record is never split, a segment closes after the record that passes the size). A segment is closed with an fsync before the next one starts, so only the last segment can end in an interrupted write. Starting a segment is recorded in GRAPH, so a lost, emptied or replaced newest segment is reported as damage instead of opening the store at an earlier commit (Damage).

Large records (from 4 KiB) are compressed (StoreOptions::with_codec).

The size of one commit

A commit whose body (every change of the unit with its before and after values, a dropped element with its full properties included) is at most 64 MiB before compression is one WAL record; a larger one is written as several records, parts of 64 MiB each, of the same commit (format spec 9.3.1). The parts always lie in one WAL segment, the commit is synced once after its last part, and every reader (recovery, checkpoints, backups, changes_since, rollback) sees one commit. A crash in the middle of a commit in parts leaves a torn tail that the next open cuts at its first part: the commit is lost as a whole, never half. There is no practical size limit (2^20 parts, 64 TiB); a unit beyond it is refused with PersistError::CommitTooLarge (inside GraphError::CommitRejected from the hook journal). What bounds a large unit is memory: its change set and its encoded body are held while it commits, checked against the process memory ceiling. See Resource Limits.

Reading the committed changes (CDC)

use graphersal::persist::{Store, StoreOptions};
let store = Store::open("data", StoreOptions::new())?;
for change in store.changes_since(10)? {        // every commit after commit 10, in order
    let change = change?;
    println!("commit {} at {}: {} mutation(s)", change.commit_seq(), change.committed_at(),
             change.mutations().len());
}
Ok::<(), Box<dyn std::error::Error>>(())

changes_since(commit) streams the committed ChangeSets from the WAL, up to the durable end: every mutation with its before and after values, the commit time and metadata. It is the basis for change data capture, replication and audit. It fails when the WAL it needs was pruned. For a live process, a commit hook gets every ChangeSet as it commits; the WAL's byte format is public (format specification, section 9) for readers in other processes and languages.

Checkpoints and Snapshots

A snapshot is a full copy of the graph at one commit, in snapshots/<commit>/. A checkpoint writes a new one from the current state. Snapshots make opening fast (only the WAL after the latest snapshot is replayed) and are the starting points of every point-in-time load. The WAL is not shortened by a checkpoint: old history stays until you prune it.

use graphersal::persist::{Store, StoreOptions};
let store = Store::open("data", StoreOptions::new())?;
let info = store.checkpoint(Some("nightly"))?;        // a name is optional
println!("snapshot at commit {} ({} vertices)", info.commit_seq, info.vertex_count);
for snapshot in store.snapshots()? {
    println!("{} {} {}", snapshot.commit_seq, snapshot.name, snapshot.vertex_count);
}
Ok::<(), Box<dyn std::error::Error>>(())
$ graphersal store checkpoint data/ --name nightly
Snapshot at commit 3
  vertices: 8
  edges: 6
  merged from: the snapshot at commit 0 and 3 commits
  segment files: 0 reused, 0 copied, 2 written
$ graphersal store list data/
      commit  last commit             vertices       edges  name
           0  -                              6           6
           3  2026-10-08T07:05:08Z           8           6  nightly

How a checkpoint is written

A checkpoint is merged: the new snapshot is built from the newest snapshot and the WAL after it, not from the graph in memory, and without the graph's lock: commits go on while it runs and land after its position (the next checkpoint picks them up).

  1. The WAL records after the newest snapshot are read (every checksum) and the ids they touch are collected: the vertices and edges a change names, and the endpoints of the edges added or dropped.
  2. The chunks of the newest snapshot that hold one of these ids (found through its manifest's chunk index, each checksum checked) are decoded into a small delta graph, with the snapshot's schema, catalog of saved queries, position and auto-id sequences.
  3. The WAL is replayed onto the delta graph exactly as an open replays it, and every change's before image must match: a WAL that does not continue the snapshot is damage.
  4. The touched segments are read again as streams and merged on the sorted id with the delta into new segment files (planned first, then written chunk by chunk and checked against the plan). A segment no touched id falls into keeps its bytes under the donor rule: it is reused by reference (the manifest names a file of an older snapshot's directory: an incremental snapshot) when the snapshot before the old one holds an identical copy in another file, and copied into a new file otherwise.
  5. The new snapshot goes into a temporary directory, is synced, verified (every file it names, the referenced ones too, read back one chunk at a time) and only then renamed to its final name. A Checkpoint record goes to the WAL and the next commit starts a new WAL segment.

Memory is proportional to the changes since the last snapshot (the delta graph, one decoded chunk, one chunk being written), not to the graph. Beyond a bound, StoreOptions::with_checkpoint_merge_bytes(bytes) (the WAL bytes after the last snapshot; 1 GiB by default, 64 MiB in the browser; 0 = never merge), the checkpoint encodes the graph in memory instead, under its read lock (writers wait, readers do not; memory: about 24 bytes per element and one chunk). The same streaming encoder writes a store's first snapshot, a fork, a repaired store and packed snapshots.

Damage in anything the merge reads (a manifest, schema.json, a chunk, a segment file, a WAL record, a gap in the commits, a foreign lineage, a WAL that does not continue the snapshot) stops the checkpoint with the error: nothing visible is written (the temporary directory is removed) and the store keeps running. Run graphersal store verify then.

  • A checkpoint at a commit that already has a snapshot returns that snapshot (nothing committed since: nothing written).
  • The live store merges up to the WAL's durable end (with Durability::EveryCommit, the last commit; a manual checkpoint or a checkpoint on close syncs the WAL first).
  • Segment files are the unit of reuse: a change rewrites the whole segment holding it (64 MiB by default for a store, with_snapshot_segment_bytes), and the next checkpoint copies it once (the donor rule). Smaller segments mean less rewriting per checkpoint and more files.
  • Files of an older snapshot that a newer one uses stay when prune removes the older snapshot; a packed export of an incremental snapshot is self-contained.
  • In a backup, in maintenance mode or in a store this version may only read, checkpoints are refused; while a dev server holds the store, use its Store menu (Checkpoint).

A closed store

graphersal store checkpoint <dir> (Rust: Store::checkpoint_dir(dir, options, name)) merges a CLOSED store without loading its graph: it takes the writer lock (a store open elsewhere is refused as "in use"), completes an interrupted operation and removes temporary files as an open would, merges the newest snapshot with the whole WAL (an interrupted last record is ignored; the next open cuts it), and writes nothing else (no Checkpoint record, GRAPH unchanged). The report says what it did:

$ graphersal store checkpoint data/ --name nightly
Snapshot at commit 3
  vertices: 8
  edges: 6
  merged from: the snapshot at commit 0 and 3 commits
  segment files: 4 reused, 0 copied, 1 written

The donor rule

A repair rebuilds a damaged chunk of the newest snapshot from the previous snapshot plus the WAL between them: the previous snapshot is the donor. A file both used would be damaged in both. So a checkpoint never uses a file the newest snapshot (its base) uses:

  • a segment it rewrites is a new file anyway;
  • an unchanged segment is referenced only through a twin: the snapshot before the base holds the same bytes (same id range, element count, length, checksum and chunk index) in another file, and the new snapshot names that file;
  • without a twin, its bytes are copied into a new file of the new snapshot (every byte read and checked).

An unchanged range therefore alternates between two files from checkpoint to checkpoint (the newest snapshot uses one, the previous one the other): only the first checkpoint after a range was rewritten copies it (the store's second snapshot copies everything unchanged once). CheckpointReport::segments_reused, segments_copied and bytes_copied say what happened. verify warns (not damage) when the newest snapshot shares a file with the previous one, which only a store written otherwise can show; the next checkpoint copies it.

Automatic checkpoints

When the WAL since the last snapshot passes 256 MiB, a checkpoint runs automatically on a background thread (StoreOptions::with_checkpoint_after_bytes(bytes); 0 = never; a store opened with more WAL than that checkpoints right away). It merges like a manual one, so commits do not wait for it. Without threads (WebAssembly) it runs when the host calls store.run_due_checkpoint() (the playground does after every run; the default threshold there is 4 MiB). store.last_auto_checkpoint_error() reports a failed background checkpoint as its own PersistError (shared, Arc); store.wal_bytes_since_checkpoint() the current amount.

When it runs:

  • Every commit wakes the background thread while the WAL since the last snapshot is at or above the threshold (wakes coalesce: a commit during a running checkpoint leaves one pending).
  • After a checkpoint that wrote a snapshot, the thread checks the level again at once: commits that landed while it ran (a single commit can be larger than the threshold) get the next checkpoint without waiting for another commit.
  • A failed automatic checkpoint is retried at the next commit, as long as the level is still at or above the threshold. It is never retried in a loop of its own: a checkpoint that keeps failing (a full disk, say) costs at most one attempt per commit, and none while nothing is committed. last_auto_checkpoint_error() keeps the last failure until a checkpoint succeeds.
  • run_due_checkpoint() follows the same rule: one attempt per call, while the level is at or above the threshold. StoreOptions::with_checkpoint_on_close(true) writes one at every clean close.

The chunk size

Elements are stored sorted by id in compressed, self-contained chunks (1 MiB uncompressed by default), grouped into segment files (64 MiB in a store, 256 MiB in a packed snapshot; with_snapshot_segment_bytes). The chunk is the unit of repair: a damaged chunk is rebuilt from an older snapshot's chunks for the same id range. Its size is a property of the store, chosen at creation (StoreOptions::with_chunk_bytes, graphersal store create --chunk-size) and fixed for the store's life. Smaller chunks mean finer repair and more overhead.

Snapshots as .gsnap files

A stored snapshot is exactly a packed snapshot laid out as files:

graphersal store export data/ data.gsnap              # the latest snapshot
graphersal store export data/ first.gsnap --commit 0  # Exported the snapshot at commit 0 to first.gsnap.
graphersal store create copy/ --from data.gsnap       # a new store from a .gsnap

store.export_packed(commit, writer) and Store::create_from_packed(dir, reader, options) do the same in Rust (an export waits while a rollback moves files; while it runs, a slow writer included, a rollback or a prune is refused); the dev server's Store menu offers each snapshot as a .gsnap download. A .gsnap of a state that has no snapshot: open it read-only at that target and write it with write_snapshot, or download Download current state (.gsnap) from a read-only view.

Marks

A mark names a position in the store's history: "the state right after the last commit". It is a record in the WAL (and a line in the marks file) and costs a few bytes; no data is copied. Use it to remember a moment by name, "before-import", and come back to it later with --at-mark before-import.

use graphersal::persist::{Store, StoreOptions};
let store = Store::open("data", StoreOptions::new())?;
let mark = store.mark("before-import")?;
println!("{} at commit {}", mark.name(), mark.commit_seq());
for mark in store.marks()? {
    println!("{} {} {}", mark.commit_seq(), mark.time(), mark.name());
}
Ok::<(), Box<dyn std::error::Error>>(())
$ graphersal store mark data/ before-import
Mark "before-import" at commit 1.
$ graphersal store marks data/
           1  2026-10-08T07:05:08Z  before-import
  • Mark names are unique along the store's whole history, across rollbacks and lineages; a duplicate is refused. A mark is never removed (an in-place rollback hides the marks after its target in the attic with the rest of that history).
  • A mark needs its history: a snapshot at or before it and the WAL from there to it. A prune that removes that history makes the mark unreachable: store.marks(), store info and the Store menu leave it out from then on, --at-mark on it fails with "a prune removed the history it needs", and its name stays taken (setting it again says so). The prune names such marks (report.marks_unreachable), and the compaction advice names them before you compact.
  • A mark's time is the time it was set (never earlier than the last commit).
  • From a script: g.mark("before-import") on a graph that has a journal (the CLI's --graph data/, the dev server; it needs the Update permission on data). From the dev server: the Store menu's Mark (MCP has no persistence tools). From Python: store.mark(name).
  • A mark inside an open transaction, or on a graph without a journal, is an error (GraphError::MarkUnavailable). A store that is a backup, read-only or in maintenance mode refuses marks.
  • Marks are not copied by a fork or a repair: they belong to the history they were set in.

Snapshots and marks

Both name a point in the store's history, but they are different things, and neither limits where you can go back to: every commit is a target (--at-commit N), and so is every point in time (--at-time).

SnapshotMark
What it isa full copy of the graph at a commit, in snapshots/<commit>/a name for a position in the history (a WAL record and a line in marks)
Made bystore.checkpoint(name), store checkpoint, the Store menu's Checkpoint, automatically past 256 MiB of WALstore.mark(name), g.mark(name), store mark, the Store menu's Mark
Coststhe size of the graph on disk; writing it merges the previous snapshot with the WAL after it (memory for the changes only)a few bytes
Good fora fast open and a fast load of that state (only the WAL after it is replayed); a .gsnap downloadremembering "before the import" by name
Removed byprune (the last two always stay)never; a prune of the history before it makes it unreachable

Point in Time

Every state the retained history covers can be brought back: read-only, as a new store, or as the store's own state again.

Targets

TargetRust (RecoveryTarget)CLIMeans
the endLatest(no option)the current state
a commitCommitSeq(n)--at-commit <N>right after commit N
a timeTime(micros)--at-time <TIME>after the last commit at or before TIME
a markMark(name)--at-mark <NAME>at the mark (right after the commit it points at)

Every commit is a target, not only snapshots and marks. A target is resolved the same way for every action: the nearest snapshot at or before it is loaded and the WAL is replayed up to the target, following the lineage chain across forks and in-place rollbacks. A target needs the snapshot and WAL that lead to it: after a prune, targets before the oldest kept snapshot are gone (PersistError::TargetNotReached).

The time format

TIME is an RFC 3339 / ISO 8601 date-time with a zone, or microseconds since the Unix epoch:

2026-10-08T02:43:00Z          UTC
2026-10-08T02:43Z             seconds may be left out
2026-10-08T04:43:00+02:00     an offset
2026-10-08T02:43:00.250Z      a fraction of a second
1760000000000000              microseconds since 1970-01-01T00:00:00Z
  • A time without a zone is refused (it would depend on the machine's time zone), and so is a bare date: a day is not a moment, and whether its start or its end is meant, in which zone, changes the target. The error shows the explicit forms (the same text in the CLI and the dev server's {"time": ..}):

    --at-time: "2026-10-08" is a date without a time and a zone, which is refused (it names no moment): write 2026-10-08T23:59:59Z for the end of that day in UTC, or with an offset, e.g. 2026-10-08T00:00:00+02:00 for its start at UTC+02:00 (RFC 3339)
    

    Python takes a time only as microseconds since the epoch (time=), so no text is parsed there.

  • A time covers the whole second (or minute) it names: 2026-10-08T02:43Z means up to 02:43:59.999999. So a time copied from store list or store marks, which print whole seconds in this format, includes the commit printed with it.

  • Times are printed in UTC (2026-10-08T07:05:08Z). The dev server's Go to time... takes a date and time in the browser's time zone.

What you can do with a target

ActionLibraryCLIDev server (Store menu)
look at it, read-onlyStore::open_read_only(dir, target), store.read_only_at(target)fork it, then open the forkOpen read-only here
branch it into a new storestore.fork(target, new_dir)graphersal store fork <DIR> <NEW_DIR> TARGETFork to a new directory...
take THIS store back to itstore.rollback_to(target, mode)graphersal store rollback <DIR> TARGETRoll back here...

Read-only views

use graphersal::persist::{RecoveryTarget, Store};

let past = Store::open_read_only("data", RecoveryTarget::CommitSeq(12))?;
println!("commit {}: {} vertices", past.report.commit_seq, past.graph.vertex_count());
let mut graph = past.graph;                  // an unpublished TraversalGraph: query it, export it
let names = graph.traversal_mut().v(None::<()>).values("name").to_list()?;
Ok::<(), Box<dyn std::error::Error>>(())

Store::open_read_only takes no lock and works while a writer has the store open, also on a backup. It returns the graph with a RecoveryReport; the graph has no journal, so changes to it are not stored anywhere (attach a journal only as a new history: a new lineage). A commit after the end of the history, or a mark that does not exist, is an error (PersistError::TargetNotReached); a time after the last commit is the latest state.

In the dev server, Open read-only here makes the server serve that state instead of the live graph: queries, the drawing, the schema and the statistics show it, every write is refused ("the served state is a read-only view at commit N ...: writes are refused"; its help points to Back to the live graph and to a fork), and a banner offers Back to the live graph. The view is shared by every browser tab and the MCP agent. See Dev Server and MCP.

Fork

A fork makes a past (or the current) state of a store into a new, writable store in another directory. The source store is not changed; to undo a fork, delete the new directory. A fork of an open store waits while a rollback moves files; while it runs a rollback or a prune of that store is refused.

use graphersal::persist::{RecoveryTarget, Store, StoreOptions};

let store = Store::open("data", StoreOptions::new())?;
let report = store.fork(RecoveryTarget::Mark("before-import".into()), "branch")?;
let info = &report.snapshot;
println!("forked at commit {}: graph {:032x}, parent {:032x}",
         info.commit_seq, info.graph_id, info.parent_graph_id);
for mark in &report.marks_not_carried {
    println!("mark not carried: {} @ commit {}", mark.name(), mark.commit_seq());
}
let branch = Store::open("branch", StoreOptions::new())?;
// Without opening the source (works while a writer has it open):
Store::fork_dir("data", RecoveryTarget::CommitSeq(2), "branch2")?;
Ok::<(), Box<dyn std::error::Error>>(())
$ graphersal store fork data/ branch/ --at-mark before-import
Forked into branch/ at commit 1: graph 01a11a54-87d2-7995-b2cb-e450e4319735 (parent 01a11a54-8209-7661-92e2-147ae6d8bbd3).
Marks not carried (1; they stay targets of data/ only):
  before-import @ commit 1
Open it: graphersal --graph branch/ --server (or the REPL: graphersal --graph branch/).
data/ is unchanged; to undo the fork, delete the directory branch/.
  • The target is any point in time; without one, the latest state.
  • The new store has a new lineage id that records its parent and the commit it branched at (graphersal store info branch/ shows parent and branched at), one snapshot at the target, and an empty WAL. It keeps the source's chunk size and damage policy, but it is another store with its own store id: it never continues the source's incremental backups (back it up into a new directory).
  • Marks are not carried: the new lineage starts without marks (they are names in the source's history, which the fork does not copy). The ForkReport (marks_not_carried), the CLI (Marks not carried ..., one name @ commit N line each), Python ("marks_not_carried") and the dev server (marksNotCarried) list the source's marks at or before the fork's position; they stay targets of the source store. Set them again in the fork if you need them there (store.mark(..), graphersal store mark).
  • NEW_DIR must not exist (or be empty). A fork of a single-file store can be a .gstore file (the dev server names it <store>-fork-<target>.gstore next to the source).
  • A fork reads the source without any lock: it works while a dev server or a REPL has the source open, and on a backup (the way to get a writable copy that leaves the backup as it is).
  • A fork of a past state is how you continue writing from it without touching the source. To take the source itself back, use an in-place rollback.
  • An attic entry can be forked too: store.attic_fork(id, dir), graphersal store attic <DIR> fork <ID> <NEW_DIR>. Its report lists the marks of the entry's history (the store's before the rollback target, the entry's own after it), not carried either.

Python: store.fork("branch", mark="before-import") (or commit_seq=, time= in microseconds) returns the snapshot's dict plus "marks_not_carried": [{"name", "commit_seq"}].

Rollback and the Attic

An in-place rollback takes the store itself back to a commit, a time or a mark. Everything after the target is not deleted: it moves into the attic, so the rollback can be undone.

use graphersal::persist::{RecoveryTarget, RollbackMode, Store, StoreOptions};

let store = Store::open("data", StoreOptions::new())?;
let report = store.rollback_to(RecoveryTarget::Mark("before-import".into()), RollbackMode::Move)?;
println!("{} -> {}", report.previous_commit_seq, report.target);
let id = report.attic.unwrap();
for change in store.attic_changes(&id)? {               // what was rolled back
    println!("{}", change?.commit_seq());
}
store.attic_restore(&id)?;            // undo the rollback (only while nothing was committed since)
// store.attic_fork(&id, "branch")?;  // or: the rolled-back history as a new store
// store.attic_remove(&id)?;          // or: delete it for good
Ok::<(), Box<dyn std::error::Error>>(())
$ graphersal store rollback data/ --at-mark before-import
Rolled back from commit 4 to commit 1: new lineage 01a11a54-8977-7c30-b874-01937ab2e3a4.
The history after it (commits 2..=4, 1 snapshot(s), 2 WAL file(s)) is in the attic as 20261008T070510Z-00000000000000000002.
Undo (only while nothing new is committed or marked): graphersal store attic data/ restore 20261008T070510Z-00000000000000000002
Keep it as a new store instead: graphersal store attic data/ fork 20261008T070510Z-00000000000000000002 <NEW_DIR>; delete it: graphersal store attic data/ remove 20261008T070510Z-00000000000000000002

What a rollback does

  • Everything after the target (the later snapshots and the WAL after it; the WAL segment holding the target is split at the first commit after it) moves into attic/<time>-<first moved commit>/, with an ATTIC file that says what it is.
  • The store continues as a new lineage: a new graph_id whose parent is the old one at the target, with a new WAL segment. Point-in-time loads and verify follow the lineage chain, so the history before the target stays reachable.
  • The marks after the target go with the history into the attic.
  • store.graph() is replaced in place: the Arc<Graph> your application holds now holds the state at the target, and the commit hooks you registered on it stay.
  • RollbackMode::Delete (CLI --delete) deletes the history instead: there is no undo.
  • The rollback runs under an INTENT file with idempotent steps: a crash in the middle is completed at the next open, never left half done. Commits wait while it runs. A backup, a verification, a fork or an export started meanwhile waits for it too.
  • A rollback, an attic restore and an attic remove are refused at once (FilesInUse) while a backup, a verification, a fork or an export reads the store's files, in this or another process: they would move files away under it. Nothing was changed; run it again when that has finished.
  • Refused: a target at or after the current commit ("there is nothing after commit N"), a target before the oldest retained snapshot, a store that is a backup, read-only or in maintenance mode. From the CLI the store must not be open elsewhere ("in use"); with a dev server running, use its Store menu (Roll back here...), which cancels a running query first.

The attic

$ graphersal store attic data/
20261008T070510Z-00000000000000000002  commits 2..=4 rolled back at 2026-10-08T07:05:10Z (rollback to mark "before-import"), 9.3 KiB, 1 snapshot(s)
$ graphersal store attic data/ changes 20261008T070510Z-00000000000000000002
commit        2  2026-10-08T07:05:08Z  1 mutation(s)
commit        3  2026-10-08T07:05:08Z  1 mutation(s)
commit        4  2026-10-08T07:05:09Z  1 mutation(s)
OperationLibraryCLI
list the entriesstore.attic_list(), Store::attic_list_dir(dir)store attic <DIR>
the commits of an entry (who, when, what)store.attic_changes(id) (ChangeSets)store attic <DIR> changes <ID>
undo the rollbackstore.attic_restore(id)store attic <DIR> restore <ID>
can it still be undone, and why notstore.attic_can_restore(id)(the restore says why)
the rolled-back history as a new storestore.attic_fork(id, dir), Store::attic_fork_dir(..)store attic <DIR> fork <ID> <NEW_DIR>
delete it for goodstore.attic_remove(id)store attic <DIR> remove <ID>
  • Restore brings the store back to where it was before the rollback (the old lineage, the moved snapshots and WAL, the marks). It is possible only while nothing was committed or marked since the rollback; after that, attic_fork still keeps the rolled-back history as a new store.
  • prune never removes the snapshot an attic entry is based on; remove the entry first. The attic is not part of a backup.
  • Every entry stays whole, whatever you do afterwards: a later rollback to a commit before an entry's history copies the WAL that entry needs into it first (and points it at its own base snapshot; the entry's own snapshots may go then, its WAL rebuilds them), so no entry ever depends on another. Removing one never touches another. verify rebuilds every entry's history. Several rollbacks restore newest first (see Restore order).
  • A rollback or restore that fails half way (a full disk, an I/O error) stops the store: it writes nothing more (commits, marks, checkpoints, prune, rollback and restore are refused with the cause stopped, and closing it writes no GRAPH) until it is closed and opened again; the open completes the operation from its INTENT (or undoes it). The reason is in store.stopped_reason(), StoreInfo::stopped and the Store menu (Store stopped).
  • If the files were changed but loading the new state into the open graph fails (an I/O error, damage, out of memory, a storage refusing the data), the graph in memory is emptied, never left half-loaded: queries read an empty graph rather than plausible but incomplete data. The error (cause reload_failed) says that the reload after the rollback or restore failed, with its cause, that the graph was emptied and the store stopped, and that the files on disk are intact. Close the store and open it again (restart the dev server): the open completes the change and loads the full graph.

Restore order

After several rollbacks, attic entries restore newest first. This is a deliberate rule (by design), not a limitation to be lifted:

  • An entry can be restored into the live store only while the store is on the lineage that entry's rollback started. A newer rollback starts another lineage, so the older entry becomes restorable again once the newer rollbacks are undone (restored) one by one, newest first. Each restore brings back exactly the lineage the next older entry needs.
  • Any entry forks at any time (attic_fork, graphersal store attic <DIR> fork <ID> <NEW_DIR>): the history of an older entry is never out of reach, it only cannot be restored in place out of order.
  • A restore out of order is refused, changes nothing, and names the newer entry to restore first:
$ graphersal store rollback data/ --at-commit 4        # entry ...-05: commits 5..=6
$ graphersal store rollback data/ --at-commit 2        # entry ...-03: commits 3..=4
$ graphersal store attic data/ restore 20261009T010700Z-00000000000000000005
Error: Cannot restore the attic entry: the store's lineage changed since that rollback (another
rollback or restore; attic entries restore newest first); restore the newer entry
20261009T010702Z-00000000000000000003 first, or fork the entry instead (the help shows the commands)
Help: Another rollback or restore came after this entry's rollback, and attic entries restore newest first: ...
        # restore the newer entry first (the message names it)
        graphersal store attic <dir> restore <newer_id>
        # or fork this entry into a new store
        graphersal store attic <dir> fork <id> <new_dir>
$ graphersal store attic data/ restore 20261009T010702Z-00000000000000000003   # back at commit 4
$ graphersal store attic data/ restore 20261009T010700Z-00000000000000000005   # back at commit 6

The rule keeps restores simple and safe: a restore always puts back one whole, consistent history on top of the lineage it branched from, never a mix of lineages.

How to undo what

You didUndo
a rollback (attic mode)attic_restore(id) / graphersal store attic <DIR> restore <ID> / Store menu > Attic > Restore, as long as nothing was committed or marked since. After that, attic_fork keeps the rolled-back history as a new store
a rollback with --deletenothing: the history is gone (restore a backup)
a forkdelete the new directory (the source store is not changed)
an attic restoreroll back again to the same target

graphersal store rollback and store fork print these commands after they ran.

Backup and Restore

A backup is a consistent copy of the store's files, taken without any graph lock: writers go on while it copies. It holds the latest snapshot and the WAL after it, up to the last durable commit (a commit whose fsync completed). While it copies, the files are pinned against prune. Every checksum of what it copies is read in the store first and again in the copy: a backup never copies damage silently, and never leaves a copy that does not read back (see Every checksum, twice).

A backup also holds the store's embedding models with their licence files (checked like the rest; BackupReport::models lists them), so a restored store opens with its models. Store::backup_zip_with(archive, ModelCopy::Exclude) (CLI store backup --zip --without-models) leaves them out of a ZIP archive meant to be handed on.

A backup of a layer store (a project layer over a frozen base, Layered Graphs) works the same way and restores into a layer store over the same base, but it holds only the layer's changes: it is useless without that very base (the same graph at the same commit). BackupReport::layer_base names the base and BackupReport::warnings says so (graphersal store backup prints it as a warning). Keep the base with its backups, or export a standalone copy of the whole graph the layer shows with Store::export_materialized (a plain .gsnap, readable without the base).

use graphersal::persist::{BackupMode, RecoveryTarget, Store, StoreOptions};

let store = Store::open("data", StoreOptions::new())?;
store.backup("backup")?;                          // an empty or new directory: a FULL backup
// ... commits ...
let report = store.backup("backup")?;             // the same directory again: an INCREMENT
println!("{} -> {} ({} bytes)", report.previous_commit_seq, report.commit_seq, report.bytes);
store.backup_with("weekly", BackupMode::Full)?;   // always full (the directory must be empty)

let past = Store::open_read_only("backup", RecoveryTarget::CommitSeq(3))?;  // any commit it holds
Store::restore_backup("backup")?;                 // the original is lost: continue from the backup
let live = Store::open("backup", StoreOptions::new())?;
Ok::<(), Box<dyn std::error::Error>>(())
graphersal store backup data/ /mnt/backup/data       # full the first time, incremental afterwards
graphersal store backup data/ /mnt/backup/data       # "nothing new since commit N" when current
graphersal store backup data/ weekly/ --full         # always full (an empty or new directory)
graphersal store backup data/ data.zip --zip         # one ZIP archive (always full)
graphersal store info /mnt/backup/data               # "backup  up to commit N, taken T"
graphersal store prune /mnt/backup/data --up-to 5000 # the backup's own retention
graphersal store restore /mnt/backup/data            # make it the live store (same graph id)
graphersal store restore data.zip restored/          # unpack a ZIP backup as the live store
$ graphersal store backup data/ backup/
Full backup into backup/
  snapshot: commit 3
  WAL: up to commit 3
  WAL segments copied: 1
  files: 8
  bytes: 9605

The backup backup/ is read-only
  # open it read-only in the REPL
  graphersal --graph backup/
  # make it the live store
  graphersal store restore backup/
$ graphersal store backup data/ backup/
Incremental backup into backup/
  commits: 4..4 (1 new)
  snapshots copied: 0
  WAL segments copied: 0
  bytes appended to the last segment: 83
  bytes: 83

The backup backup/ is read-only
  ...

Store::backup_dir(dir, target) (and backup_dir_with, backup_zip_dir) back up a store without opening it: a backup works while a dev server or another program has the store open.

Every checksum, twice

A backup (full, increment, ZIP) checks everything it copies in the store before it writes anything: both GRAPH copies, the marks file, the snapshot (manifest, schema.json, every segment and chunk, the files it references) and every WAL record (header and body checksum, the segment headers, commit continuity, a missing or emptied newest segment). After writing it reads the copy back the same way; a ZIP archive is read back entry by entry through the same handle (backup_zip takes Read + Write + Seek: a file opened for reading and writing, a Cursor<Vec<u8>>).

  • Damage in the store stops the backup before a byte is written: PersistError::BackupDamaged with side: DamageSide::Store and the problems as verify lists them (file, byte, reason). Repair the store, never the backup: graphersal store repair <dir> --to <new_dir>. While the store is open in a process whose graph is intact (the dev server, a Python program), save that graph first with a backup from memory.
  • A copy that does not read back (a bad backup disk) is side: DamageSide::Backup: a new backup directory is removed, an increment is rolled back to the backup's old state. The store is fine; check the backup's disk and back up again.
  • Redundant metadata (one GRAPH copy, one copy of a manifest's fixed part, the derived marks file) is a warning (BackupReport::warnings, printed by the CLI): the backup is intact (two fresh GRAPH copies, the manifest with the intact copy in both places, marks rebuilt from the WAL it holds). Plan a repair of the store.
  • In an open store, damage a backup finds is damage found while the store is open: the store's damage policy applies (by default it turns read-only).
$ graphersal store backup data/ backup/
Error: The backup stopped: the store data/ is damaged: wal/00000000000000000001.wal at byte 64: record of commit 1: checksum mismatch; nothing of the backup into backup/ was kept
Help: Repair the MAIN store, never the backup: Store::repair_dir builds a verified, repaired copy in a new directory and reports what was repaired, lost and diverged; the damaged files are never changed. Existing backups stay valid: keep them until the repaired store is backed up.
        # build a repaired copy of the main store
        graphersal store repair data/ --to <new_dir>
        # show the full damage report
        graphersal store verify data/

A backup from memory

When damage was found while the store is open (by a backup, a checkpoint, verify), its graph in memory is still intact: it was verified when the store was opened and changed only by commits since. store.backup_from_memory(target, mode) writes that graph into a backup directory with the streaming encoder (under the graph's read lock; commits wait meanwhile) and reads or writes nothing in the store's directory:

  • one snapshot at the graph's commit, an empty WAL segment after it, GRAPH with the backup marker and the store's identity, lineage and creation parameters;
  • into an empty or new directory a full backup; into a backup of the same store an increment (its snapshot is newer than everything the backup holds; a later normal increment of it needs a full backup and says so);
  • the result is an ordinary backup: graphersal store restore <dir> makes it the live store (same graph id), store fork a new one. Marks are not carried (like a fork).

It is refused while no damage was found (a normal backup is the right tool and checks every checksum), for a store opened in maintenance mode (its graph was salvaged from donors: use repair_to) and for a backup opened read-only. Where: Rust Store::backup_from_memory; the dev server's Store menu (Back up from memory) and POST /api/store/backup {"from_memory": true}; Python store.backup(path, from_memory=True). The graphersal store backup command runs in a new process, so --from-memory there explains where to do it.

store = graphersal.Store.open("data")
try:
    store.backup("/mnt/backup/data")
except graphersal.GraphersalError as err:          # "the store data is damaged: ..."
    store.backup("/mnt/backup/saved", from_memory=True)

A backup is marked and read-only

A backup's GRAPH file says "a backup of graph X up to commit N, taken at T". It keeps the original's graph_id and lineage. It opens read-only: Store::open refuses it (PersistError::IsBackup), so nothing writes to it by accident.

  • Store::open_backup(dir, options) is a read-only Store over it: info, listings, views at any commit it holds (read_only_at), fork, verify, export and backups of it work; every write is refused. store.backup_marker() returns the marker.

  • Store::open_read_only(dir, target) loads any commit it holds.

  • graphersal --graph backup/ (REPL, -e, --server) opens it read-only with a note:

    note: backup/ is a BACKUP: opened READ-ONLY, writes are refused
      backup: up to commit 4
      taken: 2026-10-08T07:05:09Z
      # make it the live store
      graphersal store restore backup/
      # or make a writable copy
      graphersal store fork backup/ <new_dir>
    
  • The dev server shows a "Backup: read-only" banner; its Store menu offers View and Fork only.

Restore

  • In place: Store::restore_backup(dir) (graphersal store restore <BACKUP_DIR>) clears the marker: the directory becomes the live store with the same graph id. This is the case "the original is lost, continue from the backup". Stop anything that has the backup open first.
  • As an independent copy that leaves the backup as it is: fork it (graphersal store fork backup/ copy/, a new graph id).
  • From a ZIP (persist-zip): Store::restore_zip(reader, dir) (graphersal store restore data.zip restored/) unpacks it as the live store (unpacking is the explicit restore).

Incremental backups

A backup into a directory that holds a backup of the same store copies only what the backup does not hold yet:

  • newer snapshots, new WAL segments, and the new end of its last WAL segment, after checking that the backup's WAL is a prefix of the store's (the last record's frame);
  • every file it copies is checked in the store first and read back in the backup (every chunk and record checksum), and the commits must continue the backup's without a gap or an overlap;
  • the increment runs under an INTENT file in the backup directory: interrupted (a crash, a full disk), it is rolled back at the next backup, restore or prune of the backup. The backup is a valid store after every step;
  • the BackupReport says what was copied (previous_commit_seq, commit_seq, snapshots_copied, segments_copied, tail_bytes, bytes, lineage_changed); with nothing new it copies nothing.

After an in-place rollback of the store, the next increment follows the store's new lineage when the rollback's target is at or after the backup's position. A rollback behind the backup's position is refused: the backup holds history the store moved to its attic, so it is kept as it is, the archive of the abandoned history; take a full backup into a new directory (--full) for the new one. "Behind" counts every rollback since the backup: a rollback of a later lineage to before that lineage's own start branches from the backup's lineage at that earlier commit. An attic restore re-splits the WAL segment the rollback cut, so the next increment may find its last segment no longer a prefix of the store's and asks for a full backup.

Only the same store continues a backup. Every store has a store id (creation parameter), recorded in each of its backups; an increment requires the same one. A fork, an attic fork, a repair or a store convert copy shares the original's lineage history up to the copy, but it is a different store with a new id: its increment into the original's backup is refused, take a full backup into a new directory. An in-place rollback, an attic restore and a restored backup (store restore, from a directory or a ZIP) keep the id: a restored backup is the store and continues its other backups.

Refused

PersistError::BackupRefused leaves the backup unchanged. It is returned for:

  • a backup of another graph;
  • a backup of a different store: a fork, repair or copy of the backed-up store (its store id differs; above);
  • a directory that holds a store that is not a backup (a live store is never written to);
  • a non-empty directory without a store, or --full into a non-empty directory;
  • a rollback of the store behind the backup's position (above);
  • a pruned gap: the store's prune removed WAL the backup still needs. Backups do not pin the store's WAL against prune: back up more often than you prune, or take a full backup into a new directory.

Retention of backups

A backup has its own retention: Store::prune_backup(dir, up_to) (graphersal store prune <BACKUP_DIR> --up-to N) prunes it by the store's rules (the last two snapshots stay); the next increment continues it. Keep several generations by backing up into several directories (for example one per week with --full).

ZIP archives

With the persist-zip feature, store.backup_zip(archive) writes a full backup as one archive: stored entries (the chunks are already compressed), zip64, every file's CRC. The archive is read back through the same handle and checked (every entry's CRC-32, every checksum of the store files in it), so it takes Read + Write + Seek: a file opened for reading and writing, or a std::io::Cursor<Vec<u8>> for an upload. The archive's GRAPH carries the backup marker; Store::restore_zip clears it. ZIP backups are always full. The CLI refuses an existing target file and removes the archive when the backup fails.

What is not in a backup

The attic (rolled-back history), the LOCK and BACKUP lock files, and any commit after the durable end at the moment of the copy (it is in the next increment).

Prune, Compact and Retention

Nothing is deleted implicitly. Snapshots and WAL accumulate until you remove old history explicitly, the way a database VACUUM or a WAL archive cleanup is explicit. A store therefore grows with every commit and checkpoint; prune and compact give the space back.

Prune

use graphersal::persist::{Store, StoreOptions};
let store = Store::open("data", StoreOptions::new())?;
let report = store.prune(1200)?;          // history only needed for targets before commit 1200
println!("kept from commit {}; removed snapshots {:?}, {} WAL segment(s)",
         report.kept_from, report.snapshots_removed, report.segments_removed.len());
Ok::<(), Box<dyn std::error::Error>>(())
# prune: "Pruned data/" with "kept from: commit N", "snapshots removed", "WAL segments removed"
graphersal store prune data/ --up-to 1200
graphersal store prune data/                 # refused: "needs --up-to <COMMIT> (nothing is pruned implicitly)", exit 2

prune(up_to) removes the snapshots and WAL segments that only serve targets before up_to. What it keeps:

  • the newest snapshot at or before up_to, everything after it, and the WAL from it on;
  • always the last two snapshots and the WAL between them, whatever up_to says: these are the donors a repair rebuilds damaged data from;
  • the base snapshot of every attic entry (remove the entry first).
  • the segment files of removed snapshots that kept ones still use: a merged checkpoint references the segment files it did not change in the older snapshot's directory. Such a directory loses its manifest (it is no snapshot any more) and keeps only those files (report.files_retained); a later prune removes them once no kept snapshot, and no snapshot of an attic entry, uses them.

Every snapshot it keeps is verified (read back, every checksum) before anything is deleted, and the removal runs under an INTENT file (an interruption is completed at the next open). Prune is refused while a backup, a verification, a fork or an export reads the store's files, and on a store open elsewhere ("in use": use the dev server's Store menu > Compact, which prunes up to the current commit).

After a prune, point-in-time targets before the oldest kept snapshot are gone, and changes_since cannot read before it. An incremental backup that still needs the removed WAL is refused (a full backup is needed): back up before you prune.

The last two snapshots never share a segment file (the donor rule), so each is the other's independent copy for a repair. Holder files that nothing uses any more (after a rollback with --delete, or after removing the attic entry whose snapshots used them) are removed by that operation itself.

A backup has its own retention: Store::prune_backup(dir, up_to), or graphersal store prune on the backup directory.

Prune and marks

Prune does not look at marks: a mark before the oldest kept snapshot loses the history it needs and becomes unreachable. The report names those marks (report.marks_unreachable; graphersal store prune prints marks no longer reachable: ... (their history was pruned)), and so does the compaction advice before anything is removed (advice.prune.marks_unreachable, the Store menu's Disk space block), so look there before compact. From then on the listings (store.marks(), store marks, store info, the Store menu) leave such a mark out, opening it fails with "a prune removed the history it needs", and its name stays taken. The marks file itself keeps every mark: a backup with older snapshots of its own still reaches them and lists them.

The library calls (Store::prune, Store::compact, Python store.prune()/store.compact()) never ask: they report the marks afterwards. To ask first, read the estimate: Store::prune_estimate_dir(dir, up_to) (any bound, no lock, nothing removed) or store.compaction_advice() (a Compact, up to the current commit). The front ends guard every prune with it, so a mark is never lost without a question:

Front endGuard
CLI store prune, store compactnames the marks, changes nothing and exits 1 unless --drop-marks is given (store CLI)
store compact-advicelists them (marks lost ...) and suggests --drop-marks
Dev server POST /api/store/compact409 {"error", "marksUnreachable": [...]} unless the body has {"dropMarks": true} (dev server)
Playground Store menu, Compact (server and WebAssembly)always asks when marks would become unreachable, recommended or not, naming them; sends dropMarks only after the confirmation

Compact

use graphersal::persist::{Store, StoreOptions};
let store = Store::open("data", StoreOptions::new())?;
let report = store.compact()?;            // prune up to the current commit, then the backend's compaction
println!("{} bytes given back", report.bytes_freed());
Ok::<(), Box<dyn std::error::Error>>(())

compact() is prune(current commit) followed by the backend's compaction: a single-file store copies its live data into a new file next to the old one and replaces it atomically (like SQLite's VACUUM: the disk needs room for the live data meanwhile, and commits wait while it runs). On a directory (or in memory) the prune is all: its removals free the space at once.

$ graphersal store compact data/
Compacted data/
  kept from: commit 0
  snapshots removed: 0
  WAL segments removed: 0
  file: a directory store: the prune gave the space back (nothing to compact)
$ graphersal store compact graph.gstore
Compacted graph.gstore
  kept from: commit 0
  snapshots removed: 0
  WAL segments removed: 0
  file: 23.7 KiB -> 22.8 KiB (930 B given back)

Is it worth it? The compaction advice

Whether a compaction is worth it is a cheap question to ask, as often as you like, from any thread, while the store is in use:

use graphersal::persist::{CompactionPolicy, Store, StoreOptions};
let store = Store::open("graph.gstore", StoreOptions::new())?;
let advice = store.compaction_advice()?;
if advice.recommended {
    let report = store.compact()?;                  // prune + rewrite
    println!("gave back {} bytes", report.bytes_freed());
} else {
    println!("not now: {}", advice.reason);         // which threshold decided, and why
}
// Another rule for one call, or for the store (StoreOptions::with_compaction_policy):
let eager = CompactionPolicy::new()
    .with_min_garbage_ratio(0.3)
    .with_min_reclaimable_bytes(16 << 20)
    .with_min_total_bytes(0);
let advice = store.compaction_advice_with(eager)?;
Ok::<(), Box<dyn std::error::Error>>(())
$ graphersal store compact-advice graph.gstore
no compaction needed: the store is smaller than the minimum of 64.0 MiB
  store: 23.0 KiB (single file)
  live: 23.0 KiB
  garbage: 0 B (0 %)
  prune: 0 B
  reclaimable: 0 B (0 % of the store)
  disk needed: 23.0 KiB
  disk free: 77.4 GiB
  decided by: total_bytes

CompactionAdvice carries the numbers behind the answer: the store's total, live and garbage bytes, what a prune would remove first (prune_first, prune_bytes, the snapshots and WAL segments in prune), the bytes a compaction gives back in all (reclaimable_bytes), the free disk space it needs and the free space there is, and the marks a prune would make unreachable (prune.marks_unreachable). It reads no element data: only the backend's bookkeeping, the names and sizes of the store's files (snapshot directories and WAL segments alike), and, only when a prune would remove something, the small manifests of the kept and the attic snapshots (the files they still reference stay and are not counted, so prune_bytes is what the prune removes) and the marks file when a snapshot would go. It is never recommended while the store cannot change (maintenance mode, a backup, closed) or when the disk lacks the space. decided_by names the rule that decided, checked in this order:

decided_bymeaning
not_writablethe store cannot change now
total_bytesthe store is smaller than min_total_bytes (default 64 MiB; CLI --min-size)
reclaimable_bytesless than min_reclaimable_bytes to gain (default 64 MiB; --min-reclaimable)
garbage_ratioless than min_garbage_ratio of the store to gain (default 0.5; --min-ratio)
disk_spacethe file system lacks the free space the new file needs (skipped where the free space is unknown, free_space: None: on Windows today)
thresholds_metrecommended: compact now

The defaults are conservative. For a directory store (or one in memory) the advice is about the prune only (compactable is false, garbage_bytes 0). StoreOptions::with_auto_compact(true) compacts after every prune() whose advice recommends it (off by default).

A retention routine

  1. Take a backup (incremental is cheap): graphersal store backup data/ /mnt/backup/data.
  2. graphersal store verify data/ (do not prune a store with damage: the old snapshots are its donors).
  3. Prune what you no longer need to reach: graphersal store prune data/ --up-to <COMMIT> (store list shows the snapshots and their commits; store compact prunes to now).
  4. On a single file: graphersal store compact-advice graph.gstore, then compact when it says so.

Verify

verify is the store's scrub: it reads every byte the store holds and checks it. It also checks every embedding model the store keeps (each file's size and SHA-256 against the model's manifest, VerifyReport::models_checked): a damaged model is a problem under models/<id>/, but it never makes an open store read-only (it is no graph data); remove it and add it again. On a writable store a verification waits while a rollback or a prune changes files, and a rollback, an attic change or a prune is refused while it reads.

A layer store (Layered Graphs) holds only a layer's changes to a frozen base, so its snapshots load only over that base: store.verify() of an open layer store and Store::<LayeredGraph>::verify_layer_dir(dir, &base) load every snapshot over it, while Store::verify_dir (CLI store verify) checks a layer store without its base: every checksum, every layer file decoded against its manifest row, the snapshots not loaded (a note says so). The model blobs its catalog names are the base's: a note, not a problem.

use graphersal::persist::{Store, StoreOptions};
let report = Store::verify_dir("data")?;              // or store.verify() on an open store
println!("{} snapshot(s), {} WAL record(s), commits {}..{}",
         report.snapshots_checked, report.records_checked, report.first_commit, report.last_commit);
for problem in &report.problems {
    println!("DAMAGE: {} at {:?}: {}", problem.path, problem.offset, problem.reason);
}
assert!(report.is_ok());
Ok::<(), Box<dyn std::error::Error>>(())
$ graphersal store verify data/
2 snapshot(s), 2 WAL segment(s), 5 record(s), commits 1..3
ok: no damage found

It checks:

  • both GRAPH copies, and the lineage chain;
  • every snapshot: the manifest (both copies of its fixed part), schema.json, every segment's length and checksum, every chunk's checksum against the manifest's chunk index, and every element decoded (ids in order, ranges not overlapping);
  • every WAL record's checksums, commit continuity (each commit is the previous + 1, along the lineage chain), the set of WAL segments against GRAPH (a missing, emptied or replaced newest segment, a segment whose header does not match its name, a clean close the files do not reach);
  • every attic entry: its history is rebuilt (its base snapshot and the WAL after it), its snapshots verified;
  • the marks file;
  • the donor rule: a segment file the newest snapshot shares with the previous one is a warning (report.without_donor, also a note), not damage: that id range has no independent donor until the next checkpoint copies it.

On damage, the CLI prints every problem and the damage report with the donor of each damaged item, and exits with 1:

$ graphersal store verify damaged/
Checked the store damaged/
  snapshots: 2
  WAL segments: 2
  records: 3
  commits: 1..2
DAMAGE: wal/00000000000000000002.wal: Corrupt journal 1 at byte 188: record of commit 3: checksum mismatch
DAMAGE: wal: the store was closed cleanly at commit 3, but its files end at commit 2
2 damaged item(s); readable state: snapshot 1 + WAL at commit 2; a repair LOSES data (see the items without a donor)
  DAMAGE wal/00000000000000000002.wal at byte 188: record checksum mismatch; 83 bytes up to the next valid record; commits from 3 on; no donor: LOST
  ...
Error: 2 problem(s) found
Help: keep the store's files (do not prune); build a repaired copy, restore a backup, or fork a target before the damage
        # build a repaired copy in a new directory
        graphersal store repair damaged/ --to <NEW_DIR>
  • verify takes no lock and changes nothing: run it while a dev server or another program has the store open, and on a backup.
  • A normal open checks only what it loads (the latest snapshot, the WAL after it, GRAPH); verify checks everything, including the older snapshots that are the donors of a repair. Run it regularly (a nightly job, before a prune, after copying a store): it finds damage while donors still exist.
  • Notes (note: ...) are not damage: for example a repaired copy of redundant metadata.
  • The dev server's Store menu has Verify the store, the playground too (POST /api/store/verify); Python store.verify() returns {"ok", "problems", "notes"}.

Damage, Maintenance and Repair

A disk that starts to rot in random places must not lose committed data silently. The store detects damage, locates it, keeps everything readable that is intact, and repairs from donors that already exist, into a new directory.

Detection

  • Every header, chunk and WAL record carries a CRC-32C; the manifest keeps the id range and CRC of every chunk, so a damaged chunk's elements are known even when its segment is damaged.
  • GRAPH exists twice (GRAPH, GRAPH.copy), and so does each manifest's fixed part (at its head and tail). Damage to one copy loses nothing: a read uses the intact copy, and verify reports the damaged one (a DAMAGE item whose donor is "the other copy", exit 1). A read-write open rewrites both GRAPH copies from the intact one and records that in OpenReport::graph_file_repaired (the CLI, its store commands and the dev server print it as one note: line on stderr); a backup copies the intact one and warns.
  • WAL records carry a sync marker and their commit number outside the payload, so a reader resynchronises after a damaged record; a separate header checksum tells a damaged length from an interrupted write.
  • Only an incomplete last record of the last WAL segment is a torn tail (an interrupted write, cut at the next open). A complete record with a bad checksum, anywhere, is damage, never cut. A lost, emptied or replaced newest WAL segment, or a cleanly closed store whose files end earlier, is damage too: never a silently shorter history.
  • prune always keeps the last two verified snapshots and the WAL between them: the donors.
  • What a newer Graphersal wrote is never damage (format spec 16 rule 9): an unknown value in a catalog definition (a compression codec, an index type or element kind, a saved query's parameter schema) keeps the definition, not served; a graph schema this version cannot parse opens the store read-only (the data without the schema, no damage report); an unknown interrupted operation or store state is refused with Unsupported content ... written by a newer Graphersal, not damage. Such a store is never repaired by this version (a repair would drop what it cannot read): open it with the newer version. verify lists newer content as a note:, not as a problem.

Maintenance mode

Opening a store with damage does not fail and does not repair. It opens read-only in maintenance mode with a DamageReport (store.maintenance()):

$ graphersal --graph damaged/ -e 'g.v().count().next()'
warning: the store damaged/ has DAMAGE and opened READ-ONLY in maintenance mode: queries read the intact data, writes are refused.
2 damaged item(s); readable state: snapshot 1 + WAL at commit 2; a repair LOSES data (see the items without a donor)
  DAMAGE wal/00000000000000000002.wal at byte 188: record checksum mismatch; 83 bytes up to the next valid record; commits from 3 on; no donor: LOST
  DAMAGE wal: the store was closed cleanly at commit 3, but its files end at commit 2; commit 3; no donor: LOST
  note: the open found damage: Corrupt journal 0 at byte 188: record of commit 3: checksum mismatch
  note: built on snapshot 1 (snapshots/00000000000000000001)
Help: repair it into a new directory (the damaged files stay untouched), or restore a backup
        # build a repaired copy in a new directory
        graphersal store repair damaged/ --to <new_dir>
8
  • The report lists the damaged files, chunks and records, the element id ranges and commits affected, and for each the donor its data can come from: an older snapshot's chunks for that id range plus the WAL up to the damaged one; a later snapshot that covers a damaged WAL record; or the other copy. Items without a donor are data that only a backup still has.
  • When both GRAPH copies are damaged, the identity is rebuilt from the snapshot manifests and the WAL segment headers. They name the lineages only from the base snapshot on (the first WAL segment without one), so the report says so explicitly: note: lineage before commit N is approximate (both GRAPH copies damaged) (DamageReport::lineage_approximate_before, lineage_note(); the dev server's damage view, graphersal store verify and repair, Python repair_to(..)["lineage_approximate_before"]). Older ancestors, their branch points and times are then unknown; the data is not affected.
  • Everything readable is queryable: damaged chunks are filled in from donors, so the state you query is exactly what a repair would write.
  • Commits, marks, checkpoints, prune, rollback and compaction are refused with PersistError::Maintenance ("the store ... is in maintenance mode"). Nothing is written to the damaged store: no state change, no torn-tail cut.
  • The dev server shows maintenance mode as a banner and the damage report in its Store menu; rollback and the attic's restore and remove are refused there. Python: store.maintenance is the report text (or None).

Damage found while the store is open

Damage can appear while a store is open (a disk that rots under a running server). A backup (it reads every checksum of what it copies), a checkpoint (its merge reads the newest snapshot and the WAL after it) and verify find it. What the store then does is its damage policy, chosen when it was created and never changed (Creation Parameters):

PolicyCommitsReadsShown
maintenance (default)refused from then on (PersistError::DamageFound: "read-only: backup found damage on disk"), as are marks, checkpoints, prune, rollback, compaction; the close writes nothing but the WAL syncgo onstore.damage_found(), store.is_frozen_by_damage(), StoreInfo, a log warning; the dev server's banner and Store menu, MCP graph_info
continuego ongo onthe same, without the freeze

The damage stays reported for as long as the store is open (a repaired copy is a new store). Either way the graph in memory is intact: save it with a backup from memory (Backup and Restore), which writes nothing to the damaged store, then repair the store from its files (below), or restore the backup.

The policy does not apply to damage found when the store is opened: a store that cannot be loaded intact always opens in maintenance mode, as described above. Problems in attic entries only are reported by verify but do not freeze the store (they are history moved aside, not the store's own).

$ curl -s -X POST localhost:8080/api/store/backup -d '{}'
{"error": "Error: The backup stopped: the store data is damaged: wal/...: record of commit 7: checksum mismatch; ..."}
$ curl -s localhost:8080/api/info | jq .damageFound
{"text": "DAMAGE found on disk by backup at 2026-10-09T08:12:03Z (1 problem(s); ...): the store is READ-ONLY now (damage policy maintenance). ...", "frozen": true, "foundBy": "backup", "policy": "maintenance", "problems": 1}
$ curl -s -X POST localhost:8080/api/store/backup -d '{"dir": "saved", "from_memory": true}' | jq .backup.fromMemory
true

Repair

Repair is explicit and never in place: it writes a new, verified store in another directory (do not write more to a failing disk), and the damaged store is never changed.

use graphersal::persist::{Store, StoreOptions};
let report = Store::repair_dir("damaged", "repaired")?;   // or store.repair_to(dir) on an open store
print!("{report}");
if !report.is_lossless() { /* read report.lost_commits, lost_ranges, lost_elements, diverged */ }
Ok::<(), Box<dyn std::error::Error>>(())
$ graphersal store repair damaged2/ --to repaired2/
1 damaged item(s); readable state: snapshot 1 + WAL at commit 3; a repair keeps all data
  DAMAGE snapshots/00000000000000000000/v-000000.seg at byte 64: chunk checksum mismatch; vertex ids "1"..="6"; donor: not needed: snapshot 1 covers it
  note: built on snapshot 1 (snapshots/00000000000000000001)
Repaired store repaired2/ at commit 3 (graph 01a11a54-c795-7b87-ad5b-6e723413bc32): all data kept
  mark not carried: before-import @ commit 1
  not carried: the history before commit 3, 1 mark and the store id (backups start anew); the store it was built from keeps them

ok: all data kept
  not carried: the history before commit 3, 1 mark and the store id (backups start anew)
  kept in: damaged2/ (keep it while you need them)
  # open it in the REPL
  graphersal --graph repaired2/
  # or serve it to the browser playground
  graphersal --graph repaired2/ --server
  • Damaged snapshot chunks are rebuilt from a donor: an older snapshot's intact chunks for the same id range plus the WAL records for those elements.
  • A damaged WAL record is skipped when a later snapshot covers it. Otherwise the replay continues after the gap, and every element whose state differs from a later record's before image is reported as diverged (the later value is kept) instead of being guessed.
  • The RepairReport lists what was repaired, the lost commits and id ranges, the lost elements (for example an edge whose endpoint was lost), and the diverged elements.
  • The repaired store has a new lineage id whose chain continues the damaged store's, one snapshot named repaired, and is verified before the call returns. It is a new store with its own store id: the damaged store's backups are not continued by it (its first backup is a full one into a new directory; the old backups stay valid archives).
  • Marks are not carried: the repaired store starts without marks. RepairReport::marks_not_carried (CLI mark not carried: name @ commit N, Python "marks_not_carried") lists the damaged store's marks at or before the repaired position (as far as its marks file or WAL still yields them).
  • "All data kept" is about the data, not the history. A repair writes the readable state as one snapshot: the commits before it (rollback, views of past states, the attic), the marks and the store id stay in the damaged store, so keep that one while you may need them. Every report says so (RepairReport::not_carried, the line not carried: ...), also when no data is lost.
  • Exit code of graphersal store repair: 0 when no data was lost, 1 when data is lost or diverged (the repaired store is still written: read the lists), 2 without --to.

Runbook: "the disk started to fail"

  1. Stop writing. Stop the server or program (Ctrl+C closes the store cleanly). Do not prune: older snapshots are donors.
  2. graphersal store verify <dir>: the damage report with the donor of each item. Items without a donor are data that only a backup still has.
  3. Copy the store directory to a healthy disk if you can (cp -a); work on the copy.
  4. graphersal store repair <dir> --to <new_dir> on the healthy disk. Exit 0 and "nothing lost": switch to the new directory. Exit 1: read the lost and diverged lists; restore a backup for what is lost (or fork the backup and compare), check the diverged elements by hand.
  5. graphersal store verify <new_dir>, start using it, take a fresh full backup (the repaired store is a new lineage), and run verify regularly from now on: it finds damage while donors still exist.

Damage of a single-file store's own container records is handled the same way (DamageKind::Container). The rules that tell a torn tail from damage are normative: format specification, sections 9.6, 13 and 14.4.

Format Versions and Upgrade

Every file of the format starts with a magic and a version. There are two axes (and the single-file container has its own container version):

  • the store format version, in the store's GRAPH file: this release writes and reads version 4 (graphersal::persist::STORE_FORMAT_VERSION); graphersal store info prints it (format version 4);
  • the file format version of snapshot manifests and segments, WAL segments and packed snapshots (.gsnap): this release writes version 4 (graphersal::persist::FORMAT_VERSION) and reads versions 1 to 4.
VersionWhat changed
store 1the first store format
store 2 (0.1.0)the store identity store_id in GRAPH (offset 100), which incremental backups check
store 3 (0.2.0)the same GRAPH layout; marks a store whose files are of file format version 2, so that 0.1.x refuses it as newer instead of taking its files for damage
store 4 (0.5.0)the same GRAPH layout; marks a store that may hold blobs, their ledger and the system journal, whose embedding models are blobs referenced by catalog definitions (0.4.0 kept them as files under models/), so that 0.4.x refuses it as newer
file 1 (0.1.x)the first file format
file 2 (0.2.0)the value tags of the date and time types (date, localdatetime, datetime, time, duration) and of vectors (vector); a version 1 file is read as it is
file 3 (0.3.0)nanosecond value tags for localdatetime, datetime (with or without a zone name), time, offsettime and duration (the whole java.time.Duration range); every such value is written with them. Version 1 and 2 files are read as they are
file 4 (0.5.0)the blob reference value tag (blobref, a content-addressed file of the store), the snapshot manifest's blob table and the system journal's segments; version 1 to 3 files are read as they are, and Graphersal 0.4.x refuses a version 4 file as newer, never as damage

Store format version 4 needs the upgrade (graphersal store upgrade, below): a store of 0.2.x to 0.4.x is refused as older until it is upgraded, because a 0.4.0 store may keep embedding models as files under models/, which become blobs ("0.4.0 -> 0.5.0" below). Its older files stay as they are; everything written from then on is of file format version 4.

File format version 3 (0.3.0) needed no upgrade. The store format version stayed 3, so a store written by 0.2.x opened in 0.3.x as it was: its version 2 snapshots and WAL segments stay and are read as they are, and everything written from then on (a new WAL segment, new snapshots, backups, .gsnap exports) is of file format version 3. From the first such file on, Graphersal 0.2.x refuses the store, its backups and those packed snapshots as written by a newer version (PersistError::UnsupportedVersion, the row below), never as damage. To hand data back to 0.2.x, export it as GraphSON. Files of version 2 never hold a value with digits below the microsecond, an offsettime or a zone name: 0.2.x could not write them.

The store or file isThen
the current versionread and written as usual
newer than this buildrefused with PersistError::UnsupportedVersion ("written by a newer Graphersal") by every operation (open, read-only open, store info, verify, backup, restore, fork, repair, conversion, upgrade, ...), before any lock, read of data or write: never guessed at, never reported as damage, never repaired. This holds for a newer GRAPH (either copy), for any snapshot manifest, snapshot segment or WAL segment of a newer file format version inside an otherwise current or older store (attic entries included), for a single-file container of a newer container version, and for a packed snapshot. Use a newer Graphersal
a store of an older released store format version (2: Graphersal 0.1.x; 3: Graphersal 0.2.x to 0.4.x)refused with PersistError::OlderFormat by every operation but the converter and repair (open, read-only open, store info, verify, backup, restoring a backup directory, fork, convert; a ZIP backup is upgraded as it is restored); nothing is changed, never reported as damage. Its help names the command that upgrades it
a store of store format version 1 (never released)refused with PersistError::OlderFormat everywhere; the migration is a packed snapshot exported by the build that wrote it (below)

Two rules bind every release (format specification, section 15):

  • A version from the future is not damage, and a store holding one is never worked on. A file of a newer version (intact magic and header checksum, a version word above this build's) MUST NOT be taken for damage, and a store, backup or single-file store that holds even one such file MUST NOT be worked on in any way: no write, no lock, no repair, no salvage, no maintenance mode, no upgrade, no checkpoint, no backup into or out of it. It is refused as a whole, so this build can never corrupt what a newer one wrote.
  • Format versions move only with a release that needs them. A patch release (x.y.Z) never changes any format version (store, file or container). A format version changes only with a release whose new features need it; a release that changes no format reads and writes the stores of the release before it as they are, with no upgrade.

The upgrade table

Which older store format versions this build upgrades, and how, is one table in the code (UPGRADES, persist/store/upgrade.rs); this copy, and those in the format specification 15.1 and the store upgrade command, are generated from it and checked by a test. An upgrade is done only as its row says: "version word" rows only rewrite GRAPH and GRAPH.copy and are safe in place; "migration" rows do that and migrate the embedding models of a 0.4.0 store (below), in place too; "into a copy only" rows refuse --in-place (StoreFailure::UpgradeNeedsCopy) before anything is written; an unsupported version (or one without a row) is refused with PersistError::OlderFormat, whose help is the migration through a packed snapshot (below). A bump of a format version fails that test until the table has a row for the previous version.

From store format versionWritten byToUpgrade
1never released (no store id)4unsupported (packed snapshot)
2Graphersal 0.1.x (no models: the version word only)4in place or into a copy (migration)
3Graphersal 0.2.x - 0.4.x4in place or into a copy (migration)
4Graphersal 0.5.x and later4nothing to do

Upgrading a store of an older version

Every build reads every released format. A release keeps the readers of every store and file format version released before it (from 0.1.0 on), and the converter that upgrades such a store needs no older Graphersal: graphersal store upgrade reads the older store with this build. The golden fixtures written by the released 0.1.0 binary (crates/graphersal/tests/data/v0.1.0/: a store with history, marks, an attic entry, schema and catalog; a single-file store; a backup directory; a ZIP backup) are upgraded by every test run.

graphersal store upgrade old_store/ new_store/      # into a NEW store; old_store/ is not changed
graphersal store upgrade old.gstore new.gstore      # the same for a single-file store (any backend: new.gstore, a directory, --single-file)
graphersal store upgrade old_store/ --in-place      # the store itself (back it up first)
graphersal store upgrade old_backup/ new_backup/    # a backup directory: it stays a backup
graphersal store restore old_backup.zip new_store/  # a ZIP backup is upgraded as it is restored

In Rust Store::upgrade(from, to) and Store::upgrade_in_place(dir) (any StoreDir: a path, a .gstore file, a MemDir), in Python graphersal.Store.upgrade(source, target) or graphersal.Store.upgrade(source, in_place=True); each returns what it did (UpgradeReport).

What it does:

  • Everything is carried, exactly: the graph, its schema and catalog (saved queries, compression rules), the whole history (snapshots and WAL: every point in time stays a recovery target), the marks, the lineage, the attic entries (they stay restorable or forkable) and every creation parameter, the store id included: the upgraded store is the SAME store in the new format, so an upgraded backup of it continues to take increments.
  • Only GRAPH and GRAPH.copy are rewritten (the store format version word); every snapshot, WAL segment, the marks file and the attic stay byte for byte. (A 0.4.0 store with embedding models also gets their blobs and one commit, and loses models/: below.) This build reads them as they are (each file names its own file format version), so nothing is decoded and encoded again and the history stays exactly what was written. The first commit after the upgrade goes into a NEW WAL segment of the current file format version: a record of the new version is never appended to a segment of the older one.
  • The older store is verified first (every checksum, as store verify does). A damaged store is refused before anything is written (StoreFailure::DamagedSource); repair it instead: graphersal store repair old_store/ --to new_store/ reads a store of an older released version and writes the repaired store in the current format.
  • Into a copy (the default) the older store is only read; its writer lock is held while it is copied, so a store still open by a writer (an older Graphersal, a server) is refused as in use. The copy is verified before its GRAPH is written: an interrupted upgrade never leaves something that opens as a store in the target, and running the upgrade again into it clears what was left and completes.
  • In place the store is verified, then GRAPH.copy and GRAPH are replaced, each atomically: whatever moment a crash hits, the store is either still the older one (run the upgrade again) or already the upgraded one (a reader takes the intact copy), never lost. Without models no other file changes, so no INTENT is needed (the model migration has one: below). Back the store up before (a file copy of the closed store will do): afterwards the older Graphersal refuses it as newer.
  • A store that already has the current format is left alone in place (already_current); a copy of it is refused with StoreFailure::AlreadyCurrent (use store convert or a backup).

0.4.0 -> 0.5.0: models become blobs

Graphersal 0.4.0 kept the embedding models of a store as files under models/<id>/ (the model files, card, licence files and a manifest). 0.5.0 keeps each model as ONE blob (a deterministic tar) referenced by a model definition of the catalog (Embedding Models in a Store). The upgrade converts them:

  1. Every model under models/ is checked against its manifest (every byte hashed) BEFORE anything is written. A damaged or incomplete model refuses the upgrade (StoreFailure::UpgradeModelDamaged, nothing written): restore models/<id> from a backup, or move it away, upgrade and import the model again afterwards.
  2. An INTENT (upgrade_models) is written, then GRAPH gets version 4: from here on 0.4.0 refuses the store (as newer), and an interruption is completed by the next read-write open or upgrade.
  3. Each model becomes a blob; ONE commit (principal upgrade, attribute upgrade = 3->4) defines all of them, in a new WAL segment. The history before that commit has no models: a view of a position before it whose schema names a model is refused ("not in the database at this position").
  4. models/ and the INTENT are removed.

After the upgrade

The upgrade prints (and UpgradeReport holds) what still needs your decision; the exit code is 0 in every case.

  • No default model is set: hash-ngram/1 stays the default until you choose one (graphersal store models lists them; Store::set_default_model).

  • A model 0.4.0 kept without a repository name (imported from a directory without --repo; identity model2vec@<12 hex>) gets the repository local/<12 hex> (a definition needs one), and the schema's embedder naming it is renamed in the same commit; the report and the CLI say so. Import it again with --repo owner/name to give it its real name. The same happens to a second revision of a repository another model of the store takes (the catalog keeps one model per repository).

  • Models the schema needs that the store does not keep (0.4.0 served them through its --embedder flag, removed in 0.5.0) are listed (UpgradeReport::models_missing, a CLI warning: with the commands, MissingModel::note): such a store opens once they are imported. The upgrade itself succeeds. When the store has no default model and this is the only model the schema names, the import takes --default, so embed(text) without a model name uses it (MissingModel::suggests_default; later: graphersal store models default <store> <repo>):

    warning: the schema needs the embedding model acme/tiny, which the store does not keep
      identity: model2vec/acme/tiny@0123456789ab
      needed by: doc.emb
      effect: the store does not open until the model is imported
      # download the model into the local models directory
      graphersal embed-model download acme/tiny
      # import it into the store as its default model (embed() without a model name uses it)
      graphersal embed-model import acme/tiny --into store --default
    
  • Vector properties without a rule. 0.4.0's embed_property recorded only the model (embedder), never the property the text came from, so nothing keeps such vectors current. The upgrade never guesses the source and recomputes nothing: it lists each such property (UpgradeReport::vectors_without_rule: element kind, label, property, model, how many elements hold a vector, counted in the newest snapshot) and the CLI prints ONE note: per model with the ready schema patch (UpgradeReport::vector_notes). Every note has the same layout: a short headline, then one detail per line, and each command on a line of its own under a comment saying what it does; notes are separated by a blank line. A model with one such property gets its own note, for example

    note: doc.emb has vectors of acme/tiny but no source property
      vectors: 3 element(s)
      to keep them current: add "from": "<source property>" to its schema declaration
      first fill: re-embeds every doc (the whole database is locked while it runs)
      afterwards: write the source property, never emb itself
      # add the source property (replace <source property> first)
      graphersal --graph store -e 'g.patch_schema(#{vertices: #{doc: #{schema: #{properties: #{emb: #{from: "<source property>"}}}}}})'
    

    A model with several such properties gets one note listing them (one line each: element kind, label, property, count) with ONE combined patch for all of them, one label per line (the shell takes the lines inside the quotes), for example

    note: 3 vector properties are declared with vectors of acme/tiny but have no source property
      doc.emb: 3 vector(s)
      note.emb: 2 vector(s)
      draft.emb: no element holds one yet
      vectors: 5 in all
      to keep them current: add "from": "<source property>" to each declaration, all in one change
      first fill: re-embeds every element of these labels (the whole database is locked while it runs)
      afterwards: write the source properties, never emb itself
      # add the source property (replace <source property> first)
      graphersal --graph store -e 'g.patch_schema(#{
        vertices: #{
          doc: #{schema: #{properties: #{emb: #{from: "<source property>"}}}},
          note: #{schema: #{properties: #{emb: #{from: "<source property>"}}}},
          draft: #{schema: #{properties: #{emb: #{from: "<source property>"}}}}
        }
      })'
    

    For a model the store does not keep, the comment above the patch says it runs after the model's import: the store does not open before.

    See Vector Rules: adding from makes it a rule whose first fill re-embeds EVERY element of the label while the whole database is locked. Several labels can take their rule in ONE patch (one fill, one lock), and the preview says what it fills before anything is written:

    g.validate_schema_patch(#{vertices: #{doc: #{schema: #{properties: #{emb: #{from: "text"}}}}}, note: #{schema: #{properties: #{emb: #{from: "text"}}}}}})["fill_warning"]
    

    From then on a direct write of the vector is refused (GraphError::DerivedProperty): a loader or saved query of 0.4.0 that computed the vector itself (property("emb", ..)) writes the source property instead. The upgrade lists every saved query whose body writes such a property by its literal name on a label its effects may write (UpgradeReport::saved_queries_writing_vectors, Python report["saved_queries_writing_vectors"]), one note: each, for example

    note: saved query "load_docs" writes emb directly
      where: doc.emb
      effect: once the vector rule exists, direct writes of it are refused
      fix: remove that write (the rule computes emb from its source property); the query is not rewritten
    

    The preview of the patch names them too (fill[..].direct_writes, and a line of fill_warning). Only a literal key in property(..) is found (property("emb", ..), also after a cardinality, in a Rhai body); a computed key, the maps of merge_v/merge_e and GQL bodies are not, so check such queries yourself. A property declared with a model but holding no vector yet is listed too ("no element holds one yet").

  • Saved queries calling a removed function. A saved query of 0.4.0 that calls g.embed_property(..) (removed in 0.5.0) is kept as it is, and a call of it fails with a help naming the vector rule. The upgrade lists each such query (UpgradeReport::saved_queries_using_removed, Python report["saved_queries_using_removed"]) and the CLI prints a note: with the ready command when the call names its label and properties literally, for example

    note: saved query "fill" calls embed_property, removed in 0.5.0
      effect: a call of the query fails now; the query is not rewritten
      replacement: a vector rule; its first fill embeds every element of the label (the whole database is locked while it runs)
      # declare the vector rule that replaces the call
      graphersal --graph store -e 'g.patch_schema(#{vertices: #{doc: #{schema: #{type: "object", properties: #{emb: #{type: "array", format: "vector", embedder: "hash-ngram/1", from: "text"}}}}}})'
    

    Then redefine or drop the query. graphersal store create <dir> --from <0.4.0 .gsnap> prints the same notes and warnings (Store::create_from_packed_dir returns them as an UpgradeReport; the store is created even when the schema needs a model the file does not carry, and opens once it is imported); from Rust, graphersal::script::saved_queries_using_removed(&definitions) scans any catalog.

  • Take a full backup after the upgrade. A backup directory of the 0.4.0 store upgrades too (it stays a backup), but it gets its own migration commit, so it no longer takes increments of the upgraded store (PersistError::BackupRefused): back the upgraded store up into a new directory.

  • A ZIP backup of 0.4.0 with models is migrated as it is restored (graphersal store restore); a .gsnap of 0.4.0 with model rows becomes a store whose first commit defines the models (graphersal store create <dir> --from file.gsnap), and Store::import_models_from_packed imports them into an open store. Attic entries are left as they are (their history predates the models).

The golden fixtures written by the released 0.4.0 binary (crates/graphersal/tests/data/v0.4.0/) are upgraded by every test run.

Packed snapshots need no converter. A .gsnap written by 0.1.x (file format version 1) loads as it is (--graph graph.gsnap, TraversalGraph::read_snapshot), and graphersal store create new_store/ --from graph.gsnap makes a current store from it (its version 1 segment files are kept byte for byte). That route carries only the graph state, its schema and its catalog.

Store format version 1 was never released. A store of it (no store id) keeps the migration through a packed snapshot: the build that wrote it exports the current state (graphersal --graph old_store/ -e 'g.export_snapshot("graph.gsnap")'), and this build creates a new store from the file. The full recipe: Command Cheat Sheet.

What counts as a format change, and the compatibility promises for third-party readers and writers, are in the format specification, section 15.

Growing without a new version

New kinds of definitions in the catalog (saved queries, property indexes and compression rules today; procedures and others later), new keys of a definition, and new kinds of snapshot files do not change the format version (format specification, section 16). A build that meets something it does not know:

It findsThen
a definition of an unknown kindkept byte for byte and written back unchanged at every checkpoint, fork, backup and repair
an unknown key of a saved querykept and written back
a critical definition of an unknown kind (one that must stay consistent with the data, such as an index), or a snapshot file of a critical unknown kindthe store opens read-only (Store::read_only_reason, PersistError::ReadOnly): reading, verify, export, fork and backups work; writes need the newer version that wrote it

Stores written before the catalog existed open unchanged: their catalog is empty, the first saved query goes into the WAL and the next checkpoint writes it into the snapshot.

Directory Backends

The Store is written against a directory abstraction, the persist::StoreDir trait (EXPERIMENTAL in 0.8.x, like GraphStorage: it may still change; its rustdoc is the implementer's guide). The byte format is the same on every backend.

BackendWhere the files liveTargetsUse it for
persist::FsDira directory of the file systemnativethe usual store: a server, an application, the CLI
persist::SingleFileDirONE log-structured file (.gstore)nativeembedded use: one thing to ship, copy, attach (Single-File Store)
persist::MemDirmemoryevery target, WebAssembly includedthe browser playground, tests, a server that keeps its graphs in memory but wants rollback, fork and verify
your own StoreDiranywhere: an object store, a database, an encrypting wrapperyours

Every function that takes a store directory takes anything that is IntoStoreDir: a path (&str, String, &Path, PathBuf: persist::store_dir_at(path) decides between FsDir and SingleFileDir: an existing file, or a new path ending in .gstore, is a single file), an FsDir, a MemDir (or &MemDir), or any Arc<dyn StoreDir>.

In memory: MemDir

use graphersal::persist::{MemDir, RecoveryTarget, Store, StoreOptions};

let dir = MemDir::named("memory:main");
let store = Store::create(&dir, StoreOptions::new())?;
store.graph().write().traversal_mut().add_v("person").to_list()?;
store.checkpoint(None)?;
let fork = MemDir::new();
store.fork(RecoveryTarget::CommitSeq(0), &fork)?;            // a second store in memory
assert_eq!(Store::open(&fork, StoreOptions::new())?.graph().read().vertex_count(), 0);
Ok::<(), Box<dyn std::error::Error>>(())
  • Every Store operation works: commits, checkpoints, marks, read-only views, fork, rollback and the attic, verify, backup into another MemDir, convert into a directory or a file.
  • Syncs are no-ops, the writer lock is an in-process flag, and everything is gone with the last clone of the MemDir (clones share the files; deep_copy() makes an independent copy, the way tests simulate a crash image).
  • Without threads (WebAssembly) the automatic checkpoint runs when the host calls store.run_due_checkpoint() (default threshold 4 MiB there).
  • Store::convert(memdir, "data") writes a store in memory to disk (and back).

The web playground keeps every loaded graph this way.

On disk: FsDir, relocation and split stores

  • Relocatable. No store file records a path, only names relative to the store's root: move or copy the whole directory (while no process has it open) and open it there.
  • Split over disks. Parts of a store may live on other disks as symbolic links: wal/, snapshots/, attic/, even one snapshot directory. Links are never resolved or recorded.
  • A rollback or an attic restore that moves files between parts on different file systems copies them into the target directory, syncs, renames there and only then removes the source; a crash in between is completed at the next open.
  • Removing a linked directory (prune, attic removal) removes its contents along with the link. A link that a rollback moves (one linked snapshot directory) moves as a link: give it an absolute target.
mv data/wal /fast-disk/data-wal && ln -s /fast-disk/data-wal data/wal   # the WAL on another disk (store closed)

Writing your own StoreDir

The contract, in short (the trait's rustdoc has every detail):

  • Logical names. Files are named GRAPH, wal/00000000000000000013.wal, snapshots/<commit>/manifest, ...: /-separated, relative, without empty, . or .. parts, \, : or NUL. "Directories" are namespaces; nothing assumes that two names are two OS files.
  • Writes are appends or whole replacements. A file is only written at its end (or cut back); its content changes as a whole only through write_atomic. Lengths are logical bytes.
  • Atomicity per method. write_atomic leaves the old or the new content after a crash, never a mix, durable when it returns; rename is atomic, durable after sync_dir; appended bytes are durable after StoreFile::sync (a crash may keep any prefix of unsynced appends: the WAL is built for that); truncate is durable when it returns.
  • Locks. lock(LockKind::Writer) is exclusive and never waits; the backup pin is shared (BackupShared, for backups) or exclusive (BackupExclusive, for prune, never waits). A backend shared between processes must lock between processes.
  • Optional capabilities with default implementations: space_usage and compact (a backend that keeps garbage), free_space, check (damage of the backend's own metadata, which opens the store in maintenance mode), is_volatile (front ends say "lost on reload").
Methods
location, local_path, is_volatileidentity, for diagnostics
entry_kind, list, file_lennames
read, read_range, open_readreading (bounded, ranged, streamed)
create_dir_all, create, open_write, append, write_atomicwriting
rename, truncate, remove_file, remove_tree, sync_dirchanging names and lengths
lockthe writer lock and the backup pin
space_usage, compact, free_space, checkoptional

The trait is object-safe, so a decorator (for example a transparent encryption layer over any backend) holds an inner Box<dyn StoreDir> and forwards. Test a backend with the same scenarios as the built-in ones: crash images (a copy of the files at any point), cuts at every offset, flipped bits; graphersal's own tests (tests/all/mem_store_tests.rs, single_file_store_tests.rs) show how.

Which backend for which server

SituationBackend
one process serves one graph that must survive restartsFsDir (graphersal --graph data/ --server)
an application ships its data as one documentSingleFileDir (graph.gstore)
a browser tab, a test, a demo server: history, fork and rollback without a diskMemDir (Store::convert to disk when it should stay)
many graphs on one serverone store per graph (one directory or one file each)

Single-File Store

A Store is usually a directory. For an application that embeds Graphersal, one file is often handier: one thing to ship, copy, attach or back up. A single-file store holds exactly what a store directory holds (the snapshots, the write-ahead log, the marks, the attic, GRAPH), with the same guarantees, in one file (native targets; in the browser a store lives in memory).

use graphersal::persist::{Store, StoreOptions};

// A path ending in .gstore is a single file (an existing file is one, whatever its name).
let store = Store::create("graph.gstore", StoreOptions::new())?;  // or Store::create_file(path, ..)
store.graph().write().traversal_mut().add_v("person").property("name", "ann").to_list()?;
store.checkpoint(None)?;
store.close()?;

let store = Store::open("graph.gstore", StoreOptions::new())?;    // or Store::open_file(path, ..)
Ok::<(), Box<dyn std::error::Error>>(())

Every Store operation works on it unchanged: commits and their durability, recovery on open, checkpoints, marks, read-only views of any commit or time, fork, rollback and the attic, backups (into a directory, a ZIP, another single file, or memory), prune, verify, maintenance mode and repair. persist::SingleFileDir is the backend; anything that takes a store directory takes it (Store::create(SingleFileDir::new(path), ..)).

From the command line, the dev server and Python

graphersal store create graph.gstore --from modern   # or any name with --single-file
graphersal --graph graph.gstore -e 'g.v().count().next()'   # REPL, -e, --server: as on a directory
graphersal store info graph.gstore                   # ... "file  single file, 23.0 KiB", then its live and free bytes
graphersal store compact-advice graph.gstore         # [--min-ratio 0.3] [--min-reclaimable BYTES] [--min-size BYTES]
graphersal store compact graph.gstore                # prune + rewrite (refused while a server has it open)
graphersal store convert graph.gstore graph-dir/     # one file into a directory (a closed store), verified
graphersal store convert graph-dir/ graph2.gstore    # and back into one file

The dev server on a single-file store (graphersal --graph graph.gstore --server, --create-store creates it) shows the compaction advice in its Store menu under Disk space, with a Compact button (it asks first when a compaction is not recommended); a fork of a single-file store becomes a .gstore file next to it (graph-fork-<target>.gstore).

with graphersal.Store.create("graph.gstore") as store:     # or Store.create_file(path)
    advice = store.compaction_advice()                      # min_ratio=, min_reclaimable=, min_size=
    if advice["recommended"]:
        store.compact()                                     # {"bytes_freed", ...}
graphersal.Store.convert("graph.gstore", "data")            # single_file=True for the other way

How it works

The file is log-structured: every change of a store file is appended as a record (an append to a file, a whole-file replacement, a new name, a rename, a removal), and from time to time the whole list of names and where their bytes are (the table) is appended too. Two header slots at fixed positions, each with a generation number and a checksum, point at the latest table; they are written alternately. Nothing inside the file is ever overwritten.

  • Crash-safe. An interrupted write leaves the previous table and every earlier record intact; the next open replays the records after the latest table and cuts an interrupted last write. Each record says up to where the file had been synced when it was written, so an unreadable region that nothing synced follows is the torn tail of a crash, never damage, and a damaged region that later synced records follow is damage, never silently cut.
  • Damage of the store's own files (a snapshot chunk, a WAL record) is found by the store's own checksums exactly as on a directory, with the same donors and repair. Damage of the container's records (a flipped bit in a record header, a lost record) opens the store read-only in maintenance mode (DamageKind::Container; verify lists it). A damaged header slot or table loses nothing: the other generation and the records after it give the same names.
  • One writer. The writer lock is the operating system's lock on the file itself; a second writer, in this or another process, gets PersistError::Locked. Readers (store info, Store::open_read_only, verify, backups) work while a writer has it open.
  • Relocatable. The file holds no path: move or copy it (while no process has it open) and open it there.

Free space and compaction

A removal (a pruned snapshot, a replaced GRAPH, an old table) frees its space only inside the file: the file does not shrink by itself. store.compact() gives the space back: it prunes up to the current commit (the last two snapshots, the WAL between them and every attic entry's base stay) and then copies the live data into a new file next to the old one and replaces it atomically (like SQLite's VACUUM: the disk needs room for the live data meanwhile, and commits wait while it runs).

store.compaction_advice() says cheaply whether that is worth it (the file's total, live and garbage bytes, what a prune would free first, the free disk space needed); see Prune, Compact and Retention for the rules and CompactionPolicy.

The container's byte layout is normative: format specification, section 14.

Your Own Storage

A Store keeps a graph in memory and its history on disk. By default that graph is a TraversalGraph, and Store is short for Store<TraversalGraph>. A host that brings its own in-memory storage (a type implementing GraphStorage) can keep it in a Store too: the Store is Store<S> for any S that implements PersistentStorage.

EXPERIMENTAL. PersistentStorage, like GraphStorage and StoreDir, may change in any 0.8.x release.

The overview of everything a host storage implements and where it plugs in (the DSL, the session, the Store) is Custom Storages.

What the storage implements

PersistentStorage (in graphersal::storage, feature persist) is what snapshots and the Store need on top of GraphStorage:

GroupMethods
Positiongraph_id, set_graph_id, last_committed_at, id_sequences, raise_position (raise only, never lower)
Load sink (outside units: nothing recorded, no hook, no schema scan)load_schema, load_definition, load_vertex, load_edge, finish_load
Reload in placeclear: empties data, schema, catalog and position, KEEPS the registered hooks and the journal slot
Journalattach_journal(JournalSlot): the storage keeps it in its CommitHooks, whose journal slot runs after every user hook
Replayreplay(&ChangeSet, verify): has a default over the trait's write methods

The trait's rustdoc is the implementer's guide.

Precondition. The storage must claim the capabilities atomic and change_capture (StorageCapabilities). The journal writes a commit's record in before_commit, so the storage must be able to roll a vetoed unit back, and it must build the unit's ChangeSet itself (with the public ChangeSet/Mutation constructors). Store::create_in, Store::open_in and Store::open_backup_in check this before they touch a file. Without the capabilities they fail with PersistError::Store of cause StoreFailure::MissingCapability, and the message names the missing capability.

Opening and creating

use graphersal::persist::{Store, StoreOptions};

// A new store whose first snapshot is `my_graph` (any S: PersistentStorage + Default).
let store = Store::create_in("data/graph", my_graph, StoreOptions::new())?;
store.graph().write().transaction(|g| { /* commits go to the WAL */ Ok::<_, GraphError>(()) })?;
store.close()?;

// Open it again: `empty` builds the empty instance the snapshot is loaded into.
let store: Store<MyStorage> = Store::open_in("data/graph", StoreOptions::new(), MyStorage::default)?;
let graph: &Arc<Graph<MyStorage>> = store.graph();
Store<TraversalGraph>Store<S>
Store::create(dir, options), create_with(dir, graph, options)Store::create_in(dir, graph, options)
Store::create_from_packed(dir, packed, options)Store::create_from_packed_in(dir, packed, options, empty)
Store::open(dir, options) (and open_file)Store::open_in(dir, options, empty) (a SingleFileDir is a dir too)
Store::open_backup(dir, options)Store::open_backup_in(dir, options, empty)
Store::open_read_only(dir, target)Store::open_read_only_in(dir, target, empty_instance)

Every other method (checkpoints, marks, point in time, fork, rollback and the attic, backups, prune, compact, verify, close) has the same signature for every S. store.read_only_at(target) loads the past state into a new S::default(). The functions that take a directory and no open store (Store::verify_dir, Store::inspect, Store::fork_dir, Store::restore_zip, ...) work on the files and are the same for every storage type.

The files do not depend on the storage

A snapshot and the WAL hold the graph, not the storage. A store written as Store<MyStorage> opens as Store<TraversalGraph> (in graphersal store, the dev server or the Python binding) and the other way round. The storage type is therefore not a creation parameter.

What stays a TraversalGraph inside

Some operations never touch the host's graph. They work on a TraversalGraph of their own and write files:

  • the merge checkpoint decodes the touched part of the last snapshot into a small delta graph and replays the WAL onto it (beyond the merge bound the host's graph is encoded through its read API instead);
  • salvage (maintenance mode) and repair rebuild the state from damaged files. A store that opens in maintenance mode serves the salvaged state copied into a new S built by empty. repair_to writes a new store, which a host then opens with Store::open_in;
  • fork and attic fork load the past state and write a new store; open it with Store::open_in.

Compressed properties (ElementProperty::Compressed) are a TraversalGraph feature. A foreign storage keeps compression rules in its catalog like any definition, and nothing applies them.

Creation Parameters

Some parameters of a store are chosen when it is created and never change afterwards: they are written into the store itself (its GRAPH file, its container), every copy of the store carries them, and no API, command or option changes them. Everything else is an open option: given to every open, it may differ from one open to the next and is stored nowhere.

graphersal store info <dir> lists the creation parameters under "fixed at creation"; Store::info / Store::inspect return them (StoreInfo::store_id, chunk_bytes, damage_policy, created_at, format_version, space for a single file, layer_base for a layer store), the dev server's GET /api/store and the Store menu show them.

$ graphersal store create data/ --from modern --on-damage continue
Created the store data/: graph 01a11cfc-..., commit 0, 1 snapshot(s); damage policy continue (fixed for its life).
$ graphersal store info data/
...
fixed at creation (never changed):
  store id      01a11cfd-...
  created       2026-10-08T19:27:26Z
  chunk size    1048576 bytes
  on damage     continue (damage found while open is reported, commits continue)
  backend       directory (format version 4)

A layer store lists its base too, as the last line of the block:

  base          graph 019a6b2e-... at commit 42 (commit time 1763...)
                # a layer store: opens only over this base, a backup is useless without it
                graphersal --graph <BASE> --layer-store <dir>

The parameters fixed at creation

ParameterDefaultSet withStored inCarried by
Damage policy: what an open store does when damage is found on disk while it is open (below)maintenanceRust StoreOptions::with_damage_policy on Store::create, create_with, create_from_packed, create_file; CLI graphersal store create <dir> --on-damage maintenance|continue, graphersal --graph <dir> --create-store --on-damage <p> (also with --server); Python Store.create(path, on_damage="continue"), Store.create_file(...)GRAPH flag bit 5 (format spec 5.2)every write of GRAPH; fork, attic fork, repair, convert, compact, rollback, every backup (full, increment, ZIP, from memory), restore, upgrade (copy and in place)
Chunk target size: the uncompressed size of a snapshot chunk, the unit of repair1 MiBRust StoreOptions::with_chunk_bytes; CLI store create --chunk-size <bytes>GRAPH offset 44 (5.1); each manifestfork, attic fork, repair, convert, backups, restore, upgrade
Store id: the store's identity, which an incremental backup requires to be equalrandom (128 bits)(made by the create)GRAPH offset 100 (format spec 5.5)every write of GRAPH; rollback, attic restore, compact, every backup (full, increment, ZIP, from memory), restore (a restored backup IS the store), upgrade (copy and in place: the upgraded store IS the store in the new format). RENEWED (a new store) by fork, attic fork, repair and convert
Creation timethe time of the create(the clock)GRAPH offset 32convert, backups, restore, rollback, upgrade (a fork or repair is a new store with its own time)
Backend: a directory, one container file (.gstore), memoryby the path (store_dir_at): an existing file or a new .gstore path is a single filethe path; CLI --single-file; Rust SingleFileDir, MemDir; Python Store.create_filethe location itself; a single file's preamble holds its container version (14.1)compact (same file), upgrade in place; store convert and store upgrade <old> <new> make a NEW store, in any backend
Base of a layer store (base_ref): the identity of the frozen base graph the layer was built over (its lineage id, commit and commit time, BaseRef); only a layer store has one (Layered Graphs)none (a plain store)Rust Store::<LayeredGraph>::create_layer(dir, &base, options) / create_layer_with (the LayerBase given); CLI and dev server: graphersal --graph <base> --layer-store <dir> --create-store (the --graph is the base: a Store or a .gsnap; graphersal store info shows it); Python: not yet (its layers live in memory)the layer file (layer.bin, segment kind 128) of every snapshot and its segment-table row in the manifest, file format version 5 (format spec 7.5); no GRAPH field or flag (the manifests tell, 15)every snapshot the store writes (checkpoints, live and closed); every backup (full, increment, ZIP, from memory), restore (in place and from a ZIP), the read-only open of a backup, export_packed (a layer .gsnap); a fork (fork, Store::fork_layer_dir, CLI store fork --base) and an attic fork (attic_fork, Store::attic_fork_layer_dir, CLI store attic <dir> fork --base): a new layer store over the same base; a rollback and an attic restore (the store stays a layer over it); convert (byte copy); upgrade_in_place (a layer store is current: unchanged). Not carried, by design: the materialized export (Store::export_materialized, CLI store materialize --base, a plain whole-graph snapshot without a base). Refused for a layer store (StoreFailure::LayerStore, nothing written): the repair (a salvage rebuilds whole graphs, a layer store holds only changes to a base it does not read: restore a backup instead), the closed-store model commits (a layer store keeps no model), the plain fork_dir/attic_fork_dir (no base to load over)
Store format versionthe build's (4)(the build)GRAPH offset 8 (the file format version, 4, is in every other file header; a store created from an older packed snapshot keeps that snapshot's older files)everything; a newer version is refused; an older released one (2, Graphersal 0.1.x; 3, Graphersal 0.2.x to 0.4.x) is refused until graphersal store upgrade converts it (a 0.4.0 store's models become blobs), the only change of this parameter, which carries every other one (Format Versions); the pre-release version 1 moves through a packed snapshot

The graph id is not a parameter: it identifies the current lineage. It is set when the store is created, an in-place rollback starts a new one in the same store, and a fork or repair has its own (its lineage chain names the parent). The store id identifies the store itself: a fork, repair or conversion is another store (a new id), so it never continues the original's incremental backups (Backups).

Damage policy

Damage can appear on disk while a store is open. A backup (it reads every checksum of what it copies), a checkpoint (its merge reads the last snapshot and the WAL after it) and verify find it; the damage policy decides what happens then:

  • maintenance (the default): the open store turns read-only with the damage as the reason. Commits, marks, checkpoints, prune, rollback and compaction are refused (PersistError::DamageFound); queries go on; a backup from memory saves the intact graph; the store writes nothing more to the damaged disk.
  • continue: the store keeps accepting commits; the damage stays reported (store info, the Store menu, a warning in the log) for as long as it is open.

It does not apply to damage found when the store is opened: a store that cannot be loaded intact always opens in maintenance mode. See Damage, Maintenance and Repair.

Why fixed: the policy is a decision about the data (may it change while its files are known to be damaged?), not about one process. A fork, a repair or a backup is the same data, so it keeps the decision; an open never overrides it. An open given another policy ignores it (StoreOptions::with_damage_policy is used only when a store is created), and the CLI refuses --on-damage for an existing store with another policy instead of ignoring it silently. A store whose GRAPH files are both lost cannot tell its policy: a repair of it gets the default.

The base of a layer store is fixed because the layer holds only its changes to that very base, by element id: over any other graph (also the same lineage at another commit) the changes mean something else. An open, a view, a verification or a checkpoint with the base is checked against it before anything is read (PersistError::LayerBaseMismatch, naming both; so is a fork or attic fork of the closed store, Store::fork_layer_dir/attic_fork_layer_dir), and a copy of the store is useless without the base: a backup's report warns about it. To move a layer to a new base, rebuild it there. No GRAPH flag marks a layer store: every one of its snapshots names the base in its manifest (which the version guard reads anyway, format spec 15), so a flag would only be a second copy that could disagree, and releases that do not know layer stores already refuse the version-5 manifests.

The storage type of the graph (Store<TraversalGraph> or a host's Store<S>, Your Own Storage) is NOT a creation parameter: the files do not depend on it, so any storage type opens any store.

Neither are the additions of store format version 4: the hash algorithm of a blob is stated by each blob reference itself (hash_algo, format spec 3 and 4.6), so another algorithm needs no new store; the part size of a commit in parts (64 MiB) is the writer's choice, readers accept any slice size (9.3.1); the embedding models and the default model are catalog definitions, data of the history that commits change (Embedding Models in a Store); the system journal's segment size and instance name are open options (below).

Open options (per open, stored nowhere)

OptionDefaultRust (StoreOptions)
Durability: fsync per commit, at most once per interval, or left to the OSper commitwith_durability
WAL segment size16 MiBwith_wal_segment_bytes
Automatic checkpoint after this much WAL256 MiB (4 MiB in the browser)with_checkpoint_after_bytes
Merge checkpoint bound1 GiB (64 MiB in the browser)with_checkpoint_merge_bytes
Snapshot segment target64 MiBwith_snapshot_segment_bytes
Compression codec of chunks and large WAL recordsLZ4with_codec
Checkpoint on closeoffwith_checkpoint_on_close
Read options (memory limit, value depth)defaultswith_read_options
Compaction policy and automatic compaction after prunedefaults, offwith_compaction_policy, with_auto_compact
Workload statistics level (off, memory, persisted: the sidecar WORKLOAD)persistedwith_workload_level
System journal segment size (book page "System Journal")4 MiBwith_journal_segment_bytes
Instance name in the system journal (kept in the instance file INSTANCE, never copied)the host name (HOSTNAME, COMPUTERNAME), else unknownwith_instance_name

A new creation parameter is added to the first table (and to store info); see CLAUDE.md.

Workload Statistics

A graph instance keeps statistics of what was done with it: which scheduled jobs ran and how long they took, how long writers held the graph's lock, which queries ran, and which properties they used and how. They describe the instance, not the data: they are not versioned with the graph, never written to the journal, and never part of a commit, so they do not move with a rollback and are not replicated.

Levels

LevelWhat is kept
offnothing
memoryin memory, gone with the process
persisted (default)in memory, and in the Store's sidecar file WORKLOAD, read back when the store opens

The level is set when a store is opened (StoreOptions::with_workload_level); it is not stored. Switching to off keeps what was collected; only clearing deletes it.

Time buckets

Every series keeps three tiers of buckets, like a round-robin database:

  • one bucket per minute for the last 60 minutes,
  • one per hour for the last 48 hours,
  • one per day for the last 90 days.

Each bucket counts the occurrences, the failed ones, the items they touched, their total and their longest duration. The sidecar keeps all three tiers, so a restart loses none of them; buckets that aged past their window while the process was stopped fall out at the next sample.

Channels

Every sample is counted under the channel of the work that produced it, so the report says who runs what (which queries the AI agents run, which ones the page):

ChannelWork
playgroundqueries run from the browser playground (in the page, or over the dev server)
mcpthe MCP endpoint's tools and the AI Chat's agent
clithe command line: one-shot scripts and the REPL
pythonthe Python binding
jobthe actions of scheduled jobs
hostanything else (an application embedding the library)

Only a user's queries count. The work a front end makes up itself (drawing the Graph panel, the inspector, schema inference, the panels' lists) is technical and not counted. A host declares its channel around the work it does for a request with graphersal::workload::scope(channel, technical, || ..), or once for a thread that serves one front end with set_thread_default(channel, technical); a front end that marks its own work technical runs a user's query in scope(current_channel(), false, ..). Scopes nest, and a job's run is always job.

The graph's lock

The graph has one writer lock: a writer excludes readers and other writers. To see whether it is a problem, three series measure it under the channel of the work that took the lock:

SeriesWhat it measures
write.waita writer asking for the lock until it holds it (contention)
write.holda writer holding the lock (what readers and other writers wait for)
read.waita reader waiting because a writer holds the lock (an uncontended read is not counted)

Each bucket has the count, the total and the longest time, so the mean and the worst wait are at hand. A Store attaches its statistics to its graph; a graph of your own counts after Graph::attach_workload_stats(stats). Work a front end marks as technical (its own drawing and panel queries) is not counted.

Queries

Every run of a traversal on a graph with statistics (GQL included: it runs the same pipeline) counts in the series of its fingerprint: the optimized plan, as .profile() names its steps, with every literal replaced by ?. g.v().has("name", "ann").values("age") and the same query for "bob" are one series, v().has(?, ?).values(?); a list of literals is one ?. Each run adds its result count (with bulk), its duration and whether it failed. A saved query call counts once more as saved:<name> (the call itself; the traversal it returns counts under its plan when it runs). At most 500 query series are kept: a new one beyond that replaces the one run least in the last 90 days. Like pg_stat_statements in PostgreSQL, this answers "which queries run, how often, how long", by channel (which ones the AI agents run).

Properties

The same run also counts, per property, how the plan used it: series (element, label, key, access), each counted once per run with the number of traversers that reached the step using it. The access is one of

AccessSteps
filter_scanhas(key, ..), has(key), has_not(key), has(key, __.to_lower()...), a has folded into v()/e()
filter_indexthe same filters when a property index serves them
readvalues, properties, value_map, element_map, a by(key) of project/select/path/tree
order_groupa by(key) of order, group, group_count, dedup
similaritysimilarity, nearest, embed
write / removeproperty, add_v/add_e properties / remove_property

The element kind and label are what the plan states before the step (v(labels), e(labels), has_label, out_e(labels), add_v(label)); a step that reads every property (value_map(), element_map()) names the key *, and a use inside a child traversal (where(__.out().has("lang"))) has no element, no label and no traverser count. A jpath key counts under its top-level property. These counts answer "which properties are filtered without an index, which are only written, which are read at all": the input of the planned storage advisor.

Memory

The statistics stay bounded (at most 500 query series, at most 60 + 48 + 90 buckets per series, only buckets in which something was counted). Their memory is shown as workload_bytes in g.memory_usage(), in the dev server's and the playground's statistics (Profile ▸ Statistics, Workload statistics), never added to the graph's total_bytes.

The sidecar

A writable store writes WORKLOAD once a minute (the system job stats_flush, see Scheduled Jobs) and when it closes. After an orderly stop nothing is lost; after a crash at most the last minute. The file is best effort: a missing or damaged file means the statistics start anew, never damage, and the store opens as usual. It is never copied into a backup, a fork, a repaired or a converted store: a restored store starts without statistics (an upgrade into a copy keeps them, the copy being the same store). Its byte layout is section 4.4 of the format specification.

A backup opened read-only, a read-only or maintenance-mode store keeps statistics in memory only.

Reading them

Front endHow
playgroundOptimize ▸ Workload: tables with a sparkline per row and a chart per series (Optimize)
REPL (--graph <store>)/workload: one line per series, last 90 days
dev serverGET /api/workload (the JSON below)
MCPtool workload_statistics {max_rows} (at most 50 rows per list by default)
Pythonstore.workload_report() (a dict)
Ruststore.workload_stats().report(now), WorkloadReport::to_property() / to_json() / Display

The JSON form (WorkloadReport::to_json) has the keys level, queries (query), properties (element, label, key, access), locks (lock) and jobs (name, last_run); every row has its channel and the windows last_hour, last_two_days and last_ninety_days, each with count, failed, items, total_micros and max_micros. Rows are sorted by total time over 90 days. A graph outside a store answers level off with empty lists.

History. Asked with a tier (?history=minutes|hours|days on the dev server, the MCP tool's history, Python's workload_report(history="hours"), Rust's report_with_history(now, HistoryTier::Hours)), the report adds history_tier and gives every row its history: the buckets of that tier within its window (the last 60 minutes, 48 hours or 90 days), oldest first, only those in which something was counted, each {start, count, failed, items, total_micros, max_micros} with start in microseconds since the Unix epoch. That is the data of a chart: how often a query ran and how long it took, minute by minute or day by day.

use graphersal::persist::{MemDir, Store, StoreOptions};
use graphersal::workload::{Channel, Sample, SeriesKey, SeriesKind};

let dir = MemDir::named("memory:stats");
let store = Store::create(&dir, StoreOptions::new()).unwrap();
let stats = store.workload_stats();
let now = 1_800_000_000_000_000; // microseconds since the Unix epoch
stats.record(
    SeriesKey::new(SeriesKind::Lock("write.hold".into()), Channel::Cli),
    now,
    Sample::new(10, 250),
);
let report = stats.report(now);
assert_eq!(report.series[0].last_hour.count, 1);
store.close().unwrap(); // writes WORKLOAD

System Journal

The system journal records what an instance DID, one record per operational event: a store opened or closed, a checkpoint written, a backup taken or failed, damage found, a rollback, a permission denied, the system clock stepping back. A person reads it later ("what happened to this store last night?"); a host forwards it to its own logging.

It sits beside three other streams and replaces none of them:

StreamHolds
the WAL (Journal and Recovery)the changes to the DATA, commit by commit
Workload statisticsnumbers per time bucket
tracing (the CLI's GRAPHERSAL_LOG)developer diagnostics, unstable
the system journalindividual operational events, declared and stable

The journal decides nothing: no part of Graphersal reads it to decide anything, and a failed journal write never fails the operation it describes (it is a tracing warning and a counted lost record, SystemJournal::lost_records). Records hold names, counts, durations and ids: never data values, query text or secrets.

Records

Every record has the same envelope plus typed fields:

FieldMeaning
seqthe local sequence number: monotonic, never reused; the cursor of a reader
originthe instance that created the record: a random id and a readable name
origin_seqits sequence number there; (origin, origin_seq) identifies a record everywhere
timemicroseconds since the Unix epoch (UTC), from the instance clock that also times the commits: a record about commit N is never earlier than commit N
levelerror, warn, notice or info (most severe first)
sourcea dotted hierarchy: store, store.backup, store.damage, auth, clock
kindthe stable event code (store.backup_done); every kind is declared: the engine's below, a host's by the host (Host events)
messagethe rendered English text
op, parentthe operation a record belongs to, and its parent operation (when set)
committhe commit in the WAL the event relates to (when set)
principalwho: the channel the work came through (cli, mcp, playground, python, host)
fieldsthe kind's declared fields

A reader of an older version shows a record of a kind it does not know by its message and fields.

A recommendation field says how to fix what the record reports, in the layout of every Graphersal note: a short headline, then each command on its own line under a # comment saying what it does. The text form of a record (JournalRecord::to_line, graphersal store journal, the playground's journal panel) keeps the one-line fields in parentheses on the record's line and puts a field of several lines below it, indented:

2026-10-09T08:53:20.000000Z #12 error  model.unavailable the model acme/tiny is missing: queries with it fail (repo=acme/tiny, identity=model2vec/acme/tiny@0123456789ab, cause=missing)
  recommendation: download the model again and import it into the store, or restore the store from a backup or replica
    # download the model's files again
    graphersal embed-model download acme/tiny
    # import them into the store in place of the damaged copy
    graphersal embed-model import acme/tiny --into <store> --replace

The JSON forms (--json, GET /api/journal, MCP, Python) keep the field as one string with its line breaks.

Repeats and states

The journal is append-only, so a repeat is collected BEFORE it is written, never by rewriting a record. Every kind declares a collapse key (its kind, its source and some of its fields; never the time). The first occurrence is written at once. A record whose key equals one of the last five written records is counted in memory instead; the group is closed by ONE journal.repeated record (with the original's origin_seq, the count and the time range) when the original leaves the last five records, when an hour has passed since the original (a continuing problem shows again), or when the journal is flushed or closed. A crash loses only the count of an open group.

A state (store.damage_found, store.read_only) is written once, its repeats are counted while it holds, a journal.state_reminder repeats its current values once per hour, and its ..._cleared kind ends it.

Where it is kept

  • A graph without a store keeps its journal in memory: the newest 10 000 records (JournalPage::truncated says when older ones are gone). The playground's graphs too.
  • A Store keeps it in its directory (format spec 4.7): segments journal/<20 digits>.jnl (the name is the first seq the segment may hold), append-only, framed like the WAL (sync marker, length, header and body CRC: a torn tail is cut by the next writer, a damaged record is skipped by resyncing on the next frame). A new segment starts past 4 MiB (StoreOptions::with_journal_segment_bytes), at an open by another instance, and after a failed write. There is no retention limit.
  • error records are written and synced at once. The others are batched in memory and written as described in When records appear, so the journal never writes in the middle of another operation of the store; a crash loses at most about the last second of records.
  • A store opened read-only (a backup, maintenance mode, a store holding something critical of a newer version) reads its stored journal; its new records stay in memory. Once damage is found while a store is open (either damage policy), its journal writes nothing more to the store's files: the records stay in memory and in the tracing mirror.
  • The instance identity lives in the instance-local file INSTANCE at the store root (a random id and a name: StoreOptions::with_instance_name, else the host name). No copy carries it: a restored backup or a converted store opened elsewhere is another instance, which writes into a new segment.
  • The journal is never store damage: verify lists its problems as notes (VerifyReport::journal_notes), and its files are left out of the damage found while open.

When records appear

  • In the process that holds the graph or the store a record is visible at once: every read (Graph::system_journal(), Store::journal(), the session, GET /api/journal, the MCP tool journal, the playground, Python's graph.journal/store.journal, the REPL) answers from the records in memory, written or not, and reads only older records from the segments, so a page never has a gap or a duplicate, before or after the batch is written.
  • On disk, and so for another process (graphersal store journal or Store::journal_dir on a store a server holds open), a record appears within about a second: a store on a file system writes the batch half a second after its first record, from a thread of its own, independent of the statistics job stats_flush. The thread writes only while no other operation of the store runs (a checkpoint, prune, compaction, rollback, attic change, verify, backup, fork, export or close; commits are not waited for, they write other files); during a long checkpoint the batch waits for its end.
  • Without threads (wasm32), and for a store in memory or in a host's own StoreDir, the host calls Store::flush_journal(): the playground does on its every-second tick (Session::tick_jobs). The system job stats_flush, SystemJournal::flush (which also closes the groups of repeats), the close and the next error record write the batch too, as does a batch of 1000 records or 1 MiB.

Copies

PathThe journal
full backup, ZIP backupevery segment (the newest up to its last complete record), checked frame by frame in the store and in the copy; a problem is a BackupReport::warnings entry, never a failed backup; listed in BackupReport::journal_files
incremental backupsegments the backup lacks are copied, the backup's newest one gets the new tail appended (a backup segment that is not a prefix of the store's is left as it is, with a warning)
restorethe backup's journal becomes the store's; the restoring instance continues in a new segment
backup from memorywhat is readable is copied
convertcarried (INSTANCE is not)
fork, attic fork, repairNOT carried: the new store's first record store.created names the store and the commit it was made from
.gsnap exportnot carried (a state, not operations)

Reading it

  • Rust: Graph::system_journal() (every graph), Store::journal() (an open store), Store::journal_dir(dir, &query) (a closed store, or one open elsewhere: no lock, nothing written). SystemJournal::query(&JournalQuery) filters by time range (since/until), level (min_level), source (source_prefix: store matches store.backup), kind, op and origin, from a cursor (after(seq)), at most limit records (default 1000): JournalPage::next_after is the next cursor, more says that more follow. JournalQuery::newest_first() answers the NEWEST matching records instead, newest first (a stored journal is read from its last segment backwards, one segment in memory at a time, and no older segment than needed is read): next_before is the cursor of the next older page (before(seq)), more says that older ones exist, and next_after is the newest record covered, so a reader shows the end of a long journal at once and then follows it. SystemJournal::subscribe(after) follows the journal (wait(timeout) blocks natively, WebAssembly polls); add_sink forwards every written record to a host's JournalSink; open_operations() is the last record of each operation without a _done/_failed record. Facade: graphersal::system_journal.
  • tracing: every written record is mirrored under the target graphersal::journal at its level (notice as info); the CLI shows them on stderr with GRAPHERSAL_LOG=info.
  • CLI: graphersal store journal <DIR> [--level L] [--since TIME] [--source P] [--kind K] [--after SEQ | --last N] [--limit N] [--follow] [--json]; --last N prints only the newest N records (The graphersal store Command).
  • Dev server: GET /api/journal?after=N&level=..&source=..&kind=..&limit=.. (newest_first=true&before=N: newest first, paging backwards), and the read-only MCP tool journal (the same keys) (Dev Server and MCP).
  • Python: graph.journal(...) (every graph; without a store its in-memory journal), store.journal(...) and Store.journal_dir(path, ...) (a closed store, or one open elsewhere), with the keyword arguments after, before, newest_first, since, until, level, source, kind, op, origin, limit and policy. A page is a dict {"records", "next_after", "truncated", "more", "notes"}; each record has the keys of store journal --json (Python).
  • Playground: Catalog ▸ System journal… shows the served graph's journal, newest first, with a level and a source filter, in the WebAssembly playground (the graph's store in memory) and over the dev server. It opens on the newest 300 records (a newest-first page), then reads only the records written since, every five seconds; "Show more" shows 300 more rows, reading older pages backwards (Web Playground).
  • Permissions: reading is the resource Journal (Resource::Journal, Read); the session, the dev server and MCP ask the authorizer before they answer. AccessPolicy::read_only() allows it. The Rust API itself asks nothing (it is the host's).

The journal has no DSL access yet.

Host events

A host built on the engine (a server, a daemon embedding a Store) records its own operational events in the same journal, beside the engine's: a panic it caught, an item it failed to process, its own start and stop, an install change. They then show wherever the journal shows (graphersal store journal, the MCP journal tool, /api/journal, the playground), with the same filters, collapsing, sinks and tracing mirror.

A host kind is declared once per process with graphersal::system_journal::declare, like a kind of the catalogue below: a stable code, a source, a level, one sentence and its fields, and optionally a collapse key ("Repeats and states"; host kinds are events, not states).

use graphersal::prelude::*;
use graphersal::system_journal::{HostEvent, HostEventKind, Level, declare};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let graph = Graph::new(TraversalGraph::new());

declare(
    HostEventKind::new("myhost.job_failed", "myhost.jobs", Level::Error,
                       "A background job of the host failed.")
        .field("job", "the job's name")
        .optional_field("cause", "the error")
        .collapse_by(["job"]),
)?;

let seq = graph.system_journal()?.record(
    HostEvent::new("myhost.job_failed", "the job nightly panicked")
        .field("job", "nightly")
        .field("cause", "index out of bounds"),
)?;
assert!(seq.is_some());
Ok(())
}

The rules:

  • The code has two or more dotted segments, the source one or more, each of lowercase ASCII letters, digits and _, starting with a letter. The first segment of both names the host: it may not be a first segment of the engine's own codes or sources (store, journal, auth, clock, ...) nor graphersal, so source_prefix("store") never returns a host record. Pick a prefix naming your product: an engine release that adds a new first segment is listed in its release notes.
  • A declaration holds for the whole process and every journal in it. Declaring the same kind again with the same declaration is a no-op (a component may declare its kinds at every start); a different declaration of a declared code, or a code of the engine's catalogue, is refused (JournalError::InvalidDeclaration). declared_kinds() lists the declarations.
  • SystemJournal::record refuses an undeclared kind (JournalError::Undeclared), an engine kind, a field that is not declared or given twice, and a missing required field (JournalError::InvalidEvent): nothing is written then. Fields are kept in declaration order.
  • Otherwise a host record is written like an engine record: timed by the instance clock, error records durable at once and the others batched, and a failed write of the stored journal is a lost record, never an error of record. It returns the record's seq (the op of later records of the same operation, HostEvent::op), or None when it was counted as a repeat. The principal defaults to the thread's channel (host unless a front end set one).
  • Records keep the engine's layout: a reader of any version shows a host record by its message and fields, like a kind of a newer version. A host record holds names, counts, durations and ids like every record: never data values, query text or secrets.

Event catalogue

Every kind the journal writes, generated from the declarations in the code (GRAPHERSAL_UPDATE_BOOK=1 cargo test -p graphersal --lib catalogue):

KindLevelSourceFormFieldsDescription
journal.repeatedinfojournaleventof_origin_seq: the origin_seq of the original record; of_kind: the kind of the original record; count: how many more times it occurred; first_us: the first repeat (µs since the Unix epoch); last_us: the last repeat (µs since the Unix epoch)Closes a group of repeats: the record of_origin_seq occurred count more times between first_us and last_us (written when the original leaves the last five records, after an hour, or at close). Its level is the original's.
journal.state_reminderinfojournalevent, collapsed by statestate: the kind of the state; since_us: when the state began (µs since the Unix epoch); count: how many times it was reported again since the last recordA state still holds (once per hour while it does), with its current values. Its level is the state's.
journal.records_lostwarnjournalevent, collapsed by kindcount: the records not writtenWriting journal records failed; this many records are missing from the stored journal (they were kept in memory only).
clock.step_backwarnclockevent, collapsed by kindsystem_us: the system clock's reading (µs); floor_us: the instance clock (µs); behind_ms: how far the system clock is behind (ms)The system clock stepped back more than a second behind the instance clock; times stay at the instance clock until the system clock catches up.
store.openedinfostoreeventcommit_seq: the position after the open; replayed: WAL commits replayed onto the snapshot; load_ms: how long the open took (ms); read_only: whether it opened read-only (a backup, maintenance mode, ...)The store was opened.
store.recoverednoticestore.recoveryeventtorn_tail_cut_bytes: bytes of an incomplete last WAL record cut off; intent_completed: the interrupted operation completed (empty: none); tmp_removed: temporary files removed; wal_cut: whether a refused WAL record was cut offThe open repaired the traces of a crash or an interrupted operation.
store.closedinfostoreeventcommit_seq: the last commit; clean: whether it was closed cleanlyThe store was closed.
store.read_onlywarnstorestate until store.read_only_clearedreason: whyThe store is read-only: it holds something critical this version does not know.
store.read_only_clearednoticestoreends store.read_only-The store is writable again. Not emitted yet: a later version (a store turns writable only at a new open today).
store.checkpoint_doneinfostore.checkpointeventcommit_seq: the snapshot's position; merged: whether it was merged from the last snapshot and the WAL; bytes: the snapshot's size; ms: how long it took; automatic: whether the store started it itselfA checkpoint wrote a snapshot.
store.checkpoint_failederrorstore.checkpointevent, collapsed by kinderror: the error; automatic: whether the store started it itselfA checkpoint failed; nothing visible was written (level warn when the memory ceiling refused it).
store.backup_donenoticestore.backupeventtarget: where it went; mode: full, increment, zip or memory; commit_seq: the backup's position; bytes: the bytes writtenA backup was written and verified.
store.backup_failederrorstore.backupevent, collapsed by targettarget: where it should have gone; side: where damage was found: store, backup or none; error: the errorA backup failed (level warn when the memory ceiling refused it).
store.prune_donenoticestore.pruneeventup_to: the position pruned up to; snapshots_removed: snapshots removed; segments_removed: WAL segments removed; bytes: bytes freed; marks_unreachable: marks no longer reachableOld snapshots and WAL were removed.
store.damage_founderrorstore.damagestate per first_path until store.damage_clearedfound_by: the operation that found it; problems: how many problems; first_path: the first damaged fileDamage was found in the store's files while it is open.
store.damage_clearednoticestore.damageends store.damage_foundfirst_path: the file that was damagedDamage found earlier is gone. Not emitted yet: a later version (damage is cleared by a repair into a new store today).
store.maintenance_modeerrorstore.damageeventtrigger: what the open ran intoThe store opened in maintenance mode (read-only): its files are damaged.
store.repairednoticestore.damageeventtarget: the new store; commit_seq: its position; diverged: whether the salvaged state diverged from the WALThe store's salvaged state was written as a new store.
store.rolled_backnoticestore.rollbackeventtarget: the commit rolled back to; mode: move or delete; attic_entry?: the attic entry of the later historyThe store was rolled back; the later history moved into the attic (or was deleted).
store.attic_restorednoticestore.atticevententry: the attic entryAn attic entry was restored as the store's current history.
store.attic_removednoticestore.atticevententry: the attic entryAn attic entry was removed.
store.creatednoticestoreeventhow: create, packed, fork, attic_fork or repair; from_store_id?: the store it was made from; from_commit?: the position it was made fromThe store was created (the first record of every store).
store.upgradednoticestore.upgradeeventfrom_version: the old store format version; to_version: the new one; in_place: whether it was upgraded in place; models: the embedding models of models/ that became blobs (Graphersal 0.4.0 stores)The store was upgraded to this version's store format.
store.verifiedinfostore.verifyeventproblems: damage found; warnings: warnings; notes: notes (the system journal's among them)The store's files were verified (level warn when problems or warnings were found).
auth.deniedwarnauthevent, collapsed by action, resource_kind, channelaction: the action asked; resource_kind: the kind of resource; channel: the channel the work came throughThe authorizer denied a request (one per execution; no query text).
blob.damagederrorblobevent, collapsed by hash, failurehash: the blob's hash (hex); length: its length in bytes; failure: what failed: missing, length, crc or hash; found_by: the operation that found it; referrers?: the catalog definitions that reference it, as kind:name; recommendation: how to get the bytes backA blob is missing or damaged (never store damage: the store keeps working).
blob.repairednoticeblobeventhash: the blob's hash (hex); how: rewritten (written again) or restored (copied back); source?: where a restored blob came from (graphersal store restore-blobs --from)A damaged blob was replaced by intact bytes of the same hash.
blob.droppedwarnblobeventhash: the blob's hash (hex); referrers: the catalog definitions left out with it, as kind:nameA repair left out a missing or damaged blob and the catalog definitions referencing it (graphersal store repair --drop-damaged-blobs).
blob.collectedinfoblobeventcount: blobs removed; bytes: bytes freed; by: prune, attic_remove or rollback_deleteBlobs no retained history references were removed.
catalog.closed_commitnoticecatalogeventops: the catalog and schema changes of the commit; kinds: the definition kinds it changed; wal_tail_commits: the commits after the newest snapshot read to find the current catalog; ms: how long it tookA catalog change was appended to a CLOSED store's WAL as one commit, without loading the graph (format spec 12.12).
ledger.rebuiltnoticeledgereventframes: the frames written; reason: missing or damagedThe derived blob ledger was missing or damaged and was rebuilt from the WAL.
model.importednoticemodeleventrepo: its repository; identity: its identity; bytes: the bytes of its blob; default: whether it became the default model; closed?: true when the change was committed to a closed store (format spec 12.12)An embedding model was imported into the store (one commit defining it).
model.migratednoticemodeleventrepo: its repository (local/<12 hex> when 0.4.0 kept none); identity: its identity now; former_identity: its identity in the 0.4.0 store; bytes: the bytes of its blob; closed?: true when the change was committed to a closed store (format spec 12.12)An embedding model a Graphersal 0.4.0 store kept under models/ became a blob with a catalog definition (store upgrade to store format version 4; the migration commit).
model.replacednoticemodeleventrepo: its repository; old_identity: the replaced revision's identity; new_identity: the new revision's identity; closed?: true when the change was committed to a closed store (format spec 12.12)A new revision of an embedding model replaced the current one (one commit).
model.removednoticemodeleventrepo: its repository; identity: its identity; closed?: true when the change was committed to a closed store (format spec 12.12)An embedding model was removed from the store's current state (one commit).
model.default_changednoticemodeleventfrom: the repository of the previous default (empty: none); to: the repository of the new default (empty: none); closed?: true when the change was committed to a closed store (format spec 12.12)The default embedding model changed (one commit).
model.loadedinfomodelevent, collapsed by identityrepo: its repository; identity: its identity; load_bytes: the memory the loaded model takes, measured at the load (counted by the tracking allocator, else the loader's estimate), not its size on disk; ms: how long the load tookAn embedding model was loaded into memory.
model.unloadedinfomodelevent, collapsed by identityrepo: its repository; identity: its identityAn embedding model no open position uses was unloaded.
model.load_failederrormodelevent, collapsed by identity, causerepo: its repository; identity: its identity; cause: damaged, missing, does_not_fit or invalid; needed: the bytes a load needs (blob and loaded model); recommendation: how to bring the model backAn embedding model the schema needs did not load: the store did not open.
model.unavailableerrormodelevent, collapsed by identity, causerepo: its repository; identity: its identity; cause: damaged, missing, does_not_fit or invalid; recommendation: how to bring the model backAn embedding model nothing needs at open is missing or damaged: the store works, queries with the model fail.
vector_fill.startednoticevector_filleventreason: rule_added, rule_changed or model_replaced; rules: the rules filled: element, label, from, to, model; elements: the elements to embed; estimate_ms?: the estimated time, when the model's speed is knownA vector fill started under the write lock (a vector rule added or changed, or its model replaced): the whole database is locked until it ends.
vector_fill.donenoticevector_filleventembedded: the elements embedded; removed: the vectors removed (a source without text); elapsed_ms: how long the fill held the lockA vector fill ended with the commit of its unit (commit); op is its start record.
vector_fill.failederrorvector_filleventcause: the error; elapsed_ms: how long the fill held the lock; embedded_before_failure: the elements embedded before it failedA vector fill failed (the model, the memory ceiling, a cancel): its unit was rolled back, nothing was written.
index.unique_duplicateswarnindexevent, collapsed by namename: the index; key: its property key; repeated: how many values repeat; values: the first repeated values with their counts and example ids; recommendation: how to fix itA unique property index is not served after the open: its data holds repeated values (a store written without the constraint, or an index stored without the create check). Queries scan it and writes are not checked against it until it is dropped and created again after the repeats are removed.

Optimize

The storage advisor turns what the engine already measures into concrete advice: the memory report (what the graph holds), the workload statistics (how it is used) and the catalog. Every recommendation names the ordinary catalog command that applies it, a savings figure measured on the data where one can be measured, its cost, its impact and how sure the advisor is. Nothing is applied automatically, and every action of this version can be undone (drop the index or the rule again).

The recommendations

KindWhenEffect
create an indexa (label, key) filtered by a full scan at least 10 times in two days, on a label of at least 1,000 elements, with no index serving it and values an index holds; a scan with no single label (no label, or several) is advised a label-less index (g.create_index(#{key: ..}), id create_index:vertex:*:key, the elements of the kind count), and a label-less index on the key counts as serving every label; a key holding lists is advised transform: "each" (the elements of a list), and only an each index counts as serving itthe scans become index lookups; the index takes memory (estimated from the postings layout: about 48 bytes per distinct value, from the key's distinct string estimate or one per element, and 4 bytes per further element); a unique index is never advised
drop an indexno query used the index in the time observed, after at least 7 days of statistics; or (confidence low) a per-label index whose key a label-less index of the same element kind covers too, so its entries are kept twicefrees the index's memory (measured)
compressa top-level string property of at least 256 KiB without a rule, not indexed, read fewer than 1,000 times in two days, whose best lz4 candidate saves at least 64 KiB and 20 %frees memory, measured by estimate_compression with the rule's own code; every read decompresses
deduplicatea top-level property of any value type without a rule (indexed or not, read often or not; the 200 with the most values are measured, max_dedup_estimates) whose values repeat: at most one in 8 distinct (dedup_distinct_ratio), saving at least 1 MiB (min_dedup_saving_bytes) and more than lz4 would; the evidence names the values, the distinct ones and the saving in MiBfrees memory (each value keeps a 4-byte code instead of its 32-byte slot, each distinct value is stored once), measured like the above; writes look the value up: overwriting the key costs about 5-9 % more, adding a key that is new to an element of the label or a jpath write into a deduplicated value about 30 % more (measured at query level); reads stay plain and are mostly faster
stop compressinga compressed key read at least 1,000 times in two daysreads stop decompressing; memory grows back (measured)

Every recommendation has an impact, what applying it is worth, and a confidence, how much data its figures rest on: the two are separate, so a saving measured exactly on all the data (confidence high) can still be worth little (impact low).

KindImpact highImpact mediumImpact low
compress, deduplicate, drop an indexfrees 10 % of the graph's memory or morefrom 2 %below 2 %
create an indexits scans read 100 million elements or more in two daysfrom 10 millionbelow
stop compressingread 100,000 times or more in two daysfrom 10,000below

The graph's memory is its estimated total footprint (the memory report's totals). A saving of 6 MiB in a graph of 700 MiB (under 1 %) is advised with impact low.

The list is ordered by impact, the highest first; within one impact new indexes come first (by the elements their scans read), then compression by bytes saved, then unused indexes and hot compressed keys. The thresholds can be lowered: Every candidate in the playground, everything: true in the API, or each threshold on its own. Without workload statistics (a graph outside a store) only the data is looked at, so there is no index advice.

Applying several at once

The advice also groups its recommendations by kind (and for compression by codec), each group with its ids and its total: dedup: 74 keys, total -400.1 MiB. A group (or any pick of ids) is applied with ONE call: the advice is computed again, then every catalog change the picked recommendations name runs in one unit, so one commit (one WAL record, one entry in the change feed), and all the new compression rules re-encode the data in one pass over the elements of their labels instead of one pass per rule (see Several rules at once). It is all or nothing: an id no longer advised (the data or the workload changed since) or a refused change (its error names the rule or index) applies nothing. A new index or rule whose suggested name is taken by another definition is refused, never replaced. Nothing is picked for you: grouping only makes picking easier, a human still decides.

Each applied recommendation is recorded as if applied alone: the memory before it counts the promises of the others of the same call as kept, so its outcome under Applied is its own share while the promises hold (a deviation of the whole call from its promises shows on every outcome of the call alike).

After applying compression rules: write a snapshot

Write a snapshot after adding or dropping compression rules on a store (a bulk drop offers it in its message): graphersal store checkpoint <DIR> on a closed store, Write a snapshot now in the playground, Store::checkpoint in Rust. It is an optimization, not a requirement: the data is safe either way, and the rules work from the first commit.

Rules cost almost nothing in the WAL (74 rules: about 2 KiB), so the automatic checkpoint, which goes by WAL size, does not run because of them. Until a snapshot holds them, every open replays the change: it loads the rows as they are in the snapshot, then re-encodes the labels of the rules, in one walk for all the rules in a row, even over many commits (graphersal store repair walks the same way). A snapshot that holds the rules codes each row as it enters the graph, so the plain rows never fill memory. Measured on a real graph (2.8 million elements, 74 dedup rules, --release):

The storeOpenPeak memory of the processGraph after the open
rules only in the WAL8.5-10.5 s2.2-2.9 GiB1172 MiB
rules in a snapshot (the checkpoint took 1 s)8.4-11.4 s2.0 GiB1172 MiB

The start takes about the same here: the walk is paid for by the coding it spares. The cost of the walk grows with the elements of the labels the rules name, so the peak is what a snapshot saves on a graph that barely fits. Graphersal 0.5.2 and older walk once per rule and again per rule at the end of the open: the same store took 25.1 s, and 90 rules on a graph of about 3 GB in memory took an open from 14 s to 111 s. There a snapshot is what brings the start back.

Dismissing, and what an applied one did

A recommendation can be snoozed for 7 days or dismissed for good; it is then listed under Dismissed (with Restore) until its time. Applying one records the memory before and what it promised: for 30 days the advice lists it under Applied with the memory freed (or taken) since, measured on the graph's property and property index memory (other changes of the data in the meantime count too), and for a new index the indexed lookups of its key. Dismissals and these records are settings of the instance, not data: they are kept in the store's workload statistics sidecar and need a store.

In the playground

The top bar's Optimize opens one panel with three tabs:

  • Recommendations: each with its impact, its evidence, cost, memory effect (with its share of the graph's memory), confidence and the exact command; Apply runs it (one commit, recorded in the change feed like any catalog change), Copy copies the command, Snooze 7 days and Dismiss hide it; below the list, Applied (the outcomes) and Dismissed (with Restore). With more than one recommendation each has a checkbox, and Select all names the groups (dedup: 74 keys, total -400.1 MiB); nothing is ticked when the panel opens (a human picks). Apply selected shows what the selection frees and the titles, asks for confirmation and applies them in one commit, all or nothing. After a change of compression rules on a store, a note with Write a snapshot now stays until a snapshot holds that commit (see above).
  • Workload: the workload statistics as tables (queries, properties, locks, jobs) for a window (the last hour, 2 days or 90 days) and a channel, with a sparkline of the runs per row; a row opens its chart: runs per minute, hour or day with the failed part, and the mean and the longest time.
  • Memory: the memory report: the totals, then the properties and the labels, the most bytes first, with what is compressed, indexed or a vector; at most 500 rows per list, then a line saying how many more properties or labels are not shown and their bytes.

Other front ends

Front endHow
dev serverPOST /api/advise with the thresholds ({}: the defaults); POST /api/advise/apply {id, spec} applies one by its id, {ids: [..], spec} several in one commit ({ok, applied: [{id, kind, title, memory_bytes}], memory_bytes}); POST /api/advise/dismiss {id, days?} and POST /api/advise/restore {id}
MCPtool advise {everything} (reading, also in read-only mode); apply_recommendations {ids, everything} (writing, not offered in read-only mode) applies the ids the user picked in one commit; one recommendation can also be applied with create_index, drop_index, define_compression or drop_compression when the user asks
Pythongraph.advise(everything=False), graph.apply_recommendations(ids, everything=False) (both take policy=)
RustGraph::advise(&AdviceRequest), Graph::apply_recommendations(&ids, &AdviceRequest, authorizer), module graphersal::advisor (AdviceGroup)
use std::sync::Arc;
use graphersal::advisor::AdviceRequest;
use graphersal::prelude::*;
use graphersal::workload::{WorkloadLevel, WorkloadStats};

let graph = GraphSource::tinkerpop_modern();
graph.attach_workload_stats(Arc::new(WorkloadStats::new(WorkloadLevel::Memory)));
for _ in 0..3 {
    let found = graph.read().traversal().v(None).has_label("person").has("name", "josh").to_list();
    assert_eq!(found.unwrap().len(), 1);
}
// The modern graph is tiny: every candidate.
let advice = graph.advise(&AdviceRequest::everything()).unwrap();
let index = advice
    .recommendations
    .iter()
    .find(|r| r.id == "create_index:vertex:person:name")
    .unwrap();
assert_eq!(index.action.command(), r#"g.create_index(#{label: "person", key: "name"})"#);
// Apply a pick (here one group) in one commit; `None`: no authorizer to ask.
let group = advice.groups.iter().find(|g| g.kind == "create_index").unwrap();
let applied = graph.apply_recommendations(&group.ids, &AdviceRequest::everything(), None);
assert_eq!(applied.unwrap().len(), group.ids.len());

The JSON form (Advice::to_json, the answer of every front end) has workload_level, observed_since, commit_seq, property_bytes, graph_bytes (the memory impact is measured against), estimates and recommendations, each with id (stable: the kind and the target), kind, element, label, key, title, evidence, cost, memory_bytes (freed; negative when it takes memory), measured, impact and confidence (each low, medium or high), reversible, command and action (the catalog change as fields); then groups (key, kind, codec, title, ids, memory_bytes), dismissed (id, title, until: null for good) and applied (id, kind, title, at, promised_bytes, measured_bytes, index_lookups), and memory_bytes, the figure the outcomes are measured on.

Scheduled Jobs

The engine runs background work on a schedule: jobs with a standard 5-field cron schedule (minute hour day-of-month month day-of-week, e.g. */5 * * * * for every five minutes, 0 3 * * * for 03:00 every day; ranges 1-5, steps */15, lists 1,15, names jan/mon). Times are wall-clock times in the instance's local time zone.

Who drives the clock

The engine owns no thread: the host calls the scheduler's tick periodically with the current time, and the scheduler runs the jobs that are due.

HostTicks
Dev server (graphersal --server)a thread, every 5 seconds, in the machine's time zone (TZ or /etc/localtime)
Browser playgrounda timer in the engine's worker, every 5 seconds, in the browser's time zone
Your own programcall Scheduler::tick(now) yourself, or the two-phase form of Your own thread stays free

The CLI (a script or the REPL on a store) and the Python binding do not tick: a store opened there runs no jobs (its workload statistics are still written when it closes). Open the store with the dev server, or tick a Scheduler in your own program, to run them.

Daylight saving time. A schedule is read in the local wall clock. A time that does not exist on the day the clocks go forward (02:30 in most of Europe) runs right after the gap (03:00); a time that happens twice when they go back runs once, at its first occurrence.

A job never overlaps itself. A time missed while nothing ticked (the process was stopped) or while the job ran is skipped: the job runs at its next scheduled time. A failing job (an error, a panic) is recorded and runs again at its next time.

Requests go on while a job runs. The dev server does a job's work on a thread of its own: its session thread, which answers every request, only decides what is due and takes the result back, each a short step. Jobs of one type (query, checkpoint, backup) never run at the same time: a due job waits for the one running and starts at the first tick after it, its time is not missed. Other jobs run beside it. In the browser playground there is no such thread: a job runs in the engine's worker and its requests wait.

While a job of a user runs, the operations of the Store menu that move, remove or write the store's files (checkpoint, backup, rollback, attic restore and remove, compact, closing a database) answer 409 and change nothing: try again when it has finished. What the graph itself cannot offer, a job does not offer either: a query job that writes holds the graph's write lock from its first write until it commits, as any query does, and the system job compact holds it while it runs, so other queries wait for that time. Keep such jobs short with a timeout. A job whose saved query only reads holds no lock between its traversals, so writes go on beside it; each traversal sees the graph as it is at that moment.

Limits per run

A job may limit each of its runs: a timeout and a memory limit (JobLimits, both optional). The engine cannot interrupt arbitrary code, so the limits reach the checks every traversal already makes: while the job runs, its remaining time caps each traversal's evaluationTimeout and its memory limit (bytes) caps each traversal's per-query limit traversal.max_materialized_bytes (a query's own stricter value stays). The memory limit is compared with what the traversal itself holds at once (live bytes, the measure of the per-query limit: memory it frees is given back, what it adds to the graph does not count), never with the memory of the whole process: the process memory ceiling stays the same while a job runs, so a job with 256 MiB still runs in a process that holds 2 GiB. A breach fails the traversal as any timeout or memory limit does, its work is rolled back, and the run is recorded as failed with the reason. An action doing long work of its own checks limits.timeout itself; if it finishes past its timeout anyway, the run is recorded as over time.

System jobs

A Store brings its system jobs (Store::system_jobs()):

JobScheduleDefaultWhat it does
stats_flushevery minuteonwrites the workload statistics to the sidecar
compact03:00 dailyoffreleases spare capacity of the in-memory structure

System jobs cannot be removed; their schedule and switch can be changed (the playground's and the dev server's job list, POST /api/jobs/schedule and /api/jobs/enable, or WorkloadStats::set_job_override in your own program). The change is a setting of the instance, not of the graph: it is kept in the store's workload sidecar (at the level persisted, the default), so it survives a restart but is not carried by a backup or a fork. Every run (start, duration, error) is recorded in the workload statistics.

Jobs of users

A user's job is a catalog definition (kind job, beside saved queries, compression rules and property indexes): it is versioned with the graph, written to the journal, carried by checkpoints, backups and the catalog file. Its action is one of

ActionWhat a run does
querycalls a saved query with fixed arguments
checkpointwrites a checkpoint of the store
backupbacks the store up into a directory (the first run a full backup, the next ones increments)
g.define_query(#{name: "purge", params: #{label: "string"},
    body: "fn purge(label) { g.v().has_label(label).drop() }"});
g.define_job(#{name: "nightly_purge", schedule: "0 3 * * *", action: "query",
    query: "purge", args: #{label: "software"}, timeout_ms: 30000});
g.jobs().map(|j| [j.name, j.schedule, j.action])

g.define_job(#{name, schedule, action, query?, args?, path?, enabled?, timeout_ms?, memory_limit?, run_on?, description?}) defines or replaces a job, g.jobs() lists them, g.drop_job(name) removes one. The arguments are checked against the query's parameters when the job is defined.

Rights. A job runs with the rights of whoever defined it. When it is defined, the definer's authorizer is asked for everything the job will do: Execute on the saved query and every data write the query may make, Create on the backup directory; the allowed requests are stored with the job as its effects, and every run may do exactly them (and read). If the query is changed later to write more, its runs are refused until the job is defined again. Revoking the definer's rights later does not stop a job until it is redefined (the engine has no identities; an embedding server that has them re-checks on every run). A browser playground cannot define a backup job: its pages have no files.

A job of a newer version (an action this version does not know) is kept as it was written and never run; g.jobs() lists it with served: false and the reason.

Running. The jobs of a store's catalog run on the store's scheduler beside its system jobs: the dev server and the playground pick up a defined, changed or dropped job at their next tick. A query job's run is one transaction whose commit metadata carries job: <name> (the change feed and the history name the job), its queries count under the channel job of the workload statistics, and its limits per run apply. A run that fails (a write outside its effects, a timeout, an error of the query) changes nothing and is recorded with its error; the job runs again at its next time. A job on a graph outside a store is kept but not run (there is no scheduler). In your own program, give the scheduler the store's user jobs and sync them whenever the catalog's jobs changed. Store::user_jobs lists the job definitions it does not schedule beside them, each with the reason (an action or run_on this version does not know, run_on: "replica" on a single instance, a stored schedule that does not parse), so none is dropped silently:

let found = store.user_jobs()?;
for skipped in &found.not_scheduled {
    eprintln!("job {} is not scheduled: {}", skipped.name, skipped.reason);
}
scheduler.sync_user_jobs(found.jobs);

In the playground, Catalog ▸ Scheduled jobs lists every job (the system jobs first) with its schedule, the next and the last run (with its error), the runs of the last two days, a running badge while a run is under way, and a switch; a job of yours has Run now, Edit and Drop, a system job Run now and Schedule (empty: its built-in schedule again). New job opens the form: the name, what it does (a saved query with its arguments as JSON, a checkpoint, a backup directory), the schedule (5-field cron, with presets), on or off, a timeout and a description; a refused job shows the engine's message next to the field.

History. Every run (start, duration, error) is counted in the workload statistics as series job per minute, hour and day: the job list shows the runs of the last two days, Optimize ▸ Workload ▸ Jobs draws them over time, GET /api/jobs/history?name=..&tier=.. answers the buckets.

Front ends. The dev server and the playground share one job API (graphersal-session):

Dev serverWhat it does
GET /api/jobsevery job: the system jobs, then the jobs of users: schedule, on or off, next time, whether a run is under way, last run, the run counts of the last hour, two days and 90 days, whether it runs (and why not), a user job's action, arguments and effects
POST /api/jobs/definedefines or replaces a job from the keys of g.define_job; a refused job answers the wrong fields
POST /api/jobs/drop{name}: removes a job of a user
POST /api/jobs/enable{name, enabled}: switches a job on or off (a user job's definition keeps its effects)
POST /api/jobs/schedule{name, schedule}: a system job's schedule (null: the built-in one); a user job is defined again instead
POST /api/jobs/run{name}: runs a job now, whatever its schedule, and answers when it has finished (other requests go on meanwhile); refused while it or a job of its type runs
GET /api/jobs/history?name=..&tier=minutes|hours|daysthe job's runs per minute, hour or day: count, failures, total and longest time

The dev server's user owns the machine's files, so a backup job defined there may name any directory; the browser playground has no files and refuses backup jobs.

In your own program

Your own thread stays free

Scheduler::tick does the work on the calling thread. When that thread must stay free, split it: start_due(now) does the bookkeeping and hands out one JobRun per due job (start_now(name, now) for one on demand), JobRun::run() does the work on any thread, Scheduler::finish takes the result back. Until then the job and its group count as running; Job::with_group puts jobs that must not run together into one group (Store::user_jobs does it by type). A run that cannot be started (no thread) is given up with JobRun::abandon(reason), a failed run like any other.

for run in scheduler.start_due(now) {
    let results = results.clone();
    std::thread::spawn(move || results.send(run.run()));
}
// ... later, on the thread that owns the scheduler:
for finished in finished_runs.try_iter() {
    scheduler.finish(finished);
}

The whole program

use graphersal::jobs::{Job, JobKind, JobLimits, Scheduler};
use graphersal::persist::{MemDir, Store, StoreOptions};

let dir = MemDir::named("memory:jobs");
let store = Store::create(&dir, StoreOptions::new()).unwrap();
let mut scheduler = Scheduler::new()
    .with_time_zone("Europe/Berlin")
    .unwrap()
    .with_stats(store.workload_stats());
for job in store.system_jobs() {
    scheduler.add(job).unwrap();
}
scheduler
    .add(
        Job::new("hello", JobKind::User, "0 * * * *".parse().unwrap(), |run| {
            let _started = run.started_at; // your work; traversals here get the limits below
            Ok(())
        })
        .with_limits(JobLimits::new().with_timeout(std::time::Duration::from_secs(30))),
    )
    .unwrap();
let now = 1_800_000_000_000_000; // microseconds since the Unix epoch
scheduler.tick(now); // plans the first runs; call it again every few seconds
assert_eq!(scheduler.jobs().len(), 3);

Embedding Models in a Store

A store keeps the embedding models its vectors were made with. A model is data of the database: ONE blob (its files as a deterministic tar, see Blobs) referenced by a catalog definition of kind model that follows the history like every other definition. Every position of the store (a commit, a mark, a snapshot, a rollback, a view of the past) has exactly the models, and the default model, of that moment; every copy of the store carries them. The normative description is the format specification, sections 4.5 and 6.3.

A model is named by its repository (minishlab/potion-base-8M): that is the name embed and text queries use. Inside, the schema records the model's identity (model2vec/<repo>@<12 hex>, a hash of its files), so the vectors stay tied to the exact model that made them.

An import is the ONLY way a model serves a database: the step embed(), the function embed(text), text queries, vector rules and g.embedders() use the built-in hash-ngram/1 and the models of the database, nothing else. (Graphersal 0.4.0 also served models given on the command line, --embedder, or registered by a host; 0.5.0 removed that. A host with a model of its own computes the vectors itself and writes them as values.)

Importing a model

graphersal embed-model download minishlab/potion-base-8M          # once, into the download cache
graphersal embed-model import minishlab/potion-base-8M --into data/ --default
graphersal embed-model import minishlab/potion-base-8M --into data/ --replace   # a new revision

The download fills the download cache ($GRAPHERSAL_EMBED_MODELS, else %LOCALAPPDATA%\graphersal\embed-models on Windows, $XDG_CACHE_HOME/graphersal/embed-models, else ~/.cache/graphersal/embed-models; --dir for another one): one download, imported into any number of databases without the network. The import takes a repository from the cache first, else the argument as a model directory (--repo, --license fill what a directory does not say). --default makes the model the default, --replace replaces another revision of the same repository (below). The import writes the model's files (config, tokenizer, weights, model card, licence files) as one blob and commits one definition.

From Python:

store.import_model("minishlab/potion-base-8M", default=True)          # an open store
graphersal.Store.import_model_into("data", "minishlab/potion-base-8M")  # a closed store

import_model(source, *, repo=None, license=None, replace=False, default=False) returns the report as a dict; the wheel has no download client, so the cache is filled by the command line. In Rust (the cache lookup is persist::ModelCache: ModelCache::new()?.source("minishlab/potion-base-8M") gives the ModelSource):

use graphersal::persist::{ImportModelOptions, ModelSource, Store, StoreOptions};

let store = Store::open("data", StoreOptions::new())?;
let report = store.import_model(
    ModelSource::Dir("models/minishlab/potion-base-8M".into()),
    ImportModelOptions::new().with_default(true),
)?;
println!("{} ({}), commit {:?}", report.model.repo, report.model.identity, report.commit_seq);
  • The same model again commits nothing (already_present).
  • Another revision of a repository the store holds is refused (ModelRevisionExists) unless with_replace(true): then the new revision replaces the old one in ONE commit (and becomes the default if the old one was). Vector rules naming the old revision are switched to the new one and their properties re-embedded in the same commit; vectors of the old revision without a rule refuse the replace (ModelInUse).
  • ModelSource::Files(NewModel) imports files given as streams (a host without a file system, such as the browser).
  • A closed store: Store::import_model_dir (what the CLI does). See the next section.

Changing the models of a closed store

Store::import_model_dir, Store::set_default_model_dir and Store::remove_model_dir (CLI embed-model import|download --into <dir>, store models default <dir> [<repo>|--none], store models remove <dir> <repo>; Python Store.import_model_into) change the catalog of a CLOSED store WITHOUT loading its graph: seconds on a store of any size. Each takes the writer lock (a store open elsewhere is refused with Locked: make the change on the open store, or close it), reads the catalog of the latest position from the newest snapshot's manifest and the WAL after it (the data changes are read and checked, not applied), and appends ONE ordinary commit to the WAL, synced (format spec 12.12). The commit is part of the history like any other: the next open replays it, a rollback goes behind it, changes_since and backups carry it, and it is recorded in the system journal (catalog.closed_commit, plus the model.* record with closed: true). The same refusals apply as on an open store (ModelRevisionExists, ModelInUse, UnknownModel, InvalidModel); a change that changes nothing (the model is the default already, the same identity imported again) writes nothing. The needed-model check of an open does not apply, so an import is also how a missing model comes back. ClosedCommitOptions::with_principal records who made the change (the CLI records cli).

A replace (ImportModelOptions::with_replace) stays such a closed commit when no schema property uses the old revision. When vector rules name it, the replace re-embeds their properties in the same commit, which needs the data: then, and only then, Store::import_model_dir OPENS the store (its graph is loaded, the store is write-locked for the time) and runs the open store's import; ImportModelReport::reembedded names the re-embedded properties and the first warning says that the store was opened (the CLI prints it as a note:). Vectors of the old revision without a rule (no "from") refuse the replace with ModelInUse on both paths.

A damaged store refuses the change: open it (it opens in maintenance mode) and repair it first. The commit reads the WAL after the newest snapshot; on a store with a very long WAL tail run graphersal store checkpoint <dir> first.

The default model

Store::set_default_model(Some(repo)) makes a model the one embed uses without a model name (one commit; None clears it; on a closed store Store::set_default_model_dir, CLI graphersal store models default <dir> <repo> or --none, or embed-model import --default). At most one model is the default. Without one, embed uses the built-in hash-ngram/1, and the front ends (CLI, dev server banner, playground, Python) note that the store holds models but none is the default.

Removing a model

Store::remove_model(repo) (CLI graphersal store models remove <dir> <repo>, on a closed store Store::remove_model_dir) commits the removal of the definition. It is refused while the current schema needs the model (ModelInUse: re-embed or drop the properties first). Earlier positions keep the model; its blob is removed by the prune that drops the last retained history referencing it.

Loading and memory

A model the CURRENT schema needs (a vector property's embedder names it) is loaded when the store opens; every other model is loaded at the first query that embeds with it. A model is loaded once per process, shared by every position that uses the same blob, and unloaded when no position uses it any more. Loaded models count in g.memory_usage() as model_bytes and fall under the process memory ceiling: before a load the ceiling is checked with the blob's length times 1.6 (potion-multilingual-128M's 506 MiB blob takes 514 MiB loaded and its load peaks at about 1.14 times the blob, plus a reserve), so nothing is read when it does not fit. The load streams the blob: its tar is read entry by entry and the embedding matrix is decoded while it streams, so the memory a load needs at its peak is about the loaded model plus the tokenizer's parse, never a second copy of the blob. The blob is read to its end and checked (length, CRC-32C) before the tokenizer is parsed, so a damaged blob is reported as damage.

The store does not open (in any mode: writable, --read-only, a backup, a view of a past position) when a model its schema needs is not in its catalog at that position, its blob is missing or damaged (ModelUnavailable; the message names the commands that bring it back), or it does not fit under the ceiling (ModelDoesNotFit, naming the smallest ceiling that fits). A model nothing needs that is damaged is a journal record (model.unavailable); the store works. A build that cannot run models (the browser playground, a library build without the feature model2vec) opens a store whose schema needs one read-only, without text queries.

Listing

Store::models() (CLI graphersal store models <dir>, store info) lists the models of the current position: repository, identity, revision, dimension, licence, size (a model that is not loaded shows its size on disk, the blob; a loaded one the memory measured at its load, ModelInfo::memory_bytes, ModelInfo::shown_bytes()), whether it is the default, its state (loaded, not_loaded, damaged, missing, unsupported) and the schema properties that need it. Store::verify reads every model's blob and checks it is the tar of its identity.

The licence travels with the model

The licence the repository states, its licence file (or, without one, the unchanged standard MIT or Apache-2.0 text of the licence the model card names, kept as LICENSE with a first paragraph saying where the text comes from; the copyright holders are those the model card names) and the licences of its base models are part of the model's tar. Graphersal never writes a licence of its own. graphersal store models <dir> and graphersal store info <dir> name every model with its licence and where the licence text comes from (ModelInfo::license_text): who hands a store or a copy of it on redistributes its models.

$ graphersal store models data/
── Embedding model ───────────────────────────────────────────────────────────
  model:        acme/tiny
  full name:    model2vec/acme/tiny@0123456789ab
  size:         29.5 MiB
  licence:      mit (named in the model card)
  licence text: standard MIT text (the repository has no licence file)
  default:      yes
  used by:      the schema (doc.emb)

The other two forms of licence text are from the repository (its own licence file) and none (no standard text for this licence).

What carries the models

Every copy: full and incremental backups, the ZIP backup, fork, attic fork, repair, conversion and upgrade, a packed snapshot (.gsnap; --without-models leaves the blobs out, the definitions stay and the models are then missing in the copy). Prune, checkpoint and compact keep the blobs the retained history references.

A .gsnap without a store

A packed snapshot exported from a store (graphersal store export, the playground's "Save graph") carries the blobs of its models, and so does what a graph serving models writes itself (g.export_snapshot, Python graph.save, the dev server's Save to file), also over the very file it was loaded from. Loaded WITHOUT a store (graphersal --graph file.gsnap, GraphSource::from_file, Python Graph.load; in Rust persist::read_snapshot_file, which also returns a SnapshotLoadReport) the graph serves those models: embed(), embed(text), text queries, vector rules and g.embedders() use them as a store's graph does. The load only notes where each model's blob lies in the file; a model is loaded at its first use by reading its blob from the file (checked by length, CRC-32C and SHA-256), so no copy of a blob stays in memory, only the loaded model. The file must therefore stay as it was while the graph serves its models: a file changed, truncated or removed after the load makes a model that was not loaded yet unavailable, with an error naming the file (a model loaded before keeps running). A graph with no packed models has the built-in hash-ngram/1 only. Changes stay in memory: the file is never written.

  • A .gsnap of Graphersal 0.4.0 holds its models as model rows: they are converted as the store upgrade converts them (one blob and definition each; a model without a repository becomes local/<12 hex> and the schema's embedder naming it is rewritten in memory), the file stays as it is. The load reads the rows once to convert them (briefly holding a model's files in memory) and keeps only how to build each model's tar; the tar is built again from the rows when the model loads. graphersal store create <dir> --from file.gsnap keeps them converted (the documented route for a 0.4.0 file).

  • A .gsnap exported --without-models keeps the definitions but not the blobs: the models are listed as missing, and a query that needs one fails with the import command. In a store made from it, graphersal embed-model import <repo> --into <store> (or Store::import_model) of the same model writes its blob back.

  • A 0.4.0 .gsnap whose schema names a model the file does not carry (0.4.0 served it through --embedder) loads, but text queries and vector rules on those properties fail until the graph is in a store holding the model: graphersal store create <dir> --from file.gsnap makes the store (and says so with a warning:), the import puts the model in, then the store opens.

  • The CLI prints what the load found as note: lines on stderr (SnapshotLoadReport::notes, the same text in Python as a UserWarning, in Rust from the report; GraphSource::from_file logs them as tracing warnings): converted models, models stored but none the default, models the schema names that the file lacks, vector properties without a rule, saved queries calling a removed function. Their schema patches run in a store (graphersal store create <dir> --from file.gsnap, then graphersal --graph <dir> -e '...'): a schema change of the loaded file stays in memory. Each note is a short headline with one detail per line below it and every command on a line of its own under a comment saying what it does, for example

    note: data.gsnap holds 2 embedding model(s) but none is the default
      effect: embed() without a model name uses hash-ngram/1
      name one: g.v().embed("text", #{embedder: "acme/tiny"})
      # or make one the default, in a store
      graphersal store models default <dir> <repo>
    

Older Graphersal versions

Graphersal 0.4.0 kept models as models/<model2vec-12hex>/ directories outside the history, in stores of store format version 3. This version opens such a store only after graphersal store upgrade (in place or into a copy), which turns each model into a blob and defines all of them in ONE commit (principal upgrade); the history before that commit has no models. No default model is set. A model kept without a repository name becomes local/<12 hex> (import it again with --repo to give it its name). A ZIP backup of 0.4.0 is migrated as it is restored, a .gsnap with model rows when a store is created from it. The upgrade also lists the models the schema needs that the store lacks, and every vector property with a model but no source property (from): see 0.4.0 -> 0.5.0.

Blobs

A blob is an immutable file of a Store, named by the SHA-256 of its content (blobs/<2 hex>/<64 hex>). A catalog definition references it by a BlobRef (facade graphersal::blob): the hash, the content's length and its CRC-32C. Blobs hold large binary content beside the graph (the files of embedding models, later user BLOB values) without passing it through the write-ahead log. The byte-level rules are the format specification, section 4.6.

use graphersal::blob::{BlobHashAlgo, BlobRef};

let blob = BlobRef::new(BlobHashAlgo::Sha256, &[0xab; 32], 1024, 7).unwrap();
assert_eq!(blob.relative_path(), format!("ab/{}", "ab".repeat(32)));

Writing and reading

Store::write_blob(reader) streams the content into a temporary file while it computes the SHA-256, the CRC-32C and the length (constant memory), syncs it and renames it to its name. The same content written twice is stored once. The returned PendingBlob protects the new blob from every collection until you drop it: put its BlobRef into a catalog definition's payload, commit, then drop the handle. A blob that no commit references is an orphan the next prune removes.

Store::read_blob(&blob) returns the content: the length is checked first, the process memory ceiling before anything is allocated (operation "blob read"), the CRC-32C after reading. The SHA-256 is computed only when content is written or arrives from outside and by verify, never on a read.

In this version a BlobRef lives only in catalog payloads: a graph refuses it as an element property value (GraphError::InvalidPropertyValue, kind "blob reference").

How long a blob stays

A blob stays exactly as long as some retained history references it: a snapshot's blob table, a commit in the WAL (the derived ledger file lists every commit's reference changes), or the history an attic entry keeps. prune, removing an attic entry and a rollback with delete remove every other blob (PruneReport::blobs_removed, the journal record blob.collected). Store::info() lists the blobs by name and length (StoreInfo::blobs: count, bytes, how many no history references); graphersal store info prints a blobs line when there are any.

Copies

Every copy carries the blobs its history references, checked by length and CRC-32C on both sides: full and incremental backups, ZIP backups (entries blobs/<2 hex>/<hash>, checked by their hash again on restore), backups from memory, forks, attic forks, repairs, conversions and packed snapshots (.gsnap, as rows of segment kind 4). BlobCopy::Exclude (ModelCopy is its 0.4 name) leaves the models and blobs out of a ZIP backup or a packed snapshot meant to be shared; the copy's catalog still references them, so the receiver has them missing.

Damage

A missing or damaged blob is not damage of the store: the damage policy does not apply, nothing turns read-only, and only what needs the blob's bytes fails (StoreFailure::BlobUnavailable or BlobDamaged). The system journal gets one blob.damaged error per blob and failure, with a recommendation; graphersal store verify lists every missing or damaged blob. Any copy with the same hash is the same bytes, so two tools bring a store back to a healthy state:

  • Restore the blobs from any copy that still has them: a backup directory (full or with its increments), a ZIP backup, a packed snapshot (.gsnap) or another store (a fork, a repaired copy, a .gstore). The store must be closed (the writer lock):

    graphersal store restore-blobs <dir> --from <backup_dir|file.zip|file.gsnap|other_store> [--json]
    

    In Rust Store::restore_blobs_from(dir, BlobSource::store(..) | BlobSource::zip(..) | BlobSource::packed(..)). Every blob the store's retained history references is checked (length, CRC-32C, hash); each missing or damaged one is looked up in the source by its algorithm and hash (a blob of an unknown algorithm by its name), streamed into blobs/tmp-*, checked the same way, synced and renamed into place. A healthy blob is never touched. The report (RestoreBlobsReport) lists what was restored, what the source does not hold and what it holds damaged too; the command exits 1 unless every referenced blob is intact afterwards. Each restored blob is a blob.repaired record (how = restored, source).

  • Leave them out when no copy exists: graphersal store repair <dir> --to <new_dir> --drop-damaged-blobs (RepairOptions::with_drop_damaged_blobs) builds a repaired store without every catalog definition that references a missing or damaged blob (and without the blob): RepairReport::blobs_dropped and definitions_dropped, one blob.dropped record per blob in the new store's journal. It is refused, before anything is written, while the schema needs such a definition (a model a vector property's embedder names); the error names the properties: restore the blob first, or change the schema. Without the flag a repair carries the definitions and reports their blobs as not carried.

  • Fill them while copying: graphersal store convert <dir> <new> --fill-blobs <source> (Store::convert_with(from, to, ConvertOptions::new().with_fill_missing_blobs(source))) makes the conversion copy of a closed store and fills every blob it references but lacks (or holds damaged) from the same kinds of source, checked the same way, into the COPY only: the source store and the fill source are only read. A host that keeps its model blobs in one shared directory laid out as blobs/<2 hex>/<hash> passes that directory (BlobSource::store). A blob the source does not hold, or holds with other bytes, fails the conversion (StoreFailure::BlobUnavailable / BlobDamaged, naming it) and leaves no copy; the report (ConvertReport) lists the blobs filled, and each is a blob.repaired record in the copy's journal.

  • Copy without them, to fill them later: ConvertOptions::with_skip_missing_blobs() (with or without a fill source; Rust only, no CLI flag) completes the conversion when a referenced blob is missing from the source store (and from the fill source): the copy is made without it, no placeholder is written, and ConvertReport::blobs_missing names each one. The copy is in the same state as a store whose blob was lost, which is not damage: Store::models_dir lists its model as ModelState::Missing, an open is refused with StoreFailure::ModelUnavailable while the schema names the model as an embedder (otherwise the store opens and only the calls that run the model fail), and Store::verify reports the absent blob until it is filled with restore-blobs (Store::restore_blobs_from). The copy's verification still checks everything else: a blob that is present but damaged, or one the fill source holds with other bytes, still fails the conversion.

By hand, copying the file blobs/<2 hex>/<hash> from another copy works too, and writing the content again (Store::write_blob) replaces a damaged blob.

The graphersal store Command

graphersal store <COMMAND> ... manages a Store from the command line. The store itself is used with graphersal --graph <DIR> (the REPL, -e, --in, --server): every commit of a query is durable before the query returns.

graphersal store help                 # the overview (also: graphersal store, without a command)
graphersal store help rollback        # one command
graphersal store rollback --help      # the same (-h works too)

Conventions

  • DIR is a store: a directory, or a single-file store (an existing file, or a new path ending in .gstore). Every command works on both.

  • TARGET is one of --at-commit <N> (right after commit N), --at-time <TIME> (after the last commit at or before TIME) or --at-mark <NAME>. TIME is an RFC 3339 / ISO 8601 date-time with a zone (2026-10-08T02:43:00Z, 2026-10-08T02:43Z, 2026-10-08T04:43:00+02:00) or microseconds since the Unix epoch; it covers the whole second (minute) it names. A bare date (2026-10-08) is refused with the explicit forms to write instead (2026-10-08T23:59:59Z for the end of that day in UTC, 2026-10-08T00:00:00+02:00 with an offset). See Point in Time.

  • Options take their value as the next argument or after = (--up-to 5, --up-to=5). An option a command does not know is a usage error.

  • Exit codes: 0 ok; 1 the operation failed (the diagnostic with a Help: line is on stderr), verify found damage, or repair lost data; 2 invalid invocation (unknown command or option, a missing argument or option value, a bad time, graphersal store without a command). The same holds for graphersal --graph <DIR>: a store that cannot be opened (in use, damaged beyond a read-only open, an older format) exits 1; a <DIR> that is not a store (without --create-store) or a wrong option exits 2. A command whose stdout was closed before its output was written (graphersal store info x | head -1) completes, closes the store and exits 141 (unless it failed: then its own code).

  • Warnings of the store library (damage found, a read-only open, a failed write of GRAPH, a failed automatic checkpoint) are printed on stderr as WARN graphersal::persist::store: ..., never on stdout: by the store commands and by every mode of graphersal --graph <DIR> (-e, --in, a script file, the REPL, --server). GRAPHERSAL_LOG sets the level: off, error, warn (default), info, debug, trace.

  • A read-write open (--graph <DIR>, mark, prune, rollback, compact, attic restore|remove) that finds one GRAPH copy missing, damaged or stale rewrites it from the other and says so in a note, with the command that checks the rest:

    note: the store data/: GRAPH.copy is not usable (...); GRAPH is used; the other copy was rewritten from it
      # check the rest of the store
      graphersal store verify data/
    
  • Layout. Every result is one block per thing the command did: a short headline, then one indented key: value per line, and every shell command on a line of its own under a # comment saying what it does (never inside a sentence); blocks are set apart by a blank line. Lists of records (models, attic) show one section per record with one field per line. A usage error ends with the command that shows the usage, an error's Help: lists its commands the same way.

  • Times are printed in UTC (2026-10-08T07:05:08Z), in the form --at-time accepts back.

  • While the store is open elsewhere (a dev server, a REPL): info, list, marks, verify, fork, backup, export, repair, compact-advice and attic (list, changes, fork) work; mark, checkpoint, prune, compact, rollback, attic restore|remove and convert fail with "in use" (exit 1): use the dev server's Store menu, or stop the writer.

  • On a backup directory the reading commands work, prune prunes the backup, restore makes it the live store, and the commands that write report that it is a backup.

Commands

CommandDoes
createcreate a store
infoidentity, position, snapshots, marks, WAL size
listthe snapshots
marksthe marks
markname the current position
checkpointmerge a snapshot now (closed store)
verifyscrub every checksum
journalthe system journal: what the store did
forka past state as a new store
rollbacktake the store back in place
atticlist, inspect, restore, fork, remove rolled-back history
backupfull, incremental or ZIP backup
restorea backup (or ZIP) as the live store
exporta stored snapshot as a .gsnap
materializea layer store's whole visible graph as a standalone .gsnap
modelsthe embedding models the store keeps; remove one
pruneremove old history
compactprune to now; give a single file's free space back
compact-adviceis compact worth it?
converta directory into a single file, or back
upgradea store of an older Graphersal, converted to the current format
repaira damaged store, repaired into a new directory
restore-blobsmissing or damaged blobs copied back from another copy

Layer stores (a layer's changes to a frozen base, kept with graphersal --graph <base> --layer-store <dir>; Layers): the commands that read or copy files work on them without the base (info, list, marks, journal, the attic listing and changes, backup, restore, export, convert, upgrade). Those that load the layer take --base <SOURCE>, the base it was created over (a store directory or .gstore, opened read-only, or a .gsnap): verify, checkpoint, fork, rollback, attic restore|remove|fork and materialize. Without it they exit 1 with the LayerStore reason and a note naming --base; another base exits 1 naming both (LayerBaseMismatch); a --base that is not a store or .gsnap is a usage error (exit 2). repair and models remove|default refuse a layer store (exit 1), and models <DIR> says that its graph serves the base's models. The commands' "open it" hints name --layer-store.

create

graphersal store create <DIR> [--from <SOURCE>] [--chunk-size <BYTES>] [--single-file]
                        [--on-damage maintenance|continue]

Creates a store in the new (missing or empty) DIR, at commit 0 with one snapshot. The chunk size, the damage policy and the backend are fixed for the store's life.

Option
--from <SOURCE>the initial graph: the --graph sources modern, empty, large, tree, a GraphSON/GraphML file, or a packed snapshot (.gsnap, copied as is). Default: an empty graph
--chunk-size <BYTES>the snapshot chunk size (default 1 MiB), fixed for the store's life
--single-filea single-file store whatever the name (a DIR ending in .gstore is one anyway)
--on-damage <POLICY>what the store does when damage is found on disk while it is open: maintenance (default: it turns read-only) or continue (it keeps committing and reports the damage); fixed for the store's life
$ graphersal store create data/ --from modern
Created the store data/
  graph: 01a11a54-8209-7661-92e2-147ae6d8bbd3
  commit: 0
  snapshots: 1
  damage policy: maintenance (fixed for its life)
  # open it in the REPL
  graphersal --graph data/
  # or serve it to the browser playground
  graphersal --graph data/ --server
$ graphersal store create graph.gstore --from modern --on-damage continue
Created the single-file store graph.gstore
  graph: 01a11a54-8ca5-7fd3-8ed5-fcd7729f0e80
  commit: 0
  snapshots: 1
  damage policy: continue (fixed for its life)
  # open it in the REPL
  graphersal --graph graph.gstore
  # or serve it to the browser playground
  graphersal --graph graph.gstore --server

A packed snapshot makes the store without opening it (Store::create_from_packed_dir), and what the file brought that still needs your decision is printed as store upgrade prints it (exit code 0): the converted models of a Graphersal 0.4.0 file, a warning: for every model the schema needs that the file does not carry (a 0.4.0 file whose model came from --embedder, or an export --without-models; the store is created and opens once the model is imported, with the commands named), a note: per model for the vector properties without a source property (one note listing them with one combined patch), a note: for every saved query writing such a property directly and for every saved query calling a removed function. Each note is a short headline with one detail per line below it and every command on a line of its own under a comment saying what it does; notes are separated by a blank line. When the store has no default model and the missing model is the only one the schema names, its import takes --default:

$ graphersal store create data/ --from old.gsnap
Created the store data/
  graph: 01a11a54-9f3c-7b21-8e0d-5a2c9e41d7b3
  commit: 3120
  snapshots: 1
  damage policy: maintenance (fixed for its life)

warning: the schema needs the embedding model acme/tiny, which the store does not keep
  identity: model2vec/acme/tiny@0123456789ab
  needed by: doc.emb
  effect: the store does not open until the model is imported
  # download the model into the local models directory
  graphersal embed-model download acme/tiny
  # import it into the store as its default model (embed() without a model name uses it)
  graphersal embed-model import acme/tiny --into data/ --default

note: doc.emb has vectors of model2vec/acme/tiny@0123456789ab but no source property
  vectors: 250 element(s)
  ...

Open data/
  # open it in the REPL
  graphersal --graph data/
  # or serve it to the browser playground
  graphersal --graph data/ --server

Exit 2 when the source cannot be loaded or --on-damage names no policy; 1 when DIR is a directory that is not empty (cannot create a store in data/: the directory is not empty, with the help to choose an empty or new directory, or to look at it with graphersal store info data/ if it is a store) or a store already (it is a store already). graphersal --graph <DIR> --create-store [--on-damage <POLICY>] creates a store on first use instead (--on-damage without --create-store is a usage error; for an existing store with another policy it is refused: the policy never changes).

info

graphersal store info <DIR>
$ graphersal store info data/
store       data/
format      version 2
graph id    01a11a54-8209-7661-92e2-147ae6d8bbd3
state       closed cleanly
commit      3 (2026-10-08T07:05:08Z)
snapshots   2
  latest    commit 3 (8 vertices, 6 edges)
marks       1
definitions 2 (compression 1, query 1)
wal         2 segment(s), 462 bytes
file        a directory
fixed at creation (never changed):
  store id      01a11a54-820a-7c33-b1f0-5d2e9a7c4e10
  created       2026-10-08T07:05:08Z
  chunk size    1048576 bytes
  on damage     maintenance (damage found while open makes the store read-only)
  backend       directory (format version 4)

Also printed when they apply: for a layer store its base as base under "fixed at creation", with the command that opens it (graphersal --graph <BASE> --layer-store <DIR>; it holds only a layer's changes to that base and opens only over it, and a backup of it is useless without that base, which store backup warns about; see Layers for the commands that take --base), parent and branched at (a fork, a rolled-back store), backup up to commit N with taken and access below it and the command that makes it the live store (a backup), attic N entr(y/ies), the embedding models the store keeps (a models block: one block per model under its repository, one field per line: full name (the identity), size, licence, licence text, default, used by; a model the schema names but the store lacks as missing model, see models), the store's blobs (blobs N (size) with in use and unused below it: a blob is in use while a retained history references it, for example the catalog definition of a model the schema uses, and the next prune removes the unused ones; in use not counted when the references could not be read; see Blobs), and for a single file its size with live and free below it and the command that tells whether compacting pays:

file        single file, 23.0 KiB
  live      23.0 KiB
  free      0 B inside the file
            # see whether compacting gives that space back
            graphersal store compact-advice graph.gstore

state is open (in use, or not closed cleanly) while a writer has it (or after a crash).

A store written by a newer Graphersal (its GRAPH, a snapshot or WAL file, or the single file's container of a newer format version) is not read: info, like every store command (upgrade and repair included) and --graph, exits 1 with the refusal and changes nothing (no lock file either):

$ graphersal store info data/
Error: Unsupported format version 4 of the store data/ (store format version): written by a newer Graphersal (this build reads up to version 3)
Help: The store or file was written by a newer Graphersal; open it with that version (or a later one). ...

See Format Versions.

list

graphersal store list <DIR>
      commit  last commit             vertices       edges  name
           0  -                              6           6
           3  2026-10-08T07:05:08Z           8           6  nightly

The snapshots, oldest first: the commit, the time of that commit, the counts, the name. Reads only the manifests' first 4 KiB.

marks

graphersal store marks <DIR>
           1  2026-10-08T07:05:08Z  before-import

The marks: commit, time, name.

mark

graphersal store mark <DIR> <NAME>

Sets the mark NAME at the current position (Mark "before-import" at commit 1.). Names are unique along the store's whole history. "In use" while a server has the store open (its Store menu has Mark).

checkpoint

graphersal store checkpoint <DIR> [--name <NAME>] [--base <SOURCE>]

Writes a snapshot of the current state of the CLOSED store, merged from the last snapshot and the WAL after it without loading the graph (how):

Snapshot at commit 3
  vertices: 8
  edges: 6
  merged from: the snapshot at commit 0 and 3 commits
  segment files: 4 reused, 0 copied, 1 written

written: no: nothing was committed after it, no new snapshot written when the newest snapshot is current. "In use" while another process has the store open (a server's Store menu has Checkpoint, which merges the same way while commits go on). Damage in what it reads stops it with exit 1 and nothing written; run verify. A layer store needs --base: its layer is loaded over the base and encoded (encoded from: the loaded graph ...), a snapshot the size of its changes.

verify

graphersal store verify <DIR> [--base <SOURCE>]

Reads every checksum (snapshots, WAL, GRAPH, marks) and says what it read (Checked the store data/ with snapshots, WAL segments, records and commits below it). Exit 0 with ok: no damage found; exit 1 with every problem and the damage report (the donor of each damaged item). See Verify. Files of a newer format version are never listed as damage: verify exits 1 with the "written by a newer Graphersal" refusal shown under info (no DAMAGE lines, no repair advice), and store repair refuses such a store the same way. A layer store is checked without its base file by file (a note: says its snapshots were not loaded, and a block names store verify <DIR> --base <BASE>); with --base every snapshot is also loaded over the base.

fork

graphersal store fork <DIR> <NEW_DIR> [TARGET] [--base <SOURCE>]

A new store in NEW_DIR (it must not exist, or be empty) from the state at TARGET (default: the latest), with a new lineage that records DIR as its parent. DIR is not changed.

$ graphersal store fork data/ branch/ --at-mark before-import
Forked data/ into branch/
  at commit: 1
  graph: 01a11a54-87d2-7995-b2cb-e450e4319735
  parent: 01a11a54-8209-7661-92e2-147ae6d8bbd3
  marks not carried: 1 (they stay targets of data/ only)
  mark: before-import @ commit 1
  undo: delete the directory branch/ (data/ is unchanged)
  # open it in the REPL
  graphersal --graph branch/
  # or serve it to the browser playground
  graphersal --graph branch/ --server

A fork starts without marks: the marks not carried and mark lines (printed only when there are any) name the source's marks at or before the fork's position. Exit 1 when the target is not reached (Recovery target mark "nosuch" not reached). A layer store needs --base; the fork is a new layer store over the same base (its hint: graphersal --graph <SOURCE> --layer-store <NEW_DIR>).

rollback

graphersal store rollback <DIR> TARGET [--delete]

Rolls the store back in place to TARGET: everything after it moves to the attic (with --delete: deleted, no undo), and the store continues as a new lineage. Prints the attic id and the commands that undo it. Exit 2 without a target; exit 1 when there is nothing after the target or the store is in use. See Rollback and the Attic.

$ graphersal store rollback data/ --at-commit 1 --delete
Rolled back data/ from commit 4 to commit 1
  new lineage: 01a11a54-8b90-7dba-b74a-cadc851e226f
  history after it: commits 2..=4, 1 snapshot(s), 2 WAL file(s)
  kept: no: deleted, this cannot be undone
$ graphersal store rollback data/ --at-mark before-import
Rolled back data/ from commit 4 to commit 1
  new lineage: 01a11a54-8b91-7c02-9d4e-3f6a8b2c1d07
  history after it: commits 2..=4, 1 snapshot(s), 2 WAL file(s)
  kept: in the attic as 20261008T070510Z-00000000000000000002
  # undo (only while nothing new is committed or marked)
  graphersal store attic data/ restore 20261008T070510Z-00000000000000000002
  # or keep it as a new store
  graphersal store attic data/ fork 20261008T070510Z-00000000000000000002 <NEW_DIR>
  # or delete it
  graphersal store attic data/ remove 20261008T070510Z-00000000000000000002

attic

graphersal store attic <DIR>                       list the entries
graphersal store attic <DIR> changes <ID>          the commits of an entry
graphersal store attic <DIR> restore <ID>          undo its rollback
graphersal store attic <DIR> fork <ID> <NEW_DIR>   the entry as a new store
graphersal store attic <DIR> remove <ID>           delete the entry for good
$ graphersal store attic data/
── Attic entry ───────────────────────────────────────────────────────────────
  id:          20261008T070510Z-00000000000000000002
  commits:     2..=4
  rolled back: 2026-10-08T07:05:10Z
  reason:      rollback to mark "before-import"
  size:        9.3 KiB
  snapshots:   1
$ graphersal store attic data/ restore 20261008T070510Z-00000000000000000002
Restored 20261008T070510Z-00000000000000000002: the store is at commit 4 again.

One section per entry, one field per line (The attic is empty. without entries). restore works only while nothing was committed or marked since that rollback; fork always does (and lists the marks of the entry's history it does not carry, like store fork). restore and remove are "in use" while a server has the store open.

backup

graphersal store backup <DIR> <BACKUP_DIR> [--full]
graphersal store backup <DIR> <FILE.zip> --zip [--without-models]

A consistent copy up to the last durable commit; works while a server has the store open. Into an empty or new BACKUP_DIR: a full backup. Into an existing backup of DIR: an incremental one. --full forces a full backup (the directory must be empty or new). --zip writes one ZIP archive (always full; the file must not exist; feature persist-zip, on in the CLI).

$ graphersal store backup data/ backup/
Full backup into backup/
  snapshot: commit 3
  WAL: up to commit 3
  WAL segments copied: 1
  files: 8
  bytes: 9605

The backup backup/ is read-only
  # open it read-only in the REPL
  graphersal --graph backup/
  # make it the live store
  graphersal store restore backup/
$ graphersal store backup data/ backup/
Incremental backup into backup/
  state: current (nothing new since commit 4)

The backup backup/ is read-only
  ...
$ graphersal store backup data/ data.zip --zip
Full backup into data.zip
  snapshot: commit 3
  WAL: up to commit 4
  files: 8
  bytes: 9688
  checked: every checksum read back
  # unpack it into a new live store
  graphersal store restore data.zip <NEW_DIR>

An increment that copied something lists commits (5..7 (3 new)), snapshots copied, WAL segments copied (with their numbers in brackets), bytes appended to the last segment and bytes.

The store's embedding models are copied too, with their cards and licence files, and the report lists them (It carries 1 embedding model(s) with their licences, then one section per model as models shows it): who hands a backup on redistributes them. --without-models (with --zip only; a usage error otherwise) leaves them out: such an archive is also restored by Graphersal 0.3.0, which refuses one with models as written by a newer version.

Every checksum of what is copied is read in DIR first and again in the copy (a ZIP archive is read back). Damage stops the backup (exit 1): nothing of it is kept (a new directory or archive is removed, an increment rolled back), and the report names the damaged files and recommends repairing the STORE (store repair DIR --to NEW_DIR), never the backup. Damage of a redundant copy (one GRAPH copy, one manifest copy, the marks file) is a warning: on stderr; the backup is intact.

$ graphersal store backup data/ backup/
Error: The backup stopped: the store data/ is damaged: wal/00000000000000000001.wal at byte 64: record of commit 1: checksum mismatch; nothing of the backup into backup/ was kept
Help: Repair the MAIN store, never the backup: Store::repair_dir builds a verified, repaired copy ...
        # build a repaired copy of the main store
        graphersal store repair data/ --to <new_dir>
        # show the full damage report
        graphersal store verify data/

Refused (exit 1, the backup unchanged): a backup of another graph, a directory holding a store that is not a backup, a non-empty directory without a backup, --full into a non-empty directory, a rollback of the store behind the backup, a pruned gap, a fork, repair or conversion of the backed-up store (another store id). --zip --full is a usage error (exit 2: "--zip backups are always full: drop --full").

--from-memory is a usage error here (exit 2) that says where it works: a backup from memory writes the graph of a store open in this process (whose files are damaged), and this command runs in a new process. Use the dev server's Store menu (Back up from memory), POST /api/store/backup {"from_memory": true}, or Python store.backup(path, from_memory=True). See Backup and Restore.

restore

graphersal store restore <BACKUP_DIR>
graphersal store restore <FILE.zip> <DIR>

With one argument: makes the backup in BACKUP_DIR the live store, in place, with the original's graph id (a backup directory of an older Graphersal: upgrade it first). With two: unpacks a ZIP backup into the new directory DIR as the live store; a ZIP of an older Graphersal's store is upgraded to the current format as it is unpacked (verified). To keep a backup as it is, fork it instead (store fork BACKUP_DIR NEW_DIR).

$ graphersal store restore backup/
Restored backup/: it is the live store now
  backup: up to commit 4
  taken: 2026-10-08T07:05:09Z
  graph id: the same
  # open it in the REPL
  graphersal --graph backup/
  # or serve it to the browser playground
  graphersal --graph backup/ --server
$ graphersal store restore data.zip restored/
Restored data.zip into restored/: it is the live store
  # open it in the REPL
  graphersal --graph restored/
  # or serve it to the browser playground
  graphersal --graph restored/ --server

export

graphersal store export <DIR> <FILE.gsnap> [--commit <N>] [--without-models]

Writes the latest stored snapshot (or the one at commit N, which must be a snapshot's commit: store list) as one packed file (Exported the snapshot at commit 3 to data.gsnap.). Load it with --graph FILE.gsnap, store create --from FILE.gsnap, or the playground.

The file carries the store's embedding models with their cards and licences (listed after the first line, one section per model) as blobs, unless --without-models (the definitions stay; the models are missing in what is made from the file: graphersal embed-model import <repo> --into <store> writes a missing model's blob back). store create --from FILE.gsnap and the playground put them back into a store. A damaged model blob stops the export (exit 1; export --without-models).

materialize

graphersal store materialize <DIR> <FILE.gsnap> --base <SOURCE> [TARGET] [--without-models]

Writes the whole graph a LAYER STORE shows at TARGET (default: the latest) as one standalone packed file: the base's elements with the layer's changes applied, the layer's schema and catalog, file format version 4. Unlike export (a layer snapshot, which loads only over its base) the file needs no base: --graph FILE.gsnap, store create --from FILE.gsnap and older Graphersal releases read it; its size follows the whole graph. The base's embedding models the layer's catalog references travel with it unless --without-models. Reads the files only (no lock), so it works while a server has DIR open.

$ graphersal store materialize project whole.gsnap --base product
Materialized the layer store project at commit 1 into whole.gsnap
  vertices: 7
  edges: 6
  standalone: yes: the whole graph (base and layer), it needs no base
  # open it in the REPL
  graphersal --graph whole.gsnap

--base is required (exit 2 without it); a plain store is refused (exit 1, naming store export).

models

graphersal store models <DIR>
graphersal store models default <DIR> <REPO>|--none
graphersal store models remove <DIR> <REPO>

Lists the embedding models of the store's latest state, one section per model (styled like the sections of the --server banner) with one key: value per line: model (the repository), full name (the identity a schema's embedder records, model2vec/<repo>@<12 hex>), size (of its blob), licence, licence text, default, used by (the schema places that need it), then gated and problem (a missing or damaged blob) when they apply; then a section for every model the schema names that the store does not keep (Missing embedding model). Works while a server has the store open.

licence text says where the text the store keeps beside the model comes from; Graphersal never writes a licence:

  • from the repository (its own licence file): the repository's own licence file;
  • standard MIT text (the repository has no licence file): the unchanged standard text of the licence the model card names (bundled for MIT and Apache-2.0; the copyright holders are those the model card names), and licence says mit (named in the model card);
  • none (no standard text for this licence).
$ graphersal store models data/
── Embedding model ───────────────────────────────────────────────────────────
  model:        acme/tiny
  full name:    model2vec/acme/tiny@0123456789ab
  size:         29.5 MiB
  licence:      mit (named in the model card)
  licence text: standard MIT text (the repository has no licence file)
  default:      no
  used by:      the schema (doc.emb)

── Embedding model ───────────────────────────────────────────────────────────
  model:        acme/other
  full name:    model2vec/acme/other@456789abcdef
  size:         7.6 MiB
  licence:      apache-2.0
  licence text: from the repository (its own licence file)
  default:      yes
  used by:      nothing (not used by the schema)

default makes the model of REPO the default model (the one embed() uses without a name; --none clears it, hash-ngram/1 is then the default), as one commit appended to the WAL WITHOUT loading the graph; refused for an unknown repository and while a writer has the store open. graphersal embed-model import <REPO> --into <DIR> --default imports and sets it at once.

remove removes one model by its repository as one commit appended to the WAL WITHOUT loading the graph (format spec 12.12; earlier positions keep it; its blob goes with the prune that drops the last history referencing it). It is refused while a writer has the store open, on a backup, while the schema needs the model (its properties are named), and for an unknown repository (exit 1). Models enter a store by graphersal embed-model download <REPO> --into <DIR> and graphersal embed-model import <REPO|MODEL_DIR> --into <DIR> [--default] [--replace] (see Embedding Models in a Store).

prune

graphersal store prune <DIR> --up-to <COMMIT> [--drop-marks]

Removes snapshots and WAL only needed for targets before COMMIT; the last two snapshots and the attic's bases always stay:

$ graphersal store prune data/ --up-to 1200
Pruned data/
  kept from: commit 1100
  snapshots removed: 2 (at commits 0, 600)
  WAL segments removed: 1

Without --up-to it is a usage error (exit 2: nothing is pruned implicitly). On a backup directory it prunes the backup.

A prune never makes a mark unreachable unless told to: when it would remove the history a mark needs, it names those marks, changes nothing and exits 1:

$ graphersal store prune data --up-to 4
Error: `store prune` would make the mark(s) "m0", "m1" unreachable: it removes the history they need, so they cannot be opened, forked or rolled back to afterwards (only from a backup that holds older snapshots). Nothing was changed.
Help: run it again with --drop-marks to prune anyway, or back the store up first
        # back the store up first
        graphersal store backup data <BACKUP_DIR>

With --drop-marks it prunes and names them (marks no longer reachable: m0, m1 (their history was pruned)); store marks no longer lists them. Without affected marks the flag changes nothing. A prune also removes the blobs no retained history references any more and says so (unreferenced blobs removed: N (size)). See Prune, Compact and Retention.

compact

graphersal store compact <DIR> [--drop-marks]

Prunes up to the current commit, then, for a single-file store, rewrites the file without its free space (the disk needs room for the live data meanwhile). On a directory the prune is all. Like prune, it refuses (exit 1, nothing changed) when the prune would make marks unreachable, naming them, unless --drop-marks is given; compact-advice lists them beforehand (marks lost: m0, m1 (...)).

$ graphersal store compact graph.gstore
Compacted graph.gstore
  kept from: commit 0
  snapshots removed: 0
  WAL segments removed: 0
  file: 23.7 KiB -> 22.8 KiB (930 B given back)

journal

graphersal store journal <DIR> [--level <L>] [--since <TIME>] [--source <P>] [--kind <K>]
                         [--after <SEQ> | --last <N>] [--limit <N>] [--follow] [--json]

Prints the store's system journal: one line per record (time in UTC, #seq, level, kind, message, fields), oldest first. It reads the files only (no lock, nothing written), so it works while a server has the store open; the records an open store has not written yet (below error, written in batches) appear after its next batch or its close.

  • --level error|warn|notice|info: that level and the more severe ones.
  • --since TIME: the records at or after TIME (the TIME forms of the other commands).
  • --source P: a source and the ones below it (store matches store.backup).
  • --kind K: one kind (store.backup_done, auth.denied, ...).
  • --after SEQ, --limit N: the records after a cursor, at most N (default 1000).
  • --last N: only the newest N matching records, read from the end of the journal (the older segments are not read), printed oldest first; with --follow it goes on from there.
  • --json: one JSON object per record (seq, origin, origin_seq, time in µs, level, source, kind, message, fields, ...).
  • --follow: keeps printing new records (it polls once a second) until it is interrupted.

Damaged records are skipped with a note: on stderr; they never make the command fail.

$ graphersal store journal data/ --level notice
2026-10-30T09:12:01.000000Z #1 notice store.created the store was created (create) (how=create)
2026-10-30T09:40:17.000000Z #9 notice store.backup_done a full backup to /backups/data holds commit 52 (...)

compact-advice

graphersal store compact-advice <DIR> [--min-ratio <R>] [--min-reclaimable <BYTES>] [--min-size <BYTES>]

Whether compact is worth it now, and the numbers; cheap (reads only names, sizes and small metadata files, no element data) and works while a server has the store open. The rule: at least --min-ratio of the store (0.0..1.0, default 0.5) and --min-reclaimable bytes (default 64 MiB) to gain, in a store of at least --min-size bytes (default 64 MiB), and enough free disk space. Always exit 0 (the answer is in the text: compact now: ... with the command under # compact the store now, or no compaction needed: ...).

$ graphersal store compact-advice data/
no compaction needed: the store is smaller than the minimum of 64.0 MiB
  store: 9.6 KiB (directory: compact = prune)
  prune: 0 B
  reclaimable: 0 B (0 % of the store)
  decided by: total_bytes

convert

graphersal store convert <DIR> <NEW> [--single-file] [--fill-blobs <SOURCE>]

Copies the whole closed store (snapshots, WAL, marks, attic) into NEW, byte for byte: a directory into a single file (NEW ending in .gstore, or --single-file) or back. NEW must not exist (or be an empty directory); the copy is verified; DIR is not changed. The copy is a new store with its own store id (creation parameters): it does not continue the backups of DIR (its first backup is a full one into a new directory).

A store whose catalog references a blob missing from its blobs/ (a model blob, say) does not verify, so its copy is refused. --fill-blobs <SOURCE> takes every such blob from SOURCE into the copy, checked by length, CRC-32C and hash: a directory laid out as blobs/<2 hex>/<hash> (a shared model directory, another store, a backup), a ZIP backup or a .gsnap, as for store restore-blobs. SOURCE is only read; the note adds blobs filled: <n> (<size>) from <SOURCE>. A blob SOURCE lacks too, or holds with other bytes, fails the command (exit 1) and leaves no copy. Rust: Store::convert_with with ConvertOptions::with_fill_missing_blobs; ConvertOptions::with_skip_missing_blobs (Rust only) makes the copy without such a blob and lists it instead (Blobs).

$ graphersal store convert data/ graph.gstore
Copied the store data/ into the single file graph.gstore
  files: 9
  size: 9.6 KiB
  verified: yes
  source: data/ is unchanged
  # open it in the REPL
  graphersal --graph graph.gstore
  # or serve it to the browser playground
  graphersal --graph graph.gstore --server

upgrade

graphersal store upgrade <DIR> <NEW> [--single-file]
graphersal store upgrade <DIR> --in-place

Converts a store written by an older Graphersal (store format version 2: Graphersal 0.1.x; 3: Graphersal 0.2.x to 0.4.x) to the current format, without the older binary. DIR is a store directory, a single-file store or a backup directory (it stays a backup). With NEW: a new store in NEW (a new or empty directory, or a single file: NEW ending in .gstore, or --single-file); DIR is not changed. With --in-place: DIR itself; back it up first (a copy of the closed directory or file will do): afterwards the older Graphersal refuses it as newer.

Everything is carried: the graph, its schema and catalog, the history (snapshots and WAL), the marks, the lineage, the attic entries and the store's identity and creation parameters; only GRAPH and GRAPH.copy are rewritten, every other file stays byte for byte. DIR is verified first. Exit 1 when it is damaged (nothing is written; store repair DIR --to NEW writes a repaired store of the current format), in use (a server or another writer has it open), of a newer or a pre-release version, or a copy of a store that is already current; exit 2 without NEW or --in-place, or with a NEW that exists. An upgrade in place of a current store prints nothing to do (exit 0). An interrupted upgrade leaves no store in NEW (run it again: it clears what was left), and in place leaves the store either older or upgraded (run it again). A ZIP backup of an older store is upgraded by store restore FILE.zip DIR. See Format Versions.

The embedding models of a Graphersal 0.4.0 store (models/) become blobs defined by one commit (0.4.0 -> 0.5.0); a damaged one refuses the upgrade before anything is written (exit 1, StoreFailure::UpgradeModelDamaged). What still needs your decision is printed, the exit code stays 0: a warning: for every model the schema needs that the store does not keep (with the commands that import it: the store opens once it is there), a note: per model for the vector properties with a model but no source property from (one combined schema patch for all properties of the model, one label per line; when that model is one of the missing ones, the comment above the patch says it runs after the model's import, since the store opens only then), and a note: for every saved query writing such a property directly (a vector rule refuses that write). Each note is a short headline with one detail per line and every command on a line of its own under a comment; notes are separated by a blank line (layout: Format Versions):

$ graphersal store upgrade store/ --in-place
Verified the store store/
  store format version: 3
  snapshots: 2
  WAL segments: 1
  records: 12

Upgraded store/ in place to store format version 4
  GRAPH: rewritten
  every other file: kept, the models/ directory migrated (below)
  the older Graphersal: no longer opens it

Converted the embedding model model2vec/acme/tiny@70c61d0ed332 into a blob with its catalog definition
  full name: model2vec/acme/tiny@70c61d0ed332
  size: 8.5 KiB

The models were defined by commit 12; the history before it has no models.
  # take a full backup now: a backup taken before the upgrade does not take increments of the upgraded store
  graphersal store backup store/ <new_dir>
note: doc.emb has vectors of acme/tiny but no source property
  vectors: 3 element(s)
  to keep them current: add "from": "<source property>" to its schema declaration
  first fill: re-embeds every doc (the whole database is locked while it runs)
  afterwards: write the source property, never emb itself
  # add the source property (replace <source property> first)
  graphersal --graph store/ -e 'g.patch_schema(#{vertices: #{doc: #{schema: #{properties: #{emb: #{from: "<source property>"}}}}}})'

Open store/
  # open it in the REPL
  graphersal --graph store/
  # or serve it to the browser playground
  graphersal --graph store/ --server

Which versions are upgraded, and how, is decided by one table (the same in Format Versions and the format specification 15.1); a version without a supported row is refused before anything is written, a row "into a copy only" refuses --in-place (StoreFailure::UpgradeNeedsCopy), and a store with any file of a newer version is refused like every other command does (below):

From store format versionWritten byToUpgrade
1never released (no store id)4unsupported (packed snapshot)
2Graphersal 0.1.x (no models: the version word only)4in place or into a copy (migration)
3Graphersal 0.2.x - 0.4.x4in place or into a copy (migration)
4Graphersal 0.5.x and later4nothing to do
$ graphersal store upgrade old/ new/
Verified the store old/
  store format version: 2
  snapshots: 2
  WAL segments: 2
  records: 10

Upgraded old/ into new/
  store format version: 4
  files: 15
  size: 21.2 KiB
  verified: yes
  source: old/ is unchanged (keep using new/: it is the same store, with the same identity)

Open new/
  # open it in the REPL
  graphersal --graph new/
  # or serve it to the browser playground
  graphersal --graph new/ --server
$ graphersal store upgrade old/ --in-place
Verified the store old/
  ...

Upgraded old/ in place to store format version 4
  GRAPH: rewritten
  every other file: kept
  the older Graphersal: no longer opens it

Open old/
  # open it in the REPL
  graphersal --graph old/
  # or serve it to the browser playground
  graphersal --graph old/ --server

repair

graphersal store repair <DIR> --to <NEW_DIR> [--drop-damaged-blobs]

Builds a repaired copy of a damaged store in NEW_DIR (never in place; the damaged files are not changed) and reports what was repaired, lost and diverged. A store of an older released format (Graphersal 0.1.x) is read as it is; the repaired store has the current format. Exit 0 with ok: all data kept (and what a repair never carries: not carried: the history before commit N, ... and the store id), exit 1 when data is lost or diverged (the repaired store is written anyway: read the lists), exit 2 without --to. The repaired store starts without marks: one mark not carried: name @ commit N line per mark of the damaged store at or before the repaired position. When both GRAPH copies are damaged, repair and verify print the note lineage before commit N is approximate (both GRAPH copies damaged) (verify then exits 1 with the damage report instead of "not a store"). See Damage, Maintenance and Repair.

A blob (an embedding model) missing or damaged in DIR is not carried and is reported; the repaired catalog still references it. Restore it first with restore-blobs, or give --drop-damaged-blobs: the repaired store leaves out every definition referencing such a blob (stderr note: left out ... lines; journal blob.dropped). It is refused, with nothing written (exit 1), while the schema needs one of them (the message names the properties).

restore-blobs

graphersal store restore-blobs <DIR> --from <SOURCE> [--json]

Copies the blobs the store references that are missing or damaged back from SOURCE: a backup directory (full or incremental), a ZIP backup (.zip), a packed snapshot (.gsnap) or another store (a directory or .gstore). Each blob is checked (length, CRC-32C, hash) before it is moved into place; a healthy blob is never touched. The store must be closed (exit 1 "in use" otherwise). Prints a summary (referenced, missing or damaged, restored, bytes restored) and one line per blob (restored blob, not in the source, damaged there too); --json prints the report as one JSON object (source, referenced, wanted, restored, bytesRestored, notFound, damagedInSource, complete). Exit 0 when every blob the store references is intact afterwards, else 1 with the list.

The Store in the Playground

The web playground runs the engine in the browser (WebAssembly), where there is no disk to write to. It still gives every graph the full Store: a MemDir store, with the same byte format as on disk.

Every graph you load (a sample, the empty graph, a file) is kept as a Store in memory: the loaded state is commit 0 (its first snapshot), every run that changes the graph adds a commit to the store's write-ahead log, and the Store menu in the top bar works on it exactly as the dev server's does on a store directory:

  • the position (commit, time of the last commit) and the sizes: the store's bytes in memory next to the graph's own footprint;
  • Checkpoint (a snapshot of the current state; one is also written automatically after 4 MiB of log since the last one) and Mark (a name for the current position);
  • the marks and the snapshots (each with a .gsnap download; when the store keeps embedding models, a second download .gsnap without models leaves them out, the first one carries them with their licences), the newest five of each; Calendar… (or See all… when there are more) opens the history calendar;
  • on every snapshot and mark, and through Go to commit / Go to time: Open read-only here (queries read that past state, writes are refused, a banner offers Back to the live graph), Fork into a new database and Roll back here (what comes after moves to the attic);
  • the attic: Show changes (100 commits per page with Previous/Next, the totals over all of them; the dialog scrolls in both directions and has a full-screen toggle, Esc restores its size), Restore, Fork, Remove;
  • Databases: the store you loaded and every fork made from it ("fork of Modern (TinkerPop) @ commit 12"), each a store in memory with its own history, with Switch to (the tabs' results may be stale afterwards) and Close (frees its memory);
  • Disk space with Compact: in memory a compaction is a prune up to the current commit (the last two snapshots stay), which frees the memory old snapshots and WAL hold; the button is always enabled (not while another store action runs); when the compaction advice does not recommend it, it asks first, showing what it would free and why it is not recommended;
  • Models (when the store keeps embedding models, or its schema names one it lacks): each model's identity, size, licence and where its text comes from, whether the repository is gated and whether the schema uses it. Handing the store or a snapshot with models on redistributes them. A .gsnap with models loaded on the start page keeps them in its store in memory (the browser cannot run them, but its copies and downloads carry them);
  • Verify the store checks every checksum, and Download current state (.gsnap) saves the state on screen. When the store keeps embedding models it first asks whether they go into the file, listing them with their sizes; without them the file is graphersal-graph-without-models-<stamp>.gsnap, and a store made from it reports the model's blob as missing until the model is added again. A model the store cannot hand on (its blob is missing or damaged) leaves only the download without models. The browser's Save ▸ Snapshot (.gsnap) asks the same.

The menu after a few commits, three marks and three snapshots (the buttons View, Fork… and Roll back… are the three actions above):

The Store menu of the playground: position, checkpoint and mark, databases, marks, snapshots, any point in time, disk space

Calendar… shows every mark and snapshot by day, with the same actions:

The history calendar: a month with the days that have marks and snapshots, and the entries of the selected day

A running store action is shown in three places (the same on the dev server): its button switches to the running text in bold accent colour with a spinner and the elapsed time ("Verifying the store… 0:42"); the Store button in the top bar shows it while the menu is closed ("Store · verifying… 0:42"); and a toast gives the result at the end (a problem found, such as Verify's damage, has a Details button that opens the menu, where the last Verify's result is listed under its item). Meanwhile every other store action is disabled, its tooltip saying which one to wait for; screen readers hear the start and the end through a polite live region. The engine reports no progress for these actions and none of them can be cancelled: the elapsed time is all there is.

In memory: everything is lost on page reload. Download a .gsnap to keep a state (load it back from the start page). The browser has no disk the playground writes to: syncs are no-ops, and the byte format is the same as on disk, so a downloaded snapshot opens anywhere.

Stop (next to Run) restarts the engine: the graph is restored as it was last loaded or saved, and the store in memory starts over from that state (its history is lost).

To keep a history across reloads, run the same UI on a store on disk with the dev server: graphersal --graph data/ --server.

Python

The Python binding (bindings/py-graphersal, package graphersal) has the packed snapshot, the journal and recovery on graphersal.Graph, and the Store as graphersal.Store. Errors raise graphersal.GraphersalError with the diagnostic and its help text. Build and test instructions: bindings/py-graphersal/README.md.

Packed snapshots, journal and recovery

import graphersal

graph = graphersal.Graph.tinkerpop_modern()
graph.save("g.gsnap")                                     # {"commit_seq", "vertex_count", "edge_count", "blobs_not_carried"}; name= optional; keeps its embedding models
graph = graphersal.Graph.load("g.gsnap")                  # no schema re-validation, checksummed; a snapshot over
                                                          # the process memory ceiling (graphersal.set_memory_limit) is refused
                                                          # before reading (Store.open too)

graph.start_journal("g.wal")                              # durability="every_commit" (default) | "os" | seconds
graph.execute('g.addV("person").property("name", "ann").next()')
graph.mark("after-ann")                                   # {"name", "commit_seq", "time"}

graph, report = graphersal.Graph.recover("g.gsnap", ["g.wal"])                    # to the end
graph, report = graphersal.Graph.recover("g.gsnap", ["g.wal"], mark="after-ann")  # or commit_seq=, time=

Graph.recover takes one target: commit_seq=, time= (microseconds since the Unix epoch) or mark=; without one it replays to the end. An interrupted last write is ignored (report["torn_tail"]); damage raises GraphersalError with its location. The recovered graph has no journal: save and start_journal again to continue (see Journal and Recovery).

The Store

with graphersal.Store.create("data") as store:            # or Store.open("data"); "x.gstore": one file
    store.graph.execute('g.addV("person").property("name", "ann").next()')   # durable when it returns
    store.mark("after-ann")
    store.checkpoint("nightly")
    store.snapshots(); store.marks(); store.verify()       # listings and the scrub
    store.fork("branch", mark="after-ann")                 # a new store (commit_seq=, time=, mark=)
    store.backup("bk")                                     # full, then incremental: {"incremental", "commit_seq", ...}
    store.open_report()                                    # {"clean_close", "commit_seq", "commits_replayed", ...}
MethodDoesPage
Store.create(path, on_damage="maintenance"), Store.open(path)create (missing or empty path; on_damage is the damage policy, fixed for the store's life) / open read-write, with recovery; a second writer raisesOpening and Closing
Store.create_file(path), Store.open_file(path)a single-file store (create/open of a .gstore path do the same)
store.graphthe store's Graph; every commit is durable before it returnsCommits
store.close(), with ...:a clean close; the graph refuses commits afterwards
store.open_report()what the open did
store.workload_report(history=None)the workload statistics: queries, property uses, lock times, jobs (Python's queries under the channel python); history="minutes"|"hours"|"days" adds every row's buckets
store.checkpoint(name=None)write a snapshotCheckpoints
store.mark(name), store.marks()name the position; list the marksMarks
store.snapshots()the snapshots, oldest first
store.fork(path, commit_seq=, time=, mark=)a new store from a point in time; the dict lists "marks_not_carried"Fork
store.rollback(commit_seq=, time=, mark=, delete=False)roll back in place; the rest goes to the atticRollback
store.attic(), store.attic_restore(id)the attic entries; undo a rollback
store.backup(path, full=False, from_memory=False)full or incremental backup, every checksum read in the store and in the copy (damage raises, nothing kept); from_memory=True after damage was found: the graph in memory, nothing written to the storeBackup and Restore
store.store_id, store.damage_policy, store.damage_found, store.frozen_by_damagethe store id and the policy, fixed at creation; damage found on disk while the store is open; whether it turned read-onlyDamage
Store.open_backup(path), store.backup_markera backup, read-only; its marker
Store.restore_backup(path)make a backup the live store (same graph id)
store.prune(up_to), store.compact(), store.compaction_advice(min_ratio=, min_reclaimable=, min_size=)retention and disk spacePrune, Compact
store.verify()the scrub: {"ok", "problems", "notes"}Verify
store.models()the embedding models the store keeps, with their licences (license, license_text), files and used_by_schema; the ones the schema names are registered when the store is opened (an embedders= embedder of the same model wins; a missing model is a UserWarning)Embedding Models in a Store
store.export(path, commit_seq=None, without_models=False)the latest (or the given) stored snapshot as a .gsnap, with the store's models and their licences unless without_models=True: {"commit_seq", "models"}Packed Snapshots
store.maintenanceNone, or the damage report of a store that opened read-only in maintenance modeDamage
store.repair_to(path)a repaired copy: {"commit_seq", "lossless", "marks_not_carried", "lineage_approximate_before", "report"}Damage
Store.convert(source, target, single_file=False)copy a closed store between a directory and a single fileSingle-File Store
Store.upgrade(source, target=None, in_place=False, single_file=False)convert a store (or backup) of Graphersal 0.1.x to the current format, into target or in placeFormat Versions
with graphersal.Store.open_backup("bk") as backup:        # read-only; backup.backup_marker
    backup.snapshots()
graphersal.Store.restore_backup("bk")                      # the live store from now on: Store.open("bk")

with graphersal.Store.create("graph.gstore") as store:     # one file
    if store.compaction_advice()["recommended"]:
        store.compact()
graphersal.Store.convert("graph.gstore", "data")           # a closed store into a directory (or back)
graphersal.Store.upgrade("old_store", "new_store")         # a store of Graphersal 0.1.x, upgraded (or in_place=True)

Times in Python are microseconds since the Unix epoch (time=), as in Rust.

The system journal

Every graph has a system journal of operational events (a store opened, a checkpoint written, a backup taken, a permission denied); a graph without a store keeps its newest records in memory.

page = store.journal(level="warn", since="2026-10-31T00:00:00Z")   # or store.graph.journal(...)
for record in page["records"]:                                      # oldest first
    print(record["time"], record["level"], record["kind"], record["message"], record["fields"])
newer = store.journal(after=page["next_after"])                     # only what came since
latest = store.journal(newest_first=True, limit=20)                 # the newest 20, newest first
older = store.journal(newest_first=True, before=latest["next_before"], limit=20)
graphersal.Store.journal_dir("data", kind="store.closed")           # a closed store: no lock, nothing written
graphersal.Graph().journal()                                        # a graph without a store: in memory
MethodDoes
graph.journal(...)the graph's journal (a Store's graph: the store's)
store.journal(...)the open store's journal: the records in journal/ plus the ones not yet written
Store.journal_dir(path, ...)the journal of the store in path without opening it (works while another process has it open, like graphersal store journal)

All three take the same keyword arguments and answer one page, {"records", "next_after", "truncated", "more", "notes"}:

  • after: the cursor; pass the previous page's next_after to read what came since. more says that another page follows; truncated that older records are gone from an in-memory journal; notes names damaged stored records that were skipped.
  • newest_first=True: the newest matching records, newest first (a stored journal is read from its end); the page then has next_before: pass it as before for the next older page (more says older ones exist), and its next_after follows what comes next. before also bounds an oldest-first page.
  • since (at or after) and until (before): microseconds since the Unix epoch, a timezone-aware datetime, or an ISO 8601 text with a zone (a naive datetime raises ValueError).
  • level: "error", "warn", "notice" or "info", that level and the more severe ones; source: a source and the ones below it ("store" matches "store.backup"); kind, op, origin (an instance id, a UUID text); limit (default 1000, at most 10000).
  • policy: an AccessPolicy that must allow ("read", "journal") (AccessPolicy.read_only() does), else PermissionDeniedError; without one reading is allowed, like a script.

Each record is a dict with the keys of graphersal store journal --json: seq, origin ({"id", "name"}), origin_seq, time (microseconds since the Unix epoch), level, source, kind, message, fields, and op, parent, commit, principal when set.

| Cannot create a store in data/: the directory is not empty, PersistError::DirectoryNotEmpty | a new store (Store::create, the target of Store::convert) needs a new or empty directory | choose an empty or new directory, or open the existing store if it is one (graphersal store info data/) |

FAQ and Troubleshooting

Choosing

Snapshot, journal or Store? A .gsnap when the application decides when to save (a script, the browser, a download). A journal when you need durability over streams you manage yourself. The Store for everything else: it is a snapshot plus a journal plus recovery, retention, backups and repair. See Persistence.

Directory or single file? A directory for a server (parts can live on other disks, the files are easy to inspect); a .gstore file when the store travels as one document. Both have the same guarantees, and graphersal store convert switches between them.

Is GraphSON or GraphML not enough? They are exchange formats: they do not carry the schema, the commit position or the auto-id sequences, and GraphML loses value types without a schema. A snapshot is lossless.

Errors and what to do

MessageCauseWhat to do
The store data/ is in use: another writer holds its locka dev server, a REPL or a program has the store open read-writeuse the reading commands (they work), the dev server's Store menu, or stop the writer. A crashed writer never leaves a stale lock (the OS releases it)
data/ is not a Graphersal store: no valid GRAPH file (...)the path is not a store (a typo, or not created yet), or both GRAPH copies are unreadablecheck the path; graphersal --graph <dir> --create-store creates a store; for damage see Damage
note: ... is a BACKUP: opened READ-ONLY, ..., PersistError::IsBackupa backup opens read-onlygraphersal store restore <dir> makes it the live store, store fork <dir> <new> a writable copy
warning: the store ... has DAMAGE and opened READ-ONLY in maintenance modechecksums failed, a WAL segment is missing, ...follow the runbook: stop writing, verify, repair --to
The commit was rejected by the commit hook 'maintenance'a write to a store in maintenance modethe same: repair into a new directory
The journal is poisoned by an earlier failurean fsync or a write failed (a full disk, an I/O error)fix the cause, then reopen the store (or restart the server): recovery continues from the last durable commit
The journal is poisoned by an earlier failure: a panic while writing a commit record: ...the journal panicked while it wrote a record (a bug, or a store backend that panics); the record was cut off again and the unit rolled backreport the panic; reopen the store (or restart the server): it gives the state before that unit. Every case: Failures while committing
Commit N is too large for the journal: its uncompressed record body is B bytes, more than the limit of L bytes per commit / CommitTooLarge (in CommitRejected from the hook journal)one unit needs more than 2^20 WAL parts of 64 MiB (64 TiB; every change with its before and after values). Since 0.5.0 a large commit is written in parts; before, the limit was 1 GiBsplit the work: drop in a run of its own, load in several runs; see The size of one commit. The unit rolled back; the store keeps working
Recovery target mark "x" not reachedno such mark, a commit after the end, or a target before the oldest retained snapshot (pruned)store marks, store list, store info show what exists
Cannot roll the store back: ... there is nothing after commit Nthe target is the current commit or laterchoose an earlier target
Cannot <operation>: <reason> / PersistError::Storethe store's state refuses the operation; its cause (StoreFailure, Python err.cause) says why, see the table belowfollow the help printed with it
--at-time: "..." is not a date-time: add a zonea time without a zone, or a bare datewrite 2026-10-08T02:43:00Z (UTC) or an offset like +02:00
Incremental backup ... refused / BackupRefusedanother graph, a pruned gap, a rollback behind the backup, a non-empty directory, a backup and a store upgraded from 0.4.0 each on its own (each has its own migration commit)back up into a new directory with --full (after a store upgrade that migrated models: always)
The backup stopped: the store ... is damaged: <file> at byte N: ... / BackupDamaged, side Storea checksum of something the backup copies failed in the storerepair the STORE (graphersal store repair <dir> --to <new_dir>), never the backup; while the store is open in a server or a program, save its graph first with a backup from memory. Nothing of the failed backup was kept
The backup stopped: the backup ... does not verify / side Backupthe copy did not read back intact (the backup's disk)check the backup's disk and back up again (into a new directory with --full when the old backup is damaged); the store is fine
The store ... is read-only: backup found damage on disk ... damage policy "maintenance" / DamageFounddamage was found while the store is open, and its policy (fixed at creation) is maintenancethe data in memory is intact: back it up from memory, then repair the store; see Damage found while the store is open
--on-damage ... applies only to a store being created--on-damage for an existing store with another policythe damage policy never changes; drop the option
The store ... has the older format version N; this build reads and writes only version M / OlderFormata store written by an older Graphersal (version 3: Graphersal 0.2.x to 0.4.x; version 2: Graphersal 0.1.x; version 1: a pre-release before the store id)versions 2 and 3: upgrade it with this build, no older binary needed: graphersal store upgrade <dir> <new_dir> (or --in-place), see Format Versions (a 0.4.0 store's embedding models become blobs); version 1: migrate it through a packed snapshot, the recipe. The error's help names the command
Unsupported format version N of the store ...: written by a newer Graphersal / UnsupportedVersiona store, backup, single-file store, packed snapshot or one of a store's snapshot or WAL files written by a NEWER Graphersal (a newer store format version in GRAPH, file format version, or container version)open it with that version; this build refuses it in every operation (open, info, verify, backup, restore, repair, upgrade, ...) without changing anything, and never takes it for damage or offers a repair; see Format Versions
The store open needs about N bytes in memory; the memory.limit allows M bytes / MemoryBudget (also snapshot load, recovery)the graph does not fit under the process memory ceiling (--memory-limit, graphersal.set_memory_limit, exec::set_memory_limit; in a container: its memory limit minus the headroom) or a stricter ReadOptions::with_memory_limit; refused before anything was read, nothing opened or changed (never maintenance mode)raise the ceiling to at least the minimum the help names (what is in use plus N), or open the store on a machine with more memory
Resource limit 'memory.limit' exceeded by the store open (or recovery, checkpoint, store read)the size estimate passed, but the graph (or the WAL replayed onto it, or a checkpoint's buffers) grew past the ceiling while it was read; nothing opened, the store unchangedas above; see What the ceiling covers

Refused store operations (PersistError::Store)

A refused operation reads Cannot <operation>: <reason>. Its cause is one of a closed set (graphersal::persist::StoreFailure, #[non_exhaustive]), so a program or a server can react to it with a match; StoreFailure::name() is the stable name, which the Python exception carries as err.cause (None for every other error). Each cause has its own help:

Cause (name())WhenWhat to do
Closed (closed)the store was closed (close, shutdown)open it again
LockPoisoned (lock_poisoned)a thread panicked while it held a lock of the open storeend the process and reopen the store
NameTaken (name_taken)a snapshot name in use, or a mark name used before (also by a mark a prune made unreachable)choose another name; store list, store marks
NameTooLong (name_too_long)a snapshot name over 255 bytesa shorter name
SnapshotExists (snapshot_exists)a named checkpoint at a commit that already has a snapshot under another namecommit something first, or checkpoint without a name
NoSnapshot (no_snapshot)an export of a commit without a snapshot, a backup of a store without onestore list, store checkpoint
BackupRunning (backup_running)a prune while a backup, a verification, a fork or an export reads the filesprune again afterwards
PruneRunning (prune_running)a backup while a prune deletes files (the built-in backends wait instead; a store's own StoreDir may refuse)back up again afterwards
FilesInUse (files_in_use)a rollback, attic restore or attic remove while a backup, a verification, a fork or an export reads the filesrun it again afterwards
NothingAfterTarget (nothing_after_target)a rollback to the current commit or lateran earlier target
UnknownAtticEntry (unknown_attic_entry)no attic entry with that idstore attic <dir> lists them
AtticLineageChanged (attic_lineage_changed)a later rollback or restore came after the entry's rollbackrestore the newer entry first, or fork the entry
ChangedSinceRollback (changed_since_rollback)commits or marks since the entry's rollbackfork the entry (store attic <dir> fork <id> <new_dir>)
AtticBaseMissing (attic_base_missing)the snapshot an attic entry continues is gonestore verify; take the entry from a backup or remove it
NotABackup (not_a_backup)a backup-only operation (prune_backup) on a live storeopen and prune it as a store
KeptSnapshotDamaged (kept_snapshot_damaged)a snapshot a prune would keep fails verification; nothing was removedstore verify, then store repair <dir> --to <new_dir>
CopyDoesNotVerify (copy_does_not_verify)a converted or repaired copy does not read back intactcheck the target disk, repeat into a new directory
ChangedConcurrently (changed_concurrently)a store file changed or vanished while the operation read itnever edit a store's files; repeat, then store verify
JournalSyncFailed (journal_sync_failed)writing or syncing the journal failedfix the disk, reopen the store
MissingCapability (missing_capability)the graph's storage does not claim atomic and change_capture, so no journal can be attached (never for TraversalGraph)keep the graph in a storage that claims both
ReloadFailed (reload_failed)the files of a rollback or attic restore changed, but loading the new state into the open graph failed: the graph in memory was emptied and the store stoppedclose the store and open it again (restart the server): the open completes the change
Stopped (stopped)an earlier rollback or attic restore failed part-way, so the store writes nothing more (Store::stopped_reason)close the store and open it again
AlreadyCurrent (already_current)store upgrade <dir> <new> of a store that already has the current formatopen it as it is; for a copy use store convert or a backup
DamagedSource (damaged_source)the store to upgrade does not verify (the message lists the first problems); nothing was writtengraphersal store repair <dir> --to <new_dir> reads the older store and writes a repaired one in the current format; or upgrade a backup instead
UpgradeNeedsCopy (upgrade_needs_copy)store upgrade <dir> --in-place of a store whose version the upgrade table upgrades only into a copy; nothing was writtengraphersal store upgrade <dir> <new_dir> (the older store stays as it is)
UpgradeModelDamaged (upgrade_model_damaged)store upgrade of a Graphersal 0.4.0 store one of whose embedding models under models/ is damaged or incomplete (a file missing, resized or changed against its manifest) or cannot be converted; the message names the model and the file; nothing was writtenrestore models/<id> from a backup and upgrade again; or move the directory out of models/, upgrade, then import the model again (graphersal embed-model download <repo>, graphersal embed-model import <repo> --into <dir>)
UnknownModel (unknown_model)store models remove, Store::remove_model or Store::set_default_model of a repository the store's current position has no model ofgraphersal store models <dir> lists the models by repository
BlobUnavailable (blob_unavailable)Store::read_blob (or an export that carries it) of a blob that is missing from blobs/, or named by a newer version's hash algorithm; never store damage, the store keeps workinggraphersal store verify <dir> lists every missing blob; graphersal store restore-blobs <dir> --from <backup|file.zip|file.gsnap|store> copies them back (the same hash is the same bytes); without a copy graphersal store repair <dir> --to <new_dir> --drop-damaged-blobs leaves out what references them; also refused when such a repair would leave out a model the schema needs (the message names the properties: restore the blob or change the schema first)
BlobDamaged (blob_damaged)a blob whose length, CRC-32C or hash is not its reference's; never store damageas for BlobUnavailable: store restore-blobs from any copy with the same hash, store repair --drop-damaged-blobs, or write the content again (Store::write_blob replaces a damaged blob)
InvalidModel (invalid_model)an embedding model to import lacks its config, tokenizer or weights file, has a file name that is not allowed, a file of 8 GiB or more, weights that are no safetensors file, no repository name, or a repository or licence that is not a valid name; nothing was addedcheck the model directory (graphersal embed-model list --dir <parent> lists it with its identity) and graphersal embed-model import <dir> --into <store> again
ModelUnavailable (model_unavailable)the open of a store whose schema NEEDS an embedding model (a vector property's embedder) that is not in its catalog at that position, or whose blob is missing or damaged; every open mode (also read-only, a backup, a view)graphersal embed-model download <repo> then graphersal embed-model import <repo> --into <store> --replace (the import opens the closed store without the check), or restore the store from a backup or replica
ModelDoesNotFit (model_does_not_fit)a model the schema needs does not fit under the process memory ceiling (its blob plus its loaded size, known from its definition before anything is read)raise the ceiling to at least the minimum the message names (--memory-limit, exec::set_memory_limit, graphersal.set_memory_limit)
ModelInUse (model_in_use)Store::remove_model of a model the current schema needs; the message names the propertiesre-embed those properties with another model or drop them (or their embedder) from the schema first
ModelRevisionExists (model_revision_exists)an import of another revision of a repository the store holds, without replace; the message names the properties the current revision madeimport with replace (ImportModelOptions::with_replace(true); CLI --replace): the new revision replaces the old one in one commit; while vectors of the old revision are in the data a replace needs vector rules (a later release)
LayerStore (layer_store)the store is a layer store (only a layer's changes to a frozen base) and the operation does not work on one: Store::open, open_read_only, open_backup, checkpoint_dir, fork_dir, attic_fork_dir (their layer forms take the base: open_layer_read_only, open_layer_backup, checkpoint_layer_dir, fork_layer_dir, attic_fork_layer_dir), or a repair or closed-store model commit, which do not work on layer stores (restore a backup of a damaged layer store; change the models in the base)open it with Store::open_layer(dir, &base, options) over the base it names (graphersal store info <dir>)
AutoCheckpointFailed (auto_checkpoint_failed)read from Store::last_auto_checkpoint_error after an automatic checkpoint run by Store::run_due_checkpoint (the browser) failed with a graph error; the caller of run_due_checkpoint got the error itselfnothing is lost: the commits are in the journal and the checkpoint is tried again at the next commit; graphersal store checkpoint <dir> reports a manual one with its own help

Questions

Can I change the damage policy (or the chunk size) of a store? No. Both are fixed at creation and carried by every fork, repair, conversion and backup. To get another policy, create a new store with it and load the data (for example graphersal store export old/ graph.gsnap, then graphersal store create new/ --from graph.gsnap --on-damage continue).

Does a backup check what it copies? Yes, every checksum, in the store before anything is written and again in the copy. A backup never copies damage silently; see Every checksum, twice.

Is a commit really on disk when the query returns? Yes, with the default Durability::EveryCommit: the WAL record is written and fsynced first; a failed sync rolls the commit back. With Interval or Os a machine crash may lose the last commits (never one in the middle). See Commits and Durability.

The dev server (or my program) was killed. Is the store damaged? No. The next open replays the WAL and cuts an interrupted last write; stderr notes that the store was not closed cleanly, which is harmless. Ctrl+C closes it cleanly in the first place.

The store takes much longer to start since I added compression rules. Graphersal 0.5.2 and older re-encode the data once per rule at every open until a snapshot holds the rules. Upgrade, or write a snapshot: graphersal store checkpoint <DIR> on a closed store. See Optimize.

Why does the store keep growing? Nothing is deleted implicitly: every commit is in the WAL and every checkpoint adds a snapshot until you prune. store compact-advice tells you what a prune and a compaction would give back.

How do I see the graph as it was yesterday? Store::open_read_only(dir, RecoveryTarget::Time(..)), the dev server's Go to time..., or graphersal store fork data/ yesterday/ --at-time 2026-10-07T18:00:00Z and open the fork. See Point in Time.

I rolled back by mistake. graphersal store attic data/ lists the rolled-back history; store attic data/ restore <ID> undoes the rollback as long as nothing was committed or marked since, otherwise store attic data/ fork <ID> <NEW_DIR> keeps it as a new store. A rollback with --delete cannot be undone (restore a backup).

Can I copy a store with cp or rsync? While no process has it open, yes: no file records a path. While it is open, use graphersal store backup (it copies up to the durable end and pins the files against a concurrent prune); a plain copy of a live store may catch a half-written file.

Can two processes use one store? One writer at a time (an operating-system lock). Any number of readers (info, verify, fork, backup, Store::open_read_only) at the same time as the writer.

Does a backup include the attic? No. It holds the snapshots and the WAL up to the durable end, and the marks.

Where is the time zone? Everything is stored and printed in UTC. --at-time takes any offset, but refuses a time without one.

Does it work in the browser? Snapshots, journals and recovery work over any stream in WebAssembly; the Store works there over a MemDir (the playground does that). There is no disk: download a .gsnap to keep a state.

Can another program read the WAL (change data capture)? Yes. The byte format is public (specification); a reader tails the WAL segments, reads complete records only, and treats records after the writer's durable end as possibly not final. In Rust, store.changes_since(commit) yields the ChangeSets.

Is the format stable? Store format version 4 (with file format version 4) is specified on the specification page; a newer version is refused, never guessed at, and a store of an older released version is upgraded by graphersal store upgrade without the older build (every build keeps the readers of every released format; Format Versions).

Layers

A layer is a writable graph over a frozen base graph. The base is loaded once and never changes. The layer stores only its own difference from it: the elements it adds, and the base elements it modifies or removes. To a query, a layer looks like an ordinary graph. Every step, saved query, schema rule and transaction works on it the same way, and nothing tells it apart from a graph that holds all of its data itself.

The typical use is a product graph shared by many projects. The product (the "box") is the base. Each project gets a layer, and the same indexer scripts that built the product fill it with the project's own repositories. Most of a project graph is the product itself, so a layer costs about what the project adds or changes, not a copy of the product. Several layers can share one base in the same process.

EXPERIMENTAL in 0.8.x. From Rust a layer can be saved as a layer snapshot and read back over its base, or kept in a layer Store (Store::create_layer / Store::open_layer); the CLI and the dev server keep a layer in a layer store with --layer-store, --layer and Python keep it in memory (see Limitations). How the storage works inside, its capabilities and memory figures are on the developer page Layered Graphs. A server that serves many customers' layers over shared product versions, one MCP endpoint per name, is described in Serving Layers.

Where an element comes from

Only some queries need to know whether an element is the product's or the project's. Three functions answer that question, and only when they are called. Everything else reads the layer as one graph.

FunctionExampleAnswer
layer()g.v().has_label("class").layer()the origin of each vertex or edge
has_layer(origins...)g.v().has_layer("added", "modified")only the elements with one of these origins
g.layer_diff(#{..})g.layer_diff(#{kinds: "vertex"})the whole difference against the base, as one map

An element has one of three origins:

  • "base": the element is the base's, unchanged. A base element written back to its base state, or written with a value equal to the base value, is "base" again.
  • "added": the layer created it.
  • "modified": a base element whose properties or labels the layer changed.

A removed base element cannot be traversed, so layer() never answers for it. It appears only in g.layer_diff(), under removed.

On a graph without layers (every sample graph, file and Store) all three functions still work: everything is "base" and the diff is empty. A query that uses them runs on both kinds of graph.

g.v().layer().dedup().to_list()   // ["base"]: the sample graph is no layer
g.v().has_layer("added", "modified").count().next()   // 0
g.e().has_layer("base").count().next()   // 6
g.v(1).out_e().group_count().by(__.layer()).next()   // #{"base": 3}
g.layer_diff()   // #{"added": [], "modified": [], "removed": [], "truncated": false}
g.layer_diff(#{kinds: "edge", labels: ["knows", "created"], limit: 10})["truncated"]   // false
g.v().has_layer("new").to_list()   // error: "new" is no origin (base, added or modified)

has_layer() without arguments keeps every vertex and edge; has_layer([]) keeps none, like has_label(). An unknown origin is an error before the query runs, even inside a child traversal no traverser reaches. Both steps accept vertices and edges only: anything else (a value, a property) is an error.

g.layer_diff(#{kinds, labels, limit})

g.layer_diff() returns everything the layer changed. All options are optional:

OptionValueDefault
kinds"vertex", "edge", or a list of themboth kinds
labelsa label or a list of labels; an element matches when any label of its base label set or its layer label set is in the list. [] matches nothingevery label
limita positive number of entries, counted across the whole diffno limit

The answer is a map:

KeyValue
addeda list of the elements the layer created: {kind, id, labels, properties}, an edge also with out and in (the endpoint ids)
removeda list of the base elements the layer removed, in the same form, with their base labels and properties
modifieda list of the base elements the layer changed: {kind, id, base_labels, labels, properties} (an edge also with out and in), where properties maps each changed key to {base, layer}; a key the layer added has no base, a key it removed no layer
truncatedtrue when limit left out further entries

An edge's labels is a list of one label. The diff lists vertices first (added, removed, modified), then edges in the same order; added elements are listed in creation order, except that an element created after a removal may fill the removed element's place. Values are the logical values, the same ones a query reads. In the DSL the keys of each map come out sorted (added, modified, removed, truncated), because the DSL's map type sorts them. The Rust form (LayerDiff::to_property) and Python keep the order of the table.

A g.layer_diff() in a script sees the script's own earlier writes. It reads the delta only, never every base element, so it is cheap on a large base with a small layer. It asks for Read on Data (see Permissions).

Memory: what a layer weighs

g.memory_usage() on a layer reports the layer's own footprint as total_bytes. The base it shares with other layers is reported beside it as shared_bytes and is not part of the total. The memory report breaks the layer's own part down with the option scope:

let r = g.memory_report(#{scope: "delta"});
[r.labels.map(|l| [l.label, l.elements]), r.shared_bytes, r.structure.removed_base_edges]

With #{scope: "delta"} the rows cover only the elements the layer added or modified (their labels and properties, as for a plain graph), the structure is the layer's own (its slots, indexes and totals, base_stubs, removed_base_vertices, removed_base_edges), and the base is the one figure shared_bytes. A removed base element is only counted, since the layer holds nothing of it but a tombstone. The indexes rows show the index bytes the layer owns: nothing for an index it shares with the base, the whole index for one it created. Without the option (#{scope: "all"}) the report walks every element the layer shows, base elements included, so it has the same rows as a report on the graph the layer shows. On a plain graph #{scope: "delta"} reports the whole graph, since a plain graph owns everything it shows.

On the generated large graph (222 210 elements) with 1 100 vertices modified and 500 added, the delta report read 1 600 elements and the full report 222 210 (debug build: 62 ms against 769 ms). The layer's own total was 475 KB beside a shared base of 51 MB.

Trying a layer from the command line

graphersal --layer runs the session on an empty layer over the --graph: the loaded graph becomes the frozen base, and every write goes to the layer.

graphersal --graph modern --layer \
  -e 'g.add_v("person").property("name", "ada").iterate()' \
  -e 'g.v().has("name", "marko").property("age", 30).iterate()' \
  -e 'g.v(6).drop().iterate()' \
  -e 'g.v().group_count().by(__.layer()).next()' \
  -e 'g.layer_diff(#{kinds: "vertex"})'
"added": 1
"base": 4
"modified": 1
"added": [#{"id": "7", "kind": "vertex", "labels": ["person"], "properties": #{"name": "ada"}}]
"modified": [#{"base_labels": ["person"], "id": "1", "kind": "vertex", "labels": ["person"], "properties": #{"age": #{"base": 29, "layer": 30}}}]
"removed": [#{"id": "6", "kind": "vertex", "labels": ["person"], "properties": #{"age": 35, "name": "peter"}}]
"truncated": false
  • The base can be any --graph source: a sample graph, a GraphSON or GraphML file, a packed snapshot (.gsnap), or a Store. A Store is opened read-only, without its lock, and nothing is written into it, so a layer can run over a store another process has open. --schema applies to the base as without --layer. The embedding models of a Store or .gsnap base serve the layer: embed(), text nearest and vector rules on the layer use them.
  • The REPL (graphersal --layer) and the dev server (graphersal --graph <src> --layer --server) run on the layer too. The server's start banner has a layer row; the playground pages and the server's MCP endpoint query the layer (MCP graph_info shows a layer block: the base's name and identity, what the layer added, modified and removed, its own and the shared bytes; the instructions of initialize name layer(), has_layer() and g.layer_diff(), on a layer only). "Save to file" is refused (409, "the graph is a layer kept in memory over its base"): it would write the layer's graph over the base's file.
  • The layer lives as long as the process: nothing is saved when it ends. To keep it, use a layer store (next section).
  • --layer is refused with --create-store (a layer never writes its base, so it cannot create a store; --layer-store <dir> --create-store keeps the layer in a new layer store) and with --read-only (the layer is the part that takes the writes), with exit code 2. A base the layer cannot carry yet (see below) is refused with exit code 2 too.

In the playground

The playground shows where each element of a layer comes from. Nothing of this appears for a plain graph.

  • The layer badge. The top bar shows "Layer over base" after the graph's counts, with the change counts +added ~modified −removed. Its tooltip names the base commit and splits the memory into the layer's own bytes and the shared base. A click opens the Layer changes dialog.
  • The drawing. In the Graph panel, an added vertex has a solid outline and a modified vertex a dashed outline. An added edge is solid and wider, a modified edge dashed. The colours are a colour-blind-safe pair (blue for added, reddish purple for modified), with light and dark variants. Base elements look exactly as on a plain graph. The legend adds the entries added, modified and base, and the inspector shows an origin row.
  • The Layer changes dialog lists what g.layer_diff() returns: Added, Modified and Removed, vertices before edges. A modified element shows each changed property as base → layer, a property only one side has as (absent) on the other, and a label change as the row labels. You can filter by kind and label and choose a limit. When more changes match than the limit shows, a "Truncated" notice says so. A click on an added or modified entry draws its neighbourhood in the Graph panel (for an edge, the neighbourhood of its out vertex) and opens the element in the inspector. Removed elements are listed only.
  • Memory. The process memory bar (Profile → Statistics, Optimize → Memory) gets a striped "Shared base" track below the layer's own segments. It is shared with every other layer over the base. In the tracked process heap it is part of other. Optimize → Memory has a Delta only switch: the memory report then walks only the layer's added and modified elements (scope: "delta"), and the base stays the single figure shared_bytes.
  • Starting a layer in the browser. The WebAssembly playground can make a layer without a server. Load a graph, then choose Store ▸ Start a layer over this graph. Writes now go to the layer and the badge shows them. Drop layer in the Layer changes dialog discards the layer and brings the base back unchanged. The layer has no Store menu. Stop restarts the engine and restores the graph as it was loaded or last saved, so the layer is lost. On the dev server the layer comes from --layer / --layer-store, and neither action is offered.

The UI profile key layerDiff turns the badge, the dialog and the two actions on or off (the built-in full profile has it on).

Keeping a layer durably: --layer-store

graphersal --graph <base> --layer-store <dir> runs the session on the layer kept in the layer store <dir> over the base: every commit goes to the layer store's write-ahead log before the query answers, exactly as with a --graph <store>, and the base is never written. --create-store creates the layer store (with --on-damage, as for a plain store); later runs open it over the same base.

graphersal store create product --from modern          # the base: a Store
graphersal --graph product --layer-store project --create-store \
  -e 'g.add_v("person").property("name", "ada").iterate()'
graphersal --graph product --layer-store project \
  -e 'g.v().group_count().by(__.layer()).next()'
note: created the layer store project
  base: product
  base identity: graph 01a200ad-0cec-7d75-8f50-725adf107e99 at commit 0 (commit time 0)
  damage policy: maintenance
"added": 1
"base": 6
  • The base must keep its identity from one run to the next: a Store (opened read-only, without its lock, so another process may have it open) or a packed snapshot (.gsnap). A sample graph or a GraphSON/GraphML file gets a new identity at every load, so it is refused (exit 2) with the commands that make it a Store first (graphersal store create <base_dir> --from <graph>).
  • A layer store opens only over the base it was created over. Another base exits 1 with the message naming both (LayerBaseMismatch); so does a plain store given as --layer-store. --graph <layer store> alone is refused too: it names the base to give.
  • --layer-store implies --layer; both together are the same durable layer. --read-only loads the layer store read-only (no lock, nothing written, every write refused); with --create-store it is refused (exit 2). A backup of a layer store opens read-only over the base the same way.
  • The REPL and the dev server (--server) run on it. The server commits to the layer store, its start banner shows a Store section with the layer store's path, its base and its commit position, and Ctrl+C closes it cleanly. "Save to file" answers 409 ("every commit is already durable in it"); the server's Store panel serves plain stores only, so it is not offered for a layer store: use graphersal store ... on it.

Store commands on a layer store

The graphersal store commands that read or copy files work on a layer store without the base: info (its base is a row of the "fixed at creation" block), list, marks, journal, attic (the listing and changes), backup (it warns that the backup is useless without the base), restore, export (a layer snapshot), convert and upgrade. The commands that load the layer take --base <SOURCE>, the base it was created over (a store or a .gsnap):

CommandWith --base
store verify <dir> --base <src>also loads every snapshot over the base (without --base: every checksum, plus a note)
store checkpoint <dir> --base <src>encodes the layer over the base: a snapshot the size of its changes
store fork <dir> <new> [TARGET] --base <src>a new layer store over the same base
store rollback <dir> TARGET --base <src>rolls the layer back in place; the attic keeps the rest
store attic <dir> restore|remove|fork ... --base <src>as for a plain store
store materialize <dir> <file.gsnap> --base <src> [TARGET]the whole graph the layer shows, as a standalone packed snapshot

Without --base these commands are refused (exit 1) with the LayerStore reason and the command to run instead. store materialize writes the base's elements with the layer's changes applied, the layer's schema and catalog (format version 4, the base's embedding models it uses unless --without-models); the file needs no base, so any Graphersal reads it (--graph whole.gsnap, store create <dir> --from whole.gsnap):

graphersal store materialize project whole.gsnap --base product
Materialized the layer store project at commit 1 into whole.gsnap
  vertices: 7
  edges: 6
  standalone: yes: the whole graph (base and layer), it needs no base
  # open it in the REPL
  graphersal --graph whole.gsnap

store repair refuses a layer store (a repair salvages whole graphs: restore a backup of it), and so do store models remove|default (a layer store keeps no embedding model; store models <dir> says its graph serves the base's).

Rust

A layer is the storage LayeredGraph over an Arc<TraversalGraph>. Everything that runs on a Graph<S> runs on it: the typed traversal API, the DSL, GQL and the session.

use std::sync::Arc;
use graphersal::prelude::*;
use graphersal::storage::{ElementKind, Graph, LayerDiffRequest, LayerOrigin, LayeredGraph};

let base = Arc::new(TraversalGraph::tinkerpop_modern());
let layer = Arc::new(Graph::new(LayeredGraph::over(Arc::clone(&base)).unwrap()));

// The DSL on the layer: the writes go to the layer, the base stays as it was.
let run = |script: &str| graphersal::script::eval_value(layer.clone(), script).unwrap();
run(r#"g.add_v("person").property("name", "ada").iterate()"#);
run(r#"g.v().has("name", "marko").property("age", 30).iterate()"#);
assert_eq!(run(r#"g.v().has_layer("added", "modified").count().next()"#).as_int(), Ok(2));
assert_eq!(run(r#"g.v().has("name", "ada").layer().next()"#).to_string(), "added");

// The typed API: origins and the diff.
let read = layer.read();
let g = GraphTraversalSource::new(&*read);
let diff = g.layer_diff(&LayerDiffRequest::new().kind(ElementKind::Vertex)).unwrap();
assert_eq!((diff.added.len(), diff.modified.len(), diff.removed.len()), (1, 1, 0));
assert_eq!(diff.modified[0].properties[0].name, "age");
assert!(diff.to_json().starts_with(r#"{"added":"#));
let marko = read.get_vertex_by_id("1").unwrap().unwrap();
assert_eq!(read.vertex_layer(marko).unwrap(), Some(LayerOrigin::Modified));
assert_eq!(TraversalGraph::vertex_count(&base), 6);

A layer built with LayeredGraph::over gets the base graph alone. The embedding models of a database live beside the graph, in its Graph; LayerBase keeps them together with the frozen graph and a display name, and LayerBase::new_layer() makes a Graph<LayeredGraph> that serves them. A clone of a LayerBase is cheap: every layer made from it shares one base and one set of models.

use graphersal::prelude::*;
use graphersal::storage::LayerBase;

// A Store's graph (`Store::open_read_only(..)?.into_graph()`) or a `.gsnap` read
// (`graphersal::persist::read_snapshot_file`) brings its models along the same way.
let base = LayerBase::from_graph(Graph::new(TraversalGraph::tinkerpop_modern()))
    .unwrap()
    .with_name("product");
let project_a = base.new_layer().unwrap();
let project_b = base.new_layer().unwrap();
GraphTraversalSource::new(&mut *project_a.write()).add_v("repo").iterate().unwrap();
assert_eq!(project_a.read().vertex_count().unwrap(), 7);
assert_eq!(project_b.read().vertex_count().unwrap(), 6);

LayerBase::base_ref() names the base's identity: its graph lineage id, its last commit and that commit's time. A layer snapshot (graphersal::persist::write_snapshot of the layer, or write_graph_snapshot of its Graph) holds only what the layer added and changed plus that identity, so it is about the size of the project's changes, not of the product. It is read back over the same base with graphersal::persist::read_layer_snapshot(reader, &options, &base); over another base (another graph, or the same product graph after more commits) it is refused with a message naming both bases, and read_snapshot refuses it as a whole graph. A base saved as a .gsnap or Store and loaded again keeps its identity and takes its layers' snapshots.

LayerDiff::to_property() is the map of the table above with its keys in that order, and LayerDiff::to_json() its JSON text. A storage that has no layers answers LayerOrigin::Base and an empty diff from the trait's defaults.

Python

graph.layer_diff(kinds=None, labels=None, limit=None, policy=None) answers the diff as a dict with the keys in the order of the table above. layer() and has_layer() are DSL steps and run in graph.query(...) like every other step.

import graphersal

graph = graphersal.Graph.tinkerpop_modern()
assert graph.query("g.v().layer().dedup().to_list()") == ["base"]
assert graph.layer_diff(kinds="vertex", limit=10) == {
    "added": [], "removed": [], "modified": [], "truncated": False,
}

A Python Graph cannot be a layer yet: it always holds a graph of its own, so from Python every element is "base" and the diff is empty. The functions are there so that queries and code written for layers already run.

Limitations

  • Persistence. From Rust a layer can be saved as a layer snapshot (above) or kept in a layer Store, which journals every commit and opens again only over the same base (graphersal store info shows a layer store's base); the CLI and the dev server keep it there with --layer-store (above). --layer and Python keep it in memory. A layer store is backed up, restored, verified and exported like any store; every copy holds the layer only, so a backup of a layer store is useless without its base (the backup's report and graphersal store backup say so): keep the base, or export a standalone copy of the whole graph the layer shows (Store::export_materialized, graphersal store materialize: a plain .gsnap that any Graphersal reads). Forks, rollback, the attic and conversion to another backend work on a layer store and keep it a layer over the same base. A damaged layer store is not repaired (restore a backup of it, or rebuild the layer), and the embedding models of a layer store are changed in its base.
  • One level. The base is a plain graph; there is no layer over a layer. The base is frozen for good: when the product graph changes, project layers are rebuilt over the new base.
  • Refused for now, with an error naming the feature ("... not supported on a layered graph yet"): compression rule and embedding model definitions created on a layer.
  • Vector rules: a layer over a base with vector rules keeps the derived vectors in step as a plain graph does. Creating the layer embeds nothing: the base's vectors are read as they are. A write on the layer to a rule's source embeds the element in the same unit, with the same vectors, errors and change sets as a plain graph with the layer's data; a write that leaves the text as it was copies nothing into the layer. A rule the layer adds or changes on a label the base holds fills every element of that label, so it copies each of them into the layer: the preview (validate_schema, diff_schema) names how many (base_copies, and a sentence in the warning text). A layer uses the embedding models of its base: over a Store or a .gsnap that holds models (--layer, or LayerBase in Rust), rules, embed() and text nearest on the layer run with them as on the base. A layer cannot import or define models of its own. A layer built over a bare graph without its models (LayeredGraph::over in Rust) serves only the built-in hash-ngram/1: a write that needs another model fails ("the model ... is not served here") and leaves nothing, as on a plain graph without that model.
  • Property indexes: a layer serves the base's indexes for its own data, also after it changed elements: lookups and counts answer from the index, as on a plain graph. The base's unique indexes hold for the layer: a write that would give a second element a unique value fails with the same error a plain graph with the layer's data gives, and a value that an element of the base held before the layer dropped or changed it is free again. A unique index the base keeps disabled (it was stored over repeated values) stays disabled on the layer. A layer can create, drop and redefine indexes (g.create_index(...), g.drop_index(...)) for itself: the base and the other layers keep theirs. A unique index is checked against the layer's data, as on a plain graph. Creating an index on a layer reads every element of its label in the base once and keeps its own copy of the index, which counts in the layer's g.memory_usage().
  • Order: unordered results list the same elements as a plain graph with the same data, in the same order, except after some removals (details on the developer page). Use order() when the order matters.
  • Not in GQL yet. GQL queries run on a layer like on any graph, but GQL has no function for an element's origin or the diff yet. Use the DSL for those.
  • The playground cannot draw removed elements. They are no longer in the graph, so the Layer changes dialog lists them as text only (see In the playground). The Fast drawing tier draws edge origins by colour and width only (WebGL has no dashed lines); the edge's hover label names its origin.

Custom Storages

Graphersal's reference storage is TraversalGraph, an in-memory graph. A host (a server, an application) can bring its own in-memory storage instead: any type that implements the GraphStorage trait. The engine, the Rhai DSL, saved queries, the session of the playground and the dev server (graphersal-session) and the persist Store then work over it.

EXPERIMENTAL in 0.8.x. GraphStorage, PersistentStorage, AnyGraph and the conformance crate graphersal-storage-tests may change in any 0.8.x release. Pin the exact versions (graphersal = "=0.8.0", graphersal-storage-tests = "=0.8.0"). graphersal-session is internal and has no stability guarantees at all.

How it fits together

The engine (GraphTraversalSource<'g, S>) is generic over the storage and statically dispatched: a traversal over a host storage is compiled for that storage, with no virtual call per element. Everything above the engine holds one object-safe type per layer instead, and makes one virtual call per operation (a terminal, a schema method, a catalog call, a view):

LayerHoldsImplemented for
Rhai DSL, saved queries (graphersal::script)Arc<dyn AnyGraph>every Graph<S> (sealed blanket implementation)
Session (graphersal-session)Arc<dyn SessionGraph>, Arc<dyn SessionStore>, Arc<dyn GraphFactory>every Graph<S>, every Store<S>, StorageKind<S>
Store (graphersal::persist)Store<S>, internally a non-generic coreevery S: PersistentStorage

Graph<S> (in graphersal::storage, also in the prelude) is the shared form of a storage: S behind a read-write lock, with read()/write() guards that dereference to S. Graph without a parameter means Graph<TraversalGraph>.

What a host implements

  1. GraphStorage (required). Only the read methods, the element-inserting and element-removing methods and the property writes are required; everything else has a default that is correct for a simple, non-transactional storage. The trait's rustdoc ("A guide for storage implementers") is the reference: handles that never alias, the write checks and their public helpers, units of atomicity, capabilities, change capture, statistics, schema and the catalog. The schema's defaults on create come for free: you implement the primitive insert_vertex/insert_edge (store exactly this; imports, change sets, replay and copies call it), and the queries create through the provided add_vertex/add_edge (add_vertex_with/add_edge_with with a pinned time), which fill the defaults in from get_schema() and then call your insert_vertex/insert_edge (override add_vertex_with/add_edge_with only to avoid that schema copy).

    A storage with schemas (set_schema/get_schema) must reject, or never store, every write that violates the schema in force in mode open or closed: the stored data always satisfies the stored schema. The engine relies on it: a schema change that keeps the mode checks only the elements of the labels whose declaration changed (validate_schema and TraversalGraph's set_schema do), never the rest of the graph; only a change of the mode checks every element. See GraphStorage::set_schema.

  2. Default (required by the DSL and the session). The session builds every new graph (a sample, a file load) by reading it into a TraversalGraph and copying it into an S::default() (through the load sink of a PersistentStorage, through the write methods otherwise). A whole script runs as one unit that its thread holds across locks (Graph::begin_unit), on your storage in place: the graph holds the lock upgradable until the script's first write and only then opens your storage's unit (begin_unit_at with the time it pinned from next_unit_started_at, both defaulted), so opening and closing a unit that never wrote take no exclusive moment. A unit you open yourself through a write guard (graph.write().begin_unit()) must be closed under that same guard, else other threads read its uncommitted changes and a Store checkpoint may persist them.

  3. Send + Sync + 'static, so the graph can be shared between threads.

  4. Change capture (optional; needed for commit hooks, dry runs and the Store). A storage that claims change_capture (and therefore atomic) in capabilities() builds the ChangeSet of every committed unit itself with the public constructors (ChangeSet::builder, one Mutation constructor per kind). There is no reusable undo log or capture component: the storage derives what a unit changed from its own bookkeeping. It embeds a CommitHooks (graphersal::storage) and calls it at its commit point, so the order of the hooks (user hooks in registration order, then the journal) is implemented once; the rustdoc of CommitHooks says when to call each event. Time commits with CommitHooks::commit_time (the instance clock, shared with marks and the system journal) and return Some(hooks.clock()) from GraphStorage::commit_clock; a storage that keeps the default (None) times its commits itself, and a Graph over it keeps a clock of its own.

  5. PersistentStorage (optional, feature persist; needed for snapshots and the Store): the lineage id, the commit position, a load sink outside units, clear, the journal slot and replay. See Your Own Storage.

Errors of a backend. Every trait method that reads or changes state returns a Result (since 0.4.0). The element reads (vertex_count, edge_count, vertices, edges, vertices_by_label, edges_by_label, get_vertex_by_id, get_edge_by_id, out_edges, in_edges, vertex_id, edge_id, vertex_label, edge_label, vertex_labels, vertex_has_label, vertex_properties, edge_properties, edge_endpoints, contains_vertex, contains_edge) and unit_started_at answer Ok(None) / Ok(false) / an empty label set for what does not exist and Err only when the backend cannot answer; an iterating one returns Result<impl Iterator>, one Result for starting the iteration, never one per item (a backend that can fail mid-iteration collects first, like the defaults of vertices_by_label and edges_by_label). The query that read fails with the error, located at its step. The methods beyond single elements are the unit methods (begin_unit, begin_unit_at, next_unit_started_at, rollback_unit, unit_changes, set_unit_metadata), capabilities, last_commit_seq, statistics, the schema, catalog, compression, property index and memory methods, shrink_to_fit, execution_policy, and on PersistentStorage clear, set_graph_id, raise_position, reserve_load and finish_load. A storage whose state lives behind a backend (a file, a service, a lock of its own) returns GraphError::storage_failed(operation, source) instead of an empty or made-up answer; the defaults return Ok of what a storage without the feature reports. The engine reads these once per query or unit, never per traverser, and fails the query, import or transaction with the error, before anything executes where it can. A failed rollback_unit still closes the unit and the caller gets GraphError::RollbackFailed (naming the error that caused the rollback), but a storage that returns Err from rollback_unit is treated as being in an unknown state: it must either have fully undone the unit (then it returns Ok) or consider itself failed. Behind a Graph the failure poisons the graph: every later read, write, unit, traversal, import and session operation on it fails with GraphError::Poisoned (whose help says to reopen or recover the storage), and Graph::read() / write() panic. The same holds for a discard_unit that fails other than with the Unsupported of a storage without change capture, and for a rollback during a panic's unwinding. There is no way back in place: the host drops the graph and reopens the storage; Graph::is_poisoned() and Graph::poison_cause() tell what happened, and Graph::into_inner() still hands the storage out to close or salvage it. A bare storage (a &mut S with Transactional) has no graph to poison: the caller only gets the error. The poison hits exactly the graph whose storage failed, never another graph of the process (also with write views of several graphs open on one thread): the engine names the failing storage by GraphStorage::storage_identity() (an opaque StorageIdentity, by default StorageIdentity::of(self)). A storage that owns its state keeps the default; a wrapper that forwards to a storage it borrows or owns elsewhere returns that storage's identity (as the shipped &G, &mut G, Box<G> and Arc<TraversalGraph> impls do). Graph::try_read() and Graph::try_write() answer None on a poisoned graph, the same as on a busy one; Graph::is_poisoned() and Graph::try_write_checked() tell the two apart. When a read fails while the engine only builds the message of another error (the element a refused value came from, the type of a refused value), that error is still the one reported, without the detail. TraversalGraph never fails an element read and its methods are inlined, so the Result costs nothing on the hot paths (measured with the Divan bench before the change). The conformance suite has a storage that fails each of these groups on purpose (graphersal-storage-tests, failing: element scans, property reads, adjacency, the unit clock, and the methods beyond single elements).

Units and transactions come for free: the Transactional extension trait (transaction, transaction_with, dry_run) is implemented for every GraphStorage on top of the trait's unit methods. dry_run needs change_capture.

Plugging it in

Front endEntry point
EngineGraphTraversalSource::new(&storage) (reads), GraphTraversalSource::new(&mut storage) (writes)
Shared graphGraph::new(storage); Graph::new_persistent(storage) for a PersistentStorage (adds g.export_snapshot(path) in the DSL)
Rhai DSLgraph_scope(graph), graph_scope_with_options(..), every eval_* function: they take impl IntoAnyGraph, i.e. an Arc<Graph<S>> or an Arc<dyn AnyGraph>
SessionSession::with_storage(Arc::new(StorageKind::<S>::persistent())) for a PersistentStorage (graphs, .gsnap loads, stores in memory), StorageKind::<S>::new() for any other storage (graphs only); session.load_shared(graph, name, kind) serves a graph the host already holds, session.attach_store(Arc::new(store), label) a Store
StoreStore::create_in(dir, storage, options), Store::open_in(dir, options, S::default), open_backup_in, open_read_only_in, create_from_packed_in; the Store page has the table
Snapshotspersist::write_snapshot(&storage, writer, &options), persist::read_snapshot_into(reader, &options, S::default())

A Store requires the capabilities atomic and change_capture and fails with StoreFailure::MissingCapability without them. The files a Store<S> writes do not depend on S: a store written by a host storage opens as Store<TraversalGraph> (in graphersal store, the dev server, Python) and the other way round.

A complete host

The example below is a test of graphersal-session (crates/graphersal-session/tests/custom_storage_example.rs), compiled and run by cargo test -p graphersal-session. The Forwarding storage of graphersal-storage-tests stands in for the host's storage (see below).

use std::sync::Arc;

use graphersal::TraversalGraph;
use graphersal::persist::{MemDir, Store, StoreDir, StoreOptions};
use graphersal::prelude::{ElementProperty, GraphTraversalSource};
use graphersal::script::eval_value;
use graphersal::storage::{Graph, GraphStorage, Transactional};
use graphersal_session::{RunOptions, Session, StorageKind};
use graphersal_storage_tests::forwarding::Forwarding;

/// The host's storage. A real host writes its own `GraphStorage` (+ `Default`, and
/// `PersistentStorage` to be stored); `Forwarding` stands in for it.
type MyStorage = Forwarding;

fn modern() -> MyStorage {
    Forwarding::new(TraversalGraph::tinkerpop_modern())
}

#[test]
fn a_host_plugs_its_own_storage_into_every_front_end() -> Result<(), Box<dyn std::error::Error>> {
    // 1. The engine is generic: a traversal over `&S` (reads) or `&mut S` (writes).
    let mut storage = modern();
    let people = GraphTraversalSource::new(&storage)
        .v(None)
        .has_label("person")
        .count()
        .next()?;
    assert_eq!(people, Some(ElementProperty::from(4)));
    storage.transaction(|g| {
        GraphTraversalSource::new(&mut *g).add_v("robot").next()?;
        Ok::<_, Box<dyn std::error::Error>>(())
    })?;
    assert_eq!(storage.vertex_count().unwrap(), 7);

    // 2. The DSL and saved queries take any `Arc<Graph<S>>` (`impl IntoAnyGraph`).
    //    `new_persistent` also gives the DSL's `g.export_snapshot(path)`.
    let graph = Arc::new(Graph::new_persistent(modern()));
    let _definition = eval_value(
        graph.clone(),
        r#"g.define_query(#{name: "older_than", params: #{age: "integer"},
               body: "fn older_than(age) { g.V().has(\"age\", P.gt(age)).values(\"name\").order() }"})"#,
    )?;
    let names = eval_value(
        graph.clone(),
        r#"g.query("older_than", #{age: 30}).toList()"#,
    )?;
    assert_eq!(names.to_string(), r#"["josh", "peter"]"#);

    // 3. A Store of the storage: `create_in` / `open_in` (it must claim `atomic` and
    //    `change_capture`). Every commit goes to the write-ahead log.
    let dir: Arc<dyn StoreDir> = Arc::new(MemDir::named("custom-storage-example"));
    let store = Store::create_in(&dir, modern(), StoreOptions::new())?;
    store.graph().write().transaction(|g| {
        GraphTraversalSource::new(&mut *g)
            .add_v("person")
            .property("name", "ada")
            .next()?;
        Ok::<_, Box<dyn std::error::Error>>(())
    })?;
    store.close()?;
    // `open_in` takes how to build the empty instance the snapshot is loaded into.
    let store: Store<MyStorage> = Store::open_in(&dir, StoreOptions::new(), MyStorage::default)?;
    assert_eq!(store.graph().read().vertex_count().unwrap(), 7);

    // 4. A session over the storage: every graph it builds (samples, loads, stores in memory,
    //    forks) is a `MyStorage`; here it serves the Store opened above.
    let mut session = Session::with_storage(Arc::new(StorageKind::<MyStorage>::persistent()));
    session.attach_store(Arc::new(store), "my store")?;
    let answer = session.execute(
        r#"g.V().has("name", "ada").count().next()"#,
        &RunOptions::default(),
    );
    assert!(answer.contains(r#""ok":true"#), "{answer}");
    assert_eq!(
        session.graph().storage_type_name(),
        std::any::type_name::<MyStorage>()
    );
    let mark = session.store_mark("after-ada")?;
    assert_eq!(mark["mark"]["name"], "after-ada");
    Ok(())
}

What stays TraversalGraph-only

  • Scratch graphs. Graphs a script creates itself are always TraversalGraphs, whatever the host's storage: GraphSource::*, __, _g, the results of subgraph()/cap()/to_graph() and schema.to_graph(). A host-chosen scratch storage is not planned.
  • withSideEffect(name, graph) into a host graph. A subgraph() writes only into a TraversalGraph; a foreign target fails with GraphError::Unsupported. Let the subgraph land in a scratch graph and copy what is needed.
  • Compressed properties. A foreign storage keeps compression rules in its catalog like any definition (defined, listed, persisted, dropped), but nothing applies them: recompress fails with GraphError::Unsupported and the compression statistics are absent. The session's compression manager lists and edits the rules and says "not supported by this storage" for the rest.
  • The undo log and its change-capture derivation. A foreign storage brings its own (see "Change capture" above).
  • The Store's internal working graphs. The merge checkpoint's delta graph, salvage (maintenance mode) and repair work on internal TraversalGraphs and write files; they never touch the host's graph.
  • The shipped front ends. The CLI (REPL, one-shot runner), the dev server and its MCP endpoint, the Python binding and the WebAssembly playground serve TraversalGraph. A host that serves its own storage builds on graphersal-session instead.
  • Sample graphs and TraversalGraph::with_execution_policy. The sample constructors (TraversalGraph::tinkerpop_modern(), ...) build TraversalGraphs (the session copies them into the host storage); the trait method execution_policy() gives a host storage the same policy hook.

Operations a storage does not implement fail with GraphError::Unsupported, which names the operation; its help points to the storage's documentation and capabilities.

Testing a storage

The conformance suite

Add graphersal-storage-tests as a dev-dependency (with its persist feature to test the PersistentStorage side) and invoke the macro in one test of the implementing crate:

graphersal_storage_tests::conformance!(my_storage, base = MyStorage::default() => base);

Each contract item becomes its own test; the capability-conditional items (rollback, savepoints, hooks, change sets, dry runs, property indexes and their exact lookups) run for what capabilities() claims. Claim exact_property_index_lookups only when a lookup of a point of a string, boolean, uuid or temporal value returns exactly the matching elements: the engine then stops re-checking such conditions (Kept exact). See Storage Conformance.

The Forwarding pattern

graphersal_storage_tests::forwarding::Forwarding forwards every GraphStorage (and, with persist, PersistentStorage) method to a wrapped TraversalGraph, but has its own element handle types. Graphersal uses it to prove that the front ends are storage-independent:

  • crates/graphersal/tests/all/foreign_storage_tests.rs runs every documented DSL example and a curated set of mutating, whole-script, dry-run and saved-query scripts on both storages and requires the same results;
  • crates/graphersal/tests/all/foreign_store_tests.rs runs the Store on Forwarding over every backend (commits, reopen, checkpoints, rollback, backups, ZIP, marks, damage) and opens the files with the other storage type;
  • crates/graphersal-session/src/storage/tests.rs requires the same JSON from a session over either storage;
  • GRAPHERSAL_TEST_STORAGE=forwarding runs the whole TinkerPop suite on it, gated against the same baseline;
  • the first three run in every cargo test of the workspace; the TinkerPop run on Forwarding is a check before every release.

A host can follow the same pattern for its own storage: run the same scripts on a Graph<TraversalGraph> and on a Graph<MyStorage> loaded with the same data and compare the rendered results. Differences are either bugs of the storage or behaviour the host chose (and documents).

Cost

A storage behind Graph<S> runs within 1-4 % of TraversalGraph itself on the measured traversals (measured with the Forwarding test storage), because the engine is monomorphised for it. The price is build time: one engine instantiation per storage type a host uses.

Storage Conformance Tests

GraphStorage is experimental in 0.8.x: its methods and associated types may change in any 0.8.x release (LayeredGraph, a layer over a frozen base, implements it since 0.7.0). The trait's own rustdoc is the implementer's guide: handles, units, capabilities, change capture and statistics.

The crate graphersal-storage-tests (on crates.io, EXPERIMENTAL like the trait: it may break in any minor release before 1.0, so pin the exact version) runs one contract against any GraphStorage implementation. Add it as a dev-dependency (graphersal-storage-tests = "=0.8.0") and, in a test of the implementing crate:

graphersal_storage_tests::conformance!(my_storage, base = MyStorage::new() => base);

The suite uses only graphersal's public API.

Each contract item is a separate test (ids, label sets, edge endpoints, property kinds, JSONPath writes and removals, cascading drops, counts and *_by_label equal to scans after every mutation, schema application, read-only wrappers, stale handles that never alias another element) plus a smoke layer that loads the modern graph through the trait and compares eight traversals with TraversalGraph.

Schema support is optional: the schema items check enforcement only when set_schema does not return GraphError::Unsupported (the trait default); otherwise they pass without checking anything. Schema enforcement is not reusable outside graphersal yet, so a storage in another crate keeps that default and still passes conformance!. conformance_core! leaves the schema items out entirely, for a storage that accepts schemas but deliberately does not enforce them.

Some items depend on what the storage claims in capabilities() (see Transactions): capabilities_are_consistent always runs (change_capture requires atomic); the rollback, savepoint and unit_changes items run for an atomic storage; the commit-hook and apply_change_set items run for a storage with change_capture (and check that a storage without it refuses hook registration). Where the trait documentation is silent the reference implementation decides; those points are listed in the crate README.

The suite is run against TraversalGraph, &mut TraversalGraph, Box<TraversalGraph>, Arc<TraversalGraph>, (read-only items) &TraversalGraph and the blanket &G view of that wrapper, the crate's Forwarding test storage (own handle types, every method forwarded to a TraversalGraph) and a wrapper in the suite's own tests that keeps the trait's schema defaults. It found two contract violations in TraversalGraph (a panic in add_edge for a dropped endpoint, stale edge-id entries after drop_vertex); both are fixed and the suite runs with no ignored test.

Running the TinkerPop suite against another storage

The harness (crates/graphersal/tests/tinkerpop/harness/) holds every dataset graph as Arc<dyn AnyGraph>, so the suite is storage-independent above the storage. Inside this repository GRAPHERSAL_TEST_STORAGE=forwarding runs it on the Forwarding storage of this crate (see TinkerPop Compliance). A storage in another crate cannot run it yet: the harness lives inside the library's integration tests and would have to move into a library-like crate that does not depend on test-only paths. Until then such a storage follows the Forwarding pattern: the same scripts on a TraversalGraph and on the storage, results compared.

How a host plugs its storage into the DSL, the session and the Store: Custom Storages.

Layered Graphs

A layered graph (graphersal::storage::LayeredGraph) is a frozen base graph that any number of layers share, plus a layer of its own: the elements the layer adds, and the base elements it changes or removes. From outside a layer is an ordinary storage (GraphStorage). The typed traversal API, the Rhai DSL, GQL, saved queries and the session all run on it the same way they run on a TraversalGraph. The base never changes: each layer stores only its own difference.

EXPERIMENTAL in 0.8.x, like the GraphStorage trait. A layer can be saved as a layer snapshot or kept in a layer Store; a damaged layer Store is not repaired, and a few catalog kinds are not supported on a layer yet (see Limitations).

What a layer is for and how queries see it (layer(), has_layer(), g.layer_diff(), the CLI's --layer and --layer-store, the store commands' --base, Python) is on the user page Layers. This page describes the storage.

When to use it

  • Many writers over one large graph. Give every user, session or agent its own layer over one shared product graph. Each layer costs about what it changes, not a copy of the graph.
  • What-if edits. Try changes on a layer and throw the layer away, or keep it beside the untouched base.
  • Tests and experiments. Start every test case from the same loaded graph without loading it again or copying it.

If one graph has a single writer, a plain TraversalGraph is simpler and a little faster.

Example

use std::sync::Arc;
use graphersal::prelude::*;
use graphersal::storage::{Graph, LayeredGraph};

// The base: built once, then frozen behind an `Arc` that every layer shares.
let base = Arc::new(TraversalGraph::tinkerpop_modern());

// A layer reads exactly like its base until it is written to.
let layer = LayeredGraph::over(Arc::clone(&base)).unwrap();
let graph = Graph::new(layer); // shared form: a lock around the layer, as for any storage

GraphTraversalSource::new(&mut *graph.write())
    .add_v("person")
    .property("name", "ada")
    .iterate()
    .unwrap();
GraphTraversalSource::new(&mut *graph.write())
    .v(None)
    .has("name", "marko")
    .property("age", 30)
    .iterate()
    .unwrap();

let read = graph.read();
let g = GraphTraversalSource::new(&*read);
assert_eq!(g.v(None).count().next().unwrap(), Some(7_i64.into()));
// The base is unchanged; a second layer over it sees none of these writes.
assert_eq!(TraversalGraph::vertex_count(&base), 6);
let other = LayeredGraph::over(Arc::clone(&base)).unwrap();
assert_eq!(GraphTraversalSource::new(&other).v(None).count().next().unwrap(), Some(6_i64.into()));

// Memory: the total is the layer's own; the shared base is reported beside it.
let stats = read.memory_usage().unwrap().unwrap();
assert_eq!(stats.shared_bytes, base.memory_usage().unwrap().unwrap().total_bytes());
assert!(stats.total_bytes() < stats.shared_bytes);

LayeredGraph::default() is a layer over an empty base.

The base and its models

LayeredGraph::over(Arc<TraversalGraph>) takes the bare base graph. The embedding models of the base's database are not part of the storage: a Store, a recovered view or a .gsnap read attaches their registry to the Graph<TraversalGraph> wrapper, and Graph::into_inner leaves it behind. graphersal::storage::LayerBase (EXPERIMENTAL) is the frozen base together with that registry, a display name and the base's identity:

  • LayerBase::from_graph(Graph<TraversalGraph>) takes the storage and its registry (a poisoned graph is refused); LayerBase::new(Arc<TraversalGraph>) takes a graph without models.
  • A clone is one Arc: every layer made from it shares one base graph and one registry. The registry's commit hook sits on the frozen base, which never commits, so the shared registry never changes under the layers.
  • new_layer() returns a Graph<LayeredGraph> with the registry attached: vector rules on catalog models, embed(), text nearest and g.embedders() on the layer use the base's models. LayeredGraph::over_base(&base) is the bare storage, without models.
  • The layer only uses the models: model definitions in the layer's catalog stay refused.
  • base_ref() is the base's identity, a BaseRef read from the frozen graph (BaseRef::of): its lineage id, last commit sequence number and that commit's time (always Some in this version). LayeredGraph::base_ref() answers the same for a bare layer. A layer snapshot records it and is loaded only over a base of the same identity (below).
  • LayerBase::from_store_read_only(dir, target) (feature persist) opens a Store read-only at target (no lock, no file changed) and keeps the models of that position; LayerBase::from_snapshot_file(path, &options) (feature persist, native only) reads a .gsnap and returns the load report beside the base. Both name the base after its location (the path, a MemDir's name).
  • The identity is stable across loads: every read-only open of the same commit and a .gsnap export of that commit's snapshot have equal BaseRefs (the snapshot records the lineage id, commit sequence number and commit time; the WAL replay restores the last two). A commit to the base store makes a new identity. .gsnap exports copy the store's newest snapshot, so commits still only in the WAL are not in the export: checkpoint first to export the latest commit. Samples and GraphSON/GraphML files get a new lineage id at every load, so they are never the same base twice.
  • BaseRef is Copy + Hash + Eq: a host serving many layers pools its bases in a HashMap<BaseRef, LayerBase> (or Weak handles) and drops a second load of a pooled commit. The LayerBase rustdoc has a pool example; the pool's lifetime and eviction stay the host's. Serving Layers shows a whole server: pool, catalog of names and aliases, and MCP sessions pinned to a version.
use std::sync::Arc;
use graphersal::prelude::*;
use graphersal::storage::{LayerBase, LayeredGraph};

let base = LayerBase::new(Arc::new(TraversalGraph::tinkerpop_modern())).with_name("modern");
assert!(!base.serves_models());
let shared = base.new_layer().unwrap(); // a Graph<LayeredGraph>
let bare = LayeredGraph::over_base(&base).unwrap();
assert!(Arc::ptr_eq(bare.base(), base.graph()));
assert_eq!(shared.read().vertex_count().unwrap(), 6);

How it works

  • Handles (LayeredVertex, LayeredEdge) are 8 bytes. One bit of the slot number tells a base element from an element the layer added. A base element's handle is the base's own handle, so reading it needs no lookup.

  • Dirty bits: the layer keeps one bit for every base vertex slot and every base edge slot. A clear bit means "untouched: read the base". An untouched element costs one bit test and never a hash lookup.

  • The delta holds:

    • the added vertices and edges, in a slot store of its own with its own id and label indexes;
    • a hidden stub for each base vertex that gets new incident edges, which also carries the copied-up state of a modified base vertex;
    • the copied-up state of each modified base edge;
    • tombstones (bitsets) for removed base elements.

    The first write that actually changes a base element copies it up. A write of an identical value copies nothing. An element written back to its base state reads the base again.

  • Ids are unique across the base and the layer. Auto ids continue the base's sequences. A removed base element's id is free again in the layer.

  • Units: the layer keeps its own undo log. A traversal that fails leaves nothing behind, nested units are savepoints, and the layer captures changes: commit hooks see the same ChangeSet a TraversalGraph with the same data reports, and dry runs work.

  • Schema and catalog: the layer copies the base's schema and catalog when it is created. From then on it reads and writes only its copies: set_schema checks the layer's own data, with the errors of a TraversalGraph.

Capabilities

CapabilityLayer
writableyes
atomic (units, rollback, savepoints)yes
change_capture (commit hooks, dry runs)yes
property_indexes (creating indexes)yes: the layer defines, drops and redefines indexes in its own catalog (see below)
layeredyes (a TraversalGraph and other storages: no)
exact_property_index_lookupsas the base. The base's indexes answer only while the layer has not touched that element kind; after that the engine scans
durabilityno
isolation, concurrent_writersas TraversalGraph: none; Graph<LayeredGraph> serializes writers

The engine runs the same TinkerPop and openCypher TCK scenarios on a layer as on a TraversalGraph, with the same results. The DSL test suite compares every documented example and the curated scripts on both. The GraphStorage conformance suite passes on a layer.

Memory

memory_usage() on a layer (in the DSL, g.memory_usage()) reports the layer's own footprint as total_bytes: the delta, its indexes and maps, and the dirty bits (1/8 byte per base slot, the only part that grows with the base). The base's footprint is reported separately as shared_bytes and is not part of the total. Otherwise every layer would "weigh" the whole base. The memory of several layers over one base is the sum of their totals plus shared_bytes once.

Measured (estimates, as every memory_usage figure is):

Layertotal_bytesshared_bytes
over the modern graph, untouched324 010
over 50 000 vertices + 50 000 edges, untouched12 52817 980 778
the same after 1 % writes (250 added vertices, 250 added edges between base vertices, 250 base vertices modified, 250 base edges dropped)206 98217 980 778

shrink_to_fit() releases the delta's spare capacity. It never touches the base.

The process memory ceiling (memory.limit, see Resource Limits) checks a layer's unit at its commit the way it checks a TraversalGraph's, measured on the layer's own footprint: a unit that grows the layer over the ceiling is rolled back. Without a tracking allocator the estimate leaves out the shared base, just as it leaves out the other graphs of the process. With the tracking allocator the live heap counts everything.

memory_report() on a layer has a structure section (GraphStorage::memory_structure, built by Delta::structure): the totals of memory_usage(), the delta's slots (added elements and stubs), its id and label indexes and shape table, and base_stubs, removed_base_vertices and removed_base_edges (StructureMemory::with_base_changes). MemoryReport::shared_bytes is totals.shared_bytes, and the process components add the base as graph with the detail shared base. The rows depend on the scope:

  • MemoryReportScope::All (the default) walks every visible element, base elements included, so a report on a layer equals one on the materialized graph row for row. Only structure and shared_bytes tell that it is a layer.
  • MemoryReportScope::Delta (MemoryReportRequest::with_scope, DSL #{scope: "delta"}) skips the elements whose vertex_layer/edge_layer is Base. That check is one bit test each, so the walk is O(visible elements) in bit tests plus O(delta) in property reads. With an element cap (max_elements), a first pass counts the layer's own elements to compute the sampling step. The rows of a delta report add up to the layer's memory_usage().property_bytes exactly, as a full report of a TraversalGraph does (tested on a 1 % layer). The scope applies only when capabilities().layered is set. Every other storage owns all it shows, so there Delta reports the whole graph.

The indexes rows come from property_indexes(), whose bytes are the layer-owned parts (masked, delta, and an owned base part): 0 for a shared index the layer did not touch.

Limitations

  • Layer snapshots and layer Stores. A layer implements PersistentStorage (load sink, replay of journaled change sets, clear, the journal slot, its own lineage id and auto-id sequences). persist::write_snapshot (or write_graph_snapshot of a Graph<LayeredGraph>) writes a layer snapshot: only the elements the layer added, as ordinary segments, plus a layer file (format spec 7.5, segment kind 128) with the base's identity and the layer's changes to the base (BasePatch entries by base element id: removed vertices and edges, images of changed ones, base definitions it removed). Its size follows the delta: a layer touching about 1 % of a 20,000-vertex base wrote under 3 % of the base's snapshot. persist::read_layer_snapshot(reader, options, &base) (or read_snapshot_into an empty LayeredGraph::over(base)) reads it back over the base: the patch first, then the added elements. The kinds must agree (read_snapshot refuses a layer snapshot, a layer refuses a whole-graph snapshot: PersistError::SnapshotKindMismatch) and so must the base (PersistError::LayerBaseMismatch names both bases: rebuild the layer or load it over its own base). The base's own snapshot or Store keeps its identity, so a base saved and loaded again carries its layers. A layer snapshot's header, manifest and layer file are of file format version 5 (plain snapshots stay at 4), so Graphersal 0.6.x and older refuse it as written by a newer version.

    A layer Store keeps one layer durable and recoverable on every backend (directory, single file, memory): Store::<LayeredGraph>::create_layer(dir, &base, options) (or create_layer_with for a layer built in memory) and Store::open_layer(dir, &base, options). Its snapshots are layer snapshots, its WAL holds the layer's commits; an open loads the newest layer snapshot over the base and replays the WAL, as for any store. The store records only the base's identity (BaseRef), not where the base lives: the base may be a Store opened read-only, a .gsnap or a graph in memory, as long as it is the same graph at the same commit. Another base is refused with PersistError::LayerBaseMismatch naming both; Store::open of a layer store is refused with StoreFailure::LayerStore (it needs its base), open_layer of a plain store with PersistError::SnapshotKindMismatch; all of them before the lock and before any file changes, never damage. Store::info/inspect name the base (StoreInfo::layer_base; graphersal store info prints it). A checkpoint encodes the loaded layer (a merge checkpoint works on whole graphs), so its snapshot stays the size of the delta. The embedding models are the base's: the store keeps none, and its graph serves the LayerBase's registry.

    The base a layer store was built over is a creation parameter (Creation Parameters): every copy carries it. The copies and checks of the files work as for a plain store and need no base: backups (full, incremental, ZIP, from memory), restore_backup/restore_zip, export_packed (a layer .gsnap, read with read_layer_snapshot over the base), verify_dir (every checksum, the layer files decoded, the snapshots not loaded; a note says so) and damage_report_dir. What loads the layer takes the base: verify of the open store and Store::verify_layer_dir, Store::open_layer_read_only and read_only_at of the open store (views over the base, serving its models), Store::open_layer_backup, Store::checkpoint_layer_dir (always an encoded layer snapshot, never a merge); another base is LayerBaseMismatch, a plain store SnapshotKindMismatch, and their plain forms (open_read_only, open_backup, checkpoint_dir) refuse a layer store with StoreFailure::LayerStore. A restored backup is a layer store over the same base: it opens with open_layer over that base only. A backup of a layer store holds no base, so it is useless without it: BackupReport::layer_base names the base and BackupReport::warnings says so (the CLI prints it). The portable form is the materialized export: Store::export_materialized(writer, models) (or WriteOptions::with_materialize(true) with any snapshot writer) writes the whole graph the layer shows as a plain snapshot of file format version 4, which read_snapshot, a plain Store and older releases read without the base; its size follows the whole graph. A layer store's catalog names the base's models; their blobs are the base's, so verification notes them instead of reporting them missing, a layer .gsnap carries none, and a materialized export carries them from the base's registry.

    Forks, rollbacks and the attic work on a layer store and keep it a layer over the same base: fork and attic_fork of the open store and their closed forms Store::fork_layer_dir/Store::attic_fork_layer_dir (with the base; the plain fork_dir/ attic_fork_dir refuse a layer store) load the layer over its base and write a new layer store over it (a new lineage, the creation parameters carried; blobs of the base are not listed as "not carried"); rollback_to (to a commit, a time or a mark), attic_restore and attic_can_restore reload the layer over its base in place and never rebuild the base's model registry, which the base owns (the layer store keeps no model). Store::convert copies a layer store byte for byte onto another backend (a new store id, verified without the base); Store::upgrade_in_place leaves it as it is and Store::upgrade refuses it as current (AlreadyCurrent): a layer store exists only in the current store format.

    Refused for layer stores (StoreFailure::LayerStore, nothing written): the repair (repair_to, repair_dir): a salvage rebuilds a whole graph from damaged files (chunk donors, placeholders for lost elements, divergence against before images, all over a TraversalGraph), and a layer store's files hold only the layer's changes to a base the salvage does not read; a damaged layer store refuses the open with the damage (no maintenance mode): restore a backup of it, or rebuild the layer. The closed-store catalog commits (import_model_dir, set_default_model_dir, remove_model_dir): they change embedding models, which a layer store does not keep and a layer refuses to define. And creating a layer store from a .gsnap.

  • The base is a TraversalGraph with fewer than 2^31 vertex slots and fewer than 2^31 edge slots. Nobody can change it while layers share it: it sits behind the Arc.

  • Refused, with GraphError::Unsupported ("... not supported on a layered graph yet"): compression rule and embedding model definitions in the layer's catalog, and compression estimates over element kinds the layer changed.

  • Vector rules run on the layer's own units with TraversalGraph's rule pass (the same code, generic over the RuleLog trait, graph/vector_rules.rs): the layer compiles the rules of its own schema (when it is created, at every schema write and its undo), refuses a direct write of a rule's to inside a live unit through the shared write rules (the same GraphError::DerivedProperty at the same point), runs the pass at the outermost commit before the memory check and in the discard of a dry run, and keeps apply_change_set exempt. The derived vectors, errors, rollbacks, journal records and change sets equal a TraversalGraph's with the layer's data. A base with rules costs nothing at creation; a vector recomputed to the value a base element holds stores nothing (the equal-value skip), so only an element whose sources changed is copied up, except by the first fill of a rule the layer adds or changes on a base label, which copies every element of the label it writes. PlannedFill::base_copies counts them (exact in validate_schema, the label's untouched base elements in diff_schema), from the new capability StorageCapabilities::layered and the element origins. Models: the pass finds a catalog model in the registry the Graph guard attaches to the thread, so a Graph<LayeredGraph> made by LayerBase::new_layer() embeds with the base's models (see The base and its models). A bare layer (LayeredGraph::over, or Graph::new of one) serves only hash-ngram/1: a rule on a catalog model of the base passes the schema check (the catalog is copied) and its pass fails with GraphError::VectorRuleFailed ("not served here"), rolling the unit back, as on a Graph<TraversalGraph> without the model.

    A base with plain or unique indexes or compression rules is fine: the layer reads it. The layer stores its own values uncompressed. compression_stats reports the base's figures. The base's unique indexes are enforced over base + delta: every write TraversalGraph checks (creates, property and path writes, a label added, an edge relabeled) is checked at the same point of its write rule, against the base elements the layer neither dropped nor copied up plus the layer's own elements, with the same GraphError::UniqueViolation (index, value, the other element's id). A unique index the base keeps disabled is not enforced and unique_index_duplicates answers the base's report until the layer drops or redefines it.

  • Indexes the layer defines. The layer's catalog takes property index definitions as a TraversalGraph's does (same validation, the other index kind's definition of the name replaced, the same conflict errors), each define and drop recorded in the layer's undo log and change set. A definition equal to the base's (an inherited index, or one dropped and defined again) reads the base's index in place. Any other builds a base part of its own over every base element of its label (a full scan, its bytes in the layer's property_index_bytes, never in shared_bytes), so an index on a large base label costs that label's index once per layer. A unique define is checked over the layer's data (the base elements the layer neither dropped nor copied up plus its own): repeated values keep it disabled with the layer's own report, and the front ends refuse it with the same DefinitionError::UniqueIndexDuplicates as on a TraversalGraph. Dropping an index (also one of the base) removes it for the layer: lookups, plans and unique checks stop using it, the base keeps its own. A rollback rebuilds the overlay from the catalog and data as they were.

  • Order. Unordered traversals list the same elements as a TraversalGraph holding the same data, and in the same order for every write except these:

    • after a drop followed by a create, a TraversalGraph reuses the freed slot and the layer appends;
    • after a drop or a label removal, a label lookup lists the base bucket minus the removed element, where a TraversalGraph moves the bucket's last member into the gap;
    • an edge relabeled to a label that also has added edges is listed before those edges.

    Order is not part of the TinkerPop contract for unordered traversals; use order() when it matters.

Serving Layers

A server that hosts one product graph for many customers keeps the product once and gives each customer a layer over it. Clients configure a name such as /mcp/acme, never a version. When the product is released again, the server publishes new layers over the new product version, and the name moves to them. This page describes that serving model, which pieces Graphersal provides for it, and what a host builds itself.

graphersal-serve hosts one graph per process, and it stays that way: it has no base pool, no catalog of names and no multi-graph server. A host builds those on its extension points. A complete reference host lives in the tests of graphersal-serve, in the module extension_tests::reference_resolver (crates/graphersal-serve/src/extension_tests.rs). The excerpts on this page come from it.

The serving model

  • Base pool. The server loads each product version once, as a frozen LayerBase, and keys it by its identity (BaseRef). product@2026.3 and product@2026.4 live side by side while layers over the old version still exist.

  • Catalog. Each served version is named <name>@<version> and is a layer over a pooled base:

    product@2026.3   -> base (served read-only as an empty layer over it)
    acme@2026.3      -> layer over product@2026.3
    globex@2026.3    -> another layer over the same base
    acme             -> alias, now acme@2026.3
    acme@2026.2      -> explicit pin to an old version, kept on purpose
    
  • Sessions are pinned. An MCP session is bound to a graph when it starts (initialize) and stays on that graph for its whole life. A release flips the alias: new sessions get the new version, and open sessions finish on the old one.

  • Old versions are retired. Once no alias and no pin names a version, and no session has used it for a while, the host drops it. When a base has no layers left, the host drops it from the pool.

What Graphersal provides

PieceWhereWhat it does
LayerBasegraphersal::storageA frozen base: the graph, its embedding models, a display name and its identity. A clone is one Arc. new_layer() makes a Graph<LayeredGraph> over it.
LayerBase::from_store_read_only(dir, target)feature persistOpens a versioned base store read-only at a commit or a mark (RecoveryTarget::Mark("2026.3")). It takes no lock and writes nothing, so the release process may keep the store open.
LayerBase::from_snapshot_file(path, options)feature persist, nativeLoads a base from a .gsnap file.
BaseRefgraphersal::storageThe base's identity: lineage id, commit sequence number and commit time. It is Copy + Hash + Eq, so it can key the pool.
Layer storesStore::create_layer / open_layerKeep a customer's layer durable. A layer store records the BaseRef of its base, and opens only over a base with that identity.
Host::serves_layergraphersal-mcpMakes the initialize instructions name layer(), has_layer() and g.layer_diff().
Route taggraphersal-mcpHost::session_route puts the version into the session id: <route>~<id>.
graphersal_mcp::session_route(id)graphersal-mcpReads the route out of an id, without checking the id.
Mcp::verified_session_route(id)graphersal-mcpReturns the route only when the endpoint knows the id as an anonymous session; verified_session_route_for(id, identity) for a request with an identity.
ContextBuilder::layered(true)graphersal-serveTells the context's Host that it serves a layer from the first initialize on.
ContextBuilder::mcp_session_route(Some(..))graphersal-serve, feature mcpSets the route tag of the sessions this context starts.
ContextBuilder::shared_mcp / mcp_profilegraphersal-serve, feature mcpOne MCP endpoint for every context, with a profile per context.
GraphResolver, Server::ready_withgraphersal-serveThe extension point that picks the context of each request.
Request::mark_read_onlygraphersal-serveServes one request read-only: the host's router or RequestFilter marks it, for a caller with read access only (see "Read-only requests" below). EXPERIMENTAL.
ContextBuilder::file_root, jobs_outside_file_rootgraphersal-serveConfines every file path a client names (backup jobs, catalog loads, fork and backup directories) to one directory (see "File root" below). EXPERIMENTAL.
SessionStore, Mcp::with_session_store, Mcp::forget_sessions_ofgraphersal-mcpKeeps the MCP session table across restarts, and ends the sessions of a revoked identity (see "Sessions survive a restart" below). EXPERIMENTAL.
GraphDirectory, Mcp::handle_directorygraphersal-mcpOne MCP endpoint over all graphs: the agent lists them, selects one per session and may switch (see below). EXPERIMENTAL.

Base identity

Every read-only open of the same commit has the same BaseRef, and so does a .gsnap export of that commit's snapshot. A second load of a pooled commit can be dropped in favour of the pooled base. A commit to the base store makes a new identity, so each product version is its own base.

A .gsnap export copies the store's newest snapshot. Commits that are still only in the write-ahead log are not in it, so checkpoint before you export a release. Otherwise the export holds the commit of the newest snapshot, with that commit's identity.

Samples and GraphSON or GraphML files get a new lineage id at every load. They never count as the same base twice, so a server should load its bases from a Store or a .gsnap.

This example pools two product versions loaded from one versioned store and lays two customers over the same base. It needs only the graphersal crate:

use std::collections::HashMap;
use std::sync::Arc;
use graphersal::persist::{MemDir, RecoveryTarget, Store, StoreOptions};
use graphersal::prelude::*;
use graphersal::storage::{BaseRef, LayerBase};

// The release process: one base store, a mark per product version.
let dir = MemDir::named("product");
let store =
    Store::create_with(&dir, TraversalGraph::tinkerpop_modern(), StoreOptions::new()).unwrap();
store.mark("2026.3").unwrap();
GraphTraversalSource::new(&mut *store.graph().write()).add_v("feature").iterate().unwrap();
store.mark("2026.4").unwrap();
store.close().unwrap();

// The server's pool: one LayerBase per base commit.
fn pooled(pool: &mut HashMap<BaseRef, LayerBase>, dir: &MemDir, mark: &str) -> LayerBase {
    let loaded = LayerBase::from_store_read_only(dir, RecoveryTarget::Mark(mark.into()))
        .unwrap()
        .with_name(format!("product@{mark}"));
    let key = *loaded.base_ref().unwrap();
    pool.entry(key).or_insert(loaded).clone()
}
let mut pool = HashMap::new();
let acme = pooled(&mut pool, &dir, "2026.3").new_layer().unwrap();
let globex = pooled(&mut pool, &dir, "2026.3").new_layer().unwrap(); // the pooled base
assert_eq!(pool.len(), 1);
assert!(Arc::ptr_eq(acme.read().base(), globex.read().base()));
let next = pooled(&mut pool, &dir, "2026.4").new_layer().unwrap();
assert_eq!(pool.len(), 2);
assert_eq!(acme.read().vertex_count().unwrap(), 6);
assert_eq!(next.read().vertex_count().unwrap(), 7);

The route tag

At an HTTP initialize, the endpoint asks the context for its route. If the context has one, the session id becomes <route>~<id>, for example acme@2026.3~9f2c…:

  • With signed ids (Mcp::with_session_key), the route is part of the signed data. A changed, removed or added route breaks the signature, and the endpoint answers 404. Replicas that share the key verify each other's ids, so a load balancer may send a session's requests to any replica.
  • In table mode (the default), the table stores the whole routed id. An edited route is an unknown id, which is also a 404.
  • A route is 1 to 128 bytes of [A-Za-z0-9._-@/:+=] (is_valid_session_route). An invalid route makes initialize fail with a JSON-RPC error, so a session is never left unpinned.

A stream connection (Context::mcp_connection) is its own session and has no route: the host picks the context when it opens the stream.

Sessions belong to their identity

Every HTTP MCP session belongs to the identity of the request that sent its initialize (what the host's request filter attached, McpRequest::with_identity; none means anonymous). A request that names the session id with another identity gets the same 404 as an unknown session, and a DELETE from it ends nothing. Anonymous counts as an identity of its own: an anonymous session cannot be used by a signed-in caller, and the other way round. In table mode the table stores the identity with the session; with signed ids the identity is part of the signed data (an anonymous id signs exactly what it signed before). One Mcp shared by several routes (/mcp and per-graph paths) accepts a session id on each of them, for its identity only. A resolver that checks a routed id for a caller uses mcp.verified_session_route_for(id, identity); verified_session_route(id) checks it as anonymous.

Sessions survive a restart

By default the session table lives in memory: a restarted host forgets every MCP session, and each client gets 404, initializes again and, in directory mode, selects its graph again. A host that wants the sessions back after a restart gives the endpoint a store:

let mcp = Mcp::new(false, None, false)
    .with_max_sessions(1024)                     // first: the load keeps the newest 1024
    .with_session_store(Arc::new(MyFileStore::new(dir)))?;

SessionStore has two methods: load answers the stored sessions once, and save gets the whole table after every change (a session created, a graph selected, a selection renamed or its note told, a session ended or evicted). A save runs outside the table lock, one at a time, and never writes an older table after a newer one. A failed save is a tracing warning; the request goes on and the next change saves again. So write atomically (a temporary file, then a rename).

Each row is a StoredSession: the SHA-256 of the id (64 hex digits; the table never holds the plain id, so the store holds nothing a client could present), the identity, the selected name, the old name of a pending rename note, the negotiated protocol revision, the client's {name, version} and the creation time in Unix seconds. The host serialises it in any format (strings, a number and a JSON value) and rebuilds it with StoredSession::new. A restored session answers its old id for the same identity only, with its selection and its pending note. The expiry rule is unchanged: at most with_max_sessions, the oldest dropped first.

When the host revokes a user's token or removes the user, mcp.forget_sessions_of(Some(id)) ends that identity's sessions at once (and saves the table); it answers how many it ended. Signed ids (Mcp::with_session_key) keep no table: with_session_store refuses them with an error, and forget_sessions_of ends nothing there.

Read-only requests

A host that gives some callers read access only marks their requests: request.mark_read_only(), in its router or its RequestFilter, after it decided who sent the request. The mark holds for that one request, and nothing clears it. graphersal-serve then serves the request like this (the context itself stays writable for every other request):

  • POST /api/execute and POST /api/query run under the reading authorizer. A script or saved query that would write fails with a permission error and changes nothing.
  • Every other route that writes answers 409 with the graph is served read-only: writes are refused. This request has read access only: ask for write access to change the data. (READ_ONLY_HEADLINE, READ_ONLY_REQUEST_HELP). That covers the schema, element, catalog, compression, index and saved-query writes, the scheduled jobs, the advisor's apply, dismiss and restore, POST /api/save, and every Store operation that writes: checkpoint, mark, rollback, the attic, compaction, and also fork, backup and view, which write directories or switch the view every client of the context sees.
  • Reads stay open, downloads included: exports in every format, the .gsnap download, Store snapshots, statistics, the journal, the layout.
  • /mcp serves the request under the context's MCP profile made read-only (Profile::with_read_only(true) in graphersal-mcp): only reading tools, and a writing query is refused. The same MCP session may write again on a request that is not marked.
  • GET /api/info and GET /api/changes answer readOnly: true for the request, and so does their mcp status.

The host's own extra routes (Hooks::route) see the mark with request.is_read_only() and decide for themselves. A host that serves MCP in directory mode (handle_directory) answers a reader's profile from its GraphDirectory::host instead.

File root

Without further settings a client with write access may name any path the server process can write: a backup job's directory, the directory of a Store fork or backup. A host that serves callers it does not trust with the machine's files sets a file root on each context: ContextBuilder::file_root(Some(root)). The default, None, keeps the old behaviour (the CLI dev server never sets one). With a root:

  • POST /api/jobs/define resolves a backup job's path under the root: a relative path is relative to the root, and a path that leaves it (an absolute path elsewhere, .., a symbolic link pointing out) is refused in the answer. The job stores the resolved path.
  • POST /api/catalog/load refuses with 403 a catalog with a job that writes outside the root, and loads nothing. A stored job path must be absolute and inside the root.
  • The dir of POST /api/store/fork, /api/store/attic/fork and /api/store/backup is resolved the same way: a relative dir is relative to the root (not to the store's directory), and one outside it answers 403 with paths must lie inside the server's file root. Without a dir the default directory next to the store is used, as before.

The root must exist; a requested dir under a missing root answers 500. Jobs already stored in a store the host loads (an imported, restored or cloned store) are not checked by the context: the host passes the store's definitions to graphersal_serve::jobs_outside_file_root and disables or refuses the jobs it returns.

What a host builds

The host owns four pieces: the pool, the catalog, the path rewrite and the resolver. It also decides when an old version goes.

Pool and catalog

struct Served {
    context: Arc<Context>,
    base: BaseRef,
    last_used: Instant,
}

#[derive(Default)]
struct Catalog {
    versions: HashMap<String, Served>, // "acme@2026.3" -> its context
    aliases: HashMap<String, String>,  // "acme" -> "acme@2026.3"
    kept: HashSet<String>,             // explicit pins, never retired
}

struct LayerHost {
    mcp: Arc<Mcp>, // one endpoint for every context
    pool: Mutex<HashMap<BaseRef, LayerBase>>,
    catalog: Mutex<Catalog>,
}

One context per version

Each version gets a session thread that serves its layer, and a context built with .layered(true), its route, the shared endpoint and a profile of its own. Here a read-only customer gets Profile::new(true).with_access_policy(AccessPolicy::read_only()).

fn publish(&self, version: &str, base: &LayerBase, profile: Profile) {
    let layer = Arc::new(base.new_layer()?);
    let name = version.to_string();
    let (jobs, ()) = spawn_session(
        SessionPresets::new(),
        move |session| session.load_shared(layer, &name, "layer").map(|_| ()),
        None,
    )?;
    let context = Context::builder(Runner::Session(jobs), host_check)
        .layered(true)
        .shared_mcp(self.mcp.clone())
        .mcp_profile(profile)
        .mcp_session_route(Some(version.to_string())) // "acme@2026.3"
        .build();
    self.catalog.lock()?.versions.insert(version.into(), Served { context, .. });
}

A customer layer that must survive restarts comes from a layer store instead (Store::<LayeredGraph>::open_layer(dir, &base, options)), and the session serves the store's graph. The layer store refuses a base whose BaseRef differs from the one it was created over.

Path rewrite

A context answers MCP at /mcp only. The host's listener turns POST /mcp/acme into POST /mcp and puts the name into a header. It drops any copy of that header the client sent, so only the path names the graph:

const GRAPH_HEADER: &str = "X-Graphersal-Graph";

let name = path.strip_prefix("/mcp/").filter(|name| valid_name(name))?; // else 404
let mut request = Request::new(method, "/mcp", body);
for (field, value) in client_headers {
    if !field.eq_ignore_ascii_case(GRAPH_HEADER) {
        request = request.with_header(field, value);
    }
}
server.handle(request.with_header(GRAPH_HEADER, name))

The resolver

The resolver runs for every request. A request with a session id goes to the version in the id's route, after two checks. A request without one, such as initialize, goes to the alias's current version, or to the version the path names (/mcp/acme@2026.2):

impl GraphResolver for LayerHost {
    fn resolve(&self, request: &Request<'_>) -> Result<Arc<Context>, HttpError> {
        let name = request.header(GRAPH_HEADER).ok_or_else(|| not_found())?;
        let routed = match request.header("Mcp-Session-Id") {
            Some(id) => {
                // 1. The endpoint knows the id (signature, or the table).
                let route = self.mcp.verified_session_route(id).ok_or_else(|| not_found())?;
                // 2. The route is a version of the name in the path.
                let belongs = if name.contains('@') {
                    route == name
                } else {
                    route.split_once('@').is_some_and(|(of, _)| of == name)
                };
                if !belongs {
                    return Err(not_found());
                }
                Some(route)
            }
            None => None,
        };
        let mut catalog = self.catalog.lock()?;
        let version = match routed {
            Some(route) => route.to_string(),
            None if name.contains('@') => name.to_string(), // an explicit pin
            None => catalog.aliases.get(name).cloned().ok_or_else(|| not_found())?,
        };
        let served = catalog.versions.get_mut(&version).ok_or_else(|| not_found())?;
        served.last_used = Instant::now();
        Ok(served.context.clone())
    }
}

A release publishes the new version and then flips the alias: catalog.aliases.insert("acme".into(), "acme@2026.4".into()). Nothing else changes. Sessions already open carry acme@2026.3 in their ids and keep reaching that version's context.

When to drop an old version

An open session keeps working only while the resolver still holds its version's context. The endpoint cannot tell the host when a session has ended: a client may never send DELETE, and a signed id stays valid for good. So the host decides. The reference host's policy:

  • A version is needed while an alias names it or it is in kept (an explicit pin).
  • A version that is not needed is retired after grace without a request (retire_idle). The resolver records last_used on every request it resolves. Retiring removes the context from the catalog. Its session thread then ends and its layer is dropped.
  • A session still routed to a retired version gets 404 for an unknown session. The MCP client then starts a new session, which gets the current version. Pick the grace period so that this rarely happens during a working session (minutes to hours, not seconds).
  • When no served version reads a pooled base any more, the base leaves the pool (evict_unused_bases), and its memory is freed with the last layer over it.

Other policies fit the same pieces: a deadline per release, a count of sessions per version kept by the host, or retiring only at night. The test a_retired_version_drops_its_context_layer_and_finally_its_base checks the reference policy: the context, the layer and finally the base are released.

One endpoint over all graphs (directory mode)

Instead of one MCP URL per graph (/mcp/acme), a host may offer a single endpoint that an agent's harness configures once. The host implements graphersal_mcp::GraphDirectory over its catalog:

  • list(): the graphs and aliases an agent may name, each a GraphEntry with its kind (plain, layer, base), state (unloaded, loading, loaded, needs-model, failed with a reason), read-only flag and description.
  • resolve(name): the route of a name, an alias resolved now (acme -> acme@2026.3). The endpoint calls it on every call of a session, so keep it cheap.
  • host(route): the context serving that route (a graphersal-serve Context is a graphersal_mcp::Host) and its MCP profile, or an error whose text the agent reads, such as database 'acme@2026.3' is not loaded; ask an operator to load it.

The methods take no caller. A host whose graphs differ per caller builds the directory for each request from the identity it attaches to that request, and passes that directory to handle_directory. It lists only what the caller may see, answers a hidden graph with exactly the error of an unknown name (from resolve, use_graph and the graph argument alike), and answers the caller's profile from host (read-only for a reader). The session's selected name is resolved through the directory of each request, and a session cannot be used by another identity (see "Sessions belong to their identity" above).

The host's listener passes every request to its endpoint path to mcp.handle_directory(&catalog, request). Inside an MCP session the agent calls list_graphs, selects a graph with use_graph {name} and may switch later; every data tool takes an optional graph argument that names another graph for one call. Each call runs on that graph's context under that context's profile, so its read-only flag and access policy apply. Saved queries are not tools of their own here: the agent runs them with run_saved_query (and graph).

  • The selection is a name. use_graph stores the name the agent asked for (a graph or an alias, spelled as list() spells it when one entry matches ignoring ASCII case) and the endpoint resolves it again on every call, as an HTTP path /db/<name>/ is. This is not the route tag above: a route tag pins a session to one version, a directory selection follows its name.

    • Re-pointed alias: the session follows it silently. Errors of the new target (not loaded, read-only) are ordinary tool errors.
    • Removed alias: a call fails with "pick another graph: list_graphs, then use_graph" only while no graph or alias of that name exists. The selection stays, so an alias created again under that name simply works on.
    • Renamed alias: the host renames it in its catalog, then calls mcp.rename_selection(old, new) (it answers the number of sessions moved). Each moved session's next tools/call answer starts with one line, note: alias "<first old>" was renamed to "<current>"; several renames before that call give one note from the first name to the current one.
    • A real graph name stays on that graph whatever the aliases do.
  • list_graphs answers selected (the session's name, or null) and selectedGraph (the graph that name resolves to now, or null); use_graph answers selected (the name) and graph (its graph now).

  • A new session starts empty. After a reconnect, or when the endpoint forgot the session (the table keeps MAX_SESSIONS, 64, unless Mcp::with_max_sessions says otherwise; the client then gets 404 and initializes again), calls that name no graph fail with a message that names list_graphs and use_graph, and the instructions tell the agent to select again.

  • Table sessions only. The selection lives in the session table, so a directory endpoint refuses signed session ids (Mcp::with_session_key).

  • Mcp::with_endpoint(path) sets the path Mcp::status shows.

  • The route is visible to the client. It is part of the Mcp-Session-Id header, so never put a secret, a tenant key or a storage path into it. A versioned name is enough.

  • Check the name in the path. A client that may use two graphs holds genuine session ids for both. Without the name check, an id that /mcp/globex handed out would reach globex's graph when sent to /mcp/acme, past any authorization that the host based on the path. The check is needed in both session modes: a signature proves the id is genuine, not that it belongs to this path.

  • Edited routes. In table mode an edited id is an unknown id, and with signed ids it fails the signature. Ask the endpoint (verified_session_route) before trusting the route. The plain session_route decoder does not check anything.

  • Ignore the client's copy of the routing header. The host sets the name header from the path and drops one the client sent.

  • Profiles are per context. The read-only flag and the access policy of each customer are in that customer's contexts (mcp_profile). One shared endpoint does not mean one shared policy.

  • Authentication stays the host's job, in a RequestFilter that knows the path's name. The filter attaches the caller's identity and, for a caller with read access only, marks the request read-only (see "Read-only requests" above).

GQL Queries

Experimental. GQL support is new in Graphersal 0.2.2 and marked experimental: its subset grows from version to version, and the answers of a construct (its rows, errors and plans) may still change in a later version. Gremlin stays the complete, stable interface: a gql() query runs as ordinary Gremlin steps, and this chapter shows the Gremlin twin of each construct.

g.gql(query) runs a query written in GQL, the ISO standard graph query language (ISO/IEC 39075), on the same graph and the same engine as Gremlin. A GQL query describes the pattern you are looking for; Graphersal finds every match and returns one row per match:

g.gql("MATCH (p:person)-[:created]->(s:software) WHERE p.age > 30 RETURN p.name AS who, s.name AS what ORDER BY who, what").to_list()
// #{"what": "lop", "who": "josh"}, #{"what": "ripple", "who": "josh"}, #{"what": "lop", "who": "peter"}

The Gremlin equivalent walks the graph step by step:

g.v().has_label("person").has("age", P.gt(30)).as("p").out("created").has_label("software").as("s").select("p", "s").by("name").to_list()
// #{"p": "josh", "s": "ripple"}, #{"p": "josh", "s": "lop"}, #{"p": "peter", "s": "lop"}

Every example in this chapter was run on the sample graph modern; the comment after // is its real output (a list is shown as its items, comma-separated, or one per line).

What gql() is

  • ISO GQL is the norm. Queries are written in GQL; where GQL and Cypher differ, GQL wins. Familiar Cypher spellings are accepted as aliases where they are unambiguous and mean the same (SKIP for OFFSET, != for <>, toUpper() for upper(), --> for ->, ...); Cypher Aliases lists every one. There is no Graphersal-only syntax: an accepted query means the same in a GQL or Cypher 25 database (modulo the listed aliases).
  • Reads and writes. INSERT (Cypher CREATE) creates nodes and edges, SET and REMOVE change their properties and labels, and DELETE / DETACH DELETE remove them, each once per row, and Cypher's MERGE finds or creates a pattern (Writing with GQL). A query is one unit: a query that fails changes nothing.
  • A start step. gql() starts a traversal: g.gql(..), never g.v().gql(..) or __.gql(..).
  • Rows are maps. Each result row is a map from column name to value (Result Shape). RETURN is mandatory unless the query ends in a write.
  • One engine. The query is compiled into an ordinary traversal plan: the same optimizer, property indexes, profile(), limits, cancellation, permissions and storages as Gremlin (Plans and Performance). A query that does not parse fails before anything runs, with a caret under the offending text (Errors).

This version supports INSERT and GQL read queries: MATCH and OPTIONAL MATCH, WHERE, LET, FILTER, Cypher's WITH, RETURN with aggregation (count, sum, avg, min, max, collect_list), ORDER BY, OFFSET, LIMIT, FOR (Cypher UNWIND) with a direct lookup per item where an id or index serves it, queries that start without MATCH (RETURN 1 + 2 AS x), EXISTS subqueries and Cypher pattern predicates (WHERE NOT (p)-[:created]->()), Cypher map projections and list and pattern comprehensions for nested, JSON-shaped answers (p {.name, friends: [(p)-[:knows]->(f) | f.name]}), Cypher's COUNT { } / COLLECT { } and list predicates (all(), any(), reduce(), ...), composite queries (UNION, UNION ALL, NEXT), CALL { } subqueries run per row (top k per group), node and edge patterns, quantified edges (-[:knows]->{1,3}), quantified path patterns that repeat a whole chain ((a) ((x)-[:created]->(s)<-[:created]-(y)){1,2} (b)), path variables, label expressions, expressions, parameters, the GQL scalar functions and the common openCypher ones (toInteger, substring, split, round, keys, nodes(p), ...) (The Supported Subset). EXCEPT / INTERSECT, shortest paths and a quantifier nested inside a quantified path pattern come later; until then the error names the form or the Gremlin step that does the same.

g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s) RETURN p.name AS name, count(s) AS made ORDER BY made DESC, name").to_list()
// josh 2, marko 1, peter 1, vadas 0
g.gql("MATCH (a {name: 'marko'})-[:knows]->{1,2}(b)-[:created]->(s) RETURN DISTINCT s.name AS s ORDER BY s").to_list()   // #{"s": "lop"}, #{"s": "ripple"}
g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[e:created]->(s) RETURN s.name AS top ORDER BY e.weight DESC LIMIT 1 } RETURN p.name AS who, top ORDER BY who").to_list()
// josh ripple, marko lop, peter lop: each person's heaviest software

Mixing GQL and Gremlin

Gremlin steps may follow gql(). They see the row maps and reach a column by its name, so whatever GQL cannot do yet, a Gremlin step after it can:

g.gql("MATCH (p:person) RETURN p ORDER BY p.name").select("p").out("created").values("name").order().to_list()   // "lop", "lop", "lop", "ripple"
g.gql("MATCH (a)-[:knows]->(b) RETURN *").select("a", "b").by("name").to_list()   // #{"a": "marko", "b": "josh"}, #{"a": "marko", "b": "vadas"}
g.gql("MATCH (p:person) RETURN p.name AS name, p.age AS age").select("age").sum().next()   // 123
g.gql("MATCH (p:person)-[:created]->(s) RETURN p.name AS name").select("name").dedup().order().to_list()   // "josh", "marko", "peter"

An element column (RETURN p) holds the live vertex or edge, so select("p").out(..) continues the walk from it.

Where you can use it

Entry pointHow
RustGraphTraversalSource::gql(query) and gql_with(query, params), feature gql
Gremlin DSL (Rhai)g.gql(query) and g.gql(query, #{name: value}); see Writing GQL in Rhai Strings
Command linegraphersal -e 'g.gql("MATCH (p:person) RETURN p.name AS name")', or in the REPL
Pythonthrough a script: graph.query('g.gql("...", #{...})', params={...})
Playgrounda GQL query tab (the + menu, or the Rhai / GQL switch): plain GQL with completion and a Parameters field; or g.gql("...") in a Rhai tab; the examples list has a GQL group (Web Playground)
Saved queriesg.define_query(#{name: "older", language: "gql", params: #{min: "integer"}, body: "MATCH (p:person) WHERE p.age > $min RETURN p.name AS name"}), then g.query("older", #{min: 30}) from any front end (Saved queries in GQL), or CALL older(30) YIELD name RETURN name from a GQL query (Calling saved queries)
MCP (dev server)the tool gql {query, params, profile, offset, max_rows, max_items}: the query as plain text, no Rhai string around it, its rows as compact JSON paged with offset; it writes like the query tool, and a server started with --mcp-read-only refuses its writes

In Rust:

use graphersal::prelude::*;

let graph = TraversalGraph::tinkerpop_modern();
let ages = graph
    .traversal()
    .gql_with(
        "MATCH (p:person {name: $name}) RETURN p.age AS age",
        [("name", ElementProperty::from("marko"))],
    )
    .select("age")
    .to_list()
    .unwrap();
assert_eq!(ages, [ElementProperty::from(29)]);

A writing query runs on the writing source, traversal_mut() (In Rust).

In the playground, a GQL tab takes the query as it is, without a Rhai string around it, and its parameters as a JSON map in the Parameters field under the editor:

MATCH (p:person) WHERE p.age > $min
RETURN p.name AS name ORDER BY name

Parameters: {"min": 30}

The tab runs it as g.gql("MATCH (p:person) WHERE p.age > $min\nRETURN p.name AS name ORDER BY name", #{min: 30}): a JSON integer stays an integer, 30.0 is a float, null is NULL, lists and maps stay lists and maps. An error is underlined where the engine reports it, with its GQLSTATUS in the message. To continue a GQL result with Gremlin steps (.select("p").out()), switch the tab to Rhai: the query and its parameters become that g.gql(..) call.

The feature gql is off by default in the graphersal crate (Library Features); the command line, the playground, the dev server and the Python package have it on.

From Python, values travel as script variables and from there into the GQL parameter map:

graph.query('g.gql("MATCH (p:person) WHERE p.age > $min RETURN p.name AS name, p.age AS age ORDER BY age", #{min: min_age})',
            params={"min_age": 30})
# [{'age': 32, 'name': 'josh'}, {'age': 35, 'name': 'peter'}]

In this chapter

  • The Supported Subset: clauses, patterns, label expressions, expressions, functions, parameters, and what is not supported yet.
  • Semantics: trail matching, quantified edges and path patterns and their limits, OPTIONAL MATCH, NULL and three-valued logic, subqueries (EXISTS, COUNT, COLLECT, CALL), UNION and NEXT, aggregation, DISTINCT equality, comparisons, ordering, the rules of the functions (strict CAST, lenient toInteger, rounding, where they differ from Neo4j), ids.
  • Result Shape: row maps, column names and their order, path values.
  • Writing with GQL: INSERT (Cypher CREATE), what a row sees, units, schema, permissions, and the write clauses that come later.
  • Writing GQL in Rhai Strings: quotes, multi-line queries, comments, parameters, and when the MCP tool is easier.
  • Cypher Aliases: every accepted Cypher spelling and its GQL form.
  • Refused Constructs: what gql() will not do, and why.
  • Errors: GQLSTATUS codes and diagnostics.
  • Plans and Performance: what a query becomes in profile().
  • GQL Conformance: the GQL features supported, partially supported and not supported.
  • The generated step page gql.

The Supported Subset

This page lists what gql() accepts in this version, construct by construct, each with a runnable example and, where it is natural, its Gremlin twin. Everything not listed here is an error that says so (Not supported yet at the end, Refused Constructs for what will never be supported).

The shape of a query

[ clauses, in any order and number:
  [OPTIONAL] MATCH <pattern> [, <pattern> ...] [WHERE <condition>]
  LET <name> = <expr> [, ...]
  FILTER [WHERE] <condition>
  FOR <name> IN <list> [WITH ORDINALITY <name> | WITH OFFSET <name>]
  UNWIND <list> AS <name>                     -- Cypher spelling of FOR
  WITH [DISTINCT] <item> [AS <name>], ...     -- or WITH *; Cypher
       [ORDER BY ...] [OFFSET <n>] [LIMIT <n>] [WHERE <condition>]
  [OPTIONAL] CALL [(<name>, ...) | (*)] { <query> }   -- a subquery run for each row
  [OPTIONAL] CALL <folder>.<name>(<arg>, ...)          -- a saved query run for each row
       [YIELD <column> [AS <name>], ... [WHERE <condition>]]
  INSERT <pattern> [, <pattern> ...]          -- Cypher spelling: CREATE; creates per row
  SET <item> [, ...]  /  REMOVE <item> [, ...] -- change properties and labels per row
  [DETACH | NODETACH] DELETE <expr> [, ...]   -- removes per row; NODETACH is the default
  MERGE [<name> =] <pattern>                  -- Cypher; finds or creates one pattern per row
       { ON CREATE SET <item> [, ...] | ON MATCH SET <item> [, ...] }   -- any number, any order ]
RETURN [DISTINCT] <item> [AS <name>], ...     -- or RETURN *; items may aggregate
                                              -- (mandatory unless the last clause writes;
                                              -- FINISH ends a query without a result)
[ORDER BY <expr> [ASC | DESC], ...]
[OFFSET <n>]                                  -- Cypher alias: SKIP
[LIMIT <n>]
[ UNION [ALL | DISTINCT] <clauses> RETURN ... [ORDER BY ...] [OFFSET ..] [LIMIT ..] ]   -- any number
[ NEXT <the same again: clauses, RETURN, UNION ...> ]                                   -- any number
[;]

-- or a standalone call of a saved query, the whole query:
CALL <folder>.<name>[(<arg>, ...)] [YIELD * | YIELD <column> [AS <name>], ... [WHERE <condition>]]

A pattern is a path of node and edge patterns, optionally named (p = (a)-->(b)); an edge may carry a quantifier (-[:knows]->{1,3}), and so may a parenthesized part of the path (((x)-[:knows]->(y)){1,3}, a quantified path pattern). A query usually starts with MATCH, but it may start with any clause, or with RETURN alone (Queries without MATCH). Queries ending in RETURN combine with UNION and continue with NEXT (UNION and NEXT); NEXT binds looser than UNION. A CALL runs a whole query of that shape for each row (CALL subqueries), and CALL folder.name(..) a saved query of the graph's catalog (Calling saved queries). INSERT creates nodes and edges once per row, SET / REMOVE change them, DELETE removes them and Cypher's MERGE finds or creates them; a query whose last clause writes may end there and returns no rows (Writing with GQL).

Keywords are case-insensitive (match, Match, MATCH); variables, labels and property keys are case-sensitive. The words ISO GQL lists as non-reserved (FIRST, LAST, LABELED, SHORTEST) keep their meaning where the grammar expects them (NULLS FIRST, IS LABELED) and are names everywhere a variable can stand: WITH [1, 2] AS first RETURN first. Line breaks are whitespace, so a query may span lines. Comments are // ..., /* ... */ and the GQL -- ... (the -- rule).

g.gql("match (n:person) where n.age > 30 return n.name as name order by name desc").to_list()   // #{"name": "peter"}, #{"name": "josh"}

MATCH

MATCH takes one or more patterns separated by commas. A variable written twice is the same element: that is how patterns join. Several MATCH clauses in a row combine the same way.

g.gql("MATCH (a)-[:knows]->(b), (b)-[:created]->(s) RETURN a.name AS a, s.name AS s ORDER BY s").to_list()   // #{"a": "marko", "s": "lop"}, #{"a": "marko", "s": "ripple"}
g.gql("MATCH (a)-[:knows]->(b) MATCH (b)-[:created]->(s) RETURN b.name AS b, s.name AS s ORDER BY b, s").to_list()   // #{"b": "josh", "s": "lop"}, #{"b": "josh", "s": "ripple"}

Patterns that share no variable form a Cartesian product: every combination of their matches.

g.gql("MATCH (a:person), (s:software) WHERE a.age > 32 RETURN a.name AS a, s.name AS s ORDER BY a, s").to_list()   // #{"a": "peter", "s": "lop"}, #{"a": "peter", "s": "ripple"}

Node patterns

FormMatches
()any vertex, unnamed
(n)any vertex, bound to n
(n:person) or (n IS person)a vertex with the label person
(n:person {name: 'marko'})... whose name equals 'marko'
(n:person WHERE n.age > 30)... for which the condition is TRUE
g.gql("MATCH (p:person {name: 'marko'})-->(x) RETURN x.name AS x ORDER BY x").to_list()   // #{"x": "josh"}, #{"x": "lop"}, #{"x": "vadas"}
g.gql("MATCH (p:person WHERE p.age < 30) RETURN p.name AS name ORDER BY name").to_list()   // #{"name": "marko"}, #{"name": "vadas"}
g.v().has_label("person").has("age", P.lt(30)).values("name").order().to_list()   // "marko", "vadas"

An inline property map {k: v} is the same as WHERE n.k = v: a property that is missing or NULL never matches.

Edge patterns

FormAbbreviatedMatches
-[e:T]->-> (Cypher -->)an edge pointing right
<-[e:T]-<- (Cypher <--)an edge pointing left
-[e:T]-- (Cypher --)an edge in either direction
<-[e:T]-><-> (Cypher <-->)an edge in either direction (same as -[e]-)

The brackets take the same parts as a node: a variable, a label expression after : or IS, an inline property map and a WHERE condition. Graphersal edges are always directed, so "either direction" means "pointing left or right"; a self-loop matches once (Semantics).

g.gql("MATCH (a)-[e:created]->(s:software) WHERE e.weight >= 0.4 RETURN a.name AS who, s.name AS what, e.weight AS w ORDER BY w DESC, who").to_list()
// #{"w": 1.0, "what": "ripple", "who": "josh"}, #{"w": 0.4, "what": "lop", "who": "josh"}, #{"w": 0.4, "what": "lop", "who": "marko"}
g.gql("MATCH (s:software)<-[:created]-(p) RETURN s.name AS sw, p.name AS author ORDER BY sw, author").to_list()
// #{"author": "josh", "sw": "lop"}, #{"author": "marko", "sw": "lop"}, #{"author": "peter", "sw": "lop"}, #{"author": "josh", "sw": "ripple"}
g.gql("MATCH (a)-[:knows]-(b) RETURN a.name AS a, b.name AS b ORDER BY a, b").to_list()
// #{"a": "josh", "b": "marko"}, #{"a": "marko", "b": "josh"}, #{"a": "marko", "b": "vadas"}, #{"a": "vadas", "b": "marko"}
g.gql("MATCH (a {name: 'marko'})-(b) RETURN b.name AS b ORDER BY b").to_list()   // #{"b": "josh"}, #{"b": "lop"}, #{"b": "vadas"}
g.v().has("name", "marko").both().values("name").order().to_list()   // "josh", "lop", "vadas"

Patterns chain: (a)-[..]->(b)-[..]->(c) is a path of two hops, and the same variable may close a cycle.

g.gql("MATCH (a:person)-[:knows]->(b)-[:created]->(s) RETURN a.name AS a, b.name AS b, s.name AS s ORDER BY b, s").to_list()
// #{"a": "marko", "b": "josh", "s": "lop"}, #{"a": "marko", "b": "josh", "s": "ripple"}
g.v().has_label("person").as("a").out("knows").as("b").out("created").as("s").select("a", "b", "s").by("name").to_list()
// #{"a": "marko", "b": "josh", "s": "ripple"}, #{"a": "marko", "b": "josh", "s": "lop"}
g.gql("MATCH (a)-[:created]->(s)<-[:created]-(b) RETURN a.name AS a, b.name AS b, s.name AS s ORDER BY s, a, b").to_list()
// josh/marko, josh/peter, marko/josh, marko/peter, peter/josh, peter/marko, all on "lop"

The last query never pairs a person with themselves: both edges would be the same edge, and a MATCH binds every edge at most once (trail semantics).

Quantified edges

A quantifier after an edge pattern repeats the edge: (a)-[:knows]->{1,3}(b) matches a path of one to three knows edges from a to b, every node in between unnamed. It applies to full and abbreviated edges (->{2}) in every direction.

QuantifierRepeats the edgeCypher spelling (alias)
{m,n}m to n times[*m..n]
{n}exactly n times[*n]
{m,}at least m times[*m..]
{,n}0 to n times
*0 or more times, {0,}
+1 or more times, {1,}[*] (Cypher's lower bound is 1)
1 to n times, {1,n}[*..n]
never: no match[*m..n] with m > n, [*..0]

A GQL lower bound above the upper bound ({3,1}) is a syntax error; the Cypher spelling of the same interval ([*3..1]) is empty and matches nothing, as in Neo4j.

A lower bound of 0 includes the zero-length match, where b is a itself. The edges of one match are all different (trail), so an unbounded quantifier ends on every finite graph (Semantics). The Gremlin twin is a repeat() with emit() and times():

g.gql("MATCH (a {name: 'marko'})-[:knows|created]->{1,2}(b) RETURN b.name AS b ORDER BY b").to_list()
// josh, lop, lop, ripple, vadas
g.v().has("name", "marko").repeat(__.out("knows", "created")).emit().times(2).values("name").order().to_list()
// "josh", "lop", "lop", "ripple", "vadas"
g.gql("MATCH (a {name: 'marko'})->{2}(b) RETURN b.name AS b ORDER BY b").to_list()   // #{"b": "lop"}, #{"b": "ripple"}
g.v().has("name", "marko").repeat(__.out()).times(2).values("name").order().to_list()   // "lop", "ripple"
g.gql("MATCH (a {name: 'marko'})->{0,1}(b) RETURN b.name AS b ORDER BY b").to_list()   // josh, lop, marko, vadas
g.v().has("name", "marko").emit().repeat(__.out()).times(1).values("name").order().to_list()   // "josh", "lop", "marko", "vadas"
g.gql("MATCH (a {name: 'marko'})-[:knows]->{1,2}(b)-[:created]->(s) RETURN b.name AS b, s.name AS s ORDER BY b, s").to_list()
// #{"b": "josh", "s": "lop"}, #{"b": "josh", "s": "ripple"}

The variable of a quantified edge is a group variable: after the pattern it is the list of the edges of the match, in the written order ([] for a zero-length match). Inside its own brackets (-[e WHERE e.weight > 0.5]->{1,2}) it is the single edge of each repetition, so the condition tests every edge:

g.gql("MATCH (a {name: 'marko'})-[e]->*(b) RETURN b.name AS b, size(e) AS hops ORDER BY hops, b").to_list()
// marko 0, josh 1, lop 1, vadas 1, lop 2, ripple 2
g.gql("MATCH (a {name: 'marko'})-[e:knows|created WHERE e.weight > 0.5]->{1,2}(b) RETURN b.name AS b, e AS edges ORDER BY b").to_list()
// #{"b": "josh", "edges": [e[2][1-knows->4]]}, #{"b": "ripple", "edges": [e[2][1-knows->4], e[4][4-created->5]]}
g.v().has("name", "marko").repeat(__.out_e("knows", "created").has("weight", P.gt(0.5)).in_v()).emit().times(2).values("name").order().to_list()
// "josh", "ripple"

To repeat more than one edge, put the chain in parentheses and quantify it: a quantified path pattern.

Quantified path patterns

A parenthesized path pattern ( <chain> [WHERE <condition>] ) with a quantifier after its ) repeats the whole chain, its nodes, edges and conditions included: (a) ((x)-[:created]->(s)<-[:created]-(y)){1,2} (b) walks from a to b over one or two "created the same software" hops. It takes every quantifier of a quantified edge ({m,n}, {n}, {m,}, {,n}, *, +) and also ? (0 or 1 times); without a quantifier it matches exactly once.

  • The outer nodes merge with the body. The node written before the group is the first node of the first iteration, the node after it the last node of the last iteration, and consecutive iterations join end to start: (a) ((x)-->(y)){1,3} (b) binds a = the first x and b = the last y. Where the text has no node next to the group (at the start or end of the path, or between two groups), an anonymous one stands. After zero iterations ({0,n}, *, ?) the two outer nodes are the same node.
  • Body variables are group variables. With a quantifier other than ?, every variable inside the body is, after the pattern, the list of its nodes or edges, one per iteration in walk order, like the variable of a quantified edge. Read the list (size(x), [n IN x | n.name], RETURN x), not a property of it: x.name outside the body is an error. With ? or without a quantifier the body variables are single values; with ? they are NULL when the part matched nothing (Semantics).
  • The body condition runs in every iteration. The WHERE before the closing parenthesis, and the inline maps and WHEREs of the body's elements, test each iteration's elements, and read only the body's variables, parameters and values; test an outer variable in the WHERE of the MATCH clause.
  • Trail holds across iterations. No edge is bound twice in one match, across the iterations, the body's edges and the other edges of the clause.
g.gql("MATCH (a {name: 'marko'}) ((x)-[e:knows|created]->(y)){1,2} (b) RETURN b.name AS b, size(e) AS hops ORDER BY hops, b").to_list()
// josh 1, lop 1, vadas 1, lop 2, ripple 2
g.gql("MATCH (a {name: 'marko'}) ((x)-[:knows|created]->(y)){1,2} (b) RETURN [n IN x | n.name] AS xs, [n IN y | n.name] AS ys ORDER BY ys").to_list()
// #{"xs": ["marko"], "ys": ["josh"]}, #{"xs": ["marko", "josh"], "ys": ["josh", "lop"]}, #{"xs": ["marko", "josh"], "ys": ["josh", "ripple"]}, #{"xs": ["marko"], "ys": ["lop"]}, #{"xs": ["marko"], "ys": ["vadas"]}
g.gql("MATCH (a:person) ((x)-[:created]->(s)<-[:created]-(y)){1,2} (b) RETURN DISTINCT a.name AS a, b.name AS b ORDER BY a, b").to_list()
// josh/marko, josh/peter, marko/josh, marko/peter, peter/josh, peter/marko
g.gql("MATCH (a:person) ((x)-[:knows|created]-(y) WHERE y.age > x.age){1,3} (b) RETURN a.name AS a, b.name AS b, size(y) AS steps ORDER BY a, b").to_list()
// #{"a": "marko", "b": "josh", "steps": 1}, #{"a": "vadas", "b": "josh", "steps": 2}, #{"a": "vadas", "b": "marko", "steps": 1}
g.gql("MATCH (p:person {name: 'josh'}) ((x)-[:created]->(s) WHERE s.lang = 'java')? (q) RETURN s.name AS project, q.name AS last ORDER BY project").to_list()
// #{"last": "lop", "project": "lop"}, #{"last": "ripple", "project": "ripple"}, #{"last": "josh", "project": ()}
g.gql("MATCH ((x:person)-[:created]->(s) WHERE s.name = 'ripple') RETURN x.name AS who").to_list()   // #{"who": "josh"}

The Gremlin twin is a repeat() of the body's steps; the second-to-last query is a filter on the body run in every iteration:

g.v().has_label("person").as("a").repeat(__.out_e("created").in_v().in_e("created").out_v()).emit().times(2).simple_path().as("b").select("a", "b").by("name").dedup().to_list()
// the same six pairs (simple_path() stands in for trail here)

A quantified path pattern stands wherever a pattern does: in MATCH and OPTIONAL MATCH, in EXISTS { }, COUNT { } and COLLECT { }, in a pattern comprehension and in a Cypher pattern predicate (which names no new variable, so its body stays anonymous):

g.gql("MATCH (p:person) RETURN p.name AS p, [(p) ((x)-[:created]->(s)<-[:created]-(y)){1,2} (q) | q.name] AS co ORDER BY p").to_list()
// josh [peter, marko], marko [peter, josh], peter [josh, marko], vadas []
g.gql("MATCH (p:person) WHERE EXISTS { (p) ((x)-[:knows]->(y)){1,3} (q:person {name: 'josh'}) } RETURN p.name AS p").to_list()   // #{"p": "marko"}
g.gql("MATCH (p:person) WHERE (p) (()-[:knows]->()-[:created]->()){1} RETURN p.name AS p").to_list()   // #{"p": "marko"}

Not yet supported inside the body (each refused with GQLSTATUS 0A000 and a help line naming the rewrite): a nested parenthesized path pattern, a quantified edge, a path variable (p = goes on the whole path), a path mode or search prefix, several comma-separated patterns or a union (|), a body without an edge, a variable written twice in one body, a variable bound outside the body written again inside it, a condition reading an outer variable, and a subquery. A variable inside a quantified body must be a new name (42002).

g.gql("MATCH (a) (((x)-->(y)){2})+ (b) RETURN b")   // error: a parenthesized path pattern nested in another one is not yet supported
g.gql("MATCH (a) ((x)-->(y)-->(z)){1,3} (b) RETURN b.name AS b ORDER BY b").to_list()   // #{"b": "lop"}, #{"b": "ripple"}
g.gql("MATCH (a) ((x)-->(y))+ (b) RETURN x.name")   // error: `x` is a group variable of the quantified path pattern

Path variables

p = <path pattern> names the whole path. RETURN p returns it as a path value (the alternating vertices and edges, the same value as Gremlin's path(); Result Shape), and path_length(p) (Cypher length(p)) is its number of edges. A quantified edge or path pattern contributes all its edges and the vertices in between.

g.gql("MATCH p = (a {name: 'marko'})-[:knows]->(b)-[:created]->(s) RETURN p, path_length(p) AS len ORDER BY s.name").to_list()
// #{"len": 2, "p": [v[1], e[2][1-knows->4], v[4], e[3][4-created->3], v[3]]}, #{"len": 2, "p": [v[1], e[2][1-knows->4], v[4], e[4][4-created->5], v[5]]}
g.v().has("name", "marko").out_e("knows").in_v().out_e("created").in_v().path().to_list()
// [v[1], e[2][1-knows->4], v[4], e[4][4-created->5], v[5]], [v[1], e[2][1-knows->4], v[4], e[3][4-created->3], v[3]]
g.gql("MATCH p = (a {name: 'marko'})->{1,2}(b) RETURN b.name AS b, length(p) AS len ORDER BY len, b").to_list()
// josh 1, lop 1, vadas 1, lop 2, ripple 2

A path is a value: it compares (p = q), sorts, groups and goes into collect_list(). The Cypher functions nodes(p) and relationships(p) return its vertices and its edges as lists (Lists, elements and paths):

g.gql("MATCH p = (a {name: 'marko'})-[:knows]->(b) RETURN nodes(p) AS n, relationships(p) AS r ORDER BY b.name").to_list()
// #{"n": [v[1], v[4]], "r": [e[2][1-knows->4]]}, #{"n": [v[1], v[2]], "r": [e[0][1-knows->2]]}
g.v().has("name", "marko").out_e("knows").in_v().path().to_list()
// [v[1], e[2][1-knows->4], v[4]], [v[1], e[0][1-knows->2], v[2]]

Label expressions

After : or IS, on nodes and edges:

ExpressionMeans
Ahas the label A
A&Bhas both (Cypher :A:B)
A|Bhas at least one
!Adoes not have A
%has any label (the label set is not empty)
(...)grouping, as in A&(B|C)

A vertex tests its label set; an edge has exactly one label.

g.gql("MATCH (n:person|software) RETURN n.name AS name ORDER BY name LIMIT 3").to_list()   // #{"name": "josh"}, #{"name": "lop"}, #{"name": "marko"}
g.gql("MATCH (n:!person) RETURN n.name AS name ORDER BY name").to_list()   // #{"name": "lop"}, #{"name": "ripple"}
g.v().not(__.has_label("person")).values("name").order().to_list()   // "lop", "ripple"
g.gql("MATCH (n IS person&!software) RETURN n.name AS name ORDER BY name").to_list()   // josh, marko, peter, vadas

In expressions the same test is v IS [NOT] LABELED <label expression> (Cypher: v:A):

g.gql("MATCH (n) WHERE n IS LABELED software RETURN n.name AS name ORDER BY name").to_list()   // #{"name": "lop"}, #{"name": "ripple"}
g.gql("MATCH (n) WHERE n:software RETURN n.name AS name ORDER BY name").to_list()   // #{"name": "lop"}, #{"name": "ripple"}

WHERE

WHERE after a MATCH clause (or inside a node or edge pattern) keeps the rows for which the condition is TRUE; FALSE and NULL drop the row (three-valued logic). It may read every variable of its MATCH clause and of the clauses before it.

g.gql("MATCH (a:person), (b:person) WHERE a.age < b.age AND a.name STARTS WITH 'm' RETURN a.name AS a, b.name AS b ORDER BY b").to_list()
// #{"a": "marko", "b": "josh"}, #{"a": "marko", "b": "peter"}

EXISTS and pattern predicates

An EXISTS subquery tests whether a pattern matches: it is TRUE when its body has at least one match for the row and FALSE otherwise, never NULL. Three forms mean the same:

EXISTS { MATCH <pattern> [, <pattern> ...] [WHERE <condition>] [MATCH ...] }
EXISTS { <pattern> [, <pattern> ...] [WHERE <condition>] }
EXISTS ( ... )                                -- either body in parentheses
(a)-[:knows]->(b)                             -- Cypher pattern predicate: a pattern where a condition stands

The body reads the variables bound before it (they are imported: p inside is the row's p), and the variables it binds itself stay inside it. A pattern predicate is EXISTS { <pattern> } written without the keyword; it must not name a new variable (write EXISTS { MATCH .. } to name one), and it stands only where a condition does: a WHERE or FILTER condition (also under NOT, AND, OR, XOR), the WHERE of a comprehension and a WHEN of a searched CASE. Anywhere else (a RETURN column, a function argument, a LET value) it is a syntax error (42001), as in Neo4j: write EXISTS { .. }, COUNT { .. } or a pattern comprehension there. The Gremlin twins are where(__..) and not(__..), and the "who has no ..." question runs exactly as its twin:

g.gql("MATCH (p:person) WHERE NOT EXISTS { (p)-[:created]->() } RETURN p.name AS name ORDER BY name").to_list()   // #{"name": "vadas"}
g.gql("MATCH (p:person) WHERE NOT (p)-[:created]->() RETURN p.name AS name ORDER BY name").to_list()   // #{"name": "vadas"}
g.v().has_label("person").not(__.out("created")).values("name").to_list()   // "vadas"
g.gql("MATCH (p:person) WHERE EXISTS { MATCH (p)-[:created]->(s) WHERE s.name = 'ripple' } RETURN p.name AS name").to_list()   // #{"name": "josh"}
g.v().has_label("person").where(__.out("created").has("name", "ripple")).values("name").to_list()   // "josh"
g.gql("MATCH (a:person), (b:person) WHERE (a)-[:knows]->(b) RETURN a.name AS a, b.name AS b ORDER BY b").to_list()
// #{"a": "marko", "b": "josh"}, #{"a": "marko", "b": "vadas"}
g.gql("MATCH (p:person) WHERE EXISTS (MATCH (p)-[:knows]->(f) MATCH (f)-[:created]->(:software {name: 'ripple'})) RETURN p.name AS name").to_list()   // #{"name": "marko"}

EXISTS stands anywhere an expression does: in WHERE and FILTER, in the inline WHERE of a node or edge pattern, under OR, XOR and CASE, in a RETURN or WITH column, an ORDER BY key, a grouping key or an aggregate's argument, a FOR list. It composes with three-valued logic like any boolean (Semantics).

g.gql("MATCH (p:person) WHERE p.age > 30 OR (p)<-[:knows]-() RETURN p.name AS name ORDER BY name").to_list()   // josh, peter, vadas
g.gql("MATCH (p:person) RETURN p.name AS name, EXISTS { (p)-[:knows]->() } AS knows ORDER BY knows DESC, name").to_list()
// #{"knows": true, "name": "marko"}, #{"knows": false, "name": "josh"}, ... peter, vadas
g.gql("MATCH (p:person) RETURN EXISTS { (p)-[:created]->() } AS creator, count(*) AS n ORDER BY creator").to_list()
// #{"creator": false, "n": 1}, #{"creator": true, "n": 3}
g.gql("MATCH (p:person WHERE NOT (p)-[:created]->())-[:knows]-(f) RETURN p.name AS p, f.name AS f").to_list()   // #{"f": "marko", "p": "vadas"}

The body holds MATCH clauses with their WHERE (and nested subqueries), or a whole query: any clauses (OPTIONAL MATCH, WITH, LET, FILTER, FOR, CALL), UNION and NEXT, ending in RETURN. EXISTS is then TRUE when that query returns at least one row, and its RETURN items are still evaluated (a failing expression there fails the query). Whole-query bodies nest at most 16 levels, CALL bodies included. A query holds at most 64 subqueries, pattern comprehensions, COUNT { } and COLLECT { } included (Errors).

g.gql("MATCH (p:person) WHERE EXISTS { MATCH (p)-[:created]->(s) WITH count(s) AS c WHERE c > 1 RETURN c } RETURN p.name AS name").to_list()   // #{"name": "josh"}
g.gql("MATCH (p:person) WHERE EXISTS { MATCH (p)-[:created]->(s) RETURN s UNION MATCH (p)-[:knows]->(s) RETURN s } RETURN p.name AS name ORDER BY name").to_list()   // josh, marko, peter
g.gql("MATCH (p:person) WHERE (p)-[:knows]->(q) RETURN p.name AS name")   // error: the pattern predicate introduces the new variable `q`
g.gql("MATCH (p:person) RETURN p.name AS name, (p)-[:knows]->() AS k")   // error: a pattern alone is a condition only in WHERE (42001)
g.gql("MATCH (p:person) WHERE EXISTS { MATCH (p)-[:created]->(s) } RETURN s.name AS s")   // error: `s` is bound inside a subquery

COUNT and COLLECT

COUNT { } counts and COLLECT { } collects what a subquery finds for each row. They are not GQL: like the list predicates they are openCypher compatibility forms, accepted with their Neo4j Cypher 25 meaning (Cypher Aliases). Their bodies are those of EXISTS, and they stand anywhere an expression does:

COUNT { <pattern> [WHERE <condition>] }       -- the number of matches
COUNT { MATCH ... }                           -- the same
COUNT { <query ending in RETURN> }            -- the number of rows the query returns
COLLECT { <query ending in RETURN <one item>> }   -- the list of that item, one entry per row

COUNT { } is an integer, 0 when nothing matches, never NULL; COUNT { .. } > 0 keeps the rows EXISTS keeps. COLLECT { } is a list in the order the body returns its rows (its own ORDER BY decides it), [] when there are none, with NULL items kept. Each row runs the body once, like the Gremlin twins project(..).by(__.out("created").count()) and by(__.out("created").values("name").fold()):

g.gql("MATCH (p:person) RETURN p.name AS name, COUNT { (p)-[:created]->() } AS n ORDER BY name").to_list()   // josh 2, marko 1, peter 1, vadas 0
g.v().has_label("person").order().by("name").project("name", "n").by("name").by(__.out("created").count()).to_list()   // the same rows
g.gql("MATCH (p:person) RETURN p.name AS name, COLLECT { MATCH (p)-[:created]->(s) RETURN s.name ORDER BY s.name } AS sw ORDER BY name").to_list()
// josh [lop, ripple], marko [lop], peter [lop], vadas []
g.gql("MATCH (p:person {name: 'marko'}) RETURN COLLECT { MATCH (p)-[:knows]->(f) RETURN f.lang } AS l").to_list()   // #{"l": [(), ()]}: NULLs kept
g.gql("MATCH (p:person) WHERE COUNT { (p)-[:created]->() } > 1 RETURN p.name AS name").to_list()   // #{"name": "josh"}
g.gql("MATCH (p:person) RETURN p.name AS name, COUNT { MATCH (p)-[:created]->(s) RETURN s.lang AS l UNION MATCH (p)-[:knows]->(f) RETURN f.name AS l } AS n ORDER BY name").to_list()
// josh 1 (java once), marko 3, peter 1, vadas 0

COLLECT { } needs a body ending in a RETURN of exactly one item. When a COUNT { } body is one query whose final RETURN only projects (no aggregate, DISTINCT, ORDER BY or UNION), its rows are counted without evaluating the RETURN items, so an expression there that would fail raises no error (Semantics).

g.gql("MATCH (p:person) RETURN COLLECT { MATCH (p)-[:knows]->(f) RETURN f.name, f.age } AS l")   // error: COLLECT { } needs a body that ends in a RETURN of exactly one column
g.gql("MATCH (p:person) RETURN p.name AS name, COUNT { MATCH (p)-[:created]->(s) RETURN 1 / 0 AS x } AS n ORDER BY name").to_list()   // josh 2, marko 1, peter 1, vadas 0: 1 / 0 never runs

OPTIONAL MATCH

OPTIONAL MATCH keeps every row that reaches it: where its pattern (and its own WHERE) matches, the row is extended once per match; where it does not, the row continues once with the new variables set to NULL. Gremlin's twin is optional().

g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s) RETURN p.name AS name, s.name AS sw ORDER BY name, sw").to_list()
// #{"name": "josh", "sw": "lop"}, #{"name": "josh", "sw": "ripple"}, #{"name": "marko", "sw": "lop"}, #{"name": "peter", "sw": "lop"}, #{"name": "vadas", "sw": ()}
g.v().has_label("person").as("p").optional(__.out("created").as("s")).project("name", "sw").by(__.select("p").values("name")).by(__.coalesce(__.select("s").values("name"), __.constant("-"))).order().by("name").to_list()
// the same five rows, vadas with "-"

The WHERE of an OPTIONAL MATCH belongs to it: a row whose optional part fails the condition keeps its NULLs instead of being dropped. A leading OPTIONAL MATCH starts from one empty row, so a pattern without a match gives one row of NULLs:

g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s) WHERE s.lang = 'none' RETURN p.name AS name, s AS s ORDER BY name").to_list()
// josh, marko, peter, vadas, each with s ()
g.gql("OPTIONAL MATCH (n:robot) RETURN n").to_list()   // #{"n": ()}

NULL columns then work as everywhere: count(s) skips them, so this counts each person's software, 0 for vadas (Aggregation).

LET and FILTER

LET name = expr names a value computed from the variables in scope; FILTER condition (FILTER WHERE condition too) keeps the rows for which it is TRUE, like a WHERE that may stand anywhere between the clauses. Neither changes the rows otherwise: MATCH ... LET ... FILTER ... runs exactly like the same query with the value written out in WHERE and RETURN, including the conditions that become has() (Plans and Performance).

g.gql("MATCH (p:person) LET decade = p.age / 10 * 10 FILTER decade = 30 RETURN p.name AS name, decade ORDER BY name").to_list()
// #{"decade": 30, "name": "josh"}, #{"decade": 30, "name": "peter"}
g.v().has_label("person").has("age", P.between(30, 40)).project("name", "decade").by("name").by(__.constant(30)).order().by("name").to_list()
// the same rows

A LET name may not be bound again, and a LET item may not read a name defined in the same LET (write a second LET).

WITH

WITH (Cypher; GQL's linear statements express the same) ends one part of the query and passes only its items on: the next clauses see only the names WITH lists (WITH * keeps all; with nothing in scope it passes the rows on, as in MATCH () CREATE () WITH * CREATE ()). An item that is not a plain variable needs AS. WITH may take DISTINCT, an aggregate, ORDER BY, OFFSET / SKIP, LIMIT and a WHERE, in this order; the WHERE filters after LIMIT (Cypher's order of the sub-clauses). The WHERE reads the items and also the variables the WITH drops (WITH c WHERE r IS NULL), except after an aggregation; after DISTINCT it filters the rows before they are folded (with DISTINCT and ORDER BY / OFFSET / LIMIT too, such a WHERE is not yet supported).

g.gql("MATCH (p:person) WITH p.name AS name, p.age AS age WHERE age < 30 RETURN name ORDER BY name").to_list()   // #{"name": "marko"}, #{"name": "vadas"}
g.gql("MATCH (p:person) WITH p ORDER BY p.age DESC LIMIT 2 MATCH (p)-[:created]->(s) RETURN p.name AS name, s.name AS sw ORDER BY name, sw").to_list()
// #{"name": "josh", "sw": "lop"}, #{"name": "josh", "sw": "ripple"}, #{"name": "peter", "sw": "lop"}
g.gql("MATCH (p:person) WITH p ORDER BY p.age LIMIT 3 WHERE p.age > 28 RETURN p.name AS name ORDER BY name").to_list()
// #{"name": "josh"}, #{"name": "marko"}: the three youngest, then the filter
g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[e:created]->() WITH p.name AS name WHERE e IS NULL RETURN name").to_list()   // #{"name": "vadas"}
g.gql("MATCH (p:person) WITH p.name AS name RETURN p.age")   // error: the variable `p` is not in scope: the WITH before does not carry it
g.gql("MATCH (p:person) WITH p ORDER BY p.age LIMIT 2 WITH collect(p) AS ps WITH ps[0] AS youngest MATCH (youngest)<-[:knows]-(f) RETURN f.name AS name").to_list()   // #{"name": "marko"}
g.gql("MATCH (p:person) WITH collect(p.age) AS ages WITH ages[0] AS x MATCH (x)-->(y) RETURN y")   // error: `x` is written as a node of the pattern but holds a value that is not a node

A WITH that only renames and computes values is as transparent as LET. One with DISTINCT, an aggregate, ORDER BY, OFFSET or LIMIT builds its rows first; a later MATCH continues from the elements in its columns. A LET or WITH value computed from elements (coalesce(b, c), l[0], head(collect(e))) may stand for a node or an edge of a later pattern, also as an endpoint of INSERT / CREATE: NULL matches nothing, a value of another kind is a data error (22G03) when a row reaches the pattern (a value written as an edge is compared with the edges the pattern walks, so one of another kind matches nothing). A value written as a literal, an operator or a property access is never an element and is refused before the run. The order a WITH ... ORDER BY makes is not kept by later clauses: sort again in the final RETURN (Ordering).

FOR and UNWIND

FOR x IN list gives one row per item of the list, with the item bound to x; Cypher's UNWIND list AS x is the same clause (Cypher Aliases). The list is any expression over the row before the FOR: a literal, a $parameter, a property, a collect_list() column of a WITH, nodes(p). Duplicates and NULL items give rows like any other item; a list inside the list stays one item. WITH ORDINALITY i also binds the item's position from 1, WITH OFFSET i from 0 (only after FOR). Gremlin's twin is unfold().

g.gql("FOR x IN [1, 2, 2] RETURN x ORDER BY x").to_list()   // #{"x": 1}, #{"x": 2}, #{"x": 2}
g.inject([1, 2, 2]).unfold().order().to_list()   // 1, 2, 2
g.gql("UNWIND [1, 2, 2] AS x RETURN x ORDER BY x").to_list()   // the same rows
g.gql("FOR x IN [10, 20] WITH ORDINALITY i RETURN x, i ORDER BY i").to_list()   // #{"i": 1, "x": 10}, #{"i": 2, "x": 20}
g.gql("FOR x IN [10, 20] WITH OFFSET i RETURN x, i ORDER BY i").to_list()   // #{"i": 0, "x": 10}, #{"i": 1, "x": 20}
g.gql("FOR x IN [1, 2] FOR y IN [x, x * 10] RETURN x, y ORDER BY x, y").to_list()   // 1 1, 1 10, 2 2, 2 20

The most frequent use is "for each value in a list, find its vertex": an item compared in a property map or a WHERE equality. When an index or the element id serves that equality, each item is a direct lookup instead of a scan (Plans and Performance). A name without a vertex gives no row:

g.gql("FOR n IN $names WITH ORDINALITY i MATCH (p:person {name: n}) RETURN i, n, p.age AS age ORDER BY i", #{names: ["vadas", "marko", "nobody"]}).to_list()
// #{"age": 27, "i": 1, "n": "vadas"}, #{"age": 29, "i": 2, "n": "marko"}
g.gql("FOR id IN $ids MATCH (n) WHERE element_id(n) = id RETURN id, n.name AS name ORDER BY id", #{ids: ["1", "3", "42"]}).to_list()
// #{"id": "1", "name": "marko"}, #{"id": "3", "name": "lop"}

An item that is a vertex continues a pattern by its name, like a vertex column of a WITH (an item of another kind gives no row there):

g.gql("MATCH (p:person) WITH collect_list(p) AS ps FOR p IN ps MATCH (p)-[:created]->(s) RETURN p.name AS name, s.name AS sw ORDER BY name, sw").to_list()
// josh lop, josh ripple, marko lop, peter lop
g.gql("MATCH p = (a {name: 'marko'})-[:knows]->(b) FOR n IN nodes(p) MATCH (n)-[:created]->(s) RETURN DISTINCT n.name AS who, s.name AS sw ORDER BY who, sw").to_list()
// josh lop, josh ripple, marko lop

A NULL list gives no row and a value that is not a list gives one row of that value (Semantics). The item and the position are new names: a name already in scope, or the same name for both, is an error.

Queries without MATCH

A query may start with FOR, UNWIND, LET, WITH, FILTER or RETURN. It then starts from one empty row (Gremlin's inject(0)): RETURN alone returns one row, FILTER keeps or drops it, FOR turns it into one row per item, and a later MATCH runs once for each row.

g.gql("RETURN 1 + 2 AS three, upper('gql') AS up").to_list()   // #{"three": 3, "up": "GQL"}
g.gql("RETURN count(*) AS c").to_list()   // #{"c": 1}: the one empty row
g.gql("WITH 2 AS n RETURN n * n AS sq").to_list()   // #{"sq": 4}
g.gql("FILTER $on RETURN 1 AS x", #{on: false}).to_list()   // no row
g.gql("LET k = 30 MATCH (p:person) FILTER p.age > k RETURN p.name AS name ORDER BY name").to_list()   // #{"name": "josh"}, #{"name": "peter"}

RETURN

RETURN is mandatory in a query that only reads (a query whose last clause writes may end there, and FINISH ends any query without a result; Writing with GQL). It builds one map per row: RETURN expr AS name, ..., RETURN * (every named variable) and RETURN DISTINCT (duplicate rows removed, with GQL's equality: 1 and 1.0 are one value, Semantics). Result Shape covers names and column order.

g.gql("MATCH (a)-[:created]->(s) RETURN s.name AS s ORDER BY s").to_list()   // lop, lop, lop, ripple
g.gql("MATCH (a)-[:created]->(s) RETURN DISTINCT s.name AS s ORDER BY s").to_list()   // #{"s": "lop"}, #{"s": "ripple"}
g.v().out("created").values("name").dedup().order().to_list()   // "lop", "ripple"

Aggregation

RETURN and WITH items may aggregate. The items without an aggregate are the grouping keys: one row per distinct combination of their values (grouping is implicit, as in Cypher). Without keys the whole input is one group. ISO GQL's GROUP BY may follow the RETURN items: it must list exactly the items without an aggregate (by column name, or by repeating the item's expression), changes nothing in the result, and GROUP BY () is the single group of an all-aggregate RETURN; without any aggregate it gives one row per group, like DISTINCT. After WITH (Cypher) GROUP BY is an error that explains implicit grouping.

AggregateReturnsOn no input
count(*)the number of rows0
count(x)the number of rows where x is not NULL0
sum(x)the sum of the numbers; integers stay integers0
avg(x)the mean, always a floatNULL
min(x), max(x)the smallest / largest value in the order of ORDER BYNULL
collect_list(x) (Cypher collect(x))the values as a list[]
percentile_disc(x, p) (Cypher percentileDisc)the value at percentile p (0.0 to 1.0) of the sorted numbers, with its typeNULL
percentile_cont(x, p) (Cypher percentileCont)the percentile p interpolated linearly between the two nearest numbers, always a floatNULL

The percentiles take numbers (another kind is error 22G03) and a percentile p from 0.0 to 1.0 (outside it: error 22003), evaluated and checked on every row; the group uses the value of its first row, so write a constant or a $parameter. percentile_disc returns the value at position ceil(p * n) - 1 of the n sorted numbers (the first for p = 0), percentile_cont interpolates at position p * (n - 1) (Neo4j's definitions):

g.gql("MATCH (p:person) RETURN percentile_disc(p.age, 0.5) AS d, percentile_cont(p.age, 0.5) AS c, percentileCont(p.age, 1) AS top").to_list()   // #{"c": 30.5, "d": 29, "top": 35.0}
g.gql("MATCH (p:person) RETURN percentile_cont(p.age, 1.5) AS c")   // error: percentile_cont() takes a percentile from 0.0 to 1.0, not 1.5 (22003)

NULL values are skipped by every aggregate except count(*). DISTINCT inside the call (count(DISTINCT x)) aggregates each distinct value once. An aggregate may be part of an expression (count(*) + 1); outside its aggregates such an item reads only grouping keys, constants and parameters. It may repeat a key written as a variable or a property (p.age + count(*) beside the key p.age), not a computed key (a.age + b.age): compute that one in a WITH first, as in WITH *, a.age + b.age AS k RETURN k, k + count(*). The details are on Semantics.

g.gql("MATCH (p:person) RETURN count(*) AS n, sum(p.age) AS total, avg(p.age) AS mean, min(p.age) AS lo, max(p.age) AS hi").to_list()
// #{"hi": 35, "lo": 27, "mean": 30.75, "n": 4, "total": 123}
g.v().has_label("person").values("age").fold().project("n", "total", "mean", "lo", "hi").by(__.count(Scope.local)).by(__.sum(Scope.local)).by(__.mean(Scope.local)).by(__.min(Scope.local)).by(__.max(Scope.local)).to_list()
// the same values
g.gql("MATCH (s:software)<-[:created]-(p) RETURN s.name AS sw, count(p) AS authors ORDER BY sw").to_list()
// #{"authors": 3, "sw": "lop"}, #{"authors": 1, "sw": "ripple"}
g.v().has_label("software").group().by("name").by(__.in("created").count()).to_list()   // #{"lop": 3, "ripple": 1}
g.gql("MATCH (p:person)-[:created]->(s) RETURN p.name AS name, collect_list(s.name) AS sw ORDER BY name").to_list()
// #{"name": "josh", "sw": ["ripple", "lop"]}, #{"name": "marko", "sw": ["lop"]}, #{"name": "peter", "sw": ["lop"]}
g.gql("MATCH (n) RETURN count(n.age) AS ages, count(*) AS all, count(DISTINCT n.lang) AS langs").to_list()
// #{"ages": 4, "all": 6, "langs": 1}

With OPTIONAL MATCH, count() of an optional variable gives 0 where nothing matched; Gremlin counts per vertex with group() or project():

g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s) RETURN p.name AS name, count(s) AS n ORDER BY name").to_list()
// josh 2, marko 1, peter 1, vadas 0
g.v().has_label("person").project("name", "n").by("name").by(__.out("created").count()).order().by("name").to_list()
// the same rows

An aggregating WITH passes the groups on, and its WHERE filters them (SQL's HAVING):

g.gql("MATCH (p:person)-[:created]->(s) WITH p, count(s) AS n WHERE n > 1 RETURN p.name AS name, n").to_list()   // #{"n": 2, "name": "josh"}
g.gql("MATCH (p:person)-[:created]->(s) RETURN p.name AS name, count(s) AS n GROUP BY name").to_list()   // the same rows as without GROUP BY
g.gql("MATCH (p:person) WITH p.name AS n, count(*) AS c GROUP BY n RETURN n, c")   // error: GROUP BY is not needed: grouping is implicit
g.gql("MATCH (p:person) WHERE count(p) > 1 RETURN p")   // error: an aggregate cannot be used in WHERE
g.gql("MATCH (p:person) RETURN sum(p.name) AS s")   // error: sum() takes numbers, not a string (22G03)

After an aggregation ORDER BY reads the returned columns only: by their names, or written again inside an expression, an aggregate call or a property access as an item has it (ORDER BY count(s) + 1, ORDER BY p.name + 'x' when p.name is a key). An expression written like another item next to an aggregate stays refused, as in Neo4j. The groups come out in an unspecified order: write ORDER BY.

g.gql("MATCH (p:person)-[:created]->(s) RETURN p.name AS name, count(s) AS n ORDER BY 10 - count(s), p.name").to_list()   // #{"n": 2, "name": "josh"}, #{"n": 1, "name": "marko"}, #{"n": 1, "name": "peter"}
g.gql("MATCH (p:person)-[:created]->(s) RETURN count(s) AS n ORDER BY p.age + count(s)")   // error: after an aggregation, ORDER BY can only use the returned columns

ORDER BY, OFFSET, LIMIT

ORDER BY takes expressions (a column name, a property, a function call) with ASC / ASCENDING (the default) or DESC / DESCENDING; it may read variables that are not returned (except after RETURN DISTINCT). OFFSET n (Cypher SKIP n) skips rows, LIMIT n keeps at most n. They come in this order, each at most once; n is a non-negative integer literal, a parameter, or a constant expression: one without variables, aggregates or subqueries, evaluated once before the run (LIMIT 1 + 1, SKIP toInteger(ceil(1.7)); a negative result is an error 22G02, a non-integer one 22G03). An expression with a parameter in it (LIMIT $n + 1) is refused: pass the computed value as the parameter.

g.gql("MATCH (n:person) RETURN n.name AS name ORDER BY n.age DESC").to_list()   // peter, josh, marko, vadas
g.gql("MATCH (n:person) RETURN n.name AS name ORDER BY name OFFSET 1 LIMIT 2").to_list()   // #{"name": "marko"}, #{"name": "peter"}
g.v().has_label("person").values("name").order().range(1, 3).to_list()   // "marko", "peter"
g.gql("MATCH (n:person) RETURN n.name AS name ORDER BY name OFFSET 2 - 1 LIMIT toInteger(ceil(1.7))").to_list()   // #{"name": "marko"}, #{"name": "peter"}
g.gql("MATCH (n:person) RETURN n.name AS name LIMIT n.age").to_list()   // error: LIMIT ... not an expression that reads the row (22G03)

Without ORDER BY the row order is unspecified; Semantics gives the order of NULL and of values of different types.

UNION and NEXT

UNION combines the rows of queries that each end in RETURN. Every operand returns the same column names, in any order; the result has the column order of the first operand. UNION (also written UNION DISTINCT) removes duplicate rows with GQL's equality (1 and 1.0 are one value), UNION ALL keeps them; one chain uses one kind. Each operand is a query of its own: its own variables, and its own ORDER BY, OFFSET and LIMIT, which apply to that operand only. Gremlin's twin is union(), followed by dedup() for UNION:

g.gql("MATCH (p:person) WHERE p.age > 30 RETURN p.name AS name UNION MATCH (s:software) RETURN s.name AS name").to_list()   // josh, peter, lop, ripple (in any order)
g.union(__.V().has("person", "age", P.gt(30)), __.V().has_label("software")).values("name").to_list()   // "josh", "peter", "lop", "ripple"
g.gql("MATCH (p:person) RETURN p.name AS name UNION ALL MATCH (p:person)-[:created]->() RETURN p.name AS name").count().next()   // 8: duplicates kept
g.gql("RETURN 1 AS a, 2 AS b UNION RETURN 2 AS b, 1 AS a").to_list()   // #{"a": 1, "b": 2}: one row, the first operand's order
g.gql("MATCH (p:person) RETURN p.name AS name ORDER BY p.age DESC LIMIT 1 UNION ALL MATCH (s:software) RETURN s.name AS name ORDER BY name LIMIT 1").to_list()   // peter, lop: per operand
g.gql("RETURN 1 AS x UNION RETURN 2 AS y")   // error: the operands of UNION must return the same column names
g.gql("RETURN 1 AS x UNION RETURN 2 AS x UNION ALL RETURN 3 AS x")   // error: UNION ALL is mixed with UNION in one query

NEXT continues after a RETURN: the rows that RETURN builds are the input of the next statement, which sees only its columns, by name (RETURN * passes every variable on). It may start with any clause: NEXT RETURN, NEXT FILTER, NEXT MATCH continuing from an element column. NEXT binds looser than UNION, so a NEXT after a union sorts, filters, pages or aggregates the whole union, which no operand's ORDER BY can:

g.gql("MATCH (p:person) RETURN p.name AS name UNION MATCH (s:software) RETURN s.name AS name NEXT RETURN name ORDER BY name LIMIT 3").to_list()   // josh, lop, marko
g.gql("MATCH (p:person) RETURN p.name AS name, p.age AS age NEXT FILTER age > 30 RETURN name ORDER BY name").to_list()   // #{"name": "josh"}, #{"name": "peter"}
g.gql("MATCH (p:person) RETURN p NEXT MATCH (p)-[:created]->(s) RETURN p.name AS who, s.name AS sw ORDER BY who, sw").to_list()   // josh lop, josh ripple, marko lop, peter lop
g.gql("MATCH (p:person) RETURN p.name AS name, p.age AS age NEXT RETURN count(*) AS n, avg(age) AS mean").to_list()   // #{"mean": 30.75, "n": 4}
g.gql("MATCH (p:person) RETURN p.name AS name NEXT RETURN p.age")   // error: the variable `p` is not in scope: the RETURN before NEXT does not return it

A NEXT after a plain query is the Cypher WITH of the same items: q1 RETURN a, b NEXT q2 gives the rows of q1 WITH a, b q2 (Cypher Aliases). NEXT YIELD is not supported yet.

CALL subqueries

CALL { } runs a whole query (any clauses, UNION, NEXT, ending in RETURN) once for each incoming row, and joins the row with each row the body returns: the columns of the body's RETURN become new variables of the query. Three things make it more than a MATCH:

  • the body's aggregates, DISTINCT, ORDER BY and LIMIT apply to each row's records: a count per row, the top k per group;
  • a row whose body returns no row is dropped, OPTIONAL CALL keeps it with the new variables NULL (an aggregating body returns one row anyway: count is 0 there);
  • a UNION or NEXT inside the body works per row too.
CALL (a, b) { <query> }       -- imports a and b (GQL and Cypher 25)
CALL (*) { <query> }          -- imports every variable in scope
CALL () { <query> }           -- imports nothing
CALL { <query> }              -- imports nothing, unless it starts with WITH a, b (Cypher's importing WITH)
OPTIONAL CALL ...             -- keeps a row without results, with NULL columns
g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[e:created]->(s) RETURN s.name AS top ORDER BY e.weight DESC LIMIT 1 } RETURN p.name AS who, top ORDER BY who").to_list()
// #{"top": "ripple", "who": "josh"}, #{"top": "lop", "who": "marko"}, #{"top": "lop", "who": "peter"}: vadas has no row
g.v().has_label("person").as("p").flat_map(__.out_e("created").order().by("weight", Order.desc).limit(1).in_v()).project("who", "top").by(__.select("p").values("name")).by("name").to_list()   // the same three rows
g.gql("MATCH (p:person) OPTIONAL CALL (p) { MATCH (p)-[:created]->(s) RETURN s.name AS sw ORDER BY sw LIMIT 1 } RETURN p.name AS who, sw ORDER BY who").to_list()
// josh lop, marko lop, peter lop, vadas ()
g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[:knows]->(f) RETURN count(f) AS friends } RETURN p.name AS who, friends ORDER BY who").to_list()   // josh 0, marko 2, peter 0, vadas 0
g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[:knows]->(f) RETURN f.name AS other UNION MATCH (p)-[:created]->(s) RETURN s.name AS other } RETURN p.name AS who, other ORDER BY who, other").to_list()
// josh lop, josh ripple, marko josh, marko lop, marko vadas, peter lop
g.gql("MATCH (p:person) CALL { WITH p MATCH (p)-[:created]->(s) RETURN s.name AS sw } RETURN p.name AS who, sw ORDER BY who, sw").to_list()   // Cypher's importing WITH: josh lop, josh ripple, marko lop, peter lop

The body reads only the variables it imports: in CALL { MATCH (p)-->(s) .. } without a scope clause, p is a new variable of the body, not the outer one. A body that imports nothing still runs once per row (Semantics). The returned names must be new, and a body without RETURN (a unit subquery) must end in a write (Inside CALL): a body that only reads must return something; IN TRANSACTIONS is refused. A later clause continues from a returned element as from a WITH column:

g.gql("CALL { MATCH (s:software) RETURN s } MATCH (s)<-[:created]-(p) RETURN s.name AS sw, count(p) AS n ORDER BY sw").to_list()   // lop 3, ripple 1
g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[:knows]->(f) RETURN f AS p } RETURN p")   // error: the CALL body returns `p`, which is already defined outside it
g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[:created]->(s) } RETURN p")   // error: a CALL { } body without RETURN only makes sense for writes

Calling saved queries

CALL folder.name(args) is GQL's named procedure call: it runs the saved query name of the catalog folder folder (the segments before the name joined by /; one segment, CALL name(), calls a query of the root folder) for each incoming row, like a CALL { } body that imports nothing. Only saved queries written in GQL can be called.

CALL f.name(a, b) YIELD x, y AS z [WHERE <condition>]   -- inside a query: YIELD names the columns read after it
CALL f.name(a, b)                -- inside a query, a VOID saved query (no RETURN): each row kept once
MATCH .. CALL f.name(a, b)       -- a VOID call may end the query, like a write: zero rows
CALL f.name() YIELD n MATCH (n)-->(m) ..   -- a yielded node (or edge) starts a later pattern
OPTIONAL CALL f.name(a) YIELD x  -- keeps a row without results, with x NULL
CALL f.name(a, b)                -- the whole query: every column of the saved query
CALL f.name(a, b) YIELD *        -- the same
CALL f.name                      -- the whole query, arguments from the query's parameters by name
  • The arguments are constants or $parameters (and lists, maps and arithmetic of them), positional in the order the saved query first reads its parameters; trailing ones left out take their defaults, and each is checked against the parameter's schema before the run. An argument that reads the row is not supported yet.
  • YIELD names columns of the saved query's RETURN; each yielded name is a new variable (AS renames one, also swapping two names), and WHERE after the items filters the rows. Inside a query, a call of a saved query with columns needs YIELD; YIELD * and the form without parentheses are for a standalone call only.
  • The saved query runs as a query of its own: it sees none of the caller's variables, and its variables none of the caller's. Its writes are part of the calling query's one unit.
  • A call stands wherever a clause stands, also inside CALL { } bodies and UNION operands; inside EXISTS { }, COUNT { } and COLLECT { } it is not supported yet. The vendor namespaces db, dbms, apoc and gds are refused.
g.define_query(#{
    name: "older",
    folder: "people",
    language: "gql",
    params: #{min: #{schema: #{type: "integer"}, default: 30}},
    body: "MATCH (p:person) WHERE p.age > $min RETURN p.name AS name, p.age AS age"
});
g.gql("MATCH (s:software) CALL people.older(33) YIELD name RETURN s.name AS sw, name ORDER BY sw").to_list();
// [#{"name": "peter", "sw": "lop"}, #{"name": "peter", "sw": "ripple"}]
g.gql("MATCH (s:software) OPTIONAL CALL people.older(40) YIELD name RETURN s.name AS sw, name ORDER BY sw").to_list();
// [#{"name": (), "sw": "lop"}, #{"name": (), "sw": "ripple"}]
g.gql("CALL people.older(26) YIELD name RETURN name UNION CALL people.older(33) YIELD name RETURN name").to_list();
// marko, vadas, josh, peter
g.gql("CALL people.older").to_list();   // [#{"age": 32, "name": "josh"}, #{"age": 35, "name": "peter"}]: min takes its default 30

.profile() shows a call as gql:call_query("people/older", ..) with the saved query's plan as its child. Saved Queries has the parameters, VOID queries, effects and permissions; Errors every error of a call.

INSERT

INSERT <pattern>, ... (Cypher CREATE) creates the pattern's new nodes and edges once for each row that reaches it; a variable bound before connects an existing node. Edges need a direction and one label, node labels are a conjunction (:A&B, Cypher :A:B). The full rules are on Writing with GQL.

g.gql("MATCH (p:person {name: 'marko'}) INSERT (p)-[:likes]->(f:fruit {name: 'apple'}) RETURN f.name AS fruit").to_list()   // #{"fruit": "apple"}
g.gql("FOR n IN ['ann', 'bob'] CREATE (:person {name: n})").to_list()   // no rows

SET and REMOVE

SET <item>, ... changes the elements of each row that reaches it, items left to right: a property (SET n.k = expr), all properties (SET n = {..}; Cypher's merge SET n += {..}) or labels of a node (SET n:A, SET n IS A). REMOVE <item>, ... removes a property (REMOVE n.k) or labels (REMOVE n:A). A NULL value removes the property, a NULL target is skipped. The full rules are on Writing with GQL.

g.gql("MATCH (p:person {name: 'marko'}) SET p.age = p.age + 1, p:admin RETURN p.age AS age, labels(p) AS labels").to_list()   // #{"age": 30, "labels": ["person", "admin"]}
g.gql("MATCH (p:person {name: 'marko'}) REMOVE p.age RETURN keys(p) AS keys").to_list()   // #{"keys": ["name"]}

DELETE

[DETACH | NODETACH] DELETE <expr>, ... removes the nodes, edges, paths and lists of them its expressions give, for each row. DETACH DELETE removes a node with its edges; a plain DELETE (the default, also written NODETACH DELETE) fails the query (G1001) for a node that still has edges the same clause does not delete. A NULL target is skipped; reading or returning a deleted element later in the query is an error. The full rules are on Writing with GQL.

g.gql("MATCH (p:person {name: 'vadas'}) WITH p, p.name AS name DETACH DELETE p RETURN name").to_list()   // #{"name": "vadas"}
g.gql("MATCH (a {name: 'marko'})-[e:knows]->() DELETE e RETURN count(e) AS deleted").to_list()   // #{"deleted": 2}

MERGE

MERGE [p =] <pattern> [ON CREATE SET <items>] [ON MATCH SET <items>] (Cypher, a compatibility form) looks for its one pattern on each row: every match is a row, and when nothing matches, the whole pattern is created, reusing the nodes bound before. Each row sees what the rows before it created. ON CREATE SET and ON MATCH SET hold SET items for the created or the found elements. A NULL property value in the pattern fails the query (22004). The full rules are on Writing with GQL.

g.gql("FOR n IN ['ann', 'ann'] MERGE (p:person {name: n}) ON CREATE SET p.new = true RETURN count(DISTINCT p) AS people").to_list()   // #{"people": 1}
g.gql("MATCH (a:person {name: 'marko'}), (b:person {name: 'josh'}) MERGE (a)-[e:knows]->(b) RETURN e.weight AS weight").to_list()   // #{"weight": 1.0}: found

Expressions

KindForms
literalsintegers (42, 1_000, 0x1F, 0o17, 0b101), floats (1.5, .5, 1.5e3), strings ('...' or "..."), TRUE, FALSE, NULL, lists [1, 2], maps (records) {k: v}, also written RECORD {k: v}
parameters$name (Parameters)
property accessn.name, m.key on a map
indexing and slicingx[0], x[-1], x[1..3], x[..2], x[1..], m['key'], n[k] (Cypher, below)
comparison=, <> (Cypher !=), <, <=, >, >=; a chain a < b <= c is the Cypher compatibility form of a < b AND b <= c (alias)
logicAND, OR, XOR, NOT
predicatesIS [NOT] NULL, IN [list], STARTS WITH, ENDS WITH, CONTAINS, =~ (Cypher regular-expression match of the whole string, compatibility form), IS [NOT] LABELED, IS [NOT] SOURCE OF e, IS [NOT] DESTINATION OF e
arithmetic+, -, *, /, %, ^ (Cypher power, always a float: 2 ^ 10 is 1024.0), unary - and +
concatenation|| on two strings or two lists (Cypher +); Cypher + of a list and one other value appends or prepends it ([1] + 2 is [1, 2], 0 + [1] is [0, 1])
conditionalsimple CASE x WHEN v THEN r ... ELSE d END and searched CASE WHEN cond THEN r ... END
conversionCAST(x AS INTEGER | FLOAT | STRING | BOOLEAN) (Conversions)
function callsname(args) (Functions)
map projectionp {.name, .*, f, key: expr} (Cypher, below)
list comprehension[x IN list WHERE cond | expr], either part optional (Cypher)
pattern comprehension[(p)-[:knows]->(f) WHERE cond | expr] (Cypher)

Precedence, loosest first: OR, XOR, AND, NOT, comparison, the predicates (IS NULL, IN, STARTS WITH, ...), + - ||, * / %, ^ (left to right: 2 ^ 3 ^ 2 is 64.0), unary minus (-3 ^ 2 is 9.0), property access and subscripts (x[i], x[a..b], left to right: [1, 2][0] + 1 is 2). x ^ y follows the rules of power(x, y): 0 ^ -1 and (-8) ^ 0.5 are errors (2201F), an overflow is error 22003.

g.gql("MATCH (n:person) WHERE n.age IN [27, 35] RETURN n.name AS name ORDER BY name").to_list()   // #{"name": "peter"}, #{"name": "vadas"}
g.gql("MATCH (n:person) WHERE n.name STARTS WITH 'm' OR n.name ENDS WITH 's' OR n.name CONTAINS 'et' RETURN n.name AS name ORDER BY name").to_list()   // marko, peter, vadas
g.gql("MATCH (n:person) WHERE n.name =~ '[jv].*' RETURN n.name AS name ORDER BY name").to_list()   // josh, vadas
g.gql("MATCH (n:person) WHERE n.age > 30 XOR n.name = 'josh' RETURN n.name AS name ORDER BY name").to_list()   // #{"name": "peter"}
g.gql("MATCH (n:person) RETURN n.name || '!' AS a, n.age * 2 + 1 AS b, n.age / 10 AS c, n.age % 10 AS d, n.age / 10.0 AS e ORDER BY a LIMIT 1").to_list()
// #{"a": "josh!", "b": 65, "c": 3, "d": 2, "e": 3.2}
g.gql("MATCH (n:person) RETURN n.name AS name, CASE WHEN n.age < 30 THEN 'young' WHEN n.age < 34 THEN 'middle' ELSE 'senior' END AS band ORDER BY name").to_list()
// josh middle, marko young, peter senior, vadas young
g.gql("MATCH (n) RETURN n.name AS name, CASE n.lang WHEN 'java' THEN 'jvm' ELSE 'other' END AS k ORDER BY name LIMIT 2").to_list()
// #{"k": "other", "name": "josh"}, #{"k": "jvm", "name": "lop"}
g.gql("MATCH (n:person) RETURN {name: n.name, tags: [n.age, NULL, true]} AS m ORDER BY n.name LIMIT 1").to_list()
// #{"m": #{"name": "josh", "tags": [32, (), true]}}
g.gql("MATCH (n:person) RETURN RECORD {name: n.name, age: n.age} AS m ORDER BY n.name LIMIT 1").to_list()
// #{"m": #{"age": 32, "name": "josh"}}

RECORD {k: v} is the ISO record constructor with its keyword written out; it builds the same map as {k: v}. The word is contextual, not reserved: RECORD (any case) followed by { and then } or name: is the constructor; anywhere else record is an ordinary variable, also before a map projection such as record {.name}. A variable named record whose projection is empty or starts with a key: expr item is back-quoted: `record` {k: 1}.

Integer arithmetic stays integer (/ truncates toward zero, % takes the sign of the dividend); a float operand makes the result a float. An overflow or an integer division by zero is an error, never a wrapped value (Errors); a float divided by zero follows IEEE 754 (1.0 / 0.0 is Infinity, 0.0 / 0.0 is NaN; Semantics).

g.gql("RETURN [1, 2] + 3 AS a, 0 + [1] AS b, [1] + [2] AS c").to_list()   // #{"a": [1, 2, 3], "b": [0, 1], "c": [1, 2]}

Indexing and slicing

x[i] reads the item i of a list, counted from 0; a negative index counts from the end (x[-1] is the last item), and an index out of range gives NULL. x[a..b] is the sub-list from a up to b (excluded); either bound may be left out (x[..2], x[1..]), a negative one counts from the end, bounds beyond the list are clamped, and a >= b gives []. On a map m[k] reads the entry of the string key k, and on a node or an edge n[k] reads the property k; a missing key gives NULL. n['name'] with a string literal is the property access n.name (the same plan, so a property index serves it); a computed key (n[$key], n['na' || 'me']) is read per row. A NULL list, map, index or bound gives NULL. These are Cypher forms with their Neo4j meaning, measured against the openCypher TCK (Semantics).

g.gql("RETURN [10, 20, 30][0] AS a, [10, 20, 30][-1] AS b, [10, 20, 30][5] AS c, [10, 20, 30][1..] AS d, [10, 20, 30][..-1] AS e").to_list()
// #{"a": 10, "b": 30, "c": (), "d": [20, 30], "e": [10, 20]}
g.gql("MATCH (p:person) WITH p ORDER BY p.age RETURN collect(p.name)[0] AS youngest, collect(p.name)[-2..] AS oldest").to_list()
// #{"oldest": ["josh", "peter"], "youngest": "vadas"}
g.gql("MATCH (p:person {name: 'marko'}) RETURN p['na' || 'me'] AS name, {lang: 'java'}['lang'] AS lang").to_list()
// #{"lang": "java", "name": "marko"}
g.gql("MATCH (p:person {name: 'josh'}) RETURN p[$key] AS v", #{key: "age"}).to_list()   // #{"v": 32}
g.gql("RETURN 'abc'[0] AS c")   // error: cannot index a string

The index of a list is an integer (x[1.0] and x['1'] are errors, GQLSTATUS 22G03; convert with toInteger(i)), the key of a map or an element a string; a text is no list (use substring(s, start, length)). These errors arise when a row reaches the expression, as for every other operand of the wrong kind (Errors).

Map projections and comprehensions

Three Cypher forms build maps and lists inside an expression. They are not GQL; gql() accepts them with their Neo4j meaning because Cypher users and LLMs write them all the time (Cypher Aliases). Together they give a JSON-shaped answer: one row per entity, its related data nested inside.

v {.key, .*, x, key: expr}                    -- map projection of a vertex, an edge or a map
[x IN list]  [x IN list WHERE cond]  [x IN list | expr]  [x IN list WHERE cond | expr]
[(a)-[:R]->(b) WHERE cond | expr]             -- pattern comprehension, also [p = (a)-->(b) | p]

Map projection. v {...} builds a map from the variable v: .key is its property (NULL when missing, the key kept), .* every stored property (no id, no labels), x the entry x: x, and key: expr any value, all in the written order. Its Gremlin twins are project() and value_map().by(unfold()); the GQL form is the record constructor {name: p.name}, which differs only for a NULL variable (Semantics):

g.gql("MATCH (p:person) RETURN p {.name, .age, decade: p.age / 10} AS m ORDER BY p.name LIMIT 2").to_list()
// #{"m": #{"age": 32, "decade": 3, "name": "josh"}}, #{"m": #{"age": 29, "decade": 2, "name": "marko"}}
g.gql("MATCH (p:person {name: 'marko'}) RETURN p {.*} AS m").to_list()   // #{"m": #{"age": 29, "name": "marko"}}
g.v().has("name", "marko").value_map().by(__.unfold()).to_list()   // #{"age": 29, "name": "marko"}
g.gql("MATCH (p:person {name: 'marko'})-[e:knows]->(f) RETURN e {.*, to: f.name} AS k ORDER BY k.to").to_list()
// #{"k": #{"to": "josh", "weight": 1.0}}, #{"k": #{"to": "vadas", "weight": 0.5}}

List comprehension. [x IN list WHERE cond | expr] walks the list in its order, keeps the items for which cond is TRUE and maps each kept item to expr; leave out WHERE to keep every item, | expr to keep the item itself. x is a new name that exists only inside the brackets. The Gremlin twin is local(__.unfold().is(..).fold()):

g.gql("RETURN [x IN range(1, 5) WHERE x % 2 = 1] AS odd, [x IN range(1, 3) | x * x] AS sq, [x IN [1, 2] | [y IN [10, 20] | x * y]] AS grid").to_list()
// #{"grid": [[10, 20], [20, 40]], "odd": [1, 3, 5], "sq": [1, 4, 9]}
g.inject([1, 2, 3, 4, 5]).local(__.unfold().is(P.gt(2)).fold()).to_list()   // [3, 4, 5]
g.gql("MATCH p = (a {name: 'marko'})-[:knows|created]->{2}(b) RETURN [x IN nodes(p) | x.name] AS names ORDER BY b.name").to_list()
// #{"names": ["marko", "josh", "lop"]}, #{"names": ["marko", "josh", "ripple"]}
g.gql("MATCH (p:person) RETURN p.name AS name, [x IN [p.age, p.age + 10] WHERE x > 30] AS l ORDER BY name LIMIT 2").to_list()
// #{"l": [32, 42], "name": "josh"}, #{"l": [39], "name": "marko"}

A | inside the list or the WHERE part ends that part, so a label alternative there needs parentheses: [x IN l WHERE x:(A|B) | x.name].

Pattern comprehension. [(a)-[:R]->(b) WHERE cond | expr] is the list of expr for every match of the pattern on the row: [] when nothing matches, never NULL. The pattern has at least one edge; it reads the variables bound before it (they are imported, like in EXISTS), and the names it binds itself (b here, or a path variable p = ...) exist only inside the brackets. It is a subquery: the Gremlin twin is project(..).by(__.out("knows").values("name").fold()), and the items come in no defined order.

g.gql("MATCH (p:person {name: 'marko'}) RETURN [(p)-[:knows]->(f) | f.name] AS friends").to_list()   // #{"friends": ["josh", "vadas"]}, in any order
g.v().has("name", "marko").project("friends").by(__.out("knows").values("name").fold()).to_list()   // #{"friends": ["josh", "vadas"]}
g.gql("MATCH (s:software {name: 'ripple'}) RETURN [(s)<-[:created]-(p) WHERE p.age > 30 | p.name] AS older").to_list()   // #{"older": ["josh"]}
g.gql("MATCH (p:person) WHERE size([(p)-[:created]->(s) | s]) >= 2 RETURN p.name AS name").to_list()   // #{"name": "josh"}
g.gql("MATCH (p:person {name: 'marko'}) RETURN [q = (p)-[:knows]->() | path_length(q)] AS l").to_list()   // #{"l": [1, 1]}

Together, one row per person with its friends and projects nested inside, the shape a JSON API or an LLM wants (Result Shape):

g.gql("MATCH (p:person) RETURN p {.name, friends: [(p)-[:knows]->(f) | f.name], projects: [(p)-[:created]->(s) | s {.name, .lang}]} AS person ORDER BY person.name").to_json()
// [{"person": {"name": "josh", "friends": [], "projects": [{"name": "ripple", "lang": "java"}, ...]}}, ...]

All three stand anywhere an expression does (WHERE, RETURN, WITH, LET, FILTER, FOR, ORDER BY, an aggregate's argument) and nest in each other. Their rules:

  • A comprehension variable must be a new name: one that is in scope, or that the query uses anywhere else, is an error (Semantics).
  • No aggregate inside the WHERE or | part (aggregate in a WITH first, or aggregate the list: size([..])).
  • A list-comprehension variable cannot be read inside an EXISTS or a pattern comprehension in its WHERE or | part yet (Not supported yet).
  • A pattern comprehension counts as a subquery: a query holds at most 64 subqueries (Errors).
  • The list predicates all(), any(), none(), single() and reduce() follow the same rules for their variables (below).
g.gql("MATCH (p:person) RETURN [p IN [1, 2] | p * 2] AS l")   // error: the comprehension variable `p` shadows the variable `p` in scope
g.gql("MATCH (p:person) RETURN [(p)-[:knows]->(f) | count(f)] AS l")   // error: count() cannot be used inside the | part of a pattern comprehension
g.gql("MATCH (p:person) RETURN p.name AS n, [(p)-[:knows]->(f) | f.name] AS l ORDER BY f.name")   // error: `f` is bound inside a pattern comprehension
g.gql("RETURN size([x IN [1, 2, 3] WHERE x > 0]) = size([1, 2, 3]) AS all_positive").to_list()   // #{"all_positive": true}

List predicates and reduce

Cypher's all(x IN l WHERE c), any(..), none(..), single(..) and reduce(acc = init, x IN l | expr) are openCypher compatibility forms (Cypher Aliases has their NULL rules). The predicates are three-valued: a NULL list or, when no item decides the answer, a NULL condition gives NULL. A list comprehension counted with size() gives the same answer when no condition is NULL; over a pattern comprehension they are the Gremlin where(__..) / not(__..) of a pattern. reduce folds a list per row, where FOR and an aggregate fold the rows of a query.

g.gql("RETURN all(x IN [1, 2, 3] WHERE x > 0) AS a, any(x IN [1, NULL] WHERE x > 1) AS b, single(x IN [1, 2] WHERE x > 1) AS c").to_list()   // #{"a": true, "b": (), "c": true}
g.gql("RETURN size([x IN [1, 2, 3] WHERE x > 0]) = size([1, 2, 3]) AS a").to_list()   // #{"a": true}, the count form of all()
g.gql("MATCH (p:person) WHERE all(w IN [(p)-[:created]->(s) | s] WHERE w.lang = 'java') AND any(a IN [(p)-[:knows]->(f) | f.age] WHERE a > 30) RETURN p.name AS name").to_list()   // #{"name": "marko"}
g.V().hasLabel("person").not(__.out("created").has("lang", P.neq("java"))).where(__.out("knows").has("age", P.gt(30))).values("name").to_list()   // "marko"
g.gql("MATCH (p:person) RETURN p.name AS name, reduce(s = 0, a IN [(p)-[:knows]->(f) | f.age] | s + a) AS ages ORDER BY name").to_list()   // josh 0, marko 59, peter 0, vadas 0
g.gql("FOR x IN [1, 2, 3] RETURN sum(x) AS s").to_list()   // #{"s": 6}, one fold over the rows
g.gql("RETURN reduce(s = 0, x IN [1, 2, 3] | s + x) AS s").to_list()   // #{"s": 6}, one fold per row
g.gql("MATCH (p:person) RETURN all(p IN [1] WHERE p > 0) AS a")   // error: the variable `p` of all() shadows the variable `p` in scope
g.gql("MATCH (p:person) RETURN any(x IN [1] WHERE x > count(*)) AS a")   // error: count() cannot be used inside the WHERE part of all(), any(), none() or single()

Functions

Function names are case-insensitive (toInteger, TOINTEGER). Every function returns NULL for a NULL argument (except coalesce, nullif and the ...OrNull conversions, by their definition) and fails for an argument of the wrong kind (22G03), never with a silent NULL. A position or a length counts characters (Unicode scalar values), never bytes. The aggregates are listed under Aggregation; Semantics has the exact rules and where they differ from Neo4j and from the Gremlin steps of the same name.

The functions come from two sources: the GQL functions (with their Cypher spellings as aliases), and a fixed list of openCypher compatibility functions that GQL has no counterpart for (toInteger, substring, split, round, keys, nodes, ...): they keep their Neo4j meaning (Cypher Aliases).

FunctionReturnsCypher alias
element_id(x)the id of a vertex or edge, a stringelementId(x)
labels(x)a vertex's labels in stored order (primary first); an edge's label as a one-item list
type(e)an edge's label; a vertex is an error (use labels(v))
coalesce(a, b, ...)the first argument that is not NULL
nullif(a, b)NULL when a = b is TRUE, else asame (nullIf)
path_length(p)the number of edges of a pathlength(p)
g.gql("MATCH (n) RETURN element_id(n) AS id, labels(n) AS labels ORDER BY id LIMIT 3").to_list()
// #{"id": "1", "labels": ["person"]}, #{"id": "2", "labels": ["person"]}, #{"id": "3", "labels": ["software"]}
g.gql("MATCH ()-[e]->() RETURN element_id(e) AS id, type(e) AS type, e.weight AS w ORDER BY id LIMIT 2").to_list()
// #{"id": "0", "type": "knows", "w": 0.5}, #{"id": "1", "type": "created", "w": 0.4}
g.gql("MATCH (n) RETURN n.name AS name, coalesce(n.age, n.lang) AS info ORDER BY name LIMIT 2").to_list()
// #{"info": 32, "name": "josh"}, #{"info": "java", "name": "lop"}
g.gql("MATCH (n:person) RETURN n.name AS name, nullif(n.age, 29) AS age ORDER BY name").to_list()
// #{"age": 32, "name": "josh"}, #{"age": (), "name": "marko"}, #{"age": 35, "name": "peter"}, #{"age": 27, "name": "vadas"}

Conversions

GQL's CAST is strict: text that is not a value of the target type is an error (22018). The Cypher conversions are lenient: toInteger, toFloat, toBoolean give NULL for such text, and their ...OrNull forms give NULL for a value of any unsupported kind too (Semantics).

FunctionConvertsUnconvertible textWrong kind
CAST(x AS INTEGER) (INT, INT64, BIGINT, SIGNED INTEGER)integer; float truncated toward zero; a decimal text ('42', ' 1.9 ', '1e3')error 22018error 22G03 (a boolean too)
CAST(x AS FLOAT) (FLOAT64, DOUBLE, DOUBLE PRECISION, REAL)number; a decimal text, 'NaN', 'Infinity', '-Infinity'error 22018error 22G03
CAST(x AS STRING) (VARCHAR, CHAR VARYING)any value except a vertex, edge or path-error 22G03
CAST(x AS BOOLEAN) (BOOL)boolean; 'true' / 'false' in any case, 'unknown' is NULLerror 22018error 22G03 (numbers too)
toInteger(x)as CAST, also true / false (1 / 0) and Cypher literals ('0x1F', '0o17', '1_000')NULLerror 22G03
toFloat(x)as CAST, also Cypher literalsNULLerror 22G03
toBoolean(x)as CAST, also integers (0 is FALSE, any other TRUE)NULLerror 22G03
toString(x)as CAST(x AS STRING), scalars only; a temporal value in Neo4j's text (Dates and times)-error 22G03 (a list or a map too)
toIntegerOrNull(x), toFloatOrNull(x), toBooleanOrNull(x), toStringOrNull(x)as their toXNULLNULL (for toStringOrNull a list, map, vertex, edge or path too)

A float's text always shows that it is a float (toString(1.0) is '1.0', Neo4j's form), while Gremlin's as_string() gives "1"; integers and booleans give the same text as as_string(). A list or a map converts to Neo4j's text form ('[29, marko, 1.0, null]', '{a: 1, b: marko}').

g.gql("MATCH (n:person) RETURN n.name AS name, toString(n.age) AS a, toString(n.age / 10.0) AS b ORDER BY name").to_list()
// #{"a": "32", "b": "3.2", "name": "josh"}, #{"a": "29", "b": "2.9", "name": "marko"}, #{"a": "35", "b": "3.5", "name": "peter"}, #{"a": "27", "b": "2.7", "name": "vadas"}
g.v().has_label("person").values("age").as_string().order().to_list()   // "27", "29", "32", "35"
g.gql("MATCH (n:person) RETURN toFloat(n.age) AS f ORDER BY f").to_list()   // #{"f": 27.0}, #{"f": 29.0}, #{"f": 32.0}, #{"f": 35.0}
g.v().has_label("person").values("age").as_number(GType.DOUBLE).order().to_list()   // 27.0, 29.0, 32.0, 35.0
g.gql("MATCH (n:person {name: 'marko'}) RETURN CAST('42' AS INTEGER) AS i, CAST(' 1.5 ' AS FLOAT) AS f, CAST('TRUE' AS BOOLEAN) AS b, CAST(1.0 AS STRING) AS s").to_list()
// #{"b": true, "f": 1.5, "i": 42, "s": "1.0"}
g.gql("MATCH (n:person {name: 'marko'}) RETURN toInteger(' 42 ') AS a, toInteger('1.9') AS b, toInteger('0x1F') AS c, toInteger('abc') AS d, toIntegerOrNull(true) AS e").to_list()
// #{"a": 42, "b": 1, "c": 31, "d": (), "e": 1}
g.gql("MATCH (n:person {name: 'marko'}) RETURN toBoolean(1) AS a, toBooleanOrNull(1.5) AS b, toFloat('1e3') AS c, toFloatOrNull([1]) AS d").to_list()
// #{"a": true, "b": (), "c": 1000.0, "d": ()}
g.gql("MATCH (n:person {name: 'marko'}) RETURN CAST([n.age, n.name, 1.0, NULL] AS STRING) AS l, CAST({a: 1, b: n.name} AS STRING) AS m").to_list()
// #{"l": "[29, marko, 1.0, null]", "m": "{a: 1, b: marko}"}
g.gql("MATCH (n:person {name: 'marko'}) RETURN toString([n.age])")   // error: toString() takes a number, a boolean, a string or another scalar, not a list (22G03)
g.gql("MATCH (n:person {name: 'marko'}) RETURN toStringOrNull([n.age]) AS s").to_list()   // #{"s": ()}
g.gql("MATCH (n:person) RETURN n.name || ' is ' || toString(n.age) AS s ORDER BY s LIMIT 2").to_list()
// #{"s": "josh is 32"}, #{"s": "marko is 29"}
g.gql("MATCH (n:person {name: 'marko'}) RETURN CAST('abc' AS INTEGER) AS x")   // error: invalid character value for cast (22018)
g.gql("MATCH (n:person {name: 'marko'}) RETURN toFloat(true) AS x")   // error: toFloat() takes a number or a string, not a boolean (22G03)
g.gql("MATCH (n:person {name: 'marko'}) RETURN toString(n) AS x")   // error: toString() takes no vertex, edge or path (22G03)

CAST to a GQL type Graphersal has no values of yet (DATE, LIST<..>, DECIMAL, ...) is not supported yet; an unknown type name is a syntax error with a suggestion:

g.gql("MATCH (n) RETURN CAST(n.age AS DATE) AS d")   // error: CAST to DATE is not yet supported
g.gql("MATCH (n) RETURN CAST(n.age AS INTEGR) AS d")   // error: unknown type INTEGR in CAST, did you mean INTEGER

Strings

FunctionReturnsCypher spelling
upper(s), lower(s)the string in upper / lower casetoUpper(s), toLower(s)
char_length(s), character_length(s)the number of characterssize(s)
byte_length(s), octet_length(s)the number of UTF-8 bytes
left(s, n), right(s, n)the first / last n characters (the whole string when n is larger)same
substring(s, start [, length])Cypher: length characters from the 0-based start (to the end without length); past the end ''compatibility function
TRIM([[LEADING | TRAILING | BOTH] [c] FROM] s), trim(s)s without the character c (default: the space) at both ends, the start or the end; c is exactly one charactertrim(s)
btrim(s [, chars]), ltrim(s [, chars]), rtrim(s [, chars])s without any character of the set chars (default: the space) at both ends / the start / the endsame
replace(s, search, replacement [, limit])every occurrence of search replaced, left to right; at most limit of themcompatibility function
split(s, delimiter)the list of the parts between the delimiters (a string or a list of strings); empty parts are keptcompatibility function
reverse(x)a string with its characters reversed, or a list with its items reversedcompatibility function
isEmpty(x)whether a string, list or map has no character / item / entrycompatibility function

A negative position or length is an error (22011), and a TRIM character that is not exactly one character is too (22027). The SQL form SUBSTRING(s FROM a FOR b) is not GQL; it fails with a hint to substring(s, start, length).

g.gql("MATCH (n:person) RETURN left(n.name, 2) AS l, right(n.name, 2) AS r, substring(n.name, 1, 3) AS s, substring(n.name, 2) AS t ORDER BY l").to_list()
// #{"l": "jo", "r": "sh", "s": "osh", "t": "sh"}, #{"l": "ma", "r": "ko", "s": "ark", "t": "rko"}, ... peter, vadas
g.v().has_label("person").values("name").substring(1, 4).order().to_list()   // "ada", "ark", "ete", "osh"
g.gql("MATCH (n:person) RETURN n.name AS name, replace(n.name, 'a', '4') AS r, split(n.name, 'a') AS s ORDER BY name").to_list()
// #{"name": "josh", "r": "josh", "s": ["josh"]}, #{"name": "marko", "r": "m4rko", "s": ["m", "rko"]}, ... #{"name": "vadas", "r": "v4d4s", "s": ["v", "d", "s"]}
g.v().has_label("person").values("name").replace("a", "4").order().to_list()   // "josh", "m4rko", "peter", "v4d4s"
g.gql("MATCH (n:person {name: 'marko'}) RETURN reverse(n.name) AS r, reverse([1, 2, 3]) AS l, byte_length('héllo') AS b, char_length('héllo') AS c, isEmpty('') AS e").to_list()
// #{"b": 6, "c": 5, "e": true, "l": [3, 2, 1], "r": "okram"}
g.v().has("name", "marko").values("name").reverse().to_list()   // "okram"
g.gql("MATCH (n:person {name: 'marko'}) RETURN trim('  a  ') AS a, TRIM(LEADING 'x' FROM 'xxaxx') AS b, TRIM(TRAILING FROM '  a  ') AS c, btrim('xyaxy', 'xy') AS d, ltrim('  a  ') AS e, rtrim('..a..', '.') AS f").to_list()
// #{"a": "a", "b": "axx", "c": "  a", "d": "a", "e": "a  ", "f": "..a"}
g.gql("MATCH (n:person {name: 'marko'}) RETURN split('a,,b,', ',') AS a, split('a-b;c', ['-', ';']) AS b, split('abc', '') AS c, replace('abc', '', '.') AS d, replace('aaa', 'a', 'b', 2) AS e").to_list()
// #{"a": ["a", "", "b", ""], "b": ["a", "b", "c"], "c": ["a", "b", "c"], "d": ".a.b.c.", "e": "bba"}
g.gql("MATCH (n:person {name: 'marko'}) RETURN substring(n.name, -1) AS x")   // error: substring() takes a start of 0 or more (22011)
g.gql("MATCH (n:person {name: 'marko'}) RETURN TRIM(BOTH 'ab' FROM 'abxab') AS x")   // error: TRIM(.. FROM ..) removes exactly one character (22027)
g.gql("MATCH (n) RETURN SUBSTRING(n.name FROM 1 FOR 2) AS r")   // error: SUBSTRING(s FROM a FOR b) is SQL, not GQL

Numbers

FunctionReturnsCypher spelling
abs(x)the absolute value, of the argument's typesame
floor(x), ceil(x) / ceiling(x)rounded down / up; an integer stays the integersame
round(x [, precision [, mode]])rounded, always a float; mode one of 'UP', 'DOWN', 'CEILING', 'FLOOR', 'HALF_UP' (the default), 'HALF_DOWN', 'HALF_EVEN'compatibility function
sign(x)-1, 0 or 1, an integercompatibility function
sqrt(x), exp(x)the square root, e to the power x; a floatsame
ln(x), log10(x)the natural / decimal logarithm; a floatlog(x), log10(x)
log(base, x)the logarithm to base; a float
power(x, y)x to the power y; a float(Cypher's ^ is not supported yet)
mod(a, b)the remainder, exactly as a % ba % b

None of them makes NaN or an infinity from finite numbers: the square root of a negative number and power() of 0 to a negative power are errors (2201F), the logarithm of a number <= 0 is an error (2201E), an overflow is 22003. round() with one argument rounds a half toward positive infinity (round(-2.5) is -2.0, Java's and Neo4j's rule); with a precision it rounds the decimal text of the number (round(2.675, 2) is 2.68).

g.gql("MATCH (n:person) RETURN n.name AS name, sqrt(n.age) AS s ORDER BY name LIMIT 2").to_list()
// #{"name": "josh", "s": 5.656854249492381}, #{"name": "marko", "s": 5.385164807134504}
g.v().has_label("person").order().by("name").limit(2).values("age").math("sqrt(_)").to_list()   // 5.656854249492381, 5.385164807134504
g.gql("MATCH (n:person {name: 'marko'}) RETURN abs(-3) AS a, abs(-2.5) AS b, floor(2.7) AS c, ceil(2.1) AS d, ceiling(3) AS e, sign(-0.5) AS f, mod(7, 3) AS g").to_list()
// #{"a": 3, "b": 2.5, "c": 2.0, "d": 3.0, "e": 3, "f": -1, "g": 1}
g.gql("MATCH (n:person {name: 'marko'}) RETURN round(2.5) AS a, round(-2.5) AS b, round(2.675, 2) AS c, round(-1.55, 1) AS d, round(2.5, 0, 'HALF_EVEN') AS e, round(3) AS f").to_list()
// #{"a": 3.0, "b": -2.0, "c": 2.68, "d": -1.6, "e": 2.0, "f": 3.0}
g.gql("MATCH (n:person {name: 'marko'}) RETURN exp(1) AS a, ln(1) AS b, log(100) AS c, log10(1000) AS d, log(2, 8) AS e, power(2, 10) AS f").to_list()
// #{"a": 2.718281828459045, "b": 0.0, "c": 4.605170185988092, "d": 3.0, "e": 3.0, "f": 1024.0}
g.inject(100).math("log(_)").to_list()   // 4.605170185988092
g.gql("MATCH (n:person) RETURN round(avg(n.age), 1) AS mean").to_list()   // #{"mean": 30.8}
g.gql("MATCH (n:person {name: 'marko'}) RETURN ln(0) AS x")   // error: ln() of a number <= 0 (2201E)
g.gql("MATCH (n:person {name: 'marko'}) RETURN sqrt(-1) AS x")   // error: sqrt() of a negative number (2201F)
g.gql("MATCH (n:person {name: 'marko'}) RETURN round(1234.5, -2) AS x")   // error: round() needs a precision >= 0 (22023)

Lists, elements and paths

FunctionReturnsCypher spelling
size(list), cardinality(list)the number of items (size(e) of a group variable counts its edges)size(list)
head(list), last(list)the first / last item; NULL for []compatibility function
tail(list)all items but the firstcompatibility function
trim(list, n)the list without its last n items
range(start, end [, step])the integers from start to end inclusive, by step (default 1)compatibility function
keys(x)the property keys of a vertex or edge (a stored null is no key), or the keys of a mapcompatibility function
properties(x)the properties of a vertex or edge as a map; a map itselfcompatibility function
startNode(e), endNode(e)the stored source / target vertex of the edgecompatibility function
n IS [NOT] SOURCE OF e, n IS [NOT] DESTINATION OF ewhether n is the edge's source / target (a predicate)
nodes(p), relationships(p)the vertices / the edges of a path, in the path's ordercompatibility function

startNode(e) is the edge's stored source, whatever direction the pattern was written in: in (a)-[e]-(b) the variable a may be either end. range() checks its size before it builds the list, so range(0, 9223372036854775807) is a limit error, never an out-of-memory (Errors).

g.gql("MATCH (n:person {name: 'marko'}) RETURN head([1, 2, 3]) AS h, last([1, 2, 3]) AS l, tail([1, 2, 3]) AS t, trim([1, 2, 3], 1) AS tr, range(1, 5) AS r, range(10, 0, -5) AS d, head([]) AS e").to_list()
// #{"d": [10, 5, 0], "e": (), "h": 1, "l": 3, "r": [1, 2, 3, 4, 5], "t": [2, 3], "tr": [1, 2]}
g.gql("MATCH (p:person)-[:created]->(s) WITH p, s ORDER BY s.name RETURN p.name AS name, head(collect(s.name)) AS first ORDER BY name").to_list()
// #{"first": "lop", "name": "josh"}, #{"first": "lop", "name": "marko"}, #{"first": "lop", "name": "peter"}
g.gql("MATCH (n:person {name: 'marko'}) RETURN keys(n) AS k, properties(n) AS p").to_list()   // #{"k": ["name", "age"], "p": #{"age": 29, "name": "marko"}}
g.v().has("name", "marko").properties().key().fold().to_list()   // ["name", "age"]
g.v().has("name", "marko").value_map().by(__.unfold()).to_list()   // #{"age": 29, "name": "marko"}
g.gql("MATCH (a)-[e:knows]-(b) RETURN a.name AS a, b.name AS b, startNode(e).name AS s, endNode(e).name AS t ORDER BY a, b").to_list()
// josh marko: s marko, t josh; marko josh: marko, josh; marko vadas: marko, vadas; vadas marko: marko, vadas
g.e().has_label("knows").project("s", "t").by(__.out_v().values("name")).by(__.in_v().values("name")).to_list()
// #{"s": "marko", "t": "vadas"}, #{"s": "marko", "t": "josh"}
g.gql("MATCH (a)-[e:knows]-(b) RETURN a.name AS a, b.name AS b, a IS SOURCE OF e AS src ORDER BY a, b").to_list()
// josh marko false, marko josh true, marko vadas true, vadas marko false
g.gql("MATCH p = (a {name: 'marko'})-[:knows|created]->{1,2}(b) RETURN b.name AS b, size(nodes(p)) AS n, size(relationships(p)) AS r, last(nodes(p)) = b AS same ORDER BY n, b").to_list()
// josh 2 1 true, lop 2 1 true, vadas 2 1 true, lop 3 2 true, ripple 3 2 true
g.gql("MATCH (n:person {name: 'marko'}) RETURN range(0, 9223372036854775807) AS r")   // error: Resource limit 'traversal.max_materialized_bytes' exceeded

A list comprehension maps or filters the items of a list ([x IN nodes(p) | x.name]); FOR walks a list as rows and collect_list() collects them again:

g.gql("MATCH p = (a {name: 'marko'})-[:knows]->(b) RETURN b.name AS b, [x IN nodes(p) | x.name] AS names ORDER BY b").to_list()
// #{"b": "josh", "names": ["marko", "josh"]}, #{"b": "vadas", "names": ["marko", "vadas"]}
g.gql("MATCH p = (a {name: 'marko'})-[:knows]->(b) FOR x IN nodes(p) RETURN b.name AS b, collect_list(x.name) AS names ORDER BY b").to_list()
// #{"b": "josh", "names": ["marko", "josh"]}, #{"b": "vadas", "names": ["marko", "vadas"]}

Dates and times

The temporal values are the engine's six date and time types (date, time, offsettime, localdatetime, datetime, duration): a value gql() builds is the same value a Gremlin step or a stored property holds, and a stored date reads as a date (n.born.year). The functions are openCypher's (Neo4j Cypher 25) with Neo4j's meaning; the constructors also have their ISO GQL names. The places where an answer differs from Neo4j are on Semantics, and the Gremlin step that does the same as each function on Dates in GQL.

ISO GQLCypherGives (engine type)
date(x)date(x)a calendar day (date)
local_time(x)localtime(x)a time of day without an offset (time)
zoned_time(x)time(x)a time of day with its UTC offset (offsettime)
local_datetime(x)localdatetime(x)a date and a time of day without an offset (localdatetime)
zoned_datetime(x)datetime(x)an instant with its UTC offset, and its zone name when built with one (datetime)
duration(x)duration(x)months, days and a time part (duration)

x is ISO 8601 text, a map of fields, or (not for duration) another temporal value, which is projected onto the type (date(datetime(..)) is the date at the value's own offset, datetime(localdatetime(..)) the wall clock at UTC, time(localtime(..)) at UTC, time(datetime(..)) its time of day and offset). With no argument a constructor gives the time the query started (Clocks). A NULL argument, or a NULL field of the map, gives NULL. Values hold nanoseconds, as Neo4j's: up to nine fraction digits and the nanosecond field are kept exactly. A constant can also be written as an ISO GQL literal, DATE '2015-07-21' (Literals).

g.gql("RETURN date('2015-07-21') AS d, localtime('21:40:32.142') AS t, localdatetime('2015-07-21T21:40') AS ldt, datetime('2015-07-21T21:40+01:00') AS dt").to_list()
// #{"d": date("2015-07-21"), "dt": datetime("2015-07-21T21:40:00+01:00"), "ldt": localdatetime("2015-07-21T21:40:00"), "t": time("21:40:32.142")}
g.gql("RETURN local_time('10:00') AS t, local_datetime('2015-07-21T21:40') AS ldt, zoned_datetime('2015-07-21T21:40:32+02:00') AS dt").to_list()
// #{"dt": datetime("2015-07-21T21:40:32+02:00"), "ldt": localdatetime("2015-07-21T21:40:00"), "t": time("10:00:00")}
g.gql("RETURN date(datetime('2015-07-21T23:40:32+02:00')) AS d, localtime(datetime('2015-07-21T23:40:32+02:00')) AS t, datetime(localdatetime('2015-07-21T12:00')) AS dt").to_list()
// #{"d": date("2015-07-21"), "dt": datetime("2015-07-21T12:00:00Z"), "t": time("23:40:32")}
g.gql("RETURN date(null) AS a, date({year: 2015, month: null}) AS b").to_list()   // #{"a": (), "b": ()}

Text. The constructors read ISO 8601 as Neo4j does, in the extended and the basic form:

TypeText forms (examples)
date2015-07-21 / 20150721, 2015-07 / 201507, 2015; week dates 2015-W30-2 / 2015W302, 2015-W30 (its Monday); ordinal dates 2015-202 / 2015202; quarter dates 2015-Q3-21 / 2015Q321, 2015-Q3
localtime21:40:32.142 / 214032.142, 21:40 / 2140, 21; a comma for the fraction (21:40:32,142); no offset (12:00+01:00 is 22007)
timea localtime form, then Z, +01:00, +0100 or +01 (21:40:32.142+0100, 2140-02); no offset is UTC; no zone name
localdatetimea date form, T, a time form: 2015-07-21T21:40, 2015-W30-2T2140, 2015202T21:40:32.142
datetimea local datetime with Z, +01:00, +0100 or +01, and / or a zone in brackets: 2015-07-21T21:40:32.142[Europe/London], ..+01:00[Europe/London] (the offset must be the zone's at that time; the name is kept); a date alone is midnight; no offset and no zone is UTC
durationP14DT16H12M, P5W, -P1D, P-1DT2H; a fraction on any unit (P1.5Y, PT0.75M, PT1.5H); the alternative form P0001-02-03T04:05:06
g.gql("RETURN date('2015W302') AS w, date('2015-202') AS o, date('2015-Q3-21') AS q, date('2015-W30') AS monday").to_list()
// #{"monday": date("2015-07-20"), "o": date("2015-07-21"), "q": date("2015-07-21"), "w": date("2015-07-21")}
g.gql("RETURN datetime('2015-07-21T21:40:32.142[Europe/London]') AS a, datetime('2015-07-21T21:40:32+0100') AS b, datetime('2015-07-21') AS c").to_list()
// #{"a": datetime("2015-07-21T21:40:32.142+01:00[Europe/London]"), "b": datetime("2015-07-21T21:40:32+01:00"), "c": datetime("2015-07-21T00:00:00Z")}
g.gql("RETURN time('21:40:32.142+0100') AS a, time('2140-02') AS b, zoned_time('12:00') AS c").to_list()
// #{"a": offsettime("21:40:32.142+01:00"), "b": offsettime("21:40:00-02:00"), "c": offsettime("12:00:00Z")}
g.gql("RETURN duration('P1Y2M10DT2H30M') AS a, duration('P1.5Y') AS b, duration('PT0.75M') AS c, duration('P0001-02-03T04:05:06') AS d").to_list()
// #{"a": duration("P1Y2M10DT2H30M"), "b": duration("P1Y6M"), "c": duration("PT45S"), "d": duration("P1Y2M3DT4H5M6S")}
g.gql("RETURN date('2015-13-01') AS d")   // fails: the date does not exist (22007)

Maps. A map names the fields; the keys match in any ASCII case:

TypeKeys
dateyear with one group: month / day; week / dayOfWeek (ISO 8601 weeks: year is then the week-numbering year); ordinalDay; quarter / dayOfQuarter. A missing smaller field is its first value ({year: 1984} is January 1)
localtimehour, minute, second, and millisecond, microsecond, nanosecond (added up: {millisecond: 645, microsecond: 876} is .645876)
timethe keys of localtime and timezone (an offset, or a zone name: its offset at the query's instant); no timezone is UTC
localdatetimethe keys of both
datetimethe keys of both and timezone ('+01:00', 'Europe/Stockholm': the name is kept); no timezone is UTC
base valuesdate: d takes the date (of a date, a local datetime or a datetime at its own offset), time: t the time of day (and the offset of a datetime or time t, and the zone name of a datetime t), datetime: x both; the other keys then override single fields ({date: d, day: 28}, {date: d, week: 1} keeps the day of the week), and a base with a zone name is read again in its zone. With a base that has an offset, timezone converts the instant (12:00+01:00 to 16:00+05:00); without one it attaches the zone
durationyears, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, each may be fractional and negative; a fraction cascades down (a year is 12 months, a month 2 629 746 seconds, a week 7 days, a day 86 400 seconds, then the whole days of the seconds become days: {months: 0.75} is P22DT19H51M49.5S)

An unknown key, or two groups of date keys together, is 22007; a field out of range (month: 13, day: 30 in February, hour: 25, the year 10000) is 22008.

g.gql("RETURN date({year: 2015, week: 30, dayOfWeek: 2}) AS w, date({year: 1984, quarter: 3, dayOfQuarter: 45}) AS q, localdatetime({year: 1984, ordinalDay: 202, hour: 12}) AS o").to_list()
// #{"o": localdatetime("1984-07-20T12:00:00"), "q": date("1984-08-14"), "w": date("2015-07-21")}
g.gql("RETURN localtime({hour: 12, minute: 31, second: 14, millisecond: 645, microsecond: 876}) AS t, datetime({year: 1984, month: 10, day: 11, hour: 12, timezone: 'Europe/Stockholm'}) AS dt").to_list()
// #{"dt": datetime("1984-10-11T12:00:00+01:00[Europe/Stockholm]"), "t": time("12:31:14.645876")}
g.gql("RETURN date({date: date('2015-07-21'), day: 28}) AS a, localdatetime({date: date('2015-07-21'), time: localtime('12:30')}) AS b, datetime({datetime: datetime('2015-07-21T12:00+01:00'), timezone: '+05:00'}) AS c").to_list()
// #{"a": date("2015-07-28"), "b": localdatetime("2015-07-21T12:30:00"), "c": datetime("2015-07-21T16:00:00+05:00")}
g.gql("RETURN duration({days: 14, hours: 16, minutes: 12}) AS a, duration({years: 1.5, weeks: 2, seconds: 1.25}) AS b, duration({months: 0.75}) AS c").to_list()
// #{"a": duration("P14DT16H12M"), "b": duration("P1Y6M14DT1.250S"), "c": duration("P22DT19H51M49.500S")}
g.gql("RETURN date({year: 2015, month: 2, day: 30}) AS d")   // fails: the field day cannot be 30 (22008)

datetime.fromepoch(seconds, nanoseconds) and datetime.fromepochmillis(milliseconds) give the datetime (UTC) of a time since 1970-01-01T00:00Z. The map form does the same as in Neo4j: datetime({epochSeconds: s}) with an optional millisecond / microsecond / nanosecond, or datetime({epochMillis: ms}), each with an optional timezone (the instant shown in that zone); no other field may stand next to them.

g.gql("RETURN datetime.fromepoch(1416779, 999999000) AS a, datetime.fromepochmillis(237821673987) AS b").to_list()
// #{"a": datetime("1970-01-17T09:32:59.999999Z"), "b": datetime("1977-07-15T13:34:33.987Z")}
g.gql("RETURN datetime({epochSeconds: 1416779, microsecond: 5}) AS a, datetime({epochMillis: 237821673987, timezone: '+01:00'}) AS b").to_list()
// #{"a": datetime("1970-01-17T09:32:59.000005Z"), "b": datetime("1977-07-15T14:34:33.987+01:00")}

Components

x.name reads a component of a temporal value (any ASCII case: d.weekyear is d.weekYear). A name the value's type does not have is 22G03, and the message lists the names it has:

OfComponents
date, localdatetime, datetimeyear, quarter (1-4), month, week and weekYear (ISO 8601: Monday weeks, week 1 holds January 4), dayOfQuarter (also quarterDay), day, ordinalDay (1-366), dayOfWeek (also weekDay; 1 = Monday to 7 = Sunday)
localtime, time, localdatetime, datetimehour, minute, second, millisecond, microsecond, nanosecond, each fraction counted from the start of the second (.645876 gives 645, 645876, 645876000)
datetimetimezone (the zone name, 'Europe/Stockholm', of a value built with one, else the offset text), offset (the offset text: Z, +01:00), offsetMinutes, offsetSeconds, epochSeconds, epochMillis
timetimezone and offset (the offset text), offsetMinutes, offsetSeconds
durationthe totals years, quarters, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds; the remainders quartersOfYear, monthsOfQuarter, monthsOfYear, daysOfWeek, minutesOfHour, secondsOfMinute, millisecondsOfSecond, microsecondsOfSecond, nanosecondsOfSecond

A duration's months, days and seconds stay apart: years and quarters count its months, weeks its days, hours to nanoseconds its time part (duration('P1M2D').days is 2). The divisions truncate toward zero (duration({months: -16}).years is -1).

g.gql("RETURN date('2017-10-11').year AS y, date('2017-10-11').week AS w, date('2017-10-11').dayOfWeek AS dw, date('1984-01-01').weekYear AS wy, date('1984-10-11').ordinalDay AS o").to_list()
// #{"dw": 3, "o": 285, "w": 41, "wy": 1983, "y": 2017}
g.gql("RETURN datetime('2015-07-21T21:40:32.142+01:00').epochMillis AS e, datetime('2015-07-21T21:40:32.142+01:00').offset AS o, localtime('12:31:14.645876').millisecond AS ms").to_list()
// #{"e": 1437511232142, "ms": 645, "o": "+01:00"}
g.gql("RETURN duration({months: 14, days: 3, seconds: 3725}).years AS y, duration({months: 14, days: 3, seconds: 3725}).monthsOfYear AS my, duration({months: 14, days: 3, seconds: 3725}).hours AS h").to_list()
// #{"h": 1, "my": 2, "y": 1}
g.gql("RETURN date('2015-01-01').hour AS h")   // fails: a date has no component hour (22G03)

Arithmetic and comparison

FormResult
x + dur, dur + x, x - dur (x a date, localtime, time, localdatetime or datetime)a value of x's type: the duration's months (the day clamped to the month's end), then its days, then its time part, each where the type has it
dur + dur, dur - durpart by part (P1D + PT49H is P1DT49H)
dur * n, n * dur, dur / neach part scaled, with the fraction cascade of duration({..}) (P1M * 0.5 is P15DT5H14M33S)
-durevery part negated

A date takes the months, the days and the whole days of the time part (toward zero: PT33H adds one day, PT-33H takes one away), a localtime and a time only the time part, wrapping around midnight (a time keeps its offset). A datetime keeps its offset, or, with a zone name, follows its zone: a day added across a daylight saving change keeps the wall-clock time. Two values that are not both durations cannot be added (22G03: the time between them is duration.between(a, b)); dur / 0 is 22012; a result outside the years -9999 to 9999 is 22008.

g.gql("RETURN date('2024-01-31') + duration('P1M') AS a, date('1997-09-11') + duration('P29DT33H') AS b, localtime('23:00') + duration('PT2H') AS c, localdatetime('2015-07-21T21:40') - duration('PT1H30M') AS d").to_list()
// #{"a": date("2024-02-29"), "b": date("1997-10-11"), "c": time("01:00:00"), "d": localdatetime("2015-07-21T20:10:00")}
g.gql("RETURN duration('P1M') * 0.5 AS a, duration('P1Y') / 2 AS b, duration('P1D') + duration('PT49H') AS c, -duration('P1D') AS d").to_list()
// #{"a": duration("P15DT5H14M33S"), "b": duration("P6M"), "c": duration("P1DT49H"), "d": duration("-P1D")}
g.gql("RETURN date('2015-01-01') + date('2015-01-01') AS x")   // fails: + adds a duration to a temporal value (22G03)

Values of one type compare by calendar and clock, two datetimes by their instant (12:00+01:00 = 11:00Z is TRUE). Two durations are equal when their months, days and time part are, but they are not ordered: <, >, <=, >= on two durations are NULL (a month has no fixed length); ORDER BY still sorts them, by their length with a month of 30 days. Values of different temporal types are never equal (= FALSE) and not ordered (NULL), as values of different kinds are (Comparisons across types).

g.gql("RETURN datetime('2015-07-21T12:00+01:00') = datetime('2015-07-21T11:00Z') AS a, date('2015-01-01') < date('2016-01-01') AS b, duration('P1M') < duration('P30DT1S') AS c, date('2015-01-01') = localdatetime('2015-01-01T00:00') AS d").to_list()
// #{"a": true, "b": true, "c": (), "d": false}
g.gql("FOR d IN [duration('P1M'), duration('P30DT1S'), duration('PT1H')] RETURN d ORDER BY d").to_list()
// #{"d": duration("PT1H")}, #{"d": duration("P1M")}, #{"d": duration("P30DT1S")}

toString(x) writes a temporal value in Neo4j's text ('12:00', '1984-10-11T12:31', 'PT-1M-0.001S': no zero seconds, trailing fraction zeros stripped, a sign per duration component), while CAST(x AS STRING) writes the engine's canonical ISO 8601 text ('12:00:00', '-PT1M0.001S', Text Formats). The constructors read both back.

g.gql("RETURN toString(localtime('12:00')) AS a, CAST(localtime('12:00') AS STRING) AS b, toString(duration({minutes: -1, milliseconds: -1})) AS c, CAST(duration({minutes: -1, milliseconds: -1}) AS STRING) AS d").to_list()
// #{"a": "12:00", "b": "12:00:00", "c": "PT-1M-0.001S", "d": "-PT1M0.001S"}

Truncation

date.truncate(unit, x [, map]), localtime.truncate(..), time.truncate(..), localdatetime.truncate(..) and datetime.truncate(..) cut x to the start of unit and give a value of their type (these qualified names are Cypher's; GQL has no spelling for them):

FunctionUnits (any ASCII case)
date.truncatemillennium, century, decade, year, weekYear, quarter, month, week, day
localdatetime.truncate, datetime.truncatethose, and hour, minute, second, millisecond, microsecond, nanosecond
localtime.truncate, time.truncateday (midnight) to nanosecond
  • millennium and century follow Neo4j: 2017 truncates to 2000, 1984 to 1900 (Gremlin's date_trunc keeps PostgreSQL's 2001 and 1901). weekYear is the Monday of ISO week 1 of the week-numbering year (1984-01-01 gives 1983-01-03); week is a Monday; nanosecond keeps the value (it holds nanoseconds).
  • x may be of another temporal type and is projected first: the date of a datetime at its own offset, the time of day of either, midnight for a date. datetime.truncate keeps the offset of a datetime (and its zone name: the truncated wall clock is read in that zone again) and gives UTC to a value without one; time.truncate keeps the offset of a time or a datetime.
  • The map overrides fields of the truncated value as the constructors' base form does: {day: 2}, {dayOfWeek: 2}, {hour: 1}, {millisecond: 5}, and for datetime.truncate {timezone: ..}, which keeps the wall clock and reads it in that zone (a name is kept), for time.truncate the offset of the result.
  • A unit the type lacks (date.truncate('hour', ..)) or an unknown unit is 22023; a value without the part the type needs (date.truncate('day', localtime(..))) or a duration 22G03.
g.gql("RETURN date.truncate('millennium', date('2017-10-11')) AS m, date.truncate('century', date('1984-10-11')) AS c, date.truncate('weekYear', date('1984-01-01')) AS wy").to_list()
// #{"c": date("1900-01-01"), "m": date("2000-01-01"), "wy": date("1983-01-03")}
g.gql("RETURN date.truncate('week', date('2017-10-11'), {dayOfWeek: 2}) AS a, localdatetime.truncate('quarter', localdatetime('2017-11-11T12:31:14'), {day: 2}) AS b, localtime.truncate('hour', localtime('12:31:14'), {minute: 5}) AS c").to_list()
// #{"a": date("2017-10-10"), "b": localdatetime("2017-10-02T00:00:00"), "c": time("12:05:00")}
g.gql("RETURN datetime.truncate('month', date('2017-11-11')) AS a, datetime.truncate('day', datetime('2017-10-11T12:31:14+01:00'), {timezone: 'Europe/Stockholm'}) AS b").to_list()
// #{"a": datetime("2017-11-01T00:00:00Z"), "b": datetime("2017-10-11T00:00:00+02:00[Europe/Stockholm]")}
g.gql("RETURN date.truncate('hour', date('2017-10-11')) AS d")   // fails: the unit hour is not defined for a date (22023)

Durations between two values

FunctionGives
duration.between(a, b)the whole months from a to b (a month counts once its day of the month and time of day are reached), then the whole days after them, then the rest of the time; every part has the sign of the direction
duration.inMonths(a, b)the whole months only (toward zero)
duration.inDays(a, b)the whole days only (toward zero)
duration.inSeconds(a, b)the elapsed time, as a duration of seconds only

The operands may be of different types; they are aligned first as Neo4j aligns them: when only one has a time of day, the other gets midnight; when only one has a date, the other gets that date (date('1984-10-11') to localtime('16:30') is PT16H30M); when only one has an offset, the other is read at that offset, or in that side's zone when it is a datetime with a zone name (across a daylight saving change, as Neo4j). inMonths / inDays of two localtimes or two times, a duration or a value that is no temporal value is 22G03.

g.gql("RETURN duration.between(date('1984-10-11'), date('2015-06-24')) AS d, duration.inMonths(date('1984-10-11'), date('2015-06-24')) AS m, duration.inDays(date('1984-10-11'), date('2015-06-24')) AS dd, duration.inSeconds(date('1984-10-11'), date('1984-10-12')) AS s").to_list()
// #{"d": duration("P30Y8M13D"), "dd": duration("P11213D"), "m": duration("P30Y8M"), "s": duration("PT24H")}
g.gql("RETURN duration.between(localdatetime('2015-07-21T21:40:32.142'), date('2015-06-24')) AS a, duration.between(date('1984-10-11'), localtime('16:30')) AS b").to_list()
// #{"a": duration("-P27DT21H40M32.142S"), "b": duration("PT16H30M")}
g.gql("RETURN duration.inDays(localtime('10:00'), localtime('12:00')) AS d")   // fails: two local times have no days (22G03)

Clocks

date(), localtime(), time(), localdatetime() and datetime() with no argument (and their ISO names), the ISO clocks CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, LOCAL_TIME and LOCAL_TIMESTAMP (written without parentheses; current_date() with empty ones is accepted too), and X.statement() / X.transaction() (date.statement(), datetime.transaction(), ...) give the time the query started: one instant per query, the same for every row and every call, so a query is deterministic and repeatable. A zone argument or map gives that instant in the zone (datetime.statement('Europe/Berlin'), date({timezone: '+05:00'})); the default zone is UTC. In a script the instant is the script's own: datetime() in g.gql(..) equals the script's now(), and date() its today() at UTC. X.realtime(), a clock that moves while the query runs, is refused like rand().

g.gql("RETURN date() = date.statement() AS a, datetime.transaction() = datetime() AS b, datetime({timezone: '+05:00'}).timezone AS z").to_list()   // #{"a": true, "b": true, "z": "+05:00"}
g.gql("RETURN CURRENT_DATE = date() AS a, CURRENT_TIMESTAMP = zoned_datetime() AS b, LOCAL_TIMESTAMP = local_datetime() AS c").to_list()   // #{"a": true, "b": true, "c": true}
g.gql("FOR i IN [1, 2, 3] RETURN count(DISTINCT datetime()) AS instants").to_list()   // #{"instants": 1}
g.gql("RETURN datetime.realtime() AS t")   // refused: a clock that moves while the query runs

Literals

The ISO GQL temporal literals are a type word and a string; the string is read as the constructor of that type reads its text:

LiteralValueAs
DATE '2024-01-05'a datedate('2024-01-05')
TIME '10:00:00.5'a local time (no offset in the text)local_time('10:00:00.5')
TIME '10:00+01:00'a zoned time (an offset in the text)zoned_time('10:00+01:00')
DATETIME '2024-01-05T10:00', TIMESTAMP '..'a local datetime (no offset or zone in the text)local_datetime('..')
DATETIME '2024-01-05T10:00+01:00', TIMESTAMP '..[Europe/Berlin]'a zoned datetime (an offset or a zone in the text, a zone name kept)zoned_datetime('..')
DURATION 'P1DT2H'a durationduration('P1DT2H')
ZONED TIME '..', ZONED DATETIME '..' / ZONED TIMESTAMP '..'the zoned type; a text without an offset or zone is a syntax error (42001)zoned_time('..'), zoned_datetime('..')
LOCAL TIME '..', LOCAL DATETIME '..' / LOCAL TIMESTAMP '..'the local type; an offset in the text is 22007local_time('..'), local_datetime('..')

The type follows the text as ISO GQL defines it, never a guess from its content beyond the offset: TIME '10:00' is a local time, TIME '10:00Z' a zoned one. The ZONED / LOCAL forms spell the type out (the words of the GQL type names, as in CAST). A text the type cannot read is 22007. The type words are no reserved words: date stays a variable name wherever no string follows it.

g.gql("RETURN DATE '2024-01-31' + DURATION 'P1M' AS d, TIME '10:00:00.123456789+01:00' AS t, TIMESTAMP '2024-01-05T10:00[Europe/Berlin]' AS z").to_list()
// #{"d": date("2024-02-29"), "t": offsettime("10:00:00.123456789+01:00"), "z": datetime("2024-01-05T10:00:00+01:00[Europe/Berlin]")}
g.gql("RETURN ZONED TIME '10:00' AS t")   // error: a ZONED TIME literal needs a UTC offset or a time zone (42001)

Not yet

timestamp() (Neo4j's milliseconds since 1970), date_trunc(), datetime_trunc() and CAST(x AS DATE) (and the other temporal CAST targets). Each is 0A000 with the alternative.

g.gql("RETURN timestamp() AS t")   // error: timestamp() is not yet supported
g.gql("RETURN time('12:00+01:00') AS t").to_list()   // [#{"t": offsettime("12:00:00+01:00")}]

Parameters

$name reads the value of name from the parameter map, the second argument of gql(). A parameter is a value, never query text: it cannot change the query, whatever it holds. A parameter the query reads but the map lacks is an error before the run; extra entries are ignored.

g.gql("MATCH (n:person) WHERE n.age > $min RETURN n.name AS name ORDER BY name", #{min: 30}).to_list()   // #{"name": "josh"}, #{"name": "peter"}
g.gql("MATCH (n:person) WHERE n.name IN $names RETURN n.name AS name, n.age AS age ORDER BY name", #{names: ["josh", "vadas"]}).to_list()
// #{"age": 32, "name": "josh"}, #{"age": 27, "name": "vadas"}
g.gql("MATCH (n:person {name: $who})-[:created]->(s) RETURN s.name AS s", #{who: "peter"}).to_list()   // #{"s": "lop"}
g.gql("MATCH (n:person) RETURN n.name AS name ORDER BY name SKIP $s LIMIT $l", #{s: 2, l: 5}).to_list()   // #{"name": "peter"}, #{"name": "vadas"}

A parameter may also stand where an index can serve it, so MATCH (p:person {name: $n}) uses a property index on person.name when one exists (Plans and Performance).

Not supported yet

These are part of GQL (or Cypher constructs that LLMs and Cypher users write often) and come in a later version. Each fails before the run with GQLSTATUS 0A000 and a message that names the construct and the alternative.

ConstructUntil then
Cypher's FOREACHFOR x IN list INSERT .. (or SET .., DELETE .., MERGE ..) (Writing with GQL)
a write in an operand of UNION, a path variable in INSERTrun the write on its own; name the nodes and edges
a SET / REMOVE target deeper than a variable (n.a.b = .., head(l).k = .., a computed key n[k] = ..)WITH head(l) AS x SET x.k = ..
NEXT YIELDRETURN the columns to pass on before NEXT
a CALL folder.name(..) of a saved query written in Rhaig.query(name, #{..}) from the DSL, or save it again in GQL (Calling saved queries)
an argument of CALL folder.name(..) that reads the row (CALL people.older(s.age)); a CALL of a saved query inside EXISTS { }, COUNT { }, COLLECT { }a constant or a $parameter; a CALL (s) { .. } subquery or the saved query's pattern in the query
OPTIONAL { ... } / OPTIONAL ( ... ) blocksone OPTIONAL MATCH per optional part
a quantified edge over a list of edges bound before, Cypher's WITH [r1, r2] AS rs MATCH (a)-[rs*]->(b)a new name compared in WHERE: MATCH (a)-[rs2*]->(b) WHERE rs2 = rs
a quantifier nested in a quantified path pattern, (((a)-->(b)){2})+write the inner path out, ((x)-->(y)-->(z))+, or Gremlin repeat()
path search prefixes and match modes (ANY SHORTEST, TRAIL, DIFFERENT EDGES written out)Gremlin path(), repeat()
EXCEPT, INTERSECT, OTHERWISENOT EXISTS { } / EXISTS { } on the rows of the first query, or NEXT
NULLS FIRST / NULLS LASTthe fixed order: NULL last ascending, first descending
gql() after other steps (g.v().gql(..))start with g.gql(..) and continue with Gremlin
a list-comprehension or list-predicate variable read inside a subquery of its WHERE / | parttest the variable outside the subquery, or match the pattern in the query
trigonometric functions (sin, cos, ..., pi(), degrees())Gremlin math() after gql()
timestamp(), date_trunc(), datetime_trunc()datetime().epochMillis, date.truncate(unit, d)
CAST(x AS DATE) and the other temporal CAST targetsDATE '..' for a constant, date(x) for a value
list conversions toIntegerList(), toStringList(), ...FOR t IN list RETURN collect_list(toInteger(t)), or Gremlin unfold() and as_number() after gql()
normalize(s)store normalized text
GQL's elements(p)nodes(p) and relationships(p)
the standard deviations stDev(), stDevP()collect_list(x), then compute after gql()
g.gql("MATCH (((a)-[:knows]->(b)){1,2})+ RETURN b")   // error: a parenthesized path pattern nested in another one is not yet supported
g.gql("MATCH ((a)-[:knows]->(b)){1,3} RETURN [n IN b | n.name] AS b ORDER BY b").to_list()   // #{"b": ["josh"]}, #{"b": ["vadas"]}
g.gql("MATCH (p:person) RETURN [x IN [p] WHERE (x)-[:created]->() | x.name] AS l")   // error: reading the comprehension variable `x` inside a subquery is not yet supported
g.gql("MATCH (p:person) WHERE (p)-[:created]->() RETURN [x IN [p] | x.name] AS l ORDER BY l").to_list()   // #{"l": ["josh"]}, #{"l": ["marko"]}, #{"l": ["peter"]}
g.gql("MATCH (p:person) RETURN p.name AS n EXCEPT MATCH (p:person)-[:created]->() RETURN p.name AS n")   // error: EXCEPT is not yet supported
g.gql("MATCH (p:person) WHERE NOT EXISTS { (p)-[:created]->() } RETURN p.name AS n").to_list()   // #{"n": "vadas"}
g.gql("MATCH (n:person) RETURN sin(n.age) AS s")   // error: sin() (a trigonometric function) is not yet supported
g.gql("MATCH (n:person) RETURN n.name AS name, n.age AS a ORDER BY name").select("a").math("sin(_)").to_list()   // 0.5514266812416906, -0.6636338842129675, -0.428182669496151, 0.956375928404503

Semantics

gql() follows ISO GQL. Where the standard leaves a choice to the implementation, or where its text could not be checked yet, Graphersal follows Neo4j's Cypher 25, which implements GQL too; this page says where.

Trail: different edges

Within one MATCH clause an edge is bound at most once (GQL's DIFFERENT EDGES match mode, also called trail semantics; the GQL default and Neo4j's). Vertices may repeat.

g.gql("MATCH (a)-[:created]->(s)<-[:created]-(b) WHERE s.name = 'lop' RETURN a.name AS a, b.name AS b ORDER BY a, b").to_list()
// josh/marko, josh/peter, marko/josh, marko/peter, peter/josh, peter/marko: never a person with themselves
g.gql("MATCH (a {name: 'marko'})-[:knows]->(b)<-[:knows]-(c) RETURN c.name AS c").to_list()   // no rows: c could only be marko again over the same edge

The second query has no rows: every knows edge into b comes from marko, and binding it again for c would use the same edge twice. Gremlin has no such rule, so its twin returns marko:

g.v().has("name", "marko").out("knows").in("knows").values("name").to_list()   // "marko", "marko"

Two separate MATCH clauses are checked separately: an edge bound in the first may be bound again in the second. An edge variable written twice in one MATCH is an error.

g.gql("MATCH (a {name: 'marko'})-[:knows]->(b) MATCH (b)<-[:knows]-(c) RETURN c.name AS c").to_list()   // #{"c": "marko"}, #{"c": "marko"}
g.gql("MATCH (a)-[e]->(b), (b)<-[e]-(a) RETURN a")   // error: the edge variable `e` is used for more than one edge in the same MATCH

Quantified edges

A quantified edge (-[:knows]->{1,3}, The Supported Subset) is part of its MATCH clause like any edge: within one match every edge is different, across the repetitions and from the other edges of the clause (trail). Vertices may repeat, so a quantified edge may walk around a cycle, but never over the same edge twice.

  • The zero-length match of a lower bound 0 ({0,n}, *) binds the far node to the near one; the group variable is then []. {0} matches only that.
  • Cypher's empty interval ([*2..1], [*..0]: the lower bound above the upper one) matches nothing, as in Neo4j: no row, and an OPTIONAL MATCH part gets its NULL row. The GQL form {2,1} is a syntax error (ISO).
  • An upper bound larger than any trail can be (beyond about four billion) means "no bound"; such a quantifier behaves like {m,}.
  • Unbounded quantifiers ({m,}, *, +, Cypher [*]) have no limit of their own: trail ends every walk once it has used every edge it can reach, which on a finite graph always happens. Two general limits still apply: repeat.max_loops (10 000 repetitions) and traversal.max_traversers (live rows between two steps). Reaching either is an error, never a shortened result; its help names the quantifier and how to bound it or raise the limit with g.with(..).gql(..).
g.with("repeat.max_loops", 1).gql("MATCH (a {name: 'marko'})-[:knows|created]->*(b) RETURN b.name AS b")   // error: repeat() exceeded the loop limit of 1 iterations
g.with("repeat.max_loops", 5).gql("MATCH (a {name: 'marko'})-[:knows|created]->*(b) RETURN b.name AS b ORDER BY b").to_list()
// josh, lop, lop, marko, ripple, vadas
g.gql("MATCH (a {name: 'marko'})-[e]->{0}(b) RETURN b.name AS b, e").to_list()   // #{"b": "marko", "e": []}

The help of the first error reads (shortened):

Help: The loop of the quantified edge -[:knows|created]->{0,} of the gql() query ran 1 iterations, the limit of repeat.max_loops. ...
Give the quantifier an upper bound, as in -[:knows|created]->{0,5}, ... Or raise the limit for the query, g.with("repeat.max_loops", 2).gql(..), ...

Each match of a quantified edge is a row of its own (the edges it used keep the rows apart), so the number of rows can grow fast on a densely connected graph: bound the quantifier where the question allows it.

Quantified path patterns

A quantified path pattern ((a) ((x)-[e]->(y)){1,3} (b), The Supported Subset) repeats a whole chain. Graphersal follows ISO GQL and, where a detail is open, Neo4j's Cypher 25, which implements the same construct:

  • Merge rule. The node before the group is the first node of the first iteration, the node after it the last node of the last iteration, and each iteration starts where the previous one ended: in (a) ((x)-->(y)){1,3} (b), a is the first x, b the last y, and the y of one iteration is the x of the next. After zero iterations a and b are one node, so (a) ((x)-->(y))* (a) matches the closed walks from a (the zero-length one included).
  • Trail per body edge. Within one match every edge is different: across the iterations, between the body's edges and from the other edges of the MATCH clause, so a quantified path pattern ends on every finite graph, like a quantified edge. A body edge that a ? part did not bind (zero iterations) clashes with nothing.
  • Group lists. With a quantifier other than ?, each body variable is the list of its elements, one per iteration, in the order the text reads (also when the plan walks the pattern from its far end): x = [x1, x2, ...]. A zero-length match gives []. A property of a group variable has no single value outside the body (42002); inside the body, in its conditions, the variable is the element of the current iteration.
  • ? gives nullable singletons (ISO). ((x)-[e]->(y))? matches its body once or not at all; its variables are single elements, NULL for the match where it did not match (no iteration), not lists. {0,1} matches the same paths but keeps group lists ([] or one element).
  • No quantifier: singletons. A parenthesized path pattern without a quantifier matches its body exactly once; its variables are single elements, as if the parentheses were not there, and its WHERE is a condition on that part of the path.
  • The body condition runs in every iteration and reads only body variables, parameters and values: an iteration whose condition is not TRUE ends that walk.
g.gql("MATCH (a {name: 'marko'})-[e]->(m) ((x)-[f]-(y))? (b) RETURN m.name AS m, b.name AS b ORDER BY m, b").to_list()
// josh/josh, josh/lop, josh/ripple, lop/josh, lop/lop, lop/peter, vadas/vadas: never back to marko over the edge e
g.gql("MATCH (p:person {name: 'vadas'}) ((x)-[:created]->(s))? (q) RETURN s AS s, q.name AS q").to_list()   // #{"q": "vadas", "s": ()}
g.gql("MATCH (p:person {name: 'vadas'}) ((x)-[:created]->(s)){0,1} (q) RETURN s AS s, q.name AS q").to_list()   // #{"q": "vadas", "s": []}

Limits that hold now (E17; each refused with 0A000 and a help line naming the rewrite): one chain per body, no quantifier nested inside a body (neither a group nor a quantified edge), no path variable inside a body (name the whole path instead), and a body variable is a new name: an outer variable written inside a body, a variable written twice in one body, a body condition reading an outer variable, and a subquery inside a body are not supported yet. Every body edge counts once toward the 64 edge patterns of a MATCH clause, however often the body repeats.

The unbounded quantifiers ({m,}, *, +) are bounded as for a quantified edge: repeat.max_loops counts the iterations of the whole body, traversal.max_traversers the live rows, and reaching either is an error naming the pattern (Errors), never a shortened result.

Reading ((. Where an expression stands, (( followed by a pattern and a closing ) with {..}, ?, a node, an edge, or * / + not followed by an operand reads as a quantified path pattern (a pattern predicate). So ((a)-->(b)) + (c) is the pattern ((a)-->(b))+ (c), not the boolean of the pattern predicate ((a)-->(b)) plus c; with an operand after it (((a)-->(b)) + [1], + x, + 1) it stays arithmetic. Arithmetic on a predicate's boolean is a type error (22G03) in either reading, so no working query changes meaning.

OPTIONAL MATCH and NULL

A row that reaches an OPTIONAL MATCH whose pattern does not match continues once, with every variable the optional part introduces set to NULL: a property of it is NULL, a group variable is NULL (not []), a path variable is NULL. The variables bound before keep their values. The trail rule is checked per clause, so an optional part may bind an edge the MATCH before it bound.

g.gql("MATCH (a {name: 'marko'})-[:knows]->(b) OPTIONAL MATCH (b)-[:created]->(s) RETURN b.name AS b, s.name AS s ORDER BY b, s").to_list()
// #{"b": "josh", "s": "lop"}, #{"b": "josh", "s": "ripple"}, #{"b": "vadas", "s": ()}

NULL and three-valued logic

A property that is missing reads as NULL, exactly like a property stored as null. WHERE uses three-valued logic: a comparison with NULL is NULL (unknown), AND / OR / NOT follow the SQL / GQL truth tables, and a row passes only when the condition is TRUE.

g.gql("MATCH (n) RETURN n.name AS name, n.age > 30 AS old, n.lang = 'java' AS java ORDER BY name").to_list()
// josh: old true, java (); lop: old (), java true; marko: old false, java (); ...
g.gql("MATCH (n) RETURN n.age = NULL AS a, NULL IS NULL AS b, 2 IN [1, NULL] AS c, NULL IN [] AS d LIMIT 1").to_list()
// #{"a": (), "b": true, "c": (), "d": false}
g.gql("MATCH (n) WHERE n.age IS NULL RETURN n.name AS name ORDER BY name").to_list()   // #{"name": "lop"}, #{"name": "ripple"}

(() is how Rhai shows NULL; JSON shows null.) Test for a missing value with IS NULL, never with = NULL.

The consequence that surprises Gremlin users: NOT of an unknown condition is still unknown, so the software (which has no age) passes neither n.age < 30 nor NOT n.age < 30, while Gremlin's not(has(..)) keeps them:

g.gql("MATCH (n) WHERE NOT n.age < 30 RETURN n.name AS name ORDER BY name").to_list()   // #{"name": "josh"}, #{"name": "peter"}
g.v().not(__.has("age", P.lt(30))).values("name").order().to_list()   // "josh", "lop", "peter", "ripple"
g.gql("MATCH (n) WHERE n.age <> 29 RETURN n.name AS name ORDER BY name").to_list()   // josh, peter, vadas (not lop, not ripple)

The same holds for <>: a vertex without age is not "different from 29", its comparison is unknown.

EXISTS and pattern predicates

A row is kept once, however often the body matches. EXISTS (and a pattern predicate, The Supported Subset) is a semi-join: it asks whether there is a match and adds no rows. The same pattern in MATCH gives one row per match, so josh, who created two programs, comes twice:

g.gql("MATCH (p:person)-[:created]->() RETURN p.name AS name ORDER BY name").to_list()   // josh, josh, marko, peter
g.gql("MATCH (p:person) WHERE (p)-[:created]->() RETURN p.name AS name ORDER BY name").to_list()   // josh, marko, peter

TRUE or FALSE, never NULL. A body that matches is TRUE, one that does not is FALSE, also when it reads a variable that is NULL on the row (an import from an OPTIONAL MATCH that did not match): a NULL element matches nothing, so EXISTS is FALSE and NOT EXISTS TRUE. Around it, three-valued logic works as usual: NULL OR EXISTS {..} is TRUE when the body matches and NULL otherwise. (This follows Neo4j; the ISO text is still to be checked.)

g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s WHERE s.name = 'ripple') RETURN p.name AS name, EXISTS { (s)<-[:created]-() } AS made, NOT EXISTS { (s)<-[:created]-() } AS not_made ORDER BY name").to_list()
// josh: made true, not_made false; marko, peter, vadas (s is NULL): made false, not_made true
g.gql("MATCH (p:person) RETURN p.name AS name, p.lang = 'x' OR EXISTS { (p)-[:knows]->() } AS a ORDER BY name").to_list()
// josh (), marko true, peter (), vadas ()

A pattern alone is a condition, not a value. A pattern predicate such as (p)-[:knows]->() stands only where WHERE (or FILTER, a comprehension's WHERE, a WHEN of a searched CASE) expects a condition, also under NOT, AND, OR and XOR there. Anywhere else (a RETURN or WITH item, a function argument, a SET value) it is a syntax error (42001), as in Neo4j: write EXISTS { .. } for whether it matches, COUNT { .. } for how often, or a pattern comprehension for what it matches (stage 3f, the openCypher TCK Pattern1, List6):

g.gql("MATCH (p:person) RETURN p.name AS name, (p)-[:knows]->() AS k")   // error: the pattern stands where a value is expected (42001)
g.gql("MATCH (p:person) RETURN p.name AS name, EXISTS { (p)-[:knows]->() } AS k, COUNT { (p)-[:knows]->() } AS n, [(p)-[:knows]->(f) | f.name] AS fs ORDER BY name").to_list()
// josh: false, 0, []; marko: true, 2, ["vadas", "josh"]; ...

Trail per body clause. Each MATCH clause inside a body is its own clause for the trail rule (Trail): its edges are different from each other, but they may repeat an edge of the query outside the body (an imported edge variable is that same edge) or of another body clause. (Neo4j's rule; the ISO text is still to be checked.)

g.gql("MATCH (a {name: 'marko'}) WHERE EXISTS { MATCH (a)-[:knows]->(x)<-[:knows]-(a) } RETURN a.name AS a").to_list()   // no rows: one clause, one edge twice
g.gql("MATCH (a {name: 'marko'}) WHERE EXISTS { MATCH (a)-[:knows]->(x) MATCH (x)<-[:knows]-(a) } RETURN a.name AS a").to_list()   // #{"a": "marko"}
g.gql("MATCH (a {name: 'marko'})-[e:knows]->(b) WHERE EXISTS { MATCH (b)<-[e]-(x) } RETURN b.name AS b ORDER BY b").to_list()   // josh, vadas: e imported

Evaluated only when needed, at most once per row. A body stops at its first match. Where EXISTS stands inside a larger expression, a row runs the body only when the evaluation reaches it (a OR EXISTS {..} runs nothing when a is TRUE), and once even when several columns or keys of the row hold the same subquery. A body that imports nothing (EXISTS { (:robot) }) is still run per row; its answer is not cached yet.

Filter order. The conditions of one element (or one WHERE) run in this order: those pushed into has(), the other plain conditions, then those holding a subquery, which cost the most (a subquery inside a larger expression before a plain [NOT] EXISTS). The result does not depend on the order, only the work does. The global optimizer rule filter_reorder may still move a subquery's step before a gql:filter by its own cost estimate, as it does for the same Gremlin steps (Plans and Performance).

Map projections and comprehensions

A NULL variable projects to NULL. A map projection v {..} of a NULL variable (an OPTIONAL MATCH that did not match) is NULL, and its entries are not evaluated at all, while the GQL record constructor {name: v.name} builds a map whose values are NULL. A pattern comprehension that imports a NULL variable matches nothing and gives [], never NULL:

g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s {name: 'ripple'}) RETURN p.name AS name, s {.name} AS projection, {name: s.name} AS record, [(s)<-[:created]-(c) | c.name] AS creators ORDER BY name").to_list()
// josh: projection #{"name": "ripple"}, record #{"name": "ripple"}, creators ["josh"]
// marko, peter, vadas: projection (), record #{"name": ()}, creators []
g.gql("MATCH (p:person {name: 'vadas'}) OPTIONAL MATCH (p)-[:created]->(s) RETURN s {k: 1 / 0} AS m").to_list()   // #{"m": ()}: the entry never runs

Keys. The entries come in the written order. .* puts every stored property at its place, in stored order, without the id and the labels; a property stored as null is left out, as in properties(). A key written twice (also through .*) keeps its first place and takes the later value. The variable of a projection must be a vertex, an edge or a map; any other value is the data error 22G03. An element inside the map (friend: f) stays the live element (Result Shape).

g.gql("MATCH (p:person {name: 'marko'}) RETURN p {.name, age: 1, .age} AS m").to_json()   // [{"m": {"name": "marko", "age": 29}}]
g.gql("WITH {a: 1, b: 2} AS m RETURN m {.a, .c, .*, d: 3} AS x").to_json()   // [{"x": {"a": 1, "c": null, "b": 2, "d": 3}}]
g.gql("WITH 1 AS m RETURN m {.a} AS x")   // error: a map projection reads a node, an edge or a map, not a number (22G03)

List comprehension. A NULL list gives NULL, a value that is not a list the data error 22G03. WHERE keeps an item only when the condition is TRUE: FALSE and NULL drop it (three-valued logic). The result keeps the list's order.

g.gql("RETURN [x IN [1, NULL, 3] WHERE x > 1] AS kept, [x IN [1, NULL, 3] | x] AS every, [x IN NULL | x] AS none").to_list()
// #{"every": [1, (), 3], "kept": [3], "none": ()}
g.gql("RETURN [x IN 5 | x] AS m")   // error: a list comprehension iterates over a list, not a number (22G03)

List predicates and reduce. all(), any(), none() and single() are three-valued, not counts: a NULL list gives NULL; an item that decides the answer wins (all FALSE at a FALSE item, any TRUE and none FALSE at a TRUE one, single FALSE at a second TRUE one) and the later items are not evaluated; otherwise a NULL condition gives NULL. This is the openCypher TCK (Quantifier1 to Quantifier4), which Neo4j Cypher 25 follows; Neo4j's manual words the NULL rule of any() like that of all(), but its implementation and the TCK give any(x IN [NULL, 2] WHERE x = 2) TRUE, as here. reduce(acc = init, x IN l | expr) gives NULL for a NULL list, init for an empty one, and lets NULL items flow through expr. Their variables are new names like a comprehension's.

g.gql("RETURN any(x IN [NULL, 2] WHERE x = 2) AS a, all(x IN [NULL, 2] WHERE x = 2) AS b, single(x IN [2, NULL] WHERE x = 2) AS c, single(x IN [2, NULL, 2] WHERE x = 2) AS d").to_list()
// #{"a": true, "b": (), "c": (), "d": false}
g.gql("RETURN reduce(s = 0, x IN [1, NULL] | s + x) AS a, reduce(s = 0, x IN [] | s + x) AS b, reduce(s = 0, x IN NULL | s + x) AS c").to_list()
// #{"a": (), "b": 0, "c": ()}

A comprehension variable hides no name in scope. It may not shadow a variable or column in scope, nor the variable of a comprehension around it. A name that is no longer in scope (one a WITH dropped, one bound inside a subquery) may be used again, as in Neo4j (stage 3f, the openCypher TCK Quantifier1..4). One exception keeps a LET / WITH value right: a name that the expression of such a value in scope reads is refused too, since gql() substitutes the value by its expression, which still refers to the dropped variable by that name. So MATCH (n) WITH n AS m RETURN [n IN [1] | n], which runs in Neo4j, is an error here; pick another name ([x IN [1] | x]). The variable exists only inside its brackets.

g.gql("MATCH (n:person) WITH n AS m RETURN [n IN [1] | n] AS l")   // error: the comprehension variable `n` is a name that a LET or WITH value in scope still reads
g.gql("MATCH (n:person) WITH collect(n) AS ns RETURN [n IN ns | n.name] AS names").to_list()   // #{"names": ["marko", "vadas", "josh", "peter"]}
g.gql("MATCH (n:person) WITH n AS m RETURN [x IN [1] | x] AS l ORDER BY l LIMIT 1").to_list()   // #{"l": [1]}

Pattern comprehension: one item per match, in no defined order. The list holds one item per match of the pattern, so the same value may come several times (josh created two programs in java). Like any subquery it runs on the row's imports, with the trail rule inside its own pattern (EXISTS); its items come in the order the matches are found, which depends on the plan. When the order matters, match the pattern in the query, sort the rows and collect them with collect_list(), or sort the list after gql().

g.gql("MATCH (p:person {name: 'josh'}) RETURN [(p)-[:created]->(s) | s.lang] AS langs").to_list()   // #{"langs": ["java", "java"]}
g.gql("MATCH (a {name: 'marko'}) RETURN [(a)-[:knows]->(x)<-[:knows]-(a) | x.name] AS one").to_list()   // #{"one": []}: one pattern, one edge twice

Evaluated when reached, once per row. A pattern comprehension runs its pattern only for the rows whose evaluation reaches it, at most once per row, like EXISTS; one that imports nothing still runs per row. Comprehensions nested from the same element multiply the work: [(m)-->(a) | [(m)-->(b) | ..]] runs the inner pattern once for every match of the outer one, like nested Gremlin map(..fold()) children, and only the resource limits bound a deep chain of them (Resource limits).

COUNT and COLLECT

An aggregating answer for every row. COUNT { } and COLLECT { } run their body once per row, like EXISTS, but read it to the end: COUNT { } is the number of rows the body returns (0, never NULL, when there are none) and COLLECT { } the list of its one RETURN item ([] when there are none). An imported NULL variable matches nothing, as in EXISTS, so both give 0 and []. COLLECT { } keeps NULL items, unlike collect_list(), and keeps the body's row order, so an ORDER BY inside it orders the list; without one the order is unspecified, as for a pattern comprehension.

g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s {name: 'ripple'}) RETURN p.name AS name, COUNT { (s)<-[:created]-() } AS n, COLLECT { MATCH (s)<-[:created]-(c) RETURN c.name } AS l ORDER BY name").to_list()
// josh 1 ["josh"]; marko, peter, vadas (s is NULL): 0 []
g.gql("MATCH (p:person {name: 'marko'}) RETURN COLLECT { MATCH (p)-[:knows]->(f) RETURN f.lang } AS l, [(p)-[:knows]->(f) | f.lang] AS c").to_list()   // #{"c": [(), ()], "l": [(), ()]}

A deviation: the RETURN of a counted body is not evaluated. When a COUNT { } body is one query whose final RETURN only projects (no aggregate, DISTINCT, ORDER BY or UNION, which need the values), gql() counts the body's rows without evaluating the RETURN items, nor the values a projecting WITH names only for them: the count is the same, but an expression there that would fail on a row (a division by zero, a value of the wrong kind) raises no error, while the same body run as a query (or in CALL) raises it. EXISTS and COLLECT { } evaluate theirs.

g.gql("MATCH (p:person) RETURN p.name AS name, COUNT { MATCH (p)-[:created]->(s) RETURN 1 / 0 AS x } AS n ORDER BY name").to_list()   // josh 2, marko 1, peter 1, vadas 0
g.gql("MATCH (p:person) RETURN COUNT { MATCH (p)-[:created]->(s) RETURN DISTINCT 1 / 0 AS x } AS n")   // error: division by zero: DISTINCT needs the value
g.gql("MATCH (p:person) WHERE EXISTS { MATCH (p)-[:created]->(s) RETURN 1 / 0 AS x } RETURN p.name AS name")   // error: division by zero: EXISTS evaluates its RETURN

UNION and NEXT

Columns by name. The operands of a UNION are matched by column name, not by position: an operand may list the same names in another order, and the result takes the first operand's order. (Whether the standard also allows another order is still to be checked; gql() takes the permissive reading.) UNION removes duplicate rows with GQL's equality, as DISTINCT does (1 and 1.0 are one value, DISTINCT); which of two equal rows is kept is unspecified.

g.gql("RETURN 1 AS x UNION RETURN 1.0 AS x").to_list()   // #{"x": 1}: one row
g.gql("RETURN 1 AS x UNION ALL RETURN 1.0 AS x").to_list()   // #{"x": 1}, #{"x": 1.0}

Per operand. Each operand is a query of its own: its variables are its own, and its ORDER BY, OFFSET and LIMIT apply to it before the union. The rows of a union come in no defined order: the operands' rows are not interleaved in any documented way, so an order within an operand is not an order of the result. Sort or page the whole union after NEXT.

NEXT passes on the columns, not the variables. After NEXT the next statement sees the RETURN columns of the statement before it as its variables and nothing else; an element column is the live element, so a MATCH after NEXT continues from it. NEXT after one plain query is that query with a WITH of the same items, so it gives the same rows and the same plan; after a UNION the union's rows are the input. The order a RETURN .. ORDER BY makes before NEXT is not kept by later clauses (Ordering): sort in the last RETURN.

CALL subqueries

Per row, joined. A CALL runs its body once for each incoming row, with the imported variables set to the row's values, and each row the body returns extends the incoming row: an incoming row with three results becomes three rows, one with none is dropped (OPTIONAL CALL keeps it once, the returned names NULL). A body that aggregates without grouping keys always returns one row (count 0, collect_list []), so it never drops a row. The body's DISTINCT, ORDER BY, OFFSET and LIMIT apply to one row's results: ORDER BY .. LIMIT k in a body is the top k per row, which a LIMIT of the whole query cannot express.

g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[:knows]->(f) RETURN f.name AS friend ORDER BY f.age DESC LIMIT 1 } RETURN p.name AS who, friend").to_list()   // #{"friend": "josh", "who": "marko"}
g.gql("MATCH (p:person) OPTIONAL CALL (p) { MATCH (p)-[:knows]->(f) RETURN f.name AS friend ORDER BY f.age DESC LIMIT 1 } RETURN p.name AS who, friend ORDER BY who").to_list()
// josh (), marko josh, peter (), vadas ()

Imports. The body reads only what it imports: CALL (a, b) names them, CALL (*) takes every variable in scope, CALL { } and CALL () { } take none, and Cypher's importing WITH names them as the body's first clause (Cypher Aliases). A name the body binds that is also an outer name it did not import is a new variable of the body: MATCH (p) CALL { MATCH (p)-->(x) RETURN x } matches every p in the body, for every outer row. An imported NULL (from an OPTIONAL MATCH) matches nothing in the body's patterns, as in EXISTS.

An uncorrelated body still runs per row. A body that imports nothing gives the same rows for every incoming row, but gql() does not cache them yet: it runs once for each row, so its cost multiplies with the rows before the CALL. Put such a CALL first, or compute the value once with a WITH before the MATCH that multiplies the rows:

g.gql("MATCH (p:person) CALL { MATCH (s:software) RETURN count(s) AS n } RETURN p.name AS who, n ORDER BY who").to_list()   // four rows with n 2: the count ran four times
g.gql("CALL { MATCH (s:software) RETURN count(s) AS n } MATCH (p:person) RETURN p.name AS who, n ORDER BY who").to_list()   // the same rows: the count ran once

Not lazy inside one row. A CALL builds all the results of its body for one incoming row before the first of them moves on (Gremlin's flat_map()), so a LIMIT after the CALL stops the incoming rows, not a body run that has started: MATCH (p) CALL (p) { MATCH (p)-->{1,}(x) RETURN x } RETURN x LIMIT 1 still finds every x of the first p. Bound the body itself with its own LIMIT when only a few results per row are needed. The rows the body builds count against the resource limits like any other traversers.

Labels in the body stay in the body. Variables the body binds and does not return are gone after it; reading one is an error, as for a subquery. Returned names must be new names.

Calls of saved queries

CALL folder.name(args) [YIELD ..] (Calling saved queries) runs a saved GQL query as a query of its own for each incoming row, like a CALL { } body that imports nothing; Neo4j's procedures are its model, with these differences, each a deliberate decision:

  • Constant arguments. An argument is a constant or a $parameter (lists, maps and arithmetic of them included), evaluated once when the query is compiled; Neo4j also takes expressions over the row. So arity, types and missing parameters are errors before the run, and the called query is planned once with its argument values. An argument that reads the row is 0A000 (not yet).
  • Saved GQL queries only. A procedure is a saved query of the graph's catalog written in GQL; one written in Rhai is 0A000 (call it with g.query(..) from the DSL), and the vendor namespaces db, dbms, apoc and gds are refused (CALL db.labels()).
  • Names are unique across folders. The folder of CALL a.b.name() must be a/b exactly (CALL name() is the root folder); since a saved query's name is unique in the whole catalog, a name found in another folder is an error with a "did you mean", never a second procedure.
  • Positional order. The arguments bind the parameters in the order the saved query first reads them (g.get_query(name)["params"]), not in a declared signature order.
  • Schema coercion. An argument is checked and coerced by its parameter's schema, as a write is: an integer passed for a number parameter arrives as a float (42 becomes 42.0), where Neo4j's NUMBER keeps the integer.
  • No commit attribute. The called query's writes are part of the calling query's one unit; unlike g.query(..) of a query that writes, the commit carries no attribute naming the saved query and its arguments.
  • Not inside EXISTS, COUNT or COLLECT yet. A call stands wherever a clause stands, also in CALL { } bodies and UNION operands, but not yet in those subquery bodies (0A000).
g.define_query(#{name: "sw", language: "gql", body: "MATCH (s:software) RETURN s"});
g.define_query(#{name: "half", language: "gql", params: #{x: "number"}, body: "RETURN $x AS x, $x / 2 AS h"});
g.gql("CALL sw() YIELD s RETURN s.name AS n, labels(s) AS l ORDER BY n").to_list();
// [#{"l": ["software"], "n": "lop"}, #{"l": ["software"], "n": "ripple"}]
g.gql("CALL sw() YIELD s MATCH (s)<-[:created]-(p) RETURN s.name AS s, count(p) AS n ORDER BY s").to_list();
// [#{"n": 3, "s": "lop"}, #{"n": 1, "s": "ripple"}]: a yielded node starts a later pattern
g.gql("CALL half(5)").to_list();   // [#{"h": 2.5, "x": 5.0}]: the integer 5 arrives as 5.0

Writes

What a row sees. Each clause sees every write of the clauses before it, for all rows; within one clause the rows are processed in order and each row sees the writes of the rows before it. This is Neo4j's behaviour for every case the openCypher tests check. It follows from the executor, which runs a plan step at a time: a write step starts only after the read steps before it consumed their whole input. So a query never matches what it is creating (the "Halloween problem"): MATCH (n) INSERT (:X) creates exactly one node per node that existed before, MATCH (a)-[e]->(b) INSERT (a)-[:copy]->(b) exactly one edge per existing edge, and FOR i IN range(1, 3) MATCH (n) INSERT (:Y) three per node, because each row's MATCH ran before any INSERT. No barrier step is added to the plan for this.

g.gql("MATCH (a)-[e]->(b) INSERT (a)-[:copy]->(b)").iterate();
g.e().has_label("copy").count().next()   // 6

One element per row. A plan that writes never merges traversers into one with a higher bulk, and a write step treats a traverser of bulk n as n rows: each row creates its own elements.

Values are read before the write. A value a row carries (WITH n.age AS a, LET, a RETURN column, an aggregate) is computed when the row is built; elements stay live, so RETURN n.k after a write reads the new state, as in Neo4j.

NULL is never stored. INSERT ({k: NULL}) stores no k, and SET n.k = NULL removes k; reading it gives NULL again. A null stored by Gremlin (property("k", ())) also reads as NULL in GQL.

Permissions. INSERT asks Create on the labels it creates, exactly like add_v(labels) / add_e(label), and nothing for the properties of the new element. Gremlin's add_v(..).property(..) asks Create and Update (the check runs on the plan as written, before the optimizer folds the property into the creation), so a policy that denies only Update allows the INSERT and refuses its Gremlin twin (Writing with GQL). SET and REMOVE ask exactly what their Gremlin twins property(), remove_property(), add_label() and drop_label() ask: Update on Data(vertex) for a node target, whatever labels its pattern names (a node's label set can hold more labels than the pattern tests, and a label item changes it), Update on Data(edge "label") for an edge whose pattern names its labels, and Update on any element when the kind is known only at run time (an item of a FOR list, a WITH column of a list).

Where writes differ from Neo4j:

Neo4jgql()Why
a property value must be a scalar or a list of scalars of one kind; a map, a list of mixed kinds, a nested list or a NULL inside a list is a type errorstored as given: maps, mixed and nested lists (a NULL inside a list stays in the list)Graphersal's data model stores JSON-like values (jpath keys); a schema restricts a property's type where wanted
CREATE requires WITH between a write and a following MATCH (Cypher 5)MATCH may follow INSERT directlyGQL's linear statements allow it, as Neo4j's Cypher 25 does
SET n = NULL / SET n += NULLan error (22004) whose help names SET n = {} and coalesce($map, {})a NULL map is more often a missing parameter than a wish to remove every property; an error can be relaxed later without changing a query that works, the opposite would silently start removing properties. GQL's own item takes a braced map only: standard GQL has no SET n = NULL form, so the error is our choice for the compatibility form
SET of a list of maps, a map, or a list of mixed kinds is a type errorstored as given, as for INSERTas above
RETURN n of a node deleted earlier in the query returns itan error whose help shows WITH n, properties(n) AS p DETACH DELETE n RETURN p (DELETE)a deliberate deviation (user decision): a returned deleted node would carry no id, labels or properties Graphersal could give, and a silent empty value hides the mistake
a plain DELETE of a node that still has edges is checked when the transaction commits: MATCH (n)-[r]-() DELETE n DELETE r workschecked per clause, before the clause removes anything (G1001): delete the edges in the same clause (DELETE r, n) or use DETACH DELETEa query is one unit, but each clause states its own result; a per-clause check fails at the clause that is wrong, never later

SET and REMOVE

Items run left to right. The items of one SET or REMOVE clause run in the order written, for each row in turn, and each item sees the changes of the items before it: SET n.c = 1, n.c = n.c + 1 leaves 2. The same item may be written twice; the last one wins. The value of an item is computed when the item runs, from the row and the current state of the graph.

g.gql("MATCH (p:person {name: 'marko'}) SET p.n = 1, p.n = p.n + 1 RETURN p.n AS n").to_list()   // #{"n": 2}

NULL removes. A property item whose value is NULL removes the property (it is never stored as NULL), and so does a NULL value in the map of SET n = {..} and SET n += {..}.

= replaces, += merges. SET n = {..} evaluates the whole map and checks every value before it writes: then it removes every property the map does not name and sets the others. SET n += {..} sets the keys of the map and keeps the rest. A node or an edge on the right stands for its properties, read before the first write (so SET n = n changes nothing); another value that is not a map is an error (22G03), and a NULL map is an error (22004).

The target. A target that is NULL (a variable an OPTIONAL MATCH left NULL) makes the item a no-op for that row, whatever its right side: the right side is not evaluated. A target that holds a value which is not a node or an edge is an error (22G03); a target removed before the item runs fails the query, as the element no longer exists.

g.gql("OPTIONAL MATCH (p:person {name: 'nobody'}) SET p.k = 1 / 0 RETURN p").to_list()   // #{"p": ()}
g.gql("FOR x IN [1] SET x.k = 1")   // error: the target holds a value, not a node or an edge

Labels. A label item adds or removes each name in order. Adding a label the node has and removing one it lacks change nothing; the last label may be removed (the node then has none). An edge has exactly one label: a label item on it is an error before the run (42002) when the pattern declares the variable as an edge, and at run time (22G03) when only the row knows it, like add_label() on an edge.

g.gql("MATCH (s:software {name: 'ripple'}) REMOVE s:software RETURN labels(s) AS labels").to_list()   // #{"labels": []}

What a row sees is as for INSERT (Writes): a value a row carried before the clause (WITH n.age AS old) keeps its value, while the element itself is live, so RETURN n.k reads the new state. A clause before the SET has found all its rows before the SET runs, so a SET never changes which rows an earlier MATCH matched; a LIMIT 0 after the SET still lets it run for every row.

DELETE

Targets. Each expression of a DELETE clause is evaluated per row and gives what the clause removes: a node, an edge, every node and edge of a path, or the items of a list (nested lists too). NULL (also inside a list) is skipped. A value of another kind is an error: before the run (42002) when the expression cannot give an element (a literal, arithmetic, a comparison), at run time (22G03) when only the row shows it (a WITH value, a list item). A label test (n:L, n IS L) is a syntax error (42001), since REMOVE n:L removes a label.

One clause, all rows. The clause collects the targets of every row that reaches it, each element once (deleting the same element on several rows, or twice in one row, is no error, and an element an earlier clause removed is skipped), then removes the edges, then the nodes.

NODETACH is checked per clause. Without DETACH, every node to remove must have no edges except those the same clause removes; the check covers the whole clause before anything is removed, so a failing check leaves the graph as it was and fails the query (G1001). DETACH DELETE removes the edges of each node first.

g.gql("MATCH (a)-[r]-(b) DELETE r, a, b RETURN count(*) AS n").to_list()   // #{"n": 12}
g.gql("MATCH (n:person {name: 'marko'}) DELETE n")   // error: G1001, the node still has edges

Reading a deleted element is an error. After the clause, a property, labels(), element_id(), keys(), properties(), an endpoint or a sort key of a deleted element fails the query (the root cause is the storage's "element removed"), never a silent NULL or empty value. Returning the element itself fails too (RETURN n, a path holding it, also when a LIMIT 0 follows, since the RETURN builds each row before the LIMIT counts it). Three reads still work: count(n), n IS NULL (false: the variable holds a deleted element), and type(e) of a deleted edge, which gives the label it had (the openCypher tests expect it). A pattern that walks from a deleted node finds no edges. Values computed before the DELETE keep their value: a WITH n, n.age AS age before it is evaluated before the clause runs.

g.gql("MATCH (p:person {name: 'vadas'}) WITH p, p.age AS age DETACH DELETE p RETURN age, p IS NULL AS gone").to_list()   // #{"age": 27, "gone": false}
g.gql("MATCH (p:person {name: 'vadas'}) DETACH DELETE p RETURN labels(p) AS l")   // error: the node was deleted earlier in this query

A deliberate deviation from Neo4j: Neo4j returns a node or relationship deleted earlier in the same query from RETURN n; gql() fails the query with a help naming the properties(n) pattern (see the table in Writes). An error can be relaxed later without changing a query that works.

MERGE

MERGE is a compatibility form with Neo4j Cypher 25's meaning, checked against the openCypher TCK's clauses/merge scenarios (TCK Compliance).

One pattern. A clause holds one path pattern; a second after , is a syntax error (42001). Node labels are conjunctions only (:A:B, :A&B, IS A & B); an edge has exactly one label, no quantifier, no inline WHERE, and no $parameter stands for a whole property map. A path variable (MERGE p = ..) is a new variable holding the found or the created path.

Match or create, per row. For each row the clause searches the whole pattern, with GQL = on the properties (so 1 finds 1.0), label-set containment (a node with more labels than the pattern names is found) and trail semantics (each edge at most once per match). Every match is a row: two matching nodes give two rows. When nothing matches, the whole pattern is created, the variables bound before reused and every other element new; the row continues with exactly one record.

NULL is an error. A pattern property whose value is NULL on a row fails the query with 22004 when that row runs, before the search: MERGE can neither find nor store a NULL value. The check is at run time, also for a literal NULL, as the TCK expects.

Either direction. MERGE (a)-[:T]-(b) finds an edge in either direction (a found edge in each direction is a row of its own) and creates one from left to right, a to b. Directed edges are found and created as written.

Rows see earlier rows. The rows run in order, one at a time, and each row's search sees what the rows before it created: FOR x IN [1, 1] MERGE (:N {x: x}) creates one node, and a second row matching the first row's creation runs ON MATCH. Within a clause this is the only uniqueness MERGE gives (there is no constraint); it is race-free because one query is one unit under the write lock. The search runs inside the write step, row by row, so unlike a MATCH before a write (Writes) it sees the clause's own earlier creations.

g.gql("FOR x IN [1, 1, 2] MERGE (n:N {x: x}) RETURN count(*) AS rows, count(DISTINCT n) AS nodes").to_list()   // #{"nodes": 2, "rows": 3}

ON CREATE SET and ON MATCH SET. Any number of each, in any order; they apply in the order written, each in its case, with the rules of SET (items left to right, NULL removes). They read the pattern's variables and every variable bound before. They run after the creation, as a second write in the same unit: the schema checks the created element before them (Writing with GQL).

Bound variables. A node variable bound before is a reference only, (a): new labels or properties on it, a bound edge variable, and a pattern that is only a bound node are refused before the run (42002). After WITH a AS x, a is a new name and finds any node.

Schema defaults. A created element gets the schema's create-time defaults and its write-time coercion, exactly as an INSERT of the pattern.

Where MERGE differs from Neo4j:

Neo4jgql()Why
a property existence constraint is checked when the transaction commits, so ON CREATE SET n.k = .. satisfies ita required property of the schema is checked when the element is created, before the ON CREATE SET items: give it in the pattern's mapthe schema checks each write; a later item is a second write in the same unit (Writing with GQL)
two concurrent MERGEs of the same pattern may both create, unless a uniqueness constraint holdsnever: a query writes under the write lock, and each row sees the rows before itone query is one unit; Graphersal has no concurrent writers
no permission model on the clauseasks Create per label it can create and Update for its ON items before it runs, also when every row would only find; then the Reads of its searchthe check sees the plan before anything runs (Writing with GQL)

Static kind checks

When the kind of an operand is certain from the query text and its place never takes that kind, gql() refuses the query before it runs, with error 22G03, also on an empty graph and behind a short-circuit AND / OR, as Neo4j does (stage 3f, the openCypher TCK). The kind is certain for a literal (and a list or map of literals), a node, edge or path variable of a pattern (or a WITH column holding one), a LET / WITH value computed from those, a comprehension variable over such a list (its items' kind), and the results of operators and of functions with a fixed result kind (size() is an integer, labels() a list of strings, nodes() a list of nodes). The checked places:

  • a condition (WHERE, FILTER, AND, OR, XOR, NOT, a comprehension's WHERE, a WHEN of a searched CASE) takes a boolean: false AND 123, NOT 'x', WHERE (n);
  • IN takes a list on its right: 1 IN true;
  • arithmetic (- * / % ^, a sign) takes numbers: 'a' % 2 (a NULL operand makes it NULL first);
  • a property is read from a node, an edge or a map: p.name of a path, x.num of WITH 123 AS x;
  • type() takes an edge, labels() / element_id() a node or an edge, length() a path, size() a string or a list, keys() / properties() a node, an edge or a map, upper() / lower() / char_length() a string; a label test a node or an edge; a map projection a node, an edge or a map.

A $parameter is never looked at: its kind counts as unknown, so a query is accepted or refused whatever the parameter values are (a wrong one fails when a row reaches it). A NULL literal is never refused (NULL AND TRUE is NULL).

g.gql("RETURN false AND 123 AS x").to_list()   // error: AND takes booleans, not an integer (22G03), before the run
g.gql("MATCH (n) RETURN type(n) AS t").to_list()   // error: type() takes an edge, not a node, also on the empty graph
g.gql("MATCH p = (a)-->(b) RETURN size(p) AS s").to_list()   // error: size() takes a string or a list, not a path; length(p) counts its edges
g.gql("WITH 123 AS x RETURN x.num AS y").to_list()   // error: cannot read the property `num` of an integer
g.gql("RETURN none(x IN ['a'] WHERE x % 2 = 0) AS r").to_list()   // error: arithmetic needs numbers, not a string
g.gql("RETURN 1 IN [1, 2] AS a, NULL AND TRUE AS b").to_list()   // #{"a": true, "b": ()}

Type errors surface at evaluation time

Where the kind of an operand is not certain from the query text (a property value, a $parameter, an item of a list of mixed kinds, a FOR item), an operand of the wrong kind is a type error (22G03) when a row reaches the expression, and a query whose rows never reach it raises nothing. IN with a right operand that is not a list (nor NULL) is such an error too (1 IN $p with $p = 3):

g.gql("MATCH (n) RETURN n.k AND true AS x").to_list()   // [] on the empty graph: no row reaches the expression
g.gql("MATCH (p:person) RETURN p.name AND true AS x").to_list()   // error: AND takes booleans, not a string (22G03), when the first row reaches it

A deliberate deviation from Neo4j: Neo4j may reject more queries at compile time with a SyntaxError or TypeError (InvalidArgumentType), from the static types of its own type system. Graphersal checks only the kinds that are certain from the query text (Static kind checks), which covers every such case of the openCypher TCK; any other wrong kind fails when a row reaches it. Errors that do not depend on a row (syntax, unknown variables, misplaced aggregates, the static kind checks) are raised before the run, as always (Errors).

Parameters are bound when the query is compiled

The parameters of gql_with() are bound when the query is compiled into its traversal, before any row exists. So a $parameter of OFFSET / SKIP / LIMIT whose value is negative (22G02) or not an integer (22G03) is refused before the run, also on a graph whose query would return no row:

g.gql("MATCH (n:person) RETURN n.name AS name LIMIT $n", #{n: -1}).to_list()   // error: LIMIT must be a non-negative integer, but $n is negative (22G02)
g.gql("MATCH (n:person) RETURN n.name AS name ORDER BY name LIMIT $n", #{n: 2}).to_list()   // #{"name": "josh"}, #{"name": "marko"}

A deliberate deviation from Neo4j: the openCypher TCK expects this SyntaxError at runtime. The user sees the same thing, an error before any row; the six TCK cases are excluded from the measured scope with this reason (TCK Compliance). A constant expression in their place (LIMIT 1 + 1) is evaluated at the same time (ORDER BY, OFFSET, LIMIT).

Comparisons across types

Numbers compare by value across integers and floats (1 = 1.0 is TRUE). Strings, booleans, UUIDs and dates compare within their own kind. Comparing values of different kinds is never an error and never a conversion: = is FALSE and <> TRUE (a number is not equal to a string), while the orderings <, <=, >, >= are NULL (a number is neither smaller nor larger than a string). A NULL operand gives NULL for every operator:

g.gql("MATCH (n) RETURN n.name AS n, n.age > 'a' AS cmp ORDER BY n LIMIT 2").to_list()   // #{"cmp": (), "n": "josh"}, #{"cmp": (), "n": "lop"}
g.gql("RETURN 1 = '1' AS a, [1] <> 1 AS b, 1 IN ['1'] AS c, 1 < 'a' AS d").to_list()   // #{"a": false, "b": true, "c": false, "d": ()}

= and <> also compare lists (item by item, three-valued: [1, 2] = [null, 'foo'] is FALSE because 2 and 'foo' differ, [1, 2] = [null, 2] is NULL), maps (key by key) and elements (the same vertex or edge). Lists are also ordered, lexicographically: the first pair of items that is not equal decides, a NULL (or incomparable) pair reached first makes the result NULL, and a list that is a prefix of the other is the smaller one:

g.gql("RETURN [1, 2] < [1, 3] AS a, [1, null] >= [1] AS b, [1, 2] >= [1, null] AS c, [1, 2] >= [3, null] AS d").to_list()   // #{"a": true, "b": true, "c": (), "d": false}

Maps, elements and paths are not ordered (NULL); ORDER BY still sorts them (Ordering).

Floats follow IEEE 754. A float divided by zero is not an error: 1.0 / 0.0 is Infinity, -1 / 0.0 is -Infinity, 0.0 / 0.0 and 1.0 % 0.0 are NaN; an integer divided by zero stays error 22012, and a float result that overflows from finite operands (1.0e308 * 10) stays error 22003. NaN equals nothing, itself included (NaN = NaN is FALSE, NaN <> 1 TRUE), and every ordering of NaN against a number is FALSE (NaN > 1, NaN <= NaN); against another kind it is NULL (NaN > 'a'):

g.gql("WITH 0.0 / 0.0 AS n RETURN n = n AS a, n <> n AS b, n > 1 AS c, n > 'a' AS d, toString(1.0 / 0.0) AS e, toString(n) AS f").to_list()   // #{"a": false, "b": true, "c": false, "d": (), "e": "Infinity", "f": "NaN"}
g.gql("RETURN 1 / 0 AS x").to_list()   // error: division by zero (22012)

The playground and the dev server show such a value as NaN, Infinity or -Infinity; JSON output writes it as a GraphSON typed double (Displaying Results).

These rules follow Neo4j and the openCypher TCK, where ISO GQL calls a comparison of different kinds "not comparable" and raises 22012 for a division by zero of every numeric type (differences from the standard).

No value is ever turned into text implicitly: 'a' + 1 is an error, not 'a1' (Neo4j converts here; Graphersal does not). Convert explicitly: 'a' || toString(1) or 'a' || CAST(1 AS STRING) (Conversions).

Aggregation

The aggregates follow GQL and, where the standard text could not be checked yet, Neo4j:

  • NULL is skipped by every aggregate except count(*), which counts rows.
  • Typing. sum of integers is an integer, and an overflow is an error (22003), never a wrap; one float makes it a float. avg is always a float. sum and avg of a non-number (a string, a list) are an error (22G03); count and collect_list take any value.
  • min / max compare across kinds in the order of ORDER BY (strings before numbers), never an error.
  • Empty input. Without grouping keys, an aggregation of no rows still returns one row: count 0, sum 0, collect_list [], avg / min / max NULL (Neo4j's values; ISO GQL, from SQL, may give NULL for sum: provisional). With grouping keys there is no group, so no row.
  • Reusing a key. An aggregating item may read a grouping key outside its aggregates by repeating it when the key is a variable or a property (RETURN p.age, p.age + count(*)), not when it is computed (RETURN a.age + b.age, a.age + b.age + count(*) is an error, 42002, as in Neo4j: the item reads a and b, which are no keys). Compute such a key in a WITH first and read it by name.
  • Group order is unspecified (today: the order in which the groups first appear); write ORDER BY.
  • GROUP BY after the RETURN items lists the grouping keys explicitly; grouping stays implicit, so it changes nothing in the result. A key names a column (GROUP BY name) or, beyond ISO GQL's references to variables, repeats an item's expression (GROUP BY p.name for RETURN p.name AS name, ...).
g.gql("MATCH (n) RETURN count(n.age) AS ages, count(*) AS rows, collect_list(n.lang) AS langs").to_list()
// #{"ages": 4, "langs": ["java", "java"], "rows": 6}
g.gql("MATCH (n:person) RETURN sum(n.age) AS i, sum(n.age * 1.0) AS f, avg(n.age) AS a").to_list()   // #{"a": 30.75, "f": 123.0, "i": 123}
g.gql("MATCH (n) RETURN min(coalesce(n.age, n.lang)) AS lo, max(coalesce(n.age, n.lang)) AS hi").to_list()   // #{"hi": 35, "lo": "java"}
g.gql("MATCH (n:robot) RETURN count(*) AS n, sum(n.age) AS s, avg(n.age) AS a, collect_list(n) AS l").to_list()
// #{"a": (), "l": [], "n": 0, "s": 0}
g.gql("MATCH (n:robot) RETURN n.name AS name, count(*) AS c").to_list()   // no rows
g.gql("MATCH (n:person) RETURN sum(9223372036854775807) AS s")   // error: numeric value out of range (22003)

Gremlin differs here: values("age").sum() of nothing gives no result, count() counts what reaches it (Gremlin has no NULL property), and min() of mixed kinds is an error.

DISTINCT and grouping equality

RETURN DISTINCT, WITH DISTINCT, grouping keys and DISTINCT inside an aggregate use GQL's equality: numbers are equal by value across integers and floats (1 and 1.0 are one value), and NULLs are equal to each other (they form one group). The value kept for a group is the first that arrives. Gremlin's dedup() keeps 1 and 1.0 apart:

g.gql("MATCH (p:person) RETURN DISTINCT CASE WHEN p.age > 30 THEN 1 ELSE 1.0 END AS one").to_list()   // one row
g.v().has_label("person").map(__.choose(__.has("age", P.gt(30)), __.constant(1), __.constant(1.0))).dedup().to_list()   // 1.0, 1: two values
g.gql("MATCH (n) RETURN n.lang AS lang, count(*) AS c ORDER BY lang").to_list()   // #{"c": 2, "lang": "java"}, #{"c": 4, "lang": ()}

Indexing and slicing

x[i], x[a..b], m[k] and n[k] are Cypher forms with their Neo4j meaning (the openCypher TCK List1, List2, Map2 and Graph7 cases pass):

  • A list index is an integer counted from 0; a negative one counts from the end (-1 is the last item). An index outside the list gives NULL, never an error. A float index is an error even when it is whole (x[1.0]), and so is a string, a boolean, a list or a map: convert with toInteger(i).
  • A slice x[a..b] takes the items from a up to b, b excluded. A bound left out is the start (x[..b]) or the end (x[a..]); a negative bound counts from the end; bounds are clamped to the list, so [1, 2, 3][-5..5] is the whole list; a >= b gives []. A bound written as NULL (or a parameter that is NULL) makes the slice NULL.
  • A map is read with a string key (case-sensitive; missing: NULL); a node or an edge with a string property key (missing: NULL). n['name'] with a string literal is exactly n.name.
  • NULL as the list, map, element, index or bound gives NULL.
  • Other kinds of value are not indexable: a string, a number, a boolean or a path gives 22G03 (a string is no list in GQL; use substring()). These errors arise when a row reaches the expression (Type errors surface at evaluation time).
g.gql("RETURN [1, 2, 3][-5..5] AS a, [1, 2, 3][3..1] AS b, [1, 2, 3][1..NULL] AS c, {Name: 1}['name'] AS d").to_list()
// #{"a": [1, 2, 3], "b": [], "c": (), "d": ()}
g.gql("RETURN [1, 2, 3][1.0] AS x")   // error: a list index is an integer, not a float

FOR: NULL and values that are not lists

FOR x IN list (and UNWIND list AS x, one meaning for both spellings) gives one row per item in the list's order. For a list expression that is not a list, Graphersal follows Neo4j (the ISO text is still to be checked; GQL may make it a type error):

  • NULL (a missing property included) gives no row, like the empty list [];
  • any other value that is not a list (a number, a string, a map, a vertex) gives one row of that value.
g.gql("FOR x IN null RETURN x").to_list()   // no row
g.gql("FOR x IN 5 RETURN x").to_list()   // #{"x": 5}
g.gql("MATCH (p:person) FOR t IN p.tags RETURN count(*) AS c").to_list()   // #{"c": 0}: no person has tags
g.gql("FOR x IN [1, null, [2, 3]] RETURN x").to_list()   // #{"x": 1}, #{"x": ()}, #{"x": [2, 3]}: NULL items and nested lists are items

WITH ORDINALITY i numbers the items from 1, WITH OFFSET i from 0; both count the position in the list, not the row: the numbers start again for every row the FOR reads. A row keeps its multiplicity: a list item of a row that occurs twice gives two rows.

g.gql("MATCH (p:person) WHERE p.age < 30 FOR x IN ['a', 'b'] WITH OFFSET i RETURN p.name AS name, x, i ORDER BY name, i").to_list()
// marko a 0, marko b 1, vadas a 0, vadas b 1

Lookups use GQL equality

An item compared with a property or an element id (FOR n IN $names MATCH (p:person {name: n}), WHERE element_id(n) = id) may run as a direct lookup by id or index instead of a scan (Plans and Performance). The lookup keeps GQL's = exactly, whichever way it runs: 29.0 finds the age 29, the string '29' does not, and a NULL item finds nothing.

{ g.create_index(#{label: "person", key: "age"}); g.gql("FOR a IN [29.0, '27', null] MATCH (p:person {age: a}) RETURN a, p.name AS name").to_list() }   // #{"a": 29.0, "name": "marko"}
g.gql("FOR a IN [29.0, '27', null] MATCH (p:person {age: a}) RETURN a, p.name AS name").to_list()   // the same row without the index

WITH: the order of its sub-clauses

The sub-clauses of a WITH run in this order: the items (and their aggregation), DISTINCT, ORDER BY, OFFSET / SKIP, LIMIT, and last the WHERE. So WITH p ORDER BY p.age LIMIT 3 WHERE p.age > 28 takes the three youngest and then filters them (Cypher's order; to be checked against the ISO text). The WHERE sees the variables before the WITH too, as in Neo4j: their elements are still on the row (a projecting WITH keeps it, ORDER BY / OFFSET / LIMIT keep its elements); with DISTINCT it filters before the rows are folded, since one folded row stands for many; after an aggregation only the keys and aggregates remain. A WITH that only passes values on (no DISTINCT, aggregate, ORDER BY, OFFSET or LIMIT) changes nothing in how the query runs; it only limits the names in scope.

Either direction and self-loops

-[e]- matches an edge pointing either way. A self-loop (an edge from a vertex to itself) matches once, not once per direction, as in GQL and Neo4j; Gremlin's both() sees it twice:

g.add_v("node").property("name", "a").as("a").add_e("link").to("a").iterate();
g.gql("MATCH (x)-[e:link]-(y) RETURN x.name AS x, y.name AS y").to_list()   // #{"x": "a", "y": "a"}: one row
g.add_v("node").property("name", "a").as("a").add_e("link").to("a").iterate();
g.v().both("link").values("name").to_list()   // "a", "a": two

Ordering

  • Without ORDER BY the row order is unspecified: it may change with the data, the plan or the version. Write ORDER BY whenever the order matters (every example in this chapter does).
  • NULL sorts last ascending and first descending (Neo4j's rule; GQL leaves it to the implementation). NULLS FIRST / NULLS LAST are not supported yet.
  • Only the final ORDER BY orders the result. The order of a WITH ... ORDER BY decides what its OFFSET / LIMIT keep, but later clauses do not preserve it.
  • Values of different types sort by type first, in this order (Neo4j's global order where Graphersal has the type): map, vertex, edge, list, date/time, UUID, string, boolean, number, vector, NULL. Within a type: numbers by value, strings by code point, elements by id, lists item by item and then by length.
  • The sort is stable: rows with equal keys keep their relative order.
g.gql("MATCH (n) RETURN n.name AS name, n.age AS age ORDER BY age, name").to_list()
// vadas 27, marko 29, josh 32, peter 35, lop (), ripple ()
g.gql("MATCH (n) RETURN n.name AS name, n.age AS age ORDER BY age DESC, name").to_list()
// lop (), ripple (), peter 35, josh 32, marko 29, vadas 27
g.gql("MATCH (n) RETURN coalesce(n.age, n.lang) AS v ORDER BY v").to_list()
// "java", "java", 27, 29, 32, 35: strings before numbers

Gremlin's order().by("age") drops the vertices without age; ORDER BY keeps them.

Functions

The functions (The Supported Subset) are pure: the same arguments always give the same result, so a LET or WITH name may stand for its expression anywhere. They follow these rules:

  • Characters. Every position and length counts characters (Unicode scalar values), never bytes: char_length('héllo') is 5, byte_length('héllo') is 6, and left, right, substring, reverse and split(s, '') never cut a character in two.
  • NULL in, NULL out. A function returns NULL when any argument is NULL, before it checks the kinds, except coalesce, nullif and the ...OrNull conversions. An unmatched OPTIONAL MATCH therefore gives NULL through every function.
  • Wrong kind is an error. An argument of the wrong kind fails the query (22G03), never a silent NULL (only the ...OrNull conversions turn it into NULL). An argument that must be an integer (left, substring, range, the precision of round, the n of the list trim) does not take a float.
  • No NaN or infinity from finite numbers. sqrt(-1) (2201F), ln(0) (2201E) and an exp() or power() that overflows (22003) are errors, like the arithmetic operators (whose one exception is a float divided by zero, IEEE 754: Comparisons across types). A NaN that is already stored passes through abs, floor, ceil and round unchanged, and sign(NaN) is 0. Conversions are not arithmetic: toFloat('NaN') and toFloat('Infinity') give the float values, as in Neo4j.
  • Result types. The GQL functions keep the argument's type: abs, floor and ceil of an integer are integers. round (Cypher) is always a float, sign always an integer; sqrt, exp, ln, log, log10 and power are floats; mod(a, b) is a % b, except that a float b = 0 is error 22012 (ISO MOD) where % gives NaN.
  • Bounded results. A function whose result can be larger than its arguments (range, split, replace, CAST(x AS STRING) of a list or map, and the operator ||) computes the size of the result first and asks for it against traversal.max_materialized_bytes and the memory budget, like collect_list(). A result that is too large fails the query with the limit error; it is never cut short and never runs the process out of memory (Errors).
  • No plan change. A condition with a function is evaluated by the GQL filter step and never pushed into has() or a property index: WHERE lower(n.name) = 'marko' scans the label.
g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s:software {lang: 'none'}) RETURN p.name AS name, upper(s.name) AS u, toString(s) AS t, head(s.tags) AS h ORDER BY name LIMIT 1").to_list()
// #{"h": (), "name": "josh", "t": (), "u": ()}
g.gql("MATCH (n:person {name: 'marko'}) RETURN left(n.name, 2.0) AS x")   // error: left() takes an integer length (22G03)

Conversions: strict CAST, lenient toX

GQL's CAST and Cypher's toInteger / toFloat / toBoolean / toString share one set of conversion rules and differ in what an unconvertible value gives:

CaseCAST(x AS T)toX(x)toXOrNull(x)
a text that is no value of the type ('abc' to INTEGER)error 22018NULLNULL
a value of a kind the type does not take (true to FLOAT)error 22G03error 22G03NULL
a number out of range (1.0e19 to INTEGER)error 22003error 22003NULL
a list or a map to STRINGits texterror 22G03NULL
a vertex, edge or path to STRINGerror 22G03error 22G03NULL
  • To INTEGER: a float is truncated toward zero (1.9 is 1, -1.9 is -1); a text is a decimal number, also with a fraction or an exponent, truncated the same way ('1.9' is 1, '1e3' is 1000, computed exactly, without a float in between). toInteger also reads Cypher integer literals ('0x1F' is 31, '0o11' is 9, '1_000' is 1000) and true / false as 1 / 0; CAST reads decimal text only, and a boolean is 22G03.
  • To FLOAT: a decimal number, 'NaN', 'Infinity', '-Infinity'; toFloat also reads Cypher literals. Java-only forms ('1.5f', '1d', hexadecimal floats) are not numbers.
  • To BOOLEAN: 'true' and 'false' in any letter case; CAST reads 'unknown' as NULL; toBoolean takes an integer too (0 is FALSE, every other integer TRUE), CAST does not.
  • To STRING: an integer, UUID or date gives the same text as Gremlin's as_string(); a float always shows a decimal point or an exponent, in Neo4j's (Java's) form: '1.0', '3.2', '1.0E7', '1.0E-4', '1.5E20' (plain decimal from 0.001 up to 10 000 000); booleans give 'true' / 'false'; CAST of a list or map gives Neo4j's text ('[1, a, true, null]', '{a: 1, b: hi}', strings unquoted), while toString takes scalars only, as in Neo4j (a list or map is 22G03, toStringOrNull gives NULL; stage 3f, the openCypher TCK TypeConversion4).
  • Surrounding blanks: CAST skips spaces around the text; the Cypher forms skip every character up to U+0020 (spaces, tabs, line breaks), as Java's String.trim() does, and toBoolean any Java whitespace.
g.gql("MATCH (n:person {name: 'marko'}) RETURN toString(1.0) AS a, toString(1.5e20) AS b, toString(0.0001) AS c, toString(10000000.0) AS d").to_list()
// #{"a": "1.0", "b": "1.5E20", "c": "1.0E-4", "d": "1.0E7"}
g.inject(1.0).as_string().to_list()   // "1": Gremlin's text of a float
g.gql("MATCH (n:person {name: 'marko'}) RETURN toInteger('1.9') AS a, toInteger('0x1F') AS b, toIntegerOrNull('0x1F') AS c").to_list()   // #{"a": 1, "b": 31, "c": 31}
g.inject("1.9").as_number(GType.LONG).to_list()   // error: Gremlin's as_number(GType.LONG) does not read a fraction in text
g.gql("MATCH (n:person {name: 'marko'}) RETURN CAST('0x1F' AS INTEGER) AS x")   // error: invalid character value for cast (22018)
g.gql("MATCH (n:person {name: 'marko'}) RETURN toInteger(1.0e19) AS x")   // error: out of range for an INTEGER (22003)

Rounding

round(x [, precision [, mode]]) follows Neo4j and always returns a float:

  • One argument, or precision 0 without a mode: Java's Math.round, a half rounds toward positive infinity (round(2.5) is 3.0, round(-2.5) and round(-2.5, 0) are -2.0).
  • With a positive precision, or with a mode: the shortest decimal text of x is rounded (Java's BigDecimal.valueOf), so round(2.675, 2) is 2.68 although the float 2.675 is a bit below it. The default mode is 'HALF_UP' (a half away from zero: round(-1.55, 1) is -1.6).
  • mode is one of 'UP', 'DOWN', 'CEILING', 'FLOOR', 'HALF_UP', 'HALF_DOWN', 'HALF_EVEN', written in upper case (as Neo4j, which uses Java's mode names); any other text, Java's 'UNNECESSARY' included, is 22023. A negative precision is 22023 too, and a float precision 22G03.
  • NaN and the infinities pass through. A number beyond the integer range is rounded as it is, never clamped: round(1.0e20) is 1.0e20.

Gremlin's math() has no round; the logarithm of math("log(_)") is the natural one, the same as ln(x) and the one-argument log(x). log(2, x) and log(10, x) are exact for powers of the base (log(2, 1024) is 10.0).

g.gql("MATCH (n:person {name: 'marko'}) RETURN round(-1.5) AS a, round(-1.5, 0) AS b, round(-1.5, 0, 'HALF_UP') AS c, round(1.25, 1, 'HALF_EVEN') AS d").to_list()
// #{"a": -1.0, "b": -1.0, "c": -2.0, "d": 1.2}
g.gql("MATCH (n:person {name: 'marko'}) RETURN log(2, 1024) AS a, log(10, 0.001) AS b").to_list()   // #{"a": 10.0, "b": -3.0}
g.gql("MATCH (n:person {name: 'marko'}) RETURN round(1.5, 0, 'half_up') AS x")   // error: round() has no rounding mode "half_up" (22023)

Strings: trim, split, replace

  • Trim. Every GQL trim form removes the space (U+0020) when no character is given: TRIM(s), TRIM(LEADING FROM s), trim(s), btrim(s), ltrim(s), rtrim(s). A tab or a line break stays. TRIM(c FROM s) takes exactly one character c (22027 otherwise); btrim(s, chars), ltrim(s, chars) and rtrim(s, chars) remove any character of the set chars ('' removes nothing). trim(s, x) with a string s is an error that names btrim(s, chars); trim(list, n) is GQL's list trim.
  • Split. Empty parts are kept: split('a,,b,', ',') is ['a', '', 'b', ''], and split('', ',') is ['']. An empty delimiter splits into characters (split('', '') is ['']). With a list of delimiters the text is cut at the leftmost match, and when two delimiters match at the same place the one listed first wins (split('a--b', ['-', '--']) is ['a', '', 'b'], split('a--b', ['--', '-']) is ['a', 'b']); a list containing '' splits into characters, a NULL in the list gives NULL, and [] gives [s].
  • Replace. Every non-overlapping occurrence, left to right. An empty search inserts the replacement before every character and at the end (replace('abc', '', '-') is '-a-b-c-', Java's rule). The optional fourth argument limit (Neo4j 2025.06) replaces at most that many occurrences, from the left (0 changes nothing, a negative limit is 22023).

Gremlin's string steps differ in these places, so the same-named Gremlin step is a twin only for plain inputs:

g.gql("MATCH (n:person {name: 'marko'}) RETURN split('a,,b', ',') AS s").to_list()   // #{"s": ["a", "", "b"]}
g.inject("a,,b").split(",").to_list()   // ["a", "b"]: Gremlin drops the empty part
g.gql("MATCH (n:person {name: 'marko'}) RETURN replace('abc', '', '-') AS r").to_list()   // #{"r": "-a-b-c-"}
g.inject("abc").replace("", "-").to_list()   // "abc": Gremlin leaves the text unchanged
g.gql("MATCH (n:person {name: 'marko'}) RETURN trim(' \t a \t ') AS t").to_list()   // the tabs stay: "\t a \t"
g.inject(" \t a \t ").trim().to_list()   // "a": Gremlin's trim() removes all whitespace

Regular-expression match

s =~ pattern (a compatibility form) matches the whole string: the pattern is compiled as ^(?:pattern)$, so 'marko' =~ 'ar' is FALSE and 'josh' =~ 'mark|jos' is FALSE (the alternation is anchored as a whole). Three-valued: a NULL operand gives NULL, and so does an operand that is no string (1 =~ '1', '1' =~ 1), as for STARTS WITH. A literal or $parameter pattern is compiled once, when the query is compiled, so an invalid one is error 2201B before any row; a pattern computed per row (n.name =~ m.pattern) is compiled when a row reaches it, the last one compiled kept for the next rows, and an invalid one fails that row's evaluation (2201B).

g.gql("MATCH (n:person) WHERE n.name =~ 'ar' RETURN n.name AS name").to_list()   // no rows: the whole string must match
g.gql("MATCH (n:person) WHERE n.name =~ '.*ar.*' RETURN n.name AS name").to_list()   // #{"name": "marko"}
g.gql("RETURN NULL =~ 'a' AS a, 'a' =~ NULL AS b, 1 =~ '1' AS c").to_list()   // #{"a": (), "b": (), "c": ()}

Elements and paths

  • startNode(e) / endNode(e) are the edge's stored source and target, independent of the direction the pattern was written in: MATCH (a)-[e]-(b) binds a to either end, while startNode(e) is always the source. n IS SOURCE OF e and n IS DESTINATION OF e test the same (TRUE, FALSE, or NULL when an operand is NULL).
  • keys(x) / properties(x) of a vertex or edge list its properties in stored order; a property stored as null is no key, as x.key reads it as NULL anyway. Labels never appear (labels(x) lists them). keys() of a map keeps a key whose value is NULL (keys({a: 1, b: NULL}) is ['a', 'b'], as in Neo4j); properties() of a map is the map.
  • nodes(p) / relationships(p) follow the path in the written order of the pattern; an edge matched against its direction (-[e]-) keeps its stored direction. A zero-length path gives one vertex and []; the NULL path of an unmatched OPTIONAL MATCH gives NULL.
g.gql("MATCH (a)<-[e:knows]-(b) RETURN a.name AS a, startNode(e).name AS s, endNode(e).name AS t ORDER BY a").to_list()
// #{"a": "josh", "s": "marko", "t": "josh"}, #{"a": "vadas", "s": "marko", "t": "vadas"}
g.gql("MATCH p = (a {name: 'marko'})-[*0..1]->(b) RETURN b.name AS b, size(nodes(p)) AS n, relationships(p) AS r ORDER BY n, b LIMIT 2").to_list()
// #{"b": "marko", "n": 1, "r": []}, #{"b": "josh", "n": 2, "r": [e[2][1-knows->4]]}

Where functions differ from Neo4j

The compatibility functions keep Neo4j's meaning, and the GQL functions follow GQL. These are the places where a query gives a different answer than in Neo4j, each deliberate:

Neo4jgql()Why
toInteger(1.0e19) saturates to the largest integer; toInteger(NaN) is 0error 22003a silent wrong value is worse than an error; toIntegerOrNull gives NULL
toFloat('1e400') is Infinityerror 22003 (toFloatOrNull: NULL)the same rule for both targets
toString(n) of a node, relationship or path gives vendor text ('(:A:B)')error 22G03 naming element_id(x), properties(x) or RETURN pNeo4j's element text is vendor-specific
CAST does not exist (toInteger and friends are the alternatives)GQL's strict CAST; it reads decimal text only, no Cypher literals ('0x1F')GQL is normative; the Cypher literals are toInteger's
trim(s), ltrim(s), rtrim(s) remove any whitespacespaces onlyGQL's TRIM removes spaces (to be checked against the ISO text)
floor(3), ceil(3) are floatsintegers (they compare equal)GQL keeps the argument's type
round(x, p) takes a float p; range() takes floatserror 22G03an integer argument must be an integer
a rounding mode outside Java's names fails with 22000; 'UNNECESSARY' is a modeerror 22023; 'UNNECESSARY' refusedthe code is ours; 'UNNECESSARY' fails whenever rounding is needed
round() of a number beyond the integer rangethe number itself, never saturated
left('a', null) raises an error (per the manual)NULLGQL's NULL rule
sqrt(-1) is NaN, ln(0) is -Infinity, exp(1000) is Infinityerrors 2201F, 2201E, 22003no NaN or infinity from finite numbers (GQL requires the logarithm error too)
split(s, '') splits UTF-16 code unitssplits charactersan emoji stays one item
range step 0, negative round precision: 22N38 / 22N0322023the ISO / SQL-heritage code
=~ takes a Java regular expression (look-around, back-references, possessive quantifiers)the Rust regex crate's syntax: no look-around, no back-references; an invalid pattern is 2201Bmatching stays linear in the text, as for TextP.regex (Regular-expression match)

log(2, x) and log(10, x) are exact for powers of the base, and keys(map) keeps keys whose value is NULL, both as in Neo4j.

Dates and times

The temporal functions are openCypher's, with Neo4j's meaning, on the engine's date and time values (Cypher's time is the engine's offsettime, its localtime the time). Three properties of those values shape the answers:

  • Nanoseconds. A value holds nanoseconds, as Neo4j's: text, a map field and a computed duration keep up to nine fraction digits; a duration scaled by a number keeps whole nanoseconds, truncated toward zero, as Neo4j does.
  • Zone names are kept. A datetime keeps its UTC offset and, when it was built with one, its zone name (in text, [Europe/London], or as timezone: 'Europe/Stockholm'), as Neo4j does: d.timezone gives the name, toString writes it (..+01:00[Europe/London]), and later arithmetic, truncation and duration.between follow the zone's daylight saving rules (Time Zones). A time keeps an offset only: a time of day has no date, so a named zone (time({hour: 12, timezone: 'Europe/Berlin'})) gives the zone's offset at the query's instant, the instant every clock of the query reads (+01:00 in a Berlin winter, +02:00 in summer). ISO GQL's zoned time carries a UTC offset only, and Neo4j takes the zone's offset at the current time too; reading it at the query's one instant keeps the query repeatable within itself.
  • One clock per query. The constructors without an argument, X.statement() and X.transaction() all read one instant, taken when the query starts (in nanoseconds, with the digits the platform clock has: Clock precision); X.realtime() is refused, as rand() is.

The Gremlin steps and the Rhai operators keep their own (PostgreSQL-style) rules: every difference below lives in gql() only. Dates in GQL sets each function beside the Gremlin step that does the same.

g.gql("RETURN datetime('2015-07-21T21:40:32.142[Europe/London]') AS d, datetime({year: 1984, month: 10, day: 11, hour: 12, timezone: 'Europe/Stockholm'}).timezone AS z").to_list()
// #{"d": datetime("2015-07-21T21:40:32.142+01:00[Europe/London]"), "z": "Europe/Stockholm"}
g.gql("RETURN time({hour: 12, timezone: '+01:00'}) AS t").to_list()   // #{"t": offsettime("12:00:00+01:00")}
g.gql("RETURN datetime('2015-03-29T01:30+01:00') + duration('PT1H') AS d").to_list()   // #{"d": datetime("2015-03-29T02:30:00+01:00")}
g.gql("RETURN localtime({hour: 12, minute: 0, second: 0, nanosecond: 5}) AS t").to_list()   // [#{"t": time("12:00:00.000000005")}]

Where dates and times differ from Neo4j

Neo4jgql()Why
time(): a time of day with an offset ('12:00+01:00')the same (the engine's offsettime, ISO zoned_time()); equal when the UTC times of day are equalNeo4j's = compares the offset too; no TCK case tells the two apart
a datetime keeps its zone name: '..+01:00[Europe/London]', d.timezone is 'Europe/London', arithmetic and duration.between follow the zone's daylight saving rulesthe same; equality and order use the instant onlyas for any datetime (Comparing and Sorting)
X.truncate('millennium' | 'century', ..): 2017 gives 2000, 1984 gives 1900the sameNeo4j's rule in gql(); Gremlin's date_trunc(DT.millennium) keeps PostgreSQL's (2001, 1901)
date + duration takes months, days and the whole days of the time part; localtime + duration only the time part, wrappingthe sameNeo4j's rule in gql(); Gremlin's date_add refuses a duration with a time part on a date
toString(temporal) writes '12:00', 'PT-1M-0.001S'the same; CAST(x AS STRING) writes the engine's ISO text ('12:00:00', '-PT1M0.001S')toString is the Cypher compatibility function, CAST the ISO one
< / > on two durations is NULLthe same; ORDER BY sorts durations by length (a month of 30 days)a month has no fixed length; a sort needs a total order
X.realtime() reads the live clockrefused (0A000); the other clocks read one instant per querya clock that moves during the query makes it non-deterministic, as rand()
a duration: 64-bit months, days and seconds, plus the nanoseconds of one secondthe same time part (a 64-bit count of seconds plus nanoseconds, -PT9223372036854775808S to PT9223372036854775807.999999999S); months and days are 32-bit, beyond is 22008the size of a stored value; a result leaving the years -9999 to 9999 is 22008 in both
years -999 999 999 to 999 999 999years -9999 to 9999; beyond is 22008the engine's range (Dates and Times); 2 TCK cases are excluded (year-range)
duration.between of two different types aligns them (a missing date: times only, a missing time: midnight, a missing zone: the other side's)the same; the zone lent is the other side's zone name when it has one, else its offsetNeo4j's rule
time() with a named zone takes the zone's current offsetthe zone's offset at the query's instant (one instant per query)a time of day has no date to place in the zone; one instant per query keeps every clock and constructor of a query consistent
no temporal literalsthe ISO GQL literals DATE '..', TIME '..', DATETIME '..' / TIMESTAMP '..', DURATION '..' (and ZONED / LOCAL spelled out) and the clocks CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, LOCAL_TIME, LOCAL_TIMESTAMP (Literals)ISO GQL forms; a type word followed by a string means nothing in Neo4j's language

Ids are strings

element_id(x) is the element's id as a string, the same value as Gremlin's id(). Compare it with a string: element_id(n) = '1', never = 1 (a number never equals a string). Vertex and edge ids are separate spaces in Graphersal, so a vertex and an edge may have the same id; Cypher id(x), an integer in Neo4j, is refused (Refused Constructs).

g.gql("MATCH (n) WHERE element_id(n) = '1' RETURN n.name AS n").to_list()   // #{"n": "marko"}
g.gql("MATCH (n) WHERE element_id(n) = 1 RETURN n.name AS n").to_list()   // no rows

Labels and properties

  • :A on a vertex tests whether A is in its label set; labels(v) lists the set, primary label first. An edge has exactly one label, type(e).
  • n.k reads a property. A jpath key or a map-valued property reads as a map, and m.key reads into it.
  • NULL from a missing property and a stored null are the same value.

Differences from Neo4j

gql() accepts Neo4j's Cypher spellings as compatibility forms with Neo4j's meaning, measured by the openCypher TCK (TCK Compliance: no supported construct behaves differently from the kit, except where a case is excluded below). Each of these differences is a deliberate decision, described in its section:

Neo4jgql()Where
a negative or non-integer $parameter of SKIP / LIMIT is a SyntaxError at runtimerefused when the query is compiled (22G02 / 22G03), before any row: parameters are bound then (TCK cases excluded)Parameters are bound when the query is compiled
more type errors at compile time, from its static type systemrefused before the run only where the kind is certain from the query text; any other wrong kind fails when a row reaches itStatic kind checks, Type errors surface at evaluation time
a property value is a scalar or a list of scalars of one kindmaps, mixed and nested lists are stored as given (a TCK case excluded)Writes
SET n = NULL removes every propertyan error (22004), also for SET n += NULLWrites
a plain DELETE of a node with edges is checked when the transaction commitschecked per clause (G1001)Writes, DELETE
RETURN n of a node deleted earlier in the query returns itan error naming properties(n)DELETE
a required (existence-constrained) property may come from ON CREATE SETchecked when MERGE creates the elementMERGE
the RETURN of a COUNT { } body is evaluatednot evaluated when it only projectsCOUNT and COLLECT
a comprehension variable may reuse any name that is not in scopenot a name that a LET / WITH value in scope still readsMap projections and comprehensions
'a' + 1 is 'a1'an error (22G03): convert explicitlyComparisons across types
some functions saturate, give NaN / infinity or take floatserrors or GQL's typesWhere functions differ from Neo4j
=~ takes a Java regular expressionthe Rust regex crate's syntax (no look-around, no back-references)Regular-expression match
id(x) is an integer; rand()ids are strings (element_id(x)); id() and rand() are refusedIds are strings, Refused Constructs
years up to ±999 999 999years -9999 to 9999 (TCK cases excluded)Where dates and times differ from Neo4j
X.realtime()refused; one clock per queryDates and times
a procedure argument may read the row; procedures are vendor or user code (db.*, apoc.*, Java)CALL folder.name(..) calls a saved GQL query with constant or $parameter arguments only, positional in the order its body first reads them; a saved query in Rhai, or a call inside EXISTS / COUNT / COLLECT, is 0A000; db, dbms, apoc, gds are refusedCalls of saved queries
procedure names are qualified, one per namespacesaved-query names are unique across all folders: a name in another folder is a "did you mean" errorCalls of saved queries
a NUMBER argument keeps an integer (42)coerced by the parameter's schema: a number parameter gets 42.0Calls of saved queries
a procedure call is a commit of its own in some driversthe call is part of the calling query's one unit, whose commit names no saved query (unlike g.query(..))Calls of saved queries

Where ISO GQL and Neo4j disagree, gql() follows Neo4j in a few places (comparisons across kinds, list ordering, float division by zero, NaN): Differences from the standard.

Result Shape

One map per row

Every result row of gql() is a map from column name to value, whatever the plan behind it (the planner may start a pattern at any of its nodes; the row looks the same). RETURN is mandatory in a query that only reads, as in GQL and Cypher: such a query without it is a syntax error whose help suggests RETURN * or RETURN a, b. A query whose last clause writes (or that ends with FINISH) returns no rows (Writing with GQL).

g.gql("MATCH (p:person) RETURN p.name AS name, p.age AS age ORDER BY age").to_list()
// #{"age": 27, "name": "vadas"}, #{"age": 29, "name": "marko"}, #{"age": 32, "name": "josh"}, #{"age": 35, "name": "peter"}
g.gql("MATCH (n:person)")   // error: missing RETURN

A value is a property value (number, string, boolean, date, UUID, vector, ...), NULL (a missing property gives a NULL column, the key is never left out), a list, a map (both may nest), a vertex or edge, or a path. An element column holds the live element, so Gremlin can continue from it:

g.gql("MATCH (a)-[e]->(b) RETURN * ORDER BY element_id(e) LIMIT 2").to_list()
// #{"a": v[1], "b": v[2], "e": e[0][1-knows->2]}, #{"a": v[1], "b": v[3], "e": e[1][1-created->3]}
g.gql("MATCH (s:software) RETURN s ORDER BY s.name").select("s").in("created").values("name").order().to_list()   // "josh", "josh", "marko", "peter"

Column names

ItemColumn name
expr AS namename
n.name without ASthe expression text as written: n.name
count(*) without ASthe same rule: count(*)
RETURN *every named variable, in name order (code point order, as Neo4j: a, b, p; WITH * too)
RETURN *, expr AS xthe variables first, then x

A name used twice is an error. Give every computed column an AS name: it is easier to read and to reach from Gremlin (select("name")), and the text form of an unaliased column follows Neo4j's rule today (the expression as written), which may still be aligned with the ISO naming rule.

g.gql("MATCH (p:person) RETURN p.name ORDER BY p.name LIMIT 2").to_list()   // #{"p.name": "josh"}, #{"p.name": "marko"}
g.gql("MATCH (s:software) RETURN s.name AS `the name` ORDER BY `the name`").to_list()   // #{"the name": "lop"}, #{"the name": "ripple"}
g.gql("MATCH (n:person) RETURN n.age AS a, n.name AS a")   // error: the column name `a` is used twice in RETURN

A keyword (by, order, match, ...) is fine as a label, a property key or an AS name, but where it is read back as a variable (in ORDER BY, or as a pattern variable) it must be back-quoted: RETURN p.name AS by ORDER BY `by` .

Column order

The engine keeps the columns in the written order (RETURN p.name AS name, p.age AS age gives name, then age). Whether you see that order depends on where the rows go:

OutputColumn order
JSON: to_json(), --format json, the dev server's JSON API, the MCP tools gql and querywritten order
Rust: the row is an ElementProperty::Mapwritten order
Rhai maps (to_list(), next()), the REPL / CLI table viewsorted by key
Python dictssorted by key

Rhai object maps and Python dicts built from them are sorted by key, the same as for Gremlin's project() today; the table view shows their columns in that order.

g.gql("MATCH (p:person) RETURN p.name AS name, p.age AS age ORDER BY age LIMIT 2").to_json()
// [{"name": "vadas", "age": 27}, {"name": "marko", "age": 29}]
g.gql("MATCH (p:person) RETURN p.name AS name, p.age AS age ORDER BY age").next().keys()   // "age", "name"

When the written order matters, read the rows as JSON or name the columns so that their alphabetical order is the order you want.

Paths

A path variable (RETURN p) and a group variable (the variable of a quantified edge, or a variable inside a quantified path pattern) hold elements, so Gremlin can continue from them too:

ColumnValueJSON
a path variable pa path: vertex, edge, vertex, ..., in the written order (Gremlin's path() value)a list of the element objects
a group variable e of -[e]->{1,3}a list of the edges, in the written order; [] for a zero-length matcha list of edge objects
a group variable x or e of ((x)-[e]->(y)){1,3}a list of the nodes or edges, one per iteration in the written order; [] for zero iterations (with ?: the single element, or NULL)a list of element objects
either, from an OPTIONAL MATCH that did not matchNULLnull
g.gql("MATCH p = (a {name: 'marko'})-[:knows]->(b {name: 'vadas'}) RETURN p").to_list()   // #{"p": [v[1], e[0][1-knows->2], v[2]]}
g.gql("MATCH p = (a {name: 'marko'})-[:knows]->(b {name: 'vadas'}) RETURN p").to_json()
// [{"p": [{"id": "1", "label": "person", ...}, {"id": "0", "label": "knows", "inV": "2", "outV": "1", ...}, {"id": "2", ...}]}]
g.gql("MATCH p = (a {name: 'marko'})-[:knows]->(b {name: 'vadas'}) RETURN p").select("p").unfold().to_list()   // v[1], e[0][1-knows->2], v[2]
g.v().has("name", "marko").out_e("knows").in_v().has("name", "vadas").path().to_list()   // [v[1], e[0][1-knows->2], v[2]]

Nested maps and lists

A column may hold maps and lists nested to any depth: a record constructor {k: expr}, a map projection p {.name, ...} and a list or pattern comprehension build them per row, so one row can carry an entity with its related data inside. Keys keep their written order in the JSON output, at every level, like the columns of a row (Column order); Rhai maps sort them by key as anywhere else.

g.gql("MATCH (s:software) RETURN s {.name, creators: [(s)<-[:created]-(p) | p {.name, .age}]} AS sw ORDER BY sw.name").to_json()
// [{"sw": {"name": "lop", "creators": [{"name": "peter", "age": 35}, {"name": "josh", "age": 32}, {"name": "marko", "age": 29}]}},
//  {"sw": {"name": "ripple", "creators": [{"name": "josh", "age": 32}]}}]
// (the creators of one program come in no defined order)

A vertex, edge or path inside a map or a list stays the live element, as in a column of its own: Gremlin can continue from it, and JSON renders it as the element object {id, label, properties} (an edge also its endpoints, inV and outV). Project the properties you need (f {.name} instead of f) for a smaller answer.

g.gql("MATCH (p:person {name: 'marko'})-[:knows]->(f {name: 'vadas'}) RETURN p {.name, friend: f} AS x").to_list()   // #{"x": #{"friend": v[2], "name": "marko"}}
g.gql("MATCH (p:person {name: 'marko'})-[:knows]->(f {name: 'vadas'}) RETURN p {.name, friend: f} AS x").to_json()
// [{"x": {"name": "marko", "friend": {"id": "2", "label": "person", "properties": {"name": "vadas", "age": 27}}}}]
g.gql("MATCH (p:person {name: 'marko'}) RETURN [(p)-[:knows]->(f) | f] AS friends").select("friends").unfold().values("name").order().to_list()   // "josh", "vadas"
ValueRhai / RustJSON
a map projection or recorda map (ElementProperty::Map), keys in written order in Rustan object, keys in written order
a map projection of a NULL variable() / NULLnull
a list or pattern comprehensiona list; [] when nothing is kept or matchedan array
an element inside eitherthe live vertex or edgethe element object

Row order and duplicates

  • Without ORDER BY the row order is unspecified (Ordering).
  • Rows are a multiset: the same row may appear several times (one per match). RETURN DISTINCT removes duplicates (with GQL's equality).
  • An aggregating RETURN gives one row per group; without grouping keys exactly one row, even when nothing matched (Aggregation).
  • OFFSET and LIMIT apply after ORDER BY and DISTINCT.

Writing with GQL

gql() writes too. This version supports INSERT (Cypher CREATE is its alias), which creates nodes and edges, and SET and REMOVE, which change the properties and labels of existing ones, and DELETE / DETACH DELETE, which remove them; each runs once for each row that reaches it. Cypher's MERGE, which finds a pattern or creates it when it is missing, is accepted as a compatibility form (MERGE).

A writing query is one unit, like every traversal: it commits when it succeeds, and a query that fails, on any row, changes nothing (Units).

INSERT

INSERT takes one or more comma-separated patterns. A node pattern creates a node with the labels written (none, one, or several joined by &; Cypher's :A:B is the alias) and the properties of its map. An edge pattern creates an edge between the nodes beside it: it needs a direction (-[:T]-> or <-[:T]-) and exactly one label.

g.gql("INSERT (:city {name: 'Berlin', population: 3.7})").iterate();
g.gql("INSERT (a:person {name: 'ann'})-[:knows {since: 2020}]->(b:person&admin {name: 'bob'})").iterate();
g.gql("MATCH (a {name: 'ann'})-[e:knows]->(b) RETURN e.since AS since, labels(b) AS labels").to_list()   // #{"labels": ["person", "admin"], "since": 2020}

The same in Gremlin:

g.add_v("person").property("name", "ann").as("a").add_v(["person", "admin"]).property("name", "bob").add_e("knows").from("a").property("since", 2020).count().next()   // 1

A query may end with the INSERT: it then returns no rows. GQL's FINISH ends a query without a result too. RETURN after an INSERT reads the new elements, and RETURN * includes the variables the INSERT named:

g.gql("INSERT (c:city {name: 'Berlin'}) RETURN c.name AS name").to_list()   // #{"name": "Berlin"}
g.gql("CREATE (c:city:capital {name: 'Rome'}) RETURN labels(c) AS l").to_list()   // #{"l": ["city", "capital"]}
g.gql("INSERT (:city {name: 'Paris'})").to_list()   // no rows
g.gql("INSERT (:city {name: 'Paris'}) FINISH").to_list()   // no rows

Property values are expressions: literals, $parameters, functions and the variables of the row. A property whose value is NULL is not stored (GQL has no stored NULL; a Gremlin property(k, ()) stores one). Lists and maps are stored as they are, also lists of mixed kinds (a difference from Neo4j); a node, an edge or a path cannot be a property value (22G03).

g.gql("INSERT (n:x {k: NULL, tags: ['a', 1], address: {city: 'Rome'}}) RETURN keys(n) AS keys, n.address.city AS city").to_list()   // #{"city": "Rome", "keys": ["tags", "address"]}

Pattern rules. A variable bound before the INSERT is written alone, (p): it connects the existing node and may not carry labels or properties (42002; change an existing node with SET, as in MATCH (p:person) SET p:admin). An edge without a direction, an edge with a label expression (:r|s), a node label expression other than a conjunction, a path variable (p = ...) and WHERE or a quantifier inside the pattern are errors before the run; the help shows the accepted form.

g.gql("INSERT (a:x)-[:r]-(b:y)")   // error: INSERT needs a direction
g.gql("MATCH (p:person) INSERT (p:admin)")   // error: the variable `p` is already bound

SET

SET takes one or more comma-separated items and applies them to the elements of each row that reaches it, left to right, so a later item sees the earlier ones:

ItemEffect
SET n.k = expr (also SET (n).k = expr)sets one property of the node or edge n
SET n = {k: expr, ...}replaces every property: the keys missing from the map are removed
SET n += {k: expr, ...}merges the map in (a Cypher compatibility form): other keys stay
SET n:A / SET n IS Aadds the label A to the node n; SET n:A:B and SET n IS A & B add both
g.gql("MATCH (p:person {name: 'marko'}) SET p.age = p.age + 1, p.checked = true RETURN p.age AS age, p.checked AS checked").to_list()   // #{"age": 30, "checked": true}
g.gql("MATCH (p:person {name: 'marko'}) SET p:admin:staff RETURN labels(p) AS labels").to_list()   // #{"labels": ["person", "admin", "staff"]}
g.gql("MATCH (p:person {name: 'marko'}) SET p += {city: 'Rome'} RETURN properties(p) AS props").to_list()   // #{"props": #{"age": 29, "city": "Rome", "name": "marko"}}
g.gql("MATCH (p:person {name: 'marko'}) SET p = {name: 'marko', city: 'Rome'} RETURN properties(p) AS props").to_list()   // #{"props": #{"city": "Rome", "name": "marko"}}
g.gql("MATCH (a {name: 'marko'})-[e:knows]->(b) SET e.checked = true RETURN b.name AS b, e.checked AS checked ORDER BY b").to_list()   // josh true, vadas true

NULL removes. GQL stores no NULL, so SET n.k = NULL removes the property, and a NULL value in the map of SET n = {..} or SET n += {..} removes its key. A NULL target (a variable an OPTIONAL MATCH left NULL) is skipped: the item does nothing for that row. A NULL map on the right of = or += is an error (22004): write SET n = {} to remove every property, or coalesce($map, {}) for a parameter that may be NULL.

g.gql("MATCH (p:person {name: 'marko'}) SET p.age = NULL RETURN keys(p) AS keys").to_list()   // #{"keys": ["name"]}
g.gql("MATCH (p:person {name: 'marko'}) SET p += {age: NULL, city: 'Rome'} RETURN properties(p) AS props").to_list()   // #{"props": #{"city": "Rome", "name": "marko"}}
g.gql("OPTIONAL MATCH (p:person {name: 'nobody'}) SET p.seen = true RETURN p").to_list()   // #{"p": ()}
g.gql("MATCH (p:person {name: 'marko'}) SET p = $props", #{props: ()})   // error: the right side of SET p = .. is NULL, not a map

Values follow the rules of INSERT: literals, $parameters, functions and the row's variables; lists and maps are stored as they are; a node, an edge or a path cannot be a property value (22G03). Every value of a map is checked before the item writes anything. On the right of = and += a node or an edge stands for its properties (SET n = m copies them, SET n = n changes nothing); any other value that is not a map is an error (22G03). An aggregate cannot be a value: aggregate in a WITH first.

g.gql("MATCH (p:person {name: 'marko'}), (q:person {name: 'josh'}) SET p = q RETURN properties(p) AS props").to_list()   // #{"props": #{"age": 32, "name": "josh"}}
g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s) WITH p, count(s) AS n SET p.projects = n RETURN p.name AS name, p.projects AS n ORDER BY name").to_list()
// josh 2, marko 1, peter 1, vadas 0
g.gql("MATCH (p:person {name: 'marko'}) SET p.self = p")   // error: a property cannot hold a graph element

Labels. A label item changes a node's label set: adding a label it has, like removing one it lacks, is no change. An edge has exactly one label, its type, so a label item on an edge is an error: 42002 before the run when the variable is an edge of a pattern, 22G03 when a row holds an edge (Gremlin's set_label() changes an edge's label). The item names labels joined by : or &; |, ! and % are syntax errors.

g.gql("MATCH (a)-[e:knows]->(b) SET e:friend")   // error: an edge has exactly one label

Targets. The target of an item is a variable of the row: n.k, (n).k or n. A deeper target (n.address.city = .., head(list).k = ..) is not supported yet (0A000); name the element first, as in WITH head(list) AS x SET x.k = ... The variable must be bound before the SET (42002).

REMOVE

REMOVE takes comma-separated items like SET: REMOVE n.k removes a property of a node or an edge, REMOVE n:A (also REMOVE n IS A, REMOVE n:A:B) removes labels from a node, and the last label may go too. Removing what is not there changes nothing, and a NULL target is skipped.

g.gql("MATCH (p:person {name: 'marko'}) REMOVE p.age RETURN keys(p) AS keys").to_list()   // #{"keys": ["name"]}
g.gql("MATCH (s:software {name: 'ripple'}) SET s:product REMOVE s:software RETURN labels(s) AS labels").to_list()   // #{"labels": ["product"]}
g.gql("MATCH (p:person {name: 'marko'}) REMOVE p.nothing, p:nothing RETURN labels(p) AS labels, keys(p) AS keys").to_list()   // #{"keys": ["name", "age"], "labels": ["person"]}

The same in Gremlin:

g.v().has("name", "marko").property("age", 30).add_label("admin").values("age").next()   // 30
g.v().has("name", "marko").remove_property("age").properties().key().to_list()   // "name"
g.v().has("name", "ripple").add_label("product").drop_label("software").label().next()   // "product"

DELETE

DELETE takes one or more comma-separated expressions and removes the nodes and edges they give, for every row that reaches it. DETACH DELETE removes a node together with all its edges. A plain DELETE (GQL's default, also written NODETACH DELETE) removes only nodes without edges: a node that still has an edge fails the query (G1001) and nothing is removed. Edges the same clause deletes do not count, so DELETE e, n removes a node and the edge that held it in one clause.

g.gql("MATCH (p:person {name: 'marko'}) DETACH DELETE p").iterate();
[g.v().count().next(), g.e().count().next()]   // [5, 3]
g.gql("MATCH (a {name: 'marko'})-[e:knows]->(b {name: 'vadas'}) DELETE e RETURN b.name AS still_here").to_list()   // #{"still_here": "vadas"}
g.gql("MATCH (s:software {name: 'ripple'})<-[e]-() DELETE e, s RETURN count(*) AS n").to_list()   // #{"n": 1}
g.gql("MATCH (p:person {name: 'marko'}) DELETE p")   // error: `p` is a node that still has edges (G1001)

The NODETACH check runs for the whole clause before it removes anything: the help of the error names the DETACH DELETE that works, built from the failing query.

Targets are expressions: a node or an edge variable, a path (MATCH p = .. DETACH DELETE p removes its nodes and edges), a list of them (also nested, such as collect(n)), or an expression that gives one (a map member, head(list)). A NULL target (an OPTIONAL MATCH that found nothing) is skipped, and an element already removed (by an earlier row or clause) is not removed twice. A target that gives another value fails the query: before the run when the text shows it (DELETE 1 + 1, 42002), on the row otherwise (22G03). A label test is not a target: DELETE n:L is a syntax error whose help names REMOVE n:L, which removes the label and keeps the node.

g.gql("MATCH p = (:person {name: 'marko'})-[:knows]->(:person {name: 'vadas'}) DETACH DELETE p").iterate();
[g.v().count().next(), g.e().count().next()]   // [4, 3]
g.gql("OPTIONAL MATCH (p:person {name: 'nobody'}) DELETE p RETURN p").to_list()   // #{"p": ()}
g.gql("MATCH (p:person) WITH collect(p) AS people DETACH DELETE people RETURN size(people) AS n").to_list()   // #{"n": 4}
g.gql("MATCH (n:person) DELETE n:person")   // error: a label test is not an element; REMOVE n:person removes the label

After a DELETE. A deleted element is gone for the rest of the query: reading its properties, labels, element_id() or endpoints is an error, never a silent NULL, and so is returning it (RETURN n, also with LIMIT 0 after it, and RETURN p of a path holding it). Read what you need before the DELETE and carry it in a WITH; count(n) and n IS NULL still work, and type(e) of a deleted edge still gives its label (as in the openCypher tests). A walk from a deleted node (MATCH (n)-->(m) after deleting n) finds nothing.

g.gql("MATCH (p:person {name: 'vadas'}) WITH p, properties(p) AS props DETACH DELETE p RETURN props").to_list()   // #{"props": #{"age": 27, "name": "vadas"}}
g.gql("MATCH (p:person {name: 'vadas'}) DETACH DELETE p RETURN count(p) AS deleted").to_list()   // #{"deleted": 1}
g.gql("MATCH (a)-[e:created]->(s:software {name: 'lop'}) DELETE e RETURN type(e) AS t, a.name AS who ORDER BY who").to_list()   // three rows, t "created"
g.gql("MATCH (p:person {name: 'vadas'}) DETACH DELETE p RETURN p")   // error: the node was deleted earlier in this query
g.gql("MATCH (p:person {name: 'vadas'}) DETACH DELETE p RETURN p.name AS name")   // error: the node was deleted earlier in this query

Returning a deleted node is an error in gql() where Neo4j returns a value of it; the reasons are on Semantics.

A query that fails after its DELETE changed nothing (Units): the removed elements come back with their ids, labels, properties and edges. In Rust they are new elements: a VertexId / EdgeId handle taken before the failed run is stale and must be looked up again by id (What a rollback restores), exactly as after a failing Gremlin drop(). A Rhai vertex or edge value finds the element by its id and stays usable.

The same in Gremlin:

g.v().has("name", "marko").drop().count().next()   // 0
g.v().has("name", "marko").out_e("knows").where(__.in_v().has("name", "vadas")).drop().iterate()

drop() of a vertex always removes its edges (it is DETACH DELETE); the NODETACH check has no Gremlin twin.

MERGE

MERGE is Cypher's "find or create": for each row it looks for its one pattern, and every match becomes a row; when nothing matches, it creates the whole pattern and the row goes on with the new elements. ISO GQL has no MERGE statement; gql() accepts it as a compatibility form with Cypher's meaning, so a query written for Neo4j runs as it is. The second MERGE of the first block finds the city the first one created:

g.gql("MERGE (c:city {name: 'Berlin'}) RETURN c.name AS name").to_list();   // #{"name": "Berlin"}: created
g.gql("MERGE (c:city {name: 'Berlin'}) RETURN c.name AS name").to_list();   // #{"name": "Berlin"}: found
g.v().has_label("city").count().next()   // 1
g.gql("MERGE (p:person {name: 'marko'}) RETURN p.age AS age").to_list()   // #{"age": 29}: found, nothing created
g.gql("MERGE p = (:person {name: 'marko'})-[:knows]->(f:person) RETURN f.name AS friend, path_length(p) AS hops ORDER BY friend").to_list()   // josh and vadas: two matches, two rows

The pattern. One path pattern (a second one after , is a syntax error: write one MERGE per pattern). Its nodes have the labels written (:A:B or :A&B; a found node carries all of them and may have more) and a property map compared with GQL =; its edges have exactly one label and no quantifier, and the pattern has no WHERE. A path variable (MERGE p = ..) gives the found or the created path.

A variable bound before stands for its element: write it alone, as (a), and MERGE reuses it in both cases, so an edge between matched nodes is created only when it is missing. Labels or properties on a bound node (MERGE (a:admin)), a bound edge variable, and a pattern that is only a bound node (MATCH (a) MERGE (a)) are refused before the run (42002); change a bound node with SET. An unbound variable is new: the MERGE finds or creates its element.

g.gql("MATCH (a:person {name: 'marko'}), (b:person {name: 'peter'}) MERGE (a)-[e:knows]->(b) RETURN b.name AS to").to_list();   // #{"to": "peter"}: created
g.gql("MATCH (a:person {name: 'marko'}), (b:person {name: 'peter'}) MERGE (a)-[e:knows]->(b) RETURN b.name AS to").to_list();   // found
g.e().has_label("knows").count().next()   // 3: marko's two edges and the new one
g.gql("MATCH (a:person) MERGE (a)")   // error: a bound variable alone has nothing to find or create
g.gql("MATCH (a:person) MERGE (a:admin)")   // error: a bound node carries no new labels in MERGE; SET a:admin does
g.gql("MERGE (a:person {name: 'x'}), (b:person {name: 'y'})")   // error: MERGE takes exactly one pattern

Either direction. An edge without a direction, -[:T]-, matches an edge in either direction; when it is created, it points from left to right, from the node written first:

g.gql("MATCH (a:person {name: 'josh'}), (b:person {name: 'marko'}) MERGE (a)-[e:knows]-(b) RETURN startNode(e).name AS from").to_list()   // #{"from": "marko"}: the stored edge marko -> josh
g.gql("MATCH (a:person {name: 'vadas'}), (b:person {name: 'josh'}) MERGE (a)-[e:knows]-(b) RETURN startNode(e).name AS from").to_list()   // #{"from": "vadas"}: created left to right

Per row, and each row sees the rows before it. MERGE runs once for each row, in order, and a row finds what an earlier row created: a repeated item is created once, so MERGE is idempotent within a query as across queries. The whole pattern is matched or created: MATCH (p:person) MERGE (p)-[:in]->(g:group {name: 'x'}) creates a group for every person without such an edge, because the pattern with the edge does not match for them; to share one group, MERGE the group first and the edge second:

g.gql("FOR n IN ['Rome', 'Rome', 'Oslo'] MERGE (c:city {name: n}) RETURN count(*) AS rows, count(DISTINCT c) AS cities").to_list()   // #{"cities": 2, "rows": 3}
g.gql("MATCH (p:person) WHERE p.age > 30 MERGE (g:group {name: 'over30'}) MERGE (p)-[:in]->(g) RETURN count(DISTINCT g) AS groups").to_list()   // #{"groups": 1}

ON CREATE SET and ON MATCH SET. After the pattern, ON CREATE SET <items> changes the elements of a row that the MERGE created, and ON MATCH SET <items> those of a row it found. The items are the items of SET and may read every variable of the row (the pattern's and the earlier ones). Both may be written several times and in any order; they apply in the order written, each in its own case.

g.gql("FOR name IN ['marko', 'ann'] MERGE (p:person {name: name}) ON CREATE SET p.visits = 1 ON MATCH SET p.visits = coalesce(p.visits, 0) + 1").iterate();
g.gql("FOR name IN ['marko', 'ann'] MERGE (p:person {name: name}) ON CREATE SET p.visits = 1 ON MATCH SET p.visits = coalesce(p.visits, 0) + 1 RETURN p.name AS name, p.visits AS visits ORDER BY name").to_list()   // ann 2, marko 2
g.gql("MERGE (p:person {name: 'marko'}) ON CREATE SET p.new = true ON MATCH SET p.new = false RETURN p.new AS new").to_list()   // #{"new": false}
g.gql("MERGE (p:person {name: 'marko'}) ON MATCH SET p.seen = 1 ON MATCH SET p.seen = p.seen + 1 RETURN p.seen AS seen").to_list()   // #{"seen": 2}

NULL in the pattern. MERGE cannot look for or create a NULL property value: a property of the pattern that is NULL on a row (a missing parameter, an OPTIONAL MATCH that found nothing) fails the query with 22004 when that row runs, and nothing of the query is kept. Keep such rows away with FILTER x IS NOT NULL, or give a default with coalesce():

g.gql("FOR x IN [1, NULL] MERGE (n:num {v: x})")   // error: MERGE cannot match or create `{v: NULL}` (22004)
g.gql("FOR x IN [1, NULL] FILTER x IS NOT NULL MERGE (n:num {v: x}) RETURN count(*) AS n").to_list()   // #{"n": 1}

A MERGE that only finds changes nothing. It commits no change: a commit hook and the journal see nothing, and the dev server's answer reports no change summary and no commit. An ON MATCH SET that runs is a change, as a SET is.

The same in Gremlin: merge_v() finds or creates a vertex, merge_e() an edge between given vertices, and the fold().coalesce(__.unfold(), __.add_v(..)) idiom does it by hand. Their onCreate option map replaces the creation map, while ON CREATE SET changes the created element afterwards.

g.merge_v(#{"T.label": "city", name: "Berlin"}).values("name").to_list()   // "Berlin"
g.v().has_label("city").has("name", "Berlin").fold().coalesce(__.unfold(), __.add_v("city").property("name", "Berlin")).values("name").to_list()   // "Berlin"

The same in plain GQL, without the compatibility form: a CALL body that inserts only when nothing exists yet, then a MATCH that reads the result:

g.gql("CALL { FILTER NOT EXISTS { MATCH (:city {name: 'Berlin'}) } INSERT (:city {name: 'Berlin'}) } MATCH (c:city {name: 'Berlin'}) RETURN count(c) AS cities").to_list()   // #{"cities": 1}

Once per row

A write clause runs once for each row that reaches it, so the clauses before it decide how many elements an INSERT creates and how often a SET applies (SET n.c = n.c + 1 over two rows of the same node adds 2). A MATCH gives one row per match, FOR (Cypher UNWIND) one per list item, and a variable of the row connects the new elements to what it matched:

g.gql("MATCH (p:person {name: 'marko'}) INSERT (p)-[:likes]->(f:fruit {name: 'apple'}) RETURN f.name AS fruit").to_list();   // #{"fruit": "apple"}
g.gql("FOR n IN $names INSERT (:person {name: n, born: $year})", #{names: ["ann", "bob"], year: 1990}).iterate();
g.gql("MATCH (p:person) WHERE p.born = 1990 RETURN p.name AS name ORDER BY name").to_list()   // #{"name": "ann"}, #{"name": "bob"}

A write clause may stand after MATCH, OPTIONAL MATCH, FOR, WITH, LET, FILTER and another write clause, and further clauses may follow it: a MATCH after the INSERT sees the new elements, and a new node can be connected to every row a later MATCH finds:

g.gql("INSERT (c:city {name: 'Berlin'}) MATCH (p:person) INSERT (p)-[:lives_in]->(c) RETURN count(*) AS n").to_list()   // #{"n": 4}
g.gql("MATCH (p:person) WITH p, p.age + 1 AS later INSERT (p)-[:turns]->(:age {years: later}) RETURN p.name AS name, later ORDER BY name").to_list()
// #{"later": 33, "name": "josh"}, #{"later": 30, "name": "marko"}, #{"later": 36, "name": "peter"}, #{"later": 28, "name": "vadas"}

A node an OPTIONAL MATCH left NULL cannot be an edge's endpoint: the query fails (22004) and changes nothing. Keep only the bound rows with FILTER x IS NOT NULL first:

g.gql("OPTIONAL MATCH (p:person {name: 'nobody'}) INSERT (p)-[:knows]->(:person)")   // error: the source node `p` of the inserted `:knows` edge is NULL
g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s) FILTER s IS NOT NULL INSERT (p)-[:made]->(s) RETURN count(*) AS n").to_list()   // #{"n": 4}

Inside CALL. A CALL body may end with its write instead of RETURN (a unit subquery): it runs once per incoming row and passes the row on unchanged, also when the body found nothing:

g.gql("MATCH (p:person) CALL (p) { INSERT (p)-[:likes]->(:fruit {name: p.name}) } RETURN count(*) AS c").to_list()   // #{"c": 4}

A subquery expression (EXISTS { }, COUNT { }, COLLECT { }) and a comprehension cannot write (42001), and a write in an operand of UNION is not supported yet.

What a row sees

Each clause sees every write of the clauses before it, for all rows; within one clause the rows are processed in order, and each row sees the writes of the rows before it. A query never sees its own writes while it is still finding the rows of an earlier clause: MATCH (n) INSERT (:X) creates exactly one node per node that existed before, and MATCH (a)-[e]->(b) INSERT (a)-[:copy]->(b) copies each existing edge once, never the copies.

g.gql("MATCH (n) INSERT (:X)").iterate();
g.v().has_label("X").count().next()   // 6
g.gql("FOR i IN range(1, 3) INSERT (:n {i: i}) WITH count(*) AS made MATCH (m:n) RETURN made, count(m) AS seen").to_list()   // #{"made": 3, "seen": 3}

A value a row carried before a SET keeps the value it had: WITH p.age AS old SET p.age = 0 still returns the old age in old, while p.age reads the new one.

g.gql("MATCH (p:person {name: 'marko'}) WITH p, p.age AS old SET p.age = 0 RETURN old, p.age AS now").to_list()   // #{"now": 0, "old": 29}

The details, and how this follows from the executor, are on Semantics.

One query is one unit

A gql() query is one traversal and so one unit (Transactions): when any row fails (a data error on the last row, a schema violation, a permission, a resource limit, cancellation), nothing the query wrote stays. Here the second item divides by zero, and the node of the first item is rolled back with it (execute() keeps the error instead of raising it, so the script goes on):

let run = g.gql("FOR x IN [1, 0] INSERT (:n {v: 1 / x})").execute();   // fails: division by zero
g.v().has_label("n").count().next()   // 0

A SET that fails on one row leaves the rows before it unchanged too:

let set = g.gql("MATCH (p:person) SET p.score = 100 / (p.age - 27)").execute();   // fails on vadas (27)
g.v().has("score").count().next()   // 0

Commit hooks see the query's ChangeSet and may veto it, a dry run shows its changes without keeping them, and a Store's journal records it like any Gremlin write (Change capture).

Schema

An INSERT creates each element in one storage call with all its properties, so a schema sees the whole element (Schemas): defaults on create are filled in, a required property is satisfied by the map, write-time coercion applies, and a closed schema refuses undeclared labels and properties. SET and REMOVE are checked like the Gremlin steps that do the same: a value of the wrong type, removing a required property (also with SET n.k = NULL or a SET n = {..} without it) and a label the schema does not allow fail the query. A violation fails the query (and changes nothing), with a help line written for GQL:

g.set_schema(#{mode: "open", vertices: #{person: #{schema: #{type: "object", properties: #{
    name: #{type: "string"}, age: #{type: "integer"}, active: #{type: "boolean", default: true}},
    required: ["name"]}}}});
g.gql("INSERT (:person {name: 'alice'})").iterate();
g.gql("MATCH (p:person) RETURN p.name AS name, p.active AS active").to_list()   // #{"active": true, "name": "alice"}
Caused by: Missing required property 'name' on vertex 'person'
Help: Give 'name' a value in the property map of the INSERT, as in g.gql("INSERT (:person {name: 'value'})"); a NULL value (such as a property the matched element lacks) is not stored and so is missing too: give it a fallback, as in {name: coalesce(n.name, 'unknown')}. Or remove it from the label's "required" in the schema, or give it a "default" (or "defaultFunction") in the schema: it is stored when an element is created without the property.

A MERGE that creates creates like an INSERT of its pattern: the schema's defaults are filled in and the pattern's map must satisfy required. Its ON CREATE SET items run afterwards, as a second write in the same query, so a required property given only there is missing when the element is created and fails the query; put it into the pattern's map instead (where it is also part of what MERGE looks for):

g.set_schema(#{mode: "open", vertices: #{person: #{schema: #{type: "object", properties: #{
    name: #{type: "string"}, active: #{type: "boolean", default: true}}, required: ["name"]}}}});
g.gql("MERGE (p:person {name: 'ann'}) RETURN p.active AS active").to_list()   // #{"active": true}

A value of the wrong type is not converted, and GQL never infers a type from text. Convert it where the INSERT writes it:

Caused by: Type mismatch on vertex 'person.age': expected int64, got string
Help: Convert the value to the type 'int64' where the INSERT writes it, with toInteger(), as in g.gql("INSERT (:person {age: toInteger($v)})", #{v: "29"}). toInteger() gives NULL for a value it cannot convert, and a NULL value is not stored; CAST(x AS ..) fails the query for it instead.

Permissions

The permission check sees the lowered plan before anything runs: an INSERT asks Create on Data(vertex "label") per label of each new node and Create on Data(edge "label") per new edge, exactly as add_v(labels) and add_e(label) do, plus the reads of its MATCH clauses. SET and REMOVE ask Update, as property(), remove_property(), add_label() and drop_label() do: on Data(vertex) for a node (any label, since a node's label set is not fixed by the pattern), on Data(edge "label") for an edge whose pattern names its labels, and on any element when the kind is not known before the run (an item of a FOR list). It asks nothing for the properties: they are part of creating the element. DELETE asks Delete, as drop() does: on Data(vertex) for a node, on Data(edge "label") for an edge whose pattern names its labels, and on any element for a path, a list or a value whose kind is known only at run time; DETACH asks nothing more (as drop() of a vertex, which removes its edges too). MERGE asks what its two halves need, whether a row will find or create: Read for the search (as a MATCH of its pattern), Create per label of every element the pattern can create (as the INSERT of it), and, only when it has ON CREATE SET / ON MATCH SET items, their Updates (as SET). The step's own Create and Update requests are checked first, then the Reads of its search; a policy that denies Create refuses a MERGE even where every row would only find. merge_v() and merge_e() ask Read on what they search first, then Create and Update on any vertex or edge (no labels, and Update even without on_create / on_match options). (Gremlin's add_v(..).property(..) asks Create and Update, because the check runs before the optimizer folds the property into the creation; a policy that denies only Update allows the INSERT and refuses its Gremlin twin.) A read-only host (AccessPolicy::read_only(), the MCP server's --mcp-read-only, a read-only view of a past state) refuses a GQL write before it runs.

Saved queries and the DSL

A saved query may be written in GQL itself (Saved queries in GQL): the body is the plain query text, its $parameters are the declared ones, and an INSERT, SET, REMOVE, DELETE or MERGE makes it a query that writes, whose effects name what its plan creates, changes and deletes. A call writes in one unit and returns the rows. A GQL query calls it with CALL hire('lop', 'ann') YIELD name (the arguments in the order the body first reads them: $company, then $name); its writes then belong to the calling query's unit (Calling saved queries):

g.define_query(#{name: "hire", language: "gql", params: #{name: "string", company: "string"},
    body: "MATCH (c:software {name: $company}) INSERT (p:person {name: $name})-[:created]->(c) RETURN p.name AS name"});
g.get_query("hire")["effects"].map(|e| e.text);   // ["Create Data(vertex \"person\")", "Create Data(edge \"created\")"]
g.query("hire", #{name: "ann", company: "lop"}).select("name").to_list()   // "ann"
g.define_query(#{name: "birthday", language: "gql", params: #{name: "string"},
    body: "MATCH (p:person {name: $name}) SET p.age = p.age + 1 RETURN p.age AS age"});
g.get_query("birthday")["effects"].map(|e| e.text);   // ["Update Data(vertex)"]
g.query("birthday", #{name: "vadas"}).select("age").to_list()   // 28
g.define_query(#{name: "unlink", language: "gql", params: #{}, body: "MATCH ()-[e:knows]->() DELETE e"});
g.get_query("unlink")["effects"].map(|e| e.text)   // ["Delete Data(edge \"knows\")"]
g.define_query(#{name: "visit", language: "gql", params: #{name: "string"},
    body: "MERGE (p:person {name: $name}) ON MATCH SET p.visits = coalesce(p.visits, 0) + 1 RETURN p.name AS name"});
g.get_query("visit")["effects"].map(|e| e.text)   // ["Create Data(vertex \"person\")", "Update Data(vertex)"]

A saved query in Rhai whose body runs g.gql("INSERT ...") with a literal query text is a writing query too: its effects name what it creates, changes and deletes. A computed query text claims every write; pass values as $parameters instead.

In a script, a writing gql() takes the write lock like a Gremlin write (is_mutating() is true), and the playground asks before running it again. Gremlin steps may follow:

g.gql("INSERT (c:city {name: 'Berlin'}) RETURN c").select("c").values("name").to_list()   // "Berlin"

In Rust

Run a writing query on the writing source, traversal_mut(), under the write lock. The read source refuses it with the error a Gremlin write gets there:

use graphersal::prelude::*;

let graph = Graph::new(TraversalGraph::tinkerpop_modern());
graph
    .write()
    .traversal_mut()
    .gql("MATCH (p:person {name: 'marko'}) INSERT (p)-[:likes]->(:fruit {name: 'apple'})")
    .iterate()?;

// The read source cannot write:
let error = graph.read().traversal().gql("INSERT (:x)").iterate().unwrap_err();
assert_eq!(
    error.root_cause().to_string(),
    "Invalid element state: Cannot mutate immutable graph reference"
);

The plan

An INSERT lowers to the internal steps gql:insert_node and gql:insert_edge, one per element of the pattern, in text order (Plans and Performance); a SET clause to one gql:set step and a REMOVE clause to one gql:remove step with its items, which pass the row on unchanged. A DELETE clause lowers to one gql:delete step: it collects the targets of all its rows first (the NODETACH check sees the whole clause), removes the edges, then the nodes, and passes the rows on unchanged. A MERGE lowers to one gql:merge step with two children: the search (the plan of a MATCH of the pattern, starting from a bound node or using a property index where one serves it) and the creation (the gql:insert_node / gql:insert_edge chain of the pattern); .profile() shows both under the step. Because the plan writes, its traversers are never merged into one with a higher bulk: each row creates its own elements and applies its own changes.

g.gql("MATCH (p:person {name: 'marko'}) SET p.age = 1 RETURN p").profile()
g.gql("MERGE (c:city {name: 'Rome'}) RETURN c").profile()

Not yet

ConstructUntil then
FOREACH (x IN list | ...)FOR x IN list INSERT ...
a write in a UNION operand, a path variable in INSERTrun the write on its own; name the nodes and edges
a deeper SET / REMOVE target (n.a.b, head(l).k), Cypher's dynamic n[key]name the element with WITH .. AS x and write the item on x; for a nested value Gremlin property() with a jpath key
g.gql("MATCH (p:person {name: 'marko'}) SET p.address.city = 'Rome'")   // error: `p.address.city` as a SET target is not yet supported

Writing GQL in Rhai Strings

In the Gremlin DSL (the command line, the playground, Python scripts, saved queries) a GQL query is a Rhai string passed to g.gql(..). GQL has quotes and backticks of its own, and Rhai gives some characters a meaning inside strings, so this page shows which string form to use and how to write values, names and comments inside it. Through the MCP tool gql none of this applies: the query is plain text.

Short queries: "..." with GQL '...' literals

A query on one line goes into a Rhai double-quoted string. Write GQL string literals with single quotes, so nothing needs escaping:

g.gql("MATCH (s:software) WHERE s.name = 'lop' RETURN s.lang AS lang").to_list()   // #{"lang": "java"}

GQL accepts "..." string literals too, but inside a Rhai "..." string each one must be escaped as \":

g.gql("MATCH (s:software) WHERE s.name = \"lop\" RETURN s.lang AS lang").to_list()   // #{"lang": "java"}

A single quote inside a GQL '...' literal is doubled ('it''s'), the GQL rule. Rhai processes backslash escapes in "..." strings first, so a backslash that GQL should see is written \\.

g.gql("MATCH (s:software) RETURN 'it''s' AS t LIMIT 1").to_list()   // #{"t": "it's"}

Long queries: backtick strings

A Rhai backtick string may span lines and processes no backslash escapes, so a multi-line query reads as it would in any GQL editor. Line breaks are whitespace for GQL; the error positions count lines and columns inside the query.

g.gql(`MATCH (p:person)-[:created]->(s:software)
       WHERE p.age > 30
       RETURN p.name AS who, s.name AS what
       ORDER BY who, what`).to_list()
// #{"what": "lop", "who": "josh"}, #{"what": "ripple", "who": "josh"}, #{"what": "lop", "who": "peter"}

Inside a backtick string both GQL quote forms work unescaped ('lop' and "lop"). Two characters are special to Rhai there:

  • ${ starts a Rhai interpolation: ${expr} is replaced by the value of a Rhai expression. GQL never needs ${, so this only matters when you use it on purpose (next section). A $ followed by a name, a GQL parameter such as $min, is left alone.
  • A backtick ends the string. A backtick that GQL should see is doubled: Rhai reads `` inside a backtick string as one backtick. GQL back-quoted identifiers are therefore written with doubled backticks there:
g.gql(`MATCH (s:software) RETURN s.name AS ``the name`` ORDER BY ``the name```).to_list()   // #{"the name": "lop"}, #{"the name": "ripple"}

The same query in a "..." string needs no doubling, because a backtick means nothing to a Rhai double-quoted string:

g.gql("MATCH (s:software) RETURN s.name AS `the name` ORDER BY `the name`").to_list()   // #{"the name": "lop"}, #{"the name": "ripple"}
g.gql("MATCH (`my var`:software) RETURN `my var`.name AS n ORDER BY n").to_list()   // #{"n": "lop"}, #{"n": "ripple"}

Values: parameters, not interpolation

Put values into a query as parameters: $name in the query, the value in the map after it. A parameter is a typed value that can never change the query text, whatever it contains:

g.gql(`MATCH (s:software) WHERE s.lang = $lang RETURN s.name AS name ORDER BY name`, #{lang: "java"}).to_list()   // #{"name": "lop"}, #{"name": "ripple"}
g.gql("MATCH (n:person) WHERE n.age > $min RETURN n.name AS name ORDER BY name", #{min: 30}).to_list()   // #{"name": "josh"}, #{"name": "peter"}

Interpolation (${..}) and string concatenation ("..." + x + "...") paste the value in as query text. It runs, but a value with a quote in it breaks the query (or changes it), a number becomes text, and nothing is checked:

{ let name = "o'brien"; g.gql(`MATCH (p:person) WHERE p.name = '${name}' RETURN p.age AS age`).to_list() }   // error: unterminated string literal
{ let name = "o'brien"; g.gql(`MATCH (p:person) WHERE p.name = $name RETURN p.age AS age`, #{name: name}).to_list() }   // no rows, no error

In the first query the quote in the value ends the GQL string literal early; in the second the value is compared as it is.

Parameters also keep the plan reusable and let a property index serve the lookup (Index use). A parameter name that is not an identifier is back-quoted: $`my value` (in a backtick string $``my value``).

Comments

GQL has three comment forms, and all of them work inside both Rhai string forms (Rhai does not look for comments inside a string):

  • // ... to the end of the line;
  • /* ... */, not nested;
  • -- ... to the end of the line, the ISO GQL form.
g.gql(`-- people older than 30
MATCH (p:person)            // every person
  WHERE p.age > 30          /* only the older ones */
RETURN p.name AS name       -- one column
ORDER BY name`).to_list()
// #{"name": "josh"}, #{"name": "peter"}

The -- rule. -- is a comment in GQL but an edge in Cypher ((a)--(b)). Graphersal reads -- as an edge when the next character is > or ( (-->, --(), or when the token before it is a ) on the same line ((a)--(b), (a) -- (b)); everywhere else it starts a comment. So a -- comment on a line of its own or after a value is a comment, and an edge pattern is never misread. The one trap: a -- comment written right after a node pattern on the same line becomes an edge and the query fails loudly; use // there.

g.gql(`MATCH (a:person)--(b:software) RETURN a.name AS a, b.name AS b ORDER BY a, b`).to_list()
// josh/lop, josh/ripple, marko/lop, peter/lop
g.gql(`MATCH (p:person) -- every person
       RETURN p.name AS name`)   // error: unexpected `every`: this -- is read as an edge

Which string to use

QueryUse
one line, string literals"..." with GQL '...' literals
several lines, commentsa backtick string
values from your program$name parameters, never ${..} or +
a back-quoted GQL name"..." (no doubling), or doubled backticks in a backtick string

The MCP tool gql: no Rhai string at all

An agent connected to the dev server's MCP endpoint can call the tool gql with the query as plain text and the parameters as a JSON object, so none of the quoting above applies:

{
  "query": "MATCH (p:person)-[:knows]->(f) WHERE p.name = $name RETURN f.name AS friend ORDER BY friend",
  "params": {"name": "marko"},
  "max_rows": 100
}

It runs the same g.gql(..) call with the parameters as values and returns the rows like the query tool, in written column order. Like the query tool it may write (INSERT; the answer says that it changed the graph, with a one-line summary such as +3 vertices, +2 edges), and a server started with --mcp-read-only still offers it but refuses its writes. Prefer it whenever an agent writes GQL: there is no Rhai string to escape and no interpolation to get wrong. To continue a GQL result with Gremlin steps, use the query tool with g.gql(..) in the script.

Cypher Aliases

gql() speaks ISO GQL. Common Cypher spellings are accepted as aliases where they are unambiguous and mean exactly the same: an alias is translated to its GQL form while the query is parsed, so both spellings give the same plan and the same rows. An alias never has a meaning of its own. This table lists every accepted alias; Cypher functions without any GQL counterpart are the compatibility functions below, and Cypher's map projections and comprehensions, COUNT { }, COLLECT { }, SET n += .., MERGE and the regular-expression match =~ the compatibility forms (Map projections and comprehensions, Regular-expression match, COUNT and COLLECT, SET and REMOVE, MERGE); any other Cypher spelling is either not supported yet or refused.

Cypher spellingGQL formNotes
SKIP nOFFSET n
a != ba <> b
s1 + s2 on two stringss1 || s2also on two lists; + of a string and a number is an error (no implicit conversion: write s + toString(n) or s || CAST(n AS STRING))
(n:A:B)(n:A&B)plain names only; mixing :A:B with |, & or ! is an error (write it with &)
-[:A|:B]->-[:A|B]->a colon after the | of a label disjunction
n:A in an expressionn IS LABELED A
-->->abbreviated edge pointing right
<--<-abbreviated edge pointing left
---abbreviated edge, either direction (the -- rule)
<--><->either direction
elementId(x)element_id(x)the id as a string
toUpper(s)upper(s)
toLower(s)lower(s)
size(s) on a stringchar_length(s)size(list) is the item count, as cardinality(list)
collect(x)collect_list(x)also collect(DISTINCT x)
percentileCont(x, p), percentileDisc(x, p)percentile_cont(x, p), percentile_disc(x, p)ISO's binary set functions, value first (Aggregation)
length(p)path_length(p)the number of edges of a path
log(x) (one argument)ln(x)the natural logarithm; the two-argument log(base, x) is GQL's general logarithm
-[e:T*]->-[e:T]->{1,}Cypher's lower bound is 1: not GQL's postfix *, which is {0,}
-[e:T*n]->-[e:T]->{n}
-[e:T*m..n]->-[e:T]->{m,n}
-[e:T*..n]->-[e:T]->{1,n}lower bound 1 again
-[e:T*m..]->-[e:T]->{m,}
-[e:T*m..n]-> with m > n, -[e:T*..0]->no matchthe empty interval matches nothing (no row; OPTIONAL MATCH gives its NULL row); the GQL {3,1} is a syntax error
a < b <= c, a chained comparisona < b AND b <= cany mix of =, <>, <, <=, >, >=; the middle operand is evaluated once per comparison
WHERE (a)-[:T]->(b), a pattern predicateWHERE EXISTS { (a)-[:T]->(b) }where a condition stands (WHERE, FILTER, under NOT / AND / OR / XOR, a comprehension's WHERE, a searched CASE WHEN; elsewhere 42001); it may name only variables bound before it (EXISTS)
UNWIND list AS xFOR x IN listone row per item; WITH ORDINALITY / WITH OFFSET only after FOR
CREATE <pattern>INSERT <pattern>the same clause: once per row, nodes with label conjunctions (:A:B as :A&B), directed edges with one label (Writing with GQL); CREATE INDEX / CONSTRAINT / GRAPH are refused catalog commands
CALL { WITH a, b ... }, the importing WITHCALL (a, b) { ... }the first WITH of the body, when it lists plain variables only, is the variable scope clause (CALL subqueries)
SET n:A:B, REMOVE n:A:BSET n:A, n:B, REMOVE n:A, n:Bthe labels in order; SET n IS A & B likewise (Writing with GQL)
SET (n).k = v, REMOVE (n).kSET n.k = v, REMOVE n.ka parenthesized variable as the target
localtime(x), localdatetime(x), datetime(x)local_time(x), local_datetime(x), zoned_datetime(x)the temporal constructors (Dates and times)

Each pair below returns the same rows:

g.gql("MATCH (n:person) RETURN n.name AS name ORDER BY name SKIP 2").to_list()   // #{"name": "peter"}, #{"name": "vadas"}
g.gql("MATCH (n:person) RETURN n.name AS name ORDER BY name OFFSET 2").to_list()   // #{"name": "peter"}, #{"name": "vadas"}
g.gql("MATCH (n:person) WHERE n.age != 29 RETURN n.name AS name ORDER BY name").to_list()   // josh, peter, vadas
g.gql("MATCH (n:person) WHERE n.age <> 29 RETURN n.name AS name ORDER BY name").to_list()   // josh, peter, vadas
g.gql("MATCH (p {name: 'marko'})-->(x) RETURN x.name AS x ORDER BY x").to_list()   // josh, lop, vadas
g.gql("MATCH (p {name: 'marko'})->(x) RETURN x.name AS x ORDER BY x").to_list()   // josh, lop, vadas
g.gql("MATCH (n) WHERE n:software RETURN n.name AS name ORDER BY name").to_list()   // lop, ripple
g.gql("MATCH (n) WHERE n IS LABELED software RETURN n.name AS name ORDER BY name").to_list()   // lop, ripple
g.gql("MATCH (n:person) RETURN elementId(n) AS id, toUpper(n.name) AS up, size(n.name) AS len, n.name + '?' AS q ORDER BY id LIMIT 1").to_list()
// #{"id": "1", "len": 5, "q": "marko?", "up": "MARKO"}
g.gql("MATCH (n:person) RETURN element_id(n) AS id, upper(n.name) AS up, char_length(n.name) AS len, n.name || '?' AS q ORDER BY id LIMIT 1").to_list()
// #{"id": "1", "len": 5, "q": "marko?", "up": "MARKO"}
g.gql("MATCH (p:person)-[:created]->(s) RETURN p.name AS name, collect(s.name) AS sw ORDER BY name").to_list()
// #{"name": "josh", "sw": ["ripple", "lop"]}, #{"name": "marko", "sw": ["lop"]}, #{"name": "peter", "sw": ["lop"]}
g.gql("MATCH (p:person)-[:created]->(s) RETURN p.name AS name, collect_list(s.name) AS sw ORDER BY name").to_list()
// #{"name": "josh", "sw": ["ripple", "lop"]}, #{"name": "marko", "sw": ["lop"]}, #{"name": "peter", "sw": ["lop"]}
g.gql("MATCH p = (a {name: 'marko'})-[*1..2]->(b) RETURN b.name AS b, length(p) AS len ORDER BY len, b").to_list()
// josh 1, lop 1, vadas 1, lop 2, ripple 2
g.gql("MATCH p = (a {name: 'marko'})-[]->{1,2}(b) RETURN b.name AS b, path_length(p) AS len ORDER BY len, b").to_list()
// josh 1, lop 1, vadas 1, lop 2, ripple 2
g.gql("MATCH (n:person {name: 'marko'}) RETURN log(100) AS l").to_list()   // #{"l": 4.605170185988092}
g.gql("MATCH (n:person {name: 'marko'}) RETURN ln(100) AS l").to_list()   // #{"l": 4.605170185988092}
g.gql("MATCH (p:person) WHERE (p)-[:created]->() RETURN p.name AS name ORDER BY name").to_list()   // josh, marko, peter
g.gql("MATCH (p:person) WHERE EXISTS { (p)-[:created]->() } RETURN p.name AS name ORDER BY name").to_list()   // josh, marko, peter
g.gql("MATCH (p:person {name: 'marko'}) UNWIND [p.age, p.age + 1] AS a RETURN a ORDER BY a").to_list()   // #{"a": 29}, #{"a": 30}
g.gql("MATCH (p:person {name: 'marko'}) FOR a IN [p.age, p.age + 1] RETURN a ORDER BY a").to_list()   // #{"a": 29}, #{"a": 30}
g.gql("MATCH (p:person) CALL { WITH p MATCH (p)-[:knows]->(f) RETURN count(f) AS n } RETURN p.name AS name, n ORDER BY name").to_list()   // josh 0, marko 2, peter 0, vadas 0
g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[:knows]->(f) RETURN count(f) AS n } RETURN p.name AS name, n ORDER BY name").to_list()   // josh 0, marko 2, peter 0, vadas 0
g.gql("CREATE (c:city:capital {name: 'Rome'}) RETURN labels(c) AS l").to_list()   // #{"l": ["city", "capital"]}
g.gql("INSERT (c:city&capital {name: 'Rome'}) RETURN labels(c) AS l").to_list()   // #{"l": ["city", "capital"]}
g.gql("MATCH (p:person {name: 'marko'}) SET p:admin:staff RETURN labels(p) AS l").to_list()   // #{"l": ["person", "admin", "staff"]}
g.gql("MATCH (p:person {name: 'marko'}) SET p:admin, p:staff RETURN labels(p) AS l").to_list()   // #{"l": ["person", "admin", "staff"]}
g.gql("MATCH (n:person) WHERE 27 <= n.age < 32 RETURN n.name AS name ORDER BY name").to_list()   // marko, vadas
g.gql("MATCH (n:person) WHERE 27 <= n.age AND n.age < 32 RETURN n.name AS name ORDER BY name").to_list()   // marko, vadas
g.gql("MATCH (a {name: 'marko'})-[*2..1]->(b) RETURN b.name AS b").to_list()   // [] (the empty interval)

The importing WITH passes the variables on unchanged; a first WITH that renames, computes or filters (WITH p AS q, WITH p WHERE ..) is an ordinary WITH of a body that imports nothing, so reading p there is an error (write CALL (p) { .. }). A CALL { } without a scope clause and without that WITH imports nothing, as in Neo4j Cypher 25.

Mind the Cypher *: -[*]-> starts at one edge, GQL's -[]->* at zero, so the GQL form also returns marko himself:

g.gql("MATCH (a {name: 'marko'})-[*]->(b) RETURN b.name AS b ORDER BY b").to_list()   // josh, lop, lop, ripple, vadas
g.gql("MATCH (a {name: 'marko'})-[]->*(b) RETURN b.name AS b ORDER BY b").to_list()   // josh, lop, lop, marko, ripple, vadas

The Cypher clause WITH

WITH is Cypher; GQL writes the same with its linear statements (LET, FILTER, and RETURN ... NEXT, UNION and NEXT). gql() accepts WITH with Cypher's meaning: it passes on only its items, may take DISTINCT, aggregates, ORDER BY, SKIP / OFFSET, LIMIT and a WHERE (applied last), and a later clause continues from its columns (The Supported Subset). A WITH that only passes values on is the same as LET plus a narrower scope, and its WHERE the same as FILTER:

g.gql("MATCH (p:person) WITH p, p.age / 10 AS d WHERE d = 3 RETURN p.name AS name ORDER BY name").to_list()   // #{"name": "josh"}, #{"name": "peter"}
g.gql("MATCH (p:person) LET d = p.age / 10 FILTER d = 3 RETURN p.name AS name ORDER BY name").to_list()   // #{"name": "josh"}, #{"name": "peter"}
g.gql("MATCH (p:person) RETURN p, p.age / 10 AS d NEXT FILTER d = 3 RETURN p.name AS name ORDER BY name").to_list()   // #{"name": "josh"}, #{"name": "peter"}

Spellings that are GQL as well

These look like Cypher but are GQL too, so they are not aliases: : before a label expression (GQL also has IS), ASC / DESC (also ASCENDING / DESCENDING), string literals in '...' and "...", // and /* */ comments, $name parameters, back-quoted names.

The functions abs, floor, ceil, sqrt, exp, log10, left, right, ltrim, rtrim, btrim, trim(s), nullif (Cypher nullIf; names are case-insensitive) and coalesce have the same name in both languages and are GQL functions. Where Neo4j's version differs, GQL's meaning wins: trim(s), ltrim(s) and rtrim(s) remove spaces only (Cypher removes any whitespace), and floor(3) / ceil(3) of an integer stay integers (Neo4j returns floats that compare equal). ceiling(x) is GQL's second spelling of ceil(x).

Compatibility functions

Some Cypher functions have no GQL counterpart at all, so they cannot be aliases. gql() accepts a fixed list of them, because Cypher users and LLMs write them all the time, with their openCypher / Neo4j Cypher 25 meaning: a query using them means the same as in Neo4j, except where Semantics says otherwise. They never get a meaning of their own, and no vendor function joins them (apoc.*, text.* are refused).

FunctionFamilyGQL nearest form
toInteger(x), toFloat(x), toBoolean(x), toString(x)conversionsCAST(x AS INTEGER | FLOAT | BOOLEAN | STRING), but stricter (below)
toIntegerOrNull(x), toFloatOrNull(x), toBooleanOrNull(x), toStringOrNull(x)conversionsnone
substring(s, start [, length])stringsleft(s, n), right(s, n)
replace(s, search, replacement [, limit]), split(s, delimiter), reverse(x), isEmpty(x)strings, listsnone
round(x [, precision [, mode]]), sign(x)numbersnone
head(list), last(list), tail(list), range(start, end [, step])liststrim(list, n) drops items from the end
keys(x), properties(x)elementsx.key reads one property
startNode(e), endNode(e)elementsthe predicates n IS SOURCE OF e, n IS DESTINATION OF e
nodes(p), relationships(p)pathsGQL's elements(p) (not supported yet)
all(x IN l WHERE c), any(..), none(..), single(..)list predicatesnone; a list comprehension counted with size() (below)
reduce(acc = init, x IN l | expr)listsnone; FOR x IN l and an aggregate fold the rows of a query, not a list per row
date.truncate(unit, x) and the other X.truncate(), duration.between(a, b), duration.inMonths() / inDays() / inSeconds(), X.statement(), X.transaction(), datetime.fromepoch(), datetime.fromepochmillis(), toString(temporal)dates and timesthe constructors date(), local_time(), ... and duration() (Dates and times)

CAST is not an alias of toInteger(). Both convert with the same rules, but they treat a text that does not convert differently: GQL's CAST fails the query with 22018, Cypher's toInteger / toFloat / toBoolean give NULL, and the ...OrNull forms also give NULL for a value of the wrong kind. toInteger and toFloat also read Cypher literals ('0x1F', '1_000'), CAST only decimal text. Use CAST to catch dirty data, toInteger to skip it (Semantics).

g.gql("MATCH (n:person {name: 'marko'}) RETURN toInteger('42') AS a, CAST('42' AS INTEGER) AS b").to_list()   // #{"a": 42, "b": 42}
g.gql("MATCH (n:person {name: 'marko'}) RETURN toInteger('forty') AS a").to_list()   // #{"a": ()}
g.gql("MATCH (n:person {name: 'marko'}) RETURN CAST('forty' AS INTEGER) AS b")   // error: invalid character value for cast (22018)
g.gql("MATCH (a)-[e:knows]-(b) WHERE startNode(e) = a RETURN a.name AS a, b.name AS b ORDER BY b").to_list()   // #{"a": "marko", "b": "josh"}, #{"a": "marko", "b": "vadas"}
g.gql("MATCH (a)-[e:knows]-(b) WHERE a IS SOURCE OF e RETURN a.name AS a, b.name AS b ORDER BY b").to_list()   // #{"a": "marko", "b": "josh"}, #{"a": "marko", "b": "vadas"}

List predicates and reduce

all(x IN l WHERE c), any(..), none(..) and single(..) test the items of a list, and reduce(acc = init, x IN l | expr) folds them: acc starts at init and takes the value of expr for each item in list order. x (and acc) exist only inside the call and must be new names, like a list comprehension's variable. The WHERE is required; an aggregate may stand in the list and in init, not in the condition or after |. Their NULL rules are the three-valued ones of the openCypher TCK, which Neo4j Cypher 25 follows:

  • a NULL list gives NULL (reduce too), a value that is not a list is error 22G03;
  • a decided answer wins and stops at once: all is FALSE at the first FALSE item, any TRUE and none FALSE at the first TRUE one, single FALSE at the second TRUE one (later items are not evaluated);
  • otherwise an item whose condition is NULL makes the answer NULL;
  • otherwise all and none are TRUE, any FALSE, single whether exactly one item was TRUE; so for an empty list all / none are TRUE, any / single FALSE, and reduce gives init.

A list comprehension counted with size() gives the same answer when no condition is NULL (it drops a NULL condition instead): all is size([x IN l WHERE c]) = size(l), any is > 0, none is = 0, single is = 1. Over a pattern comprehension the predicates test the matches of a pattern per row, the Gremlin where(__..) / not(__..):

g.gql("RETURN all(x IN [1, NULL] WHERE x > 0) AS a, any(x IN [1, NULL] WHERE x > 0) AS b, single(x IN [1, 2] WHERE x > 1) AS c, none(x IN [] WHERE x > 1) AS d").to_list()   // #{"a": (), "b": true, "c": true, "d": true}
g.gql("MATCH (p:person) WHERE any(a IN [(p)-[:knows]->(f) | f.age] WHERE a > 30) RETURN p.name AS name").to_list()   // #{"name": "marko"}
g.V().hasLabel("person").where(__.out("knows").has("age", P.gt(30))).values("name").to_list()   // "marko"
g.gql("MATCH (p:person) WHERE none(w IN [(p)-[:created]->(s) | s] WHERE w.name = 'lop') RETURN p.name AS name").to_list()   // #{"name": "vadas"}
g.V().hasLabel("person").not(__.out("created").has("name", "lop")).values("name").to_list()   // "vadas"
g.gql("MATCH (p:person) RETURN p.name AS name, reduce(total = 0, w IN [(p)-[e]->() | e.weight] | total + w) AS weight ORDER BY name").to_list()
// josh 1.4, marko 1.9, peter 0.2, vadas 0 (reduce starts at 0)
g.V().hasLabel("person").order().by("name").project("name", "weight").by("name").by(__.out_e().values("weight").fold().sum(Scope.local)).to_list()
// josh 1.4, marko 1.9, peter 0.2, vadas without "weight" (the sum of no values is no value)
g.gql("MATCH (p:person) RETURN reduce(s = '', n IN collect_list(p.name) | s || n) AS names").to_list()   // one string of the four names

Regular-expression match

GQL has no regular-expression operator, so Cypher's s =~ pattern is a compatibility form with Neo4j's meaning: TRUE when the pattern matches the whole string (Java's String.matches), so 'marko' =~ 'mar' is FALSE and 'marko' =~ 'mar.*' TRUE; an alternation is anchored as a whole ('josh' =~ 'mark|jos' is FALSE). It binds like STARTS WITH, and NOT s =~ p negates it. A NULL or non-string operand gives NULL, as for STARTS WITH.

The pattern is written in the syntax of the Rust regex crate, not Java's: no look-around, no back-references, matching linear in the text; inline flags such as (?i) work. A pattern that is no valid expression is error 2201B: a literal or $parameter pattern before the query runs (it is compiled once), a pattern computed per row when a row reaches it (Semantics). On a property with a literal or $parameter pattern it becomes has(key, TextP.regex("^(?:pattern)$")) (Plans).

g.gql("MATCH (n:person) WHERE n.name =~ 'm.*' RETURN n.name AS name").to_list()   // #{"name": "marko"}
g.V().hasLabel("person").has("name", TextP.regex("^(?:m.*)$")).values("name").to_list()   // "marko"
g.gql("MATCH (n:person) WHERE n.name =~ '(?i)J.*' RETURN n.name AS name").to_list()   // #{"name": "josh"}
g.gql("MATCH (n:person) RETURN n.name AS name, n.name =~ '.*a.*' AS a ORDER BY name").to_list()   // josh false, marko true, peter false, vadas true
g.gql("MATCH (n:person) WHERE n.name =~ 'm(' RETURN n.name AS name")   // error: invalid regular expression (2201B)

Map projections and comprehensions

Three Cypher expression forms have no GQL counterpart with the same meaning, so they are not aliases either. gql() accepts them as compatibility forms, like the compatibility functions: with their openCypher / Neo4j Cypher 25 meaning, because they are how Cypher users and LLMs ask for nested, JSON-shaped answers (The Supported Subset).

Cypher formGQL nearest formDifference
map projection p {.name, .age, .*, f, k: expr}the record constructor {name: p.name, age: p.age, f: f, k: expr} (or RECORD {..})for a NULL p the projection is NULL, the record {name: NULL, ...}; .* has no record form (properties(p) is the map of all properties)
list comprehension [x IN list WHERE cond | expr]none; FOR x IN list FILTER cond RETURN collect_list(expr) gives one list per query, not per row
pattern comprehension [(p)-[:R]->(f) WHERE cond | expr]none; OPTIONAL MATCH (p)-[:R]->(f) WHERE cond + collect_list(expr) groups the rows insteadthe comprehension keeps the row and gives [] when nothing matches

The projection and the record give the same map whenever the variable is not NULL:

g.gql("MATCH (p:person) RETURN p {.name, .age} AS m ORDER BY p.name LIMIT 1").to_list()   // #{"m": #{"age": 32, "name": "josh"}}
g.gql("MATCH (p:person) RETURN {name: p.name, age: p.age} AS m ORDER BY p.name LIMIT 1").to_list()   // #{"m": #{"age": 32, "name": "josh"}}
g.gql("MATCH (p:person) RETURN p.name AS name, [(p)-[:created]->(s) | s.name] AS sw ORDER BY name").to_list()
// josh [ripple, lop] (in any order), marko [lop], peter [lop], vadas []
g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s) RETURN p.name AS name, collect_list(s.name) AS sw ORDER BY name").to_list()
// josh [ripple, lop], marko [lop], peter [lop], vadas []

Cypher's list predicates all(), any(), none(), single() and reduce() bind a variable the same way; they are compatibility functions.

COUNT and COLLECT

Cypher's COUNT { } and COLLECT { } subqueries have no GQL counterpart either; gql() accepts them as compatibility forms with their Neo4j Cypher 25 meaning (COUNT and COLLECT). They take the bodies of EXISTS: a pattern, MATCH clauses, or a whole query ending in RETURN (one item for COLLECT).

Cypher formGQL nearest formDifference
COUNT { <pattern or query> }CALL (p) { OPTIONAL MATCH .. RETURN count(x) AS n }, or OPTIONAL MATCH + count()the subquery keeps the row and stands in any expression; COUNT { } > 0 is EXISTS { }
COLLECT { <query> RETURN x }CALL (p) { OPTIONAL MATCH .. RETURN collect_list(x) AS l }COLLECT keeps NULL items, collect_list() skips them
g.gql("MATCH (p:person) RETURN p.name AS name, COUNT { (p)-[:created]->() } AS n ORDER BY name").to_list()   // josh 2, marko 1, peter 1, vadas 0
g.gql("MATCH (p:person) CALL (p) { OPTIONAL MATCH (p)-[:created]->(s) RETURN count(s) AS n } RETURN p.name AS name, n ORDER BY name").to_list()   // josh 2, marko 1, peter 1, vadas 0
g.gql("MATCH (p:person) RETURN p.name AS name, COLLECT { MATCH (p)-[:created]->(s) RETURN s.name ORDER BY s.name } AS sw ORDER BY name").to_list()
// josh [lop, ripple], marko [lop], peter [lop], vadas []
g.gql("MATCH (p:person) CALL (p) { OPTIONAL MATCH (p)-[:created]->(s) WITH s ORDER BY s.name RETURN collect_list(s.name) AS sw } RETURN p.name AS name, sw ORDER BY name").to_list()
// josh [lop, ripple], marko [lop], peter [lop], vadas []

One difference from Neo4j: a COUNT { } body whose final RETURN only projects is counted without evaluating its items (Semantics).

SET and REMOVE

GQL's SET items are a property (SET n.k = v), all properties from a braced map (SET n = {k: v}) and a label (SET n:A / SET n IS A); REMOVE takes a property or a label. Two Cypher forms have no GQL counterpart and are accepted as compatibility forms with Cypher's meaning:

  • SET n += map merges the map into the properties: the keys of the map are set (a NULL value removes its key), the other properties stay.
  • SET n = expr with an expression that is not a braced map: a $parameter or any map value replaces every property, and a node or an edge stands for its properties, so SET n = m copies them (SET n = n changes nothing). Write SET n = properties(m) for the same as a plain map.

A NULL on the right of = or += is an error (22004) rather than an empty map; write coalesce($map, {}) (Semantics). This is our choice for the compatibility form, where Neo4j removes every property: standard GQL has no such form, since its SET n = {..} takes a braced map only.

g.gql("MATCH (p:person {name: 'marko'}) SET p += {city: 'Rome'} RETURN properties(p) AS props").to_list()   // #{"props": #{"age": 29, "city": "Rome", "name": "marko"}}
g.gql("MATCH (p:person {name: 'marko'}) SET p = $props RETURN properties(p) AS props", #{props: #{name: "marko", city: "Rome"}}).to_list()   // #{"props": #{"city": "Rome", "name": "marko"}}
g.gql("MATCH (p:person {name: 'marko'}), (q:person {name: 'josh'}) SET p = q RETURN properties(p) AS props").to_list()   // #{"props": #{"age": 32, "name": "josh"}}
g.gql("MATCH (p:person {name: 'marko'}) SET p += $more", #{more: ()})   // error: the right side of SET p += .. is NULL, not a map

MERGE

Cypher's MERGE ("find or create") has no ISO GQL counterpart. gql() accepts it as a compatibility form with Neo4j Cypher 25's meaning, and with it its ON CREATE SET and ON MATCH SET actions:

CypherIn gql()Notes
MERGE <pattern>supported as a compatibility formone path pattern per clause; per row, every match is a row, or the whole pattern is created; each row sees the rows before it (Writing with GQL)
ON CREATE SET <items>, ON MATCH SET <items>supported as a compatibility formthe items of SET, several actions in any order, applied in the order written
MERGE p = <pattern>supportedthe path found or created
MERGE (a)-[:T]-(b) without a directionsupportedmatches either direction, creates from left to right

Plain GQL writes the same with a CALL body that inserts only when nothing exists:

g.gql("MERGE (c:city {name: 'Berlin'}) RETURN c.name AS name").to_list()   // #{"name": "Berlin"}
g.gql("CALL { FILTER NOT EXISTS { MATCH (:city {name: 'Berlin'}) } INSERT (:city {name: 'Berlin'}) } MATCH (c:city {name: 'Berlin'}) RETURN c.name AS name").to_list()   // #{"name": "Berlin"}

The differences from Neo4j are on Semantics.

Dates and times

The temporal constructors have an ISO GQL name and a Cypher name; the Cypher names are aliases (the same function, the same value). The qualified Cypher functions have no ISO spelling: they are compatibility functions with Neo4j's meaning (Dates and times).

CypherISO GQLNotes
date(x)date(x)the same name
localtime(x)local_time(x)a time of day without an offset
localdatetime(x)local_datetime(x)
datetime(x)zoned_datetime(x)an instant with its UTC offset (and its zone name)
time(x)zoned_time(x)a time of day with its UTC offset
duration(x)duration(x)the same name
date.truncate(), localtime.truncate(), time.truncate(), localdatetime.truncate(), datetime.truncate()nonecompatibility functions
duration.between(), duration.inMonths(), duration.inDays(), duration.inSeconds()nonecompatibility functions; ISO's duration_between() is an unknown function that suggests duration.between()
X.statement(), X.transaction(); datetime.fromepoch(), datetime.fromepochmillis()nonecompatibility functions; the clocks give the time the query started

| X.realtime() | none | refused: a clock that moves while the query runs |

g.gql("RETURN datetime('2015-07-21T21:40+01:00') = zoned_datetime('2015-07-21T21:40+01:00') AS a, localtime('12:00') = local_time('12:00') AS b, localdatetime('2015-07-21T21:40') = local_datetime('2015-07-21T21:40') AS c").to_list()
// #{"a": true, "b": true, "c": true}
g.gql("RETURN zoned_time('12:00+01:00') = time('12:00+01:00') AS t").to_list()   // #{"t": true}

Cypher spellings that are not aliases

CypherIn gql()
id(n)refused: an integer in Neo4j, Graphersal ids are strings; use element_id(n)
nodes(p), relationships(p)supported as compatibility functions, not aliases: GQL has no such functions
x ^ ysupported as a compatibility operator: GQL has no operator for it; it means power(x, y) (always a float, the same errors), binding tighter than * and looser than a unary minus
rand(), randomUUID()refused: gql() functions are deterministic
time(), time.*(); date.realtime() and the other X.realtime()time() not supported yet (no time-with-offset type: use localtime() or datetime()); X.realtime() refused, like rand() (Dates and times)
map projections, list and pattern comprehensionssupported as compatibility forms, not aliases
any() / all() / none() / single(), reduce()supported as compatibility functions, not aliases: GQL has no such functions
COUNT { }, COLLECT { }supported as compatibility forms, not aliases
CALL { } IN TRANSACTIONSrefused: a write form; the CALL itself is supported
exists(n.p) (Cypher 4)refused: EXISTS takes a pattern; test a property with n.p IS NOT NULL
GROUP BY (not Cypher)ISO GQL, accepted after the RETURN items (optional: grouping is implicit); after WITH an error that explains implicit grouping
MERGEsupported as a compatibility form, with ON CREATE SET / ON MATCH SET
FOREACHnot supported yet (Writing with GQL); CREATE is an alias of INSERT; SET and REMOVE are supported, += as a compatibility form
DELETE, DETACH DELETEthe same in GQL, supported (Writing with GQL); GQL also writes the default explicitly as NODETACH DELETE
SET n[key] = v, SET n:$(expr) (Cypher 25 dynamic keys and labels)not supported; name the key and the label in the query
CALL proc(..) YIELD ..supported for saved queries written in GQL: CALL folder.name(..) with YIELD, YIELD * and the standalone forms of Cypher (Calling saved queries)
CALL db.*(), dbms.*, apoc.*, gds.*, SHOW ...refused: vendor extensions
a--1 (minus minus one)a comment starts at -- (GQL wins): RETURN n.age--1 AS x returns the column n.age; write n.age - -1

Refused Constructs

Some constructs gql() refuses for good, not just for now. A refused construct fails before the traversal runs, with GQLSTATUS 0A000, a caret under it and a help line naming what to use instead. (Constructs that are only not supported yet are listed on The Supported Subset.) GROUP BY is neither: it is accepted after the RETURN items, and grouping is implicit anyway; after WITH (no ISO counterpart) it is a syntax error whose help shows the query without it (Aggregation).

ConstructWhyInstead
undirected edges ~[e]~, <~[e]~, ~[e]~>, ~, <~, ~>Graphersal edges are always directed; there is no undirected edge to match-[e]-, an edge in either direction
catalog commands CREATE INDEX, CREATE CONSTRAINT, CREATE GRAPH, CREATE DATABASEnot part of a query: indexes, schemas and graphs are the host'sg.create_index(..), g.set_schema(..), opening another graph
LOAD CSVa vendor extension, not GQLthe host's import (GraphSON, GraphML), or the rows as a list parameter: FOR row IN $rows INSERT (..)
vendor procedures: the namespaces db, dbms, apoc and gds (CALL db.labels(), CALL apoc.*)vendor extensions, not GQL (an inline CALL { } subquery is supported, and any other CALL folder.name(..) calls a saved query)the Gremlin steps that do the same, such as g.v().label().dedup(), or a saved GQL query that does it
CALL { ... } IN TRANSACTIONScommits the writes of a subquery in batches; a gql() query is one unit, which commits at once or not at allthe same CALL without IN TRANSACTIONS
SHOW ...a vendor command, not GQLthe catalog steps (indexes(), queries(), get_schema(), statistics())
vendor path search *BFS, *WSHORTEST, *ALLSHORTESTvendor extensions, not GQLGremlin repeat()
id(n)Cypher's id() is an integer; Graphersal ids are strings, and returning a different type under the same name would misleadelement_id(n), the id as a string
exists(n.p), the Cypher 4 property testEXISTS is GQL's subquery predicate and takes a graph pattern; reading it as a property test as well would give one keyword two meaningsn.p IS NOT NULL; EXISTS { (n)-[:T]->() } tests a pattern (EXISTS)
USE graphgql() runs on the graph of its traversal sourceopen the other graph and run there
non-deterministic functions rand(), randomUUID()every gql() function is pure, so a LET or WITH name may stand for its expression and the plan stays deterministic; a random value would differ between its usesGremlin after gql(): sample(n) or coin(p) to pick rows at random
vendor and namespaced functions apoc.*, db.*, gds.*, text.*, ...vendor extensions, not GQL; the accepted Cypher functions are a fixed list (compatibility functions)a gql() function, or Gremlin steps after gql()
g.gql("MATCH (a)~[e]~(b) RETURN a")   // refused: undirected edges (`~`) are not supported
g.gql("CALL db.labels() YIELD label RETURN label")   // refused: the vendor procedures of db, dbms, apoc and gds are vendor extensions
g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[:created]->(s) RETURN s.name AS sw } IN TRANSACTIONS RETURN sw")   // refused: CALL { } IN TRANSACTIONS commits writes in batches
g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[:created]->(s) RETURN s.name AS sw } RETURN sw ORDER BY sw").to_list()   // lop, lop, lop, ripple
g.gql("SHOW INDEXES")   // refused: SHOW commands are vendor extensions
g.gql("CREATE INDEX FOR (n:person) ON (n.name)")   // refused: CREATE INDEX is a catalog command
g.gql("LOAD CSV FROM 'people.csv' AS row RETURN row")   // refused: LOAD CSV is a vendor extension
g.gql("MATCH (n) RETURN id(n)")   // refused: use element_id(n)
g.gql("MATCH (a)-[:knows*BFS]->(b) RETURN b")   // refused: *BFS is a vendor path search extension
g.gql("USE g MATCH (n) RETURN n")   // refused: USE is not supported
g.gql("MATCH (n:person) WHERE exists(n.age) RETURN n.name AS name")   // refused: exists(value) is the Cypher 4 property test
g.gql("MATCH (n:person) WHERE n.age IS NOT NULL RETURN n.name AS name ORDER BY name").to_list()   // josh, marko, peter, vadas
g.gql("MATCH (n) RETURN rand() AS r")   // refused: rand() is a non-deterministic function
g.gql("MATCH (n) RETURN apoc.text.join(['a', 'b'], ',') AS r")   // refused: apoc.text.join() is a vendor function
g.gql("MATCH (n:person) RETURN n.name AS name ORDER BY name").sample(1).count().next()   // 1
g.gql("MATCH (n) RETURN element_id(n) AS id ORDER BY id LIMIT 2").to_list()   // #{"id": "1"}, #{"id": "2"}

Writes are supported (INSERT, SET, REMOVE, DELETE, and Cypher's MERGE as a compatibility form: Writing with GQL); Cypher's FOREACH is not supported yet and is listed there. The full message of a refused construct reads:

Error: GQL unsupported construct at line 1, column 1: CREATE INDEX is a catalog command, not part of a gql() query (step #1 'gql:error("0A000")' refused the query before the traversal ran)
  at #1: v().gql:error("0A000")
             ^^^^^^^^^^^^^^^^^^
  query:     CREATE INDEX FOR (n:person) ON (n.name)
             ^^^^^^^^^^^^
  GQLSTATUS: 0A000
Help: create a property index with g.create_index(#{label: "person", key: "age"}); every query that can use it then does. gql() does not support this construct; write this part of the query as Gremlin steps.

Errors

A GQL error is a TraverserError::Gql (feature gql) with a kind, a message, the position (line and column inside the query), a caret under the offending text, the expected tokens, a "did you mean" suggestion where one fits, and a GQLSTATUS code, the five-character status code of ISO GQL (derived from SQL's SQLSTATE). Like every Graphersal error it has a Help: line that names the fix.

Errors before the run

A query that does not parse or bind fails before the traversal runs, even when no traverser would ever reach the step, as math() does with an equation. On the empty graph, where nothing matches, the query is still checked:

g.gql("MATCH (n:person) RETURN n.name +")   // error: unexpected end of input
Error: GQL syntax error at line 1, column 33: unexpected end of input (step #1 'gql:error("42001")' refused the query before the traversal ran)
  at #1: v().gql:error("42001")
             ^^^^^^^^^^^^^^^^^^
  query:     MATCH (n:person) RETURN n.name +
                                             ^
  expected:  an expression
  GQLSTATUS: 42001
Help: Expected an expression at the marked position. Fix the query at the marked position: a GQL read query is MATCH <pattern> [WHERE <condition>], then any further MATCH, OPTIONAL MATCH, WITH, LET or FILTER clauses, then RETURN <items>, for example g.gql("MATCH (p:person) WHERE p.age > 30 RETURN p.name") or g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s) WITH p, count(s) AS n RETURN p.name, n"). CALL (p) { .. RETURN .. } runs a query for each row, UNION combines the records of two queries and NEXT continues after a RETURN, as in g.gql("MATCH (p:person) RETURN p NEXT MATCH (p)-[:created]->(s) RETURN p.name, s.name"). FOR x IN <list> (Cypher UNWIND <list> AS x) gives one row per item of a list, and a query may also start with FOR, LET, WITH, FILTER or RETURN, as in g.gql("FOR n IN ['marko', 'josh'] MATCH (p:person {name: n}) RETURN n, p.age").

The plan of a query that failed this way is the marker step gql:error("<GQLSTATUS>"), which raises the error before anything runs; the query: line, not the plan, shows the position. In a multi-line query the error names the line and shows only that line:

g.gql(`MATCH (n:person)
       WHERE n.age >
       RETURN n`)   // error: unexpected keyword RETURN at line 3
Error: GQL syntax error at line 3, column 8: unexpected keyword RETURN (step #1 'gql:error("42001")' refused the query before the traversal ran)
  at #1: v().gql:error("42001")
             ^^^^^^^^^^^^^^^^^^
  line 3:           RETURN n
                    ^^^^^^
  expected:  an expression
  GQLSTATUS: 42001

Misspelt keywords, functions and variables get a suggestion:

g.gql("MATCH (n:person) RETRUN n")   // error: unexpected `RETRUN`, did you mean RETURN
g.gql("MATCH (n:person) RETURN m.name")   // error: the variable `m` is not defined, did you mean n
g.gql("MATCH (n:person) WHERE n.age > $min RETURN n.name AS name")   // error: the parameter `$min` has no value
Error: GQL syntax error at line 1, column 18: unexpected `RETRUN` (step #1 'gql:error("42001")' refused the query before the traversal ran)
  at #1: v().gql:error("42001")
             ^^^^^^^^^^^^^^^^^^
  query:        MATCH (n:person) RETRUN n
                                 ^^^^^^
  expected:     `,`, WHERE, MATCH, OPTIONAL MATCH, WITH, LET, FILTER, FOR, UNWIND, CALL, RETURN
  did you mean: RETURN
  GQLSTATUS:    42001
Help: Did you mean RETURN? Expected `,`, WHERE, MATCH, OPTIONAL MATCH, WITH, LET, FILTER, FOR, UNWIND, CALL, ... at the marked position. ...

Errors while the query runs

A valid query can still fail on a row of the data: a division by zero, an overflow, an operand of the wrong kind. These fail the traversal when the row reaches the expression (kind Data, GQLSTATUS class 22), with the caret under the expression and the step that ran it:

g.gql("MATCH (n:person) RETURN n.age / 0 AS x")   // error: division by zero
g.gql("MATCH (n:person) RETURN n.name + 1 AS x")   // error: + joins two strings or adds two numbers, not a string and a number
g.gql("MATCH (n:person) RETURN type(n) AS x")   // error: type() takes an edge, not a node
Error: Step #1 'gql:project("x")' execution failed
  at #1: v().has_label("person").gql:project("x")
                                 ^^^^^^^^^^^^^^^^
  plan:  v(labels: ["person"]).gql:project("x")
                               ^^^^^^^^^^^^^^^^
Caused by: GQL data exception at line 1, column 25: division by zero
  query:     MATCH (n:person) RETURN n.age / 0 AS x
                                     ^^^^^^^^^
  GQLSTATUS: 22012
Help: A row of the data made the marked expression fail. Keep such rows away from it with a WHERE condition or a CASE expression, ...

Comparisons never fail: = of values of different kinds is FALSE (<> TRUE), an ordering < of them is NULL, and any comparison with NULL is NULL (Semantics).

+ of a string and a number names the explicit conversions in its help:

Help: Convert the number or boolean to text first, with toString(x) or CAST(x AS STRING), and join text with ||, as in g.gql("MATCH (p:person) RETURN p.name || ' is ' || toString(p.age) AS s"); or compute with numbers only, converting text with toInteger(x) or toFloat(x). ...

Function errors

A function fails on an argument it cannot take, with a GQLSTATUS that says why and a help line that leads with the fix for that function, then the general advice above:

g.gql("MATCH (n:person) RETURN CAST(n.name AS INTEGER) AS x")   // error: invalid character value for cast (22018)
g.gql("MATCH (n:person) RETURN substring(n.name, -1) AS x")   // error: substring() takes a start of 0 or more (22011)
g.gql("MATCH (n:person) RETURN TRIM(BOTH 'ab' FROM n.name) AS x")   // error: TRIM(.. FROM ..) removes exactly one character (22027)
g.gql("MATCH (n:person) RETURN ln(n.age - 29) AS x")   // error: ln() of a number <= 0 (2201E)
g.gql("MATCH (n:person) RETURN n.name =~ (n.name + '(') AS x")   // error: invalid regular expression (2201B)
g.gql("MATCH (n:person) RETURN sqrt(27 - n.age) AS x")   // error: sqrt() of a negative number (2201F)
g.gql("MATCH (n:person) RETURN range(1, n.age, 0) AS x")   // error: range() step 0 (22023)
g.gql("MATCH (n:person) RETURN toFloat(n.age > 30) AS x")   // error: toFloat() takes a number or a string, not a boolean (22G03)
Caused by: GQL data exception at line 1, column 30: invalid character value for cast: 'marko' is not an INTEGER (expected a decimal number, surrounding spaces allowed)
  query:     MATCH (n:person) RETURN CAST(n.name AS INTEGER) AS x
                                          ^^^^^^
  GQLSTATUS: 22018
Help: CAST is strict: text that is not a value of the target type fails the query. The Cypher conversions are lenient: toInteger(x), toFloat(x) and toBoolean(x) give NULL for such text, and toIntegerOrNull(x), toFloatOrNull(x) and toBooleanOrNull(x) give NULL for a value of any other kind too, as in g.gql("MATCH (p:person) RETURN p.name, toInteger(p.name) AS n"). A row of the data made the marked expression fail. ...

A function gql() knows but does not support gets a message with the reason and the alternative instead of "unknown function", and a misspelt name a suggestion:

g.gql("MATCH (n:person) RETURN sin(n.age) AS x")   // error: sin() (a trigonometric function) is not yet supported
g.gql("MATCH (n:person) RETURN rand() AS x")   // refused: rand() is not supported: a non-deterministic function
g.gql("MATCH (n:person) RETURN toInt(n.age) AS x")   // error: unknown function toInt(), did you mean toInteger()
Error: GQL construct not supported yet at line 1, column 25: sin() (a trigonometric function) is not yet supported in this version (step #1 'gql:error("0A000")' refused the query before the traversal ran)
  ...
  GQLSTATUS: 0A000
Help: Gremlin math() after gql(), for example g.gql("MATCH (n:person) RETURN n.age AS a").select("a").math("sin(_)"). This construct comes in a later version of gql(); until then, write the query without it or as Gremlin steps.

Dates and times

The temporal functions fail with these codes; the help line shows the accepted forms with a runnable example:

CodeWhen
22007text that is no value of the type (date('nonsense'), date('2015-13-01'), an offset in localtime('12:00+01:00'), an offset that is not the zone's in '..+02:00[Europe/London]'); a map with an unknown key or with two groups of date keys; an unknown time zone
22008a field out of range (month: 13, day: 30 in February, hour: 25) or a value outside the years -9999 to 9999, also as the result of arithmetic (date('9999-12-31') + duration('P1D'))
22G03a component the value's type does not have (date(..).hour; the message lists the components it has); a constructor argument of the wrong kind (date(42), localdatetime(date(..))); arithmetic without a meaning (date + date, date * 2); a truncation or difference of a value without the part it needs (date.truncate('day', localtime(..)), duration.inDays() of two local times)
22023a truncation unit the type does not have (date.truncate('hour', ..)) or an unknown unit
22012a duration divided by zero
0A000X.realtime() (refused)
g.gql("RETURN date('nonsense') AS d")   // error: cannot parse "nonsense" as a date (22007)
g.gql("RETURN date({year: 2015, mnth: 3}) AS d")   // error: the map has an unknown field mnth (22007)
g.gql("RETURN datetime({year: 2015, timezone: 'Mars/Olympus'}) AS d")   // error: unknown time zone (22007)
g.gql("RETURN date({year: 2015, month: 13, day: 1}) AS d")   // error: the field month cannot be 13 (22008)
g.gql("RETURN date('9999-12-31') + duration('P1D') AS d")   // error: the result is outside the supported range (22008)
g.gql("RETURN date('2015-01-01').foo AS x")   // error: a date has no component foo; its components are year, quarter, ... (22G03)
g.gql("RETURN date('2015-01-01') * 2 AS x")   // error: * with a temporal value takes a duration and a number (22G03)
g.gql("RETURN date.truncate('fortnight', date('2017-10-11')) AS d")   // error: unknown unit 'fortnight' (22023)
g.gql("RETURN duration('P1D') / 0 AS d")   // error: division by zero (22012)
g.gql("RETURN datetime.realtime() AS t")   // error: datetime.realtime() is not supported (0A000)
Caused by: GQL data exception at line 1, column 13: date(): the field month cannot be 13
  query:     RETURN date({year: 2015, month: 13, day: 1}) AS d
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  GQLSTATUS: 22008
Help: Temporal fields stay within their ranges (month 1 to 12, day within its month, week within its week-numbering year, hour 0 to 23, minute and second 0 to 59, millisecond 0 to 999) and every value within the years -9999 to 9999, as in g.gql("RETURN date({year: 1984, month: 10, day: 11}) AS d, localtime({hour: 23, minute: 59, second: 59, millisecond: 999}) AS t"). A row of the data made the marked expression fail. ...

Scope, grouping and limits

The help of a semantic error explains the rule behind it. A variable that a WITH did not carry on, a value read outside an aggregate that is not a grouping key, and a GROUP BY that leaves out a grouping key each name the fix:

g.gql("MATCH (p:person) WITH p.name AS name RETURN p.age")   // error: the variable `p` is not in scope: the WITH before does not carry it
g.gql("MATCH (p:person) RETURN p.name AS n, count(p.age) + p.age AS x")   // error: `p` is read outside an aggregate and is not a grouping key
g.gql("MATCH (p:person) RETURN p.name AS n, p.age AS a, count(*) GROUP BY n")   // error: the RETURN item `a` has no aggregate, so it is a grouping key, and GROUP BY does not list it
Help: add `p` to the WITH items, as in WITH ..., p. WITH passes on only its columns: a variable it does not list is out of scope after it (only the WHERE of a WITH without an aggregate still reads it), so list every variable a later clause reads, ...
Help: add `p` to the RETURN items (it then becomes a grouping key), or read it inside an aggregate, as in collect(p). A RETURN or WITH with an aggregate groups the rows by its other items (the grouping keys): ...
Help: add it to GROUP BY (GROUP BY ..., a), or remove GROUP BY: grouping is implicit, the items without an aggregate are the keys. ...

A FOR (or UNWIND) defines new names; reusing a name in scope, giving the item and its position one name, or using the position as a node is an error whose help says what FOR defines:

g.gql("MATCH (p:person) FOR p IN [1] RETURN p")   // error: the variable `p` is already defined; FOR defines a new variable
g.gql("FOR x IN [3, 1, 2] WITH OFFSET x RETURN x")   // error: `x` names both the item and its position
Help: choose another name, as in FOR p2 IN <list>. FOR x IN <list> (Cypher UNWIND <list> AS x) gives one row per item of the list, which it reads on the row before the FOR; the item x and, with WITH ORDINALITY i (from 1) or WITH OFFSET i (from 0), its position i are two new variables with names of their own; ...

An unbounded quantifier that reaches repeat.max_loops or traversal.max_traversers fails with the ordinary limit error (RepeatLimitExceeded, ResourceLimitExceeded; no GQLSTATUS), never with fewer rows. Its help is written for GQL: it names the quantified edge, an upper bound to give it and the g.with(..).gql(..) that raises the limit (Semantics):

g.with("traversal.max_traversers", 3).gql("MATCH (a)-[:knows|created]->{1,}(b) RETURN b.name AS b")   // error: traversal.max_traversers exceeded
Caused by: Resource limit 'traversal.max_traversers' exceeded (limit 3, reached 6)
Help: The gql() query kept more traversers (rows in the making) alive between two steps than 'traversal.max_traversers' allows (3). Each path a quantified edge (-[:knows|created]->{1,}) matches is a traverser of its own (trail keeps them apart, so they do not merge), ... give it a lower upper bound, as in -[:knows|created]->{1,5}. ...

A function whose result can be larger than its arguments (range(), split(), replace(), toString() of a list or map, ||) checks the size of its result before it builds it, against traversal.max_materialized_bytes and the memory budget, like collect_list(). A result that is too large fails with the ordinary limit error (ResourceLimitExceeded, no GQLSTATUS: the option and its lock are the engine's), never with a shortened value; inside gql() its help names the growing functions, a bound for them and the g.with(..).gql(..) that raises the limit. The limit counts everything the query holds at once (its rows in the making too), so the result is checked together with what is already held:

g.gql("MATCH (n:person) RETURN range(0, 9223372036854775807) AS r")   // error: Resource limit 'traversal.max_materialized_bytes' exceeded
g.with("traversal.max_materialized_bytes", 100).gql("MATCH (n:person) RETURN split(n.name, '') AS s")   // error: Resource limit 'traversal.max_materialized_bytes' exceeded
Caused by: Resource limit 'traversal.max_materialized_bytes' exceeded (limit 1073741824, reached 18446744073709551615)
Help: The gql() query held more memory at once than 'traversal.max_materialized_bytes' allows (1073741824 bytes); it reached 18446744073709551615 bytes (estimated: the engine's count of its buffers and values). Memory a step frees is given back, so only what is held at the same time counts. A function whose result can be larger than its arguments (range(), split(), replace(), || and CAST(x AS STRING) of a list or map) and the list of collect_list() are checked before they are built, so the query stops instead of running out of memory; the result is never cut short. Build smaller values: bound range() and replace() by the data, as in g.gql("MATCH (p:person) RETURN range(1, p.age / 10) AS r"), ... or raise the limit for the query, g.with("traversal.max_materialized_bytes", 2147483648).gql(..), ...

Subqueries

The errors of an EXISTS subquery or a pattern predicate share one help text that explains subqueries: TRUE or FALSE, never NULL; the body reads the variables bound before it, and the variables it binds stay inside it; a pattern predicate binds no new variable. Before it, each names its own fix:

g.gql("MATCH (p:person) WHERE (p)-[:knows]->(q) RETURN p.name AS name")   // error: the pattern predicate introduces the new variable `q`
g.gql("MATCH (p:person) RETURN p.name AS name, (p)-[:knows]->() AS k")   // error: the pattern stands where a value is expected (42001)
g.gql("MATCH (p:person) WHERE EXISTS { MATCH (p)-[:created]->(s) } RETURN s.name AS s")   // error: the variable `s` is not in scope: it is bound inside a subquery
g.gql("MATCH (a:person) WHERE EXISTS { MATCH (a)-->() WHERE b.age > 1 MATCH (b) } RETURN a")   // error: `b` is bound by a later MATCH clause of the subquery
Help: write it as EXISTS { MATCH (p)-[:knows]->(q) }, whose MATCH may bind new variables, or leave `q` out of the pattern. A subquery, EXISTS { MATCH <pattern> [WHERE <condition>] }, EXISTS { <pattern> } or a Cypher pattern predicate such as (p)-[:created]->(), is TRUE when its body has a match and FALSE otherwise, never NULL; its body reads the variables bound before it, and the variables it binds itself stay inside it. A pattern predicate binds no new variable: name new elements in an EXISTS { MATCH .. }, as in g.gql("MATCH (p:person) WHERE NOT EXISTS { MATCH (p)-[:created]->(s) WHERE s.lang = 'java' } RETURN p.name"), and bind an element in the MATCH clause of the query to read it after the subquery, as in g.gql("MATCH (p:person)-[:created]->(s) RETURN p.name, s.name").
Help: write EXISTS { (p)-[:knows]->() } for whether it has a match, COUNT { (p)-[:knows]->() } for the number of matches, or a pattern comprehension such as [(n)-->(m) | m] for the list of what it matches, as in g.gql("MATCH (p:person) RETURN p.name, COUNT { (p)-[:knows]->() } AS friends, [(p)-[:created]->(s) | s.name] AS made"). A subquery, ...
Help: bind `s` in the MATCH clause of the query to use it here, or test it inside the subquery. A subquery, ...
Help: move the condition to the WHERE of that later MATCH clause inside the subquery. A subquery, ...

A query holds at most 64 subqueries (EXISTS, pattern predicates, pattern comprehensions, COUNT { } and COLLECT { }, nested ones included) and runs at most 1024 subquery bodies, where a LET or WITH variable holding a subquery counts once for every place that reads it. A CALL { } body counts toward neither; CALL bodies and whole-query subquery bodies nest at most 16 levels (UNION, NEXT and CALL). Either limit is 54001 before the run, and its help names both bounds and the forms that need fewer subqueries:

Error: GQL limit exceeded at line 1, column 785: the query holds more than 64 subqueries (EXISTS and pattern predicates), pattern comprehensions included, as are COUNT { } and COLLECT { } ...
Help: join the patterns into fewer subqueries (one EXISTS { MATCH .. } may hold several MATCH clauses and patterns), or add the patterns to the MATCH clause of the query; a pattern comprehension is a subquery too: collect the matches of several patterns with OPTIONAL MATCH and collect_list() instead. The query is larger than gql() accepts: one query holds at most 64 subqueries (EXISTS, pattern predicates, pattern comprehensions, COUNT { } and COLLECT { }, nested ones included) and runs at most 1024 subquery bodies, where a LET or WITH variable holding a subquery counts once for every place that reads it; a CALL { } body counts toward neither (CALL bodies nest at most 16 levels). One EXISTS may hold several MATCH clauses and patterns, as in g.gql("MATCH (p:person) WHERE EXISTS { MATCH (p)-[:knows]->(f) MATCH (f)-[:created]->(s) } RETURN p.name"), and one CALL may compute what several COUNT { } and COLLECT { } over the same pattern do, as in g.gql("MATCH (p:person) CALL (p) { OPTIONAL MATCH (p)-[:created]->(s) RETURN count(s) AS n, collect_list(s.name) AS names } RETURN p.name, n, names").

A quantified edge inside a subquery that reaches repeat.max_loops or traversal.max_traversers fails like one outside, and the help says where it stands and why a subquery may loop long:

g.with("repeat.max_loops", 1).gql("MATCH (p:person) WHERE EXISTS { (p)-[:knows|created]->{1,}(x) } RETURN p.name AS n")   // error: repeat() exceeded the loop limit of 1 iterations
Help: The loop of the quantified edge -[:knows|created]->{1,} inside an EXISTS subquery (or pattern predicate) of the gql() query ran 1 iterations, the limit of repeat.max_loops. ... A subquery stops at its first match, so its loop runs this long on a row that has no match, or only a late one. Give the quantifier an upper bound, as in -[:knows|created]->{1,5}, ...

COUNT { } and COLLECT { } follow the same rules (a variable bound inside one is named as bound inside that COUNT { } or COLLECT { }, and the help explains the two forms); a COLLECT { } body must end in a RETURN of exactly one column. Cypher 4's exists(n.p) is refused:

g.gql("MATCH (p:person) RETURN COLLECT { MATCH (p)-[:knows]->(f) RETURN f.name, f.age } AS l")   // error: COLLECT { } needs a body that ends in a RETURN of exactly one column
g.gql("MATCH (p:person) RETURN COUNT { MATCH (p)-[:knows]->(f) } AS n, f.name AS x")   // error: the variable `f` is not in scope: it is bound inside a COUNT { } subquery
g.gql("MATCH (p:person) RETURN exists(p.age) AS a")   // refused: exists(value), the Cypher 4 property test, is not supported
Help: return the one value to collect, as in MATCH (p:person) RETURN COLLECT { MATCH (p)-[:created]->(s) RETURN s.name } AS names. A subquery, ...
Help: bind `f` in the MATCH clause of the query to use it here, or test it inside the COUNT { } body. COUNT { <body> } is the number of matches of its body (or of the records its RETURN gives), and COLLECT { <body> RETURN <expression> } the list of the values it returns; the body reads the variables bound before it, and the variables it binds itself stay inside it, ...
Help: test a property with n.p IS NOT NULL, here p.age IS NOT NULL; EXISTS tests a graph pattern, as in MATCH (p:person) WHERE EXISTS { (p)-[:created]->() } RETURN p.name. ...

Map projections and comprehensions

A pattern comprehension is a subquery, so its errors follow the rules above with their own help text: the variables it binds stay inside it (read them in its | part), and its | part holds no aggregate (aggregate the list, size([..]), or use OPTIONAL MATCH and an aggregate). A list-comprehension variable must be a new name, and its WHERE and | parts hold no aggregate either. Each help names the form that works:

g.gql("MATCH (p:person) RETURN p.name AS n, [(p)-[:knows]->(f) | f.name] AS l ORDER BY f.name")   // error: `f` is bound inside a pattern comprehension
g.gql("MATCH (p:person) RETURN [(p)-->(f) | count(f)] AS l")   // error: count() cannot be used inside the | part of a pattern comprehension
g.gql("MATCH (p:person) RETURN [p IN [1, 2] | p * 2] AS l")   // error: the comprehension variable `p` shadows the variable `p` in scope
g.gql("MATCH (p:person) RETURN [x IN [1, 2] | count(x)] AS l")   // error: count() cannot be used inside the WHERE or | part of a list comprehension
g.gql("MATCH (p:person) RETURN [x IN [1, 2] WHERE x:A|B | x] AS a")   // error: unexpected `|`
Help: bind `f` in the MATCH clause of the query to use it here, or read it in the | part of the comprehension, as in [(a)-->(f) | f.name]. A pattern comprehension, [(a)-[:knows]->(f) WHERE <condition> | <expression>], is the list of its | part evaluated for every match of its pattern (the empty list when nothing matches); its pattern reads the variables bound before it, and the variables it binds itself stay inside it. ...
Help: aggregate the list the comprehension builds, as in MATCH (p) RETURN size([(p)-->(f) | f.age]) AS n, or aggregate in a WITH after an OPTIONAL MATCH, as in MATCH (p) OPTIONAL MATCH (p)-->(f) RETURN p, count(f.age) AS n. ...
Help: give the comprehension its own variable, as in [p2 IN list WHERE p2 > 0 | p2]. ...
Help: aggregate in a WITH first and use its column in the comprehension, as in MATCH (p)-->(f) WITH p, count(f.age) AS n RETURN [x IN [1, 2, 3] WHERE x < n]. ...
Help: a `|` in a comprehension ends its list or its WHERE condition; write a label alternative there in parentheses, as in [x IN l WHERE x:(A|B) | x.name]. ...

A map projection of a value that is not an element or a map, and a list comprehension over a value that is not a list, are data errors (22G03) of the row; so is all(), any(), none(), single() or reduce() over a value that is not a list, and the message names the function. Their variables are new names like a comprehension's (42002), and an aggregate inside their condition or | part is 42002 with a WITH example of the same form. A list-comprehension variable read inside an EXISTS or a pattern comprehension of its own WHERE or | part is not supported yet (0A000), the variables of the list predicates and reduce() neither:

g.gql("WITH 1 AS m RETURN m {.a} AS x")   // error: a map projection reads a node, an edge or a map, not a number
g.gql("MATCH (p:person) RETURN [x IN [p] WHERE (x)-->() | x.name] AS l")   // error: reading the comprehension variable `x` inside a subquery is not yet supported
g.gql("RETURN any(x IN 5 WHERE x > 1) AS a")   // error: any() iterates over a list, not a number (22G03)
g.gql("MATCH (p:person) RETURN reduce(p = 0, x IN [1] | p + x) AS a")   // error: the accumulator `p` of reduce() shadows the variable `p` in scope
Help: test `x` outside the subquery, as in [x IN list WHERE x > 0 AND EXISTS { MATCH (n)-->() }]. ...
Help: give reduce() an accumulator of its own, as in reduce(p2 = 0, item IN list | p2 + item). ... The same holds for the variable of all(), any(), none() and single() and for both variables of reduce(), as in g.gql("MATCH (p:person) RETURN p.name, all(a IN [p.age] WHERE a > 30) AS old, reduce(s = 0, a IN [p.age, 1] | s + a) AS total").

A resource limit reached inside a pattern comprehension names it. A quantified edge in its pattern loops until the row's last match is found (unlike EXISTS, which stops at its first), and its list is checked against traversal.max_materialized_bytes and the memory budget before it is built, like collect_list():

g.with("repeat.max_loops", 1).gql("MATCH (p:person) RETURN p.name AS n, [(p)-[:knows|created]->{1,}(x) | x.name] AS r")   // error: repeat() exceeded the loop limit of 1 iterations
g.with("traversal.max_materialized_bytes", 100).gql("MATCH (p:person) RETURN [(p)-[:created]->(s) | s.name] AS r")   // error: Resource limit 'traversal.max_materialized_bytes' exceeded
Help: The loop of the quantified edge -[:knows|created]->{1,} inside a pattern comprehension [(a)-->(b) | ..] of the gql() query ran 1 iterations, the limit of repeat.max_loops. ... A pattern comprehension collects every match of its pattern for each row, so its loop runs until the row's last match is found. Give the quantifier an upper bound, as in -[:knows|created]->{1,5}, ...
Help: ... A function whose result can be larger than its arguments (range(), split(), replace(), || and CAST(x AS STRING) of a list or map) and the list of collect_list() are checked before they are built, as is the list of a pattern comprehension [(a)-->(b) | b.name], so the query stops instead of running out of memory; the result is never cut short. ... count the values instead of collecting them, ... or, for the matches of a pattern, g.gql("MATCH (p:person) OPTIONAL MATCH (p)-->(f) RETURN p.name, count(f) AS n"), ...

UNION, NEXT and CALL

The errors of a composite query share one help text that explains UNION and NEXT: the operands return the same column names in any order (the result keeps the first operand's order), UNION removes duplicates and UNION ALL keeps them, one chain uses one kind, each operand has its own variables, ORDER BY and LIMIT, and NEXT passes on only the RETURN columns. The column mismatch names both column sets:

g.gql("RETURN 1 AS x UNION RETURN 2 AS y")   // error: the operands of UNION must return the same column names
g.gql("RETURN 1 AS x UNION RETURN 2 AS x UNION ALL RETURN 3 AS x")   // error: UNION ALL is mixed with UNION in one query
g.gql("MATCH (p:person) RETURN p.name AS name NEXT RETURN p.age")   // error: the variable `p` is not in scope: the RETURN before NEXT does not return it
g.gql("MATCH (p:person) RETURN p MATCH (p)-[:created]->(s) RETURN s")   // error: MATCH after RETURN: RETURN ends the query
Error: GQL semantic error at line 1, column 21: the operands of UNION must return the same column names: the first returns `x`, this one returns `y` (`x` is missing) ...
Help: name the columns alike with AS in every operand (their order may differ), as in MATCH (p:person) RETURN p.name AS name UNION MATCH (s:software) RETURN s.name AS name. UNION combines the records of queries that return the same column names, in any order (the result keeps the order of the first query): UNION (or UNION DISTINCT) removes duplicate records, UNION ALL keeps them, and one chain of UNIONs uses one kind. Each query of a UNION has its own variables, ORDER BY, OFFSET and LIMIT. NEXT passes the records of the statement before it on by their column names (only those), so it sorts, filters or aggregates a UNION as a whole, as in g.gql("MATCH (p:person) RETURN p.name AS name UNION MATCH (s:software) RETURN s.name AS name NEXT RETURN name ORDER BY name LIMIT 3").
Help: write the same kind between every operand, or combine the parts with NEXT, as in RETURN 1 AS x UNION ALL RETURN 1 AS x NEXT RETURN x UNION RETURN 2 AS x. UNION combines ...
Help: add `p` to the RETURN items before NEXT, as in RETURN ..., p NEXT ... UNION combines ...
Help: put every MATCH before the RETURN, or continue with NEXT, which passes the columns of the RETURN on to the next statement, as in MATCH (p:person) RETURN p NEXT MATCH (p)-[:created]->(s) RETURN p.name, s.name, or chain Gremlin steps after gql(). ...

The errors of a CALL share a help text on its scope: the body reads only the variables its scope clause names (CALL (*) all, CALL { } none, Cypher's CALL { WITH a .. } those of its first WITH), returns new names, aggregates per row, and drops a row without records unless the CALL is OPTIONAL. Cypher's importing WITH lists plain variables only, as in Neo4j: a first WITH with a WHERE, an alias, an expression, DISTINCT, ORDER BY, OFFSET or LIMIT is no importing WITH, so the body imports nothing and the error says so. A body without RETURN (a unit subquery, which only a write could use) is not supported, and IN TRANSACTIONS is refused:

g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[:knows]->(f) RETURN f AS p } RETURN p")   // error: the CALL body returns `p`, which is already defined outside it
g.gql("MATCH (p:person) CALL { WITH p AS q MATCH (q)-->(s) RETURN s.name AS sw } RETURN sw")   // error: the variable `p` is not imported into the CALL body: its first WITH is not an importing WITH
g.gql("MATCH (p:person) CALL { WITH p WHERE p.age > 30 MATCH (p)-->(s) RETURN s.name AS sw } RETURN sw")   // error: the variable `p` is not imported into the CALL body: its first WITH is not an importing WITH
g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[:created]->(s) } RETURN p")   // error: a CALL { } body without RETURN (a unit subquery) only makes sense for writes, and this body writes nothing
g.gql("MATCH (p:person) CALL (p) { MATCH (p)-->(s) RETURN s.name AS sw } IN TRANSACTIONS RETURN sw")   // refused: CALL { } IN TRANSACTIONS commits writes in batches
Help: rename the column inside the body, as in RETURN ... AS p2. A CALL subquery, CALL (a, b) { <query ending in RETURN, or in a write (INSERT, SET, REMOVE, DELETE, MERGE / FINISH)> }, runs its query once for each incoming row: the body reads only the variables its scope clause names (CALL (*) imports all of them, CALL { } none, and Cypher's CALL { WITH a .. } those of its first WITH), and passes on only the columns of its RETURN, which must be new names; its aggregates, ORDER BY and LIMIT apply to each row's records, as in g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[:created]->(s) RETURN count(s) AS made } RETURN p.name, made"). A row whose body returns no record is dropped; OPTIONAL CALL keeps it with NULL columns.
Help: import `p` with a variable scope clause, as in CALL (p) { MATCH ... WHERE ... }, or in Cypher with a WITH of plain variables first and the rest of the body after it, as in CALL { WITH p MATCH ... WHERE ... }. A CALL subquery, ...
Help: end the body with RETURN and the columns the query reads after it, for example MATCH (p:person) CALL (p) { MATCH (p)-[:created]->(s) RETURN count(s) AS made } RETURN p.name, made. A CALL subquery, ...
Help: remove IN TRANSACTIONS: the whole query commits at once, and a query that fails changes nothing. A CALL subquery, ...

CALL bodies and whole-query subquery bodies (EXISTS, COUNT or COLLECT with WITH, RETURN, ...) nest at most 16 levels (54001); the help shows how to un-nest them. A resource limit reached inside a CALL body names it: the body runs for each incoming row and keeps every record, so a quantified edge in it loops until the row's last match:

g.with("repeat.max_loops", 1).gql("MATCH (p:person) CALL (p) { MATCH (p)-[:knows|created]->{1,}(x) RETURN count(x) AS n } RETURN p.name AS who, n")   // error: repeat() exceeded the loop limit of 1 iterations
Error: GQL limit exceeded at line 1, column 113: the query nests CALL { } and subquery bodies deeper than 16 levels ...
Help: un-nest the bodies: a CALL body may follow another in the same query, as in CALL { .. RETURN a } CALL (a) { .. RETURN b }, and NEXT passes the result of one query to the next. The query is larger than gql() accepts.

Help: The loop of the quantified edge -[:knows|created]->{1,} inside a CALL { } subquery of the gql() query ran 1 iterations, the limit of repeat.max_loops. ... A CALL { } subquery runs its body for each incoming row and keeps every record it returns, so its loop runs until the row's last match is found. Give the quantifier an upper bound, as in -[:knows|created]->{1,5}, ...

A limit inside an operand of a UNION or a block after NEXT at the top level keeps the plain text of a top-level clause; inside a subquery the place named is the innermost subquery (CALL, COUNT, COLLECT, EXISTS or a pattern comprehension).

Calls of saved queries

The errors of a CALL folder.name(..) of a saved query are found before the run and point at the call; they share one help text that explains the call (folder and name, positional arguments, YIELD, the standalone form, g.queries()), after a fix of their own:

GQLSTATUSWhen
42002no saved query of that name in that folder (with "did you mean" when it is in another folder); too many arguments, or too few for parameters without a default; a standalone call without parentheses whose parameter has no value; an in-query call without parentheses of a query with parameters; an in-query call of a query with columns without YIELD; YIELD of a column the query does not return, of a name already in scope or twice, YIELD on a query without RETURN; an aggregate in an argument; a saved query that calls itself, directly or through others
42001YIELD * inside a query (only a standalone call takes it)
22G03an argument that does not fit its parameter's schema (CALL people.older('x') for an integer)
0A000a saved query written in Rhai (the help names g.query(..)); an argument that reads the row; a call inside EXISTS { }, COUNT { } or COLLECT { }; the vendor namespaces db, dbms, apoc, gds (refused); a read-only saved query that would write through a call
54001saved queries that call each other more than 16 levels deep, or more than 1024 calls in one query and the queries it calls
g.gql("CALL people.older(26) YIELD name RETURN name")   // error: there is no saved query `older` in the folder `people`
g.gql("CALL db.labels()")   // refused: procedure calls of the vendor namespaces are vendor extensions

With the saved query people.older($min) of Saved Queries, returning name and age:

Error: GQL semantic error at line 1, column 6: there is no saved query `older` in the folder `people` ...
Help: save it first with g.define_query(#{name: "older", folder: "people", language: "gql", body: ".."}); g.queries() lists the saved queries. CALL folder.name(args) runs the saved query `name` of the catalog folder `folder` (the segments before the name, joined by /; CALL name() calls one of the root folder), written in GQL. Its arguments are constants or $parameters, in the order its query first reads its parameters (a trailing one left out takes the parameter's default). YIELD names the columns of its RETURN the query reads after the call (YIELD a AS x renames one; each must be a new name), and a call alone is a whole query returning every column, as in g.define_query(#{name: "adults", folder: "people", language: "gql", body: "MATCH (p:person) WHERE p.age >= $min RETURN p.name AS name", params: #{min: "integer"}}); g.gql("CALL people.adults(30) YIELD name RETURN name ORDER BY name"). g.queries() lists the saved queries with their folders and parameters; a saved query written in Rhai runs with g.query(name, #{..}).

Error: GQL semantic error at line 1, column 6: there is no saved query `older` in the root folder: the saved query `older` is in the folder `people` ...
  did you mean: CALL people.older
Help: Did you mean CALL people.older? CALL folder.name(args) runs the saved query ...

Error: GQL semantic error at line 1, column 22: too many arguments: people.older(min :: integer) takes 1 argument, 2 given ...
Error: GQL data exception at line 1, column 19: the argument for `min` of CALL people.older must be integer: Type mismatch on query 'older.min': expected int64, got string ...
  GQLSTATUS: 22G03

Error: GQL semantic error at line 1, column 25: CALL people.older inside a query names the columns it reads with YIELD: the saved query returns `name`, `age` ...
Help: add YIELD, as in CALL people.older(..) YIELD name, age. CALL folder.name(args) runs ...

Error: GQL semantic error at line 1, column 27: `nope` is not a column of the saved query called by CALL people.older; it returns `name`, `age` ...
Error: GQL syntax error at line 1, column 46: YIELD * is allowed only in a standalone CALL (the whole query) ...

Error: GQL construct not supported yet at line 1, column 38: an argument of CALL people.older that reads the row is not yet supported (the variable s is not defined) ...
Help: pass a constant or a $parameter, or write the saved query's pattern in the query itself. CALL folder.name(args) runs ...

Error: GQL construct not supported yet at line 1, column 6: the saved query `rh` is written in Rhai; CALL runs saved queries written in GQL in this version ...
Help: run it from the DSL with g.query("rh", #{..}), or save it again in GQL (language: "gql"). CALL folder.name(args) runs ...

Error: GQL semantic error at line 1, column 6: recursive call of the saved query `a`: a calls b calls a (the arguments of a CALL are constants, so the recursion would never end) ...

Error: GQL limit exceeded at line 1, column 6: saved queries call each other more than 16 levels deep (CALL q0 at the end of q16 -> q15 -> ... -> q1) ...
  GQLSTATUS: 54001
Help: Saved queries called with CALL nest at most 16 levels deep, and one query and the saved queries it calls hold at most 1024 calls in all. Call an inner saved query directly, as in g.gql("CALL people.adults(30) YIELD name RETURN name"), or write a part of the chain in the query itself; g.get_query(name) shows a saved query's body.

Error: GQL unsupported construct at line 1, column 1: CALL: procedure calls are vendor extensions, not part of GQL ...
Help: write what the procedure does as Gremlin steps, for example g.v().label().dedup() instead of CALL db.labels(), or save it as a query in GQL and call that one, CALL folder.name(args), which runs a saved query of the graph's catalog. ...

An error inside the called query keeps its own text and caret (under the saved query's text) and gains the line in saved query: "name".

Quantified path patterns

The forms a quantified path pattern does not take yet are refused before the run with 0A000; each help names the rewrite. A body variable is a new name (42002), and outside a quantified body it is a list, so a property of it is an error whose help offers the body's WHERE or a list comprehension:

g.gql("MATCH (a) ((x)-[:knows]->{1,2}(y)){1,3} (b) RETURN b")   // error: a quantified edge inside a parenthesized path pattern is not yet supported
g.gql("MATCH (a) ((x)-->(y) WHERE y.age > a.age){1,3} (b) RETURN b")   // error: a condition inside a parenthesized path pattern that reads a variable declared outside it is not yet supported
g.gql("MATCH (a) ((a)-->(y)){1,2} (b) RETURN b")   // error: `a` is already bound; a variable of a quantified path pattern must be a new name
g.gql("MATCH (a) ((x)-->(y)){1,3} (b) RETURN x.name")   // error: `x` is a group variable of the quantified path pattern
Help: write the edge out as often as needed inside the parentheses, as in ((x)-->()-->(y)){1,3}, or quantify the edge outside them, as in MATCH (a)-[:knows]->{1,3}(b) RETURN b. ...
Help: compare the body's variables with each other, with values or with parameters inside it, as in ((x)-[e]->(y) WHERE e.weight > $w){1,3}, and test the outer variable in the WHERE of the MATCH clause. ...
Help: give the element inside its own variable: the node before a parenthesized path pattern is the first node of its first iteration and the node after it the last node of its last iteration, as in (a) ((x)-->(y)){1,3} (b). ...
Help: test each element inside the parenthesized path pattern, with WHERE x.name ... before its closing parenthesis, or read the list, as in [v IN x | v.name]. ...

An unbounded quantified path pattern that reaches repeat.max_loops or traversal.max_traversers fails like a quantified edge (RepeatLimitExceeded, ResourceLimitExceeded, no GQLSTATUS), never with fewer rows, and its help names the pattern as the plan walks it: read back from the lowered repeat() body, so it shows each node's labels but not its variable (a node without a label is ()), each edge with its labels in the direction of the walk (the plan may walk the pattern from its far end), and a body of one edge with nothing on its nodes as the quantified edge it equals (-[:knows]->{1,}):

g.with("repeat.max_loops", 1).gql("MATCH (a {name: 'marko'}) ((x:person)-[:knows]->(m)-[:created]->(y))+ (b) RETURN b.name AS b")   // error: repeat() exceeded the loop limit of 1 iterations
Help: The loop of the quantified path pattern ((:person)-[:knows]->()-[:created]->()){1,} of the gql() query ran 1 iterations, the limit of repeat.max_loops. A quantifier without an upper bound ({m,}, *, + or Cypher [*]) repeats the pattern until every path has used all the edges it can reach (trail), ... Give the quantifier an upper bound, as in ((:person)-[:knows]->()-[:created]->()){1,5}, ... Or raise the limit for the query, g.with("repeat.max_loops", 2).gql(..), ...

A MATCH clause holds at most 64 edge patterns; an edge in a quantified body counts once, however often the body repeats, so the help of that limit names a quantified path pattern as one of the fixes:

Help: split the pattern into several MATCH clauses that share a variable, for example MATCH (a)-->(b)-->(c) MATCH (c)-->(d)-->(e) RETURN e (edge uniqueness then holds within each clause only), repeat a chain as a quantified path pattern, whose body edges count once however often it repeats, for example MATCH (a) (()-->()){65} (z) RETURN z, or walk a long path with Gremlin repeat(), for example g.v().repeat(__.out()).times(100). The query is larger than gql() accepts.

INSERT

An INSERT pattern that cannot create what it says fails before the run; its help shows the accepted form and ends with one shared paragraph on INSERT:

g.gql("INSERT (a:x)-[:r]-(b:y)")   // error: INSERT needs a direction; write -[e:T]-> or <-[e:T]-
g.gql("INSERT (:a)-[:r|s]->(:b)")   // error: an edge in INSERT has exactly one label
g.gql("MATCH (p:person) INSERT (p:admin)")   // error: the variable `p` is already bound
g.gql("INSERT (:x {a: 1, a: 2})")   // error: the key `a` appears twice in this map
g.gql("MATCH (p:person) INSERT (:x {n: count(p)})")   // error: the aggregate function count() cannot be used in INSERT
g.gql("MATCH (p:person) WHERE EXISTS { INSERT (:a) } RETURN p")   // error: INSERT inside EXISTS { }: a subquery expression or a comprehension cannot write
Error: GQL syntax error at line 1, column 13: INSERT needs a direction; write -[e:T]-> or <-[e:T]- (step #1 'gql:error("42001")' refused the query before the traversal ran)
  at #1: v().gql:error("42001")
             ^^^^^^^^^^^^^^^^^^
  query:     INSERT (a:x)-[:r]-(b:y)
                         ^^^^^^
  GQLSTATUS: 42001
Help: give the new edge its direction, from the node before it (-[:r]->) or to it (<-[:r]-); for example g.gql("INSERT (a:person {name: 'ann'})-[:knows]->(b:person:admin)"). INSERT (Cypher CREATE) creates its pattern once for each row: a new node with the labels written, joined by & or :, and a property map; a new edge with a direction and exactly one label; and a variable bound before, written alone as (p), connects the existing node, as in g.gql("MATCH (p:person {name: 'marko'}) INSERT (p)-[:likes]->(f:fruit&food {name: 'apple'}) RETURN f.name"). A query may end with the INSERT (it then returns no rows), and FOR gives it one row per item, as in g.gql("FOR n IN ['ann', 'bob'] INSERT (:person {name: n})"). To create a pattern only where it is missing, MERGE finds it or creates it, as in g.gql("FOR n IN ['ann', 'marko'] MERGE (:person {name: n})").

While the query runs, a row whose endpoint is NULL (22004) or no node (22G03), or whose property value is a node, an edge or a path (22G03), fails the query, and it changes nothing:

g.gql("OPTIONAL MATCH (p:person {name: 'nobody'}) INSERT (p)-[:knows]->(:person)")   // error: the source node `p` of the inserted `:knows` edge is NULL
g.gql("MATCH (p:person) INSERT (:x {v: p})")   // error: the value of property `v` is a node
Caused by: GQL data exception at line 1, column 51: the source node `p` of the inserted `:knows` edge is NULL
  query:     …person {name: 'nobody'}) INSERT (p)-[:knows]->(:person)
                                              ^^^
  GQLSTATUS: 22004
Help: keep only the rows where it is bound before the INSERT: FILTER p IS NOT NULL. A row of the data gave the marked endpoint of the new edge no node: an edge connects two nodes, so a variable that OPTIONAL MATCH may leave NULL is filtered first, as in g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s) FILTER s IS NOT NULL INSERT (p)-[:made]->(s)"), and a value that is no node is turned into one by a MATCH, as in g.gql("FOR n IN ['lop'] MATCH (s:software {name: n}) INSERT (:review {stars: 5})-[:about]->(s)").

A schema violation of an INSERT is the schema's error, with a help line written for GQL: a missing required property names the INSERT map and coalesce(), a type mismatch the conversion function (toInteger(), ...) with a $parameter example (Writing with GQL). A bound node written with labels or properties (MATCH (p:person) INSERT (p:admin)) gets the SET that changes it, built from the query, as in g.gql("MATCH (p:person) SET p:admin"), beside the Gremlin steps. The write clause that is not supported yet (FOREACH) is 0A000 with a help line naming the GQL form:

g.gql("MATCH (p:person) FOREACH (x IN [1] | SET p.k = x)")   // error: FOREACH is not yet supported in this version
Help: write FOR x IN <list> followed by the write clause, for example FOR name IN ['ann', 'bob'] INSERT (:person {name: name}). DELETE takes a list itself, as in MATCH p = (:person)-[:knows]->() DETACH DELETE nodes(p). This construct comes in a later version of gql(); until then, write the query without it or as Gremlin steps.

SET and REMOVE

A SET / REMOVE item of the wrong form fails before the run: a label item joined by |, ! or % (42001), a label item on a variable known to be an edge, an aggregate in a value, or a target that is undefined, a LET / WITH value, a path, a group variable or a FOR position (42002); a deeper target such as p.a.b or head(l).k is not supported yet (0A000). Each help names the accepted form and ends with one shared paragraph on SET / REMOVE:

g.gql("MATCH (p:person) SET p:A|B")   // error: `|` (a label alternative) cannot stand in SET
g.gql("MATCH (a)-[e:knows]->(b) SET e:met")   // error: `e` is an edge: an edge has exactly one label
g.gql("MATCH (p) SET p.k = count(*)")   // error: the aggregate function count() cannot be used in SET
g.gql("MATCH (p) SET p.a.b = 1")   // error: `p.a.b` as a SET target is not yet supported in this version
Error: GQL syntax error at line 1, column 24: `|` (a label alternative) cannot stand in SET: a label item names the labels, joined by `:` or `&` (step #1 'gql:error("42001")' refused the query before the traversal ran)
  at #1: v().gql:error("42001")
             ^^^^^^^^^^^^^^^^^^
  query:     MATCH (p:person) SET p:A|B
                                    ^^^
  GQLSTATUS: 42001
Help: write the labels, as in SET p:A:B. SET changes the nodes and edges of each row, item by item from left to right: n.k = <value> sets a property (a NULL value removes it), n = {map} replaces every property, n += {map} merges the map into them, and n:A:B adds labels to a node (an edge has exactly one label); REMOVE n.k removes a property and REMOVE n:A a label, as in g.gql("MATCH (p:person {name: 'marko'}) SET p.age = p.age + 1, p:employee REMOVE p.nick RETURN p.age"). A variable that OPTIONAL MATCH leaves NULL is skipped, and a query may end with the SET or REMOVE (it then returns no rows), as in g.gql("MATCH (s:software) SET s += {open: true}").
Help: change the type of the edge with the Gremlin step set_label(), as in g.gql("MATCH (a)-[e:knows]->(b) RETURN e").select("e").set_label("met"). In a MATCH clause a node variable names one node ...

While the query runs, a NULL right side of n = .. or n += .. (22004), a right side that is no map, node or edge, a node, edge or path as a property value, a target that holds no element, and a label item on a value that turns out to be an edge (22G03) fail the query, and it changes nothing. The help rewrites the failing query where it can:

g.gql("MATCH (p:person) SET p = NULL")   // error: the right side of SET p = .. is NULL, not a map
g.gql("MATCH (p:person) SET p.best = p")   // error: the value of property `best` is a node
g.gql("MATCH (p:person) SET p = 1")   // error: the right side of SET p = .. is a single value
g.gql("FOR x IN [1] SET x.k = 1")   // error: SET changes a node or an edge, but `x` holds a value of type 'int64'
Caused by: GQL data exception at line 1, column 26: the right side of SET p = .. is NULL, not a map
  query:     MATCH (p:person) SET p = NULL
                                      ^^^^
  GQLSTATUS: 22004
Help: SET p = {} removes every property; to keep them when the map is NULL, give it the element's own properties as a default with coalesce($p, properties(p)), as in g.gql("MATCH (p:person) SET p = coalesce(NULL, properties(p))"). A row of the data gave the marked SET or REMOVE item a value it cannot write; keep such rows away from it with FILTER or WHERE, as in g.gql("MATCH (p:person) FILTER p.age IS NOT NULL SET p.next = p.age + 1"). SET changes the nodes and edges of each row, ...
Help: store a value of it instead, such as its id, as in g.gql("MATCH (p:person) SET p.best = element_id(p)"), or its properties with properties(..). A row of the data gave the marked SET or REMOVE item a value it cannot write; ...

A schema violation of a SET / REMOVE gets a help line written for GQL too: a type mismatch names the conversion function in a SET of the label and key, a removed required property (REMOVE, a NULL value, SET n = {map} without the key) the map that keeps it and +=, and a label whose required property the node lacks the SET that writes the key before the label.

DELETE

A DELETE target that cannot hold an element fails before the run: a label test such as n:person or n IS person (42001: it is a boolean, and DELETE removes whole elements), a literal, a computed value, a map or a FOR position (42002). DROP n, the Gremlin step written as a clause, is a syntax error naming DETACH DELETE, and REMOVE n without an item names it too. Each help rewrites the failing query and ends with one shared paragraph on DELETE:

g.gql("MATCH (n:person {name: 'vadas'}) DELETE n:person")   // error: `n:person` is a label test (a boolean), not an element
g.gql("MATCH (n:person) DELETE 1 + 1")   // error: `1 + 1` is a computed value, not a node, an edge, a path or a list of them
g.gql("MATCH (p:person) DROP p")   // error: GQL has no DROP clause: DELETE removes nodes and edges
Error: GQL syntax error at line 1, column 41: `n:person` is a label test (a boolean), not an element; DELETE removes whole nodes and edges (step #1 'gql:error("42001")' refused the query before the traversal ran)
  at #1: v().gql:error("42001")
             ^^^^^^^^^^^^^^^^^^
  query:     MATCH (n:person {name: 'vadas'}) DELETE n:person
                                                     ^^^^^^^^
  GQLSTATUS: 42001
Help: delete the element itself with DELETE n, as in g.gql("MATCH (n:person {name: 'vadas'}) DELETE n"), or remove the label and keep the element with REMOVE n:person, as in g.gql("MATCH (n:person {name: 'vadas'}) REMOVE n:person"). DELETE removes, for each row, the nodes and edges its targets give: a node or edge variable, a path (all its nodes and edges) or a list of them; a NULL target is skipped, and an element given twice is removed once. A node that still has edges is removed only together with them: DETACH DELETE removes its edges too, as in g.gql("MATCH (s:software {name: 'lop'}) DETACH DELETE s"). The rest of the query can no longer read what it deleted, so read what it needs first, as in g.gql("MATCH (p:person {name: 'vadas'}) WITH p, p.name AS name DETACH DELETE p RETURN name"); a query may end with the DELETE (it then returns no rows).
Help: name the element to remove by its variable, as in g.gql("MATCH (n:person) DETACH DELETE n"). DELETE removes, for each row, ...
Help: write DETACH DELETE (the GQL form of the Gremlin step drop()), as in g.gql("MATCH (p:person) DETACH DELETE p"). DELETE removes, for each row, ...

While the query runs, a plain (or NODETACH) DELETE of a node that still has an edge the same clause does not delete fails with G1001; the help names DETACH DELETE in the failing query and the form that deletes the edges in the same clause. A target that turns out to hold no element (a WITH value, a property) is 22G03. Either failure changes nothing:

g.gql("MATCH (n:person {name: 'marko'}) DELETE n")   // error: `n` is a node that still has edges
g.gql("MATCH (n:person) WITH 1 AS x DELETE x")   // error: DELETE removes nodes, edges and paths, but `1` gives a number on this row
Caused by: GQL data exception at line 1, column 41: `n` is a node that still has edges, and DELETE removes only nodes without edges (besides the edges deleted in the same clause)
  query:     MATCH (n:person {name: 'marko'}) DELETE n
                                                     ^
  GQLSTATUS: G1001
Help: remove the node together with its edges with DETACH DELETE, as in g.gql("MATCH (n:person {name: 'marko'}) DETACH DELETE n"), or delete its edges in the same clause, as in g.gql("MATCH (s:software {name: 'ripple'})<-[r]-() DELETE r, s").
Help: give DELETE a node, an edge, a path or a list of them, and keep the rows where the target holds something else away from it with FILTER or WHERE, as in g.gql("MATCH (n:person {name: 'marko'}) DETACH DELETE n"). DELETE removes, for each row, ...

After a DELETE, a later part of the query that reads a deleted element (a property, labels(), element_id(), a SET, REMOVE or INSERT on it) or returns it fails, and the query changes nothing. The error is the storage's (ElementRemoved), with a help line written for GQL: read what the query needs before the DELETE, for example with properties(n). count(n), n IS NULL and type(r) of a deleted edge still work, and a pattern from a deleted node matches nothing:

g.gql("MATCH (n:software) DETACH DELETE n RETURN n.name")   // error: the node was deleted earlier in this query
g.gql("MATCH ()-[r:created]->() DELETE r RETURN r.weight")   // error: the edge was deleted earlier in this query
Caused by: The vertex was removed earlier in this query; its id, label and value are no longer available
Help: The node was deleted earlier in this query (by DELETE or DETACH DELETE, or together with a node a DETACH DELETE removed), but a later part of the query still reads it: a deleted node has no properties, labels or id any more and cannot be returned or changed, and a pattern from it matches nothing; only count(n) and n IS NULL still work. Read what you need before the DELETE and keep that instead, for example g.gql("MATCH (n:person {name: 'marko'}) WITH n, properties(n) AS p DETACH DELETE n RETURN p"), or run the DELETE as a separate query after reading.
Help: The edge was deleted earlier in this query (...); only count(r), r IS NULL and type(r) still work. Read what you need before the DELETE and keep that instead, for example g.gql("MATCH (:person)-[r:knows]->() WITH r, properties(r) AS p DELETE r RETURN p"), or for a node g.gql("MATCH (n:person {name: 'marko'}) WITH n, properties(n) AS p DETACH DELETE n RETURN p"), or run the DELETE as a separate query after reading.

MERGE

A MERGE pattern that cannot be matched or created as written fails before the run: a second pattern after ,, an edge without its one label or with a label expression, a quantifier (42001); a node bound before written with labels or properties, a bound edge variable, and a pattern that is only a node bound before (MATCH (a) MERGE (a): nothing to find or create) (42002). Each help rewrites the failing query where it can and ends with one shared paragraph on MERGE:

g.gql("MERGE (a:x), (b:y)")   // error: MERGE takes exactly one pattern
g.gql("MATCH (a) MERGE (a)")   // error: MERGE (a) with `a` bound earlier has nothing to find or create
g.gql("MATCH (a:person) MERGE (a:admin)-[:r]->(:b)")   // error: the variable `a` is already bound
g.gql("MERGE (a:x)-[:r|s]->(b)")   // error: an edge in MERGE has exactly one label
Error: GQL syntax error at line 1, column 12: MERGE takes exactly one pattern: a second pattern after `,` cannot stand here (step #1 'gql:error("42001")' refused the query before the traversal ran)
  at #1: v().gql:error("42001")
             ^^^^^^^^^^^^^^^^^^
  query:     MERGE (a:x), (b:y)
                        ^
  GQLSTATUS: 42001
Help: write one MERGE for each pattern, as in g.gql("MERGE (a:x) MERGE (b:y)"), or connect the patterns with an edge into one. MERGE looks for its whole pattern for each row: every match is a row, and when nothing matches the whole pattern is created, reusing the nodes bound before. Its one pattern has nodes with the labels written, joined by & or :, and a property map, edges with exactly one label (an edge without a direction matches either direction and is created from left to right), and a node bound before written alone, as (p); ON CREATE SET and ON MATCH SET items change what was created or matched, as in g.gql("MERGE (p:person {name: 'ann'}) ON CREATE SET p.new = true ON MATCH SET p.new = false RETURN p.new"). Each row sees what the rows before it created, so FOR creates a repeated item once, as in g.gql("FOR n IN ['ann', 'ann'] MERGE (:person {name: n})").
Help: to find or create a connection, give the pattern an edge, as in g.gql("MATCH (a) MERGE (a)-[:T]->(:Label)"); to find or create another node, give it its own name, as in g.gql("MATCH (a) MERGE (a2:Label)"). MERGE looks for its whole pattern for each row: ...
Help: write (a) to connect the node, or give a new node its own name, as in MERGE (a)-[:T]->(a2:Label {k: 1}); to change the bound node itself use SET on it, as in g.gql("MATCH (a:person) SET a:admin"), or the Gremlin steps add_label() and property() on it, as in g.gql("MATCH (a) RETURN a").select("a").add_label("admin"). MERGE looks for its whole pattern for each row: ...
Help: give the new edge one label, as in -[:r]->; for example g.gql("MERGE (a:person {name: 'ann'})-[:knows]->(b:person:admin)"). MERGE looks for its whole pattern for each row: ...

While the query runs, a property value of the pattern that is NULL (22004: MERGE can neither match nor create {k: NULL}, checked for each row before the match), a node bound before that is NULL (22004) or no node (22G03), and a node, edge or path as a property value (22G03) fail the query, and it changes nothing, also what earlier rows created. The help names the FILTER before the MERGE or the coalesce() default in the failing query:

g.gql("FOR x IN [1, NULL] MERGE (:n {k: x})")   // error: MERGE cannot match or create `{k: NULL}`
g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s) MERGE (p)-[:made]->(s)")   // error: the destination node `s` of the merged `:made` edge is NULL
g.gql("MERGE (p:person {name: NULL})")   // error: MERGE cannot match or create `{name: NULL}`
Caused by: GQL data exception at line 1, column 34: MERGE cannot match or create `{k: NULL}`: a property value is NULL
  query:     FOR x IN [1, NULL] MERGE (:n {k: x})
                                              ^
  GQLSTATUS: 22004
Help: keep only the rows where it has a value with FILTER x IS NOT NULL before the MERGE, or give it a default with coalesce(), as in g.gql("FOR x IN [1, NULL] MERGE (:n {k: coalesce(x, 0)})"). A row of the data gave the marked part of the MERGE pattern a value it can neither match nor create: a property value that is NULL or a graph element, or a node bound before that is NULL or no node. A variable that OPTIONAL MATCH may leave NULL is filtered first, and a value that is no node is turned into one by a MATCH, as in g.gql("FOR n IN ['lop'] MATCH (s:software {name: n}) MERGE (:review {stars: 5})-[:about]->(s)"). MERGE looks for its whole pattern for each row: ...
Help: keep only the rows where it is bound before the MERGE: FILTER s IS NOT NULL, as in g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s) FILTER s IS NOT NULL MERGE (p)-[:made]->(s)"). A row of the data gave the marked part of the MERGE pattern a value it can neither match nor create: ...
Help: MERGE matches and creates only property values that are not NULL: leave `name` out of the pattern, and find the elements that lack it with a MATCH, as in g.gql("MATCH (n) FILTER n.name IS NULL RETURN n"). A row of the data gave the marked part of the MERGE pattern a value it can neither match nor create: ...

A schema violation of a MERGE gets a help line written for GQL too. One raised by the create names the MERGE pattern and keeps its node variable: a type mismatch the conversion function, as in g.gql("MERGE (p:person {w: toFloat($v)})", #{v: "1.5"}), and a missing required property the pattern's property map, because the ON CREATE SET items run after the create and cannot give it (or a "default" in the schema, to match on other keys only). One raised by an ON CREATE SET / ON MATCH SET item gets the SET fix in MERGE form, as in g.gql("MERGE (n:person) ON MATCH SET n.w = toFloat($v)", #{v: "1.5"}).

GQLSTATUS codes

CodeKindWhen
42001syntaxthe query does not parse: an unexpected token, a missing RETURN, an unclosed bracket, a quantifier with m > n, GROUP BY after WITH (grouping is implicit) or after ORDER BY; an unknown function or CAST type name (with a suggestion), a function called with the wrong number of arguments, the SQL form SUBSTRING(s FROM a FOR b); a ZONED TIME '..' / ZONED DATETIME '..' literal whose text has no offset or zone; WITH ORDINALITY / WITH OFFSET after UNWIND; an INSERT edge without a direction or with a label expression, an INSERT node label other than a conjunction, WHERE or a quantifier in an INSERT pattern, a SET / REMOVE label item joined by `
42002semantican undefined variable, a variable used as a node and an edge, an edge variable bound twice in one MATCH, a duplicate column name, a missing parameter, an ORDER BY key that RETURN DISTINCT dropped; a variable a WITH did not carry on, a LET name bound again; a variable read outside an aggregate that is not a grouping key, an aggregate in WHERE / FILTER / LET or inside another aggregate, ORDER BY after an aggregation reading something other than a column; a GROUP BY key that is not an item without an aggregate, or such an item missing from GROUP BY; a path or group variable bound twice; a variable of a quantified path pattern that is not a new name, or a property of one read outside its body; a FOR / UNWIND name already in scope, one name for the item and its position, the position used as a node or edge, an aggregate in the FOR list; a new variable in a pattern predicate, a variable bound inside a subquery (EXISTS, a pattern predicate, COUNT { }, COLLECT { }) read outside it, a condition in a subquery reading a variable of a later MATCH clause of the body, a subquery in an aggregating item reading a variable outside the aggregates that is not a grouping key; a variable bound inside a pattern comprehension read outside it, a comprehension variable named like another variable of the query, an aggregate inside a comprehension's WHERE or | part; a COLLECT { } body that does not return exactly one column; UNION operands with different column names, UNION mixed with UNION ALL in one chain, a variable read after NEXT that the RETURN before it does not return; a CALL body returning a name already in scope, reading a variable it does not import (also through a first WITH that is no importing WITH), importing one twice; a CALL folder.name(..) of a saved query that does not exist in that folder, with too many or too few arguments, a missing parameter value, an aggregate in an argument, without YIELD inside a query, or with a YIELD of a column it does not return or of a name already in scope, a recursive call (Calls of saved queries); in INSERT, a bound variable with labels or properties, a bound edge variable, a duplicate key in a property map, an aggregate in a property value; in SET / REMOVE, an undefined target, a target that is a LET / WITH value, a path, a group variable or a FOR position, a label item on an edge variable, an aggregate in a value; in DELETE, a target known to hold no element (a literal, a computed value, a map, a FOR position), an aggregate in a target; in MERGE, a bound node with labels or properties, a bound edge variable, a pattern that is only a node bound before
0A000refused / not yeta refused construct or one not supported yet (also a function: sin(), rand(), elements(), CAST to DATE; X.realtime(); EXCEPT, INTERSECT, OTHERWISE; a CALL body without RETURN that writes nothing, CALL { } IN TRANSACTIONS; Cypher 4's exists(n.p); a CALL of a saved query written in Rhai, with an argument that reads the row, or inside EXISTS / COUNT / COLLECT, a vendor procedure (db, dbms, apoc, gds); a SET / REMOVE target deeper than a variable (p.a.b, head(l).k), the write clause FOREACH, a subquery in a MERGE property value, an INSERT in a UNION operand or with a path variable; LOAD CSV, CREATE INDEX / CONSTRAINT / GRAPH; a list-comprehension or list-predicate variable read inside a subquery; inside a parenthesized path pattern: a nested group or quantified edge, a path variable, several patterns, no edge, a variable written twice or bound outside, a condition reading an outer variable, a subquery); also gql() after other steps
54001limitthe query nests too deeply (more than 128 levels of parentheses, or an expression taller than 512)
54001limitmore than 64 subqueries (EXISTS, pattern predicates, pattern comprehensions, COUNT { } and COLLECT { }, nested ones included), or more than 1024 subquery bodies to run (a LET / WITH variable holding a subquery counts once per reader); CALL bodies and whole-query subquery bodies nested more than 16 levels; saved queries calling each other more than 16 levels deep, or more than 1024 calls of saved queries in one query
54001limita MATCH clause holds more than 64 edge patterns (over all its comma-separated paths; a quantified body's edges count once); split it into several MATCH clauses that share a variable, repeat a chain as a quantified path pattern, or use Gremlin repeat()
22004dataan endpoint of an INSERT edge is NULL (from an OPTIONAL MATCH); the right side of SET n = .. / SET n += .. is NULL; a property value of a MERGE pattern or a node bound before it is NULL
22G02dataa negative OFFSET / LIMIT (literal or parameter value)
22G03dataa value of the wrong type, before the run when the kind is certain from the query text (static kind checks: false AND 123, 1 IN true, type(n) of a node variable, p.name of a path, WITH 123 AS x RETURN x.num), else when a row reaches it: OFFSET / LIMIT not an integer, 'a' + 1, type() of a vertex, a non-boolean condition, IN with a right operand that is no list, sum() / avg() of a non-number; a map projection of a value that is no element or map, a list comprehension over a value that is no list; a temporal component the type lacks (date(..).hour), temporal arithmetic without a meaning (date + date); an argument of a CALL of a saved query that does not fit its parameter's schema; a function argument of the wrong kind (toFloat(true), a float where an integer is required, toString() of a list, map, vertex, edge or path, trim(s, x) with a string s); an INSERT endpoint that is no node, a node, edge or path as an INSERT or SET property value; a SET / REMOVE target that holds no node or edge, a label item on an edge at run time, a right side of SET n = .. / += that is no map, node or edge; a DELETE target that holds no node, edge or path; a node bound before a MERGE that is no node, a node, edge or path as a MERGE property value
G1001dataa DELETE / NODETACH DELETE of a node that still has an edge the same clause does not delete (use DETACH DELETE)
22012datainteger division or % by zero (a float one gives Infinity or NaN), also mod(a, 0); a duration divided by zero
22007datatemporal text that is no value of the type, a temporal map with an unknown key or conflicting date keys, an unknown time zone (Dates and times)
22008dataa temporal field out of range, a temporal value or result outside the years -9999 to 9999
22003dataa numeric result out of range (integer overflow, also of sum(), abs(), exp(), power()); a conversion out of range (toInteger(1.0e19), CAST('1e400' AS FLOAT))
22018dataCAST of text that is no value of the target type (CAST('abc' AS INTEGER))
22011dataa negative position or length in substring(), left(), right()
22027dataa TRIM(c FROM s) character c that is not exactly one character
2201Bdataan invalid regular expression on the right of =~: a literal or $parameter pattern before the run, a pattern computed per row when a row reaches it
2201Edatathe logarithm of a number <= 0, or to a base <= 0 or 1 (ln, log, log10)
2201Fdatasqrt() of a negative number, power() of 0 to a negative power or of a negative number to a non-integer power
22023dataan argument outside the function's values: a truncation unit the type lacks or an unknown one (date.truncate('hour', ..)), range() step 0, a negative round() precision or an unknown rounding mode, a negative replace() limit, a negative n in the list trim(list, n)

42001 is fixed; the other codes are provisional: they follow the standard's classes and may still be refined before the GQL support is complete. The function codes (22018, 22011, 22027, 2201E, 2201F, 22023, 22007, 22008) are the ISO / SQL-heritage subclasses of class 22; Neo4j reports the same failures with its own vendor subclasses (22N38, 22N03, ...). Match on the kind (GqlErrorKind) in code, and treat the code as diagnostic information.

g.gql("MATCH (n:person) RETURN n.name AS name ORDER BY name LIMIT $l", #{l: -1})   // error: LIMIT must be a non-negative integer (22G02)
g.v().gql("MATCH (n) RETURN n")   // error: gql() starts a traversal in this version (0A000)

In Rust

use graphersal::error::GqlErrorKind;
use graphersal::prelude::*;

let graph = TraversalGraph::tinkerpop_modern();
let error = graph.traversal().gql("MATCH (n:person) RETRUN n").to_list().unwrap_err();
if let TraverserError::Gql { kind, gqlstatus, line, column, .. } = error.root_cause() {
    assert_eq!(*kind, GqlErrorKind::Syntax);
    assert_eq!(gqlstatus, "42001");
    assert_eq!((*line, *column), (1, 18));
}

The DiagnosticError trait gives the help text (help()) and the labelled lines (details(): query, expected, did you mean, GQLSTATUS) shown above.

Plans and Performance

gql() has no executor of its own. A query is parsed, its variables bound, a planner picks where each pattern starts and in which order it expands, and the result is lowered into an ordinary traversal plan: Gremlin steps (v(), has_label(), has(), out(), as(), where(), skip(), limit(), ...) plus a few internal steps. That plan then goes through the same optimizer, path analysis, property indexes, limits, cancellation, permissions and storages as a hand-written traversal. .profile() shows it.

g.gql("MATCH (p:person) WHERE p.age > 30 RETURN p.name AS name").profile()
Step                                                         Call      In     Out
==================================================================================
v(labels: ["person"])                                           1       0       4
has("age", P.gt(30))                                            1       4       2
gql:project("name")                                             1       2       2
Optimizer rules applied: source_filter_pushdown

(The profiles on this page leave out the time columns.) The query became v().has_label("person").has("age", P.gt(30)) plus a projection, and the optimizer folded the label into the scan, exactly as it does for the Gremlin form.

The internal steps

StepDoes
gql:project("a", "b", ...)builds the row map of RETURN (or of a WITH that builds rows) in written order, keeping NULL columns
gql:aggregate([keys], [aggregates], [columns])groups the rows by the key values and builds one row map per group (a barrier)
gql:distinct()DISTINCT on the row maps, with GQL's equality (1 = 1.0)
gql:bind("p")continues the pattern from the element in a WITH column
gql:trail("#1", ...)the trail check of a quantified edge or of an edge in the body of a quantified path pattern: the edge is none of the edges already bound under these labels
gql:filter("<condition>")a WHERE condition, or the part of it that cannot become has(), with GQL's three-valued logic
gql:order("<keys>")ORDER BY with GQL's NULL placement and type order; stable
gql:not_self_loop()keeps a self-loop from matching twice in an either-direction edge
gql:for("x IN <list>")FOR / UNWIND: one row per item of the list (unfold() with GQL's NULL rule); with an ordinal the row is the record of item and position
gql:lookup("(n:label)", "<equality>")starts a pattern at the vertices an equality with a value of the row finds, by id ([id]) or through a property index ([index: vertex label.key], or [index: vertex key, any label] for a label-less one)
gql:value("<expression>")the last step of a pattern comprehension's child: the value of its | part for one match, which the host step collects into the list
gql:insert_node(["label", ...], "{props}")INSERT of one node: creates it per row, with all its properties in one storage call, and makes it the current element (Writes)
gql:insert_edge("label", "from", "to", "{props}")INSERT of one edge between the nodes of the row named from and to ((#n) for an unnamed node of the pattern)
gql:set("<items>"), gql:remove("<items>")one SET / REMOVE clause: applies its items per row to the elements the row's variables hold and passes the row on unchanged
gql:delete("[DETACH] DELETE <targets>")one DELETE clause: collects the targets of every row, checks the NODETACH rule for the whole clause, removes the edges, then the nodes, and passes the rows on unchanged
gql:merge("<pattern>", <search>, <creation>[, "ON CREATE SET ..", "ON MATCH SET .."])one MERGE clause: per row, runs the search child (a MATCH of the pattern from the row) and emits a row per match, or runs the creation child (the insert chain) once; then its ON items
gql:error("<GQLSTATUS>")the marker of a query that failed to parse or bind; raises the error before the run

gql:filter, gql:project, gql:value, gql:order, gql:aggregate and gql:for may hold the bodies of the EXISTS, COUNT { } and COLLECT { } subqueries and pattern comprehensions their expressions contain as child traversals, shown as \> lines under the step (EXISTS and pattern predicates, comprehensions, COUNT and COLLECT). UNION and CALL need no step of their own: they are Gremlin's union(), flat_map() and optional() (UNION, NEXT and CALL). They exist only in plans of gql(); they are not DSL steps. Everything else in a GQL plan is an ordinary step.

What becomes has()

A WHERE condition is split at its top-level ANDs. A part of the form var.key <op> value, where the value is a literal or a $parameter, is pushed into has() right at the scan or the edge it reads, where the optimizer and the property indexes see it; the rest runs in gql:filter. Pushed: = (as P.eq), <, <=, >, >=, IN (with NULL items removed), STARTS WITH, ENDS WITH, CONTAINS with a string, =~ with a valid pattern (as TextP.regex("^(?:pattern)$"), the whole-string expression), IS NOT NULL. Never pushed: <>, IS NULL, OR, NOT, conditions over two variables, NULL or list operands: there the semantics of has() and GQL's three-valued logic differ.

g.gql("MATCH (n:person) WHERE n.age > 30 AND n.name STARTS WITH 'j' RETURN n.name AS n").profile()
g.gql("MATCH (n) WHERE n.age <> 29 RETURN n.name AS n").profile()
v(labels: ["person"])                                           1       0       4
has("name", TextP.starting_with("j"))                           1       4       1
has("age", P.gt(30))                                            1       1       1
gql:project("n")                                                1       1       1

v()                                                             1       0       6
gql:filter("n.age <> 29")                                       1       6       3
gql:project("n")                                                1       3       3

Index use

When a property index exists, the planner starts at the node with an indexed equality (or IN), then one with a label and a property condition, then one with a label, then the first node; and the property index rule of the optimizer serves the scan. A parameter works as well as a literal:

{ g.create_index(#{label: "person", key: "name"}); g.gql("MATCH (p:person {name: $n})-[:created]->(s) RETURN s.name AS s ORDER BY s", #{n: "josh"}).to_list() }   // #{"s": "lop"}, #{"s": "ripple"}
v(labels: ["person"]).has("name", P.eq("josh")) [index: vertex person.name, exact]    1       0       1
out("created")                                                                        1       1       2
gql:project("s")                                                                      1       2       2
gql:order("s")                                                                        1       2       2
Optimizer rules applied: source_filter_pushdown, property_index

The equality of a string, boolean, uuid or temporal value is answered by the index exactly in a query that does not write: its has step leaves the plan (, exact). A correlated gql:lookup(..) reads the same index but keeps checking GQL's = on each candidate (its value is known only per row).

A label-less index (g.create_index(#{key: "name"})) serves a node without a label, MATCH (n {name: $x}), and a node whose labels have no index of their own on the key (the labels are checked after it), both as the root scan and as a correlated lookup: .profile() shows [index: vertex name, any label] on v() or on gql:lookup(..).

The planner reads only what every storage offers (statistics() and the index catalog), so a host's own storage gets the same plans.

Edges: out() when nothing reads the edge

An edge that is not named, filtered or read becomes a plain out("T") / in("T"), the cheapest form. A named, filtered or trail-checked edge becomes out_e("T") ... in_v(), with its filters on the edge in between. An either-direction edge is a union() of both directions with the self-loop guard:

g.gql("MATCH (a:person)-[e:created]->(s) WHERE e.weight > 0.5 RETURN a.name AS a, s.name AS s ORDER BY a").profile()
g.gql("MATCH (a:person)-[:knows]-(b) RETURN b.name AS b").profile()
v(labels: ["person"])                                           1       0       4
as("a") [path: labels(a)]                                       1       4       4
out_e("created") [path: labels(a)]                              1       4       4
has("weight", P.gt(0.5)) [path: labels(a)]                      1       4       1
in_v() [path: labels(a)]                                        1       1       1
gql:project("a", "s")                                           1       1       1
gql:order("a")                                                  1       1       1

v(labels: ["person"])                                                     1       0       4
union(__.out("knows"), __.in_e("knows").gql:not_self_loop().out_v())      1       4       4
gql:project("b")                                                          1       4       4

as() only where needed

A variable gets a path label (as("a")) only when something reads it while the traversal has moved past it: a RETURN column of an earlier node, a join, a trail check, a condition over two variables. MATCH (p:person) RETURN p.name records no path at all. The [path: ...] note in the profile shows what is recorded (Path Requirement Analysis). Return only what you need: each returned earlier variable is one more label per traverser.

Merge points

Between two hops the lowering places a lazy_barrier(), a merge point: traversers that reached the same vertex with the same recorded labels merge into one with a higher bulk, so the next hop runs once for all of them (Bulk and Barriers). The rows stay the same; the work shrinks. Here four authors (josh twice) become three traversers:

g.gql("MATCH (s:software)<-[:created]-(p)<-[:knows]-(m) RETURN m.name AS m").profile()
Step                                                         Call      In     Out Bulk
=======================================================================================
v(labels: ["software"])                                         1       0       2    2
in("created")                                                   1       2       4    4
lazy_barrier()                                                  1       4       3    4
in("knows")                                                     1       3       1    2
gql:project("m")                                                1       1       1    2

Merging needs equal labels, so it pays off where the middle node is not returned. Returning p labels it, and traversers at the same vertex still merge only with the same p.

Trail checks and merging. The trail rule (an edge is bound once per MATCH) is checked with where(P.neq("#1")) against the earlier edge, which must therefore be labelled. When two edges of one MATCH can have the same label, the first is labelled and the traversers stay apart until the check has run. The planner skips the check when the label sets cannot overlap (-[:knows]-> then -[:created]->), so name edge labels in multi-hop patterns where you can:

g.gql("MATCH (a)-[:created]->(s)<-[:created]-(b) RETURN a.name AS a, b.name AS b").profile()
v()                                                             1       0       6
as("a") [path: labels(a)]                                       1       6       6
out_e("created") [path: labels(a)]                              1       6       4
as("#1") [path: labels(#1,a)]                                   1       4       4
in_v() [path: labels(#1,a)]                                     1       4       4
lazy_barrier() [path: labels(#1,a)]                             1       4       4
in_e("created") [path: labels(#1,a)]                            1       4      10
where(P.neq("#1")) [path: labels(a)]                            1      10       6
out_v() [path: labels(a)]                                       1       6       6
gql:project("a", "b")                                           1       6       6

Disconnected patterns are not optimized yet

Patterns that share no variable (MATCH (a:person), (s:software)) are a Cartesian product, built with a second v() in the middle of the traversal. The optimizer does not fold labels or use indexes for a v() there yet, so the second scan runs in full once per row of the first:

g.gql("MATCH (a:person), (s:software) RETURN a.name AS a, s.name AS s").profile()
v(labels: ["software"])                                         1       0       2
as("s") [path: labels(s)]                                       1       2       2
v() [path: labels(s)]                                           1       2      12
has_label("person") [path: labels(s)]                           1      12       8
gql:project("a", "s")                                           1       8       8

A pattern after the first with an equality an id or index serves is the exception: it starts with a gql:lookup instead of the second v(). Otherwise, connect patterns through a shared variable where the question allows it; the planner prefers connected patterns and starts the product at the smaller side. The same holds for a pattern after a WITH or inside an OPTIONAL MATCH that shares no variable with what came before, and for a leading OPTIONAL MATCH (its scan runs inside optional()).

LET, FILTER and WITH

LET, FILTER and a WITH that only passes values on add no steps: the planner treats their names as the expressions they stand for and their conditions like WHERE, so a condition on a LET value can still become has() where it reads a property directly, and the plan is that of the same query written without them:

g.gql("MATCH (p:person) LET d = p.age / 10 FILTER d = 3 AND p.name STARTS WITH 'j' RETURN p.name AS name").profile()
v(labels: ["person"])                                           1       0       4
has("name", TextP.starting_with("j"))                           1       4       1
gql:filter("d = 3")                                             1       1       1
gql:project("name")                                             1       1       1

A WITH with DISTINCT, an aggregate, ORDER BY, OFFSET or LIMIT builds its rows with the same steps as a RETURN. When a later clause reads them, the row is labelled once (#w1) and gql:bind moves to the element of a column to continue the pattern; the barrier starts fresh paths, so nothing recorded before it is carried on:

g.gql("MATCH (p:person) WITH p ORDER BY p.age DESC LIMIT 2 MATCH (p)-[:created]->(s) RETURN p.name AS name, s.name AS sw").profile()
v(labels: ["person"])                                           1       0       4
as("p") [path: labels(p)]                                       1       4       4
gql:project("p") [path: labels(p)]                              1       4       4
gql:order("p.age DESC")                                         1       4       4
limit(2)                                                        1       4       2
as("#w1") [path: labels(#w1)]                                   1       2       2
gql:bind("p") [path: labels(#w1)]                               1       2       2
out("created") [path: labels(#w1)]                              1       2       3
gql:project("name", "sw")                                       1       3       3

FOR and the correlated lookup

FOR (and UNWIND) becomes one gql:for step; the item is the current object of each row, and as("x") labels it only when a later step reads it after the row moved on. A query that does not start with MATCH starts from one empty row, inject(0):

g.gql("FOR x IN [10, 20] WITH ORDINALITY i RETURN x, i").profile()
inject(0)                                                       1       0       1
gql:for("x IN [10, 20] WITH ORDINALITY i")                      1       1       2
gql:project("x", "i")                                           1       2       2

A MATCH after FOR runs once per row. Without help that is a scan per item, so a list of 1000 names reads the whole label 1000 times:

g.gql("FOR n IN $names MATCH (p:person {name: n}) RETURN n, p.age AS age", #{names: ["vadas", "marko", "nobody"]}).profile()
inject(0)                                                       1       0       1
gql:for("n IN $names")                                          1       1       3
as("n") [path: labels(n)]                                       1       3       3
v() [path: labels(n)]                                           1       3      18
has_label("person") [path: labels(n)]                           1      18      12
gql:filter("name: n") [path: labels(n)]                         1      12       2
gql:project("n", "age")                                         1       2       2

When an equality between the pattern's vertex and a value of the row can be answered directly, the planner starts the pattern with gql:lookup instead: by element id always (element_id(n) = id, either operand order), by a property ({name: n}, n.name = x) when a property index on that key exists for every label of the node. Each row then reads only the vertices the value finds:

g.gql("FOR id IN $ids MATCH (n) WHERE element_id(n) = id RETURN id, n.name AS name", #{ids: ["1", "3", "42"]}).profile()
inject(0)                                                          1       0       1
gql:for("id IN $ids")                                              1       1       3
as("id") [path: labels(id)]                                        1       3       3
gql:lookup("(n)", "element_id(n) = id") [id] [path: labels(id)]    1       3       2
gql:project("id", "name")                                          1       2       2
{ g.create_index(#{label: "person", key: "name"}); g.gql("FOR n IN $names MATCH (p:person {name: n}) RETURN n, p.age AS age", #{names: ["vadas", "marko", "nobody"]}).profile() }
inject(0)                                                                            1       0       1
gql:for("n IN $names")                                                               1       1       3
as("n") [path: labels(n)]                                                            1       3       3
gql:lookup("(p:person)", "name: n") [index: vertex person.name] [path: labels(n)]    1       3       2
has_label("person") [path: labels(n)]                                                1       2       2
gql:project("n", "age")                                                              1       2       2

The lookup checks every vertex it finds with GQL's =, so it returns exactly the rows of the scan (Semantics); a NULL value finds nothing, and a value an index cannot serve (a list, NaN, a non-string id, a storage that reports no index) falls back to scanning the label. The same lookup starts any pattern that is not the first one: a second, disconnected pattern with an indexed equality (MATCH (a:person {name: 'marko'}), (b:person) WHERE b.age = a.age + 3 with an index on person.age), or a MATCH after a WITH. The first pattern of a query is never a lookup: it is a scan the optimizer serves with the index as usual. Edges are not looked up (an equality on element_id(e) stays a filter).

Aggregation

An aggregating RETURN (or WITH) becomes one gql:aggregate in place of gql:project. It does not use Gremlin's group() / count() / fold(), whose rules for missing values and empty input differ from GQL's (Semantics). It counts a merged traverser by its bulk, so merge points before it save work without changing a count:

g.gql("MATCH (s:software)<-[:created]-(p) RETURN s.name AS sw, count(p) AS authors ORDER BY sw").profile()
g.gql("MATCH (p:person) RETURN DISTINCT p.age > 30 AS old").profile()
v(labels: ["software"])                                         1       0       2
as("s") [path: labels(s)]                                       1       2       2
in("created") [path: labels(s)]                                 1       2       4
gql:aggregate(["s.name"], ["count(p)"], ["sw", "authors"])      1       4       2
gql:order("sw")                                                 1       2       2

v(labels: ["person"])                                           1       0       4
gql:project("old")                                              1       4       4
gql:distinct()                                                  1       4       2

Counts

count(x) of a variable that can never be NULL (a node or edge of a MATCH that is not optional, outside a parenthesized path pattern, in a query without writes) counts like count(*), so x gets no as(). An aggregation whose every column is such a count, with no grouping key, is the Gremlin count() followed by the row (gql:project), whatever the walk before it: one row per match is never built. A pattern of one node with its labels and pushed properties is then answered from the statistics (or an index), like g.v().has_label(..).count(), and one directed edge between two nodes without labels or conditions is scanned as e(), so MATCH ()-[r:T]->() RETURN count(r) is g.e().has_label("T").count():

g.gql("MATCH (n:person) RETURN count(n) AS people").profile()
g.gql("MATCH ()-[r:knows]->() RETURN count(r) AS c").profile()
g.gql("MATCH ()-[r:knows]-() RETURN count(r) AS c").profile()
v(labels: ["person"]).count()                                   1       0       4
gql:project("people")                                           1       1       1

e(labels: ["knows"]).count()                                    1       0       2
gql:project("c")                                                1       1       1

v()                                                                       1       0       6
union(__.out("knows"), __.in_e("knows").gql:not_self_loop().out_v())      1       6       4
  \> out("knows")                                                         6       6       2
  \> in_e("knows")                                                        6       6       2
  \> gql:not_self_loop()                                                  6       2       2
  \> out_v()                                                              6       2       2
count()                                                                   1       4       1
gql:project("c")                                                          1       1       1

Either direction walks the pattern, since it matches every edge twice and a self-loop once, which no statistic holds; so do a longer pattern, a labelled endpoint, a filter, OPTIONAL MATCH, UNWIND and WITH before the count, all counted lazily by count(). A count in the body of a subquery or CALL, a count beside a grouping key or another aggregate, and a count in a writing query (its plan stays as written) go through gql:aggregate, without a label for the counted variable. count(DISTINCT x), count(x) of a variable that may be NULL (an OPTIONAL MATCH, a WITH column, a FOR item, a ? singleton) and every other aggregate read their argument as written.

The executor runs one step over all its input before the next, so a count that walks still holds every traverser of its pattern at once, just not a row per match nor the counted variable's label: on 1 000 000 edges MATCH (a)-[r]->(b) WHERE a.id < b.id RETURN count(r) needs about 92 MiB (the edge level and the label of a), under a traversal.max_materialized_bytes of 100 000 000 bytes.

OPTIONAL MATCH

An OPTIONAL MATCH is Gremlin's optional() around the lowered part, its WHERE inside. Where the part does not match, the row continues unchanged and the labels set inside are absent, which reads as NULL. A leading OPTIONAL MATCH starts from one row, inject(0):

g.gql("MATCH (p:person) OPTIONAL MATCH (p)-[:created]->(s) RETURN p.name AS name, count(s) AS n").profile()
g.gql("OPTIONAL MATCH (n:robot) RETURN n").profile()
v(labels: ["person"]) [path: labels(s)]                                   1       0       4
as("p") [path: labels(p,s)]                                               1       4       4
optional(__.out("created").as("s")) [path: labels(p,s)]                   1       4       5
  \> out("created") [path: labels(p)]                                     4       4       4
  \> as("s") [path: labels(p,s)]                                          4       4       4
gql:aggregate(["p.name"], ["count(s)"], ["name", "n"])                    1       5       4

inject(0) [path: labels(n)]                                               1       0       1
optional(__.v(labels: ["robot"]).as("n")) [path: labels(n)]               1       1       1
  \> v(labels: ["robot"])                                                 1       1       0
  \> as("n") [path: labels(n)]                                            1       0       0
gql:project("n")                                                          1       1       1

After an optional part every later read goes through a label, since the current element differs between the rows that matched and those that did not.

Quantified edges

A quantified edge is a repeat() of the single edge, with emit() and times() for its bounds: {1,2} is repeat(..).emit().times(2), {0,n} emit().repeat(..).times(n), {n} repeat(..).times(n), {m,n} with m > 1 emit(__.loops().is(P.gte(m))), an unbounded one has no times(). Inside the loop each edge is labelled and checked with gql:trail against the edges of the match so far (trail):

g.gql("MATCH (a {name: 'marko'})-[:knows|created]->{1,2}(b) RETURN b.name AS b").profile()
v() [path: labels(#1)]                                                                  1       0       6
has("name", P.eq("marko")) [path: labels(#1)]                                           1       6       1
repeat(__.out_e("knows", "created").gql:trail("#1").as("#1").in_v()).times(2).emit()    1       1       5
[loops: 2, max_depth: 2, avg_loops: 1.4]
  \> out_e("knows", "created") [path: labels(#1)]                                       2       4       5
  \> gql:trail("#1") [path: labels(#1)]                                                 2       5       5
  \> as("#1") [path: labels(#1)]                                                        2       5       5
  \> in_v() [path: labels(#1)]                                                          2       5       5
gql:project("b")                                                                        1       5       5

The labels keep the traversers of different matches apart, so there is no merge point after a quantified edge: a quantified pattern costs more than the plain repeat() that ignores trail. The plan never records full paths ([path: labels(..)], never full).

Quantified path patterns

A quantified path pattern is a repeat() of its whole body, with the same emit() / times() modulators as a quantified edge. Inside the loop each body edge is labelled and checked with gql:trail against every edge of the match so far that could be the same edge (the earlier iterations of each body edge, the other body edges, the edges of the clause outside), and each body variable the query reads is labelled with as(): the list of a group variable is read back from those labels, one per iteration. The plan records labels only, never full paths:

g.gql("MATCH (a {name: 'marko'}) ((x)-[e:knows]->(m)-[f:created]->(y)){1,2} (b) RETURN b.name AS b, [n IN m | n.name] AS via").profile()
{p1}

The two gql:trail steps check one label each here: a knows edge can never be a created edge. A body condition on one element runs where it is matched, as a has() or gql:filter; one that reads several body elements runs as a gql:filter at the end of the body, in every iteration.

? is emit().repeat(B).times(1) and a body without a quantifier is inlined, its steps run once in the plan as if the parentheses were not there:

g.gql("MATCH (a {name: 'josh'}) ((x)-[:created]->(s))? (q) RETURN s.name AS s, q.name AS q").profile()
g.gql("MATCH ((x:person)-[:created]->(s) WHERE s.name = 'ripple') RETURN x.name AS who").profile()
{p2}
{p3}

The planner may walk a quantified path pattern from its far end when that end is the cheaper start (a label, an indexed property); the body then runs in reverse, and the group lists are still given in the order the text reads.

Path variables

A path variable is assembled from labels, not from Gremlin's path() (which would record the full path at every step): every element of the named pattern is labelled, and for a quantified edge also the vertices inside the loop (#gv..):

g.gql("MATCH p = (a {name: 'marko'})-[:knows]->{1,2}(b) RETURN p").profile()
v() [path: labels(#2,#gv2)]                                                                                       1       0       6
has("name", P.eq("marko")) [path: labels(#2,#gv2)]                                                                1       6       1
as("a") [path: labels(#2,#gv2,a)]                                                                                 1       1       1
repeat(__.out_e("knows").gql:trail("#2").as("#2").in_v().as("#gv2")).times(2).emit() [path: labels(#2,#gv2,a)]    1       1       2
[loops: 2, max_depth: 2, avg_loops: 1.0]
  \> out_e("knows") [path: labels(#2,#gv2,a)]                                                                     2       3       2
  \> gql:trail("#2") [path: labels(#2,#gv2,a)]                                                                    2       2       2
  \> as("#2") [path: labels(#2,#gv2,a)]                                                                           2       2       2
  \> in_v() [path: labels(#2,#gv2,a)]                                                                             2       2       2
  \> as("#gv2") [path: labels(#2,#gv2,a)]                                                                         2       2       2
as("b") [path: labels(#2,#gv2,a,b)]                                                                               1       2       2
gql:project("p")                                                                                                  1       2       2

A path variable that nothing reads labels nothing.

EXISTS and pattern predicates

A subquery is lowered in one of two ways.

The fast path. A [NOT] EXISTS (or pattern predicate) that is a condition of its own in a WHERE or FILTER (alone, or joined to the others by AND) becomes Gremlin's filter(__.<body>) or not(__.<body>), the step Gremlin's where(__..) / not(__..) would run. The body starts where the row stands: a body that starts at the element the row is on needs no step and no label, so the "who has no ..." question is exactly its Gremlin twin:

g.gql("MATCH (p:person) WHERE NOT (p)-[:created]->() RETURN p.name AS name").profile()
g.gql("MATCH (a:person), (b:person) WHERE (a)-[:knows]->(b) RETURN a.name AS a, b.name AS b").profile()
g.gql("MATCH (s:software) WHERE EXISTS { (p:person) WHERE p.age > 33 } RETURN s.name AS s").profile()
v(labels: ["person"])                                                     1       0       4
not(__.out("created"))                                                    1       4       1
  \> out("created")                                                       4       4       4
gql:project("name")                                                       1       1       1

v(labels: ["person"])                                                     1       0       4
as("a") [path: labels(a)]                                                 1       4       4
v() [path: labels(a)]                                                     1       4      24
has_label("person") [path: labels(a)]                                     1      24      16
filter(__.in("knows").where(P.eq("a"))) [path: labels(a)]                 1      16       2
  \> in("knows") [path: labels(a)]                                       16      16       8
  \> where(P.eq("a"))                                                     8       8       2
gql:project("a", "b")                                                     1       2       2

v(labels: ["software"])                                                   1       0       2
filter(__.v(labels: ["person"]).has("age", P.gt(33)))                     1       2       2
  \> v(labels: ["person"])                                                2       2       8
  \> has("age", P.gt(33))                                                 2       8       2
gql:project("s")                                                          1       2       2

A body that reads a second imported variable joins it with where(P.eq("a")) (or starts from it with select(), or with gql:bind from a WITH column); a body that imports nothing starts with its own scan, which the optimizer folds and pushes down as anywhere else. The optimizer treats the child like any Gremlin child: between two hops it may add a lazy_barrier(), as it does for where(__.out("knows").out("created")).

The expression hook. Anywhere else (under OR, XOR, CASE, in a RETURN or WITH column, an ORDER BY key, an aggregate, a FOR list) the gql:* step that evaluates the expression holds the body as a child and runs it when the evaluation of a row needs the answer: the Call and In columns of the child show how many rows ran it. Here only the two rows that p.age > 30 did not already decide ran in("knows"):

g.gql("MATCH (p:person) WHERE p.age > 30 OR (p)<-[:knows]-() RETURN p.name AS name").profile()
g.gql("MATCH (p:person) RETURN p.name AS name, EXISTS { (p)-[:knows]->() } AS knows").profile()
v(labels: ["person"])                                                     1       0       4
gql:filter("p.age > 30 OR (p)<-[:knows]-()")                              1       4       3
  \> in("knows")                                                          2       2       1
gql:project("name")                                                       1       3       3

v(labels: ["person"])                                                     1       0       4
gql:project("name", "knows")                                              1       4       4
  \> out("knows")                                                         4       4       2

Both forms run the same body, so they give the same rows. On an element, the subquery steps come last (Semantics): after the pushed has() and the plain gql:filter, and after the element's as(), so a body that reads the element through its label (a second body clause starting at it) finds it:

g.gql("MATCH (a:person) WHERE CASE WHEN EXISTS { MATCH (a)<-[:knows]-() MATCH (a)--() } THEN true ELSE false END RETURN a.name AS name ORDER BY name").profile()
v(labels: ["person"])                                                                         1       0       4
as("a") [path: labels(a)]                                                                     1       4       4
gql:filter("CASE WHEN EXISTS { MATCH (a)<-[:knows]-() MATCH (a)--() } THEN t…" (82 chars))    1       4       2
  \> in("knows") [path: labels(a)]                                                            4       4       2
  \> select("a")                                                                              2       2       2
  \> union(__.out(), __.in_e().gql:not_self_loop().out_v())                                   2       2       4
...
gql:project("name")                                                                           1       2       2
gql:order("name")                                                                             1       2       2

The global optimizer rule filter_reorder may still move a fast-path child before a gql:filter by its cost estimate (WHERE NOT (p)-->() AND p.name <> 'x' runs not(__.out()) before gql:filter("p.name <> 'x'")), as it would in a Gremlin plan; the rows are the same.

Map projections and comprehensions

A map projection and a list comprehension add no step: the gql:* step that evaluates the expression builds the map or the list from the row's values, with no allocation per item beyond the result.

g.gql("MATCH (p:person) RETURN p {.name, .age} AS m, [x IN [p.age, 30] WHERE x > 28] AS l").profile()
v(labels: ["person"])                                           1       0       4
gql:project("m", "l")                                           1       4       4

A pattern comprehension is a subquery that collects: like an EXISTS in an expression, its body is a child of the step evaluating it, and the child ends in gql:value(..), the value of the | part per match. The host runs it once per row that reaches it and builds the list from the child's results (here 4 rows ran out("knows"), which found 2 friends), the plan of its Gremlin twin project(..).by(__.out("knows").values("name").fold()):

g.gql("MATCH (p:person) RETURN p.name AS name, [(p)-[:knows]->(f) | f.name] AS friends").profile()
g.gql("MATCH (p:person) RETURN p {.name, projects: [(p)-[:created]->(s) | s {.name, n: size([(s)<-[:created]-(c) | c])}]} AS m").profile()
v(labels: ["person"])                                                     1       0       4
gql:project("name", "friends")                                            1       4       4
  \> out("knows")                                                         4       4       2
  \> gql:value("f.name")                                                  4       2       2

v(labels: ["person"])                                                     1       0       4
gql:project("m")                                                          1       4       4
  \> out("created")                                                       4       4       4
  \> gql:value("s {.name, n: size([(s)<-[:created]-(c) | c])}")           4       4       4
        \> in("created")                                                  4       4      10
        \> gql:value("c")                                                 4      10      10

A comprehension nested in the | part is a child of the inner gql:value, so it runs once per match of the outer pattern: nested comprehensions from the same element multiply the work, as nested Gremlin fold() children do (Semantics). The collected list is checked against the limits before it is built (Limits).

COUNT and COLLECT

COUNT { } and COLLECT { } are hosted like an EXISTS in an expression: the step evaluating the expression holds the body as its child and runs it once per row that reaches it. A COUNT child ends in count(), which counts the body's traversers with their bulk, and a COLLECT child in gql:value(..), the RETURN item, which the host collects in arrival order (after the body's own gql:order). A COUNT body whose RETURN only projects keeps its gql:project, which count() never reads, so its items are not evaluated (Semantics):

g.gql("MATCH (p:person) RETURN p.name AS who, COUNT { (p)-[:created]->() } AS n").profile()
g.gql("MATCH (p:person) RETURN p.name AS who, COLLECT { MATCH (p)-[:created]->(s) RETURN s.name ORDER BY s.name } AS sw").profile()
g.gql("MATCH (p:person) WHERE COUNT { (p)-[:created]->() } > 1 RETURN p.name AS who").profile()
v(labels: ["person"])                                                     1       0       4
gql:project("who", "n")                                                   1       4       4
  \> out("created")                                                       4       4       4
  \> count()                                                              4       4       4

v(labels: ["person"])                                                     1       0       4
gql:project("who", "sw")                                                  1       4       4
  \> out("created")                                                       4       4       4
  \> gql:project("s.name")                                                4       4       4
  \> gql:order("s.name")                                                  4       4       4
  \> gql:value("s.name")                                                  4       4       4

v(labels: ["person"])                                                     1       0       4
gql:filter("COUNT { (p)-[:created]->() } > 1")                            1       4       1
  \> out("created")                                                       4       4       4
  \> count()                                                              4       4       4
gql:project("who")                                                        1       1       1

A whole-query body (WITH, an aggregate, RETURN) is lowered like a top-level query onto the child, so an EXISTS with one keeps the fast path when it stands alone in a WHERE; the child ends in the body's own steps, and filter() asks only whether one traverser comes out:

g.gql("MATCH (p:person) WHERE EXISTS { MATCH (p)-[:created]->(s) WITH count(s) AS c WHERE c > 1 RETURN c } RETURN p.name AS who").profile()
v(labels: ["person"])                                                                                    1       0       4
filter(__.out("created").gql:aggregate([], ["count(s)"], ["c"]).gql:filter("c > 1").gql:project("c"))    1       4       1
  \> out("created")                                                                                      4       4       4
  \> gql:aggregate([], ["count(s)"], ["c"])                                                              4       4       4
  \> gql:filter("c > 1")                                                                                 4       4       1
  \> gql:project("c")                                                                                    4       1       1
gql:project("who")                                                                                       1       1       1

A body that starts from an import with an equality the id or a property index serves starts with gql:lookup, as a later pattern of the query does (FOR and the correlated lookup); this holds for EXISTS, COUNT, COLLECT, pattern comprehensions and CALL bodies alike.

UNION, NEXT and CALL

UNION is Gremlin's union() as the start step: each operand is lowered onto its own child exactly as a query of its own, so its scan keeps the label, the pushed has() and an index, and UNION (not ALL) adds gql:distinct() after it. Each operand's ORDER BY and LIMIT stay inside its child:

g.gql("MATCH (p:person) WHERE p.age > 30 RETURN p.name AS name UNION MATCH (s:software) RETURN s.name AS name").profile()
union(__.v(labels: ["person"]).has("age", P.gt(30)).gql:project("name"), __.v(labels: ["software"]).gql:project("name"))    1       1       4
  \> v(labels: ["person"])                                                                                                  1       1       4
  \> has("age", P.gt(30))                                                                                                   1       4       2
  \> gql:project("name")                                                                                                    1       2       2
  \> v(labels: ["software"])                                                                                                1       1       2
  \> gql:project("name")                                                                                                    1       2       2
gql:distinct()                                                                                                              1       4       4

NEXT adds no step. After a plain query it is the WITH of the same items, so it gives the same plan (here the FILTER after NEXT became the has() of the scan); after a UNION the next statement continues from the union's row maps:

g.gql("MATCH (p:person) RETURN p.name AS name, p.age AS age NEXT FILTER age > 30 RETURN name").profile()
g.gql("MATCH (p:person) RETURN p.name AS name UNION ALL MATCH (s:software) RETURN s.name AS name NEXT RETURN name ORDER BY name LIMIT 3").profile()
v(labels: ["person"])                                           1       0       4
has("age", P.gt(30))                                            1       4       2
gql:project("name")                                             1       2       2

union(__.v(labels: ["person"]).gql:project("name"), __.v(labels: ["software"]).gql:project("name"))    1       1       6
  \> v(labels: ["person"])                                                                             1       1       4
  \> gql:project("name")                                                                               1       4       4
  \> v(labels: ["software"])                                                                           1       1       2
  \> gql:project("name")                                                                               1       2       2
gql:project("name")                                                                                    1       6       6
gql:order("name")                                                                                      1       6       6
limit(3)                                                                                               1       6       3

CALL is flat_map(__.<body>): the body is lowered onto the child from the row's current element, so a body that continues from an import needs no step to reach it, and its gql:order and limit() run per call (Call 4: once per person). OPTIONAL CALL wraps it in optional(..) and labels the body's row (as("#c<k>")) so a row without results reads NULL columns. After a CALL, the outer variables are read through their labels (as("p")):

g.gql("MATCH (p:person) CALL (p) { MATCH (p)-[e:created]->(s) RETURN s.name AS top ORDER BY e.weight DESC LIMIT 1 } RETURN p.name AS who, top").profile()
g.gql("MATCH (p:person) OPTIONAL CALL (p) { MATCH (p)-[:created]->(s) RETURN s.name AS sw } RETURN p.name AS who, sw").profile()
v(labels: ["person"])                                                                                                    1       0       4
as("p") [path: labels(p)]                                                                                                1       4       4
flat_map(__.out_e("created").as("e").in_v().gql:project("top").gql:order("e.weight DESC").limit(1)) [path: labels(p)]    1       4       3
  \> out_e("created")                                                                                                    4       4       4
  \> as("e") [path: labels(e)]                                                                                           4       4       4
  \> in_v() [path: labels(e)]                                                                                            4       4       4
  \> gql:project("top") [path: labels(e)]                                                                                4       4       4
  \> gql:order("e.weight DESC")                                                                                          4       4       4
  \> limit(1)                                                                                                            4       4       3
gql:project("who", "top")                                                                                                1       3       3

v(labels: ["person"]) [path: labels(#c2)]                                                     1       0       4
as("p") [path: labels(#c2,p)]                                                                 1       4       4
optional(__.flat_map(__.out("created").gql:project("sw")).as("#c2")) [path: labels(#c2,p)]    1       4       5
  \> flat_map(__.out("created").gql:project("sw")) [path: labels(p)]                          4       4       4
        \> out("created")                                                                     4       4       4
        \> gql:project("sw")                                                                  4       4       4
  \> as("#c2") [path: labels(#c2,p)]                                                          4       4       4
gql:project("who", "sw")                                                                      1       5       5

flat_map() builds the results of one call before the first moves on, so an outer LIMIT does not shorten a call that has started (Semantics); a body that imports nothing still runs once per row. A UNION or NEXT inside a body is a union() or the next steps inside the flat_map child, run per row.

Writes

An INSERT becomes one gql:insert_node per new node and then one gql:insert_edge per new edge, in text order; a query that ends in a write ends with discard(), which drops the rows. A leading INSERT starts from one empty row, inject(0):

g.gql("INSERT (:city {name: 'Berlin'})").profile()
Step                                                         Call      In     Out
==================================================================================
inject(0)                                                       1       0       1
gql:insert_node(["city"], "{name: 'Berlin'}")                   1       1       1
discard()                                                       1       1       0

After a MATCH, the variables the insert reads are labelled with as():

g.gql("MATCH (p:person {name: 'marko'}) INSERT (p)-[:likes]->(f:fruit {name: 'apple'})").profile()
Step                                                            Call      In     Out
=====================================================================================
v(labels: ["person"])                                              1       0       4
has("name", P.eq("marko"))                                         1       4       1
as("p") [path: labels(p)]                                          1       1       1
gql:insert_node(["fruit"], "{name: 'apple'}") [path: labels(p)]    1       1       1
gql:insert_edge("likes", "p", "f")                                 1       1       1
discard()                                                          1       1       0
Optimizer rules applied: source_filter_pushdown

A SET or REMOVE clause becomes one gql:set / gql:remove step with its items as written; the variables it changes are labelled with as() before it, like those an insert reads:

g.gql("MATCH (p:person {name: 'marko'}) SET p.age = p.age + 1, p:admin").profile()

A DELETE clause becomes one gql:delete step with the clause as written. It is a barrier: it takes every row before it removes anything, so the NODETACH check sees the whole clause:

g.gql("MATCH (p:person {name: 'marko'}) DETACH DELETE p").profile()

A MERGE clause becomes one gql:merge step holding two children, shown as \> lines: the search, planned like a MATCH of the pattern that starts from a bound node of the row (or from a lookup by id or a property index), and the creation, the insert chain of the pattern; both end in the same gql:project of the pattern's variables, so a found and a created row look alike:

g.gql("MATCH (a:person {name: 'marko'}) MERGE (a)-[:likes]->(f:fruit {name: 'apple'})").profile()

A plan that writes never merges traversers, so the lowering places no merge points in it; a lazy_barrier() the optimizer adds between two hops passes every traverser on unmerged (In = Out). The write steps run only after the steps before them consumed their whole input, which is what makes the visibility rule of Semantics hold. A CALL body that ends in a write is optional(__.<body>.discard()): it runs per row and keeps the row.

Limits, cancellation, permissions

A GQL query is a traversal, so everything that bounds a traversal bounds it too: resource limits and query limits, cancellation, the memory budget, and the permission check, which sees the reads and writes of the lowered plan (an INSERT asks Create per new label, like add_v() and add_e(), a SET or REMOVE Update like property(); Writing with GQL): reading a denied label through gql() is refused as the equivalent Gremlin is (also a label reached only through a quantified edge, the body of a quantified path pattern or an optional part, or only inside an EXISTS, COUNT or COLLECT body, a pattern comprehension, a CALL body or a later UNION operand, whichever way it is lowered: a subquery's child is checked like a Gremlin child, even when no row reaches it). An unbounded quantifier (on an edge or a path pattern) is bounded by repeat.max_loops and traversal.max_traversers (Semantics), also inside a subquery. The list of a pattern comprehension expands the bulk of its child's results under bulk.max_expansion and is checked against traversal.max_materialized_bytes and the memory budget before it is built, like collect_list(). The parser bounds nesting (128 levels, 54001) so no query can exhaust the stack, CALL bodies and whole-query subquery bodies nest at most 16 levels, and a query holds at most 64 subqueries (pattern comprehensions, COUNT { } and COLLECT { } included; CALL bodies are not counted) and runs at most 1024 subquery bodies (Errors).

GQL Conformance

This page lists which parts of ISO/IEC 39075 (GQL) gql() supports, in the style of the conformance appendices that GQL implementations publish. It is maintained by hand together with the code; when a construct lands, its row moves here in the same change.

GQL names its optional features with identifiers such as G036 (graph pattern features), GQ.. (query features), GE.. (expressions), GF.. (functions), GA.. (additional behaviour), GB.. (lexical), GL.. (literals), GH.. (other). This page cites only those identifiers and short descriptive names of our own; it does not reproduce the standard. An identifier marked (provisional) could not be checked against the standard text yet and may be corrected.

How far the Cypher compatibility forms agree with Neo4j's behaviour is measured against the openCypher TCK: TCK Compliance.

Status: supported, partial (what is missing is named), not yet (planned), no (refused for good; see Refused Constructs).

Core language

The mandatory core of a GQL query, by construct.

ConstructStatusNotes
MATCH with node and edge patterns, comma-separated patterns, several MATCH clausessupportedtrail (DIFFERENT EDGES) match mode per clause
WHERE after MATCH, inline WHERE and property maps in element patternssupported
RETURN, RETURN *, RETURN DISTINCT, ASsupportedRETURN is mandatory unless the last clause writes; FINISH ends a query without a result
ORDER BY ... ASC / DESCsupportedNULL last ascending, first descending
label expressions &, |, !, ( )supported
property reference x.keysupported
comparison, AND / OR / NOT, IS [NOT] NULLsupportedthree-valued logic
arithmetic + - * / %, string concatenation ||supported
simple and searched CASE, COALESCE, NULLIFsupported
UPPER, LOWER, CHAR_LENGTH / CHARACTER_LENGTH, LEFT, RIGHT, TRIM(s)supportedTRIM removes spaces by default; NORMALIZE not yet
BYTE_LENGTH / OCTET_LENGTH of a character stringsupportedthe number of UTF-8 bytes; Graphersal has no byte strings
list trim TRIM(list, n)supporteddrops the last n items
parameters $namesupportedvalues only, never text
aggregate functions COUNT, SUM, AVG, MIN, MAX, COLLECT_LIST, with DISTINCTsupportedimplicit grouping by the items without an aggregate; Cypher collect alias
binary set functions PERCENTILE_CONT, PERCENTILE_DISCsupportedvalue first, then the percentile (0.0 to 1.0, 22003 outside); Cypher percentileCont / percentileDisc aliases (stage 3f)
OPTIONAL MATCHsupportedalso as the first clause
EXISTS predicate: EXISTS { MATCH ... }, EXISTS { <pattern> }, EXISTS ( ... ) (provisional: whether the standard makes it core or an optional feature, and its identifier, are still to be checked)supportedanywhere an expression stands, nested too; TRUE or FALSE, never NULL; the body is a pattern, MATCH clauses, or a whole query ending in RETURN (EXISTS); Cypher pattern predicates as aliases
Cypher WITHsupportednot GQL; accepted with Cypher's meaning (Cypher Aliases)
record constructor {k: expr, ...} / RECORD {k: expr, ...} and list value constructor [a, b]supportedRECORD is contextual: a variable named record stays usable, back-quoted before a projection that starts with key: or is empty (Expressions)
Cypher map projections p {.k, .*, x, k: expr}, list comprehensions [x IN l WHERE c | e], pattern comprehensions [(a)-->(b) WHERE c | e]supportednot GQL; accepted as compatibility forms with Cypher's meaning (Cypher Aliases); a pattern comprehension is a subquery; all() / any() / none() / single() / reduce() likewise, three-valued as the openCypher TCK (Cypher Aliases)
Cypher COUNT { } and COLLECT { } subqueriessupportednot GQL; compatibility forms with Cypher's meaning (Cypher Aliases); bodies as for EXISTS, COLLECT returns one item; one deviation below
a query without MATCH (RETURN 1)supporteda query may start with FOR, LET, WITH, FILTER or RETURN; it starts from one empty row
data-modifying statements: INSERTsupportednodes with label conjunctions and properties, directed edges with one label, once per row; Cypher CREATE as an alias (Writing with GQL)
data-modifying statements: SET, REMOVEsupportedproperty items n.k = v, all properties n = {..}, label items n:A / n IS A; once per row, items left to right, NULL removes; Cypher's += and SET n = <expression> as compatibility forms (Writing with GQL)
data-modifying statements: DELETEsupportedDETACH DELETE and [NODETACH] DELETE of nodes, edges, paths and lists of them, once per row; NODETACH checked per clause (G1001); reading a deleted element afterwards is an error (Writing with GQL, Semantics)
Cypher MERGE with ON CREATE SET / ON MATCH SETsupportednot GQL; a compatibility form with Cypher's meaning (Cypher Aliases): one pattern, per row every match a row or the whole pattern created, rows see earlier rows' creations, NULL in the pattern 22004 (Writing with GQL, Semantics)
catalog statements (CREATE GRAPH, CREATE GRAPH TYPE, ...), session and transaction commandsnothe host application manages graphs, schemas and transactions
value typespartialthe GQL types Graphersal has (integers, floats, strings, booleans, lists, records/maps, dates and times, NULL); path values; no byte strings

Optional features

IDFeatureStatusNotes
G002different-edges match modepartialthe semantics is the default and only mode; writing DIFFERENT EDGES is not accepted yet
G004path variablessupportedp = (a)-->(b), path_length(p) (Cypher length); Cypher's nodes(p) / relationships(p) as compatibility functions
G005path search prefix in a path patternnot yetANY, ALL, SHORTEST prefixes
G010explicit WALK keywordnot yet
G011advanced path modes: TRAILnot yettrail is the semantics of every MATCH; the keyword is not accepted yet
G012advanced path modes: SIMPLEnot yet
G013advanced path modes: ACYCLICnot yet
G016any path searchnot yet
G017all shortest path searchnot yetGremlin repeat()
G018any shortest path searchnot yetGremlin repeat()
G019counted shortest path searchnot yet
G035quantified paths (provisional)partiala parenthesized path pattern with {m,n}, {n}, {m,}, {,n}, *, + (Quantified path patterns); body variables are group variables (lists), the outer nodes merge with the body's first and last node, trail per body edge; one chain per body, no quantifier, path variable, path mode or search prefix inside a body, a body variable is a new name (each refused with 0A000)
G036quantified edgessupported{m,n}, {n}, {m,}, {,n}, *, + on full and abbreviated edges; Cypher [*m..n] and its forms are aliases; trail per clause
G037questioned paths (provisional)supported((..))?: the body once or not at all; its variables are single elements, NULL when it did not match (Semantics)
G043complete full edge patternspartialpointing left, right, either direction (-[e]-, <-[e]->); the undirected forms (~[e]~ and its variants) are refused, Graphersal edges are directed
G044basic abbreviated edge patternssupported->, <-, - (Cypher -->, <--, --)
G045complete abbreviated edge patternspartial<-> supported; ~, <~, ~> refused
G050parenthesized path pattern: WHERE clause (provisional)partial((x)-[e]->(y) WHERE <condition>) with or without a quantifier, run in every iteration; it reads the body's variables, parameters and values (a condition reading an outer variable is not yet supported); a parenthesized path pattern without a quantifier matches once and keeps singletons
G074label expression: wildcard labelsupported%
G100ELEMENT_ID functionsupportedthe id as a string; Cypher elementId alias
G110IS DIRECTED predicate (provisional)not yetevery edge is directed
G111IS LABELED predicatesupportedCypher x:A alias
G112IS SOURCE OF / IS DESTINATION OF predicates (provisional)supportedn IS [NOT] SOURCE OF e, n IS [NOT] DESTINATION OF e: the stored direction of the edge; Cypher's startNode(e) / endNode(e) as compatibility functions
G113ALL_DIFFERENT predicate (provisional)not yet
G114SAME predicate (provisional)not yet
G115PROPERTY_EXISTS predicate (provisional)not yetx.key IS NOT NULL tests a property
GA03explicit ordering of nullsnot yetNULLS FIRST / NULLS LAST
GA04universal comparison (provisional)partial= / <> between values of different kinds are FALSE / TRUE, the orderings NULL (Neo4j's reading, see Differences from the standard); there is no total order across kinds outside ORDER BY
GA05cast specificationpartialCAST(x AS INTEGER | FLOAT | STRING | BOOLEAN) and their synonyms (INT, BIGINT, DOUBLE, VARCHAR, BOOL, ...); the other target types (DATE, LIST<..>, DECIMAL, ...) not yet; strict: unconvertible text is 22018
GA07ordering by discarded binding variables (provisional)supportedORDER BY may read variables that RETURN does not return (not after RETURN DISTINCT)
GB02double minus sign commentssupported-- ..., with the edge rule of Writing GQL in Rhai Strings
GB03double solidus commentssupported// ...
GD01updatable graphs (provisional)partialINSERT (Cypher CREATE), SET, REMOVE, DELETE; Cypher's MERGE (no ISO counterpart) as a compatibility form (Writing with GQL); the Cypher forms pass every in-scope case of the openCypher TCK's write clauses (TCK Compliance)
GD02graph label set changes (provisional)supportedSET n:A / SET n IS A and REMOVE n:A add and remove node labels; an edge's single label is not changed by them (Writing with GQL)
GD03DELETE statement: subquery support (provisional)supporteda DELETE item may hold a subquery, as in DETACH DELETE COLLECT { MATCH (s)<-[e]-() RETURN e }; a CALL { } body may end with a DELETE (Writing with GQL)
GD04DELETE statement: simple expression support (provisional)supporteda DELETE item is an expression: a variable, a path, a list (collect(n)), a map member, a function result; NULL is skipped, another value is 42002 / 22G03 (Semantics)
GE07Boolean XORsupported
GF01enhanced numeric functionssupportedABS, FLOOR, CEIL / CEILING, SQRT, MOD; an integer argument keeps its type
GF02trigonometric functions (provisional)not yetGremlin math() after gql()
GF03logarithmic functionssupportedEXP, LN, LOG10, LOG(base, x) (provisional), POWER; an argument outside the domain is an error (2201E, 2201F), never NaN
GF04enhanced path functionspartialPATH_LENGTH; ELEMENTS(p) (provisional) not yet (Cypher's nodes(p) / relationships(p) instead)
GF05multi-character trim functionssupportedBTRIM, LTRIM, RTRIM with an optional set of characters (default: the space)
GF06explicit TRIM functionsupportedTRIM([LEADING | TRAILING | BOTH] [c] FROM s); c is one character (22027 otherwise), the space by default
GF12CARDINALITY functionsupported
GF13SIZE functionsupportedalso on strings as the Cypher alias of CHAR_LENGTH
GH02undirected edge patternsnoGraphersal edges are directed; -[e]- matches either direction
GL01hexadecimal literalssupported0x1F
GL02octal literalssupported0o17
GL03binary literalssupported0b101
GQ01USE graph clausenogql() runs on the graph of its traversal source
GQ02composite query: OTHERWISE (provisional)not yet
GQ03composite query: UNIONsupportedUNION, UNION DISTINCT, UNION ALL; operands return the same column names in any order; one kind per chain; ORDER BY / OFFSET / LIMIT per operand (UNION and NEXT)
GQ04composite query: EXCEPT DISTINCT (provisional)not yet
GQ06composite query: INTERSECT DISTINCT (provisional)not yet
GQ08FILTER statementsupportedFILTER [WHERE] <condition>
GQ09LET statementsupported
GQ10FOR statement: list value supportsupportedFOR x IN <list> (Cypher UNWIND <list> AS x), also as the first clause; a NULL list gives no row, a value that is not a list one row (Semantics)
GQ11FOR statement: WITH ORDINALITY (provisional)supportedthe position from 1
GQ24FOR statement: WITH OFFSET (provisional)supportedthe position from 0
GQ12ORDER BY and page statement: OFFSET clausepartialOFFSET / SKIP after RETURN and in WITH; the standalone statement form not yet
GQ13ORDER BY and page statement: LIMIT clausepartialLIMIT after RETURN and in WITH; the standalone statement form not yet
GQ14complex expressions in sort keys (provisional)supportedORDER BY element_id(e), ORDER BY n.age * 2
GQ15GROUP BY clause (provisional)supportedafter the RETURN items, GROUP BY () included; the keys must be the items without an aggregate (grouping is implicit, so it is optional); a key may also repeat an item's expression (GROUP BY p.name), beyond ISO's variable references
GQ18scalar subqueries (provisional)not yet
GQ20advanced linear composition with NEXTpartialRETURN .. NEXT .., also after a UNION and inside subquery bodies; NEXT YIELD not yet
GQ21OPTIONAL: multiple MATCH statements (provisional)not yetone OPTIONAL MATCH per optional part is supported; the block form OPTIONAL { MATCH ... MATCH ... } is not
GP01inline procedure (provisional)supported[OPTIONAL] CALL { <query> }, run once per incoming row, the body ending in RETURN (CALL subqueries) or, as a unit subquery, in a write (Writing with GQL); IN TRANSACTIONS refused
GP02inline procedure with implicit nested variable scope (provisional)partialCALL { } without a scope clause is accepted but imports nothing (Neo4j Cypher 25's reading; the ISO scoping is still to be checked); import with CALL (*) or Cypher's importing WITH
GP03inline procedure with explicit nested variable scope (provisional)supportedCALL (a, b) { }, CALL (*) { }, CALL () { }
GP04named procedure calls (provisional)partial[OPTIONAL] CALL folder.name(args) [YIELD ..] calls a saved query written in GQL of the graph's catalog, once per row, standalone or inside a query (Calling saved queries); arguments are constants or parameters; a saved query in Rhai and a call inside EXISTS / COUNT / COLLECT not yet; vendor procedures (CALL db.*, dbms.*, apoc.*, gds.*) are refused
GV39temporal types: date, local datetime and local time (provisional)partialdate(), local_time(), local_datetime() (Cypher localtime(), localdatetime()) from ISO 8601 text, a map of fields or another temporal value, components (d.year), arithmetic with durations, comparison (Dates and times); values hold nanoseconds; the literals DATE '..', TIME '..' / LOCAL TIME '..', TIMESTAMP '..' / LOCAL DATETIME '..' and the clocks CURRENT_DATE, LOCAL_TIME, LOCAL_TIMESTAMP (Literals); CAST(x AS DATE) not yet
GV40temporal types: zoned datetime and zoned time (provisional)partialzoned_datetime() (Cypher datetime()) keeps a UTC offset and the zone name it was built with, its arithmetic following the zone; zoned_time() (Cypher time()) keeps a time of day and its offset (Dates and times); the literals TIME '10:00+01:00', DATETIME '..+01:00' (also ZONED TIME '..', ZONED DATETIME '..') and the clocks CURRENT_TIME, CURRENT_TIMESTAMP (Literals); CAST(x AS ZONED TIME) not yet
GV41temporal types: duration (provisional)partialduration() from text or a map, the literal DURATION '..', + / - / * / /, components; ISO DURATION_BETWEEN not yet (the Cypher compatibility function duration.between() instead); < on two durations is NULL

Every feature not listed here is not supported. Cypher spellings that GQL does not have, and the openCypher functions accepted without a GQL counterpart (toInteger, substring, split, round, keys, nodes, the temporal date.truncate(), duration.between(), ...), are on Cypher Aliases.

Implementation-defined choices

Where the standard leaves a choice to the implementation, gql() makes this one (Neo4j's, where it has one):

TopicChoice
NULL in ORDER BYlast ascending, first descending
order of values of different typesmap, vertex, edge, list, date/time, UUID, string, boolean, number, vector, NULL
row order without ORDER BYunspecified
item order of a pattern comprehensionunspecified: the order the matches are found, which depends on the plan
item order of COLLECT { }the order of the body's rows: its ORDER BY when it has one, unspecified otherwise
UNION operands with the same column names in another orderaccepted, matched by name; the result has the first operand's column order (provisional)
order of the rows of a UNIONunspecified, also when the operands are sorted: sort after NEXT
a CALL body that imports nothingstill run once per incoming row; its rows are not cached
the RETURN items of a projecting COUNT { } bodynot evaluated: the rows are counted, an expression that would fail raises no error (a deviation, Semantics)
a comprehension variable named like another variable of the queryan error (42002) for a name in scope or one a LET / WITH value in scope still reads (stricter than Neo4j only there); a name no longer in scope may be used again (Semantics)
DISTINCT, grouping keys, DISTINCT in aggregatesGQL equality: 1 and 1.0 are one value, NULLs form one group
aggregates of no rows (no grouping keys)one row: count 0, sum 0, collect_list [], avg / min / max NULL (Neo4j's values, which the openCypher TCK confirms; the ISO text is still to be checked)
min / max over values of different kindsthe ORDER BY order, never an error
sum of integersan integer; overflow is an error (22003)
unbounded quantifiersno own limit: trail ends them; repeat.max_loops and traversal.max_traversers are errors, never a shortened result (quantified edges and quantified path patterns alike)
outer nodes next to a quantified path patternmerged with the body's first node of the first iteration and last node of the last iteration (Neo4j Cypher 25's reading)
order of a group variable's listthe iterations in the order the text reads, also when the plan walks the pattern from its far end
WITH ... LIMIT ... WHEREthe WHERE filters after ORDER BY / OFFSET / LIMIT (Cypher's order; provisional)
name of an unaliased columnthe expression as written (Neo4j's names, such as count(*), which the openCypher TCK confirms; the ISO text is still to be checked)
element idsstrings, the same as Gremlin's id(); vertex and edge ids are separate spaces
integer divisiontruncates toward zero; % takes the sign of the dividend
temporal precisionnanoseconds
default time zoneUTC: a datetime without an offset or zone, and the clocks without a zone
the current date and timeone instant per query, taken when it starts; X.realtime() is refused
ORDER BY of durationsby length, a month counted as 30 days (< on two durations is NULL)
CAST(temporal AS STRING)the engine's ISO 8601 text ('12:00:00'); Cypher's toString() writes Neo4j's ('12:00')
integer overflowan error (22003), never a wrap
text and numbersno implicit conversion: 'a' + 1 is an error (22G03); convert with CAST(x AS STRING)
CAST of a float to INTEGER, of text with surrounding spacestruncated toward zero; the spaces are skipped (provisional)
CAST to STRING of a float, a boolean, a list or a mapJava's float text ('1.0', '1.0E7'), 'true' / 'false', Neo4j's list and map text (provisional)
CAST(x AS BOOLEAN) of a number; of 'unknown'22G03; NULL (provisional)
default character of TRIM, BTRIM, LTRIM, RTRIMthe space U+0020 only (provisional)
BTRIM / LTRIM / RTRIM with charactersany character of the set is removed (Neo4j's semantics; provisional)
functions and NULLa NULL argument gives NULL, before the kinds are checked
strings in functionspositions and lengths count characters (Unicode scalar values)
GQLSTATUS codes42001 for syntax errors; the others provisional (Errors)
order of the writes of one INSERTper row: its nodes in text order, then its edges in text order
property values of INSERTNULL is not stored; maps and lists of any kinds are stored as given (a difference from Neo4j)

Differences from the standard

Where ISO GQL and Neo4j disagree and the openCypher TCK measures the Neo4j behaviour, gql() follows Neo4j in these places (user decision, stage 3f):

TopicISO GQLgql()
= / <> / IN / simple CASE between values of different kindsnot comparable= FALSE, <> TRUE (1 = '1', [1] = 1, 1 IN ['1']); the orderings < .. >= stay NULL (Semantics)
< <= > >= on two listsnot comparablelexicographic, three-valued
a float divided by zero22012IEEE 754: Infinity, -Infinity or NaN; an integer divided by zero stays 22012
NaN in a comparison(no NaN arises: every division by zero is 22012)never equal (NaN = NaN FALSE), every ordering against a number FALSE

The deliberate differences from Neo4j are listed on Semantics.

TCK Compliance

Graphersal's GQL is measured against the openCypher TCK (Technology Compatibility Kit): Gherkin scenarios that each set up a graph, run one query and state the exact expected result, side effects or error. They exercise the Cypher compatibility forms that gql() accepts (CREATE, MATCH ... RETURN, WITH, UNWIND, ...) with Neo4j's semantics, so the kit works as a ready-made differential test. It serves three purposes:

  1. Compliance measure: what passes, what does not, and why.
  2. Regression gate: a test case that passed must keep passing; cargo test fails otherwise.
  3. Backlog generator: the report ranks the missing constructs and lists every wrong behaviour.

Graphersal's GQL is not a Cypher implementation; the TCK measures how far its compatibility forms agree with the behaviour the kit specifies.

The kit

  • Pinned version: openCypher TCK release 2024.3 (commit 677cbafabb8c3c5eed458fd3b1ec0daec8d67d23), vendored unmodified under crates/graphersal/tests/opencypher/ (features/, the named graphs in graphs/, its licence and notice). The directory's README.md records the upgrade procedure. A test case is a scenario, or one Examples row of a scenario outline.
  • Runner: the integration test target crates/graphersal/tests/opencypher_tck.rs (feature gql), with its harness in crates/graphersal/tests/opencypher/harness/. Every case runs on a fresh graph through the Rust GQL API: the setup queries (having executed, the named graphs) run through gql()'s own writes, the query runs with its parameters, then its rows, its side effects (a state diff) and its error are compared. Every query runs under resource limits and a wall-clock guard.
  • Gate: crates/graphersal/tests/opencypher/baseline.toml lists every in-scope case that does not pass yet, with its class and a one-line reason.

Headline numbers

The numbers below are the kit's result on the current code. All totals and percentages count in-scope cases only (see Out of scope). The text between the opencypher:begin / opencypher:end markers on this page is generated by the run and checked by every test run (see Running and regenerating); never edit it by hand.

3887 in-scope test cases; 10 excluded (upstream-ignore 1, w21-property-kinds 1, parameter-at-compile-time 6, year-range 2).

Test casesShare
Passed3810 / 388798.0 %
Unsupported (not yet or refused)77 / 38872.0 %
Wrong behaviour of supported constructs0 / 38870.0 %
Passed without expressions/temporal2813 / 288597.5 %

Unsupported = missing 74, setup 3. Wrong behaviour = wrong_result 0, wrong_columns 0, wrong_side_effects 0, wrong_error 0, unexpected_error 0, timeout 0, panic 0.

The date and time functions (date(), datetime(), duration(), datetime.truncate(), ...) are supported with the differences listed on Semantics (zoned time() not yet), and expressions/temporal is about a quarter of the kit and its least covered part, so the headline also shows the share without it. The write clauses (CREATE, SET, REMOVE, DELETE, MERGE) pass, and so do the procedure calls of clauses/call: the kit declares each procedure it calls with its signature and a table of rows, and the harness saves it as a saved GQL query before the case runs (test.my.proc is the query proc of the folder test/my, its parameters typed from the signature, its body returning the table's rows that match the arguments), which the query then calls with CALL test.my.proc(..) (Calling saved queries). rand() is refused by design (Refused Constructs). The ranking with counts is in the report.

Per sub-directory of the kit:

DirectoryPass %PassedTotalUnsupportedWrong
clauses/call100.0 %5252··
clauses/create100.0 %7878··
clauses/delete100.0 %4141··
clauses/match99.2 %3783813·
clauses/match-where100.0 %3434··
clauses/merge100.0 %7575··
clauses/remove100.0 %3333··
clauses/return98.4 %62631·
clauses/return-orderby100.0 %3535··
clauses/return-skip-limit96.0 %24251·
clauses/set100.0 %5252··
clauses/union100.0 %1212··
clauses/unwind100.0 %1414··
clauses/with96.6 %28291·
clauses/with-orderBy100.0 %292292··
clauses/with-skip-limit77.8 %792·
clauses/with-where100.0 %1919··
expressions/aggregation100.0 %3535··
expressions/boolean100.0 %150150··
expressions/comparison100.0 %7272··
expressions/conditional100.0 %1313··
expressions/existentialSubqueries100.0 %1010··
expressions/graph100.0 %6060··
expressions/list100.0 %185185··
expressions/literals100.0 %131131··
expressions/map100.0 %4444··
expressions/mathematical100.0 %66··
expressions/null100.0 %4444··
expressions/path100.0 %77··
expressions/pattern98.0 %49501·
expressions/precedence100.0 %121121··
expressions/quantifier89.6 %54160463·
expressions/string100.0 %3232··
expressions/temporal99.5 %99710025·
expressions/typeConversion100.0 %4747··
useCases/countingSubgraphMatches100.0 %1111··
useCases/triadicSelection100.0 %1919··
all98.0 %3810388777·

Out of scope

Some cases are excluded from the scope: they are not run, get the class excluded, have no baseline entry and are in no total or percentage. They are listed by case id, grouped by reason, in crates/graphersal/tests/opencypher/harness/scope.rs (ids, never tags or content, so a case that a kit upgrade adds is never excluded silently). Merely unimplemented constructs are never excluded: they stay missing, the backlog.

CodeWhyDocsTest cases
upstream-ignoremarked @ignore by the TCK itself ("does not work in Cypher")gql/tck_compliance.md#out-of-scope1
w21-property-kindsa list of maps is a valid property value (maps and lists of any kinds are stored as given); Neo4j raises a TypeError (deliberate deviation)gql/semantics.md#writes1
parameter-at-compile-timeparameters are bound when the query is compiled: a negative or non-integer SKIP / LIMIT parameter is refused then (22G02 / 22G03), not at runtime (deliberate deviation)gql/semantics.md#parameters-are-bound-when-the-query-is-compiled6
year-rangetemporal values hold the years -9999 to 9999; a year beyond them is a data error (22008), Neo4j reads years up to 999999999 (deliberate deviation)gql/semantics.md#where-dates-and-times-differ-from-neo4j2
all10
  • upstream-ignore: the one scenario that the kit itself marks @ignore.
  • w21-property-kinds (a deliberate deviation, user decision): a list of maps is a valid property value in Graphersal, where Neo4j raises a TypeError (Semantics).
  • parameter-at-compile-time (a deliberate deviation, user decision): a negative or non-integer $parameter of SKIP / LIMIT is refused when the query is compiled, since parameters are bound then; the kit expects the SyntaxError at runtime. The user sees the same thing, an error before any row (Semantics).

Every difference from Neo4j, also those the kit has no case for, is listed on Semantics.

The deliberate deviations run in a guard test (deviation_cases_still_deviate): it fails when one of them passes, so it moves back into scope. id() (an integer in Neo4j, a string id here) does not occur in the pinned kit.

Classes

ClassMeaning
passevery expectation holds: rows (and their order where stated), column names, side effects, the error type and phase
missingthe query uses a construct that gql() refuses or does not support yet (GQLSTATUS 0A000); the report ranks the constructs
setupa setup step (having executed, a named graph, a parameter value) does not run, usually for the same reason
excludedout of the scope (above): not run, in no total
wrong_resultthe rows differ
wrong_columnsthe column names differ
wrong_side_effectsthe side effects differ, or a failed query changed the graph
wrong_erroran error was expected and another one (type or phase), or none, came
unexpected_erroran error where a result was expected
timeouta time or resource budget of the harness fired
panica panic was caught (a rule-1 violation, top priority)

The headline groups them: Unsupported = missing + setup; Wrong behaviour of supported constructs = the seven classes from wrong_result to panic. An unimplemented construct is fine; a supported construct must behave as the kit specifies, unless a user decision says otherwise (then the case is excluded with its reason and documented as a difference from Neo4j). The wrong-behaviour count is driven to 0.

Errors match by type and phase only, never by the detail text. The phase comes from where the error arose: compile time is an error of parsing, binding or planning, before the traversal runs; runtime is an error while it runs.

Running and regenerating

# Run the kit (also part of the plain `cargo test --package graphersal --features script,io,display,serde,persist,gql`)
cargo test --package graphersal --features script,io,display,serde,persist,gql --test opencypher_tck

# Rewrite the baseline AND the generated blocks of this page after intended changes; review the diff like code
OPENCYPHER_UPDATE_BASELINE=1 cargo test --package graphersal --features script,io,display,serde,persist,gql --test opencypher_tck

Every run prints a summary to stderr and writes the full report to target/opencypher-report.md: the headline, the per-directory table, the exclusions with their ids, the full wrong-behaviour list by class, the missing constructs ranked by the number of cases they block, the setup failures by reason and the baseline class changes. OPENCYPHER_DETAILS=1 prints one line per in-scope case that does not pass; OPENCYPHER_LANES=<n> sets the number of parallel lanes (default: one per core).

The test fails when:

  • a case that is not in the baseline does not pass (a regression);
  • a case in the baseline passes now, no longer exists or is excluded (the entry is stale; remove it in the same change);
  • an id of the scope table does not exist, an @ignore case is not in it, or a deliberate deviation passes now (scope_table_is_consistent, deviation_cases_still_deviate);
  • a generated block of this page (scope, headline, directories, excluded) differs from what the run computes. Only trailing whitespace is ignored.

A case still failing under another class than recorded is reported, not failed. GRAPHERSAL_TEST_STORAGE=forwarding runs the whole kit on a storage that is not TraversalGraph (the Forwarding wrapper of graphersal-storage-tests): the same gate against the same baseline and page, it additionally fails when a case changes class, never rewrites either and writes target/opencypher-report-forwarding.md.

Writing Queries

This part describes the Gremlin DSL in detail, topic by topic. The DSL is the text form of a query: what the command line, the playground, Python, saved queries and AI agents run, and what script::eval_value evaluates in Rust. It is Gremlin embedded in Rhai.

The shape of a script

A script is a sequence of Rhai statements. g is the graph, __ starts an anonymous traversal, and the token classes (P, T, Order, Scope, Column, Pop, ...) are predefined:

let min_age = 30;
let names = g.v().has_label("person").has("age", P.gt(min_age)).values("name").to_list();
names.len()                                        // 2
  • Terminals run a traversal. to_list(), next() and iterate() run it and return native values; a traversal that is the last value of a script is displayed instead. A traversal in the middle of a script without a terminal is only built, not run.
  • Two spellings for TinkerPop's steps. Every TinkerPop step and function is available in snake_case (has_label, out_e) and in Gremlin camelCase (hasLabel, outE), with the same overloads. Graphersal's own extensions (create_index, memory_report, remove_property, glob_path, define_query, the Fake methods, ...) are snake_case only (since 0.3.0); a camelCase call of one fails with a help that names the snake_case name.
  • Strings in double quotes. Single quotes are Rhai character literals; maps are written #{key: value}.
  • Anonymous traversals start with __.: where(__.out("knows")), repeat(__.both()).
  • Every traversal is atomic. A failing traversal leaves nothing it wrote (Transactions).

An error names the failing step with its position in the plan, and most errors come with a help text that suggests a fix built from the failing query.

Topics

PageWhat it covers
Displaying Resultshow results are shown, the row and item limits
PredicatesP.* and TextP.*, comparison and resolution rules
Id Argumentswhat v(), e() and has_id() accept
Type Conversionas_string(), as_bool(), as_number(), length()
Math Expressionsthe math() step
Map Keys and Values, Non-String Keysmaps in the stream
Local Scopesteps applied inside a collection
Path Keys (jpath)reading and writing nested values
UUID Values, Multi-Label Vertices, Property Elementsvalues and elements beyond strings and numbers

The following chapters cover traversal patterns, changing the graph, schemas, saved queries and profiling; every single step is in the Step Reference.

Displaying Results

A traversal's result is either data or display:

  • Data is what to_list(), next(), a script variable, and the Rust data API return. It is never cut: let xs = g.v().to_list(); xs.len() counts every vertex. iterate() runs a traversal for its side effects (g.add_v("x").property("a", 1).iterate()) and returns nothing: its results are discarded, never materialized, so nothing is shown.
  • Display is every rendering of results into text: a traversal left without a terminal (the session visualizer), a list or map that is a script's final value, and the explicit visualizers to_table(), to_markdown(), to_json(), to_tree(), to_mermaid(), to_plantuml(), to_json_schema() and visualize(fmt).

Display can be bounded by two limits:

LimitWhat it bounds
max_rowstop-level results: table rows, traversers, list items
max_itemsitems of every nested collection inside a row, at any depth (a fold() list, the keys of one group() row)

Where the limits come from

  • The library is unbounded by default. A Rust caller of visualize_with and a script engine built without render options get everything.
  • Front ends set a session default. graphersal and the web playground show at most 100 rows and 100 nested items, for every kind of display, including an explicit to_table(): the DSL cannot write a string to a file, so in a front end such a call is for viewing.
  • A single call overrides the session default with an options map.

Per-call options (DSL)

g.v().to_table(#{max_rows: 20})             // other limits for this call
g.v().to_json(#{max_items: 5})
g.v().visualize(V.Markdown, #{no_limit: true})  // no limit at all for this call
g.with("render.max_rows", 10).v()           // session default for one query

max_rows: 0 / max_items: 0 is an error: no_limit: true is the one way to say "unlimited". no_limit: true together with max_rows or max_items is an error too. no_limit: false keeps the session default. Both spellings work: max_rows/maxRows, max_items/maxItems, no_limit/noLimit.

Session default (embedding the DSL)

A host passes its limits as scope options, and can change them later (a REPL /set):

use std::sync::Arc;
use graphersal::prelude::*;
use graphersal::auth::AllowAll;
use graphersal::exec::RenderOptions;
use graphersal::script::{graph_scope_with_options, render_scope_options, set_scope_render_options};

let limits = RenderOptions::new().with_max_rows(100).with_max_items(100);
let graph = Arc::new(GraphSource::tinkerpop_modern());
let mut scope =
    graph_scope_with_options(graph, &render_scope_options(&limits), Arc::new(AllowAll));
// ... later: remove the limits for the rest of the session.
set_scope_render_options(&mut scope, &RenderOptions::unlimited());

render_value / try_render_value take the host's RenderOptions for final lists and maps and return a RenderedOutput.

Rust API

use graphersal::prelude::*;
use graphersal::exec::RenderOptions;

let graph = TraversalGraph::tinkerpop_modern();
let rendered = graph
    .traversal()
    .v(None::<()>)
    .visualize_with(VisualizeFormat::Table, &RenderOptions::new().with_max_rows(2))
    .unwrap();
println!("{}", rendered.text);
if let Some(notice) = rendered.notice() {
    eprintln!("{notice}");
}

visualize(fmt), to_table(), to_json(), ... are always unbounded and return a String; visualize_with, to_table_with and to_markdown_with take RenderOptions and return a RenderedOutput. RenderOptions::unlimited() / .with_no_limit() remove both limits.

How a cut is shown

The truncation is never part of the result text. RenderedOutput::truncation reports it (rows_shown, more_rows, items_cut, max_items; there is no total count, because counting would cost a full execution), and Truncation::notice() builds the one notice text every front end prints:

… showing the first 100 rows; more exist. Use .limit(n), #{no_limit: true}, /set no-limit (--no-limit), or to_list() for the data.
… nested collections were cut to 100 items. Use #{max_items: n}, /set max-items <n> (--max-items <n>), or /set no-limit (--no-limit).
  • Tables, markdown and trees mark a nested cut inside the cell with …, for example [1, 2, 3, …], or with a └─ … line in a tree. A row with more keys than max_items shows max_items columns and a … column.
  • Maps with typed keys in JSON: a map with a non-string key (groupCount().by("age")) is written in the GraphSON shape {"@type": "g:Map", "@value": [29, 1, 27, 1]}; a string-keyed map is a plain object. Tables and trees print such keys as text (29, v[1]); see Maps With Non-String Keys.
  • Non-finite floats in JSON: JSON has no number for NaN, Infinity or -Infinity, so a result holding one (math("0 / 0"), 0.0 / 0.0, a stored NaN property) writes it in GraphSON's typed form, {"@type": "g:Double", "@value": "NaN"} (payloads "NaN", "Infinity", "-Infinity"), at any depth, the same form a GraphSON export writes. The tag keeps it apart from the string "NaN", which stays a plain string. This holds for to_json(), --format json, execute().to_json(), the playground's and the dev server's answers and the MCP query tool; tables and trees print the number itself (NaN, inf, -inf), and the playground shows NaN, Infinity, -Infinity in its Table view and inspector. The tag is written, not read: plain JSON read back (serde of a value, GraphML's embedded JSON) does not turn it into a float; GraphSON import does. The serde Serialize of a value itself stays strict and refuses a non-finite float, and GraphML export refuses one (with a help naming the fix).
  • JSON stays valid JSON: an array of the first max_rows results, with nested collections cut and no marker inside, since a sentinel element would break the data's types. The only signal is the notice. The JSON-per-line fallback formats (jsonschema, mermaid, plantuml on traversal results) follow the same rules.
  • A schema (g.get_schema(), g.infer_schema()) and a profile() result are never bounded.

Graph values

A graph as a script's final value (g.e(0).to_graph(), g.e().subgraph("sg").cap("sg").next(), GraphSource::empty(), g itself) is shown as one result {"vertices": [..], "edges": [..]}, each element materialized like a g.v()/g.e() result: exactly what cap("sg") shows for a graph inside a traversal. A table prints the elements in their short form ([v[1], v[2]]), JSON with all their properties:

graphersal> g.e(0).to_graph()
╭────────────────────┬──────────────╮
│ edges              │ vertices     │
├────────────────────┼──────────────┤
│ [e[0][1-knows->2]] │ [v[1], v[2]] │
╰────────────────────┴──────────────╯

max_items bounds both lists, and only max_items + 1 vertices and edges are read, so even g on a large graph shows its first elements and the cut notice instead of materializing everything. This is display only: next() and to_graph() still return the graph itself, a source you traverse (sub.v().count().next()). The web playground shows the same result (and draws it in the Graph panel).

A single list-valued result

A traversal that yields ONE list-valued traverser (g.v().values("age").fold(), cap("a") of an aggregate("a")) is a list of one element in every terminal: to_list().len() is 1 and to_json() is [[29, 27, 32, 35]]. Nothing is unwrapped. The only difference you may see is in the graphersal printer: it prints a returned script array one element per line, so the list of one list prints as [29, 27, 32, 35] (the single element), while the flat list [29, 27, 32, 35] prints as four lines. Use to_json() or .len() to tell them apart.

Tokens and anonymous traversals

A DSL token shows as the DSL text that builds it, wherever a script prints it: as the final value (also inside a list or map), through to_string() and in string interpolation ${..}. The text is the canonical dotted spelling, and evaluating it gives the same token back:

ScriptShows
Scope::localScope.local
Order::DescOrder.desc
keys, firstColumn.keys, Pop.first
T.id, By.CountT.id, By.Count
GType.INTGType.LONG (the same type)
Operator.sum, Barrier.normSackOperator.sum, Barrier.normSack
P.gt(1).and(P.lt(3))P.gt(1).and(P.lt(3))
TextP.containing("a")TextP.containing("a")
Cardinality.single(5), CastPolicy.Default("x")the same text
__.out().has("name", "x")__.out().has("name", "x")
Scope, P (a class itself)Scope, P

An anonymous traversal (__...) is a template for a child position, not a query of your graph, so a script that returns one shows its text instead of running it; the steps read like .profile() names them. The session's step-name spelling (--spelling camel, render.spelling) applies to a displayed result (__.outE(), TextP.startingWith("a")); to_string() and ${..} always give the canonical snake_case text. A UUID is a value, not a token: it shows its canonical text.

Early stop

With max_rows = n, the visualizer appends an internal limit(n + 1) to the pipeline before it is optimized and executed, so only n + 1 results are produced and materialized. The extra one only tells whether more exist. Barriers before it (group(), order(), ...) still see the whole stream. In the executed plan it is the step limit(n + 1) [display].

An error location never shows it: the at #N: line with its caret, the plan: line, step_location() and the query a help text rewrites show the traversal as you wrote it, so g.inject(1).math("value + 1") fails with

Error: Step #1 'math("value + 1")' execution failed
  at #1: inject(1).math("value + 1")
                   ^^^^^^^^^^^^^^^^^

and not with a .limit(101) [display] you never wrote. The display step is appended last, so leaving it out changes no step number. It is shown only when the failure is that step itself.

No limit is appended, and the traversal runs completely with only the output cut, when the pipeline mutates the graph (so g.v().property("x", 1) still updates every vertex) or already ends on a single-result step such as count(), fold() or group().

graphersal

  • Defaults: 100 rows, 100 nested items, the same in the REPL, -e and --in.
  • Flags: --max-rows <N>, --max-items <N> (N ≥ 1), and --no-limit. --no-limit together with either of the others is an invalid invocation (exit code 2).
  • REPL: /set max-rows <N>, /set max-items <N>, /set no-limit. Setting a limit after /set no-limit turns limits back on.
  • In -e / --in the notice goes to stderr, so stdout carries only the result (and --format json stays parseable) and the exit code stays 0. The REPL prints it after the output.
graphersal --graph large -e 'g.v()'                         # 100 rows, notice on stderr
graphersal --graph large --no-limit -e 'g.v()' > all.txt    # everything
graphersal --graph large --format json -e 'g.v()' | jq length   # 100

Web playground

The web playground uses the same defaults (changeable in its settings). It runs a traversal without a terminal as execute() and keeps all results as data; its Table, JSON and Raw views show them within the limits (Raw is the text the CLI prints), and a cut result shows the same notice above them. g.with("render.max_rows", n) and to_table(#{max_rows: n}) override the limits for one query there too.

Predicates: Comparison and Resolution

This page lists where Graphersal's predicates (P.eq, P.neq, P.lt, P.lte, P.gt, P.gte, P.within, P.without, P.inside, P.outside, P.between), their composition (and, or, not, negate) and the id order of elements differ from Apache TinkerPop 3.8.2 or settle what TinkerPop leaves open. The Deviations table at the end collects them.

One comparison core

All of these predicates compare through one rule set (TinkerPop's semantics/Comparability).

  • Numbers compare by value across int64 and float64; NaN is incomparable with everything, itself included.
  • Strings compare with strings, booleans with booleans (false < true), UUIDs with UUIDs, null only with null.
  • A string is never read as a number, a date or a UUID.
  • Incomparable means false, never an error. Every test except neq is false for an incomparable pair. A vertex, edge, path or collection on the stream against a number is false as well; for example g.V().where(P.eq(111)) is an empty result, not a cast error.
g.V().where(P.eq(111)).count().next()          // 0, no error
g.V().has("age", P.gt("x")).count().next()     // 0, a number never compares with a string

Operands are single values: a string, a number, a boolean, a date or time, a UUID, a vector or () (the items of P.within([..]) / P.without([..]) each). A list, a map or a traversal as an operand is an ArgumentMismatch naming the predicate when the step is built, never compared as its text. Comparing a list or map inside a predicate is not supported; to match a list or map property as a whole, pass the value itself, as in has("tags", ["a", "b"]). P.within() / P.without() without arguments are the empty set.

g.V().has("name", P.gt(["a"])).count().next()          // error: Argument mismatch for step 'P.gt'
g.V().has("name", P.within(["a", "b"])).count().next()  // 0: the list holds the values
g.V().has("name", P.without()).count().next()           // 6

Text predicates match strings only

TextP.startingWith, endingWith, containing and their negations (also spelled P.startingWith(..)) test a string. Any other value on the stream (a number, a UUID, a list from fold(), a map, a path, a vertex or an edge) is not one, so the predicate is false and its negation true. This is never an error, matching TinkerPop, where TextP only matches a String:

g.V().values("age").is(TextP.startingWith("2")).count().next()   // 0
g.V().fold().is(TextP.startingWith("a")).count().next()           // 0
g.V().fold().is(TextP.notStartingWith("a")).count().next()        // 1

A property handle (values("name")) and a property element (properties("name")) are tested by their stored value.

Regular expressions

TextP.regex(pattern) holds for a string in which pattern matches somewhere; TextP.notRegex(pattern) is its complement (also spelled not_regex, and bare regex(..)/notRegex(..)). Like the other text predicates, a value that is not a string makes regex false and notRegex true. The match is unanchored, as Java's Matcher.find() is; write ^...$ to match the whole string.

g.V().has("name", TextP.regex("^[jp]")).values("name").to_list()   // josh, peter
g.V().has("name", TextP.regex("(?i)^MAR")).values("name").to_list() // marko

Deviation from TinkerPop: Graphersal compiles the expression with the Rust regex crate and uses that crate's dialect, not Java's java.util.regex. Look at the crate's syntax page for what an expression may contain. Matching takes linear time in the input. The expression is compiled once, when the predicate is built: an invalid one is a script error (ValueError::InvalidRegex) before the traversal runs. In Rust the predicate is P::regex("^mar")? / P::not_regex(..)?.

Resolution of a string operand

  • where(P): a bare string operand of eq/neq/lt/lte/gt/gte/within/without is resolved in this order: a path label (as("a")), then a side effect (aggregate, store, withSideEffect), then the literal string. A side effect holding a collection compares as a whole value for eq/neq and is false for the ordering predicates. An unknown name stays a literal.
  • has(key, P), is(P), hasValue(P), all(P), any(P), none(P): operands are always literal values, as in TinkerPop; they never resolve to a label or side effect, so a name that exists as a step label or side-effect key cannot change the meaning of a property filter: g.V().as("vadas").out("knows").has("name", P.eq("vadas")) finds vadas.
  • eq/neq with a string on a vertex compares the vertex's id (is(P.eq("1")), kept from the original implementation); under where(P) a step label of that name comes first.
  • Changed in 0.2.2: before, a value filter compared a string naming a step label with the labelled element (so the first query below returned nothing). TinkerPop compares the literal; only where(P) resolves labels.
g.v(1).as("vadas").out("knows").has("name", P.eq("vadas")).values("name").to_list()   // ["vadas"]: a value filter compares the string
g.v(1).as("a").out("created").in("created").where(P.eq("a")).values("name").to_list()   // ["marko"]: where() reads the label a

hasId(P), hasLabel(P), hasKey(P)

hasId(P.neq("1")) and its siblings evaluate the predicate instead of stringifying it. A lone P.eq(x)/P.within(xs) is rewritten to the literal step so source-filter pushdown still applies.

  • Operands are always literal. No step label or side effect is consulted, so a label named like an id cannot shadow it.
  • Label and key sets. A vertex carries a set of labels, a map a set of keys. A positive predicate (eq, within, lt, ...) holds if any label or key satisfies it; a negated one (neq, without, notStartingWith, ...) holds only if all do. For a single-label vertex this is TinkerPop's behaviour.
  • A predicate mixed with other arguments (hasId(P.eq("1"), "2")) is an ArgumentMismatch.
  • Ids are strings. An order predicate (P.gt, P.gte, P.lt, P.lte, P.between, P.inside, P.outside) with a number operand in hasId(P) / has(T.id, P) is an error before the query runs, not a filter that silently matches nothing; the help shows the string form. Compare with a string instead, hasId(P.gt("3")), and mind the string order: "10" sorts before "9". Equality forms (hasId(3), hasId(P.eq(3)), hasId(P.neq(3)), hasId(P.within(1, 2)), hasId(P.without(1, 2)), also nested as in hasId(P.eq(1).or(P.eq(2)))) take numbers and compare their literal text, in the DSL and the Rust API (has_id_p(P::Neq(3))): 3 matches the id "3", a float 3.0 the id "3.0".
g.V().hasId(P.neq("1")).count().next()                     // 5
g.V().hasId(P.gt("3")).count().next()                      // 3 ("4", "5", "6")
g.V().hasId(P.without(1, 2)).count().next()                // 4
g.V().hasLabel(P.within("person", "x")).count().next()     // 4

Element order

  • TinkerPop: vertices and edges order by id; its ids are typically numbers, so 9 sorts before 10.
  • Graphersal: ids are stored as strings and compared as strings (a string is never parsed into a number), so "10" sorts before "9". Elements with equal or missing ids fall back to a structural comparison.
g.V().order().by(T.id).id().toList()   // "1", "2", ... ; with ids up to 10: "1", "10", "2", ...

Composing predicates: and, or, not, negate

g.V().has("age", P.gt(18).and(P.lt(30)).or(P.gt(35))).values("name").toList()   // marko, vadas
g.V().has("name", TextP.containing("o").and(P.lt("m"))).values("name").toList() // lop, josh
g.V().hasLabel(P.not(P.eq("person"))).count().next()                            // 2
g.V("1").out().aggregate("a").out().where(P.not(P.within("a"))).values("name").toList()
  • p.and(q) and p.or(q) are binary and left-associative: a.and(b).or(c) means (a and b) or c, a.or(b).and(c) means (a or b) and c. Evaluation is left to right and short-circuits, as TinkerPop's AndP/OrP do: P.eq(1).or(q) never evaluates q for a value equal to 1, so a runtime error on the right is not raised when the left side decides.
  • P.not(p) (also P::not(p) and a bare not(p)) and p.negate() are the complement of the result for the same stream value. TextP predicates compose with P ones.
  • The logic is two-valued. An incomparable pair is plain false (see above), so P.lt(NaN) is the "error" column of the Comparability scenarios and reduces to false; there is no third value.
  • Over a label or key set (hasLabel(P), hasKey(P)) a leaf keeps the rule above (positive: any, negated: all); a composite combines the set results: and is &&, or is ||, not is ! of the child's set result.
  • In where(P) each child resolves a string operand on its own (step label, then side effect, then literal), and the path analysis records the union of the labels of the children (P.eq("a").or(P.eq("d")) records a and d).
  • A composite is never pushed into an index or a source filter (.profile() shows has("age", P.gt(27).and(P.lt(33))) with no optimizer rule named); the results are identical with g.with("optimizer.disabled", [...]).
  • A non-predicate operand (P.gt(1).and(__.out()), P.not("x")) is an ArgumentMismatch whose help names the predicate and the traversal combinators (__.and(..), __.or(..)).
  • Not part of this feature: the infix steps g.V().has(..).and().has(..) (TinkerPop's ConnectiveStrategy) and the two-argument where("a", P) with by() modulators.

Type predicates

P.typeOf(GType.X) keeps a value of the given type (GType.STRING, GType.LONG, GType.NUMBER, GType.LIST, GType.VERTEX, ...). TinkerPop 3.8 also accepts a type name, and so does Graphersal, for a fixed list of names:

g.V().values("name").is(P.typeOf("String")).count().next()   // 6
g.V().values("age").is(typeOf("Long")).count().next()         // 4
g.V().values("age").is(P.typeOf("Byte"))                      // script error: unknown type name
NameToken
StringGType.STRING
Integer, LongGType.LONG (every integer is an int64)
Double, FloatGType.DOUBLE (every float is a float64)
OffsetDateTimeGType.DATETIME (TinkerPop's date type; see Dates and Times)
DurationGType.DURATION
LocalDate, LocalDateTime, LocalTimeGType.DATE, GType.LOCALDATETIME, GType.TIME (Graphersal's other date and time types, by their java.time names)
Boolean, UUID, Number, List, Map, Vertex, Edge, Path, Graphthe token of the same name

Both forms take the same values in both spellings (P.typeOf(GType.LONG), P::typeOf(GType::LONG), typeOf("Long") select the same ages). The names are Java's simple class names, as TinkerPop registers them, not the token names: "LONG" is not a type name, in TinkerPop either. The names are case-sensitive. Any other name is a script error (ArgumentMismatch listing the accepted names), as TinkerPop rejects a name it has not registered. In Rust, the same lookup is GType::from_type_name.

Deviations

AreaTinkerPop behaviourGraphersal behaviourWhyScenarios affected
P.typeOf(name)any name in TinkerPop's registered-type cache, custom types includeda fixed list of names (above)Graphersal has no type registry; one width per number kindnone (the suite uses "String" and an unregistered name)
negate() / P.not(p)Compare.negate() flips the operator (gt becomes lte), so the result differs from the complement for incomparable operandsThe plain complement of the result: P.not(P.gt(1)) is true for "foo" and NaNOne rule for every predicate (text, typeOf, composites); operator flipping would need a per-variant inverseNone (every vendored scenario negates a comparable number)
Error value in and/orComparability scenarios call a NaN comparison an "error" columnThere is no error value: incomparable is false, the logic is two-valuedThe expected results reduce to boolean and/or18 Comparability
Numeric widths in the test surfacebyte, short, BigInteger, BigDecimal are distinct typesOnly int64/float64 exist; the harness maps 1b/1s/1n to an integer and 1m to a float (documented in tests/tinkerpop/README.md)Widths cannot be told apart; equality is by value8 Equality, Sum, AsNumber, Inject with width literals
Composites and indexesn/aA composite predicate is not index-pushableOnly a single comparison can be folded into a rangenone
Incomparable pairsSome comparisons raisefalse for every test but neq, never an errorSee "One comparison core"Comparability, where(111) on a vertex
Element id orderNumeric ids order numericallyIds compare as strings, "10" sorts before "9"; an order predicate on a number in hasId(P)/has(T.id, P) (P.gt(3)) is an error naming the string form P.gt("3")A string is never parsed into a number; a number comparison against a string id could never holdorder().by(T.id) on ids with different digit counts
nullProperty null handling depends on the @AllowNullPropertyValues flavournull is a real stored valueGraphersal has a null typeAddVertex/AddEdge/MergeEdge null-property scenarios
Property cardinalitylist/set propertiesOne value per property keyBy design@MultiProperties scenarios

Id Arguments of V(), E() and hasId()

g.V(ids...), g.E(ids...), the nested __.V(ids...)/__.E(ids...) and hasId(ids...) take element ids. This page lists where Graphersal differs from Apache TinkerPop 3.8.2.

Arrays flatten in the first position only

  • TinkerPop: hasId(id, otherIds...) treats a list in a later position as one id that matches nothing; a list as the first argument is flattened.
  • Graphersal: the same observable result, modelled explicitly. Only the first argument flattens an array (recursively); an array in any later position contributes the empty id, which matches no element.
  • Why: the TinkerPop scenario HasId::g_VX1X_out_hasIdX2_listXid3_id4XX depends on it.
g.V(["1", "2"]).values("name").toList()      // "marko", "vadas"
g.V("1", ["2", "3"]).values("name").toList() // "marko" only

null is the empty id

  • TinkerPop: a null id is not a defined element id.
  • Graphersal: () (the DSL's null) contributes the empty id, which matches nothing, so g.E(()) and hasId(()) stay empty instead of widening to every element.

Elements and maps as ids (extension)

A map with an "id" key, as returned by next()/toList(), contributes that id, so g.E(e) works with a previously fetched edge. Any other map is rejected with an ArgumentMismatch error instead of being turned into an id that never matches.

Predicates

hasId(P) evaluates the predicate over the id; see Predicates: Comparison and Resolution.

Type Conversion and length()

Deviations of length(), as_string(), as_bool(), as_number() and cast() from Apache TinkerPop 3.8.2.

length() accepts strings only

  • TinkerPop: length() is a string step; any other input is a cast error.
  • Graphersal: the same. A list, map, path, vertex, edge or number raises a cast error, in both scopes; null stays null. Use count(Scope.local) for the size of a collection. Earlier Graphersal versions also measured lists and paths; that was removed.
g.V().fold().length().toList()            // error: expected type [string], got type 'array'
g.V().fold().count(Scope.local).toList()  // 6
  • Deviation: the length counts Unicode scalar values (Rust chars().count()). TinkerPop counts Java chars (UTF-16 code units). The two agree for every character in the Basic Multilingual Plane ("é" is 1, "日本語" is 3, in both). They differ for astral-plane characters such as emoji: "😀" is 1 here and 2 in TinkerPop. The same applies to length(Scope.local) and to length() of a label.

null: asString() and asBool() raise, asNumber() and cast() keep it

  • TinkerPop: asString() and asBool() reject null ("Can't parse null"); asNumber() keeps it.
  • Graphersal: the same, per step. as_string() and as_bool() raise a cast error on null (the configured CastPolicy still applies); as_number() and the Graphersal extension cast() keep null as null. The behaviour is deliberately not uniform.
g.inject(()).asString().toList()   // error: expected type [string], got type 'null'
g.inject(()).asNumber().toList()   // null

asBool() and asNumber() are explicit conversions

as_bool() and as_number(GType.INT | GType.LONG) follow TinkerPop's own rules, not the schema coercion matrix. The matrix (used when a declared property is written) and the Graphersal extension cast() stay strict: cast(GType.BOOLEAN) of 2 or of "TRUE" and cast(GType.INT) of 5.43 still fail, because a lossy conversion there would corrupt stored data.

asBool():

InputResult
true, falseunchanged
0, 0.0, -0.0, NaNfalse
any other number (1, -1, 3.14, Infinity)true
the texts true / false in any ASCII letter case ("tRUe", "FALSE")true / false
any other text ("hello", "1", "", " true"), null, a uuid, a collectionerror

asNumber(GType.INT) and asNumber(GType.LONG) (the same int64 target):

InputResult
an integerunchanged
a floattruncated toward zero (5.67 is 5, -5.67 is -5)
a text that parses as a whole integer ("5"), a boolean5, 1/0
nullnull
"5.7", NaN, infinity, a float outside the int64 rangeerror
  • Deviation (asNumber): TinkerPop's Integer target wraps or narrows to its own width; Graphersal has one integer width, so a NaN, infinite or out-of-range float is an error instead.
  • Deviation (asBool): only the two literals true and false convert from text, never "1" or "yes": a string is not interpreted by its content.
g.inject(-1, 0.0, "tRUe").asBool().toList()        // [true, false, true]
g.inject(5.67, -5.67).asNumber(GType.INT).toList() // [5, -5]
g.inject(5.43).cast(GType.INT).toList()            // error: stays strict

trim(), lTrim() and rTrim()

  • Deviation: the three steps strip Unicode whitespace (the White_Space property, Rust str::trim), while Java's String.trim() strips only characters up to U+0020. A no-break space (U+00A0) or an ideographic space (U+3000) at the end of a string is removed here and kept by TinkerPop. No vendored scenario depends on it.

Math Expressions

math("<equation>") evaluates an arithmetic equation for every traverser and emits the result, always as a double. Graphersal follows TinkerPop's math() step, which uses the exp4j expression language: the same operators, precedence, functions and constants, the same variable resolution and the same errors. The equation is parsed once, when the traversal is built, by Graphersal's own expression engine; it does not need the script feature.

Every example on this page was run with graphersal on the default modern graph; the line after // is its real output.

Quick reference

g.V("1").values("age").math("_ / 2").toList()                                  // 14.5
g.V().math("_ + 1").by("age").toList()                                         // 30.0, 28.0, 33.0, 36.0
g.V().as("a").out("knows").as("b").math("a + b").by("age").toList()            // 61.0, 56.0
g.V("1").project("a", "b").by("age").by(__.out().count()).math("a / b").toList()  // 9.666666666666666
g.withSideEffect("x", 100).V("1").values("age").math("_ + x").toList()          // 129.0
g.inject(1).math("2^3").toList()                                                // 8.0

In Rust the step is math(expr) on GraphTraversalSource, AnonymousTraversal and __, with the same by() modulators as in the DSL.

Syntax

An equation is built from:

  • numbers: 12, 1.5, .5, 5., 1e3, 1.2E-3, 2.5e+2 (no sign, hex or inf literal; a sign is the unary operator);
  • the current value _ and variables (a, price_2): a name [A-Za-z_][A-Za-z0-9_]* that is not a function;
  • operators, functions and constants from the tables below;
  • parentheses: (, [ and { all group and call (sqrt[_]), but a closer must match its opener.

There is no implicit multiplication, as in TinkerPop (which turns it off): 2 pi, 2(3) and 2 _ are errors; write 2 * pi.

A function name without parentheses applies to everything to its right up to the end of the enclosing group, as in exp4j: sin _ is sin(_), sin _ + 1 is sin(_ + 1), and (sin _ + 1) * 2 is sin(_ + 1) * 2.

g.inject(2).math("sin _ + 1").next()           // 0.1411200080598672  (= sin(3))
g.inject(100).math("log10(_) + log(e)").next() // 3.0

Operators

Higher precedence binds tighter. Unary operators never take a pending binary operator, so -2^2 is -(2^2) and 2^-2^2 is 2^(-(2^2)).

OperatorPrecedenceAssociativityMeaning
a + b500leftaddition
a - b500leftsubtraction
a * b1000leftmultiplication
a / b1000leftdivision; a zero divisor is an error
a % b1000leftremainder with the sign of the dividend (Java %); a zero divisor is an error
a ^ b10000rightpower (right-associative)
-a5000rightnegation
+a5000rightidentity
g.inject(1).math("-2^2").next()   // -4.0
g.inject(1).math("2^3^2").next()  // 512.0
g.inject(-7).math("_ % 3").next() // -1.0

+ and - are unary at the start, after an opening bracket, after , and after another operator; everywhere else they are binary (2--2 is 4).

Functions

The exp4j 0.4.8 built-in set. All take one argument except pow. Domain errors are not errors: sqrt(-1) and log(-1) are NaN and log(0) is negative infinity, as in Java.

FunctionMeaning
abs(x)absolute value
acos(x)arc cosine (radians)
asin(x)arc sine (radians)
atan(x)arc tangent (radians)
cbrt(x)cube root
ceil(x)round up to an integer
cos(x)cosine (radians)
cosh(x)hyperbolic cosine
cot(x)cotangent; an error where tan(x) = 0
exp(x)e raised to x
expm1(x)exp(x) - 1
floor(x)round down to an integer
log(x)natural logarithm
log10(x)base-10 logarithm
log1p(x)log(1 + x)
log2(x)base-2 logarithm
pow(x, y)x raised to y
signum(x)sign: -1, 0 or 1
sin(x)sine (radians)
sinh(x)hyperbolic sine
sqrt(x)square root
tan(x)tangent (radians)
tanh(x)hyperbolic tangent

There is no round; use floor(_ + 0.5). cot, expm1, log1p and pow are exp4j built-ins that TinkerPop's math() cannot use (it declares their names as variables, which exp4j rejects); Graphersal accepts them.

Constants

ConstantValueMeaning
pi3.141592653589793π
π3.141592653589793π
e2.718281828459045Euler's number
φ1.61803398874golden ratio (exp4j's 12-digit value)

pi and e are variables with a fallback, as in exp4j: a map key, side effect or step label named e wins, and the constant is used only when the name resolves to nothing else (TinkerPop fails in that case). π and φ are always constants.

g.withSideEffect("e", 2).inject(1).math("e + _").next()  // 3.0

Variables and by()

_ is the current traverser's value. Any other variable is resolved as in TinkerPop's Scoping, in this order:

  1. a key of the current value when it is a map (project(), select(), valueMap(), elementMap(), group() results, a map-valued property);
  2. a side effect (withSideEffect(), aggregate(), store());
  3. a step label (as()); the last object with that label on the path.

The by() modulators form a ring over the distinct variables in order of first appearance: the first by() applies to the first variable, the second to the second, and so on, cycling when there are fewer by()s than variables. A variable used twice takes one slot. _'s by() runs on the current traverser; any other variable's by() runs on the resolved object.

// b appears first: b takes in("created").count(), a takes age
g.V().as("a").out("created").as("b").math("b + a").by(__.in("created").count()).by("age").toList()
// 32.0, 33.0, 35.0, 38.0

A traverser for which a by() produces nothing (by("age") on a vertex without age) is filtered out, as in TinkerPop 3.6+.

Every variable must resolve to a number. A string, a list or a map is an error; convert a numeric string with as_number(GType.DOUBLE) first.

Nested access (Graphersal extension)

Graphersal extends the language with nested access after any variable, with no whitespace before . or [. It is not part of exp4j or TinkerPop: exp4j rejects every such equation, so no TinkerPop equation changes its meaning.

FormReads
_.keya key of a map (or a property of a vertex or edge)
_["unit price"], _['k']a key that is not an identifier (escapes \\, \", \')
_[0], _[-1]an element of a list; a negative index counts from the end

The path is applied after the variable's by() projection and reads the value in place, without materializing the element.

g.V("1").elementMap().math("_.age * 2").toList()        // 58.0
g.V("1").valueMap().math("_.age[0] + 1").toList()       // 30.0  (valueMap() values are lists)
g.inject(#{price: #{total: 10, items: [1, 2.5, 4]}}).math("_.price.total * 2 + _.price.items[-1]").toList()
// 24.0
g.inject(#{"unit price": 3}).math("_[\"unit price\"] * 4").toList()  // 12.0

Errors

An equation that does not parse fails before the traversal runs, even when no traverser reaches the step. Every other problem fails the traversal for the traverser that hits it. The diagnostic underlines the offending token:

g.inject(1).math("2 pi")
// Error: math("2 pi") failed at column 3: missing operator before name 'pi'; implicit multiplication is not supported, write '*' explicitly
//   equation: math("2 pi")
//                     ^
ProblemExampleMessage
syntaxmath("2 +* 3")unexpected '*'; expected a number, a variable, a function or '('
unknown functionmath("sqr(_)")unknown function 'sqr'; ... (the help suggests sqrt)
unknown variablemath("_ + x") with no x anywherevariable 'x' is not '_', a key of the current map, a side effect or a step label
bad pathelementMap().math("_.agee")_.agee leads to no value: no key 'agee'; the available keys are: id, label, name, age
not a numbervalues("name").math("_ + 1")the variable _ for math() must resolve to a number, but it is a string
nulla null valuethe variable _.a for math() must resolve to a number, but it is null
division by zeromath("_ / 0")Division by zero! (exp4j's message; also % and cot)

The current value is _

The current value is _, as in TinkerPop; there is no other name for it. math("value + 1") fails with an unknown-variable error whose help shows the rewritten query. Results are doubles (math("2 + 2") is 4.0), and ^ is the power operator.

Map Keys and Values

group(), group_count(), project(), element_map() and select("a", "b") produce maps. This page covers how a query reads a map's keys and values generically: unfold() turns a map into its entries, and select(Column.keys) / select(Column.values) (TinkerPop select(Column)) reads keys or values.

Quick reference

On the modern graph:

g.V().group().by("name").by(__.out().count())                                 // one map
g.V().group().by("name").by(__.out().count()).unfold()                        // 6 entries: marko=3, vadas=0, ...
g.V().group().by("name").by(__.out().count()).unfold().select(Column.keys)    // "marko", "vadas", "lop", ...
g.V().group().by("name").by(__.out().count()).unfold().select(Column.values)  // 3, 0, 0, 2, 0, 1
g.V().group().by("name").by(__.out().count()).select(Column.keys)             // ONE list: ["marko", "vadas", ...]
g.V().group().by("name").by(__.out().count()).select(Column.keys).unfold()    // "marko", "vadas", "lop", ...

The order is the map's own order. group() keeps first-seen order. The index-backed group_count().by(T.label) pushdown does not guarantee any order.

unfold() of a map

unfold() emits one traverser per map entry. It still unrolls a list into its elements, and any other value passes through unchanged. An entry is its own kind of stream value (TinkerPop's Map.Entry). When an entry reaches a terminal (to_list(), next(), a table), it becomes a single-key map, which is how the Gremlin console prints marko=3:

g.V().groupCount().by(T.label).unfold().toList()
// #{"person": 4}
// #{"software": 2}

unfold() of an entry passes it through unchanged. An entry is not a collection.

select(Column.keys) / select(Column.values)

Inputselect(Column.keys)select(Column.values)
a map (group(), group_count(), project(), element_map(), a nested object property)one list of all keysone list of all values, types kept
an entry (from unfold() of a map)the keythe value
a path (from path())one list holding the step labels of each positionnot implemented: cast error
anything elsecast errorcast error

Map or entry? The rule depends on the kind of value, not on how many keys it has. A map is always a map, even with one key:

g.V("1").groupCount().by("name").select(keys).toList()            // [["marko"]]: one list
g.V("1").groupCount().by("name").unfold().select(keys).toList()   // ["marko"]: the key itself

This follows TinkerPop, where Map and Map.Entry are different types. A rule based on the number of keys ("a single-key map is an entry") would make one-group group() results behave differently from every other group() result. Only unfold() creates entries. A single-key map that went through a terminal and came back into a query (for example through inject()) is a map again, and values(k), select(k) and has(k, v) read its keys like those of a project() result:

let m = #{name: "x", age: 3};
g.inject(m).values("name").toList()        // ["x"]
g.inject(m).select("name", "age").toList() // [#{age: 3, name: "x"}]
g.inject(m).has("age", P.gt(2)).count()    // 1

A path. select(Column.keys) of a path lists the step labels of its positions, one list per position in position order (TinkerPop's Path.labels()); an unlabelled position is an empty list, and the labels of one position keep the order of their as() calls:

g.V("1").as("a", "b").out().as("c").path().select(Column.keys).toList()   // [[["a", "b"], ["c"]], ...]

select(Column.values) of a path lists its objects in position order (TinkerPop's Path.objects(); after path().by(..) the modulated values), so keys and values line up by index:

g.V("1").out("knows").path().select(Column.values).toList()   // [[v[1], v[4]], [v[1], v[2]]]
g.V("1").out("knows").path().by("name").select(Column.values) // [["marko", "josh"], ["marko", "vadas"]]

select(Column...) has nothing to do with label-based select("a"). It reads the current value only, never the traverser path. So an as() label before it records nothing, and .profile() shows the step as select(Column.keys).

Spellings

NotationKeysValues
Gremlin (dot)select(Column.keys)select(Column.values)
Gremlin console static importselect(keys)select(values)
Rhai static moduleselect(Column::keys)select(Column::values)
Rust API.select(Column::Keys).select(Column::Values)

The bare tokens keys and values are script constants. They do not interfere with the values("age") step, because Rhai keeps variables and methods in separate namespaces. Column, keys and values are reserved names and cannot be used as script parameters.

There is no keys() step. It does not exist in TinkerPop either. g.V().group().keys() fails with Rhai's own Function not found: keys error. Use select(Column.keys) instead.

Errors

A map is not a graph element. So properties(), key(), value(), id() and out() on a map or an entry stay errors, as in TinkerPop. The help text shows how to read the map instead:

g.V().group().by("name").by(__.out().count()).properties().key()
// Cast exception: expected type [vertex or edge], got type 'object'
// Help: ... Read its keys or values with unfold().select(Column.keys) / unfold().select(Column.values), ...

select(Column.keys) on something that is not a map fails with expected type [map or entry]. The help names the steps that produce maps, and it names unfold().

Maps With Non-String Keys

In TinkerPop a map key is any value: groupCount().by("age") returns {29=1, 27=1}, and group().by(out()) has vertices as keys. Graphersal's logical value model holds such a map as ElementProperty::Map(Box<ValueMap>). A map whose keys are all strings stays an ElementProperty::Object, so everything that exists today (JSON shape, Rhai object maps, schemas, storage) keeps seeing Object.

This page describes the value type and where a query produces it. group(), groupCount(), tree() and unfold() of such a map keep the type of their keys: g.V().groupCount().by("age") is {29: 1, 27: 1, 32: 1, 35: 1} with int64 keys, next()[29] reads 1, a list key stays a list, a float stays a float, a UUID stays a UUID, and a vertex key stays a vertex. A result whose keys are all strings is unchanged (an Object, a Rhai object map, a plain JSON object). Builders for the Rust API are ElementProperty::from_entries and ValueMap::into_property.

g.V().groupCount().by("age").next()[29]                    // 1
g.V().group().by(__.out("created")).by("name").next()      // vertex keys
g.V().groupCount().by("age").unfold().select(Column.keys)  // 29, 27, 32, 35 as ints

The rule

  • ElementProperty::from_entries(entries) and ValueMap::into_property() are the only constructors that decide the variant: all keys strings gives Object, any other key gives Map. A Map always has at least one non-string key.
  • A Map is never storable as a property, in every schema mode: addV().property("k", map) fails with InvalidPropertyValue (the help shows the string-key form and to_json()).
  • type_of(map) is object (declared fields only describe string keys, so a Map carries none) and GType.MAP matches it.

Key equality

Keys follow Java equals, as TinkerPop does:

PairSame key?
1 and 1.0no (P.eq(1) still matches 1.0; key equality is stricter than predicate equality)
NaN and NaNyes
"1" and 1no
[1, 2] and [2, 1]no
two maps with the same entries in a different orderyes

Map equality and hashing ignore entry order: two equal maps built in a different order hash alike.

Output

  • JSON (to_json()): a Map is written in the GraphSON 3 shape {"@type": "g:Map", "@value": [k1, v1, k2, v2]}, keys and values lowered recursively. A string-keyed map is always a plain JSON object. The tag is output only: reading JSON back never interprets @type (a Map cannot be stored, so it never needs to be read back).
  • Table and tree: keys print through the display renderer (string unquoted, 29, 2.0, null, true, a vertex v[1], a list as compact JSON). When two keys of one map print the same text ("29" and 29) they stay separate columns, and the string key's header is shown quoted.
  • Console / to_string: {29: 1, "a": 2}, strings quoted.

In scripts

A Map reaches Rhai as a Map value (Rust type ScriptMap, public so hosts can downcast it):

RhaiMeaning
m[29], m["name"]read an entry by any key; a missing key is ()
m.namethe same as m["name"] for a string key
m.len(), m.is_empty() / m.isEmpty()size
m.keys(), m.values()arrays in insertion order, keys keep their type
m.contains(k), m.containsKey(k) / m.contains_key(k)membership
for pair in m[key, value] arrays
m.to_map() / m.toMap()a Rhai object map; an error when a key is not a string

select(Column.keys) and unfold() on a materialized Map return typed keys. json_path() and math() address string keys only; a non-string entry is unreachable by path.

Deviations from TinkerPop

  • 0.0 and -0.0 are the same key (Graphersal canonicalizes -0.0 when a number is built; Java treats them as different keys).
  • asString() of a map fails, for a Map as for a string-keyed map (see TinkerPop Deviations).
  • A missing key in a script reads as (), the script's null.
  • Vertex and edge keys are snapshots, not live elements (see above).
  • Not storable: a map with a non-string key cannot be a property value (a string-keyed map can), because stored maps are plain JSON-like objects and GraphML and schemas only describe string keys.

Vertex and edge keys are snapshots

TinkerPop's key is the live element, compared by id. Graphersal materializes a vertex or edge key once, when the result is built, into an ElementProperty::Vertex/Edge snapshot (its element map). Two keys of one result that are the same vertex are equal (same snapshot), and a later graph change does not alter an already returned key. Rendered as a table or tree a vertex key prints as v[1]; in JSON it is the whole element. Entries of unfold() on a map are materialized as one-entry maps ({29: 1}), not as a separate entry type.

What stays a string

Where the key space is text by definition a key is still text: T.label and the label-keyed groupCount pushdown, the select("a", "b") and project(..) names, and GraphML or schema data. A group() key that merely looks like a number ("29") stays a string and is a different key from 29.

Local Scope

Most steps work on the whole stream: count() counts traversers, sum() adds up every number that flows past. TinkerPop's Scope token changes that. With Scope.local a step works on the collection that each single traverser holds — a list from fold(), a map from group(), a stored list property — and emits one result per traverser.

Quick reference

On the modern graph:

g.V().fold().count(Scope.local)                          // 6: the size of the one folded list
g.V().group().by(T.label).count(Scope.local)             // 2: the number of map entries
g.V().count(Scope.local)                                 // 1, 1, 1, 1, 1, 1: a vertex is one element
g.V().values("age").fold().sum(Scope.local)              // 123
g.V().values("age").fold().min(Scope.local)              // 27
g.V().values("age").fold().max(Scope.local)              // 35
g.V().values("age").fold().mean(Scope.local)             // 30.75
g.V().values("foo").fold().sum(Scope.local)              // nothing: the list is empty
g.V("1").values("age").sum(Scope.local)                  // 29: a scalar is a one-element list
g.V().where(__.out().fold().count(Scope.local).is(P.gt(2))).values("name")   // "marko"
g.V().values("name").fold().limit(Scope.local, 2)        // ["marko", "vadas"]
g.V().values("name").fold().skip(Scope.local, 4)         // ["ripple", "peter"]
g.V().values("name").fold().tail(Scope.local)            // ["peter"]: still a list
g.V().values("name").fold().range(Scope.local, 1, 3)     // ["vadas", "lop"]
g.V("1").valueMap("name", "age").tail(Scope.local, 1)    // {age: [29]}: a map stays a map
g.V("1").values("age").range(Scope.local, 20, 30)        // 29: a scalar passes through
g.V().hasLabel("person").fold().order(Scope.local).by("age")   // [v[vadas], v[marko], v[josh], v[peter]]
g.V().values("age").fold().order(Scope.local).by(Order.desc)   // [35, 32, 29, 27]
g.V("1").elementMap().order(Scope.local).by(Column.keys)       // {age, id, label, name}: entries sorted by key
g.V().out().in().values("name").fold().dedup(Scope.local)      // ["marko", "peter", "josh"]
g.V().values("name").order().fold().toUpper(Scope.local)       // ["JOSH", "LOP", "MARKO", "PETER", "RIPPLE", "VADAS"]
g.V().values("name").order().fold().length(Scope.local)        // [4, 3, 5, 5, 6, 5]
g.V().hasLabel("person").values("age").order().fold().asString(Scope.local)   // ["27", "29", "32", "35"]
g.V().hasLabel("software").values("name").order().fold().replace(Scope.local, "p", "g")  // ["log", "riggle"]
g.V().hasLabel("software").values("name").order().fold().substring(Scope.local, 1, 4)   // ["op", "ipp"]
g.V().values("name").toUpper(Scope.local)                      // "MARKO", "VADAS", ...: a string is one string

In Rust the scoped form of a step is <step>_scoped(scope):

use graphersal::prelude::*;

let graph = GraphSource::tinkerpop_modern();
let lock = graph.read();
let total = lock.traversal().v(None).values("age").fold().sum_scoped(Scope::Local).to_list();

What counts as a collection

The traverser holdsScope.local works on
a list: fold(), cap() of an aggregate, a stored list property (values("list"))its elements, in order
a map: group(), group_count(), project(), select("a", "b"), value_map(), a stored map propertyits entries
a path (path())its objects (count(Scope.local) is the path length; the limit/skip/tail/range family fails with "not implemented" on a path)
anything else: a number, a string, a vertex, an edge, a map entrya one-element collection holding the value

Supported steps

StepListMapAnything else
count(Scope.local)the number of elementsthe number of entries1
sum(Scope.local)the sum of the elementserrorthe value itself
min(Scope.local) / max(Scope.local)the smallest / largest elementerrorthe value itself
mean(Scope.local)the mean of the elements, a doubleerrorthe value as a double
limit(Scope.local, n)the first n elements, as a listthe first n entries, as a mapthe value itself
skip(Scope.local, n)all but the first n elementsall but the first n entriesthe value itself
tail(Scope.local, n)the last n elements (tail(Scope.local) = n = 1)the last n entriesthe value itself
range(Scope.local, low, high)the elements [low, high) (high = -1: to the end)the entries [low, high)the value itself, even out of range
order(Scope.local) + by(...)the elements, sortedthe entries, sorted (still a map)the value itself
dedup(Scope.local)the elements without duplicates, first occurrence firstthe map itself (not a list)the value itself
toUpper/toLower/trim/lTrim/rTrim(Scope.local)each string transformed, as a list of the same lengtherror, as the unscoped stepa string: transformed as by the unscoped step; null: null
length(Scope.local)the length of each stringthe map's size, as length()a string: its length; null: null
replace(Scope.local, from, to) / substring(Scope.local, start[, end])each string transformederror, as the unscoped stepa string: transformed as by the unscoped step; null: null
asString(Scope.local)each element converted to a string (a null element is an error)error, as the unscoped stepconverted as by asString()

The reducers sum/min/max/mean skip null elements. A list that holds no number at all (empty, or only nulls) emits nothing, so the traverser is dropped — exactly like the global sum() on an empty stream. They use the numeric rules of the global steps, described next.

Numeric rules

These rules hold for the global sum()/min()/max() and their Scope.local forms alike.

  • An integer stream stays an integer and stays exact; overflow of int64 raises an error (there is no BigInteger, see TinkerPop Deviations).
  • A float joining an integer stream promotes the result to a float, whatever the order: sum of 1, 2.5 is 3.5, min of 3, 2.5, 1 is 1.0, and max of 29, 0.5 is 29.0 even though the maximum came from an integer (as in TinkerPop's NumberHelper). Integers beyond 2^53 lose precision once widened. mean always computes in floating point.
  • min/max also compare strings (str order), booleans (false < true) and UUIDs: g.V().values("name").max() is "vadas". Numbers compare with numbers and text with text; a stream that mixes kinds (a number and a string, a boolean and a number) fails with a clear error naming both kinds. Read the property as one kind first, with as_string() or as_number(GType.LONG).
  • Graph elements, paths and collections are not ordered by min/max and fail the same way. TinkerPop orders vertices and edges by id here; this engine orders elements only inside order(). sum and mean accept numbers only.

The limit/skip/tail/range family always returns a collection of the kind it got: a list stays a list even when one element (or none) is left, as in TinkerPop 3.8 (limit(Scope.local, 1) on [1, 2, 3] is [1], not 1), and a map stays a map in entry order. Bounds follow the global range(): low and every count must be zero or more and high must be -1 or at least low; otherwise the traversal fails with an "Invalid range" error. In Rust the steps are limit_scoped(scope, n), skip_scoped(scope, n), tail_scoped(scope, n) and range_scoped(scope, low, high), all taking i64.

order(Scope.local) takes the same by() clauses as the global order(): a property key, T.label/T.id, a traversal (its first result), Order.asc/Order.desc, and several by()s as tiebreakers. The sort is stable, and an element whose by() yields nothing (a vertex without the property) is dropped from the list, as in the global step. A by(__...) traversal runs on each element with the path of the traverser that holds the list, so by(__.select("x")) sees the outer step labels. In Rust: order_scoped(Scope::Local).by("age").

dedup(Scope.local) compares vertices and edges by identity and everything else by value, and keeps the elements as they were (a folded vertex list stays a list of vertices). Like TinkerPop, dedup(Scope.local, "x", "y") ignores the labels — upstream passes them only to the global step. The global label form (dedup(Scope.global, "x"), dedup("x", "y")) is not implemented. In Rust: dedup_scoped(Scope::Local) and dedup_scoped_labels(Scope::Local, ["x", "y"]).

count(Scope.local) is a per-traverser step, so the count_pushdown optimizer rule never folds it into the source step: .profile() shows it as count(Scope.local).

String steps

The per-value string steps toUpper, toLower, trim, lTrim, rTrim, length, replace, substring and asString take a Scope as their first argument. With Scope.local a list is transformed element by element into a new list of the same length. A null element stays null (["a", null, "b"] → ["A", null, "B"]), and so does a null input. Any other element fails with TinkerPop's message, for example The trim(local) step can only take string or list of strings. The help shows how to convert or filter the elements first (...fold().unfold().as_string().fold().trim(Scope.local)). asString(Scope.local) converts numbers, booleans and UUIDs, but a null element has no string form and fails ("Can't parse"). A single string (not a list) is handled exactly as by the unscoped step, and a map fails with the unscoped step's cast error.

substring also takes a single index: substring(2) cuts from the third character to the end, substring(-3) keeps the last three characters. Indices count characters, a negative index counts from the end, and every index is clamped to the string, so substring(-4, 2) on "lop" is "lo" and substring(1, 0) is "".

In Rust: to_upper_scoped(Scope::Local), to_lower_scoped, trim_scoped, l_trim_scoped, r_trim_scoped, length_scoped, as_string_scoped, replace_scoped(scope, from, to), substring_from(start) and substring_scoped(scope, start, Option<end>). .profile() shows the scope only when it is local: to_upper(Scope.local), substring(Scope.local, 1, 4), replace(Scope.local, "h", "j").

Sorting maps with by(Column.keys) / by(Column.values)

Column.keys and Column.values are order() sort keys, in both scopes. On a map entry (from unfold() of a map) they read the entry's key or value; order(Scope.local) applies them to each entry of the map it sorts:

g.V().hasLabel("person").group().by("name").by(__.outE().values("weight").sum()).
  order(Scope.local).by(Column.values)                  // {peter: 0.2, josh: 1.4, marko: 1.9}
g.V().hasLabel("person").group().by("name").by(__.outE().values("weight").sum()).
  unfold().order().by(Column.values, Order.desc)        // marko=1.9, josh=1.4, peter=0.2

In Rust: .by(Column::Values). Every other step rejects by(Column...) with an "invalid modulator" error whose help shows these forms; to read a map's keys or values as data, use select(Column.keys) / select(Column.values).

Scope.global

Scope.global is the ordinary stream-wide step: sum(Scope.global) is exactly sum(), with the same plan and the same errors, tail(Scope.global, 2) is exactly tail(2), order(Scope.global) / dedup(Scope.global) are order() / dedup(), and toUpper(Scope.global) is toUpper() (it fails on a list; use Scope.local).

Spelling

The token is written Scope.local / Scope.global (also Scope.Local / Scope.Global) or Scope::local / Scope::global. There are no bare local / global tokens: local(...) is the local() step, and global is reserved by the script engine. Scope is a reserved name, so a query parameter cannot be called Scope.

Feeding a list to a global reducer is a common slip. The error names the fix:

g.V().values("age").fold().sum()
// Cast exception: expected type [...], got type 'array'
// The value is a list (for example from fold()): reduce each traverser's list with Scope.local,
// for example g.v().values("age").fold().sum(Scope.local) ...

Path keys (jpath)

Wherever a read step takes a property name, it also accepts jpath("..."): a path into a nested property value (an object or an array). A plain string is always a literal property name: "a.b" names a property called a.b, jpath("a.b") reads key b inside the property a. Strings are never sniffed.

g.v().values(jpath("meta.tags[0]"))
g.v().has(jpath("meta.k"), P.gt(1))
g.v().order().by(jpath("meta.k"))
g.v().valueMap(jpath("meta.k"), "name")      // key of the entry: "$.meta.k"
g.v().properties(jpath("meta.k")).key()      // "$.meta.k"

Grammar

RFC 9535 singular queries only: member names and integer indices, so a path always reaches at most one value. $ is optional (a.b[1].c and $.a.b[1].c are the same). Bracket names ['a.b'] / ["a.b"] hold a name that contains a dot, a quote or a bracket, with the escapes \', \", \\ (and the RFC control escapes and \uXXXX). Negative indices count from the end: [-1] is the last element. Not supported (a parse error naming the position): .. recursive descent, wildcards *, filters [?(..)], slices [a:b], unions [a,b]. A path needs at least one segment: $ alone and the empty string are errors. A path has at most 256 segments, and an index is at most 9007199254740991 (2^53 - 1, the interoperable JSON integer range) from either end; beyond that it is a parse error naming the position.

Deliberate leniencies compared to the RFC, kept so that old json_path("meta.tags[0]") strings keep working: the dot notation accepts any non-structural character in a name (user-name; the canonical form then renders it as ['user-name']), a leading . and a leading [ without $ are accepted, and whitespace inside brackets is allowed. Empty segments (a..b, a., a.[0]) are rejected. The canonical text ($.a.b[1].c, bracket form only for names that need it) is what shows up as a result key and in .profile(); parsing the canonical text gives the same path back.

A plain string is never parsed: values("a.b") reads the property named a.b. Write jpath("a.b") for the path. In the Rust API, any &str/String converts to a name key (PropKey::Name) and a JsonPath to a path key (PropKey::Path).

Missing paths

A path that does not exist (missing key, index out of range, a scalar on the way) is an absent property, never an error: values yields nothing, has is false, hasNot is true, by() is unproductive.

properties(jpath(...))

A path has no stored property to point at, so properties(jpath(..)) yields a path property element: a materialized pair of the canonical path text and the value the path ends on. It behaves like a property element otherwise:

StepResult
key()canonical path text, e.g. $.meta.k
value()the leaf value
label(), hasLabel(..), hasKey(..)the path text (like a property's key)
hasValue(..), is(P), where(P)compare the leaf
id()error: property elements have no id in Graphersal
as_string()p[$.meta.k->1]
dedup()compares path text and leaf
terminal (toList(), display, JSON)the leaf value
out(), has(..), drop(), ...error (not a vertex or an edge)

Only a vertex or an edge is a valid input. This is a Graphersal extension: a plain name never produces this element and behaves exactly as in TinkerPop.

Name-taking steps and what they accept

Converted (accept a path): values, properties, has (all forms with a key), hasNot, valueMap, elementMap, and by(jpath(..)) everywhere a property by() is read (order, group, groupCount, dedup, path, tree, select, project, where, math, aggregate, store, sack).

Not applicable, on purpose:

  • hasKey / hasKey(P) filter the key of a property element or the keys of a map; there is nothing nested to descend into. Pass names; to filter a path property element use its path text (properties(jpath("a.b")).hasKey("$.a.b")).
  • glob_path().by(..): the match key is the stored value of one property, a jpath there is rejected with a message that names by("name").
  • project(names), select(labels), as(..), dedup("label"), math("a + b"), cap, aggregate("x"), store("x"), loops(name): these take step labels or result names, not property names (only their by() was relevant).
  • has_label, has_id, hasValue, out(..), in(..), ...: labels, ids, values.
  • merge_v / merge_e match maps: literal property names.
  • property(map), property(T.id|T.label, v), property_json(..), mergeV/mergeE maps: the keys of a map are literal property names (a map key "a.b" is the property a.b), property_json merges whole top-level properties. Use property(jpath(..), v) for nested writes.
  • remove_property(jpath(..)) is covered below; drop() on a path property element is an error (see below).

Writing: property(jpath(..), value)

The first segment is the property name on the vertex or edge, the rest descends into its value. value is anything a plain property(name, value) accepts (a constant, a nested map or list, or a traversal whose first result is used; an empty traversal result writes nothing). Vertices and edges are still rejected as values.

SituationResult
a key segment, the key is missing (also the whole top-level property)created as an object
a key segment, the key existsreplaced (leaf or whole subtree)
[n], 0 <= n < lenreplaces the element
[len] as the last segmentappends
[n], n > len, or [len] followed by more segmentserror, arrays are never padded with null
[-k], 1 <= k <= lenreplaces counting from the end; error when out of range or the array is empty
an index segment where the array does not existerror: only key segments create missing containers
key on an array / scalar / null / non-string-keyed maperror, never an overwrite
index on an object / scalar / nullerror
first segment is an index (jpath("[0]"))error: the first segment names the property
property(Cardinality.x, jpath(..), v)error in v1 (Graphersal stores one value per property)
g.V("a").property(jpath("meta.k.z"), 1)          // creates meta, k, z as objects
g.V("a").property(jpath("meta.tags[0]"), "x")    // replace; error when meta.tags does not exist
g.V("a").property(jpath("meta.tags[-1]"), "z")   // replace the last element

All faults surface as GraphError::InvalidPropertyPath with a help text, and every fault is detected before anything changes, so a refused write leaves the property as it was. The failing traversal is then rolled back as a whole, so writes made by earlier steps (or earlier traversers) of the same traversal are undone too, exactly as for a plain property (see Transactions). A single-segment path is the plain property. The write mutates the stored value in place (no clone of the top-level property) when the graph has no schema; with a schema the leaf is coerced at its declared nested type and the whole resulting top-level property is validated (see Schemas and nested paths). A property index on the top-level property is updated with it (an index holds top-level scalar values only).

A write counts one nesting level per path segment below the property, plus the depth of the written value: property(jpath("a.b.c"), [1]) leaves a value three levels deep. The result must stay within the execution option traversal.max_value_depth (default 128), so a stored value is never too deep to read back (see Resource Limits).

Removing: remove_property(jpath(..))

remove_property(key) (and the array form remove_property([k1, k2]), which may mix names and paths) removes the value at a path and lets the element continue, so values(..) can follow. The first segment is the property name, the rest descends into its value.

SituationResult
the last segment is an object key that existsthe key is removed (the parent object stays, even when it becomes empty)
the last segment is [n] / [-k] in rangethe element is removed with shift (Vec::remove); [-1] is the last one
a missing key, a missing top-level property, an out-of-range indexno-op, not an error
a type mismatch on the way (key step on an array, index step on an object, descent through a scalar or null, a non-string-keyed map)no-op: for removal a mismatch means "the path does not exist"
first segment is an index (jpath("[0]"))no-op (it names no property)
a one-segment path (jpath("age"))the same as plain remove_property("age")
a plain string, remove_property("a.b")still a literal key: removes the property named a.b

Removal is deliberately more lenient than writing (where a mismatch is an error): removing something that is not there reaches the desired end state, whereas writing through a wrong container type would have to overwrite data. property(k, null) still stores a null; remove_property is the explicit removal.

g.V("a").remove_property(jpath("meta.k"))          // removes the key k below meta
g.V("a").remove_property(jpath("meta.tags[0]"))    // removes the first element, the rest shifts down
g.V("a").remove_property([jpath("meta.k"), "age"]) // paths and names mix

With no schema the removal mutates the stored value in place (no clone of the top-level property). With a schema active the whole resulting top-level property is validated as described in Schemas and nested paths: a removal that would violate the declaration (a required nested key, min_items, ...) is refused and leaves the property as it was; a path that does not exist never reaches the schema layer. A removal of a whole property (a name or a one-segment path) is the plain removal and is not checked against the schema, like drop(). A property index on the top-level property is updated with it.

properties(jpath(..)).drop() stays an error: a path property element is a materialized leaf and holds no reference to the vertex or edge it was read from, so drop() cannot know what to remove (its help text names remove_property(jpath(..))). Use remove_property on the element instead.

Schemas and nested paths

A schema describes nested content (properties of objects, items of arrays, anyOf members), and every write and removal below a stored property honours it. The three modes:

ModeDeclared nested fieldUndeclared nested key
noneunchecked, nothing is coercedallowed
opencoerced and type/constraint checkedallowed (unless the object says "additionalProperties": false)
closedcoerced and type/constraint checkedrejected (unless the object says "additionalProperties": true), the error names the full path ($.meta.extra)
  • Leaf coercion. property(jpath("meta.w"), 3) coerces the written leaf at the type the schema declares at that location (walking properties by key segments and items by index segments): an int64 becomes a float64 where "number" is declared, a canonical UUID string becomes a uuid where "format": "uuid" is declared. Nothing else converts, no type is guessed from content, and reads never coerce. An undeclared location is not coerced.
  • Validation of the result. The complete resulting top-level property is then validated: nested types, nested constraints (minimum, maximum, minLength, maxLength, pattern, minItems, maxItems, enum, const), and the nested required keys (they must be present in every present object, in open and closed alike, because an object missing a required key does not conform to its declared type). Siblings that were already stored are validated but not re-coerced.
  • Unions. A value is valid when one anyOf member (or one type of a type array) accepts it. When a write path runs through members that declare the location with different types, the member the written value already conforms to exactly wins; with none exact the write is refused with a type mismatch listing the candidates (union<int64|string>). Ambiguity is never resolved by guessing a coercion.
  • Whole objects. property("meta", #{..}) and property_json(..) run the same nested validation (a plain object value is checked at any depth). Without a schema nothing changes.
  • Removal. remove_property(jpath(..)) that leaves the property violating the schema (a required nested key removed, an array below min_items) is refused with the schema error; a removal of something that is not there is a no-op and never errors.
  • Errors. The schema errors keep their variants (TypeMismatch, UndeclaredProperty, MissingRequiredProperty, CoercionFailed, ConstraintViolation) and carry the canonical path ($.a.b[1].c) as the property name; their help texts read the location with jpath(..).
  • Inference and patches. An inferred schema (infer_schema) and a schema changed with patch_schema describe nested types the same way (properties/items at any depth), so nested writes are enforced against them.
// schema: P.meta = {"type": "object", "properties": {"k": {"type": "integer"},
//                     "w": {"type": "number"}}, "required": ["k"]}
g.V("a").property(jpath("meta.w"), 3)          // stored as 3.0
g.V("a").property(jpath("meta.k"), "x")        // error: Type mismatch on vertex 'P.$.meta.k'
g.V("a").property(jpath("meta.extra"), 1)      // Closed: error, Open: stored
g.V("a").remove_property(jpath("meta.k"))      // error: Missing required property '$.meta.k'

json_path() vs jpath

json_path("a.b[1]") is a standalone step: the path is a string argument and it navigates whatever the stream carries (a vertex or edge property, or a materialized map). A jpath key is the same grammar used as the name of the property inside the step that reads it (values, has, by, ...). Both resolve a single target, share one parser, and a missing target produces nothing. json_path() is unchanged and does not take a jpath(..) object.

Errors

ErrorWhenFix
InvalidJsonPath (script error at jpath(..))the text is not a singular query: a..b, a[*], $..x, an unclosed bracket, $, ""the help lists the grammar
InvalidPropertyPath + FirstSegmentNotNamewrite path starts with an index, jpath("[0]")start with the property name
InvalidPropertyPath + KeyOnNonObject / IndexOnNonArraya write meets a value of the wrong kindwrite a whole value at a shorter path first
InvalidPropertyPath + IndexOutOfRange / MissingArray[n] beyond [len], or an index where the array does not exist[len] appends, create the array first
InvalidPropertyPath + CardinalityWithPathproperty(Cardinality.x, jpath(..), v)drop the cardinality
ArgumentMismatcha key that is neither a string nor a jpath(..) (property(5, 1))pass a string or jpath(..)
InvalidModulatorglob_path().by(jpath(..))by("name")
schema errors (TypeMismatch, UndeclaredProperty, MissingRequiredProperty, CoercionFailed, ConstraintViolation)a nested write or removal violates the declared schemathe property name in the error is the canonical path
cast error got type 'pathProperty'drop() / navigation on properties(jpath(..))remove_property(jpath(..))

Reads never fail on a bad path target (see Missing paths); only the text of the path itself can be invalid. Every error above carries a help() with a runnable example.

For storage implementers

A GraphStorage outside the crate sees a parsed path as JsonPath::segments(): a slice of JsonPathSegments (Key(name) for a dot or bracket name, Index(i) for an index, negative counting from the end; the leading $ is not a segment; the enum is #[non_exhaustive]). It does not need to walk them itself: graphersal::storage has the helpers the trait defaults and TraversalGraph use, path_property_name, write_path (on a copy of the top-level property) and write_path_in (in place), remove_path / remove_path_in, with exactly the InvalidPropertyPath faults of the table above, and check_property_value for the written value. A path is built with "meta.tags[-1]".parse::<JsonPath>().

Performance

  • A plain name builds exactly the step it always built (identical .profile() text, same optimizer behaviour). A path key builds a separate step with the same name (has, values, ...) and is never fused or pushed into an index: has(jpath(..)).count() shows has(jpath("$.a.b"), v) then count(), with no count_only. A property index orders top-level values only, so it never serves a jpath key.
  • Reads descend into the stored property by reference and clone only the leaf, never the whole top-level object or array, per traverser. A one-segment path on a vertex keeps the lazy property handle.
  • Writes and removals mutate the stored value in place when the graph has no schema. With a schema active they work on a copy of the top-level property so the complete result can be validated.
  • .profile() shows the optimized plan with the canonical path text, [path: ..] annotations are unrelated (those are traverser paths).

Groovy to Rhai

Gremlin / earlier GraphersalRhai DSL
values('a.b') (a literal key)values("a.b") is still the literal name; a path is values(jpath("a.b"))
has('k', 1)has("k", 1); nested: has(jpath("meta.k"), 1)
valueMap('a')valueMap("a") / valueMap(jpath("meta.k")) (key $.meta.k)
by('age')by("age") / by(jpath("meta.k"))
property('a', v)property("a", v) / property(jpath("meta.tags[0]"), v)
properties('a').drop()remove_property("a") / remove_property(jpath("meta.k"))
.json_path("$.a.b")unchanged, a string argument, no jpath(..) object

The camelCase spellings (hasNot, valueMap, elementMap, removeProperty) and their snake_case twins (has_not, value_map, element_map, remove_property) both take a jpath(..). Rust: g.values(jpath)/g.has(key, v)/g.property(key, v) take impl Into<PropKey> (so "a", String and a parsed JsonPath all work).

UUID Values

A UUID is a value type of its own in Graphersal, not a string that happens to look like one. This page covers how UUIDs are stored, how a query writes one, and how they compare.

Storage model

At runtime a UUID is ElementProperty::Uuid(u128): 16 bytes stored inline, with no heap allocation. A 36-character string would not fit CompactString's inline buffer. Equality and ordering are single integer comparisons.

A UUID stays a UUID end to end, including in the Rhai DSL. A value that next() or to_list() returns to a script has the Rhai type Uuid (type_of(x) == "Uuid"), so you can pass it back into a filter and it still matches:

let x = g.v().values("uid").next();   // a Uuid, not a string
g.v().has("uid", x).count()            // 1

It prints as its canonical string (print(x), `${x}`, x.to_string(), x.as_string()).

Graphersal never infers a type from a string's content. A string that looks like a UUID stays a string until a query or a schema declaration converts it explicitly (see below).

Literals

NotationLiteral
Java GremlinUUID.fromString("550e8400-e29b-41d4-a716-446655440000")
snake_case (Rhai, dot)UUID.from_string("550e8400-e29b-41d4-a716-446655440000")
Rhai static moduleUUID::fromString("…"), UUID::from_string("…")
Rust APIElementProperty::uuid_from_string("…")?

Only the canonical form parses: 8-4-4-4-12 lowercase hex digits, no braces. An uppercase or malformed literal is a cast error, and the error's help shows the canonical form:

UUID.fromString("550E8400-E29B-41D4-A716-446655440000")   // Cast exception: expected type [uuid]

UUID() with no argument is a random UUID (version 4), the Gremlin grammar's UUID() and Java's UUID.randomUUID(): g.inject(UUID()). It draws from the operating system's entropy; the random.seed option does not apply to it.

UUID is a reserved name in the script scope, so a script parameter cannot be called UUID.

To convert a stream of canonical strings, use cast(GType::UUID). To go the other way, use as_string():

g.inject("550e8400-e29b-41d4-a716-446655440000").cast(GType::UUID)
g.v().values("uid").as_string()

Strict equality

A Uuid never equals a String. This is the same as TinkerGraph, where UUID.equals(String) is false. A filter never raises an error on a type difference; it just does not match:

g.v().has("uid", "550e8400-e29b-41d4-a716-446655440000")                   // finds nothing
g.v().has("uid", UUID.fromString("550e8400-e29b-41d4-a716-446655440000"))  // finds the vertex

The same holds for P.eq, P.neq, P.within, P.without and is(..). Each of them accepts a UUID literal. In the Rust API the predicate value is PValue::Uuid(bits).

Reads never coerce, even when a schema declares the field uuid. If a has(..) on a UUID field finds nothing, check whether the query passes a plain string where it should pass UUID.fromString(..).

order() sorts UUIDs by their u128 value. That order is the same as the lexicographic order of their canonical strings. dedup() and group_count() key by the UUID value. A group_count() result is a map whose keys keep their type: m[UUID.fromString(..)] reads an entry, and the table prints a UUID key in its canonical form (see Maps With Non-String Keys).

Coercion on write

JSON has no UUID type. property_json(#{uid: UUID.fromString(..)}) therefore writes the canonical string. What gets stored depends on the schema mode:

  • In None mode (no schema), the string is stored as a String.
  • In Open or Closed mode, a field declared uuid converts a canonical string to a Uuid before validation. This applies to property_json and to property(..) alike. A non-canonical string is rejected.

GraphSON import and export

GraphSON has a UUID type: export writes a Uuid as {"@type": "g:UUID", "@value": "<canonical text>"} and import reads it back as a Uuid without any schema (an upper-case payload is accepted). A plain string stays a string unless the target graph's open/closed schema declares the property uuid, which coerces it on write like any other write.

GraphML import and export

GraphML has no UUID type either. Export writes a Uuid as its canonical string under a key with attr.type="string". Import restores a Uuid only from a declaration: load the schema into the graph before importing the file (set_schema(..)), and every <data> value of a property that the schema declares uuid is converted, whatever the schema mode. For a vertex with several labels the first label that declares the property decides. Without a declaration the value stays a String; the importer never guesses a type from the text. A declared uuid whose text is not canonical fails the import with an InvalidAttributeValue error that names uuid as the expected type.

GraphML is an exchange format and carries no schema: export writes the elements only, and import never reads a schema from the file (graph-level <data> values are ignored). The schema travels separately as its own JSON text (the schema format): save it next to the GraphML file and set it on the target graph before importing, then the declared types come back:

let mut target = GraphSource::empty();
target.write().set_schema(GraphSchema::from_json(&schema_json)?)?;   // 1. the schema
target.import_graphml_reader(std::io::Cursor::new(graphml_text))?;       // 2. the graph

In Python the schema is a keyword of the load (a mapping or JSON text; mode replaces its own mode), or set it on a live graph and import into it:

typed = graphersal.Graph.from_graphml("items.graphml", schema=json.load(open("items.schema.json")))
# or: graph.set_schema(schema); graph.import_graphml("items.graphml")   # one unit, all or nothing

The command line does the same with graphersal --graph items.graphml --schema items.schema.json. The browser playground's Save menu downloads these two files (Data as GraphML, Schema), and its "Load from file" dialog takes both: the schema file is set on the new graph before the GraphML file is imported.

The other value types are written as their own text: dates and times as their canonical text (restored like a uuid, from a declared format; see Dates and Times), true/false, integers as long keys (GraphML's int is 32-bit), floats as double keys, and arrays and objects as JSON text under a string key. A property whose type differs between labels is written under a string key, so an integer there comes back as the string of its digits. A property the target's schema declares array or object (also as a member of a union) is read back from that JSON text and must conform to the declared type (IOError::InvalidJsonValue names the property when the text is not JSON); without a declaration the JSON text stays a string. A union of a container and a text type (string/uuid/a date or time type, e.g. union<string|array<int64>>) cannot be imported, because its GraphML text could be either (IOError::AmbiguousContainerImport): declare one of the two. NaN and infinite floats cannot be exported.

String operations do not apply

The string steps to_lower(), to_upper(), trim(), l_trim(), r_trim(), substring(), replace() and length() raise a cast exception on a UUID (got type 'uuid'). Convert with as_string() first if you really want string operations.

The text predicates (TextP.containing, starting_with, ending_with and their negations) evaluate to false on a UUID and do not raise an error. TinkerPop behaves the same way, because a text predicate never matches a non-string value.

Multi-Label Vertices

Gremlin/TinkerPop vertices carry exactly one label. Cypher and GQL vertices (nodes) carry a set of labels: MATCH (n:A:B) matches a node tagged with both A and B, and SET n:Admin adds a label to an existing node without touching the others. Graphersal's storage carries a vertex's labels as an ordered, deduplicated set — zero, one, or many — so that the GQL front end sits on top of the same storage: MATCH (n:A&B) (Cypher (n:A:B)) tests a vertex's label set.

This page documents storage and Gremlin-facing behavior. g.gql() reads label sets with GQL label expressions and creates multi-label nodes with INSERT (n:A&B) (Cypher CREATE (n:A:B)) and changes the labels of an existing node with SET n:Admin and REMOVE n:Admin (Writing with GQL); the Gremlin steps below do the same.

Creating a multi-label vertex

add_v() accepts a single label, a list of labels, or none:

g.addV("Person")                    // one label
g.addV(["Person", "Admin"])         // two labels, in the given order
g.addV()                            // no label
graph.traversal_mut().add_v(vec!["Person", "Admin"]).next()?;

Labels are a set, not a multiset: adding the same label twice is a no-op, not an error, and the first label ever assigned is the vertex's primary label.

label() vs labels()

  • label() returns the vertex's single primary label — the first one it was given. This matches TinkerPop's single-valued label() contract, and is what elementMap()'s "label" key keeps returning too (valueMap() returns properties only, with no id or label key). Unaffected by this feature for single-label vertices.
  • labels() returns the full ordered label set as a list. For a single-label vertex this is a one-element list; for an unlabeled vertex, an empty list. On an edge (which always carries exactly one label), labels() returns a single-element list for parity with the vertex side.
g.addV(["Person", "Admin"]).label()    // "Person"
g.addV(["Person", "Admin"]).labels()   // ["Person", "Admin"]

has_label()'s OR-over-set semantics

has_label(a, b, ...) matches a vertex whose label set intersects the candidate set — true iff any candidate label is one of the vertex's labels. For a single-label vertex this is exactly the old "does my one label equal any candidate" check, so single-label queries behave identically to before multi-label support existed. Under multi-label, it generalizes correctly:

g.addV(["Person", "Admin"]).hasLabel("Admin")              // matches
g.addV(["Person", "Admin"]).hasLabel("Person", "Admin")    // matches (either is enough)
g.addV(["Person", "Admin"]).hasLabel("Person").hasLabel("Admin")  // matches (both filters pass independently)

Changing the labels of a vertex

The steps add_label("L")/addLabel and drop_label("L")/dropLabel add or remove a single label on an existing vertex (Graphersal extensions, TinkerPop has no such steps; see add_label, drop_label, set_label):

g.V("1").add_label("Admin").labels().next()    // ["person", "Admin"]
g.V("1").drop_label("person").label().next()   // "Admin"

They call GraphStorage::add_vertex_label/remove_vertex_label, which GQL's SET n:Admin/REMOVE n:Admin use as well.

Both methods go through the schema and commit only on success (Ok(true)/Ok(false) as before): the vertex must be valid under the new label set. Adding a label fails when it is undeclared in a Closed schema, when a field it newly requires is missing, or when an existing property contradicts its declared type; removing a label fails in Closed mode when it would leave the vertex without a label or with properties no remaining label declares. An undeclared label is allowed in Open mode. In Closed mode a label change is also rejected when it would make an incident edge violate its declared connections (see Schemas).

Schema

The schema's vertices stay keyed by a single label string — there is no composite multi-label schema constraint (a rule requiring two labels to co-occur, for example). Instead, schema inference and validation treat each of a multi-label vertex's labels independently:

  • Inference contributes the vertex's properties to every label bucket it carries.
  • Required keys are enforced in open and closed mode alike, per label: each label's own required list must be present (on add, on set and on removal); whether null is allowed is the declared type's business, independent of required.
  • Undeclared properties: a top-level key that no label declares is allowed when ANY of the vertex's labels admits additional properties (the mode's default, or the label schema's own additionalProperties), the same "any label" rule as edge topology. closed also requires every label the vertex carries to be declared.
  • Coercion on write (Open and Closed mode, on add and on property()) follows the declaration of the first label, in the vertex's label order, that declares the key: a canonical UUID string becomes a uuid, an int64 becomes a float64. The coerced value is then type-checked against every label that declares the key, so conflicting declarations (A.k a uuid, B.k a string) are reported as a type mismatch.

GraphML representation

GraphML has no native list-valued attribute type. Graphersal represents multiple vertex labels by joining them into the same labelV attribute value with a "::" delimiter:

<data key="labelV">Person::Admin</data>

A single-label vertex round-trips to an unqualified value with no delimiter, byte-for-byte identical to a graph with no multi-label vertices. Because "::" is the delimiter, a label containing the literal substring "::" is rejected at add_vertex/insert_vertex/add_vertex_label time with a clear error, rather than silently corrupting a later export.

This delimiter convention is vertex-only — edges keep exactly one label in both Gremlin and Cypher, and edge_label()/the edge schema/edge GraphML export are untouched by multi-label support.

GraphSON representation

GraphSON uses the same convention, as Amazon Neptune does: export writes "label":"Person::Admin", and import splits a "::" label into the label set (empty parts are dropped). TinkerGraph has no label sets and reads "Person::Admin" as one opaque label.

Property Elements

This page lists where Graphersal's property elements differ from Apache TinkerPop 3.8.2. Everything not listed follows Dedup.feature and AsString.feature.

properties() yields property elements; properties(jpath(..)) yields a path property element, see Path Keys (jpath).

properties() yields property elements. A property element is not its value: it has an identity, key()/value() and a text form. values(), id(), label() and labels() yield plain values. dedup(), as_string() and set side effects (withSideEffect("a", Set.of())) tell the two apart:

g.V().properties("name").dedup()          // by identity: three "josh" vertices stay three
g.V().values("name").dedup()              // by value: one "josh"
g.V().properties("name").asString()       // "vp[name->marko]"
g.E().properties("weight").asString()     // "p[weight->0.5]"
g.V().asString()                          // "v[1]"
g.E().asString()                          // "e[0][1-knows->2]"

Labels and ids of property elements

The label of a vertex property is its key, as in TinkerPop, where a vertex property is an element:

g.V().properties().label()                // "name", "age", ...
g.V().properties().hasLabel("name")       // the name properties
g.V().properties().hasLabel(())           // empty: a null label matches nothing
g.V().properties().id()                   // error: property elements have no id
g.V("1").properties("name").element().id()  // "1": the owning vertex

Only elements from properties() have a label. A plain value (values("name"), or the output of id()/label()) and an edge property are not elements, and label()/hasLabel() fail on them with a cast error. Other label readers (has(T.label, ..) and the token predicates) do not take property elements and are unchanged.

by() tokens over property elements

by(T.label) over properties() is the key, like label(), so it works in order(), group(), dedup(), project() and the other by() steps:

g.V().properties().order().by(T.label)               // sorted by key: age, lang, name
g.V().properties().group().by(T.label).by(__.count())

by(T.id) over property elements is an error with the same help as id() (there are no property ids). by(T.label) or by(T.id) over a value that is not a vertex, edge or vertex property (values("name")) is an error too, as in TinkerPop (TokenTraversal throws IllegalStateException, read from the 3.7.2 bytecode; the 3.8.2 feature files agree): it is never a silently dropped traverser. A missing property key, or a child traversal that yields nothing, still drops the traverser (TinkerPop 3.6+).

by(T.key) and by(T.value) read a property element's key and value, as in TinkerPop 3.8:

g.V().properties().order().by(T.key, Order.desc).key()   // name, name, ..., lang, lang, age, ...
g.V().properties("name").dedup().by(T.value).count()       // distinct names

Both also read a map entry (unfold() of a map: its key and its value) and a properties(jpath(..)) value (its path and its leaf). Any other value is a cast error, as in TinkerPop: a vertex, a number, and also a values(..) result, which is the plain value, not a property element. To order or deduplicate plain values, use by() with no argument:

g.V().values("age").order().by(T.value)    // cast error: expected a property element or a map entry
g.V().values("age").order().by()           // 27, 29, 32, 35

has() on property elements

has(key), has(key, value), has(key, P) and hasNot(key) on a property element address the property's own value: the key inside an object-valued property, never another property of the owning element. Graphersal has no meta-properties, so this is where has() looks instead:

// vertex: a = 100, meta = {a: 1, b: "x"}
g.V().properties("meta").has("a", P.eq(1))      // matches: meta.a is 1
g.V().properties("meta").has("a", P.eq(100))    // empty: the top-level `a` is not read
g.V().properties("meta").has("a")               // meta has a key `a`
g.E().properties("info").has("w", P.gt(1))      // the same for edge properties

A missing nested key filters the traverser out; a property whose value is not an object is a cast error (expected type [object], got type 'string'). For a deeper path use a jpath key on the element, has(jpath("meta.a"), P.eq(1)), see Path Keys (jpath).

valueMap tokens

valueMap(true, keys..) starts each map with the element's T.id and T.label entries, which are plain values, not lists (written "id" and "label" outside the engine; a property named id or label is an entry of its own, see Properties Named id or label). by() modulates only the property lists, never the tokens. A leading false is the plain valueMap(keys..). A null key (() in Rhai) matches no property and is dropped.

g.V("1").valueMap(true, "name")           // {id: "1", label: "person", name: ["marko"]}
g.V("1").valueMap(true).by(__.unfold())   // {id: "1", label: "person", age: 29, name: "marko"}
g.V("1").valueMap("name", ())             // {name: ["marko"]}

In Rust: value_map_with_tokens(args).

Deviations

  • A vertex property's identity is the vertex and the key. A graph stores one value per key, so that pair is the property id. TinkerPop gives every property instance its own id; there is no multi-property (Cardinality.list/set) here.
  • dedup() of an edge property compares key and value, as TinkerPop's Property.equals does: the same weight on two edges is one result.
  • A set side effect keeps an edge property by identity (its edge and key). TinkerPop compares edge properties by key and value, so withSideEffect("a", Set.of()).E().properties() keeps the same weight of two edges twice here and once there. values() is by value in both.
  • has(key, ..) on a property element reads the key inside the property's object value. TinkerPop tests the property's meta-properties there (and an edge property has none). Graphersal has no meta-properties, so properties("meta").has("a", P.eq(1)) addresses meta.a, never the owning element's top-level a; a non-object value is a cast error.
  • key() and value() also accept a plain value that came from values(key). TinkerPop rejects them there, because values() yields no property. Graphersal keeps the lazy handle that values(key) produces for speed and lets these two steps read it.
  • Number text follows the string cast, not Java's toString. The value inside vp[..]/p[..] is as_string()'s text of the stored value: 29 for an integer, and a float with no fractional part prints without .0 (TinkerPop: p[weight->1.0]).
  • as_string() of a map or a list is not Java's Map.toString. valueMap().asString() does not give {name=[marko]}; a map or list is a cast error. as_string(local) over a list converts each element with the rules above.
  • A property whose value is missing or null renders null inside the brackets (vp[name->null]); TinkerPop never holds such a property.
  • Property elements have no id. Graphersal has no property ids, so properties().id() is an error whose help names key() and element().id(); TinkerPop returns an opaque property id. No synthetic id is invented: it could never equal TinkerPop's and could not be fed back into V() or hasId(). Orderability::g_V_properties_order_id stays failing for this reason (it is a deliberate incompatibility).
  • order() of property elements sorts by value only. TinkerPop orders Property elements by their own total order (key, then value, with cross-type rules) and by property id; here properties().order() compares the values, so Orderability::g_E_properties_order_value, its by(desc) twin and the two path().order().by(..) scenarios differ. Those scenarios, and g_V_properties_order_id, are deliberate incompatibilities.
  • label() and hasLabel() work for vertex-property elements only. Edge properties are plain properties in TinkerPop and stay errors, as do value handles from values().
  • valueMap(null) alone means all keys. In Java the single-null varargs call is ambiguous; here a null key is dropped wherever it stands, so a lone null leaves no key and selects every property.

Properties Named id or label

Every vertex and edge has an id and a label. They are not properties: id() and label() read them, and the tokens T.id and T.label name them. A property may still be called id or label (or labels); like TinkerPop, Graphersal accepts these keys and keeps such a property apart from the element's own id and label.

The rule in one line: a string names a property, a token names the element's id or label.

Writing

property(), property_json(), add_v()/add_e() with properties and mergeV()/mergeE() maps store a property named id or label like any other. It changes neither the element's id nor its label:

g.add_v("person").property("name", "Bill").property("label", "CUSTOM").label().next()       // "person"
g.add_v("person").property("name", "Bill").property("label", "CUSTOM").values("label").next() // "CUSTOM"

To set the id or the label, use add_v(label), add_e(label), set_label() (edges), add_label()/drop_label() (vertices) or the "T.id"/"T.label" keys of a mergeV() map.

Reading

Reads the property named id / labelReads the element's id / label
values("id"), values("label"), values()id(), label(), labels()
properties("label"), properties()
has("label", "x")has_id(..), has_label(..)
by("id"), by("label")by(T.id), by(T.label)
select("id"), select("label") on a mapselect(T.id), select(T.label) on an element_map() map
g.add_v("person").property("label", "CUSTOM").values().to_list()                            // ["CUSTOM"]
g.add_v("person").property("label", "CUSTOM").project("p", "t").by("label").by(T.label).next() // #{"p": "CUSTOM", "t": "person"}
g.V("1").project("p").by("label").to_list()                                                 // [#{}]: marko has no property label
g.V().group_count().by(T.label).next()                                                      // #{"person": 4, "software": 2}

by("label") is unproductive on an element without a property named label, like any other missing property (group_count().by("label") counts nothing). Use by(T.label) for the label.

element_map() and value_map(true)

As in TinkerPop, the map element_map() builds holds the id and the label under the tokens T.id and T.label, and an edge's endpoints under Direction.OUT and Direction.IN (each a map of the endpoint's T.id and T.label). The properties follow under their names, so a property named label is an entry of its own. value_map(true) holds T.id and T.label the same way.

g.add_v("person").property("name", "Bill").property("label", "CUSTOM").element_map().count(Scope.local).next() // 4
g.add_v("person").property("name", "Bill").property("label", "CUSTOM").element_map().select("label").next()    // "CUSTOM"
g.add_v("person").property("name", "Bill").property("label", "CUSTOM").element_map().select(T.label).next()    // "person"
g.V("1").element_map().select("label").to_list()                                                               // []: no property label
g.E("0").element_map().select(Direction.OUT).next()                                                            // #{"id": "1", "label": "person"}

select(T.id), select(T.label), select(Direction.OUT) and select(Direction.IN) are a Graphersal extension (TinkerPop's select() takes no token): each takes one token alone and reads that entry of the map; a value without it is filtered. by(T.id)/by(T.label) read the same entries (element_map().order().by(T.label)).

When the map leaves the engine

Outside the engine (a script value, a table, JSON in the playground, Python, MCP) a map has string keys only. The tokens are then written "id", "label", "OUT" and "IN", the way TinkerPop's untyped JSON writes them:

g.E("0").element_map().next()
// #{"IN": #{"id": "2", "label": "person"}, "OUT": #{"id": "1", "label": "person"}, "id": "0", "label": "knows", "weight": 0.5}

When a property has the same name, the property wins: the written map shows the property's value under "id" or "label", and the element's own value is not in it. Naming a property id or label is taken as the wish to see it there. To get the element's id or label in that case, read it with a token (select(T.label), project("l").by(T.label)) or with id()/label(), or give the property another name.

g.add_v("person").property("name", "Bill").property("label", "CUSTOM").element_map().next()
// #{"id": "7", "label": "CUSTOM", "name": "Bill"}: the property, not the label person
g.add_v("person").property("name", "Bill").property("label", "CUSTOM").element_map().unfold().to_list()
// [#{"id": "7"}, #{"label": "person"}, #{"name": "Bill"}, #{"label": "CUSTOM"}]: both entries

Steps that work on the map keep the tokens apart from the names: unfold(), count(Scope.local), order(Scope.local), select(). Only an entry key taken out of the map as a value (select(Column.keys), an unfolded entry's key) is the written string "label".

Vertices and edges returned as values

A vertex or an edge returned by a terminal (to_list(), next()) keeps its id and label apart from its properties too: v.label is the label, v["label"] the property, and a table shows a same-named property in a column label (property). See Vertices and Edges as Values.

Vertices and Edges as Values

A traversal yields vertices and edges as live references into the graph. When a terminal returns them (to_list(), next(), execute()), each becomes a value: a detached copy of the element, as in TinkerPop. The copy keeps the element's own id and label apart from its properties, so a property named id or label never takes their place (see Properties Named id or label).

VertexEdge
Own fieldsid, label (the primary one), labels (the full set)id, label, outgoing vertex, incoming vertex (each an id and a label)
Propertiesa snapshot of every propertya snapshot of every property
Prints asv[1]e[0][1-knows->2]
Equal toanother vertex of the same idanother edge of the same id

Property values may be nested objects and lists, on edges exactly as on vertices.

In a script

A vertex is a Vertex, an edge an Edge. The getters read the element; the index reads the properties:

g.V("1").next().id                       // "1"
g.V("1").next().label                    // "person"
g.V("1").next().labels                   // ["person"]
g.V("1").next()["name"]                  // "marko"
g.V("1").next().properties               // #{"age": 29, "name": "marko"}
g.E("0").next().out_v.id                 // "1"  (also outV; in_v / inV)
g.E("0").next()["weight"]                // 0.5

v.name works too, for a name that is not one of the getters (id, label, labels, properties, and on an edge out_v/outV/in_v/inV): it falls back to the index. So v.label is always the label and v["label"] always the property:

g.addV("person").property("label", "CUSTOM").next().label        // "person"
g.addV("person").property("label", "CUSTOM").next()["label"]     // "CUSTOM"

A missing property reads as (). An edge's endpoints (e.out_v, e.in_v) are VertexRefs: id and label only, printed v[1].

Passing a value back

A vertex or an edge value stands for its element when it goes back into a query, as a detached element does in TinkerPop: g.V(v), has_id(v) and g.inject(v) reach the stored element of its id.

let v = g.V("1").next();
g.V(v).values("name").next();            // "marko"
g.inject(v).out().count().next()         // 3

A value is a snapshot: it does not change when the graph does, and reading it reads no graph data. To read the current state, pass it back into a query; that query asks Read on the element's data like V() does (Permissions).

In the results: tables and JSON

A table shows a vertex as the columns id, label and one column per property; an edge as id, label, outV, inV and its properties. A property named like one of those columns gets its own column headed <name> (property):

$ graphersal -e 'g.addV("person").property("name", "Bill").property("label", "CUSTOM")'
╭────┬────────┬──────────────────┬──────╮
│ id │ label  │ label (property) │ name │
├────┼────────┼──────────────────┼──────┤
│ 7  │ person │ CUSTOM           │ Bill │
╰────┴────────┴──────────────────┴──────╯

JSON (the playground, the dev server, MCP, to_json()) writes the untyped GraphSON 3 shape:

{"id": "1", "label": "person", "properties": {"name": "marko", "age": 29}}
{"id": "0", "label": "knows", "inVLabel": "person", "outVLabel": "person",
 "inV": "2", "outV": "1", "properties": {"weight": 0.5}}

A vertex with more than one label adds "labels": [..] after "label" (a Graphersal extension: TinkerPop has one label per vertex). "properties" holds each value directly: Graphersal keeps one value per key and has no property ids, so there is no list of vertex-property objects as in GraphSON ({"name": [{"id": .., "value": "marko"}]}).

In Python

The same values are graphersal.Vertex and graphersal.Edge, like gremlin-python's:

v = graph.query('g.V("1").next()')
v.id, v.label, v.labels      # ('1', 'person', ['person'])
v["name"], v.properties      # ('marko', {'name': 'marko', 'age': 29})
e = graph.query('g.E("0").next()')
e.out_v, e.in_v.id, e["weight"]   # (v[1], '2', 0.5)
graph.query('g.V(v).values("name").toList()', params={"v": v})   # ['marko']

v["missing"] raises KeyError. A Vertex/Edge can be a parameter; it stands for its element.

In Rust

A terminal returns ElementProperty::Vertex(Box<VertexValue>) and ElementProperty::Edge(Box<EdgeValue>): id(), label(), labels() (vertex), out_v() / in_v() (edge, each a VertexRef) and properties().

Traversal Patterns

The chapters of this section describe the steps that shape a walk through the graph: loops, labels and paths, branches, side effects and the sack. Several of them are short pages about the exact rules in a corner of TinkerPop's semantics and the few places where Graphersal differs.

PageWhat it covers
Recursive Traversalsrepeat() with times(), until(), emit(), loops(); breadth and depth first
Bulk and Barriershow equal traversers are merged, barrier(), why it stays invisible
where() Start and End Labelswhere() with labels and predicates, filter() versus where()
Repeated Labels: select with Popselect(Pop.first/last/all/mixed, ...), the Groovy copy-paste table
Path Windowsfrom()/to() on path(), simple_path(), cyclic_path()
union() as a Start Stepg.union(...) without v()
Branch Children and Global Statehow union(), choose() and branch() feed their children
Option Keys of choose() and branch()option() keys and unmatched traversers
The by() Modulator: Single-by Stepssteps that take one by()
Set Side Effects, tree() as a Side Effectaggregate(), store(), cap(), tree("key")
Sack and Operatorswith_sack(), sack(), Operator, reducers

Recursive Traversals

See the Execution Options Reference for the full table of every g.with() key, including repeat.order and repeat.max_loops below, and how a host can lock either one so a query cannot override it.

repeat() loops a traversal: the output of each iteration is the input of the next. With it you can write variable-length paths, walk hierarchies, compute a transitive closure, and search breadth first or depth first. Graphersal follows the semantics of TinkerPop's RepeatStep, including where the modulators times(), until() and emit() are written.

g.V("1").repeat(__.out()).times(2)                                  // two hops away
g.V("1").repeat(__.out()).until(__.has("name", "ripple")).path()    // the route to ripple
g.V("1").emit().repeat(__.out("knows")).times(2)                    // marko, josh, vadas

The script DSL and the Rust API use the same step names, with these Rust spellings for the overloads Rust cannot express:

ScriptRust
repeat(__.out())repeat(__::out(None))
repeat("a", __.out())repeat_named("a", __::out(None))
times(2)times(2)
until(__.has("name", "x"))until(__::has("name", "x"))
emit()emit()
emit(__.hasLabel("person"))emit_with(__::has_label("person"))
loops()loops()
loops("a")loops_named("a")

For tree-shaped walks, such as a directory tree matched against a pattern like **/src/*.rs, the glob_path() step is shorter than a repeat() loop: it matches the pattern level by level, prunes branches that cannot match, emits each match once and stops on cycles. Where a loop would use times(n), glob_path("**", #{max_depth: n}) bounds the walk to n levels below the start, and prune: __... stops it below matching vertices the way until() stops a loop (see Options). It is a Gremlin extension, not part of TinkerPop.

Stopping and emitting

  • times(n) stops after n iterations. It is until(__.loops().is(n)).
  • until(t) stops a traverser once t yields a result for it. The traverser is output.
  • emit() also outputs every traverser the loop visits, not only those it ends with. emit(t) outputs only the traversers for which t yields a result.
  • Without times()/until(), a traverser goes round until the body yields nothing for it. Without emit(), such a traverser is dropped, not output.

Placement: before or after repeat()

Where a modulator is written decides when it is checked, exactly as in TinkerPop:

  • After repeat() (do-while): the condition is checked after each iteration, so the body runs at least once. repeat(__.out()).times(0) runs the body once.
  • Before repeat() (while-do): the condition is checked before each iteration, the first one included. times(0).repeat(__.out()) returns its input unchanged, and emit().repeat(__.out()) outputs the start vertex too.
WrittenMeaning
repeat(__.out()).times(2)two iterations
times(2).repeat(__.out())two iterations, checked first
emit().repeat(__.out()).times(2)the start and every visited vertex, two iterations
repeat(__.out()).emit().until(__.has(...))every visited vertex, until a match
repeat(__.out()).times(2).emit().repeat(__.in())the emit() belongs to the first loop; the second repeat() is a new loop

When a traverser meets both emit and until at the same check, it is output once. Setting a modulator twice keeps the last one. A modulator with no repeat() before or after it, as in g.V().times(2), fails with RepeatWithoutBody.

Loop counters: loops()

loops() is the number of iterations the enclosing loop has completed for the traverser:

  • 0 before the first iteration and inside its body;
  • k + 1 after the body of iteration k, which is when postfix until()/emit() run;
  • 0 outside any loop, including after a traverser left its loop.

So repeat(__.out()).until(__.loops().is(2)) is repeat(__.out()).times(2), and emit(__.loops().is(P.gt(0))).repeat(__.out()) emits everything except the start.

Nested and named loops

A repeat() can appear in the body, in until()/emit(), or in any child traversal of another repeat(). loops() reads the innermost loop. To read an outer loop, name it:

g.V("1").repeat("a", __.out().repeat("b", __.in()).until(__.loops("b").is(1))).times(2)
g.V("1").repeat("a", __.out().repeat("b", __.in()).until(__.loops("a").is(0))).times(1)

loops(name) reads the nearest enclosing loop with that name. A name no enclosing loop has fails with UnknownLoopName, which lists the active loop names.

Cycles and limits

On a graph with cycles, g.V().repeat(__.both()) never runs out of traversers. Three tools keep loops finite:

  • simple_path() in the body drops every traverser that returns to an element it already visited: g.V("a").repeat(__.out().simplePath()).emit().path().
  • times()/until() bound or stop the loop.
  • repeat.max_loops (10 000 by default) stops a loop without times() with RepeatLimitExceeded: g.with("repeat.max_loops", 100). A loop with times(n) is never limited. evaluationTimeout bounds the wall-clock time of the whole traversal. See Query Limits.

Breadth first and depth first

By default a loop runs breadth first: the body runs once per iteration on all traversers of that iteration, and everything iteration k outputs comes before what iteration k + 1 outputs. Within an iteration, traversers output before the body (prefix emit/until) come before those output after it.

g.with("repeat.order", "dfs") walks the loop depth first instead, in pre-order: a traverser is followed to the end of its loop before its siblings. The walk uses an explicit stack, so deep loops cannot overflow the call stack.

// a tree, children in the order out() returns them: r -> (b -> b1, a -> (a2, a1))
g.V("r").emit().repeat(__.out())                              // r, b, a, b1, a2, a1
g.with("repeat.order", "dfs").V("r").emit().repeat(__.out())  // r, b, b1, a, a2, a1

Both orders return the same results for a body without barrier steps; only the order differs. TinkerPop does not define the output order of repeat() in the same way, so a query that depends on order should sort its results.

dedup() and other barriers in the body

A dedup() in the body keeps one seen-set for the whole loop, like in TinkerPop: an element met again in a later iteration, or reached by another traverser, is dropped. V().repeat(dedup()).times(2) passes every vertex in the first iteration and nothing in the second, and g.V("s").repeat(__.out().dedup()).emit() is a visited set. Both orders (repeat.order) agree, and merging the frontier stays invisible (survivors have bulk 1).

  • Every dedup() step of the body has its own set; a nested repeat() starts a fresh set each time it runs.
  • A dedup() inside a per-traverser child of the body (where(...), not(...), local(...), by(traversal), the until()/emit() conditions) starts fresh for every traverser, like TinkerPop's reset children. A union()/choose() child of the body is not reset.
  • simplePath() is still the way to stop cycles.

Other barriers in the body (limit(), range(), tail(), count()) run once per iteration in breadth-first order, like TinkerPop 3.8.2: its feature files expect g.V().repeat(both().limit(1)).times(2) to return one traverser and repeat(union(constant('y').limit(1), identity())).times(2) to return y twice, which a loop-wide counter would not give. In depth-first order (g.with("repeat.order", "dfs"), which TinkerPop does not have) such a barrier sees one traverser at a time, so a limit() there limits each traverser's walk, not the iteration. Only dedup() keeps loop-wide state.

Merging the frontier

In breadth-first order the loop merges equal traversers of the frontier (the same vertex reached by different routes) into one traverser with a bulk, before until()/emit() are checked. The next iteration then expands each distinct vertex once, so repeat(__.out()).times(8).count() on a dense graph stays cheap. The results are the same multiset as without merging; only the order of duplicates can change. Merging does not happen in depth-first order, when the plan records full paths (path(), simplePath()), or when it mutates the graph. This is not a visited set: unlike dedup(), every route still counts. A sack merge operator or withBulk(false) turns the frontier merge off; write repeat(__.out().barrier()) to merge per iteration. See Bulk and Barriers and turn it off with g.with("bulk.merge", false).

Paths and labels

Every step of the body extends the path of its traversers, so path() after a loop shows the whole route. as("x") in the body labels the position of every iteration, and select("x") returns the last one. The path requirement analysis treats the body as loop-carried; see Path Requirement Analysis.

Profiling

.profile() shows the loop as written, with the body and the until()/emit() traversals as children. Their counts and times add up over all iterations. The loop summary line reports the number of body executions, the deepest iteration reached, and the average loop count of the output traversers:

repeat(__.out()).times(2)            1   1   2
[loops: 2, max_depth: 2, avg_loops: 2.0]
  \> out()                           2   4   5

repeat() and inject()

inject() cannot be a direct step of a repeat() body, because the injected values would enter again in every iteration. Graphersal raises TraverserError::RepeatInject when the traversal executes (not when it is built). An inject() nested deeper, for example inside union(..), is allowed:

g.V("1").repeat(__.inject(1)).times(2).toList()                         // error
g.V().repeat(__.union(__.identity(), __.inject("y"))).times(2)           // fine

A repeat() body that updates a sack (sack(Operator.sum).by(..)) keeps the sack of each traverser through every iteration; see Sack and Operators.

Bulk and Barriers

Every traverser carries a bulk: how many identical traversers it stands for. When two traversers are equal (the same vertex, reached by different routes), the engine can keep one of them with bulk 2 instead of processing both. A step that expands the survivor does the work once, and a count() adds up the bulks. This is the same idea as TinkerPop's traverser bulk.

Without it, repeat(out()).times(8).count() on the grateful-dead graph would have to walk about 2.5 * 10^15 paths. With it, the loop never holds more than one traverser per distinct vertex:

g.V().repeat(__.out()).times(8).count().next()    // grateful graph: 2505037961767380 in milliseconds

Bulk is invisible

A query returns the same multiset of results with and without merging. Merging is an optimization, never a semantic change. Only the order of duplicates can change: equal traversers are emitted together, at the position of their first occurrence.

g.V().both().both().values("name").groupCount().next()                   // josh 7, lop 7, marko 7, ...
g.V().both().both().barrier().values("name").groupCount().next()         // the same counts

Steps that need every value as its own item (fold(), aggregate(), store(), a terminal toList(), group() value lists) expand a merged traverser back into one value per unit of bulk. Steps that can work on the multiplicity directly (count(), sum(), mean(), groupCount(), limit(), ...) never expand it.

Where traversers are merged

Merge pointWhat it is
barrier() / barrier(n)An explicit merge point you write yourself.
the repeat() frontier(off with a sack merge operator or withBulk(false)) In breadth-first order, the starting traversers and the output of every iteration are merged before until()/emit() are checked. Depth-first repeat() never merges.
lazy_barrier()(off with a sack merge operator or withBulk(false)) Inserted by the lazy_barrier optimizer rule between adjacent steps such as out().out().

.profile() shows a Bulk column next to Out when some step's bulk differs from its traverser count, and names the inserted steps:

g.V().both().both().barrier().profile()

dedup() is not a merge: every survivor gets bulk 1.

What prevents merging

Two traversers merge only if nothing later in the query can tell them apart.

  • Full paths. path(), simplePath() or an as() label that is read later make every traverser carry its own history, so none are equal. The merge pass is skipped. See Path Requirement Analysis. g.V().out().out().path() does not merge.
  • Containers. Arrays, maps, records, entries, paths and schemas are never merged (hashing them costs per item and they are not where explosions happen). Vertices, edges, properties and scalar values merge.
  • Mutating traversals. If the plan contains addV(), addE(), property(), drop(), mergeV() or another mutation, nothing merges, so every logical traverser runs its mutation.

barrier() and barrier(n)

g.V().out().barrier().out().values("name").toList()

barrier() merges the whole stream at that point. barrier(n) is accepted for TinkerPop compatibility; n must be an integer of at least 1, and it is shown in .profile(), but it does not cut the stream into chunks of n: the whole stream is merged at once. Because our engine already materializes each step's stream, the size only affects TinkerPop's unspecified order of grouped duplicates, so it is not implemented. barrier(0) fails with barrier(0): the size must be an integer from 1 to 4294967295.

Options

OptionDefaultMeaning
bulk.mergetruefalse turns every merge point into a pass-through. The result is the same, only slower on dense graphs. Use it to diagnose or to compare.
bulk.onefalsetrue (g.withBulk(false)) makes a merge keep bulk 1 (duplicates collapse and are emitted once), stops sacked traversers from merging, and switches the automatic merge points off. A strict boolean. See Sack and Operators.
bulk.max_expansion10 000 000The most values a step may produce when it expands a merged traverser into single items. Larger expansions fail with BulkExpansionLimit.
traversal.max_materialized_bytes1 GiB (256 MiB on wasm32)The memory the query holds at once (live bytes), an expansion included: one that would take it over the limit fails with ResourceLimitExceeded before anything is allocated. See Resource Limits.
g.with("bulk.merge", false).V().both().both().count().next()                 // same 30, no merging
g.with("bulk.max_expansion", 5).V().both().both().barrier().toList()         // fails: 30 values > 5

The second query fails with: Step 'to_list' would have to materialize 30 values, more than the limit of 5 (bulk.max_expansion). The limit exists because a merged traverser is cheap but its expansion is not: one record with bulk 10^12 would otherwise try to build 10^12 values and exhaust memory. The error message suggests count(), groupCount(), dedup() or limit(n) before the step, or raising the limit with g.with("bulk.max_expansion", n) when you really need every value and have the memory.

Both options are listed in the Execution Options Reference.

Rust callbacks: side_effect(SideEffectFn)

The Rust API's side_effect(func) (no DSL form: a Rhai script uses sideEffect(traversal)) calls func(&value, bulk) once per traverser, as TinkerPop's sideEffect(Consumer) does: after a merge point a traverser with bulk 3 is one call with bulk == 3. A callback that counts adds bulk, and its total is then the same with and without merging. A failure later in the traversal rolls back the writes of the unit; what the callback itself did outside the graph stays.

Overflow

Bulks are u64 and all arithmetic is checked. A bulk or total that does not fit fails with BulkOverflow instead of wrapping. A count() above i64::MAX fails the same way.

Differences from TinkerPop

  • Mutations never merge. In TinkerPop, addV() after a barrier creates one vertex per merged traverser. Graphersal creates one vertex per logical traverser.
  • Side-effect children run once per logical traverser. A child traversal that writes a side effect (for example local(__.aggregate("x"))) runs bulk times for a traverser with bulk bulk, so the side effect has the same content with and without merging. This holds for the child of sideEffect(traversal) too: sideEffect(__.aggregate("x")) after a bulk-3 traverser aggregates three times (TinkerPop runs it once per merged traverser object); the incoming traverser itself continues unchanged, with its bulk.
  • barrier(n) does not chunk (see above).
  • withBulk(false) is the option bulk.one: merging still happens at an explicit barrier(), the merged traverser keeps bulk 1, and the automatic merge points are off. A sack merge operator (withSack(initial, Operator)) also switches the automatic points off and makes merging part of the result; a loop body then writes repeat(__.out().barrier()). See Sack and Operators.
  • Merge equality is by identity. A vertex merges with the same vertex only. Paths are compared by handle, not by content, so traversers with equal but separately recorded paths do not merge.

A heuristic and its limit

Merging a stream in which nothing is equal is wasted work. The repeat() frontier and lazy_barrier() therefore probe: after the first 4096 traversers, if fewer than one in sixteen merged, the pass gives up and passes the stream through unchanged (and a repeat() stops merging for its remaining iterations). Before that, lazy_barrier() also skips a merge whose duplicates would save the following step less than one output per two traversers (their fan-out on that step, estimated on the same first 4096; see Lazy Barrier Rule). The probes only change speed, never results. Its limit is that it judges the start of a stream. A stream whose first 4096 traversers are all distinct but whose tail contains many duplicates is not merged, and a loop whose early iterations are sparse but later ones dense stops merging early. Use an explicit barrier() (never adaptive) to force a full merge at a chosen point.

Operators, sacks and bulk

fold(seed, Operator) and a side effect declared with withSideEffect(key, init, Operator) apply their operator once per unit of bulk, so merging never changes their result. A sack merge operator and withBulk(false) are the two places where merging is visible on purpose: see Sack and Operators and Merge operator.

where() Start and End Labels

This page lists where Graphersal's where(traversal) start and end labels differ from Apache TinkerPop 3.8.2. Everything not listed follows Where.feature.

In where(__.as("a").out().as("b")) a leading as("a") is a start label: the child starts at the object labelled a (a key of the current map value, a side-effect key, or a path label, in that order, like select()). A trailing as("b") is an end label: the traverser is kept only when some result of the child equals the object labelled b. The same holds for the children of and(), or() and not() when that connective is the first step of the where() child. A start or end label that resolves to nothing filters the traverser out, without an error.

where(P) and by()

where(P) takes by() modulators, and a bare-string operand of any comparison (eq, neq, lt, lte, gt, gte) is resolved as a step label first, then as a side-effect key, and only then taken as a literal text:

g.V("1").as("a").out().has("age").where(P.gt("a")).by("age").values("name")   // ["josh"]

The by() modulators form a ring, as in TinkerPop. The current object is projected through the first by(); each label operand then takes the next one, from left to right in the textual order of the predicate (and, or and not children included), cycling when there are fewer by() than operands:

QueryCurrent objectOperand a
where(P.gt("a")).by("age")ageage
where(P.gt("a")).by("age").by("weight")ageweight
where(P.gt("a").and(P.lt("b"))).by("x").by("y").by("z")xy for a, z for b

A comparison without a label operand (where(P.gt(30)).by("age")) projects only the current object. A by() that yields no value (a vertex without the property, a child traversal with no result) drops the traverser, also under a not(). Without by(), two scalars compare by value (values("age").as("a") followed by where(P.gt("a")) works), however each is held: a computed 29 (g.inject(29).as("x").V().values("age").where(P.eq("x"))) equals a property read with values("age"), and 1 equals 1.0, as P.eq(29) and is(29) compare; the end label of where(__.values("age").as("x")) and where(P.within("side effect")) compare the same way. Two elements compare by identity for eq/neq and are incomparable (false) for an ordering; lists and maps are equal when their contents are. has(key, P.gt("x")), is(P.gt("x")), all() and any() keep comparing literal strings, even when a label x exists.

Deviations

  • The end label is read on the incoming traverser. TinkerPop looks it up on the child's output traverser. Both see the same path labels; they differ only when the child itself defines the label.
  • Several labels on a start or end step are rejected when the query is planned, for both ends. TinkerPop rejects an end step with several labels only.
  • A connective after a start label is an ordinary step. where(__.as("a").and(...)) does not turn the as() calls inside the and() children into labels, as in TinkerPop.
  • Outside a where() nothing changes. An as() at the start or end of the children of not(), and(), or() or union() labels the child's own path.
  • A start label that was never declared. where(__.as("a").out()) with no earlier as("a") filters every traverser out (TinkerPop's missing-key behaviour).
  • No flattening. The optimizer rule where_unnest leaves a where() with a start or end label alone, because the label changes what the child runs on.
  • where(P.gt("a")) resolves the label a for every comparison predicate, the ordering ones included, so it compares against the labelled object, never the text "a".
  • Ring order of composite predicates follows the textual order. where(P.gt("a").and(P.lt("b"))) gives a the second and b the third by() whatever short-circuiting skips. How TinkerPop's connective handling orders its traversal ring was not verified, and no vendored scenario has a composite predicate with by().
  • Not implemented: a by() projection of the operands of within/without.

where("a", P)

The two-argument form tests the object labelled a instead of the current object (TinkerPop's WherePredicateStep with a start key). a is looked up like select("a"): a key of the current map, then a side effect, then the path label (Pop.last); a traverser without it is filtered out. The by() ring starts with that object.

g.V("1").as("a").out("created").in("created").as("b").where("a", P.neq("b")).values("name")
// ["peter", "josh"]
g.V().as("a").out("created").in("created").as("b").where("a", P.gt("b")).by("age").
  select("a", "b").by("name")
// {"a": "josh", "b": "marko"}, {"a": "peter", "b": "josh"}, {"a": "peter", "b": "marko"}

Rust: where_label_p("a", P::Neq("b")).

filter() versus where()

filter(traversal) (Rust filter_t, also __.filter) keeps a traverser when the child traversal yields at least one result, exactly like TinkerPop's TraversalFilterStep. It is not an exact alias of where(traversal):

where(traversal)filter(traversal)
plain childexistence testexistence test (same result)
leading as("a")start label: the child starts at the object labelled aordinary label of the child's own path
trailing as("b")end label: some child result must equal bordinary label of the child's own path
predicate formwhere(P.gt("a"))not accepted
g.V().filter(__.as("a").out("knows").as("b")).values("name")   // ["marko"]
g.V().where(__.as("a").out("knows").as("b")).values("name")    // []: `a` is not labelled outside

Labels declared inside a filter() child are not visible to the outer traversal. The child is optimized and path-analysed like the child of where(); a child that mutates the graph makes the whole query a mutating one. There is no deviation from TinkerPop.

Repeated Labels: select with Pop

A step label can occur several times on one path: as("a") inside repeat() sets it once per iteration, and a query can reuse a name at several steps. select("a") reads the newest occurrence. The Pop token chooses which occurrence select reads, as in TinkerPop:

PopReads
Pop.firstthe oldest occurrence
Pop.lastthe newest occurrence (what select("a") does)
Pop.alla list of every occurrence, in path order; always a list, also for one occurrence
Pop.mixedthe value itself for one occurrence, a list in path order for several

Pop goes first: select(Pop.all, "a"), select(Pop.first, "a", "b") (a map, one entry per label), select(Pop.all, ["a", "b"]).

g.V("1").as("a").repeat(__.out().as("a")).times(2).select(Pop.first, "a").by(__.unfold().id().fold())  // ["1"]  ["1"]
g.V("1").as("a").repeat(__.out().as("a")).times(2).select(Pop.last,  "a").by(__.unfold().id().fold())  // ["5"]  ["3"]
g.V("1").as("a").repeat(__.out().as("a")).times(2).select(Pop.all,   "a").by(__.unfold().values("name").fold())
// ["marko", "josh", "ripple"]   ["marko", "josh", "lop"]

Pop.all returns one list per traverser; the elements stay lazy handles until a terminal materializes them. In Rust:

use graphersal::prelude::*;

let graph = GraphSource::tinkerpop_modern();
let lock = graph.read();
let lists = lock
    .traversal()
    .v("1")
    .as_("a")
    .repeat(__::out(None).as_("a"))
    .times(2)
    .select_pop(Pop::All, "a")
    .to_list()
    .unwrap();
assert_eq!(lists.len(), 2);

select_pop(pop, labels) exists on the traversal source, on AnonymousTraversal and as __::select_pop; select(labels) is Pop::Last.

Lookup order

For each key, select looks in this order, and Pop applies only to the last source:

  1. the traverser's own value, when it is a map that contains the key (valueMap().select(Pop.all, "name") returns the map's list for name, not a wrapped list);
  2. a side effect of that name (aggregate("a"), store("a"), ...);
  3. a path label: here the pop chooses among the occurrences.

If the key is found nowhere, the traverser is filtered out. With several keys, the result is a map and one missing key filters the whole traverser. Several labels on one position (as("a").as("a"), or as("a").has(..).as("a"): a filter adds no position) are one occurrence, so Pop.all has one element for it.

by() applies to the selected value as a whole, never per element: after select(Pop.all, "a") it receives the list. by("name") on a list fails with PropertyNotFound (a list has no properties); use by(__.unfold().values("name").fold()) as above. With several keys the existing by() ring applies (one by() per key in turn, the last one wins for a repeated key).

Notations

The Rhai DSL accepts both the Gremlin (Java/Groovy) and the Rust spellings, so a Gremlin query can be pasted as it is:

SpellingExample
dot (Gremlin)Pop.first, Pop.last, Pop.all, Pop.mixed
:: (Rust style)Pop::first, Pop::all ...
PascalCase aliasesPop.First, Pop::All ...
bare constants (Groovy import static Pop.*)first, last, all, mixed
RustPop::First, Pop::All ..., select_pop(Pop::All, "a")

Notes:

  • The bare names are scope constants, like keys and values for Column. They coexist with steps and methods of the same name (g.V().all(P.gt(0)), [1, 2].all(|x| x > 0)): a constant and a method share no namespace. A script variable named first/last/all/mixed shadows the constant for the rest of the script (after let all = 1, select(all, "a") reads the labels 1 and a, which the undeclared-label diagnostic catches).
  • eval_with_params reserves the class name Pop as a parameter name, but not the bare names (first, last, all are likely parameter names; a parameter named first wins over the constant).
  • Pop must be the first argument. A lone Pop, a Pop in any other position and a non-string label after it are an ArgumentMismatch with a help() that shows the forms, never a silent select("first", "a").
  • Pop.first == Pop::first works (== and != are registered for the token).
  • Only Column (keys, values) and Pop have bare constants in the DSL. Every other token needs its class (Scope.local, Order.desc, Direction.OUT, T.label, Operator.sum): a bare local, desc or OUT is "Variable not found" in a script (the TinkerPop test harness rewrites them, a user query does not).
  • select(Pop, traversal) and select(traversal) take a traversal as the key, see the next section.

A traversal as the key

The key does not have to be a literal: select(Pop.x, <traversal>) and plain select(<traversal>) (TinkerPop's TraversalSelectStep; plain select(traversal) is Pop.last) compute it.

g.V().as("a").out("knows").as("a").select(Pop.all, __.constant("a")).by(__.unfold().values("name").fold())
// ["marko", "josh"]   ["marko", "vadas"]
  • The key traversal runs on the incoming traverser with its path, so it can read labels itself (__.select("k") where k holds the name of the label to read).
  • Its first result is the key; the other results are ignored. No result filters the traverser. A result that is not a string (a vertex, a number) can only be a key of the incoming map, for example group().by().by(..) keyed by vertices: g.V().as("a").group("m").by().by(__.bothE().count()).barrier().select("m").select(__.select("a")). A key that is not found filters the traverser (TinkerPop raises KeyNotFoundException, which select turns into an empty traverser).
  • The key is then looked up exactly like a literal one: a key of the traverser's own map, then a side effect, then a path label read with the Pop (the pop applies to the last source only).
  • One by() applies, the last one, to the whole selected value; a by() that yields nothing filters the traverser. A second by() is not an error (TinkerPop's ring has size 1 and the last modulator wins).
  • Exactly one key traversal is allowed: select(Pop.all, __.constant("a"), "b") is an ArgumentMismatch, as TinkerPop has no such overload.
  • The key is only known at run time, so the plan cannot name the label it needs and records the full path upstream ([path: full] in .profile(), step text select(Pop.all, __.constant("a"))). The plan-time undeclared-label diagnostic does not apply to a traversal key.

In Rust: select_traversal(Pop::All, __::constant("a")) on the traversal source, on AnonymousTraversal and as __::select_traversal; plain select(traversal) is select_traversal(Pop::Last, ..).

Reading a property of every element of a selected list: by("name") is applied to the list itself and fails with PropertyNotFound (the help() of the error shows the recipe). Use a child traversal, .by(__.unfold().values("name").fold()).

How the occurrences are found

Only Pop.last with literal labels keeps the cheap recording: the path analysis records just the labelled positions it needs. Every other pop needs all occurrences, so the plan records full paths upstream of the select (.profile() shows [path: full] on every step before it, and a select text such as select(Pop.all, "a")). Full paths also switch off bulk merging for those steps, so a repeat() that explodes into many equal paths is slower and uses more memory with Pop.all than with select("a"). A plan without a Pop select is not affected. Measured on the 110k-element large graph (g.V().as("a").repeat(__.out().as("a")).times(3)....count(), debug build): execute time 117 ms for select("a"), 164 ms for select(Pop.all, "a") (about 1.4x); these forms record full paths.

Copy-paste cheat sheet

The DSL is Gremlin with Rhai syntax. A Gremlin Groovy line pastes as it is, except for the few places below; the Pop forms need no edit at all.

Gremlin GroovyRhai DSLWhy
select(Pop.all, 'a'), select(Pop.first, "a")the same (Pop.all, Pop::all, Pop.All, Pop::All or bare all)Pop is a registered class; Pop.all and Pop::all are equal
select(first, 'a') (static import)select(first, "a")bare first/last/all/mixed are constants, but a script variable of that name shadows them
'a' single quotes"a"Rhai strings: use double quotes (single quotes are a char literal)
count(local), sum(local)count(Scope.local)bare local exists only through the test-harness translator
order().by(desc), by('age', asc)by(Order.desc), by("age", Order.asc)same: bare asc/desc/shuffle are harness-only
toE(OUT, 'x'), property(list, 'k', 1)toE(Direction.OUT, "x"), property(Cardinality.list, "k", 1)bare token names are harness-only; T.label/T.id already carry the class
by(label), group().by(values)by(T.label), by(Column.values)keys/values also work bare for Column, label does not
where(out()), union(out(), in()), not(has('x'))where(__.out()), union(__.out(), __.in()), not(__.has("x"))an anonymous step needs the __. prefix, also for V() (__.V())
by(constant(1))by(__.constant(1)); never by(1)a literal in by() is a property key (by(1) reads the property 1 and finds nothing), not a constant
1L, 1.5d1, 1.5Rhai integers are 64-bit, floats 64-bit
[1, 2], [a: 1][1, 2], #{a: 1}Rhai object maps use #{ }
g.V().as('a'), hasLabelthe same; as_/has_label also workevery step is registered in both snake_case and camelCase
Rust: select_pop(Pop::All, "a"), select_traversal(Pop::All, __::constant("a"))select(Pop::All, "a"), select(Pop::All, __.constant("a"))the DSL has one select; the token tells which form it is

A snake_case query with a Gremlin token and a camelCase query with a Rust token both work: the receiver spelling and the token spelling are independent (the matrix in tests/all/pop_notation_tests.rs runs every combination).

Deviations from TinkerPop

All also listed in TinkerPop Deviations.

  • Undeclared label. g.V().select(Pop.first, "a") where nothing in the query declares a raises the same plan-time diagnostic as g.V().select("a"); TinkerPop returns nothing. Six map/Select.feature scenarios (g_V_selectXfirst_aX, g_V_selectXfirst_a_bX, g_V_selectXlast_aX, g_V_selectXlast_a_bX, g_V_selectXall_aX, g_V_selectXall_a_bX) are therefore deliberate incompatibilities and leave the compatibility scope. A map-producing step upstream (valueMap(), inject()) disables the check, so g.V().valueMap().select(Pop.first, "a") filters to nothing like TinkerPop (those six scenarios pass).
  • Full path recording (above, and for every traversal key) is a cost difference, not a result difference.
  • Pop.mixed with a list-valued oldest occurrence. TinkerPop's Path.get(label) appends the later occurrences to the stored list in place when the oldest occurrence is itself a list. Graphersal gives the same result (the list's elements followed by the later occurrences) on a copy and never changes the stored value.

The list-valued occurrence

A label whose single occurrence is itself a list (g.V("1").values("name").fold().as("a")) is returned whole by first, last and mixed, and all wraps it: [[ "marko" ]]. This is TinkerPop's behaviour for the path every live traversal uses (no deviation): javap -c of gremlin-core 3.7.2 shows that ImmutablePath, the only path the traverser classes of that version create, overrides Path.get(Pop, String) and returns an occurrence as it is (first/last the occurrence, all a list of the occurrences, so a list-valued occurrence stays nested). MutablePath also returns first/last as they are; only its all unwraps a single list-valued occurrence, and no traverser creates one. The interface default of Path.get(Pop, String) does unwrap a list (first/last return its first/last element, all returns it unwrapped), but only paths that do not override it use it (DetachedPath, ReferencePath, EmptyPath: results already detached from a traversal); select never reads those. No scenario of the vendored 3.8.2 feature files depends on it; the 3.8.2 sources were not available, so 3.7.2 is the source for this rule.

Path Windows: from() and to() on path(), simplePath() and cyclicPath()

path(), simplePath() and cyclicPath() take from(label), to(label) and by(...), as the Apache TinkerPop steps do. from() and to() cut the path of each traverser down to a window between two labelled positions; by() projects the objects of that window before the step uses them.

g.V().as("a").out().as("b").out().as("c").path().from("b").to("c").by("name")
// ["josh", "ripple"], ["josh", "lop"]

g.V().as("a").out().as("b").out().as("c").simplePath().by(T.label).from("b").to("c").path().by("name")
// ["marko", "josh", "ripple"], ["marko", "josh", "lop"]

Rules

  • Window. The window starts at the position labelled by from() (position 0 without from()) and ends at the position labelled by to() (the last position without to()), both included. The two bounds are found independently of each other. from("a").to("a") is the one object labelled a; two labels on the same position (as("a", "b")) work the same way.
  • path() returns the windowed objects. The traverser's own path is unchanged, so a later path() is the whole path again.
  • simplePath() / cyclicPath() test only the window (after by()). The traverser continues with its whole path; only the test sees the window.
  • by() is a ring over the window: the first by() applies to the first object of the window, the next one to the second object, and so on, cycling. A by() that yields no value for an object (a missing property) drops the traverser, for path(), simplePath() and cyclicPath() alike. simplePath().by(...) compares the projected values, so two different vertices with the same age are a repeat.
  • Order of the modulators does not matter: path().by("age").from("a").to("b") and path().from("a").to("b").by("age") are the same.
  • Cost. The plain forms (no modulator) test the path in place without copying it. The modulated forms materialize the path once per traverser. .profile() shows the modulators, for example simple_path().from("b").to("c").by(T.label) [path: full].

Deviations

These are choices where the engine had to decide; none is a difference from TinkerPop's behaviour on a feature scenario.

  • Repeated labels. If several positions carry the same label (the same as("a") inside a repeat(), or as("a") twice), both from() and to() use the last position carrying the label. This is TinkerPop's Path.subPath (checked against the 3.7.2 byte code, since no Java sources are available offline), so a window may start at the last a even when an earlier a exists. A to() position before the from() position is an error.
  • Unknown label. A from() or to() label that no position carries is an error (Property '<label>' not found on element type 'path'). TinkerPop raises an IllegalArgumentException too; only the text differs.
  • Repeated from()/to(). A second from() replaces the first (TinkerPop's addFrom setter does the same).
  • Exactly one label. from(["a", "b"]) (a list) is an InvalidModulator error, detected before the traversal runs. TinkerPop's from() takes one label (or a traversal, which Graphersal does not support for path()).
  • No value from by(). A by() that produces nothing drops the traverser (as path().by() already did); TinkerPop does the same without ProductiveByStrategy.
  • Empty argument list. from([])/to([]) in a script is the no-argument form and is ignored, as it is for addE().

union() as a Start Step

g.union(branches...) starts a traversal without V(). It differs from Apache TinkerPop 3.8.2 in two details.

The seed is null

  • TinkerPop: the start union has no incoming traverser of its own.
  • Graphersal: a root traversal whose first step is union() gets exactly one seed traverser holding null; child traversals are never seeded. A branch such as __.identity() therefore yields that null: g.union(__.identity()) returns one null.

A branch that opens with inject() is its own start

  • Graphersal: such a branch runs over an empty source instead of the seed.
  • Why: otherwise g.union(__.inject(1), __.inject(2)) would echo the seed and return null, 1, null, 2 instead of 1, 2. In the middle of a traversal inject() still emits the incoming traverser as well.
g.union(__.inject(1), __.inject(2)).toList()   // 1, 2
g.union(__.identity()).toList()                // null
g.union(__.V("1"), __.V("4")).values("name").toList()

Nested V()/E() in a branch start from the incoming traverser and extend its path.

Branch Children and Global State

union(), choose() and branch() run their child traversals over a stream of traversers. This page lists where Graphersal differs from Apache TinkerPop 3.8.2 in how it feeds that stream to a child.

The rule

A child traversal is stateful when one of its top-level steps holds global state: a barrier (count, sum, min, max, mean, fold, group, ...) or a stream-wide step (order, dedup, limit, range, tail, skip-like steps).

  • Stateful child: every traverser routed to the child is fed into one run of it, as in TinkerPop's BranchStep. union(__.limit(1), __.limit(2)) over six vertices returns 3 results, and union(__.outE().count()) returns one total, not one count per vertex.
  • Stateless child: each traverser runs through the child on its own. The multiset of results is the same as in TinkerPop.
  • local(...) is the per-traverser form of a stateful child: union(__.outE().count(), __.local(__.inE().count())) returns one global count and then one count per vertex.

For choose() and branch() the selector still runs per traverser; the traversers it routes to an option form that option's stream. A traverser dropped by the selection joins no stream; one that choose() passes through unchanged is emitted after the option streams. The option keys and the unmatched-traverser rules are on Option Keys.

Deviations

  • Output order. With a stateful child the branches run one after the other, so the output is branch-major (all results of the first branch, then of the second); for choose()/branch() it is option-major (declaration order). Without a stateful child the output stays traverser-major. TinkerPop does not promise an order for either, so only the order of results can differ.
  • What counts as stateful is decided from the optimized plan, by step kind. repeat(), barrier() and discard() do not make a child stateful (a loop streams in TinkerPop), except a repeat() whose body holds a dedup(): its seen-set lives for the whole loop, so the child runs as one batch. A limit inside a repeat() body is not looked at here: repeat() keeps its own frontier semantics.
  • Bulk. A stateful child receives the stream with its bulks (bulk.merge, on by default), so a count() is bulk-weighted; results are the same with merging on or off.
  • Side effects. A child that writes side effects runs once for the whole stream, not once per traverser.
g.V().union(__.limit(1), __.limit(2)).toList().len()                       // 3
g.V("1","2").union(__.outE().count(), __.inE().count()).toList()           // 3, 1
g.V().choose(__.values("age").is(P.lte(30)),
             __.out().order().by("name").limit(1),
             __.out().order().by("name").limit(2)).count().next()          // 3

Option Keys of choose() and branch()

This page lists where Graphersal's option() keys and unmatched-traverser rules differ from, or deliberately extend, Apache TinkerPop 3.8.2. Everything not listed follows the TinkerPop feature files (Choose.feature, Branch.feature).

Rules in one table

choose(traversal)branch(traversal)
option keysliteral, predicate (P.between(26, 30)), Pick.none, Pick.unproductivethe same, plus a traversal key and Pick.any
matchthe first matching option, in declaration orderevery matching option
selector produced a value, nothing matchesthe Pick.none option (the first one); without one the traverser passes through unchangedevery Pick.none option; without one the traverser is dropped
selector produced nothingthe Pick.unproductive option (the first one); without one the traverser passes through unchanged, even when a Pick.none option existsevery Pick.unproductive option; without one the traverser is dropped
traversal key, Pick.anyerror when the traversal executesallowed; Pick.any is additive

A literal key is compared like P.eq(literal): numbers match by value (option(2, ..) matches the integer 2 and the float 2.0). A literal or predicate operand is always data: a bare string never names a step label or a vertex id. A traversal key matches when it produces at least one result with the selector's value as its start.

Deviations

  • Pick.any and an unproductive selector. Pick.any is documented as "always", so it also runs for a traverser whose selector produced nothing. The TinkerPop feature files do not cover this case.
  • Traversal key and paths. A traversal key starts at the selector's value but keeps the path of the choosing traverser, so path() inside a key sees that path.
  • Profile attribution. .profile() lists the steps of a traversal key as nested steps of the option, before the steps of its branch.
  • Order of passed-through traversers. When a choose() option holds global state (Branch Children), traversers that pass through unchanged are emitted after the option buckets. TinkerPop does not promise an order.
  • Errors. choose() with a traversal key or Pick.any raises InvalidOption when the traversal executes, not when the step is built. The error text differs from TinkerPop's; only the error type is compared by the conformance suite.
  • Pick.unproductive is implemented for both steps. discard() and fail() in the TinkerPop option scenarios are separate steps that are not implemented yet.

The by() Modulator: Single-by Steps

aggregate(), store(), groupCount() and valueMap() take one by().

  • TinkerPop: a second by() on these steps is an error.
  • Graphersal: the same; the second by() fails with InvalidModulator when the traversal executes, and the help() text shows how to project several values in one traversal.
  • valueMap().by(...) applies its one by() to every key; it never cycles through several by() modulators.
  • Unaffected: group() takes a key by() and a value by(); project(), order() and path() keep their own by() rules.
g.V().aggregate("x").by("name").by("age").toList()
// Caused by: `aggregate()` cannot use its by() #2: aggregate() and store() take a single by()

g.V().aggregate("x").by(__.values("name", "age").fold()).cap("x")   // one traversal instead

Set Side Effects

withSideEffect("a", Set.of(..)) declares a side effect as a set: aggregate("a") and store("a") keep each value once, and cap("a")/select("a") return it as a list without duplicates. It differs from Apache TinkerPop 3.8.2 in these details.

A set is a property of the side effect, not a value type

  • TinkerPop: a set is a first-class value ({"alice"} in Groovy, toSet(), GType.SET).
  • Graphersal: there is no set value. The set belongs to the side-effect bucket. cap("a") returns a plain array (insertion order, no duplicates); toSet(), GType.SET and set literals anywhere else are not implemented.
  • DSL spelling: Set.of("a", "b") (0 to 10 arguments), Set.ofList(["a", "b"]) and the Set::of(..)/Set::of_list([..]) forms. The Groovy literal {..} does not exist in Rhai. In Rust: GraphTraversalSource::with_side_effect_set.
  • Set.of(..) accepts only plain values (strings, numbers, booleans, UUIDs, null); a vertex, a traversal or a map is a script error.

Order

  • TinkerPop: the iteration order of a set is the one of its implementation (HashSet: unspecified).
  • Graphersal: first-seen order, seed values first.

Equality of members

  • Members are compared by value. 1 and 1.0 are different members.
  • A property value collected from values() is compared by its value, not by the element it came from, so two vertices named "x" contribute one member. A property element collected from properties() is compared by its element and key (TinkerPop's property id), so those two vertices contribute two members (an edge property is also kept by identity, unlike TinkerPop; see Property Elements). Elements (vertices, edges) keep their identity.
  • Bulk is invisible: a traverser of bulk n inserts its value once, with merging on or off.
g.withSideEffect("a", Set.of()).V().both().values("name").aggregate("a").cap("a").next()
// ["josh", "lop", "vadas", "marko", "peter", "ripple"]
g.withSideEffect("a", []).V().both().values("name").aggregate("a").cap("a").next()
// a list seed keeps duplicates

Empty side effects

aggregate("a"), store("a") and subgraph("a") declare their key when they run, even if they collect nothing (an empty upstream, or a by() that resolves no value). cap("a") then returns the empty collection, as in TinkerPop, and where(P.within("a")) is false and where(P.without("a")) true for it. Only a key that no step declares (a typo) is an error.

  • cap("sg") of a subgraph("sg") that collected nothing is an empty graph (see Subgraphs).

Subgraphs

subgraph("sg") collects the edges that pass through it, and cap("sg") returns them as a graph value, as in TinkerPop:

let sub = g.e(0).subgraph("sg").cap("sg").next();
sub.v().to_json()     // the two endpoint vertices of edge 0, with all their properties
sub.e().count().next()   // 1

The graph value is a traversal source: sub.v(), sub.e(), sub.addV(..) work as on g.

What the graph holds:

  • the selected edges and both endpoint vertices of each (a vertex shared by several edges is copied once; a vertex without a selected edge is not included),
  • ids, the whole label set of every vertex (not only the first label) and all properties at full depth (nested objects and arrays),
  • the schema the source graph stores (mode and declarations, copied; clear it with set_schema on the copy if you do not want it). A source with no stored schema gives a copy that keeps inferring from its own data.

subgraph() needs the label: subgraph() alone is an error that names subgraph("sg") + cap("sg") and the short to_graph() terminal. The stream must be made of edges: a vertex (or any other value) reaching subgraph("sg") is an error whose help points at outE()/inE()/bothE() (g.v(1).bothE().subgraph("sg").cap("sg")). The kind is checked when each traverser arrives, so this also holds inside a nested traversal (local(__.out().subgraph("sg")) fails, local(__.outE().subgraph("sg")) works); an empty stream is fine and gives the empty graph.

It is a snapshot: a copy, never a view. Changing the subgraph does not touch the source, and later changes of the source do not reach the subgraph. Ids are preserved (so the same vertex has the same id in both graphs) and stay unique. Bulk is invisible: an edge that reaches subgraph() once or a thousand times is collected once. While the stream runs only edge handles are collected; the copy is built when cap() runs.

to_graph() is the short form (a Graphersal extension, TinkerPop has no such step): a terminal that builds the same graph from a stream of edges, without a label.

g.e(0).to_graph()                 // one edge and its two vertices
g.v(1).bothE().to_graph()         // all edges of vertex 1, with their vertices
g.v(1).to_graph()                 // error: to_graph() needs edges

A stream of anything else than edges (vertices, values) is an error that names the edge forms; a stream with no results is an empty graph. In the Rust API to_graph() returns the shared graph handle (Arc<Graph>), and cap("sg").next() lists the graph as {"vertices": [..], "edges": [..]}. A script that ends on a graph value (g.e(0).to_graph(), cap("sg").next()) shows that same listing in graphersal and the playground, cut to the display limits (see Graph values); in the script the value stays a graph you traverse.

Writing into your own graph

By default cap("sg") builds a new in-memory TraversalGraph. To write into a graph you own, declare it as the side effect, as in TinkerPop:

let target = g.e(0).to_graph();                        // or GraphSource::empty()
g.withSideEffect("sg", target).v(1).outE("created").subgraph("sg").toList();
target.e().count().next()                              // 2: the edge copied before, plus one

The step writes through the graph mutation API when it has run, and cap("sg") returns the target itself. A vertex id the target already holds is reused and an edge id it already holds is skipped, so writing the same edges twice changes nothing. The target's own stored schema is kept (the source schema is copied only into a target that stores none). The target must not be the graph being traversed (g itself): that fails with an error instead of deadlocking.

The target must also be a TraversalGraph. Every graph a script builds is one (GraphSource::*, to_graph(), cap("sg"), _g), but a host may serve its own g from another GraphStorage. withSideEffect("sg", g) with such a graph fails when the step is built, with GraphError::Unsupported naming the target's storage type. To get a subgraph of a foreign graph, let it land in a graph of the script (g.E().hasLabel("knows").to_graph()) and copy what you need from there.

  • Deviations from TinkerPop: the default graph is a Graphersal TraversalGraph, not a TinkerGraph, and an explicit target must be a graph value of this kind. to_graph() and the schema copy are extensions. In the Rust API a graph value is shown by next()/to_list() as its {"vertices", "edges"} listing; use to_graph() for the graph itself. See TinkerPop deviations.

Reduced values

withSideEffect("a", 0, Operator.sum) declares a side effect that aggregate("a") and store("a") combine with an Operator instead of collecting a list: g.withSideEffect("a", 1, Operator.sum).V().aggregate("a").by("age").cap("a") is 124. See Sack and Operators for the rule and the deviations.

tree("key") as a Side Effect

This page lists where tree("key") differs from Apache TinkerPop 3.8.2. Everything not listed follows Tree.feature.

tree() without a key is a reducing barrier that emits the tree. tree("a") is a side effect: every traverser passes through unchanged and its path is added to the tree stored under a. A second tree("a") adds to the same tree, cap("a") and select("a") read it, and by() works on both forms:

g.V().out().tree("a").select("a").count(Scope.local)   // six rows of 3
g.V("1").out().out().tree("a").by("name").both().both().cap("a")

Deviations

  • A later step does not see a half-built tree. The engine runs each step over the whole batch before the next one starts, so g.V().out().order().by("name").local(__.tree("a")).select("a") gives the finished tree on every row, where TinkerPop's streaming execution gives the growing tree (1, 1, 1, 2, 2, 3). Everything inside one local() child is evaluated per traverser and is progressive: g.V().out().local(__.tree("a").select("a").count(Scope.local)) matches TinkerPop. Reading the tree before the traversers are done needs a streaming executor.
  • Bulk is ignored, as in TinkerPop: a path reached many times is one branch.
  • A key that already holds something other than a tree is an error (aggregate("a").tree("a")). TinkerPop fails with its own cast error.
  • An empty stream still leaves an empty tree that cap("a") returns as {}.

Sack and Operators

TinkerPop's Operator is a binary function over two values. One token drives four features: the sack (a value that travels with a traverser: withSack(init, Operator), sack(Operator)), and two reducers (fold(seed, Operator) and withSideEffect(key, init, Operator)). This page is the complete reference: the operators first, then the sack, the merge operator, withBulk(false), the reducers, and finally every deviation from TinkerPop in one list.

Operators

Eleven tokens, written Operator.sum or Operator::sum in the Rhai DSL (there are no bare constants: sum() and max() are steps). In Rust the token is graphersal::prelude::Operator and Operator::apply(&left, &right) applies it to two property values.

OperatorAcceptsResultErrors
sum, minus, multtwo numbersinteger arithmetic when both are int64, float64 when either is a floatinteger overflow; a non-number
divtwo numbersint64 / int64 truncates toward zero; with a float operand IEEE division (inf, NaN, no error)integer divisor 0; i64::MIN / -1; a non-number
max, mintwo numbers (int and float widen to float) or two values of one scalar kind (string, boolean, uuid)the larger or smaller valuemixed kinds, lists, maps, elements
assignanythingthe right operand, even nullnone
and, ortwo booleanslogical and / ora non-boolean
addAlllist + list, map + map, list + scalarconcatenation; putAll (the right value wins, the left key order is kept, new keys are appended); the scalar is appendedlist + map, map + scalar
sumLongtwo int64the suma non-int64; overflow

Every failure is a ValueError::OperatorFailed with a kind (Overflow, DivisionByZero, IncompatibleOperands); its help() names the casts as_number(), as_bool() and as_string().

Examples (each runs in graphersal; inject with withSack shows an operator on its own):

g.withSack(2).inject(5).sack(Operator.mult).sack()       // 10
g.withSack(2).inject(5).sack(Operator.minus).sack()      // -3
g.withSack(7).inject(2).sack(Operator.div).sack()        // 3     (int / int truncates)
g.withSack(7.0).inject(2).sack(Operator.div).sack()      // 3.5
g.withSack(3).inject(9).sack(Operator.max).sack()        // 9
g.withSack("b").inject("a").sack(Operator.min).sack()    // a
g.withSack(true).inject(false).sack(Operator.and).sack() // false
g.withSack([1,2]).inject(3).sack(Operator.addAll).sack() // [1, 2, 3]
g.withSack(#{a: 1}).inject(#{b: 2}).sack(Operator.addAll).sack()   // {a: 1, b: 2}
g.withSack(1).inject(2).sack(Operator.assign).sack()     // 2
g.withSack(9223372036854775807).inject(1).sack(Operator.sum).sack()
// error: Operator 'sum' overflowed the int64 range combining 9223372036854775807 (int64) with 1 (int64)

Null rule: for sum, minus, mult and div a null operand makes the result the left operand (sum(null, 1) is null, sum(1, null) is 1); min/max and and/or return the other operand (two nulls give null); assign returns the right operand even when it is null. This is TinkerPop's NumberHelper rule, kept on purpose.

Sack

A sack is a value that travels with a traverser, separate from the value the traverser currently holds.

g.withSack(5).V().sack()                 // 5, six times
g.withSack(0.0).inject(1).sack()         // 0.0
g.V().sack()                             // null, six times: no withSack, no sack
g.withSack(7).V().values("age").sack()   // 7 each: the value changes, the sack stays
  • withSack(initial) (with_sack in Rust and as a snake_case alias in Rhai) is an option of the traversal source, like withSideEffect. The initial value may be a number, string, boolean, UUID, list or map. As in Gremlin, both exist only on g: written inside a child traversal (local(__.withSack(1).sack())) they fail before execution with SourceStepInChild, whose help shows the fix (g.withSack(1).V().local(__.sack())).
  • sack() replaces the traverser's value with its sack. Without withSack the sack is null.
  • Who gets the initial sack. A traverser generated by a start step (V(), E(), inject(), a first addV()) or by a reducing barrier (count(), sum(), fold(), group(), cap(), ...) starts with the initial sack, so g.withSack(9).V().count().sack() is 9. A traverser derived from another one (every out(), has(), values(), unfold() and so on) keeps the sack of its parent, and a child traversal sees the sack of the traverser it runs for (where(__.sack().is(P.eq(5))), order().by(__.sack()), local(__.sack())). A by() that projects an object taken from the traverser (path().by(..), select("a").by(..), tree().by(..), math(..).by(..) over a named variable, where(P).by(..)) starts a fresh traverser for that object, which has the initial sack: this is what TinkerPop does (TraversalUtil.produce(object, traversal)).
  • Sacks are immutable values. Nothing changes a sack in place; an update (sack(Operator)) gives that one traverser a new value. A traverser stores only a four byte handle into a per-execution table, so carrying a sack costs nothing for queries that do not use one (the traverser stays 80 bytes) and equal scalar sacks share one stored copy (about 48 bytes per distinct scalar, 32 bytes per container). 1 and 1.0 are different values; 0.0 and -0.0 too.
  • Merging. Traversers merge at a barrier(), in a repeat() frontier and at the optimizer's lazy_barrier() only when their sacks are equal (same stored value). Different sacks never merge. A list or map sack is stored once per update and therefore only merges with copies of the very same stored value. The results never depend on merging (see Bulk and barriers).

Updating a sack

sack(Operator) replaces the traverser's sack with operator(sack, operand). The operand is what a following by() resolves for the traverser, or the traverser's own value without a by().

g.withSack(0).V().outE().sack(Operator.sum).by("weight").inV().sack()   // running total of edge weights
g.withSack("hello").V().outE().sack(Operator.assign).by(T.label).inV().sack()
g.withSack(2).V().sack(Operator.div).by(__.constant(4.0)).sack()        // 0.5, six times
g.withSack(1).inject(2).sack(Operator.sum).sack()                       // 3: no by(), the value is the operand
  • by() rules. A property key, T.id/T.label, or a traversal; a traversal contributes its first result (write by(__.values("x").sum()) to combine several) and runs with the traverser's sack. A by() that resolves nothing (a missing property, an empty traversal) is unproductive: the traverser is dropped, so g.V().sack(Operator.assign).by("age").sack() has four results, not six. A second by() is an InvalidModulator error ("Sack step can only have one by modulator").
  • The path and bulk are untouched. The step does not add a path position (sack() does), and a traverser that stands for several equal ones is updated once, all copies share the new sack. A child traversal's own sack(Operator) never flows back to the parent: where(__.sack(Operator.sum).by(__.constant(5))) leaves the outer sack alone, local(__.sack(Operator.sum)...) carries the update out because local hands the child's traverser on.
  • Which sack a child sees. A child that receives the traverser itself (project().by(__.sack()), order().by(__.sack())) sees its updated sack. A by() that projects an object taken from the traverser (path().by(__.sack()), select("a").by(..)) starts a fresh traverser, which has the initial sack, so g.withSack(1).V().sack(Operator.sum).by(__.constant(1)).path().by(__.sack()) yields 1, not 2. TinkerPop does the same.
  • Null sack. The NumberHelper rule applies: sum of a null sack is null (a null left operand wins), assign works on it.
  • Only an Operator. sack(BiFunction) lambdas are not supported; g.V().sack(5) fails with a message that names sack(Operator.sum).

normSack

barrier(Barrier.normSack) (or Barrier::normSack) merges the stream like barrier() and then scales every numeric sack so that the sacks add up to one: total = 0.0 + sum(sack * bulk), sack = sack / total (sack * bulk / total next to a merge operator), always a float64. g.withSack(1.0).V().out().barrier(Barrier.normSack).sack() gives six times 1/6. A null sack is skipped and stays null; a sack that is neither a number nor null fails with OperatorFailed. A zero total divides by zero in IEEE arithmetic (no error). The consumer runs even with bulk.merge=false and on a stream of one traverser (it gives 1.0).

Merge operator

g.withSack(initial, Operator.sum) (Rust with_sack_merge(initial, Operator::Sum)) sets the merge operator. It is not a split operator: in TinkerPop the two-argument form takes a BinaryOperator that combines the sacks of traversers that merge, and a split needs a UnaryOperator lambda, which is not supported (a non-Operator second argument fails with a message that says so, and so does the three-argument form).

With a merge operator, merging becomes part of the result. Traversers that are equal (same object, same path) merge whatever their sacks are; the merged sack is operator(first, next) in encounter order, and the bulks add up:

g.withSack(1, Operator.sum).V().out().barrier().sack()               // 3, 3, 3, 1, 1, 1: lop merges three traversers
g.withSack(1, Operator.assign).V().out().barrier().sack()            // the last sack wins

A merge that fails (sum over string sacks) is an error of the barrier step. Plans that record full paths (path(), simplePath(), a read as() label) and plans that mutate never merge, so the operator never combines there; containers (arrays, maps) never merge either.

barrier(Barrier.normSack) next to a merge operator uses TinkerPop's numerator: total = sum(sack * bulk) and sack = sack * bulk / total (see normSack). Without a merge operator the numerator is sack.

withBulk(false)

g.withBulk(false) (Rust with_bulk(false), also with_bulk) sets the option bulk.one (TinkerPop's ONE_BULK requirement). It does not switch merging off: an explicit barrier() still collapses equal traversers, but the merged traverser keeps bulk 1, so the duplicate is emitted once:

g.V().out().barrier().count()                       // 6
g.withBulk(false).V().out().barrier().count()       // 4: lop, vadas, josh, ripple
g.withBulk(false).withSack(1, Operator.sum).V().out().barrier().sack()   // 3, 1, 1, 1

Under bulk.one a traverser that carries a sack and has no merge operator never merges (TinkerPop carriesUnmergeableSack), so g.withBulk(false).withSack(0).V().out().barrier() has six results. withBulk(true) clears the option. This is the one place where merging is visible on purpose.

Automatic merging and sacks

PlanEqual-key ruleExplicit barrier()repeat() frontier and lazy_barrier()
no sackthe sack handle is NONE on both sidesmergesmerge (invisible optimization)
withSack(init), no operatorequal sacks merge, different sacks do notmergesmerge (invisible: the multiset is the same)
withSack(init, Operator)the sack is ignored, the operator combines the sacksmerges and combinespass through (off for the whole execution)
withBulk(false)a sacked traverser never merges; others merge but keep bulk 1merges (bulk 1)pass through
bulk.merge=falsenothing mergespass throughpass through

With a merge operator or bulk.one the automatic merge points are switched off for the whole execution, so the result does not depend on where the optimizer happens to put a lazy_barrier(). The lazy_barrier rule still inserts its steps (the profile shows the row with Out == In). A loop body that wants merging writes it:

g.withSack(1, Operator.sum).V().repeat(__.out().barrier()).times(3).sack()

Without the barrier() the loop does not merge and a dense graph runs into the path explosion; the help of the timeout and loop-limit errors says so.

bulk.merge=false keeps its diagnostic meaning (no merging anywhere, including the explicit barrier). For a plan with a merge operator that changes the result: g.with("bulk.merge", false).withSack(1, Operator.sum).V().out().barrier().sack() gives six times 1.

Reducer operators

fold(seed, Operator)

fold(seed, Operator) keeps one accumulator, starting at seed, and applies acc = operator(acc, value) to every value of the stream in order. It emits one traverser holding the accumulator (with the initial sack, like every reducing barrier). An empty stream gives the seed. A traverser that stands for n equal ones (after a merge) applies the operator n times, within bulk.max_expansion: there is no acc + value * n shortcut, so minus and div stay exact and the result never depends on merging.

g.V().values("age").fold(0, Operator.sum)                  // 123
g.V().hasLabel("none").values("age").fold(0, Operator.sum) // 0, the seed
g.V().values("age").fold(100, Operator.minus)              // -23, in stream order
g.V().values("age").fold([], Operator.addAll)              // [29, 27, 32, 35]
g.inject(#{a: 1}, #{b: 2}, #{b: 4}).fold(#{}, Operator.addAll)   // {a: 1, b: 4}
g.V().constant(false).fold(true, Operator.and)             // false
g.withSack(3).V().values("age").fold(0, Operator.sum).sack()     // 3

The seed decides the kind (0 for sum, 1 for mult, true for and, [] or #{} for addAll). A seed the operator cannot combine with (fold("", Operator.sum) over names) is an OperatorFailed error. Rust: fold_with(seed, Operator::Sum) on the source, AnonymousTraversal and __. The profile row is fold(0, Operator.sum). A second argument that is not an Operator (a BiFunction lambda) is an error that names fold(0, Operator.sum).

withSideEffect(key, initial, Operator)

A side effect declared with an operator is a reduced value: aggregate(key) and store(key) combine what they collect into it with the operator instead of appending to a list, and cap(key), select(key) and where(P.lt(key)) read the accumulated value.

g.withSideEffect("a", 1, Operator.sum).V().aggregate("a").by("age").cap("a")      // 124
g.withSideEffect("a", 100, Operator.min).V().aggregate("a").by("age").cap("a")    // 27
g.withSideEffect("a", [1,2,3], Operator.addAll).V().aggregate("a").by("age").cap("a")
                                                       // [1, 2, 3, 29, 27, 32, 35]
g.withSideEffect("a", 0, Operator.assign).V().aggregate("a").by("age").cap("a")   // [29, 27, 32, 35]
g.withSideEffect("a", 7, Operator.sum).V().hasLabel("none").aggregate("a").cap("a")   // 7: nothing collected

The rule. One execution of aggregate() (the whole stream of the step, or a single traverser inside a local() child) collects the values v1..vk in stream order (bulk expanded, by() applied, unproductive ones skipped). Then:

  • assign and addAll receive the values as one list: operator(value, [v1..vk]). assign keeps the list ([29, 27, 32, 35]; inside local() there is one execution per vertex, so the last one wins: [35]), addAll concatenates it;
  • every other operator folds the values one by one: operator(operator(value, v1), v2). This is what the expectations for sum, minus, mult, div, min, max, and and or need (124, 0, 1753920, 1, 27, 35).

store(key) is lazy and applies the rule after every element (one value per execution), so assign leaves a one-element list. An execution that collects nothing leaves the value unchanged. Bulk is invisible: a traverser of bulk n contributes n values. An array seed together with an operator is a reduced value, not a list. A reduced value is neither a list nor a set bucket: within("a") over it tests the items when it holds a list and the value when it holds a scalar. Rust: with_side_effect_reduced(name, initial, Operator).

Where the rule comes from. TinkerPop 3.7.2 (AggregateGlobalStep, DefaultTraversalSideEffects.add, Operator$1, read with javap -c on gremlin-core-3.7.2.jar) hands the reducer one BulkSet per step execution, so sum(1, BulkSet) is a ClassCastException there and cannot give 124. The suite pins 3.8.2 and its source is not available offline, so the 24 sideEffect/Aggregate.feature scenarios with an Operator decide the rule (all 24 pass): the global and the local form of sum, minus, mult, div, min and max (seeds 1 and 100), and, or, addAll and assign. Global assign returns the four rows 29, 27, 32, 35, so the reducer must see the whole collection and not one element per call; every numeric and boolean operator needs the element-by-element result (minus: 123 - 29 - 27 - 32 - 35 = 0, div: 876960 / 29 / 27 / 32 / 35 = 1). The local scenarios cannot tell a scalar 35 from a one-element list [35] (iterated next spreads a collection into rows), so the special case "a single value is applied as a scalar", which an earlier design considered, is not used: one uniform rule keeps the type of the result independent of how many traversers reach the step.

Deviations from TinkerPop

Every deliberate difference in one list (the same rows are in the developer table tinkerpop_deviations.md).

Operators

  • Integer overflow is an error. TinkerPop widens int to long and long to BigInteger; Graphersal has int64 and float64 only, so sum, minus, mult and div (i64::MIN / -1) fail with OperatorFailed instead of promoting. Floats follow IEEE (1.79e308 + 1.79e308 is Infinity). The integer widths of the feature files collapse to int64.
  • sumLong does not wrap around (TinkerPop 3.7.2 does); it fails on overflow and on a non-int64 operand.
  • div of two integers truncates toward zero like Java; a zero integer divisor is an error, a float divisor gives inf/NaN.
  • addAll with a scalar appends it (3.8.2 feature files; 3.7.2 throws for a non-collection).
  • Only the Operator and Barrier tokens. No lambdas: sack(BiFunction), fold(seed, BiFunction), withSideEffect(key, init, BinaryOperator), barrier(Consumer), and no Supplier initial value (withSack { [:] }). There is no split operator (withSack(init, UnaryOperator)); a container sack is shared by handle, which is safe because sack values are never modified in place.
  • The null rule is TinkerPop's (see Operators), not an error.

Sack

  • A vertex or edge is not a valid sack value or operand (withSack(vertex), sack(assign) of an element, an element in normSack): a cast or OperatorFailed error whose help names by(T.id). TinkerPop accepts any object.
  • BigInteger/BigDecimal sacks (withSack(BigInteger ...)) are not supported; that scenario stays a translator gap.
  • A traversal in sack(op).by(..) contributes its first result; write by(__.values("x").sum()) to combine.
  • Equal sacks merge at automatic merge points when there is no merge operator (TinkerPop never merges sacked traversers); the result multiset is identical after bulk expansion.
  • normSack numerator. Without a merge operator the sack is divided by total = sum(sack * bulk) (not sack * bulk / total), so merging never changes the answer; next to withSack(initial, Operator) the formula is TinkerPop's.
  • Memory. About 48 bytes per distinct scalar sack and 32 bytes per container update; SackArenaExhausted at about 4 billion values (compaction at barriers is a follow-up).

Merging

  • Only an explicit barrier() merges next to a merge operator or withBulk(false). TinkerPop's LazyBarrierStrategy also inserts barriers when a sack exists, so its merged sacks depend on where it puts them. Here the repeat frontier and lazy_barrier() pass through; write repeat(__.out().barrier()).
  • bulk.merge=false also disables the explicit barrier, so it changes the result of a merge-operator plan.
  • withBulk(false) is the option bulk.one: merging collapses duplicates and keeps bulk 1 (TinkerPop's ONE_BULK); it is not "no merging".
  • Containers and Full-path traversers never merge, so a merge operator cannot combine them (path equality is by handle; content-based path equality is a follow-up).

Reducers

  • The aggregate/store reducer rule (one list for assign and addAll, an element-by-element fold for every other operator, the same for any batch size) is inferred from the 3.8.2 feature files because 3.7.2 cannot run sum there (see Reducer operators).
  • fold(seed, Operator) applies the operator n times for bulk n (no shortcut), within bulk.max_expansion.

Math

  • sin in the last scenario of map/Math.feature differs from Java in the last digit (Rust libm), see the deviations table.

Sources: the semantics were read from the Operator, NumberHelper, SackFunctions, SackValueStep, TraverserSet, AggregateGlobalStep and DefaultTraversalSideEffects classes of gremlin-core-3.7.2.jar (javap -c) and checked against the vendored 3.8.2 feature files, which win on any conflict.

Changing the Graph

add_v(), add_e(), property(), drop(), remove_property() and the upsert steps merge_v()/merge_e() write to the graph. Whatever writes, the same guarantees hold:

  • One traversal is one unit. It commits when it succeeds; when any step fails (a schema violation, a limit, a timeout) nothing it wrote stays. A whole script, or several traversals in Rust, can be one unit too.
  • A schema is enforced on every write, when the graph has one in mode open or closed.
  • Writes need permission when the host restricts queries: Create, Update or Delete on the data, checked before the traversal runs.
g.add_v("person").property("name", "ann").as("a")
  .v().has("name", "marko").add_e("knows").to("a")
  .iterate();
g.merge_v(#{name: "ann"}).iterate();                // finds ann, creates nothing
g.v().has("name", "ann").remove_property("age").iterate();
PageWhat it covers
Transactionsunits, whole-script units, dry runs, change capture, commit hooks
Upserts: mergeV and mergeEfind-or-create in one step
addE() Endpointsevery way to name the ends of a new edge
Dropping Elementsdrop() and what an old reference sees afterwards
Removing Propertiesremove_property()
Compressed Propertieskeeping large texts compressed in memory

Transactions

Every traversal is atomic: it runs as one unit of work (implicit auto-commit). When it succeeds, all its changes stay. When it fails, every change it made is rolled back before the error is returned, so a failing traversal leaves nothing behind.

g.V().property("checked", true).values("name").asNumber(GType.LONG).toList()
// fails in asNumber("marko") -> no vertex has "checked" afterwards

g.inject(1).sideEffect(__.V("1").drop()).constant("x").asNumber(GType.LONG).next()
// fails -> vertex 1 and its three edges are still there

Any error counts: a failing step, a schema violation, a resource limit (traversal.max_traversers, see Resource Limits), an expired evaluationTimeout (see Query Limits), and an error while the terminal materializes the results (for example returning a vertex the same traversal dropped, see Dropping Elements).

What one unit is

Entry pointUnit
Rust API and Rhai: to_list(), next(), iterate(), to_table() and the other visualizers, profile(), execute(), to_graph()one traversal, including the materialization of its results
Rhai (CLI, Python, eval_* entries): every executed traversal of a scriptone traversal; statements before a failing one stay applied
Rhai through eval_value_atomic (host option), the playground, Python execute(.., atomic=True)the whole script (below)
Rhai through eval_value_dry_run (host option), Python Graph.dry_runthe whole script, always rolled back (below)
Rust API: Transactional::transaction(|g| ..) (every storage)the closure; every traversal inside is a savepoint (below)
Rust API: Transactional::dry_run(|g| ..) (storages with change capture)the closure, always rolled back (below)
GraphStorage methods called directly (add_vertex, insert_vertex, set_vertex_property, ...)one call: it either succeeds or changes nothing; outside a unit it is not recorded, so no hook sees it (use it for loading, see below)
set_schema() / patch_schema() outside a unitone unit of its own
a catalog change (set_definition(), remove_definition(), define_query(), move_query(), describe_query()) outside a unitone unit of its own
import_graphml() / import_graphson() into an existing graphthe whole import
apply_change_set()the whole change set

In a script, the unit is the traversal, not the whole script:

g.V("1").property("checked", true).toList();                               // applied
g.V("2").property("checked", true).values("name").asNumber(GType.LONG).toList(); // fails, rolled back
// vertex 1 has "checked", vertex 2 has not

A host can make the whole script one unit instead (see below); the script itself cannot.

A GQL query is one traversal, so one unit too: when its last row fails, the elements its earlier rows created are rolled back with it.

let run = g.gql("FOR x IN [1, 0] INSERT (:n {v: 1 / x})").execute();   // fails on the second row
g.v().has_label("n").count().next()   // 0: the node of the first row is gone too

execute() never throws: on failure its error and the partial profile are kept, its results are empty, and none of the traversal's changes are applied.

Explicit transactions (Rust)

graph.transaction(|g| -> Result<T, E> { .. }) -> Result<T, E> runs a closure as one unit. There is no transaction object to finish or forget, and nothing is rolled back in a Drop: the closure's result decides.

The API is the extension trait Transactional (transaction, transaction_with, dry_run; in graphersal::prelude and graphersal::storage). It has a blanket implementation for every GraphStorage: TraversalGraph, its &mut/Box/solely owned Arc wrappers and a storage of your own, built only on the trait's unit methods (begin_unit, set_unit_metadata, commit_unit, rollback_unit, discard_unit). What Err undoes is the storage's business: an atomic storage (capabilities().atomic, like TraversalGraph) rolls everything back, a non-atomic one keeps what was changed before the error.

use graphersal::prelude::*;

let mut graph = TraversalGraph::tinkerpop_modern();
let result: TraverserResult<()> = graph.transaction(|g| {
    g.traversal_mut().add_v("person").property("name", "ann").to_list()?;
    // A failing traversal is a savepoint: only its own changes are rolled back, and the
    // closure gets the error and decides (here: go on).
    let failed = g.traversal_mut().v("1").property("age", 30).constant("x")
        .as_number(GType::LONG).to_list();
    assert!(failed.is_err());
    g.traversal_mut().v("2").property("age", 28).to_list()?;
    Ok(())
});
assert!(result.is_ok());
  • Savepoints. Every traversal inside the closure is a nested unit. When it fails, only its own changes are rolled back and the error is returned to the closure, which gives up with ? or goes on (TinkerPop / SQL behaviour).

  • Err from the closure rolls back everything the transaction changed. The commit hooks get after_rollback (RollbackReason::Failed) when it had changed something.

  • A rollback that fails (only a host's own storage can fail one; TraversalGraph and the Store cannot) closes the unit and reports GraphError::RollbackFailed. The storage is then in an unknown state, so a Graph holding it is poisoned: every later read and write fails with GraphError::Poisoned until the host drops the graph and reopens the storage (Graph::is_poisoned(); book page "Custom Storages").

  • Ok commits once: one commit sequence number and one ChangeSet for the whole transaction.

  • A veto. When a hook's before_commit refuses the change set, everything is rolled back and the call returns E::from(GraphError::CommitRejected { hook, source }); source is the hook's own error. This is why the closure's error type needs E: From<GraphError>. The usual types all qualify: TraverserResult / BoxedTraverserError (what ? on a terminal gives), TraverserError, GraphError, Box<dyn Error>, or an application error with a From impl.

  • Nesting. A transaction inside another one is a savepoint of the enclosing transaction: its Err rolls back only its own changes, its Ok keeps them in the enclosing unit, which alone commits and can still roll them back.

  • Commit metadata. transaction_with(CommitMetadata::new().with_principal("migrator"), |g| ..) gives the commit's ChangeSet a principal and free attributes. A nested transaction_with that succeeds adds its metadata to the enclosing one's (a principal only when none is set yet, attributes only for keys not set yet); a nested one that fails adds nothing. Plain traversals commit with empty metadata.

  • No isolation needed. &mut excludes every other reader and writer for the duration; a shared Graph is used through its write lock (graph.write().transaction(..)).

  • A unit lives inside one guard. A unit opened on the storage through a write guard (graph.write().begin_unit()) must be closed under that same guard: once the guard is dropped, other threads read its uncommitted changes (a Store checkpoint could even write them to disk). To keep one unit over several locks, open it on the shared graph with Graph::begin_unit() (it returns Result<UnitMark, GraphError>) and close it on the same thread with Graph::commit_unit, commit_unit_with, rollback_unit or discard_unit: the thread then holds the unit, its own read()/write() calls run inside it, other threads read on until its first write and wait from then on until it closes, other writers wait for it, and a nested begin_unit() on that thread is a savepoint. The storage's own unit opens only at the first write, with the unit's time pinned when it opened (defaultFunction now and the GQL clocks read one value for the whole unit). Closing it from another thread fails with GraphError::UnitNotHeld; opening or closing it while the thread still holds a guard of the graph, or reaching back into the graph from a commit hook of the unit, fails with GraphError::GraphViewHeld (read()/write() panic there, like RefCell::borrow_mut; read_checked(), write_checked(), try_read() and try_write() report it instead). This is what the whole-script units below and the playground's runs use.

  • A write that must not wait. try_write() answers None both when the graph is busy (another thread reads, writes or holds a unit) and when the current thread may not write it at all (it holds a unit and another view of the graph is alive on it). try_write_checked() tells them apart: Ok(Some(guard)), Ok(None) for busy (try again later) and Err(GraphError::GraphViewHeld { .. }) for forbidden (drop the other view first; waiting would never help).

    use graphersal::prelude::*;
    let graph = Graph::new(TraversalGraph::tinkerpop_modern());
    let mark = graph.begin_unit().unwrap();
    let view = graph.read();
    assert!(matches!(graph.try_write_checked(), Err(GraphError::GraphViewHeld { .. })));
    drop(view);
    match graph.try_write_checked() {
        Ok(Some(mut guard)) => {
            GraphTraversalSource::new(&mut *guard).add_v("person").iterate().unwrap();
        }
        Ok(None) => { /* busy: try again later */ }
        Err(err) => panic!("{err}"),
    }
    graph.commit_unit(mark).unwrap();
    assert_eq!(graph.read().vertex_count(), 7);
    use graphersal::prelude::*;
    let graph = Graph::new(TraversalGraph::tinkerpop_modern());
    // Not: `let mark = graph.write().begin_unit();` closed under a later guard.
    let mark = graph.begin_unit().unwrap();
    GraphTraversalSource::new(&mut *graph.write()).add_v("person").iterate().unwrap();
    graph.commit_unit(mark).unwrap();
    assert_eq!(graph.read().vertex_count(), 7);
  • A rolled-back transaction leaves gaps in the automatic ids (they are never reused).

Execution::mutated() (Rhai: r.mutated) of a traversal inside a transaction says whether it changed something that is now part of the enclosing unit; whether that becomes final is decided by the transaction. Outside a transaction it says whether the run committed a change.

Dry run

graph.dry_run(|g| ..) runs the closure like a transaction and then always rolls it back. It returns the closure's result together with the ChangeSet of what the closure changed (and what was undone), exactly as a commit hook would have received it; compact() gives the net effect. A preview of a migration:

use graphersal::prelude::*;

let mut graph = TraversalGraph::tinkerpop_modern();
let (_, changes) = graph
    .dry_run(|g| g.traversal_mut().v(None).has_label("software").drop().to_list())
    .unwrap();
assert_eq!(changes.len(), 6); // 2 vertices and their 4 edges
assert_eq!(graph.vertex_count(), 6); // untouched
  • The graph is left exactly as it was, schema included. Only the automatic id sequences keep their progress.
  • No commit hook is called: nothing is committed, attempted or vetoed. The change set is built whether or not hooks are registered; its commit_seq() and committed_at() are 0 (never committed), its metadata is empty, and last_commit_seq() / last_committed_at() do not move. Its node_sequence() / edge_sequence() are the id sequences after the dry run.
  • A failing traversal inside the dry run is a savepoint as in a transaction and is not in the change set. Err from the closure comes back unchanged (no change set).
  • Inside a transaction a dry run is a savepoint that is always rolled back; its change set holds only its own changes.
  • A dry run needs a storage with change capture (capabilities().change_capture, like TraversalGraph): it ends with GraphStorage::discard_unit ("roll back without hooks, tell me what it changed"). On any other storage the unit is closed with an ordinary rollback and the call returns E::from(GraphError::Unsupported { .. }); that is why dry_run also needs E: From<GraphError>.

A whole script as one unit (Rhai)

The default unit of a script is one traversal. A host that wants all-or-nothing for the whole script (a migration script, an import, a playground run) calls graphersal::script::eval_value_atomic(graph, script, params, &limits, authorizer) instead of eval_value_with_limits. The script cannot choose this itself (there is no g.tx()).

g.addV("person").property("name", "ann").next();          // part of the unit
g.V("1").property("age", 99).next();                      // part of the unit
g.V().values("name").asNumber(GType.LONG).toList();       // fails: the whole script is rolled back
  • Every traversal of the script is a savepoint. A failure the script handles (execute() never throws; try/catch) rolls back only that statement, and the script goes on.
  • An uncaught error (or a resource limit) rolls back everything the script changed and is returned.
  • A script that ends normally commits once (one ChangeSet); a commit hook's veto rolls it back and is returned as the script's error.
  • The calling thread holds the unit for the whole script (Graph::begin_unit): no other writer (and no other whole-script unit) of the same graph runs between its statements. Other readers are not blocked while the script only reads: they go on and see the committed state. From the script's first write until it ends they wait, so nobody ever sees its uncommitted changes. Opening the unit and closing a unit that never wrote never wait for the readers in flight: they take no exclusive moment, because the storage's own unit opens only at the script's first write (a dry run that never wrote is the exception: its close asks the storage for the empty change set under the exclusive lock).
  • A traversal the script returns without a terminal is not part of the unit: it runs when the host renders it, after the commit, as a unit of its own.
  • The script must not return a closure or function pointer (also inside an array or a map): it would run after the unit closed, outside its atomicity. It fails with ScriptError::ReturnedClosure and everything is rolled back; return data or a traversal.
  • The authorizer is asked per traversal as everywhere else (Permissions).

Front ends: the playground runs every script as one unit (it also counts the implicit execution of a trailing traversal, and commits only when the run reports no error, so a run that shows an error leaves nothing behind). The CLI keeps the default (each traversal is a unit), so a scripted -e session behaves like TinkerPop's Gremlin console. The Python binding keeps the default too and offers the whole-script unit per call: graph.execute(script, atomic=True) (a returned closure raises ReturnedClosureError; a traversal returned without a terminal is run like to_list() after the commit).

Dry run of a script (Rhai)

graphersal::script::eval_value_dry_run(graph, script, params, &limits, authorizer) is the script-side counterpart of Transactional::dry_run: it runs the script like eval_value_atomic and then always rolls everything back, returning (value, ChangeSet).

use std::sync::Arc;
use graphersal::prelude::*;
use graphersal::auth::AllowAll;
use graphersal::script::{ScriptLimits, eval_value_dry_run};

let graph = Arc::new(GraphSource::tinkerpop_modern());
let (count, changes) = eval_value_dry_run(
    graph.clone(),
    r#"g.V().hasLabel("software").drop().toList(); g.V().count().next()"#,
    Default::default(),
    &ScriptLimits::default(),
    Arc::new(AllowAll),
)
.unwrap();
assert_eq!(count.as_int().unwrap(), 4);
assert_eq!(changes.len(), 6); // 2 vertices and their 4 edges
assert_eq!(graph.read().vertex_count(), 6); // untouched
  • The rules of Dry run apply: the graph is left as it was, no commit hook is called, commit_seq() is 0, a failing traversal the script handles is a savepoint and is not in the change set, and a failing script returns its error and no change set.
  • As in a whole-script unit, the calling thread holds the unit for the whole script (other readers go on while it only reads and wait from its first write until it ends), and a returned closure fails with ScriptError::ReturnedClosure.
  • A traversal the script returns without a terminal (also inside an array or a map) runs inside the dry run, as if it ended in toList(), so its result reflects the previewed changes (graphersal::script::materialize_traversals).

The Python binding exposes it as graph.dry_run(script, params=None, *, policy=None), which returns a DryRunResult with .result and .changes (the change set's serde form as plain Python data).

What a rollback restores

Everything the traversal changed: vertices and edges (a dropped vertex comes back with all its edges), labels, properties (at their old position in the property order), ids and the lookups by id (g.V(id), g.E(id)), the label index and the label counts, the stored schema and the catalog of definitions (saved queries).

Not restored:

  • Iteration order. A restored element can come back in another place: g.V() / g.E() order, the order of a neighbour's out()/in(), the order within a label. Iteration order is unspecified, as in TinkerGraph.
  • Element handles (Rust API). A handle taken inside the failed traversal, or a handle to an element the traversal dropped, stays stale: a restored element is a new element with the same id. Look elements up again by id.

Cost

The reference storage TraversalGraph keeps an internal undo log while a unit is open. A read costs nothing. A mutation costs one log entry holding the old value (a property write, a label change, a schema change) or the removed element (a drop); on success the log is cleared.

A rollback does not give back automatically assigned ids: an id handed out to an element that was rolled back is never handed out again, exactly like a database sequence. Auto ids can therefore have gaps; they are unique, not dense.

The counters never wrap around. The commit sequence number and both automatic id sequences are u64; an increment past u64::MAX fails with GraphError::SequenceOverflow instead (a reused commit number or id would corrupt a journal or a replica). For the commit sequence number the failing unit is rolled back like any failed unit (the hooks get after_rollback); for an id sequence the step that needed the id fails, and with it the query. In practice only a renumbered graph (with_last_commit_seq(u64::MAX)) or an explicit numeric id at the end of the range (property(T.id, "18446744073709551615"), which raises the vertex id sequence to it) gets there; explicit ids keep working.

Change capture: ChangeSet

What a committed unit changed is described as a ChangeSet (Rust API, graphersal::changes): the basis for persistence, replication, change data capture and audit on top of the library. It is handed to the commit hooks (next section).

A ChangeSet carries:

  • commit_seq(): the commit sequence number, monotonic per graph. Only a unit that changed something advances it (last_commit_seq()); a read-only, rolled-back or vetoed unit does not.
  • committed_at(): the commit time, i64 microseconds since the Unix epoch (UTC), taken from the system clock at the outermost commit (web_time, so also on wasm32). It is monotonic per graph: max(now, time of the previous commit), so a clock that steps back repeats the previous time instead of going back. Every commit of a unit that changed something takes a time, also without hooks (last_committed_at()); point-in-time recovery compares against it.
  • node_sequence() / edge_sequence(): the automatic id sequences of vertices and edges after the unit (the last auto id handed out, or the highest numeric explicit id seen). They are on every change set because an id of a rolled-back unit or of a dropped element leaves no other trace in a journal: replay and apply_change_set raise the graph's sequences to them, so no automatic id is ever handed out twice, also not after recovery or on a replica.
  • metadata(): an optional principal and free attributes, passed through, never interpreted.
  • mutations(): the changes in execution order, each with its before and after values:
MutationFields
AddVertexid, labels, properties
DropVertexid, before (labels and properties)
AddEdgeid, label, out_id, in_id, properties
DropEdgeid, before (label, endpoints and properties)
SetPropertyelement (kind and id), key, before (absent: None), after
RemovePropertyelement, key, before
AddLabel / RemoveLabelid, label (a vertex label)
SetEdgeLabelid, before (unlabeled: None), after
SetSchemabefore, after
SetDefinitionkind, name, before (absent: None), after (removed: None): one mutation for every kind of catalog definition (define, replace, move, describe, remove)

Rules a consumer can rely on:

  • Cascades are explicit. Dropping a vertex lists one DropEdge per removed edge before the DropVertex; replaying the list in order needs no knowledge of the cascade.
  • jpath writes (property(jpath("a.b[1]"), v)) appear as SetProperty of the top-level key with the whole new value.
  • Schema changes are in the same stream, in order with the data; so are catalog changes (SetDefinition).
  • A write of an equal value is still a SetProperty (before == after).
  • compact() returns the net effect: one entry per element, key and label (an element added and dropped again disappears, an added element absorbs its later changes, a property set back to its old value disappears). Schema changes stay barriers, and the result is ordered so that it replays. The changes of one catalog definition merge into one (dropped when it ends where it started), listed at the end. Under a unique index a compacted set that swaps two values cannot be applied (the intermediate value is gone); apply the uncompacted one.

Building a change set

The graph builds the change sets of its own commits. Outside it (a storage of your own that captures changes, a replication feed, a test) a change set is built with ChangeSet::builder(commit_seq, committed_at), optionally .with_sequences(node, edge) and .with_metadata(..), then push(..) per mutation and build(). Every mutation kind has a constructor: Mutation::add_vertex, drop_vertex (with VertexState::new), add_edge, drop_edge (with EdgeState::new), set_property, remove_property, add_label, remove_label, set_edge_label, set_schema and set_definition. build() makes the cheap checks and fails with GraphError::InvalidChangeSet: a commit_seq of 0 (a never-committed change set, like a dry run's) has no commit time, a commit time is not negative, and a definition change has a before or an after image of its own kind and name. A built change set applies, replays and serializes exactly like a captured one.

use graphersal::changes::{ChangeSet, ElementRef, Mutation};
use graphersal::prelude::*;

let mut builder = ChangeSet::builder(1, 1_700_000_000_000_000);
builder
    .push(Mutation::add_vertex("ann", ["person"], Default::default()))
    .push(Mutation::set_property(ElementRef::vertex("ann"), "age", None, 29i64.into()));
let changes = builder.build().unwrap();
let replica = TraversalGraph::new().replay(&changes).unwrap();
assert_eq!(replica.last_commit_seq(), 1);

Serialization

With the serde feature a ChangeSet serializes as JSON ({"commit_seq": 1, "committed_at": 1791369725123456, "node_sequence": 7, "edge_sequence": 12, "mutations": [{"op": "set_property", ...}]}; a missing committed_at or sequence reads as 0, which replay ignores), and a serialized change set replays into an identical graph without any schema. JSON-native values stay plain JSON; a value of a logical type JSON cannot hold carries an explicit per-value type tag, at any depth (in element images, property writes and commit attributes): uuid and the date and time types, in TinkerPop GraphSON style with the canonical text:

{"@type": "g:UUID", "@value": "6f1d3c2a-0000-4000-8000-000000000001"}
{"@type": "gx:OffsetDateTime", "@value": "2024-05-01T09:30:00+02:00"}
TypeTag
datetime, date, localdatetime, timegx:OffsetDateTime, gx:LocalDate, gx:LocalDateTime, gx:LocalTime
duration of a time part only (no months, no days)gx:Duration (PT26H)
duration of months and days onlygx:Period (P1Y2M3D)
any other durationgraphersal:Interval (P1MT2H)
vector (book page Vectors)graphersal:Vector with an object: {"element": "f32", "data": [0.5, -1.0]} (f16 the same), {"element": "i8", "scale": 0.007874016, "codes": [64, -127]}, {"element": "bit", "dimension": 3, "bits": "a0"} (the packed bytes in hex); exact for every element kind

A user map that happens to have an "@type" key of its own is escaped, so it can never be misread as a tag: {"@type": "graphersal:Object", "@value": {"@type": "mine", "x": 1}} (the payload's keys are literal). Reading is strict: an object with an "@type" key must be exactly one of these forms (only @type and @value, a canonical lowercase uuid, the text of a value of the tag's type, with a gx:Duration holding no months or days and a gx:Period no time part, or an object payload); anything else is an error, never a guess. The tags exist for the ChangeSet only; GraphML and the other exports are unchanged.

Commit hooks

A host registers a CommitHook on the graph (GraphStorage::register_commit_hook); while at least one is registered, every committed unit builds its ChangeSet (without hooks nothing is captured and nothing is paid):

EventWhenCan veto?
before_commit(&ChangeSet) -> Result<(), HookError>the unit validated, before it is finalyes: Err rolls the unit back
after_commit(&ChangeSet)after the unit is finalno
after_rollback(&RollbackReason)after a unit that changed something was rolled back (vetoed or failed)no
use graphersal::prelude::*;
use graphersal::changes::ChangeSet;
use graphersal::changes::{CommitHook, HookError, RollbackReason};

/// A write-ahead log: one JSON line per committed unit (needs the `serde` feature).
struct Wal<W: std::io::Write + Send + Sync> {
    out: W, // a `std::fs::File` in a server (call `sync_data()` after the write)
}

impl<W: std::io::Write + Send + Sync> CommitHook for Wal<W> {
    fn name(&self) -> &str {
        "wal"
    }

    fn before_commit(&mut self, changes: &ChangeSet) -> Result<(), HookError> {
        // Persist BEFORE the commit is final: an Err rolls the unit back and the caller
        // gets GraphError::CommitRejected { hook: "wal", source }.
        serde_json::to_writer(&mut self.out, changes)?;
        self.out.write_all(b"\n")?;
        self.out.flush()?;
        Ok(())
    }

    fn after_rollback(&mut self, reason: &RollbackReason) {
        let _ = reason; // metrics, audit of failed attempts
    }
}

let mut graph = TraversalGraph::tinkerpop_modern();
graph.register_commit_hook(Box::new(Wal { out: Vec::new() })).unwrap();
graph.traversal_mut().add_v("person").property("name", "ann").to_list().unwrap();
assert_eq!(graph.last_commit_seq(), 1); // one committed unit, one WAL line
  • Hooks run in registration order. The first before_commit that returns Err stops the commit: the later before_commit hooks are not called, the unit is rolled back, every hook gets after_rollback (RollbackReason::Vetoed), and the caller gets GraphError::CommitRejected { hook, source } (inside a TraverserError for a traversal) whose source is the hook's own error. The error's help says to fix the cause and run the query again; a veto for which that is wrong (a state that refuses every write) returns a changes::HookRefusal::new(message, help), whose help replaces it (a Store's refusals do the same with their own help: a backup, maintenance mode, damage, a read-only view).
  • This makes before_commit a write-ahead log: when persisting fails the in-memory change is undone, so memory and journal never diverge.
  • Only the outermost unit emits events; a unit that changed nothing emits none and takes no sequence number, unless it raised an automatic id sequence (a sequence-only commit, see Applying and replaying change sets). Hooks run synchronously, strictly in commit sequence order, and get the change set only, never the graph.
  • Hooks cannot be removed (register them before publishing the graph).
  • A hook that panics in before_commit is treated like a veto that does not come back as an error: the unit is rolled back, every hook gets after_rollback (RollbackReason::Failed; a second panic there is dropped), the commit sequence number does not move, and the panic then continues to the caller (see Panics). A Store's journal runs after every user hook, so it never writes a unit whose user hook panicked. A panic inside the journal itself cuts its record off again, poisons it and rolls the unit back as well (Failures while committing). A panic in after_commit comes after the unit is final (and, with a journal, durable): the unit stays committed and the panic continues.

execute() reports whether a run changed the graph: Execution::mutated() (Rhai: r.mutated; inside a transaction or a whole-script unit see above).

Applying and replaying change sets

  • apply_change_set(&changes) (any GraphStorage) applies a change set to a live graph as one unit: ids preserved (an explicit numeric id raises the automatic id sequence), schema enforced, all-or-nothing, captured and seen by the hooks like any other commit. A replica or a migration uses it. Inside the unit it raises the graph's automatic id sequences to the change set's own (GraphStorage::raise_id_sequences, never lowered), like replay does: an automatic id the source handed out to an element whose add and drop were compacted away, or in a unit it rolled back, is never handed out again in the target. The raise is not undone by a rollback (ids are never reused, gaps are fine). When the change set changes nothing in the target (every mutation was compacted away) but raises a sequence, the unit is still committed as a sequence-only commit: it takes a commit sequence number, the hooks get a change set without mutations whose node_sequence/edge_sequence carry the raised values (a veto rolls it back; the raise stays in memory), and a journal or a Store writes it, so the raise survives a reopen, a checkpoint, a backup or a fork. Execution::mutated() stays false for it (no data changed). A change set that raises nothing (the target's sequences are already as high) commits nothing.
  • TraversalGraph::replay(self, &changes) -> Result<TraversalGraph, _> rebuilds a graph nobody sees yet (recovery from a snapshot plus the write-ahead log). It runs outside units: no undo log, no capture, no hook fires (a server must not re-write the journal it is reading). The graph's commit sequence number, commit time and both automatic id sequences are raised to the change set's own (never lowered), so the next live commit continues the journal's numbering and clock, and an automatic id of an element that was dropped or rolled back before the journal ends is never handed out again. On error the half-built graph is simply dropped.

Loading versus importing

Two ways to bring data in, with different rules:

Loading (a graph nobody sees yet)Importing (a live graph)
Examplesstart-up from disk: GraphSource::from_graphml, from_graphml_reader; recovery: TraversalGraph::replay; building a graph with direct GraphStorage calls before it is sharedimport_graphml into an existing graph, apply_change_set, any mutating traversal
Unitnone: no undo log, no ChangeSet, no hooksone unit: all-or-nothing
On errordrop the half-built graphthe import is rolled back
Commit hooksnever called (replaying a journal must not re-write it)called like for any commit, may veto

Isolation for loading comes from "build, then publish": nobody else can see the graph yet. A server therefore registers its hooks after loading and before it publishes the graph. Only an import into a live graph pays for change capture (a ChangeSet about the size of the imported data, built only while hooks are registered).

Snapshot with position

last_commit_seq() read together with a full export under the same read lock is a consistent snapshot with its position:

use graphersal::prelude::*;
use graphersal::changes::ChangeSet;

fn wal_after(_position: u64) -> Vec<ChangeSet> { Vec::new() }
fn main() -> Result<(), Box<dyn std::error::Error>> {
let graph: Graph = GraphSource::tinkerpop_modern(); // the live, shared graph
let (graphml, position) = {
    let g = graph.read();
    let mut buf = Vec::new();
    g.export_graphml_writer(&mut buf)?;
    (buf, g.last_commit_seq())
};
// keep the snapshot, truncate the write-ahead log up to `position`

// recovery:
let loaded = GraphSource::from_graphml_reader(std::io::Cursor::new(graphml))?;
let mut recovered = std::mem::take(&mut *loaded.write()).with_last_commit_seq(position);
for changes in wal_after(position) {
    recovered = recovered.replay(&changes)?;
}
// register the commit hooks, then publish `recovered`
Ok(())
}

GraphML carries no schema. A graph that stores one keeps its schema JSON next to the snapshot (serde_json::to_string(&schema) under the same read lock); on recovery, set that schema on the empty target before importing the GraphML, so the declared types (uuid, array, object) come back (see UUID Values).

Storages

The unit boundaries are three methods of GraphStorage: begin_unit(), commit_unit(mark) and rollback_unit(mark, reason). Units nest; an inner unit is a savepoint. Their default implementation does nothing: a custom storage that does not implement them is not atomic, and a failing traversal keeps the changes it made before the error. TraversalGraph (and &mut, Box and a solely owned Arc of it) implements them with the undo log. An atomic storage also answers unit_changes(mark) exactly (UnitChanges { data, schema, definitions }; it drives Execution::mutated() and Execution::changes() inside an outer unit) and counts its commits in last_commit_seq(). Outside a unit a mutation records nothing: no hook is called and last_commit_seq() does not move.

Three more methods carry the explicit units of Transactional, each with a default: set_unit_metadata(metadata) hands transaction_with's metadata to the unit before its commit (default: ignored); discard_unit(mark) undoes a unit without hooks and returns its ChangeSet (the end of dry_run; it needs change_capture, the default rolls back and returns GraphError::Unsupported); mark(name) has the storage's journal record a named mark (Rhai g.mark; default GraphError::MarkUnavailable). A storage with a unit clock (unit_started_at()) also implements next_unit_started_at() and begin_unit_at(started_at): Graph::begin_unit pins a held unit's time from the first and opens the storage's unit at the unit's first write with the second, so the unit reads one clock value (defaults: no clock, and begin_unit()). The rustdoc of GraphStorage is the guide for writing a storage; Storage Conformance is its test suite.

A storage that captures changes builds its change sets with the constructors above (there is no reusable undo-log component) and embeds a CommitHooks (graphersal::storage): it registers the user hooks, holds the journal slot (JournalSlot, handed out by the library's journal and Store) and runs the events in the required order: before_commit of the user hooks in registration order, then the journal's. The storage assigns the commit sequence number first and does nothing fallible after an Ok (the journal has written its record); on a veto it rolls back and calls after_rollback(&RollbackReason::from_error(&err)). GraphStorage::mark forwards to CommitHooks::mark. With feature persist, PersistentStorage (EXPERIMENTAL) adds what a snapshot and a Store need: the lineage id, the commit position (raise_position, never lowered), a load sink (load_vertex, load_edge, load_schema, load_definition, finish_load; outside units, no hooks, no schema scan), clear (keeps the hooks and the journal), attach_journal and replay(&changes, verify) (a default over the write methods; TraversalGraph overrides it).

What a storage guarantees is GraphStorage::capabilities(), a StorageCapabilities value (facts, not permissions): atomic, change_capture, isolation, concurrent_writers, durability, writable, immutable. The default claims nothing. TraversalGraph reports atomic, change_capture and writable; a read-only &TraversalGraph and a shared Arc claim nothing.

change_capture requires atomic. A storage that cannot roll back cannot honour a before_commit veto, so it reports change_capture: false and refuses hook registration (GraphError::Unsupported); there is no half-atomic notification. The conformance suite (graphersal-storage-tests) runs its rollback and hook items only for a storage that claims them.

Panics

The engine maps every failure to an error, so a panic inside it is a bug. Still, a host that catches a panic (a server thread, a test harness) must not keep serving a half-applied unit: every unit rolls itself back when a panic unwinds through it, innermost first, and the panic then continues to the caller unchanged. This covers a traversal run and its terminal, execute(), an explicit transaction(|g| ..) (also a panic in the caller's own closure; the commit hooks get after_rollback), a dry_run(|g| ..), a whole-script unit (eval_value_atomic, eval_value_dry_run), apply_change_set, a GraphML or GraphSON import into a live graph and a schema change. The commit itself is covered too: a panic in a commit hook's before_commit rolls the unit back before it continues (see Commit hooks); a panic in after_commit leaves the unit committed. No unit is left open afterwards, so the graph keeps working. The success path pays nothing for it (no allocation, no clock).

With panic = "abort" (the default on wasm32-unknown-unknown) there is nothing to catch: the process ends, and the graph with it.

Not covered yet

  • Transactions in the script DSL (g.tx()) and a dry-run preview in the playground.
  • Commit hooks registered from Python (Python gets change sets only as data, through dry_run).
  • Removing a commit hook.
  • Isolation of concurrent readers during a write: readers wait for the writer. A layered storage with snapshot reads is planned.

Deviations from TinkerPop

  • TinkerGraph without transactions keeps the changes a traversal made before it failed. Graphersal rolls them back: the graph is never left half-changed by one failing traversal.
  • TinkerPop opens an explicit transaction with g.tx() and ends it with commit() / rollback(). Graphersal has no tx(); the Rust API uses the closure transaction(|g| ..), and a host can make a whole script one unit.
  • TinkerPop's EventStrategy reports each mutation to a MutationListener after it happened. Graphersal's commit hooks get one ChangeSet per committed unit, before it is final (with a veto) and after it; there are no per-mutation events.

See TinkerPop Deviations.

Upserts: mergeV and mergeE

An upsert finds an element and creates it only when it does not exist yet. Graphersal follows TinkerPop's mergeV() / mergeE() steps: one map describes the element to look for, and option(Merge.onCreate, ..) / option(Merge.onMatch, ..) say what to write in either case.

Every example on this page was run with graphersal (--graph empty where noted, otherwise the default modern graph); the line after // is its real output.

Quick reference

// --graph empty: the first call creates, the second one matches and updates
g.mergeV(#{"T.label": "person", "name": "marko"}).option(Merge.onCreate, #{"age": 29}).elementMap().toList()
// #{"age": 29, "id": "1", "label": "person", "name": "marko"}
g.mergeV(#{"T.label": "person", "name": "marko"}).option(Merge.onCreate, #{"age": 29}).option(Merge.onMatch, #{"age": 30}).elementMap().toList()
// #{"age": 30, "id": "1", "label": "person", "name": "marko"}

// modern graph
g.mergeV(#{"T.id": "1"}).values("name").toList()                       // "marko"
g.mergeE(#{"T.label": "knows", "Direction.OUT": "1", "Direction.IN": "2"}).elementMap().toList()
// #{"IN": #{"id": "2", "label": "person"}, "OUT": #{"id": "1", "label": "person"}, "id": "0", "label": "knows", "weight": 0.5}: the existing edge
g.mergeE(#{"T.label": "knows", "Direction.OUT": "2", "Direction.IN": "1"}).option(Merge.onCreate, #{"weight": 0.1}).elementMap().toList()
// #{"IN": #{"id": "1", "label": "person"}, "OUT": #{"id": "2", "label": "person"}, "id": "6", "label": "knows", "weight": 0.1}: created

In Rust the steps are merge_v(map), merge_v_by(traversal), merge_e(map), merge_e_by(traversal) and option_merge(Merge::OnCreate, map), option_merge_by(Merge::OnMatch, traversal), option_merge_with(Merge::OnCreate, map, Cardinality::Single) on GraphTraversalSource, AnonymousTraversal and __. A map is an ElementProperty::Object with the same string keys as in the DSL.

Map keys: properties and reserved token keys

Rhai map keys are strings, so a Gremlin token such as T.label cannot be a key. Graphersal reserves four string keys spelled exactly like the token:

Gremlin keyDSL keyMeaning
T.id"T.id"the element id
T.label"T.label"the label
Direction.OUT (Direction.from)"Direction.OUT"the out-vertex (mergeE() only)
Direction.IN (Direction.to)"Direction.IN"the in-vertex (mergeE() only)

Every other key is a property name. The engine reads these keys in every map a merge step receives, whether it is written as a literal, injected, taken from select() or built by project(), so a map keeps its meaning when it travels through a traversal:

// --graph empty
g.inject(#{"T.label": "person", "name": "marko"}, #{"T.label": "person", "name": "stephen"}).mergeV().elementMap().toList()
// #{"id": "1", "label": "person", "name": "marko"}
// #{"id": "2", "label": "person", "name": "stephen"}

Why not "id" and "label"? Those are ordinary property names: elementMap() uses them for the id and label entries, but a vertex may also carry a property called id, which then shadows the entry, and [id: 1] in Gremlin is the property id as well:

// --graph empty
g.addV("person").property("id", 5).property("label", "x").elementMap().toList()
// #{"id": 5, "label": "x"}

So #{"id": "1"} in a merge map searches for a property named id. Note the consequence for round trips: elementMap() returns "id"/"label", so its result cannot be passed to mergeV() unchanged (TinkerPop's elementMap() returns T.id/T.label keys; see the backlog).

Reserved prefixes. In a merge map and in property(map), a key that starts with T. or Direction. but is not one of the four keys above, or a key that starts with ~, is an error, never a silent property name:

// --graph empty
g.mergeV(#{"~id": 1}).toList()
// Error: Property key can not be a hidden key: ~id (in the merge() map of mergeV())
// Help: Write the id with the reserved key "T.id" instead of "~id", for example g.merge_v(#{"T.id": "1"}). ...
g.mergeV(#{"T.key": 1}).toList()
// Error: unsupported token key "T.key": a merge map takes only the token keys "T.id", "T.label", "Direction.OUT" and "Direction.IN" (in the merge() map of mergeV())

A property literally named "T.label" can still be written one key at a time:

// --graph empty
g.addV("person").property("T.label", "x").valueMap().toList()     // #{"T.label": ["x"]}

mergeV

mergeV(map) searches for vertices whose id equals "T.id" (if given), whose label set contains "T.label" (if given) and whose every other entry equals the stored property, with the same equality as has(key, value). Every match is emitted. null (() in Rhai) and #{} match every vertex. mergeV(traversal) takes the map from the first result of the traversal, and mergeV() with no argument uses the incoming traverser itself as the map (the inject() example above).

  • onMatch runs on each match. Its map is written with property() semantics; null / #{} change nothing. An onMatch traversal receives the matched vertex and must yield a map. "T.id"/"T.label" are not allowed in onMatch.
  • onCreate runs only when nothing matched. The new vertex gets the merge map plus the onCreate map (inheritance). An onCreate traversal receives the incoming traverser.
  • Override rule. A key present in both maps must have the same value; onCreate can only add keys. With two constant maps the check runs before execution, even when a match exists:
// --graph empty
g.mergeV(#{"T.label": "person", "name": "marko"}).option(Merge.onCreate, #{"T.label": "dog"}).toList()
// Error: option(onCreate) cannot override values from merge() argument: T.label is "person" in mergeV() but "dog" in option(onCreate)
// Help: option(Merge.onCreate, ..) can only add keys to the merge() map: a key present in both must have the same value there. ...
// --graph empty: inheritance, the label comes from onCreate
g.mergeV(#{"name": "marko"}).option(Merge.onCreate, #{"T.label": "person", "age": 29}).elementMap().toList()
// #{"age": 29, "id": "1", "label": "person", "name": "marko"}
g.mergeV(()).option(Merge.onCreate, #{"T.label": "person", "name": "marko"}).elementMap().toList()
// #{"id": "1", "label": "person", "name": "marko"}

// modern graph: an onMatch traversal
g.mergeV(#{"name": "marko"}).option(Merge.onMatch, __.project("visits").by(__.constant(1))).valueMap("name", "visits").toList()
// #{"name": ["marko"], "visits": [1]}

Start step or mid-traversal. As the first step, mergeV() runs once. In the middle of a traversal it runs once per incoming traverser and emits every match each time; an empty stream merges nothing:

g.mergeV(#{}).count().next()                                         // 6
g.V().hasLabel("software").mergeV(#{}).count().next()                // 12: 2 traversers × 6 vertices
g.V().hasLabel("software").mergeV(#{"T.label": "person", "name": "vadas"}).values("name").toList()
// "vadas"
// "vadas"

Graphersal keeps its own defaults where they differ from TinkerPop: a vertex created without "T.label" is unlabeled (as with addV()), ids are strings, and a null property value is stored.

mergeE

mergeE() takes the same forms and options, plus the keys "Direction.OUT" and "Direction.IN". Their value is an existing vertex id, a vertex, or the placeholder Merge.outV / Merge.inV, which option(Merge.outV, ..) / option(Merge.inV, ..) resolve before the search:

g.V("1").as("a").V("3").as("b").mergeE(#{"T.label": "likes", "Direction.OUT": Merge.outV, "Direction.IN": Merge.inV}).option(Merge.outV, __.select("a")).option(Merge.inV, __.select("b")).project("label", "out", "in").by(T.label).by(__.outV().values("name")).by(__.inV().values("name")).toList()
// #{"in": "lop", "label": "likes", "out": "marko"}
g.mergeE(#{"T.label": "knows", "Direction.OUT": "2", "Direction.IN": Merge.inV}).option(Merge.inV, #{"T.label": "person", "name": "josh"}).elementMap().toList()
// #{"id": "6", "label": "knows"}

An option(Merge.outV|inV, map) map is a vertex search ("T.id", "T.label", properties) that must find exactly one vertex; an option traversal receives the incoming traverser and must yield a vertex or a vertex id.

  • Search. Edges with the given id, label, out-vertex, in-vertex and properties. The incoming vertex is not an implicit endpoint: g.V().hasLabel("person").mergeE(#{"T.label": "knows"}).count().next() returns 8 (4 traversers × 2 knows edges).
  • Create. Needs both vertices after onCreate inheritance:
// --graph empty
g.mergeE(#{"T.label": "knows"}).toList()
// Caused by: Out Vertex not specified
// Help: An edge merge_e() creates needs both vertices: give "Direction.OUT" and "Direction.IN" an existing vertex id, ...

// modern graph
g.mergeE(#{"T.label": "knows", "Direction.OUT": "1", "Direction.IN": "100"}).toList()
// Caused by: Vertex id could not be resolved from mergeE: 100
  • The override rule covers "Direction.OUT"/"Direction.IN" too. "Direction.BOTH" is rejected (an edge has two named ends), and so is every Cardinality: edge properties have none. "T.id" sets the id of a created edge.

Cardinality

Graphersal stores one value per property key. Of TinkerPop's three cardinalities only Cardinality.single (replace the current value) is supported:

g.V("1").property(Cardinality.single, "age", 30).values("age").toList()   // 30
g.V("1").property(Cardinality.list, "age", 30).toList()
// Caused by: Cardinality.list is not supported: Graphersal stores one value per property key (property() would write a second value)
// Help: ... To keep several values, store them as one array value: g.v("1").property("tags", ["a", "b"]).
g.V("1").property("tags", ["a", "b"]).values("tags").toList()             // ["a", "b"]

Cardinality.list and Cardinality.set are accepted as tokens and fail with TraverserError::UnsupportedCardinality only when a value would be written, because that is where a second value would silently replace the first. A call that writes nothing succeeds, as in TinkerPop:

// --graph empty
g.addV("person").property(Cardinality.set, #{}).count().next()           // 1

The token works everywhere TinkerPop takes it: as the first argument of property(), as the default of a map (property(Cardinality.single, map), option(Merge.onCreate, map, Cardinality.single)) and per value with Cardinality.single(v):

g.mergeV(#{"name": "marko"}).option(Merge.onCreate, #{"age": Cardinality.single(29)}, Cardinality.single).values("age").toList()
// 29

On an edge any cardinality is an error ("Property cardinality can only be set for a Vertex").

property(map), property(T.id), property(T.label)

property(map) writes one property per entry; null / #{} write nothing. Its keys are plain property names (the reserved prefixes above are errors). The id and label of a vertex that addV() is creating are set with property(T.id, v) / property(T.label, v), anywhere among the property() calls that follow it:

// --graph empty
g.addV("person").property(#{"name": "marko", "age": 29}).valueMap().toList()
// #{"age": [29], "name": ["marko"]}
g.addV("person").property(T.id, "p1").property("name", "marko").elementMap().toList()
// #{"id": "p1", "label": "person", "name": "marko"}
g.addV("person").property(T.label, "animal").label().toList()             // "animal"

// modern graph: the id of an existing element cannot change
g.V("1").property(T.id, "p1").toList()
// Caused by: property(T.id, ..) can only set the id of an element addV()/addE() is creating

Direction, to/toE/toV and has(label, key, value)

Direction.OUT, Direction.IN and Direction.BOTH (aliases Direction.from = OUT, Direction.to = IN) are the merge-map keys above and the argument of the generic navigation steps: to(Direction, labels..) is out/in/both(labels..), toE(Direction, labels..) is outE/inE/bothE, and toV(Direction) is outV/inV/bothV. In Rust: to_direction, to_e, to_v.

g.V("1").to(Direction.OUT, "knows").values("name").toList()              // "josh", "vadas"
g.V("1").toE(Direction.OUT, "created").toV(Direction.IN).values("name").toList()   // "lop"
g.V("4").to(Direction.BOTH).values("name").toList()                      // "ripple", "lop", "marko"

The three-argument has(label, key, value) (and has(label, key, P)) combines hasLabel() and has(); in Rust has_labeled / has_labeled_p:

g.V().has("person", "name", "marko").values("age").toList()              // 29
g.V().has("person", "age", P.gt(30)).values("name").toList()             // "josh", "peter"

Confirming the lookup with profile()

A merge step looks elements up through the storage indexes, not through a nested traversal. .profile() names the strategy after the step: id ("T.id"), label ("T.label"), out-edges / in-edges (mergeE() with a known vertex), scan (only property keys) or dynamic (the map comes from a traversal). Add the missing key to turn a scan into an index lookup.

g.mergeV(#{"T.id": "1"}).profile()
// merge_v(#{"T.id": "1"}) [lookup: id]                            1       0       1  360.416µs    40.60
g.mergeV(#{"T.label": "person"}).profile()
// merge_v(#{"T.label": "person"}) [lookup: label]                 1       0       4    1.375µs    20.75
g.mergeV(#{"name": "marko"}).profile()
// merge_v(#{name: "marko"}) [lookup: scan]                        1       0       1    1.125µs    27.83
g.mergeE(#{"Direction.OUT": "1"}).profile()
// merge_e(#{"Direction.OUT": "1"}) [lookup: out-edges]            1       0       3   12.250µs    73.13

The three-argument has() folds its label into the source step:

g.V().has("person", "name", "marko").profile()
// v(labels: ["person"])                                           1       0       4    3.833µs    12.92
// has("name", "marko")                                            1       4       1   11.166µs    37.64
// Optimizer rules applied: source_filter_pushdown

Two limits of the profile output: a long step name is cut, so the [lookup: ..] suffix of a large map may not be visible, and the option traversals of one merge step share one nested row.

Not supported yet

  • Cardinality.list / Cardinality.set writes and meta-properties (property(key, value, metaKey, metaValue)): Graphersal has one value per key.
  • Removing a property by writing null (TinkerPop's @DisallowNullPropertyValues mode): Graphersal stores the null. This is deliberate: null is a real value of the property model, and the four @AllowNullPropertyValues scenarios, which expect it to be stored, pass; removing on null would trade them for the three @DisallowNullPropertyValues ones. Settling it would need a graph-level null mode (not scheduled). Remove a property explicitly with remove_property() instead, see Removing Properties.
  • PartitionStrategy and the other traversal strategies.
  • Multi-label merge ("T.label" as a list).

addE() Endpoints: property(), Traversals and Side Effects

addE() takes everything Apache TinkerPop's AddEdgeStep takes: property() calls between addE() and from()/to(), an endpoint given as a vertex, as a traversal, as a step label or as a side-effect key, and a label given as a traversal.

// property() before from()/to() (as() labels in between are fine too)
g.addV("p").as("a").addV("p").as("b").
  addE("knows").property("weight", 1).from("a").to("b")

// an endpoint is a vertex a query returned (TinkerPop's from(Vertex) / to(Vertex))
marko = g.V("1").next()
vadas = g.V("2").next()
g.addE("knows").from(marko).to(vadas)

// an endpoint is a traversal: its first result is the vertex (or the id of a vertex)
g.addE("knows").from(__.V("1")).to(__.V().has("name", "vadas"))
g.V("1").addE("knows").to(__.V("2").id())

// a traversal runs once per incoming traverser, and may create the vertex itself
g.addV().as("first").
  repeat(__.addE("next").to(__.addV()).inV()).times(5).
  addE("next").to(__.select("first"))

// an endpoint is a side-effect key
g.withSideEffect("b", "2").V("1").addE("likes").to("b")

// the label is a traversal: its first result must be a string
g.V().has("name", "marko").as("a").outE("created").as("b").inV().
  addE(__.select("b").label()).to("a")

Rules

  • Where from()/to() attach. They modulate the addE() before them, with any number of property() calls, as() labels and other from()/to() calls in between. After any other step (g.V().property("a", 1).from("x")) they still name that step in the error.
  • Endpoints. from()/to() take a vertex, a step label, a side-effect key, a vertex id, or a traversal. A vertex value (a vertex a query returned, a Python Vertex parameter, an edge's out_v/in_v) is that vertex, found by its id; it is never read as a step label or side-effect key, and a vertex no longer in the graph is an error. An edge value is an error. A name is looked up as the object last labelled so on the path (as()), then as a side effect of that key (a single value; an aggregate()/store() list or a set bucket is an error), then as a vertex id. A traversal endpoint is run on the incoming traverser (for g.addE(..) on a seed holding null) and its first result is used; no result is an error.
  • What an endpoint value may be. A vertex, or the id of a vertex present in the graph: a string or an integer (its decimal text). An edge, a path, a list, a map, a property element (properties()) and null are errors, and so is an id that matches no vertex. Nothing is created when an endpoint fails.
  • Labels. addE(traversal) runs the traversal on the incoming traverser before the endpoints and uses its first result, which must be a string; no result is an error.
  • One endpoint per traversal. The traversal of one from()/to() yields one vertex; to connect many vertices, run addE() per traverser.
  • Incoming traverser. With from() only, the incoming vertex is the to end; with to() only, it is the from end; with neither, the edge is a self-loop. With both, the incoming traverser is only the parent of the traversals and the owner of the path labels.

Rust API: from()/to() take names (&str, String, lists of them) and vertex values (ElementProperty::Vertex as next() returns it, VertexValue, an edge's VertexRef, or a Vec<ElementProperty> of vertices); from_by(traversal), to_by(traversal) and add_e_by(traversal) take traversals, on the traversal source, on __ (add_e_by) and on anonymous traversals.

use graphersal::prelude::*;

let mut graph = TraversalGraph::tinkerpop_modern();
let marko = graph.traversal_mut().v("1").next().unwrap().unwrap();
let vadas = graph.traversal_mut().v("2").next().unwrap().unwrap();
let edge = graph.traversal_mut().add_e("likes").from(&marko).to(&vadas).next().unwrap();
assert!(matches!(edge, Some(ElementProperty::Edge(_))));

Deviations

Documented from TinkerPop 3.8.2 behaviour as seen in its feature files; AddEdgeStep itself was not read.

  • A plain vertex id is an endpoint. A name that is neither a path label nor a side-effect key is treated as the id of a vertex (to("2")). TinkerPop resolves a string like select(key) only and fails when nothing is found.
  • A list of names creates one edge per name. to(["2", "3"]) creates two edges (a list of vertices likewise); TinkerPop takes exactly one endpoint. (Rhai's from([]) / to([]) is read as no argument and is ignored.)
  • Endpoint ids compare as strings. 2 and "2" are the same id, consistent with the id rule for hasId() and V().

Dropping Elements

drop() removes the incoming vertices or edges from the graph (a vertex together with its edges) and emits nothing. sideEffect(__.drop()) removes them and lets the traverser continue. To remove only properties, see Removing Properties.

g.V().hasLabel("software").drop()                 // remove all software vertices and their edges
g.V("1").outE("knows").drop()                     // remove two edges
g.V("1").sideEffect(__.drop()).count()            // remove and keep counting: 1

Dropping an element that is already gone is not an error; the step is idempotent.

An element dropped earlier in the same query

A traversal can still hold an element after it was dropped: through a step label (as("a") ... select("a")), a side effect (aggregate("x") ... cap("x")), a path, or a lazy value taken before the drop (values("name"), id(), label() are read only when they are returned). Graphersal never lets such a handle reach another element, even when a new element is stored in the freed place (generational handles): the removed element reads as removed.

Use of a removed elementResult
property reads (values(), properties(), has(k, v), by("k"))absent: nothing is emitted, has() filters it out
adjacency (out(), inE(), outV(), ...)empty
filters that need its data (hasLabel(), hasId(), has(T.id, ..))filtered out
id(), label(), returning it (materialization), elementMap(), a lazy values()/id() read after the droperror ElementRemoved
writes (property(), addE() to it)error ElementRemoved
drop() againno-op

An error here fails the whole traversal, and a failing traversal is rolled back: the drop itself is undone too (see Transactions).

g.V("1").as("a").sideEffect(__.drop()).addV("ghost").property("name", "GHOST").select("a").values("name")
// []  (the new vertex may take the freed storage place, but never the dropped one's handle)

g.V("1").outE().as("e").sideEffect(__.drop()).select("e").label()
// error: The edge was removed earlier in this query; its id, label and value are no longer available

To keep data of an element you drop, materialize it before the drop, for example with elementMap(), valueMap() or project():

g.V("1").as("a").elementMap().as("m").select("a").sideEffect(__.drop()).select("m")

Deviation from TinkerPop

TinkerGraph keeps id() and label() of a removed element on its element object, so select("a").id() after the drop still returns 1 there, and properties and edges are gone, as here. Graphersal keeps no data of a removed element (its storage place may already hold another element), so id(), label() and returning the element fail with ElementRemoved instead. The same holds for a lazy values(k)/id() taken before the drop and returned after it. outV()/inV() of a removed edge return its endpoints in TinkerGraph and nothing here. See TinkerPop Deviations.

Removing Properties

remove_property(keys...) (Gremlin spelling removeProperty) removes properties from the incoming vertices or edges and lets the element continue. A jpath(..) key removes a value below a stored property instead, see Path Keys (jpath).

g.V().hasLabel("person").remove_property("age")             // one key
g.V().remove_property(["age", "name"])                       // several keys, as an array
g.E().remove_property()                                     // every property of each edge
g.V("1").remove_property("age").values("name")              // the vertex flows on
  • A key the element does not carry is not an error; the step is idempotent (a bulk-n traverser removes once).
  • A value, map, path or property handle as input is a cast error (vertex or edge expected).
  • An empty array is an argument error, because it would silently mean "everything".
  • The step is mutating, like property(); it is never fused or reordered, and count() after it does not skip it.

Relation to properties(k).drop()

properties("age").drop() also removes the property, but it consumes the traverser (nothing is emitted) and needs a handle per key. remove_property("age") takes the element, names keys directly and emits the element, so it behaves like sideEffect(properties("age").drop()) without the handles.

Why a separate step, and why this name

property(k, null) stores a real null (see Upserts), so removal must be explicit. remove is the verb the storage layer uses for partial removals and the one Cypher/GQL use (REMOVE n.prop); the singular mirrors the writer property(k, v). drop_properties was rejected because drop() ends the stream, and a sentinel value in property(k, <sentinel>) cannot remove several keys or all keys and cannot come from a child traversal.

Deviations

  • remove_property() is a Graphersal extension. TinkerPop removes with properties(k).drop() or, in the @DisallowNullPropertyValues flavour, with property(k, null).
  • property(k, null) keeps storing null; the three @DisallowNullPropertyValues scenarios stay failing and are excluded from the compatibility numbers. remove_property() is the supported way.
  • Removal is checked against a declared schema (open and closed mode): removing a property in its label's required list is rejected, the element stays unchanged, and the error names the property and the label. This holds for remove_property(), properties(k).drop() and a one-segment jpath removal alike. Removing a property that is not required (whether or not its type admits null) or an undeclared one is allowed, and removing an absent property is a no-op. A property required by any of a multi-label vertex's labels cannot be removed. With schema mode None nothing is checked.
  • Several keys are passed as an array; there is no variadic form (start-up cost of the overload table).

Compressed Properties

Large text values that queries rarely read (a CV, a product description, a document body) can take most of a graph's memory. A compression rule names where such values live (an element kind, a label and a property path) and the graph keeps the strings there LZ4-compressed in memory. A traversal that reads one gets the plain string, decompressed on the fly; the graph never holds a decompressed copy. Nothing else changes: queries, results, change sets, exports and files see plain strings only.

// Strings of `customer` vertices at `details.career.cv` (and their `bio`) are kept compressed.
g.define_compression(#{name: "customer_cv", label: "customer", path: "details.career.cv"});
g.define_compression(#{name: "customer_bio", label: "customer", path: "bio", min_bytes: 512});
// An edge rule.
g.define_compression(#{name: "order_notes", element: "edge", label: "bought", path: "notes"});

g.v().has_label("customer").values(jpath("details.career.cv")).limit(1)   // plain text
g.compressions()                                                         // the rules and their stats
g.memory_usage()                                                         // compressed_values, ...

Long values that repeat across many elements (file paths, URLs, addresses, category or status texts) are a different case: a rule with codec: "dedup" stores each distinct value once and lets every element point to it.

Not sure a rule pays off, or which min_bytes to take? Estimate it first: g.estimate_compression(#{label: "customer", path: "bio"}) measures the candidate rules on the current data without changing anything.

When it pays off

  • Long strings (hundreds of bytes and more) that are written once and read seldom: CVs, descriptions, notes, logs, document bodies. Typical text compresses to 40 to 55 % of its size (measured below); highly repetitive text much further.
  • Not for short strings (names, codes): a value is compressed only when it is at least min_bytes long (default 256) and its compressed form is at most 90 % of the plain size; everything else stays plain.

The cost model

  • A read decompresses. values(), value_map(), element_map(), project().by(), order().by(), a jpath read, a result: each decompresses the value it reads (about 1.5 to 3 GB/s, below). A read that never touches the field costs nothing.
  • A filter on such a field decompresses every candidate. has("bio", TextP.containing("Rust")) reads the text of every vertex it tests. Filter on other properties first. A property index on the field serves equality and ranges without reading the candidates, but it holds the plain text (the memory compression saved).
  • A write compresses a string at a rule path (with the rule's dictionary). Only the touched top-level property is looked at; with no rule for the element's labels a write costs one lookup.
  • The disk stays plain. Snapshots, the write-ahead log, GraphSON and GraphML hold the plain text: the persistence layer compresses whole chunks and large WAL records already, compressing single values twice would only cost CPU. A load compresses the rule paths again in one pass (in parallel threads where the platform has them; dedup keys are coded while the elements are read, see "Deduplicating repeated values").

Rules

A rule is a definition of kind compression in the graph's catalog, next to the saved queries. It has:

FieldMeaningDefault
namean identifier, unique among the rulesrequired
element"vertex" or "edge""vertex"
labelthe label the rule applies to (it need not exist yet)required
patha property name or a jpath of names: "cv", "details.career.cv", jpath("$['a b'].c"); no index ([0], [-1]): arrays are not compressed in this versionrequired
codec"lz4" (compress each value) or "dedup" (store each distinct value once)"lz4"
min_bytesstrings shorter than this (UTF-8 bytes) stay plain; 1 to 16 MiB (lz4), 0 to 16 MiB (dedup, strings only: a dedup rule on a top-level key codes every other type)256 (lz4), 0 (dedup)
dictionarybuild a dictionary from the rule's values (lz4 only; true with dedup is refused)true (lz4), false (dedup)
  • Any number of rules: several paths on one label, the same path on different labels, vertex and edge labels. One rule per element kind, label and path: a second one is refused (DefinitionError::Conflict, its help names drop_compression).
  • Several labels of one vertex: every label's rules apply; when two labels have a rule for the same path, the first label in label order wins (the same rule as schema coercion).
  • A label change (add_vertex_label/remove_vertex_label, set_edge_label) compresses what a new label's rules cover and decompresses what no rule covers any more.
  • An lz4 rule compresses only strings: a number, an object or an array at its path stays as it is. A dedup rule on a top-level key takes every value type (below).

The explicit pass

Defining a rule, redefining it with other parameters, dropping it and loading the catalog run the pass over the rule's label in the same commit: every value at the old and the new path is re-encoded (compressed when it qualifies, decompressed when it no longer does). g.recompress(name) runs it again on demand and rebuilds the dictionary, for example after much data was added to a rule that was defined on an empty label. The pass changes no data: a commit hook sees only the SetDefinition of the rule, and a recompress alone commits nothing.

Dictionaries

With dictionary: true the pass builds a dictionary from a sample of the rule's current values (in id order, up to 1 KiB of each value, up to 64 KiB, the LZ4 window) and compresses with it, which helps short and similar texts most. A dictionary is in memory only: a load builds it again. A value written before a dictionary exists (a rule on an empty label) is compressed without one until the next recompress or load. Every compressed value carries its dictionary, so it stays readable when the rule changes.

Deduplicating repeated values

A rule with codec: "dedup" keeps one copy of every distinct value at its path, and every element whose value is that one keeps only a reference to it. Reads stay plain and cost nothing extra (the value is read in place, nothing is decompressed); query results, change sets, exports and files never change, and the files keep their format (plain values; a load shares them again).

// Every `symbol` vertex's `path`, `kind` and `visibility` (a few hundred distinct values over
// 100,000 symbols).
g.define_compression(#{name: "symbol_path", label: "symbol", path: "path", codec: "dedup"});
g.define_compression(#{name: "symbol_kind", label: "symbol", path: "kind", codec: "dedup"});
g.compressions()[0]          // compressed_values, distinct_values, ...

On a top-level property (a path of one name, the common case) a dedup rule takes every value type: strings of any length, numbers, booleans, dates and times, UUIDs, arrays, objects, vectors and null. The rule keeps a dictionary of the distinct values; the element's row holds a 4-byte code instead of the 32-byte value slot, and the value's heap (a long string's text, an array's elements, an object's entries) exists once, in the dictionary. Two values share an entry only when they are identical: the same type (the int 1 and the float 1.0 are two values), floats by their bits, a datetime with its offset and zone (one instant at two offsets is two values), arrays element by element and objects entry by entry in their key order. min_bytes (default 0) applies to strings only: a shorter string stays in the row; every other type is coded whatever its size.

Under a nested path (loc.file) a dedup rule shares strings only, and only those longer than 24 bytes and at least min_bytes (a string of at most 24 bytes is stored inline in its slot and owns no heap to share): the value inside the object keeps its slot and points to the one copy of its text in the rule's table.

When it pays: values repeated across many elements: file paths, URLs, kinds, states, flags, categories, dates, small lists of roles or line numbers. Measured on a code knowledge graph: the path of its symbols took 1.17 MB of heap for 816 distinct values, about 40 KB deduplicated; on a larger one (2.8 million elements) the advisor's dedup rules on 130 keys saved about 30 % of the property memory. Each coded value saves 28 bytes of its slot plus its heap; each distinct value costs its entry (52 bytes) and its heap once.

When it does not: mostly distinct values (ids, hashes, descriptions, CVs): every distinct value costs its entry, so a key whose values rarely repeat saves little or costs memory. The estimate warns with high_cardinality; for long unique text use lz4. The advisor recommends a dedup rule only where at most one value in eight is distinct and it saves at least 1 MiB.

The cost: a write of a coded key looks the value up in the dictionary (a hash of the value). Measured at query level on a real graph: overwriting a deduplicated key costs about 5-9 % more than a plain write; adding a key that is new to an element whose row is coded, and a jpath write into a deduplicated value, about 30 % more. Reads stay plain and are mostly faster (a filter on a coded key compares codes). A load codes the rule keys while it reads the elements: a snapshot holds its rules before its elements, so each row is coded as it enters the graph, straight into the dictionaries, and no plain copy of a coded value is kept until the end of the load. Opening a store with rules is then about as fast as opening it without them (measured on a real graph of 2.8 million elements with 74 dedup rules and two lz4 rules, --release, the embedding model loaded: 4.9-5.1 s with the rules; earlier versions took 5.2-5.3 s without the 74 dedup rules and 6.6-7.0 s with them).

The rule's numbers: compressed_values counts the values the rule holds (coded or shared, one per element), distinct_values the distinct values among them, plain_bytes and stored_bytes what they take without and with the rule. On a top-level key plain_bytes is each value's slot (32 bytes) plus its heap and stored_bytes each value's code (4 bytes) plus every distinct value once (its dictionary entry, 52 bytes, plus its heap); under a nested path plain_bytes is the text of each value and stored_bytes every distinct text once plus 32 bytes for it (a reference costs nothing beyond the slot a plain string occupies too). saved_bytes of an estimate is plain_bytes - stored_bytes.

A dictionary only grows while the graph runs; a value no element holds any more (overwritten, its element dropped) is removed when the dictionary is rebuilt: at the end of a transaction once it holds max(256, twice its entries at the last rebuild, an eighth of the label's elements) entries, after a rolled-back transaction that added values, on g.recompress(name), on g.shrink_to_fit() and on a load. A nested path's table is swept the same way when it has doubled since its last sweep. g.memory_usage() reports deduped_values, deduped_plain_bytes and dedup_table_bytes (the dictionaries, the coded rows' layouts and the nested paths' tables, every value once, part of property_bytes).

lz4 and dedup are one rule per element kind, label and path: redefining the rule with the other codec re-encodes its values in the same commit.

Warning (stores written by this version): a dedup rule with min_bytes 0 (the default since this version) cannot be read by Graphersal 0.5.2 and older: they report a store holding one as damaged. Upgrade the engine before opening such a store; this version reads every older store and its rules (min_bytes 25) as they were written. Rules defined by 0.2.1 to 0.5.2 code their non-string values too once this version loads them; strings shorter than their min_bytes stay in the row.

Warning (0.2.0): Graphersal 0.2.0 does not know the codec dedup and reads a store that holds a dedup rule as damaged from the commit that defined it on (maintenance mode; its repair would drop those commits). Do not open such a store with 0.2.0, and never run graphersal store repair from 0.2.0 on it; use 0.2.1 or later.

Several rules at once

Defining many rules one by one walks the elements of their labels once per rule and commits once per rule. A list of ordinary rules is stored in one unit: one commit (one WAL record), and one walk over the elements of all their labels re-encodes them for every rule together. Measured on a real graph (2.8 million elements, the advisor's 74 dedup rules, 11.9 million values coded, --release): one by one 8.6 s and 74 commits (13,932 bytes of WAL), as one list 1.5 s and one commit (2,210 bytes of WAL), with the same values coded and the same memory after a reopen. There is no wildcard or template rule: the list holds ordinary rules, each stored, listed, dropped and persisted like one defined alone. It is all or nothing: a refused rule (an invalid one, a conflict with a stored rule or with another rule of the list) fails the whole list with its error, which names the rule, and nothing is stored. Undoing such a unit (a rolled-back outer transaction) re-encodes in one walk as well.

g.define_compressions([#{label: "person", paths: ["name", "age"], codec: "dedup"}, #{name: "software_lang", label: "software", path: "lang", codec: "dedup"}])

Each item is define_compression's map, or the short form #{label, paths: [..], element?, codec?, min_bytes?, dictionary?}: one rule per path, each named <label>_<path> (the path's names joined by _, _edge added for an edge rule, characters a name may not hold replaced by _), the advisor's naming. A short form has no name. The call answers the number of rules stored and asks for Create (Update for a name already stored) on each rule before anything changes.

Dropping a list is the way back: one commit, one walk over the elements of all the labels, and the values are stored in full again. A name that is not stored is skipped; the call answers the number of rules removed and asks for Delete on each rule before anything changes. In the playground: Catalog ▾ ▸ Compression, tick a group or some rules, Drop selected.

g.define_compressions([#{label: "person", paths: ["name", "age"], codec: "dedup"}]);
g.drop_compressions(["person_name", "person_age"])

The advisor groups its recommendations the same way (dedup: 74 keys, total -400.1 MiB) and applies a picked group in one commit too.

On a store, write a snapshot after changing rules (graphersal store checkpoint <DIR>, or the playground's Store menu): until one holds them, every open re-encodes the labels of the rules once, with a higher memory peak. See Optimize.

A rule from a newer version

A store (or a catalog file, a change set) written by a newer Graphersal may hold a rule whose codec or element this version does not know, or whose path it cannot parse. Since 0.2.1 such a rule is never damage: it is kept in the catalog exactly as read and written back unchanged (its payload byte for byte through the journal, checkpoints, backups, forks and snapshots), but it is not applied: its values stay plain in memory, as they are on disk anyway. g.compressions() (and the playground, the dev server and MCP's list_compressions, Python's compressions()) shows it with the codec, element and path as read, served: false and a reason such as codec 'zstd' is not known to this version; g.recompress(name) refuses it with that reason. It can be dropped like any rule. A rule of a known codec on the same element kind, label and path conflicts with it (so the newer version never finds two rules on one path). Creating a rule of an unknown codec is refused by every front end (they take only the known codec names).

Estimating the gain

Before defining a rule, an estimate measures what rules for one element kind, label and path would hold over the current values, without changing the graph (no commit, no catalog change, no value re-encoded; it only reads):

g.estimate_compression(#{label: "person", path: "name"})   // short names: nothing qualifies
let e = g.estimate_compression(#{label: "customer", path: "bio"});
e.candidates[e.best]          // the candidate that saves the most
// Only some candidates: each key given narrows the set.
g.estimate_compression(#{label: "customer", path: "details.career.cv", min_bytes: 512});
g.estimate_compression(#{element: "edge", label: "bought", path: "notes", dictionary: false});
// Deduplication, alone or side by side with lz4.
g.estimate_compression(#{label: "symbol", path: "path", codec: "dedup"});
g.estimate_compression(#{label: "symbol", path: "path", codec: ["lz4", "dedup"]});

Without codec, min_bytes and dictionary the candidates are lz4 without and with a dictionary at min_bytes 64, 128, 256, 512 and 1024, plus the parameters of the rule that covers the path today (if any, a dedup rule too). codec: "dedup" measures dedup at min_bytes 0, 25, 64, 128 and 256 (on a top-level key counting every value type, with the dictionary's exact identity); a list of codecs measures each codec's candidates. The answer:

KeyMeaning
elements, values_found, string_values, string_bytesthe elements carrying the label, how many have a value at the path, how many of those are strings, and their size
histogramthe strings by size (min_bytes, max_bytes, values, bytes; buckets from 64 B to 16 KiB), to choose min_bytes
candidatesper candidate: codec, min_bytes, dictionary, compressed_values (the strings it would compress or share), plain_bytes, stored_bytes, dictionary_bytes, distinct_values (dedup: the distinct texts among them), saved_bytes (= plain - stored - dictionary; negative: the rule costs memory), ratio, current (the parameters of today's rule), encode_bytes_per_sec and decode_bytes_per_sec (the speed measured on this data: a read of a compressed value pays the decode; () for dedup, whose reads cost nothing extra)
bestthe index of the candidate that saves the most, () when none saves anything
currenttoday's rule on that path (name, parameters and what it holds now), the baseline
warningsunknown_label (no element has the label: a typo?), no_values (nothing at the path), not_strings (values a rule never compresses), nothing_qualifies, no_saving, high_cardinality (dedup would share values but saves nothing: they are mostly distinct)
sampled, measured_valueswhether the candidates were measured on a sample (below)

The estimate is the rule. The trial dictionary is built by the same code as a defined rule's (the values in id order, up to 1 KiB of each, up to 64 KiB) and a value counts exactly when the rule's write path would compress it, so the numbers of a candidate are what g.compressions() reports after defining that rule on the same data. The byte counts are those of the rule's stats: the plain and the compressed size of the values and the dictionary, not the per-value bookkeeping.

Bounded. The estimate compresses at most 100,000 strings and 16 MiB of plain text per dictionary setting. Above either cap it compresses a deterministic sample (every k-th string in id order), says sampled: true, and extrapolates each candidate from the exact count and size of the strings that reach its threshold; the counts and the histogram stay exact, and so do the dedup candidates (they need no trial compression: every string is counted). A running estimate stops when the host cancels (the dev server's Stop, a CancelToken).

It reads the data of that label, so it asks for Read on Data of that element kind and label, never for a catalog write: AccessPolicy::read_only(), the MCP read-only mode and a saved query may estimate. A storage without compressed properties answers Unsupported.

In the playground, the rule form of Catalog ▾ ▸ Compression has a Codec choice (lz4 or dedup; the dictionary is lz4 only) and an Estimate button once the label and the path are filled: a table of the lz4 and dedup candidates (with the distinct values of each dedup candidate) with a saving bar each, the best one highlighted, the note "the graph was not changed", and Use copying a candidate's codec, minimum size and dictionary into the form.

API

DefineListDropRecompressEstimate
Rhaig.define_compression(#{..}), g.define_compressions([#{..}, ..])g.compressions()g.drop_compression(name)g.recompress(name)g.estimate_compression(#{label, path, element?, codec?, min_bytes?, dictionary?})
Rust (GraphTraversalSource)define_compression(name, CompressionDefinition), define_compressions([(name, rule), ..]), set_definition(Definition::compression(..)), set_definitions(vec![..])list_definitions(Some(DefinitionKind::COMPRESSION)), compression_stats(name)remove_definition(DefinitionKind::COMPRESSION, name)recompress(name)estimate_compression(&CompressionEstimateRequest)
Python (Graph)define_compression(name, label, path, element="vertex", min_bytes=None, dictionary=None, codec=None), define_compressions([{..}, ..])compressions()drop_compression(name)recompress(name)estimate_compression(label, path, element="vertex", min_bytes=None, dictionary=None, codec=None)
PlaygroundCatalog ▾ ▸ Compression: the rules with their stats, a form with field errors and Estimate
Dev serverPOST /api/compression/defineGET /api/compressionPOST /api/compression/dropPOST /api/compression/recompressPOST /api/compression/estimate
MCPdefine_compressionlist_compressionsdrop_compressionrecompressestimate_compression (also read-only)

g.compressions() lists each rule with compressed_values, plain_bytes, stored_bytes, dictionary_bytes and distinct_values (dedup). g.memory_usage() (and MemoryStats) adds compressed_values, compressed_plain_bytes, compressed_stored_bytes and compression_dictionary_bytes (lz4), and deduped_values, deduped_plain_bytes and dedup_table_bytes (dedup); property_bytes counts the compressed (stored) size and every shared text once.

use graphersal::prelude::*;
use graphersal::{catalog::CompressionDefinition, storage::ElementKind};

let mut graph = TraversalGraph::new();
let rule = CompressionDefinition::new(ElementKind::Vertex, "customer", "details.career.cv")
    .unwrap()
    .with_min_bytes(512)
    .with_dictionary(false);
graph.traversal_mut().define_compression("customer_cv", rule).unwrap();

Several rules in one unit, one commit and one walk (a storage gets the list through GraphStorage::set_definitions, whose default stores them one by one):

use graphersal::prelude::*;
use graphersal::catalog::{Codec, CompressionDefinition};
use graphersal::storage::ElementKind;

let mut graph = TraversalGraph::tinkerpop_modern();
let dedup = |key: &str| {
    let rule = CompressionDefinition::new(ElementKind::Vertex, "person", key).unwrap();
    (format!("person_{key}"), rule.with_codec(Codec::Dedup))
};
graph.traversal_mut().define_compressions([dedup("name"), dedup("age")]).unwrap();

The estimate in Rust (graphersal::catalog: CompressionEstimateRequest, CompressionCandidate, CompressionEstimate); a storage implements it as GraphStorage::estimate_compression:

use graphersal::prelude::*;
use graphersal::catalog::{CompressionCandidate, CompressionDefinition, CompressionEstimateRequest};
use graphersal::storage::ElementKind;

let mut graph = TraversalGraph::new();
let request = CompressionEstimateRequest::new(ElementKind::Vertex, "customer", "bio")
    .unwrap()
    .with_candidates([CompressionCandidate::lz4(256, true), CompressionCandidate::lz4(512, false)]);
let estimate = graph.traversal().estimate_compression(&request).unwrap();
if let Some(best) = estimate.best {
    let rule = CompressionDefinition::new(ElementKind::Vertex, "customer", "bio").unwrap();
    let rule = estimate.candidates[best].candidate.apply_to(rule);
    graph.traversal_mut().define_compression("customer_bio", rule).unwrap();
}

Authorization: a rule is the resource Definition { kind: compression, name }: define asks Create (Update when it replaces one; a list asks it for each rule before anything changes), drop Delete, recompress Update, listing Read. No data request is made (the logical data does not change). AccessPolicy::read_only(), the MCP read-only mode and a saved query (which never writes the catalog) cannot change rules. An estimate asks Read on the Data of its element kind and label.

The catalog file: rules travel with the saved queries in one catalog file ({"definitions": [..]}, the playground's Catalog ▾ ▸ Save catalog, the dev server's GET /api/catalog/export); loading it stores the rules and compresses their values at once. A snapshot and a Store carry the catalog, so a rule survives every store operation (WAL replay, checkpoint, fork, backup, restore, repair, rollback); the files hold plain values, and the load compresses again. A version that does not know the kind keeps the rule unchanged and only loses the compression (the definition is not critical). A version that knows the kind but not the codec (0.2.0 reading a dedup rule written by 0.2.1), or a threshold it refuses (0.5.2 and older reading a dedup rule with min_bytes 0), reports the definition as damage; drop dedup rules before opening a store with an older version.

In the playground, Catalog ▾ ▸ Compression lists the rules with their statistics (here 400 customer biographies, about 1 KiB each) and defines, edits, recompresses and drops them. The table sorts by any column (at first by the bytes saved) and groups the rules by codec or by label, with the total each group saves; a group of many rules starts collapsed. A checkbox per rule and per group selects them for Drop selected, which asks first and drops them all in one commit:

The compression manager: a rule with its values, plain and stored size, ratio and the bytes saved

Measured

On a generated CV-like corpus of 5,000 texts of 2 to 20 KB (55 MB: section headers, sentences from a 200-word vocabulary, company names, years and numbers), Apple M-series, --release (compressed_property_tests::measure_ratio_and_throughput, an #[ignore]d test):

Stored / plainDictionaryDefine pass (compress)Read (decompress + materialize)
LZ40.52none451 MB/s2,741 MB/s
LZ4 with dictionary0.4264 KiB328 MB/s1,626 MB/s

The compression figures include a round-trip check of every value (a compressed value is verified once when it is made, so reading it back cannot fail). A highly repetitive corpus (a dozen phrases recombined) compresses to 0.07 (0.05 with a dictionary). The figures come from a source build, not from the musl-linked prebuilt Linux binary (Performance of the prebuilt Linux binaries).

Vectors

New to embeddings? Embeddings and Vector Search is the task-oriented tour: semantic search, filtered search, GraphRAG and recommendations, in the playground with toy vectors and in Python with a real model. This page is the reference.

A vector is a fixed-length list of numbers stored as one value: an embedding of a text, an image or a node, as a language or vision model computes it. A property holds a vector, not a list that happens to contain numbers, and the engine stores it compactly, converts it between element kinds and compares it as one value. Vectors are a Graphersal extension: TinkerPop has no vector type.

The engine never calls a model on its own. A query that reached out to an embedding service by itself would depend on the network, could not be rolled back (a paid call stays paid) and would not run in the browser playground. The host either computes embeddings itself (in Python, in an MCP tool, in a server) and writes them as ordinary property values, or registers embedders that the embed step calls (Embeddings below); one small embedder, hash-ngram/1, is built in.

type_of(vector([0.12, -0.5, 0.33]))   // "Vector"
vector([0.12, -0.5, 0.33]).dimension   // 3
vector([0.12, -0.5, 0.33], "i8").element   // "i8"
g.inject(vector([0.5, 1.0])).is(P.typeOf(GType.VECTOR)).count().next()   // 1

Element kinds and quantization

A vector has 1 to 65 536 components, all of one element kind:

ElementA componentBytes per component768 components
f32 (default)an IEEE single-precision float43 KiB
f16an IEEE half-precision float21.5 KiB
i8an 8-bit code times one f32 scale per vector (value = code * scale)1768 B
bitone sign bit: 1.0 for a set bit, -1.0 otherwise1/896 B

A list of 768 numbers as a plain array takes about 24 KiB; the same vector as f32 3 KiB.

Quantization converts a vector to another element kind, to save memory at a small cost in precision:

  • f32 to f16 rounds every component to the nearest half value (ties to even). A component beyond the half range (65 504) is an error, never an infinity.
  • f32 to i8 is symmetric scalar quantization: scale = max |x| / 127, code = round(x / scale) in -127..=127. A zero vector has scale 0.
  • f32 to bit keeps the sign: a component > 0 sets its bit (binary quantization).
  • Every other conversion goes through the f32 values, so quantize("f32") dequantizes.
vector([0.5, -1.0, 0.25]).quantize("bit").to_list()   // [1.0, -1.0, 1.0]
vector([0.5, -1.0, 0.25]).quantize("f16").to_list()   // [0.5, -1.0, 0.25]
g.inject(vector([0.5, -1.0, 0.25])).quantize("i8").next().element   // "i8"
vector([1e10], "f16")   // fails: the component is beyond the range of an f16 vector

All four kinds are part of the value type and of every file format from the start, so storing a property quantized is a choice of the data, never a format change.

Building vectors

  • vector(list) builds an f32 vector of a list of numbers; vector(list, kind) quantizes it to "f16", "i8" or "bit".
  • The as_vector() step converts a list of numbers in a traversal (a stored list, a fold()); a vector passes, null stays null.
  • A schema that declares the property as a vector converts a written list on write (below).

A vector never holds NaN or an infinity (it would break ordering and comparison); -0.0 is kept and equals 0.0. An empty list, a component that is not a number and more than 65 536 components are errors:

g.inject([0.5, 1]).as_vector().next()   // vector([0.5, 1.0])
g.inject(1, 2, 3).fold().as_vector().next().dimension   // 3
vector([])   // fails: a vector has 1 to 65536 components
vector([1, "x"])   // fails: component 1 is not a number

A vector prints as its DSL literal, which evaluates back to the same vector (an i8 or bit vector shows its dequantized values and its kind): vector([0.5, 1.0]), vector([0.503937, -1.0], "i8"). to_string() and the step names in .profile() cut it after 16 components, like a list. In a script a vector has the getters element and dimension and the methods quantize(kind) and to_list() (the values as floats).

Writing, filtering and ordering

A vector is written like any other value, and has() compares it by value: the same element kind, the same dimension and equal components. A list is never equal to a vector, and an f16 vector never equals an f32 one, even with the same values:

g.add_v("doc").property("title", "Graphs").property("emb", vector([0.1, 0.9])).iterate();
g.add_v("doc").property("title", "Vectors").property("emb", vector([0.8, 0.2])).iterate();
g.v().has("emb", vector([0.1, 0.9])).values("title").next();   // "Graphs"
g.v().has("emb", [0.1, 0.9]).count().next();   // 0
g.v().has_label("doc").order().by("emb").values("title").to_list()   // ["Graphs", "Vectors"]

Vectors order (a Graphersal extension) after the dates and before strings; among themselves by element kind (f32, f16, i8, bit), then by dimension, then component by component. A vector is one value in the local steps (count(Scope.local) is 1, unfold() passes it), and min()/max() refuse it.

A property index never holds vectors: has(key, vector) on an indexed key reads the elements by a scan, with the same result.

Quantize an existing property with one write per element, then declare the new element in the schema (g.patch_schema(..), below). This works as shown while no schema declares the property; when the schema already declares it as f32 (mode open or closed), a write is converted back to f32 and the new element is refused while f32 data remains: the migration recipe for that case (mode none for the rewrite, one unit) is in Embeddings and Vector Search.

g.add_v("doc").property("emb", vector([0.5, -1.0, 0.25])).iterate();
g.v().has_label("doc").has("emb").property("emb", __.values("emb").quantize("i8")).iterate();
g.v().values("emb").next().element   // "i8"

Vectors in a schema

A schema declares a vector property as an array with the custom format vector:

{"type": "array", "format": "vector", "element": "i8", "dimension": 768, "metric": "cosine"}
  • element (default f32) and dimension (optional: any dimension) are checked exactly: a stored vector of another kind or length does not conform. metric (cosine, dot, l2, hamming) is an annotation: the metric the vectors are meant to be compared with, which similarity() and nearest() use when the query names none (Metrics). It never changes or checks any data.
  • embedder (on a label's top-level property only) records the model identity of the embedder that produced the vectors ("hash-ngram/1"): a vector rule embeds with it and the text queries read it (Which model produced a property). A plain write does not check it.
  • from (with embedder, on a label's top-level property only) makes the property a vector rule: the engine embeds the text of from into it at the end of every unit that writes it, and refuses direct writes of it.

Warning: a vector rule ("from" on a vector property) added or changed fills every element of its label in the schema-changing unit, and the WHOLE database is locked while it runs: every write and every read waits until it ends. The schema preview (validate_schema, diff_schema) reports how many elements and how long first.

  • items is not allowed next to the format (the components are numbers of the element kind).
  • Another JSON Schema validator ignores the unknown format and keywords and sees an array of numbers, which is what a vector exports as. The schema visualizer's per-label JSON Schema (visualize("jsonschema")) spells out items and minItems/maxItems for it.

In mode open or closed, a list of numbers written to the property becomes a vector of the declared element, and a vector of another element is quantized to it: a property is stored quantized from the start, whatever the host sends. The dimension is never changed:

g.set_schema(#{mode: "open", vertices: #{doc: #{schema: #{type: "object", properties: #{
  emb: #{type: "array", format: "vector", element: "i8", dimension: 3}}}}}});
g.add_v("doc").property("emb", [0.5, -1.0, 0.25]).iterate();
g.add_v("doc").property("emb", vector([1.0, 2.0, 3.0])).iterate();
g.v().values("emb").to_list().map(|v| v.element)   // ["i8", "i8"]

On that graph, g.add_v("doc").property("emb", [1.0, 2.0]) fails with "Type mismatch on vertex 'doc.emb': expected vector<i8, 3>, got vector<i8, 2>", and its help names the conversion (values("emb").as_vector().quantize("i8")).

infer_schema() reports a vector as such, with its dimension when every vector of that element at the position has the same one. diff_schema() counts a change of element or dimension (and a list turned into a vector, or back) as incompatible, since the stored data no longer conforms; dropping dimension (any dimension) is compatible. An embedder change is the entry embedder_changed: declaring one where there was none is compatible, changing it is not (the stored vectors and a text query embedded by the new model are no longer comparable), and removing it is not either (a text query on the property no longer finds its model). infer_schema() never reports an embedder: nothing in the data says which model made a vector. A saved query takes a vector parameter the same way: params: #{q: #{schema: #{type: "array", format: "vector", element: "f32", dimension: 768}}}; a list argument is converted to the declared vector.

Similarity

similarity() scores a vector against a query vector q and yields a float64. It is a map step in two forms:

FormScores
similarity(key, q[, metric])the vector property key (a name or a jpath(..)) of the incoming element (or map)
similarity(q[, metric])the incoming value itself, a vector (values("emb").similarity(q), a computed vector)

q is a vector, a list of numbers (made an f32 vector when the step is built), or an anonymous traversal run on each incoming traverser whose first result is the query (__.select("q")). The key form drops an element without the property or whose value is not a vector; the value form drops null and fails on any other value that is not a vector.

g.add_v("doc").property("title", "Graphs").property("emb", vector([0.6, 0.8])).iterate();
g.add_v("doc").property("title", "Vectors").property("emb", vector([1.0, 0.0])).iterate();
g.v().has_label("doc").similarity("emb", vector([1.0, 0.0])).to_list();   // [0.6000000095367428, 1.0]
g.v().has_label("doc").values("emb").similarity([0.0, 0.0], "l2").to_list();   // [1.000000023841858, 1.0]
g.v().has_label("doc")
 .project("title", "score").by("title").by(__.similarity("emb", vector([1.0, 0.0])))
 .to_list()

Metrics

MetricScoreCloser isVectors
cosine (default)the dot product over the product of the norms, -1 to 1; 0.0 when either vector is zero (never NaN)higherany kind except bit against non-bit
dotthe dot producthigheras cosine
l2the Euclidean distancesmalleras cosine
hammingthe number of differing bitssmallerbit vectors only

The metric is the step's argument if it names one; otherwise the metric annotation the stored schema declares for the property (a top-level name on a vertex or edge, by the element's labels like a write; for the value form, the property a values("emb") reference points to), and cosine without one. A computed vector, a jpath key and a map have no declaration: cosine.

Scores are exact: every component is read from the stored kind (an f16 or i8 vector dequantized, bits counted) and summed in f64, in a fixed order, so the same vectors always give the same score. Vectors of different element kinds compare through their values: an i8 property can be searched with an f32 query. A bit vector compares only with another bit vector (for which the dot product, cosine and distance follow exactly from the Hamming distance, the components being ±1). Two vectors of different dimensions are an error, never truncated:

g.inject(vector([1.0, 0.0])).similarity(vector([1.0, 0.0, 0.0])).next()   // fails: vectors of dimensions 2 and 3 cannot be compared
g.inject(vector([1.0, -1.0], "bit")).similarity(vector([1.0, -1.0])).next()   // fails: a bit vector compares only with another bit vector
g.inject(vector([1.0, -1.0], "bit")).similarity(vector([1.0, 1.0], "bit"), "hamming").next()   // 1.0

Exact search: nearest()

nearest(key, q, k[, #{metric: ".."}]) keeps the k incoming elements whose vector property key is closest to q, best first (the highest cosine or dot, the smallest l2 or hamming). It is an exact search: every incoming element is scored, with a bounded heap of k (O(n log k), never a full sort).

  • Elements without the property, or whose value is not a vector, are skipped.
  • Equal scores keep the input order, the earlier element first: the answer is deterministic, the same in a live graph, a view at a commit and a fork.
  • q is a vector, a list of numbers or a traversal. A traversal runs for every scored element and must give the same vector each time (one query per search, "more like this" below); a query that depends on the element fails and names similarity(), which scores each element against its own vector.
  • The metric follows the same rule as for similarity(). Without a metric argument, elements whose labels declare different metrics fail: one search ranks with one metric.
  • Bulk counts as in limit(): a traverser that stands for n equal ones is n results, cut at k.
  • .profile() shows the step as written, nearest("emb", vector([..]), 10, #{metric: "l2"}); the deadline (evaluationTimeout) and a cancel stop it while it scores.
g.add_v("doc").property("title", "Graph databases 101").property("emb", vector([0.9, 0.1, 0.0])).iterate();
g.add_v("doc").property("title", "Vector search").property("emb", vector([0.1, 0.9, 0.1])).iterate();
g.add_v("doc").property("title", "Indexes").property("emb", vector([0.6, 0.6, 0.2], "i8")).iterate();
g.add_v("doc").property("title", "Draft").iterate();
g.v().has_label("doc").nearest("emb", vector([1.0, 0.2, 0.0]), 2).values("title").to_list();   // ["Graph databases 101", "Indexes"]
g.v().has_label("doc").nearest("emb", [0.0, 1.0, 0.0], 1, #{metric: "l2"}).values("title").next()   // "Vector search"

nearest() is the same as ordering by the score and keeping k, which is how to get the scores along with the elements:

g.add_v("doc").property("title", "a").property("emb", vector([1.0, 0.0])).iterate();
g.add_v("doc").property("title", "b").property("emb", vector([0.6, 0.8])).iterate();
let q = vector([1.0, 0.1]);
g.v().has_label("doc").nearest("emb", q, 2)
 .project("title", "score").by("title").by(__.similarity("emb", q))
 .to_list()

Filtered search

Filter first, then search: has_label() and has() before nearest() reduce what it scores (a has_label() folds into v() as usual, a property index serves a has()), and a where() can filter by the graph around each element:

g.add_v("team").property("name", "engineering").as("eng")
 .add_v("doc").property("title", "Design").property("lang", "en").property("year", 2026)
   .property("emb", vector([0.9, 0.1])).add_e("owned_by").to("eng")
 .add_v("doc").property("title", "Entwurf").property("lang", "de").property("year", 2026)
   .property("emb", vector([0.9, 0.1])).add_e("owned_by").to("eng")
 .iterate();
g.v().has_label("doc")
 .has("lang", "en").has("year", P.gte(2026))
 .where(__.out("owned_by").has("name", "engineering"))
 .nearest("emb", vector([1.0, 0.0]), 5)
 .values("title").to_list()   // ["Design"]

GraphRAG: a vector hit, then the graph

Retrieval-augmented generation over a graph finds the chunks nearest to the question's embedding and expands along the edges to build the context:

g.add_v("doc").property("title", "Graphersal").as("d")
 .add_v("entity").property("name", "Rhai").as("e")
 .add_v("chunk").property("text", "Graphersal runs Gremlin in Rhai.").property("emb", vector([0.9, 0.2]))
   .add_e("part_of").to("d")
 .add_e("mentions").from("d").to("e")
 .iterate();
g.v().has_label("chunk").nearest("emb", vector([1.0, 0.1]), 5).as("hit")
 .out("part_of").as("doc")
 .out("mentions").has_label("entity").as("ent")
 .select("hit", "doc", "ent").by("text").by("title").by("name")
 .to_list()

The embedding of the question comes from the host (the model is never called by the engine), as a query parameter or the argument of a saved query: params: #{q: #{schema: #{type: "array", format: "vector", dimension: 384}}} with the body g.v().has_label("chunk").nearest("emb", q, k). MCP clients and the AI Chat call such a query with run_saved_query.

More like this

The query vector can come from the graph itself: label it, then search with __.select(..):

g.add_v("doc").property("id", "d42").property("emb", vector([1.0, 0.0])).iterate();
g.add_v("doc").property("id", "d7").property("emb", vector([0.9, 0.1])).iterate();
g.add_v("doc").property("id", "d9").property("emb", vector([0.0, 1.0])).iterate();
g.v().has("id", "d42").as("me").values("emb").as("q")
 .v().has_label("doc").where(P.neq("me"))
 .nearest("emb", __.select("q"), 2)
 .values("id").to_list()   // ["d7", "d9"]

Recommendations with vector_mean()

vector_mean() is a reducing barrier (like mean()): the component-wise mean of the incoming vectors, as an f32 vector. An incoming list of vectors (fold()) counts each of its vectors, null is skipped, quantized vectors count with their values, an empty stream gives no result, and vectors of different dimensions fail. local(__.unfold().vector_mean()) averages each list on its own. The mean of what a user liked is a taste vector to search with:

g.add_v("user").property("name", "u7").as("u")
 .add_v("article").property("title", "Graphs").property("emb", vector([1.0, 0.0])).as("a")
 .add_v("article").property("title", "Trees").property("emb", vector([0.8, 0.4])).as("b")
 .add_v("article").property("title", "Cooking").property("emb", vector([0.0, 1.0]))
 .add_v("article").property("title", "Forests").property("emb", vector([0.9, 0.3]))
 .add_e("liked").from("u").to("a").add_e("liked").from("u").to("b").add_e("read").from("u").to("a")
 .add_e("read").from("u").to("b")
 .iterate();
g.v().has("name", "u7").out("liked").values("emb").fold().vector_mean().as("taste")
 .v().has_label("article")
 .where(__.in("read").has("name", "u7").count().is(0))
 .nearest("emb", __.select("taste"), 1)
 .values("title").next()   // "Forests"

Performance

The search is an exact scan: its time grows with the number of scored elements times the dimension, and it needs no index, so it costs nothing to keep up to date and answers the same at every commit, mark and snapshot. Measured with the bench nearest_10k_x_384 (cargo bench -p graphersal --bench graph --features io,script,display,serde -- nearest_10k_x_384): 10 000 vertices with a random 384-dimensional embedding, v().has_label("doc").nearest("emb", q, 10), on an Apple M3:

Stored elementMetricMedianPer vector
f32cosine1.3 ms130 ns
f16cosine2.3 ms230 ns
i8cosine1.8 ms180 ns
bithamming0.21 ms21 ns

So about 13 ms per 100 000 f32 vectors of 384 components: enough for most in-memory graphs, and a filter before the search (above) scores fewer. There is no approximate (ANN) index yet (see Current Limitations). These figures come from a source build, not from the musl-linked prebuilt Linux binary (Performance of the prebuilt Linux binaries).

Quantization: memory against accuracy

A quantized property takes less memory and gives approximately the same answers. Measured by the test quantized_search_recall_against_f32 on 2 000 random 128-dimensional vectors (20 queries, recall@10 against the f32 search with cosine); random vectors are the hardest case, real embeddings usually keep more:

Stored asBytes per 384 componentsrecall@10
f321 5361.00 (exact)
f167681.00
i8384 (+ 4 for the scale)0.99
bit (hamming)480.30
bit top 100, re-ranked by f3248 + 1 5360.74

Bit vectors are a coarse, very fast prefilter: keep both properties and re-rank the prefilter's hits exactly, nearest("emb_bit", q.quantize("bit"), 100, #{metric: "hamming"}) followed by nearest("emb", q, 10).

Embeddings

An embedder turns text into vectors. The step embed() embeds the incoming string, embed(key) the string property key (a name or a jpath(..)) of the incoming element, and the function embed(text) makes a query vector before any traversal runs. The embedders of a graph are the built-in hash-ngram/1 and the embedding models kept in its database (imported into a Store, or carried by a .gsnap file: Embedding Models in a Store). Each step and function takes an option map naming the embedder, #{embedder: "name"} (a model by its repository, minishlab/potion-base-8M); without it the database's default model runs, else hash-ngram/1. g.embedders() lists them:

g.embedders()[0].name   // "hash-ngram/1"
embed("graph").dimension   // 256
g.v().has_label("person").embed("name").count().next()   // 4
g.v().embed("name", #{embedder: "hash-ngram/1"}).count().next()   // 6
g.v().values("age").embed().next()   // error: embed() takes a string, not int64
g.v().embed("name", #{embedder: "nope"}).next()   // error: there is no embedder "nope"

Rules of the step:

  • an element without the property is dropped (like values(key)); a value that is not a string fails: nothing is converted implicitly, write as_string() first;
  • an empty text, or one with no word at all, fails (has(key, P.neq("")) leaves them out);
  • the step hands the embedder batches (up to the embedder's max_batch traversers per call), each traverser once whatever its bulk, and keeps the order;
  • .profile() names the embedder that ran: embed("name", embedder: "hash-ngram/1");
  • writing the vectors (property("emb", __.embed("text"))) happens inside the traversal's unit under the graph's write lock, which suits a fast local embedder such as the built-in one;
  • a property declared {"type": "array", "format": "vector", "dimension": 384} refuses a vector of another dimension or element kind, as for any write (Vectors in a schema).

A fuzzy name search on the modern graph:

g.v().has_label("person").property("name_emb", __.embed("name")).iterate();
g.v().has_label("person").nearest("name_emb", embed("Markus"), 2).values("name").to_list()   // ["marko", "vadas"]

What g.embedders() returns for each embedder:

Key
namewhat #{embedder: ..} takes: hash-ngram/1, or a model's repository
modelthe stable identity of what computes the vectors (hash-ngram/1, model2vec/minishlab/potion-base-8M@fac4fa854e68), independent of any file path: two embedders of one model give comparable vectors
dimension, elementthe shape of every vector it returns
metricthe metric it recommends for comparing them
max_batchthe most texts per call
deterministicwhether the same text always gives the same bits
localwhether the texts stay in the process
defaultwhether it runs without an embedder option

Running an embedder asks Execute on the resource Embedder("name"), for every embedder including the built-in one (Permissions); AccessPolicy::read_only() allows it, and a saved query may embed. A computed vector is stored as a plain value: replay, recovery, change sets and loads never call an embedder, so an embedder that is not deterministic is safe to use.

Filling a vector property

A vector rule fills a vector property from a text property of the same label and keeps it in step: the schema names the source with from beside the model in embedder, and the engine embeds the text at the end of every unit that writes it (the first fill embeds every element of the label when the rule is applied):

"emb": {"type": "array", "format": "vector", "embedder": "hash-ngram/1", "from": "name"}

A rule embeds with the built-in hash-ngram/1 or a model of the database (Models in the store). Without a rule, write the vectors in a query of your own, and again for the elements whose text changed:

g.v().has_label("person").property("emb", __.embed("name")).iterate()

(__.embed("name", #{embedder: "minishlab/potion-base-8M"}) names a model of the database; an element without the text, or with a text the embedder finds nothing in, fails the whole query, so filter first: has("name", P.neq("")).) Declare the model in the schema then, as the next section shows, so a text query finds it. The job embed_property of earlier releases was removed in 0.5.0: a call fails with a help naming the vector rule.

Which model produced a property

Vectors of different models cannot be compared: a cosine between a hash-ngram/1 vector and one of a semantic model means nothing. The schema therefore records, per label and property, which model produced the vectors: the keyword embedder of a vector declaration holds the embedder's model identity (model in g.embedders(), never a file path; a vector rule may name a model of the database by its repository, and the schema stores its identity):

{"type": "array", "format": "vector", "element": "f32", "dimension": 256, "metric": "cosine", "embedder": "hash-ngram/1"}

A vector rule declares it by its embedder; for vectors you write yourself, declare it in an attached schema (mode open or closed; g.set_schema(g.infer_schema(), SchemaMode.open) attaches the structure a graph has) with g.patch_schema(..). The schema then keeps it right:

  • changing the embedder of a declared property is an incompatible schema change (the stored vectors and a text query embedded by the new model are not comparable): embed into another property, or change it deliberately and write the vectors again (a rule does it for you: changing its model re-embeds every element);
  • a declaration of another element kind (i8, f16, bit) than the embedder returns is fine: each vector is quantized to the declared element on write, as a schema write of a vector of another element is, so an f32 model can fill an i8 property (a quarter of the memory) directly.

Different labels and properties may use different models: doc.emb from one, doc.title_emb or person.emb from another. A plain write of a vector (property("emb", vector)) still checks only the element kind and the dimension (a rule's vector refuses direct writes): the provenance is used by the text queries, not checked on every write.

Text queries

With the provenance recorded, nearest() and similarity() take the query as text: the text is embedded once per execution, with the embedder of the database whose model the schema declares for the property, so the query vector always comes from the model of the stored ones:

g.v().has_label("person").property("emb", __.embed("name")).iterate();
g.set_schema(g.infer_schema(), SchemaMode.open);
g.patch_schema(#{vertices: #{person: #{schema: #{properties: #{emb: #{embedder: "hash-ngram/1"}}}}}});
g.v().has_label("person").nearest("emb", "Markus", 2).values("name").to_list()   // ["marko", "vadas"]

With a vector rule instead, the vectors appear when the unit that applied it ends: run the text query as the next query.

  • The model is read per element from the attached schema (the element's labels, the property); every element the query meets must declare the same model, else the query fails naming both (filter by label first: has_label("doc")).
  • No schema attached, or no embedder declared for the property: the query fails, and its help shows how to attach a schema and declare a vector rule; passing a vector, nearest("emb", embed("Markus"), 2), keeps working without any schema.
  • The database does not keep the declared model: the query fails, and its help shows how to import it (graphersal embed-model import <repo> --into <store>, Python store.import_model(..)); passing a vector keeps working.
  • The key form only: similarity("emb", "text") and nearest("emb", "text", k), with a top-level property name.
  • On a property declared i8 or f16 the embedded (f32) query is compared with the stored vectors as a vector query is; on a bit property, which compares only with bit vectors, the query is quantized to bits first, with the quantizer of a write (the same as nearest("emb", g.inject(embed("text")).quantize("bit").next(), k)).
  • It asks Execute on the embedder it resolves (on each one, when the schema declares several models for the property on different labels), and .profile() names it: nearest("emb", "Markus", 2, embedder: "hash-ngram/1").

The built-in hash-ngram/1

hash-ngram/1 needs no model file and no dependency and gives the same bits on every target (the CLI, Python, the dev server, the browser playground). It lowercases the text, splits it into words (runs of letters and digits), and hashes each word and its character 3-, 4- and 5-grams (of the word framed as <word>) into 256 signed buckets, then scales the result to length 1 (f32 components, metric cosine).

It measures lexical similarity: typos, word forms and shared stems come out close, in any script ("Graph" and "grahp", "Москва" and "Москве"), meaning does not ("car" and "automobile" are unrelated). Uses: fuzzy lookup, entity matching, deduplication, and a baseline before a semantic model.

The algorithm is frozen: the output of hash-ngram/1 never changes (a different algorithm would be a new name, hash-ngram/2), and tests pin its bits. Two caveats: there is no Unicode normalization (a precomposed "é" and "e" followed by a combining accent are different words), and lowercasing and the letter/digit classes follow the Unicode version of the Rust toolchain the binary was built with.

Its time grows with the length of the text. Measured with the bench embed_hash_ngram_1000 (cargo bench -p graphersal --bench graph --features io,script,display,serde -- embed_hash_ngram_1000, 1000 texts per call, Apple M-series, source build): about 0.84 µs per short title (5 words) and about 18.5 µs per paragraph of about 1 KB, so embedding a property of 100 000 short texts takes well under a second.

Models of the database (feature model2vec)

Besides hash-ngram/1, the embedders are Model2Vec static embedding models (one vector per token, averaged over the text; semantic, fast on a CPU) kept in the graph's database: one blob plus a catalog definition that follows the history (Store::import_model, CLI graphersal embed-model import <repo> --into <store>, Python store.import_model(..)); every copy carries them with their licences. A store's traversals, embed(text) and g.embedders() use its models without any setup: each model is an embedder named by its repository (the default model, when one is set, is the default), the models the schema needs are loaded at open, the others at their first use (Embedding Models in a Store). A .gsnap file loaded without a store serves the models it carries the same way; a graph without models has hash-ngram/1 only.

Running a model needs the feature model2vec of the graphersal crate (off by default, native targets only; the command line and the Python wheel have it on): the engine then loads the models kept in the database. It adds no public item. A build without it (and the browser playground) keeps and copies the models but opens a store whose schema needs one read-only without text queries.

  • Layouts an import reads: config.json, tokenizer.json and model.safetensors in the directory (the Model2Vec layout), or config_sentence_transformers.json beside them or beside a 0_StaticEmbedding directory holding them (the sentence-transformers layout).
  • Tokenizer: a tokenizer with a Unigram model (the potion models) runs on Graphersal's compact Unigram model, built from tokenizer.json when the model loads (flat arrays: about 25 MiB for the 500 000 tokens of potion-multilingual-128M, where the tokenizers crate's own model takes 442 MiB), inside the tokenizers pipeline the file declares (normalizer, pre-tokenizer, added tokens); the token ids and the vectors are the bits tokenizers and model2vec-rs give. Every other tokenizer runs on tokenizers' own model.
  • Info: the model's dimension, f32, metric cosine, 256 texts per call, local, and deterministic: false: one build gives the same bits for the same text, but they depend on the versions of model2vec-rs and tokenizers it was built with.
  • Model identity: model2vec/<repo>@<12 hex digits>; the digits start a SHA-256 over the three files, no path is part of it (persist::ModelCache::identity(dir) computes it for a downloaded directory).
  • Failures: a model that does not load (a missing or damaged blob, a model that does not fit under the memory ceiling) is EmbedError::Unavailable with the reason and the commands that bring it back; a tokenizer failure while embedding is EmbedError::Failed, never a panic. A text with no known token fails like an empty text for hash-ngram/1.

Changed in 0.5.0. The host embedder API is removed: the Rust trait vector::Embedder, the registry vector::Embedders (builder, scope), vector::HashNgram, vector::Model2Vec, GraphTraversalSource::with_embedders, script::set_engine_embedders/set_scope_embedders, the CLI flags --embedder/--default-embedder and the Python graphersal.Embedder/ graphersal.Model2Vec. A host with a model of its own computes the vectors outside and writes them as values (property("emb", vector)), and searches with a vector (nearest("emb", q, 10)); embed() stays for hash-ngram/1 and the database's models. A script host that builds its own engine and scope gives the global embed(text) the graph's models with script::set_engine_graph(&mut engine, graph) (the eval_* entry points do it themselves).

Storage and exchange

FormatA vector
Graphersal's binary format (snapshots, the Store, the journal)its own value tag: the element kind, the dimension, for i8 the scale, then the packed components (format spec 3)
Serialized ChangeSetexact, tagged: {"@type": "graphersal:Vector", "@value": {"element": "f32", "data": [..]}} (Transactions)
JSON results, to_json()the list of its values (an i8 or bit vector dequantized)
GraphSON exporta g:List of g:Float, which TinkerGraph loads
GraphSON importa list stays a list; it becomes a vector where the target schema declares one (mode open/closed); the exact graphersal:Vector tag is read too (GraphSON)
GraphMLthe JSON text of the list; a vector again where the target graph's schema declares one (any mode)

Exporting an i8 or bit vector as its values loses nothing that matters: a declared i8 property quantizes them back to the same codes. memory_usage() counts a vector's components exactly (plus a small header), and the memory budget of a query estimates them the same way.

From Python

A vector property is a graphersal.Vector in Python, built from a list of numbers or from any one-dimensional float32/float64 buffer such as a numpy array (the extension does not depend on numpy):

import numpy as np
from graphersal import Graph, Vector

g = Graph()
emb = np.array([0.12, -0.5, 0.33], dtype=np.float32)      # model.encode(text) in practice
g.execute('g.add_v("doc").property("emb", e).iterate()', params={"e": Vector(emb)})
v = g.query('g.v().values("emb").next()')                # graphersal.Vector
v.element, v.dimension, v.tolist()                       # ('f32', 3, [0.12, -0.5, 0.33])
Vector(emb, element="i8")                                # quantized, 1 byte per component

q = np.array([0.1, -0.4, 0.3], dtype=np.float32)          # the question's embedding
g.query('g.v().nearest("emb", q, 10).to_list()', params={"q": q})

A one-dimensional float32/float64 numpy array passed as a parameter arrives as an f32 vector, like Vector(array). See the Python binding's README for the details.

From Python, a model enters a store with store.import_model("minishlab/potion-base-8M"); text queries and vector rules then work as described above (Python Quick Start: Embedding models).

In the playground and the CLI

The result table shows a vector as vector[768 f32] with an expandable preview of its first values; the JSON view holds all of them. The property editor edits a vector as a JSON list of numbers (a declared vector property offers the type vector). The CLI's tables show the kind and the first values (vector[768 f32] [0.012, -0.5, 0.33, 0.1, …]), and a final vector prints as its literal.

Vector Rules

A vector rule keeps a vector property in step with the text it is computed from. The schema declares it on the vector property: beside embedder (the model) it names the source property from of the same label. From then on the engine embeds the text of from into the vector at the end of every unit that writes it, in the same unit: the text and its vector commit together, or neither does.

"emb": {"type": "array", "format": "vector", "element": "f32", "dimension": 256,
        "metric": "cosine", "embedder": "hash-ngram/1", "from": "text"}

The preview says what applying the rule fills (on the modern sample: the names of the four people), and applying it embeds every name:

g.validate_schema(#{vertices: #{person: #{schema: #{type: "object", properties: #{name: #{type: "string"}, emb: #{type: "array", format: "vector", embedder: "hash-ngram/1", from: "name"}}}}}})["fill"][0]["elements"]   // 4
g.patch_schema(#{vertices: #{person: #{schema: #{type: "object", properties: #{name: #{type: "string"}, emb: #{type: "array", format: "vector", embedder: "hash-ngram/1", from: "name"}}}}}})

The vectors are written when the writing unit ends: run a read in the next query. (The playground and a script run as one unit see them in their next run.)

The keyword

  • from needs format: "vector" and embedder on the same node, and sits on a label's top-level property only (like embedder).
  • from names a top-level property of the same label (1 to 128 bytes), never the vector's own key and never the vector of another rule of the label: rules are not chained. When the label declares from, its type must admit a string, or the rule would always remove the vector.
  • embedder names the built-in hash-ngram/1 or a model of the store, by its repository (minishlab/potion-base-8M) or its identity; the schema stores the identity of the store's current revision, and get_schema shows it. Any other model is refused when the schema is set, with the command that imports it (graphersal embed-model import <repo> --into <store>). An identity with a normalization override (?normalize=false) is refused too: a stored model is served as it was imported.
  • An undeclared dimension is declared from the model; a declared one must be the model's.
  • A storage without change capture (StorageCapabilities::change_capture) refuses rules (Unsupported: vector rules): the rule pass reads the unit's undo log.
  • Inference never infers a rule.
  • Two labels may each have a rule for the same key. For a vertex with several labels the FIRST label that declares a rule for the key wins (as for coercion).

When the vector is written

At the end of the outermost unit (a query, a transaction, a whole-script unit, a schema change, a live import), once per element, however often the unit wrote it:

  1. Every element whose from the unit wrote, every element it created, and every vertex whose labels it changed (a label with a rule added) is looked at.
  2. Its text is embedded, in ONE batch per model over the whole unit (chunks of the model's batch size).
  3. The vector is written as an ordinary write of the unit: the change set, the write-ahead log and a rollback see it. Replay, recovery, loads and replicas never call a model; vectors travel as data.

Inside the unit a read of the vector after a write of from sees the old vector: the new one appears when the outermost unit ends (Execution::changes() of an inner unit does not show it). A whole script run as one unit (the playground, eval_value_atomic) therefore reads the new vectors in its NEXT run.

A source without text removes the vector, in the same unit: from removed, set to null, set to "", set to a value that is not a string, or a text in which the model finds nothing to embed (hash-ngram/1: separators only).

A failing model, a cancelled execution or the memory ceiling (memory.limit, operation "vector rule fill") rolls the whole unit back: nothing is written (GraphError::VectorRuleFailed, ResourceLimitExceeded). A cancellation (CancelToken) stops a fill with the cause EmbedError::Cancelled; the execution timeout is not checked while the fill runs inside the commit.

Direct writes are refused

The vector of a rule is computed, like a generated column of SQL. Writing or removing it directly (property("emb", ..), add_v(..).property("emb", ..), GQL SET, a jpath into it, an imported file that carries it) fails with GraphError::DerivedProperty, whose help names the source to write instead. apply_change_set (the replication form) takes the vector as given, and so do replay, recovery and loads. To write the vectors yourself, remove from from the declaration: the vectors stay as plain data.

First fill and model replacement

Warning: adding a rule (or changing its from, embedder, element or dimension) over existing data embeds EVERY element of the label in the schema-changing unit, also those that hold a vector already. While it runs the WHOLE database is locked: every write and every read waits until it ends. hash-ngram/1 embeds about 200,000 short texts per second; a Model2Vec model is measured at its load (a batch of 64 sentences). Run it at a quiet time. If it fails, nothing is written.

The same holds for a model replacement (Store::import_model with replace): the rules naming the old revision switch to the new one and re-embed every element of their labels in the replacing commit. A property whose vectors the old revision made WITHOUT a rule (an embedder but no from) refuses the replace (StoreFailure::ModelInUse, naming it): there is no text to re-embed. Add the rule first.

A first fill and a replacement write vector_fill.started before the first batch, vector_fill.done after the commit (its op is the start record) or vector_fill.failed after the rollback to the system journal. Graph::vector_fill_progress() (Rust) reports a running fill without taking the lock.

Removing a rule does nothing to the data: the vectors stay as plain values.

The preview and the one warning

validate_schema, validate_schema_patch and diff_schema report the planned fill before anything is applied: fill lists per rule the label, from, to, the model, the reason (rule_added, rule_changed, model_replaced), the elements to embed, the vectors to remove, the estimated time (estimate_ms: the embedding plus the schema check the apply runs under the same lock, scan_elements / scan_ms; the embedding part is three times what the model's measured speed gives, because that speed is measured on short sentences and real texts are longer) and the saved queries whose body writes the rule's property directly (direct_writes: such a write is refused once the rule exists; remove it, the queries are never rewritten); on a layer, base_copies counts the base elements the fill copies into the layer (a line of the warning names it; 0 on any other graph); fill_warning is the ONE text every front end shows:

Applying this schema fills vectors: 1,204,331 elements of doc.emb from doc.text with the model
minishlab/potion-multilingual-128M (about 1 min).
The whole database is LOCKED while this runs: every write and every read waits until it ends.
Run it at a quiet time. If it fails, nothing is written.

and, when saved queries write a filled property directly, a line per property such as Saved queries writing doc.emb directly fail once the rule exists (remove that write; they are not rewritten): load_docs. Only a Rhai body with a literal key in property(..) is found (property("emb", ..), also after a cardinality); a computed key, the maps of merge_v/merge_e and GQL bodies are not, so check such queries yourself.

The schema check of a change that keeps the mode (open or closed) reads only the elements of the labels whose declaration changed: adding a rule to three labels of a graph of millions of elements checks those three labels, not the whole graph. A change of the mode checks every element. validate_schema runs the same check and measures it, so its scan_ms is the time the apply's check takes; diff_schema reads no data: its counts come from the label statistics ("up to") and its check time from a fixed rate. A fill needs confirmation when its estimate (the check included) is 1 s or more, or, without an estimate, from 10,000 elements or a check of 1 s or more:

  • the playground's schema editor asks with a dialog "Apply and lock" / "Cancel" (below the threshold a plain note);
  • the MCP tools set_schema / patch_schema refuse it with the text and "Repeat with confirm_lock: true" (Dev Server);
  • the CLI prints it as a note: before applying --schema;
  • Python issues graphersal.VectorFillWarning before applying.

The diff lists a rule as vector_rule_added (compatible on a new property, incompatible when the property was declared before: its direct writes are refused from then on), vector_rule_changed (incompatible) or vector_rule_removed (compatible).

Permissions

Setting a schema with a rule asks Update on the schema. The derived writes ask nothing of their own (like create-time defaults), and the rule's model runs without Execute on the embedder.

Dates and Times

Graphersal has six date and time types. They are values of their own, like numbers and UUIDs: a property holds a date, not a string that looks like one, and a query compares, sorts and computes with it. The model follows PostgreSQL and the SQL standard; the part TinkerPop defines (datetime(), asDate(), dateAdd(), dateDiff(), DT.second to DT.day) behaves exactly as TinkerPop 3.8 specifies it (TinkerPop compatibility).

The six types

Graphersal (type_of, GType)What it isLiteralPostgreSQLSQL standardPythonTinkerPop / java.time
datetime (GType.DATETIME)an instant with the UTC offset it was written with, and the IANA zone name when it was written with onedatetime("2023-08-02T09:30:00+02:00"), datetime("2023-08-02T09:30[Europe/Berlin]")timestamptz (keeps no offset)TIMESTAMP WITH TIME ZONEaware datetime.datetime (a zoneinfo.ZoneInfo for a zone name)datetime, OffsetDateTime, ZonedDateTime
localdatetime (GType.LOCALDATETIME)a wall-clock date and time, no zonelocaldatetime("2023-08-02T09:30")timestampTIMESTAMPnaive datetime.datetimeLocalDateTime
date (GType.DATE)a calendar daydate("2023-08-02")dateDATEdatetime.dateLocalDate
time (GType.TIME)a time of day, no zonetime("09:30:15.5")timeTIMEnaive datetime.timeLocalTime
offsettime (GType.OFFSETTIME)a time of day with a UTC offsetoffsettime("09:30:15.5+02:00")timetzTIME WITH TIME ZONE (GQL ZONED TIME)datetime.time with a datetime.timezoneOffsetTime
duration (GType.DURATION)months, days and nanoseconds, each with its own signduration("P1Y2M3DT4H")intervalINTERVALdatetime.timedelta, or graphersal.Interval with monthsDuration, Period
type_of(datetime("2023-08-02T09:30:00+02:00"))   // "datetime"
date("2024-02-29").day   // 29
duration("P1Y2M3DT4H").months   // 14
g.inject(datetime("2023-08-02T09:30Z")).is(P.typeOf(GType.DATETIME)).count().next()   // 1
  • Resolution: one nanosecond for every type with a time, as in java.time and TinkerPop (PostgreSQL and Python stop at the microsecond). TinkerPop's millisecond views (as_number() of a datetime, date_diff()) round down to milliseconds. Python's datetime holds microseconds: a value with a part below them comes back as a pandas.Timestamp / pandas.Timedelta (From Python). The store format, GraphSON, GraphML and the serialized change set keep every nanosecond (Storage and Exchange). The clock behind now() has the digits the platform gives (nanoseconds on Linux, microseconds on macOS, milliseconds in the browser: Clock precision).
  • Range: the years -9999 to 9999 in the proleptic Gregorian calendar (date("-0044-03-15") is year 44 BC counted astronomically, year 0 = 1 BC). A value outside the range, or a result that would leave it, is an error, never a wrapped value.
  • Offsets: a datetime keeps its offset (±18:00, whole seconds) and shows it, unlike PostgreSQL's timestamptz, which keeps only the instant. A datetime written with an IANA zone name keeps the name too (2024-03-31T12:00:00+02:00[Europe/Berlin]) and follows the zone's daylight saving rules in its calendar arithmetic; a step given an IANA zone (at_zone("Europe/Berlin")) returns a value carrying that name, one given a fixed offset (at_zone("+02:00")) a value with the offset only (Time Zones). An offsettime keeps its offset.
  • A duration is not normalized: P1M, P30D and PT720H are three different values. A month has no fixed length and a day is not always 24 hours in a time zone, so the three fields stay apart, as in PostgreSQL's interval.
  • Duration range: the months and the days are 32-bit integers each; the time part has the range of java.time.Duration (TinkerPop) and of Neo4j's duration, a 64-bit count of seconds plus the nanoseconds of one second: from -PT9223372036854775808S to PT9223372036854775807.999999999S (about ±292 billion years). Adding such a duration to a date or time whose result leaves the years -9999 to 9999 is an error.
  • No guessing: a string stays a string whatever it looks like. A date comes from a constructor, a conversion step (Conversions), a schema that declares the property (Schema), a typed value in a file (Storage and Exchange) or a Python datetime (From Python).

Script values

In a script each type is a value of its own Rhai type with getters and operators:

TypeGetters
datetimeyear, month, day, hour, minute, second, microsecond, nanosecond (on its own wall clock), offset (seconds), timezone (the zone name, else the offset text), epoch_millis
localdatetimeyear, month, day, hour, minute, second, microsecond, nanosecond
dateyear, month, day
timehour, minute, second, microsecond, nanosecond
offsettimehour, minute, second, microsecond, nanosecond (of its local time), offset (seconds), timezone (the offset text)
durationmonths, days, micros (the time part in whole microseconds), nanos (in nanoseconds); micros beyond a 64-bit integer (about 292,000 years) and nanos beyond one (about 292 years) are a range error

microsecond is the whole microseconds of the second (0-999999), nanosecond all its nanoseconds (0-999999999): time("12:00:00.123456789") has microsecond 123456 and nanosecond 123456789.

let d = datetime("2023-08-02T09:30:15.25+02:00"); [d.hour, d.offset, d.microsecond]   // [9, 7200, 250000]
datetime("2023-08-02T12:00Z") + duration("P1M")   // datetime("2023-09-02T12:00:00Z")
date("2023-08-02") - date("2023-01-01")   // duration("P213D")
time("10:00") - time("09:30")   // duration("PT30M")
offsettime("10:00+02:00") - offsettime("07:30Z")   // duration("PT30M")
datetime("2024-03-30T12:00[Europe/Berlin]") + duration("P1D")   // datetime("2024-03-31T12:00:00+02:00[Europe/Berlin]")
datetime("2023-08-02T09:30+02:00").as_string()   // "2023-08-02T09:30:00+02:00"

+ and - with a duration work as date_add() does; the difference of two values of one type is a duration (two datetimes or localdatetimes give days of 24 hours and a time part, two dates days, two times the elapsed time, two offsettimes the time between their UTC times of day). as_string() is the canonical text, to_string() the DSL literal. A value printed or shown as a script value is its literal (date("2023-08-02")); tables, JSON and the playground show the canonical text.

The pages of this part

The steps have generated reference pages: as_date, as_duration, date_add, date_diff, age, date_trunc, date_part, at_zone and as_local; the constructors, now(), today() and DT are on Functions, Tokens and Values.

Comparing and Sorting

Every comparison of dates goes through one set of rules: == in a script, the predicates (P.eq, P.gt, P.between, P.within, ...), dedup(), group() and group_count() keys, order(), min()/max() and the schema bounds.

datetime: by its instant

Two datetimes are equal when they are the same instant, whatever their offsets (12:00Z equals 14:00+02:00). This is PostgreSQL's equality and TinkerPop's ("dates are evaluated based on the numerical comparison of Unix Epoch time"). The offset is kept and shown, but never compared:

datetime("2023-08-02T12:00Z") == datetime("2023-08-02T14:00+02:00")   // true
g.inject(datetime("2023-08-02T12:00Z"), datetime("2023-08-02T14:00+02:00")).dedup().count().next()   // 1
g.inject(datetime("2023-08-02T14:00+02:00")).is(P.gt(datetime("2023-08-02T11:00Z"))).count().next()   // 1

A zone name is shown but never compared either: 2023-08-02T14:00+02:00[Europe/Berlin] equals 2023-08-02T12:00Z (as Neo4j and the openCypher TCK compare instants).

datetime("2023-08-02T14:00[Europe/Berlin]") == datetime("2023-08-02T12:00Z")   // true

Of two values with the same instant and different offsets the first one met is kept (dedup(), a group() key); their order in a sort is unspecified. To compare the wall clocks instead, convert first: as_local() gives the wall-clock localdatetime (Time Zones).

offsettime: by its UTC time of day

Two offsettimes are equal when they are the same time of day in UTC (12:00+01:00 equals 11:00Z), and order by it, as a datetime compares by its instant (java.time OffsetTime.isEqual / isBefore). The offset is kept and shown, never compared; the UTC time is not wrapped around midnight (01:00+02:00 is before 00:00Z, the previous day's 23:00 in UTC).

offsettime("12:00+01:00") == offsettime("11:00Z")   // true
offsettime("01:00+02:00") < offsettime("00:00Z")   // true

duration: field-wise equal, ordered by length

Two durations are equal when their months, days and nanoseconds are equal: P1M is not P30D, and P1D is not PT24H (a day in a time zone may have 23 or 25 hours). Sorting compares their length as PostgreSQL does for an interval, counting a month as 30 days and a day as 24 hours; equal lengths are ordered by months, then days, then the time part:

duration("P1M") == duration("P30D")   // false
g.inject(duration("P1M"), duration("P30D"), duration("PT719H")).order().to_list()   // [PT719H, P30D, P1M]

The other types: by calendar and clock

A date, a localdatetime and a time compare by their calendar or clock value.

g.inject(time("10:00")).is(P.between(time("09:00"), time("17:00"))).count().next()   // 1
g.inject(date("2023-08-02")).is(P.within(date("2023-08-02"), date("2023-08-03"))).count().next()   // 1

Different types

Values of different types are never equal, and an ordering predicate between them does not match (no error): a date is not a datetime, and a date is never equal to a string, as a UUID is not. Convert one side first (Conversions).

g.inject(date("2023-08-02")).is(P.eq("2023-08-02")).count().next()   // 0
g.inject(date("2023-08-02")).is(P.lt(datetime("2024-01-01T00:00Z"))).count().next()   // 0
g.inject(date("2023-08-02")).as_date().is(P.lt(datetime("2024-01-01T00:00Z"))).count().next()   // 1

order() of a mixed stream puts the dates after the numbers and before the strings (TinkerPop's orderability places its date type there), in the order date, localdatetime, datetime, time, duration, offsettime:

g.inject("x", 1, duration("P1D"), time("01:00"), datetime("2023-08-02T00:00Z"), date("2023-08-02")).order().to_list()

Property indexes

A property index on a key holding dates and times serves has() with these same rules: an equality or P.within reads the values equal to the operand (a datetime by its instant, an offsettime by its UTC time of day, a duration field by field), a range (P.gt, P.between, ...) reads the values of the operand's type in that range. The results are always the same as without the index.

g.create_index(#{label: "person", key: "joined"});
g.v().has("name", "marko").property("joined", datetime("2023-08-02T12:00Z")).iterate();
g.v().has_label("person").has("joined", datetime("2023-08-02T14:00+02:00")).count().next()   // 1

Text Formats

Dates are read and written as ISO 8601 text (RFC 3339 for a datetime, with the RFC 9557 zone suffix). No locale formats, no two-digit years, no guessing: a text is read as a date only where a date is asked for (a constructor, a conversion step, a declared schema format, a typed value in a file).

Canonical output

Every value has one text, the one tables, JSON, GraphML, GraphSON and as_string() write. It is the text java.time writes, so other tools read it back:

TypeCanonical text
date2023-08-02; a year before 1 or after 9999 with its sign: -0044-03-15
time09:30:00; a fraction only when it is not zero, in groups of three digits (milliseconds, microseconds or nanoseconds): 09:30:00.500, 09:30:00.123456, 09:30:00.123456789
localdatetime2023-08-02T09:30:00 (the date, T, the time)
datetime2023-08-02T09:30:00+02:00; Z for a zero offset; an offset with seconds as +00:19:32; a zone name after the offset in brackets: 2023-08-02T09:30:00+02:00[Europe/Berlin]
offsettime09:30:00+02:00, 09:30:00Z: the time as for a time, then the offset
durationP1Y2M3DT4H5M6S: years and months from the months, days, then the time part; a zero part is left out, a zero duration is PT0S; a sign before P when every part is negative (-P1M2D), else a sign per part (P1M-2D)
time("09:30:00.1").as_string()   // "09:30:00.100"
datetime("2023-08-02 09:30+00:00").as_string()   // "2023-08-02T09:30:00Z"
duration("PT90M").as_string()   // "PT1H30M"
duration("P2W").as_string()   // "P14D"

A duration keeps its three fields as they are: PT36H stays PT36H (not P1DT12H), and weeks are read as 7 days. Years and months are one field, months: P1Y2M is 14 months.

What is read

TypeAccepted text
dateYYYY-MM-DD; a year before 1 with its sign (-0044-03-15)
timeHH:MM, HH:MM:SS, HH:MM:SS.f with 1 to 9 fraction digits, kept to the nanosecond
localdatetimea date, optionally followed by T (or t, or a space) and a time; a date alone is midnight
datetimea local date-time, then an offset (Z, +02:00, +0200, +02, +00:19:32) and/or a zone in brackets ([Europe/Berlin], kept in the value)
offsettimea time as for a time, then an offset (Z, +02:00, +0200, +02), which it must have; no zone name
duration[+-]P[nY][nM][nW][nD][T[nH][nM][n[.f]S]], a sign per number allowed (P1M-2D), letters in either case
datetime("2023-08-02T09:30+0200")   // datetime("2023-08-02T09:30:00+02:00")
datetime("2023-08-02T09:30[Europe/Berlin]")   // datetime("2023-08-02T09:30:00+02:00[Europe/Berlin]")
datetime("2023-08-02T09:30:00.123456789Z")   // datetime("2023-08-02T09:30:00.123456789Z")
offsettime("09:30+0200")   // offsettime("09:30:00+02:00")
offsettime("09:30")   // error: an offsettime needs its UTC offset
date("10000-01-01")   // error: expected a four-digit year
duration("1 day")   // error: not an ISO 8601 duration

A datetime with only a zone is resolved in it (a wall-clock time the zone skips moves forward, one it repeats takes the earlier offset, see Time Zones); with an offset and a zone the offset must be the zone's at that instant.

Strict and lenient: a datetime without an offset

TinkerPop reads a date-time text without an offset as UTC (asDate("2023-08-02") is midnight UTC). Graphersal does that only where a query asks for a conversion:

  • lenient (no offset = UTC, a date alone = midnight UTC): the datetime() / DateTime() constructor and the conversion steps as_date() and as_date(GType.DATETIME);
  • strict (an offset or a zone is required): every place a text is stored as a datetime, namely a property declared "format": "date-time" in the schema, the formatMinimum/formatMaximum bounds, a typed gx:OffsetDateTime in GraphSON or a change set, a saved query argument declared as a date-time, and the playground's property editor.
datetime("2023-08-02T09:30")   // datetime("2023-08-02T09:30:00Z")
g.inject("2023-08-02").as_date().next()   // datetime("2023-08-02T00:00:00Z")

A stored instant without its offset would be a guess about where it was written; the strict rule turns that guess into an error that names the expected form. The other types have no offset (an offsettime always needs its offset), so they read the same everywhere.

Time Zones

A datetime carries the UTC offset it was written with. Written with an IANA zone name (datetime("2024-03-30T12:00[Europe/Berlin]"), a GQL timezone: 'Europe/Berlin', a Python zoneinfo.ZoneInfo), it keeps the name as well, and its calendar arithmetic follows the zone (Zone names in a value). An operation can also take a zone as an argument and give back a datetime with the zone's offset at that instant, carrying the zone's name when the argument is an IANA name: the PostgreSQL model (AT TIME ZONE, a session zone for the calendar arithmetic), with the zone passed explicitly instead of a session setting, and the java.time model (atZoneSameInstant gives a ZonedDateTime that keeps its zone).

Zone arguments

A zone argument is one of:

  • an IANA zone name: "Europe/Berlin", "America/New_York", "UTC"; a datetime the step returns keeps the name (+02:00[Europe/Berlin], Z[UTC]);
  • a fixed offset: "+02:00", "-0530", "Z"; a datetime the step returns has that offset and no name.
g.inject(datetime("2023-08-02T12:00Z")).at_zone("Europe/Berlin").next()   // datetime("2023-08-02T14:00:00+02:00[Europe/Berlin]")
g.inject(datetime("2023-08-02T12:00Z")).at_zone("+02:00").next()   // datetime("2023-08-02T14:00:00+02:00")

The IANA rules come from the time zone database bundled with Graphersal (the jiff-tzdb crate). Every machine, and the browser playground, gives the same answer to the same query, and a replayed journal computes what it computed when it was written; the database changes only with a Graphersal release, not with an operating system update. An unknown name is an error, found before any value is read:

g.inject(datetime("2023-08-02T12:00Z")).at_zone("Mars/Olympus").next()   // error: unknown time zone

The steps that take a zone: at_zone(zone), as_local(zone), date_add(.., zone), date_diff(.., zone), age(.., zone), date_trunc(.., zone), date_part(.., zone), and today(zone). Only a datetime (and the localdatetime of at_zone) takes one; the other types have no instant, and a zone argument for them is an error.

Zone names in a value

A text with a zone in brackets (RFC 9557, java.time ZonedDateTime) keeps the zone's name beside the offset; the value prints it back:

datetime("2024-03-30T12:00[Europe/Berlin]")   // datetime("2024-03-30T12:00:00+01:00[Europe/Berlin]")
datetime("2024-03-30T12:00[Europe/Berlin]").timezone   // "Europe/Berlin"
datetime("2024-03-30T12:00+01:00").timezone   // "+01:00"

Such a value computes in its zone wherever a zone argument could be given and none is: adding days, weeks, months or years keeps the wall-clock time and takes the zone's offset at the new day, while hours and smaller units (and the time part of a duration) move the instant. A difference in days or larger units, age(), date_trunc() and date_part() read the wall clock of the zone. The result keeps the name.

datetime("2024-03-30T12:00[Europe/Berlin]") + duration("P1D")   // datetime("2024-03-31T12:00:00+02:00[Europe/Berlin]")
datetime("2024-03-30T12:00[Europe/Berlin]") + duration("PT24H")   // datetime("2024-03-31T13:00:00+02:00[Europe/Berlin]")
g.inject(datetime("2024-03-31T12:00[Europe/Berlin]")).date_trunc(DT.day).next()   // datetime("2024-03-31T00:00:00+01:00[Europe/Berlin]")

A zone argument wins over the value's own zone (at_zone(), date_add(.., zone), ...): the result carries the argument's name when it is an IANA zone and no name when it is a fixed offset, whatever zone the input had. To drop a name and keep the instant, pass the offset: at_zone("+02:00"). Equality and order ignore the name, as they ignore the offset (Comparing and Sorting). The name is the database's spelling (europe/berlin reads as Europe/Berlin); a fixed offset in brackets ([+01:00]) is no name. The store, GraphSON, GraphML (through a schema), the change set and Python keep the name (Storage and Exchange).

Moving between a datetime and its wall clock

  • at_zone(zone) on a datetime: the same instant, written with the zone's offset at it (PostgreSQL AT TIME ZONE, java.time atZoneSameInstant).
  • at_zone(zone) on a localdatetime: the wall-clock time read in the zone, the datetime of that instant (java.time atZone).
  • as_local() / as_local(zone): the wall-clock localdatetime a datetime shows on its own offset or in the zone (toLocalDateTime).
g.inject(datetime("2023-08-02T12:00Z")).at_zone("America/New_York").next()   // datetime("2023-08-02T08:00:00-04:00[America/New_York]")
g.inject(localdatetime("2023-08-02T12:00")).at_zone("+02:00").next()   // datetime("2023-08-02T12:00:00+02:00")
g.inject(datetime("2023-08-02T12:00Z")).as_local("Asia/Tokyo").next()   // localdatetime("2023-08-02T21:00:00")

Daylight saving: gaps and folds

Where a zone moves its clocks, a wall-clock time can be missing (a spring-forward gap) or happen twice (a fall-back fold). Graphersal resolves both as PostgreSQL and java.time do (the "compatible" rule), never with an error:

  • a time in a gap moves forward by the length of the gap: 02:30 on 2023-03-26 in Berlin becomes 03:30+02:00;
  • a time in a fold takes the earlier offset: 02:30 on 2023-10-29 in Berlin is 02:30+02:00, the first of the two.
g.inject(localdatetime("2023-03-26T02:30")).at_zone("Europe/Berlin").next()   // datetime("2023-03-26T03:30:00+02:00[Europe/Berlin]")
g.inject(localdatetime("2023-10-29T02:30")).at_zone("Europe/Berlin").next()   // datetime("2023-10-29T02:30:00+02:00[Europe/Berlin]")

The same rule applies to a text with only a zone (datetime("2023-03-26T02:30[Europe/Berlin]")) and to every result a zone computes on the wall clock.

Calendar arithmetic in a zone

Without a zone a datetime is computed on its own fixed offset: date_add(DT.day, 1) adds 24 hours, as TinkerPop specifies. With a zone, calendar units work on the zone's wall clock, so a day stays a calendar day across a daylight saving change (23 or 25 hours long), while hours stay hours:

g.inject(datetime("2023-03-25T12:00+01:00")).date_add(DT.day, 1).next()   // datetime("2023-03-26T12:00:00+01:00")
g.inject(datetime("2023-03-25T12:00+01:00")).date_add(DT.day, 1, "Europe/Berlin").next()   // datetime("2023-03-26T12:00:00+02:00[Europe/Berlin]")
g.inject(datetime("2023-03-25T12:00+01:00")).date_add(DT.hour, 24, "Europe/Berlin").next()   // datetime("2023-03-26T13:00:00+02:00[Europe/Berlin]")

The same holds for date_diff() in days and larger units, age(), date_trunc() and date_part(): they read the wall clock of the zone. Without a zone, date_diff() and age() read both operands on the wall clock of the second operand's offset:

g.inject(datetime("2023-03-26T12:00+02:00")).date_diff(datetime("2023-03-25T12:00+01:00"), DT.day).next()   // 0 (23 hours)
g.inject(datetime("2023-03-26T12:00+02:00")).date_diff(datetime("2023-03-25T12:00+01:00"), DT.day, "Europe/Berlin").next()   // 1
g.inject(datetime("2023-08-02T12:00Z")).date_trunc(DT.day, "America/New_York").next()   // datetime("2023-08-02T00:00:00-04:00[America/New_York]")

GQL has no zone argument of a step: a zone name in its text (datetime('..[Europe/Berlin]')), in a map (timezone: 'Europe/Berlin') or given to a clock (datetime('Europe/Berlin')) is kept in the value, as Neo4j keeps it, and its arithmetic then follows the zone (Dates in GQL).

Arithmetic

Three steps compute with dates: date_add() moves a value, date_diff() measures the distance between two values as a number, age() as a duration. All of them are checked: a result outside the years -9999 to 9999 is an error, never a wrapped value. In a script the operators + and - do the same (script values). In GQL, + with a duration and duration.between() follow Neo4j's rules instead (Dates in GQL).

Units: the DT token

DT.second, DT.minute, DT.hour and DT.day are TinkerPop's (the bare names second, minute, hour and day work too, as in the TinkerPop scenarios). Graphersal adds the smaller and the calendar units, with PostgreSQL's field names:

UnitKindAdding it
DT.nanosecond, DT.microsecond, DT.millisecond, DT.second, DT.minute, DT.houra fixed lengthmoves the instant (or the clock) by that many units
DT.day, DT.weekcalendar daysmoves the wall-clock date; in a zone the time of day is kept across a daylight saving change
DT.month, DT.quarter, DT.year, DT.decade, DT.century, DT.millenniumcalendar months (1, 3, 12, 120, 1200, 12000)moves the month and clamps the day to the end of the target month

DT.day_of_week, DT.iso_day_of_week, DT.day_of_year, DT.iso_year, DT.epoch and DT.offset are parts, not units: only date_part() takes them.

date_add()

date_add(DT.unit, n) adds n units (a negative n subtracts); date_add(duration) adds a duration. Both take an optional zone as the last argument (Time Zones).

g.inject(datetime("2023-08-02T12:00Z")).date_add(DT.hour, 36).next()   // datetime("2023-08-04T00:00:00Z")
g.inject(date("2023-08-02")).date_add(day, 3).next()   // date("2023-08-05")
g.inject(datetime("2023-08-02T12:00Z")).date_add(DT.millisecond, 1500).next()   // datetime("2023-08-02T12:00:01.500Z")

Month ends. Adding months keeps the day of the month where it exists and otherwise takes the last day of the target month, as PostgreSQL and java.time do. Each step clamps on its own, so two single months can end earlier than two months at once:

g.inject(date("2024-01-31")).date_add(DT.month, 1).next()   // date("2024-02-29")
g.inject(date("2024-01-31")).date_add(DT.month, 2).next()   // date("2024-03-31")
g.inject(date("2024-01-31")).date_add(DT.month, 1).date_add(DT.month, 1).next()   // date("2024-03-29")

A duration is added in PostgreSQL's order: its months first (clamped), then its days, then its time part.

g.inject(datetime("2023-08-02T12:00Z")).date_add(duration("P1M1DT1H")).next()   // datetime("2023-09-03T13:00:00Z")
g.inject(date("2024-02-29")).date_add(duration("P1Y1D")).next()   // date("2025-03-01")

What each type accepts:

TypeDT unitsA duration
datetimeall units; a fixed length moves the instant and keeps the offset (TinkerPop: a day is 24 hours at a fixed offset), with a zone the result takes the zone's offset (and its name, for an IANA zone); a datetime with a zone name computes in its zone and keeps the name when no zone is given (Time Zones)any
localdatetimeall units, on the wall clockany
dateday and largerwithout a time part
timehour and smaller; the clock wraps around midnight (PostgreSQL time + interval)without months or days
offsettimeas a time, on its local time; the offset stayswithout months or days
durationall units: adds to the matching fieldany (field by field)
g.inject(time("23:00")).date_add(DT.hour, 2).next()   // time("01:00:00")
g.inject(date("2024-02-29")).date_add(DT.hour, 2).next()   // error: adding the unit hour is not defined for a date

date_diff()

date_diff(other) is TinkerPop's dateDiff(): the incoming value minus other in milliseconds, an int64, each operand's epoch milliseconds rounded down. other is a value or a child traversal whose first result is the operand; () (null) stands for the epoch.

g.inject(datetime("2023-08-02T12:00Z")).date_diff(datetime("2023-08-01T00:00Z")).next()   // 129600000
g.inject(datetime("2023-08-02T12:00Z")).date_diff(__.constant(datetime("2023-08-01T00:00Z"))).next()   // 129600000
g.inject(datetime("1970-01-01T00:00:01Z")).date_diff(()).next()   // 1000

Graphersal extends it to the other types (both operands of one type: a date counts from midnight, a time within the day; () is 1970-01-01 or midnight) and adds date_diff(other, DT.unit[, zone]): the difference in whole units, truncated toward zero.

  • Units below a day count the elapsed time.
  • Days and weeks count wall-clock days (a datetime on the wall clock of other's offset, or of the zone).
  • Months and larger count as java.time's ChronoUnit.between: a month is complete when the day of the month (and the time) is reached again, so January 31 to February 28 is 0 months.
g.inject(datetime("2023-08-02T12:00Z")).date_diff(datetime("2023-08-01T00:00Z"), DT.hour).next()   // 36
g.inject(time("10:00")).date_diff(time("09:00"), DT.minute).next()   // 60
g.inject(date("2024-02-28")).date_diff(date("2024-01-31"), DT.month).next()   // 0
g.inject(date("2024-03-31")).date_diff(date("2024-02-29"), DT.month).next()   // 1

age()

age(other[, zone]) is PostgreSQL's age: the difference as a duration of whole years and months, days and a time part, all with the same sign. It is counted down from the incoming value to other with PostgreSQL's borrowing rules, so swapping the operands negates the result. Both operands have the same type; () is an error.

g.inject(date("2001-04-10")).age(date("1957-06-13")).next()   // duration("P43Y9M27D")
g.inject(date("1957-06-13")).age(date("2001-04-10")).next()   // duration("-P43Y9M27D")
g.inject(datetime("2024-02-29T00:00Z")).age(datetime("2023-01-31T12:00Z")).next()   // duration("P1Y28DT12H")

To get a plain number of days, years or hours, use date_diff(other, DT.unit); to get a duration of elapsed time without calendar units, subtract the two values in a script (a - b).

Truncation and Parts

date_trunc(DT.unit) is PostgreSQL's date_trunc, and date_part(DT.unit) is its extract. Both are Graphersal extensions; TinkerPop has neither. GQL's X.truncate() and x.year do the same with Neo4j's names, but truncate millennia and centuries as Neo4j does (Dates in GQL). A datetime is read on its own wall clock, or on the wall clock of a zone given as the last argument (Time Zones).

date_trunc()

The fields below the unit become their first value: the start of the hour, the day, the month. A truncated datetime keeps its offset (or, with a zone, takes the zone's offset at the new instant, and the zone's name when it is an IANA zone).

g.inject(datetime("2023-08-17T15:47:12.5+02:00")).date_trunc(DT.hour).next()   // datetime("2023-08-17T15:00:00+02:00")
g.inject(datetime("2023-08-17T15:47:12.5+02:00")).date_trunc(DT.week).next()   // datetime("2023-08-14T00:00:00+02:00")
g.inject(datetime("2023-08-17T15:47:12.5+02:00")).date_trunc(DT.day, "UTC").next()   // datetime("2023-08-17T00:00:00Z")
g.inject(date("2023-08-17")).date_trunc(DT.quarter).next()   // date("2023-07-01")
g.inject(duration("P1Y2M3DT4H5M")).date_trunc(DT.day).next()   // duration("P1Y2M3D")
UnitTruncates to
nanosecond ... hourthe start of that unit of the clock (nanosecond keeps the value)
daymidnight
weekMonday, midnight (ISO 8601 weeks)
month, quarter, yearthe first day of the month, of the quarter (January, April, July, October), of the year
decadethe first day of a year divisible by 10 (2020-01-01)
century, millenniumthe first day of a year ending in 01/001: centuries and millennia start at year 1, as PostgreSQL counts them (2001-01-01 starts the 21st century)

A date takes day and larger, a time and an offsettime hour and smaller (the offset stays), a duration keeps the fields at and above the unit (month and larger keep whole multiples of the unit's months and drop the days and the time part).

date_part()

One field as a number: an int64, except DT.epoch, a float64 of seconds.

PartValue
DT.year, DT.month (1-12), DT.day (1-31), DT.hour, DT.minute, DT.second (0-59)the field
DT.millisecond (0-999), DT.microsecond (0-999999), DT.nanosecond (0-999999999)the fraction of the second in that unit; unlike PostgreSQL, not the seconds with the fraction
DT.quarter (1-4)the quarter
DT.week (1-53)the ISO 8601 week number
DT.iso_yearthe ISO 8601 week-numbering year (2023-01-01 is in week 52 of 2022)
DT.day_of_week0 = Sunday to 6 = Saturday (PostgreSQL dow)
DT.iso_day_of_week1 = Monday to 7 = Sunday (PostgreSQL isodow)
DT.day_of_year (1-366)the day of the year
DT.decade, DT.century, DT.millenniumas PostgreSQL counts them (the 21st century is 2001-2100)
DT.epochseconds since 1970-01-01T00:00:00Z (a localdatetime read as UTC); for a duration its length with a year of 365.25 days and a month of 30 days
DT.offsetthe UTC offset of a datetime or an offsettime in seconds
g.inject(date("2023-08-17")).date_part(DT.day_of_week).next()   // 4
g.inject(datetime("2023-01-01T15:47:12.5+02:00")).date_part(DT.week).next()   // 52
g.inject(datetime("2023-01-01T15:47:12.5+02:00")).date_part(DT.iso_year).next()   // 2022
g.inject(datetime("2023-08-17T15:47:12.5+02:00")).date_part(DT.epoch).next()   // 1692280032.5
g.inject(datetime("2023-08-17T15:47:12.5+02:00")).date_part(DT.offset).next()   // 7200
g.inject(datetime("2023-08-02T02:00Z")).date_part(DT.day, "America/New_York").next()   // 1

A date has no clock parts (hour and smaller), a time only those (and epoch, the seconds since midnight). A duration gives PostgreSQL's interval fields: year and month from its months (14 months are 1 year and 2 months), day its days, hour and smaller from its time part; it has no week, day-of parts, iso_year or offset:

g.inject(duration("P1Y2M3DT4H5M6.5S")).date_part(DT.month).next()   // 2
g.inject(date("2023-08-17")).date_part(DT.hour).next()   // error: the part hour is not defined for a date

Conversions

A value becomes a date only through an explicit step; nothing is converted by guessing (a string that looks like a date stays a string).

as_date(): TinkerPop's asDate()

as_date() converts to a datetime exactly as TinkerPop's asDate() does:

IncomingResult
a datetimeunchanged
a stringread leniently as ISO 8601 / RFC 3339: without an offset it is UTC, a date alone is midnight UTC (Text Formats)
an int64milliseconds since the epoch, in UTC
a date, a localdatetimethe datetime at UTC (Graphersal: TinkerPop has no such types)
anything else (a float64, (), a list, a map, a time, a duration, an element)an error starting with "Can't parse", as in TinkerPop
g.inject("2023-08-02T09:30:00+02:00", 1690000000000, date("2023-08-02")).as_date().to_list()   // [2023-08-02T09:30:00+02:00, 2023-07-22T04:26:40Z, 2023-08-02T00:00:00Z]
g.inject(1.5).as_date().next()   // error: Can't parse float64 1.5 as a datetime

as_date(GType.X): to another date type

as_date(GType.DATETIME | DATE | LOCALDATETIME | TIME | OFFSETTIME) converts to that type (a Graphersal extension, spelled like as_number(GType.LONG)):

Incoming →DATETIMEDATELOCALDATETIMETIMEOFFSETTIME
stringlenient, as as_date()strict: a date textstrict: a local date-time textstrict: a time textstrict: a time text with its offset
datetimeunchangedits wall-clock date (at its own offset)its wall clockits wall-clock timeits wall-clock time and offset
localdatetimeat UTCits dateunchangedits timeits time at UTC
datemidnight UTCunchangedmidnightan erroran error
timean erroran erroran errorunchangedat UTC
offsettimean erroran erroran errorits local timeunchanged
int64epoch milliseconds, UTCan erroran erroran erroran error
g.inject(datetime("2023-08-02T09:30+02:00")).as_date(GType.OFFSETTIME).next()   // offsettime("09:30:00+02:00")
g.inject(offsettime("09:30+02:00")).as_date(GType.TIME).next()   // time("09:30:00")

GType.DURATION is not a target here: use as_duration(). To read a datetime's wall clock in another zone, use as_local(zone) first (Time Zones).

g.inject(datetime("2023-08-02T23:30-07:00")).as_date(GType.DATE).next()   // date("2023-08-02")
g.inject(datetime("2023-08-02T23:30-07:00")).as_local("UTC").as_date(GType.DATE).next()   // date("2023-08-03")
g.inject("2023-08-02").as_date(GType.DATE).next()   // date("2023-08-02")
g.inject("2023-08-02T09:30").as_date(GType.DATE).next()   // error: unexpected text after the value

as_duration()

as_duration() reads an ISO 8601 duration text; a duration passes unchanged, anything else fails with "Can't parse".

g.inject("PT90M").as_duration().next()   // duration("PT1H30M")

To numbers and text

  • as_number() of a datetime is its epoch milliseconds (TinkerPop), rounded down; the other date types are not numbers (use date_part(DT.epoch) or date_diff()).
  • as_string() of any date is its canonical text; in a script, x.as_string() does the same.
  • cast(GType.DATETIME) (and the other date tokens) parses a string or, for DATETIME, reads an int64 as epoch milliseconds, like as_date(GType.X).
g.inject(datetime("2023-08-02T00:00Z")).as_number().next()   // 1690934400000
g.inject(datetime("2023-08-02T09:30+02:00")).as_string().next()   // "2023-08-02T09:30:00+02:00"
g.inject(date("2023-08-02")).as_number().next()   // error: Cast exception

Storing text as a date

A property written as a string stays a string. To store dates, declare the property in the schema ("format": "date-time"): in open and closed mode a string written to it is converted on write. Or convert in the query: property("at", __.constant(text).as_date()), or write a date value (property("on", date("2023-08-02"))).

now() and today()

now() is the current time as a datetime in UTC; today() is its date, and today(zone) the date in a zone (an IANA name or an offset).

type_of(now())   // "datetime"
now() == now()   // true
type_of(today("Europe/Berlin"))   // "date"
g.add_v("event").property("at", now()).values("at").count().next()   // 1

The start of the evaluation

Like PostgreSQL's now() (CURRENT_TIMESTAMP), now() is the time the script evaluation started, the same value for every call in it: a script that stamps a thousand elements stamps them all with one instant, and now() == now() holds. In the playground a whole script is one unit, so now() is the start of that unit. A saved query called from a script sees its caller's now().

now() and today() are script functions, evaluated before the traversal runs: the traversal gets the resulting value as a constant (inject(now()), property("at", now()), has("at", P.lt(now()))). The journal of a Store and a change set record that value, never the call, so a replay or a recovery writes the same instant, not the time of the replay.

today() is the date of now() in UTC, PostgreSQL's current_date in a UTC session. For the date in another zone pass the zone, or convert the instant yourself:

today("UTC") == today()   // true
g.inject(now()).as_local("America/Los_Angeles").as_date(GType.DATE).next() == today("America/Los_Angeles")   // true

Pinning the clock (hosts)

A host that needs a deterministic clock (tests, a replay of a recorded session) pins it on its engine with graphersal::script::pin_now; every evaluation on that engine then returns the pinned instant, until it is unpinned with None:

use graphersal::script::{engine_with_options, pin_now};
use graphersal::temporal::DateTime;

let mut engine = engine_with_options(&limits, authorizer, &presets);
pin_now(&mut engine, Some("2023-08-02T23:30:00-07:00".parse::<DateTime>()?));
// now() is 2023-08-02T23:30:00-07:00, today() is 2023-08-03 (the UTC date)
pin_now(&mut engine, None); // the system clock again

The system clock is read through web_time, so now() works the same in the WebAssembly playground.

Clock precision

now(), today(), the GQL clocks (datetime(), date(), CURRENT_TIMESTAMP, X.statement(), ...) and the time a schema's defaultFunction: "now" stores all come from the system clock, taken once (at the start of the evaluation, or of the outermost open unit). The time is kept in nanoseconds, with the digits the platform clock gives and never invented ones (the digits below are zero):

PlatformDigits of the system clock
Linuxnanoseconds
macOSmicroseconds (CLOCK_REALTIME)
Windows100 nanoseconds
WebAssembly (the browser playground, Node.js)milliseconds (Date.now())

A pinned clock (pin_now, GraphTraversalSource::with_now) keeps every digit of the pinned value. A Store keeps every digit of a stored now() (file format version 3, Storage and Exchange).

Dates in a Schema

A schema declares a date property as a JSON Schema string with a format, and bounds it with the format* keywords. The full reference (every keyword, the errors and why, inference and diffs) is on the Schemas page; this page is the overview.

formatTypeExample value
date-timedatetime2024-05-01T09:30:00+02:00
local-date-timelocaldatetime2024-05-01T09:30:00 (a Graphersal name: JSON Schema has none)
datedate2024-05-01
timetime09:30:00 (local; JSON Schema's own time requires an offset)
offset-timeoffsettime09:30:00+02:00 (a Graphersal name: JSON Schema's time is this form, but Graphersal's time is local)
durationdurationP1Y2M3DT4H

JSON Schema validators treat format as an annotation and ignore one they do not know, so a schema with these formats stays usable with other tools; Pydantic writes date-time, date, time and duration for datetime, date, time and timedelta fields.

Coercion on write

In open and closed mode a string written to a declared date property becomes the date: the declaration says the property is a date, so nothing is guessed. The text must be one the type reads (Text Formats); a date-time text needs its UTC offset or a zone (2024-05-01T09:30 is refused, never read as UTC). A date value is stored as it is; a value of another date type is refused (a date is not a datetime). Reads never convert: a string stored before the schema was set does not conform to the format, and set_schema reports it.

g.set_schema(#{vertices: #{event: #{schema: #{type: "object", properties: #{
    at: #{type: "string", format: "date-time"},
    on: #{type: "string", format: "date", formatMinimum: "2000-01-01"}
}}}}}, SchemaMode.open);
g.add_v("event").property("at", "2024-05-01T09:30:00+02:00").property("on", date("2024-05-01")).iterate();
g.v().has_label("event").values("at").next().offset   // 7200: a datetime, not a string
{
    g.set_schema(#{vertices: #{event: #{schema: #{type: "object", properties: #{
        at: #{type: "string", format: "date-time"}
    }}}}}, SchemaMode.open);
    g.add_v("event").property("at", "2024-05-01T09:30").iterate()
}   // refused: the text has no offset

Bounds

formatMinimum, formatMaximum, formatExclusiveMinimum and formatExclusiveMaximum (the keywords of JSON Schema's format-comparison proposal, which ajv-formats implements) bound a date property. Their value is the text of a value of the node's type, and a value is compared as the type compares: a datetime by its instant, a duration by its length. minimum and maximum stay number keywords.

{ "type": "string", "format": "date-time", "formatMinimum": "2020-01-01T00:00:00Z" }
{ "type": "string", "format": "duration", "formatExclusiveMaximum": "P1D" }

Inference

infer_schema() reports a stored date with its format ({"type": "string", "format": "date-time"}), and a position that holds strings and dates as an anyOf, so freezing the structure you have (g.set_schema(g.infer_schema(), SchemaMode.closed)) keeps the dates dates. The playground's schema editor offers the date formats as types and their bounds as constraints.

Storage and Exchange

A date keeps its type wherever it goes: in memory, in a snapshot or a Store, in a change set and in a GraphSON file. GraphML has no date type and needs the schema.

In memory

A date is stored inline in the property value, 20 bytes at most, without a heap allocation: a date is a day number, a time and a localdatetime nanoseconds, a datetime nanoseconds since the epoch plus its offset in seconds and, when it has one, a two-byte index of its zone name in the bundled time zone database, an offsettime nanoseconds of the day plus its offset, a duration its months, days and nanoseconds. Equality and ordering compare these numbers (Comparing and Sorting).

Snapshots, journals and the Store

The binary format (packed snapshots .gsnap, Store segments, the write-ahead log) has a value tag per type, defined in the format specification: the exact payload, the range of each type, and the rule that a datetime keeps its offset while equality uses the instant. Every value is stored exactly as it is in memory: nanoseconds over the whole range of years, an offsettime with its offset, a datetime with its zone name (as text, Europe/Berlin, never as a number of this build), a duration over its whole range (a 64-bit count of seconds plus the nanoseconds of one second). Nothing is refused and nothing is cut.

These nanosecond tags came with file format version 3 (Graphersal 0.3.0); version 2 (0.2.x) had microsecond tags only and could not store a value with digits below the microsecond, an offsettime or a zone name. A build that knows version 3 writes version 3 and reads versions 1 to 3, so a .gsnap or a Store written by 0.1.x or 0.2.x still loads; a Store written by 0.2.x is continued as it is, with no upgrade. Graphersal 0.2.x refuses a version 3 file as written by a newer version instead of misreading it. A zone name that this build's time zone database does not know (a file written by a newer Graphersal with a newer database) is refused as content of a newer version, never taken for damage. See Format Versions and Upgrade.

Change sets

A serialized ChangeSet (feature serde) writes a date as a per-value type tag in TinkerPop's GraphSON style, so a replay restores the type without a schema:

TypeTag
datetime{"@type": "gx:OffsetDateTime", "@value": "2024-05-01T09:30:00+02:00"}
datetime with a zone name{"@type": "gx:ZonedDateTime", "@value": "2024-05-01T09:30:00+02:00[Europe/Berlin]"}
date, localdatetime, time, offsettimegx:LocalDate, gx:LocalDateTime, gx:LocalTime, gx:OffsetTime
duration of a time part onlygx:Duration (PT26H)
duration of months and days onlygx:Period (P1Y2M3D)
any other durationgraphersal:Interval (P1MT2H)

Reading is strict: the text must be a value of the tag's type, and a gx:OffsetDateTime must carry its offset.

GraphSON

GraphSON 3.0 reads and writes the java.time types: g:Date/g:Timestamp (epoch milliseconds) become a datetime in UTC, gx:OffsetDateTime, gx:Instant and gx:ZonedDateTime a datetime with the offset of the text (a gx:ZonedDateTime keeps its zone id when the bundled database knows it and the text's offset is that zone's offset at that instant; otherwise the id is dropped and reported, and the offset of the text is kept: the instant is never recomputed from the name, as in the store), gx:LocalDate, gx:LocalDateTime, gx:LocalTime and gx:OffsetTime the types without a date or a zone and the offsettime, gx:Duration and gx:Period a duration. The export writes the tags of the change set table above, which TinkerGraph's g.io(file).read() loads, with one exception: a duration with both months or days and a time part has no java.time type, so it is written as graphersal:Interval, which only Graphersal reads (a deliberate deviation), and a negative gx:Duration is written as java.time writes it, each field signed (PT-1H-30M), because java.time cannot read -PT2562047788015215H30M8S, the canonical text of the shortest duration. Up to nine fraction digits are kept in both directions, and the java.time types Graphersal cannot hold (gx:Year, gx:YearMonth, gx:MonthDay, gx:ZoneOffset) are skipped and reported. The full mapping is on the GraphSON page.

A date-like string without a type tag (GraphSON 1.0, types=false) stays a string; declare the property in the schema to store it as a date.

GraphML

GraphML has no date type: a date is written as its canonical text under a string key. It is read back as a date only when the target graph's schema declares the property with a date format: set the schema on the empty graph first, then import (the playground's "Load from file" takes the schema file next to the graph file; the CLI's --schema). Without a schema the text stays a string. See UUID Values, which describes the same rule for UUIDs, and the Schemas page.

JSON, tables and the playground

Tables, JSON results, the CLI's visualizers, MCP and the dev server write the canonical text ("2023-08-02T09:30:00+02:00"); a script value prints as its literal (datetime("2023-08-02T09:30:00+02:00")). The playground's property editor keeps the type: it shows and edits a date property as one of the date types (Text Formats).

From Python

The Python binding converts the six types to and from the standard datetime module, both as results and as params=. Python's types count microseconds, the engine nanoseconds: a value with digits below the microsecond becomes a pandas type, which holds nanoseconds and subclasses the standard type, when the optional extra is installed (pip install graphersal[pandas]); without pandas it raises ImportError naming the extra. Nothing is ever rounded.

GraphersalPythonWith digits below the microsecond
datetimeaware datetime.datetime with tzinfo=datetime.timezone(timedelta(seconds=offset))aware pandas.Timestamp, the same tzinfo
datetime with a zone nameaware datetime.datetime with tzinfo=zoneinfo.ZoneInfo(name)aware pandas.Timestamp in the ZoneInfo
localdatetimenaive datetime.datetimenaive pandas.Timestamp
datedatetime.date-
timenaive datetime.timeValueError
offsettimedatetime.time with tzinfo=datetime.timezone(timedelta(seconds=offset))ValueError
duration without monthsdatetime.timedelta (an Interval beyond 999999999 days)pandas.Timedelta (an Interval beyond an int64 of nanoseconds, about 292 years)
duration with monthsgraphersal.Intervalgraphersal.Interval

Why pandas: pandas.Timestamp and pandas.Timedelta are subclasses of datetime.datetime and datetime.timedelta, so code written for the standard types keeps working; they hold nanoseconds, fixed offsets and ZoneInfo zones, and pandas is the most widely installed library that has them. whenever holds nanoseconds too (also a time of day) but its types are not the standard ones, and numpy.datetime64 has neither offsets, zones nor a time of day. Which type comes back depends on the value only, never on what is installed. Limits:

  • A time of day (time, offsettime) with digits below the microsecond raises ValueError: no common Python type holds one (pandas has no time of day; a pandas.Timedelta since midnight would come back as a duration). Truncate it with date_trunc(DT.microsecond) or read it with as_string().
  • A pandas.Timestamp holds nanoseconds only from 1677-09-21 to 2262-04-11: a datetime or localdatetime with digits below the microsecond outside these years raises.
import datetime as dt
import graphersal

graph = graphersal.Graph()
at = dt.datetime(2023, 8, 2, 9, 30, tzinfo=dt.timezone(dt.timedelta(hours=2)))
graph.query("g.inject(x).date_add(DT.day, 1).next()", params={"x": at})
# datetime.datetime(2023, 8, 3, 9, 30, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)))
graph.query('duration("P1Y2M")')
# Interval('P1Y2M')
  • An aware datetime is passed with the UTC offset it has at that instant; with a zoneinfo.ZoneInfo its zone name is kept too (a name the bundled database does not know is an error), and it comes back as a ZoneInfo datetime (with the right fold in a repeated hour). Any other tzinfo gives its offset only. An offset with a fraction of a second is refused. A Python installation without the zone (no tzdata on some systems) raises when such a value is returned, rather than dropping the name.
  • An aware datetime.time with a fixed offset (datetime.timezone) is an offsettime; one whose tzinfo has no fixed offset (a ZoneInfo) is refused: a zone's offset needs a date.
  • A timedelta becomes whole days and the rest, both with the sign of the whole (timedelta(hours=-1) is -PT1H).
  • graphersal.Interval is immutable, equal when its three fields are equal (Interval("P1M") != Interval(0, 30), as in the engine), has months, days, micros and nanos (Python ints, exact over the whole range of a duration; micros raises ValueError for a time part with digits below the microsecond) and to_iso(), and is built from the fields or from ISO 8601 text with up to nine fraction digits (Interval("P1Y2M3DT4.000000001H")).
  • A pandas.Timestamp or pandas.Timedelta parameter keeps its nanoseconds; a pandas.Timestamp in a pytz zone keeps the zone name as a ZoneInfo one does. pandas.NaT is refused (pass None).
  • Python's datetime holds the years 1 to 9999; a date before year 1 cannot be returned as one (read it with as_string()).

The binding's README has the details and more examples.

TinkerPop Compatibility

TinkerPop 3.8 has one date type, datetime (a Java OffsetDateTime), the literal datetime(..), the steps asDate(), dateAdd() and dateDiff(), the units DT.second, DT.minute, DT.hour and DT.day, and the tokens GType.DATETIME and GType.DURATION (a Java Duration, which no TinkerPop step produces). Graphersal implements all of it as TinkerPop specifies, with no deviation:

  • datetime("..") (also spelled DateTime("..")) reads ISO 8601 text, a text without an offset as UTC;
  • asDate() converts text and epoch milliseconds, and fails with "Can't parse" for the same inputs as TinkerPop;
  • dateAdd(DT.unit, n) keeps the offset and moves the instant, a day being 24 hours;
  • dateDiff(other) is the difference in milliseconds, null being the epoch;
  • asNumber() of a datetime is its epoch milliseconds;
  • equality and ordering use the instant ("Dates are evaluated based on the numerical comparison of Unix Epoch time"), and dates sort after numbers and before strings.

Every date scenario of the vendored TinkerPop 3.8.2 suite passes (DateTime, AsDate, DateAdd, DateDiff, the date cases of TypeOf and AsNumber), except two Orderability scenarios that also hold a set literal ({"x", "y", "z"}), for which Graphersal has no value type (TinkerPop Compliance).

Extensions

Everything else on the pages of this part is a Graphersal extension, modelled on PostgreSQL:

  • the types date, localdatetime, time and offsettime (GType.DATE, LOCALDATETIME, TIME, OFFSETTIME; typeOf names LocalDate, LocalDateTime, LocalTime, OffsetTime), and duration as a value with months, days and nanoseconds (PostgreSQL's interval, broader than Java's Duration), with their constructors;
  • a zone name kept in a datetime written with one (datetime("..[Europe/Berlin]"), Java's ZonedDateTime, which TinkerPop's datetime() does not produce): its calendar arithmetic follows the zone; a datetime without a name behaves as TinkerPop specifies;
  • the units DT.nanosecond, DT.microsecond, DT.millisecond, DT.week to DT.millennium and the parts DT.day_of_week, DT.iso_day_of_week, DT.day_of_year, DT.iso_year, DT.epoch, DT.offset;
  • date_add(duration), zone arguments, date_diff(other, DT.unit), age(), date_trunc(), date_part(), at_zone(), as_local(), as_duration(), as_date(GType.X);
  • now(), today(), the getters and operators of script values;
  • the schema formats and bounds, GraphSON's java.time types beyond g:Date, and the Python mapping.

The extensions add behaviour where TinkerPop defines none; none of them changes what a TinkerPop step returns. The one deliberate difference in the exchange formats is GraphSON's graphersal:Interval for a duration that no java.time type can hold (Storage and Exchange); all deviations are listed on TinkerPop Deviations.

Dates in GQL

gql() has openCypher's temporal functions (date(), datetime(), duration(), x.year, date.truncate(), duration.between(), ...) with Neo4j's meaning. They build and read the same six values as the Gremlin steps of this part (Cypher's time is the offsettime, its localtime the time): a date a GQL query returns is a date value, and a date a Gremlin step stored reads as a date in GQL. The full list of forms is on The Supported Subset, the differences from Neo4j on Semantics.

The Gremlin steps keep their PostgreSQL-style rules; where a GQL function means something else, the GQL function changes, never the step. This page sets each GQL form beside the Gremlin step or Rhai literal that does the same, and names the differences.

g.gql("RETURN date('2024-03-15') AS d").select("d").next() == date("2024-03-15")   // true
g.gql("RETURN $d + duration('P1M') AS d", #{d: date("2024-01-31")}).to_list()   // #{"d": date("2024-02-29")}
g.add_v("event").property("at", date("2024-03-15")).iterate();
g.gql("MATCH (e:event) RETURN e.at.year AS y, e.at + duration('P1M') AS next").to_list()   // #{"next": date("2024-04-15"), "y": 2024}

Building values

GQLGremlin / RhaiDifference
date('2015-07-21'), localtime('21:40'), time('21:40+01:00'), localdatetime('..'), datetime('..'), duration('P1D')the literals date("2015-07-21"), time("21:40"), offsettime("21:40+01:00"), localdatetime(".."), datetime(".."), duration("P1D")GQL also reads Neo4j's forms: week, ordinal and quarter dates (2015-W30-2, 2015-202, 2015-Q3-21), basic forms (20150721T2140, 2140-02), fractions on any duration unit (P1.5Y); GQL's time('21:40') without an offset is UTC, Rhai's offsettime() needs the offset; both keep a zone in brackets ([Europe/London]) and nine fraction digits
date({year: 2015, week: 30, dayOfWeek: 2}) and the other mapsnone: build the text, or date_add() from a start
date(x), localdatetime(x), datetime(x) of another temporal valueas_date(GType.DATE), as_date(GType.LOCALDATETIME), as_date(GType.DATETIME)the same projections (the date of a datetime at its own offset, a localdatetime read at UTC); GQL's localdatetime(date) and datetime(date) are errors as in Neo4j (localdatetime({date: d}) is midnight), as_date(GType.LOCALDATETIME) of a date is midnight
datetime({.., timezone: 'Europe/Berlin'}), datetime({datetime: x, timezone: z})at_zone(z)the same: both resolve a zone name to its offset at that instant and keep the name in the value (a fixed offset keeps no name)
time(x), time({time: x, timezone: z})as_date(GType.OFFSETTIME)the same projections (a localtime or localdatetime at UTC, a datetime with its offset)
datetime.fromepochmillis(ms), datetime({epochMillis: ms}), datetime({epochSeconds: s})as_date() of an int64 (epoch milliseconds)
the ISO literals DATE '2015-07-21', TIME '21:40+01:00', TIMESTAMP '..', DURATION 'P1D' (Literals)the literals date("2015-07-21"), offsettime("21:40+01:00"), localdatetime(".."), duration("P1D")TIME '..' / TIMESTAMP '..' are the zoned type when the text has an offset, the local one otherwise
date(), datetime(), CURRENT_DATE, CURRENT_TIMESTAMP, LOCAL_TIMESTAMP, X.statement(), X.transaction()today(), now()both are one instant per run; a query run from a script reads the script's instant, so datetime() in g.gql(..) equals the script's now() (a host's pinned clock too); run alone, a query takes it when it starts
g.gql("RETURN date(datetime('2015-07-21T23:40:32+02:00')) AS d").to_list()   // #{"d": date("2015-07-21")}
g.inject(datetime("2015-07-21T23:40:32+02:00")).as_date(GType.DATE).next()   // date("2015-07-21")

Reading components

GQLGremlin / RhaiDifference
x.year, x.month, x.day, x.hour, x.minute, x.seconddate_part(DT.year), ..., or the getters d.year of a script valuethe same
x.quarter, x.week, x.weekYear, x.ordinalDaydate_part(DT.quarter), DT.week, DT.iso_year, DT.day_of_yearthe same (ISO 8601 weeks)
x.dayOfWeek (1 = Monday)date_part(DT.iso_day_of_week)DT.day_of_week is PostgreSQL's 0 = Sunday
x.millisecond, x.microsecond, x.nanoseconddate_part(DT.millisecond), DT.microsecond, DT.nanosecondthe same: the fraction of the second
x.epochSeconds, x.epochMillisdate_part(DT.epoch) (seconds with the fraction), the getter epoch_millis
x.offset ('+01:00'), x.timezone (the zone name, else the offset), x.offsetSecondsdate_part(DT.offset) (seconds), the getter timezoneGQL writes the offset as text
dur.months, dur.years, dur.days, dur.hours, ... (totals)date_part(DT.month) of a duration is the remainder field (PostgreSQL: P1Y has month 0); the getters months, days, microsGQL's names are Neo4j's totals (duration('P1Y').months is 12); its remainders are monthsOfYear, minutesOfHour, ...
g.gql("RETURN date('2015-07-21').dayOfWeek AS a, duration('P1Y').months AS b").to_list()   // #{"a": 2, "b": 12}
g.inject(date("2015-07-21")).date_part(DT.iso_day_of_week).next()   // 2
g.inject(duration("P1Y")).date_part(DT.month).next()   // 0

Truncation

GQLGremlinDifference
date.truncate('month', d), localdatetime.truncate(..), datetime.truncate(..), localtime.truncate(..), time.truncate(..)date_trunc(DT.month)the same for year down to nanosecond and week
X.truncate('millennium' | 'century', d)date_trunc(DT.millennium), DT.centuryGQL follows Neo4j (2017 gives 2000, 1984 gives 1900), Gremlin PostgreSQL (2001, 1901)
X.truncate('weekYear', d), a map of overrides ({dayOfWeek: 2})none
datetime.truncate(unit, d, {timezone: z})date_trunc(unit, z)GQL keeps the wall clock and reads it in z; Gremlin truncates on the wall clock of z
g.gql("RETURN date.truncate('millennium', date('2017-10-11')) AS d").to_list()   // #{"d": date("2000-01-01")}
g.inject(date("2017-10-11")).date_trunc(DT.millennium).next()   // date("2001-01-01")

Arithmetic

GQLGremlin / RhaiDifference
x + dur, x - durdate_add(dur), the Rhai operators x + durthe same order (months clamped, days, time); but in GQL a date takes the whole days of a time part (date + PT33H adds a day) and a localtime ignores months and days, where date_add is an error
dur + dur, dur * n, dur / ndate_add(dur) on a duration (field by field)GQL scales with the fraction cascade (P1M * 0.5 is P15DT5H14M33S)
duration.between(a, b)age() (the operands swapped: age counts from the incoming value back to other)GQL counts whole months, then days, then time, each part signed (Neo4j); age borrows as PostgreSQL does; GQL takes two different types, age one type
duration.inMonths(a, b), duration.inDays(a, b)date_diff(other, DT.month), DT.day (a number, the incoming value minus other)GQL gives a duration (P30Y8M), date_diff an integer (368)
duration.inSeconds(a, b)date_diff(other) (the milliseconds, an integer)GQL gives a duration of seconds only (PT24H)
g.gql("RETURN date('1997-09-11') + duration('P29DT33H') AS d").to_list()   // #{"d": date("1997-10-11")}
g.inject(date("1997-09-11")).date_add(duration("P29DT33H")).next()   // error: adding a duration with a time part is not defined for a date
g.gql("RETURN duration.between(date('1984-10-11'), date('2015-06-24')) AS d").to_list()   // #{"d": duration("P30Y8M13D")}
g.inject(date("2015-06-24")).age(date("1984-10-11")).next()   // duration("P30Y8M13D")
g.inject(date("2015-06-24")).date_diff(date("1984-10-11"), DT.month).next()   // 368

Comparing and text

GQLGremlinDifference
a = b, a < b on one typeis(P.eq(..)), is(P.lt(..)) (Comparing and Sorting)the same; two datetimes by their instant
a < b on two durationsis(P.lt(..)) orders by lengthGQL gives NULL; ORDER BY and order() sort by length
a = b, a < b on two different temporal typesGQL: = is FALSE, < is NULL, as for any two kinds
toString(x)as_string()GQL writes Neo4j's text ('12:00'), as_string() the canonical ISO text ("12:00:00"), as GQL's CAST(x AS STRING) does
g.gql("RETURN toString(localtime('12:00')) AS a, CAST(localtime('12:00') AS STRING) AS b").to_list()   // #{"a": "12:00", "b": "12:00:00"}
g.inject(time("12:00")).as_string().next()   // "12:00:00"

Zone names and the zoned time

A zone name in a value (datetime('2017-08-08T12:31[Europe/Stockholm]'), datetime({.., timezone: 'Europe/Stockholm'})) is kept, printed (toString writes ..+02:00[Europe/Stockholm]), read as x.timezone, and later arithmetic, truncation and duration.between follow the zone's daylight saving rules, as Neo4j does; the Gremlin steps with a zone argument keep the name in the same way. Cypher's time() (ISO zoned_time(), the literal TIME '12:00+01:00', the clock CURRENT_TIME) is the offsettime; a named zone gives a time the zone's offset at the query's instant (Semantics).

g.gql("RETURN datetime('2024-03-30T12:00[Europe/Berlin]') + duration('P1D') AS d").to_list()   // #{"d": datetime("2024-03-31T12:00:00+02:00[Europe/Berlin]")}
g.gql("RETURN time({hour: 12, timezone: '+01:00'}) AS t").to_list()   // #{"t": offsettime("12:00:00+01:00")}

X.realtime() stays refused: Semantics.

Schemas

A graph can store a schema: which vertex and edge labels exist, which properties they carry, of which types and within which constraints, and how edges may connect labels. The schema is plain data in one format, the same in Rust, the script DSL, Python and the playground: our envelope outside, standard JSON Schema 2020-12 inside (a strict subset), so a model_json_schema() from Pydantic can be pasted as a label's schema.

The rule behind enforcement: the storage owns consistency. Every operation that changes the graph passes the schema inside one storage call, never in a step, and every traversal is one unit of work: it is applied completely or not at all.

Warning: a vector rule ("from" on a vector property) added or changed fills every element of its label in the schema-changing unit, and the WHOLE database is locked while it runs: every write and every read waits until it ends. The schema preview (validate_schema, diff_schema) reports how many elements and how long first.

A first schema

g.set_schema(`{
  "mode": "closed",
  "vertices": {
    "person": {"schema": {
      "type": "object",
      "properties": {
        "name": {"type": "string", "minLength": 1},
        "age":  {"type": ["integer", "null"], "minimum": 0}
      },
      "required": ["name"]
    }}
  },
  "edges": {
    "knows": {"connections": [{"from": "person", "to": "person"}],
              "schema": {"type": "object", "properties": {"weight": {"type": "number"}}}}
  }
}`)
g.add_v("person").property("name", "Ann").next()     // ok
g.add_v("person").property("age", -1).next()         // error: age >= 0 (and name is required)

g.get_schema() returns the stored schema as a map (() without one), g.infer_schema() the schema the data satisfies. Rendered as the final value of a session (the CLI, the playground) a schema shows as a table; --format mermaid|plantuml|json|jsonschema|markdown|tree picks another view.

Freeze the structure you have

A common way to start: build the graph without a schema, experiment until the shape is right, then freeze that shape so every later write has to follow it:

g.set_schema(g.infer_schema(), SchemaMode.closed)   // or SchemaMode.open / SchemaMode.none

set_schema(schema, mode) stores schema with its mode replaced by mode (an inferred schema has mode none, which enforces nothing). The mode is a SchemaMode token (SchemaMode.closed, SchemaMode::closed) or one of the strings "none", "open", "closed"; validate_schema(schema, mode) is the dry run. SchemaMode is a reserved name in the script scope.

BindingFreeze
DSLg.set_schema(g.infer_schema(), SchemaMode.closed) (the mode also as a string: "closed")
Rustlet s = g.infer_schema()?.with_mode(SchemaMode::Closed); g_mut.set_schema(s)?
Pythongraph.set_schema(graph.infer_schema(), mode="closed")
PlaygroundSchema panel: Freeze as open / Freeze as closed (shown while the graph stores no enforcing schema)

What each mode freezes:

  • open: the labels and properties that exist get their types and required lists; new labels and new properties stay allowed (unchecked).
  • closed: additionally, no other label, no other property (at any depth) and no edge between other labels than the ones that exist.

It always succeeds on the data the schema was inferred from, in both modes: inference declares every kind seen at every position and requires only the keys every element has (see Inference). The one exception is closed with elements without a label: an unlabeled vertex or edge has no label to declare, and a closed schema admits only declared labels. Then the call fails, changes nothing, and the report names them:

Cannot apply the Closed schema: the existing data violates it (2 kinds of violations on 2 elements of 6 checked)
  1) 1 edge without a label (Closed admits only declared labels) [ids: "7"]
  2) 1 vertex without a label (Closed admits only declared labels) [ids: "3"]

Freeze such a graph in open mode (it admits unlabeled elements unchecked), or give those elements a label first with the label steps (add_label, drop_label, set_label) and freeze again:

g.v("3").add_label("thing").to_list();                                  // a vertex from the report
g.e().not(__.has_label()).set_label("link").to_list();   // every unlabeled edge
g.set_schema(g.infer_schema(), SchemaMode.closed)

(g.v().not(__.has_label()).add_label("thing") labels every unlabeled vertex; Rust: the same steps, or GraphStorage::add_vertex_label/set_edge_label.) (The generated large sample graph has unlabeled edges: it freezes open, not closed.)

Later changes go through patch_schema (add a property, relax a rule) like any other schema.

The format

Envelope

KeyTypeMeaning
$schemastring, optionalThe format: https://graphersal.dev/schema/v1 (any other value is an error).
metaobject, optionalFree-form data the library stores, round-trips and never interprets (a version, a status, server data). Changing it is a schema change.
mode"none" | "open" | "closed", default "none"What is enforced, see Modes.
verticesobjectVertex label → {"schema": <label schema>}.
edgesobjectEdge label → {"connections": [{"from": .., "to": ..}], "schema": <label schema>}.

A label schema is a JSON Schema object node describing the element's property map: {"type": "object", "properties": {..}, "required": [..], "additionalProperties": ..} plus annotations. It may carry $defs (for $ref), $schema and $id (accepted and not stored). A label without schema declares no properties. A connection's from/to is a vertex label or * (any label).

Unknown keys are errors everywhere, the envelope included: {"mdoe": "closed"} is rejected with its location (Invalid schema at /mdoe: unknown key 'mdoe'), never silently ignored.

The canonical form (what get_schema, to_json and every binding return) always writes $schema, mode, vertices and edges, keywords in a fixed order, integers as integers. The empty schema (mode none, no meta, no labels) is no schema: set_schema({}) removes the stored schema. The format is described by the meta-schema graphersal-schema-v1.json (graphersal::schema::META_SCHEMA_JSON).

Types

JSON SchemaEngine typeNote
"integer"int64A value outside i64 cannot be stored at all; 3.0 is not an integer.
"number"float64An int64 written to it is coerced when exactly representable; a stored int64 does not conform.
"string"string
"string" + "format": "uuid"uuidA canonical UUID string is coerced on write; a stored string does not conform.
"string" + "format": "date-time"datetimeAn instant with its UTC offset (2024-05-01T09:30:00+02:00).
"string" + "format": "date"dateA calendar day (2024-05-01).
"string" + "format": "local-date-time"localdatetimeA date and time without a zone (2024-05-01T09:30:00). A Graphersal format name: JSON Schema has none.
"string" + "format": "time"timeA time of day without an offset (09:30:00). JSON Schema's own time requires an offset; Graphersal's is local.
"string" + "format": "offset-time"offsettimeA time of day with its UTC offset (09:30:00+02:00). A Graphersal format name (JSON Schema's time is this form, but Graphersal's time is local).
"string" + "format": "duration"durationISO 8601 (P1Y2M3DT4H): months, days and nanoseconds.
"boolean", "null"boolean, null
"array" + itemsarray<T>items is a full schema (constraints and nullability apply to the items); without items any item.
"array" + "format": "vector" (+ element, dimension, metric)vector<f32, 768>A vector of the declared element (f32 default, f16, i8, bit) and dimension (optional). A list of numbers is coerced on write, a vector of another element quantized; a stored list does not conform. items is not allowed next to it; metric is an annotation; embedder (a label's top-level property only) records the model identity of the embedder that produced the vectors ("hash-ngram/1"), which a vector rule (from) embeds with and the text queries of nearest()/similarity() read; a plain write does not check it. Book page Vectors.
"object" + propertiesobjectWith required and additionalProperties.
["integer", "null"]union<int64|null>A type array: any of the listed types.
anyOf: [..]union<..>At least one member accepts the value (Pydantic's Optional[X] is anyOf: [X, {"type": "null"}]).
{} (no type)anyAdmits every value.

Diagnostics, Display and GType keep the engine's names (int64, float64, uuid, datetime, localdatetime, ...).

Dates and times. In open and closed mode a property declared with a temporal format coerces a string on write: any text the type's parser accepts (ISO 8601 / RFC 3339; the canonical form and the usual variants such as 2024-05-01 09:30Z or 09:30) becomes the temporal value, and text it refuses is a coercion failure that names the expected form. A date-time text must carry its UTC offset or a time zone (2024-05-01T09:30:00Z, 2024-05-01T09:30[Europe/Berlin]): 2024-05-01T09:30 is refused, never read as UTC, and the same holds for a formatMinimum/formatMaximum bound and a typed gx:OffsetDateTime (only the explicit conversion step as_date() keeps TinkerPop's "no offset is UTC"). This is the explicit declaration at work, like the uuid coercion, never a guess from content: an undeclared date-like string stays a string. A stored string does not conform to a temporal format (reads never coerce), and one temporal type never conforms to another (a date is not a datetime). A front end that compares user text with stored values (the playground's Graph panel filter) coerces the text first with GraphSchema::coerce_value(kind, labels, key, value) in Rust: the same coercion a write applies, without writing. JSON Schema's format is an annotation for other validators, which ignore a format they do not know, so a schema with local-date-time stays usable with them. The part Dates and Times describes the types themselves; its page Dates in a Schema has examples.

Keywords

KindKeywords
Structuretype, format (uuid, date-time, date, local-date-time, time, offset-time, duration on a string; vector on an array), element, dimension, metric, embedder (with format: "vector"; embedder on a top-level property only), items, properties, required, additionalProperties (true/false), anyOf
Constraintsminimum, maximum, exclusiveMinimum, exclusiveMaximum (numbers), formatMinimum, formatMaximum, formatExclusiveMinimum, formatExclusiveMaximum (dates and times), minLength, maxLength, pattern (strings), minItems, maxItems (arrays), enum, const (any value)
Annotations (no effect on validation)title, description, $comment, examples, deprecated
Create-time defaults (Defaults on create)default (also an annotation below the top level), defaultFunction (uuidv4, uuidv7, now, today)
References$ref: "#/$defs/Name" with $defs at the label schema's root; inlined when the schema is loaded

A constraint applies to the values of its own kind and ignores the others (JSON Schema semantics): in {"type": ["integer", "string"], "minimum": 10, "minLength": 3} the bound checks the integers and the length the strings. Next to a declared type, a keyword of another kind is an error (minLength on an integer is a mistake, not a no-op). enum/const compare JSON values (1 equals 1.0, a uuid and a date or time compare as their canonical text, so a datetime matches only the text with its own offset).

formatMinimum, formatMaximum, formatExclusiveMinimum and formatExclusiveMaximum bound a date or time: the keywords of JSON Schema's format-comparison proposal (ajv-formats implements them; other validators ignore unknown keywords). Their value is the text of a value of the node's temporal format, and they are valid only next to one (minimum stays a number keyword):

{ "type": "string", "format": "date-time", "formatMinimum": "2020-01-01T00:00:00Z" }
{ "type": "string", "format": "duration", "formatExclusiveMaximum": "P1D" }

A value is compared with its type's ordering: a datetime by its instant (2020-01-01T01:00:00+01:00 equals the minimum above), a duration by its length (a month counts 30 days, a day 24 hours, as PostgreSQL orders intervals), the others by their calendar or clock value.

Local references are inlined: a loaded schema has no $ref/$defs, and a reference cycle is an error (recursive schemas are not supported). Only annotations, default and defaultFunction may sit next to a $ref; they override the definition's.

What is an error, and why

InputWhy it is rejected
An unknown key or keyword, anywhereA typo must never weaken a schema silently.
format other than uuid, date-time, date, local-date-time, time, offset-time, duration (email, uri, ...)Accepting an unknown format as a plain string now would let a later version silently change what an existing schema accepts. Remove the format (the value is a string).
formatMinimum (and the other format bounds) without a temporal format, or with text that is not of the format's typeA bound needs the type it compares in; the hint shows an example of the type's text.
additionalProperties: {schema} (a map of T, Pydantic dict[str, T])No map type yet. Use {"type": "object", "additionalProperties": true}.
oneOf, allOf, not, if/then/elseNot implemented; anyOf covers oneOf when the members cannot both match.
prefixItems, contains, tuples (items: [..])An array has one item schema.
uniqueItems, multipleOfNot yet (additive later).
patternProperties, propertyNames, minProperties, dependent*, unevaluated*Keys are declared with properties, required, additionalProperties.
readOnly, writeOnly, content*Not among the accepted annotations.
A remote or non-$defs $ref, a reference cycleReferences are inlined at load.
nullable, variants, min, min_length, int64, ... (spellings of other schema dialects, such as OpenAPI's nullable)The hint names the JSON Schema spelling.

Every error is SchemaError::InvalidSchema { path, reason, hint }, path a JSON Pointer into the input (/vertices/person/schema/properties/age/minimum), and its help names the fix.

Defaults on create

default has SQL DEFAULT semantics: when a vertex or edge is created without a property whose schema declares a default, the default is stored, as if the query had written it.

g.set_schema(#{mode: "open", vertices: #{person: #{schema: #{type: "object", properties: #{
    name: #{type: "string"},
    active: #{type: "boolean", default: true},
    uid: #{type: "string", format: "uuid", defaultFunction: "uuidv7"}}}}}});
g.addV("person").property("name", "alice").iterate();
g.V().valueMap("name", "active").toList()   // [#{"active": [true], "name": ["alice"]}]
  • Only on create: addV()/addE() (also with their folded property() steps), mergeV()/mergeE() when they create (never on a match), GQL's INSERT (Cypher CREATE), the playground's create dialog, and GraphStorage::add_vertex/add_edge in Rust (and their _with forms). The default is filled in before the new element is coerced and validated, so a required property with a default is satisfied, and a canonical string default of a uuid property is stored as a uuid.
  • Only what is missing: a value the create writes wins, also an explicit null (property("k", ()) stores null). A property() that is not folded into the creation (a traversal value, say) overwrites the default afterwards.
  • default: null is never stored. Pydantic writes "default": null on every optional field; storing it would fill the data with nulls nobody wrote. Write the null explicitly when you want one.
  • Never on read: values("k"), valueMap(), the display and every export show what is stored, nothing is substituted for an absent property.
  • No backfill: setting or changing a schema never fills existing elements, and a changed default is never re-applied. To fill existing elements, use the backfill recipe.
  • Stored data is reproduced, not re-created: GraphML/GraphSON imports, apply_change_set, replay, recovery and snapshot loads store exactly what they carry: they go through the storage primitive GraphStorage::insert_vertex/insert_edge, which applies no default (call it yourself to store an element exactly as given, like a load).
  • Modes open and closed only: mode none stores the schema without enforcing anything, and applies no default either.
  • Top-level properties only: a default inside an object value's schema (address.city) stays an annotation; nothing fills in keys of a value the create supplies.
  • Multi-label vertices: the first label, in label order, that declares a key decides, as for coercion: its default is stored, or nothing when that label declares the key without one.

A default must be a valid value of its property (after the write coercion): set_schema, patch_schema and validate_schema reject {"type": "integer", "default": "x"} or a default below the property's minimum with an InvalidSchema error. Only the defaults that are applied are checked: a default: null and a nested default are not.

defaultFunction computes the value instead (like PostgreSQL's gen_random_uuid()/uuidv7()/now()/current_date):

defaultFunctionValueThe property must admit
uuidv4a random version-4 UUID, new for every element{"type": "string", "format": "uuid"}
uuidv7a time-ordered version-7 UUID (RFC 9562: 48 bits of Unix milliseconds, then random bits; increasing within a process), new for every element{"type": "string", "format": "uuid"}
nowthe datetime of the unit's start: ONE value for every element created in the same unit{"type": "string", "format": "date-time"}
todaythe UTC date of that same time{"type": "string", "format": "date"}

set_schema, patch_schema and validate_schema reject a function on a property that does not admit its value (now on a string or a date, uuidv4 on an integer) with an InvalidSchema error whose hint names the declaration it needs. A property has either default or defaultFunction, never both, and defaultFunction sits only on a label's top-level property (a saved query's parameter schema rejects it). The generated value is stored as a plain value: the change set and the journal record it, so replay and recovery reproduce the same UUID or time.

Which time now stores (PostgreSQL's now(): the start of the transaction):

  • In a script it is the time the DSL's now() returns in the same evaluation: one clock per evaluation, so let t = now(); g.addV("event").iterate(); stores exactly t, and every element the script creates gets the same time. A host pins that clock with script::pin_now (the playground and the CLI use the system clock).
  • In Rust it is the start of the storage's outermost open unit (GraphStorage::unit_started_at): the traversal's own unit, or the explicit transaction(|g| ..) around several traversals. GraphTraversalSource::with_now(t) pins it for one traversal (deterministic tests). GraphStorage::add_vertex/add_edge take the unit's start (CreateContext::for_storage); add_vertex_with/add_edge_with take a CreateContext (CreateContext::at(t) pins).
  • A later unit never gets an earlier time than a previous one of the same graph (the system clock is raised to the previous unit's start and the last commit time).
  • The time is kept in nanoseconds, with the digits the platform clock gives (Clock precision).
g.set_schema(#{mode: "open", vertices: #{event: #{schema: #{type: "object", properties: #{
    at: #{type: "string", format: "date-time", defaultFunction: "now"},
    day: #{type: "string", format: "date", defaultFunction: "today"}}}}}});
let t = now();
g.inject(1, 2, 3).addV("event").iterate();
g.V().values("at").dedup().toList() == [t]   // true: three events, one time

A change of a default or defaultFunction is listed by diff_schema as default_changed, and it is always backward compatible: it changes only what future creates store.

Required and nullable

required (on the object) and nullability (the type) are independent, as in JSON Schema:

null not admitted ("type": "string")null admitted ("type": ["string", "null"])
in requiredmust be present, non-nullmust be present, may be null
not in requiredmay be absent, never nullmay be absent or null

A missing required key is MissingRequiredProperty; a null where the type does not admit it is a TypeMismatch (expected string, got null). null stays a real stored value (property("k", ()) stores it, it never removes a property: use remove_property, see Removing Properties). Inside a JSON value {"a": null} differs from {}.

Required properties must be supplied when an element is created. The optimizer rule add_property_fold folds addV(..)/addE(..) and the property(k, v) steps that follow into one creation, so g.addV("Person").property("name", "Ann").property("age", 30) creates a valid element in one call. With the rule disabled, or for a property() that cannot be folded, the empty creation is rejected before anything is written. Removing a required property is rejected in open and closed mode.

Modes and additionalProperties

noneopenclosed
Coercion on write (canonical string to uuid, date and time text to its declared type, int64 to float64)nodeclared propertiesdeclared properties
Types, constraints, required of declared labels (any depth)noyesyes
Undeclared labelsallowedallowed, uncheckedrejected (also unlabeled elements)
Default additionalProperties of an object node-truefalse
Defaults on create (default, defaultFunction)noyesyes
Edge topology (connections)nonoyes

mode governs undeclared labels and topology, and it is the default additionalProperties of every node typed object that does not state its own. An explicit value wins, both ways: a free-form object in a closed graph is {"type": "object", "additionalProperties": true}, a strict object in an open graph says false. A node without type: "object" (an anyOf wrapper) puts no constraint on keys; its members do.

Multi-label vertices (see Multi-Label Vertices): every label checks the properties it declares and its own required list; a top-level property that no label declares is allowed when ANY label admits additional properties (the same "any label" rule as topology). Coercion uses the first label, in label order, that declares the key. closed rejects a vertex without a label or with an undeclared label. Adding or removing a label re-validates the vertex under the new label set and commits only on success.

Edge labels are single, but can be changed (set_label(..), GraphStorage::set_edge_label). The change checks the edge as stored under the new label (closed: a declared label and a declared connection; open and closed: the new label's required keys and declared types) and changes nothing on a violation. Stored values are not coerced by a label change (reads never coerce); later writes coerce by the new label's declarations.

none describes without enforcing; the GraphML import still restores the declared logical types from it (uuid, the date and time types, array, object; see UUID Values). A date or time is written to GraphML as its canonical text under a string key (up to nine fraction digits, a zone name in brackets, an offsettime with its offset) and read back exactly as a temporal value where the target schema declares its format (date-time, date, local-date-time, time, offset-time, duration; text that is not of the type, such as an offset-time without its offset, fails the import with InvalidAttributeValue); without a declaration it stays a string.

Edge topology (closed)

An edge label declares its allowed connections ({"from": "Person", "to": "Company"}, * matches every label). Because labels are a set, an edge is accepted if ANY label of the source and ANY label of the target matches a declared connection. An edge label without connections allows every pair. A label change that would make an incident edge violate the connections is rejected as a whole.

Nested values

The content of an object, array or anyOf value is validated at any depth: declared nested keys are type- and constraint-checked, required nested keys must be present, undeclared nested keys follow the object's additionalProperties. Errors name the canonical path ($.address.zip, $.items[1].n). A nested write (property(jpath("address.zip"), v)) coerces the leaf to the type declared at that location. See Path Keys (jpath).

Constraints

pattern is a regular expression with JSON Schema semantics: it is not anchored, so a value matches when the expression matches anywhere in it. Write ^...$ to match the whole value:

{ "type": "string", "pattern": "^[A-Z][a-z]+$" }
{ "type": "string", "pattern": "@" }
{ "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" }

The syntax is the ECMA-262-like subset of the Rust regex crate: literals, ., classes ([a-z], [^0-9], \d, \w, \s), anchors, groups, alternation | and the quantifiers *, +, ?, {n}, {n,}, {n,m}. Two differences to ECMA-262: look-around and back-references are not supported (matching stays linear in the input), and \d, \w, \s, \b are Unicode-aware (write [0-9] for ASCII digits). A JSON text doubles every backslash. The expression is compiled once, when the schema is loaded, and an invalid one rejects the schema.

minLength/maxLength count characters (code points). An empty array satisfies every items (it has no item of a wrong type); use minItems: 1 to require one.

The schema methods

Seven methods, the same everywhere. They are plain calls on the graph source, not traversal steps (like g.statistics()); each runs in the current unit (a transaction, a whole-script unit) or as a unit of its own.

MethodReturnsAuthorization
get_schema()the stored schema, or none (never inferred)Read on Schema
set_schema(schema), set_schema(schema, mode)- (replaces the stored schema; mode replaces the schema's mode)Update on Schema
patch_schema(patch)the new schema (JSON Merge Patch, RFC 7396, onto the stored one)Update on Schema
validate_schema(schema), validate_schema(schema, mode){violations, diff, compatible}: a dry run against the dataRead on Schema
validate_schema_patch(patch)the same for a patchRead on Schema
infer_schema()the schema the data satisfiesRead on Schema
diff_schema(schema){changes, compatible} from the stored schemaRead on Schema
InputOutput
Rust (GraphTraversalSource)GraphSchema (GraphSchema::from_json(text), from_value, or the builders), SchemaPatch (graphersal::schema)GraphSchema, SchemaValidation, SchemaDiff (to_value() gives the data shape)
DSL (get_schema, set_schema, ...)a map or JSON texta map
Python (Graph.get_schema(), ...)a dict or JSON str (keyword policy=)a dict
Playground engine (wasm getSchema, ...)JSON textJSON

A map built in the DSL keeps its keys in alphabetical order (Rhai maps are sorted), so the property order of a schema that went through a map is alphabetical; JSON text and Python dicts keep it. The traversal step g.v()...infer_schema() infers over a stream, with the same inference.

In a DSL map literal, quote the keys that are not plain identifiers: $ref, $defs, $schema and $id start with $. default (a word Rhai reserves) is accepted as a plain key in the Graphersal DSL, quoted or not:

g.patch_schema(#{vertices: #{person: #{schema: #{type: "object", properties: #{
    age: #{type: ["integer", "null"], default: 7}
}}}}})

JSON text needs no quoting rules of its own: g.set_schema(text) takes the schema as written.

A schema change is a database change: it advances the commit sequence number, makes the run mutated, is recorded as Mutation::SetSchema { before, after } (the canonical JSON) in the same change set as the data, rolls back with its unit, and is reported in the result's changes: {data, schema} (Execution::changes(), the DSL's r.changes, the playground's response). Validation is immediate: the existing data is checked when the schema is set, not at commit.

The schema summary

The schema JSON is precise but long, and says nothing about the data's counts: the stored schema of a knowledge graph of 124 labels is 204 KB. The schema summary is the map a reader (an agent behind the MCP endpoint, a person at the REPL) needs first, one line per label:

graph: 6 vertices, 6 edges; 2 vertex labels, 2 edge labels; no stored schema (mode none)
notation: label count: key type, ...; "?" = not on every element ...

vertex labels
person 4: age int, name str
software 2: lang str, name str

edge labels
created 4 person->software: weight float
knows 2 person->person: weight float
  • Built from the data: one walk over every element, so element counts, key counts and endpoint pairs are exact; only the value types are sampled per label (the first 1000 elements of a label, then fewer per doubling, plus the first element of every distinct key set, so every key has a type). Writes nothing, can be cancelled.
  • A key not on every element of its label is marked ?, with its share under 10 % (? 3%) and its count under 1 % (? n=12). Types: str int float bool uuid date datetime localdatetime time offsettime duration null, [T] a list, map, vector<f32,384>, a|b mixed.
  • An edge label lists its from->to pairs of primary vertex labels (with counts when several); a vertex label lists the other labels its vertices carry (also labelled: admin 1).
  • With at least four labels of a kind, the key entries at least 80 % of the labels share are written once (every vertex label except _IndexRun has: ...); the lines of the labels named as exceptions keep every key.
  • The stored schema is laid over the data: its mode in the header, label descriptions (the first sentence, cut to 80 characters), declared enums (lang str in(java|rust)), declared keys and labels without data ((declared, no data)), declared connections without data (person->company 0).
  • Caps: 30 keys per label (the most frequent; ... N more keys), 200 labels per kind (the largest; ... N more vertex labels (M vertices)).
  • Details of some labels: every key with its declared description, and for a vertex label the edges going out and coming in (edges out: created->software 4, knows->person 2).
WhereHow
MCPget_schema / infer_schema answer it by default, without the descriptions (descriptions: true adds them, labels for details, format: "json" for the JSON); resource graphersal://schema-summary (with the descriptions)
REPL/schema, /schema person knows
Rustg.schema_summary(&SchemaSummaryRequest::new().with_labels(["person"]))?.to_string() (graphersal::schema; with_max_keys, with_max_labels, with_type_samples, with_descriptions, with_cancel)
AI Chatits system prompt carries the summary of the graph at the conversation's start

It needs Read on Schema, like infer_schema().

Applying a schema to existing data

set_schema and patch_schema validate all existing data first, in one pass over the vertices and edges, when the mode is open or closed. When the stored schema already has that mode, the data satisfies it (every write was checked), so only the elements of the labels whose declaration was added, changed or removed are read: a patch of one label checks that label's elements, not the whole graph (validate_schema checks the same elements). If anything violates the schema, the graph and its current schema stay unchanged and the call fails with one aggregated error that lists every kind of violation, grouped by rule with a count and a few sample ids:

Cannot apply the Closed schema: the existing data violates it (5 kinds of violations on 22 elements of 22 checked)
  1) Person.age is declared mandatory but is missing on 12 vertices [ids: "p0", "p1", "p2", "p3", "p4" and 7 more]
  2) vertex label Alien is not declared (Closed): 5 vertices [ids: "x0", "x1", "x2", "x3", "x4"]
  3) Company.name is declared mandatory but is missing on 3 vertices [ids: "c0", "c1", "c2"]
  4) Person.age has the wrong type on 1 vertex (declared int64, found string) [ids: "t"]
  5) Robot.model is not declared (Closed) on 1 vertex [ids: "r"]
  • A group is (kind, label, field or path): missing required keys, undeclared labels or properties, type mismatches, constraint violations, edge topology violations (closed) and nested path violations (Person $.address.zip is declared mandatory but is missing on 1 vertex).
  • Every violation inside a value is listed, not only the first: all keys, all array items, at any depth, each under its own path ($.address.zip wrong type, $.address.street missing and $.address.city undeclared are three groups). Array indices are collapsed into [*]: a rule broken by any item of an array is ONE group ($.addresses[0].zip and $.addresses[2].zip missing are the group $.addresses[*].zip), which shows the first concrete path it met (Person $.addresses[*].zip is declared mandatory but is missing on 5 vertices (first at $.addresses[1].zip) [ids: ...]). Per node only the first failing constraint is named. An element counts once per group, however many of its items break the rule. A single write still fails on the first violation it meets.
  • Groups are ordered by count (largest first), then kind, element, label and field, so the same data gives the same report.
  • Each group shows its count and up to 5 sample ids (cut to 40 characters, escaped); at most 20 groups are printed, the structured report keeps up to 1000, further violations are only counted.
  • Stored data is checked exactly as it is: nothing is coerced and nothing is written.
  • validate_schema returns the same report as data: violations: {mode, elements_checked, violating_elements, total_violations, omitted_violations, groups: [{kind, element, label, field, example_field, detail, count, sample_ids, omitted_ids}]} (example_field is the first concrete path of a [*] field, null otherwise), with kind one of unknown_label, missing_required, type_mismatch, constraint_violation, undeclared_property, invalid_topology.

How to proceed: fix or migrate the offending data, relax the schema (make a key optional, admit null, declare the label or property), apply it with mode none, or start from infer_schema(), which is valid for the data it came from.

Making a key required: backfill first, in one transaction

A schema that requires a key the existing elements lack is rejected. Backfill first and tighten last, all in one transaction, so no reader ever sees the intermediate state:

let declare = SchemaPatch::from_json(
    r#"{"vertices": {"person": {"schema": {"properties": {"email": {"type": "string"}}}}}}"#)?;
let require = SchemaPatch::from_json(
    r#"{"vertices": {"person": {"schema": {"required": ["name", "age", "email"]}}}}"#)?;
graph.transaction(|g| -> TraverserResult<()> {
    // 1. In a closed schema, declare the key (optional) so it may be written.
    g.traversal_mut().patch_schema(&declare)?;
    // 2. Backfill.
    g.traversal_mut().v(None).has_label("person").property("email", "unknown").to_list()?;
    // 3. Make it required.
    g.traversal_mut().patch_schema(&require)?;
    Ok(())
})?;

(schema_api_tests::backfill_then_require_in_one_transaction runs this recipe.)

The same in a script run as one unit (atomic=True in Python, every playground run): patch to optional, backfill, patch to required. A schema default does not backfill anything: it is stored only for elements created after it is set (Defaults on create).

Changing a schema: patch and diff

patch_schema applies a JSON Merge Patch (RFC 7396) to the canonical form of the stored schema ({} without one): an object merges member by member (property order is kept), null removes a member, any other value (an array too) replaces it. RFC 7396 cannot set a member to null; use set_schema for a "default": null. validate_schema_patch previews the result against the data.

diff_schema lists the changes (kind, element, label, path such as $.address.zip or $.tags[*], before, after) and whether each is backward compatible: data and clients written against the old schema keep working: the old data stays valid and every write that followed the old schema still succeeds. In short, a compatible change only adds (an optional key, a label, an allowed value) or relaxes (a wider type, a looser bound, a less strict mode); tightening a rule or removing a declaration something could depend on (a label, a key of a closed object) is incompatible. This is the usual schema-registry convention: adding an optional property is compatible, also to an open object, and so is removing a property declaration from an open object (the key becomes an undeclared one, which the object admits; the change is still listed as property_removed). A server's "compatible changes only" policy can veto the rest in a before_commit hook.

ChangeCompatible when
modeit gets less strict (closed → open → none); open → closed is incompatible
meta, annotations (title, description, ...)always
default, defaultFunction (added, changed, removed; kind default_changed)always: it changes only what future creates store
embedder of a vector (kind embedder_changed)when it is declared where there was none; changing or removing it is incompatible: the stored vectors and a text query embedded by another model are not comparable, and a text query needs the model
label addedthe old mode was closed (no client could write it), or its schema requires no key and admits undeclared keys (an open graph)
label removednever
connection added/removedthe label's connections still allow every old pair (an empty list allows all), or the new mode is not closed (topology binds only there)
property addedit is optional (not in required), also in an open object
property removedthe object admits undeclared keys (open: mode open/none or additionalProperties: true), whether the key was optional or required; from a closed object never
key made required / optionalnever / always
additionalPropertiesfalse → true
typethe new type admits every kind the old one did ("integer" → ["integer", "null"])
minimum, maxLength, minItems, formatMinimum, ...removed or relaxed (a later formatMaximum, an earlier formatMinimum)
formatnever (date → date-time is another type, so are adding and removing a format)
pattern, constremoved
enumremoved, or a superset

A key the old schema listed in required without declaring it was written by every old client, with any value: declaring it later is compatible only if the declaration accepts everything. With a new mode none every change is compatible (nothing is enforced any more).

The diff is static: it compares the two schemas, never the data. Existing data that conflicts with a compatible change (an element that already holds a newly declared optional key with another type, say) is found by validate_schema / validate_schema_patch, and set_schema refuses to apply the schema until it is fixed.

Inference

infer_schema() (and the step) report what the data holds, at every position: the kinds seen (a type array, or anyOf when a string, a uuid and the date and time types share a position: a datetime is {"type": "string", "format": "date-time"}), items of arrays, properties of objects, and required only for keys every object at that position has, at any depth (also inside arrays and next to other kinds). Every label of a vertex is declared; connections use the endpoints' first labels. The result has mode none and is valid for the data it came from in open and in closed mode (an unlabeled element has no label to declare, so closed rejects it; see Freeze the structure you have). It never guesses from string content: a UUID-shaped string is a string. Inference statistics (counts) are not part of the format.

Renderers

FormatShows
table, markdownone row per property path (address.zip, roles[].name), type, required, nullable, constraints (0..150, length 1..80, pattern ^x$), notes (description, default, marked (annotation) where it is not applied: null or below the top level, defaultFunction)
treethe labels and their properties as a tree
jsonthe canonical format
jsonschemaone standalone JSON Schema per label ($defs: vertex:person, edge:knows), the mode's default additionalProperties written out
mermaidan erDiagram; nested objects are entities of their own (`person
plantumlthe label topology as entity diagrams, then a @startjson view of the condensed schema

The meta-graph (schema.to_graph() in the DSL, GraphSchema::to_graph in Rust) has one vertex per vertex label and one edge per connection, each with its schema node as the schema property.

The playground's Schema panel shows the same schema as editable tables, as JSON, as a graph of its labels (node size and count from the data) and as the Mermaid diagram, here for a small cloud inventory:

The label graph of a schema: vertex labels with their counts, edge labels as arrows

The Mermaid entity diagram of the same schema

Pasting a Pydantic model

Model.model_json_schema() loads as a label schema as it is ($defs/$ref, anyOf with null, title, description, default, enum, const, exclusive*, additionalProperties: false, and the date and time fields: datetime ("format": "date-time"), date, time and timedelta ("format": "duration")), except for one thing to remove first:

  • dict[str, T] fields ("additionalProperties": {..}): no map type; write {"type": "object", "additionalProperties": true}.

A Pydantic time field is a time of day: Graphersal's time has no offset, so a text with one (10:00:00+02:00) is refused by the coercion (declare a date-time for an instant).

Tuples (prefixItems) and Decimal (anyOf with a string pattern for some versions) are not supported either. The top level of the model must be an object ("type": "object").

A field's non-null default (active: bool = True) becomes a default on create in mode open/closed; the "default": null Pydantic writes on every optional field stores nothing.

GQL writes

A GQL INSERT creates each element in one storage call with every property of its map, so defaults, required, coercion and the mode apply to the whole element, as for a folded addV(..).property(..). A NULL value is not stored, so it does not satisfy required. A violation fails the query, and its help line is written for GQL (toInteger() for a type mismatch, the INSERT map and coalesce() for a missing property):

g.set_schema(#{mode: "closed", vertices: #{person: #{schema: #{type: "object", properties: #{
    name: #{type: "string"}, active: #{type: "boolean", default: true}}, required: ["name"]}}}});
g.gql("INSERT (:person {name: 'alice'})").iterate();
let refused = g.gql("INSERT (:robot {name: 'r2'})").execute();   // fails: the closed schema has no label robot
g.gql("MATCH (n) RETURN labels(n) AS labels, n.active AS active").to_list()   // #{"active": true, "labels": ["person"]}

GQL's SET and REMOVE change an existing element property by property and label by label, as property(), remove_property(), add_label() and drop_label() do, and each change is checked like theirs: a value of the wrong type, an undeclared property or label in a closed schema, and removing a required property (with REMOVE n.k, SET n.k = NULL, or a SET n = {..} whose map lacks it) fail the query, which then changes nothing:

g.set_schema(#{mode: "closed", vertices: #{person: #{schema: #{type: "object", properties: #{
    name: #{type: "string"}, age: #{type: "integer"}}, required: ["name"]}}}});
g.gql("INSERT (:person {name: 'alice'})").iterate();
let refused = g.gql("MATCH (p:person) SET p.age = 3, p.name = NULL").execute();   // fails: 'name' is required
g.gql("MATCH (p:person) RETURN properties(p) AS props").to_list()   // #{"props": #{"name": "alice"}}

A failing query changes nothing

The schema is validated per storage call (one add_v with its folded properties, one single property(key, value), one drop, ...), and every traversal is one unit of work: when a call fails, the whole traversal is rolled back, including what its earlier steps wrote (see Transactions).

In the playground a refused write shows the failing step and how to fix it (here a closed schema that declares cpus as int64):

A schema violation in the Results panel with its help text

CaseTest
property(map) with several entriesschema_gap_tests::gap4_property_map_is_atomic
property_json (Rust API)schema_gap_tests::gap4_property_json_is_atomic
mergeV/mergeE option(Merge.onMatch, map) with several entriesschema_gap_tests::gap4_merge_v_on_match_is_atomic
addE over several start verticesschema_gap_tests::gap4_add_e_over_several_endpoints_is_atomic
any traversal with several stepstransaction_tests::a_schema_violation_rolls_back_the_whole_traversal

A GraphML import into an existing graph is one unit too: an invalid element rolls back the elements imported before it. GraphML carries no schema: set the schema first, then import. The CLI does both in that order with graphersal --graph g.graphml --schema schema.json [--schema-mode closed] (also for GraphSON, and with --server); a violation stops the start with exit code 1.

Saved Queries

A saved query is a named, parameterized piece of DSL stored IN the database, next to the schema: written once, called by name from any front end (the CLI, Python, the playground).

g.query("older_than", #{age: 30}).values("name").toList()
// ["josh", "peter"]
  • The body is the text of ONE Rhai function, or ONE GQL query; its parameters are named and typed.
  • A call returns what the function returns: a traversal can be continued by the caller (like a SQL view), a value (a number, a list, a map) is a value (like a stored procedure).
  • A query reads, unless its body writes data: then it is saved as a query that writes, and a call may write exactly what the engine infers from the body (its effects), as one transaction. Nobody declares effects, and a query never writes the schema, the saved queries or files.
  • Queries live in folders (an attribute, not part of the name) and carry an optional description.

Every example on this page was run with graphersal on the default modern graph; the line after // is its real output. Each block starts from a fresh graph.

Defining a query

g.define_query(#{
    name: "older_than",
    folder: "reports/people",
    description: "Persons older than the given age.",
    params: #{
        age: #{schema: #{type: "integer", minimum: 0, maximum: 150,
                         description: "Age in years"},
               default: 30}
    },
    body: `fn older_than(age) {
        g.v().has_label("person").has("age", P.gt(age)).order().by("age")
    }`
})
g.query("older_than").values("name").toList()
// ["josh", "peter"]

g.define_query(#{..}) stores a new query or replaces the one of that name. The keys:

KeyRequiredMeaning
nameyesthe query's name, also its Rhai function name: [A-Za-z_][A-Za-z0-9_]*, 1 to 128 bytes, not a Rhai keyword; case-sensitive, unique per database
bodyyesthe text of ONE Rhai function named like the query (with language: "gql": one GQL query)
languageno"rhai" (the default) or "gql" (see Saved queries in GQL)
paramswhen the function has parametersparameter name -> its declaration (see Parameters)
foldernoa /-separated path such as "reports/sales"; "" or () is the root
descriptionnofree text (at most 4 KiB); defaults to the function's doc comment
metanofree text, stored and never interpreted

The definition is checked before anything is stored, and refused with an error naming the problem:

  • the body compiles and is exactly one function named like the query, with nothing beside it (closures inside it, such as .filter(|n| n.len() > 3), are part of that function);
  • every parameter of the function is declared in params, and params declares nothing else;
  • the catalog rules: name, folder (at most 8 segments, 255 bytes), sizes (source at most 64 KiB), parameter names (not a DSL global such as g, P or T), every parameter schema, and every default against its schema.

Saved queries called by the body are not checked at definition: a missing one fails when it is called.

Several queries at once

g.define_queries(folder, source[, params]) stores every function of a source as a query of its own, named like the function, described by its doc comment (/// lines or a /** .. */ block). params maps each function name to its parameter map. All of them are stored in one unit: either every query is stored or none. It returns the names.

g.define_queries("reports/sales", `
    /// Persons, oldest first.
    fn oldest(n) { g.v().has_label("person").order().by("age", Order.desc).limit(n) }

    /// Software names.
    fn software() { g.v().has_label("software").values("name") }
`, #{oldest: #{n: #{schema: #{type: "integer", minimum: 1}, default: 2}}})
// ["oldest", "software"]
g.query("oldest").values("name").toList()
// ["peter", "josh"]
g.get_query("oldest")["body"]
// fn oldest(n) { g.v().has_label("person").order().by("age", Order.desc).limit(n) }

Each query stores the text of its own function only.

Parameters

A parameter is declared as #{schema: <schema node>, default: <value>}, or as a bare type name (the short form): "integer", "number", "string", "boolean", "array", "object", "null" or "uuid".

  • The schema uses the node format of the graph schema: type, enum, minimum, maximum, pattern, minLength, items, ..., and the annotations title, description, examples.
  • The default sits beside the schema, not inside it: a default keyword inside the parameter's schema is an annotation (a data schema's default applies only when a vertex or edge is created), while a parameter default IS substituted when the argument is left out. A parameter without a default is required. A defaultFunction (uuidv4, now, ...) anywhere in a parameter's schema is an error: it fills a property of a created element and means nothing for an argument.

params may also be the list g.get_query(name)["params"] returns, one #{name, schema, default?, required?} per parameter (required must match the default: a parameter is required exactly when it has none), so a stored definition can be read, changed and given back:

let q = g.get_query("older_than");
let body = q["body"];
body.replace("P.gt", "P.gte");
g.define_query(#{name: "older_than", params: q["params"], body: body})

Arguments are named: g.query("x", #{limit: 5}), or g.query("x") when every parameter has a default. An argument is a data value (a string, a number, a boolean, a UUID, a date or time, a list, a map; never a traversal or a closure), bound to the function's parameter like a prepared-statement parameter, never spliced into text. It is checked against its schema before the body runs; the only conversion is the schema's write coercion (an int64 where a float64 is declared, a canonical UUID string where a uuid is declared, the ISO 8601 text of a declared date or time format such as date-time). () is a value (null), not an omitted argument.

g.query("older_than", #{age: 200})
// Error: Invalid argument 'age' for saved query 'older_than': Constraint violation on 'older_than.age': value <= 150 (actual: 200)
g.query("older_than", #{years: 30})
// Error: Saved query 'older_than' has no parameter 'years'

Calling a query

g.query(name) / g.query(name, #{..}) calls the query at the start of a traversal, on g; it works anywhere a script can use g (loops, functions, the body of another saved query). It is not a step: g.v().query(..) and __.query(..) fail with an error that says so (calling a query on incoming traversers is a later feature).

A traversal result is continued like any other traversal, and the optimizer sees the whole plan: the caller's filters are pushed into the body's steps.

g.define_query(#{name: "everything", body: "fn everything() { g.v() }"})
g.query("everything").has_label("person").count().profile()
// Step                                    Call      In     Out  ...
// v(labels: ["person"]).count()              1       0       4  ...
// Optimizer rules applied: source_filter_pushdown, count_pushdown

A value result is returned as it is:

g.define_query(#{name: "stats", body: `fn stats() {
    #{people: g.v().has_label("person").count().next(), software: g.v().has_label("software").count().next()}
}`})
g.query("stats")
// #{"people": 4, "software": 2}

A call does not recompile an unchanged body: a compiled body is cached per thread, keyed by the stored text, so a redefined query (or one restored by a rollback) always runs its current body, and the plan is made anew on every call (new optimizations apply to old queries).

Saved queries may call each other up to 16 levels deep; a deeper call (usually a query that calls itself without an end) fails with Saved query calls nested deeper than 16 levels.

Queries that read and queries that write

Whether a query may write is decided when it is SAVED, from its body: the engine walks the body's Rhai syntax tree and infers its effects, the data writes its steps can make. A query with no effects is saved in the dialect graphersal-rhai/1 and only reads; a query with effects is saved in graphersal-rhai/2 and may write exactly those. Every save (define_query, define_queries, a replacement, the playground's editor) sets the dialect again, also back to /1 when the body no longer writes; moving or describing a query does not.

g.define_query(#{name: "add_person", params: #{name: "string", age: "integer"},
                 body: "fn add_person(name, age) { g.add_v(\"person\").property(\"name\", name).property(\"age\", age).next() }"})
g.get_query("add_person")["dialect"]
// graphersal-rhai/2
g.get_query("add_person")["effects"].map(|e| e.text)
// "Create Data(vertex \"person\")"
// "Update Data(vertex \"person\")"
g.query("add_person", #{name: "ann", age: 41})
// v[7]

An effect is a request as an authorizer sees it: an action (Create, Update, Delete) on Data, with the element kind and label the chain states before the writing step. The inference follows the same rules as the authorization check of a plan, so the run-time check can hold every write against it:

BodyInferred
add_v("person"), add_e("knows")Create on that label
add_v(label) (a variable)Create on any vertex
g.e().has_label("knows").drop(), out_e("knows").property(..)Delete / Update on knows edges
g.v().has_label("person").property(..)Update on any vertex: a vertex has a label SET, so has_label("person") says nothing about its other labels
a chain from a variable or __ (t.drop(), side_effect(__.property(..)))Delete / Update on any data
merge_v(..) / merge_e(..)Create and Update on the kind
g.query("other")the effects of other, when it writes
g.gql("MATCH (p:person) INSERT (p)-[:owns]->(:pet)")the writes of the lowered GQL query: Create on pet vertices and owns edges
g.gql("MATCH (p:person) SET p.age = 1")Update on any vertex, as for property()
g.gql(text) with a computed text (a variable, a concatenation)Create, Update and Delete on any data: pass values as $parameters to keep a GQL read read-only
a method of the same name on something else (m.drop() on a map)counted as a write

The inference may claim more than a body writes, never less. What it cannot see, it refuses:

  • a body that writes the schema, the catalog or files (set_schema, define_query, create_index, export_graphml, import_graphson, mark, ...) is refused when it is saved: a saved query writes data only;
  • a body that writes and hides what it calls (Fn(..), call, curry, eval, import, or g.query(name) with a computed name) is refused when it is saved. A closure passed to a method (names.for_each(|n| g.add_v(label).property("name", n).iterate())) hides nothing: its writes are inferred like the function's, also when it uses the function's parameters. Without writes such a body is saved as a read-only query, and whatever it reaches stays read-only.
g.define_query(#{name: "q", params: #{n: "string"}, body: "fn q(n) { g.query(n); g.add_v(\"x\").next() }"})
// Error: Invalid body of saved query 'q': it writes data (Create Data(vertex "x")) and uses g.query(name) with a computed name, which hides what it calls, so its effects cannot be inferred; ...

Effects are never stored. They are inferred again when a query is saved, listed or called, so a newer version of Graphersal may infer more or less for the same text; a call always uses the effects inferred now.

A call of a query that writes

  • Invoker rights. The whole effect set is asked of the caller's authorizer before the body runs (Permission denied for 'query("name")' (Delete Data(edge "knows"))), so a denial comes before the first write. The body then runs under the caller's rights restricted to the effects: a write the effects do not cover is denied (it would be a bug of the inference, and the message says so).
  • One unit. The body runs as one transaction: a failing body rolls back everything it wrote, and the commit's ChangeSet carries the query's name and arguments as metadata (saved_query, saved_query_args). Inside a running unit (the playground runs a whole script as one) the call is a savepoint: a later failure of the script rolls it back too. A dry run (eval_value_dry_run) of a call previews its changes; nothing stays.
  • Nesting. A query that writes may call queries that read and queries that write; their effects are part of its own. A read-only query that calls one that writes stays read-only: that call's writes are denied.
  • The result is read-only. What the query returns is used after the call, outside its unit, so it can be continued only by reading; a returned traversal that writes runs INSIDE the call (next section).
g.define_query(#{name: "unfriend", params: #{name: "string"},
                 body: "fn unfriend(name) { g.v().has(\"name\", name).out_e(\"knows\").drop().iterate(); g.v().has(\"name\", name).out(\"knows\").count().next() }"})
g.get_query("unfriend")["effects"].map(|e| e.text)
// "Delete Data(edge \"knows\")"
g.query("unfriend", #{name: "marko"})
// 0

What a query that writes returns

A query that writes may end with the writing traversal itself, without a terminal. The call runs that traversal inside its unit, as if it ended in toList(), and returns a read-only traversal over what it wrote (inject(results) on the caller's graph). The caller continues it like the result of a read-only query:

g.define_query(#{name: "add_person", params: #{p_name: "string"},
                 body: "fn add_person(p_name) { g.add_v(\"person\").property(\"name\", p_name) }"})
g.query("add_person", #{p_name: "Bill"}).count().next()
// 1

Each call writes once, whatever the caller does with the result; the result only reads what was written:

g.query("add_person", #{p_name: "Bill"}).values("name").toList()
// ["Bill"]
g.query("add_person", #{p_name: "Bill"}).id().toList()
// ["7"]
g.v().has("name", "Bill").count().next()
// 1

Without a step after it, the result is shown like any traversal (in the playground and the CLI: the written elements as a table). The written elements are the stored ones, so the continuation walks the graph from them:

g.define_query(#{name: "befriend", params: #{a: "string", b: "string"},
                 body: "fn befriend(a, b) { g.v().has(\"name\", a).add_e(\"knows\").to(__.v().has(\"name\", b)) }"})
g.query("befriend", #{a: "vadas", b: "peter"}).in_v().values("name").toList()
// ["peter"]

The continuation itself may not write: the call's effects end with the call.

g.query("add_person", #{p_name: "Bill"}).property("age", 30).iterate()
// Error: ... Permission denied for 'property' (Update Data): a saved query is read-only: ...

Write the change into the query, or write in a traversal of your own after the call. The rules in detail:

  • Only the returned traversal is run. A traversal the body ends with a terminal (next(), toList(), iterate()) has already run; its value is returned as a value (fn add(n) { g.add_v("person").property("name", n).next() } returns the vertex v[7], which is no traversal: g.query("add", ..).count() fails with Function not found: count). Return the traversal, or g.v(written) after let written = ...toList();, to let callers continue.
  • Also inside a list or a map: fn pair() { [g.add_v("a"), g.add_v("b")] } writes both and returns two read-only traversals.
  • In the call's unit: a returned traversal that fails rolls back everything the body wrote, and a dry run of the call previews its writes too.
  • The results are kept in memory until the caller reads them, like a toList(): a query that writes millions of elements should end the writing traversal with iterate() and return a count or nothing instead.
  • An anonymous writing traversal (__.add_v("x")) is no query of the graph: returning one fails the call (returned a traversal with a writing step).

Read-only queries

A query of the dialect graphersal-rhai/1 never writes. The call runs under a read-only restriction on top of the host's authorizer: creating, changing or deleting data, the schema, saved queries or files is denied with PermissionDenied (a saved query is read-only) before anything runs, and nested queries inherit it. A traversal ANY query returns carries the restriction too:

g.define_query(#{name: "people", body: "fn people() { g.v().has_label(\"person\") }"})
g.query("people").property("seen", true).toList()
// Error: ... Permission denied for 'property' (Update Data(vertex)): a saved query is read-only: ...

Write in a traversal of your own after the call:

let ids = g.query("people").id().toList();
g.v(ids).property("seen", true).toList();
g.v().has("seen").count().next()
// 4
  • A graph the query builds itself (GraphSource::empty(), __) stays writable; it is not the database.
  • Terminals inside the body (next(), toList()) are allowed: a value-returning query needs them.
  • Nothing built from a query result is mutating (is_mutating() is false); whether a script that calls a query that writes changed the graph is what its run reports (mutated).
  • Stored before queries could write. Opening a database never changes a dialect: a graphersal-rhai/1 query whose body has writing steps (saved by 0.2.0, or through the Rust API or a catalog file, which keep the dialect as given) stays read-only and its writes are denied; g.queries() lists them as denied_writes. Saving the query again makes it one that writes.

Unavailable queries and older versions

A query that cannot run is listed with status: "error" and the reason, and a call fails with Invalid body of saved query: its body does not compile (after an upgrade of the language, or stored through the Rust API), it is a graphersal-rhai/2 query whose effects cannot be inferred, or its dialect is one this version does not know. Such a query never blocks opening a database.

A database written by this version keeps every read-only query in graphersal-rhai/1, so Graphersal 0.2.0 runs them; 0.2.0 lists a query that writes (graphersal-rhai/2) as not runnable ("its dialect is 'graphersal-rhai/2', this version runs 'graphersal-rhai/1'"). A version without saved queries in GQL (0.2.2 and older, or a build without the feature gql) lists a GQL query (graphersal-gql/1, graphersal-gql/2) the same way, keeps it unchanged and writes it back byte for byte; so does this version with a dialect of a newer one (graphersal-gql/3).

Saved queries in GQL

With language: "gql" the body is one GQL query, written as it is, with no g.gql(..) around it and no quotes to escape; $name reads the parameter name:

g.define_query(#{
    name: "older",
    language: "gql",
    params: #{min: #{schema: #{type: "integer"}, default: 30}},
    body: "MATCH (p:person) WHERE p.age > $min RETURN p.name AS name, p.age AS age ORDER BY age"
})
g.query("older").toList()
// [#{"age": 32, "name": "josh"}, #{"age": 35, "name": "peter"}]
g.query("older", #{min: 26}).select("name").toList()
// ["vadas", "marko", "josh", "peter"]
  • Defining checks the query before anything is stored: it parses, binds and plans like a g.gql() call (a GQL error keeps its GQLSTATUS, the caret under the offending text and its Help:, with the line in saved query: "name"), every $name it reads is declared in params and every declared parameter is read. The parameters are stored in the order the query first reads them. The other keys (folder, description, meta) are those of a Rhai query; a GQL body has no doc comment, so description has no default.
  • Calling is the same g.query(name, #{..}) with the same argument checks; the call runs the query like g.gql(body, args) (no Rhai is evaluated) and returns its rows, one map per row, a traversal Gremlin steps may continue (select("name") above).
  • Reads and writes: the dialect comes from the query's plan, graphersal-gql/1 when it writes nothing and graphersal-gql/2 when it writes (INSERT / CREATE, SET, REMOVE, DELETE, MERGE); its effects are the writes of the plan, exact per label (a SET on a node is Update Data(vertex), as for property()). A call is authorized and limited exactly like a Rhai query of the same kind: a read-only query (and any query called from one) cannot write, also not through its result; a query that writes asks its whole effect set of the caller's authorizer first and runs as ONE transaction whose commit names the query and its arguments, then returns a read-only traversal over the rows it produced:
g.define_query(#{
    name: "hire",
    language: "gql",
    params: #{name: "string", company: "string"},
    body: "MATCH (c:software {name: $company}) INSERT (p:person {name: $name})-[:created]->(c) RETURN p.name AS name"
})
g.get_query("hire")["effects"].map(|e| e.text)
// ["Create Data(vertex \"person\")", "Create Data(edge \"created\")"]
g.query("hire", #{name: "ann", company: "lop"}).toList()
// [#{"name": "ann"}]
g.define_query(#{
    name: "birthday",
    language: "gql",
    params: #{name: "string"},
    body: "MATCH (p:person {name: $name}) SET p.age = p.age + 1 RETURN p.age AS age"
})
g.get_query("birthday")["effects"].map(|e| e.text)
// ["Update Data(vertex)"]
  • A Rhai query may call a GQL query (g.query("hire", #{..}) in its body); its effects then include those of the GQL query, as with any called query. A GQL query calls one with CALL folder.name(args) (Calling saved queries from GQL).
  • get_query and queries() show language: "gql" and the dialect; the body is the query text.
  • g.define_queries(folder, source) stays Rhai only: define GQL queries one by one.
  • Every front end below works with GQL queries: the playground's editor has a Rhai / GQL switch, MCP and Python list them with their language and call them like any other.

Calling saved queries from GQL

A GQL query calls a saved query written in GQL with CALL folder.name(args), the procedure call of GQL and Cypher: the segments before the name are the query's folder (joined by /, so CALL people.older() calls older of the folder people, and CALL older() one of the root folder), the arguments are its parameters in order, and YIELD names the columns of its RETURN that the query reads after the call:

g.define_query(#{
    name: "older",
    folder: "people",
    language: "gql",
    params: #{min: #{schema: #{type: "integer"}, default: 30}},
    body: "MATCH (p:person) WHERE p.age > $min RETURN p.name AS name, p.age AS age"
});
g.gql("CALL people.older(26) YIELD name RETURN name ORDER BY name").to_list();
// [#{"name": "josh"}, #{"name": "marko"}, #{"name": "peter"}, #{"name": "vadas"}]
g.gql("CALL people.older(26) YIELD name AS who, age WHERE age < 35 RETURN who ORDER BY who").to_list();
// [#{"who": "josh"}, #{"who": "marko"}, #{"who": "vadas"}]
g.gql("CALL people.older(26) YIELD age RETURN count(age) AS n, max(age) AS oldest").to_list();
// [#{"n": 4, "oldest": 35}]
g.gql("MATCH (s:software) CALL people.older($min) YIELD name RETURN s.name AS sw, name ORDER BY sw, name", #{min: 33}).to_list();
// [#{"name": "peter", "sw": "lop"}, #{"name": "peter", "sw": "ripple"}]: the call runs once per row
  • Arguments are constants or the caller's $parameters (also lists, maps and arithmetic of them), evaluated once when the query is compiled; an argument that reads the row (CALL people.older(s.age)) is not supported yet. They bind the saved query's parameters in the order its query first reads them (g.get_query(name)["params"] lists that order): a query RETURN $a AS a, $b AS b takes a first. Trailing parameters left out take their defaults (CALL people.older() is min: 30). Each argument is checked against its parameter's schema like an argument of g.query(..), with its write coercion (an integer for a number parameter arrives as a float: 42 becomes 42.0); a value that does not fit is an error before the run.
  • YIELD names columns of the saved query's RETURN: YIELD a AS x renames one, every yielded name must be new in the query, and YIELD .. WHERE <condition> filters the rows. Inside a query a call of a saved query that returns columns needs YIELD.
  • Standalone: a call that is the whole query returns every column of the saved query, in its order, with no YIELD or with YIELD *; without parentheses it reads its arguments from the query's parameters of the same names (a missing one takes its default):
g.define_query(#{
    name: "older",
    folder: "people",
    language: "gql",
    params: #{min: #{schema: #{type: "integer"}, default: 30}},
    body: "MATCH (p:person) WHERE p.age > $min RETURN p.name AS name, p.age AS age"
});
g.gql("CALL people.older()").to_list();
// [#{"age": 32, "name": "josh"}, #{"age": 35, "name": "peter"}]
g.gql("CALL people.older YIELD *", #{min: 33}).to_list();
// [#{"age": 35, "name": "peter"}]
  • VOID: a saved query without RETURN (one that ends in a write or in FINISH) returns no columns. Called alone it returns no rows; inside a query it runs once per row and keeps each row once, so the query goes on after it. A saved query that writes is called like any other; its writes are part of the calling query, which is ONE unit (a failure anywhere leaves nothing):
g.define_query(#{
    name: "hire",
    folder: "staff",
    language: "gql",
    params: #{name: "string"},
    body: "MATCH (c:software {name: 'lop'}) INSERT (:person {name: $name})-[:created]->(c)"
});
g.gql("CALL staff.hire('ann')").to_list();   // [] (VOID), and ann is created
g.gql("FOR n IN ['bob', 'cy'] CALL staff.hire('temp') RETURN n").to_list();
// [#{"n": "bob"}, #{"n": "cy"}]: two persons named temp, one per row
g.gql("FOR n IN ['bob', 'cy'] CALL staff.hire('tmp')").to_list();
// []: like a last clause that writes, a VOID call may end the query (zero rows)
  • Yielded nodes and edges keep their properties and labels, and a later pattern may start at one (CALL sw() YIELD s MATCH (s)-->(x) ..); the kind is checked when a row reaches the pattern: NULL gives no row, any other value that is not a node (or edge) is 22G03.

  • A body that is only a call without parentheses (body: "CALL people.older") reads the called query's parameters by name: declare them in the calling query's params.

  • Effects are transitive: a saved GQL query that calls another is checked against the catalog when it is saved (the called query must exist, its arguments fit), and its dialect and effects include those of the queries it calls. A query that only reads but calls one that writes is saved as a query that writes (graphersal-gql/2):

g.define_query(#{
    name: "hire",
    folder: "staff",
    language: "gql",
    params: #{name: "string"},
    body: "MATCH (c:software {name: 'lop'}) INSERT (:person {name: $name})-[:created]->(c)"
});
g.define_query(#{
    name: "onboard",
    folder: "staff",
    language: "gql",
    body: "CALL staff.hire('dan') RETURN 'dan' AS hired"
});
g.get_query("onboard")["dialect"];   // "graphersal-gql/2"
g.get_query("onboard")["effects"].map(|e| e.text);
// ["Create Data(vertex \"person\")", "Create Data(edge \"created\")"]
g.gql("CALL staff.onboard()").to_list();   // [#{"hired": "dan"}]

A call is checked again when the calling query runs: a read-only saved query (graphersal-gql/1) whose plan would write through a call (the called query was changed since) is refused, so no read-only query ever writes.

  • Permissions: a call asks Execute on Definition(query "name"), like g.query(..), and every read and write of the called query is asked of the caller's authorizer, as part of the calling query; under AccessPolicy::read_only() a call of a saved query that writes is denied before anything runs (Permissions).
  • One unit, no commit attribute: unlike g.query(..) of a query that writes, which commits as a unit of its own that names the query and its arguments, a GQL call is part of the calling query's unit, and its commit names no saved query.
  • Only GQL bodies: a saved query written in Rhai cannot be called from GQL in this version (0A000, the help names g.query(name, #{..})); call it with g.query(..) from the DSL, or save it again in GQL. Calls nest at most 16 levels deep (and one query resolves at most 1024 calls in all, 54001); a saved query that calls itself, directly or through others, is an error (42002), since its arguments are constants and the recursion would never end.
  • Names: saved-query names are unique across all folders, so a name found in another folder than the call names gets a "did you mean": CALL older() answers did you mean: CALL people.older. Names are case-sensitive; a folder segment with other characters is back-quoted (CALL `my reports`.top()). The vendor namespaces db, dbms, apoc and gds stay refused (CALL db.labels()).

The errors point at the call:

g.gql("CALL people.older()")   // error: there is no saved query `older` in the folder `people` (42002)
g.gql("CALL db.labels()")   // refused: the vendor procedures of db, dbms, apoc and gds (0A000)
Error: GQL semantic error at line 1, column 22: too many arguments: people.older(min :: integer) takes 1 argument, 2 given ...
Error: GQL data exception at line 1, column 19: the argument for `min` of CALL people.older must be integer: Type mismatch on query 'older.min': expected int64, got string ...
Error: GQL semantic error at line 1, column 25: CALL people.older inside a query names the columns it reads with YIELD: the saved query returns `name`, `age` ...
Help: add YIELD, as in CALL people.older(..) YIELD name, age. CALL folder.name(args) runs the saved query `name` of the catalog folder `folder` ...
Error: GQL construct not supported yet at line 1, column 38: an argument of CALL people.older that reads the row is not yet supported (the variable s is not defined) ...
Help: pass a constant or a $parameter, or write the saved query's pattern in the query itself. CALL folder.name(args) runs ...
Error: GQL construct not supported yet at line 1, column 6: the saved query `rh` is written in Rhai; CALL runs saved queries written in GQL in this version ...
Help: run it from the DSL with g.query("rh", #{..}), or save it again in GQL (language: "gql"). CALL folder.name(args) runs ...

The GQL error reference lists every error of a call.

Errors name the query

An error inside a body keeps its diagnostic and gains one line per call, innermost first:

g.define_query(#{name: "broken", body: "fn broken() { g.v().values(\"name\").as_number(GType.LONG).toList() }"})
g.query("broken")
// Error: Step #2 'as_number(GType.LONG)' execution failed
//   at #2: v().values("name").as_number(GType.LONG)
// ...
// Caused by: Cast exception: expected type [int64], got type 'string'
//   value:  "marko"
//   origin: vertex id="1" label="person" property="name"
//   in saved query: "broken" (line 1, position 58 of its body)
// Help: ...

A missing query, a body that no longer compiles and a call at the wrong position fail with errors naming the query and a Help: line with the fix.

Managing queries

CallResult
g.queries()every saved query as a list of maps, by name
g.queries("reports")the queries in reports and the folders below it (reports/sales, not reportsx)
g.get_query(name) / getQueryone query as a map, () when there is none
g.drop_query(name) / dropQueryremoves it; false when there was none
g.move_query(name, folder) / moveQuerymoves it ("" or (): the root)
g.describe_query(name, text) / describeQuerysets the description ("" or () removes it)

An entry of queries() has name, folder and description (() when absent), params (a list in signature order: #{name, schema, default?, required}), status: "ok", or "error" with error, the reason the query cannot run (see Unavailable queries), writes (a call may write), effects (what it may write) and denied_writes (the writes of a read-only query's body that a call denies), each effect #{action, element, label, text} (element / label () when open), language ("rhai" or "gql") and dialect. get_query adds body and meta.

g.define_query(#{name: "older_than", folder: "reports/people", params: #{age: #{schema: #{type: "integer"}, default: 30}},
                 body: "fn older_than(age) { g.v().has(\"age\", P.gt(age)) }"})
g.queries("reports")
// [#{"denied_writes": [], "description": (), "dialect": "graphersal-rhai/1", "effects": [], "folder": "reports/people", "language": "rhai", "name": "older_than", "params": [#{"default": 30, "name": "age", "required": false, "schema": #{"type": "integer"}}], "status": "ok", "writes": false}]

Moving a query or renaming a folder never breaks a caller: a call uses the name only. Dropping a query that others call is allowed (dependencies are not tracked); the callers fail when they call it.

Every change of the catalog (define, replace, move, describe, drop) is a database change like a schema change: one unit of its own, or a savepoint inside a running unit (the playground runs a script as one unit, so a script that fails leaves no definition behind), rolled back with it, visible to commit hooks as a SetDefinition mutation (see Transactions).

Permissions

Calling a query asks Execute on Definition(query "name") before the body runs; a query that writes then asks its whole effect set; the body's own reads and writes are then asked as usual. Listing asks Read, defining Create (Update to replace, move or describe), dropping Delete. AccessPolicy::read_only() allows calling and listing, so under it a query that writes is denied before it writes anything. A GQL CALL folder.name(..) asks the same Execute, and the called query's reads and writes are asked as part of the calling query (Calling saved queries from GQL). See Permissions.

Limits

WhatLimit
name1 to 128 bytes, [A-Za-z_][A-Za-z0-9_]*, not a Rhai keyword
folderat most 255 bytes and 8 segments
descriptionat most 4 KiB
body (source)at most 64 KiB
parametersat most 64 per query
definitionsat most 10 000 per database
call depth16

Persistence

The catalog is part of the database: a Store keeps it in its snapshots and journal, losslessly (every catalog change is a durable commit; recovery, rollback, forks and backups carry it), and a packed snapshot (.gsnap) carries it too. A query is stored as its source text (the Rhai function or the GQL query), never as a compiled plan: every call plans anew. GraphML and GraphSON carry no saved queries, like they carry no schema. The byte layout is in the format spec (sections 6.3, 9.3 and 16).

Front ends

  • Playground (WebAssembly and the dev server alike): the Catalog ▾ ▸ Saved queries manager lists the queries by folder with a badge each (R/O reads, R/W writes, its tooltip lists the effects; R/O ⚠ read-only with writing steps that a call denies; unavailable with the reason), creates and edits them in an editor with a parameter list and the body in the code editor, deletes them, and runs one from a form built from its parameter schemas, which writes the g.query(..) call into a query tab. Running an R/W query shows a preview of what the call would change first (a dry run, rolled back) and asks. The editor's Rhai / GQL switch picks the language: a GQL query is edited with GQL highlighting as the whole query text (+ Add $parameters of the query declares the $names it reads), and the list shows a Rhai or GQL badge per query. Save as query… in a query tab's ⋯ menu opens the editor on the tab's text: a tab holding one g.gql(`...`) call becomes a GQL query of its inner text, with every $name as a parameter (typed and defaulted by the values the tab passes in #{..}); any other tab becomes a Rhai query whose body is the tab's text. Saved queries travel in the catalog file with the other definitions (Catalog ▾ ▸ Save catalog, Load catalog), like the schema. See Web Playground.
  • MCP (the dev server with --mcp): an AI agent lists them with list_saved_queries, runs one with run_saved_query, reads graphersal://saved-queries, and is told to look for a saved query before writing a new one and to run one with writes: true only when the user asked for that change; --mcp-query-tools also offers each query as a tool of its own (readOnlyHint / destructiveHint from its effects). The listing carries each query's language (rhai or gql) and dialect; a GQL query runs the same way and answers rows like the gql tool. MCP has no tool that defines queries: the user does that (playground, Python, a script), or the agent through the query tool with g.define_query(#{..}). With --mcp-read-only the queries that write are neither listed nor run. The AI Chat runs a query that writes only after the user confirmed it in the chat.
  • Python: graph.queries(folder), graph.get_query(name), graph.define_query(spec), graph.drop_query(name) and graph.call_query(name, params) (graph.query stays the alias of execute); graph.define_query({"name": .., "language": "gql", "body": "MATCH ..", "params": {..}}) stores a GQL query, whose call returns its rows as dicts.
  • CLI: the DSL calls (graphersal -e 'g.queries()', g.define_query(#{.., language: "gql", ..})); graphersal store info <dir> prints how many definitions a Store's catalog holds.

In the playground, Catalog ▾ ▸ Saved queries lists the queries by folder:

The saved queries manager: queries by folder, with Run, Edit and Delete

Edit… opens the editor: name, folder, description, every parameter with its type, default and constraints, and the body in the code editor:

The saved query editor: parameters with type, default and minimum, and the body

Run… builds a form from the parameter schemas; Run writes the g.query(..) call into a query tab and runs it there:

The run form of a saved query with one integer parameter

In Rust

The catalog is reachable without the DSL: GraphTraversalSource::list_definitions, get_definition, define_query(name, QueryDefinition), remove_definition, move_query, describe_query (module graphersal::catalog). The Rust API stores a body without compiling it (the core has no Rhai) and keeps the dialect as given (QUERY_DIALECT by default, WRITING_QUERY_DIALECT for a query that writes); the DSL compiles it on definition and on every call. A front end that builds definitions itself runs them through graphersal::script::with_inferred_dialect (the body checked like define_query checks it, the dialect set from the effects) and lists them with graphersal::script::saved_query_effects.

Host-defined catalog kinds

Saved queries are one kind of catalog definition; property indexes and compression rules are others. An application built on the library (a server, say) can keep its own entities in the same catalog, so they are stored, journaled, rolled back, forked and backed up with the graph: definition kinds 128 to 255 are reserved for hosts and never assigned by the library (DefinitionKind::host(n) refuses a kind below 128; DefinitionKind::HOST_FIRST/HOST_LAST, is_host()). Kind 2 is the library's property index.

use graphersal::catalog::{decode_payload, encode_payload};
use graphersal::catalog::{Definition, DefinitionFlags, DefinitionKind};

let kind = DefinitionKind::host(200).unwrap();
let bytes = encode_payload(&payload)?; // a property map, the codec of the library's own kinds
graph.set_definition(Definition::opaque(kind, DefinitionFlags::NONE, "person_name", bytes))?;
let back = decode_payload(graph.definition(kind, "person_name").unwrap().opaque_payload().unwrap())?;

The library keeps a host definition as opaque bytes: it checks only the name (1 to 1024 bytes) and the payload size, writes the bytes back unchanged everywhere, and never reports them as damage. encode_payload/decode_payload (feature persist) are optional, but they keep the payload a property map like every library kind (decoding is safe on hostile input). The critical flag means what it means for any kind the library does not decode: a store holding a critical host definition opens read-only, and a Store refuses to write one. The byte rules are in the format spec (sections 6.3 and 16).

Property Indexes

g.v().has_label("person").has("title", "CEO") reads every person vertex and compares its title. On a large graph that dominates the query time even when only a few vertices match. A property index orders the elements of one label by the value of one property, so the same query reads only the matching vertices.

// Declare: the `person` vertices, ordered by `age`.
g.create_index(#{label: "person", key: "age"});

// Served: equality, P.within and ranges on `age` after has_label("person").
g.v().has_label("person").has("age", 29).values("name").to_list();
g.v().has_label("person").has("age", P.between(30, 40)).values("name").to_list();

g.indexes()                                  // the indexes and what they hold

Without label an index is label-less: it holds every vertex (or edge) and also serves g.v().has("name", "josh") without a label. With transform: "each" an index holds every element of a list value, so "all nodes of one owner", g.v().has("_owners", __.unfold().is(o)), reads it. With unique: true an index is a unique constraint: a write that would repeat one of its values fails.

Indexes are declared, never automatic: nothing is indexed until you ask for it, and an index costs memory and a little time on every write of its key (below).

Declare, list, drop

DSLRust (GraphTraversalSource)Python (Graph)
g.create_index(#{key, label?, element?, name?, type?, transform?, unique?}) / g.create_index(..)create_index(name, PropertyIndexDefinition::new(kind, label, key)) (label-less: PropertyIndexDefinition::label_less(kind, key)), .with_type(PropertyIndexType::MemoryOrdered), .with_transform(Some(PropertyIndexTransform::ToLower)) (Each; a chain: PropertyIndexTransform::from_names(["each", "to_lower"])), .with_unique(true)graph.create_index(label, key, element="vertex", name=None, type="memory-ordered", transform=None, unique=False) (label=None: label-less; transform="each", transform=["each", "to_lower"])
g.indexes()list_indexes()graph.indexes()
g.drop_index(name)drop_index(name)graph.drop_index(name)
  • element is "vertex" (the default) or "edge"; label is one vertex or edge label (it need not exist yet), or omitted (()) for a label-less index; key is one top-level property name (a plain name, not a jpath: nested values are not indexed).
  • name defaults to <label>_<key> (<key> for a label-less index), then _edge for an edge index, then _to_lower for an index with the transform to_lower (person_name_to_lower, knows_note_edge_to_lower), _each or _each_to_lower for the each transforms (index__owners_each for a label-less index on _owners), with every character that is not a letter, a digit or _ replaced by _, and index_ in front when it would not start with a letter. It is an identifier like a saved query's name. The DSL, the session, the dev server, MCP and Python use this default; the playground's form shows it as the name's placeholder and follows the Transform choice until a name is typed.
  • type is the index type, "memory-ordered" by default (the only type this version knows).
  • transform is the transform of the index keys: absent (the default) for the values themselves, "to_lower" for case-insensitive search, "each" for the elements of a list, or a chain written as an array of names applied in order: ["each", "to_lower"] (the only chain this version serves; ["to_lower", "each"] is refused).
  • unique (false by default) makes the index a unique constraint; it does not change the default name.
  • One index per (element, label, key, type, transform): a second one under another name fails with a Conflicting property index error that names the first. A plain index and a to_lower index on the same key coexist (their default names differ), and so do a label-less and a per-label index on one key. Declaring the same name again replaces the index (also a per-label index by a label-less one of the same name, and back: index names are one namespace). unique is not part of that identity: to make an index unique, declare it again under its name with unique: true.
  • g.indexes() lists each index (by name) with its label (() for a label-less index), its type, its transform (() without one, a chain as the array of its names), unique, served (whether it is served, with a reason when it is not: see unknown types, repeated values under a unique index and other storages) and its current entries (indexed elements; with each one per distinct element of a list), distinct_values, skipped (elements whose non-null value the index does not hold; with each list elements it does not hold) and bytes (an estimate of its memory).
g.create_index(#{element: "edge", label: "knows", key: "weight"});
g.e().has_label("knows").has("weight", P.gt(0.6)).count().next()

Label-less indexes

An index declared without label holds every element of its kind, unlabeled ones included (a vertex with several labels once):

g.create_index(#{key: "name"});                        // named `name`
g.create_index(#{element: "edge", key: "weight"});     // named `weight_edge`

g.v().has("name", "josh").values("age").to_list();     // no label: reads the index
g.v().has("name", "josh").count().next();              // counted from the index
g.e().has("weight", P.gt(0.5)).count().next()
  • A v()/e() without labels reads it for the same conditions a per-label index serves (below), and so does a MATCH (n {name: $x}) node pattern without a label in GQL (the root scan and a correlated lookup).
  • A source with labels reads it when no per-label index covers its labels, or when it is cheaper by the index statistics (an equality reads about entries / distinct_values of the label-less index, against the sum over the per-label indexes; a tie keeps the per-label ones); the source then keeps only the candidates carrying one of its labels.
  • .profile() names it with any label, also under a labelled source: v(labels: ["person"]).has("name", "josh") [index: vertex name, any label], and with a transform [index: vertex name to_lower, any label].
  • It costs the memory of every element of the kind holding the key; a per-label index on the same key keeps its entries a second time (the advisor points this out).
  • Persistence: it is stored as catalog kind property_index_ext (6) with the critical flag (plain per-label indexes stay kind property_index), so a version that does not know it (0.5.x and older) opens such a store read-only instead of writing it without maintaining the index. The schema check looks at every label of its element kind that declares the key.

Counting from an index

A count() right after a start step whose one condition an index answers exactly is counted from the index without visiting the elements: one equality (a folded has(key, value), has(key, P.eq(..)), the each point has(key, __.unfold().is(..)) or a to_lower point) with a string, boolean, uuid or temporal value, no other condition, and either a label-less index under a start without labels or the index of the start's one label. .profile() shows [count from index]:

v().has("name", "josh").count() [index: vertex name, any label, exact] [count from index]
v().has("_owners", __.unfold().is(P.eq("o1"))).count() [index: vertex _owners each, any label, exact] [count from index]

A number (ranged by its float64 value), null, a range, P.within, a second condition, a label to check or a whole-value condition read from an each index (a superset) falls back to counting the candidates of the index read.

Index types

Every index has a type (the key type): how it keeps its entries, which values it holds and which conditions it serves. This version knows one type, and it is the default:

TypeWhat it isServes
memory-orderedan ordered index kept in memory; its entries are derived from the data and rebuilt whenever the graph is loaded (below)equality, P.within and the ranges (below)

Which value types an index holds (Rust: PropertyIndexType::holds for the type, PropertyIndexTransform::accepts for the transform, both combined by PropertyIndexDefinition::holds, the one place the engine and the front ends take it from):

Value typememory-orderedwith to_lowerwith eachwith ["each", "to_lower"]
null, booleanyesnoyesno
int64, float64yes (ranged by their value as float64)noyesno
string (also a compressed one, by its text)yesyes, by its lowered textyesyes, by its lowered text
uuidyesnoyesno
date, localdatetime, datetime, time, durationyesnoyesno
array (a list)nonoby its elements (the scalar ones, each once)by its string elements, lowered
object (a map)nononono
vectorno (vectors are searched with nearest() and similarity())nonono

A value the index does not hold is skipped: the element is not in the index, and a condition on such a value is answered by a scan, so results never change.

g.create_index(#{label: "person", key: "age", type: "memory-ordered"})   // the default, spelled out
g.create_index(#{label: "person", key: "age", type: "hash"})   // refused: not a type this version knows

Checked against the schema when created

When the graph's stored schema declares the key at the top level of the index's label (a vertex label for a vertex index, an edge label for an edge index) and none of the declared types, null aside, can be held by the index (for the type a vector, a list, a map, or an anyOf of only such; with the transform to_lower every type but string; with each a map, a vector, or a list whose items declare only such; with ["each", "to_lower"] anything but a string or a list of strings), creating the index is refused, with a message that names the label, the key, the declared type and the index type:

// refused: the schema declares `embedding` as a vector
{
  g.set_schema(#{mode: "open", vertices: #{doc: #{schema: #{type: "object", properties: #{
    embedding: #{type: "array", format: "vector", element: "f32"}}}}}});
  g.create_index(#{label: "doc", key: "embedding"})
}
Error: Cannot create a property index on vertex 'doc' key 'embedding': the schema declares
'embedding' as vector<f32>, and an index of type 'memory-ordered' holds none of its values
Help: Vectors are not index keys: search them with nearest() or similarity() (an exact search,
book page "Vectors"), for example g.v().has_label("doc").nearest("embedding", query, 10) for the
10 closest; a vector index type is planned. ...

With to_lower the message says an index of type 'memory-ordered' with the transform 'to_lower' holds none of its values, and the help suggests a plain index or a string property. For a list or a map the help suggests indexing a scalar top-level property instead (an index key is one top-level name; nested fields are not indexed), and for a list the each transform. A list whose items declare no type is fine for each. A declaration with at least one type the index holds (anyOf of a list and a string, ["string", "null"]), a key the schema does not declare, a label it does not declare, and a graph without a schema are all accepted. The schema's mode does not matter (a declaration in mode none counts too). The playground's form shows the refusal under its Key field.

The check runs when an index is created (the DSL, GraphTraversalSource::create_index, Python, the playground, the dev server and MCP), never when a definition is stored as it is: set_definition, apply_change_set, a replay or recovery, a catalog file or a snapshot load keep what they carry. A later schema change never drops an index: an index whose key the schema later declares as a vector stays and simply holds nothing of it.

An index type from a newer version

A store (or a catalog file, a change set) written by a newer Graphersal may hold an index of a type this version does not know. Such a definition is never damage: it is kept in the catalog exactly as read and written back unchanged (its payload byte for byte through the journal, checkpoints, backups, forks and snapshots), but it is not served: no entries are built, the optimizer never reads it, and g.indexes() (and the playground, the dev server and MCP's list_indexes) shows it with served: false and a reason such as index type 'x' is not known to this version. It can be dropped like any index. Creating or redefining an index of an unknown type is refused with an error whose help lists the known types. Indexes of different types may cover the same (element, label, key). A transform this version does not know is handled the same way: kept byte for byte, built and served never, listed with the reason index transform 'x' is not known to this version, refused when created (the field transform). So is an element kind other than vertex and edge (since 0.2.1; g.indexes() shows the name as read, the reason element kind 'x' is not known to this version, refused when created with the field element).

An index can carry a transform (the key transform): its keys are then the transformed values, and it serves a condition that applies the same transform before comparing. This version knows one transform, to_lower, named after the step to_lower(): the index key is the lowered text of a string value, computed by exactly the function the step uses (Rust's str::to_lowercase: Unicode, no locale), so the index and the scan never disagree. The query form is TinkerPop's has(key, traversal): has("name", __.to_lower().is(x)) keeps the elements whose lowered name is x.

g.v("1").property("name", "MARKO").iterate();
g.create_index(#{label: "person", key: "name", transform: "to_lower"});   // person_name_to_lower

// Served: the lowered value against the constants, equality, P.within and the ranges.
g.v().has_label("person").has("name", __.to_lower().is("marko")).values("name").to_list();
g.v().has_label("person").has("name", __.to_lower().is(P.within("josh", "vadas"))).count().next();
g.v().has_label("person").has("name", __.to_lower().is(P.gte("p"))).values("name").to_list();

// The constant is compared AS GIVEN with the lowered value: write it in lower case.
g.v().has_label("person").has("name", __.to_lower().is("Marko")).count().next()   // 0

What is served and what is not:

  • Served: v()/e() with a folded has_label(..) (every label with a to_lower index on the key), followed in the run of pure filters by has(key, __.to_lower().is(P)) with P a value, P.eq, P.within or a range (P.gt/gte/lt/lte/between/inside/outside). .profile() shows [index: vertex person.name to_lower] on the start step; for a range the has step stays in the plan and re-checks every candidate, a point (a value, P.eq, P.within) is answered exactly in a query that does not write: the has step leaves the plan, v(labels: ["person"]).has("name", __.to_lower().is(P.eq("marko"))) [index: vertex person.name to_lower, exact].
  • Not served (a scan, the same result): any other child (__.is("x") without to_lower(), __.to_upper(), __.to_lower(Scope.local), more steps after is(..), P.neq, text predicates), where(__.values("name").to_lower().is(..)), a jpath key, a source without has_label. The constant is never lowered for you: is("Marko") matches nothing.
  • Only strings are in the index; null and a missing key are not. Because to_lower() fails on any other value (an int64 name, a list), such a value must make the query fail as the scan does: while the index has skipped a non-null, non-string value (g.indexes() shows skipped), queries do not read it and scan, with the step's error. Remove or convert those values and the index is served again.
  • A plain index and a to_lower index on the same key coexist: has("name", "Marko") reads the plain one, has("name", __.to_lower().is("marko")) the lowered one. A to_lower index never serves a plain has("name", "marko").
  • Creating one on a key the schema declares as a non-string type only (an integer) is refused with a message naming the transform; a union with string is fine (below).
  • An unknown transform (written by a newer version) is kept byte for byte and listed as not served (below).

Arrays: the each transform

A list value is one value (Graphersal has no multi-properties): has("_owners", "o1") compares the whole list, and "the elements whose list holds o1" is written with TinkerPop's has(key, traversal): has("_owners", __.unfold().is("o1")). An index with the transform each holds one entry per element of a list value, so that query reads it instead of every element:

g.v("1").property("_owners", ["o1", "o2"]).iterate();
g.v("2").property("_owners", ["o2"]).iterate();
g.v("4").property("_owners", "o1").iterate();                  // a scalar: one entry
g.create_index(#{key: "_owners", transform: "each"});           // named index__owners_each

g.v().has("_owners", __.unfold().is("o1")).values("name").to_list();
g.v().has_label("person").has("_owners", __.unfold().is(P.within("o1", "o2"))).count().next();
g.v().has("_owners", "o1").values("name").to_list()           // the whole value: josh only
  • Entries: one per element of a list, an element held twice once (["x", "x"] is one entry); a scalar value gives its one entry, as unfold() emits it; an empty list none. A nested list, a map or a vector inside the list is not a key and counts in skipped (one per such element), and so does a map or a vector value itself.
  • Served exactly: has(key, __.unfold().is(P)) with P a value, P.eq, P.within or a range, whatever the index skipped: what unfold() emits for a skipped value (a nested list, the entries of a map, a vector) never equals or ranges with a scalar constant. For a point of a string, boolean, uuid or temporal value (P.within of such values too) the has step leaves the plan and the start shows it: v().has("_owners", __.unfold().is(P.eq("o1"))) [index: vertex _owners each, any label, exact] (per label [index: vertex Method._owners each, exact]; see Kept exact); a range, a number or null keeps the has step, which re-checks.
  • Served as a superset: a condition on the whole value, has(key, value) and has(key, P), reads an each index when no index without a transform covers the key: the lists holding the value are candidates too, and the re-check of the whole value drops them. A plain index on the same key is preferred for those conditions.
  • The chain ["each", "to_lower"] holds the lowered text of every string element and serves has(key, __.unfold().to_lower().is(P)) ([index: vertex tags each to_lower, any label]), like to_lower only while it skipped nothing (a number in a list makes to_lower() fail, and the scan must report it); a point is then answered exactly, like to_lower's. A to_lower transform never serves a null constant (to_lower() passes a null through, the index holds none).
  • Not served: __.unfold().unfold().is(..), __.to_lower().unfold().. (the wrong order), negations and text predicates, GQL's x IN n.list (a gql:filter expression: a right operand that is not a list is an error there, so it scans).
  • A storage lookup returns each element once even when it holds several values of the slice (["a", "b"] in P.between("a", "c"), or 1 and 1.0); a fused count() is answered from an each index only for one exact point (above).
  • Persistence: an index with each is stored as catalog kind property_index_ext (6) with the critical flag, also with a label, so a version that does not know it opens the store read-only. The payload keeps a single transform as its name and a chain as the array of its names ("transform": ["each", "to_lower"]).
  • Memory: about 4 bytes per element entry after a build for a key with few distinct values (an owner).
  • The advisor recommends transform: "each" for a scanned key holding lists.

Unique indexes

With unique: true an index is a constraint: no two elements of the index hold an equal value of its key. A write that would give an element a value the index already holds for another element fails, and the query (or import, or applied change set) rolls back as a whole:

g.create_index(#{label: "person", key: "name", unique: true});
g.v("2").property("name", "marko").iterate()      // vertex 1 holds "marko" already
Error: The unique index 'person_name' already holds "marko" at 'name' for the vertex '1'
  • Scope: a per-label index is unique within its label (person and software may share a name); a label-less one over the whole element kind (every vertex, or every edge); with transform: "to_lower" the comparison is case-insensitive (logins, e-mail addresses: "Ann" and "ann" collide).
  • Equality is has()'s: an int64 and a float64 of the same value collide (1 and 1.0), two int64s only when they are the same number, a datetime by its instant.
  • null is not part of uniqueness: any number of elements may hold null (or lack the key).
  • Values the index does not hold are exempt as well: a list, a map or a vector under a plain unique index, a non-string under to_lower. They count in skipped, as for any index.
  • Every write path is checked: add_v()/add_e() with their properties, property() on an existing element (also a one-segment jpath), merge_v()/merge_e() when they create or change, GQL INSERT, SET and MERGE, add_label() and GQL SET n:Label when they bring a vertex into a per-label unique index, GraphSON and GraphML imports, apply_change_set. Nothing of the failing unit stays.
  • The check is immediate, at each write, never deferred to the commit. Swapping the values of two elements in one query therefore needs an intermediate value:
g.create_index(#{label: "person", key: "name", unique: true});
// Vertex 2 can take "marko" only after vertex 1 has let it go: through "tmp".
g.v("1").property("name", "tmp").v("2").property("name", "marko").v("1").property("name", "vadas").iterate();
g.v("1").values("name").next()
  • A compacted change set may not apply. ChangeSet::compact() keeps only the net effect, so the intermediate value of such a swap is gone: applying the compacted set with apply_change_set gives the first element the value the second still holds, and the unit is refused with a unique violation (nothing applied). Apply the uncompacted change set instead; a journal replay and a recovery always use the uncompacted, ordered writes.
  • A unique index is an ordinary index for queries: equality, P.within and ranges read it, and a point lookup returns at most one element.
  • Not with each: a unique index cannot use the transform each (a list gives one key per element); the create is refused.
  • Persistence: a unique index is stored as catalog kind property_index_ext (6) with the critical flag, also with a label (a version that does not know it opens the store read-only, so it never writes past the constraint). The payload has "unique": true (absent when false). A journal replay and a recovery apply only writes that were checked when they were committed.

Created over repeated values

Creating a unique index over data that already holds a value twice is refused, and nothing is created. The error names up to 10 repeated values, each with its count and up to 3 example ids, and its help gives the query that lists all of them:

Error: Cannot create the unique index 'User_email': 2 value(s) of 'email' are held by more than one vertex labelled 'User': "a@x" (2 elements: 1, 7), "b@x" (3 elements: 2, 8, 9)
Help: ... List every repeated value with its count: g.v().has_label("User").has("email").group_count().by("email").unfold().where(__.select(Column.values).is(P.gt(1))). ...

With to_lower the query groups by the lowered value (.group_count().by(__.values("email").to_lower())). Give the repeated elements other values (or drop the extra ones), then create the index again.

Stored over repeated values

Storing a definition never checks the data (set_definition, a catalog file, a journal replay, a store load). A unique index whose data holds repeated values (a store written past the constraint, an index stored without the create check) is kept, but neither served nor enforced: g.indexes() lists it with served: false and a reason that starts with duplicates: and names the values, the open of a store writes the system journal event index.unique_duplicates (see System Journal), and the open never fails for it. The fix: remove the repeats, then drop the index and create it again (GraphStorage::unique_index_duplicates returns the report to a host).

What is served

A v()/e() start step reads an index when

  • it is the start of the traversal (or of a child traversal), the optimizer folded a has_label(..) into it, and every folded label has an index on the key: the index of has_label("person"), or of has_label("person", "employee") when both labels have one; or a label-less index covers the key (with or without folded labels);
  • and a has() on the indexed key follows directly (only has(), has_label(), has_id(), has_key(), has_not() in between):
ConditionServed
has(key, value)equality
has(key, P.eq(v)), has(key, P.within(a, b, ..))one slice per value
has(key, P.gt/gte/lt/lte(v))one range
has(key, P.between(a, b)), P.inside(a, b)one range
has(key, P.outside(a, b))two ranges
P.neq, P.without, text predicates, P.typeOf, and/or/not compositesnot served (scan)
a value that is a list or a map (has("tags", ["a"]))not served (scan)
has(key, __.unfold().is(P))by an each index
a point (value, P.eq, P.within) of a string, boolean, uuid or temporal value, without a transform or by eachexactly: no re-check (Kept exact)
has(key, value), has(key, P) with only an each index on the keyby it, as a superset (re-checked)
v().has("title", "CEO") without a labelserved by a label-less index only
a jpath keynot served (scan)

With several served conditions the optimizer picks the most selective index from the index statistics (an equality reads about entries / distinct_values elements of each label, a range about half the entries).

Results are the same as without the index, always: the index returns a superset of the matching elements (numbers are ranged by their value as float64, so 29 and 29.0 are both read), and the start step and the has() step still check every condition on each candidate, except the one condition the index answers exactly, which no longer needs it. The comparison is exactly that of has(): has("age", 29) matches an int64 29 only, has("age", P.eq(29.0)) and the ranges compare numbers across int64 and float64, a string never equals a uuid, null equals only null. Dates and times are index keys with the same rules (Comparing and Sorting): each of date, localdatetime, datetime, time and duration is its own kind (a date never equals a datetime or a string, and a range reads only values of its bounds' type), a datetime is keyed by its instant (12:00Z and 14:00+02:00 are one key), and a duration is keyed by all its fields (P1M and P30D are two keys) and ranged by its length, a month as 30 days, ties broken by the fields: equality, P.within and every range on durations are served. Only the order of the elements may differ (the index reads them by value): use order() when the order matters.

A string operand of has(key, P) is always a value, also inside a child traversal and after an as() of the same spelling (only where(P.eq("a")) names a path label), so P.eq("a") is served wherever the start step is.

See it in .profile()

The start step names the index it reads, and the rule property_index is listed:

$ graphersal -e 'g.create_index(#{label: "person", key: "age"})' \
             -e 'g.v().has_label("person").has("age", P.gt(30)).values("name").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(labels: ["person"]) [index: vertex person.age]                1       0       2   55.666µs     7.53
has("age", P.gt(30))                                            1       2       2   42.625µs     5.77
values("name")                                                  1       2       2    1.834µs     0.25
                                                      TOTAL:             execute:  738.958µs    13.55
=====================================================================================================
Optimizer rules applied: source_filter_pushdown, property_index

The range keeps its has step, which re-checks every candidate. A condition the index answers exactly adds , exact inside the brackets: an equality folded into the start step shows as v(labels: ["person"]).has("title", "CEO") [index: vertex person.title, exact] (the start step does not check it again), and a has step it answers leaves the plan and is shown on the start step:

v().has("_owners", __.unfold().is(P.eq("o1"))) [index: vertex _owners each, any label, exact]
out()

To compare with the scan, turn the rule off for one query: g.with("optimizer.disabled", ["property_index"]) (see Property Index Rule).

Kept exact

An index is maintained on every write: adding and dropping elements (a vertex drop takes its edges out of the edge indexes), writing and removing the key (also through a jpath write that changes it), adding and removing a vertex label (a vertex with several labels is in the index of each of them), changing an edge label. A rolled-back unit restores the index with the data; replay, apply_change_set and a store's recovery rebuild it exactly. A string kept compressed is indexed by its text (the index holds the plain text, so indexing a long compressed field costs the memory compression saved).

Because it is kept exact, the index answers some conditions instead of narrowing them: a point (has(key, value), P.eq, P.within) of a string, boolean, uuid or temporal value read from an index without a transform, the same point inside has(key, __.unfold().is(..)) read from an each index, or inside has(key, __.to_lower().is(..)) / has(key, __.unfold().to_lower().is(..)) read from a to_lower / ["each", "to_lower"] index while it skipped nothing (every value is then a string, to_lower() cannot fail, and nothing writes during a reading query), finds exactly the elements the condition accepts, each once. In a query that does not write (no mutating step at any level), the optimizer then drops the re-check of that one condition: a folded equality is not checked again on the candidates, a has step is removed from the plan, and .profile() marks the access exact. Every query form gains, not only count(): .id().to_list(), .values(..), a traversal from the found elements. Everything else is still checked: the other conditions, the labels when a label-less index serves a start with labels, ranges, numbers (a slice spans int64 and float64), null, a whole-value condition read from an each index (a superset), a to_lower index that skipped a value (it is not read at all), and every condition of a query that writes. The index is trusted on purpose: a wrong entry would show in the result instead of being hidden by a re-check, and the randomized differential tests compare every exact shape with the scan. A custom storage opts in with StorageCapabilities::exact_property_index_lookups.

Persistence

An index is a catalog definition (kind property_index, or property_index_ext with the critical flag for a label-less index, a unique index and an index with each, like saved queries and compression rules), so its declaration travels with the graph: the journal (WAL), snapshots, backups, forks, rollbacks and the catalog file. Its entries are never stored: they are rebuilt from the data whenever a graph is loaded, by a store open, a read-only view (also of a past state), a backup open, a recovery, a snapshot load. A read-only view is therefore always consistent with the data it shows. GraphML and GraphSON files carry no catalog, so no index.

Memory

An index keeps each distinct value once (strings longer than 24 bytes on the heap), with about 48 bytes of ordered-map bookkeeping, and the elements holding it as a sorted list of 4-byte element slots: a value held by one element keeps it inline, a value held by many costs about 4 bytes per element after a build and at most about 8 bytes once later writes have grown the list. A key with few distinct values (an owner, a status) is therefore cheap; a near-unique key (a name, a hash) costs about one map entry per element. g.memory_usage() reports the indexes as property_index_bytes (part of total_bytes, so the memory budget sees them), g.indexes() per index. Building an index reads every element of its label once.

Other storages

Indexes are a capability of the storage (StorageCapabilities::property_indexes); the built-in graph has it. On a custom storage without it, create_index fails with unsupported: property indexes; an index definition can still be stored in its catalog (a catalog file loaded into it, say) and is listed with served: false, but no query reads it. A storage that serves indexes implements GraphStorage::property_indexes and the lookups vertices_by_property_index/edges_by_property_index, and for indexes with a transform vertices_by_transformed_property_index/edges_by_transformed_property_index (reporting PropertyIndexStats::skipped, which the optimizer reads before it uses a to_lower index; an each lookup returns each element once, deduplicating an element held under several keys of the slice). The lookups take the label as Option<&str>: None reads the label-less index (PropertyIndexInfo::label is None for one). count_by_property_index (default Ok(None)) answers an exact count from the index for counting from an index; without it the engine counts the lookup's candidates. A storage whose lookups return exactly the matching elements for a point of a string, boolean, uuid or temporal value (an each lookup: the elements whose value is it or a list holding it), never more, claims StorageCapabilities::exact_property_index_lookups; the engine then drops the re-check of such conditions (Kept exact); without it every lookup is treated as a superset (the conformance item exact_property_index_lookups_return_exactly checks a storage that claims it). A storage that serves a unique index lists it with PropertyIndexInfo::unique, refuses every write that would repeat a key with GraphError::UniqueViolation (constructor GraphError::unique_violation) without changing anything, and reports an index stored over repeated values through GraphStorage::unique_index_duplicates instead of serving it (the trait's rustdoc has the contract).

In the playground, the dev server and MCP

  • Playground (WebAssembly and over the dev server): Catalog ▾ ▸ Property indexes lists the indexes with their type, transform, entries, distinct values, elements per value (what an equality reads) and memory (an index that is not served says why), creates one from a form (element, label or any label for a label-less index, key, type, transform: none, to_lower, each or the chain each, to_lower, each with a hint on the query form, a unique box (disabled with each; a unique index carries a unique badge in the list), optional name; the default name is shown as you type and follows the transform; an engine refusal shows under its field) and drops one after a confirmation. The Statistics tab of the Profile panel shows Property indexes with their memory when the graph has some. Indexes travel with the catalog file (Catalog ▾ ▸ Save catalog).
  • Dev server: GET /api/indexes, POST /api/indexes/create {key, label?, element?, name?, type?, transform?, unique?} (label absent or null: label-less; listed with label: null), POST /api/indexes/drop {name} (see the dev server); a create or drop is a commit recorded in the change feed, so open browsers reload. The start block on stderr names the index memory.
  • MCP: the tools list_indexes (also with --mcp-read-only), create_index (with an optional label, omitted for a label-less index, an optional type and transform, enums of the known ones; a chain as the array ["each", "to_lower"], and an optional boolean unique) and drop_index (not offered read-only, where query refuses g.create_index too).

Limits

  • Not indexed: nested values (jpath keys), lists (without each), maps and vectors as values (see index types), labels other than the one declared (an index on person does not serve v().has("title", ..) without has_label; a label-less index does).
  • One index type (memory-ordered): persisted, hash, vector (approximate nearest neighbour) and full-text types are planned and will be additional values of type.
  • Two transforms (to_lower, each) and one chain (["each", "to_lower"]); they serve only the exact children __.to_lower().is(P), __.unfold().is(P) and __.unfold().to_lower().is(P). A to_lower index does not serve a plain has(key, value), and TextP predicates are not served.
  • A unique index checks each write at once (no deferred, commit-time check) and cannot use each; composite (multi-key) unique constraints are not available.
  • order().by(key) does not read the index.

Profiling and execute()

Two terminals tell you how a traversal ran:

  • profile() runs the traversal and returns only its metrics, like TinkerPop's profile().
  • execute() runs it and returns an execution object: the results, the error (as data, never thrown) and, when you ask for it, the metrics of the same run.

Both report the optimized plan, the one that actually ran: fused steps appear under their real names (v(labels: ["person"]).count()). What a step records into traverser paths is the separate path_recording field ("full", "labels(a,b)"); only the table renders it after the name, as [path: ...]. Profiling instruments every step, so a profiled run is slightly slower; its results are identical.

profile()

g.V().hasLabel("person").where(__.out("knows")).profile()

As the final value of a session (the CLI, the REPL, the playground) it renders as the familiar table:

Traversal Metrics
Step                                                                   Call      In     Out       Time    % Dur
===============================================================================================================
v(labels: ["person"])                                                     1       0       4    3.708µs     0.44
where(__.out("knows"))                                                    1       4       1  131.291µs    15.72
  \> out("knows")                                                         4       4       2  128.000µs    15.33
     [min: 41ns, avg: 32.000µs, max: 127.542µs]
                                                                TOTAL:             execute:  835.000µs    16.17
===============================================================================================================
Optimizer rules applied: source_filter_pushdown

The Step column is as wide as the longest step text, annotations such as [index: ..] and [path: ..] included (at least 60 characters, 70 with nested steps); only a step text longer than 160 characters is cut with ....

In a script it is data, a TraversalMetrics value:

let p = g.V().hasLabel("person").out("knows").profile();
p.duration_ns                       // the whole run, integer nanoseconds
p.metrics[0].name                   // "v(labels: [\"person\"])"
p.metrics[1].counts.traverser_count // 2
p.optimizer_rules_applied           // ["source_filter_pushdown"]
p.to_map()                          // the whole tree as a map
p.to_json()                         // ... as compact JSON text
p.to_table()                        // the text table above

profile(ProfileType.Memory) (also ProfileType::Memory, and profile_with(..)) adds a memory section to every step; see Memory Inspection and Profiling.

Every profile also carries the memory of the whole query against its per-query limit traversal.max_materialized_bytes: the PEAK of the live bytes the query held at once (memory a step frees is given back; see Resource Limits). In Rust it is TraversalMetrics::memory() (QueryMemory: peak_bytes(), limit_bytes(), source(), tracked or estimated; None only when the query failed before it started); in the map and the JSON it is the top-level key query_memory:

p.query_memory  // #{peak_bytes: 2240, limit_bytes: 1073741824, limit: "traversal.max_materialized_bytes", source: "estimated"}

The peak is sampled where the engine checks the limit (every step boundary, bulk expansion, repeat() traverser and sized value), so a short spike between two checks can be missed. A failed execute() reports the figure of the check that failed. The text table shows it as one line under the TOTAL: rows only with ProfileType::Memory (a plain .profile() table is unchanged):

Peak memory: ~2.2 KiB of 1 GiB (traversal.max_materialized_bytes, estimated)

It is never compared with the process ceiling memory.limit: the two limits are never mixed.

A traversal that fails inside profile() is a script error with the full diagnostic, exactly like to_list(). Use execute(#{profile: true}) to get the profile up to the failing step.

In Rust, profile() / profile_with(flags) return TraverserResult<TraversalMetrics>; its Display impl renders the table.

Step names

Every step has one rendering, used by .profile(), by the step location of an error (at #2: ... with its caret) and by the help() text that rewrites the failing query. It reads like the DSL call that builds the step:

  • snake_case step names: has_label("person"), group_count(), side_effect(__.out());
  • Rhai literals for arguments: "x", 1, 2.5, (), [1, 2], #{name: "marko"}, UUID.from_string("..."), jpath("$.a.b");
  • predicates and tokens as you write them: P.gt(30).and(P.lt(40)), TextP.starting_with("m"), Order.desc, T.label, Scope.local, Pop.first, Column.keys, GType.LONG, Operator.sum, Cardinality.list;
  • child traversals as __.out().has("name", "x"); a where() child shows its start and end labels where you wrote them: where(__.as("a").out().as("b"));
  • nothing for an argument you left out (v(), out()), and the default Order.asc of a sort key is left out too (order().by("age")).

A step the optimizer fused or inserted shows under the name of what it does: v(labels: ["person"]).count(), v(ids: ["1"], labels: ["person"]), e().group_count().by(T.label), add_v("person", properties: ["name"]), lazy_barrier(). An empty intersection of id filters (g.V("1").hasId("2")) is v([]), a scan of nothing. Profile annotations stay after the name in brackets: [path: full], [lookup: label].

g.with("render.spelling", "camel") switches the whole rendering to the Gremlin camelCase spelling for one query ("snake" is the default):

$ graphersal -e 'g.with("render.spelling", "camel").V().hasLabel("person").outE().groupCount().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(labels: ["person"])                                           1       0       4    3.958µs     5.86
outE()                                                          1       4       6    2.542µs     3.76
groupCount()                                                    1       6       1    4.667µs     6.91
                                                      TOTAL:             execute:   67.541µs    16.54
=====================================================================================================
Optimizer rules applied: source_filter_pushdown

Front ends set it for a session: graphersal --spelling camel (REPL: /set spelling camel), the playground's Settings dialog, and in Rust RenderOptions::with_spelling(Spelling::Camel) passed on through graphersal::script::render_scope_options. A query's own g.with(..) wins. The camelCase names are the ones the DSL registers for each step (hasLabel for has_label), so a step that was not fused can be pasted back into a query in either spelling. Error messages and help() follow the same spelling, also for an error raised before the run (a denied step, an invalid option, a plan-time check); results never depend on it. In the Rust API, TraverserError::spelling() tells which spelling an error was rendered in; an error without a step frame comes wrapped in TraverserError::Spelled under camel (root_cause() unwraps it).

Long literal arguments are cut in every rendered step: a string after 64 characters (replace("aaaa…" (8192 chars), "b")) and a list, a map or the arguments of a variadic step after 16 items (a 10 000-item list shows its first 16 items, then , …] (10000 items)), so a location stays readable.

The metrics

TraversalMetrics { duration_ns, metrics: [Metrics], optimizer_rules_applied: [string] }
Metrics {
  id, name, duration_ns, percent_duration,
  path_recording?: "full" | "labels(a,b)",                // what the step records into paths
  counts: { traverser_count, element_count },
  calls, count_in,
  timing?: { min_duration_ns, max_duration_ns },          // once the step completed a call
  loops?:  { total_loops, max_depth, avg_loops_per_traverser },   // repeat() only
  memory?: { bytes_materialized, bytes_retained, alloc_count, source },  // ProfileType.Memory
  nested: [Metrics],                                     // steps of the child traversals
}

Keys are snake_case everywhere: Rust getters (metrics.counts().traverser_count()), Rhai map keys and JSON keys. Durations are Duration in Rust and integer nanoseconds (duration_ns) in Rhai and JSON. A key marked ? is absent unless it applies.

TinkerPop MetricsGraphersalNotes
durduration (duration_ns)total over all calls of the step
traverserCountcounts.traverser_counttraverser objects the step emitted
elementCountcounts.element_countlogical traversers they stand for (sum of bulks)
percentDurpercent_durationshare of the run's duration
nested metricsnestedflat list of every child-traversal step, ordered by id
—calls, count_inours: completed calls, traversers handed in
—timing, loops, memoryours: optional sections

traverser_count and element_count differ only when equal traversers were merged (bulk); the table then shows a Bulk column.

The extensibility rule

The metrics are data that you may store, compare and parse, so they only ever grow one way: a new ProfileType adds a new optional section to Metrics (as memory did), present only when that type was requested. The meaning and type of an existing field never change. Rust structs are #[non_exhaustive] and read through getters; consumers of the map or JSON form must ignore keys they do not know.

Step ids

Every step of the optimized plan has an id, its static position in the plan:

  • a top-level step is its index: "0", "1", ...;
  • a step inside a child traversal alternates step index and child-traversal index: <step>.<child>.<step>.... "3.1.0" is top-level step 3, its child traversal 1, step 0 in it.

The children of a step are numbered in a fixed order: the step's own traversal arguments first, in argument order (the union()/coalesce()/and()/or() branches, the body of where()/not()/filter()/local()/optional()/sideEffect(), the repeat() body, the choose()/branch() selector, the key of select(traversal)), then the modulator children in attachment order (by(__...), every option()'s key traversal and branch, the until() and emit() conditions of repeat()). A modulator without a traversal (by("name"), times(2)) takes no number.

g.V().union(__.out("knows"), __.in("created").values("name"))
// 0: v()   1: union(..)   1.0.0: out("knows")   1.1.0: in("created")   1.1.1: values("name")

Ids come from the plan, not from execution: a branch that never runs leaves no gap, and a step called once per traverser keeps one id (its calls counts the calls). The same numbering locates errors (below), so a partial profile and an error join by id.

execute()

let r = g.V().hasLabel("person").out("knows").execute();
r.results     // what to_list() returns
r.error       // () on success, else a map (below)
r.profile     // () unless requested
r.is_ok       // also isOk

let r = g.V().hasLabel("person").execute(#{profile: true});
let r = g.V().hasLabel("person").execute(#{profile_types: [ProfileType.Memory]});  // implies profile
r.to_map()    // #{results, error, profile}
r.to_json()

execute() never throws. Every error is in r.error: a runtime error (with the profile up to the failing step when profiling was on), an error that prevents the run from starting (an invalid with() option, a plan check, a locked option), and a malformed options map (execute(#{colour: 1})). The options are profile (bool) and profile_types (a list of ProfileType values or their names, "memory").

The error map:

#{
  message: "Step #1.1.1 'sum()' execution failed: Cast exception: ...",
  help: "...",                 // how to fix the query, when there is advice
  step_id: "1.1.1",            // the failing step, numbered like Metrics.id
  step_path: [#{id: "1", name: "union(...)"}, #{id: "1.1.1", name: "sum()"}],
  diagnostic: "Error: ...",    // the full text the CLI prints
}

step_id/step_path are absent for an error that has no step (an invalid option). An error found before the run (a rejected by()/from()/to(), an invalid constant argument such as merge_v(1) or math("_ +"), an undeclared step label, a denied step) carries the location of the step it is about, like a run-time failure. The names in step_path are the same plain step names as Metrics.name.

As the final value of a session an execution renders as its results (in the traversal's visualizer format, within the display limits) followed by the profile table; a failed execution renders as its diagnostic, followed by the partial profile, and counts as a failure (the CLI exits with code 1).

In Rust

use graphersal::prelude::*;

let graph = GraphSource::tinkerpop_modern();
let g = graph.read();
let exec = g
    .traversal()
    .v(None::<()>)
    .has_label("person")
    .out(None::<()>)
    .execute_with(ExecOptions::profile(ProfileType::none()));
assert!(exec.error().is_none());
assert_eq!(exec.results().len(), 6);
let profile = exec.profile().unwrap();
assert_eq!(profile.metrics()[0].id(), "0");
let results = exec.into_result().unwrap(); // the Result shape, for `?`

When the run fails, none of its changes are applied: the traversal is rolled back as a whole (see Transactions); results is empty and error and the partial profile are kept. exec.error() is Option<&TraverserError>; TraverserError::step_location() returns its StepLocation { step_id, step_path } (also usable on any error of to_list() and the other terminals). exec.mutated() (Rhai r.mutated) says whether the run changed the graph and kept the change: committed on its own, or part of the enclosing unit inside an explicit transaction or a whole-script unit (see Transactions). exec.changes() (Rhai r.changes, a map #{data, schema}) says what it changed: UnitChanges { data, schema }, with schema true when the run set or patched the schema (Schemas). Execution is #[non_exhaustive]: later per-run data is added to it as new getters.

TinkerPop differences

  • profile() returns the metrics in the same shape, with snake_case names and our extra fields (table above). The TinkerPop key names are not mirrored.
  • Step ids are static plan positions with the child-traversal index in them (3.1.0); TinkerPop numbers its metrics by internal step ids.
  • execute() is ours; TinkerPop has no terminal returning results and metrics of one run.
  • Step names are the canonical DSL rendering described in Step names (snake_case, or camelCase with render.spelling), not TinkerPop's step class names such as HasStep([~label.eq(person)]).

Memory Inspection and Memory-Aware Profiling

The structured result of profile() and the execute() terminal are described in Profiling and execute(); this page covers the memory figures.

Graphersal has two related tools for answering "how much memory is this using": an on-demand snapshot of a graph's own footprint, and a per-step memory figure inside .profile(). What the process memory ceiling checks (queries, loads, store opens, checkpoints, ...) and how a host asks whether an allocation fits (exec::check_memory_for, exec::memory_room) is described in What the ceiling covers.

Three different figures, two limits, never mixed:

FigureWhat it isAgainst
the graph's footprint (g.memory_usage(), below)an estimate of the graph's own datanothing: no percentage
the process memory bar (playground Statistics tab and Optimize -> Memory, REPL /memory, /api/statistics)the whole process (tracked live heap), split into structure, properties, compressed, indexes, models, live_graph, store, engine and otherthe process ceiling memory.limit (Seeing how full the process is)
a query's peak (query_memory of a profile, "Peak memory" in the playground's Profile panel)the most one execution held at oncethe per-query limit traversal.max_materialized_bytes

graph.memory_usage()

g.memory_usage()

Returns a map with structure_bytes, index_bytes, property_bytes (with its part shape_bytes), total_bytes, and total_mb — an on-demand, opt-in-by-call snapshot of the graph's own vertex/edge storage, its label/ID indexes, and its property store. It is entirely separate from traversal execution: it never touches a running query and cannot regress query performance.

With compression rules it also reports compressed_values (strings kept compressed), compressed_plain_bytes and compressed_stored_bytes (their plain and stored sizes) and compression_dictionary_bytes (the rules' dictionaries, each shared one once; part of total_bytes). property_bytes counts the stored, compressed size, so a rule's saving shows there directly. All four are 0 without rules. The dedup rules add deduped_values (the values they hold: coded in the element's row on a top-level key, shared strings under a nested path), deduped_plain_bytes (their plain size: a coded value's 32-byte slot plus its heap, a shared string's text) and dedup_table_bytes (the value dictionaries, the coded rows' layouts and the nested paths' tables: every value once, part of property_bytes); all three are 0 without dedup rules. In the memory report a coded value counts its 4-byte code as its slot and no heap (its heap is in the dictionary).

With property indexes it reports property_index_bytes, an estimate of their entries (part of total_bytes; 0 without indexes).

A graph in a store also reports workload_bytes: the memory of its workload statistics, held beside the graph and NOT part of total_bytes (which is the graph's own data); 0 for a graph without statistics. The playground's Profile ▸ Statistics tab shows it as Workload statistics below the total.

A graph whose catalog holds embedding models reports model_bytes: the memory of the models it holds loaded (a model shared by several positions counted once per graph), also NOT part of total_bytes; 0 when none is loaded. The process memory ceiling counts it.

How property memory works

Element properties share their key names. Every distinct sequence of keys (a "shape", say name, age in that order) is stored once per graph, and each vertex or edge keeps only its values, in that order. A property slot therefore costs one value (32 bytes on a 64-bit target) plus whatever heap the value owns (a string longer than 24 bytes, an array, a nested object, a vector), no matter how long the key name is or how many elements carry it. shape_bytes reports the shared key lists: the key names, a lookup index for shapes of more than 16 keys, and the graph's table of shapes. It is part of property_bytes, never added to total_bytes a second time. Insertion order stays what every step reports (valueMap(), elementMap(), properties()). The playground's Statistics tab shows the figure under Properties as "of which key lists (shapes)".

Two elements share a shape only when they have the same keys in the same order. Adding the properties of a label in one consistent order (always name then age, never sometimes age then name) keeps the number of shapes small. Elements that differ (optional properties, a key added later to some elements) are fine; they just make a few more shapes:

g.add_v("person").property("name", "ann").property("age", 31).iterate();
let one = g.memory_usage().shape_bytes;
g.add_v("person").property("name", "bob").property("age", 42).iterate();
let same_order = g.memory_usage().shape_bytes;      // unchanged: the second vertex shares the shape
g.add_v("person").property("age", 27).property("name", "cid").iterate();
let other_order = g.memory_usage().shape_bytes;     // grows: age, name is another shape
[one, same_order, other_order]

Dropping a property moves the element to the shape without that key; its value slot stays allocated until the element gains a key again (so a drop followed by an add, or a rollback of either, allocates nothing). A key list no element uses any more is not released right away: it goes when the graph has twice as many shapes as after the last release, after a load (opening a Store, reading a snapshot, a GraphSON or GraphML file read into a new graph), or on shrink_to_fit() (Rust: TraversalGraph::shrink_to_fit, also GraphStorage::shrink_to_fit). Until then shape_bytes still counts it. A shape is never released while anything still refers to it, such as a rollback image of an open transaction or a copied property map.

On a test graph of 1 million vertices and 3 million edges with UUID ids, six properties per vertex and two per edge, shared key lists took the live heap from about 2.2 GB to 1.4 GB.

IDs and the ID index

Each element's id is stored once, with the element. The ID index (part of index_bytes) keeps only a handle and a 32-bit hash of the id per element (12 bytes plus one control byte per bucket), and confirms a lookup by comparing the id stored with the element. Long ids such as UUID strings therefore cost their length once, not twice: choose ids for your data, not for memory. On a 1M/3M test graph with UUID ids and one property per vertex, dropping the index's second copy of every id saved about 20 % of the live heap. How both structures work inside is described in In-Memory Storage Internals.

Accuracy

All figures are estimates: they sum std::mem::size_of/capacity-based arithmetic over the structures that back the graph, not a true allocator-level accounting. Every hash map (a nested object, a free-standing map, the ID and label indexes) counts both of its allocations: the entries (per slot a cached hash, the key and the value; 64 bytes on a 64-bit target) and the hash index (a pointer-sized slot and a control byte per bucket, at most 7/8 full). Allocator rounding and bookkeeping are not counted. Two caveats worth knowing:

  • structure_bytes can be a loose bound on a heavily churned graph. The underlying storage never releases a removed vertex/edge's slot immediately (it keeps the slot to preserve other indices' stability), so a graph that has added and removed many elements can retain more memory than its current live element count would suggest. structure_bytes accounts for this using the storage's actual retained capacity, not just the live count, but no operation today reclaims the vacant slots of removed elements (shrink_to_fit(), below, releases only the spare capacity above the highest live slot and the indexes' spare room).
  • property_bytes is an O(n) walk. It visits every vertex, every edge, and every property, so its cost scales with graph size. On a graph of ~110k elements it completes in roughly a millisecond (see the crate's benchmarks for a current number) — fine for interactive use, not something to call in a hot loop.

memory_usage() is reachable through the GraphStorage trait, so any storage backend plugged into a GraphTraversalSource gets it uniformly — not just TraversalGraph. A backend that doesn't support introspection returns None.

Releasing spare capacity: shrink_to_fit()

A graph that grows by write queries (add_v, add_e, GQL CREATE, ...) grows its vertex and edge slot vectors by 1/8 of their size at a time (small ones by doubling) and its hash indexes by doubling, so after a bulk load part of the slots and index entries can be allocated but unused: the memory report's structure.vertex_slots.spare and edge_slots.spare. On 5 million vertices and 10 million edges built with GQL CREATE that was about 1.2 GB of 4.9 GB. A loaded graph never has any: every load (opening a Store, reading a snapshot, a GraphSON or GraphML file read into a new graph, the sample graphs) allocates its slots exactly and ends with a shrink.

g.shrink_to_fit() releases that spare capacity on the live graph and returns what it released:

g.inject(1).repeat(__.add_v("p")).times(1000).iterate();
g.shrink_to_fit()   // #{measured: true, before_bytes: .., after_bytes: .., released_bytes: ..}

before_bytes and after_bytes are memory_usage().total_bytes measured before and after, under the same write lock (measured is false and the figures are () for a storage that reports no memory figures). Call it once, after a bulk load by queries, not after every batch: the next write regrows the vectors from their exact size, so shrinking between batches copies the whole slot vector again each time. That is also why the engine never shrinks by itself at the end of a unit.

What it releases: the slots above the highest live vertex and edge, the spare room of the id and label indexes and of the handle generation arrays, and the shared property key lists no element uses any more. What stays: the vacant slots of removed elements below the highest live one (tombstoned; handles and slot positions are stable, and new elements reuse those slots first) and every element, property and index entry. It changes no data and commits nothing: no unit, no change set, no journal record, the commit position unchanged, so a Store reopens to the same graph. It takes the write lock for its duration (two memory walks and the reallocation), so writers and readers wait meanwhile. It asks for Update on the data (a read-only policy refuses it); on a graph the script built itself it asks nothing.

A Store also has a system job for it: compact (off by default, daily at 03:00 when enabled, book page Scheduled Jobs). Elsewhere: Rust Graph::shrink_to_fit() (a ShrinkReport with before_bytes, after_bytes and released_bytes(); also AnyGraph::shrink_to_fit, and GraphStorage::shrink_to_fit on the bare storage, which reports nothing), Python graph.shrink_to_fit() (the same dict).

The memory report

memory_usage() says how much; the memory report says where: per element kind and label and per top-level property, with the property indexes, the compression rules and the slots. It reports facts, not advice: what a key holds, how big its values are, how many distinct strings it has, which vectors. It is computed on demand by one walk over the elements and changes nothing.

g.memory_report().properties.filter(|p| p.path == "$.name").map(|p| [p.label, p.elements, p.bytes])

The answer is a map:

  • properties: one row per (element, label, path), most bytes first, at most 500 (see the options below; rows_omitted counts the rows left out and rows_omitted_bytes their bytes). elements have the key out of label_elements (sparsity); value_types counts the values per logical type (string, int64, date, vector, object, null, ...); bytes = slot_bytes (one 32-byte slot per value) + heap_bytes (what the values own: strings above 24 bytes, compressed blocks, vectors, arrays, nested objects with everything in them); sizes is a histogram of the values by their heap bytes (max_bytes 0 = no heap, then 32 B up to 1 MiB, null = above 1 MiB; each bucket with values and bytes, so "how many bytes sit in values above 2 KiB" is a sum); max_value_bytes; strings (values, inline_values, heap_bytes, plain_bytes and a distinct_estimate from a HyperLogLog sketch, exact up to 32 distinct texts, above that about 6.5 % standard error); vectors per element kind and dimension; compressed_* and deduped_* values with the rules and indexes on the key. leaf is false when some value is an object: the row then aggregates the nested keys (nested_values counts them). path is a jpath ($.name); rows are top-level keys today.
  • labels: per (element, label), at most 500, the largest (property_bytes plus slot_bytes) of both kinds, vertices listed first; labels_omitted counts the label rows left out, labels_omitted_elements their elements, labels_omitted_bytes their property and slot bytes and labels_omitted_property_bytes their property bytes alone. Each row has the elements, id_heap_bytes (ids above 24 bytes), label_bytes (a vertex's label list), slot_bytes (for edges this is the adjacency), property_bytes (its rows plus map_overhead_bytes: value slots kept for reuse after a key was dropped) and, for vertices, degree (max_out, max_in, max, p95: supernodes).
  • shapes: the number of key sequences met and a histogram of elements per shape.
  • indexes (each property index with its entries and bytes) and compression_rules (each rule with its values and plain, stored and dictionary bytes).
  • structure: what only the storage knows: vertex_slots/edge_slots (live, tombstoned: vacant slots of removed elements below the highest live one, spare: allocated above it, slot_bytes), id_index_bytes, label_index_bytes, shape_table_shapes and the totals of memory_usage() (with its shared_bytes). A layered graph adds base_stubs (base vertices holding a slot of the layer: an image or edges of the layer), removed_base_vertices and removed_base_edges; these are 0 for any other graph. null for a storage that does not report one; everything else is computed for any storage.
  • property_bytes (equal to memory_usage().property_bytes for a full report), estimated_total_bytes, shared_bytes (the memory shared with other graphs, outside the estimated total: a layered graph's base, 0 otherwise), scope ("all" or "delta", see below), tracked_live_bytes (the process heap where a tracking allocator is installed: the CLI, the dev server, the playground, Python; read when the report starts), components, attributed_bytes and unattributed_bytes (see Where the process memory goes), sampled, sample_every, visited_elements, commit_seq, elapsed_ms.

A vertex with several labels counts once, under its first (primary) label.

Options, all optional: #{max_elements: n} or #{sample_every: k} sample a large graph; #{limit: n} keeps the n property rows and the n label rows with the most bytes (default 500, so a graph that gives each of a hundred thousand vertices its own label still answers a small report), #{max_rows: n} and #{max_labels: n} set one list each and win over limit. The rows left out are counted with their bytes (rows_omitted, labels_omitted and the fields above); the totals (property_bytes, structure, shapes) always cover everything. A sample is stratified by label: the walk still passes every element and counts it under its label, but reads the properties of only every k-th element of each label (always the first), and scales each label by its exact count. So a small label is never missed; distinct counts from a sample are flagged distinct_reliable: false. A graph with very many labels reads about one element per label.

g.memory_report(#{sample_every: 2, max_rows: 3, max_labels: 2}).sampled   // true

#{scope: "delta"} reports only what the graph holds of its own. On a layered graph the walk then reads only the added and modified elements (the layer's delta), the structure is the layer's own, and the shared base is the single figure shared_bytes, so a layer does not "weigh" the base it shares with other layers. The default #{scope: "all"} walks every element the graph shows, so a report on a layer has the same rows as a report on the graph it shows. A plain graph owns everything it shows: there "delta" reports the whole graph, exactly as "all", and does not fail, so a query asking for the delta works on any graph.

let r = g.memory_report(#{scope: "delta"});
[r.scope, r.shared_bytes, r.properties.len()]   // ["delta", 0, 6]

The walk runs under a read lock: writers wait while it runs. A full report of about 1 million elements took about 0.9 s in a release build, a sample of 20 000 elements about 50 ms. The generated large graph (111 111 vertices, each with its own label: 333 330 property rows) reports in about 0.15 s (release) with the default limit; only the rows kept are built.

Elsewhere: Rust g.memory_report(&MemoryReportRequest::new()) (a MemoryReport with typed rows, Display as a terminal summary, to_property()/to_json() as this map; a CancelToken stops it; MemoryReportRequest::DEFAULT_LIMIT is 500, with_limit(usize::MAX) keeps every row); the REPL's /memory [delta] [max_elements] prints the summary (the 20 largest labels and properties, then how many more there are; delta: the scope "delta", a layer's own elements only); the dev server POST /api/memory/report (the playground's Optimize -> Memory, at most 500 rows per list with a "N more not shown" line) and the MCP tool memory_report (at most 50 property and label rows unless limit or max_rows/max_labels say otherwise); Python graph.memory_report(max_elements=.., limit=.., scope=..). Rust takes the scope as MemoryReportRequest::with_scope(MemoryReportScope::Delta); the session, the dev server and the MCP tool take the key scope.

use graphersal::prelude::*;
use graphersal::storage::{ElementKind, MemoryReportRequest, PropertyTarget};

let graph = TraversalGraph::tinkerpop_modern();
let report = graph.traversal().memory_report(&MemoryReportRequest::new()).unwrap();
let name = report
    .property(&PropertyTarget::top_level(ElementKind::Vertex, Some("person"), "name"))
    .unwrap();
assert_eq!(name.elements, 4);
assert_eq!(report.property_bytes(), graph.memory_usage().unwrap().unwrap().property_bytes);
println!("{report}");

A storage of your own gets every part except structure without any work; it fills that one by overriding GraphStorage::memory_structure (default None). The delta scope reads the storage's capabilities().layered and vertex_layer/edge_layer; a storage without layers needs nothing for it.

Where the process memory goes

The graph is often not the largest part of a process. components names every part the report can see, each {name, detail, bytes, exact} (exact: counted by the tracking allocator or the exact length of plain buffers; otherwise estimated from the structure):

nameWhat it isFigure
graphthe reported graph's own data (estimated_total_bytes, broken down in structure)estimated
workload_statisticsthe graph's workload statisticsestimated
embedding_modelone per embedding model loaded in the process (detail: its identity), shared by every graph that uses itexact where a tracking allocator counted the load, else the loader's estimate
script_enginethe DSL's registrations (Rhai's standard library and every step), built once per thread that runs scriptsexact (tracking allocator)
storea Store's buffers and caches (detail: its location)estimated
store_filesthe files of a store kept in memory (the playground's databases)exact
store_grapha Store's live graph, when the report is about another graph (a read-only view of a past state)estimated
session, mcp, ai_chatwhat the playground session (layouts), the dev server's MCP client sessions and its AI Chat conversations holdestimated

attributed_bytes is their sum and unattributed_bytes the tracked heap minus it: what no component explains (the estimates' error, other graphs that no Store holds, a host's caches it did not register, small buffers). It is null without a tracking allocator or for a storage that reports no structure. On the knowledge graph of this repository (44 k vertices, 211 k edges, a Model2Vec model in the store) the dev server's report reads:

Process memory: where it goes
  embedding_model         513.6 MiB  exact      model2vec/minishlab/potion-multilingual-128M@dc7b0f9e9e87
  graph                   186.8 MiB  estimated
  script_engine             2.0 MiB  exact      the DSL's registrations, built on 1 thread
  workload_statistics       1.2 MiB  estimated
  ...
  unattributed              2.9 MiB  of 1.1 GiB tracked

That model is counted when it loads: its embedding matrix takes 489 MiB, its tokenizer about 25 MiB (an 18 MiB file: a Unigram vocabulary of 500 000 tokens). Graphersal keeps a Unigram vocabulary in a few flat arrays (the tokens' bytes, their scores and a byte trie in breadth-first order), built when the model loads; the tokenizers crate's own form of the same vocabulary took 442 MiB. The token ids and the vectors are the same bits.

Everything here is computed when the report is asked for, by reading structures that exist anyway: nothing is counted on the read, write, commit or query paths (a model's bytes and the script registrations are measured once, when they are built). A Store lists its live graph as store_graph only in a report through the graph's front end (the DSL, AnyGraph::memory_report, the dev server, the playground, Python), which knows which graph is reported.

A host adds what it holds itself: implement MemorySource and register it with register_memory_source (both in graphersal::storage); it is held weakly (dropping it unregisters it) and asked at every report, so the DSL, the REPL and every other front end show it. A source answers quickly, never waits on a lock a query may hold, and never asks for a report itself. A part only the caller of one report knows goes in with MemoryReport::add_component.

The process's parts alone, without the report's walk, come from AnyGraph::process_memory_components: the components above except graph and workload_statistics, cheap enough for every statistics refresh. The process memory bar (Seeing how full the process is) groups them into its segments models, live_graph, store and engine.

use std::sync::Arc;
use graphersal::prelude::*;
use graphersal::storage::{
    AnyGraph, MemoryComponent, MemoryComponents, MemoryReportRequest, MemorySource,
    register_memory_source,
};

struct ResultCache(Vec<u8>);
impl MemorySource for ResultCache {
    fn memory_components(&self, components: &mut MemoryComponents) {
        components.push(MemoryComponent::exact("result_cache", self.0.capacity() as u64));
    }
}

let cache: Arc<dyn MemorySource> = Arc::new(ResultCache(Vec::with_capacity(4096)));
register_memory_source(&cache);
let graph = Graph::new(TraversalGraph::tinkerpop_modern());
let report = AnyGraph::memory_report(&graph, &MemoryReportRequest::new()).unwrap();
assert!(report.component("result_cache", None).is_some());

The resident set (RSS) of a process is usually larger than its tracked heap: the allocator keeps pages that were freed after a peak (a model load reads its blob whole and converts its matrix; a checkpoint encodes chunks; an open replays the WAL), and the program itself is not on the heap. The playground's memory bar shows the RSS beside the tracked heap.

Graph statistics

g.statistics()

Returns the element counts the graph keeps up to date as it changes: vertex_count, edge_count, and three label maps:

KeyCounts
vertex_labelsvertices carrying a label anywhere in their label set (a multi-label vertex counts under every label, like has_label)
primary_vertex_labelsvertices whose primary (first) label it is, what label() returns; every labeled vertex counts once
edge_labelsedges per label
$ graphersal -e 'g.statistics()'
"edge_count": 6
"edge_labels": #{"created": 4, "knows": 2}
"primary_vertex_labels": #{"person": 4, "software": 2}
"vertex_count": 6
"vertex_labels": #{"person": 4, "software": 2}

In Rust, GraphStorage::statistics() (and GraphTraversalSource::statistics()) returns Option<&GraphStatistics>, with getters such as vertex_label_count(label) and primary_vertex_label_counts(). Unlike memory_usage() this costs nothing to read: the counts are maintained incrementally by every mutation (O(labels involved), no allocation except for a label seen for the first time) and restored exactly by a rollback. A storage backend that keeps no statistics returns None; GraphStatistics::from_storage(&storage) computes them with one scan, and a backend that does report statistics must report exactly that. The optimizer reads label counts only through this method (Group Count Pushdown) and scans when it gets None.

The statistics are the place for everything the engine knows about the data. Planned extensions: degree statistics, property statistics (counts, distinct values), histograms, and persisted statistics stamped with the commit sequence they describe. Everything kept today is recomputable from the data, so nothing is persisted: loading a graph (GraphML, a change-set replay) rebuilds the statistics. A serialized form (behind the serde feature) will come with the first statistic that cannot be derived cheaply on load.

In the playground the same counts, the memory footprint and the limits a query runs under are the Statistics tab of the Profile panel:

The Statistics tab: counts per vertex and edge label, memory footprint and the query limits

.profile_with(ProfileType::Memory)'s Mem/Retained/Allocs columns

A bare .profile() (no argument) collects no memory data: it renders the plain Step | Call | In | Out | Time | % Dur table, at no extra measurement cost. Memory collection and its columns are opt-in through the ProfileType bitmask: .profile_with(ProfileType::Memory) (Rust) or g.profile(ProfileType::Memory) / g.profile(ProfileType.Memory) (Rhai, both token forms). .profile() is .profile_with(ProfileType::none()).

g.v().group().by(T.label).profile(ProfileType::Memory)

In the playground, tick Memory next to Profile in the Query toolbar: the Steps tab gets the Mem, Retained and Allocs columns (shown here on the dev server, whose timings are native; the browser rounds its timer to 0.1 ms):

A profile with the memory columns, the figures tracked by the allocator

Traversal Metrics
Step                                                         Call      In     Out       Time       Mem Retained Allocs    % Dur
===============================================================================================================================
v()                                                             1       0       6   13.208µs      480B     480B      1     6.30
group().by(T.label)                                             1       6       1   50.042µs    1.37KB     588B      7    23.87
                                                      TOTAL:             execute:  209.625µs                              30.17
                                                      TOTAL: memory materialized:               1.84KB                         
                                                      TOTAL:        net retained:                        1.04KB                
===============================================================================================================================

(real output, captured via graphersal.) Compare with a bare .profile() on the same query — no Mem/ Retained/Allocs columns, no TOTAL: memory materialized:/TOTAL: net retained: rows:

Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v()                                                             1       0       6    1.750µs     5.01
group().by(T.label)                                             1       6       1    7.041µs    20.14
                                                      TOTAL:             execute:   34.958µs    25.15
=====================================================================================================

Every step in a memory-profiled traversal reports bytes_materialized: how much heap data that step newly owns, beyond the lazy handles it passes through. Most steps (filters, has_label, out()/in()/both(), values() before a terminal materializes them, ...) never own new heap data at all — they carry lazy vertex/edge handles — so they report 0 at no measurement cost. Steps that build something new (group(), fold(), sum(), mean(), median(), path(), element_map()) report their aggregation/materialization buffer's size in the Mem column, next to Retained (net bytes kept) and Allocs (allocator call count) — see the next section for how to read all three together.

A ~ prefix on a Mem figure means it is estimated; a plain number means it is tracked (exact). Which one you get depends on how the binary was built — see below. As data, the figures are the optional memory section of every step's Metrics (MemoryMetrics: bytes_materialized, bytes_retained, alloc_count, source); a Retained/Allocs value of - means that figure simply isn't tracked for this run (source: "estimated", which has no allocator-level figures to show).

The whole query's figure is separate: the peak of the live bytes the query held at once, against its per-query limit traversal.max_materialized_bytes, on every profile as TraversalMetrics::memory() (key query_memory) and, with ProfileType::Memory, as the line Peak memory: .. of .. (traversal.max_materialized_bytes, tracked|estimated) under the table (see Profiling and execute()). It is not the sum of the Mem column: Mem counts what each step allocated, the peak what the query held at the same time.

No memory section vs. Estimated vs. Tracked

  • No memory section (a bare .profile(), no ProfileType argument): memory profiling wasn't asked for. No allocator thread-local is read, no estimate is computed — the executor skips the work entirely, not just its display. Every step's memory is absent (None in Rust, no key in the Rhai map and the JSON): "never measured," not "measured and found zero."
  • Estimated (.profile_with(ProfileType::Memory) without the alloc-tracking feature): a size_of/capacity-based estimate over the data the step already built, computed inside .profile_with()'s timing-collection gate. Expect roughly 10-30% divergence from true bytes for structures dominated by many small, separately-heap-allocated values, and it cannot see temporary allocation churn (memory allocated and freed again within a single step's own execution).
  • Tracked (.profile_with(ProfileType::Memory) with alloc-tracking): a real allocator-level measurement, via the alloc-tracking feature's TrackingAllocator. This requires two things: the feature compiled in, and the binary installing TrackingAllocator as its own #[global_allocator] (a library crate cannot do this for you — the attribute can only be set once, by the final binary). The CLI (graphersal), the web playground's WebAssembly module (graphersal-wasm) and the Python extension (py-graphersal, a cdylib that installs it for its own Rust heap; Python objects are not counted) all do this by default.

The trade alloc-tracking makes: once a binary installs TrackingAllocator, every allocation in that process pays a small, constant bookkeeping cost (a thread-local counter increment), whether or not the query in flight is profiled. This is the accepted cost in the graphersal command line, the web playground and the Python extension, for always-exact numbers in the reference binaries this project ships; the graphersal library without the feature, and any other consumer that doesn't opt in, stay exactly zero-cost. ProfileType::Memory gates a further, finer-grained cost on top of that: even in an alloc-tracking build, a query profiled without ProfileType::Memory (or not profiled at all) skips AllocSnapshot::capture/step_memory_metrics completely for every step.

The Bulk column

When equal traversers were merged (barrier(), the repeat() frontier, the optimizer's lazy_barrier()), .profile() shows a Bulk column after Out. Out counts traverser objects (TinkerPop's "Traversers"); Bulk is the sum of their bulks, i.e. how many logical traversers the step's output stands for (TinkerPop's "Count"). A lazy_barrier() row that reads In 8049, Out 562, Bulk 8049 merged 8049 traversers into 562 without losing any. A query where nothing merged has no Bulk column at all.

Gross vs. net: reading Mem alongside Retained/Allocs

Under Tracked, a step whose Mem figure looks alarmingly large is not automatically a bug. The Mem column (bytes_materialized) is gross allocation traffic: it sums every byte the step ever asked the allocator for during its execution, including a buffer that was grown by reallocation and then partly (or wholly) freed again before the step finished. It answers "how much allocator work did this cost," not "how much memory does this step's output now occupy."

For that second question, a Tracked step's row also carries real Retained/Allocs columns:

Step                                                         Call      In     Out       Time       Mem Retained Allocs    % Dur
===============================================================================================================================
v(labels: ["company"])                                          1       0   88000   29.126ms   11.25MB  10.00MB     33    12.62
in()                                                             1   88000  747988  136.318ms   80.00MB  70.00MB     19    59.04
has_label("country")                                            1  747988   88000   65.371ms       80B  -80.00MB      1    28.31
count()                                                          1   88000       1      375ns        0B        0B      0     0.00

(real figures from a 110k-element dataset, .profile_with(ProfileType::Memory): in() has a large fan-out, each input vertex expanding to 8-9 output vertices on average, written into one amortized-growth output buffer. has_label("country")'s -80.00MB Retained is a genuine negative delta: it drops in()'s large intermediate output as it filters, so it frees far more than it allocates.)

  • Retained is the net figure: live bytes at the step's exit minus live bytes at its entry. It is MemoryMetrics::bytes_retained, and it can be smaller than Mem (gross) whenever the step freed more than it kept (the reallocation churn described below), and it can even be negative — a step that frees more than it allocates (for instance, one that drops a large intermediate the previous step built) genuinely shows a negative delta, and this is reported honestly rather than clamped to 0, as has_label("country")'s -80.00MB above shows. For in(), gross (80.00MB) is only modestly larger than retained (70.00MB): about 10MB of that 80MB was allocated and freed again within the step's own execution (the shared output buffer's amortized-doubling growth), not memory the step's output still holds by the time it hands off to the next step — a tight Mem/Retained gap like this, together with a low Allocs count relative to output size, is the signature of a step writing into one reused buffer rather than allocating per item.
  • Allocs is MemoryMetrics::alloc_count: the number of distinct calls the step made to the allocator (alloc/alloc_zeroed, plus any realloc that grew a buffer). A step that does a handful of large, deliberate allocations (reserve()d once, filled once, or grown by a shared buffer's own amortized doubling — 19 allocations for 747,988 output items above) has a low Allocs relative to its output size — efficient and expected. A step whose Allocs count runs into the hundreds of thousands for tens of thousands of output items is very likely allocating per-item or per-small-batch, which is exactly the structural symptom a large Mem/Retained gap usually traces back to.

Together, Retained and Allocs turn "this step's Mem figure looks huge" into a diagnosable statement: high Mem, low Retained, high Allocs reads as "high churn, low net retention" — a step reallocating a growing buffer many times over — rather than a flat, unexplained number.

Both columns read - under Estimated (the size_of-based path has no allocator to draw them from), and neither column exists at all — not even as - — under a bare .profile(), since the Mem column itself isn't rendered without ProfileType::Memory.

This is a lightweight, always-available, in-process diagnostic, not a replacement for external profiling tools. It tells you that a step is churning and roughly how much, at the whole-step granularity; it does not attribute any individual allocation to a call site (e.g. "this came from Vec::push at line 107"), and it has no peak/high-water-mark figure (the maximum live bytes at any point during a step, as opposed to just at its entry and exit). For that level of detail, reach for valgrind --tool=massif, heaptrack, or a sampling allocator profiler — this feature exists so you rarely need to reach for those tools for a first-pass diagnosis, not so you never do.

Summary

ScopeCost when unusedAccuracy
graph.memory_usage()The whole graph's storageN/A — never runs on the query pathEstimate (capacity-based)
A bare .profile() (no memory section)One query's steps, timing onlyZero — no memory collection at allN/A — no memory data
.profile_with(ProfileType::Memory), EstimatedOne query's stepsZero when ProfileType::Memory isn't requestedEstimate, ~10-30% divergence possible
.profile_with(ProfileType::Memory), TrackedOne query's stepsA small, constant, always-on cost per allocation once alloc-tracking is installed, plus the per-call cost of requesting ProfileType::MemoryExact (Mem, gross); Retained/Allocs add net and churn figures

Step Reference

Every step of the DSL has a page of its own, listed in alphabetical order under this chapter in the sidebar and by category below. This page is the short guide to what every query shares: where it starts, how it runs, how much it returns and how it is shown.

g and __

g is the graph you query; a query starts with a start step on it, such as v() (vertices), e() (edges) or inject(..) (values). __ starts an anonymous traversal: the child of a step such as where, repeat, union or by, which runs once for every element that reaches it.

g.v().has_label("person").where(__.out("created")).values("name")   // marko, josh, peter

Every TinkerPop step has a snake_case name and its Gremlin camelCase twin (has_label and hasLabel, out_e and outE); they are the same function. Graphersal's own extensions are snake_case only. Strings are written in double quotes, maps as #{key: value}, lists as [1, 2]. Tokens are written with their class: P.gt(30), Order.desc, T.label, Scope.local, Column.keys (see Predicates and Functions, Tokens and Values).

Running a query

A query runs when it reaches a terminal. A query without one, at the end of a script, is run and shown (a table in the command line and the playground).

TerminalReturns
to_list()all results, as a list
next()the first result
iterate()nothing: runs the query for what it writes
to_graph()the edges reached and their vertices, as a graph
profile()the optimized plan with timings and counts
execute()results, error and profile together, never throws
g.v().values("name").next()                                   // marko
g.v().has("name", "marko").property("age", 30).iterate()      // a write, nothing returned

Every query is one unit: when a step fails, nothing the query wrote stays (Transactions).

How many results

The data a query returns is never cut. To ask for less, use the steps that select a part: limit(n), range(low, high), tail(n), skip(n), dedup(), sample(n).

g.v().has_label("person").values("name").limit(2)         // marko, vadas
g.v().has_label("person").values("name").range(1, 3)      // vadas, josh

What is shown is bounded: a displayed result has at most 100 rows and 100 items per nested list or map, with a notice when more exist. One query changes it with an argument of its visualizer or a g.with() option; the command line has --max-rows, --max-items and --no-limit (Displaying Results).

g.v().to_table(#{max_rows: 2})                     // two rows and a notice that more exist
g.with("render.max_rows", 2).v().values("name")    // the same for one query

Showing results

VisualizerShows
to_table()a table (the default)
to_markdown()a Markdown table
to_json()JSON
to_tree()a tree of nested values
to_mermaid(), to_plantuml(), to_json_schema()a diagram or a JSON Schema of a schema, for example of infer_schema()
visualize(V.Json)any of them by token: V.Table, V.Markdown, V.Json, V.Tree, V.Mermaid, ...
g.v().has_label("person").value_map("name", "age").to_markdown()
g.v().infer_schema().to_mermaid()

Options of one query

g.with(key, value) sets an option for the query that follows it: a time limit, the loop limit, the display limits, the spelling of the profile, which optimizer rules run. Every key is in the Execution Options Reference; a host can lock them (Running Queries Safely).

g.with("evaluationTimeout", 1000).v().count()        // stops after one second
g.with("repeat.max_loops", 10).v("1").repeat(__.out()).until(__.has("name", "ripple")).values("name")

Help inside the tools

The text of every step page is also where you write queries:

  • in the REPL: /help <name> (/help has_label, /help hasLabel), /help steps, /help tokens;
  • in the web playground: the completion of the query editor;
  • over MCP: the graphersal://dsl-reference resource of the dev server.

Steps follow the Apache TinkerPop reference documentation unless a page says otherwise; the differences are collected in TinkerPop Deviations.

Steps by category

Start

v · e · inject · gql

Walking the graph

out · in · both · out_e · in_e · both_e · out_v · in_v · both_v · other_v · to_e · to_v · glob_path

Filters

has · has_id · has_key · has_label · has_layer · has_not · has_p · has_value · has_value_any · has_value_p · is · where · where_p · where_t · filter · and · or · not · dedup · limit · range · skip · tail · coin · sample · simple_path · cyclic_path · none · discard · all · any

Values and properties

values · value_map · element_map · properties · id · label · labels · layer · key · value · constant · element · json_path · index · identity

Strings and type conversion

to_lower · to_upper · trim · l_trim · r_trim · substring · replace · concat · format · split · length · as_string · as_bool · as_number · cast

Dates and times

as_date · as_duration · date_add · date_diff · age · date_trunc · date_part · at_zone · as_local

Vectors

as_vector · quantize · similarity · nearest · vector_mean · embed · embedders

Lists and ordering

fold · unfold · combine · conjoin · difference · disjunct · intersect · merge · product · reverse · order

Aggregation

count · sum · min · max · mean · median · group · group_count · tree · aggregate · store · cap · barrier

Labels and paths

as · select · path · project · math

Branches and loops

union · choose · branch · option · coalesce · optional · repeat · times · until · emit · loops · local · map · flat_map

Modulators and options

by · from · to · with · with_path · with_bulk

Sack and side effects

sack · with_sack · with_side_effect · side_effect · subgraph

Changing the graph

add_v · add_e · property · property_json · drop · remove_property · add_label · drop_label · set_label · merge_v · merge_e · fail

Running and showing results

to_list · next · iterate · execute · profile · profile_with · to_graph · to_table · to_json · to_markdown · to_tree · to_mermaid · to_plantuml · to_json_schema · visualize · set_visualizer

Schema

get_schema · set_schema · patch_schema · validate_schema · validate_schema_patch · infer_schema · diff_schema

Saved queries

define_query · define_queries · query · queries · get_query · drop_query · move_query · describe_query

Property indexes

create_index · drop_index · indexes

Scheduled jobs

define_job · jobs · drop_job

Compressed properties

define_compression · define_compressions · drop_compression · drop_compressions · compressions · recompress · estimate_compression

Graph information and files

statistics · memory_usage · memory_report · layer_diff · shrink_to_fit · mark · import_graphml · import_graphson · export_graphml · export_graphson · export_snapshot

Predicates, tokens and test data

Predicates · Functions, Tokens and Values · Test Data Functions

Predicates

See also Predicates: Comparison and Resolution.

P.between: At least the first and less than the second value.

g.v().values("age").is(P.between(27, 30)).to_list()   // [29, 27]

P.containing: The string contains the given text.

g.v().values("name").is(TextP.containing("ar")).to_list()   // ["marko"]

P.ending_with · P.endingWith: The string ends with the given text.

g.v().values("name").is(TextP.ending_with("o")).to_list()   // ["marko"]

P.eq: Equal to the value.

g.v().has("age", P.eq(29)).values("name").to_list()   // ["marko"]

P.gt: Greater than the value.

g.v().values("age").is(P.gt(30)).to_list()   // [32, 35]

P.gte: Greater than or equal to the value.

g.v().values("age").is(P.gte(32)).to_list()   // [32, 35]

P.inside: Strictly between the two values (both excluded).

g.v().values("age").is(P.inside(27, 32)).to_list()   // [29]

P.lt: Less than the value.

g.v().values("age").is(P.lt(29)).to_list()   // [27]

P.lte: Less than or equal to the value.

g.v().values("age").is(P.lte(29)).to_list()   // [29, 27]

P.neq: Not equal to the value.

g.v().values("age").is(P.neq(29)).to_list()   // [27, 32, 35]

P.not: The complement of the given predicate (see the book page Predicates for the deviation from TinkerPop).

g.v().values("age").is(P.not(P.gt(30))).to_list()   // [29, 27]

P.not_containing · P.notContaining: The string does not contain the given text.

g.v().values("name").is(TextP.not_containing("o")).to_list()   // ["vadas", "ripple", "peter"]

P.not_ending_with · P.notEndingWith: The string does not end with the given text.

g.v().values("name").is(TextP.not_ending_with("s")).to_list()   // ["marko", "lop", "josh", "ripple", "peter"]

P.not_starting_with · P.notStartingWith: The string does not start with the given text.

g.v().values("name").is(TextP.not_starting_with("r")).to_list()   // ["marko", "vadas", "lop", "josh", "peter"]

P.outside: Below the first or above the second value.

g.v().values("age").is(P.outside(27, 32)).to_list()   // [35]

P.starting_with · P.startingWith: The string starts with the given text.

g.v().values("name").is(TextP.starting_with("m")).to_list()   // ["marko"]

P.typeOf: The value is of the given GType or type name (String, Integer, Double, UUID, ...).

g.v().has("age", P.typeOf(GType.LONG)).count().next()   // 4

P.within · P.WithIn: Equal to one of the values (given as arguments or one list).

g.v().values("age").is(P.within(27, 35)).to_list()   // [27, 35]

P.without · P.WithOut: Equal to none of the values (given as arguments or one list).

g.v().values("age").is(P.without(27, 35)).to_list()   // [29, 32]

TextP.containing: The string contains the given text.

g.v().values("name").is(TextP.containing("ar")).to_list()   // ["marko"]

TextP.ending_with · TextP.endingWith: The string ends with the given text.

g.v().values("name").is(TextP.ending_with("o")).to_list()   // ["marko"]

TextP.not_containing · TextP.notContaining: The string does not contain the given text.

g.v().values("name").is(TextP.not_containing("o")).to_list()   // ["vadas", "ripple", "peter"]

TextP.not_ending_with · TextP.notEndingWith: The string does not end with the given text.

g.v().values("name").is(TextP.not_ending_with("s")).to_list()   // ["marko", "lop", "josh", "ripple", "peter"]

TextP.not_regex · TextP.notRegex: The string does not match the regular expression.

g.v().values("name").is(TextP.not_regex("^[mjp]")).to_list()   // ["vadas", "lop", "ripple"]

TextP.not_starting_with · TextP.notStartingWith: The string does not start with the given text.

g.v().values("name").is(TextP.not_starting_with("r")).to_list()   // ["marko", "vadas", "lop", "josh", "peter"]

TextP.regex: The string matches the regular expression (Rust regex dialect, see the book page Predicates).

g.v().values("name").is(TextP.regex("^[mj]")).to_list()   // ["marko", "josh"]

TextP.starting_with · TextP.startingWith: The string starts with the given text.

g.v().values("name").is(TextP.starting_with("m")).to_list()   // ["marko"]

Predicate.and: Combines two predicates: both must match.

g.v().has("age", P.gt(30).and(P.lt(35))).values("name").to_list()   // ["josh"]

Predicate.negate: The complement of the predicate (see the book page Predicates for the deviation from TinkerPop).

g.v().has("age", P.gt(30).negate()).values("name").to_list()   // ["marko", "vadas"]

Predicate.or: Combines two predicates: at least one must match.

g.v().has("age", P.lt(28).or(P.gt(33))).values("name").to_list()   // ["vadas", "peter"]

Functions, Tokens and Values

as_string · asString: The canonical ISO 8601 text of a date or time value.

datetime("2023-08-02T09:30+02:00").as_string()   // 2023-08-02T09:30:00+02:00

between: the same as P.between, without the class name.

containing: the same as P.containing, without the class name.

date: A date from ISO 8601 text.

date("2024-02-29").day   // 29

datetime · DateTime: A datetime from ISO 8601 text.

datetime("2023-08-02T09:30Z").hour   // 9

duration: A duration (PostgreSQL interval).

duration("P1Y2M").months   // 14

embed: A vector for a text from an embedder (default hash-ngram/1), computed before any traversal runs.

embed("Marko") == embed("marko")   // true

empty: Creates a new empty graph, private to the script, and returns its traversal source.

GraphSource::empty().v().count().next()   // 0

ending_with · endingWith: the same as P.ending_with, without the class name.

eq: the same as P.eq, without the class name.

Fake: A seeded generator of English test data and random numbers: the same seed and calls give the same values; without a seed it picks one (see the book page Generating test data).

Fake(1).full_name()   // Victoria Vargas

file: Loads a graph file (.xml/.graphml, GraphSON .json) into a new private graph (needs file access).

GraphSource::file("modern.graphml").v().count().next()

file_tree: Creates a private sample graph of a file tree (directories, files, symlinks), as used by glob_path().

GraphSource::file_tree().v().count().next()   // 37

gt: the same as P.gt, without the class name.

gte: the same as P.gte, without the class name.

inside: the same as P.inside, without the class name.

jpath: Builds a JSONPath property key for nested values, usable wherever a property name is (see the book page Path keys (jpath)).

g.inject(#{a: #{b: [5, 6]}}).values(jpath("a.b[1]")).to_list()   // [6]

localdatetime: A date and time without a zone.

localdatetime("2023-08-02T09:30").hour   // 9

lt: the same as P.lt, without the class name.

lte: the same as P.lte, without the class name.

neq: the same as P.neq, without the class name.

not: the same as P.not, without the class name.

not_containing · notContaining: the same as P.not_containing, without the class name.

not_ending_with · notEndingWith: the same as P.not_ending_with, without the class name.

not_regex · notRegex: the same as TextP.not_regex, without the class name.

not_starting_with · notStartingWith: the same as P.not_starting_with, without the class name.

now: Script start time, the same for every call (PostgreSQL now()).

now() == now()   // true

offsettime: A time of day with its UTC offset.

offsettime("09:30+02:00").offset   // 7200

outside: the same as P.outside, without the class name.

regex: the same as TextP.regex, without the class name.

starting_with · startingWith: the same as P.starting_with, without the class name.

time: A time of day.

time("09:30:15").second   // 15

tinkerpop_modern: Creates a private copy of TinkerPop's modern sample graph (6 vertices, 6 edges).

GraphSource::tinkerpop_modern().e().count().next()   // 6

today: The date of now() in UTC or in the given zone.

type_of(today())   // date

typeOf: the same as P.typeOf, without the class name.

UUID: Returns a new random UUID value.

type_of(UUID())   // Uuid

vector: A vector value (an embedding) from a list of numbers: f32, or quantized to f16, i8 or bit.

vector([0.5, -1.0], "bit").to_list()   // [1.0, -1.0]

within: the same as P.within, without the class name.

without: the same as P.without, without the class name.

By.JsonPath: A by() argument that reads a nested value by a JSONPath.

g.inject(#{a: #{b: 2}}, #{a: #{b: 1}}).order().by(By.JsonPath("a.b")).to_list()   // [#{"a": #{"b": 1}}, #{"a": #{"b": 2}}]

By.Property: A by() argument that reads the named property (the same as by("name")).

g.v().has_label("person").order().by(By.Property("age")).values("name").to_list()   // ["vadas", "marko", "josh", "peter"]

By.Traversal: A by() argument that runs a child traversal (the same as by(__.x())).

g.v().has_label("person").order().by(By.Traversal(__.out_e().count())).values("name").to_list()   // ["vadas", "peter", "josh", "marko"]

Cardinality.list: A property value tagged with Cardinality.list; writing it fails (one value per key, see the book page Upserts).

type_of(Cardinality.list(5))   // CardinalityValue

Cardinality.set: A property value tagged with Cardinality.set; writing it fails (one value per key, see the book page Upserts).

type_of(Cardinality.set(5))   // CardinalityValue

Cardinality.single: A property value tagged with Cardinality.single, for merge_v()/merge_e() option maps.

g.merge_v(#{"T.id": "1"}).option(Merge.onMatch, #{age: Cardinality.single(30)}).values("age").next()   // 30

CastPolicy.Default: A cast policy that replaces a value that does not convert with the given fallback.

g.inject("x", "1").as_number(GType.LONG, CastPolicy.Default(0)).to_list()   // [0, 1]

UUID.from_string · UUID.fromString: Parses a UUID value from its canonical text.

UUID.from_string("123e4567-e89b-12d3-a456-426614174000").as_string()   // 123e4567-e89b-12d3-a456-426614174000

Uuid.as_string · Uuid.asString: The canonical text of the UUID value.

UUID.from_string("123e4567-e89b-12d3-a456-426614174000").as_string().len()   // 36

temporal.as_string · temporal.asString: The canonical ISO 8601 text of a date or time value.

datetime("2023-08-02T09:30+02:00").as_string()   // 2023-08-02T09:30:00+02:00

Vector.quantize: The vector in another element kind (f32, f16, i8, bit).

vector([0.5, -1.0]).quantize("i8").dimension   // 2

Vector.to_list · Vector.toList: The values of the vector as a list of floats (dequantized).

vector([0.5, 2]).to_list()   // [0.5, 2.0]

Set.of: A set value (duplicates dropped) of the given values, e.g. to seed a set side effect.

g.with_side_effect("s", Set.of()).v().out().values("name").aggregate("s").cap("s").next()   // ["josh", "lop", "vadas", "ripple"]

Set.of_list · Set.ofList: A set value (duplicates dropped) of the elements of the given list.

g.with_side_effect("s", Set.of_list(["lop"])).v().out().values("name").aggregate("s").cap("s").next()   // ["lop", "josh", "vadas", "ripple"]

Map.contains: Whether a map with non-string keys has the given key.

g.v().group().by("age").next().contains(29)   // true

Map.contains_key · Map.containsKey: Whether a map with non-string keys has the given key (alias of contains()).

g.v().group().by("age").next().contains_key(30)   // false

Map.is_empty · Map.isEmpty: Whether a map with non-string keys has no entries.

g.v().group().by("age").next().is_empty()   // false

Map.keys: The keys of a map with non-string keys (group(), group_count() results).

g.v().has_label("person").group_count().by("age").next().keys()   // [29, 27, 32, 35]

Map.len: The number of entries of a map with non-string keys.

g.v().group().by("age").next().len()   // 4

Map.to_map · Map.toMap: Converts the map to a plain Rhai object map; fails when a key is not a string.

g.v().group_count().by("age").next().to_map()   // error: non-string key 29

Map.values: The values of a map with non-string keys.

g.v().has_label("person").group_count().by("age").next().values()   // [1, 1, 1, 1]

V.Auto: The default display format: chosen by the result's shape.

g.v(1).values("name").visualize(V.Auto)

V.Json: Display format: JSON text.

g.v(1).values("name").visualize(V.Json)

V.JsonSchema: Display format: the JSON Schema of the results (a schema map as JSON Schema; other results as JSON per line).

g.v(1).values("name").visualize(V.JsonSchema)   // "marko"

V.Markdown: Display format: a Markdown table.

g.v(1).values("name").visualize(V.Markdown)

V.Mermaid: Display format: Mermaid (a schema map as a diagram; other results as JSON per line).

g.v(1).values("name").visualize(V.Mermaid)   // "marko"

V.PlantUML: Display format: PlantUML (a schema map as a diagram; other results as JSON per line).

g.v(1).values("name").visualize(V.PlantUML)   // "marko"

V.Table: Display format: a text table.

g.v(1).values("name").visualize(V.Table)

V.Tree: Display format: an indented tree.

g.v(1).out().visualize(V.Tree)

GraphSource.empty: Creates a new empty graph, private to the script, and returns its traversal source.

GraphSource::empty().v().count().next()   // 0

GraphSource.file: Loads a graph file (.xml/.graphml, GraphSON .json) into a new private graph (needs file access).

GraphSource::file("modern.graphml").v().count().next()

GraphSource.file_tree: Creates a private sample graph of a file tree (directories, files, symlinks), as used by glob_path().

GraphSource::file_tree().v().count().next()   // 37

GraphSource.tinkerpop_modern: Creates a private copy of TinkerPop's modern sample graph (6 vertices, 6 edges).

GraphSource::tinkerpop_modern().e().count().next()   // 6

map.subgraph: The meta-graph of one label of a schema map (private to the script).

g.infer_schema().subgraph("person").v().count().next()   // 1

map.subgraph_labels: The meta-graph of the given labels of a schema map (private to the script).

g.infer_schema().subgraph_labels(["person", "software"]).v().count().next()   // 2

map.to_graph: Builds the meta-graph of a schema map: one vertex per label, one edge per declared connection (private to the script).

g.infer_schema().to_graph().v().count().next()   // 2

TraversalMetrics.to_json: The profile as JSON text.

g.v().count().profile().to_json().contains("count_pushdown")   // true

TraversalMetrics.to_map · TraversalMetrics.toMap: The profile as a map: duration_ns, metrics per step, optimizer_rules_applied.

g.v().count().profile().to_map()["optimizer_rules_applied"]   // ["count_pushdown"]

TraversalMetrics.to_table: The profile as the text table that profile() shows.

g.v().count().profile().to_table().contains("v().count()")   // true

Execution.to_json: The execution (results, error, profile) as JSON text.

g.v().count().execute().to_json()   // {"results":[6],"error":null,"profile":null}

Execution.to_map · Execution.toMap: The execution as a map: results, error, profile, mutated, changes.

g.v().count().execute().to_map()["results"]   // [6]

Test Data Functions

See also Generating Test Data.

Fake.address: A random one-line US address whose city and state belong together.

Fake(1).address()   // 5666 Broad Trail, Bakersfield, CA 44960

Fake.chance: True with the given probability (0.0 to 1.0).

Fake(1).chance(0.5)   // false

Fake.city: A random US city name.

Fake(1).city()   // Irvine

Fake.company: A random company name.

Fake(1).company()   // Vargas & Ryan

Fake.country: A random country name.

Fake(1).country()   // South Africa

Fake.domain_name: A random domain name.

Fake(1).domain_name()   // vasquezsalt.info

Fake.email: A random e-mail address at a reserved example domain (example.com, .org, .net); with a name, one made from that name.

Fake(1).email("Ada Lovelace")   // ada.lovelace57@example.net

Fake.first_name: A random English given name.

Fake(1).first_name()   // Victoria

Fake.float: A random float from 0.0 (included) to 1.0 (excluded), or from lo to hi.

Fake(1).float(0, 100)   // 56.65615751722809

Fake.fork: An independent generator for a named stream of the same seed, unaffected by what was drawn before.

Fake(1).fork("people").first_name()   // Mason

Fake.full_name: A random given name and surname.

Fake(1).full_name()   // Victoria Vargas

Fake.int: A random integer from lo to hi, both included.

Fake(1).int(1, 6)   // 4

Fake.job_title: A random job title such as Senior Data Analyst.

Fake(1).job_title()   // Principal Infrastructure Officer

Fake.last_name: A random English surname.

Fake(1).last_name()   // Vasquez

Fake.lorem: Lorem ipsum text of a random length from lo to hi bytes, in paragraphs, ending with a period.

Fake(1).lorem(100, 200).len()   // 157

Fake.lorem_paragraph: A random Lorem ipsum paragraph of 3 to 7 sentences.

Fake(1).lorem_paragraph().len()   // 300

Fake.lorem_sentence: A random Lorem ipsum sentence of 6 to 14 words.

Fake(1).lorem_sentence()   // Vel non non accumsan libero est consequat ac excepteur montes sunt.

Fake.phone: A random US phone number in the fictional 555-01xx range.

Fake(1).phone()   // +1-648-555-0174

Fake.pick: A random element of a non-empty array.

Fake(1).pick(["red", "green", "blue"])   // green

Fake.sample: The given number of distinct elements of the array, in random order.

Fake(1).sample([1, 2, 3, 4], 2)   // [3, 4]

Fake.seed: The seed the generator (or the root of a fork) was created with; pass it to Fake(seed) to reproduce a run.

Fake(1).seed()   // 1

Fake.sentence: A random sentence of 4 to 12 words.

Fake(1).sentence()   // Salt winter linen linen shadow swift mountain glacier snow.

Fake.shuffle: A copy of the array in random order.

Fake(1).shuffle([1, 2, 3, 4])   // [1, 2, 4, 3]

Fake.state: A random US state name.

Fake(1).state()   // New Hampshire

Fake.state_abbr: A random US state postal abbreviation.

Fake(1).state_abbr()   // NH

Fake.street_address: A random house number and street name.

Fake(1).street_address()   // 5666 Broad Trail

Fake.street_name: A random street name.

Fake(1).street_name()   // Lakeview Circle

Fake.username: A random user name: a lowercase given name, an initial and a number.

Fake(1).username()   // victoriav971

Fake.uuid: A random version 4 UUID value drawn from the seed.

Fake(1).uuid().as_string()   // 910a2dec-8902-4cc1-beeb-8da1658eec67

Fake.word: A random English word.

Fake(1).word()   // onyx

Fake.zip_code: A random five-digit US ZIP code.

Fake(1).zip_code()   // 57062

List Functions

The list functions work on the list a traverser holds and turn it into one new value per traverser (they are map steps, 1 to 1):

StepResultPage
combine(list)the incoming list followed by list, duplicates keptcombine
conjoin(delimiter)the elements joined into one stringconjoin
difference(list)the incoming elements that are not in list (a set)difference
disjunct(list)the elements in exactly one of the two lists (a set)disjunct
intersect(list)the incoming elements that are also in list (a set)intersect
merge(list) / merge(map)the union of two lists (a set), or two maps mergedmerge
product(list)every [a, b] pair of the two listsproduct

They are TinkerPop 3.7+ steps and follow the TinkerPop 3.8.2 feature files (map/Combine.feature and the others: every in-scope scenario passes).

The incoming list

A traverser holds a list after fold(), path(), a list constant (constant([..]), inject([..])) or a list-valued property (values("tags")). A path counts as the list of its objects. Anything else, null included, is an error that names the step and the fix:

graphersal> g.V().values("name").combine(["x"])
Error: Step #2 'combine(["x"])' execution failed
  at #2: v().values("name").combine(["x"])
                            ^^^^^^^^^^^^^^
Caused by: The combine() step takes a list as its incoming value, but got string
Help: combine() works on the list a traverser holds (a fold(), a path(), a list-valued property). Collect the stream into a list with fold() first, for example g.V().values("name").fold().combine(["x"]).

A fused count() after the step does not skip it: g.V().values("name").combine(["x"]).count() raises the same error.

The argument

The second operand is either

  • a list constant: combine(["dave", "kelvin"]) (Rust: combine(vec!["dave", "kelvin"])), or
  • a child traversal whose first result is the list: combine(__.V().values("name").fold()) (Rust: combine_traversal(__::v(None).values("name").fold())). It runs on the incoming traverser, with its path, so __.select("a") reads a label of the traverser. End it with fold() to turn a stream into a list.

null, a single value (combine(2)) and a traversal that yields nothing, null or a non-list are errors. merge() of a map takes a map instead (see merge).

Element equality

difference, disjunct, intersect and merge have set semantics: every element appears at most once in the result, in the order of its first occurrence (incoming list first). Elements compare the way dedup() compares traversers: vertices and edges by identity, everything else by value (1 and 1.0 are different values, as in TinkerPop). null is an element like any other. The kept elements stay what they were, so a folded vertex list keeps its vertices:

graphersal> g.V("1").out("knows").fold().difference(__.V("4").fold()).unfold().values("name")
vadas

In the Rust API

Every list function has a constant form and a _traversal form on GraphTraversalSource, AnonymousTraversal and __: combine / combine_traversal, difference / difference_traversal, and so on; conjoin(delimiter) has one form. In the DSL both spellings are the same name (combine, conjoin, ...), which takes a list, a map or a traversal.

Steps - add_label, drop_label, set_label

Graphersal extensions that change the labels of existing elements. TinkerPop labels are immutable and TinkerPop has no such steps, so these add to Gremlin rather than deviate from it. Each step changes the element it receives and passes the same element on, so the traversal can continue.

StepElementWhat it does
add_label("L")vertexadds L to the vertex's label set (appended; the first label stays the primary one label() returns)
drop_label("L")vertexremoves L from the label set; dropping the last one leaves the vertex unlabeled
set_label("L")edgereplaces the edge's one label (an unlabeled edge gets L)
g.v(1).add_label("employee").labels().next()        // ["person", "employee"]
g.v(1).drop_label("person").labels().next()         // []
g.e(0).set_label("met").label().next()              // "met"
g.v().has_label("person").add_label("employee")     // every person
  • Idempotent. Adding a label a vertex already carries, dropping one it does not carry, or setting the label an edge already has changes nothing and is no error; a traverser with bulk n changes its element once.
  • Wrong element kind. add_label/drop_label on an edge, set_label on a vertex, or any of them on a value (g.v().values("name").add_label("x")) fails; the help names the step for the kind that arrived.
  • Schema. With an open or closed schema the element must be valid under its new labels, or the step fails and the traversal rolls back: in closed mode the new label must be declared, a vertex may not lose its last label or keep a property no remaining label declares, and every connection (incident edges, an edge's endpoints) must stay declared; in both modes a newly applying label's required keys must be present and the stored values must have its declared types. Stored values are not coerced. See Schema Enforcement and Multi-Label Vertices.
  • Atomic. Like every traversal, a failing one leaves no label change behind (Transactions).
  • Permissions. add_label/drop_label ask Update on vertex data, set_label on edge data (Permissions).
  • A label containing "::" is rejected for vertices (the multi-label encoding of GraphSON and GraphML).

Selecting labeled and unlabeled elements

has_label() / hasLabel() without arguments keeps the elements that have a label at all: a vertex with a non-empty label set, an edge with a label (a vertex property is labeled with its key, so it always passes). Its complement not(__.has_label()) selects the unlabeled ones. There is no has_not_label(). TinkerPop has no zero-argument hasLabel(), so this is a Graphersal extension (TinkerPop Deviations); has_label([]) (an empty list) still keeps nothing. label() yields null for an unlabeled vertex, so not(__.label()) does not select them; use not(__.has_label()).

g.v().has_label().count().next()             // labeled vertices
g.v().not(__.has_label()).count().next()     // unlabeled vertices
g.e().not(__.has_label()).to_list()          // unlabeled edges

The optimizer never folds the zero-argument form into the source step (it is not an empty label list), and .profile() shows it as has_label().

A typical use is labelling unlabeled elements before freezing a closed schema (Freeze the structure you have):

g.v().not(__.has_label()).add_label("thing").to_list()
g.e().not(__.has_label()).set_label("link").to_list()
g.set_schema(g.infer_schema(), SchemaMode.closed)

Rust: add_label(label), drop_label(label), set_label(label) on GraphTraversalSource and __; they call GraphStorage::add_vertex_label, remove_vertex_label and set_edge_label.

Step-level with(WithOptions..)

with(WithOptions.key) / with(WithOptions.key, WithOptions.value) after a step configures that step (TinkerPop's Configuring steps). Two steps take an option:

StepOptionValues
valueMap()WithOptions.tokensnone given or all: id and label; ids; labels; none
index()WithOptions.indexerlist (default): [element, position] pairs; map: {position: element}
g.V("1").valueMap("name", "age").with(WithOptions.tokens, WithOptions.labels).next()
// {"label": "person", "name": ["marko"], "age": [29]}
g.V().hasLabel("person").values("name").fold().order(Scope.local).
  index().with(WithOptions.indexer, WithOptions.map).next()
// {0: "josh", 1: "marko", 2: "peter", 3: "vadas"}
  • WithOptions.keys/WithOptions.values select the key and value tokens of a vertex-property map in TinkerPop; valueMap() here reads vertices and edges only, so they add no token.
  • Any other step, an option the step does not know, or a with() with no step before it fails with InvalidModulator before the traversal runs.
  • with("key", value) with a string key is something else: an execution option of the whole traversal (g.with("random.seed", 7)), see the options reference.

The DSL spells the tokens WithOptions.tokens and WithOptions::tokens.

Rust: with_option(WithOptions::Tokens, Some(WithOptions::Labels)), with_option(WithOptions::Indexer, Some(WithOptions::Map)).

Step - add_e

add_e · addE · category: Changing the graph

Adds an edge with the given label; its endpoints come from from() and to() (see the book page addE() Endpoints).

Forms

add_e()
add_e(arg1: any)

Example

g.v(1).add_e("likes").to("3").label().next()   // likes

See also

Step - add_label

add_label · category: Changing the graph

Adds a label to the label set of each incoming vertex and passes it on (Graphersal extension; edges use set_label()).

Forms

add_label(arg1: string)

Example

g.v(1).add_label("employee").labels().next()   // ["person", "employee"]

See also

Step - add_v

addV(label) adds a vertex, addV([labels]) a vertex with several labels, addV() an unlabeled one. As a start step (g.addV(..)) it adds one vertex; in the middle of a traversal one per incoming traverser.

addV(traversal)

The label is the first result of a child traversal, run on the incoming traverser (on a null seed when the step starts the traversal), TinkerPop's AddVertexStep with a label traversal.

g.addV(__.V("1").label()).label()                                   // "person"
g.addV(__.constant("prefix_").concat(__.V("1").label())).label()   // "prefix_person"

The result must be a string; no result or another value is a cast error, and the traversal is rolled back. Directly following property(key, constant) calls fold into the step as for the other forms.

Rust: add_v(label), add_v_by(traversal).

Step - age

age · category: Dates and times

The difference as a duration (PostgreSQL age).

Forms

age(arg1: any)
age(arg1: any, arg2: string)

Example

g.inject(date("2001-04-10")).age(date("1957-06-13")).next().months   // 525

Step - aggregate

aggregate · category: Aggregation

Collects every incoming value into the named list side effect before passing them on (a barrier); read it with cap() or select().

Forms

aggregate(arg1: string)

Example

g.v().has_label("person").values("age").aggregate("ages").cap("ages").next()   // [29, 27, 32, 35]

See also

Step - all

all · category: Filters

Keeps a list whose every element matches the predicate (an empty list matches).

Forms

all(arg1: any)

Example

g.inject([1, 2, 3]).all(P.gt(0)).next()   // [1, 2, 3]

Step - and

and(a, b, ...) keeps a traverser when every child traversal produces a result for it.

g.V().and(__.outE("knows"), __.values("age").is(P.lt(30))).values("name")   // ["marko"]

The infix form a.and().b

and() with no argument is TinkerPop's infix notation, rewritten as TinkerPop's ConnectiveStrategy does before the traversal runs:

  • the left operand is every step before and(), back to the start of the traversal; the start step of the root traversal (V(), E(), inject(), ...) and the step labels it carries stay outside;
  • the right operand is every step after and() up to the end of the traversal; a further and() starts another operand (a.and().b.and().c is and(a, b, c));
  • and() binds tighter than or(): a.and().b.or().c is or(and(a, b), c).
g.V().where(__.out("created").and().out("knows").or().in("knows")).values("name")
// ["marko", "vadas", "josh"]
g.V().has("name", "marko").and().has("age", 29)              // v[1]

Because the right operand runs to the end, a step written after the infix form is part of it: g.V().has("name", "marko").and().has("age", 29).values("name") still yields the vertex, with values("name") inside the and(). Wrap the connective in a child traversal (filter(__.has(..).and().has(..)), where(..)) to continue after it.

Rust: the prefix form and(vec![a, b]); the infix form is a DSL notation.

Step - any

any · category: Filters

Keeps a list where at least one element matches the predicate.

Forms

any(arg1: any)

Example

g.inject([1, 5, 3]).any(P.gt(4)).next()   // [1, 5, 3]

Step - as

as · as_ · category: Labels and paths

Labels the current step so select(), where() and path() can refer back to it.

Forms

as(arg1: any)
as(arg1: array)
as(arg1: any, arg2: any)
as(arg1, …, arg10)

Example

g.v(1).as("a").out("knows").as("b").select("a", "b").by("name").next()   // #{"a": "marko", "b": "josh"}

Step - as_bool

as_bool · asBool · category: Strings and type conversion

Converts the value to a boolean: true/false strings in any case, numbers (0 is false); anything else is an error unless a CastPolicy says otherwise.

Forms

as_bool()
as_bool(arg1: CastPolicy)

Example

g.inject("true", "FALSE", 0).as_bool().to_list()   // [true, false, false]

See also

Step - as_date

as_date · asDate · category: Dates and times

Text or epoch milliseconds to a datetime (TinkerPop asDate()), or to a GType.

Forms

as_date()
as_date(arg1: GType)

Example

g.inject(0).as_date().next().year   // 1970

Step - as_duration

as_duration · category: Dates and times

Converts ISO 8601 text to a duration.

Forms

as_duration()

Example

g.inject("P1D").as_duration().next().days   // 1

Step - as_local

as_local · category: Dates and times

A datetime's wall clock.

Forms

as_local()
as_local(arg1: string)

Example

g.inject(datetime("2023-08-02T12:00Z")).as_local().next().hour   // 12

Step - as_number

as_number · asNumber · category: Strings and type conversion

Converts the value to a number, optionally of the given GType (GType.LONG truncates toward zero, see the book page Type Conversion and length()).

Forms

as_number()
as_number(arg1: GType)
as_number(arg1: GType, arg2: CastPolicy)

Example

g.inject("42", 3.9).as_number(GType.LONG).to_list()   // [42, 3]

See also

Step - as_string

as_string · asString · category: Strings and type conversion

Converts each value to its string text (Scope.local: each element of a list); a list itself is a cast error.

Forms

as_string()
as_string(arg1: CastPolicy)
as_string(arg1: Scope)

Example

g.v(1).values("age").as_string().to_list()   // ["29"]

See also

Step - as_vector

as_vector · category: Vectors

Converts a list of numbers to an f32 vector; a vector passes (see the book page Vectors).

Forms

as_vector()

Example

g.inject([0.5, 1]).as_vector().next()   // vector([0.5, 1.0])

Step - at_zone

at_zone · category: Dates and times

Places a date-time in a time zone: an IANA name ("Europe/Berlin") is kept in the result, a UTC offset ("+02:00") gives the offset only.

Forms

at_zone(arg1: string)

Example

g.inject(datetime("2023-08-02T12:00Z")).at_zone("Europe/Berlin").next().timezone   // Europe/Berlin

Step - barrier

barrier · category: Aggregation

Collects the whole stream before passing it on; equal traversers merge into one with a bulk (see the book page Bulk and Barriers).

Forms

barrier()
barrier(arg1: any)

Example

g.v().out().barrier().count().next()   // 6

See also

Step - both

both · category: Walking the graph

Moves to the adjacent vertices over incoming and outgoing edges, optionally only edges with the given labels.

Forms

both()
both(arg1: any)
both(arg1: array)
both(arg1: any, arg2: any)
both(arg1, …, arg10)

Example

g.v(4).both("knows").values("name").to_list()   // ["marko"]

Step - both_e

both_e · bothE · category: Walking the graph

Moves to the incident edges in both directions, optionally only edges with the given labels.

Forms

both_e()
both_e(arg1: any)
both_e(arg1: array)
both_e(arg1: any, arg2: any)
both_e(arg1, …, arg10)

Example

g.v(4).both_e().label().to_list()   // ["knows", "created", "created"]

Step - both_v

both_v · bothV · category: Walking the graph

Moves from an edge to both of its endpoint vertices (out vertex first).

Forms

both_v()

Example

g.e("0").both_v().values("name").to_list()   // ["marko", "vadas"]

Step - branch

branch · category: Branches and loops

Routes each traverser by the value its child traversal yields to the matching option().

Forms

branch(arg1: any)

Example

g.v(1, 2).branch(__.values("age")).option(29, __.values("name")).option(Pick.none, __.constant("other")).to_list()   // ["marko", "other"]

See also

Step - by

by() modulates the step right before it: what to read from each traverser, or how to sort or group it. The arguments and the steps that take by() are described in The by() Modulator.

by("label") and by(T.label)

A string is always a property key: by("label") and by("id") read a property of that name (as in TinkerPop) and are unproductive on an element without one. The element's label and id are the tokens by(T.label) and by(T.id). See Properties Named id or label.

g.V().groupCount().by(T.label).next()    // {"person": 4, "software": 2}
g.V().groupCount().by("label").next()    // {}: no vertex has a property named label

by() without an argument

A bare by() is the identity: TinkerPop's by() is by(__.identity()), and Graphersal lowers it to exactly that child traversal.

g.V("1").as("a").values("name").as("b").select("a", "b").by(T.label).by().next()
// {"a": "person", "b": "marko"}
g.V().values("name").fold().order(Scope.local).by()          // the same as order(Scope.local)
g.V().repeat(__.out()).times(2).path().by().by("name").by("lang")

In group() a bare value by() collects the members of each key as a list, as TinkerPop's GroupStep does for an identity value traversal (map(identity).fold()), instead of keeping one member: g.V().group().by(T.label).by() maps person to its four vertices.

Rust: by(__::identity()).

Step - cap

cap · category: Aggregation

Emits the value of the named side effect(s) (one map for several keys) after the stream is exhausted.

Forms

cap()
cap(arg1: any)
cap(arg1: array)
cap(arg1: any, arg2: any)
cap(arg1, …, arg10)

Example

g.v().group_count("c").by(T.label).cap("c").next()   // #{"person": 4, "software": 2}

Step - cast

cast · category: Strings and type conversion

Converts the value to the given GType (number, string, boolean, uuid, list, map), optionally with a CastPolicy for values that do not convert.

Forms

cast(arg1: GType)
cast(arg1: GType, arg2: CastPolicy)

Example

g.inject("1", "2").cast(GType.LONG).sum().next()   // 3

Step - choose

choose · category: Branches and loops

If-then-else: runs the true or false child traversal depending on a predicate or child traversal; with one argument it picks an option() by value.

Forms

choose(arg1: any)
choose(arg1: any, arg2: any)
choose(arg1: any, arg2: any, arg3: any)

Example

g.v(1, 4).choose(__.values("age").is(P.gt(30)), __.constant("old"), __.constant("young")).to_list()   // ["young", "old"]

See also

Step - coalesce

coalesce · category: Branches and loops

Runs the child traversals in order and emits the results of the first one that yields anything.

Forms

coalesce(arg1: any)
coalesce(arg1: any, arg2: any)
coalesce(arg1, …, arg10)

Example

g.v(1, 3).coalesce(__.values("age"), __.values("lang")).to_list()   // [29, "java"]

Step - coin

coin · category: Filters

Keeps each traverser with the given probability (0.0 to 1.0); seed it with g.with("random.seed", n).

Forms

coin(arg1: f64)
coin(arg1: i64)

Example

g.v().coin(1.0).count().next()   // 6

Step - combine

combine(list) appends a second list to the list a traverser holds. Duplicates and order are kept. The incoming value must be a list (see List Functions for the input and argument rules shared by all list functions).

graphersal> g.V().values("name").fold().combine(["dave", "marko"])
[marko, vadas, lop, josh, ripple, peter, dave, marko]

graphersal> g.V().out().out().path().by("name").combine(["dave"])
[marko, josh, ripple, dave]
[marko, josh, lop, dave]

graphersal> g.inject([1, 2]).combine(__.constant([2, 3]))
[1, 2, 2, 3]

Rust: combine(vec!["dave"]) and combine_traversal(__::constant(vec![2, 3])).

The set counterpart, which keeps each element once, is merge.

Step - compressions

compressions · category: Compressed properties

Lists the compression rules as maps: name, element, label, path, codec, min_bytes, dictionary, served (with reason when not applied) and the current compressed_values, plain_bytes, stored_bytes, dictionary_bytes.

Forms

compressions()

Example

{ g.define_compression(#{name: "bio", label: "person", path: "details.bio"}); g.compressions().map(|r| r.path) }   // ["$.details.bio"]

See also

Step - concat

concat(string...) appends strings to the string a traverser holds; concat(traversal...) appends the first result of each child traversal, run on the incoming traverser (its path included). The arguments are all strings or all traversals. Without an argument the string passes unchanged.

graphersal> g.V().hasLabel("software").as("s").values("name").concat(" uses ").concat(__.select("s").values("lang")).to_list()
"lop uses java"
"ripple uses java"

graphersal> g.V("1").outE("created").as("e").V("1").values("name").concat(__.select("e").label(), __.select("e").inV().values("name")).to_list()
"markocreatedlop"

graphersal> g.inject("a").concat(__.inject("c")).to_list()
"aa"

The last example shows the first-result rule: __.inject("c") yields the incoming "a" first.

null

A null is skipped wherever it occurs, as the incoming value, as a constant (() in Rhai) or as a child result. The result is null only when everything was null:

graphersal> g.inject((), "a").concat((), "b").to_list()
"b"
"ab"

graphersal> g.inject(()).concat().to_list()
()

Errors

  • An incoming value that is neither a string nor null is a cast error. Convert it first, for example values("age").as_string().concat(" years old").
  • A constant argument that is neither a string nor null (concat(1)) is rejected before the traversal runs.
  • A child traversal that yields nothing, or a value that is not a string, is a ValueError::StringFunctionInput. Make the child always produce a string, for example with coalesce(..., constant("")) or as_string().

Rust API: concat(vec!["a", "b"]) (a null argument is ElementProperty::Null) and concat_traversal(vec![__::select("a").values("lang")]).

Step - conjoin

conjoin(delimiter) joins the elements of the list a traverser holds into one string, with delimiter between two elements. null elements are skipped (no delimiter is written for them), and an empty list gives the empty string. The incoming value must be a list (a fold(), a path(), a list constant or property; see List Functions).

graphersal> g.V().values("age").order().fold().conjoin(";")
27;29;32;35

graphersal> g.V("1").out().path().by("name").conjoin(" -> ")
marko -> josh
marko -> lop
marko -> vadas

graphersal> g.inject(["a", (), "b"]).conjoin("+")
a+b

Each element is written as as_string() writes it: numbers (27, 2.5), booleans, UUIDs and strings as their text, a vertex as v[1], an edge as e[7][1-knows->2].

Deviation from TinkerPop

A nested list or a map inside the list has no string form in Graphersal: conjoin() fails with a cast error there, where TinkerPop writes Java's toString text ([a, b], {k=v}). Graphersal never produces Java formats as data text (the same rule as for asString() of a map); unfold or conjoin() the inner list first. No scenario of the TinkerPop suite covers the case.

Step - constant

constant · category: Values and properties

Replaces every incoming value with the given constant.

Forms

constant(arg1: any)

Example

g.v().has_label("software").constant("app").to_list()   // ["app", "app"]

Step - count

count · category: Aggregation

Counts the traversers (bulk included); with Scope.local counts the elements of each incoming collection.

Forms

count()
count(arg1: Scope)

Example

g.v().has_label("person").count().next()   // 4

Step - create_index

create_index · category: Property indexes

Declares a property index #{key, label, element, name, type, transform, unique}: a v() or e() with that label and a has() on that key then reads the index instead of every element of the label; without label the index is label-less (every element of the kind) and serves a has() with any or no label; type defaults to "memory-ordered", transform "to_lower" indexes lowered strings for has(key, __.to_lower().is(..)), "each" every element of an array value for has(key, __.unfold().is(..)), a chain is an array applied in order (["each", "to_lower"]); unique: true refuses every write that would repeat a value (null exempt; not with each) (see the book page Property Indexes).

Forms

create_index(arg1: any)

Example

{ g.v(1).property("tags", ["a", "b"]).iterate(); g.create_index(#{key: "tags", transform: "each"}); g.v().has("tags", __.unfold().is("b")).values("name").to_list() }   // ["marko"]

Step - cyclic_path

cyclic_path · cyclicPath · category: Filters

Keeps only traversers whose path visits some element twice.

Forms

cyclic_path()

Example

g.v(1).out().in().cyclic_path().count().next()   // 3

Step - date_add

date_add · dateAdd · category: Dates and times

Adds n DT units or a duration, optionally in a zone whose IANA name the result keeps (TinkerPop dateAdd()).

Forms

date_add(arg1: duration)
date_add(arg1: DT, arg2: i64)
date_add(arg1: duration, arg2: string)
date_add(arg1: DT, arg2: i64, arg3: string)

Example

g.inject(date("2024-01-31")).date_add(DT.month, 1).next().day   // 29

Step - date_diff

date_diff · dateDiff · category: Dates and times

Difference in milliseconds (TinkerPop dateDiff()) or whole DT units.

Forms

date_diff(arg1: any)
date_diff(arg1: any, arg2: DT)
date_diff(arg1: any, arg2: DT, arg3: string)

Example

g.inject(time("10:00")).date_diff(time("09:00"), DT.hour).next()   // 1

Step - date_part

date_part · category: Dates and times

One field as a number (PostgreSQL extract).

Forms

date_part(arg1: DT)
date_part(arg1: DT, arg2: string)

Example

g.inject(date("2023-08-17")).date_part(DT.day_of_week).next()   // 4

Step - date_trunc

date_trunc · category: Dates and times

Truncates to a DT unit (PostgreSQL date_trunc).

Forms

date_trunc(arg1: DT)
date_trunc(arg1: DT, arg2: string)

Example

g.inject(date("2023-08-17")).date_trunc(DT.month).next().day   // 1

Step - dedup

dedup() keeps the first traverser of each distinct object, in stream order; one by() makes the key a projection of the object. dedup(Scope.local) removes duplicates inside the list each traverser holds. The rules are in the rustdoc of GraphTraversalSource::dedup.

dedup("a", "b", ...)

With step labels the key is the list of the objects last labelled so on each traverser's path, each projected by the by() when there is one (TinkerPop's DedupGlobalStep with dedup labels).

g.V().as("a").both().as("b").dedup("a", "b").by(T.label).select("a", "b").by("name")
// {"a": "marko", "b": "josh"}, {"a": "marko", "b": "lop"}, {"a": "lop", "b": "peter"}
  • One traverser survives per distinct combination; its bulk is reset to 1, as for dedup().
  • The by() runs on each labelled object as a fresh traverser.
  • A traverser whose by() yields nothing is filtered out. Deviation from TinkerPop: a traverser that lacks one of the labels is filtered out too, where TinkerPop raises an error.
  • dedup(Scope.local, "a") ignores the labels, as TinkerPop does.

Rust: dedup_scoped_labels(Scope::Global, ["a", "b"]).

Step - define_compression

define_compression · category: Compressed properties

Stores (or replaces) a compression rule #{name, label, path, element, codec, min_bytes, dictionary}: strings at that path are kept compressed in memory (codec "lz4") or stored once per distinct value (codec "dedup") and read plain (see the book page Compressed Properties).

Forms

define_compression(arg1: any)

Example

{ g.define_compression(#{name: "n", label: "person", path: "name"}); g.compressions().len() }   // 1

See also

Step - define_compressions

define_compressions · category: Compressed properties

Stores a list of compression rules in one commit and re-encodes their labels in one walk: each item a define_compression map, or #{label, paths: [..], codec, ..} for one rule per path named

Forms

define_compressions(arg1: any)

Example

{ g.define_compressions([#{label: "person", paths: ["name", "age"], codec: "dedup"}, #{name: "sw_lang", label: "software", path: "lang", codec: "dedup"}]); g.compressions().map(|r| r.name) }   // ["person_age", "person_name", "sw_lang"]

See also

Step - define_job

define_job · category: Scheduled jobs

Defines (or replaces) a scheduled job: on a 5-field cron schedule it calls a saved query, writes a checkpoint or takes a backup of the store, with the definer's rights checked now and stored (Graphersal extension).

Forms

define_job(arg1: any)

Example

{ g.define_job(#{name: "nightly", schedule: "0 3 * * *", action: "checkpoint"}); g.jobs().map(|j| j.name) }   // ["nightly"]

Step - define_queries

define_queries · category: Saved queries

Stores every function of a Rhai source as a saved query in a folder, described by its doc comment; params maps function name -> its parameter map (see the book page Saved Queries).

Forms

define_queries(arg1: any, arg2: string)
define_queries(arg1: any, arg2: string, arg3: any)

Example

{ g.define_queries("reports", "/** Persons. */ fn people() { g.v().has_label(\"person\") }"); g.query("people").count().next() }   // 4

See also

Step - define_query

define_query · category: Saved queries

Stores (or replaces) a saved query: #{name, body, language, folder, description, params}, the body being one Rhai function named like the query, or with language: "gql" one GQL query reading the declared $params; a body that writes data saves a query that writes (see the book page Saved Queries).

Forms

define_query(arg1: any)

Example

{ g.define_query(#{name: "older", params: #{min: #{schema: #{type: "integer"}, default: 30}}, body: "fn older(min) { g.v().has(\"age\", P.gt(min)) }"}); g.query("older").count().next() }   // 2

See also

Step - describe_query

describe_query · category: Saved queries

Sets the description of a saved query ("" or () removes it).

Forms

describe_query(arg1: string, arg2: any)

Example

{ g.define_query(#{name: "n", body: "fn n() { 1 }"}); g.describe_query("n", "One."); g.get_query("n")["description"] }   // One.

See also

Step - diff_schema

diff_schema · category: Schema

Compares the stored schema with the given schema map: {changes, compatible}.

Forms

diff_schema(arg1: any)

Example

g.diff_schema(g.infer_schema())["compatible"]   // true

See also

Step - difference

difference(list) keeps the elements of the list a traverser holds that are not in list. The result is a set: each element at most once, in the order of its first occurrence. Elements compare like dedup() compares traversers (see List Functions).

graphersal> g.V().values("age").fold().difference([27, 29])
[32, 35]

graphersal> g.V().out().out().path().by("name").difference(["ripple"])
[marko, josh]
[marko, josh, lop]

graphersal> g.inject(["a", (), "b"]).difference(["a", "c"])
[null, b]

Rust: difference(vec![27, 29]) and difference_traversal(__::v(None).values("age").fold()).

Step - discard

discard() filters out every traverser. It is TinkerPop 3.8's name for the step that older versions (and Graphersal before 0.1.0) called none(); none(P) is now a list predicate.

g.V().hasLabel("person").discard().to_list()          // []
g.V().discard().fold().to_list()                      // [[]]: fold() still emits its seed
g.V().project("x").by(__.coalesce(__.values("age").is(P.gt(29)), __.discard())).select("x").to_list()
// [32, 35]

The last query uses discard() as the "drop it" branch of coalesce(): a vertex younger than 30 (or without an age) produces nothing, so project()'s by() is unproductive and the vertex is dropped. discard() is also the usual option(Pick.none, __.discard()) of choose().

Rust: GraphTraversalSource::discard(), __::discard().

Step - disjunct

disjunct(list) is the symmetric difference: the elements that are in exactly one of the list a traverser holds and list. The result is a set: first the incoming elements that are not in list, then the elements of list that are not in the incoming list, each at most once (see List Functions for element equality).

graphersal> g.V().values("age").fold().disjunct([27, 40])
[29, 32, 35, 40]

graphersal> g.inject(["a", (), "b"]).disjunct(["a", "c"])
[null, b, c]

Rust: disjunct(vec![27, 40]) and disjunct_traversal(__::v(None).values("age").fold()).

Step - drop

drop · category: Changing the graph

Removes the incoming vertices, edges or properties from the graph (a vertex takes its edges with it) and yields nothing (see the book page Dropping Elements).

Forms

drop()

Example

{ g.v(1).out_e("knows").drop().to_list(); g.e().count().next() }   // 4

See also

Step - drop_compression

drop_compression · category: Compressed properties

Removes a compression rule and decompresses its values; false when there is none.

Forms

drop_compression(arg1: string)

Example

{ g.define_compression(#{name: "bio", label: "person", path: "bio"}); g.drop_compression("bio") }   // true

See also

Step - drop_compressions

drop_compressions · category: Compressed properties

Removes a list of compression rules in one commit and decompresses their values in one walk; a name not stored is skipped, answers the number of rules removed (see the book page Compressed Properties).

Forms

drop_compressions(arg1: any)

Example

{ g.define_compressions([#{label: "person", paths: ["name", "age"], codec: "dedup"}]); g.drop_compressions(["person_name", "person_age", "none"]) }   // 2

See also

Step - drop_index

drop_index · category: Property indexes

Drops a property index; false when there is none.

Forms

drop_index(arg1: string)

Example

{ g.create_index(#{label: "person", key: "age"}); g.drop_index("person_age") }   // true

Step - drop_job

drop_job · category: Scheduled jobs

Removes a scheduled job; false when there is none (Graphersal extension).

Forms

drop_job(arg1: string)

Example

{ g.define_job(#{name: "nightly", schedule: "0 3 * * *", action: "checkpoint"}); g.drop_job("nightly") }   // true

Step - drop_label

drop_label · category: Changing the graph

Removes a label from the label set of each incoming vertex and passes it on; the last one leaves it unlabeled (Graphersal extension).

Forms

drop_label(arg1: string)

Example

g.v(1).drop_label("person").labels().next()   // []

See also

Step - drop_query

drop_query · category: Saved queries

Removes a saved query; false when there is none.

Forms

drop_query(arg1: string)

Example

{ g.define_query(#{name: "n", body: "fn n() { 1 }"}); g.drop_query("n") }   // true

See also

Step - e

e · E · category: Start

Starts at the edges of the graph, all or the ones with the given ids.

Forms

e()
e(arg1: any)
e(arg1: array)
e(arg1: any, arg2: any)
e(arg1, …, arg10)

Example

g.e().has_label("created").count().next()   // 4

See also

Step - element

element · category: Values and properties

Moves from a property to the vertex or edge that owns it.

Forms

element()

Example

g.v(1).properties("name").element().values("age").next()   // 29

Step - element_map

element_map · elementMap · category: Values and properties

Turns each vertex or edge into a map of the T.id and T.label tokens (an edge also Direction.OUT and Direction.IN) and the given (or all) properties, written "id", "label", "OUT", "IN" outside the engine where a property of the same name wins (see the book page Properties Named id or label).

Forms

element_map()
element_map(arg1: any)
element_map(arg1: array)
element_map(arg1: any, arg2: any)
element_map(arg1, …, arg10)

Example

g.v(1).element_map("name").next()   // #{"id": "1", "label": "person", "name": "marko"}

Step - embed

embed · category: Vectors

Embeds the incoming string, or the string property key, as a vector; #{embedder: name} picks the embedder (default hash-ngram/1).

Forms

embed()
embed(arg1: any)
embed(arg1: any, arg2: map)

Example

g.v().has("name", "marko").embed("name").next().dimension   // 256

Step - embedders

embedders · category: Vectors

Lists the embedders of the database, the built-in hash-ngram/1 and its imported models (name, model, dimension, element, metric, ...), the default first.

Forms

embedders()

Example

g.embedders()[0].name   // hash-ngram/1

Step - emit

emit · category: Branches and loops

Within repeat(): also emits the traversers of intermediate iterations (all, or those that match the child traversal or predicate).

Forms

emit()
emit(arg1: any)

Example

g.v(1).repeat(__.out()).times(2).emit().values("name").to_list()   // ["josh", "lop", "vadas", "ripple", "lop"]

See also

Step - estimate_compression

estimate_compression · category: Compressed properties

Measures what compression rules for a label and path would save on the current values (lz4 with and without a dictionary at several min_bytes, or the given ones; codec: "dedup" or ["lz4", "dedup"] measures deduplication too), without changing the graph.

Forms

estimate_compression(arg1: any)

Example

{ let e = g.estimate_compression(#{label: "person", path: "name"}); [e.values_found, e.candidates.len(), e.warnings[0].code] }   // [4, 10, "nothing_qualifies"]

See also

Step - execute

execute · category: Running and showing results

Runs the traversal and returns an Execution with results, error and optionally the profile; it never throws (see the book page Profiling and execute()).

Forms

execute()
execute(arg1: any)

Example

g.v().count().execute().results   // [6]

See also

Step - export_graphml

export_graphml · category: Graph information and files

Writes the whole graph to a GraphML file at the given path (needs file access).

Forms

export_graphml(arg1: string)

Example

g.export_graphml("modern.graphml")

Step - export_graphson

export_graphson · category: Graph information and files

Writes the whole graph to a GraphSON file at the given path (needs file access).

Forms

export_graphson(arg1: string)

Example

g.export_graphson("modern.json")

See also

Step - export_snapshot

export_snapshot · category: Graph information and files

Writes the whole graph to a packed snapshot file (.gsnap) at the given path (needs file access).

Forms

export_snapshot(arg1: string)

Example

g.export_snapshot("modern.gsnap")

See also

Step - fail

fail() and fail(message) stop the whole traversal with an error as soon as a traverser reaches the step (TinkerPop FailStep). Use it to assert that a branch is never taken.

g.V().fail("msg").to_list()
// Error: ... Caused by: msg (fail() reached by v[1])

g.V().coalesce(__.values("name"), __.fail("no name")).count().next()   // 6: fail() is never reached
g.V().union(__.out(), __.fail()).to_list()
// Error: ... Caused by: fail() step triggered (fail() reached by v[1])
  • The error is TraverserError::Fail, with the message (fail() step triggered without one) and a short rendering of the value that reached the step (v[1], e[7], or the JSON text of a value). Its help() shows how to guard the step with coalesce() or choose().
  • Like every failing traversal, a traversal that changed the graph before fail() is rolled back as a whole (see Transactions).
  • fail() is a side-effect step: the optimizer never moves a filter across it, so only the traversers that reach it as written fail the query.

Rust: GraphTraversalSource::fail(None | Some(message)), __::fail(..).

Step - filter

filter · category: Filters

Keeps the traverser when the child traversal yields a result (or the predicate matches).

Forms

filter(arg1: any)

Example

g.v().filter(__.out_e("created")).values("name").to_list()   // ["marko", "josh", "peter"]

Step - flatMap

flatMap(traversal) (also flat_map) replaces each traverser by every result of a child traversal run on it (TinkerPop FlatMapStep). A traverser for which the child yields nothing is dropped.

g.V("1").flatMap(__.out().values("name")).to_list()    // ["josh", "lop", "vadas"]
g.V().flatMap(__.out().out()).path().by("name").to_list()
// [["marko", "ripple"], ["marko", "lop"]]
g.V().local(__.out().out()).path().by("name").to_list()
// [["marko", "josh", "ripple"], ["marko", "josh", "lop"]]

The last two queries show the difference to local(): flatMap() hides the child's steps from path() (each result is one new position after the incoming path), while local() continues the child's own path.

  • The child sees the incoming traverser with its path, sack and labels.
  • Bulk is kept: the results of a merged traverser carry its bulk.

For only the first result, use map().

Rust: GraphTraversalSource::flat_map(traversal), __::flat_map(traversal).

Step - fold

fold · category: Lists and ordering

Collects the whole stream into one list; with a seed and an Operator it reduces the stream instead.

Forms

fold()
fold(arg1: any, arg2: any)

Example

g.v().has_label("person").values("age").fold(0, Operator.sum).next()   // 123

See also

Step - format

format(pattern) builds a string from pattern. Each %{name} placeholder is replaced by a value read from the incoming traverser.

graphersal> g.V().format("%{name} is %{age} years old").to_list()
"marko is 29 years old"
"vadas is 27 years old"
"josh is 32 years old"
"peter is 35 years old"

The two software vertices have no age, so they are filtered out.

Resolving a placeholder

%{name} is looked up in this order:

  1. the property name of an incoming vertex or edge;
  2. as select(name) resolves it: the key name of an incoming map (elementMap(), project()), then a side-effect key, then the last path value labelled name (as("name")).
graphersal> g.V().hasLabel("person").as("a").values("name").as("p1").select("a").in("knows").format("%{p1} knows %{name}").to_list()
"vadas knows marko"
"josh knows marko"

%{_} takes the next by() modulator. The by()s form a ring: they are used round robin, and the ring restarts for every traverser. Without a by(), %{_} is the incoming value itself.

graphersal> g.V().format("%{name} has %{_} connections").by(__.bothE().count()).to_list()
"marko has 3 connections"
"vadas has 1 connections"
"lop has 3 connections"
"josh has 3 connections"
"ripple has 1 connections"
"peter has 1 connections"

graphersal> g.V("1").format("%{_} %{_} %{_}").by(__.constant("hello")).by("name").to_list()
"hello marko hello"

When a placeholder resolves to nothing or to null (a missing property or label, an unproductive by(), a null map or path value), the traverser is filtered out. A stored null property is present, so it is written as the text null, as in TinkerPop (g.V("1").property("nick", ()) then g.V("1").format("%{name} aka %{nick}") gives "marko aka null"). %%{x} is not a placeholder and stays in the output as written, and so does a %{ without a closing } on the same line.

Value text

A value is written as as_string() writes it: 29, true, a UUID as its canonical text, a vertex as v[1]. A list or a map has no string form here, so format() fails with a cast error. This is the same deviation as for conjoin(): TinkerPop writes Java's toString text, and no suite scenario covers the case.

Step - from

from · category: Modulators and options

Sets the out vertex of the edge add_e() creates: a vertex, a vertex id, a path label or a child traversal; for path() it starts the window at a label.

Forms

from(arg1: any)
from(arg1: array)

Example

g.add_e("knows").from("2").to("4").out_v().values("name").next()   // vadas

Step - get_query

get_query · category: Saved queries

Returns a saved query as a map (name, folder, description, language, dialect, params, status, writes, effects, denied_writes, body, meta), unit when there is none.

Forms

get_query(arg1: string)

Example

{ g.define_query(#{name: "add", body: "fn add() { g.add_v(\"person\").next() }"}); g.get_query("add")["effects"].map(|e| e.text) }   // ["Create Data(vertex \"person\")"]

See also

Step - get_schema

get_schema · category: Schema

Returns the graph's stored schema as a map (unit when none is stored).

Forms

get_schema()

Example

g.get_schema() == ()   // true

See also

Step - glob_path

glob_path(pattern) walks the tree below each incoming vertex along a filesystem-style glob pattern and emits every vertex the pattern matches:

g.v("root").glob_path("**/author/*/some/*.rs").by("name").by(["directory","file"])

It is a Gremlin extension: TinkerPop has no such step, and a query that uses it does not run on other Gremlin servers. It makes nothing newly possible (see Equivalents), but it turns a common tree query into one short step. The step prunes every branch as soon as the pattern can no longer match there, emits each match once, and stops on cycles.

  • pattern: /-separated segments; each segment matches one level below the incoming vertex.
  • First by() (required): the match key, which a named segment is compared with: a property key such as by("name"), the vertex id or the vertex labels.
  • Second by() (optional): a list of vertex labels; the walk only visits vertices that carry one of them.

Every example on this page runs on the file_tree sample graph and shows the output of graphersal --graph tree. The step's output order is unspecified, so the examples sort with order().by(T.id) where there is more than one result.

Quick start

Start the CLI on the sample tree:

graphersal --graph tree

The graph is a small filesystem. Vertex ids are paths from root, the labels are directory, file and symlink, the name property holds the file name, and contains edges point from a directory to its entries. Two points_to edges add a cycle and a second route to root/author:

root                                   directory
├── author
│   ├── x
│   │   └── some
│   │       ├── f.rs                   file
│   │       └── readme.md              file
│   └── q
│       └── author
│           └── w
│               └── some
│                   └── h.rs           file
├── y
│   ├── author
│   │   └── z
│   │       └── some
│   │           └── g.rs               file
│   └── loop                           symlink ──points_to──▶ root        (a cycle)
├── src
│   ├── main.rs  lib.rs  test_a.rs  test_b.rs
│   └── util
│       ├── mod.rs
│       └── io.rs
├── docs
│   └── guide.md  notes.txt  data[1].csv  résumé.md
├── #unnamed                           directory without a name property
│   └── orphan.rs
├── #42                                directory whose name is the int64 42
│   └── answer.rs
├── #slash                             directory named "a/b"
│   └── c.rs
└── latest                             symlink ──points_to──▶ root/author (a diamond)

Every unmarked entry with children is a directory, every other one a file. The id of each vertex is the path of names from root, for example root/src/util/io.rs; the three directories marked # have the ids root/#unnamed, root/#42 and root/#slash.

Find every Rust file two levels below any author directory, where the level in between is some:

g.v("root").glob_path("**/author/*/some/*.rs").by("name").by(["directory","file"]).order().by(T.id).id().to_list()
"root/author/q/author/w/some/h.rs"
"root/author/x/some/f.rs"
"root/y/author/z/some/g.rs"

** crosses any number of levels, so the nested root/author/q/author/... is found too. The second by() keeps the walk on directories and files: it never follows a symlink.

The step can be chained, and used in child traversals like any other step:

g.v("root").glob_path("src").by("name").glob_path("util/*").by("name").order().by(T.id).id().to_list()
"root/src/util/io.rs"
"root/src/util/mod.rs"
g.v("root").glob_path("*").by("name").by(["directory"]).where(__.glob_path("*.md").by("name")).id().to_list()
"root/docs"

Pattern syntax

A pattern is a list of segments separated by /. Segment k matches the vertices k levels below the incoming vertex. A segment with at least one character that is not * is a named segment: it reads the match key of the vertex and compares it with the segment. * and ** alone never read the key.

Each row below is the query g.v("root").glob_path(PATTERN).by("name").order().by(T.id).id().to_list() with the pattern of that row:

ConstructMeaningPatternMatches on file_tree
literalexactly this valuesrc/main.rsroot/src/main.rs
*any value, including the empty onesrc/*root/src/lib.rs, root/src/main.rs, root/src/test_a.rs, root/src/test_b.rs, root/src/util
* inside a segmentany sequence of characterssrc/util/*.rsroot/src/util/io.rs, root/src/util/mod.rs
?exactly one character (a Unicode character, not a byte)src/test_?.rsroot/src/test_a.rs, root/src/test_b.rs
? with non-ASCIIé is one characterdocs/r?sum?.mdroot/docs/résumé.md
leading **zero or more levels**/srcroot/src
leading **zero or more levels**/utilroot/src/util
inner **zero or more levelsauthor/**/h.rsroot/author/q/author/w/some/h.rs
trailing **one or more levels: everything below, not the level itselfsrc/**root/src/lib.rs, root/src/main.rs, root/src/test_a.rs, root/src/test_b.rs, root/src/util, root/src/util/io.rs, root/src/util/mod.rs
[..]one character of the setsrc/test_[ab].rsroot/src/test_a.rs, root/src/test_b.rs
[!..]one character not in the setsrc/test_[!a].rsroot/src/test_b.rs
[a-z]one character of the rangesrc/[a-m]*.rsroot/src/lib.rs, root/src/main.rs
{a,b}one of the alternativessrc/{main,lib}.rsroot/src/lib.rs, root/src/main.rs
several {..}every combinationdocs/{guide,notes}.{md,txt}root/docs/guide.md, root/docs/notes.txt
empty alternativethe group may match nothingdocs/guide{,s}.mdroot/docs/guide.md
{..} per segmentgroups choose within their own segment{src,docs}/{m,g}*root/docs/guide.md, root/src/main.rs
\the next character is literaldocs/data\[1\].csvroot/docs/data[1].csv
\/a / inside one value, not a separatora\/b/c.rsroot/#slash/c.rs
casematching is case-sensitivedocs/*.MDnothing

Details:

  • ** must be a whole segment; a** or **b is an error. A run such as **/** counts as one **.
  • A ] right after [ or [! is a literal member of the set, so []] matches ]. A stray ], } or , outside a class or alternatives is an ordinary character.
  • Alternatives cannot be nested and cannot contain /. The {..} groups of one segment expand to their product, at most 256 alternatives.
  • A pattern has at most 63 segments, after collapsing **/**.
  • . and .. as whole segments are reserved (see Limitations and reserved extensions); \. matches a value that is literally ..
  • A pattern cannot be empty, start or end with /, or contain //.
  • In a Rhai or Rust string literal the backslash itself must be escaped: the pattern docs/data\[1\].csv is written "docs/data\\[1\\].csv" (or r"docs/data\[1\].csv" in Rust):
g.v("root").glob_path("docs/data\\[1\\].csv").by("name").id().to_list()
"root/docs/data[1].csv"

Every violation fails with a positioned error; see Errors.

The by() modulators

The by() modulators of glob_path() are positional, like group().by(key).by(value):

PositionRequiredAccepts
1st by()yesthe match key: a property key (by("name")), the vertex id (by(T.id)) or the vertex labels (by(T.label))
2nd by()noa non-empty list of vertex labels (by(["directory","file"]))

In Rust the tokens are By::Id and By::Label.

Match on the id. Here a segment is compared with the full vertex id. Inside one segment * also matches /, so an id's / is written \/ in the pattern:

g.v("root").glob_path("**/*\\/util\\/*").by(T.id).order().by(T.id).id().to_list()
"root/src/util/io.rs"
"root/src/util/mod.rs"

Match on the label. A named segment matches when any of the vertex's labels matches:

g.v("root").glob_path("**/symlink").by(T.label).order().by(T.id).id().to_list()
"root/latest"
"root/y/loop"

Restrict the walk by label. With a second by(), every vertex the walk visits below the start must carry one of the listed labels. A vertex without one is neither emitted nor walked through:

g.v("root").glob_path("src/*").by("name").by(["directory"]).id().to_list()
"root/src/util"

Invalid combinations. Anything else fails when the traversal runs, with InvalidModulator naming the position of the offending by():

WrittenError (Caused by: line)Fix
glob_path("*")`glob_path()` cannot use its by() #1: glob_path() needs a first by() naming the match keyAdd the match key as the first by().
glob_path("*").by(["directory"])`glob_path()` cannot use its by() #1: the first by() is the match key; the vertex-label list goes into the second by()The first by() is the key and the label list goes second: put a key such as by("name") before the label list.
glob_path("*").by(__.values("name"))`glob_path()` cannot use its by() #1: the match key must be a property key, T.id or T.labelA traversal, an order, a JSON path, Value or Count cannot be the match key.
glob_path("*").by("name").by("name")`glob_path()` cannot use its by() #2: the second by() must be a list of vertex labelsThe second by() only filters by vertex label: pass a list such as by(["directory", "file"]), or drop it to visit every vertex.
glob_path("*").by("name").by([])`glob_path()` cannot use its by() #2: the vertex-label list is emptyAn empty label list would admit no vertex: list at least one label, or drop the second by() to visit every vertex.
glob_path("*").by("name").by(["file"]).by(T.id)`glob_path()` cannot use its by() #3: glob_path() takes at most two by() modulatorsThere is no third by(): drop it.

Options

glob_path(pattern, #{...}) takes a map of options after the pattern. Each option is independent and optional; glob_path(pattern) is the same as glob_path(pattern, #{}). The by() modulators stay the same.

OptionValueEffect
max_depthan integer from 1never visit a vertex more than this many levels below the start vertex
prunean anonymous traversaldo not descend into a visited vertex for which it yields a result

In Rust the options are a GlobPathOptions built with max_depth(n) and prune(traversal), passed to glob_path_with(pattern, options); see Rust API.

max_depth. The start vertex is level 0, its children are level 1. With max_depth: n a vertex deeper than level n is not visited at all: it is not emitted, not walked through, and its key is never read. The bound applies to the whole walk, not only to **. max_depth: 1 visits exactly the children of the start vertex:

g.v("root").glob_path("**", #{max_depth: 1}).by("name").order().by(T.id).id().to_list()
"root/#42"
"root/#slash"
"root/#unnamed"
"root/author"
"root/docs"
"root/latest"
"root/src"
"root/y"

The Rust files at most two levels down:

g.v("root").glob_path("**/*.rs", #{max_depth: 2}).by("name").order().by(T.id).id().to_list()
"root/#42/answer.rs"
"root/#slash/c.rs"
"root/#unnamed/orphan.rs"
"root/src/lib.rs"
"root/src/main.rs"
"root/src/test_a.rs"
"root/src/test_b.rs"

A vertex that several routes reach, such as root/author (directly and through root/latest), counts at the depth of its shortest route within the bound, so no match within the bound is lost whatever order the walk takes.

prune. The child traversal starts from each visited vertex; when it yields at least one result, the walk does not descend below that vertex, like find -prune. Nothing below the three author directories:

g.v("root").glob_path("**/*.rs", #{prune: __.has("name", "author")}).by("name").order().by(T.id).id().to_list()
"root/#42/answer.rs"
"root/#slash/c.rs"
"root/#unnamed/orphan.rs"
"root/src/lib.rs"
"root/src/main.rs"
"root/src/test_a.rs"
"root/src/test_b.rs"
"root/src/util/io.rs"
"root/src/util/mod.rs"

Pruning never suppresses the vertex itself: a pruned vertex that matches the pattern is still emitted. Here the nested root/author/q/author is not found, because the walk stops below root/author:

g.v("root").glob_path("**/author", #{prune: __.has("name", "author")}).by("name").order().by(T.id).id().to_list()
"root/author"
"root/y/author"

The child starts from a vertex that carries the path of the incoming traverser (the walk records no intermediate levels), so it can read a step label set before glob_path. Here select("a") is the start vertex, so every child is emitted and none is descended into:

g.v("root/src").as("a").glob_path("**", #{prune: __.select("a").has("name", "src")}).by("name").order().by(T.id).id().to_list()
"root/src/lib.rs"
"root/src/main.rs"
"root/src/test_a.rs"
"root/src/test_b.rs"
"root/src/util"

The child can be any traversal, a glob_path included (__.glob_path("*.md").by("name") prunes every directory that holds a Markdown file). An error it raises fails the whole traversal.

The label filter is the cheap prune. A second by() already prunes: a vertex without one of the listed labels is neither emitted nor walked through, and checking a label costs no child traversal. Use prune for conditions a label cannot express.

The options combine with each other and with the label filter; the checks for each visited vertex run in this order: label filter, depth bound, pattern, emission, prune.

g.v("root").glob_path("**/*.rs", #{max_depth: 3, prune: __.has("name", "author")}).by("name").by(["directory","file"]).count().next()
9

Any other key fails when the step is built, so a misspelled option is never silently ignored. The keys edges, path and case_insensitive are reserved for later options (see Limitations and reserved extensions).

Semantics

The start vertex is the root. The pattern describes the path below the incoming vertex: the first segment matches its children. The start vertex itself is never checked against the pattern or the label filter, and it is never emitted, even when the walk comes back to it through a cycle:

g.v("root").glob_path("root").by("name").count().next()
0
g.v("root").glob_path("**/root").by("name").count().next()
0

root/latest is a symlink, but as the start it passes a ["directory"] filter:

g.v("root/latest").glob_path("*").by("name").by(["directory"]).id().to_list()
"root/author"

All outgoing edges. The walk follows every outgoing edge, whatever its label. Here it goes through the points_to edge of root/latest; with the label filter it does not enter the symlink at all:

g.v("root").glob_path("latest/*").by("name").order().by(T.id).id().to_list()
"root/author"
g.v("root").glob_path("latest/*").by("name").by(["directory","file"]).count().next()
0

The filter applies to every visited vertex, not only to emitted ones, which is what keeps a walk on a real filesystem tree:

g.v("root").glob_path("**/loop").by("name").order().by(T.id).id().to_list()
"root/y/loop"
g.v("root").glob_path("**/loop").by("name").by(["directory","file"]).count().next()
0

Multiplicity. Each matched vertex is emitted at most once per incoming traverser, even when several routes or several splits of ** reach it. root/author is reachable directly and through root/latest, yet it appears once:

g.v("root").glob_path("**/author").by("name").order().by(T.id).id().to_list()
"root/author"
"root/author/q/author"
"root/y/author"
g.v("root").glob_path("**/author/**/*.rs").by("name").order().by(T.id).id().to_list()
"root/author/q/author/w/some/h.rs"
"root/author/x/some/f.rs"
"root/y/author/z/some/g.rs"

Distinct incoming traversers are independent, like out(): each one emits its own matches.

g.v(["root","root/author"]).glob_path("**/f.rs").by("name").id().to_list()
"root/author/x/some/f.rs"
"root/author/x/some/f.rs"

Path. The step extends the traverser path by exactly one element, the matched vertex. The intermediate levels are not recorded:

g.v("root").glob_path("src/util/io.rs").by("name").path().by(T.id).to_list()
["root", "root/src/util/io.rs"]

Output order is unspecified. Sort with order() (or order().by(...)) when the order matters.

Missing and non-string values. A named segment works like has(): a vertex whose match key is missing, or holds a value that is not a string, does not match. The value is never converted to a string, and no error is raised. * and ** never read the key, so such vertices are still walked through:

g.v("root").glob_path("*/orphan.rs").by("name").id().to_list()
"root/#unnamed/orphan.rs"
g.v("root").glob_path("?*/orphan.rs").by("name").count().next()
0

?* matches every non-empty string, but root/#unnamed has no name. root/#42 has the int64 name 42, which the segment 42 does not match:

g.v("root").glob_path("42/*").by("name").count().next()
0
g.v("root").glob_path("*/answer.rs").by("name").id().to_list()
"root/#42/answer.rs"

Case-sensitive. docs/*.MD matches nothing (see the syntax table).

No hidden-file rule. Unlike a shell, * and ? also match a value that starts with .. There are no special names.

Performance

  • The pattern is compiled once, when the traversal is built, into an automaton whose live states fit in one 64-bit mask. The walk is an iterative depth-first search, so deep trees cannot overflow the stack.
  • Pruning. A branch is abandoned as soon as no pattern state is alive in it. A pattern without **, such as src/util/*.rs, reads only the levels it names; a leading ** has to visit the whole subtree, but still skips everything the label filter excludes.
  • Trees and graphs. On a tree every vertex is visited at most once per incoming traverser. A vertex reachable over several routes (a diamond, a cycle) is walked again only when it arrives with pattern states it has not seen yet, so the walk always ends, but it may do more than one pass over a shared subtree. Use the label filter to keep the walk on the tree edges when the graph has shortcuts such as symlinks: without it the walk below counts every vertex once, including the symlinks; with it, the 34 directories and files.
g.v("root").glob_path("**").by("name").count().next()
36
g.v("root").glob_path("**").by("name").by(["directory","file"]).count().next()
34
  • Depth bound. max_depth stops the walk at a fixed level, so a ** walk over a deep or huge tree costs only the levels it is allowed to see. On a vertex that several routes reach, the walk keeps the smallest depth per pattern state and walks the vertex again only when it arrives at a smaller depth, which keeps it exact and finite.
  • Prune cost. prune runs its child traversal once for every visited vertex the walk would descend into, so it pays off when it cuts large subtrees; prefer the label filter where a label is enough.
  • Counting. A count() directly after the step counts the matches without creating a traverser for each one, also with max_depth. With prune, the child traversal may allocate for every vertex it is evaluated on:
g.v("root").glob_path("**/*.rs").by("name").by(["directory","file"]).count().next()
12
  • Output size. Graphersal executes a traversal one step at a time, so a step with N matches holds N traversers in memory before the next step runs, exactly like out(). Put a limit() after the step to shorten the result, not to shorten the walk.
  • A long walk respects evaluationTimeout; see Query Limits.
  • .profile() shows the step with its modulators and the options that are set, for example glob_path("**/*.rs", {max_depth: 3, prune: __.has("name", "author")}).by("name"), with its traverser counts; the prune child appears as a nested row with how often it ran.

Errors

The pattern and by() errors are raised when the traversal runs. graphersal shows the failing step, the cause and a help text. For example:

g.v("root").glob_path("src/a**").by("name").to_list()
Error: Step #1 'glob_path("src/a**").by("name")' execution failed
  at #1: v("root").glob_path("src/a**").by("name")
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Caused by: Invalid glob pattern 'src/a**' at position 5: '**' must be a whole segment
Help: '**' spans whole levels, so it must stand alone between slashes. Write glob_path("src/a*/**") instead, or plain glob_path("**") to match every level below the start vertex. A literal '*' is written '\*'.
      A pattern is a '/'-separated list of segments matched level by level below the start vertex: '*' (any value), '?' (one character), '**' (any number of levels, a whole segment only), '[a-z]' / '[!a-z]' (character classes), '{a,b}' (alternatives within one segment) and '\' to escape any of them, for example glob_path("**/src/*.{rs,toml}").

Invalid glob pattern

InvalidGlobPattern reports the pattern, the 0-based character position of the problem and the reason. Each row is g.v("root").glob_path(PATTERN).by("name").to_list(); the Fix column quotes the help text, which graphersal shows in full together with a summary of the pattern syntax:

PatternError (Caused by: line)Fix
empty: ""Invalid glob pattern '' at position 0: the pattern is emptyPass a non-empty pattern, for example glob_path("*") for the children of the start vertex or glob_path("**") for all of its descendants.
/srcInvalid glob pattern '/src' at position 0: a pattern cannot start with '/'The pattern is relative to the start vertex: drop the leading and trailing '/' and the empty segments
src/Invalid glob pattern 'src/' at position 3: a pattern cannot end with '/'The pattern is relative to the start vertex: drop the leading and trailing '/' and the empty segments
src//aInvalid glob pattern 'src//a' at position 4: empty segment between two '/'The pattern is relative to the start vertex: drop the leading and trailing '/' and the empty segments
src/..Invalid glob pattern 'src/..' at position 4: '.' and '..' are reserved as whole segmentsThe start vertex is already the current level: glob_path("docs/*") matches its children directly. To walk back up use .in() or repeat(__.in()) before the step, for example g.v("x").in().glob_path("docs/*"). A value that is literally '.' is matched with '\.'.
src/a**Invalid glob pattern 'src/a**' at position 5: '**' must be a whole segmentWrite glob_path("src/a*/**") instead, or plain glob_path("**") to match every level below the start vertex. A literal '*' is written '\*'.
src\Invalid glob pattern 'src\' at position 3: a trailing '\' escapes nothing'\' escapes the character after it; match a literal backslash with '\\'
src/[abInvalid glob pattern 'src/[ab' at position 4: unclosed character class '['Close the character class with ']' in the same segment, for example glob_path("file[0-9].txt"); match a literal '[' with '\['.
src/[]Invalid glob pattern 'src/[]' at position 4: empty character classA character class needs at least one character; a ']' right after '[' or '[!' is taken literally, so glob_path("[]]") matches ']' and glob_path("[!]]") anything else.
src/[z-a]Invalid glob pattern 'src/[z-a]' at position 5: inverted character rangeA range goes from the lower to the higher character, for example glob_path("[a-z]*") instead of glob_path("[z-a]*").
src/{a,bInvalid glob pattern 'src/{a,b' at position 4: unclosed alternatives '{'Close the alternatives with '}', for example glob_path("*.{rs,toml}"); match a literal '{' with '\{'.
src/{a,{b}}Invalid glob pattern 'src/{a,{b}}' at position 7: alternatives '{..}' cannot be nestedAlternatives cannot be nested; flatten them into one group, for example glob_path("{a,b1,b2}") instead of glob_path("{a,b{1,2}}"), or place two groups side by side: glob_path("{a,b}{1,2}").
src/{a/b,c}Invalid glob pattern 'src/{a/b,c}' at position 6: alternatives '{..}' cannot contain '/'Split the alternative into two queries, for example glob_path("src/a") and glob_path("lib/b") instead of glob_path("{src/a,lib/b}"), or use '**' to span levels, for example glob_path("**/{a,b}"). A value that itself contains '/' is matched with '\/'.
{a,b} nine timesInvalid glob pattern '{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}' at position 40: a segment expands to more than 256 alternativesReplace a group with a class or a wildcard, for example glob_path("file[0-9][0-9]") instead of glob_path("file{0,1,...,9}{0,1,...,9}"), or split the query.
a 64 times, joined by /Invalid glob pattern 'a/a/.../a' at position 126: the pattern has more than 63 segmentsSplit the walk into two consecutive steps, each matching below the vertices the previous one emits, for example glob_path("a/b/c").glob_path("d/e/f") instead of glob_path("a/b/c/d/e/f").

In Rhai the backslash pattern is written "src\\", and the last row builds its pattern in a loop:

let p = "a"; for i in 0..63 { p += "/a"; } g.v("root").glob_path(p).by("name").to_list()

Invalid modulator

InvalidModulator names the step, the position of the by() and the reason. The cases are listed under Invalid combinations. Every help text ends with a corrected query: g.v("root").glob_path("**/*.rs").by("name").by(["directory","file"]).

Invalid options

A max_depth below 1 or above 4294967295 fails when the traversal runs, after the pattern and by() checks, with InvalidOption for the key glob_path.max_depth. The help repeats the query with a valid value:

g.v("root").glob_path("**", #{max_depth: 0}).by("name").to_list()
Error: Step #1 'glob_path("**", {max_depth: 0}).by("name")' execution failed
  at #1: v("root").glob_path("**", {max_depth: 0}).by("name")
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Caused by: Invalid value for option 'glob_path.max_depth': must be at least 1, got 0
Help: max_depth is the deepest level below the start vertex that glob_path() visits: the start vertex is level 0 and its children are level 1, so max_depth is an integer from 1 to 4294967295. Leave it out to walk without a bound. For example g.v("root").glob_path("**", #{max_depth: 1}).by("name").

An unknown or reserved key, or a value of the wrong type (max_depth: "3", prune: 5), fails in Rhai as soon as the step is built, with an argument mismatch:

g.v("root").glob_path("**", #{edges: ["contains"]}).by("name").to_list()
Error: Argument mismatch for step 'glob_path': expected an options map with the keys max_depth, prune, got the reserved key `edges`, which is not implemented yet
Help: glob_path(pattern, #{...}) accepts the options max_depth (an integer from 1: the deepest level below the start vertex the walk visits) and prune (an anonymous traversal: a visited vertex for which it yields a result is not descended into, but is still emitted when it matches); the keys edges, path and case_insensitive are reserved. For example g.v("root").glob_path("**/*.rs", #{max_depth: 3, prune: __.has("name", "target")}).by("name").

An error inside the prune child traversal fails the traversal with that error.

Equivalents

The step makes a common query compact and fast; it makes nothing newly possible. The quick-start query reads as follows elsewhere.

Vanilla Gremlin. emit().repeat(...) covers the leading ** (zero or more levels), one out() per segment follows, and dedup() removes the duplicates of several routes. In Graphersal (TextP.endingWith(".rs") stands in for *.rs, which only differs for a name containing /):

g.V("root").emit().repeat(__.out().hasLabel("directory","file")).out().hasLabel("directory","file").has("name","author").out().hasLabel("directory","file").out().hasLabel("directory","file").has("name","some").out().hasLabel("directory","file").has("name", TextP.endingWith(".rs")).dedup().order().by(T.id).id().to_list()
"root/author/q/author/w/some/h.rs"
"root/author/x/some/f.rs"
"root/y/author/z/some/g.rs"

In TinkerPop's Groovy syntax, with an exact regex for *.rs:

g.V('root').emit().repeat(out().hasLabel('directory','file'))
  .out().hasLabel('directory','file').has('name','author')
  .out().hasLabel('directory','file')
  .out().hasLabel('directory','file').has('name','some')
  .out().hasLabel('directory','file').has('name', regex('^[^/]*\\.rs$'))
  .dedup()

emit().repeat(...) needs no until(): the loop ends when no vertex is left, and emit() before repeat() also covers zero levels. Do not write ** as repeat(...).until(has("name", "author")): it stops at the first author on each branch and loses the nested author/.../author/... match, here h.rs:

g.V("root").repeat(__.out().hasLabel("directory","file")).until(__.has("name","author")).out().hasLabel("directory","file").out().hasLabel("directory","file").has("name","some").out().hasLabel("directory","file").has("name", TextP.endingWith(".rs")).dedup().order().by(T.id).id().to_list()
"root/author/x/some/f.rs"
"root/y/author/z/some/g.rs"

The vanilla form grows with every **, {a,b} or character class, and it expands the whole subtree before it filters. On a cycle TinkerPop loops forever; Graphersal stops after repeat.max_loops iterations (see Recursive Traversals).

Cypher. A classic variable-length relationship cannot constrain the labels of the vertices in between without a WHERE over the whole path:

MATCH p = (r {id:'root'})-[*0..]->(a:directory|file {name:'author'})
          -->(:directory|file)-->(s:directory|file {name:'some'})-->(f:directory|file)
WHERE all(n IN nodes(p)[1..] WHERE n:directory OR n:file) AND f.name =~ '[^/]*\\.rs'
RETURN DISTINCT f

GQL (ISO/IEC 39075) and Neo4j 5 quantified path patterns express the ** directly:

(r) ( ()-->(:directory|file) ){0,} (a:directory|file {name:'author'}) --> ...

TigerGraph GSQL (pattern syntax v2) can express it with -(>)-*0.. and LIKE or regex conditions, but verbosely.

Limitations and reserved extensions

  • Only outgoing edges are followed, whatever their label. An edge-label filter is reserved.
  • The path grows by one element. Recording the full path of intermediate vertices is reserved.
  • Matching is case-sensitive. Case-insensitive matching is reserved.
  • .. as "go to the parent" is reserved; today . and .. as whole segments are an error.

The first three will be further keys of the options map (edges, path: "full", case_insensitive; today these keys are rejected), never extra positional by()s, and the defaults never change: a one-element path, all outgoing edges, case-sensitive matching. max_depth and prune are available now; see Options.

Rust API

The step is glob_path(pattern) on GraphTraversalSource, followed by by(); __::glob_path builds it in a child traversal. TraversalGraph::file_tree() builds the sample graph (GraphSource::file_tree() wraps it in a lock):

use graphersal::prelude::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let graph = TraversalGraph::file_tree();

let rust_files = graph
    .traversal()
    .v("root")
    .glob_path("**/author/*/some/*.rs")
    .by("name")
    .by(["directory", "file"])
    .id()
    .order()
    .to_list()?;
assert_eq!(
    rust_files,
    vec![
        ElementProperty::from("root/author/q/author/w/some/h.rs"),
        ElementProperty::from("root/author/x/some/f.rs"),
        ElementProperty::from("root/y/author/z/some/g.rs"),
    ]
);

let symlinks = graph.traversal().v("root").glob_path("**/symlink").by(By::Label).count().next()?;
assert_eq!(symlinks.and_then(|count| count.as_i64()), Some(2));

let docs_with_markdown = graph
    .traversal()
    .v("root")
    .glob_path("*")
    .by("name")
    .by(["directory"])
    .where_t(__::glob_path("*.md").by("name"))
    .id()
    .to_list()?;
assert_eq!(docs_with_markdown, vec![ElementProperty::from("root/docs")]);

let outside_author = graph
    .traversal()
    .v("root")
    .glob_path_with(
        "**/*.rs",
        GlobPathOptions::default().max_depth(3).prune(__::has("name", "author")),
    )
    .by("name")
    .by(["directory", "file"])
    .count()
    .next()?;
assert_eq!(outside_author.and_then(|count| count.as_i64()), Some(9));
Ok(())
}

The options are glob_path_with(pattern, GlobPathOptions), on GraphTraversalSource and in child traversals (__::glob_path_with). GlobPathOptions::default() sets nothing, max_depth(n) takes a u32 and prune(traversal) an anonymous traversal; glob_path(p) is glob_path_with(p, GlobPathOptions::default()).

An invalid pattern, by() or max_depth surfaces as a TraverserError from the terminal step: ValueError::InvalidGlobPattern (under TraverserError::Value), TraverserError::InvalidModulator or TraverserError::InvalidOption.

Step - gql

gql · category: Start

Runs a GQL query (experimental: MATCH, OPTIONAL MATCH, WHERE, LET, FILTER, WITH, RETURN with aggregates, ORDER BY, OFFSET, LIMIT, quantified edges and path patterns, path variables, and the writes INSERT / CREATE, SET, REMOVE, [DETACH] DELETE and MERGE; $name reads a value of the optional parameter map) at the start of a traversal; each row is a map from column name to value, and Gremlin steps may follow.

Forms

gql(arg1: string)
gql(arg1: string, arg2: any)

Example

g.gql("MATCH (p:person) WHERE p.age > $min RETURN p.name AS name ORDER BY name", #{min: 30}).to_list()   // [#{"name": "josh"}, #{"name": "peter"}]

See also

Step - group

group() is a reducing barrier: it collects the whole stream into one map. The first by() gives the key of each traverser, the second by() its value; without by() the key is the traverser itself and the value is the list of its members.

g.V().group().by(T.label).by("name").next()
// {"person": ["marko", "vadas", "josh", "peter"], "software": ["lop", "ripple"]}
g.V().group().by(T.label).by(__.count()).next()      // {"person": 4, "software": 2}

How the value by() reduces the members of one key:

  • a property key, T.id, T.label, T.key, T.value, a jpath(..) or a bare by(): a list with one projected value per member (map(projection).fold() in TinkerPop). A key whose members all lack the property maps to [];
  • by(Count) or by(__.count()): the member count;
  • a traversal without a barrier: the first result of the last member that produced one;
  • a traversal with a barrier (fold(), count(), sum(), order(), limit(), ...): the traversal runs once over all members of the key, and the key maps to its first result. A key whose run produces nothing is left out.

The side-effect form: group("key")

group("a") does the same grouping into the side effect a and passes every traverser on unchanged (TinkerPop's GroupSideEffectStep). Read the map with cap("a"), select("a") or where(P.within("a")).

g.V().group("a").by(T.label).by("name").cap("a").next()
// {"person": ["marko", "vadas", "josh", "peter"], "software": ["lop", "ripple"]}
g.V().hasLabel("person").as("p").out("created").
  group("a").by("name").by(__.select("p").values("age").sum()).cap("a").next()
// {"lop": 96, "ripple": 32}
  • The map grows while the traversal runs: a reader later in the same traversal sees everything the step has collected so far. g.V().groupCount("a").select("a") sees all six vertices (one execution of the step handles the whole batch), local(groupCount("a").select("a")) a map that grows by one per vertex, as in TinkerPop.
  • A value traversal with a barrier is re-run over all members of each key that grew, at the end of every execution of the step; inside repeat() that is once per iteration.
  • The side effect exists, as {}, as soon as the step has run, even when no traverser reached it: g.V().has("no").groupCount("a").cap("a") is {}.
  • Several group steps may fill one key (union(__.groupCount("m").by(..), __.groupCount("m").by(..))) as long as they reduce a key the same way; a key that holds another kind of side effect (aggregate("a"), withSideEffect("a", ..), tree("a")) is an error. Deviation from TinkerPop, which merges the map into whatever the key holds.

Rust: group(), group_side_effect("a") (and the same on __/AnonymousTraversal).

See also group_count and by.

Step - group_count

groupCount() counts the traversers per key into one map. Its single by() gives the key; without it the key is the traverser itself. A second by() is an InvalidModulator error.

g.V().values("age").groupCount().next()              // {29: 1, 27: 1, 32: 1, 35: 1}
g.V().groupCount().by(T.label).next()                // {"person": 4, "software": 2}

groupCount("key") is the side-effect form: it counts into the side effect key and passes every traverser on (TinkerPop's GroupCountSideEffectStep). The same rules as for group("key") apply.

g.V().out("created").groupCount("a").by("name").cap("a").next()   // {"lop": 3, "ripple": 1}
g.V("1").repeat(__.groupCount("m").by(__.loops()).out()).times(3).cap("m").next()
// {0: 1, 1: 3, 2: 2}

Rust: group_count(), group_count_side_effect("a"); the DSL spells both groupCount and group_count.

Step - has

has · category: Filters

Keeps elements that have the property (and, with a value or predicate, whose value matches, a string operand being a value, never a path label; with a traversal, for whose value the traversal yields a result, like filter(__.values(key)...)); with T.id or T.label first it tests the id or label; the 3-argument form also tests the label.

Forms

has(arg1: any)
has(arg1: By, arg2: any)
has(arg1: any, arg2: any)
has(arg1: string, arg2: any, arg3: any)

Example

{ [g.v().has("person", "age", P.gt(30)).count().next(), g.v().has("name", __.to_lower().is("josh")).count().next(), g.v().has(T.label, __.is("software")).count().next()] }   // [2, 1, 2]

See also

Step - has_id

has_id · hasId · category: Filters

Keeps elements whose id is one of the given ids (ids are strings, see the book page Id Arguments).

Forms

has_id(arg1: any)
has_id(arg1: array)
has_id(arg1: any, arg2: any)
has_id(arg1, …, arg10)

Example

g.v().has_id(1, 2).values("name").to_list()   // ["marko", "vadas"]

See also

Step - has_key

has_key · hasKey · category: Filters

Keeps properties whose key is one of the given keys.

Forms

has_key(arg1: any)
has_key(arg1: array)
has_key(arg1: any, arg2: any)
has_key(arg1, …, arg10)

Example

g.v(1).properties().has_key("age").value().to_list()   // [29]

Step - has_label

has_label · hasLabel · category: Filters

Keeps elements whose label is one of the given labels (or matches a predicate); without arguments it keeps the elements that have a label, so not(__.has_label()) selects the unlabeled ones (Graphersal extension).

Forms

has_label()
has_label(arg1: any)
has_label(arg1: array)
has_label(arg1: any, arg2: any)
has_label(arg1, …, arg10)

Example

{ g.add_v().to_list(); [g.v().has_label("software").count().next(), g.v().not(__.has_label()).count().next()] }   // [2, 1]

Step - has_layer

has_layer · category: Filters

Keeps the vertices and edges whose layer origin is one of the given names ("base", "added", "modified"); on a graph without layers everything is "base" (Graphersal extension).

Forms

has_layer()
has_layer(arg1: any)
has_layer(arg1: array)
has_layer(arg1: any, arg2: any)
has_layer(arg1, …, arg10)

Example

[g.v().has_layer("base", "added").count().next(), g.v().has_layer("modified").count().next()]   // [6, 0]

See also

Step - has_not

has_not · hasNot · category: Filters

Keeps elements that do not have the given property.

Forms

has_not(arg1: any)

Example

g.v().has_not("age").values("name").to_list()   // ["lop", "ripple"]

Step - has_p

has_p · category: Filters

Graphersal form of has(key, predicate) (a bare value means P.eq); a string operand is always a value, never a path label (only where() reads labels; before 0.2.2 a string naming a label compared with the labelled element).

Forms

has_p(arg1: any, arg2: any)

Example

g.v(1).as("vadas").out("knows").has_p("name", P.eq("vadas")).values("name").to_list()   // ["vadas"]

See also

Step - has_value

has_value · hasValue · category: Filters

Keeps properties whose value is one of the given values (or matches a predicate, whose string operand is a value, never a path label).

Forms

has_value(arg1: any)
has_value(arg1: array)
has_value(arg1: any, arg2: any)
has_value(arg1, …, arg10)

Example

g.v(1).properties().has_value("marko").key().to_list()   // ["name"]

See also

Step - has_value_any

has_value_any · category: Filters

Graphersal alias of has_value(v1, v2, ...).

Forms

has_value_any(arg1: array)
has_value_any(arg1: any, arg2: any)
has_value_any(arg1, …, arg10)

Example

g.v().properties("name").has_value_any("marko", "josh").value().to_list()   // ["marko", "josh"]

Step - has_value_p

has_value_p · category: Filters

Graphersal form of has_value(predicate); a string operand is always a value, never a path label (only where() reads labels; before 0.2.2 a string naming a label compared with the labelled element).

Forms

has_value_p(arg1: any)

Example

g.v(1).as("vadas").out("knows").properties("name").has_value_p(P.eq("vadas")).value().to_list()   // ["vadas"]

See also

Step - id

id · category: Values and properties

Yields the id of each vertex or edge (a string), never a property named id.

Forms

id()

Example

g.v().has("name", "josh").id().to_list()   // ["4"]

Step - identity

identity · category: Values and properties

Passes every traverser through unchanged.

Forms

identity()

Example

g.v().identity().count().next()   // 6

Step - import_graphml

import_graphml · category: Graph information and files

Imports a GraphML file into the graph as one unit (needs file access).

Forms

import_graphml(arg1: string)

Example

g.import_graphml("modern.graphml")

Step - import_graphson

import_graphson · category: Graph information and files

Imports a GraphSON file into the graph as one unit (needs file access).

Forms

import_graphson(arg1: string)

Example

g.import_graphson("modern.json")

See also

Step - in

in · in_ · category: Walking the graph

Moves to the adjacent vertices over incoming edges, optionally only edges with the given labels.

Forms

in()
in(arg1: any)
in(arg1: array)
in(arg1: any, arg2: any)
in(arg1, …, arg10)

Example

g.v(3).in("created").values("name").to_list()   // ["peter", "josh", "marko"]

Step - in_e

in_e · inE · category: Walking the graph

Moves to the incoming edges, optionally only edges with the given labels.

Forms

in_e()
in_e(arg1: any)
in_e(arg1: array)
in_e(arg1: any, arg2: any)
in_e(arg1, …, arg10)

Example

g.v(3).in_e("created").count().next()   // 3

Step - in_v

in_v · inV · category: Walking the graph

Moves from an edge to its in (head) vertex.

Forms

in_v()

Example

g.e("0").in_v().values("name").next()   // vadas

Step - index

index() maps a collection to the list of its [element, position] pairs, positions counted from 0 (TinkerPop IndexStep with its default list indexer).

g.V().hasLabel("software").values("name").fold().index().to_list()   // [[["lop", 0], ["ripple", 1]]]
g.V("1").values("age").index().to_list()                             // [[[29, 0]]]
g.V("1").valueMap("name", "age").index().to_list()
// [[[{"name": ["marko"]}, 0], [{"age": [29]}, 1]]]
  • A list and a path are indexed element by element.
  • A map is indexed entry by entry; each entry is a one-entry map.
  • Any other value (a number, a string, a vertex, null) is a one-element collection, so g.V().hasLabel("software").index().unfold() yields [v[3], 0] and [v[5], 0].

with(WithOptions.indexer, WithOptions.map) (see with(WithOptions..)) builds a {position: element} map instead:

g.V().hasLabel("person").values("name").fold().order(Scope.local).
  index().with(WithOptions.indexer, WithOptions.map).next()
// {0: "josh", 1: "marko", 2: "peter", 3: "vadas"}

Rust: GraphTraversalSource::index(), __::index(), followed by with_option(WithOptions::Indexer, Some(WithOptions::Map)).

Step - indexes

indexes · category: Property indexes

Lists the property indexes as maps: name, element, label (() for a label-less index), key, type, transform (a chain as the array of its names), unique, served (with a reason when it is not) and the current entries, distinct_values, skipped and bytes.

Forms

indexes()

Example

{ g.create_index(#{label: "person", key: "name", unique: true}); g.indexes().map(|i| [i.unique, i.entries]) }   // [[true, 4]]

Step - infer_schema

infer_schema · category: Schema

Infers a schema map from the data: on g from the whole graph, after steps from the elements the traversal yields.

Forms

infer_schema()

Example

g.infer_schema()["vertices"].keys()   // ["person", "software"]

See also

Step - inject

inject · category: Start

Inserts the given values into the stream (on g it starts a traversal with them).

Forms

inject()
inject(arg1: any)
inject(arg1: any, arg2: any)
inject(arg1, …, arg10)

Example

g.inject(1, 2, 3).sum().next()   // 6

Step - intersect

intersect(list) keeps the elements of the list a traverser holds that are also in list. The result is a set: each element at most once, in the order of its first occurrence; null is an element like any other (see List Functions).

graphersal> g.V().values("age").fold().intersect([27, 40])
[27]

graphersal> g.inject(["marko", "dave"]).intersect(__.V().values("name").fold())
[marko]

Rust: intersect(vec![27, 40]) and intersect_traversal(__::v(None).values("name").fold()).

Step - is

is · is_ · category: Filters

Keeps values equal to the given value or matching the predicate; a string operand is always a value, never a path label (only where() reads labels; before 0.2.2 a string naming a label compared with the labelled element).

Forms

is(arg1: any)

Example

g.v(1).as("vadas").out("knows").values("name").is(P.eq("vadas")).to_list()   // ["vadas"]

See also

Step - iterate

iterate · category: Running and showing results

Runs the traversal for its side effects and returns unit; the results are discarded, never materialized.

Forms

iterate()

Example

{ g.add_v("x").property("n", 1).iterate(); g.v().has_label("x").count().next() }   // 1

See also

Step - jobs

jobs · category: Scheduled jobs

Lists the scheduled jobs as maps: name, schedule, action, query and args or path, enabled, timeout_ms, memory_limit, run_on, description, the stored effects and served (Graphersal extension).

Forms

jobs()

Example

{ g.define_job(#{name: "nightly", schedule: "0 3 * * *", action: "checkpoint"}); g.jobs().map(|j| j.schedule) }   // ["0 3 * * *"]

Step - json_path

json_path · category: Values and properties

Reads a nested value from each element with a JSONPath (Graphersal extension, see the book page Path keys (jpath)).

Forms

json_path(arg1: string)

Example

g.inject(#{a: #{b: [1, 2]}}).json_path("a.b[1]").next()   // 2

See also

Step - key

key · category: Values and properties

Yields the key of each property.

Forms

key()

Example

g.v(1).properties().key().to_list()   // ["name", "age"]

Step - l_trim

l_trim · lTrim · category: Strings and type conversion

Removes leading whitespace (Unicode White_Space) from each string.

Forms

l_trim()
l_trim(arg1: Scope)

Example

g.inject("  a ").l_trim().next()   // a 

Step - label

label · category: Values and properties

Yields the label of each vertex or edge, never a property named label.

Forms

label()

Example

g.v(1).out_e().label().to_list()   // ["knows", "created", "knows"]

Step - labels

labels · category: Values and properties

Yields the full label set of each vertex as a list (Graphersal multi-label vertices).

Forms

labels()

Example

g.v(1).labels().next()   // ["person"]

See also

Step - layer

layer · category: Values and properties

Yields the layer origin of each vertex or edge: "base", "added" or "modified"; on a graph without layers always "base" (Graphersal extension).

Forms

layer()

Example

g.v(1).out_e().layer().to_list()   // ["base", "base", "base"]

See also

Step - layer_diff

layer_diff · category: Graph information and files

Returns what a layered graph changed against its frozen base as a map of added, removed and modified vertices and edges (base and layer values side by side), filtered by #{kinds, labels} and cut at #{limit} (truncated); empty on a graph without layers (Graphersal extension).

Forms

layer_diff()
layer_diff(arg1: any)

Example

g.layer_diff()   // #{"added": [], "modified": [], "removed": [], "truncated": false}

See also

Step - length

length · category: Strings and type conversion

Yields the length of each string in characters (Unicode scalar values, see the book page Type Conversion and length()).

Forms

length()
length(arg1: Scope)

Example

g.v(1).values("name").length().next()   // 5

See also

Step - limit

limit · category: Filters

Passes on only the first n traversers; with Scope.local the first n elements of each collection.

Forms

limit(arg1: i64)
limit(arg1: Scope, arg2: i64)

Example

g.v().values("name").limit(2).to_list()   // ["marko", "vadas"]

Step - local

local · category: Branches and loops

Runs the child traversal separately for each traverser (per-object scope).

Forms

local(arg1: any)

Example

g.v().has_label("person").local(__.out_e().limit(1)).label().to_list()   // ["knows", "created", "created"]

See also

Step - loops

loops · category: Branches and loops

Within repeat(): yields the current iteration count (of the named loop).

Forms

loops()
loops(arg1: string)

Example

g.v(1).repeat(__.out()).until(__.loops().is(2)).values("name").to_list()   // ["ripple", "lop"]

See also

Step - map

map(traversal) replaces each traverser's value by the first result of a child traversal run on it (TinkerPop TraversalMapStep). A traverser for which the child yields nothing is dropped.

g.V("1").out().map(__.values("name")).to_list()                       // ["josh", "lop", "vadas"]
g.V().map(__.out("created").values("name")).to_list()                 // ["lop", "ripple", "lop"]
g.V().as("a").out("created").map(__.select("a").values("name")).to_list()
// ["marko", "josh", "josh", "peter"]
  • The child sees the incoming traverser with its path, sack and labels, so select("a") inside the child reads an as("a") before map().
  • The result is one new path position: the child's own steps do not show up in a later path().
  • null is a result like any other: g.V().map(__.constant(())) yields six nulls.
  • Bulk is kept: a merged traverser maps once and keeps its bulk.

For every result of the child instead of the first, use flatMap(). withPath() is accepted on g for Gremlin compatibility and changes nothing: Graphersal records the path positions a query reads on its own. Like withSack(), it is a source step: inside a child traversal (__.withPath()) it fails before execution with SourceStepInChild, as __.withSack(1) does.

Rust: GraphTraversalSource::map(traversal), __::map(traversal).

Step - mark

mark · category: Graph information and files

Records a named mark in the graph's journal for point-in-time recovery; needs a journal (see the book page Persistence).

Forms

mark(arg1: string)

Example

g.mark("before-import")   // error: no journal is registered

See also

Step - math

math · category: Labels and paths

Evaluates an arithmetic expression; _ is the incoming value and other names are path labels or by() values (see the book page Math Expressions).

Forms

math(arg1: string)

Example

g.v(1).values("age").math("_ * 2").next()   // 58.0

See also

Step - max

max · category: Aggregation

Yields the largest value of the stream (Scope.local: of each collection; see the book page Local Scope).

Forms

max()
max(arg1: Scope)

Example

g.v().values("age").max().next()   // 35

Step - mean

mean · category: Aggregation

Yields the arithmetic mean of the stream (Scope.local: of each collection).

Forms

mean()
mean(arg1: Scope)

Example

g.v().values("age").mean().next()   // 30.75

Step - median

median · category: Aggregation

Yields the median of the numbers in the stream.

Forms

median()

Example

g.v().values("age").median().next()   // 30.5

Step - memory_report

memory_report · category: Graph information and files

Reports where the graph's memory goes per label and top-level property (elements, value types, bytes, size histogram, distinct strings, vectors), with indexes, compression rules and slots, and where the whole process memory goes (components: the graph, embedding models, the script engine, stores, the host's parts); #{sample_every, max_elements} sample it, #{limit, max_rows, max_labels} keep the largest rows (default 500 per list, the rest counted), #{scope: "delta"} reports only a layered graph's own elements with its base as shared_bytes (a plain graph owns all it shows).

Forms

memory_report()
memory_report(arg1: any)

Example

g.memory_report().properties.filter(|p| p.path == "$.name").map(|p| p.elements)   // [4, 2]

See also

Step - memory_usage

memory_usage · category: Graph information and files

Returns the graph's own memory footprint in bytes (structure, indexes, properties), with its workload statistics, loaded embedding models and the memory shared with other graphs (a layered graph's base) beside the total (workload_bytes, model_bytes, shared_bytes).

Forms

memory_usage()

Example

g.memory_usage().total_bytes > 0   // true

See also

Step - merge

merge() has two forms.

Lists. merge(list) is the union of the list a traverser holds and list: a set, each element at most once, the incoming elements first (see List Functions). Use combine to keep duplicates.

graphersal> g.V().values("age").fold().merge([27, 40])
[29, 27, 32, 35, 40]

Maps. When the traverser holds a map (project(), elementMap(), valueMap(), a map constant), merge(map) adds the argument's entries to it; an entry of the argument replaces the incoming entry with the same key.

graphersal> g.V().hasLabel("person").project("name").by("name").merge(#{kind: "person"})
╭────────┬───────╮
│ kind   │ name  │
├────────┼───────┤
│ person │ marko │
│ person │ vadas │
│ person │ josh  │
│ person │ peter │
╰────────┴───────╯

graphersal> g.V("1").elementMap().merge(__.V("3").elementMap())
╭─────┬────┬──────────┬──────┬──────╮
│ age │ id │ label    │ lang │ name │
├─────┼────┼──────────┼──────┼──────┤
│ 29  │ 3  │ software │ java │ lop  │
╰─────┴────┴──────────┴──────┴──────╯

The two forms do not mix: a list with a map argument, or a map with a list argument, is an error. The DSL writes a map constant as #{kind: "person"}; Rust: merge(ElementProperty::Object(..)) and merge_traversal(__::v("3").element_map(None)).

merge() is unrelated to the upsert steps mergeV()/mergeE().

Step - merge_e

merge_e · mergeE · category: Changing the graph

Upsert of an edge: finds the edge matching the map (T.label, Direction.OUT/IN ids, properties) or creates it (see the book page Upserts).

Forms

merge_e()
merge_e(arg1: any)

Example

g.merge_e(#{"T.label": "knows", "Direction.OUT": "1", "Direction.IN": "2"}).id().next()   // 0

See also

Step - merge_v

merge_v · mergeV · category: Changing the graph

Upsert of a vertex: finds the vertices matching the map or creates one; option(Merge.onCreate/onMatch, ..) adds properties (see the book page Upserts).

Forms

merge_v()
merge_v(arg1: any)

Example

g.merge_v(#{"T.label": "person", name: "marko"}).values("age").next()   // 29

See also

Step - min

min · category: Aggregation

Yields the smallest value of the stream (Scope.local: of each collection; see the book page Local Scope).

Forms

min()
min(arg1: Scope)

Example

g.v().values("age").min().next()   // 27

Step - move_query

move_query · category: Saved queries

Moves a saved query into a folder ("" or () for the root); callers name it without the folder.

Forms

move_query(arg1: string, arg2: any)

Example

{ g.define_query(#{name: "n", body: "fn n() { 1 }"}); g.move_query("n", "archive"); g.get_query("n")["folder"] }   // archive

See also

Step - nearest

nearest · category: Vectors

Exact top-k: the k inputs whose vector property is closest to q, best first; a text q is embedded by the model the schema declares for the property.

Forms

nearest(arg1: any, arg2: any, arg3: i64)
nearest(arg1: any, arg2: any, arg3: i64, arg4: map)

Example

g.inject(#{n: 1, emb: vector([1.0, 0.0])}, #{n: 2, emb: vector([0.0, 1.0])}).nearest("emb", vector([0.0, 1.0]), 1).select("n").next()   // 2

Step - next

next · category: Running and showing results

Runs the traversal and returns its first result (unit when there is none).

Forms

next()

Example

g.v().values("name").next()   // marko

See also

Step - none

none(P) keeps a list traverser when no element of the list satisfies the predicate. It is the sibling of any(P) and all(P) (TinkerPop 3.8 NoneStep). The step that filtered out every traverser, called none() before TinkerPop 3.8, is now discard().

g.V().values("age").fold().none(P.gt(40)).to_list()   // [[29, 27, 32, 35]]
g.V().values("age").fold().none(P.gt(30)).to_list()   // []
g.inject([], [1, 2]).none(P.eq(3)).to_list()          // [[], [1, 2]]
g.inject(7).none(P.eq(8)).to_list()                   // []
  • The list is a fold(), an injected or constant list, or a stored list property.
  • An empty list passes: none of its elements matches.
  • A value that is not a list (a number, a string, null, a map, a vertex) never passes, whatever the predicate.
  • null elements are compared like any other value: none(P.eq(null)) drops [null, 1].

Rust: GraphTraversalSource::none(predicate), __::none(predicate).

Step - not

not · category: Filters

Keeps the traverser when the child traversal yields nothing.

Forms

not(arg1: any)

Example

g.v().not(__.out_e()).values("name").to_list()   // ["vadas", "lop", "ripple"]

Step - option

option · category: Branches and loops

Adds a branch to choose()/branch() for a key (a value, Pick.none, Pick.any), or the onCreate/onMatch map of merge_v()/merge_e().

Forms

option(arg1: any, arg2: any)
option(arg1: Merge, arg2: any, arg3: Cardinality)

Example

g.v(1, 2).choose(__.values("age")).option(29, __.constant("a")).option(Pick.none, __.constant("b")).to_list()   // ["a", "b"]

See also

Step - optional

optional · category: Branches and loops

Emits the results of the child traversal, or the traverser itself when it yields nothing.

Forms

optional(arg1: any)

Example

g.v(2).optional(__.out()).values("name").to_list()   // ["vadas"]

Step - or

or(a, b, ...) keeps a traverser when at least one child traversal produces a result for it.

g.V().or(__.has("age", P.gt(30)), __.hasLabel("software")).values("name")

or() with no argument is the infix form a.or().b, with the operand rules of the infix and(); and() binds tighter, so a.and().b.or().c is or(and(a, b), c).

g.V().emit(__.has("name", "marko").or().loops().is(2)).repeat(__.out()).values("name")
// ["marko", "ripple", "lop"]

Rust: the prefix form or(vec![a, b]); the infix form is a DSL notation.

Step - order

order · category: Lists and ordering

Sorts the stream (Scope.local: each collection) by the by() modulators, ascending by default.

Forms

order()
order(arg1: Scope)

Example

g.v().values("name").order().to_list()   // ["josh", "lop", "marko", "peter", "ripple", "vadas"]

See also

Step - other_v

other_v · otherV · category: Walking the graph

Moves from an edge to the vertex at the other end than the one the traverser came from.

Forms

other_v()

Example

g.v(1).out_e("knows").other_v().values("name").to_list()   // ["josh", "vadas"]

Step - out

out · category: Walking the graph

Moves to the adjacent vertices over outgoing edges, optionally only edges with the given labels.

Forms

out()
out(arg1: any)
out(arg1: array)
out(arg1: any, arg2: any)
out(arg1, …, arg10)

Example

g.v(1).out("knows").values("name").to_list()   // ["josh", "vadas"]

Step - out_e

out_e · outE · category: Walking the graph

Moves to the outgoing edges, optionally only edges with the given labels.

Forms

out_e()
out_e(arg1: any)
out_e(arg1: array)
out_e(arg1: any, arg2: any)
out_e(arg1, …, arg10)

Example

g.v(1).out_e().count().next()   // 3

Step - out_v

out_v · outV · category: Walking the graph

Moves from an edge to its out (tail) vertex.

Forms

out_v()

Example

g.e("0").out_v().values("name").next()   // marko

Step - patch_schema

patch_schema · category: Schema

Applies a JSON Merge Patch to the stored schema (checking the data first) and returns the new schema.

Forms

patch_schema(arg1: any)

Example

g.patch_schema(#{vertices: #{robot: #{schema: #{type: "object"}}}})["vertices"].keys()   // ["robot"]

See also

Step - path

path · category: Labels and paths

Yields the path of each traverser (every element it visited), modulated by by() round-robin.

Forms

path()

Example

g.v(1).out("knows").path().by("name").to_list()   // [["marko", "josh"], ["marko", "vadas"]]

Step - product

product(list) is the Cartesian product of the list a traverser holds and list: one two-element list [a, b] per pair, a from the incoming list (outer loop) and b from list (inner loop). Duplicates are kept; an empty side gives an empty list (see List Functions for the input rules).

graphersal> g.inject(["a", "b"]).product([1, 2])
[[a, 1], [a, 2], [b, 1], [b, 2]]

graphersal> g.V().values("age").order().limit(2).fold().product(__.V().hasLabel("software").values("name").fold()).unfold()
[27, lop]
[27, ripple]
[29, lop]
[29, ripple]

Rust: product(vec![1, 2]) and product_traversal(__::v(None).values("name").fold()).

Step - profile

profile · category: Running and showing results

Runs the traversal and returns its metrics per step of the optimized plan (time, traverser counts; ProfileType.Memory adds memory; see the book page Profiling and execute()).

Forms

profile()
profile(arg1: ProfileType)

Example

g.v().count().profile().to_map()["optimizer_rules_applied"]   // ["count_pushdown"]

See also

Step - profile_with

profile_with · category: Running and showing results

Rust-API spelling of profile(ProfileType).

Forms

profile_with(arg1: ProfileType)

Example

g.v().count().profile_with(ProfileType.Memory).to_table().contains("Mem")   // true

See also

Step - project

project · category: Labels and paths

Turns each traverser into a map with the given keys, one by() per key in order.

Forms

project(arg1: any)
project(arg1: array)
project(arg1: any, arg2: any)
project(arg1, …, arg10)

Example

g.v(1).project("name", "degree").by("name").by(__.both().count()).next()   // #{"degree": 3, "name": "marko"}

Step - properties

properties · category: Values and properties

Yields the property elements of vertices/edges (all, or the given keys; a property named id or label is one of them, never the element's id or label).

Forms

properties()
properties(arg1: any)
properties(arg1: array)
properties(arg1: any, arg2: any)
properties(arg1, …, arg10)

Example

g.v(1).properties("age").value().next()   // 29

See also

Step - property

property(key, value) sets a property on the incoming vertex or edge; the value can be a constant or a child traversal (its first result; no result leaves the property untouched). The key can be a jpath(..) (Path Keys), and property(Cardinality, key, value) and property(map) exist as well.

A key named id or label

property("id", ..) and property("label", ..) store ordinary properties; they never change the element's id or label (TinkerPop accepts these keys too). values("label"), by("label") and select("label") on an element_map() read such a property, label(), by(T.label) and select(T.label) the element's label. Where a map leaves the engine with both (an element_map() result in a table or as JSON), the property wins under "label". See Properties Named id or label.

g.V("1").property("label", "CUSTOM").project("p", "t").by("label").by(T.label).next()   // {"p": "CUSTOM", "t": "person"}

property(traversal, value)

The key is the first result of a child traversal run on the incoming traverser (TinkerPop's AddPropertyStep with a key traversal):

g.withSideEffect("a", "name").addV().property(__.select("a"), "marko").values("name")   // "marko"

The key must be a string; no result or another value is a cast error. The value may be a traversal too (property(__.select("k"), __.values("age"))).

Rust: property_key_by(key_traversal, value), property_key_by_traversal(key_traversal, value_traversal).

Step - property_json

property_json · category: Changing the graph

Sets every key of the given map (or JSON object) as a property of the incoming vertex (Graphersal extension); a key id or label makes an ordinary property, never the element's id or label.

Forms

property_json(arg1: any)

Example

g.v(1).property_json(#{age: 30, tags: ["a", "b"]}).values("tags").next()   // ["a", "b"]

See also

Step - quantize

quantize · category: Vectors

Converts a vector to the element kind f32, f16, i8 or bit; quantize("f32") dequantizes.

Forms

quantize(arg1: string)

Example

g.inject(vector([0.5, -1.0])).quantize("i8").next().element   // i8

Step - queries

queries · category: Saved queries

Lists the saved queries (of a folder and its subfolders) as maps: name, folder, description, language, dialect, params, status, writes and the effects a call may write.

Forms

queries()
queries(arg1: string)

Example

{ g.define_query(#{name: "n", folder: "a/b", body: "fn n() { 1 }"}); g.queries("a").map(|q| q.name) }   // ["n"]

See also

Step - query

query · category: Saved queries

Calls a saved query by name with named arguments (start of a traversal only); a query that writes writes in the call, and a traversal result can be continued, read-only (see the book page Saved Queries).

Forms

query(arg1: string)
query(arg1: string, arg2: any)

Example

{ g.define_query(#{name: "people", body: "fn people() { g.v().has_label(\"person\") }"}); g.query("people").values("name").limit(2).to_list() }   // ["marko", "vadas"]

See also

Step - r_trim

r_trim · rTrim · category: Strings and type conversion

Removes trailing whitespace (Unicode White_Space) from each string.

Forms

r_trim()
r_trim(arg1: Scope)

Example

g.inject(" a  ").r_trim().next()   // a

Step - range

range · category: Filters

Passes on the traversers from position low (inclusive) to high (exclusive); with Scope.local inside each collection.

Forms

range(arg1: i64, arg2: i64)
range(arg1: Scope, arg2: i64, arg3: i64)

Example

g.v().values("name").range(1, 3).to_list()   // ["vadas", "lop"]

Step - recompress

recompress · category: Compressed properties

Rebuilds a compression rule's dictionary from the current values and re-encodes them; changes no data.

Forms

recompress(arg1: string)

Example

{ g.define_compression(#{name: "bio", label: "person", path: "bio"}); g.recompress("bio"); g.compressions()[0].compressed_values }   // 0

See also

Step - remove_property

remove_property · category: Changing the graph

Removes the given properties (none = all) from vertices and edges and passes them on (Graphersal extension, see the book page Removing Properties).

Forms

remove_property()
remove_property(arg1: any)

Example

g.v(1).remove_property("age").values("age").to_list()   // []

See also

Step - repeat

repeat · category: Branches and loops

Runs the child traversal in a loop, controlled by times(), until() and emit(); a name makes loops(name) readable.

Forms

repeat(arg1: any)
repeat(arg1: string, arg2: any)

Example

g.v(1).repeat(__.out()).times(2).values("name").to_list()   // ["ripple", "lop"]

See also

Step - replace

replace · category: Strings and type conversion

Replaces every occurrence of a substring in each string.

Forms

replace(arg1: any, arg2: any)
replace(arg1: Scope, arg2: any, arg3: any)

Example

g.v(1).values("name").replace("ar", "AR").next()   // mARko

Step - reverse

reverse() reverses a string or a list. One step covers both.

  • A string comes back with its characters in reverse order (Unicode scalar values).
  • A list comes back with its elements in reverse order. This covers a fold(), a path() (which becomes a list) and a list constant or property.
  • Every other value passes through unchanged: null, numbers, booleans, maps, vertices and edges.
graphersal> g.inject("feature", ()).reverse().to_list()
"erutaef"
()

graphersal> g.V().out().out().path().by("name").reverse().to_list()
["ripple", "josh", "marko"]
["lop", "josh", "marko"]

graphersal> g.V().values("age").fold().reverse().to_list()
[35, 32, 27, 29]

g.V().values("age").reverse() returns the ages unchanged, because a number is neither a string nor a list.

Step - sack

sack · category: Sack and side effects

Without arguments yields the traverser's sack value; with an Operator, by() feeds a value into the sack (see the book page Sack and Operators).

Forms

sack()
sack(arg1: any)

Example

g.with_sack(1).v(1).out().sack(Operator.sum).by(__.constant(2)).sack().to_list()   // [3, 3, 3]

See also

Step - sample

sample(n) keeps a random sample of n traversers of the whole stream, drawn without replacement (TinkerPop SampleGlobalStep). sample(Scope.local, n) samples n elements of the list (or entries of the map) each traverser holds (SampleLocalStep).

g.with("random.seed", 42).V().values("name").sample(2).to_list()               // ["vadas", "josh"]
g.with("random.seed", 42).V().values("name").fold().sample(Scope.local, 3).to_list()
// [["josh", "peter", "marko"]]
g.V("1").values("age").sample(Scope.local, 5).to_list()                         // [29]
  • A stream (or a list) of at most n elements passes unchanged.
  • sample(Scope.local, n) keeps the drawn elements in the order they were drawn; a value that is not a list or map (a number, a vertex, a path, null) passes through.
  • A negative n samples nothing.
  • Merged traversers are sampled unit by unit, so the sample never stands for more than n traversers.
  • In a repeat() body, sample(n) samples each iteration's frontier (g.V().repeat(__.sample(2)).times(2) yields 2 vertices); in local() it samples per traverser (g.V().local(__.outE().sample(1))).

Weights

A by() after sample(n) weighs each traverser: it is drawn with a probability proportional to its weight.

g.E().sample(2).by("weight")                         // heavier edges are more likely
g.V().sample(1).by(__.outE().count())                // vertices with more out-edges are more likely
  • The weight must be a number of at least 0; anything else fails with ValueError::SampleWeight, whose help shows how to convert it.
  • A traverser whose by() is unproductive (a missing property) is dropped, as in order().
  • A weight of 0 is never drawn, so fewer than n traversers come back when fewer have a positive weight. TinkerPop's sampling loop does not end in that case; this is a deliberate difference.
  • Only one by() is allowed; a second one fails with InvalidModulator.

Reproducible samples

sample(), coin() and order().by(Order.shuffle) draw from one random number generator per execution, shared by child traversals. Without options it is seeded from the operating system's entropy (also in the browser playground). With g.with("random.seed", n) (any integer) the same query draws the same values on every run with the same Graphersal version:

g.with("random.seed", 42).V().values("name").order().by(Order.shuffle).to_list()
// ["marko", "ripple", "peter", "lop", "vadas", "josh"]

The option is Graphersal's counterpart of TinkerPop's SeedStrategy. It does not reproduce the draws of TinkerPop's Java Random for the same seed, and the SeedStrategy scenarios of the TinkerPop suite stay out of scope with withStrategies(). See the execution options reference.

Order.shuffle

order().by(Order.shuffle) puts the stream (or, with order(Scope.local), the list) into random order. As in TinkerPop, a clause after the shuffle still sorts: the items are shuffled first and then stably sorted by the clauses that follow the last Order.shuffle, so order().by(Order.shuffle).by("age") is sorted by age with ties in random order.

Rust: GraphTraversalSource::sample(n), sample_scoped(Scope, n), Order::Shuffle; .with("random.seed", n) on the source.

Step - select

select · category: Labels and paths

Selects path labels, map keys or side effects (one label: the value, several: a map; an undeclared label is an error, see the book page Repeated Labels: select with Pop); select(T.id)/select(T.label) read the token entries of an element_map() map, select("label") a property named label.

Forms

select(arg1: Column)
select(arg1: any)
select(arg1: array)
select(arg1: any, arg2: any)
select(arg1, …, arg10)

Example

g.v(1).as("a").out("created").as("b").select("a", "b").by("name").next()   // #{"a": "marko", "b": "lop"}

See also

Step - set_label

set_label · category: Changing the graph

Changes the label of each incoming edge and passes it on (Graphersal extension; vertices use add_label()/drop_label()).

Forms

set_label(arg1: string)

Example

g.e(0).set_label("met").label().next()   // met

See also

Step - set_schema

set_schema · category: Schema

Stores a schema map on the graph, optionally with a SchemaMode; open/closed modes check the existing data first.

Forms

set_schema(arg1: any)
set_schema(arg1: any, arg2: any)

Example

{ g.set_schema(g.infer_schema()); g.get_schema()["mode"] }   // none

See also

Step - set_visualizer

set_visualizer · category: Running and showing results

Sets how results of g are displayed in this session (a V token such as V.Table or V.Json).

Forms

set_visualizer(arg1: VisualizeFormat)

Example

{ g.set_visualizer(V.Json); g.v(1).values("name").to_list() }   // ["marko"]

See also

Step - shrink_to_fit

shrink_to_fit · category: Graph information and files

Releases the spare capacity a graph built by write queries keeps (slots and index room past the data) and returns its memory total before and after (before_bytes, after_bytes, released_bytes; measured false when the storage reports no figures); changes no data.

Forms

shrink_to_fit()

Example

{ g.inject(1).repeat(__.add_v("p")).times(100).iterate(); g.shrink_to_fit().released_bytes > 0 }   // true

See also

Step - side_effect

side_effect · sideEffect · category: Sack and side effects

Runs the child traversal for its side effects and passes each traverser on unchanged.

Forms

side_effect(arg1: any)

Example

g.v(1).side_effect(__.out().aggregate("x")).cap("x").next().len()   // 3

Step - similarity

similarity · category: Vectors

Score of a vector property (or the incoming vector) against q: cosine (default), dot, l2 or hamming; a text q is embedded by the model the schema declares for the property.

Forms

similarity(arg1: any)
similarity(arg1: any, arg2: any)
similarity(arg1: any, arg2: any, arg3: string)

Example

g.inject(vector([3.0, 4.0])).similarity([0, 0], "l2").next()   // 5.0

Step - simple_path

simple_path · simplePath · category: Filters

Keeps only traversers whose path never repeats an element.

Forms

simple_path()

Example

g.v(1).both().both().simple_path().count().next()   // 4

Step - skip

skip · category: Filters

Skips the first n traversers (Scope.local: elements of each collection).

Forms

skip(arg1: i64)
skip(arg1: Scope, arg2: i64)

Example

g.v().values("name").skip(4).to_list()   // ["ripple", "peter"]

Step - split

split(separator) turns the string a traverser holds into a list of strings, cut around separator. The separator itself is not kept.

graphersal> g.inject("that", "this", "test", ()).split("h").to_list()
["t", "at"]
["t", "is"]
["test"]
()
  • A null (() in Rhai, None in Rust) separator splits on runs of whitespace: g.inject(" hello world ").split(()) gives ["hello", "world"].
  • An empty separator splits into single characters: g.inject("abc").split("") gives ["a", "b", "c"].
  • A non-empty separator follows Apache Commons' splitByWholeSeparator, which TinkerPop uses. Adjacent separators produce no empty string, but a separator at the very end leaves a trailing "": "a--b" split by "-" is ["a", "b"], and "ath" split by "h" is ["at", ""].
  • A null input stays null. Any other value that is not a string is a cast error.

Scope.local

split(Scope.local, separator) splits each string of the list a traverser holds, which gives a list of lists. A null element stays null, and a single string is split as by the unscoped step.

graphersal> g.V().hasLabel("person").values("name").order().fold().split(Scope.local, "a").to_list()
[["josh"], ["m", "rko"], ["peter"], ["v", "d", "s"]]

Rust API: split("h"), split(None), split_scoped(Scope::Local, "a").

Step - statistics

statistics · category: Graph information and files

Returns the graph's counts: vertices and edges in total and per label.

Forms

statistics()

Example

g.statistics()["vertex_labels"]   // #{"person": 4, "software": 2}

See also

Step - store

store · category: Aggregation

Like aggregate(), but adds each value lazily, without a barrier.

Forms

store(arg1: string)

Example

g.v().has_label("software").values("name").store("s").cap("s").next()   // ["lop", "ripple"]

See also

Step - subgraph

subgraph · category: Sack and side effects

Collects the incoming edges with both endpoints into a graph side effect; cap() it or use to_graph() (see the book page Set Side Effects).

Forms

subgraph()
subgraph(arg1: string)

Example

g.v(1).out_e("knows").subgraph("sg").cap("sg").next().v().count().next()   // 3

See also

Step - substring

substring · category: Strings and type conversion

Yields the part of each string from start (to end, exclusive); negative positions count from the end.

Forms

substring(arg1: i64)
substring(arg1: Scope, arg2: i64)
substring(arg1: i64, arg2: i64)
substring(arg1: Scope, arg2: i64, arg3: i64)

Example

g.v(1).values("name").substring(1, 3).next()   // ar

Step - sum

sum · category: Aggregation

Yields the sum of the numbers in the stream (Scope.local: of each collection).

Forms

sum()
sum(arg1: Scope)

Example

g.v().values("age").sum().next()   // 123

Step - tail

tail(n) keeps the last n traversers of the stream; tail() is tail(1). tail(Scope.local, n) keeps the last n elements of the list each traverser holds.

g.V().values("name").order().tail()           // ["vadas"]
g.V().values("name").order().tail(2)          // ["ripple", "vadas"]

Rust: tail(n), tail_scoped(Scope::Local, n).

Step - times

times · category: Branches and loops

Within repeat(): runs the loop body exactly n times.

Forms

times(arg1: i64)

Example

g.v(1).repeat(__.out()).times(2).values("name").to_list()   // ["ripple", "lop"]

See also

Step - to

to · category: Modulators and options

Sets the in vertex of the edge add_e() creates (vertex, vertex id, path label or child traversal); with a Direction it moves like out()/in()/both().

Forms

to(arg1: Direction)
to(arg1: any)
to(arg1: array)
to(arg1: any, arg2: any)
to(arg1, …, arg10)

Example

g.v(1).to(Direction.OUT, "knows").values("name").to_list()   // ["josh", "vadas"]

Step - to_e

to_e · toE · category: Walking the graph

Moves to the incident edges in the given Direction, optionally only edges with the given labels.

Forms

to_e(arg1: Direction)
to_e(arg1: any, arg2: any)
to_e(arg1, …, arg10)

Example

g.v(1).to_e(Direction.OUT, "knows").count().next()   // 2

Step - to_graph

to_graph · category: Running and showing results

Runs the traversal and builds a new graph from the edges it yields, both endpoints included (Graphersal terminal).

Forms

to_graph()

Example

g.v(1).out_e().to_graph().v().count().next()   // 4

See also

Step - to_json

to_json · category: Running and showing results

Runs the traversal and renders its results as JSON text.

Forms

to_json()
to_json(arg1: any)

Example

g.v(1).values("name").to_json()

See also

Step - to_json_schema

to_json_schema · category: Running and showing results

Runs the traversal and renders the JSON Schema of its results (a schema map as JSON Schema; other results as JSON per line).

Forms

to_json_schema()
to_json_schema(arg1: any)

Example

g.v(1).values("name").to_json_schema()   // "marko"

See also

Step - to_list

to_list · toList · category: Running and showing results

Runs the traversal and returns all results as a list.

Forms

to_list()

Example

g.v().has_label("software").values("name").to_list()   // ["lop", "ripple"]

See also

Step - to_lower

to_lower · toLower · category: Strings and type conversion

Converts each string to lower case.

Forms

to_lower()
to_lower(arg1: Scope)

Example

g.inject("ABC").to_lower().next()   // abc

Step - to_markdown

to_markdown · category: Running and showing results

Runs the traversal and renders its results as a Markdown table.

Forms

to_markdown()
to_markdown(arg1: any)

Example

g.v(1).values("name").to_markdown()

See also

Step - to_mermaid

to_mermaid · category: Running and showing results

Runs the traversal and renders its results in Mermaid format (a schema map as a diagram; other results as JSON per line).

Forms

to_mermaid()
to_mermaid(arg1: any)

Example

g.v(1).values("name").to_mermaid()   // "marko"

See also

Step - to_plantuml

to_plantuml · category: Running and showing results

Runs the traversal and renders its results in PlantUML format (a schema map as a diagram; other results as JSON per line).

Forms

to_plantuml()
to_plantuml(arg1: any)

Example

g.v(1).values("name").to_plantuml()   // "marko"

See also

Step - to_table

to_table · category: Running and showing results

Runs the traversal and renders its results as a text table.

Forms

to_table()
to_table(arg1: any)

Example

g.v(1).values("name").to_table()

See also

Step - to_tree

to_tree · category: Running and showing results

Runs the traversal and renders its results as an indented tree.

Forms

to_tree()
to_tree(arg1: any)

Example

g.v(1).out().to_tree()

See also

Step - to_upper

to_upper · toUpper · category: Strings and type conversion

Converts each string to upper case.

Forms

to_upper()
to_upper(arg1: Scope)

Example

g.v(1).values("name").to_upper().next()   // MARKO

Step - to_v

to_v · toV · category: Walking the graph

Moves from an edge to its vertex in the given Direction (Direction.OUT: out vertex).

Forms

to_v(arg1: Direction)

Example

g.e("0").to_v(Direction.IN).values("name").next()   // vadas

Step - tree

tree · category: Aggregation

Builds a tree map of the paths the traversers took (modulated by by()); with a key it is a side effect (see the book page tree("key") as a Side Effect).

Forms

tree()
tree(arg1: string)

Example

g.v(1).out("knows").tree().by("name").next()   // #{"marko": #{"josh": #{}, "vadas": #{}}}

See also

Step - trim

trim · category: Strings and type conversion

Removes leading and trailing whitespace (Unicode White_Space, see the book page Type Conversion and length()) from each string.

Forms

trim()
trim(arg1: Scope)

Example

g.inject("  a  ").trim().next()   // a

See also

Step - unfold

unfold · category: Lists and ordering

Splits a list (or map, into entries) into its elements, one traverser each.

Forms

unfold()

Example

g.inject([1, 2, 3]).unfold().sum().next()   // 6

Step - union

union(a, b, ...) runs every child traversal on each traverser and emits all their results. As a start step (g.union(..)) the children start the traversal themselves.

g.V("1").union(__.out("knows"), __.out("created")).values("name")   // ["josh", "vadas", "lop"]
g.union()                                                         // nothing

union() with no child produces nothing.

Rust: union(vec![a, b]).

Step - until

until · category: Branches and loops

Within repeat(): stops the loop for a traverser when the child traversal yields a result (or the predicate matches).

Forms

until(arg1: any)

Example

g.v(1).repeat(__.out()).until(__.has_label("software")).values("name").to_list()   // ["lop", "ripple", "lop"]

See also

Step - v

v · V · category: Start

Starts at the vertices of the graph (all, or the ones with the given ids); after steps it starts a new scan per traverser.

Forms

v()
v(arg1: any)
v(arg1: array)
v(arg1: any, arg2: any)
v(arg1, …, arg10)

Example

g.v(1, 2).values("name").to_list()   // ["marko", "vadas"]

See also

Step - validate_schema

validate_schema · category: Schema

Dry run of set_schema(): checks the data against a schema map (optionally with a SchemaMode) and returns {violations, diff, compatible}.

Forms

validate_schema(arg1: any)
validate_schema(arg1: any, arg2: any)

Example

g.validate_schema(g.infer_schema())["compatible"]   // true

See also

Step - validate_schema_patch

validate_schema_patch · category: Schema

Dry run of patch_schema(): checks the patched schema against the data and returns {violations, diff, compatible}.

Forms

validate_schema_patch(arg1: any)

Example

g.validate_schema_patch(#{vertices: #{robot: #{schema: #{type: "object"}}}})["compatible"]   // true

See also

Step - value

value · category: Values and properties

Yields the value of each property.

Forms

value()

Example

g.v(1).properties("name").value().next()   // marko

Step - value_map

value_map · valueMap · category: Values and properties

Turns each element into a map of its properties (each value in a list); value_map(true) adds the T.id and T.label tokens, written "id" and "label" outside the engine where a property of the same name wins.

Forms

value_map()
value_map(arg1: any)
value_map(arg1: array)
value_map(arg1: any, arg2: any)
value_map(arg1, …, arg10)

Example

g.v(1).value_map("name").next()   // #{"name": ["marko"]}

Step - values

values · category: Values and properties

Yields the values of the given (or all) properties; a jpath() key reads a nested value; values("label") reads a property named label, never the element's label.

Forms

values()
values(arg1: any)
values(arg1: array)
values(arg1: any, arg2: any)
values(arg1, …, arg10)

Example

g.v(1).values("name", "age").to_list()   // ["marko", 29]

Step - vector_mean

vector_mean · category: Vectors

The component-wise mean of the incoming vectors (or lists of vectors).

Forms

vector_mean()

Example

g.inject(vector([1.0, 0.0]), vector([0.0, 1.0])).vector_mean().next()   // vector([0.5, 0.5])

Step - visualize

visualize · category: Running and showing results

Runs the traversal and renders its results in the given V format (default: the session's).

Forms

visualize()
visualize(arg1: VisualizeFormat)
visualize(arg1: VisualizeFormat, arg2: any)

Example

g.v(1).values("name").visualize(V.Json)

See also

Step - where

where · category: Filters

Keeps the traverser when the child traversal yields a result, or when a labelled object matches a predicate on another label; where(P.eq("a")) is the step whose string operand names a path label (see the book page where() Start and End Labels).

Forms

where(arg1: any)
where(arg1: string, arg2: any)

Example

g.v(1).as("a").out().where(__.in("created").as("a")).values("name").to_list()   // ["lop"]

See also

Step - where_p

where_p · category: Filters

Graphersal form of where(predicate), modulated by by(); a string operand names a path label first (has() and is() never read labels).

Forms

where_p(arg1: any)

Example

g.v(1).as("a").out("created").in("created").where_p(P.neq("a")).values("name").to_list()   // ["peter", "josh"]

See also

Step - where_t

where_t · category: Filters

Graphersal form of where(traversal).

Forms

where_t(arg1: any)

Example

g.v().where_t(__.out("created")).values("name").to_list()   // ["marko", "josh", "peter"]

See also

Step - with

with · category: Modulators and options

On g sets an execution option (g.with("key", value), see the book page Execution Options Reference); after a step a WithOptions token configures it.

Forms

with(arg1: WithOptions)
with(arg1: WithOptions, arg2: WithOptions)
with(arg1: string, arg2: any)

Example

g.with("random.seed", 7).v().count().next()   // 6

See also

Step - with_bulk

with_bulk · withBulk · category: Modulators and options

g.with_bulk(false) makes every merge keep bulk 1, so equal traversers collapse at barrier().

Forms

with_bulk(arg1: bool)

Example

g.with_bulk(false).v().out().barrier().count().next()   // 4

See also

Step - with_path

with_path · withPath · category: Modulators and options

Records full paths for this traversal (TinkerPop's withPath(); path recording is otherwise derived from the query).

Forms

with_path()

Example

g.with_path().v(1).out().path().count().next()   // 3

Step - with_sack

with_sack · withSack · category: Sack and side effects

Gives every traverser an initial sack value, optionally with a merge Operator for when traversers merge.

Forms

with_sack(arg1: any)
with_sack(arg1: any, arg2: any)

Example

g.with_sack(0).v(1).sack().next()   // 0

See also

Step - with_side_effect

with_side_effect · withSideEffect · category: Sack and side effects

Starts the traversal with a named side effect holding the given value (optionally with a reducing Operator).

Forms

with_side_effect(arg1: string, arg2: any)
with_side_effect(arg1: string, arg2: any, arg3: any)

Example

g.with_side_effect("x", [1]).v(1).values("age").aggregate("x").cap("x").next()   // [1, 29]

Query Optimizer

Before a traversal runs, Graphersal's rule-based optimizer rewrites its steps into a cheaper physical plan: it folds filters into the start step, fuses counts, inserts merge points and so on. .profile() always shows the plan after optimization, with fused steps under their real names (for example v(labels: ["person"]).count()).

See the Execution Options Reference for the full table of every g.with() key, including optimizer.disabled/optimizer.enabled below.

Rules, order and default state

The rules run in this order, once per traversal level. Each has a stable name: the string .profile() reports and the string g.with("optimizer.disabled", [...]) / g.with("optimizer.enabled", [...]) accept.

#RuleNameDefaultRewrites
1Where Unnestwhere_unnestonwhere(__.has...) of local filters → the filters inline
2Add Property Foldadd_property_foldonadd_v(..).property(k, v)... → one creation with all properties
3Filter Reorderfilter_reorderonadjacent filters sorted cheapest first
4Has ID Pushdownhas_id_pushdownonv().has_id(..) → v(ids)
5Source Filter Pushdownsource_filter_pushdownonv().has_label(..)/has_id(..)/has(k, v) → v(labels, ids).has(k, v) (checked while scanning)
6Property Indexproperty_indexonv(labels).has(k, ..) reads a declared property index ([index: ..])
7Barrier Pushdownbarrier_pushdownonout_e().has_label(..) → out_e(labels)
8Group Count Pushdowngroup_count_pushdownonv().group_count().by(T.label) → one fused step
9Count Pushdowncount_pushdownonv().count() → one fused step
10Lazy Barrierlazy_barrieroninserts lazy_barrier() between adjacent adjacency steps

All 10 rules ship on by default; none is opt-in today. The order matters: the early rules bring filters into the position where the later ones can fold them. For example g.v().where(__.has_label("person")).count() becomes v(labels: ["person"]).count() through where_unnest, source_filter_pushdown and count_pushdown together.

Nested traversals (the children of where(), union(), repeat(), by(__...), ...) are optimized first, bottom-up, with the same rules, before their parent level. The rules that fold into a start step only fire on a level that begins with v()/e(), so they rarely apply inside a child; where_unnest, filter_reorder, barrier_pushdown and lazy_barrier do.

Modulators. A by() belongs to the step in front of it and moves with it: no rule moves a filter across a by(), from()/to() or as(). filter_reorder, has_id_pushdown, source_filter_pushdown and barrier_pushdown stop at such a step; lazy_barrier and add_property_fold look past modulators (and add_property_fold past as()) because these do not change their stream. group_count_pushdown reads the by() modulators of the grouping step: only by(T.label) (plus by(Count) for group()) can be fused.

See which rules fired

.profile()/.profile_with(...) end with an "Optimizer rules applied: ..." line after the timing table, naming every rule (top-level and nested, deduplicated, in pipeline order) that actually changed the plan. The line is omitted when no rule fired.

$ graphersal -e 'g.v().has_label("person").count().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(labels: ["person"]).count()                                   1       0       4    4.042µs    10.58
                                                      TOTAL:             execute:   38.208µs    10.58
=====================================================================================================
Optimizer rules applied: source_filter_pushdown, count_pushdown

The same list is available as data: optimizer_rules_applied on the TraversalMetrics value (a property in Rhai, TraversalMetrics::optimizer_rules_applied() in Rust).

$ graphersal -e 'g.v().has_label("person").count().profile().optimizer_rules_applied'
"source_filter_pushdown"
"count_pushdown"

Toggle rules for one query

Disable a rule, e.g. to compare a plan with and without it, or to work around a rule producing an unwanted plan:

g.with("optimizer.disabled", ["filter_reorder"]).v().has_label("person").count().profile()

Disable every rule at once with the reserved name "all", to see a query's genuinely unoptimized plan (the "Optimizer rules applied" line then disappears):

$ graphersal -e 'g.with("optimizer.disabled", ["all"]).v().has_label("person").count().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v()                                                             1       0       6    3.041µs    10.21
has_label("person")                                             1       6       4    2.000µs     6.71
count()                                                         1       4       1       42ns     0.14
                                                      TOTAL:             execute:   29.791µs    17.06
=====================================================================================================

Force-enable an off-by-default rule with optimizer.enabled (it also accepts "all"). This is a no-op today, since no rule defaults to off, but it is ready for the first rule that does.

A name that is neither a rule above nor "all", or a rule named in both lists, fails with InvalidOption when the traversal executes (not at with() time):

$ graphersal -e 'g.with("optimizer.disabled", ["no_such_rule"]).v().count().to_list()'
Error: Invalid value for option 'optimizer.disabled': unknown optimizer rule "no_such_rule"; valid names are: where_unnest, add_property_fold, filter_reorder, has_id_pushdown, source_filter_pushdown, property_index, barrier_pushdown, group_count_pushdown, count_pushdown, lazy_barrier, all
Help: Set 'optimizer.disabled'/'optimizer.enabled' to an array of optimizer rule names ...

Do the rules change results?

A rule changes the plan, not the result, with these exceptions, each described on the rule's page:

  • Add Property Fold decides whether addV(..).property(..) can satisfy a schema with required properties at all. Without it, the creation fails.
  • The order of results is not part of the guarantee: Source Filter Pushdown reads elements label by label from the index, and Property Index reads them in index order, and Lazy Barrier can reorder duplicates. Use order() when the order matters.

Path requirement analysis

After the rules, the path requirement analysis walks every level of the final plan backwards and decides what each step must record into traverser paths (none, only some labels, or full) so that later readers such as path(), select("a") or simple_path() find what they need. .profile() shows the decision as [path: ...] on each step that records something, and g.with("path.analysis", false) forces full recording everywhere for diagnosis. It runs after the rules because they fuse and remove steps, and it is not a rule: it cannot be disabled through optimizer.disabled.

Optimizer cost

The optimizer's own cost is not broken out as a separate row in .profile(). On a real graph it is negligible next to the actual traversal work; on graphs the size of tinkerpop_modern the whole query runs in microseconds, a scale where debug-build measurement noise dominates any number this crate could report.

Where Unnest Rule

Rule name: where_unnest (on by default, runs first).

What it rewrites

A where(__...) whose child traversal consists only of local element filters is replaced by those filters, inlined at the position of the where():

v().where(__.has_label("person").has("age", P.gt(30)))   →   v().has_label("person").has("age", ...)

The local filters are has, has_label, has_id, has_not, has_key, has_property, has_value, the predicate forms of has (has_p), is and is(GType...). A where() with an empty child traversal (which keeps every traverser) is removed.

Why

A where() runs its child traversal once per incoming traverser. A child made of filters only neither walks the graph nor changes the number of results, so running it inline is equivalent and saves the per-traverser child execution. More importantly, the inlined filters become visible to the rules that run later: Filter Reorder can sort them, and Source Filter Pushdown / Has ID Pushdown can fold them into v()/e().

When it does not fire

  • The child contains any other step: where(__.out("created")), where(__.has_label("person").out()), where(__.values("age").is(P.gt(30))).
  • The child starts or ends with an as() label (where(__.as("a")...)): a start or end label changes what the child runs on, so it cannot be flattened.
  • where(P...) (the predicate form), filter(__...), not(__...), and(...), or(...): the rule looks at where(traversal) only. g.v().filter(__.has_label("person")) stays a filter() with a child.

Example

With the rule (the default), the has_label inside the where() ends up folded into v():

$ graphersal -e 'g.v().where(__.has_label("person").has("age", P.gt(30))).values("name").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(labels: ["person"])                                           1       0       4    3.500µs     6.19
has("age", P.gt(30))                                            1       4       2    4.042µs     7.15
values("name")                                                  1       2       2   11.166µs    19.75
                                                      TOTAL:             execute:   56.542µs    33.09
=====================================================================================================
Optimizer rules applied: where_unnest, source_filter_pushdown

Without it, the child traversal runs once per vertex:

$ graphersal -e 'g.with("optimizer.disabled", ["where_unnest"]).v().where(__.has_label("person").has("age", P.gt(30))).values("name").profile()'
Traversal Metrics
Step                                                                   Call      In     Out       Time    % Dur
===============================================================================================================
v()                                                                       1       0       6    1.667µs     3.75
where(__.has_label("person").has("age", P.gt(30)))                        1       6       2    7.042µs    15.85
  \> has_label("person")                                                  6       6       4    1.292µs     2.91
     [min: 0ns, avg: 215ns, max: 1.042µs]
  \> has("age", P.gt(30))                                                 4       4       2    3.292µs     7.41
     [min: 83ns, avg: 823ns, max: 3.000µs]
values("name")                                                            1       2       2    2.208µs     4.97
                                                                TOTAL:             execute:   44.416µs    24.58
===============================================================================================================

Note that no other rule fired either: source_filter_pushdown cannot see a has_label hidden in a child traversal.

Results

Unchanged. Both plans return "josh" and "peter", in the same order. A filter-only child keeps or drops a traverser exactly as the same filters do inline.

Interaction with other rules

Runs first so that every later rule sees the inlined filters. Nested traversals are optimized before their parent level, so a where() inside a repeat() body or a union() branch is unnested too.

Add Property Fold Rule

Rule name: add_property_fold (on by default, second in the pipeline).

What it rewrites

addV("Person").property("name", "Ann").property("age", 30) is written as three steps, but the graph should see one creation: the vertex with all its properties. The rule folds addV() / addE() and the run of constant property(key, value) steps right behind it into a single add_vertex_with / add_edge_with call (the create path that also fills the schema's defaults). .profile() lists the folded keys: add_v("Person", properties: ["name", "age"]).

Why

  • Required properties. A schema (open or closed) that lists a property in required rejects an element created without it (unless its schema has a default, which the creation stores). Without the fold, the empty addV("Person") would be validated before any property() ran and could never succeed.
  • No half-created elements. The storage validates the complete element before inserting it, so a failing property (wrong type, undeclared key in a Closed schema) leaves no element behind.
  • It is also faster: one storage call instead of one per property.

What folds

The run starts directly after the add step and continues over:

  • property(key, constant) steps with a plain string key;
  • as() labels and the from() / to() modulators of addE() (they do not break the run).

The same key repeated keeps the last value, exactly as the unfused sequence does.

When it does not fire (where the run stops)

The run stops at the first step it cannot reproduce exactly; that step and everything after it stay unfused and run as separate steps on the created element:

  • property(key, __.something): the child traversal receives the new element as input, so it cannot be evaluated before the element exists;
  • property(Cardinality, key, value);
  • property(jpath("a.b"), value): a path write below a stored property. A required top-level property cannot be supplied through a path write at creation; give the whole value instead, e.g. property("a", #{b: 1});
  • property(map), property_json(..) and any other step.

An unfolded property() that fails after the element was created fails the traversal, and the failing traversal is rolled back as a whole, the created element included (every traversal is one unit, see Transactions). The fold still matters: it lets a required property be supplied at creation, where a separate property() would come too late.

Example

$ graphersal -e 'g.add_v("Person").property("name", "Ann").property("age", 30).profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
add_v("Person", properties: ["name", "age"])                    1       0       1   28.291µs    19.91
                                                      TOTAL:             execute:  142.125µs    19.91
=====================================================================================================
Optimizer rules applied: add_property_fold

$ graphersal -e 'g.with("optimizer.disabled", ["add_property_fold"]).add_v("Person").property("name", "Ann").property("age", 30).profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
add_v("Person")                                                 1       0       1  262.250µs    18.84
property("name", "Ann")                                         1       1       1  115.834µs     8.32
property("age", 30)                                             1       1       1      292ns     0.02
                                                      TOTAL:             execute:    1.392ms    27.19
=====================================================================================================

An edge, with as() and from() inside the run:

$ graphersal -e 'g.v("1").as("a").v("2").add_e("knows").from("a").property("weight", 0.5).property("since", 2020).profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v("1")                                                          1       0       1    4.167µs     2.73
as("a") [path: labels(a)]                                       1       1       1    2.250µs     1.47
v("2") [path: labels(a)]                                        1       1       1    1.916µs     1.25
add_e("knows", properties: ["weight", "since"]).from("a")       1       1       1   21.125µs    13.83
                                                      TOTAL:             execute:  152.750µs    19.29
=====================================================================================================
Optimizer rules applied: add_property_fold

A traversal-valued property() ends the run; the constant property("age", 30) behind it is not folded either:

$ graphersal -e 'g.add_v("Person").property("name", "Ann").property("nick", __.values("name")).property("age", 30).profile()'
Traversal Metrics
Step                                                                   Call      In     Out       Time    % Dur
===============================================================================================================
add_v("Person", properties: ["name"])                                     1       0       1   15.417µs     3.50
property("nick", __.values("name"))                                       1       1       1  168.833µs    38.37
  \> values("name")                                                       1       1       1    1.875µs     0.43
property("age", 30)                                                       1       1       1      292ns     0.07
                                                                TOTAL:             execute:  440.000µs    41.94
===============================================================================================================
Optimizer rules applied: add_property_fold

Results

Without a schema, or with a schema the element satisfies at every intermediate step, the created element and the results are the same. g.add_v("Person").property("name", "Ann").property("name", "Bo").values("name") returns "Bo" either way.

This is the one rule whose absence can change a result: under a schema with required properties, the empty creation fails without it. With this schema (both fields are required):

$ S='g.set_schema(`{"mode": "open", "vertices": {"Person": {"schema": {"type": "object",
     "properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
     "required": ["name", "age"]}}}}`)'

$ graphersal --graph empty -e "$S" -e 'g.addV("Person").property("name", "Ann").property("age", 30).values("name").toList()'
"Ann"

$ graphersal --graph empty -e "$S" -e 'g.with("optimizer.disabled", ["add_property_fold"]).addV("Person").property("name", "Ann").property("age", 30).values("name").toList()'
Error: Step #0 'add_v("Person")' execution failed
  at #0: add_v("Person").property("name", "Ann").property("age", 30).values("name")
         ^^^^^^^^^^^^^^^
Caused by: Missing required property 'name' on vertex 'Person'
Help: Provide a value for 'name' or remove it from the label's "required" in the schema, or give it a "default" (or "defaultFunction") in the schema: it is stored when an element is created without the property (mode open or closed), but never filled into existing elements, and never by an import or a property removal.
      A required property must be supplied when the element is created: add_v("L").property("name", value) works because the optimizer rule add_property_fold folds the directly following constant property() steps into add_v()/add_e(). If a property() after it is not folded (the rule is disabled with g.with("optimizer.disabled", ["add_property_fold"]), the value is a traversal, a Cardinality or a jpath key, or another step sits in between), the element is created empty and this error is raised; move a constant property("name", value) directly behind add_v()/add_e() and keep add_property_fold enabled.

The failed query leaves the graph unchanged. See Schemas.

Interaction with other rules

Runs before every other rule except Where Unnest. The folded add_v/add_e is a mutating step, so Lazy Barrier's merge points in the same plan pass traversers through without merging.

Filter Reorder Rule

Rule name: filter_reorder (on by default, third in the pipeline).

What it rewrites

Every run of adjacent filter steps is sorted by an estimated cost, cheapest first. The sort is stable: filters of the same cost keep the order in which they were written.

RankFiltersWhy this cost
0has_idan id comparison
1has_labela check of the element's labels
2has_key, has_property, has_not, is(GType...)a key presence or type check, no value comparison
3has, has with a predicate, is, has_value, has_id/has_label/has_key with a predicatea property value is read and compared
4where(...), filter(...), not(...), and(...), or(...)a child traversal runs per traverser
5every other filter stepunknown cost

Why

A cheap filter that runs first shrinks the stream that the expensive filters must look at. It also moves has_id/has_label to the front of the run, directly behind v()/e(), where Has ID Pushdown and Source Filter Pushdown can fold them into the start step.

When it does not fire

  • The filters are already in rank order (the profile then does not list the rule).
  • The filters are not adjacent: any non-filter step between them, including as(), out() or a by() modulator, ends the run. Only filters inside one run are sorted, nothing moves across another step.
  • A run of a single filter.
  • A filter with an effect (see Results) splits the run: the filters before it and the filters after it are sorted separately.

Example

has("age", ...) is written before has_label("person"). The rule swaps them, and the label filter then folds into v():

$ graphersal -e 'g.v().has("age", P.gt(30)).has_label("person").values("name").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(labels: ["person"])                                           1       0       4    3.875µs     8.44
has("age", P.gt(30))                                            1       4       2    3.959µs     8.62
values("name")                                                  1       2       2    2.500µs     5.44
                                                      TOTAL:             execute:   45.916µs    22.51
=====================================================================================================
Optimizer rules applied: filter_reorder, source_filter_pushdown

Disabled, the plan keeps the written order, and the label filter can no longer be folded because it does not follow v() directly:

$ graphersal -e 'g.with("optimizer.disabled", ["filter_reorder"]).v().has("age", P.gt(30)).has_label("person").values("name").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v()                                                             1       0       6    1.417µs     3.91
has("age", P.gt(30))                                            1       6       2    4.084µs    11.27
has_label("person")                                             1       2       2      666ns     1.84
values("name")                                                  1       2       2    2.333µs     6.44
                                                      TOTAL:             execute:   36.250µs    23.45
=====================================================================================================

The rule also works in the middle of a traversal, where no pushdown follows:

$ graphersal -e 'g.v().out().has("lang", "java").has_id("3").values("name").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v()                                                             1       0       6    2.833µs     3.53
out()                                                           1       6       6    5.459µs     6.80
has_id("3")                                                     1       6       3    2.084µs     2.60
has("lang", "java")                                             1       3       3    2.417µs     3.01
values("name")                                                  1       3       3    1.584µs     1.97
                                                      TOTAL:             execute:   80.250µs    17.92
=====================================================================================================
Optimizer rules applied: filter_reorder

Results

For pure filters, the same results in the same order: a run of filters keeps a traverser only if every filter in the run keeps it, whatever their order.

A filter with an effect is never moved, and nothing moves across it: a filter that mutates the graph or writes a side effect, itself (drop()) or anywhere in its child traversals (filter(__.aggregate("x")), where(__.sideEffect(..)), filter(__.property(..))), ends the run like a non-filter step. It therefore sees exactly the traversers it sees in the written order:

$ graphersal -e 'g.v().filter(__.aggregate("x")).has_label("software").cap("x").count(Scope.local).to_list()'
6
$ graphersal -e 'g.with("optimizer.disabled", ["filter_reorder"]).v().filter(__.aggregate("x")).has_label("software").cap("x").count(Scope.local).to_list()'
6

Filters that can raise an error are reordered like any other filter (by design, as TinkerPop's FilterRankingStrategy does): a cheap filter moved in front of one that fails for some elements can drop those elements first, so a query that fails unoptimized may succeed optimized. The results of a query that succeeds both ways are the same.

Interaction with other rules

Runs after Where Unnest, so filters inlined from a where() are sorted too, and before the pushdown rules, which only fold filters that directly follow the start step.

Has ID Pushdown Rule

Rule name: has_id_pushdown (on by default, fourth in the pipeline).

What it rewrites

A has_id(...) filter in the run of filters directly behind a leading v() or e() is removed and its ids are moved into the start step, which then looks the ids up instead of scanning every element:

v().has_id("1", "2")         →   v("1", "2")
v("1", "2").has_id("2", "3") →   v("2")              (the intersection)
v().has_label("person").has_id("1")  →  v("1").has_label("person")
  • If the start step already has ids, the new id list is the intersection of both lists.
  • The rule looks past has_label filters while it searches for has_id (it does not fold the labels; that is Source Filter Pushdown's job).
  • has_id(P.within(...)) is built as a plain has_id and folds the same way.

Why

An id lookup costs one hash-map access per id; the scan it replaces touches every vertex or edge of the graph.

When it does not fire

  • The traversal does not start with v()/e(). A v() in the middle of a traversal (g.v("1").as("a").v()) and child traversals (__.has_id("1")) are left alone.
  • Any step other than has_id/has_label sits between the start step and the has_id: g.v().out().has_id("3") keeps its filter.
  • A has_id with another predicate (has_id(P.neq("1")), has_id(P.gt(...))): it has no fixed id list to fold.

Example

$ graphersal -e 'g.v("1", "2").has_id("2", "3").values("name").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v("2")                                                          1       0       1    7.042µs     6.33
values("name")                                                  1       1       1    5.459µs     4.91
                                                      TOTAL:             execute:  111.209µs    11.24
=====================================================================================================
Optimizer rules applied: has_id_pushdown

With both rules that fold ids disabled, the scan and the filter stay separate (Filter Reorder still moves has_id to the front):

$ graphersal -e 'g.with("optimizer.disabled", ["has_id_pushdown", "source_filter_pushdown"]).v().has_label("person").has_id("1", "2", "3").values("name").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v()                                                             1       0       6    5.500µs     4.56
has_id("1", "2", "3")                                           1       6       3    5.000µs     4.15
has_label("person")                                             1       3       2    3.667µs     3.04
values("name")                                                  1       2       2    5.917µs     4.91
                                                      TOTAL:             execute:  120.541µs    16.66
=====================================================================================================
Optimizer rules applied: filter_reorder

and with both enabled (the default), ids and labels end up in the start step:

$ graphersal -e 'g.v().has_label("person").has_id("1", "2", "3").values("name").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(ids: ["1", "2", "3"], labels: ["person"])                     1       0       2    1.750µs     4.61
values("name")                                                  1       2       2    3.125µs     8.22
                                                      TOTAL:             execute:   38.000µs    12.83
=====================================================================================================
Optimizer rules applied: filter_reorder, has_id_pushdown, source_filter_pushdown

An empty intersection leaves a start step with an empty id list, which produces nothing. The profile renders that empty list as v([]); the Out column (0) shows that nothing was scanned:

$ graphersal -e 'g.v("1").has_id("2").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v([])                                                           1       0       0    1.667µs     1.94
                                                      TOTAL:             execute:   86.000µs     1.94
=====================================================================================================
Optimizer rules applied: has_id_pushdown

Results

Unchanged: g.v("1", "2").has_id("2", "3") returns "vadas" with and without the rule. An id that does not exist is skipped by the lookup exactly as the filter would drop it.

A repeated id in the filter is folded once: the filter's ids are a set (has_id("1", "1") passes vertex 1 once), while a start step's ids are a sequence (g.v("1", "1") yields vertex 1 twice, as in TinkerPop), so g.v().has_id("1", "1").count() is 1 with and without the rule.

Interaction with other rules

Source Filter Pushdown, which runs right after, folds has_id as well, so in the default pipeline the two overlap: disabling only has_id_pushdown produces the same plan. has_id_pushdown is the one that still folds when the ids sit behind more than one has_label (Source Filter Pushdown stops at the second has_label) and Filter Reorder has been disabled. With Filter Reorder on, has_id is moved in front of every has_label first.

$ graphersal -e 'g.with("optimizer.disabled", ["filter_reorder"]).v().has_label("person").has_label("software").has_id("3").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(ids: ["3"], labels: ["person"])                               1       0       0    1.541µs     4.71
has_label("software")                                           1       0       0      333ns     1.02
                                                      TOTAL:             execute:   32.709µs     5.73
=====================================================================================================
Optimizer rules applied: has_id_pushdown, source_filter_pushdown

$ graphersal -e 'g.with("optimizer.disabled", ["filter_reorder", "has_id_pushdown"]).v().has_label("person").has_label("software").has_id("3").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(labels: ["person"])                                           1       0       4    5.375µs     9.38
has_label("software")                                           1       4       0    1.500µs     2.62
has_id("3")                                                     1       0       0       42ns     0.07
                                                      TOTAL:             execute:   57.333µs    12.06
=====================================================================================================
Optimizer rules applied: source_filter_pushdown

Source Filter Pushdown Rule

Rule name: source_filter_pushdown (on by default, fifth in the pipeline).

What it rewrites

The run of has_label(...), has_id(...) and has(key, value) filters directly behind a leading v() or e() is folded into the start step, which then reads its candidates from the label index or by id instead of scanning the whole graph, and checks the property conditions while it reads:

v().has_label("person")                       →   v(labels: ["person"])
e().has_label("knows")                        →   e(labels: ["knows"])
v().has_label("person").has_id("1")           →   v(ids: ["1"], labels: ["person"])
v().has_label("person").has("title", "CEO")   →   v(labels: ["person"]).has("title", "CEO")
  • has_label(a, b) folds as "carries at least one of a, b", which is exactly has_label's meaning. has_label(P.within(...)) folds the same way.
  • has_id folds into the start step's id list (intersected with ids that are already there), like Has ID Pushdown.
  • With ids and labels both folded, the start step looks the ids up and keeps the elements that carry one of the labels.
  • has(key, value) with a plain property name folds as a condition the start step checks on each candidate before it creates a traverser, with exactly the equality of the has step. The profile shows the fused step as one row, v(labels: ["person"]).has("title", "CEO"). Without a property index every candidate is still read, but the ones that fail cost no traverser, no memory and no second pass (on 546 500 person vertices with 500 matches: 18 ms → 11 ms, 42 MB → 40 KB); with one, the next rule, Property Index, lets the start step read only the matches.

Why

The label index answers "every vertex with label person" without touching other vertices. On a graph where a label is a small share of all elements, this replaces a full scan by a read of just that share. A folded has(key, value) keeps the elements that fail it from ever becoming traversers.

When it does not fire

  • The traversal does not start with v()/e() (a mid-traversal v(), a child traversal).
  • The first step after the start step is neither has_label, has_id nor has(key, value). Anything in between (as("a"), out(), a predicate has("age", P.gt(30)), a jpath key has(jpath("a.b"), 1)) stops the rule; the filters after it stay filters. Filter Reorder usually moves has_label/has_id to the front of a run of filters first, so v().has("name", "marko").has_label("person") folds completely.
  • A folded has(key, value) keeps Count Pushdown and Group Count Pushdown from answering from the statistics (they count every element of the label): v().has_label("person").has("age", 29).count() scans and counts the matches.
  • Only the first has_label folds. A second one (v().has_label("person").has_label("software")) stays a filter step, and so does everything after it. This is deliberate: a multi-label vertex tagged {a, b} passes has_label("a").has_label("b"), and intersecting both label lists into one start step could drop it.
  • A has_label with another predicate (has_label(P.neq("person"))) has no fixed label list and is left as a filter.

Example

$ graphersal -e 'g.v().has("name", "marko").has_label("person").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(labels: ["person"]).has("name", "marko")                      1       0       1   78.041µs    15.09
                                                      TOTAL:             execute:  517.042µs    15.09
=====================================================================================================
Optimizer rules applied: filter_reorder, source_filter_pushdown

With the whole optimizer off, the scan touches all six vertices:

$ graphersal -e 'g.with("optimizer.disabled", ["all"]).v().has_label("person").count().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v()                                                             1       0       6    2.875µs    10.18
has_label("person")                                             1       6       4    1.625µs     5.75
count()                                                         1       4       1       41ns     0.15
                                                      TOTAL:             execute:   28.250µs    16.07
=====================================================================================================

and with the default pipeline the label folds into v() (and the count then into the start step, see Count Pushdown):

$ graphersal -e 'g.v().has_label("person").count().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(labels: ["person"]).count()                                   1       0       4    3.500µs    11.21
                                                      TOTAL:             execute:   31.209µs    11.21
=====================================================================================================
Optimizer rules applied: source_filter_pushdown, count_pushdown

Only the first of two label filters folds:

$ graphersal -e 'g.v().has_label("person", "software").has_label("software").count().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(labels: ["person", "software"])                               1       0       6    3.791µs    10.55
has_label("software")                                           1       6       2    1.083µs     3.02
count()                                                         1       2       1       41ns     0.11
                                                      TOTAL:             execute:   35.917µs    13.68
=====================================================================================================
Optimizer rules applied: source_filter_pushdown

Results

Unchanged (4 for the count above, with and without the rule). A vertex that carries several of the requested labels is produced once, not once per matching label, and a repeated label or id in the filter is folded once (g.e().has_label("knows", "knows").count() is 2). The order of the produced elements can differ from a full scan: the folded start step reads them label by label from the index.

$ graphersal -e 'g.v().has_label("software", "person").id().fold().to_list()' -e 'g.with("optimizer.disabled", ["all"]).v().has_label("software", "person").id().fold().to_list()'
["3", "5", "1", "2", "4", "6"]
["1", "2", "3", "4", "5", "6"]

Add an order() step when a query depends on the order.

Interaction with other rules

Property Index Rule

Rule name: property_index (on by default, sixth in the pipeline, right after Source Filter Pushdown).

What it rewrites

It records on a v()/e() start step which property index the step reads instead of its label buckets, and, for a condition the index answers exactly, drops that condition's re-check. .profile() shows the choice on the start step:

v().has_label("person").has("title", "CEO")      →   v(labels: ["person"]).has("title", "CEO") [index: vertex person.title, exact]
v().has_label("person").has("age", P.gt(30))     →   v(labels: ["person"]) [index: vertex person.age]
                                                      has("age", P.gt(30))
e().has_label("knows").has("weight", P.lt(0.5))  →   e(labels: ["knows"]) [index: edge knows.weight]
                                                      has("weight", P.lt(0.5))
v().has_label("person")                          →   v(labels: ["person"]).has("name", __.to_lower().is(P.eq("ada")))
   .has("name", __.to_lower().is("ada"))                  [index: vertex person.name to_lower, exact]
v().has("name", "josh")                          →   v().has("name", "josh") [index: vertex name, any label, exact]
v().has("name", "josh").count()                  →   v().has("name", "josh").count() [index: vertex name, any label, exact] [count from index]
v().has("_owners", __.unfold().is("o1"))         →   v().has("_owners", __.unfold().is(P.eq("o1"))) [index: vertex _owners each, any label, exact]
v().has("_owners", __.unfold().is(P.gt("o1")))   →   v() [index: vertex _owners each, any label]
                                                      has("_owners", __.unfold().is(P.gt("o1")))
v().has_label("doc")                             →   v(labels: ["doc"]) [index: vertex doc.tags each to_lower]
   .has("tags", __.unfold().to_lower().is(P.gte("x")))  has("tags", __.unfold().to_lower().is(P.gte("x")))

It looks at

  • the has(key, value) conditions Source Filter Pushdown folded into the start step (scalar values), and
  • the has(key, P) steps in the run of pure filters (has, has_label, has_id, has_key, has_not) right after it, with P.eq, P.within, P.gt/gte/lt/lte, P.between, P.inside or P.outside, and
  • the has(key, __.to_lower().is(P)) steps in that run (TinkerPop's has(key, traversal) with exactly that child, P as above), which only an index with the transform to_lower on the key covers. Its slices are P's constants as given (the child compares the lowered value with them); it is covered only while that index has skipped no value (skipped 0), because the child's to_lower() fails on a non-string value and the scan must report that error. A null constant is not covered (to_lower() passes a null through, the index holds none).
  • the has(key, __.unfold().is(P)) steps in that run, covered by an index with the transform each (one entry per list element) whatever it skipped (a nested list, a map's entries or a vector that unfold() emits never equals or ranges with a scalar), and has(key, __.unfold().to_lower().is(P)) by ["each", "to_lower"] while it skipped nothing. Any other has(key, traversal) ends the run of pure filters.

A condition on the whole value (a folded has(key, value), a has(key, P)) with no index of no transform on the key is covered by an each index as a SUPERSET: lists holding the value are candidates and the re-check of the whole value drops them; such an access is never exact.

A condition is covered when every label folded into the start step has an index on its key (of the condition's transform: none for has(key, ..), to_lower for the lowered form), or when a label-less index on the key exists: a start step without labels can only read a label-less index; one with labels compares the sum of its per-label estimates with the label-less index's estimate, the lower wins (a tie keeps the per-label indexes), and with the label-less index it checks each candidate's labels. Of the covered conditions the rule picks the most selective by the indexes' statistics (an equality: about entries / distinct_values elements per index and value; a range: half the entries). A unique index is read like any other index (its statistics give an equality about one element; one that is not served, its data holding repeated values, is never read).

Exact accesses

An access is exact (user decision 2026-11-08) when the index answers the condition it reads exactly, so no re-check could drop a candidate:

  • every slice is a point (an equality, or each operand of P.within) of a string, boolean, uuid or temporal value: a number slice spans int64 and float64 (a superset), and null and ranges keep their re-check;
  • the index has no transform (a condition on the whole value), or each reading has(key, __.unfold().is(..)) (an element is in the postings of each of its values once; the start step deduplicates several slices), or to_lower / ["each", "to_lower"] reading has(key, __.to_lower().is(..)) / has(key, __.unfold().to_lower().is(..)) (read only while the index skipped nothing, so in a reading query to_lower() cannot fail and the lowered keys answer the condition; a null constant is never served); not an each index read as a superset;
  • the query does not write at any level (no mutating step, in a child traversal neither: a write could change what the index holds while the plan reads it);
  • the storage claims StorageCapabilities::exact_property_index_lookups (the built-in graph, its read-only views and the wrappers that forward it do; a custom storage's lookups otherwise count as supersets).

Then the re-check of that one condition is dropped: a folded has(key, value) is no longer checked on the candidates (the start step still shows it), a has step leaves the plan and the start step shows it after its folded conditions, and the index marker reads , exact. Every other condition is still checked, and so are the labels of a label-less index's candidates under a start with labels. When nothing else is left (one slice, no other folded condition, and a label-less index under a start without labels or the index of the start's single label) the access is also countable, and Count Pushdown may fuse a following count() into the start step, which the storage then answers from the index (GraphStorage::count_by_property_index) without visiting the elements: .profile() shows [count from index]. Should the storage not serve the index after all, the start step scans and checks the answered condition itself, as the index keys it.

.profile() shows what happened at run time, not only what was planned: when the storage declines a lookup (it lists the index but answers no candidates for it), the marker reads , declined, scanned inside the brackets, and when it does not count a countable slice from the index, [count from index declined] (the candidates were counted instead):

v(labels: ["person"]).has("name", "marko").count() [index: vertex person.name, exact, declined, scanned] [count from index declined]

The fact is recorded once per execution of the start step, never per element.

Why

The start step then reads only the elements whose value lies in the slices of the index, instead of every element of its labels. The conditions it does not answer exactly are not removed: the start step still checks its other folded conditions on each candidate and their has(key, P) steps stay in the plan, so the result equals the scan's (only the order of the elements may differ). An exact condition is not checked twice: the index is maintained exactly on every write and rollback, it is trusted, and a wrong entry would show in the result instead of being hidden by a re-check (the randomized differential tests compare every exact shape with the scan).

When it does not fire

  • No index is declared (the rule then costs nothing), or one of the folded labels has none on the key and no label-less index covers it. Only indexes the storage serves count: an index of a type this version does not know (written by a newer version) is kept in the catalog but never read.
  • The start step has no folded label (v().has("title", "CEO")) and no label-less index covers the key, has ids folded (v("1").has_label(..): the ids are cheaper), or a fused count()/group_count().
  • The condition is not served: P.neq, P.without, text predicates, composites, a list or map value, a jpath key, NaN; a has(key, traversal) whose child is not exactly to_lower().is(P), unfold().is(P) or unfold().to_lower().is(P); a lowered form while its index skipped a non-string value.

g.with("optimizer.disabled", ["property_index"]) turns it off for one query, for example to compare the plan with the label scan.

Barrier Pushdown Rule

Rule name: barrier_pushdown (on by default, sixth in the pipeline).

Despite its name, this rule has nothing to do with barriers: it pushes edge label filters into the edge-walking step in front of them.

What it rewrites

The run of has_label(...) filters directly behind an out_e(), in_e() or both_e() is folded into that step's label parameter:

out_e().has_label("knows")                       →   out_e("knows")
out_e("knows", "created").has_label("created")   →   out_e("created")      (the intersection)

If the edge step already has labels, the folded list is the intersection of both lists. Unlike Source Filter Pushdown, every consecutive has_label folds: an edge carries exactly one label, so intersecting is exact.

The rule fires anywhere in a traversal, not only at its start, and in child traversals too.

Why

An out_e("knows") reads only the matching edges from the vertex's adjacency, instead of creating a traverser for every incident edge and dropping most of them in the next step.

When it does not fire

  • The filter does not directly follow the edge step: out_e().has("weight", ...).has_label("knows") only folds because Filter Reorder first moves has_label in front of has. An as() or any other step in between stops the rule.
  • Vertex steps: out().has_label("person") filters the adjacent vertices, not the edges, and is left alone.
  • has_label with another predicate (has_label(P.neq("knows"))).

Example

$ graphersal -e 'g.v("1").out_e().has_label("knows").in_v().values("name").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v("1")                                                          1       0       1    4.625µs     4.21
out_e("knows")                                                  1       1       2    7.792µs     7.10
in_v()                                                          1       2       2    1.166µs     1.06
values("name")                                                  1       2       2    3.042µs     2.77
                                                      TOTAL:             execute:  109.791µs    15.14
=====================================================================================================
Optimizer rules applied: barrier_pushdown

Disabled, out_e() produces all three edges of vertex 1 and the filter drops one:

$ graphersal -e 'g.with("optimizer.disabled", ["barrier_pushdown"]).v("1").out_e().has_label("knows").in_v().values("name").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v("1")                                                          1       0       1    2.917µs     4.13
out_e()                                                         1       1       3    3.708µs     5.25
has_label("knows")                                              1       3       2    2.708µs     3.83
in_v()                                                          1       2       2      833ns     1.18
values("name")                                                  1       2       2    2.000µs     2.83
                                                      TOTAL:             execute:   70.625µs    17.23
=====================================================================================================

Together with Filter Reorder:

$ graphersal -e 'g.v("1").out_e().has("weight", P.gt(0.4)).has_label("knows").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v("1")                                                          1       0       1   10.458µs     0.48
out_e("knows")                                                  1       1       2   37.375µs     1.70
has("weight", P.gt(0.4))                                        1       2       2  118.209µs     5.38
                                                      TOTAL:             execute:    2.197ms     7.56
=====================================================================================================
Optimizer rules applied: filter_reorder, barrier_pushdown

Results

Unchanged, in the same order: the edge step produces the same edges the filter would have kept.

Interaction with other rules

Runs after Filter Reorder, which brings has_label to the front of a run of filters behind the edge step. Lazy Barrier never inserts a merge point directly behind an out_e()/in_e()/both_e() (each edge is produced once), so the two rules do not compete for the same position.

Group Count Pushdown Rule

Rule name: group_count_pushdown (on by default, seventh in the pipeline).

What it rewrites

A "count per label" directly behind a leading v() or e() is fused into the start step, which then computes the counts from the graph's label index instead of producing one traverser per element and grouping them:

v().group_count().by(T.label)                 →   v().group_count().by(T.label)    (one fused step)
v().group().by(T.label).by(__.count())        →   v().group_count().by(T.label)
e().group_count().by(T.label)                 →   e().group_count().by(T.label)
v().has_label("person").group_count().by(T.label)  →  v(labels: ["person"]).group_count().by(T.label)

The accepted spellings are group_count().by(T.label), and group().by(T.label) followed by by(Count) or by a child traversal that is a plain count(). The fused step keeps any ids and labels that Source Filter Pushdown already folded into the start step.

Why

The counts per label are already known to the label index. Without the rule, the scan creates a traverser for every element and the grouping step reads each element's label and updates a map.

When it does not fire

  • The grouping step does not directly follow the start step: anything between them that was not folded into v()/e() (out(), has("age", ...), a second has_label) stops the rule.
  • The traversal does not start with v()/e().
  • The key is not T.label: group_count().by("age"), group_count().by(__.label()).
  • group().by(T.label) without a second by(), or with a value projection other than a count.
  • The start step was already fused with a count() by Count Pushdown (which runs later, so this only matters for hand-built plans).

Example

$ graphersal -e 'g.v().group_count().by(T.label).profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v().group_count().by(T.label)                                   1       0       1  166.792µs    86.66
                                                      TOTAL:             execute:  192.459µs    86.66
=====================================================================================================
Optimizer rules applied: group_count_pushdown

Disabled, the scan produces six traversers that the grouping step consumes:

$ graphersal -e 'g.with("optimizer.disabled", ["group_count_pushdown"]).v().group_count().by(T.label).profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v()                                                             1       0       6    1.833µs     1.36
group_count().by(T.label)                                       1       6       1  106.208µs    78.70
                                                      TOTAL:             execute:  134.958µs    80.06
=====================================================================================================

Combined with a folded label filter:

$ graphersal -e 'g.v().has_label("person").group_count().by(T.label).profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v(labels: ["person"]).group_count().by(T.label)                 1       0       1    5.458µs    16.21
                                                      TOTAL:             execute:   33.667µs    16.21
=====================================================================================================
Optimizer rules applied: source_filter_pushdown, group_count_pushdown

The rule saves the scan, not the result: the cost of building the result map stays. The large graph gives every vertex its own label (V_0_0, V_0_1, ...), so the result has 111110 entries, building it dominates both plans, and the fused plan only saves the few milliseconds of the scan:

$ graphersal --graph large -e 'g.v().group_count().by(T.label).profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v().group_count().by(T.label)                                   1       0       1   18.220ms    99.83
                                                      TOTAL:             execute:   18.251ms    99.83
=====================================================================================================
Optimizer rules applied: group_count_pushdown

$ graphersal --graph large -e 'g.with("optimizer.disabled", ["group_count_pushdown"]).v().group_count().by(T.label).profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v()                                                             1       0  111110    1.536ms     9.23
group_count().by(T.label)                                       1  111110       1   15.087ms    90.59
                                                      TOTAL:             execute:   16.653ms    99.82
=====================================================================================================

Results

Unchanged. Every vertex is counted once, under its primary label, the value label() returns; a vertex without a label is not counted, with or without the rule. A multi-label vertex counts once, under its first label:

$ graphersal --graph empty -e 'g.add_v(["Person", "Admin"]).next(); g.add_v("Person").next(); g.add_v().next(); g.v().group_count().by(T.label).to_list()'
#{"Person": 2}

Without a label filter, the fused step reads the per-primary-label counts from the storage's statistics (GraphStorage::statistics), which the graph keeps up to date on every mutation: no scan at all, one map entry per label. A storage that keeps no statistics is scanned instead, with the same result. With a folded label filter the fused step fetches the matching vertices once each and groups them by primary label.

In a child traversal that receives several traversers at once (union(__.V().groupCount().by(T.label))), every incoming traverser stands for its own pass over the graph, so the counts are multiplied by the number of incoming traversers, as in the unfused plan.

Interaction with other rules

Runs after Source Filter Pushdown (whose folded filters it keeps) and before Count Pushdown. A count() after the fused step is not folded again; it counts the single map the fused step produces.

Count Pushdown Rule

Rule name: count_pushdown (on by default, eighth in the pipeline).

What it rewrites

A count() directly behind a leading v() or e() is fused into the start step, which then computes the number without producing a traverser per element:

v().count()                        →   v().count()            (one fused step)
e().has_label("knows").count()     →   e(labels: ["knows"]).count()
v("1", "2", "99").count()          →   v("1", "2", "99").count()

How the fused step counts:

Start stepSource of the number
v() / e() without ids or labelsthe graph's element count, no iteration at all
with labels (v(labels: ...))the label index; a vertex carrying several of the labels counts once
with ids (v("1", "2"))one lookup per id; ids that do not exist (or, with labels, whose element carries none of them) are not counted
with a countable index access (one exact equality, folded or a has step it removed, nothing else to check)the entries of the index slice (GraphStorage::count_by_property_index), no element visited; .profile() shows [count from index]

The count() does not have to be the last step: v().count().is(6) fuses as well, and the following steps run on the single count value.

Why

v().count() on an unfiltered graph becomes a constant-time read instead of a scan.

When it does not fire

  • Any step between the start step and count() that was not folded into the start step: v().out().count(), v().has("age", P.gt(30)).count(), v().as("a").count(), a second has_label.
  • A start step with folded has(key, value) conditions or an index access, unless the Property Index Rule marked its index access countable (see the table).
  • The traversal does not start with v()/e().
  • count(Scope.local): it counts the elements of a collection, not the stream.
  • The start step was already fused with a count per label by Group Count Pushdown.

Example

On the large graph (111110 vertices):

$ graphersal --graph large -e 'g.v().count().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v().count()                                                     1       0  111110    3.125µs     4.45
                                                      TOTAL:             execute:   70.208µs     4.45
=====================================================================================================
Optimizer rules applied: count_pushdown

$ graphersal --graph large -e 'g.with("optimizer.disabled", ["count_pushdown"]).v().count().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v()                                                             1       0  111110    1.557ms    98.25
count()                                                         1  111110       1        0ns     0.00
                                                      TOTAL:             execute:    1.585ms    98.25
=====================================================================================================

The fused step's Out column shows the counted number (111110), not the one traverser that carries it.

On the modern graph, combined with Source Filter Pushdown:

$ graphersal -e 'g.e().has_label("knows").count().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
e(labels: ["knows"]).count()                                    1       0       2    1.667µs     5.31
                                                      TOTAL:             execute:   31.417µs     5.31
=====================================================================================================
Optimizer rules applied: source_filter_pushdown, count_pushdown

A count that is not directly behind the start step stays a separate step:

$ graphersal -e 'g.v().has("age", P.gt(30)).count().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v()                                                             1       0       6    1.875µs     4.97
has("age", P.gt(30))                                            1       6       2    5.375µs    14.25
count()                                                         1       2       1        0ns     0.00
                                                      TOTAL:             execute:   37.708µs    19.23
=====================================================================================================

Results

Unchanged: the fused step returns the same number as the scan and the count (4 for g.v().has_label("person").count(), with and without the rule).

In a child traversal that receives several traversers at once, every incoming traverser stands for its own pass over the graph, so the fused count is multiplied by the number of incoming traversers, as the unfused plan counts them: g.v().has_label("software").union(__.v().count()) returns 12 (2 x 6) either way.

Interaction with other rules

Runs after Source Filter Pushdown and Has ID Pushdown, whose folded labels and ids it keeps, and after Group Count Pushdown, which it leaves alone. Where Unnest and Filter Reorder indirectly widen its reach: v().where(__.has_label("person")).count() ends up as v(labels: ["person"]).count().

Lazy Barrier Rule

Rule name: lazy_barrier (on by default, runs last).

What it rewrites

Between two adjacent adjacency steps the rule inserts a merge point, shown as lazy_barrier() in .profile():

v().out().out().count()   →   v().out().lazy_barrier().out().count()

It inserts before out, in, both, out_e, in_e, both_e, out_v, in_v, both_v or other_v when the previous step is out, in, both, out_v, in_v, both_v or other_v (the steps whose output can contain duplicates; an out_e() yields each edge once per input). Modulators between the two are ignored. This follows TinkerPop's LazyBarrierStrategy.

Why

Equal traversers (the same vertex reached along different routes) are merged into one traverser that carries a bulk, so the next step expands each distinct vertex once instead of once per route. On a dense graph this turns an exponential number of traversers into a bounded one. See Bulk and Barriers.

A merge costs a hash insert per traverser and pays only through the work it saves the next step, so on a stream of 4096 traversers or more lazy_barrier() first estimates that saving: over the first 4096 traversers it adds, for every one that would merge into an earlier one, its fan-out on the following step (how many traversers that step would produce from it, counted without producing them). Fewer than one saved output per two traversers and the stream passes through unmerged. A high merge ratio alone is not enough: when the vertices the duplicates meet on have no edges in the next step's direction, merging saves nothing (measured on an org chart: has_label("person").out() gives 1.64M traversers that merge into 183k, but the merge cost 39 ms and saved 12 ms on the following out()). Smaller streams are always merged. If the estimate says merge, the pass still stops early when, after the first 4096 traversers, fewer than one in sixteen merged (and a repeat() stops merging for its remaining iterations). Neither check changes results.

When it does not fire

  • Never across as() or any other non-modulator step: v().out().as("x").out() gets no merge point.
  • Never at the end of a traversal level, and never next to an explicit barrier().
  • Never directly behind out_e()/in_e()/both_e().
  • Nested traversals (repeat() bodies, union() branches) are optimized on their own, so the rule applies inside each of them separately.

In some plans the rule still inserts its step, but the step passes traversers through without merging (the profile row shows Out equal to In):

  • the plan mutates the graph or records full paths (path(), simple_path(), shown as [path: full]), because then no two traversers are equal;
  • withSack(init, Operator) with a merge operator, or withBulk(false): merging is visible there, so only an explicit barrier() merges. See Sack and Operators;
  • g.with("bulk.merge", false), which turns every merge off.

Example

On the modern graph, the six traversers that out() produces hold only four distinct vertices:

$ graphersal -e 'g.v().out().out().count().profile()'
Traversal Metrics
Step                                                         Call      In     Out Bulk       Time    % Dur
==========================================================================================================
v()                                                             1       0       6    6  148.167µs     2.41
out()                                                           1       6       6    6   17.208µs     0.28
lazy_barrier()                                                  1       6       4    6  560.750µs     9.13
out()                                                           1       4       2    2  145.042µs     2.36
count()                                                         1       2       1    1      333ns     0.01
                                                      TOTAL:                  execute:    6.141ms    14.19
==========================================================================================================
Optimizer rules applied: lazy_barrier

$ graphersal -e 'g.with("optimizer.disabled", ["lazy_barrier"]).v().out().out().count().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v()                                                             1       0       6    6.542µs     5.16
out()                                                           1       6       6    7.709µs     6.08
out()                                                           1       6       2    5.584µs     4.40
count()                                                         1       2       1      375ns     0.30
                                                      TOTAL:             execute:  126.792µs    15.94
=====================================================================================================

The Bulk column (shown when some traverser carries a bulk above 1) is the number of traversers the stream stands for; Out is the number of traverser objects. On the tiny modern graph the merge pass costs more than it saves. On the large graph (about 110k vertices) it cuts a three-hop expansion from about 896 ms to about 282 ms (a debug build):

$ graphersal --graph large -e 'g.v().both().both().both().count().profile()'
Traversal Metrics
Step                                                         Call      In     Out    Bulk       Time    % Dur
=============================================================================================================
v()                                                             1       0  111110  111110    5.236ms     1.86
both()                                                          1  111110  222200  222200   52.350ms    18.58
lazy_barrier()                                                  1  222200  111110  222200   72.081ms    25.58
both()                                                          1  111110  222200 1444100   41.948ms    14.89
lazy_barrier()                                                  1  222200  111110 1444100   69.180ms    24.55
both()                                                          1  111110 4884000 4884000   37.058ms    13.15
count()                                                         1 4884000       1       1      500ns     0.00
                                                      TOTAL:                     execute:  281.776ms    98.61
=============================================================================================================
Optimizer rules applied: lazy_barrier

$ graphersal --graph large -e 'g.with("optimizer.disabled", ["lazy_barrier"]).v().both().both().both().count().profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v()                                                             1       0  111110    5.487ms     0.61
both()                                                          1  111110  222200   41.880ms     4.67
both()                                                          1  222200 1444100  203.851ms    22.75
both()                                                          1 1444100 4884000  644.628ms    71.95
count()                                                         1 4884000       1      500ns     0.00
                                                      TOTAL:             execute:  895.971ms    99.99
=====================================================================================================

(Timings are from a debug build and vary between runs; the traverser counts do not.)

With full path recording the merge point is inserted but passes everything through:

$ graphersal -e 'g.v().out().out().path().by("name").profile()'
Traversal Metrics
Step                                                         Call      In     Out       Time    % Dur
=====================================================================================================
v() [path: full]                                                1       0       6    8.458µs     1.71
out() [path: full]                                              1       6       6    7.625µs     1.54
lazy_barrier() [path: full]                                     1       6       6    2.250µs     0.46
out() [path: full]                                              1       6       2    1.417µs     0.29
path().by("name")                                               1       2       2  189.292µs    38.33
                                                      TOTAL:             execute:  493.791µs    42.33
=====================================================================================================
Optimizer rules applied: lazy_barrier

Results

The same multiset of results with and without the rule (2 for the count above, 4884000 on the large graph). Only the order of duplicates may change, because merged traversers are expanded together:

$ graphersal -e 'g.v().out().in().values("name").to_list()'
"marko"
"peter"
"peter"
"peter"
"josh"
"josh"
"josh"
"marko"
"marko"
"marko"
"marko"
"josh"
$ graphersal -e 'g.with("optimizer.disabled", ["lazy_barrier"]).v().out().in().values("name").to_list()'
"marko"
"peter"
"josh"
"marko"
"marko"
"josh"
"peter"
"josh"
"marko"
"peter"
"josh"
"marko"

Interaction with other rules

Runs last, on the final shape of every level: steps that earlier rules fused or removed are no longer between two adjacency steps. Turn it off for one query with g.with("optimizer.disabled", ["lazy_barrier"]), or merge nothing at all with g.with("bulk.merge", false). The path requirement analysis runs after it and decides whether the inserted steps can merge ([path: full] disables merging).

Path Requirement Analysis

See the Execution Options Reference for the full table of every g.with() key, including path.analysis below.

Steps such as path(), select("a") and simple_path() read the path of a traverser: the objects it went through, and the step labels as() attached to them. Recording a path costs memory and time, so Graphersal records only what a later step actually reads. The path requirement analysis decides what that is. It follows the idea of TinkerPop's PathRetractionStrategy.

The analysis runs once for each compiled traversal, after all optimizer rules, because rules fuse and remove steps. A query without a path consumer records no path at all.

Path modes

Each step reports what it reads from the path of its incoming traversers:

StepReads
path(), simple_path(), cyclic_path()the full path
select("a", ...), math("a + b") (every variable except _), add_e().from("a").to("b"), where(P.eq("a")), is(P.eq("a")), has(key, P.eq("a"))those labels
where(), not(), and(), or(), union(), coalesce(), optional(), repeat(), until(), emit(), by(__...), property(key, __...)what their child traversals read
as("a")nothing: it produces the label a

One backward walk over each traversal level then gives every step a mode: what it must write into the paths of its outputs so that every later step finds what it reads.

  • full: the step records each output object as a new path position.
  • labels(a, ...): only an as() with one of these labels records its position, together with its labels. Every other step leaves the path untouched.
  • none: the step drops the path of its outputs.

A string in P.eq("marko") is treated as a label only when some as("marko") exists in the query, so ordinary value comparisons never turn tracking on.

Retraction

Walking backwards, a label stops being needed once the walk passes the as() that produces it. In g.V().as("a").out().as("b").select("a"), only a is stored: as("b") records nothing, because no later step reads b. Steps before the last consumer track the path; steps after it drop it. full is never retracted, because a full path covers every position from the start.

Barriers (fold(), group(), count(), ...) start new paths, so nothing upstream of them is needed for the steps that follow. A pure map right before a fused count() is never executed, so g.V().out().path().count() records nothing.

Nested traversals

A child traversal is analysed with its own backward walk. What its first step still needs is reported as the requirement of the step that holds it. For example, g.V("1").out().where(__.in().simple_path()) makes v("1") and out() record full paths.

When a child's output continues the parent path (union(), coalesce(), optional()), the parent passes its own downstream needs into the child. The child then keeps writing what the parent's later steps read.

Loops

The body of a repeat() is loop-carried: its output feeds the steps after the loop, the until()/emit() conditions, and its own input on the next iteration. It is therefore analysed with the downstream need

need after repeat() ∪ entry(body) ∪ entry(until) ∪ entry(emit)

and the walk is repeated until that need stops growing. This settles within two passes: sets only grow over the finite set of labels in the query, and full absorbs everything. The repeat() step reports entry(body) ∪ entry(until) ∪ entry(emit) upward, on top of what the steps after it read (a loop can end before its first iteration).

For example, g.V("1").repeat(__.out().simple_path()).times(3).values("name") makes v("1") and every step of the body record full paths, while values("name") records nothing:

v("1") [path: full]
repeat(__.out().simple_path()).times(3)
  \> out() [path: full]
  \> simple_path() [path: full]
values("name")

Observing the analysis

.profile() appends the mode to each step that records something:

v("1") [path: full]
out() [path: full]
path()

Kill switch

g.with("path.analysis", false) turns the analysis off: every step records its full path. Use it to diagnose a suspected analysis bug. With the analysis on or off, a query must return the same results.

Storage

Paths live in a per-execution arena. A traverser holds a 4-byte handle to the last position of its path, and positions link to their parent. Siblings produced by one fan-out share their prefix, so extending a path is a single push and cloning a traverser copies no path data.

In-Memory Storage Internals

This page describes how TraversalGraph, the in-memory reference storage, lays out element properties and the ID index, for contributors working on crates/graphersal/src/graph/ and value/property_map.rs. None of it is public API: the GraphStorage trait, PropertyMap's methods, Debug text, equality, serde and the persist format are the same whatever the internal representation. A custom storage is not affected by anything here. What a user sees of it (memory_usage(), shape_bytes, the advice about property order) is on Memory Inspection.

Slots and adjacency

Vertices and edges live in two vectors of slots (graph/topology.rs, an own store that replaced petgraph's StableGraph and keeps its behaviour). A slot index never changes while the element lives: a removed element leaves its slot vacant, and the next insertion of that kind reuses the most recently freed slot first, else appends. g.V() and g.E() walk the slots in order, which is why their order is stable but not insertion order after removals.

Each edge slot holds its source and target and two links: the next edge of the source's outgoing list and the next edge of the target's incoming list. A vertex slot holds the heads of its two lists. A new edge goes to the front of both lists, so out()/in() see the newest edge first; a self-loop is in both lists of its vertex. Removing an edge unlinks it from both lists; removing a vertex removes its edges first.

A vertex slot holds its id, a number for its label set, its property map and its slot generation (96 bytes on a 64-bit target); an edge slot its id, a number for its label, its property map, the generations of itself and its endpoints and the list links (112 bytes). The labels live once per graph in a label table (graph/labels.rs): every distinct edge label and every distinct ordered vertex label SET, so a vertex with labels person, admin costs 4 bytes in its slot, not a list of strings, and vertex_labels() still returns a slice. A materialized element (a vertex or edge value in a result) keeps its stored map's shape: the copy is the shared key list and the values, no key is hashed.

The vectors grow by 1/8 of their capacity at a time once they hold more than 512 slots (below, by doubling, as Vec does; topology::growth_step), so a graph built element by element carries at most about 1/9 of its slots as spare capacity, and the first insert after a load adds 1/8 of the slots instead of doubling them (the generations, the label index's member lists and its per-slot positions follow the same rule; the id index is a power-of-two table and keeps its own spare room after a load). The growth stays geometric, so an insert is amortized O(1). A snapshot load reserves the slots from the manifest's counts, and every load (snapshot, Store, GraphSON, GraphML) ends with shrink_to_fit, which releases the spare capacity (vacant slots stay: indices are stable). The memory report shows live, tombstoned (vacant) and spare slots per kind.

Property maps: Indexed, Shaped and Coded

PropertyMap is a newtype over a crate-internal Repr with three variants:

VariantHoldsUsed for
Indexedan IndexMap<CompactString, ElementProperty> (FNV)every free-standing map: catalog payloads, change sets, results, schema values, every map a caller builds; a stored nested object whose key sequence was seen once or that sits deeper than eight levels
ShapedArc<Shape> (the ordered key list, shared) + Vec<ElementProperty> (this element's values, in key order)every map a TraversalGraph stores per vertex or edge, and the objects nested in its values (see Nested maps below)
CodedArc<Layout> (shape, per position own value or code, the dedup rules' dictionaries, shared) + Box<[ElementProperty]> (own values) + Box<[u32]> (codes)a stored map with values at the top-level keys of dedup rules (Compressed Properties)

An IndexMap slot costs a cached hash, the key and the value (64 bytes) plus its share of the hash index and spare capacity, about 84 to 132 bytes per property. A Shaped slot is the value alone (32 bytes); the keys and their lookup structure are paid once per distinct key sequence. Elements with the same keys in the same order share one Shape, like the hidden classes of a JavaScript engine. Insertion order is externally visible (valueMap(), elementMap(), properties()) and is kept by the shape.

A Shape holds its keys, one KeyPrint per key (length plus the first and last eight bytes, exact for keys up to 16 bytes), the hash of the key sequence and the id of the shape table that interned it. A key lookup in a shape of up to 16 keys scans the prints, which avoids a memcmp per candidate; a wider shape keeps an IndexSet of its keys. The values vector is exactly sized when built or grown; a removed key keeps its slot as spare capacity, so a drop followed by an add, or the rollback of either, reallocates nothing.

Both variants behave identically through the public API. A key-changing mutation of a Shaped map outside the graph (a clone handed out to a caller who then inserts a new key) first converts it to Indexed; a value-only mutation keeps it Shaped. Crate code never assumes a representation: it uses the positional helpers (insert_full, shift_remove_full, get_full, shift_insert, insert_if_absent, indexed_mut). The hot read paths match Indexed first and keep the Shaped arm out of line, so free-standing maps pay nothing for the second variant.

A Coded row exists only under a dedup rule on a top-level key: the Layout (interned per shape, coded positions and rules, in the compression rules' layout table) says for each position whether the row holds the value itself or a 4-byte code into the rule's ValueDictionary (value/dictionary.rs: append-only segments of OnceLock slots that never move, so a read gives &ElementProperty without a lock; appends under a mutex; safe Rust only). A coded row never leaves the graph: Clone, the owned iteration and every mutation through the generic methods turn it into a plain Shaped row first; the graph's write path replaces an existing key in place (a new code, the undo log keeping the old code with its dictionary) and runs every other write on the plain row and codes it again (CompressionRules::code_row). A graph without dedup rules never builds one, and the Shaped read path has no extra check. The own values and the codes are two boxes (no unsafe single allocation, user decision 2026-11-04).

The shape table

Each TraversalGraph owns a ShapeTable (graph/shape.rs): a hashbrown::HashTable of the interned non-empty shapes, keyed by the hash of the key sequence. Interning a key sequence that is already known allocates nothing; the last shape interned is tried before the table.

Transitions. A key-adding write moves a map to the next shape through a cache (shape, position, key) -> shape; a key-removing write through (shape, position) -> shape. An added key goes to the end; the undo log puts a removed key back at its old position, which is why the insertion transition carries a position. Both caches sit behind one-entry memos (a bulk write repeats the same transition) and use a cheap word-mixing hasher over the shape address, the position and the key.

Choke points. Every map enters the graph through insert_vertex_raw / insert_edge_raw (graph/undo.rs), which adopt it: an Indexed map is converted (keys interned, values moved into an exact vector), a Shaped map of another table gets this table's shape for the same keys, and a map of this table is left alone. Since a shape carries its table's id, that last check is one integer comparison. Loads, replay, undo restores, damage repair, checkpoint merges, imports and add_* all go through these two functions. Every in-graph key-changing write goes through ShapeTable::insert_full, shift_remove_full or shift_insert, reached through TraversalGraph::with_vertex_map / with_edge_map (which hand the table and the element's map out side by side). A write through a generic map helper (the jpath writes) is followed by adopt. A map that missed adoption is still correct, it only does not share its keys.

Nested maps. The objects inside a stored value (ElementProperty::Object, also inside arrays) are shaped in the same table, down to eight container levels below the element's own values (NESTED_DEPTH); deeper maps stay Indexed, so the recursive clone, comparison and drop of a deeply nested value keep the frames of a plain IndexMap below that bound. A nested key sequence gets a shape at its second sighting: a key sequence that already has a shape takes it at once, a new one is remembered by its hash (seen_once, at most 65 536 hashes, cleared by shrink_to_fit and so at the end of every load) and interned when it comes again. A map whose keys never repeat (a JSON document keyed by ids) therefore stays Indexed, which is smaller than a shape of its own. Nested maps are shaped by adopt (a map that is not one of this table's yet), by insert_full (the value written), by shaped_copy (change sets) and after a jpath write of the property; they keep their own one-entry memo, so they do not evict the element maps' last shape. They never take the transition caches: a key-changing write inside a value (through the public PropertyMap API) turns that nested map Indexed, which stays correct and is shaped again by the next write of the property. Two Shaped maps of one shape compare their value vectors directly. A snapshot chunk builds a nested map Shaped over a shape of its own from the second sighting of its key sequence in the chunk (no IndexMap); the graph swaps in its own shape when it stores the value, by the same second-sighting rule, and turns the map Indexed in the rare case the rule says the graph has not seen the sequence before, so the stored form does not depend on how the chunk was decoded. On a real code index graph (534k vertices, 2.3M edges) nested shapes save 91 MiB of property memory (7.7 %) and the open takes about 1 % longer; the snapshot bytes are the same except the header's memory estimate.

Sweep. ShapeTable::sweep removes every shape that only the table still refers to (strong count 1) and clears the transition caches and memos, which are keyed by shape address. It runs when a new shape is interned and the table has doubled since the last sweep (at least 64 shapes), on shrink_to_fit, and at the end of a load (finish_load, the GraphSON and GraphML readers). It never runs under &self: reads never touch the table. A shape that anything still refers to (a stored map, an element image in the undo log, a clone in a result) is never removed, so a shape carrying this table's id is always in the table.

Undo. The undo log stores element images and old values with their positions, not handles or shapes. Overwriting an existing key is a value-only change and restores in place. Rolling back an added key removes it again; rolling back a dropped key puts it back at its old position through shift_insert, so the map returns to the very shape it had (restore_stored_property). A dropped element comes back through insert_vertex_raw / insert_edge_raw with its image, whose shape is still this table's (the image kept it alive), so adoption is the one comparison.

Snapshot decode. A snapshot chunk has its own string table, and its elements repeat a few key sequences. The decoder (persist::codec::ChunkShapes) builds each element map Shaped directly, keyed by the sequence of key references, without building an IndexMap and without hashing a key string. These chunk-local shapes belong to no table; the graph re-interns them on adopt, and a one-entry memo (last_foreign) makes a run of elements with the same chunk shape cost one pointer comparison each.

Imports and change sets. The GraphSON and GraphML readers do the same without a string table: they collect each element's keys and values in order in a MapBuilder (graph/shape.rs; a repeated key keeps its first position and its last value, as PropertyMap::insert does) and intern the key sequence in an importer-own table, one per element kind, so the graph adopts the maps through the same last_foreign memo. TraversalGraph::apply_change_set and every replay path copy each added map straight into the graph's own table (ShapeTable::shaped_copy); other storages receive ordinary maps. Coercion, validation, compression, property indexes and change capture run inside insert_vertex/insert_edge as for any write.

Memory accounting. MemoryStats::shape_bytes is ShapeTable::heap_bytes: every interned shape once (its Arc allocation, keys and prints, heap-allocated keys, a wide shape's index) plus the table's and the caches' hash tables. A stored map adds only its value vector (by capacity) and its values' heap to property_bytes; shape_bytes is included in property_bytes.

The ID index

The ID index (graph/index.rs, GraphIndex.nodes / edges) maps an element id to its handle without storing the id a second time. Each table is a hashbrown::HashTable<(u32, u32)>: the element's slot plus a cached 32-bit FNV-1a hash of the id, 8 bytes per bucket and one control byte. The id itself lives once, in the element's weight in the graph, and so does the slot's generation.

  • Lookup probes with the cached hash and confirms a candidate by reading the weight at its slot: the slot must be occupied and hold the id asked for; the handle returned carries the generation the weight holds. Lookups therefore take the graph as an argument.
  • Removal matches by slot and reads nothing from the graph.
  • Growth re-places entries from the cached hash alone (the probe hash is derived from the 32-bit value), so growing the table during a bulk load does no random reads into the graph.

The invariant that makes this sound, kept by the raw insert and remove helpers of graph/undo.rs (the only writers of the ID index):

  • every slot in the ID index is a live slot whose weight carries the id the entry was hashed from (so a slot is in the index at most once);
  • an element's id never changes after insert.

An entry is inserted after its slot's generation is patched and removed by slot right after the element left the graph, before the slot can be reused. Cloning the index together with the graph keeps it valid, since a topology clone keeps every slot. Nothing iterates the ID index; it serves point lookups only, so it keeps no insertion order.

The label index

The label index (graph/index.rs, GraphIndex.node_labels / edge_labels, one LabelIndex per element kind) answers vertices_by_label / edges_by_label, the scans behind has_label and hasLabel-led starts:

  • per label, its members as a Vec of handles in bucket order: insertion order, and a removal moves the last member into the removed one's place (swap_remove), the order the earlier IndexSet per label gave, so label scans return elements in the same order as before;
  • per slot, one u32: the position of the slot's first recorded membership in its label's list, so a removal is O(1) without a hash set per label;
  • a small (slot, label number) -> position map for every further label of a multi-label vertex. A membership is recorded in exactly one of the two places, and the map is asked first; a per-slot position is confirmed against the list (the member at that position has the slot), since it may belong to another label of the same slot.

Every member is a live element, since the raw insert and remove helpers of graph/undo.rs keep the label index in step with the slots, as they do for the ID index; a member's handle stays current because a slot's generation changes only when its element is removed, which removes its memberships first. Removal is by slot and reads nothing from the graph. An element costs 12 bytes (its handle and its position) plus about 21 bytes for each label beyond its first, against about 30 bytes per label membership with a hash set per label (on a graph of 534 thousand vertices and 2.3 million edges: 89 MB before, 34 MB after). Keeping bare slots (8 bytes per element) and building the handles from the slot generations at scan time would save 11 MB more there, but made label scans of that graph 6 to 10 % slower.

Measured effect

On a test graph of 1 million vertices and 3 million edges with 36-character UUID ids:

ChangeOne property per vertexSix properties per vertex, two per edge
Before both1.61 GB live heap2.56 GB
ID index without the second id copy1.29 GB (-20 %)2.24 GB
Shared key lists (shapes)1.09 GB (-15 %)1.43 GB (-36 %)

Building such a graph through the public insert_vertex / insert_edge became 5 to 12 % slower (adopting a caller-built Indexed map costs one allocation and two frees per element); a lookup followed by a property read, what g.v(id).values(..) does, became faster.

Storage Format Specification (store version 4, file version 4)

This page is the normative specification of Graphersal's storage format, store format version 4 with file format version 4 (15; version 5 marks only a layer snapshot, 7.5): the packed snapshot (.gsnap), the write-ahead log (journal), the Store directory and its files, and the single-file container (.gstore). It is written so that a third party can read (and write) these files without Graphersal's code: a backup tool, a converter, a change-data-capture connector that tails the WAL.

The reference implementation is the persist module of the graphersal crate. Where this text and the implementation disagree, it is a bug in one of them; please report it.

Contents

  1. Scope, conformance and terms
  2. Conventions
  3. Value encoding
  4. The store: layout and names
  5. The GRAPH file
  6. The snapshot manifest
  7. Segment files and chunks
  8. The packed snapshot
  9. The write-ahead log
  10. The marks file
  11. The INTENT and ATTIC files
  12. Operations
  13. Damage handling
  14. The single-file container
  15. Versioning
  16. Extensibility
  17. Conformance notes
  18. Time: the instance clock

1. Scope, conformance and terms

The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are to be read as described in RFC 2119. Byte layouts, numeric constants, magic values, names and the rules that tell a valid file from a damaged one are normative. Default sizes (chunk, segment, thresholds) are informative unless a file records them; a reader MUST NOT assume a default where the file states the value.

Terms

TermMeaning
grapha property graph: vertices (an id, a set of labels, properties) and edges (an id, at most one label, an out and an in vertex, properties), plus an optional schema and a catalog of definitions
definitiona named entry of the graph's catalog, stored beside the schema: a saved query, a property index, a compression rule, a scheduled job or an embedding model today, other kinds later (6.3)
commitone committed unit of change (a transaction); it has a commit sequence number and a time
commit_seqthe commit sequence number: u64, the first commit of a graph is 1, every later commit is the previous one + 1; 0 is the position before any commit
positiona commit_seq: the state after that commit
graph_ida UUID (version 7 when created by the reference implementation) naming a lineage: a history of commits. A fork, an in-place rollback and a repair start a new lineage
lineage chainthe list of lineages a store descends from, with the commit at which each child branched off
snapshotthe whole graph at one position: a manifest (with the catalog of definitions), a schema and segment files
chunka self-contained, optionally compressed block of elements inside a segment
WAL, journalthe write-ahead log: a sequence of records, one per commit and one per mark
marka name for a position, recorded in the WAL
targeta position to recover to: a commit_seq, a time, or a mark name
storethe set of files of ONE graph, kept below a root (a directory, a single container file, or memory)
backupa store whose GRAPH file carries a backup marker (12.6)
atticthe part of a store that keeps history an in-place rollback moved aside
donoran intact older copy of damaged data (13)
torn tailthe incomplete end of a file left by an interrupted write; distinguished from damage by the rules of 9.6 and 14.4

2. Conventions

  • Fixed-width integers are little-endian: u8, u16, u32, u64 unsigned, i64 two's complement.
  • uvar is an unsigned LEB128 varint (7 bits per byte, least significant group first, high bit = more bytes follow). A uvar longer than 10 bytes, or one whose value overflows u64, is invalid. Writers MUST write the shortest encoding.
  • svar is a signed integer as zigzag ((n << 1) ^ (n >> 63)) followed by uvar.
  • string is uvar byte length followed by that many bytes of UTF-8. Invalid UTF-8 is invalid.
  • opt_string is uvar 0 for "none", else uvar (length + 1) followed by the UTF-8 bytes.
  • Time is an i64 of microseconds since the Unix epoch, UTC. Commit times of one lineage are monotonic: a commit's time is max(now, time of the previous commit). Commit, mark and checkpoint times and system-journal times of one instance share one monotonic clock: max(now, the latest time the instance wrote); after a restart the floor is the latest time in the WAL and the journal (the floor itself is not stored). Section 18 gives the rules.
  • UUID values and every graph_id are 16 bytes in RFC 9562 network order (big-endian), so that byte order equals the order of the canonical text.
  • Element ids are strings. "Sorted by id" means the bytewise order of the UTF-8 encoding.
  • Checksums are CRC-32C (Castagnoli, polynomial 0x1EDC6F41, reflected, initial value and final XOR 0xFFFFFFFF), stored as u32. "The CRC of bytes a..b" covers exactly those bytes.
  • Reserved bytes and fields MUST be written as zero. A reader MUST ignore reserved bytes unless a section says otherwise.
  • Bounds. Every length or count read from a file MUST be checked against the bytes that remain before anything is allocated for it; a count that the remaining bytes cannot hold is invalid. An uncompressed chunk, single-record WAL body or slice of a commit in parts (9.3.1) is at most 1 GiB; a commit in parts is not bounded by it. A declared uncompressed size of an LZ4 block above 255 * stored length + 64 is invalid.

2.1 Compression codecs

Codec byteCodecStored bytes
0nonethe raw bytes; the stored length MUST equal the uncompressed length
1LZ4one LZ4 block (no frame, no size prefix)
2zstdone zstd frame

Writers compress a block only when it is at least 4096 bytes long and compression makes it smaller; otherwise they store it with codec 0. Other codec bytes are invalid. A reader that does not implement codec 2 MUST report such a block as unsupported, never as damage.

3. Value encoding

One encoding is shared by segment chunks and WAL records. A value starts with a tag byte:

TagValuePayload
0nullnone
1falsenone
2truenone
3int64svar
4float648 bytes, IEEE 754 binary64, little-endian; NaN payloads are preserved
5stringstring
6uuid16 bytes, big-endian
7arrayuvar n, then n values
8objectuvar n, then n pairs of key and value; a key is a string-table reference (uvar) inside a segment chunk and an inline string inside a WAL record
9datesvar days: days since 1970-01-01 (file format version 2)
10localdatetimesvar micros: microseconds since 1970-01-01T00:00:00, wall clock, no zone (file format version 2; read only since version 3)
11datetimesvar micros since 1970-01-01T00:00:00Z (the instant), then svar offset: the UTC offset in seconds (file format version 2; read only since version 3)
12timeuvar micros: microseconds since midnight (file format version 2; read only since version 3)
13durationsvar months, svar days, svar micros, each with its own sign (file format version 2; read only since version 3)
14vectoru8 element (0 f32, 1 f16, 2 i8, 3 bit), uvar dimension, then for i8 the scale (4 bytes, IEEE 754 binary32, little-endian), then the packed components: f32 4 bytes each (binary32, little-endian), f16 2 bytes each (binary16, little-endian), i8 1 byte each (two's complement), bit ceil(dimension / 8) bytes in all, the first component in the most significant bit of the first byte (file format version 2)
15localdatetimesvar seconds since 1970-01-01T00:00:00 rounded down (toward minus infinity), then uvar nanos: the nanoseconds of that second, 0..10^9; wall clock, no zone (file format version 3)
16datetimesvar seconds since 1970-01-01T00:00:00Z rounded down and uvar nanos as in tag 15 (the instant), then svar offset: the UTC offset in seconds (file format version 3)
17datetime with a zone namethe fields of tag 16, then the IANA zone name (Europe/Berlin) as a key: a string-table reference (uvar) inside a segment chunk, an inline string inside a WAL record (file format version 3)
18timeuvar nanos: nanoseconds since midnight (file format version 3)
19offsettimeuvar nanos: nanoseconds since midnight (the local time of day), then svar offset: the UTC offset in seconds (file format version 3)
20durationsvar months, svar days, then the time part as svar seconds rounded down and uvar nanos of that second (0..10^9); each part with its own sign (the time part's sign is that of seconds * 10^9 + nanos) (file format version 3)
21blobrefa reference to a blob of the store (4.6): u8 hash_algo (1 = SHA-256; 0 is invalid; 2..255 a newer writer's algorithm), uvar hash_len (1..=64; exactly 32 for SHA-256), the hash bytes, u64 length of the content (little-endian), u32 CRC-32C of the content (little-endian) (file format version 4)
22..254reservedinvalid in versions 1 to 4
255absentonly where a field explicitly allows it (the before value of a SetProperty mutation, 9.3)
  • The order of object entries (and of property maps, 7.3) is the insertion order and MUST be preserved. A repeated key in one object or property map is invalid.

  • Temporal values use the proleptic Gregorian calendar. Tags 9 to 13 (file format version 2) have a resolution of one microsecond; tags 15 to 20 (version 3) one nanosecond. A writer of version 3 or later writes ONE form per kind: a date as tag 9, a localdatetime as tag 15, a datetime as tag 16 (tag 17 when it keeps a zone name), a time as tag 18, an offsettime as tag 19, a duration as tag 20; every engine value has an encoding, so nothing is refused. A reader of version 3 or later reads tags 9 to 13 as well (a version 2 segment's chunks copied into a newer snapshot keep them). The svar seconds + uvar nanos pairs hold nanoseconds over the years -9999 to 9999 (about ±3.2 * 10^20 ns, more than an i64) and a duration's whole time part. Their ranges are normative; a value outside its range is invalid:

    TagValid payload
    9days within the years -9999 to 9999: -4371587 (-9999-01-01) to 2932896 (9999-12-31)
    10micros within the same days (-9999-01-01T00:00:00 to 9999-12-31T23:59:59.999999)
    11offset within ±64800 (±18:00); both the instant and the local time (micros + offset * 10^6) within the range of tag 10
    12micros in 0..86400000000
    13months and days within i32, micros within i64
    15nanos below 10^9; seconds * 10^9 + nanos within the days of tag 9 (-9999-01-01T00:00:00 to 9999-12-31T23:59:59.999999999)
    16, 17nanos below 10^9; offset within ±64800; both the instant and the local time within the range of tag 15
    18nanos in 0..86400000000000
    19nanos as in tag 18; offset within ±64800
    20months and days within i32; nanos below 10^9 (seconds is an svar, so the time part spans -9223372036854775808 s to 9223372036854775807.999999999 s, the range of java.time.Duration)

    A datetime keeps the offset it was written with; equality and order of two datetimes use the instant only (the offset and the zone name are not compared). The zone name of tag 17 is stored as text, never as an index into a build's own table; the offset is stored as written and is not recomputed from the name. A name the reader's time zone database does not know (a newer database's) is content of a newer writer behind a valid checksum: unsupported content (16 rule 9), never damage; the reference reader refuses the value and the operation, as it does with every unsupported content; ASCII case is ignored when the name is looked up. An offsettime orders by its UTC time of day (the local time minus the offset, not wrapped). A duration is not normalized: P1M, P30D and PT720H are three different values.

  • Vector values (tag 14): dimension is 1 to 65536; a component of an f32 or f16 vector is finite (no NaN, no infinity; -0.0 is valid and equals 0.0); the i8 scale is finite and >= 0 (-0.0 is written as 0.0); the value of an i8 component is code * scale; a bit component is 1.0 for a set bit and -1.0 otherwise, and the padding bits of the last byte are 0. An unknown element byte, a dimension out of range and any other violation are invalid (damage): every element kind of version 2 is defined here. A reader checks the payload length (dimension times the component size) against the remaining bytes before it allocates.

  • Blob references (tag 21): a hash_algo of 0, a hash_len outside 1..=64 and a SHA-256 hash that is not 32 bytes are invalid (damage). An algorithm 2..255 is a newer writer's: the value is decoded and kept, and its blob is carried BY NAME (4.6) by every copy (backups, ZIP archives, forks, repairs, packed snapshots), checked by its length and CRC-32C; it is never read and its hash never computed (unsupported content, 16 rule 9). In this version a blobref appears only in catalog definition payloads (6.3); a writer MUST NOT store one as an element property value.

  • Tags 9 to 14 are invalid in a file of format version 1, tags 15 to 20 in a file of format version 1 or 2, tag 21 in a file of a format version before 4 (15): a reader MUST report such a value as damage, never decode it. A reader takes the version from the header of the file the value is in: a segment chunk from its segment's header (7.1, also when the chunk is read through the chunk index without framing the whole segment), a WAL record from its WAL segment's header (9.1), a definition from the manifest (6.1) or WAL segment it is stored in.

  • Readers MUST bound the nesting depth of arrays and objects (the reference reader defaults to 128 levels and is configurable); writers MUST NOT write more than 4096 levels.

A property map is uvar count followed by count pairs of key and value, with keys encoded as object keys are in the same context.

4. The store: layout and names

4.1 Layout

A store is a set of named files below a root:

GRAPH                         identity and state (5); written with its copy GRAPH.copy
GRAPH.copy
LOCK                          an empty file; the writer's operating-system lock (12.10)
BACKUP                        an empty file; the backup pin (12.10)
INTENT                        present only while a multi-file operation runs (11.1)
marks                         the marks, derived from the WAL (10)
WORKLOAD                      the workload statistics sidecar (4.4); optional, instance data
INSTANCE                      the instance identity of the system journal (4.7); instance data
journal/                      the system journal (4.7); optional
    00000000000000000001.jnl  a journal segment; the name is the first seq it may hold
    tmp-<32 hex digits>       never listed, removed on open
ledger                        the blob ledger, derived from the WAL (10.1); optional
blobs/                        the blobs the store keeps (4.6); optional
    3f/3fa1...e9              one blob: its whole content; the name is the lowercase hex of its hash
    tmp-<32 hex digits>       a blob being written (never listed, removed on open)
models/                       store format version 3 only (Graphersal 0.4.0): the embedding models as
                              files (4.5 "Older stores"); migrated away by the upgrade (15.1)
    model2vec-0123456789ab/   one model; the name is its content address
        graphersal-embed-model.json   its manifest, written last
        config.json  tokenizer.json  model.safetensors  README.md  LICENSE ...
    tmp-<32 hex digits>/      a model being added, copied or removed (never listed, removed on open)
snapshots/
    00000000000000052817/     one snapshot; the name is its commit_seq, 20 decimal digits
        manifest              6
        schema.json           the schema, canonical compact JSON
        v-000000.seg          vertex segments (7), six decimal digits per kind, from 0
        e-000000.seg          edge segments
    00000000000000052000/     a holder: the directory of a pruned snapshot without its manifest,
        e-000002.seg          keeping only files newer snapshots reference (6.2, 12.4)
    tmp-<32 hex digits>/      a snapshot being written (never listed, removed on open)
wal/
    00000000000000052818.wal  a WAL segment; the name is the first commit_seq it may hold (9)
attic/
    20261007T182205Z-00000000000000052001/   one rolled-back history (11.6, 12.5)

LOCK and BACKUP exist only for directories on a file system; other backends provide the same locks without files (4.3). A snapshot directory holds exactly the files its manifest lists. A directory under snapshots/ named by a commit but without a manifest file is a holder: it is no snapshot (it is not listed, loaded or counted) and only keeps segment files that newer snapshots reference (6.2); a prune removes it when no snapshot uses them any more (12.4).

4.2 Names

Every name a store file records (segment paths in a manifest, paths in INTENT, names in ATTIC) is relative to the store root, /-separated, and contains no empty, . or .. part, no \, no : and no NUL. No store file holds an absolute path, an operating-system path, a device, or the target of a symbolic link. A store is therefore relocatable: moved or copied as a whole, it opens unchanged. A reader MUST refuse a recorded name that breaks these rules.

4.3 Backends

The format does not depend on where the named files live. The reference implementation provides three backends behind one directory abstraction:

  • a directory on a file system (names map to files below the root; parts of the tree MAY be symbolic links to other file systems, which are never resolved or recorded);
  • a single container file (14);
  • memory (no durability; locks are in-process flags).

A backend MUST provide: reading a file or a byte range of it; appending to a file (an append MAY tear on a crash); replacing a whole file atomically (GRAPH, GRAPH.copy, marks rewrites, INTENT, ATTIC); an atomic rename; removal of a file or a directory tree; a durability barrier (fsync of a file and of a directory); an exclusive writer lock; and a shared/exclusive backup pin. Files are only ever appended to, cut back, or replaced whole; lengths are logical bytes.

On a file system, a move between two parts of the tree that live on different file systems is done as: copy into tmp-xdev-<name> in the target directory, sync, rename there, sync the directory, remove the source, sync its directory. Leftover tmp-xdev-* names MUST be ignored by every listing.

4.4 The workload statistics sidecar

WORKLOAD holds the instance's workload statistics (book page "Workload Statistics"): data of the running instance, not of the graph. It is never in the WAL, never in a snapshot, and never copied by a backup, a ZIP backup, a fork, a repair or a conversion; a restored or copied store starts without it. An upgrade into a copy (15.1) keeps it: the copy is the same store. A writable store replaces it whole (write_atomic) periodically and at close.

magic "GRWLSTAT" | version u32 = 2 | series count u32
per series: byte length u32 | kind u8 (1 job, 2 lock, 3 query, 4 property)
            | name (u32 length + UTF-8; a property series: the key, "*" for all)
            | channel u8 (0 host, 1 playground, 2 mcp, 3 cli, 4 python, 5 job)
            | kind 4 only: element u8 (0 unstated, 1 vertex, 2 edge) | label flag u8
              [+ label (u32 length + UTF-8)] | access u8 (0 filter_scan, 1 filter_index,
              2 read, 3 order_group, 4 similarity, 5 write, 6 remove)
            | tier count u8 | per tier: tier u8 (0 minutes, 1 hours, 2 days) | bucket count u16
            | per bucket: index i64 (the bucket's start in minutes/hours/days since the Unix
              epoch, UTC) | count u64 | failed u64 | items u64 | total microseconds u64
              | max microseconds u64
job count u32 | per job: name | started_at i64 (microseconds) | microseconds u64
            | error flag u8 [+ error text]
section count u32 | per section: tag u8 | byte length u32 | bytes        (version 2; may be absent)
    tag 1, the system jobs' settings: count u32 | per job: name | schedule flag u8
            [+ cron text] | enabled u8 (0 unset, 1 off, 2 on)
    tag 2, the storage advisor's marks (book page "Optimize"): count u32 | per mark: id
            | dismissed flag u8 [+ until i64, microseconds; i64::MAX = for good]
            | applied flag u8 [+ at i64 | kind | title | promised bytes i64 | bytes before u64]
CRC-32C u32 of everything before it

All integers little-endian. Version 1 has no sections and is still read; in version 2 the sections may be left out (no settings). A section of a tag the reader does not know is skipped by its byte length. The settings of the system jobs (book page "Scheduled Jobs") and the advisor's marks are data of the instance like the statistics: they are lost with the file. A reader MUST treat the file as optional: a missing file, a wrong magic, length or checksum, or a version it does not know means "no statistics" (it starts anew and replaces the file at its next write), never damage, never a reason to refuse the store. A series of a kind or channel it does not know is skipped by its byte length, a tier it does not know by its bucket count; a reader keeps at most 60 minute, 48 hour and 90 day buckets. The magic is none of a segment's or a WAL segment's, so the version guard (15) ignores the file.

4.5 Embedding models

An embedding model the store keeps (book page "Embedding Models in a Store") is ONE blob (4.6) holding all its files as a deterministic tar, referenced by a catalog definition of kind 5 (model, 6.3) that follows the history: every position (commit, mark, snapshot, rollback, view) has exactly the models, and the default model, of that moment. A model enters a store only by an explicit import (one commit defining it) and leaves its current state only by a removal (one commit dropping the definition, refused while the current schema needs the model); its blob goes with the prune that drops the last retained history referencing it (12.4). The identity stays the link between a schema's vector properties (their embedder) and the model: model2vec/<repo>@<12 hex>, the first 12 lowercase hex digits of the SHA-256 of the text model2vec-identity/1\n followed by one line <role> <size> <sha256 hex>\n per identity file, for the roles config, tokenizer and model in that order (the rule of the Model2Vec loader; no path is part of it).

The tar. POSIX ustar (magic "ustar\0", version "00"): one regular-file entry (typeflag '0') per file, entries sorted by name bytewise, mode 0000644, uid/gid 0, uname/gname empty, mtime 0, devmajor/devminor 0, prefix and linkname empty, the checksum as ustar defines it (six octal digits, NUL, space), the size as eleven octal digits and a NUL (so a file is at most 8 GiB - 1), the data padded with zeros to 512 bytes; the end is two zero blocks and nothing after them (a reader accepts further zero bytes only). No directories, links, pax or GNU headers. The same files give the same bytes, so the same blob hash.

Files. The model's own files (the three identity files under the names they had, for example config.json or config_sentence_transformers.json, tokenizer.json, model.safetensors), its card README.md, the repository's licence and notice files (LICENSE*, LICENCE*, COPYING*, NOTICE*), and the manifest graphersal-model.json. Every file name is 1 to 40 bytes of ASCII letters, digits, ., _ and -, not starting with .. A model has at most 64 files besides its manifest. When the repository has no licence file, the writer adds the standard text of an MIT or Apache-2.0 license as LICENSE (license_text template); for every known base-model licence other than license with a bundled text, the file LICENSE-BASE-<licence> (lowercase SPDX id, role license), since parts of a base model (such as a tokenizer) may be in the model.

Manifest (format 3; compact UTF-8 JSON, keys in this order, absent optional keys left out, so the bytes are deterministic; at most 1 MiB):

KeyContent
format3; a reader that sees a higher value does not load the model
familymodel2vec
identitymodel2vec/<repo>@<12 hex>: MUST match the files
repothe Hugging Face repository (name or owner/name)
revision, committhe revision asked for, the commit it resolved to (optional)
licensethe licence as an SPDX id as the repository states it, else unknown
license_textfile (a licence file of the repository), template (the standard text the writer added) or none
base_models[{repo, license?}]: the models this one was made from
gatedwhether the repository is gated (its terms may restrict passing the model on)
files[{name, role, size, sha256}], sorted by name: every file of the tar but the manifest; role is config, tokenizer, model (exactly one each), card, license, notice

No time stamp is part of the manifest or the definition (when a model was added is instance data, never part of the immutable model).

Reading. A reader reads the tar as a stream, entry by entry (this version's model load and verify never hold the whole blob in memory): every header's checksum is checked, sizes are bounded by the remaining bytes, names validated; an unknown type flag, a duplicate or unsorted name, more than 64 files besides the manifest, a manifest that does not list exactly the tar's files are invalid content of the model's blob (never damage of the store, 13). The files are used where they are (no extraction to disk).

Needed models and the open. A model the CURRENT schema needs (a vector property's embedder naming its identity) is loaded when the store opens, in every mode (also read-only, a backup, a view of a past position). A needed model that is not in the catalog of that position, whose blob is missing or damaged, or whose files do not load refuses the open (model_unavailable), with the commands that bring it back; one whose load would take the process over its memory ceiling refuses it too (model_does_not_fit): the check uses the blob's length times 1.6 before anything is read (versions up to 0.5.2: length plus the definition's load_bytes), and the message names the smallest ceiling that fits. A writable open records the refusal in the journal (model.load_failed, 4.7) best effort. A model of a family or blob algorithm the reader does not know opens the store read-only (16 rule 9); a reader that cannot run models at all (no Model2Vec loader, such as the browser) checks the needed blobs by length and CRC-32C and opens the store read-only without text queries. A model nothing needs is loaded at the first query that embeds with it; a missing or damaged one is a journal record (model.unavailable), the store works.

Copies. The models travel as blobs: every copy carries the blobs its history references (4.6, 12.x) and the definitions with the catalog, so the copy has the models of every position it holds.

Older stores. Graphersal 0.4.0 kept models as models/<model2vec-12hex>/ directories with a manifest graphersal-embed-model.json (format 2, with added_at), outside the history, carried by every copy as files and by a packed snapshot as segment-table rows of kind 3. A store of store format version 4 has no models/: the upgrade (15.1) migrates each such model into a blob (the tar above, its manifest rebuilt from the old one) and one commit defines them all. A packed snapshot with kind-3 rows imported into a store is migrated the same way (the new store's first commit after the snapshot defines the models; into an open store each is imported).

4.6 Blobs

A blob is an immutable file of the store, named by the hash of its content and referenced from values by a blobref (3, tag 21): hash_algo, the hash, the content's length and its CRC-32C. The hash is the blob's identity (computed when the content is written or arrives from outside, and by a verification); the CRC-32C checks every read; the length is checked, and used for memory decisions, before reading.

blobs/
    3f/3fa1...e9                  a SHA-256 blob: blobs/<first 2 hex digits>/<64 hex digits>
    algo-<n>/3f/3fa1...           a blob of another algorithm n (2..255): its own directory
    tmp-<32 hex digits>           a blob being written (never listed, removed on open)
  • Names are lowercase hex; a blob file holds exactly the content, uncompressed. Anything else under blobs/ is invalid (a verification lists it).
  • Writing. The content is streamed into blobs/tmp-<random> while its SHA-256, CRC-32C and length are computed (constant memory), the file is synced; when a blob of that hash exists and its length and CRC-32C are intact the new file is dropped (deduplication), otherwise (none, or a damaged one) the file is renamed to its name and both directories are synced. The commit that references the blob comes AFTER. Several writers may write the same blob at once.
  • Reading. A missing file, a length other than the reference's and a CRC-32C mismatch are failures of that blob only. A reader checks the length before it allocates.
  • Referenced set. A blob is kept exactly as long as some retained history references it (12.4): the blob tables of the snapshots (6.2 item 5), the ledger (10.1) and the attic entries' WAL. A blob no retained history references is removed by a prune, an attic removal or a rollback delete (12.4, 12.5); a blob written and not yet referenced by a durable commit is kept by the writer that wrote it until its commit.
  • Damage. A missing or damaged blob is NOT damage of the store (13): the damage policy does not apply, the store keeps working, and only what needs the blob's bytes fails. Any copy of a blob with the same hash is the same bytes.
  • The version walk (15) does not read blobs/ (a blob may hold any bytes) nor ledger.

4.7 The system journal

The system journal (book page "System Journal") holds operational events of the instances that wrote the store: opens and closes, checkpoints, backups, prunes, damage, rollbacks, permission denials. Nothing reads it to decide anything: a missing, cut or damaged journal changes nothing of the store, is never damage (13) and never stops an operation; verify lists its problems as notes (12.9).

INSTANCE (instance data: never copied by any copy path, an upgrade into a copy included; regenerated when missing or unreadable):

magic "GRSLINST" | version u32 = 1 | instance id 16 bytes (big-endian) | reserved 28 bytes, zero
| CRC-32C u32 of bytes 0..56 | name (LEB128 length + UTF-8) | CRC-32C u32 of the name's bytes

The id is a random version-7 UUID, the name the configured instance name, else the host name.

Segments journal/<20 digits>.jnl: the name is the first seq the segment may hold. A segment starts with a 64-byte header:

OffsetSizeField
08magic GRSLJRNL
84file format version (15)
1216the instance id that writes the segment (big-endian)
288the first seq it may hold (= the file name)
368created at, µs
4416reserved, zero
604CRC-32C of bytes 0..60

Then record frames (26 bytes + payload):

OffsetSizeField
04sync marker u32 0x4A525347 (bytes 47 53 52 4A; not the WAL's)
44payload length (at most 1 MiB; checked before allocating)
88seq
161level: 0 error, 1 warn, 2 notice, 3 info (a larger value is shown as info)
171reserved, 0
184CRC-32C of bytes 0..18
224CRC-32C of the payload
26npayload (uncompressed)
payload = origin 16 (big-endian) | origin_seq u64 | time i64 (µs) | source | kind | message
        | presence u8 (bit 0 op, bit 1 parent, bit 2 commit, bit 3 principal; other bits:
          newer content, kept)
        | [op u64] [parent u64] [commit u64] [principal]
        | fields: a property map with inline keys (3)
        | origin name                                  (strings: LEB128 length + UTF-8)
  • A record's seq is local and never reused: the next writer continues after the last valid record of the newest segment (after a damaged newest segment, after its name plus the frames it holds). (origin, origin_seq) identifies a record across copies; records of another origin keep theirs.
  • Torn tail and damage follow 9.6: a frame cut by a crash at the end of the newest segment is a torn tail, cut by the next writer; a frame whose header CRC fails is skipped by resyncing on the next sync marker with a valid header CRC, one whose body CRC fails by its length. Sealed segments (every one but the newest) never change.
  • A new segment starts when the current one exceeds its size (default 4 MiB), when the instance of the open differs from the newest segment's header (a restored copy, another machine), when the newest segment has another file format version or damage, and after a failed write.
  • An unknown kind, level or presence bit is shown, never damage (16 rule 9); a field value of a newer value tag makes only that record's fields unreadable (shown as fields_unreadable).
  • Writing: error records are written and synced at once; the others are written in batches (before a checkpoint, by the instance's periodic flush, at close). A read-only open (a backup, maintenance mode, 16 rule 3) and a store in which damage was found while it is open (13.3, either policy) write no journal records; their new records stay in memory.
  • Copies: 12.6 to 12.8 and 12.11 carry the journal; a fork, an attic fork and a repair do not (a new store: its first record store.created names the source); a packed snapshot (8) does not.

5. The GRAPH file

5.1 Layout

A fixed part of 256 bytes, followed by the lineage chain:

OffsetSizeField
08magic GRSLGRPH
84store format version (u32, 3; see 15)
124state: 0 = closed cleanly, 1 = open (a writer has it, or it was not closed cleanly); another value in an intact file (both checksums valid) is a newer writer's: the store is refused as unsupported, never damage (16 rule 9)
1616graph_id of the current lineage
328created at (time)
404lineage entry count n (at least 1)
444chunk target size in bytes, fixed when the store is created
484flags (5.2)
528WAL cut: segment (its first commit_seq); zero unless flag bit 1
608WAL cut: byte offset in that segment; zero unless flag bit 1
688backup marker: the last commit the backup holds; zero unless flag bit 2
768backup marker: taken at (time); zero unless flag bit 2
848wal_head: the first commit_seq (the name) of the newest WAL segment; zero unless flag bit 3
928closed_at: the last commit at a clean close; zero unless flag bit 4
10016store_id: the store's identity, random, never zero (5.5)
116136reserved, zero
2524CRC-32C of bytes 0..252
25632 × nlineage entries, newest first: graph_id (16), branched at commit_seq (u64), at time (i64)
256 + 32n4CRC-32C of the lineage entries

The file's length MUST be exactly 256 + 32n + 4. The first lineage entry's graph_id MUST equal the one at offset 16. The root entry (the last) has branched at 0. A store_id of zero is invalid (the file is damaged).

5.2 Flags

BitMeaning
0reserved for parity data; MUST be 0 in store format versions 2 and 3
1a WAL cut is recorded (offsets 52, 60; 12.2)
2the store is a backup (offsets 68, 76; 12.6)
3wal_head is recorded (offset 84; 9.8)
4closed_at is recorded (offset 92; 9.8)
5the damage policy is continue (13.3); clear: maintenance, the default
6..31reserved; a writer MUST preserve unknown bits it read

Bit 5 is a creation parameter like the chunk target size (offset 44): it is set when the store is created and never changed; every writer of GRAPH keeps it, and every copy of the store (fork, repair, conversion, backup, restore, a backup from memory) carries it. A reader that does not know it treats the store as maintenance, the safe default. A repair that finds both GRAPH copies unusable cannot read it and writes the default.

A GRAPH file without bits 3 and 4 (written before they existed) means "unknown": the checks of 9.8 are skipped.

5.3 Two copies

GRAPH is written as two files, GRAPH.copy first and then GRAPH, each through a temporary name (<name>.tmp), fsync and an atomic rename; then the directory is synced. A reader uses: both valid and equal, either; both valid and different, the one with the longer lineage chain, on a tie GRAPH.copy (it was written first, so it is the newer); one valid, that one. A read-write open that found the copies different or one of them invalid rewrites both (and reports it). Both invalid is damage (13).

5.4 The lineage chain

The chain records every lineage the store descends from. A fork's chain is [new id, branched at the target commit, time] followed by the parent's chain; an in-place rollback adds such an entry in the same store; a repair starts a new lineage whose chain continues the damaged store's. An ancestor lineage is valid only up to the branched at of its child entry: a WAL record of an ancestor beyond that commit does not belong to this store's history. A file (a WAL segment, a snapshot manifest) whose graph_id is not on the chain MUST NOT be replayed.

5.5 The store identity

store_id (offset 100; new in store format version 2) identifies the STORE, where graph_id identifies a lineage of its data. It is a creation parameter: a create writes a new random one (128 bits, like a lineage id), and every writer of GRAPH keeps it. A fork, an attic fork (12.5), a repair (13.4) and a conversion to another backend are new stores with a new store_id (their lineage chain still names the parent); an in-place rollback, an attic restore, a compaction, a restored backup (12.6, 12.8) and an upgrade (15.1) keep it: a restore IS the store, an upgrade is the same store in a new version. Every backup (full, increment, ZIP, from memory) records its source's store_id, and an increment requires it to be equal (12.7).

6. The snapshot manifest

manifest = fixed part (4096) | variable part | CRC-32C of the variable part (u32) | copy of the fixed part (4096).

6.1 Fixed part

OffsetSizeField
08magic GRSLMANI
84format version
124flags (bit 0: incremental, the segment table references files of older snapshots; other bits reserved)
1616graph_id
3216parent graph_id (zero if none)
488parent commit_seq
568commit_seq: every commit up to and including it is contained
648created at (time)
728last commit at: the time of the commit at commit_seq
808node_sequence: the vertex auto-id sequence
888edge_sequence: the edge auto-id sequence
968vertex count
1048edge count
1128vertex property count
1208edge property count
1288estimated in-memory bytes of the loaded graph (lets a loader refuse a snapshot that does not fit a memory budget before reading it)
1368schema.json length
1444schema.json CRC-32C
1484segment count
1528offset of the variable part: 4096
1608length of the variable part: from offset 4096 up to, not including, its CRC
1682name length (bytes, at most 255)
170255name: UTF-8, name length bytes followed by zeros (optional, human-readable)
4253reserved, zero
4284chunk target size in bytes
4323660reserved, zero
40924CRC-32C of bytes 0..4092

Listing the snapshots of a store reads only the first 4096 bytes of each manifest. A reader uses the head copy and falls back to the tail copy when the head's CRC fails.

6.2 Variable part

In this order:

  1. meta: string (empty = none). Free-form text the format never interprets.
  2. Segment table: segment count rows of kind u8 (1 vertex, 2 edge, other kinds 7.5; 0 is invalid) | path string | first id string | last id string | element count u64 | byte length u64 | CRC-32C u32 of the whole segment file. Vertex rows precede edge rows, rows of other kinds follow the edge rows; vertex and edge rows of one kind are ordered by id range and their ranges never overlap. A path is v-NNNNNN.seg or e-NNNNNN.seg in the snapshot's own directory, or, in an incremental snapshot (flag bit 0), a reference: a name relative to snapshots/ such as 00000000000000001000/v-000003.seg, exactly two parts, a 20-digit snapshot name and a file name (see References below).
  3. Definitions: the definitions table (6.3).
  4. Chunk index: uvar row count, then rows of segment number u32 (its position in the segment table; it MUST name a vertex or edge row) | chunk offset u64 | first id string | last id string | chunk CRC u32 (the value of 7.2), grouped by segment in table order. With it the id range of a damaged chunk is known even when the segment's own footer is damaged.
  5. Blob table (file format version 4; absent in a manifest of an older version, which references no blob): uvar row count, then rows of a blobref payload (3, tag 21, without the tag) | refs uvar (>= 1): every blob the snapshot's state references with the number of references, rows strictly increasing by (hash_algo, hash bytes). In this version only catalog definitions (6.3) reference blobs. A merged checkpoint (12.3) writes the table of its whole catalog, the same table a full encode writes. A packed export keeps it as it is.

schema.json holds the stored schema as canonical compact JSON (an empty schema of mode none when the graph stores none); its length and CRC MUST match the manifest.

References (incremental snapshots). A reference names a vertex or edge segment file of an OLDER snapshot of the same store, unchanged; its row (kind, ids, count, length, CRC) and its chunk index rows are those of the referenced file. Rules:

  • A manifest with a reference MUST have flag bit 0 set; a reference in a manifest without it, a reference that is not <20 digits>/<file name>, and a row of another kind than 1 or 2 with a / are invalid.
  • Every segment a manifest lists, a referenced one too, carries the manifest's graph_id in its header (7.1): a snapshot of a new lineage (after an in-place rollback) references no file of an older lineage.
  • A reference is resolved in the directory that holds the snapshot: snapshots/ of the store, or of an attic entry (11.2) for a snapshot moved there; a referenced file not found next to a snapshot of an attic entry is resolved in the store's own snapshots/.
  • The referenced file may lie in a snapshot directory or in a holder (4.1). Reading, verifying and loading an incremental snapshot check the referenced files exactly like its own.
  • A writer MUST NOT reference a file that the store's newest snapshot uses (the donor rule of 12.3): a new snapshot references only twins of the newest snapshot's files, held by the snapshot before it.
  • A packed snapshot (8) is self-contained and has no references: writing one from an incremental snapshot names each segment v-NNNNNN.seg/e-NNNNNN.seg by its position per kind and clears flag bit 0 (the manifest is re-encoded; the segment sections are the files' bytes).

6.3 The definitions table

The graph's catalog of definitions: named, typed entries stored in the database beside the schema (saved queries, property indexes, compression rules, scheduled jobs and embedding models today). One self-describing table serves every kind, present and future, so that a new kind needs no new layout and no new version (16).

definitions = uvar count | definition*
definition  = kind u8 | flags u8 | name string | length uvar | payload (length bytes)
flags       = bit 0: critical (a reader that does not know `kind` MUST NOT write the store, 16);
              bits 1-7 reserved: written as zero, preserved as read
payload     = property map (3) with inline keys (as in a WAL record)
  • The rows are ordered by kind, then by name bytewise, strictly increasing: a kind and name appear at most once. A table out of this order is invalid.
  • length MUST NOT exceed the bytes that remain; the payload is exactly length bytes.
  • The payload of every kind, known or not, is a property map. Its keys MUST NOT be kind, name or flags: these are the envelope keys of the exchange form of a definition, a JSON object that puts the payload keys beside them. A writer never writes such a key; a reader that decodes the payload treats one as invalid.
  • A reader that knows the kind decodes the payload. A payload that is not a valid property map (truncated or invalid bytes, trailing bytes, a repeated or reserved key) is damage (13; a repair takes the catalog from a donor, 13.4). A valid map is NEVER damage (16 rule 9): keys the reader does not know are ignored and kept (16 rule 1); an unknown VALUE of a known key it can represent (a compression codec, element or path, an index element, type or transform, a saved query's parameter schema) keeps the definition, not served, its payload written back exactly as read; a map it cannot read as its kind at all (a missing or mistyped known key) keeps the definition as opaque bytes like an unknown kind (16 rules 2 and 3).
  • A reader that does not know the kind keeps the definition as opaque bytes (kind, flags, name, payload) and writes it back unchanged (16 rules 2 and 3).
  • A load does not validate a definition beyond this (as it does not validate data against the schema, 12.1); a saved query whose source no longer compiles is loaded and fails when called.
KindDefinition
0invalid
1saved query
2property index
3compression rule
4scheduled job of a user (since 0.3.0)
5embedding model (since 0.5.0, 4.5)
6property index of an extended form (since 0.6.0): a label-less index; always critical
7..127unassigned (assigned only by this format)
128..255host kinds: reserved for applications built on the library, never assigned by this format (16 rule 8)

An embedding model (kind 5, not critical: a reader that does not know the kind keeps it and serves no model) is named by the model identity (model2vec/<repo>@<12 hex>, at most 256 bytes; for a family the reader does not know, any name of 1 to 256 bytes). Its payload keys, in this order, followed by the keys the writer does not know:

KeyValue
blobblobref (3, tag 21): the model's tar (4.5)
familystring: model2vec; another family is kept, written back unchanged, not served
repostring: the repository, the model's user-visible name (required)
revision, commitstrings (optional)
dimensionint64: the vector dimension
load_bytesint64: the import's estimate of the memory the loaded model takes (the f32 embedding matrix plus the tokenizer file). Still written; read by the memory check of versions up to 0.5.2 only (later versions check the blob's length times 1.6 and show the size measured at the load)
license, license_textstrings, as the manifest's (4.5)
base_modelsarray of {repo, license?}
gatedboolean
defaultboolean, absent = false: the default model

A catalog holds at most one model per repo (the current revision) and at most one default (a writer refuses a second; a replace drops the old revision and defines the new one in one commit). A model of an unknown family or blob hash algorithm is kept, listed as unsupported and written back unchanged, never loaded.

A saved query (kind 1) is one Rhai function (or one GQL query) stored as text and called by name; its name is an identifier ([A-Za-z_][A-Za-z0-9_]*, at most 128 bytes). Its payload keys, written in this order, followed by the keys the writer does not know in the order it read them:

KeyValue
folderstring: a /-separated folder path; absent = the root
descriptionstring; absent = none
dialectstring: the language and content version of source: "graphersal-rhai/1" (a Rhai function that reads), "graphersal-rhai/2" (a Rhai function that may write), "graphersal-gql/1" (a GQL query that reads), "graphersal-gql/2" (a GQL query that writes); a reader that does not run a dialect keeps the query unchanged and lists it as not runnable
sourcestring: the Rhai function text, or the GQL query text
paramsstring: canonical compact JSON of an object, parameter name -> {"schema": <schema node>, "default": <value>} (default absent when the parameter has none), in declaration order
metastring, free, never interpreted; absent = none

source is required; every other key is optional. The text is stored, never a compiled plan: every call plans it anew. A params value the reader cannot read (a schema keyword or a parameter form of a newer writer) keeps the query: it is listed with the reason, written back exactly as read and refused when called (since 0.2.1; the exchange form a user imports stays strict).

A compression rule (kind 3, not critical) keeps the strings of one element kind and label at one property path compressed in memory (book page "Compressed Properties"). Its name is an identifier as for a saved query. The data in snapshots and the WAL is ALWAYS plain: the rule describes only the in-memory representation, so a reader that does not know the kind loses nothing but the compression, and a load compresses the rule paths again. Its payload keys, in this order, followed by the unknown keys:

KeyValue
elementstring: "vertex" or "edge"
labelstring: the label
pathstring: canonical jpath text of object keys only ($.details.career.cv)
codecstring: "lz4" (each value compressed) or "dedup" (each distinct value held once in memory; since 0.2.1; on a top-level key every value type since 0.6.0)
min_bytesint64: strings shorter than this (UTF-8 bytes) stay plain, 1 to 16777216 (lz4), 0 to 16777216 (dedup; 0 since 0.6.0, which 0.5.2 and older refuse)
dictionaryboolean: whether the load builds a dictionary from the rule's values (lz4 only; true with "dedup" is invalid)

label and path are required; element defaults to "vertex", codec to "lz4", min_bytes to 256 (lz4) or 0 (dedup; 25 before this version, whose rules always stored it), dictionary to true (lz4) or false (dedup); writers always write min_bytes and dictionary. A codec or an element the reader does not know, or a path it cannot parse (a newer writer's), is NOT damage and needs no new format version (16 rules 1 and 9): the reader keeps the definition, writes its payload back exactly as read (every key, in the order read), does not apply it (the values stay plain in memory as on disk) and lists it as not applied with the reason; a front end never creates such a rule. The codec changes no stored data, which stays plain. Two rules with the same element, label and path (compared as read) are invalid (a writer refuses the second).

0.2.0 decodes an unknown codec as an invalid payload, that is as damage: it reads a store holding a dedup rule (0.2.1) as damaged from that commit on and proposes a repair that would drop commits. Open such a store with 0.2.1 or later only; 0.2.1 and later follow the rule above.

A scheduled job (kind 4, not critical; since 0.3.0) runs an action on a cron schedule (book page "Scheduled Jobs"). Its name is an identifier as for a saved query. A reader that does not know the kind keeps it and never runs it. Its payload keys, in this order, followed by the unknown keys:

KeyValue
schedulestring: a 5-field cron schedule, at most 256 bytes
actionstring: "query", "checkpoint" or "backup"
querystring: the saved query a query job calls (query jobs only)
argsobject: its arguments by parameter name (query jobs only)
pathstring: the directory a backup job writes (backup jobs only)
enabledboolean
timeout_msint64: the longest a run may take, in milliseconds; absent = no limit
memory_limitint64: the most memory a run may use, in bytes; absent = no limit
run_onstring: "any", "primary" or "replica" (for replication); absent = "any"
descriptionstring; absent = none
effectslist of objects: what the definer was allowed when the job was defined, each {"action", "resource", ..} with action one of "read", "create", "update", "delete", "execute" and resource "data" (+ element, label when stated), "file" (+ path) or "definition" (+ kind as its number, name)

schedule and action are required; enabled defaults to true, effects to none. A run may do exactly the stored effects (and read). An action, a run_on value or an effect form the reader does not know is NOT damage (16 rules 1 and 9): the reader keeps the job, writes its payload back exactly as read, never runs it and lists it as not served with the reason.

A property index (kind 2, not critical) orders the elements of one element kind and label by the value of one top-level property (book page "Property Indexes"). Its name is an identifier as for a saved query. Only the declaration is stored: snapshots and the WAL hold NO index entries, a load builds them from the data, so a reader that does not know the kind loses nothing but the speed-up. Its payload keys, in this order, followed by the unknown keys:

KeyValue
elementstring: "vertex" or "edge"
labelstring: the label
keystring: the top-level property name (not a jpath)
typestring: the index type, "memory-ordered" (an ordered index in memory whose entries a load builds from the data)
transformstring, optional: the transform of the index keys, "to_lower" (the lowered text of string values, as the step to_lower() computes it; other values are not in the index); absent for an index of the values themselves

label and key are required; element defaults to "vertex", type to "memory-ordered" (a payload written before the key existed has none), transform to none. A writer of this version always writes type and writes transform only for an index with a transform. Two indexes with the same element, label, key, type and transform are invalid (a writer refuses the second); indexes of different types or transforms may cover the same key. A type, a transform or (since 0.2.1) an element the reader does not know (a newer writer's) is NOT damage and needs no new format version (16 rules 1 and 9): the reader keeps the definition, writes its payload back exactly as read (every key, in the order read), builds no entries for it and serves no query from it. A store written before this kind was decoded never holds it (kind 2 was reserved), so no format version changes.

A property index of an extended form (kind 6, property_index_ext, since 0.6.0) is a property index whose meaning a reader must know to keep it exact: today a label-less index, which orders every element of its element kind (unlabeled ones included) by the value of one top-level property, an index whose transform starts with each (one entry per element of a list value; also with a label), and a unique index (also with a label: a reader that does not know it would write past the constraint). It is ALWAYS written with the critical flag (bit 0 of the flags), so a reader that does not know kind 6 opens the store read-only (16 rule 3) instead of writing data without maintaining the index; a plain per-label index stays kind 2, not critical. The payload keys are those of kind 2; label is OPTIONAL (absent: label-less), transform is a string (one transform: to_lower, each) or an array of strings (a chain applied in order; this version serves ["each", "to_lower"], any other order or name keeps the definition, not served), unique is a boolean (absent: false; a writer writes it only when true; a non-boolean is a malformed payload; with each the definition is kept, not served), and the rest is read as for kind 2 (an unknown type, transform or element keeps the definition, not served). Index names are one namespace across kinds 2 and 6: a writer never stores the same name in both (it replaces one by the other in one commit). Two indexes of kinds 2 and 6 with the same element, label, key, type and transform are invalid (unique is not part of that identity). Like kind 2, only the declaration is stored: a reader rebuilds a unique index from the data, and data that holds a key twice keeps the definition but neither serves nor enforces it (never damage). A store written before 0.6.0 never holds kind 6 (it was unassigned), so no format version changes.

7. Segment files and chunks

segment = header (64) | chunk* | footer. A segment holds elements of one kind, in strictly increasing id order across its chunks.

7.1 Header

OffsetSizeField
08magic GRSLSEGM
84format version
121kind: 1 vertex, 2 edge
131default codec (informative)
142zero
1616graph_id
324chunk count
368footer offset
4416reserved, zero
604CRC-32C of bytes 0..60

7.2 Chunks

chunk = uncompressed length u32 | stored length u32 | codec u8 | element count u32 | chunk CRC u32 | stored bytes.

The chunk CRC covers the first 13 header bytes (both lengths, the codec, the element count) followed by the stored bytes, so a damaged length or codec is detected too. Chunks start right after the header and end exactly at the footer offset. The uncompressed payload (2.1) is the chunk payload (7.3), which its elements fill exactly. A chunk's uncompressed size is close to the store's chunk target size (default 1 MiB); the chunk is the unit of repair (13.4).

7.3 Chunk payload

payload    = string table | element*            (element count elements)
string tbl = uvar n | string*n                  labels and property keys of this chunk
vertex     = id string | uvar label count | uvar label ref * | property map
edge       = id string | label uvar (0 = none, else ref + 1) | out id string | in id string | property map

A chunk is self-contained: its own string table holds every label and property key it uses (string values stay inline), so any chunk decodes alone. References are indexes into that table; a reference outside it is invalid. A vertex's labels are a set (a repeated label is invalid); its first label is its primary label. In a property map and in object values inside a chunk, keys are table references. An edge with an empty property map and one without properties are the same (count 0).

footer = (chunk offset u64 | first id string) per chunk | CRC-32C u32 of the footer bytes before it.

The footer allows a binary search by id without reading every chunk.

7.5 Files of other segment kinds

Large data of a future feature (an index, statistics) lives in files of its own, not in the manifest (16 rule 5): a row of the segment table with another kind than 1 and 2 names such a file. Its path is a plain file name in the snapshot's own directory (4.2), its byte length and CRC-32C are those of the whole file; first id, last id and element count belong to the kind (a reader that does not know it ignores them). The file's content belongs to the kind; no chunk index row names it.

  • Kinds 3..127 are ignorable: a reader that does not know the kind checks the file's length and CRC like any segment (a mismatch is damage), copies it wherever the snapshot is copied file by file (backup, import and export of the packed form, 8) and otherwise ignores it. Such a file holds data derived from the snapshot; a writer that does not know the kind does not carry it into a new snapshot (a checkpoint, fork or repair), and a writer that knows it rebuilds it.
  • Kinds 128..255 are critical: a store whose base snapshot has such a row opens read-only for a reader that does not know the kind (16 rule 3).

Assigned kinds: 3, an embedding model's file (4.5), written only into packed snapshots (8): path is <model id>.<file name> (a plain name, at most 64 bytes), first id the model id, last id the file name, element count 0. A reader that knows the kind puts the file into models/<model id>/<file name> of the store a packed snapshot is imported into (never into the snapshot directory) and checks each model against its manifest (4.5); it treats a kind-3 row of a snapshot directory (one a reader without models imported) as a model file when it exports the snapshot again.

4, a blob (4.6), written only into packed snapshots (8), after the snapshot's own rows: path is the blob's hash as lowercase hex (64 digits for SHA-256: a plain name), first id the algorithm's name (sha256), last id empty, element count 0; the byte length and CRC-32C are the blob's, and the manifest's blob table (6.2 item 5) names it. A reader that knows the kind checks the file's SHA-256, length and CRC-32C against the table (foreign input), puts it into blobs/ of the store a packed snapshot is imported into and does not keep the row in the stored manifest; a reader without a store skips it like every ignorable file.

128, the layer file of a layer snapshot (critical). A layer is a graph stored as its changes to a frozen base graph (book page Layered Graphs); its snapshot holds only those changes and loads only over that base. Such a snapshot is an ordinary snapshot whose vertex and edge segments hold only the elements the layer added (also edges at base vertices, which name their endpoints by id like every edge, 7.3), whose manifest holds the layer's own schema, whole catalog, lineage id, position, commit time and auto-id sequences (6), and whose segment table has exactly one row of kind 128 after the edge rows: path layer.bin, first id the base's lineage id as canonical UUID text, last id <commit_seq>@<committed at> of the base (both decimal, the commit time as in 2), element count the number of entries below. The manifest's vertex, edge and property counts (6.1) are those of the layer's own elements, its memory estimate is the layer's own footprint (the base is shared, not counted). The file:

layer file = magic "GRSLLAYR" | format version u32 (5) | base graph_id (16) | base commit_seq u64
             | base committed at i64 | entry count u64 | entry*
entry      = 1 | id string                                   removed base edge
           | 2 | id string                                   removed base vertex (and its base edges)
           | 3 | id string | uvar n | label string * n | property map    base vertex image
           | 4 | id string | label opt_string | 0 | 1 property map         base edge image
           | 5 | kind u8 | name string                        removed base definition
  • The base reference (graph_id, commit_seq, committed at) is the identity of the base the layer was built over: its lineage id (5.4, 6.1) and the position and commit time of its state. It is written twice, in the file's header and in the row's ids, and both MUST agree. A reader MUST refuse to load the snapshot over a base of another identity, before it reads any segment (the row is in the manifest). The commit time tells two branches apart that reached the same commit_seq after an in-place rollback (12.5); a store id is not part of it, so a packed export of the same base state is the same base.
  • Entries name base elements by id, never by position: ids are stable across loads of the same base state, slots are not. An image is the element's whole state in the layer: the vertex's labels in order (the first is primary) and its property map; the edge's label (opt_string, none = unlabeled) and, after a marker byte, 0 for "no property map" or 1 and its property map. Property maps are those of 3 with inline keys (as in a WAL record, 9.3), values the tagged values of 3. A removed definition names a definition of the base's catalog (6.3) the layer removed (the layer's catalog starts as a copy of the base's). Other entry types are invalid in this version; the file's own format version guards them like a record type (15).
  • Entry order: removed base edges, removed base vertices, vertex images, edge images, removed definitions. Removing an element twice (an edge taken by a removed vertex) changes nothing; an image of a missing or removed base element is invalid.
  • Load order. A reader builds a fresh layer over the base, applies the schema and the catalog (6), then EVERY entry, then the layer's vertex and edge segments (an added element may reuse the id of a base element the layer removed), then rebuilds what it derives. In a stream the layer file follows the element segments (8), so a reader holds the checked segment bytes until it has read the layer file: memory in proportion to the layer's snapshot, never to the base.
  • A reader that knows the kind MUST refuse to load a layer snapshot as a whole graph and a whole-graph snapshot (no kind-128 row) into a layer. A layer writes no embedding model and carries no blob (4.5, 4.6): its catalog's model definitions are copies of the base's, whose blobs stay with the base.
  • Version. A layer snapshot's packed header (8), its manifest (both fixed-part copies, 6.1) and its layer file carry file format version 5; its vertex and edge segments keep version 4 (nothing in them differs). A reader of file format version 4 (Graphersal 0.6.x and before) therefore refuses a layer snapshot as written by a newer version (15), as a packed snapshot and as a snapshot directory of a store, and never takes the layer's own elements for a whole graph. Version 5 belongs to layer snapshots only: a packed header or manifest of version 5 without a kind-128 row, and a version 5 in any other file, is of a newer version than this specification (refused, never damage); a layer snapshot under a version word below 5 is invalid. Every other file is written in version 4.

8. The packed snapshot

A packed snapshot (.gsnap) is a whole snapshot in one stream:

packed  = magic "GRSLPACK" | format version u32 | section count u32 | section* | trailer
section = kind u8 | length u64 | bytes
trailer = CRC-32C u32 of every byte before it, from the magic on
Section kindContent
1the manifest (6)
2schema.json
3a vertex segment (7)
4an edge segment
5a named extra file: name string followed by the file's bytes; the file of a segment-table row of another kind (7.5), name = the row's path (a blob, a model file, the layer file of a layer snapshot)
0, 6..255invalid

A packed snapshot exported from a store carries the store's embedding models (4.5) unless the export leaves them out: each model file is a segment-table row of kind 3 (7.5) after the snapshot's own rows, so a named extra file (section kind 5), each model's manifest after its other files. The manifest of the packed snapshot is re-encoded with those rows (its checksums recomputed); the snapshot's own rows and chunk index are unchanged. Importing the packed snapshot into a store moves the model files into models/ and writes the snapshot's manifest without their rows.

The sections appear in this order: the manifest, schema.json, the vertex segments, the edge segments, the named extra files, each in the manifest's table order; the section count is 2 + the manifest's segment count, and each section's length MUST equal what the manifest records for it (for kind 5: the length of name as a string plus the row's byte length; the file's bytes MUST match the row's length and CRC). A new file type therefore needs no new section kind. The manifest and schema.json sections are at most 256 MiB each. The sections are byte-identical to the files of a store's snapshot directory, so a store imports and exports packed snapshots by copying, and a directory snapshot can be read as the packed stream it is equivalent to. A reader of a non-seekable stream checks each section's CRC as it streams and the trailer at the end; nothing follows the trailer.

Writing without seeking (informative). The manifest precedes the segments, every section starts with its length, and a segment file starts with its chunk count and footer offset (7.1), so a writer must know every segment's length, CRC and chunk index before it writes the first segment byte. A writer that neither seeks nor holds the encoded snapshot can plan first: encode every chunk once and keep only its size, CRC and first and last id; write the header, the manifest and schema.json; then encode each chunk again from the same elements and write it. Chunks are self-contained (7.3), so with a deterministic compressor the second encoding yields the planned bytes; the reference writer checks every chunk's CRC against its plan and fails on a difference (the graph must not change in between). A segment's CRC covers its header, which is known only after the chunks; it is the CRC-32C combination of the header's CRC and the CRC of the rest. A store writes a snapshot directory the same way, each segment file as soon as its plan is complete and the manifest last, holding one chunk at a time.

9. The write-ahead log

The WAL is a sequence of segment files. Over a plain stream (a journal outside a store) the same bytes are one segment that is never rotated.

9.1 Segment header

OffsetSizeField
08magic GRSLWALS
84format version
1216graph_id of the lineage that writes the segment
288first commit_seq the segment may contain
368created at (time)
4416reserved, zero
604CRC-32C of bytes 0..60

In a store the file name is the first commit_seq as 20 decimal digits; a header whose first commit_seq differs from its file name is damage (9.8).

9.2 Record frame

A record is a 25-byte frame followed by its payload:

OffsetSizeField
04sync marker 0x47525357 (bytes 57 53 52 47)
44payload length
88commit_seq: a Commit's own number; for a Mark or Checkpoint, the commit it refers to
161record type
174header CRC-32C of bytes 0..17
214body CRC-32C of the payload
25lengthpayload
TypeRecord
1Commit (9.3)
2Mark (9.4)
3Checkpoint (9.5)
4Commit part (9.3.1; file format version 4 and later)
0, 5..255reserved: an unknown type is invalid, never skipped

Type 4 is valid only in a WAL segment whose header (9.1) states file format version 4 or later; in an older segment it is an unknown type.

The sync marker and commit_seq lie outside the possibly compressed payload, so a reader can resynchronise after a damaged record by searching for the next position that holds the sync marker, a valid header CRC and a valid body CRC. The separate header CRC makes a damaged length detectable, so it is never taken for an interrupted write (9.6). A record is never split between segments, and neither is a commit: the parts of a commit in parts (9.3.1) are consecutive records of one segment.

9.3 Commit payload

commit   = commit_seq u64 | time i64 | node_sequence u64 | edge_sequence u64 | codec u8 | body'
body'    = body                                  when codec = 0
         | uncompressed length u32 | stored body  when codec = 1 or 2
body     = principal opt_string | attributes property map | uvar mutation count | mutation*

commit_seq MUST equal the frame's. The auto-id sequences are written with every commit so that an id handed out before a crash, a drop or a rollback is never handed out again after a recovery. A writer writes a commit whose body is at most the part size (64 MiB) as this one record, and a larger one in parts (9.3.1); a reader accepts a single-record body up to 1 GiB (the bound of section 2). A commit with a mutation count of 0 is valid: a sequence-only commit, a unit that changed nothing but raised an auto-id sequence (applying a change set whose mutations were all compacted away); replaying it only raises the sequences (and advances the commit position). The attributes are free metadata of the commit (keys inline). Every string is inline.

OpMutationFields
1AddVertexid string | uvar label count | label string* | property map
2DropVertexid | before: labels (as in AddVertex) | property map
3AddEdgeid | label opt_string | out id | in id | property map
4DropEdgeid | before: label opt_string | out id | in id | property map
5SetPropertyelement kind u8 (1 vertex, 2 edge) | id | key string | before value (tag 255 = absent) | after value
6RemovePropertyelement kind | id | key | before value
7AddLabelvertex id | label
8RemoveLabelvertex id | label
9SetSchemabefore schema string | after schema string (canonical JSON)
10SetDefinitionkind u8 | name string | before opt(definition) | after opt(definition)
11SetEdgeLabeledge id | before label opt_string | after label string

opt(definition) is u8 0 for none, or u8 1 followed by a definition encoded as in the definitions table (6.3); other presence bytes are invalid. Op 10 serves every definition kind, so a new kind needs no new op: a define has no before, a removal no after, a change (replace, move, describe) both; at least one is present, and each present image MUST carry the op's kind and name. A definition the reader cannot decode follows 6.3: an unknown kind is kept opaque (and replayed as such), a payload of a known kind that is not a valid property map is damage, and a valid map is never damage (kept, not served, or kept opaque; 16 rule 9). A writer MUST NOT write an after image that is a critical definition of a kind it does not know (16 rule 3).

Mutations are in execution order. Before images are always present: a reader can reconstruct the state before each commit, and CDC consumers get before and after values. The edges a vertex drop removes appear as DropEdge mutations before the DropVertex. A write to a nested path inside a property is a SetProperty of the top-level key.

A schema (op 9) may declare vector rules: a vector property with an embedder and a from property (book page "Vector Rules"). The vectors a rule computes are ordinary SetProperty and RemoveProperty mutations of the commit that changed their source (or of the commit that added the rule, which fills every element of the label), written as they were computed. A replay, a recovery, a merge checkpoint and every other reader apply them as recorded and MUST NOT embed: replaying a commit never needs the model.

9.3.1 Commit in parts

A commit whose uncompressed body (9.3) is larger than the writer's part size (64 MiB) is written as parts >= 2 consecutive records of type 4 (file format version 4); a commit up to the part size stays one Commit record (type 1), unchanged.

frame        = 9.2 frame, type 4, commit_seq = the commit's (equal in every part)
part payload = part u32 | parts u32 | part_body
part_body    = (part = 0) commit_seq u64 | time i64 | node_sequence u64 | edge_sequence u64
                          | body_length u64 | slice
             | (part > 0) slice
slice        = codec u8 | data                         codec 0: data = the raw bytes
             | codec u8 | uncompressed u32 | stored    codec 1, 2 (as in 9.3)
  • The uncompressed slices of parts 0..parts concatenated are body of 9.3 (principal | attributes | uvar mutation count | mutation*); a mutation may span a part boundary. Each slice is compressed on its own (section 2.1).
  • A writer writes slices of 1..=part size uncompressed bytes (all but the last exactly the part size). A reader accepts any slice of 1 byte to 1 GiB (the bound of section 2) and requires their sum to equal body_length. It never allocates from body_length up front: the body grows per part, checked against what it may use.
  • parts is 2..=1048576 (2^20, 64 TiB at 64 MiB per part) and equal in every part; part runs 0..parts without gaps; commit_seq of part 0 MUST equal the frame's. A commit needing more parts is refused by the writer (PersistError::CommitTooLarge, the unit rolls back).
  • The parts of one commit are consecutive records of ONE segment: no other record lies between them (rotation, 9.7, happens only before part 0).
  • A commit in parts is ONE commit for every reader: its position (where a recovery cuts a torn tail, a rollback splits a segment, a backup compares records) is the start of part 0.

9.4 Mark payload

mark = commit_seq u64 | time i64 | name string.

A mark names the position right after commit commit_seq (recovering to it replays up to and including that commit). Its time comes from the instance clock (section 2, "Time"): never earlier than the last commit, nor than any other time the instance wrote. Mark names are unique along a store's whole history (across lineages); a duplicate MUST be refused when it is set.

9.5 Checkpoint payload

checkpoint = commit_seq u64 | time i64: informational, "a snapshot at commit_seq exists". Readers accept and skip it. Commits newer than commit_seq MAY precede it.

9.6 Torn tail and damage

At the end of the last segment (of a recovery's last journal), the following are a torn tail, the remains of an interrupted write:

  1. fewer than 25 bytes that are a prefix of the sync marker (the first up to four bytes match) or all zero;
  2. a frame with a valid header CRC whose payload runs past the end of the file;
  3. zero bytes only, from a record boundary to the end (space the file system allocated that the interrupted write never filled).

A full frame header with a bad header CRC, a full record with a bad body CRC, and any other bytes at the end are damage, wherever they are, also in the last record. Anything that is not a valid record before the end of a segment that is not the last one is damage. A torn tail is cut off by the next read-write open (12.2), never by a reader; damage is never cut (13).

A commit in parts (9.3.1) at the end of the last segment with fewer than parts complete parts (the last present one possibly torn by the rules above) is a torn tail too; it starts at part 0, where it is cut. Damage, wherever it is: a part other than 0 not preceded by its predecessor, a record of another type or commit_seq between parts, part or parts inconsistent, slices whose sum differs from body_length, and an incomplete commit in parts before the end of a segment that is not the last one. A resynchronisation (salvage, 13) that lands on a part other than 0 skips to the next record that is a part 0 or of type 1, 2 or 3; a commit with a damaged part is one damaged region covering all its parts.

9.7 WAL segments in a store

  • Segments are named by the first commit_seq they may contain. Rotation is lazy: before a record (before part 0 of a commit in parts, never between its parts) is written, if the current segment exceeds the segment size (default 16 MiB) or a checkpoint asked for a new segment, the current file is synced, and a new segment named by the next commit sequence number is created with its header, synced, and its directory synced. A Mark or Checkpoint record may therefore be the first record of a segment named commit_seq + 1 of the commit it refers to. Only the last segment can end in a torn record.
  • The replay set of a snapshot at position S is the last segment whose name is <= S + 1 and every later one. Commit records <= S are skipped; every later commit record MUST be exactly the previous + 1 (else the history has a gap: damage).
  • After an in-place rollback or a fork, the new lineage writes a new segment (its header carries the new graph_id).
  • A record whose write or sync failed is cut off again (the file truncated to the record's start, for a commit in parts to the start of part 0, whatever part failed, and synced) before the writer refuses further commits. When that cut fails, the valid end is recorded in GRAPH (flag bit 1); readers MUST read only up to it, and the next read-write open truncates the segment there and removes later segments.

9.8 The newest segment and a clean close

A cut of the last WAL record is indistinguishable from an interrupted write and is treated as a torn tail. A segment that is missing, emptied or replaced by another segment's bytes must never be: it would silently open the store at an earlier commit. Without a metadata write per commit, GRAPH therefore records:

  • wal_head (flag bit 3, offset 84): the name of the newest WAL segment, written whenever a segment is started, after the segment's header was written and synced and its directory synced (rotation, the first segment of an open, the segment target + 1 of a rollback together with its lineage entry), and after an attic restore (the newest restored segment); a recorded WAL cut lowers it to the cut segment. A failed write leaves the older value.
  • closed_at (flag bit 4, offset 92): the last commit at a clean close (state 0). A catalog commit on a closed store (12.12) moves it forward to that commit; it never lowers it.

At every read-write open (before the torn-tail rules), in the damage scan and in verification it is damage when: a segment's header names another first commit than its file name; the segment wal_head is missing, or it or an older segment is shorter than its 64-byte header; or the store was closed cleanly at closed_at and the snapshot plus the WAL end at an earlier commit. A last segment newer than wal_head and shorter than its header is a crash while it was being started: it is removed as a torn tail.

9.9 Write ordering and durability

The writer of a journal MUST:

  1. assign the commit's sequence number (checked against overflow) before writing its record;
  2. run every other commit check (hooks that may veto) before writing, so that nothing fallible follows a written record and the WAL never holds a commit that did not happen;
  3. write the record (every part of a commit in parts, 9.3.1), then make it durable according to the configured durability: a sync after every commit (the default), at most once per interval, or left to the operating system; a commit in parts gets one sync, after its last part;
  4. treat a failed write or sync as a vetoed commit (the unit rolls back) and refuse every later commit and mark until the WAL is reopened, because the state of the file is unknown.

The durable end is the offset after the last record whose sync completed; it moves only after the last part of a commit in parts, so it never lies inside one. Records after it may still be vetoed and MUST NOT be copied by a backup (12.6).

10. The marks file

A derived list of the store's marks: append-only frames length u32 | CRC-32C u32 of the payload | Mark payload (9.4), appended and synced after the Mark record is durable in the WAL. The WAL is the source of truth: a missing or damaged marks file is rebuilt from all WAL segments on open, and marks in the replayed WAL that the file lacks are appended. Listing marks reads only this file and lists only the marks a target can reach: those at or after the oldest snapshot of the store (or backup) listed. The file is not rewritten by a prune (12.4): a backup copies it and may still reach older marks with older snapshots of its own. A mark that is not listed keeps its name taken; resolving it as a target fails.

10.1 The ledger file

A derived list of blob reference changes (4.6): append-only frames length u32 | CRC-32C u32 of the payload | payload, payload = commit_seq u64 | graph_id 16 bytes (big-endian) | blobref (3, tag 21, without the tag) | delta svar: one frame per (commit, blob) whose net delta is not 0, the delta counting every blobref in the commit's after images (+1) and before images (-1). Frames are appended and synced after the commit is durable in the WAL. The WAL is the source of truth:

  • A frame counts for a position when its graph_id and commit_seq lie on that position's lineage chain (5.4): its lineage is on the chain and its commit at or before that lineage's branch point. A rollback does not rewrite the file: frames of an abandoned lineage are ignored by this rule.
  • A damaged file, and a missing one in a store that holds blobs, is rebuilt from all WAL segments on open (a warning and a journal record ledger.rebuilt, never damage). After a crash the frames of the replayed commits the file lacks are appended and frames of the current lineage after the recovered end are dropped. A store that never referenced a blob needs no ledger.
  • A prune rewrites it (atomically) without the frames at or before the oldest kept snapshot and without the frames off the current chain (their history lives on in attic entries, whose WAL is read for them); no INTENT is needed (the file is derived).

11. The INTENT and ATTIC files

11.1 INTENT

A multi-file operation writes INTENT (compact JSON, replaced atomically and synced) before its first file change and removes it after its last one. Every step is idempotent; a read-write open that finds INTENT completes (or, for a backup increment, rolls back) the operation before anything else. An unknown op MUST fail the open, as unsupported content of a newer writer (16 rule 9), never as damage. Every path in it follows 4.2.

{"op": "<operation>", "files": ["<store-relative names>"], "started_at": <micros>, ...}

Further parameters are string values. Operations of store format version 4 (versions 2 and 3 have all but upgrade_models):

opParameters and steps
prunefiles: the snapshot directories and WAL segments to remove. On open: each listed name is removed (missing is fine), the directories synced, INTENT removed
rollbackfiles: snapshot directories and WAL segments to move (or delete); target, last_commit, base_snapshot (newest snapshot at or before the target), mode (move | delete), old_graph_id, new_graph_id (32 hex digits), time, attic (attic/<YYYYMMDDTHHMMSSZ>-<target+1, 20 digits>), reason; and either split + split_offset (the segment holding the first commit after the target is cut there; its tail becomes <attic>/wal/<target+1>.wal with the old lineage's header) or kept (hex; when that segment is itself named target+1, it moves whole, and the records before the cut, marks pointing at the target, open the new lineage's segment). The tail of a split segment keeps the header lineage of the segment it is cut from (an ANCESTOR's when the target lies before the current lineage's branch point), not necessarily old_graph_id. files names every directory under snapshots/ after the target, holders (4.1) included. For the existing attic entries (11.2) whose history before their own WAL reaches past the target, three more parameters, each a list of lines separated by \n: copies (<source> <destination>: the store's WAL segments, or the split segment meaning its tail as the attic gets it, that hold the commits from target + 1 up to such an entry's prefix end, copied into <entry>/wal/ under their names), rebase (the ids of those entries) and drop (the snapshot directories of entries one of whose snapshots references a file of a directory this rollback moves). Steps: attic directories; the copies (each written whole under its final name, skipped when present; all of them exist before any source changes); the drop directories removed; each rebase entry's ATTIC rewritten with base_snapshot = this rollback's base_snapshot; tail and cut; move or delete files; ATTIC; marks filtered to <= target; GRAPH with the new lineage entry [new id, branched at target, time]; the new lineage's segment <target+1>.wal (written whole, its header created at time, then the kept records; one found shorter is written again); holders no snapshot of the store or of an attic entry references any more are removed (12.4); INTENT removed
attic_restoreAllowed only while the store is at the entry's target on the rollback's lineage and its new segment holds nothing beyond the kept records. files: the entry's directories under snapshots/ (holders too) and its WAL segments named after its target (its prefix copies, 11.2, stay behind: the store holds that history again); refused when one of them exists in the store. Steps: remove the new lineage's segment and a snapshot of the new lineage at the target (a checkpoint of the closed store after the rollback writes one without a WAL record), move the entry's files back, drop the lineage entry from GRAPH, rebuild marks from the WAL, remove the entry
upgrade_modelsthe migration of a store format version 3 store's models/ (15.1): files the model directories models/<id> checked before it was written, from the old store format version. Written before GRAPH gets the new version (a reader of version 3 then refuses the store as newer; one that reads GRAPH as 3 but finds this op refuses it as unknown). Steps, each idempotent: every model of models/ becomes a blob (a blob of the same content stays); ONE catalog commit (12.12) defines every model whose identity's 12 hex digits no model definition has yet (principal upgrade, attribute upgrade = "<from>-><to>"; a renamed model's embedder in the schema renamed in the same commit), none when all are defined; each model directory renamed to models/tmp-<32 hex> and removed, then models/; INTENT removed
backup_incrementwritten in the backup's root (12.7): files (new snapshot directories and WAL segments), graph_before (hex of the backup's GRAPH), taken_at, optionally tail + tail_len (the segment appended to and its length before) and replaced

Stray *.tmp files in the store root and snapshots/tmp-* directories are removed on open.

11.2 ATTIC and attic entries

An attic entry is a directory attic/<YYYYMMDDTHHMMSSZ>-<first moved commit, 20 digits>/ with the moved snapshots/ and wal/ and an ATTIC file (the name is unique: when it is taken, by an entry or an entry being removed, the time part is advanced by one second until it is free; the ATTIC file records the exact time): compact JSON with the string values graph_id (the old lineage), new_graph_id, target, last_commit, time, reason, base_snapshot and kept_bytes. An entry being removed is first renamed attic/removing-<id> (removed at the next open).

An entry is self-sufficient given the store (it never needs another entry). Its history is its base snapshot (base_snapshot, a snapshot of the store's own snapshots/), then the store's WAL from it up to the prefix end, then the entry's own WAL; or, when the entry holds snapshots, its newest one and its own WAL after it. The prefix end is the commit before the entry's first WAL segment, at most its target. Segments of the entry named at or before its target are its prefix: copies of the store's history that a later rollback to an earlier commit (rebase, 11.1) gave it before moving that history into its own entry; the same rollback points base_snapshot at its own base and drops the entry's snapshots when they reference files it moves (they are derived: the entry's WAL rebuilds every state they held). The store's history up to an entry's prefix end therefore stays in the store: rollbacks keep everything at or before their target, restores add only history after theirs, and prune keeps every entry's base and the WAL after it (12.4). The entry's segment and snapshot listings treat a missing snapshots/ or wal/ as empty.

12. Operations

12.1 Load and recovery

A target is Latest, a commit_seq, a time (the last commit whose time is at or before it), or a mark name. Loading a target: take the newest snapshot at or before the target (for Latest, the newest), then replay its replay set (9.7) along the lineage chain (5.4) up to the target.

  • A load checks GRAPH and the lineage, may check the manifest's estimated in-memory bytes against a budget, loads the vertex segments, then the edge segments (an edge's endpoints are resolved by id), rebuilds every index and statistic, and restores the graph_id, the position, the last commit time and the auto-id sequences.
  • A snapshot load does not validate the data against the stored schema: the data was valid when it was committed, and integrity comes from the checksums. It restores the catalog of definitions from the manifest (6.3).
  • A layer snapshot (7.5, kind 128) loads only into a fresh layer over the base it names, in the order of 7.5: schema, catalog, the layer file's entries, then the layer's own segments.
  • WAL replay applies mutations without running commit hooks or schema validation; op 10 stores or removes a definition.
  • A read-write open whose loaded state holds a critical definition of a kind the reader does not know, or whose base snapshot has a file of a critical segment kind it does not know (7.5), opens the store read-only (16 rule 3): every commit, mark, checkpoint, prune, rollback and compaction is refused, and nothing is written after the load (no torn-tail cut, no marks rebuild, no change of GRAPH). The steps of 12.2 before the load (completing an INTENT, removing leftovers, applying a recorded WAL cut) MAY have run; they do not change the graph. Reading, verification, export, fork and backups work; a fork or backup keeps the definition and is read-only for that reader too.
  • A read-write open whose snapshot schema.json or a schema image of op 9 the reader cannot parse (a newer writer's keyword or mode; its checksum is valid) loads the data WITHOUT the schema and opens the store read-only in the same way (16 rule 9). As the loaded state lacks the schema, every store operation that would write a state derived from the files (a checkpoint, a fork, a repair) is refused as unsupported; a file-level backup and the export of a stored snapshot copy the bytes as they are. A snapshot written from the loaded graph in memory (g.export_snapshot) has no schema.
  • Recovery to a target before the end yields a read-only past state. A writable state from it is either a fork (a new store, 12.5) or an in-place rollback.
  • Without a snapshot (a journal over a stream), the first journal MUST start at commit 1.

12.2 Open and close

A read-write open: take the writer lock (12.10); complete an INTENT; remove leftovers (snapshots/tmp-*, *.tmp); apply a recorded WAL cut; run the checks of 9.8; load (12.1, mode Latest); cut a torn tail of the last segment; rebuild marks if needed; set GRAPH state 1. A clean close: sync, then write GRAPH with state 0 and closed_at. A store whose state is 1 at open was not closed cleanly; that is not damage (the WAL replay recovers it).

12.3 Checkpoints

A checkpoint writes a snapshot of the current state: encoded consistently at one position (the reference implementation streams it chunk by chunk, see 8, or merges it, below), into snapshots/tmp-<32 hex>/, every file synced, the directory synced, verified (manifest CRCs, schema.json, every segment's length and CRC, every chunk CRC and the chunk index), renamed to its 20-digit name, snapshots/ synced; then a Checkpoint record is appended and a new WAL segment is requested. The manifest carries the whole catalog of definitions, every definition of an unknown kind byte for byte as read (6.3). Only renamed snapshots exist for listing, loading and retention. A checkpoint at a position that already has a snapshot returns that snapshot. The chunk target size is the store's (GRAPH offset 44) for its whole life.

Merge checkpoint. A writer MAY build the new snapshot from the newest snapshot (the base) and the WAL after it instead of from a loaded graph (the reference implementation does, without the graph's lock, unless the WAL after the base exceeds a configured bound). Such a writer:

  • reads the WAL only up to its durable end (9.9), from the base's replay set (9.7) along the lineage chain (5.4), with every header and body CRC, commit continuity and every lineage rule of a load; the new snapshot's position is the last commit read and its graph_id the lineage the replay ends in (an empty segment of a new lineage counts);
  • applies the commits as a load replays them (12.1) to the base's state of every element they name, and MUST check every mutation's before image against that state: a mismatch (the WAL does not continue the base) is damage;
  • reads every base chunk it uses with its CRC and chunk index row, every base segment it rewrites in full (header, chunks, footer, file CRC), and verifies the new snapshot, referenced files included, before the rename;
  • carries the schema, the catalog (unknown non-critical definitions byte for byte), the auto-id sequences, the position and the last commit time exactly as a load followed by a checkpoint would; drops files of an ignorable unknown segment kind (7.5); refuses a base or a state with something critical it does not know (16 rule 3);
  • rewrites every segment that holds an element a commit names (an element whose id falls between two segments' ranges goes to the later one, beyond the last range to the last one); the rewritten elements are in strictly increasing id order across the new segments;
  • keeps every other segment of the base byte for byte under the donor rule: the new snapshot uses no file the base uses, so the base stays an independent copy of every id range, the donor of 13.4. Such a segment is referenced (6.2) when the snapshot before the base (the newest snapshot older than the base, of the same lineage) has a twin: a row with the same kind, first and last id, element count, byte length and file CRC, the same chunk index rows, naming another file than the base's (after resolving both, 6.2); the reference names that file. Otherwise the segment's bytes are copied into a new file of the new snapshot (read with the file CRC checked). So an unchanged range alternates between two files from checkpoint to checkpoint, and only the first checkpoint after the range was rewritten copies it. A writer that encodes a loaded graph (8) writes only new files and meets the rule too;
  • on damage, writes nothing visible: the temporary directory is removed, no file of the store changes.

A closed store MAY be checkpointed the same way by a process that takes the writer lock (12.10), completes an INTENT and removes leftovers (12.2); it ignores a torn tail of the last segment, honours a recorded WAL cut, applies the checks of 9.8, and appends no Checkpoint record.

12.4 Prune and retention

prune(up_to) keeps every snapshot from min(newest snapshot <= up_to, second-newest snapshot) on, plus the base snapshot of every attic entry; it verifies each kept snapshot first, then removes the older snapshots and the WAL segments before the replay set of the oldest kept one, under an INTENT (prune). The last two verified snapshots and the WAL between them always stay (the donors of 13.4). Nothing is ever removed implicitly. Prune is refused while the pin is held shared (12.10). Marks before the oldest kept snapshot become unreachable (10); a prune reports them, from the marks file only.

Files that a kept snapshot or a snapshot of an attic entry references (6.2) stay: of a removed snapshot directory that holds one, only the other files are removed, the manifest first (the directory is a holder from then on, 4.1); a holder older than the oldest kept snapshot that no such snapshot uses any more is removed whole. The INTENT's files then name single files of such a directory. Under the donor rule (12.3) the last two snapshots share no file, so each is the other's donor. A rollback that deleted the history using a holder's files, and the removal of an attic entry whose snapshots used them, remove the files no snapshot of the store or of an attic entry references any more (and the holder when it is left empty); a file nobody references is never referenced again (a checkpoint references only files of a listed snapshot), so this needs no INTENT.

Blobs (4.6). The referenced set R of a store is the union of the blob tables (6.2 item 5) of every snapshot of the store and of its attic entries, the blobs of the ledger frames (10.1) on the current chain, the blobs every attic entry's own WAL references, and the blobs a running writer holds (written, its commit not yet durable). After its own removals a prune rewrites the ledger (10.1) and removes every blob file not in R (the orphans of interrupted writes too); an attic removal and a rollback delete do the same. A removal is idempotent and needs no INTENT (a blob not in R is never referenced again). When the referenced set cannot be read nothing is removed.

12.5 Fork, in-place rollback, attic

  • Fork: load the target (12.1) and write it as a new store: one snapshot (with the catalog, 6.3), a new graph_id, the manifest's parent fields set, the chain [new id, branched at target, time] + the source's chain. Marks are not copied.
  • In-place rollback (move or delete), under INTENT rollback (11.1): everything after the target (later snapshots, the WAL after it; the segment holding the target is split) moves into an attic entry or is deleted; the store continues as a new lineage in the same root.
  • Attic restore (11.1) undoes a rollback while nothing was committed or marked since; an attic fork writes the entry's history as a new store. Prune never removes an attic entry's base snapshot except together with the entry.
  • Every attic entry stays whole after any sequence of rollbacks, restores, removals and prunes (11.2): a rollback to a commit before an older entry's history copies what that entry needs into it first (11.1 copies, rebase, drop). Entries never depend on each other: removing, restoring or forking one never breaks another. Restore order (normative): an entry MAY be restored only while GRAPH's current graph_id equals the entry's new_graph_id (the lineage its rollback started) and nothing was committed or marked since; after several rollbacks the entries therefore restore newest first, each restore bringing back the lineage the next older one needs. A writer MUST refuse an out-of-order restore without changing any file, and SHOULD name the newer entry to restore first. Any entry MAY be forked at any time.
  • A rollback or restore that fails once its INTENT is written leaves the files ahead of the graph in memory: the writer refuses every further change and its close writes no GRAPH; the next open completes the operation.

12.6 Backups

A backup is a file-level copy that takes no graph lock: snapshots are immutable once renamed and the WAL is append-only. A full backup copies GRAPH (rewritten: state 0, no WAL cut, the backup marker, wal_head and closed_at of the backup's own files) to GRAPH and GRAPH.copy; the marks file as read before the copy ends were fixed (every mark in it is in the copied WAL); the latest snapshot (verified before and after the copy) with the files it references (6.2, copied under their names, in holders when their snapshot is not copied) and its replay set, the segment of the durable end cut at the durable end, later segments left out. A copy by another process, which has no durable end, copies the last segment up to its last complete record (a torn tail, 9.6, is left out; damage before it stops the backup), never past a recorded WAL cut. LOCK, BACKUP and the attic are not copied. During the copy the source's BACKUP pin is held shared.

Blobs (4.6). A full backup copies the blobs its copied history references: the blob table of the copied snapshot (6.2 item 5) and the blobs the commits of the copied WAL reference, each checked by length and CRC-32C in the source and again in the copy (streamed). A blob missing or damaged in the source is not carried (a warning; the backup's catalog still references it): blob damage is never damage of the store. The ledger (10.1) is not copied: it is derived, and a backup's history is read from its WAL.

Verification. A backup (full, increment, ZIP) reads every checksum of what it copies in the SOURCE before it writes anything, and again in the COPY after writing it:

  • in the source: both GRAPH copies (one unusable copy is a warning, both are damage; the backup writes two fresh ones); the marks file (derived, 10: damage is a warning and the backup's is rebuilt from the WAL it copies); every snapshot it copies with everything 12.3 verifies (manifest CRCs, schema.json, every segment and chunk, the chunk index, referenced files) and both copies of the manifest's fixed part (one damaged copy is a warning: the backup gets the file with the intact copy in both places, byte for byte what the writer wrote); every WAL record of every segment it copies, header and body CRC, each segment's header against its name (9.8) and the lineage chain, the segment set of 9.8, and commit continuity (every commit the previous + 1; the first commit after the snapshot, or after the backup's position, its successor);
  • in the copy: GRAPH, GRAPH.copy and marks byte for byte as written, every snapshot as 12.3 verifies it (both fixed copies strictly), every WAL segment read again with the same end and the same commits as the source's; a ZIP archive is read back entry by entry (12.8).

Damage in the source stops the backup before anything is written; damage of the copy removes a new backup and rolls an increment back (for an increment, the backup's old GRAPH is written first, so the rollback never takes a final GRAPH that did not read back for a completed one). When the copy does not read back, the source's checks run again: a source that fails them now is the source's damage. The report lists each problem with its file, offset and reason, as verification does (12.9), and names the side; the remedy for damage in the source is a repair of the SOURCE (13.4, never of the backup), or, while the source is open in a process whose graph is intact, a backup from memory (12.11).

Marker. Flag bit 2 marks a backup; offset 68 holds the last commit it holds and offset 76 when it (its last increment) was taken. graph_id, store_id and the lineage chain are the source's. A marked store never opens read-write; read-only loads, verification, listing, export, fork, prune of the backup and backups of it work. Restoring a backup in place takes the writer lock, rolls back an interrupted increment, clears bit 2 and the marker fields and writes GRAPH clean: the root is then the live store with the same graph_id and store_id.

12.7 Incremental backups

A backup into a root that holds a marked backup is an increment; into an empty or missing root, a full backup; anything else is refused (a store that is not a backup is never written to).

  • Relation. The backup's chain MUST equal the tail of the source's chain that starts at the entry with the backup's graph_id. With that entry at position k > 0, the backup may hold commits only up to the smallest branched at of the entries 0..k-1 (a rollback of a later lineage to before its own start branches from an ancestor at an earlier commit); a backup holding more (the source was rolled back behind the backup's position) is refused; a full backup into a new directory follows the new history, and the old backup stays as the archive of the abandoned one. Unrelated stores are refused.
  • Identity. The backup's store_id (5.5) MUST equal the source's. A fork, repair or conversion of the backed-up store shares its lineage chain up to the copy but is a different store: its increment is refused, and a full backup into a new directory is needed.
  • Position. The backup's position is the larger of its newest snapshot and the last commit of its WAL; its last segment L MUST end with a complete record.
  • WAL. If the source has a segment named L with an equal 64-byte header: the source's copy end MUST be at least L's length, and the 25-byte frame of L's last record MUST equal the source's bytes at that offset (prefix check); the bytes from L's length to the copy end are appended. Equal name, different header: allowed only when L holds no commit record and the source branched from the backup's lineage (a rollback to exactly the backup's position); the source's segment then replaces L. The source has no segment L (pruned): its next segment MUST be named at most position + 1, else the gap is refused and a full backup is needed. Every source segment named after L, up to the durable end, is copied whole.
  • Snapshots. Every source snapshot newer than the backup's newest is copied, verified before and after. A referenced file (6.2) the backup lacks (its snapshot was written and pruned since the last increment) is copied from the source, under its name, before the snapshots that use it, and listed in the INTENT's files; one the source lacks too is refused.
  • Steps, with the backup's writer lock held and the source's pin shared: complete or roll back an earlier interrupted increment; write INTENT backup_increment; when the lineage changed, write GRAPH with the source's chain and the OLD marker; copy each snapshot through snapshots/tmp-<hex>/ (synced, verified, renamed); append the tail and sync, re-reading every record of the segment; copy a replacing segment and each new segment through <name>.wal.tmp (synced, re-read, renamed; a replaced L is first renamed <name>.wal.replaced); check that the copied commits continue the backup's WAL without gap or overlap; write marks; write GRAPH with the source's identity, clean, no WAL cut, the new marker; remove the .replaced file; remove INTENT. The backup is a valid store after every step.
  • Interrupted increment (found at the next backup, restore or prune of the backup): when the marker's time equals the intent's taken_at, the increment is complete (remove .replaced and INTENT); otherwise it is rolled back: the listed files and every snapshots/tmp-* and wal/*.tmp removed, a .replaced segment renamed back, the tail cut to tail_len, GRAPH rewritten from graph_before, marks rebuilt from the WAL, INTENT removed.
  • Nothing pins the source's WAL for a backup: a prune of the source can make the next increment impossible (a full backup is then needed).
  • Blobs (4.6): after the increment, every blob the backup's history references that it lacks is copied from the source (checked by length and CRC-32C on both sides); nothing is removed (a prune of the backup, 12.4, collects).

12.8 ZIP backups

A full backup MAY be written as one ZIP archive: stored entries (method 0), UTF-8 names (the store's names, 4.2), DOS time 1980-01-01 00:00, the CRC-32 (IEEE, as ZIP requires) in the local header, zip64 extended fields always (sizes in the local header, sizes and offset in the central header), then the zip64 end record, its locator and the end record. The archive's GRAPH carries the backup marker; unpacking it is the explicit restore and clears the marker. A reader MUST accept only the store's names and MUST refuse compressed, encrypted or streamed (data descriptor) entries. A well-formed name outside the layout it knows (plain segments, at most four) is a newer writer's file: the restore is refused as unsupported, never as damage (16 rule 9); any other name is damage. The reference writer reads the archive back after writing it (12.6): every entry's CRC-32 and every checksum of the store files in it, which arrive in an order a one-pass reader can check (GRAPH, GRAPH.copy, marks, then each snapshot's manifest before its other files, then the WAL segments, then the blobs, blobs/<2 hex>/<hash> (4.6: each read back with its length, CRC-32C and SHA-256), then the segments of the system journal, journal/<20 digits>.jnl, 4.7: checked frame by frame, a problem is a warning). Unpacking an archive checks every blob as foreign input: the SHA-256 of its content against its name, its length and CRC-32C against every reference its history holds; a mismatch refuses the restore as damage of the archive. A writer MAY leave the models and blobs out of an archive meant to be shared (the reference implementation's BlobCopy::Exclude): its catalog still references them, so the receiver has them missing.

12.9 Verification (scrub)

Verification reads every checksum: both GRAPH copies, every manifest (both fixed copies), every schema.json, every segment and chunk (and the chunk index), every WAL record; it checks id order and non-overlapping ranges, WAL continuity (commit_seq + 1 per Commit, no gaps) along the lineage chain, the checks of 9.8, every attic entry (its history is rebuilt as 11.2 describes, and each of its snapshots verified), and the marks file. A holder (4.1) with files that no snapshot of the store or of an attic entry references is a problem (a lost manifest, or files a prune left). A segment file the newest snapshot shares with the previous one (a break of the donor rule, 12.3) is a warning, not damage: the range has no independent donor; the next checkpoint finds no twin for it and copies it. It is meant to be run regularly: it finds damage while donors still exist. Verification also checks every embedding model (4.5): its manifest, the set of files, every file's size and SHA-256; a model of a newer manifest format is a note. It reads every segment of the system journal (4.7): a damaged record or segment is a note, never a problem. It reads every blob of the referenced set (12.4) whole: SHA-256, CRC-32C and length; a missing or damaged blob, and an entry under blobs/ that is not a blob's name or tmp-*, is a problem with its path under blobs/ (never damage of the store, 13); a blob file outside the referenced set is a note (an orphan the next prune removes); a blob of an unknown algorithm is checked by length and CRC-32C only, with a note that its hash was not checked.

12.10 Locks and pins

  • Writer lock: at most one writer per store. On a directory it is an exclusive operating system advisory lock (flock / LockFileEx) on LOCK, held while the store is open read-write; in a container file it is the lock on the file itself (14.5). Read-only loads, verification, listing, export, fork and out-of-process backups take none.
  • Backup pin: a backup holds the BACKUP lock shared while it copies, and so do a verification, a fork and a packed export of a writable open store while they read (the forms on a closed directory, fork_dir and export_packed_dir, take no lock); each waits while the lock is held exclusively, and takes it before it reads the durable end of the WAL. A prune, a rollback, and an attic restore or removal take it exclusively and without blocking, and are refused while it is held shared.

12.11 Backups from memory

A writer that holds a store open and has found damage in its files (13.3) MAY write a backup of its graph in memory instead of copying files: the graph was verified when it was loaded and changed only by commits since. It reads and writes NOTHING in the store's directory. The backup is an ordinary marked backup (12.6):

  • snapshots/<seq>/: one snapshot of the graph at its last commit seq, written through snapshots/tmp-<hex>/, synced, verified (12.3) and renamed;
  • wal/<seq + 1>.wal: an empty WAL segment of the graph's lineage (its header only), synced;
  • GRAPH and GRAPH.copy: the store's identity, lineage chain and creation parameters (5.2) with state 0, no WAL cut, the backup marker (seq, the time), wal_head seq + 1, closed_at seq; read back. No marks file: like a fork, the backup holds no WAL before its snapshot, so the marks would not be targets.

Into a missing or empty root it is a full backup. Into a marked backup of the same store (the relation of 12.7, and its position at most seq) it is an increment under an INTENT backup_increment whose files are the new snapshot directory and segment: the snapshot is newer than everything the backup holds, the commits between the backup's position and seq are not in it (no target between them). A later file-level increment of such a backup finds no segment of the source it continues and is refused: a full backup is needed.

The blobs the graph's state references (the new snapshot's blob table) are copied from the store's blobs/ leniently: the one exception to "reads nothing in the store's directory", since blobs live only there; one that is missing or damaged is listed as not carried.

12.12 Catalog commits on a closed store

A writer holding the writer lock of a CLOSED store MAY append one commit that changes only the schema (op 9) and the catalog (op 10), computed WITHOUT loading the elements (book page "Embedding Models in a Store"). No byte changes: the record is an ordinary Commit (9.3, a single record: such a commit is small) and the next open replays it like any commit.

  1. The catalog view: the newest snapshot's definitions table (6.3, with the forward-compatibility rules of 16: opaque definitions kept) and schema.json, then every record of the WAL after it in the replay set (12.1) up to the last complete record: a Commit's ops 9 and 10 applied with their before images VERIFIED against the view (a mismatch is damage), its data ops read (frames and checksums checked) and skipped; continuity, lineage (5.4) and 9.8 as for a recovery. The last commit's position, time and id sequences are the new commit's base (the manifest's without WAL commits). Damage refuses the commit with nothing written.
  2. A store this version may only read (a critical opaque definition or segment kind, 16 rule 3; a schema it cannot parse) is refused.
  3. Before appending, the writer MUST do what an open does to the WAL: apply a recorded wal_cut (9.7) and write GRAPH without it, remove an unstarted last segment and cut a torn tail (9.6), complete the marks file (10) and the blob ledger (10.1).
  4. The commit continues the last segment unless it is of an older file format version (never continued; one that starts at this commit is rewritten in the current version with its records, 15.1) or past the segment size: then a new segment (9.7, wal_head). Its time is at least every time the files hold (commits, marks, checkpoint records, the system journal's tail). It is synced before anything follows; a failed write is cut off again or its cut recorded (9.7). Then its ledger frames.
  5. GRAPH: a store closed cleanly records the new commit as closed_at (it MUST NOT be lowered); a crashed store (state 1) stays as it is. A crash between the commit and this write leaves a WAL ending later than closed_at, which is valid (9.8).

A reader without the lock (--read-only) sees at most an unfinished last record, which it ignores (9.6). No snapshot is written.

13. Damage handling

13.1 Redundancy

  • GRAPH and GRAPH.copy (5.3); the manifest's fixed part at its head and its tail (6).
  • The manifest's chunk index (6.2) carries the id range and CRC of every chunk.
  • WAL frames carry a sync marker and commit_seq outside the payload (9.2).
  • Retention keeps the last two verified snapshots and the WAL between them (12.4), and the donor rule (12.3) makes them independent: the newest snapshot shares no segment file with the previous one, so every id range of the newest has a donor in a distinct file (the previous snapshot's chunks plus the WAL between the two), and every range of the previous one has a later snapshot covering it. A file the newest snapshot references is a twin in the directory (or holder) of an older snapshot; its damage is repaired from the previous snapshot like damage of the newest's own files.
  • Flag bit 0 of GRAPH is reserved for parity data (not in store format version 4).

13.2 The damage scan

Chunks are checked one by one against the manifest's chunk index (a damaged segment header or footer with intact chunks is framing damage; the data is intact). WAL records are read with resynchronisation (9.2). Torn tails follow 9.6, the segment set follows 9.8. The commits a damaged WAL region lost are those between the valid commits around it; if none are missing, the region held a Mark or Checkpoint record. Damage to one copy of redundant metadata (one GRAPH copy, one manifest fixed part of the latest snapshot) is a warning, not damage.

13.3 Maintenance mode

A read-write open whose load fails with damage (a checksum, a gap, a lineage mismatch, a missing file, both GRAPH copies invalid, container damage, 14.4) does not fail and does not repair: the store opens read-only with a damage report that lists the damaged files, chunks and records, the id ranges and commits affected, and for each its donor: an older snapshot whose chunks cover the id range plus the WAL up to the damaged one; a later snapshot that covers a damaged WAL record; or the other copy. The readable state is built from donors. Nothing is written in maintenance mode (no state change in GRAPH, no torn-tail cut).

Damage found while a store is open. Damage a writer finds in its files while it holds the store open (a backup, 12.6; a checkpoint's merge, 12.3; a verification, 12.9) follows the store's damage policy (5.2 bit 5), fixed when the store was created:

  • maintenance (the default): the store turns read-only for the rest of the time it is open, with the damage as the reason: every commit, mark, checkpoint, prune, rollback and compaction is refused, and nothing more is written (a close syncs the WAL and does not rewrite GRAPH, so the next open sees an unclean close, which is no damage). Reading and a backup from memory (12.11) go on.
  • continue: the store keeps accepting commits; the damage stays reported for as long as it is open.

The policy does not apply to damage found when the store is OPENED: that is always maintenance mode, as above. Problems of attic entries alone (history moved aside, 11.2) are reported by verification but do not count as damage of the store's own history.

13.4 Repair

Repair is explicit and never in place; it writes a new, verified store elsewhere:

  • The base is the newest snapshot with a readable manifest; its schema comes from schema.json, else an older snapshot's plus the WAL's schema changes. Its catalog of definitions comes from its manifest (covered by the variable part's CRC); when a definition there does not decode, from an older snapshot's catalog plus the WAL's op 10 changes up to the base, else it is lost (reported). The repaired snapshot carries the catalog, unknown definitions byte for byte.
  • A damaged chunk is rebuilt from the newest older snapshot whose chunks overlapping its id range are all intact, provided the WAL between the two is complete: that range's elements are decoded and every WAL mutation naming an element of the range is replayed. Edges of intact chunks whose endpoint is lost are lost elements.
  • The WAL after the base is replayed mutation by mutation: a damaged record is skipped when a later snapshot covers it; otherwise replay continues after the gap, and every element whose current state does not match a later mutation's before image (or whose mutation fails) is reported as diverged (the later value is kept), never guessed.
  • The result is a new lineage whose chain continues the damaged store's, with one snapshot named repaired. The report lists what was repaired, the lost commits, id ranges and elements, and the diverged elements. The damaged files are never changed.
  • The blobs the repaired state references are copied, each checked by length, CRC-32C and SHA-256 (the source is damaged); a missing or damaged one is reported as not carried and does not fail the repair. A fork and an attic fork (12.5) copy the blobs of their new snapshot's table the same way (length and CRC-32C).

Blobs are not store damage. A missing or damaged blob (4.6) never opens a store in maintenance mode, never freezes it under the damage policy and never makes a repair necessary: what needs its bytes fails (reading it, exporting it), everything else goes on. The writer reports it once per blob and failure in its operational journal (the reference implementation's blob.damaged record names the blob, the failure and a recommendation: any copy with the same hash, from a backup or another copy of the store, is the same bytes).

Bringing blobs back. Two operations of a CLOSED store (the writer lock) deal with missing or damaged blobs; neither changes the history:

  • A blob restore checks every blob of the referenced set (12.4: length, CRC-32C and hash) and copies each faulty one from another copy (a backup directory with its increments, a ZIP backup, a packed snapshot, another store) by its algorithm and hash, a blob of an unknown algorithm by its name (4.6): streamed into blobs/tmp-<random>, checked the same way, synced and renamed into place as a blob write (4.6). A healthy blob is never touched; a source blob that fails the check is not used.
  • A repair that drops faulty blobs (13.4 above, opt-in) leaves out of the repaired store's catalog every definition that references a missing or damaged blob, and the blob. It MUST be refused before anything is written while the current schema needs such a definition (a model a vector property's embedder names, 4.5).

14. The single-file container

A whole store in ONE file (extension .gstore by convention; the content decides): a log-structured container behind the backend abstraction of 4.3. The store's own files, names and byte formats are exactly those of a directory; the container only records which bytes a name holds. Nothing inside the file is ever overwritten, except the two header slots.

14.1 Layout

0      preamble (16): magic "GRSLFILE" | container version u32 = 1 | flags u32 = 0;
       zeros up to 4096; written once at creation
4096   header slot 0 (64), zeros up to 8192
8192   header slot 1 (64), zeros up to 12288
12288  records, appended one after the other to the end of the file

Header slot (64 bytes): 0 magic "GRSLHEAD" | 8 generation u64 | 16 table offset u64 (the table record's frame) | 24 table record length u64 (the whole frame) | 32 table record sequence number u64 | 40 zero (20) | 60 CRC-32C of bytes 0..60. An all-zero slot is unused. Generation g lives in slot g mod 2; a new table is published by writing the OLDER slot with g + 1.

Record frame:

OffsetSizeField
04sync marker GSFR
41record type
53zero
88sequence number: +1 per record within one file, the first record is 1
168durable end: the file offset up to which every byte was synced when this record was written (at most the record's own offset)
244fields length F (at most 16 KiB)
288payload length P
36Ffields
36 + F4header CRC-32C of bytes 0..36+F
40 + F4payload CRC-32C
44 + FPpayload

Record types (fields: strings are string, numbers uvar; names follow 4.2 and are never empty):

TypeRecordFieldsPayload
1appendname, logical offsetthe bytes to append there (a missing file is created; a longer file is first cut to the offset)
2createnamenone: an empty file, replacing one
3putnamethe file's whole new content (an atomic replacement)
4truncatename, lengthnone
5mkdirnamenone (parents are implied)
6renamefrom, tonone: a file replaces a file; a directory moves with its subtree; onto an existing directory it is the completed cross-device move of 4.3 (only the source goes)
7removenamenone: a file or a whole subtree
8tablenoneevery name (14.1, below)

Table payload: uvar directory count, the directory names (string); uvar file count, per file name string | length uvar | extent count uvar | extents (container offset uvar, length uvar). An extent at offset 0 is a hole (zeros: bytes a damaged record lost); every other extent lies in 12288..table offset; the extents of a file add up to its length.

14.2 Writing

  • Every backend operation appends records: an atomic replace is one put record + sync; an append is one append record + sync; a truncate one truncate record + sync; name changes (mkdir, create, rename, remove) one record each, durable at the next sync. Bytes written through an open file handle are buffered (at most 1 MiB) and become one append record when the handle is flushed, synced, cut, full or dropped.
  • A new table is appended when the records since the last one reach max(16 MiB, 16 × the last table record's length), when the writer lock is released (a close), and after a damaged or missing table was found: table record, sync, the older header slot with generation + 1, sync. A torn table write leaves the previous header and table valid.
  • A new file is written under <name>.create-<hex>.tmp (preamble, an empty table as record 1, header slot 1 with generation 1), synced, hard-linked to the name only when nothing is there (a rename on file systems without links), and the directory synced.

14.3 Opening

The header slots are read; the valid ones are tried newest generation first: the table record a slot points at MUST be a type-8 frame with that sequence number and length, an intact payload CRC and a valid table. The first one that works is the base; the records after it are replayed. A damaged slot or table is a warning: the older generation and the records after it give the same names, because every change is a record. Without any usable table every record from offset 12288 is replayed (a warning).

14.4 Torn tail and damage

Replaying from the base, at a position p:

  • fewer than 44 bytes, or a header whose CRC is valid but whose payload runs past the end: the torn tail of an interrupted write;
  • an invalid frame header (marker, type, non-zero padding, fields length, header CRC, a durable end above p, or a sequence number below the expected one): the next position with a valid frame header is searched. None: if every byte from p on is zero, a torn tail; otherwise damage. Found at q: if the last valid frame of the file names a durable end above p, the bytes p..q had been made durable and are damage (replay continues at q; a sequence gap is reported as lost records); otherwise nothing after p was ever made durable: a torn tail at p;
  • an intact header with a payload CRC mismatch: an append whose bytes were made durable (a later frame names a durable end above p) is applied as it is and reported as damage; the last append of the file is applied as it is without a report (the store's own checksums judge it, as on a directory: zeros at the end of a WAL segment are a WAL torn tail, other bytes WAL damage); a put or another record made durable is skipped and reported as damage (a put keeps the old content); a table made durable is skipped with a warning (redundant); anything not made durable is a torn tail at p;
  • a valid record whose sequence number is above the expected one: damage (lost records);
  • an append beyond a file's end (a lost earlier append) leaves a hole and is damage.

A torn tail is cut (truncate + sync) at the next write, never by a reader. Container damage opens the store in maintenance mode (13.3); the container then refuses every write. Damage of both header slots or both tables alone loses nothing.

14.5 Locks, processes, relocation

  • The writer lock is the operating system's lock on the container file itself, held on its own handle; after taking it, the path MUST still name the locked file (a compaction may have replaced it), else it is taken again. A process without the writer lock changes the file only under that lock, taken for the one change.
  • A process that does not hold the writer lock compares the file's identity and length before each operation and replays what another process appended (or reloads a replaced file). A backup pin freezes the pinning process's view: every byte it references stays where it is until a compaction, and a replaced file stays readable through the open handle.
  • The file holds no path; it may be moved or copied while no process has it open. Temporary files of an interrupted create or compaction (<name>.create-*.tmp, <name>.compact-*.tmp) are removed when the writer lock is taken.

14.6 Compaction

A removal frees space only inside the file. Compaction copies the live state into <name>.compact-<hex>.tmp next to the file: the preamble, one mkdir record per directory, per file one create record (empty) or append records of at most 64 MiB, the table, header slot 1 with generation 1; synced; the writer lock is moved to the new file; the new file is renamed over the old one and the directory synced. It needs free disk space for the live data meanwhile and is refused on a damaged container.

Space accounting: total = the file's size; live = what a compaction would write, from the in-memory table; garbage = total - live (old tables, replaced and removed files, the framing of many small appends).

15. Versioning

  • Every file starts with a magic and a format version. There are three version axes: the store format version in GRAPH (offset 8, 5.1), the file format version in the manifests, segments, WAL segments and packed snapshots, and the single-file container version (14.1). This specification is store format version 4, file format version 4 and container version 1.
  • Version history of the store format: 1, the first version; 2 (Graphersal 0.1.0) added the store identity store_id at GRAPH offset 100 (5.5), which version 1 left zero; 3 (Graphersal 0.2.0) has the layout of version 2 and marks a store written with file format version 2. The bump exists for older readers: a reader of store format version 2 knows only file format version 1 and would take the manifests and WAL segments of file format version 2 for damage (an unknown version word is damage there, 13), open the store in maintenance mode and offer a repair that loses data; with version 3 in GRAPH it refuses the store as newer before it reads any other file. 4 (Graphersal 0.5.0) has the layout of version 3 and marks a store whose embedding models are blobs referenced by catalog definitions (4.5, 4.6), with the blob ledger (10.1) and the system journal (4.7); a version 3 store of Graphersal 0.4.0 may keep models as files under models/, which the upgrade migrates (15.1). With version 4 in GRAPH, Graphersal 0.4.x refuses the store as newer.
  • Version history of the file format: 1 (Graphersal 0.1.x); 2 (Graphersal 0.2.0) added the temporal value tags 9 to 13 and the vector value tag 14 (3); 3 (Graphersal 0.3.0) added the nanosecond temporal value tags 15 to 20 (with offsettime and the zone name of a datetime) and writes every temporal kind but date with them; 4 (Graphersal 0.5.0) adds the blob reference value tag 21 (3), the manifest's blob table (6.2 item 5), the segments of the system journal (4.7) and the Commit part record type 4 of the WAL (9.2, 9.3.1), written for commits larger than one part; 5 (Graphersal 0.7.0) adds the layer snapshot (7.5, segment kind 128) and is written ONLY in the packed header, manifest and layer file of a layer snapshot, every other file staying at version 4. Nothing else differs between these versions, so a reader of version 4 reads files of versions 1 to 3 as they are: a packed snapshot written by an older release loads, and a store created from it keeps its older manifest and segment files byte for byte (8, 12.1). Every file carries its own version: a snapshot MAY reference (6.2) or a packed snapshot MAY contain segment files of older versions, and a manifest of an older version MAY be rewritten in the current version (its content is valid in both). A file of a newer version is not readable by an older reader: since 0.1.1 every reader checks every file header first and refuses a store, backup or packed snapshot holding one as written by a newer version (unsupported version, below), never as damage. That is why file format versions 3 and 4 need no new store format version of their own, unlike version 2 (whose readers, 0.1.0, took an unknown file version for damage); store format version 4 marks the model migration (above). The container is still at version 1.
  • A writer writes only the current version: 4 for every file, 5 for the packed header, manifest and layer file of a layer snapshot (7.5).
  • A file with a newer version than the reader knows MUST be refused (unsupported version), never guessed at. A reader of file format version 4 MUST accept versions 1 to 4 in every file header (manifest 6.1, segment 7.1, packed snapshot 8, WAL segment 9.1), and version 5 in the packed header, manifest and layer file of a layer snapshot (7.5). A store whose snapshots are layer snapshots is a layer store (nothing else marks it: its manifests tell): it is opened only as a layer over the base its layer rows name. A version-5 manifest is read as a layer manifest only with its kind-128 row (else it is newer); a layer store opened as a whole graph, a whole-graph store opened as a layer, and a layer manifest over another base are refusals before anything is written, never damage. A reader without layer stores refuses the version-5 manifest as newer.
  • A version from the future is not damage, and a store holding one MUST NOT be worked on. A file whose magic matches and whose header checksum is valid (the GRAPH fixed part, 5.1; a manifest fixed-part copy, 6.1; a segment or WAL segment header, 7.1, 9.1) but whose version word is above the reader's is "written by a newer version". The reader MUST refuse the whole operation with an unsupported-version error and MUST NOT classify it as damage (13). A store, backup or single-file store holding even one such file MUST NOT be worked on in any way: no write, no lock, no maintenance mode, no salvage or repair, no upgrade (15.1), no checkpoint, no backup into or out of it, so a reader can never corrupt what a newer writer wrote. A single-file container (14.1, whose preamble has no checksum) is newer when its magic matches and its container version is above the reader's. A header whose checksum fails stays damage. Every operation on an existing store, backup or attic checks, before it takes a lock, reads data or writes: the container version, then both GRAPH copies (either one newer refuses the store, whatever the other holds), then the headers of every manifest, snapshot segment and WAL segment of the tree (snapshots, holders, tmp-* directories and attic entries); a header it cannot read is left to the operation's own checks. A restored ZIP backup that is refused this way is removed again. (The reference implementation does so since 0.1.1.)
  • Format versions move only with a release that needs them. A patch release (x.y.Z) MUST NOT change any format version (store, file or container). A format version changes only with a release whose new features need it; a release that changes no format reads and writes the stores of the release before it as they are, with no upgrade.
  • A GRAPH of an OLDER store format version (its magic and fixed-part checksum valid, the version word below the current one) MUST be classified by its version word before any field that version did not have is checked: it is neither damage (13) nor "not a store". Every operation refuses it with "older format" (open, read-only open, info, verify, backup, restore of a backup directory, fork, conversion), except the upgrade (15.1), the repair (which reads a store of a released older version as upgraded and writes the repaired store in the current version) and the restore of a ZIP backup (which upgrades what it unpacks).
  • Every release reads every released version. A reader of store format version 4 MUST read the files of store format versions 2 (Graphersal 0.1.0) and 3 (0.2.0 to 0.4.x) and of file format versions 1 to 3, and a later version MUST keep reading them; a store of a released older version is upgraded without the build that wrote it (15.1). Store format version 1 was never released: a store of it is migrated through a packed snapshot exported by the build that wrote it, from which the current build creates a new store (only the graph state, schema and catalog move; marks, the attic and backups do not).
  • New value tags, record types, mutation ops, INTENT operations and flag bits require a new version, except flag bits that a reader may ignore without misreading the store (a writer preserves unknown bits it read).

15.1 Upgrading a store

Which store format versions an implementation upgrades, and how, is an explicit table; an upgrade not in it is refused before anything is written. The reference implementation's table (generated from its code):

From store format versionWritten byToUpgrade
1never released (no store id)4unsupported (packed snapshot)
2Graphersal 0.1.x (no models: the version word only)4in place or into a copy (migration)
3Graphersal 0.2.x - 0.4.x4in place or into a copy (migration)
4Graphersal 0.5.x and later4nothing to do

"Version word" means only the version word of GRAPH and GRAPH.copy (and their checksums) changes, which is safe in place; "migration" means the version word plus the migration of the embedding models a version 3 store keeps under models/ (below; a store without models/ changes only its version word), in place or into a copy; "into a copy only" means the upgrade writes a new store and an in-place upgrade is refused; "unsupported" means the migration through a packed snapshot (below). A store holding a file of a newer version is never upgraded (15).

An upgrade converts a store of store format version 2 or 3 (a store, a backup directory, either backend) to version 4. Version 4 has the layout of versions 2 and 3 and every file of them is a valid file of version 4 (its own header names its file format version, which a version 4 reader reads), so an upgrade:

  1. Takes the writer lock of the store and refuses it while held (an older writer has it open).
  2. Checks every model of models/ against its manifest (4.5 "Older stores": every file's size and SHA-256, the three identity files, the weights' safetensors header) WITHOUT writing; a damaged, incomplete or unconvertible model refuses the upgrade.
  3. Verifies the store as version 4 would read it (12.6's checks: both GRAPH copies, every snapshot, every WAL record and the segment set of 9.8, the attic) WITHOUT writing: the GRAPH copies are read with the version word replaced by 4. Any problem refuses the upgrade (repair it instead, 13).
  4. With models/: writes INTENT upgrade_models (11.1).
  5. Rewrites GRAPH.copy, then GRAPH (each atomically, 5.3) with version 4 and every other field unchanged (lineage, identity, flags, the backup marker, wal_head, closed_at, wal_cut). Without models/ no other file changes, so no INTENT is needed: after a crash between the two writes the copies differ by the version word only and a version 4 reader uses the valid copy (5.3); repeating the upgrade rewrites both. An older reader refuses either state as newer.
  6. With models/: completes the INTENT (11.1): each model becomes ONE blob, the model tar of 4.5 holding its files and a manifest of format 3 built from the old one (identity, repository, revision, commit, licence, licence text, base models, gated, the files); ONE catalog commit (12.12, in a new WAL segment) defines the models (kind 5, no default); models/ is removed. The repository of a definition is the old manifest's; a model without one, or a second revision of a repository another model of the store takes, gets local/<12 hex> (its identity changes; the schema's embedder naming the old identity is renamed in the same commit). The positions before the migration commit have no models. A reader of version 4 that finds the INTENT completes it at its next read-write open or upgrade.

An upgrade into a NEW location copies every file of the store (as a conversion does: name by name, without the locks and temporary files) after step 2, writes a marker upgrade-in-progress.tmp into the target first, verifies the copy with its new GRAPH held in memory, then writes GRAPH.copy, GRAPH and removes the marker: until GRAPH is written the target is not a store, and a target holding the marker is an interrupted upgrade that the next upgrade into it clears. Unlike a conversion, the copy keeps the store id: it is the same store in the new version.

After an upgrade the files of file format version 1 stay where they are: snapshots, WAL segments and the attic keep their bytes, so the history is exactly what was written. A writer MUST NOT append to a WAL segment of an older file format version: when the newest segment of the lineage is older, the next record goes into a new segment of the current version (9.8: wal_head names it); a segment of an older version that holds no commit (it starts at the next commit) is replaced whole, atomically, by one of the current version under the same name that holds the same records. Such a segment is no rarity: a checkpoint taken while the store is open starts a segment named by the next commit and writes its Checkpoint record there (9.7), and a mark set afterwards adds its Mark record. Those records keep their bytes (their frames do not depend on the file format version), a torn tail after them is cut (9.6), and a commit record in the segment is damage (it holds a commit the store's state does not).

A new FILE format version alone needs no upgrade and no table row: a store of store format version 3 written by 0.2.x (files of version 2) was opened and continued as it is by a reader of file format version 3 (Graphersal 0.3.x); its version 2 files stay, the files written from then on are of version 3 (a new WAL segment, new snapshots), and from then on 0.2.x refuses the store as newer (15).

  • New definition kinds (6.3), new payload keys of a known kind, new segment kinds (7.5) and named extra files (8) do not change the version: the rules of 16 tell every reader how to treat what it does not know. The layer file (7.5, kind 128) is the exception: its kind alone would let an older reader load a layer's own elements as a whole graph, so a layer snapshot is of file format version 5 (below).

16. Extensibility

The format is meant to grow without migrations. These rules bind every reader and writer of store format version 4 and file format version 4:

  1. Length before payload, payload as a map. Every definition carries its length before its payload (6.3), so a reader skips an unknown kind by its length; a payload is a property map, so a reader ignores unknown keys of a known kind. A new field is a new key, never a new layout. Payload keys are never kind, name or flags (6.3).
  2. Unknown, not critical: kept. A definition of an unknown kind without the critical flag is kept as opaque bytes (kind, flags, name, payload) and written back unchanged at the next checkpoint and in every copy (fork, backup, ZIP, repair), so an older reader never drops a newer definition. Unknown keys of a known kind are kept the same way (their values, written after the known keys in the order read).
  3. Unknown and critical: read-only. A critical definition of an unknown kind, or a file of a critical unknown segment kind (7.5), must stay consistent with the data (an index, for example); a writer that does not maintain it would corrupt it. A store holding one opens read-only for that reader (12.1), and a writer never stores such a definition itself (9.3).
  4. One WAL op for every kind. Op 10 (9.3) carries every definition change; a new kind needs no new op and no new version. Its replay follows rules 2 and 3.
  5. Large data in files of its own. The manifest is read whole and bounded at 256 MiB: a feature with large data stores a definition in the catalog plus files in the snapshot directory, referenced from the segment table by a new segment kind (7.5) with the same critical/ignorable rule; packed snapshots carry such a file as a named extra file (section kind 5, 8).
  6. Two version axes. The format version (the byte structure; with rules 1-5 it rarely moves) and content versions such as a saved query's dialect: a DSL evolves by compiling the stored text, never by re-encoding files.
  7. Upgrades without the older build. Every release reads every released store and file format version (15), so a store of a released older version is upgraded by the current build itself (15.1); a store format change keeps that possible. A packed snapshot of an older file format version loads as it is.
  8. Host kinds. Definition kinds 128-255 (6.3) belong to hosts, the applications built on a library that implements this format; the format never assigns them, so a host entity never collides with a future library kind. To the library a host kind is an unknown kind: kept as opaque bytes under rules 2 and 3 (a critical one opens the store read-only), never damage. A host SHOULD encode its payload as the property map of 6.3 (the reference implementation offers that codec publicly), so the payload stays inspectable and extensible by key.
  9. An unknown value of a known key is not damage. Damage is what a checksum, a length or the byte structure (value tags, record types, mutation ops, guarded by the format version, 15) says is wrong. Content behind a valid checksum that the reader cannot interpret was written by a newer writer, and a reader MUST NOT report it as damage or offer a repair that would drop it (a repair by a reader that cannot read it loses it):
    • in a definition payload (6.3): kept and not served (an unknown value it can represent), or kept opaque (a payload it cannot read as its kind at all); a critical one opens the store read-only (rule 3);
    • in the graph schema (schema.json, 6.1; a schema image of op 9, 9.3): the schema changes what writes are allowed, so it is never ignored. A reader opens the store READ-ONLY (the data without the schema; nothing is written, not even a torn-tail cut) and refuses every operation that would write a state derived from it (a checkpoint, a fork, a repair) as unsupported; a backup copies its bytes as they are; verify reports it as a note, not a problem;
    • an INTENT operation (11.1) or a GRAPH state value (5.1) the reader does not know, and a well-formed entry outside its layout in a backup archive (12.8): refused as unsupported, never damage.
  10. Side areas of the store. A directory at the store root that a reader does not know (as models/ is for a reader older than 4.5) is left alone: never listed as damage, never removed by a prune or a compaction, not copied by that reader's copies. A new side area therefore needs no new version when an older reader ignoring it cannot misread the store; the copies it misses are listed with the area (4.5). journal/ and INSTANCE (4.7) are such areas for a reader older than 4.7 (it refuses a store whose journal segment has a newer file format version through the header walk of 15, like any newer file). blobs/ and ledger (4.6, 10.1) are side areas too; a store referencing a blob holds files of file format version 4, which an older reader refuses as newer.

17. Conformance notes

Readers

  • Check every CRC before using the bytes it covers; check every count and length against the remaining input before allocating (2).
  • Never treat damage as a torn tail: apply 9.6 and 14.4 exactly. Never skip an unknown record type, value tag or mutation op.
  • Keep what you do not know (16): an unknown definition byte for byte, unknown payload keys of a known kind, an unknown value of a known key (not served, written back as read), an ignorable file of an unknown segment kind in every file-level copy; open a store with something critical you do not know, or a graph schema you cannot parse, read-only. Content behind a valid checksum that you cannot interpret is never damage (16 rule 9).
  • Replay only files whose graph_id is on the lineage chain, each ancestor only up to its branch point (5.4), and require commit continuity (9.7).
  • A read-only reader of a store MUST NOT write anything into it, take the writer lock, or cut a torn tail. It SHOULD take the shared backup pin while it copies files, so that a prune cannot remove them meanwhile.
  • A reader tailing a live WAL (CDC) reads only complete records with valid CRCs and treats an incomplete record at the end as "not yet written". Records before the writer's durable end are final; a record after it may still be cut off (9.7).
  • Read every file with the version in its own header (15): accept files of format versions 1 to 4 in one store or packed snapshot, reject a temporal value tag in a version 1 file, a nanosecond temporal value tag (15 to 20) in a version 1 or 2 file and a blob reference (tag 21) or a Commit part record (type 4) in a file of version 1 to 3, and reject a temporal value outside its range (3) as damage; a zone name you do not know is unsupported content (3).
  • Assemble a commit in parts (9.3.1) as ONE commit at the position of part 0; grow its body part by part, never from body_length up front; an incomplete commit in parts at the end of the last segment is a torn tail starting at part 0 (9.6).
  • Check a blob's length before reading it and its CRC-32C on every read; a missing or damaged blob fails only what needs its bytes and is never damage of the store (4.6, 13.4). Treat the content of a blob (a model tar, 4.5) as untrusted input.
  • Treat marks and ledger as derived from the WAL (10, 10.1) and the system journal as information only (4.7): a damaged or missing one is rebuilt or shown as a note, never damage, and nothing is decided from the system journal.
  • A store whose current schema needs a model (4.5) is opened only with that model loaded, or read-only by a reader that cannot run models; a needed model that is missing, damaged or does not fit refuses the open.

Writers

  • Write every new file with the current file format version (4) and GRAPH with store format version 4; never append a record to a WAL segment of an older file format version (start a new segment, 15.1), and never write a nanosecond temporal tag into a file of version 1 or 2.
  • Write a commit whose body is larger than the part size in parts (9.3.1): consecutive records of one segment, rotation only before part 0, one sync after the last part, and a failed part cuts the WAL back to part 0 (9.7, 9.9).
  • Write a blob completely (temporary name, sync, rename, directory sync) BEFORE the commit that references it, and remove a blob only when no retained history references it (4.6, 12.4).
  • Never copy instance data (WORKLOAD except into an upgraded copy, INSTANCE, the locks) as part of another store (4.4, 4.7); never write the system journal of a read-only store or of a store in which damage was found (4.7).
  • Take every commit, mark and checkpoint time and every system-journal time from the instance clock (18).
  • Follow the write ordering of 9.9: a WAL never holds a commit that did not happen, and a caller never gets "ok" for a commit that is not durable under the configured durability.
  • Make files visible only when complete: a temporary name, sync, an atomic rename, a sync of the directory. Verify a snapshot before it is renamed (12.3).
  • Write GRAPH as specified in 5.3, wal_head as in 9.8, and every multi-file change under an INTENT with idempotent steps (11.1).
  • Never remove WAL or snapshots implicitly: only an explicit prune (12.4), a rollback (12.5) or removal of an attic entry removes history.
  • Record only store-relative names (4.2).

18. Time: the instance clock

Every time a store's history holds (commits, 9.3; marks, 9.4; checkpoint records, 9.5) and every time of the system journal (4.7) is read from ONE clock per instance (a process that has the store open, or a closed-store operation, 12.12):

  • Reading. A reading is max(system clock, floor) in microseconds (section 2) and raises the floor to itself, so readings never decrease (two readings may be equal). A commit's time is at least the time of the commit before it, and a record about commit N (a mark, a checkpoint, a journal record) is never earlier than commit N.
  • The floor is not stored. When an instance opens a store, or a closed-store operation starts, the floor is raised to the latest time the store's files hold: the loaded snapshot's times (6.1: created at, last commit at), every commit, mark and checkpoint record of the replayed WAL, and the newest record of the system journal. A recovery to a target (12.1) raises it from what it read; a read-only view of a past position uses the store's full floor.
  • A system clock that steps back (a resumed virtual machine, a manual change) leaves every time at the floor until the system clock passes it again; a step of more than one second is reported (the reference implementation writes a clock.step_back journal record). Times therefore stay monotonic, and the target "the last commit at or before time T" (12.1) stays well defined.
  • Times that are not part of the history (the "created at" of a snapshot manifest, a WAL segment header, the times of GRAPH, backups and attic entries) are informative and read from the system clock.

TinkerPop Compliance

Graphersal measures its Gremlin compliance against the reference semantics that Apache TinkerPop ships as executable Gherkin scenarios. Each scenario names a graph, a traversal and the exact expected result, so the suite works as a ready-made differential test against real Gremlin. It serves three purposes:

  1. Compliance measure: what passes, what does not, and why, grouped by root cause.
  2. Regression gate: a scenario that passed must keep passing; cargo test fails otherwise.
  3. Backlog generator: the failure report ranks the fix tasks.

The suite

  • Pinned version: Apache TinkerPop 3.8.2 (commit 952d8d8e4c3cd37ed8e192ecb97348e6e82594a9), vendored under crates/graphersal/tests/tinkerpop/features/. Only the scenarios in the compatibility scope count (see Out of scope and Deliberate incompatibilities); their number is in the generated headline numbers. The vendored directory's README.md records the upgrade procedure.
  • Runner: the integration test target crates/graphersal/tests/tinkerpop_features.rs, with its harness in crates/graphersal/tests/tinkerpop/harness/. Every scenario is translated to the Rhai DSL and runs through the script engine, the same path users take, so the suite also tests DSL parity.
  • Gate: crates/graphersal/tests/tinkerpop/baseline.toml lists every scenario that does not pass yet, with its class and a one-line reason.

Headline numbers

The numbers below are the suite's result on the current code, with the strategy scenarios and the deliberate incompatibilities excluded from the compatibility scope. All totals and percentages count in-scope scenarios only. The scope, the tables and the counts between the tinkerpop:begin/tinkerpop:end markers on this page are generated by the suite and checked by every test run (see Running and regenerating); never edit them by hand.

Scope of this run:

1675 in-scope scenarios; 215 excluded (strategies), 182 excluded (deliberate incompatibilities).

ScenariosShare
Passed1631 / 167597.4 %
Skipped5 / 16750.3 %
Unsupported (not implemented)39 / 16752.3 %
Wrong behaviour of supported steps0 / 16750.0 %
Passed of executed (non-skipped)1631 / 167097.7 %

Unsupported = translate 32, missing 7. Wrong behaviour = runtime 0, wrong_result 0, wrong_error 0, timeout 0, panic 0.

Every remaining non-pass is a missing step, overload or token, or a literal type the translator cannot express (see Classes); the scenarios that ran but differed on purpose are the deliberate incompatibilities. The per-class counts are in the line below the table.

CategoryPass %PassedTotalSkippedUnsupportedWrong
branch100.0 %142142···
data88.0 %7383·10·
filter98.9 %358362·4·
integrated100.0 %44···
map97.1 %759782320·
semantics97.2 %103106·3·
sideEffect98.0 %19219622·
all97.4 %16311675539·

API inventory (TinkerPop 3.8.2): 19 of 151 methods, 5 of 21 token classes, 37 of 131 members of registered token classes not registered

The largest remaining blockers are the call() step (its name is a Rhai built-in function), the set literals and GType.SET/TREE/VPROPERTY (no such value types), ranked with their scenario counts in the report and in the API inventory section of it. The date and time steps and literals (asDate, datetime, dateAdd, dateDiff) pass since 0.2.0. The full ranking is in the report. The open gaps are listed in TinkerPop Deviations.

Out of scope

Graphersal will provide subgraph views, partitions, read-only mode and row-level security through its own, more flexible access-control mechanism, and execution settings through its own unified, hierarchical execution-metadata mechanism (replacing with()/withStrategies()/parameters) — not through TinkerPop TraversalStrategys. GraphComputer/OLAP strategies do not apply to an in-memory OLTP engine. Therefore every scenario whose traversal, graph initializer or graph-count traversal calls withStrategies(...) or withoutStrategies(...) is excluded from the compatibility scope: it is not run, gets the class excluded, has no baseline entry, and is left out of every total and percentage. Scenarios that only use withSideEffect, withSack or with(key, value) stay in scope. The rule matches the strategy call wherever the scenario lives, not the feature file name; the table is crates/graphersal/tests/tinkerpop/harness/scope.rs.

ReasonStrategies
Views, partitions, read-only, row-level security: Graphersal's own access-control mechanismSubgraphStrategy, PartitionStrategy, ReadOnlyStrategy
GraphComputer/OLAP, not applicableVertexProgramStrategy, HaltedTraverserStrategy, VertexProgramRestrictionStrategy, ComputerVerificationStrategy, ComputerFinalizationStrategy, MessagePassingReductionStrategy, GraphFilterStrategy
Strategy configuration not supported: Graphersal's own execution-metadata mechanismevery other strategy (catch-all), e.g. ProductiveByStrategy, RepeatUnrollStrategy, SeedStrategy, CountStrategy, EarlyLimitStrategy, OptionsStrategy, the verification strategies

The counts per reason and strategy (generated):

Excluded from compatibility scope: 215 scenarios [views/partitions/read-only/row-level security are provided by Graphersal's own access-control mechanism, not by TinkerPop strategies: 93 (SubgraphStrategy 62, PartitionStrategy 24, ReadOnlyStrategy 7); GraphComputer/OLAP — not applicable to Graphersal: 16 (VertexProgramStrategy 3, VertexProgramRestrictionStrategy 2, ComputerVerificationStrategy 2, ComputerFinalizationStrategy 2, HaltedTraverserStrategy 3, MessagePassingReductionStrategy 2, GraphFilterStrategy 2); TinkerPop strategy configuration is not supported — Graphersal will provide its own unified, hierarchical execution-metadata mechanism (replacing with()/withStrategies()/parameters): 106 (AdjacentToIncidentStrategy 4, ByModulatorOptimizationStrategy 2, ConnectiveStrategy 2, CountStrategy 2, EarlyLimitStrategy 3, EdgeLabelVerificationStrategy 3, ElementIdStrategy 2, FilterRankingStrategy 2, IdentityRemovalStrategy 2, IncidentToAdjacentStrategy 2, InlineFilterStrategy 2, LambdaRestrictionStrategy 2, LazyBarrierStrategy 2, MatchAlgorithmStrategy 3, MatchPredicateStrategy 2, OptionsStrategy 3, OrderLimitStrategy 2, PathProcessorStrategy 2, PathRetractionStrategy 2, ProductiveByStrategy 29, ProfileStrategy 2, ReferenceElementStrategy 2, RepeatUnrollStrategy 18, ReservedKeysVerificationStrategy 3, SeedStrategy 6, StandardVerificationStrategy 2)]

Most of them are in integrated/ (all its strategy feature files); the rest live in a few other files (map/Max, Mean, Min, Sum, filter/Sample, sideEffect/Aggregate and single scenarios elsewhere). A feature file whose scenarios are all excluded is not listed in the report's per-file table. The report's "Excluded from compatibility scope" section lists the counts per reason and strategy and every excluded id.

Deliberate incompatibilities

Some scenarios cannot pass because Graphersal chose a different behaviour, or does not plan the feature at all. Each reason is a design decision, is documented on the page linked in the table and as a row of TinkerPop Deviations, and is listed explicitly by scenario id in INCOMPATIBILITIES in crates/graphersal/tests/tinkerpop/harness/scope.rs (ids, never tags, so a scenario a suite upgrade adds is never excluded silently). These scenarios are not run, have no baseline entry and are in no total or percentage; a guard test fails when one of them starts to pass, and another when an id does not exist. To move one back into scope, remove its id from the table and run the suite.

CodeWhere (feature files)WhyDocsScenarios
select-undeclared-labelSelectselect("a"), select("a", "b") and select(Pop.x, ..) on a step label that no as() or side-effect key of the query declares raise Graphersal's own detailed diagnostic, which names the label and shows how to declare it, before execution; TinkerPop silently filters the traverser out. A silent filter hides typos.for_developers/tinkerpop_deviations.md#deliberate-differences9
property-element-orderOrderabilityorder() over properties() elements: TinkerPop orders Property elements by their own total order (key, then value, with cross-type rules) and by property id; properties() here yields value-bearing handles that are ordered by value only, and Graphersal has no property ids. Property elements are handles, not values.users_guide/property_elements.md#deviations5
multi-meta-propertiesAddVertex, Combine, Conjoin, Dedup, Difference, Disjunct, Drop, Element, Has, HasLabel, Intersect, Local, Merge, MergeVertex, Product, Repeat, Select, ValueMapThe storage model is one value per property key, by design, with no properties on properties: Cardinality.list and Cardinality.set fail with UnsupportedCardinality and meta-property arguments are not stored. Every non-passing scenario tagged @MultiProperties or @MetaProperties that runs here (the executable part of the reason) is listed. The scenarios that need the crew dataset (the multi-/meta-property dataset, which the GraphSON import loads with one value per key: several entries fold into an array and meta-properties into _meta) are listed too.users_guide/upserts.md#not-supported-yet41
null-property-removalAddEdge, AddVertex, MergeEdgeScenarios tagged @DisallowNullPropertyValues: TinkerPop removes the property on property(k, null); Graphersal stores a real null, and removal is the explicit remove_property() step. By design: no hidden deletes.users_guide/removing_properties.md3
map-to-stringAsStringvalueMap().asString() yields Java Map.toString text ({name=[marko]}) in TinkerPop; Graphersal never produces Java formats as data text (the physical codec is the only text form), so a map is a cast error.users_guide/property_elements.md#deviations2
path-retraction-artefactPathsexpected result depends on TinkerPop's PathRetractionStrategy dropping repeat-loop labels; Graphersal returns the full shortest-path set (verified on TinkerPop: 24 with the strategy, 30 without)for_developers/tinkerpop_deviations.md#deliberate-differences1
match-stepLocal, MatchThe declarative match() step is not planned: declarative pattern matching will come through a Cypher/GQL front end on top of the same engine instead. match is also a reserved Rhai word.for_developers/tinkerpop_deviations.md#excluded-for-good36
extra-number-typesAsNumber, BigDecimal, BigInt, Byte, Sack, Short, TypeOfThe number model is int64 and float64 by design: GType.BYTE, SHORT, BIGINT, BIGDECIMAL, CHAR and BINARY and BigInteger literals have no Graphersal value type and are not planned; the width literals 1b/1s/1n/1m collapse to int64/float64 in the harness.for_developers/tinkerpop_deviations.md#excluded-for-good42
io-stepRead, WriteThe io() source step with read()/write() and the IO tokens is not planned: GraphML import and export is Graphersal's own API (GraphSource::from_graphml, import_graphml, the CLI --graph), not a traversal step.for_developers/tinkerpop_deviations.md#excluded-for-good12
graph-algorithmsConnectedComponent, PageRank, PeerPressure, ShortestPathThe GraphComputer vertex-program steps pageRank(), shortestPath(), connectedComponent() and peerPressure() (and their token classes) are not planned for the traversal language; these scenarios are also @GraphComputerOnly.for_developers/tinkerpop_deviations.md#excluded-for-good31
all182

The report's "Deliberate incompatibilities" section has the same table, with the full id list per code.

Running and regenerating

# Run the suite (also part of the plain `cargo test --package graphersal --features script,io,display,serde,persist,gql`)
cargo test --package graphersal --features script,io,display,serde,persist,gql --test tinkerpop_features

# Rewrite the baseline AND the generated blocks of this page after intended changes; review the diff like code
TINKERPOP_UPDATE_BASELINE=1 cargo test --package graphersal --features script,io,display,serde,persist,gql --test tinkerpop_features

Every run prints the summary to stderr and writes the full report to target/tinkerpop-report.md: headline, per-category and per-file tables, failures grouped by class (within missing ranked by the missing name, within runtime/wrong_result by the exercised step), baseline class changes, order-relaxed passes and the API inventory. TINKERPOP_DETAILS=1 prints one line per non-passing scenario; TINKERPOP_LANES=<n> sets the number of parallel worker lanes (default: one per core).

The test fails when:

  • a scenario that is not in the baseline fails (a regression);

  • a scenario in the baseline passes now, no longer exists or is excluded from the scope (the entry is stale; remove it in the same change);

  • an id of the deliberate-incompatibility table does not exist, is also excluded by a strategy, has no existing doc page, or names a scenario that passes now (deliberate_table_is_consistent, deliberate_scenarios_do_not_pass_silently).

  • a generated block of this page (between <!-- tinkerpop:begin NAME --> and <!-- tinkerpop:end NAME -->: scope, headline, categories, inventory, excluded, incompat) differs from what the run computes. The message shows the differing lines and the command above. Only trailing whitespace is ignored. A missing, duplicated or unclosed marker fails with a clear error too.

A normal run never writes a file (apart from the report under target/). With TINKERPOP_UPDATE_BASELINE=1 the run rewrites baseline.toml and the text between the markers of this page, nothing else: the prose and the step tables are hand-written. The blocks render the same Markdown as target/tinkerpop-report.md, so the page and the report cannot disagree. The page path resolves through CARGO_MANIFEST_DIR, so the suite works from the repository root and from the crate directory. Commit the regenerated page together with the change that moved the numbers.

A baseline scenario that keeps failing under a different class is reported, not failed.

GRAPHERSAL_TEST_STORAGE=forwarding runs the whole suite on a storage that is not TraversalGraph (the Forwarding wrapper of graphersal-storage-tests, with its own element handle types) to prove the front ends are storage-independent: it is gated against the same baseline and generated blocks, additionally fails when a scenario changes class, never rewrites either (TINKERPOP_UPDATE_BASELINE is refused with it) and writes its report to target/tinkerpop-report-forwarding.md.

Classes

ClassMeaning
skipped@GraphComputerOnly (OLAP) or an upstream "unsupported test"; counted in the scope, not executed (the crew scenarios are not skipped: they are the deliberate incompatibility multi-meta-properties, since Graphersal stores one value per key and its GraphSON import maps multi- and meta-properties to arrays and _meta)
translatethe translator cannot express it, e.g. a literal type Graphersal lacks (BigDecimal, BigInteger, byte, short, set, a map with a non-string key)
missingRhai "Function/Variable not found": a missing step, overload or token; the name is extracted
runtimean error while executing: the step exists but rejects this input
wrong_resultexecuted, but the result differs from the expected one
wrong_errorexpected an error but got a result (an expected error matches by type: any non-missing runtime error, whatever its text; a deliberate deviation of the harness, Graphersal's error texts differ from TinkerPop's)
timeoutexceeded the per-scenario budget
panica panic was caught (a rule-1 violation, top priority)
excludedout of the compatibility scope (a withStrategies/withoutStrategies scenario, or a deliberate incompatibility): not run, in no total

The headline splits the non-passing, non-skipped scenarios into two groups, because they mean different things. Graphersal does not plan to support 100 % of Gremlin's steps, but every step it does support must behave as the specification says:

  • Unsupported (classes missing and translate): the step, overload, token or literal type does not exist in Graphersal. An open feature gap, not a defect.
  • Wrong behaviour of supported steps (classes runtime, wrong_result, wrong_error, timeout, panic): the step exists and runs, but differs from the specification or fails. This is the number to keep at 0, and any entry in it is a bug.

The report, the console summary and the per-category and per-file tables use the same two groups; the per-class counts stay in a line below the headline table and in the "Failures by class" section.

Documented normalizations

The runner applies a small, fixed set of normalizations. None of them hides a semantic gap.

  • Tolerant id comparison. Graphersal's element ids are strings, TinkerPop's stock datasets use small integers with the same values. An expected d[N].i/d[N].l that stands for an id is stringified and compared with the string id. This applies to ids only.
  • Number-class comparison. Graphersal has int64 and float64 only, so numbers compare by class (integer vs. floating point), ignoring the declared width: d[1].i and d[1].l both match an int64, d[1].f and d[1].d both match a float64.
  • 1 ulp float tolerance. Two float64 result values compare equal when they are equal or differ by at most 1 ulp (NaN equals NaN, infinities exact, +0 equals -0, other signs must agree). This absorbs last-digit differences between Rust's libm and Java (sin(4.0)), not an arithmetic deviation of Graphersal (see Deviations). It applies to float vs. float result values only, never to integers, ids, orderings or error cases.
  • Order relaxation. When a scenario expects an ordered result, the sequence differs but the multiset matches, and the translated traversal has no explicit ordering step (order()/by()), the scenario passes as an "order-relaxed pass", listed separately in the report. Graphersal does not guarantee TinkerGraph's insertion order across GraphStorage implementations. With an explicit ordering step the exact sequence is required.
  • Tree assertions. the result should be a tree with a structure of compares the single result as a map of key to nested map (a leaf is an empty map). Keys are compared by value (vertices by id, numbers by class, strings) and the siblings of a node match as a set, because TinkerPop's Tree is an unordered map.
  • Subgraph assertions. the result should be a subgraph with the following compares the graph value's {"vertices": [..], "edges": [..]} listing with the edge and the vertex table, each as a multiset (vertices and edges by id).
  • Lexical-only translation. The translator from canonical Gremlin to the Rhai DSL rewrites only lexical differences between Groovy and Rhai: numeric suffixes (1L, 1d), list and map literals, string quoting, parameter and side-effect bindings, and Groovy's static imports (a bare out() becomes __.out(), a bare desc becomes Order.desc). Token map keys (T.label:, (T.id):, Direction.OUT:, and the t[..]/D[..] keys of parameter maps) become the DSL's reserved string keys "T.label", "T.id", "Direction.OUT", "Direction.IN". A missing step, overload or token is never emulated: it reaches the engine and fails there, counted against that step.

Test Coverage

Coverage is measured with cargo-llvm-cov (source-based LLVM coverage on the stable toolchain; install the tool and llvm-tools-preview once). Coverage is an analysis aid, not an acceptance gate: it shows thinly tested places, it does not prove behaviour.

Running it

Three runs separate what the hand-written tests cover from what only the TinkerPop suite reaches. Clear the old profile between runs, otherwise the runs are merged:

F=script,io,display,serde,persist,gql
IGN='(tests/|benches/)'

# 1. everything: lib unit tests + tests/all + the TinkerPop suite
rm -f target/llvm-cov-target/*.profraw target/llvm-cov-target/*.profdata
cargo llvm-cov --no-report --package graphersal --features $F

# 2. hand-written tests only (no TinkerPop suite)
rm -f target/llvm-cov-target/*.profraw target/llvm-cov-target/*.profdata
cargo llvm-cov --no-report --package graphersal --features $F --lib --test all

# 3. TinkerPop suite only
rm -f target/llvm-cov-target/*.profraw target/llvm-cov-target/*.profdata
cargo llvm-cov --no-report --package graphersal --features $F --test tinkerpop_features

Right after a run, turn its profile into a report:

cargo llvm-cov report --package graphersal --ignore-filename-regex "$IGN"                 # table on stdout
cargo llvm-cov report --package graphersal --ignore-filename-regex "$IGN" --json --summary-only > summary.json
cargo llvm-cov report --package graphersal --ignore-filename-regex "$IGN" --html          # target/llvm-cov/html/index.html

--ignore-filename-regex '(tests/|benches/)' removes the tests, the TinkerPop harness and the benches from the percentages, so only crates/graphersal/src/ is measured. Never commit target/. The single command from CLAUDE.md (cargo llvm-cov --package graphersal --features script,io,display,serde,persist,gql) is run 1 with a text report.

Reading the report

  • Lines % is the number to rank by. Functions count monomorphized instances (a generic step instantiated for three storages counts three times). Regions are finer than lines (branches, ? early returns, match arms).
  • A file with a #[cfg(test)] module counts those test lines as covered code, so error.rs looks a little better than it is.
  • Doc tests are not measured: --doctests needs a nightly toolchain.
  • Compare the runs per file: covered by run 1 but not run 2 means only the TinkerPop suite protects that code (fragile; add a hand-written test). Missed by run 1 means nothing tests it.
  • In the HTML report, red lines are uncovered; open a file and look for whole process/error branches that are red. Fused or batch steps often have an unexercised per-traverser fallback; run the query with the optimizer disabled (g.with("optimizer.disabled", [...])) to reach it.

The book's Rust code blocks

mdbook test compiles every Rust block of the book against the library. A plain mdbook test book fails ("crate graphersal not linked"), because rustdoc needs the compiled crate and mdbook cannot pass --extern. book/test.sh does the whole job: it builds graphersal with script,io,display,serde,persist,gql into its own target directory (target/mdbook-test, so exactly one rlib exists) and runs mdbook test with that library path and a rustdoc shim that adds the --extern.

book/test.sh

A block that cannot compile by nature (it needs another crate or a feature the script does not enable) is marked rust,ignore; verbatim program output is a text block.

Last measured numbers

Measured with the three-run recipe above, with the features script,io,display,serde (before persist joined the recipe, so the persistence code is not in these figures):

RunLinesFunctionsRegions
Everything89.50 %89.14 %89.63 %
Hand-written only89.22 %89.03 %89.37 %
TinkerPop only32.82 %29.26 %29.87 %

The TinkerPop suite adds only 0.3 points on top of the hand-written tests, so little code depends on it alone. The weakest hand-written areas at that point were traversal/traverser.rs (72 %, the string readers of edge-property handles), the from()/to() modulators (72 %, Debug/Clone only), has(key, P) (75 %), step_by.rs (75 %), traversal/step/mod.rs (75 %, trait default methods every step overrides) and value/mod.rs (76 %, the per-shape fetch_* arms).

These figures are a snapshot, not a gate; re-run the recipe for a current report.

Releases and Versioning

Versioning

Graphersal follows Semantic Versioning. Before 1.0 a minor version (0.1 to 0.2) may break the API; a patch version (0.2.0 to 0.2.1) does not.

Every crate of the workspace shares one version number ([workspace.package] in the root Cargo.toml), and the Python package and the web playground are released with the same number:

ArtifactWhereNotes
graphersalcrates.iothe library: engine, Rhai DSL, I/O, persistence (feature flags)
graphersal-sessioncrates.iothe playground session logic, published because the CLI depends on it; internal, no stability guarantees
graphersal-mcpcrates.iothe MCP endpoint of the servers (protocol, connections, tools, resources, operator configuration, profiles), published because the CLI depends on it; internal, EXPERIMENTAL, no stability guarantees (a dependent pins the exact version during 0.x)
graphersal-servecrates.iothe hosting core of the dev server (session thread, run registry, the playground HTTP API without an HTTP library, the embedded playground UI, extension points), published because the CLI depends on it; internal, EXPERIMENTAL, no stability guarantees (a dependent pins the exact version during 0.x)
graphersal-clicrates.iothe graphersal binary: REPL, one-shot runner, graphersal store, the dev server
graphersal (CLI binaries)GitHub Releaseprebuilt archives of the graphersal binary for four platforms, with SHA256SUMS and build provenance attestations
graphersal-storage-testscrates.iothe GraphStorage conformance suite, EXPERIMENTAL like the trait (pin the exact version)
graphersal (Python)wheels (abi3, Python 3.10+)the PyO3 binding from bindings/py-graphersal
web playgroundstatic filesruns graphersal-wasm (not published; its JS API is internal to the playground)

Stability in 0.8.x

The same rules hold for every minor line before 1.0 (they held for 0.1.x to 0.7.x as well); a minor release (0.7 to 0.8) may break them, and its release notes list every break with the upgrade step (Release Notes 0.8.0).

  • Stable within 0.8.x (additive changes only): the public API of graphersal outside the items marked EXPERIMENTAL, the DSL and the schema format.
  • EXPERIMENTAL (may change in any 0.8.x release): the GraphStorage trait and its associated types, PersistentStorage, AnyGraph, StoreDir, and graphersal-storage-tests; pin the exact version.
  • Internal: graphersal-session, the wasm crate's JS API, the dev server's HTTP API and its MCP tools (--server is a development tool, bound to the loopback interface unless --host or a container says otherwise), the experimental AI Chat.
  • Internal and EXPERIMENTAL, no stability guarantees, changed in any release (a patch release included): graphersal-mcp and graphersal-serve, the building blocks of Graphersal's own servers; a crate that depends on them pins their exact versions during 0.x.
  • The storage format has its own version numbers (Format Versions and Upgrade): a patch release never changes a format version, and every release reads the formats of every release before it (an older store is upgraded with graphersal store upgrade, no older build needed).

The API rules that keep a change additive (public enums and result structs #[non_exhaustive], default methods for every new trait method) are checked with cargo-semver-checks:

cargo install --locked cargo-semver-checks          # one-time
cargo semver-checks --package graphersal --baseline-rev <previous release tag>

From 0.1.0 on a reported break is a release blocker unless the version number says so.

Release gates

Before a version is tagged:

  • the CI workflow, started by hand with full (gh workflow run CI -f full=true: Linux and Windows), is green: format, clippy, every test suite incl. the TinkerPop suite, the feature and wasm32 matrices, the MSRV, the playground tests;
  • the checks CI leaves out pass locally: RUSTDOCFLAGS="-D warnings" cargo doc with the feature sets of CLAUDE.md, mdbook build book, the TinkerPop suite on the foreign storage (GRAPHERSAL_TEST_STORAGE=forwarding), and the tests that depend on the machine's CPU time or memory (an upper bound on wall-clock time, a speed ratio, measured process memory): they skip themselves on a CI runner (the environment variable CI, which GitHub Actions sets, through the helper skip_on_ci), because a shared runner guarantees neither, so the plain local cargo test runs (without CI) are the only place they are checked;
  • cargo deny check (licences, RustSec advisories, duplicate crates, sources) passes against deny.toml;
  • the long fuzz budgets pass: robustness, the merge checkpoint, the verified backups and the closed-store catalog commits (below; a fast budget of each runs in every cargo test), and the ignored test of a commit larger than 1 GiB;
  • a benchmark run on a quiet machine shows no unexplained regression against the previous release;
  • a dry run of the CLI binaries (gh workflow run "CLI binaries" --ref <release branch>, see Publishing) is green on all four platforms;
  • cargo publish --dry-run succeeds for every published crate, graphersal first, then the crates that depend on it (graphersal-serve after crates/graphersal-serve/prepare-package.sh, see Publishing);
  • the version's release notes (book/src/release_notes/, for 0.2.0 Release Notes 0.2.0) describe what changed; they are the project's record of changes (there is no separate CHANGELOG.md) and the text of the GitHub Release.

The long fuzz budgets (release builds with overflow checks and debug assertions kept on):

CARGO_PROFILE_RELEASE_OVERFLOW_CHECKS=true CARGO_PROFILE_RELEASE_DEBUG_ASSERTIONS=true \
ROBUSTNESS_CASES=500000 ROBUSTNESS_SEED=23 ROBUSTNESS_THREADS=7 \
  cargo test --release -p graphersal --features script,io,display,serde,persist,gql \
  --test all robustness_fuzz_tests::fuzz_long -- --ignored
ROBUSTNESS_INPUT_CASES=20000 cargo test --release -p graphersal \
  --features script,io,display,serde,persist,gql --test all robustness_input_tests::
ROBUSTNESS_INPUT_CASES=20000 cargo test --release -p graphersal \
  --features script,io,display,serde,persist,gql --test all persist_robustness_tests::
MERGE_FUZZ_CASES=60000 MERGE_FUZZ_SEED=1 MERGE_FUZZ_THREADS=8 cargo test --release -p graphersal \
  --features script,io,display,serde,persist,gql,persist-zip --test all merge_checkpoint_fuzz_tests::
BACKUP_FUZZ_CASES=60000 BACKUP_FUZZ_SEED=1 BACKUP_FUZZ_THREADS=8 cargo test --release -p graphersal \
  --features script,io,display,serde,persist,gql,persist-zip --test all backup_fuzz_tests::
CLOSED_FUZZ_CASES=60000 CLOSED_FUZZ_SEED=1 CLOSED_FUZZ_THREADS=8 cargo test --release -p graphersal \
  --features script,io,display,serde,persist,gql,persist-zip --test all closed_commit_fuzz_tests::
cargo test --release -p graphersal --features script,io,display,serde,persist,gql \
  --test all persist_tests::a_unit_over_one_gib_commits -- --ignored --exact

Robustness findings go to target/robustness-findings.txt (ROBUSTNESS_REPLAY=<seed> replays one case); a failing merge, backup or closed-commit case prints MERGE_FUZZ_REPLAY=<seed>, BACKUP_FUZZ_REPLAY=<seed> or CLOSED_FUZZ_REPLAY=<seed>. Memory: the long robustness run (7 threads, each under its own memory ceiling) and the commit of more than 1 GiB (it peaks at 4.4 to 5.7 GB) need about 9 GB of RAM.

Benchmarks

cargo bench -p graphersal --bench graph --features io,script,display,serde is the regression benchmark. Every supported step or feature has at least one representative shape in crates/graphersal/benches/graph.rs, run on a graph large enough to surface an O(n²)-class regression (the 110k-element large graph), so a change that reintroduces an allocation- or complexity-class regression is caught by cargo bench rather than by a user profiling a real dataset. A new step gets its bench shape with the step. Benchmarks run once per release on a quiet machine and are compared with the previous release, not per change.

Publishing

  1. Tag the release commit: git tag -a v0.2.0 -m "Graphersal 0.2.0" && git push origin v0.2.0 (the tag equals the workspace version).
  2. The crates go to crates.io by hand, in dependency order: cargo publish -p graphersal, then graphersal-storage-tests, graphersal-session, graphersal-mcp, graphersal-serve and graphersal-cli. Before graphersal-serve, run crates/graphersal-serve/prepare-package.sh: it copies the playground UI the crate embeds into its git-ignored ui/ (check with cargo package -p graphersal-serve --list). Its cargo publish -p graphersal-serve needs --allow-dirty: Cargo counts the git-ignored ui/ copy as uncommitted changes.
  3. The workflow release.yml, started on the tag: gh workflow run Release --ref v0.2.0. It checks that the tag matches the version and that the version's release notes exist, then runs two independent parts:
    • PyPI. It builds the four-platform wheels and the sdist through python.yml (which also runs the binding's tests and installs each wheel it can run), and uploads them with PyPI Trusted Publishing from the environment pypi (no token is stored).
    • CLI binaries and the draft GitHub Release. It builds the graphersal binary through binaries.yml with the dist profile (release + fat LTO + stripped symbols; never panic = "abort", units roll back on unwind), natively on each platform's runner: Linux x86_64 and aarch64 as static musl builds, macOS arm64, Windows x86_64. Each build is smoke-tested on its runner (--version, a query, the dev server's /api/info) and packed as graphersal-v<version>-<platform>.tar.gz (Windows .zip) with LICENSE-APACHE, NOTICE, README.md and THIRD-PARTY-LICENSES.html (cargo-about, about.toml). A final job writes SHA256SUMS and creates the GitHub build provenance attestations. The job github-release then creates a draft GitHub Release for the tag, titled "Graphersal ", with the four archives and SHA256SUMS attached; its text is the version's release notes (book/src/release_notes/release_notes_<version>.md) with the book links made absolute on graphersal.dev, the soft line breaks joined and a section about the prebuilt binaries added (.github/scripts/release_notes.py <version> prints the same text locally).
  4. Check the draft on the repository's Releases page: four archives (linux-x86_64, linux-aarch64, macos-arm64, windows-x86_64) plus SHA256SUMS; download one archive and check it (sha256sum -c SHA256SUMS --ignore-missing, gh attestation verify <archive> --repo graphersal/graphersal, unpack it and run graphersal --version); read the release text, its links included. Then publish the draft ("Publish release", or gh release edit v0.2.0 --draft=false). Only a published release is visible to users and to cargo binstall graphersal-cli (its metadata in crates/graphersal-cli/Cargo.toml names the same archives).

Before tagging, the binaries can be built as a dry run on any branch: gh workflow run "CLI binaries" --ref <branch> builds, smoke-tests and uploads the archives as workflow artifacts and publishes nothing (no attestations). -f compare_musl=true adds a job that times the same queries on the large graph with a glibc and a musl build of linux-x86_64 and writes the comparison into the run's summary.

Version Control and Contributions

The short human guide for contributors is CONTRIBUTING.md in the repository root; this page summarizes how changes reach the repository.

Branches and pull requests

  • main is the only long-lived branch; every change comes as a pull request against it.
  • A pull request keeps the CI workflow green (format, clippy, the test suites, the feature and wasm32 matrices); CI runs on a manual start, so run the checks locally (CONTRIBUTING.md) and a maintainer starts CI for the pull request. When it adds or fixes a Gremlin step, the TinkerPop baseline is updated in the same pull request (TinkerPop Compliance).
  • A user-visible change is described in the upcoming version's release notes (book/src/release_notes/).
  • Releases are tags on main (Releases and Versioning).

Commit messages

Commit messages follow Conventional Commits, in English: type(scope): summary, for example fix(step): has_id() with a numeric predicate or docs(book): the Store's backup page. Common types are feat, fix, docs, test, refactor, perf, build and chore.

Contributor License Agreement

Graphersal is licensed under Apache-2.0, and contributions are accepted under the Contributor License Agreement (the CLA.md file in the repository root): the author keeps the copyright and grants the maintainer a licence to use, distribute and sublicense the contribution, including under licence terms other than Apache-2.0, plus a patent licence. A version already published under Apache-2.0 stays available under it.

The agreement is signed once, by a comment on the first pull request; a CI check (.github/workflows/cla.yml) asks for it and keeps the signatures on the branch cla-signatures:

I have read the CLA Document and I hereby sign the CLA

A pull request is merged only when every author of its commits has signed. No Signed-off-by: line is needed.

Release 0.8.0

A minor release for hosts. The EXPERIMENTAL hosting crates graphersal-serve and graphersal-mcp get what a server needs once it knows who sends each request: MCP sessions that belong to the identity that opened them and can survive a restart, directory selections that follow a re-pointed or renamed alias, a read-only mark per request, a file root that keeps client paths inside one directory, and presets a query may lower but not raise. The playground sends a visitor to the host's login page when the host asks for a login. GQL counts after any walk without building a row per match, and the knowledge base Docker image is built by one Python script.

The public API of graphersal is unchanged apart from additions: cargo semver-checks against 0.7.1 reports no break of graphersal, graphersal-session, graphersal-serve and graphersal-storage-tests. The breaks are in the EXPERIMENTAL crate graphersal-mcp (one API break and changes of behaviour): read "Upgrading from 0.7.x" first. No format changes; stores, snapshots, journals and backups of 0.7.x are read and written exactly as before. The graphersal --server dev server answers as before.

Upgrading from 0.7.x

Stores and files. A drop-in replacement: no format change, no upgrade step. 0.7.x reads everything 0.8.0 writes.

graphersal-mcp (EXPERIMENTAL, breaking). These changes affect hosts built on the crate and agents of a directory-mode endpoint. The dev server's MCP endpoint is unchanged: it serves one graph and attaches no identity.

  • use_graph answers a new shape. It answers selected (the name the agent asked for, a graph or an alias), graph (the graph that name resolves to now), kind, state, readOnly and note. The requested key is gone, and selected is now the name, not the route. list_graphs gains selectedGraph beside selected.
  • A directory selection follows its name. A session that selected an alias follows it when the alias is re-pointed (before, it stayed on the graph resolved at use_graph). A removed name fails the session's calls with a message naming list_graphs and use_graph until a graph or alias of that name exists again.
  • A session belongs to its identity. A request that names an MCP session id with another identity than the session's initialize (McpRequest::with_identity; none is anonymous, an identity of its own) gets the unknown-session 404, and its DELETE ends nothing. Signed session ids minted for an identity differ from anonymous ones; anonymous ids are unchanged. Mcp::verified_session_route(id) now checks the id as anonymous; a host that attaches identities calls Mcp::verified_session_route_for(id, identity).
  • Mcp is no longer UnwindSafe and RefUnwindSafe (it may now hold an Arc<dyn SessionStore>). Code that moves an Mcp into std::panic::catch_unwind wraps it in AssertUnwindSafe.

graphersal-session (internal). SessionPresets gains the field ceilings (the struct is #[non_exhaustive], so this is additive).

Hosting pieces for identity-aware servers (EXPERIMENTAL)

These additions to graphersal-serve, graphersal-mcp and the script engine let a host that authenticates its callers serve them safely. Every one is off unless the host turns it on, so the dev server and every host that does not use them behave as in 0.7.1. The book page Serving Layers describes each one.

  • Directory selections follow aliases. use_graph stores the name the agent asked for and the endpoint resolves it again on every call, as an HTTP path /db/<name>/ is. A host that renames an alias calls Mcp::rename_selection(old, new) (it answers the number of sessions moved); each moved session's next tool answer starts with the line note: alias "<old>" was renamed to "<new>" (directory mode).
  • Sessions belong to their identity. Every MCP session is bound to the identity of its initialize, in table mode and with signed ids, with Mcp::verified_session_route_for for the host's resolver. A host whose graphs differ per caller builds its GraphDirectory per request and answers a hidden graph like an unknown one (Sessions belong to their identity).
  • Sessions survive a restart. Mcp::with_session_store(Arc<dyn SessionStore>) loads the stored sessions once and saves the whole table after every change. Each row is a StoredSession: the SHA-256 of the id (the table never holds the plain id), the identity, the selected name, a pending rename note, the protocol revision, the client and the creation time. A failed save is a tracing warning, never a failed request. Mcp::forget_sessions_of(identity) ends one identity's sessions at once, for a revoked token or a removed user. Signed ids keep no table, so with_session_store refuses them (Sessions survive a restart).
  • Read-only requests. Request::mark_read_only() (and Request::is_read_only()) marks one request as coming from a reader, in the host's router or RequestFilter. /api/execute and /api/query then run under the reading authorizer, every other writing route answers 409 (READ_ONLY_REQUEST_HELP names the reason), reads and downloads stay open, /mcp serves the request under the context's profile made read-only (the new Profile::with_read_only), and /api/info and /api/changes answer readOnly: true for it. The context stays writable for every other request (Read-only requests).
  • File root. ContextBuilder::file_root(Some(root)) (Context::file_root) confines the paths a client names to one directory: backup job paths of POST /api/jobs/define, the jobs of a loaded catalog, and the dir of a Store fork, attic fork or backup. A relative path is relative to the root; one that leaves it (an absolute path elsewhere, .., a symbolic link pointing out) is refused. Jobs already stored in a store the host loads are checked by the host with graphersal_serve::jobs_outside_file_root, which answers a JobOutsideFileRoot per offending job. The default, no root, keeps the old behaviour (File root).
  • Presets as ceilings. graphersal::script::graph_scope_with_ceilings and engine_with_ceilings (the same arguments as graph_scope_with_options and engine_with_options) make the preset limits ceilings: a query's g.with(..) may lower evaluationTimeout, repeat.max_loops, bulk.max_expansion and the traversal.max_* limits without asking the authorizer, and a larger value or no limit at all fails before anything runs with the new TraverserError::OptionAboveCeiling (a raise is refused, never clamped). The rule covers every source the script reaches and the saved queries it calls. A graphersal-session host sets SessionPresets::with_ceilings(true); its presets then answer ceilings: true (Presets as ceilings).

Playground

  • Login of a host (EXPERIMENTAL). When a host answers an API request with 401 and names its login page in the body ({"error": "...", "login": "/"}), the playground goes to that page with ?next= and its own path, when it starts (instead of falling back to the WebAssembly engine) and on every later request. Only a path of the page's own origin is followed, and the page never redirects to itself. The dev server and the WebAssembly playground never send it (Login of a host).

Performance

  • GQL count(*) after any walk is the lazy count. An aggregation that only counts rows (count(*), or count(x) of a variable that is never NULL, without a grouping key) became the fused count() only after a node scan or one plain hop; after any other walk (more hops, joins, OPTIONAL MATCH, UNWIND, WITH) it built a row per match. It is now the lazy count whatever comes before it. On the large graph, MATCH (a)-->(b) WHERE b.id <> "x" RETURN count(*) materializes 21.8 MB like the equivalent Gremlin count() (before: 33.5 MB), and MATCH (a)--(b) RETURN count(*) peaks at 8.5 MiB instead of 34.8 MiB (Counts).

Docker

  • One build script for the knowledge base image. docker/prebuilt/build.py (Python 3.9+, standard library only; Linux, macOS and Windows) replaces fetch-binary.sh and prepare-kb.sh. It takes the binary from a release archive checked against its SHA256SUMS, a plain Linux binary, or a GitHub Release or CI run (--version, cached for offline builds), and builds with Docker or Podman (--engine, --push for a multi-platform manifest). The image ships the prepared single-file Store as is: the build runs nothing on it, so prepare the store first (store fork, store verify, mcp-cost); a directory store is refused with a hint to fork it into a .gstore (A knowledge base image).

Release 0.7.1

A patch release of the 0.7 line. Running a large query again and again no longer grows the process on macOS (#36), and large expansions run 5 to 35 % faster. GQL calls the allocator less per row. The dev server gets a run administration that lists and stops every client's queries (#32), and a store conversion can leave out the blobs it cannot find.

It changes no format; stores, snapshots and journals of 0.7.0 are read and written exactly as before. The API changes of graphersal and of the EXPERIMENTAL crate graphersal-serve are additive (cargo semver-checks reports no break of graphersal against 0.7.0).

Upgrading from 0.7.0

A drop-in replacement: no format change, no upgrade step. The run administration stays off unless the dev server is started with --admin-runs.

Fixed

  • Repeated executions keep memory flat on macOS (#36). A query whose intermediate results grew beyond about 8 MB kept that memory after every execution. A two-hop over 400k edges added about 288 MB per run: 2.4 GB of resident memory after 8 runs. It now stays at about 440 MB however often it runs. The engine did not leak: the macOS allocator never reuses a large block that realloc grew in place once it is freed. The engine's step buffers (expansions, repeat(), filter and write outputs, the path arena and the undo log) now grow by moving to a new block sized from a projection of the inputs so far, so the peak of a single large expansion is also slightly lower. Buffers below 128 KiB grow as before. Other platforms are unaffected.

    The fix matters most where one process runs many queries: the REPL, the dev server, MCP agents and host applications. Maximum resident memory after 1 and after 8 runs:

    Query0.7.00.7.1
    two-hop over 400k edges386 -> 2399 MB441 -> 438 MB
    GQL variable-length match *1..3683 -> 1676 MB712 -> 712 MB
    GQL SET over 250k rows172 -> 495 MB162 -> 164 MB
    GQL two-hop with ORDER BY ... LIMIT 3194 -> 314 MB169 -> 169 MB

Performance

  • Large expansions are faster. A large step buffer no longer faults in fresh pages on every execution, so the benchmark cases that expand many traversers on the large graph run 5 to 35 % faster than in 0.7.0: repeat(out()).times(3).count() 23 %, out().out().count() 21 %, out().out().simple_path() 16 %, as()/select() over two hops 12 %, both_v() 9 %, tree() 5 %. A benchmark process of such a case peaks at about 100 MB instead of 0.5 to 1.6 GB. The two-hop benchmarks, which exceeded 5 GB in 0.7.0, run at 420 MB. Across all 145 benchmark cases the geometric mean is 2.5 % faster.
  • GQL allocates less per row. ORDER BY no longer allocates per row for its sort keys (ORDER BY ... LIMIT 10 over 10k rows: about 20 000 -> 10 000 allocator calls). Function calls (toString, substring, left, right, toUpper, toLower, replace, ...) no longer allocate for their arguments, and short string results stay inline (substring and toString over 10k rows: 70 000 and 80 000 -> 40 000 calls). A GQL query's steps now allocate per row as the equivalent Gremlin project() query does.

Added

  • Run administration for the dev server (EXPERIMENTAL, off by default; #32). graphersal --server --admin-runs [--admin-runs-token <SECRET>] lets the operator see every query that waits or runs, from every client (browser pages, MCP agents, the AI Chat), and stop any of them. GET /api/admin/runs lists each run's id, client, kind, state (queued or running), start time, duration and the first 200 characters of its text. POST /api/admin/runs/cancel {"id": n} cancels one, whatever its client, and rolls back its changes. With a token, every admin request must send X-Graphersal-Admin-Token. Without the flag both endpoints answer 404. While it is on, GET /api/info answers adminRuns: {tokenRequired} and the playground shows a Runs button with a live list and a Kill button per run. The MCP endpoint offers no tool for it. Both flags are also keys of the arguments file, and the start banner names the setting (Run administration).
  • graphersal-serve (EXPERIMENTAL, additive). A host turns the run administration on per graph with ContextBuilder::admin_runs(token) (Context::admin_runs_enabled). A graph served under a mount path lists and stops only its own runs. A host's own view across its graphs uses Runs::list and Runs::cancel_run, with the new RunEntry and RunState and the new RunKind::name and RunInfo::mount.
  • A store conversion can leave out the blobs it cannot find. ConvertOptions::with_skip_missing_blobs() makes Store::convert_with complete when a blob the store references (an embedding model's) is missing from the source store and from the fill source: the copy is made without it, never with a placeholder, and the new field ConvertReport::blobs_missing names each one. The copy is a store whose blob was lost, which is not damage: its model is listed as missing, an open is refused while the schema needs the model, and Store::restore_blobs_from fills the blob later. Everything else is still verified; the default stays strict. See Blobs.

Release 0.7.0

A minor release. Its main feature is layers (EXPERIMENTAL). A layer is a writable graph over a frozen base graph and stores only its own difference from that base. Several layers can share one base in a process. To a query a layer looks like any other graph. Three new functions say where an element comes from: layer(), has_layer() and g.layer_diff(). A layer can be saved as a layer snapshot (file format version 5) or kept durably in a layer store. From the command line it runs with --layer and --layer-store, and the playground marks what a layer added or modified.

The servers get the pieces a host needs to serve many graphs from one process. graphersal-serve can launch any source into a session, mount it under a URL prefix and switch it to read-only at run time. graphersal-mcp gets a directory mode: one endpoint over many graphs. The playground gets a server mode, and it now recognizes a Graphersal host by a protocol marker. Stores get Store::convert_with, which fills missing blobs while converting, and hosts can declare their own system journal event kinds (#35).

The public API of graphersal is unchanged apart from additions (cargo semver-checks reports no break against 0.6.2). The breaking changes are in the EXPERIMENTAL crate graphersal-serve and in how the playground recognizes a host: read "Upgrading from 0.6.x" first. Plain stores, snapshots, journals and backups keep their format. Only layer snapshots and layer stores are new, and older releases refuse them.

Upgrading from 0.6.x

Stores and files. Stores, snapshots, journals and backups of 0.6.x open unchanged, with no upgrade step. Everything 0.7.0 writes for a plain graph is still file format version 4, so 0.6.x keeps reading it. As always, every release reads the formats of every release before it. The one new format is for layers:

  • A layer snapshot (a .gsnap of a layer, a snapshot inside a layer store) carries file format version 5 in its packed header, its manifest and its layer file. Graphersal 0.6.x and older refuse it as written by a newer version. They never load the layer's own elements as if they were a whole graph. The same holds for a layer store and its backups. To hand a layer's graph to an older release, export it whole: graphersal store materialize <layer store> whole.gsnap --base <base> (or Store::export_materialized) writes a plain format-4 snapshot that needs no base (format spec 7.5).

graphersal-serve (EXPERIMENTAL, breaking). These changes affect hosts built on the crate. The graphersal --server dev server behaves as before.

  • graphersal_serve::SERVER_ID is renamed to DEFAULT_SERVER_NAME (same value, "graphersal-dev"). Rename it where you use it. There is no alias.
  • GET /api/info answers "dev": false by default. Before, it was always true. A host that should show the playground's DEV SERVER badge calls ContextBuilder::dev(true), as the CLI's dev server does. ContextBuilder::server_name sets the server field, which is now only the host's name.
  • GET /api/info carries "protocol": "graphersal/1" (graphersal_serve::PROTOCOL). A host built on graphersal-serve sends it automatically.

Playground (breaking for hosts that answer /api/info themselves). The playground uses a server as its engine only when that server's /api/info answers "protocol": "graphersal/1". It no longer compares server with "graphersal-dev". A host that answers /api/info without graphersal-serve must add the field, or the playground falls back to its in-browser engine. The number changes only when the HTTP API breaks (an endpoint or field removed or renamed, or a meaning changed). Additions keep it.

Behaviour.

  • .profile() no longer shows [index: ..] or [count from index] when the storage declined the lookup and the source scanned instead. It shows , declined, scanned inside the index brackets, or [count from index declined]. A TraversalGraph never declines. A host storage or a layer can.
  • The dev server with --read-only disables the playground's editing (edit mode, the inspector's Edit and Delete, the element editor). Before, the playground offered edits and they then failed.

graphersal-session (internal, breaking). The public structs Node, Edge and CompactGraph of its display model gain the fields origin, vertex_origin and edge_origin (None on a graph without layers). Code that builds them with a struct literal adds the new fields.

For GraphStorage implementers (EXPERIMENTAL trait). The new trait methods vertex_layer, edge_layer, layer_diff and layer_summary have defaults: every element is "base" and the diff is empty. A wrapper storage that forwards to another storage should forward them too, so that a layer under it still reports its origins. The same goes for the new PersistentStorage methods load_base_patch and layer_parts. MemoryStats gains shared_bytes.

Layers (EXPERIMENTAL)

A layer is the storage LayeredGraph over a frozen Arc<TraversalGraph>. It stores only what it adds, and the base elements it modifies or removes. Every step, saved query, schema rule, GQL query and transaction runs on it as on a plain graph. The typical use is a product graph shared by many projects: each project gets a layer, and that layer costs about what the project adds or changes, not a copy of the product. How the storage works, its capabilities and its memory figures are on the developer page Layered Graphs.

  • Where an element comes from. These are new DSL functions, Graphersal extensions in snake case only:

    • layer() answers "base", "added" or "modified".
    • has_layer(origins...) keeps the elements with one of the named origins. An unknown origin is the new TraverserError::UnknownLayerOrigin, raised before the query runs.
    • g.layer_diff(#{kinds, labels, limit}) answers the whole difference against the base as one map: added, modified (each changed property as base/layer), removed and truncated.

    On a graph without layers, everything is "base" and the diff is empty, so one query runs on both kinds of graph. Rust: GraphTraversalSource::layer_diff(&LayerDiffRequest), and LayerOrigin, LayerDiff, LayerSummary in graphersal::storage. Python: Graph.layer_diff(kinds=, labels=, limit=).

  • Writes. A layer can add elements and edges that touch base vertices. It can write to base elements through copy-up images and drop base elements, which leave tombstones. It has its own schema and catalog (copied from the base when the layer is created), and its own units, savepoints, rollback, change capture, commit hooks and dry runs.

  • Property indexes and vector rules. A layer serves the base's property indexes for its own data, lookups and counts included, and enforces the base's unique indexes over base plus delta. It can create, drop and redefine indexes for itself. Vector rules keep the derived vectors in step, using the embedding models of the base (LayerBase). Compression rule and model definitions on a layer are refused for now.

  • Memory. g.memory_usage() on a layer reports its own footprint as total_bytes and the shared base beside it as shared_bytes. g.memory_report(#{scope: "delta"}) (MemoryReportScope::Delta) walks only the layer's added and modified elements. The REPL equivalent is /memory delta. On the large graph with 1 600 changed elements, a layer's own total was 475 KB beside a shared base of 51 MB.

  • Layer snapshots and layer stores. persist::read_layer_snapshot reads a layer snapshot back over its base. Store::<LayeredGraph>::create_layer and Store::open_layer keep a layer durable and recoverable on every backend. The base must be the same one (BaseRef: lineage, commit and time). Another base is refused with PersistError::LayerBaseMismatch. A plain open of a layer store is refused with StoreFailure::LayerStore. A layer store's base is a creation parameter, and every copy path keeps it: backups, restores, verify, views, checkpoints, fork, attic, rollback, convert, upgrade. A backup of a layer store is useless without its base, and graphersal store backup warns about this. A damaged layer store is not repaired; restore a backup of it instead. Store::export_materialized writes the whole graph the layer shows as a plain snapshot. A base loads from a read-only Store or a .gsnap with its embedding models: LayerBase::from_store_read_only and LayerBase::from_snapshot_file.

  • CLI. graphersal --graph <base> --layer runs the one-shot runner, the REPL or the dev server on an empty layer kept in memory. --layer-store <dir> runs it on a layer store instead (--create-store creates the store). The base is a Store opened read-only without its lock, or a .gsnap. The graphersal store commands that load a layer take --base <SOURCE> (verify, checkpoint, fork, rollback, attic restore|remove|fork). The new graphersal store materialize writes the whole graph as a standalone .gsnap, and store info names the base (Layers).

  • Dev server, MCP and playground. /api/info describes the layer, and POST /api/layer/diff answers the diff. MCP graph_info shows a layer block, and the initialize instructions name the three functions (on a layer only). The playground shows a layer badge with the change counts, draws added and modified elements with their own outlines in colour-blind-safe colours, and adds a Layer changes dialog and a shared-base track in the memory bar. The browser playground can start a layer over a loaded graph (Store ▸ Start a layer over this graph) and drop it again. The UI profile key layerDiff turns these on or off.

  • Serving many layers. MCP session route tags (Host::session_route, ContextBuilder::mcp_session_route) pin an MCP session to the graph resolved at initialize. The book page Serving Layers describes how a host serves many customers' layers over shared product versions behind one endpoint.

Hosting pieces for multi-graph servers (EXPERIMENTAL)

These additions to graphersal-serve and graphersal-mcp let one process serve many graphs. Their single-graph behaviour is unchanged, as is the dev server's output.

  • Launch a source. graphersal_serve::launch launches a ServedSource (a sample, a file, a Store, a layer store or a host graph) into a session and returns a pre-filled ContextBuilder. open_store, open_layer_store and layer_base_of_store return their open notes as data (OpenNote). New error: ServeError::Open. The CLI's dev server launches through it.
  • Read-only at run time. With ContextBuilder::runtime_read_only, a host can switch a served graph read-only and back without reopening it: Context::set_read_only, Context::is_read_only. Writes from the HTTP API, MCP and jobs are refused, and scheduled jobs pause. /api/changes gains readOnly, and /api/info's readOnly follows the switch.
  • Mount under a URL prefix. ContextBuilder::mount_path adds mountPath to /api/info and prefixes the openapi and MCP endpoint paths. HostCheck::with_hint puts the host's own advice into its 403 answers. Request::copy_body_to streams an upload into a host sink.
  • MCP directory mode. Mcp::handle_directory serves one endpoint over a host's GraphDirectory: the tools list_graphs and use_graph, plus an optional graph argument on every data tool. Mcp::with_max_sessions sizes the session table, and Mcp::with_endpoint sets the status path.
  • Protocol marker. Every /api/info answers protocol: "graphersal/1". The ContextBuilder::server_name and ContextBuilder::dev settings are described under "Upgrading from 0.6.x".

Playground

  • Server mode. Under a mount (/db/<name>/) the playground keeps its tabs, history and layout separately for each mount. Keys at the root are unchanged, and the theme is shared. The header shows the database name, linked to the host's home from /api/info. A read-only badge follows /api/changes live, and the MCP endpoint comes from /api/info.
  • UI profiles (EXPERIMENTAL): any host can now deliver a profile, not only the dev server. The new optional key styles lists the profile's own style sheets, and a profile's modules read the host's raw /api/info as api.info.host (UI profiles).

Stores and the system journal

  • Convert a store and fill its missing blobs. Store::convert_with(from, to, ConvertOptions) with ConvertOptions::with_fill_missing_blobs(BlobSource) fills every blob the copy references but the store lacks, or holds damaged. The blob source can be a shared models directory, another store, a backup, a ZIP backup or a .gsnap. Each filled blob is checked by length, CRC-32C and hash, and only the copy changes. A blob that is still missing is StoreFailure::BlobUnavailable; one with other bytes is BlobDamaged. Either way the copy is undone. ConvertReport lists the filled blobs. CLI: graphersal store convert --fill-blobs <SOURCE>. Store::convert is unchanged (Blobs).
  • Host events in the system journal (#35). A host built on the engine declares its own event kinds with system_journal::declare(HostEventKind), under its own first code segment, and records them with SystemJournal::record(HostEvent). They go through the same collapsing, sinks and listings as the engine's events. system_journal::declared_kinds() lists the declared kinds. New errors: JournalError::InvalidDeclaration, Undeclared and InvalidEvent. The record layout is unchanged (Host events).

Fixed

  • .profile() showed an index lookup or a count from an index when the storage had declined it at run time and the source had scanned. It now shows that the lookup was declined (see "Behaviour" above).

Release 0.6.2

A patch release of the 0.6 line for the playground and the dev server: UI profiles (EXPERIMENTAL) let one playground code base serve several pages, each with its own tabs, cards, graph views and top-bar module, and the dev server's hosting core gains an allow-list mode that offers a page nothing but selected saved queries. The engine (graphersal) is unchanged: no format change, no API change; stores, snapshots, journals and backups of 0.6.0 and 0.6.1 are read and written exactly as before.

Playground: UI profiles (EXPERIMENTAL)

A UI profile says what a playground page shows. The playground as before is the built-in profile full, and it stays the default; demo is a small built-in profile for tests and smoke checks. A profile names its title, its tabs (the built-in workspace or ES modules of its own), its start tab and what the user can reach (can).

  • Profile API. A profile's own tabs get an api object: query (a saved query), markdown, card, graph, mergeGraph, toast, navigate, theme and info. A tab that fails to load shows an error card; an invalid profile is shown as an error naming every problem, never replaced by another profile.
  • Delivery. The dev server takes --ui-profile <NAME|FILE> (a built-in name or a JSON file; GET /api/info names it as uiProfile); the browser playground takes #/play?profile=<built-in>.
  • Cards. Card templates per label (cards: {<label>: template}) with title, subtitle, badges, Markdown body, fields and action buttons, rendered by api.card(label, row, options).
  • Graph views. api.graph draws a module's {nodes, edges} with the Graph panel's renderers, styled per label by the profile key graph; api.mergeGraph merges expanded neighbours without duplicates and keeps the positions already drawn. The full profile's Graph panel draws exactly as before.
  • Top-bar module and version. header: {module} puts a module of the profile into the top bar on every tab; the optional key version shows the product's version there, the engine's version moves into the tooltip.
  • Request headers of a host (EXPERIMENTAL). A host page can set window.GRAPHERSAL_ENGINE = {headers} (for example Authorization) before the playground's modules run; the HTTP engine sends them with every request. Unused, every request is as before.
  • Subresource integrity everywhere. Mermaid now loads from cdnjs's single-file build with its SRI hash, like every other CDN file (a test checks that each has one).

Dev server

  • POST /api/query {name, params?, runId?} runs one saved query with named arguments and answers every result ({ok, results, mutated, changes}), in every mode; the playground's engines (runSavedQuery) and the profile API's query use it. openapi.json and the HTTP API table describe it.
  • Allow-list mode (EXPERIMENTAL, for hosts built on graphersal-serve; the graphersal CLI never turns it on): ContextBuilder::api_allow_list(selection, policy) makes the server answer only GET /api/info (apiMode: "allow-list"), GET /api/changes and POST /api/query for the selected saved queries, each run under the access policy; every other /api/ route, the host's extra routes and /mcp answer 403. The playground refuses to show a profile with the built-in workspace on such a server.
  • The MCP usage dialog of the playground is wider and fits its tables without horizontal scrolling.

Internal crates

graphersal-session, graphersal-mcp and graphersal-serve are internal (the last two EXPERIMENTAL) and may change in any release; their changes in 0.6.2 are additive:

  • graphersal-session: Session::run_saved_query, queries::SavedQuerySelection (folders with their subfolders, names, excluded names) and authorizer_for(read_only, policy), moved here from graphersal-mcp, which now uses them (its saved-query tool selection is unchanged).
  • graphersal-serve: ContextBuilder::ui_profile, ContextBuilder::api_allow_list, Context::is_allow_list and the route POST /api/query.
  • graphersal-wasm (not published): runSavedQuery.

Upgrading from 0.6.1

A drop-in replacement: no format change, no API change of graphersal, no upgrade step. Stores, snapshots, journals and backups of 0.6.0, 0.6.1 and 0.6.2 are interchangeable. A crate that pins graphersal-mcp, graphersal-serve or graphersal-storage-tests to the exact version moves the pin to =0.6.2.

Release 0.6.1

A patch release of the 0.6 line that fixes a crash of the playground session and the dev server on scripts holding a multi-byte character. It changes no format and no API; stores, snapshots and journals of 0.6.0 are read and written exactly as before.

Fixed

  • A multi-byte character before a script's last call no longer crashes the session. To show the result of the last call, the session looks for the terminal call of a script by searching back from its last (. It cut the script one byte after the character it stopped at, which fell inside that character when it was not ASCII: a script with, for example, Cyrillic text in a string literal and an unbalanced parenthesis after it made the session thread panic. The playground's engine and the dev server (with its MCP tools) both run this session, so such a query failed with an internal error instead of its result. The search now steps over whole characters.
  • The REPL's command completion no longer panics on a multi-byte space. The same pattern in the completion of / commands cut a line holding, for example, a no-break space (U+00A0) inside that character.

Dependencies

  • rustix 1.1.5 -> 1.1.6 in the lock file of the binaries (RUSTSEC-2026-0486, unsound extended-attribute functions; Graphersal does not call them, it reaches rustix through fd-lock).

Upgrading from 0.6.0

A drop-in replacement: no format change, no API change, no upgrade step. Stores, snapshots, journals and backups of 0.6.0 and 0.6.1 are interchangeable.

Release 0.6.0

A minor release. Property indexes grow up: label-less indexes, indexes over array elements (each), unique indexes, exact index reads and counts from an index, on a layout that takes a fraction of the memory. The graph itself takes less memory (smaller id and label indexes, nested objects stored as shapes, dedup for every value type, a smaller embedding model in memory). The servers get their own building blocks: the MCP endpoint becomes the crate graphersal-mcp (shorter tool descriptions, a compact schema summary, MCP over a byte stream, per-connection profiles) and the dev server's hosting core the new crate graphersal-serve; read-only serving gets a reader pool. A series of store, dev-server and playground fixes lands as well.

It changes some public types (property index labels, transforms, advisor actions) and what the MCP tool get_schema answers by default: read "Upgrading from 0.5.2" first. Snapshot and journal formats are unchanged and no store needs an upgrade step; a store that uses one of the new index forms opens read-only in 0.5.x, and one with a dedup rule of min_bytes: 0 is reported as damaged by 0.5.2 and older.

Upgrading from 0.5.2

Stores. Stores, snapshots, journals and backups of 0.5.x open unchanged, with no upgrade step. What 0.6.0 writes can stop an older version from using a store:

  • A new catalog kind 6 property_index_ext (DefinitionKind::PROPERTY_INDEX_EXT, CRITICAL) holds the new index forms (label-less, each, unique); once a store has one, Graphersal 0.5.x opens it read-only. Plain per-label indexes stay kind 2. Index names are one namespace across both kinds.
  • A dedup compression rule with min_bytes: 0 (the extended dedup, below) makes Graphersal 0.5.2 and older report the store as damaged. There is no format marker for it: users upgrade, older versions need not open newer stores.

Rust API (breaking).

  • PropertyIndexDefinition::label() returns Option<&str>; PropertyIndexInfo.label is Option<String> and PropertyIndexInfo::new takes Option<&str>.
  • GraphStorage::vertices_by_property_index, edges_by_property_index, vertices_by_transformed_property_index and edges_by_transformed_property_index take label: Option<&str> (None = the label-less index).
  • RecommendedAction::CreateIndex.label and Recommendation.label are Option<String>; the advice JSON and the memory report's index JSON show "label": null for a label-less index.
  • The struct variants of RecommendedAction (CreateIndex, DropIndex, AddCompression, DropCompression) are #[non_exhaustive]: patterns outside the crate need .., and the variants cannot be built outside it. RecommendedAction::CreateIndex gains transform.
  • PropertyIndexTransform gains Each and Chain, and PropertyIndexTransform::KNOWN_NAMES holds two names. A transform chain is an array in the payload, the session JSON, the DSL and Python. Indexes with each are kind 6 even with a label.
  • StoreFailure gained FilesInUse in the middle of its variants: code that casts the enum to a number sees shifted discriminants.
  • The Rust from/to of add_e take impl Into<EndpointArgs> instead of impl Into<ArgStrings> (neither type is nameable outside the crate; every argument type that compiled still does, see "Fixed").
  • graphersal-session (internal): Session::set_cancel_reset_by_host is removed; every cancellable run of the dev server has a token of its own.

Behaviour.

  • create_index without a label no longer fails: it creates a label-less index.
  • The MCP tools get_schema and infer_schema answer a compact text summary by default, without the stored schema's descriptions. A client that parses the default answer as JSON must pass format: "json"; one that needs the descriptions passes descriptions: true or reads the resource graphersal://schema-summary.
  • The MCP tool descriptions are the short ones (the long texts of 0.5.2 are gone), and a saved query offered as a tool (--mcp-query-tools) lists the paging parameters offset, max_rows and max_items only with saved_query_tools.paging_params: true in --mcp-config; a call may still pass them.
  • graphersal store repair reports all data kept instead of nothing lost. Scripts that matched nothing lost should check the exit code instead (0: no data lost) or match ok: all data kept.

Property indexes

  • Property indexes take far less memory. Each indexed value is held once with its elements as compact slot lists: a low-cardinality index drops from about 48 to about 4 bytes per entry (field graph: an edge _owner index 28.2 -> 2.4 MB; a synthetic 1M-entry index over 500 values 48 -> 4 MB); building one is 2-8x faster, lookups and maintenance equal or faster. Near-unique keys cost as before. No API or format change.
  • Label-less property indexes. g.create_index(#{key: "name"}) (no label) indexes every vertex (or, with element: "edge", every edge) whatever its labels, unlabeled ones included. g.v().has("name", x) and g.e().has("_owner", o) without a label now read it instead of scanning (field graph: an edge owner lookup 46 ms -> 0.09 ms); a labelled source reads it when it is cheaper than its per-label indexes and checks the labels. .profile() shows [index: vertex name, any label]. GQL MATCH (n {name: $x}) uses it too. Rust PropertyIndexDefinition::label_less, Python graph.create_index(None, "name"), session/HTTP with label absent or null, MCP create_index without label, playground "any label" (Property Indexes).
  • Array indexes: the each transform. g.create_index(#{key: "_owners", transform: "each"}) holds one entry per array element, so g.v().has("_owners", __.unfold().is(o)) reads the index (field graph: 105 ms -> 5-13 ms); transform: ["each", "to_lower"] serves __.unfold().to_lower().is(..). A whole-value has(k, x) can use it too (the value is re-checked). .profile() shows [index: vertex _owners each, any label]. New PropertyIndexTransform::Each/Chain and PropertyIndexTransformChain; the advisor recommends each for keys holding arrays.
  • Unique indexes. g.create_index(#{label: "User", key: "email", unique: true}) refuses a write that would give a second element the same value (per label; label-less = over all vertices or edges; with transform: "to_lower" case-insensitive). The check is immediate at each write, so swapping two values needs an intermediate one; null and values the index does not hold are outside uniqueness. Creating one over existing duplicates is refused with up to 10 of them and a query listing all. A store holding duplicates under a unique index (written by an older version) still opens: the index is not served, listed with the reason, and the journal records index.unique_duplicates. New GraphError::UniqueViolation, DefinitionError::UniqueIndexDuplicates, GraphStorage::unique_index_duplicates; Python unique=True; playground checkbox. Overhead: +1.5-4 % per insert over a plain index.
  • Exact index reads skip the re-check. In a reading query, a condition a property index answers exactly (a string, boolean, uuid or temporal value, P.eq or P.within; whole-value, each under __.unfold().is(..), to_lower and ["each","to_lower"] while the index skipped nothing) is no longer re-checked on each candidate: the has step leaves the plan, and count() over one such point is answered from the index. Field graph: an owner lookup .id() 21-27 ms -> 1-2 ms, .count() -> microseconds. .profile() shows , exact in the index marker. Results are unchanged; writing queries, numbers, ranges and supersets keep the re-check. New StorageCapabilities::exact_property_index_lookups (EXPERIMENTAL trait; a host storage claims it only when its lookups return exactly the matching elements); &G and a shared Arc<TraversalGraph> forward it.
  • Counts from an index. g.v().has(k, "x").count() served by an exact index (label-less, or the single label's) is answered from the index without visiting elements; .profile() shows [count from index]. New trait method GraphStorage::count_by_property_index (default Ok(None)).
  • Advisor: recommends label-less indexes for scans without one label and hints when a key is indexed both per label and label-less. help() of a timed-out unlabeled filter names g.create_index(#{key: ..}).
  • Fixed: a to_lower index no longer answers has(k, __.to_lower().is(P.eq(()))) (null) with no rows where the scan finds them.

Memory

  • Smaller id and label indexes. The label index keeps handles plus one position per slot, the id index a slot and a hash: on a 534k-vertex / 2.3M-edge graph 157 -> 81 MB, the whole graph 1.82 -> 1.64 GB.
  • Nested objects are stored as shapes, also straight from a snapshot load, like top-level maps.
  • Embedding models take less memory: a compact tokenizer (931 -> 514 MiB for the same vectors), streaming model load, bounded slot growth after a load (no doubling at the first insert) (#24).
  • The memory report attributes the whole process memory (graph, models, script engine, Stores, session, MCP, AI Chat); the playground and the REPL show a process memory bar.
  • The memory report needs less transient memory: its per-row distinct-string sketch stays a small exact list up to 32 distinct texts (--graph large: peak 478 -> 408 MB); distinct counts up to 32 are exact.

Compression rules

  • dedup codes top-level values of every type, with an advisor pass for repeated values; compression rules are applied in bulk (one unit, one commit, one walk), several advisor recommendations at once, and a snapshot load codes rows straight into the dictionaries (Compressed Properties).
  • g.drop_compressions([names]): several rules dropped in one commit and one walk over the data, like g.define_compressions. Also GraphStorage::remove_definitions (with a default), GraphTraversalSource::remove_definitions, AnyGraph::remove_definitions, POST /api/compression/drop-many, Python graph.drop_compressions(names).
  • Catalog ▸ Compression in the playground handles many rules. The table no longer scrolls sideways, sorts by any column and groups the rules by codec or label with each group's total; a checkbox per rule and group and Drop selected drop them in one commit.
  • Advice to write a snapshot after changing compression rules. Until a snapshot holds them, every open re-encodes their labels, with a higher memory peak (74 rules: 2.2-2.9 GiB against 2.0 GiB). The Optimize panel shows a note with Write a snapshot now; the book pages Optimize, Compressed Properties and the FAQ say so.
  • A store whose compression rules are only in the WAL opens much faster. An open walked the data once per rule, then once more per rule at its end. Now rule changes in a row, even over many commits, take one walk, and a dictionary just filled by it is not rebuilt: 74 dedup rules on a real graph of 2.8 million elements opened in 8.5-10.5 s instead of 26.7-28.7 s, about as fast as from a snapshot. A repair walks the same way, TraversalGraph::replay once per change set, and apply_change_set once per run of rule changes; a mix of drops and new rules in apply_recommendations takes two walks. Dictionaries that grew are rebuilt in one walk as well, also at the end of a commit and in shrink_to_fit. New PersistentStorage::begin_replay/finish_replay (defaults: nothing): between them PersistentStorage::replay walks once over the rule changes of many change sets.

MCP and the servers

  • The MCP endpoint is its own crate, graphersal-mcp (internal, EXPERIMENTAL), configured with the new --mcp-config file; graphersal mcp-cost shows what a configuration costs in context, and the resource graphersal://gql-reference (the whole GQL subset) is listed by default (Dev Server and MCP).
  • One set of short tool descriptions. About 6.7K tokens of context read-write and 4.6K read-only (12.6K / 10.0K before). In A/B tests with Claude Code and Sonnet on 48 read and write tasks the accuracy was the same, with a third of the failed calls and 19-27K fewer input tokens per task. The gql text names element_id(n), labels/type, anchoring of variable-length patterns and, on writable servers, the write clauses; the query text the write steps and that a traversal before the last statement needs a terminal; the AI Chat prompt carries the GQL reference. Saved-query tools use the query's own description and list paging parameters only with saved_query_tools.paging_params: true. --mcp-config accepts "descriptions": "short" (it changes nothing) and refuses any other style.
  • Schema summary. get_schema and infer_schema answer a compact text map of the graph by default: labels with counts, keys with types and how often they occur, edge from->to label pairs, indexes and the schema mode (field graph: 24k chars, where the JSON did not fit the answer limit at all). labels details some labels; format: "json" returns the JSON as before. A/B with Sonnet on 16 schema tasks: 48/48 correct vs 46/48 with the JSON, half the calls and half the time. Resources mirror it: graphersal://schema-summary (text, new) and graphersal://schema (JSON), both listed by default. Rust GraphTraversalSource::schema_summary / AnyGraph::schema_summary with graphersal::schema::{SchemaSummary, SchemaSummaryRequest}; REPL /schema [label ...]; the AI Chat prompt carries the summary.
  • The schema summary leaves out the stored schema's descriptions by default (#34): 24,182 -> 15,459 characters on a real knowledge graph (-36 %). descriptions: true or the resource graphersal://schema-summary give the full summary. A/B on 16 schema tasks: billed cost -13 %, input tokens -9 %, accuracy within noise (46/48 vs 48/48).
  • MCP over a byte stream. Besides HTTP, graphersal-mcp serves MCP over any reader and writer: Connection (one MCP session with its own host) and serve_lines (the MCP stdio framing, newline-delimited JSON-RPC). On stream connections the server sends notifications/tools/list_changed (when saved queries are tools) and notifications/progress heartbeats for tool calls that carry a progressToken; Mcp::check_tools_changed lets a host trigger the notice. Cancellation works the same over HTTP and streams. The dev server's HTTP MCP endpoint is unchanged (no SSE).
  • Per-connection profiles. A Profile (an McpConfig, read-only, an optional AccessPolicy the engine enforces, an answer limit) is chosen by the host for each connection; the session's writing tools follow the policy too. A host per connection, and an identity carried to the session jobs (ClientRef::identity).
  • Bound saved-query parameters. Profile::with_bound_params lets a host fix saved-query parameters per connection or HTTP request (for example the project it serves): a bound parameter disappears from the saved-query tools' input schemas, and every call of a saved query that declares it runs with the bound value, whatever the client sent.
  • Two new --mcp-config keys. saved_query_tools.write_note ("default", "none" or your own text with {effects}) sets the note at the end of a writing saved query's tool description; server_title sets serverInfo.title in initialize (until now always "Graphersal dev server").
  • A served graph shuts down cleanly. graphersal_serve::start_job_ticker returns a JobTicker (stop()), neither the ticker nor the job workers keep the context alive, and Context::background_runs() reports scheduled-job runs still in progress; Context::call and call_fallible return ServeError (HTTP answers unchanged).
  • Read-only serving has a reader pool: stateless MCP session ids, per-client limits, parallel readers (Read-only serving mode).
  • MCP usage statistics in memory: /api/mcp/stats, a playground dialog and the opt-in tool usage_statistics.
  • A self-contained knowledge-base image from prebuilt binaries, and --allowed-host.
  • New crate graphersal-serve (internal, EXPERIMENTAL): the hosting core of the dev server (session thread and job queue, job workers, the run registry, the playground HTTP API as an HTTP-library-free boundary, Host/Origin/loopback checks, the embedded UI behind the feature ui-assets, the graphersal-mcp glue behind the feature mcp; no default features). graphersal --server behaves as before (flags, HTTP API, MCP endpoint). Its extension points: a graph resolver (default: one graph), a run observer with a cancel handle, a request filter (it runs after the always-on Host/Origin checks), extra routes for unknown /api/ paths, lifecycle and activity hooks, an executor policy (JobQueue), one MCP endpoint shared by several contexts with a profile per context (Context::mcp_connection), and the request filter's identity reaching MCP runs. A Server type answers the health probes and the loading/stopping 503s before the graph is loaded.
  • graphersal-mcp and graphersal-serve have no stability guarantees during 0.x: a dependent pins their exact versions (Releases and Versioning). Their errors follow the crate rule for shared state: serve_lines returns Result<(), McpError>, Context::mcp_connection and the run registry's methods return Result, and a session's setup error keeps the host's error as its source (ServeError::Setup).
  • A panicking session job of the dev server is logged through tracing (target graphersal::server) instead of a warning: line on stderr; an unreadable store space usage answers 500 instead of ending the server, and a refused job-ticker time zone is an error. --ui-dir is documented as an overlay over the embedded UI (only the files to override).

Dev server and playground

  • A running scheduled job no longer holds up the dev server (#26). Requests are answered while a backup, a checkpoint or a reading query job runs; GET /api/jobs says running, and the jobs dialog shows a running badge. While a user's job runs, Store-menu operations on the files answer 409. New in graphersal::jobs: Scheduler::start_due/start_now/finish/running/ set_time_zone, JobRun, JobFinished, Job::with_group, JobInfo::running, JobError::Running.
  • The Scheduled jobs dialog lists one wrapping block per job instead of a table that scrolled sideways. The AI Chat shows a thinking timer, and its Markdown export holds the answers only.

Fixed

  • A Stop hits the right query (#30, #31). A shared, reused cancel token lost a cancel or stopped the wrong work: on the read-write server a Stop before a query reached the session thread was reset by the query (or stopped another page's work), and the drain of the read-only serving mode cancelled worker tokens that an AI Chat query does not check. Every query, layout slice, MCP query and AI Chat tool call now registers a token of its own under its client: a Stop cancels the page's run (or all its runs), MCP notifications/cancelled the client's own request, the graceful stop every run, never another client's run. Store views and rollbacks wait for running queries instead of cancelling them.

  • Read-only serving: a Stop just before a query starts is no longer lost (#29). POST /api/cancel answered cancelled: true and the query still ran to the end; a graceful stop past its drain timeout had the same gap.

  • A backup or a verification beside a rollback no longer freezes an undamaged store (#27). They wait while a rollback or an attic change moves files; a rollback, attic restore or attic remove is refused with the new cause StoreFailure::FilesInUse while files are being read.

  • A fork or a packed export beside a rollback no longer fails with an I/O error or calls a manifest corrupt (#28). Store::fork, Store::attic_fork and Store::export_packed hold the same pin as a backup: they wait while files move; while they run, a rollback, an attic restore or remove (FilesInUse) and a prune (BackupRunning) are refused, a slow export writer included.

  • Playground: "Download current state (.gsnap)" no longer drops embedding models silently (#23). It asks, with the models' sizes; GET /api/export?format=gsnap carries them unless &models=without.

  • Saving a graph no longer loses its embedding models. g.export_snapshot, AnyGraph::write_snapshot, Python graph.save and the dev server's "Save to file" carry the models the graph serves; before, "Save to file" over a --graph x.gsnap destroyed them in the file. These writes replace the file only when finished, so the path may be the file the graph was loaded from. New: AnyGraph::write_snapshot_with, persist::write_graph_snapshot, SnapshotInfo::blobs_not_carried.

  • A snapshot that reuses segment files of an older snapshot downloads with its models. A checkpoint references the unchanged segment files of an earlier snapshot instead of copying them. Exporting such a snapshot WITH the store's embedding models failed with I/O error while reading a snapshot segment: No such file or directory, while the same snapshot exported without models, and snapshots that hold all their files, worked. This hit the Store menu's download (the dev server answered 404), graphersal store export without --without-models, Python Store.export_packed and Store::export_packed(_with) in Rust. Nothing in the store was wrong, and no broken .gsnap was ever written: the export stopped before its first byte. Backups (directory, increment, ZIP), forks and repairs were not affected. The dev server now answers a failed download with 404 only when the snapshot does not exist, 422 when the store refuses it (damage, a missing or damaged model) and 500 when a file cannot be read.

  • addE().from(v) / .to(v) take a vertex (TinkerPop's from(Vertex)/to(Vertex)). In Rhai and Python a vertex value (a next() result, a Python Vertex parameter, an edge's out_v/in_v) failed with "expected vertex or vertex id, got null"; in Rust a vertex was read as a name, so a step label or side-effect key equal to its id won, and an edge value connected the vertex of the edge's id. Now a vertex is that vertex by its id; an edge value is an error. Rust: from/to take impl Into<EndpointArgs> instead of impl Into<ArgStrings> (neither type is nameable outside the crate; every argument type that compiled still does, plus VertexValue, &VertexRef and Vec<ElementProperty>).

  • An upgraded store whose newest WAL segment holds only a checkpoint record opens and takes commits again. A checkpoint taken while a store is open starts a new WAL segment named by the next commit and writes its checkpoint record there (a mark set afterwards adds its record too). After graphersal store upgrade of a store of format version 3 (Graphersal 0.2.x to 0.4.x) that segment is of the older file format, and the first write after the upgrade refused the whole store as damaged: Corrupt …/wal/<N>.wal at byte 64: it starts at commit N, which is not committed yet. This hit:

    • opening the upgraded store;
    • a commit to the closed store, such as graphersal embed-model import <repo> --into <store>, which an upgraded store needs when its schema names a model it does not keep yet (0.4.x served such models through --embedder);
    • the upgrade of a 0.4.x store with models under models/: its migration commit failed, and an in-place upgrade left the store half converted (GRAPH already in the new version, the INTENT and models/ still there), so neither an open nor a second upgrade worked.

    Nothing was lost: store verify found no damage, and store repair built a complete copy. Now such a segment is rewritten in the current format with its checkpoint and mark records kept, and the commit follows them. A store that is already stuck needs no manual step: with this release the open, the import or the repeated store upgrade --in-place completes. A store repaired with 0.5.x as a workaround is a complete store as well; only its history before the repaired commit and its marks stayed in the original (Store Format Versions, format spec 15.1).

  • store repair says what a repair never carries. A repair writes the readable state as one snapshot of a new store; the commits before it (rollback, views of past states, the attic), the marks and the store id stay in the store it was built from. The report used to say nothing lost right next to mark not carried. It now reads all data kept and names the rest in one line, also when no data is lost:

    Repaired store repaired/ at commit 3 (graph …): all data kept
      mark not carried: before-import @ commit 1
      not carried: the history before commit 3, 1 mark and the store id (backups start anew); the store it was built from keeps them
    
    ok: all data kept
      not carried: the history before commit 3, 1 mark and the store id (backups start anew)
      kept in: damaged/ (keep it while you need them)
    

    The damage report of store verify and of a store in maintenance mode says a repair keeps all data instead of a repair loses nothing, and so does the playground's Store menu. In Rust RepairReport::not_carried() returns the same words, in Python the report of Store.repair_to() has them under the new key "not_carried". The exit codes do not change (Damage, Maintenance and Repair).

  • graphersal embed-model import printed a library error with a doubled headline (Error: Error: …); it now has one Error: like every other command.

  • Playground: closing the Store menu with its button no longer reloads it (#25).

Release 0.5.2

A patch release of the 0.5 line. Three fixes come from a benchmark against another in-memory graph database on graphs of up to 5 million vertices and 10 million edges: whole-pattern counts in GQL, membership tests against side effects, and the spare memory a graph built by write queries keeps. The release also adds the GQL operator =~ and gives every note of the command line tool one readable layout. It changes no format; stores, snapshots and journals of 0.5.0 and 0.5.1 are read and written exactly as before. The new API items are additive.

Added

  • shrink_to_fit() releases the spare capacity of a graph built by write queries (#22). A graph grows its vertex and edge slots by doubling; after a bulk load by queries up to half of them can stay unused (on 5M vertices and 10M edges built with GQL CREATE: 1.24 GB of 5.0 GB). Every load of a file already ended compact; now a graph in memory can be made compact too: g.shrink_to_fit() in the DSL, graph.shrink_to_fit() in Python, Graph::shrink_to_fit() / AnyGraph::shrink_to_fit() in Rust (ShrinkReport in the storage module). It reports the memory before and after, writes no commit and keeps every handle valid; call it once after a bulk load, not after every batch. It asks for Update on the data (Permissions), so a read-only policy refuses it (Memory Inspection and Profiling).
  • GQL: the regular-expression match s =~ pattern, Cypher's operator as a compatibility form: it matches the whole string, in the dialect of the Rust regex crate; a NULL or non-string operand gives NULL, an invalid literal pattern is refused before the query runs, and n.key =~ 'literal' is answered with has(key, TextP.regex(..)) (GQL aliases).

Changed

  • GQL counts over a whole pattern are answered from the statistics (#20). MATCH (n) RETURN count(n), MATCH (n:Label) ..., MATCH ()-[r]->() RETURN count(r), MATCH ()-[r:TYPE]->() ... and their count(*) forms now get the plans of g.v().count() / g.e().count(): on 10M edges the edge count takes 0.03 ms instead of 1.3 s, and it no longer fails the default 1 GiB per-query memory limit. Every other count(x) of a variable that can never be NULL no longer records the variable for each row, so counts over larger patterns need less memory. Results do not change (GQL plans). An edge count now reads edges only, as g.e().count() does: a policy that denies reading vertices but allows edges allows it.
  • within / without against a side effect or a long list are hash lookups (#21). where(P.without("x")) against an aggregate("x") or store("x") of 16 or more members, and has / is / has_value with a literal within / without list of 16 or more values, no longer compare against every member for every traverser. The usual breadth-first search with a visited set, aggregate("x").repeat(__.both().where(P.without("x")).aggregate("x")), was quadratic: on 100 000 vertices and 1M edges it now takes 0.7 s, where 0.5.1 did not finish in 10 minutes. The comparison itself is unchanged (a hash only proposes candidates), so results do not change; one edge case: when reading a member fails, its error now surfaces only if no other member matches.
  • Every note of the command line tool has one layout (#19): the notes of an upgrade, a .gsnap load, a model import, the store refusals, the store, embed-model and start outputs, the error helps that name commands and the journal's recommendations are a short headline, one indented key: value per line and each shell command on a line of its own under a # comment. graphersal store models, store attic list and embed-model list show one section per entry.

Fixed

  • graphersal store info counts the blobs in use and the unused ones apart; before, the row read as if a model's blob were about to be removed by the next prune (#19).

Upgrading from 0.5.1

A drop-in replacement: no format change, no upgrade step, only additive API. Stores, snapshots, journals and backups of 0.5.0, 0.5.1 and 0.5.2 are interchangeable.

Release 0.5.1

A patch release of the 0.5 line that fixes a performance regression of 0.5.0. It concerns scripts, saved-query calls and transactions that run many writing traversals in one unit after the graph has shrunk or grown a lot in it, such as a loader that drops most of a graph and writes it again: in 0.5.0 each of these traversals walked the whole graph. A real loader of that kind took 618 s with 0.5.0 and takes about 33 s with 0.5.1. The release also documents what the estimated memory measure reports inside such a unit (see "Fixed"). It changes no format and no API; stores, snapshots and journals of 0.5.0 are read and written exactly as before.

Fixed

  • Writing traversals no longer walk the whole graph one after the other inside a script or transaction. 0.5.0 measured what a writing traversal adds to the graph (for the per-execution limit and the process memory ceiling, Resource Limits) from the graph's average element size, and took that average from a full walk of the graph's footprint whenever the last walked figure was out of date: before the first walk, or once the element count had doubled or halved since it. Inside a unit that already holds changes (a script run as one unit, every saved-query call, a transaction) such a walk is not cached, so every following writing traversal of the unit walked the graph again: time proportional to the graph per traversal. A loader that dropped most of a 250 000-element graph and then ran some 200 000 single merge_e(...) traversals in scripts of 300 took over ten minutes instead of under one. Now the tracked measure (the graphersal command line, the dev server, the playground, Python) never walks the graph for this, and the estimated measure (a library host without the tracking allocator) never walks the graph inside a unit that holds changes, also near the ceiling: it keeps the last walked figure, adjusted by the elements added or removed, until the unit ends; between units a stale figure is walked again at most once, and cached, as before. In the estimated mode the figure inside such a unit is therefore an extrapolation from the last walk and can be off after large changes in it; install the tracking allocator for exact figures (Resource Limits).

Upgrading from 0.5.0

A drop-in replacement: no format change, no API change, no upgrade step. Stores, snapshots, journals and backups of 0.5.0 and 0.5.1 are interchangeable.

Release 0.5.0

A minor release about models as data and memory that never runs out unannounced. A Store keeps its embedding models in its history, as blobs referenced by catalog definitions, so every position, copy and backup has exactly the models of its moment; vector rules in the schema keep vectors in step with their text; the process has a memory ceiling, on by default, so a query, load or write that would exhaust the memory fails and rolls back instead of the operating system killing the process. A system journal records what each instance did, all times of an instance come from one monotonic clock, and a commit of any size is written to the WAL in parts.

It is not a drop-in update: the store format changes (stores need graphersal store upgrade), the external embedders and embed_property are removed, and the memory limit moves from the execution options to the process. Read "Upgrading from 0.4" first; every removed or changed API, with its replacement, is in "Breaking changes in detail" at the end of this page.

Upgrading from 0.4

  • Stores need an upgrade. The store format version is now 4 (file format version 4). Graphersal 0.5.0 refuses a store of 0.1.x to 0.4.x as "older format" until graphersal store upgrade <dir> <new_dir> (or --in-place; Rust Store::upgrade, Store::upgrade_in_place; Python Store.upgrade) converts it, and 0.4.x refuses an upgraded store as newer. The upgrade checks every 0.4.0 model file before it writes anything, turns each model under models/ into a blob and defines them all in ONE commit; no default model is set (Format Versions and Upgrade).
  • What the upgrade tells you (CLI note:/warning: lines, UpgradeReport, Python report dict; the exit code is 0): models converted or renamed (a model without a repository becomes local/<12 hex>), models the schema needs but the store does not keep (0.4.0 served them through --embedder; import them, or the store does not open), vector properties without a rule with a ready schema patch adding "from", and saved queries calling the removed embed_property (never rewritten). The vector notes come as ONE note per model listing its properties with their counts and one combined patch (UpgradeReport::vector_notes, VectorWithoutRule::combined_schema_patch; a real 0.4.0 file went from 18 notes to one), and the saved queries that write a vector property directly (property("emb", ..) with a literal key) are listed too, one note each (UpgradeReport::saved_queries_writing_vectors): such a write fails once the rule exists, so remove it (queries are never rewritten; a computed key and merge_v/merge_e maps are not found). The .gsnap notes say the same.
  • Take a full backup after the upgrade. An upgraded backup directory stays a backup, but it no longer takes increments of the upgraded store (BackupRefused): back the upgraded store up into a new directory.
  • A 0.4.0 .gsnap loads as it is (--graph file.gsnap, GraphSource::from_file): its model rows are converted in memory, the file is not changed. To work on it durably, graphersal store create <dir> --from file.gsnap makes a store without opening it and prints the same report as the upgrade, also when the schema needs a model the file does not carry; import the model, then open the store.
  • Embedders come from the database only. The CLI flags --embedder/--default-embedder (and their args-file keys), the Python Embedder/Model2Vec classes and keywords and the Rust host registry are removed. Import a model once (graphersal embed-model import <repo> --into <store>, Store.import_model, Store::import_model); it then travels with the store (Embedding Models in a Store).
  • embed_property is removed: declare a vector rule instead ("from" beside embedder in the schema). Its first fill embeds every element of the label while the whole database is locked; the preview says how many and how long first (Vector Rules).
  • The memory ceiling is on by default. Unless the host sets it, it is the cgroup limit minus a headroom, else 80 % of the physical memory (3.5 GiB on wasm32). A query, import, load or store open that would take the process over it now FAILS (ResourceLimitExceeded or PersistError::MemoryBudget, naming the minimum ceiling that fits) where 0.4 went on. memory.limit is a process setting now: exec::set_memory_limit, CLI --memory-limit, Python graphersal.set_memory_limit; as a g.with() option, policy default or session preset it fails with InvalidOption (The process memory ceiling).
  • traversal.max_materialized_bytes means "held at once". The per-query limit now counts the live bytes one execution holds at the same time (freed memory is given back), no longer the size of one value; every profile reports the query's peak against it (Memory: materialized bytes and expansions). A query that built many medium values may now reach the default of 1 GiB: raise it per query, or for the CLI with --max-materialized-bytes, for Python with graph.set_limits(max_materialized_bytes=...).

Added

  • Models as data (Embedding Models in a Store): a model is ONE blob (a deterministic tar of its files, card, licence files and manifest) referenced by a catalog definition of kind 5. Importing, replacing, removing and choosing the default model are commits, so every position (commit, mark, view, rollback, backup) has the models of its moment. A model the current schema needs loads when the store opens, in every mode; a missing, damaged or too large one refuses the open with the commands that fix it. CLI embed-model import <repo|dir> --into <store> [--replace] [--default], embed-model download <repo> --into <store>, store models, store models default, store models remove; Rust Store::import_model/set_default_model/remove_model/ models and the closed-store forms import_model_dir/set_default_model_dir/ remove_model_dir; Python Store.import_model, Store.import_model_into, store.set_default_model; the playground's Store menu marks the default model. A store that holds models but has no default says so (CLI note, Python UserWarning, modelsNote of the dev server and playground).
  • Catalog commits on a closed store: a model import, removal or default change on a CLOSED store appends ONE commit without loading the graph (format spec 12.12); a replace whose old revision feeds vector rules opens the store and re-embeds, and says so.
  • A .gsnap without a Store serves its models: --graph file.gsnap, Python Graph.load, GraphSource::from_file and persist::read_snapshot_file read a model's blob from the file by offset when the model is first used (no copy is kept in memory); a file changed meanwhile is refused for the model, a loaded model keeps running. A graph with no packed models has the built-in hash-ngram/1 only.
  • Vector rules (Vector Rules): a vector property with embedder and "from": "<property>" is recomputed at the end of every unit that writes its source, in the same unit; adding a rule (or replacing its model) fills every element of the label while the database is locked. Previews (validate_schema, validate_schema_patch, diff_schema) report the planned fill and one warning text; MCP set_schema/patch_schema take confirm_lock above the threshold (refused without it as a tool error, isError: true, nothing applied); the playground asks "Apply and lock"; Python issues graphersal.VectorFillWarning. The embedding part of the estimate is three times what the model's measured speed gives (that speed is measured on short sentences). The estimate of the locked time includes the schema check (PlannedFill::scan_elements/scan_ms; validate_schema measures it), and the preview names the saved queries writing the filled property directly (PlannedFill::direct_writes, a line of the warning). A cancelled fill (CancelToken) rolls the unit back as GraphError::VectorRuleFailed with the cause EmbedError::Cancelled; the execution timeout is not checked while the fill runs inside the commit. A direct write of a rule's vector is refused (GraphError::DerivedProperty); replay and recovery never call a model.
  • Blobs (Blobs): immutable files of a store named by their SHA-256, referenced by BlobRef values (graphersal::blob), kept as long as retained history references them and collected by prune; Store::write_blob/read_blob. A missing or damaged blob is never store damage: only what needs its bytes fails. Every copy carries the blobs its history references (backups, increments, ZIP, fork, attic fork, repair, convert, upgrade, .gsnap). Blob recovery: graphersal store restore-blobs <dir> --from <backup|zip|gsnap|store> (Store::restore_blobs_from) copies missing or damaged blobs back from any copy, and graphersal store repair --drop-damaged-blobs (RepairOptions::with_drop_damaged_blobs) builds a repaired store without what references a lost blob.
  • The system journal (System Journal): declared operational events (opens, closes, checkpoints, backups, prunes, damage, rollbacks, model loads, vector fills, permission denials) with levels and collapsed repeats, kept in memory per graph and in a store's journal/. It never decides anything and is never damage. Read it with graphersal store journal <dir> [--level] [--since] [--kind] [--follow] [--json], GET /api/journal, the MCP tool journal, Store::journal/Store::journal_dir, Graph::system_journal, in Python with graph.journal(...), store.journal(...) and Store.journal_dir(path, ...) (pages of dicts with the keys of --json), and in the playground under Catalog ▸ System journal… (newest first, level and source filters, incremental refresh; WebAssembly and dev server), where new records also pop up as notifications in the top-right corner (coloured by level; warn and error stay until closed; a click opens the journal at the record; the level is a setting, default notice); a newest-first page (JournalQuery::newest_first/before, newest_first=true&before=N, --last N) reads a stored journal from its end; reading needs Read on the new Resource::Journal (AccessPolicy::read_only() allows it; Python policy=). A record is read at once in the process; a store on a file system writes it to disk within about a second (a thread of its own, never in the middle of another store operation), other hosts call Store::flush_journal (the playground every second). A record names who caused it (principal: the channel, e.g. playground, mcp, cli, python) and its instance by the host name (the OS host name when no HOSTNAME is exported).
  • One clock per instance (format spec 18): commit, mark and checkpoint times and journal times never go backwards, also when the system clock steps back; the floor is restored from the files at open (storage::CommitClock, GraphStorage::commit_clock).
  • Commits of any size: a commit body over 64 MiB is written as consecutive WAL records of 64 MiB (format spec 9.3.1); the 1 GiB limit of one commit is gone (up to 2^20 parts). Memory bounds it now: a commit needs several times its size in RAM (a single commit of a little over 1 GiB peaked at 4.4 to 5.7 GB in our measurements), so split very large writes into units (The size of one commit).
  • The process memory ceiling covers every allocation proportional to data: queries (estimated or tracked live bytes), imports, snapshot loads, store opens and recovery (a graph that does not fit refuses the open, naming the minimum ceiling, never maintenance mode), checkpoints, backup verifies, model loads and vector fills (What the ceiling covers). exec::check_memory_for and exec::memory_room let a host check its own allocations.
  • Seeing how full the process is: process.memory of the statistics (/api/statistics, MCP statistics) gains usedBytes, limitBytes, limitSource, usedPercent and the segments structure, properties, compressed, indexes, models and other, with the same names and figures as g.memory_usage() (structure is structure_bytes, indexes the id and label indexes plus the property indexes). The playground shows the bar in Profile -> Statistics and in Optimize -> Memory, the REPL before /memory, the dev server in its banner. PROFILE adds a "Peak memory X of Y" line (profile::QueryMemory, TraversalMetrics::memory(), JSON key query_memory). g.memory_usage() reports the loaded models as model_bytes (MemoryStats::model_bytes, the session's memory JSON, a row of the playground's statistics), beside total_bytes, not in it.
  • Bounded memory report: g.memory_report() and MemoryReportRequest return the 500 largest rows per list (a limit parameter; usize::MAX keeps every row) plus a "remaining N labels, X bytes" count; the totals cover everything. The MCP tool memory_report defaults to 50 per list. On a graph with 111 000 labels the dev server's answer went from 207 MB in 4.2 s to 386 KB in 0.15 s.
  • Store::quick_info: the store's info() without the blob count (blobs.unreferenced is 0, not counted); it reads no WAL, no attic and no blob. The dev server adds GET /api/store/summary and GET /api/store/details (GET /api/store is unchanged).
  • CLI: --max-materialized-bytes (the per-query limit), --memory-limit <bytes|auto|none> for the process, store journal, store restore-blobs, store repair --drop-damaged-blobs, store models default, embed-model import --replace/--default; store info shows the blobs, store models marks the default model. Python: graphersal.set_memory_limit, graphersal.memory_limit, graph.limits(), memory_report(limit=), VectorFillWarning.

Fixed

  • A job's memory_limit lowered the process ceiling (it compared with the whole process); it is now the per-execution limit of the job's traversals.
  • PROFILE memory figures of nested steps: the filter, as and side-effect steps inside a short-circuiting child traversal (filter(__.out_v().not(__.has_label(..)))) were measured against a zeroed snapshot and showed trillions of allocations under the tracking allocator.
  • embed-model import takes a model from the download cache before looking for a directory of that name.
  • --license of embed-model import now applies only when the model's manifest states no licence (the library's rule); before, it overrode the manifest.
  • A ceiling help() no longer names a Rust crate path to a script user; nor do the helps of the script limits (script.max_*): they name the command line flag and the Python call, and the ScriptLimits builder as the Rust host's.
  • A store opened read-only (a model this build cannot load, newer critical content) or in maintenance mode listed no commit in changes_since and backed up no WAL commit: it used a durable end no journal had set. It now reads the WAL to its last complete record.
  • Backups of a closed store (Store::backup_dir, Store::backup_zip_dir) fill BackupReport::models like the open store's backups.
  • A closure using g inside a chain on g (g.queries().map(|q| g.get_query(q.name))) failed with Rhai's bare "Data race detected": the error now explains it and its help names the forms that work (let qs = g.queries(); qs.map(..), or a for loop).
  • A text query on a property whose model the database does not keep now says "no model of this database has the identity ..." (EmbedError::ModelNotRegistered; there is no registry since 0.5.0); its help names g.embedders() and graphersal embed-model import.
  • Playground: the Graph panel no longer flickers between showing and hiding its scrollbars with classic scrollbars (Windows): a canvas half a pixel taller than its panel made them appear and disappear about ten times a second.

Performance

  • The Divan bench of 0.5.0 against 0.4.0 (119 comparable cases, alternating runs on one machine): reads and traversals that take 10 µs or more are unchanged (68 cases, geometric mean +0.6 %; the depth-first repeat() walks +3 to +4.5 %, a sack-merging barrier() loop -10 %); imports, change sets, vector search and property-level writes within noise. A query of a microsecond or two pays about 0.1 µs more per run for setting up the memory checks (15 cases, +8 % on average). Writes on a FRESH graph measure slower (query mutations +11 %, GQL writes +6 %): without a tracking allocator, the memory ceiling walks the whole graph once at its first unit to learn its size (about 12 ns per element, 0.1 ms for 10 000 vertices). A graph walks again only after its element count has doubled or halved, or when its estimate reaches half of the ceiling, and a host with the tracking allocator (the CLI, Python, the playground) never walks. Vector rules: a unit writing one source text costs 2.3 µs including its embedding, a unit rewriting 10 000 texts 15 ms (hash-ngram/1).
  • The short-circuiting child runs of filter(), where() and not() reuse their output buffers: g.e().filter(__.out_v()...) on the large graph makes 1 allocation instead of 111 100 and runs 12 % faster (filter(__.both().has(..)): 28 %).
  • A snapshot load passes under a ceiling of 1.00x its manifest estimate (the graph is no longer counted twice; it needed about 1.4x).
  • The memory report picks its largest rows in one selection pass before building any row.
  • The playground's Store menu opens without reading the history: it shows a summary at once and the sizes when they are weighed. Store::info reads the snapshot blob tables and the ledger before an attic's WAL and stops once every blob is found, and an open store remembers what each attic entry references. On a 4.9 GB store with a model and four attic entries the menu's call went from 180-190 ms and 464 MB read to 6 ms and 43 KB (the dev server's GET /api/store from about 300 ms to 12-15 ms).
  • A schema change checks only the labels it changes when the mode stays open or closed (the apply and the validate_schema preview); a change of the mode checks everything. Adding vector rules to labels of 9,000 to 30,500 elements in a graph of 2.5 million elements: the preview went from 587-668 ms to 6-15 ms, the apply from 616-679 ms to 39-99 ms (a store: 709-824 ms to 82-183 ms). This relies on the data satisfying the stored schema, which every write checks: a storage of a host must reject writes that violate the schema in force (GraphStorage::set_schema, Custom storage).
  • Blobs are written at about 276 MB/s (SHA-256, CRC-32C and the disk together); SHA-256 is the engine's own scalar code.

Format

  • Store format version 4 (Graphersal 0.5.0): models are blobs referenced by catalog definitions of kind 5 (spec 4.5, 6.3), with the blob ledger (10.1) and the system journal (4.7); the 0.4.0 models/ area is migrated by the upgrade (15.1, INTENT op upgrade_models).
  • File format version 4: the blob reference value tag 21 (3), the manifest's blob table (6.2 item 5), system-journal segments (4.7) and the WAL Commit part record type 4 (9.3.1). A packed snapshot carries blobs as segment rows of kind 4 (7.5, 8).
  • New spec sections: 4.6 (blobs), 4.7 (system journal), 9.3.1 (commit in parts), 10.1 (ledger), 12.12 (catalog commits on a closed store), 18 (the instance clock); the vector-rule rule for replay in 9.3, blob recovery in 13.4, and the conformance notes of 17. No section was renumbered.
  • Nothing new is a creation parameter: the hash algorithm is stated per blob, and the WAL part size is a writer's choice (Creation Parameters).
  • WORKLOAD (the workload statistics) is no longer copied by a conversion (store convert), as the specification already said; an upgrade into a copy keeps it.

Project

  • No prebuilt binary or wheel for macOS on Intel from 0.5.0 on (its CI runner made every release much slower): build the CLI from source with Cargo; the Python package installs there from the sdist, which needs a Rust toolchain (Installation).

Breaking changes in detail

Each row: what 0.4.x had, what 0.5.0 has instead.

0.4.x0.5.0
graphersal --embedder ml=<repo> --default-embedder ml --graph s.gstoregraphersal embed-model import <repo> --into s.gstore --default once, then graphersal --graph s.gstore (Embedding Models in a Store)
--embedder/--default-embedder in an args filekey removed: a usage error (exit 2) naming the import command
g.embed_property(#{label: "doc", from: "text", to: "emb", embedder: "ml"})a vector rule: schema "emb": {"type": "array", "format": "vector", "embedder": "<model>", "from": "text"} (g.patch_schema(..)); applying it fills every element while the database is locked (Vector Rules). A call of embed_property, also in a saved query, fails with a help showing the rule
a loader or saved query writing the vector itself (property("emb", embed(..)))under a rule: write the source property; a direct write is GraphError::DerivedProperty
Rust Embedders::builder().with(Arc::new(my)), GraphTraversalSource::with_embedders, Embedders::scope, script::set_engine_embedders, script::set_scope_embeddersremoved: compute vectors outside and write them as values, or import a Model2Vec model into the store (Store::import_model(ModelSource::Dir(..), ImportModelOptions::new())); a host building its own Rhai engine calls script::set_engine_graph
Python graphersal.Embedder, graphersal.Model2Vec, embedders=, default_embedder=, graph.register_embedder, graph.embed_property, EmbedPropertyErrorstore.import_model(repo or dir, repo=, license=, replace=, default=), Store.import_model_into(path, ..); vector rules (Python). A removed keyword raises TypeError
memory.limit/memory.headroom as a g.with() option, an ExecutionPolicy default or a session presetthe process ceiling: exec::set_memory_limit/set_memory_headroom, CLI --memory-limit/--memory-headroom, Python graphersal.set_memory_limit(.., headroom=); per query traversal.max_materialized_bytes. The old keys fail with InvalidOption
Python memory_limit=/memory_headroom= constructor and loader keywordsgraphersal.set_memory_limit(..) (process); graph.set_limits(max_materialized_bytes=..) (per query)
presets of AnyGraph::import_graphml/import_graphsonremoved (they carried only memory.limit)
traversal.max_materialized_bytes: the size of one value or bufferthe live bytes one execution holds at once; the profile reports the peak
no default memory ceilingon by default (cgroup minus headroom, else 80 % of RAM; 3.5 GiB on wasm32); none turns it off
a commit body over 1 GiB vetoed (CommitTooLarge)written in parts; CommitTooLarge only beyond 2^20 parts
g.memory_report(), MemoryReportRequest::new(): every rowthe 500 largest rows per list plus the count of the rest (limit/with_limit(usize::MAX) for all)
graphersal store export: the snapshot plus the models/ files as they werethe stored snapshot with the models of ITS position: a model imported after the last checkpoint is exported after the next store checkpoint
embed-model import --license X overriding the manifestapplies only when the manifest states no licence
a 0.1.x-0.4.x store opened as it isgraphersal store upgrade first (store format version 4)

graphersal (Rust), removed from the public API (checked with cargo semver-checks against v0.4.0):

  • vector::{Embedder, EmbedderInfo, EmbedContext, Embedders, EmbeddersBuilder, HashNgram, Model2Vec, Model2VecOptions, EmbedJob, EmbedReport, EmbedJobError, DEFAULT_MAX_BATCH, MAX_EMBEDDER_NAME_BYTES}; the vector facade keeps the Vector* types, MAX_VECTOR_DIMENSION and EmbedError. Feature model2vec now means "the engine can load the models kept in the database" and has no public item of its own.
  • Graph::embed_property, AnyGraph::embed_property, ScriptGraphTraversalSource::embed_property, GraphTraversalSource::with_embedders, script::set_engine_embedders, script::set_scope_embedders.
  • EmbedError::Registry and EmbedError::EmbedderMismatch; the constructors EmbedError::unavailable/failed/bad_output/no_features are crate-internal.
  • persist::{StoredModel, ModelFile, AddModelReport, StoredEmbedders}, Store::add_model, read_model_file, stored_embedders, stored_embedders_dir, add_model_dir, read_model_file_dir.

Changed:

  • persist::BaseModel moved to catalog::BaseModel.
  • Store::models/models_dir return Vec<ModelInfo>; Store::remove_model(repo) and remove_model_dir(dir, repo, ClosedCommitOptions) take a repository and return ModelChangeReport; StoreInfo::models and the models of BackupReport, ForkReport and RepairReport are Vec<ModelInfo>; Store::import_models_from_packed returns Vec<BlobRef>; persist::ModelCopy is an alias of BlobCopy (Exclude leaves out models and blobs).
  • AnyGraph::import_graphml/import_graphson take no presets argument.
  • Store::import_model with replace re-embeds the vectors of rules naming the old revision; vectors of it without a rule refuse the replace with StoreFailure::ModelInUse.
  • set_schema may write data: the first fill of a vector rule.
  • Graph is no longer UnwindSafe, Recovered no longer UnwindSafe nor RefUnwindSafe (they hold the model registry and the instance clock).
  • The implicit discriminants of Resource::Custom and StoreFailure::AutoCheckpointFailed changed (new variants before them); only an as cast sees it.
  • MemoryReportRequest::new() is bounded (above).

Added (not breaking), beyond the features above: GraphError::{DerivedProperty, VectorRuleFailed, VectorRuleModelMissing}, the field needed of GraphError::ResourceLimitExceeded, PersistError::MemoryBudget fields operation, in_use, setting, PersistError::Journal, the StoreFailure causes BlobUnavailable, BlobDamaged, ModelUnavailable, ModelDoesNotFit, ModelInUse, ModelRevisionExists, UpgradeModelDamaged (each with a faq.md row), ElementProperty::Blob (refused as element data), SchemaChangeKind::{VectorRuleAdded, VectorRuleChanged, VectorRuleRemoved}, VectorSchema::from, schema::{PlannedFill, FillReason, fill_warning}, exec::FillProgress, Graph::vector_fill_progress, UpgradeReport::{models_converted, migration_commit, models_missing, vectors_without_rule, saved_queries_using_removed, saved_queries_writing_vectors, vector_notes}, SnapshotLoadReport::saved_queries_writing_vectors, VectorWithoutRule::combined_schema_patch, PlannedFill::{scan_elements, scan_ms, direct_writes}, catalog::{RemovedFunctionUse, VectorPropertyWrite}, script::{saved_queries_using_removed, saved_queries_writing_vectors}, persist::{ModelSource, ImportModelOptions, ModelInfo, ModelState, ImportModelReport, ModelChangeReport, ClosedCommitOptions, BlobSource, RestoreBlobsReport, RepairOptions, ModelCache, ConvertedModel, MissingModel, VectorWithoutRule, SnapshotLoadReport, read_snapshot_file}, Store::create_from_packed_dir, Recovered::into_graph, RecoveryReport::clock_floor, the report fields for blobs, models and journal files.

graphersal-session and graphersal-wasm (internal): the session JSON carries modelsNote, the models' state, loadBytes, neededBy and default, fill/fill_warning in schema previews (each fill with scan_elements, scan_ms, direct_writes), model_bytes in the memory JSON (views::memory_stats_view), process.memory with the bar keys, query_memory in profiles, and a limit for the memory report; Session::journal and wasm journal(spec) read the system journal.

Release 0.4.0

A minor release about errors that are never swallowed and readers that keep reading. Every public method that touches shared state (the graph's lock, a storage, a Store, files, embedders) now returns a Result and never answers a failure with an empty or default value; a host's own storage reports a backend failure through every method of GraphStorage, and the engine fails the query with it. A whole-script unit and a playground run no longer block other readers while they only read, and a checkpoint taken while a run is open no longer persists data the run later rolls back. A Store can keep the embedding models it needs inside it.

It is not a drop-in update for Rust callers: read "Upgrading from 0.3" first. The DSL, GQL, the schema format and the storage formats are unchanged; scripts and stores of 0.3 work as they are.

Upgrading from 0.3

  • Result for shared state (Rust API). Reads of AnyGraph, Graph, Store and GraphTraversalSource (statistics(), memory_usage()) that answered a plain value now return a Result with a #[non_exhaustive] error type (GraphError, PersistError, TraverserError). The upgrade step for each is "handle the Result" (?, or .unwrap() where the caller knows better). Every changed signature is listed under "Breaking changes in detail" below.
  • Storage implementers (EXPERIMENTAL GraphStorage, PersistentStorage, StoreDir). Every method of GraphStorage returns Result<_, GraphError>, the element reads included (vertex_count, vertices, out_edges, get_vertex_by_id, vertex_properties, ...: one Result per call, never per item); the defaults return Ok of the old default. Wrap a backend failure with GraphError::storage_failed; the engine fails the reading query with it, located at its step. Return Err from rollback_unit only when the storage really is in an unknown state: a failed rollback now poisons the Graph that holds the storage (below). A wrapper storage over a storage held elsewhere forwards the new GraphStorage::storage_identity(). TraversalGraph never fails these reads and its impls are inlined, so the Result costs nothing on the hot paths. The guide is Custom Storages; graphersal-storage-tests gains the failing::Failing storage, which fails each group of methods on purpose.
  • A failed rollback poisons the graph (behaviour). When a host storage's rollback_unit (or discard_unit) fails in a unit the engine closes on a Graph, that graph refuses every later data operation with the new GraphError::Poisoned; try_read/try_write answer None, read()/write() panic. There is no unpoison: drop the graph and reopen the storage (Graph::is_poisoned, Graph::poison_cause). Exactly the graph whose storage failed is poisoned, never another one. TraversalGraph and the Store cannot get there (their rollback cannot fail) (Transactions).
  • Errors that surface now. Failures that used to read as "no data" are errors: an unreadable store directory or single-file store (Store::is_store, SingleFileDir::is_single_file), an unreadable attic or models directory (Store::info), a failing compression estimate (Graph::advise), a read the current thread may not have (GraphError::GraphViewHeld instead of an empty answer), a poisoned internal lock of a Store (StoreFailure::LockPoisoned instead of a default answer). The CLI, the dev server, MCP and Python report them.
  • graphersal-session (internal) returns the typed SessionError instead of String; graphersal-wasm's JS methods throw instead of answering an empty value.
  • Python: Store.close() raises on a poisoned store lock (was "already closed"), Graph.execute raises on a poisoned limits lock (was the default limits). Everything else is unchanged.
  • DSL: a predicate whose operand is a list, map or traversal (P.gt(["a"])) is an error now; it used to compare with the operand's text (issue #14, under "Fixed").

Added

  • Embedding models inside a Store (Embedding Models in a Store, issue #10): graphersal embed-model download <repo> --into <store> and embed-model import <dir> --into <store> put a Model2Vec model into a store, with its model card, its licence files (a standard licence text when the model ships none, and the texts of its base models' licences) and a manifest with a SHA-256 per file. Opening the store registers its models, so a text query embeds with the model the schema recorded wherever the store goes. Every copy carries them (backups, ZIP backups, fork, attic fork, repair, convert, upgrade, restore, packed snapshots); store verify checks every file. graphersal store models lists and removes them, store info shows them, store export and store backup --zip take --without-models. Rust Store::add_model/models/remove_model, Python Store.models() and Store.export(without_models=), the playground's Store menu (downloads with or without models).
  • Units held across locks (Transactions): Graph::begin_unit/commit_unit/commit_unit_with/rollback_unit/discard_unit/ unit_changes/holds_unit keep one unit over several locks on the opening thread. Other threads read on while the unit has only read and wait from its first write until it closes, so nobody sees uncommitted changes. Whole-script units (eval_value_atomic, dry runs, writing saved queries, query jobs) and the playground's and dev server's runs use them: readers are no longer blocked by a script that only reads. Graph::try_write_checked tells "busy" from "forbidden on this thread"; Graph::read_checked/write_checked/try_read report an aliasing view as GraphError::GraphViewHeld instead of panicking.
  • AI Chat export: the AI Chat tab's Export menu downloads the transcript as Markdown or JSON (AI Chat, issue #18). The AI Chat keeps its history compressed, shows the input, output and cached token counts of each answer, and answers from what it has when it reaches the tool-call limit.
  • Storage advisor: every recommendation has an impact (low, medium, high: its share of the graph's memory, or the scans and reads it saves) beside its confidence, and the list is ordered by it (Optimize).
  • Dev server on any address, and in Docker (Listening address and Docker): the dev server (graphersal --server, with --mcp and --ai) has a new --host <ADDR> option to listen on any address (for example --host 0.0.0.0), and inside a Docker or Podman container it now listens on 0.0.0.0 by default, so docker run -p 8080:8080 ... graphersal --server --port 8080 works without flags. A non-loopback address prints a warning that the server has no authentication; on the loopback the Host/Origin checks stay as strict as before, and on a network address they still refuse DNS-rebinding requests. A Kubernetes pod (KUBERNETES_SERVICE_HOST) counts as a container.
  • Running in Docker and Kubernetes (Running in Docker): a Dockerfile in the repository builds the static graphersal binary into a small distroless image (non-root, HEALTHCHECK, STOPSIGNAL SIGTERM) whose default command serves /data/graph.gstore read-only with a read-only MCP endpoint.
    • Health endpoints: GET/HEAD /healthz (liveness: 200 while the process answers HTTP) and /readyz (readiness: 200 when the graph is loaded, 503 while it loads or the server stops). They take no lock, never wait for a running query and are exempt from the Host/Origin checks, so Kubernetes probes and Docker health checks work in every bind mode. The server listens before the graph loads: during a long Store open /healthz answers 200, /readyz and the API 503.
    • graphersal health [--ready] [--host ADDR] [--port N] [--timeout MS]: the probe for images without curl or wget (exit 0 when the endpoint answers 200, 1 otherwise).
    • SIGTERM: the dev server always stops on SIGINT/SIGTERM, also as PID 1 of a container (where a process without a handler ignores SIGTERM and docker stop waits for its kill): the running query is cancelled, /readyz turns 503, a Store is closed cleanly, and the process exits with 0. As PID 1, a one-shot script and the REPL exit with 130 on them too.
    • --read-only: the served graph refuses every write (queries, schema, catalog, "Save to file"; MCP offers only reading tools), and a Store is loaded without its lock and without writing anything, so a :ro mount, a read-only root file system or a file without write permission works, models included. A Store that cannot be opened for writing falls back to it with a note. Rust: Store::stored_embedders_dir (the models of a store loaded with Store::open_read_only); a single-file store on a read-only file system now reads like one without write permission.
  • Dev server: the start output is grouped in sections (Store, Graph, Embedding models, Server) and names every embedding model with its repository, licence and source; the playground shows no Examples menu with the dev server (the examples are written for the sample graphs).
  • New Rust items (additive): Graph::begin_unit and its closes, Graph::try_write_checked, Graph::is_poisoned, Graph::poison_cause, GraphError::StorageFailed, RollbackFailed, Poisoned, GraphViewHeld and UnitNotHeld (with constructors such as GraphError::storage_failed), GraphStorage::storage_identity and storage::StorageIdentity, GraphStorage::next_unit_started_at/begin_unit_at (defaulted), UserJobs and NotScheduledJob, RepairReport::marks_unreadable, StoreFailure::AutoCheckpointFailed, and the model API of the Store.
  • Benchmarks: the Divan bench gains mutation cases (bulk writes through traversals, small write queries through the Graph<S> lock, Rhai scripts per statement and as one unit, GQL writes).

Fixed

  • A checkpoint while a run is open no longer persists rolled-back data. A playground or dev server run kept its unit open between per-traversal locks, so a Store checkpoint taken in that window could write data the run later rolled back. Runs now hold their unit across the locks, so a checkpoint never sees a run's uncommitted changes.
  • Predicates take single values (issue #14): P.gt(["a"]) compared with the text ["a"]. Every step that takes a predicate now refuses a list, map or traversal operand with a help naming the predicate (Predicates); P.within() and P.without() without arguments are the empty set.
  • Saved queries with closures (issue #16): a closure in a saved query's body is part of its one function, and a capturing closure no longer makes a writing body dynamic.
  • define_query takes the params list get_query returns (issue #17), so get, change and define round-trip (Saved Queries).
  • Swallowed errors: a session run's commit or rollback, the Store menu's compaction advice (now compactionError), an unknown job time zone, a failed system job, the workload and memory report answers, a stored model or embedder a store cannot load, and an AI Chat saved query whose entry cannot be read (now treated as writing) report their error.
  • A storage read that fails while the engine builds the message of another error no longer replaces that error.

Performance

  • The Result of the element reads costs nothing measurable: the Divan bench of 0.4.0 against 0.3.0 is within noise overall (geometric mean -0.4 %); the glob_path() walk, which first got 4-9 % slower, reads the storage through a plain match again and is back at its 0.3.0 speed.

Format

  • No format version changes: the store format and the file format stay at version 3. Embedding models live in a new optional models/ area of a store (format spec, section 4.5) and as ignorable rows of kind 3 in a packed snapshot's segment table (section 8). Graphersal 0.3.0 opens a store with models and ignores them, loads a .gsnap with models, and refuses a ZIP backup with models as written by a newer version (make one with --without-models for it).

Project

Breaking changes in detail

One user decision (2026-10-28) drives them: a public method that touches shared state (the graph's lock, the storage, a Store, files, embedders) returns a Result with a #[non_exhaustive] error type, even where it cannot fail today, and never answers a failure with an empty or default value.

graphersal:

  • AnyGraph (EXPERIMENTAL): capabilities() -> Result<StorageCapabilities, GraphError>, last_commit_seq() -> Result<u64, GraphError>, statistics() -> Result<Option<GraphStatistics>, GraphError>, memory_usage() -> Result<Option<MemoryStats>, GraphError>, get_schema() -> Result<Option<GraphSchema>, GraphError>, definitions(kind) -> Result<Vec<Definition>, GraphError>, definition(kind, name) -> Result<Option<Definition>, GraphError>, compression_stats(name) -> Result<Option<CompressionStats>, GraphError>, property_indexes() -> Result<Vec<PropertyIndexInfo>, GraphError> (were the plain values; a read the current thread may not have was answered as "no data", now GraphError::GraphViewHeld).

  • Graph::advise fails when a compression estimate fails for another reason than GraphError::Unsupported (was: advice without compression recommendations).

  • Store: read_only_reason() -> Result<Option<String>, PersistError>, stopped_reason() -> Result<Option<String>, PersistError>, damage_policy() -> Result<DamagePolicy, PersistError>, store_id() -> Result<u128, PersistError>, damage_found() -> Result<Vec<FoundDamage>, PersistError>, last_auto_checkpoint_error() -> Result<Option<Arc<PersistError>>, PersistError> (was Option<String>), user_jobs() -> Result<UserJobs, PersistError> (was Vec<Job>; UserJobs { jobs, not_scheduled } lists the definitions it does not schedule with the reason), stored_embedders(&registered) -> Result<StoredEmbedders, PersistError>, Store::is_store(dir) -> Result<bool, PersistError> and SingleFileDir::is_single_file(path) -> Result<bool, PersistError> (an unreadable directory or file is PersistError::Io, not false). A poisoned internal lock is StoreFailure::LockPoisoned (was a default answer).

  • Store::info (and StoreInfo everywhere) fails when the attic or the models directory cannot be read (was an empty list); a fork or attic fork fails before writing when the marks it does not carry cannot be listed.

  • GraphStorage (EXPERIMENTAL; implementers and callers): the methods beyond single elements return Result<_, GraphError> (defaults: Ok of the old default): statistics, infer_schema, get_schema, declared_property_schema, definitions (Result<impl Iterator>), definition, compression_stats, property_indexes, the four property index lookups (Result<Option<Box<dyn Iterator>>>), shrink_to_fit, memory_usage, memory_structure, memory_footprint_bytes, execution_policy, begin_unit, begin_unit_at, next_unit_started_at, rollback_unit, unit_changes, set_unit_metadata, capabilities, last_commit_seq. A failed rollback_unit still closes the unit; the engine reports GraphError::RollbackFailed.

  • Behaviour (user decision 2026-10-28): a failed rollback POISONS the Graph (was: "the graph stays usable"). When a host storage's rollback_unit (or discard_unit, other than the Unsupported of a storage without change capture) fails in any unit the engine closes on a Graph (a traversal, a transaction or dry run on a write view, an import, a change-set apply, a held unit's close, a panic unwinding through a unit), the graph refuses every later data operation with the new GraphError::Poisoned { cause } (read_checked, write_checked, try_write_checked, begin_unit, the closes of a held unit, the AnyGraph methods, sessions; try_read/try_write answer None) and Graph::read()/write() panic. No unpoison: drop the graph and reopen the storage. TraversalGraph and the Store cannot get there (their rollback cannot fail). Upgrade step for a host storage: return Err from rollback_unit only when the storage really is in an unknown state. The poison is isolated per graph: the failing storage is named by the new GraphStorage::storage_identity() -> StorageIdentity (opaque; default StorageIdentity::of(self); a wrapper over a storage held elsewhere forwards it, as the shipped wrapper impls do; the pinned clock of a held unit is now found the same way, also for Graph<Box<TraversalGraph>> and wrapper storages), so a failure never poisons another graph on the same thread, and a bare storage poisons nothing.

  • Behaviour: a storage read that fails while the engine builds the diagnostic of another error (the value origin of cast, numeric and incomparable-value errors, the type a string step, a list function or T.value names) no longer replaces that error with the storage's: the original error is reported without the unreadable detail.

  • GraphStorage, the element reads too: vertex_count/edge_count -> Result<usize, _>, vertices/edges/out_edges/in_edges -> Result<impl Iterator, _> (one Result per call, never per item), vertices_by_label/edges_by_label -> Result<Box<dyn Iterator>, _> (their defaults now collect the matches first, so a failing label read is the call's error), get_vertex_by_id/get_edge_by_id/vertex_id/edge_id/vertex_label/edge_label/ vertex_properties/edge_properties/edge_endpoints -> Result<Option<_>, _>, vertex_labels -> Result<&[CompactString], _>, vertex_has_label/contains_vertex/ contains_edge -> Result<bool, _>, unit_started_at -> Result<Option<i128>, _>. The engine fails the reading query with the error, located at its step. TraversalGraph's own inherent vertex_count()/edge_count() stay plain usize (an in-memory count that cannot fail).

  • CreateContext::for_storage and GraphStatistics::from_storage return Result<_, GraphError> (they read the storage).

  • PersistentStorage (EXPERIMENTAL): set_graph_id, raise_position, reserve_load, finish_load, clear return Result<(), GraphError>.

  • StoreDir (EXPERIMENTAL): space_usage() -> io::Result<Option<SpaceUsage>>, free_space() -> io::Result<Option<u64>>, check() -> io::Result<DirCheck>. A failing free_space fails the compaction advice (PersistError::Io) instead of reading as unknown; a failing check opens the Store in maintenance mode with that damage (as SingleFileDir did for an unreadable file).

  • GraphTraversalSource::statistics() -> TraverserResult<Option<&GraphStatistics>> and memory_usage() -> TraverserResult<Option<MemoryStats>> (were the plain values).

  • Added (not breaking): Graph::try_write_checked, UserJobs, NotScheduledJob, RepairReport::marks_unreadable, StoreFailure::AutoCheckpointFailed, GraphError::StorageFailed (GraphError::storage_failed), GraphError::RollbackFailed (GraphError::rollback_failed), GraphError::Poisoned (GraphError::poisoned), Graph::is_poisoned, Graph::poison_cause, GraphStorage::storage_identity (with a default) and storage::StorageIdentity, graphersal-storage-tests' failing::Failing (with the discard_unit, element_identity and fail_element_reads_after faults).

graphersal-session (internal, listed for the CLI and the wasm crate):

  • SessionError replaces String as the error of every public method that returned Result<_, String> (session methods, SessionGraph, GraphFactory, the generic helpers of views, filter, selection, create, edit, queries, compression, layout, advisor, store::parse_time).
  • Now Result<_, SessionError>: Session::info, statistics, get_schema, get_schema_text, infer_schema, infer_schema_text, load_shared, attach_store, list_queries, get_query, query_count, save_catalog_text, list_compressions, get_compression, compression_count, list_indexes, get_index, index_count, jobs_view, job_entry, workload_report, tick_jobs, read_only_reason.
  • SessionGraph: vertex_count, edge_count, inferred_schema, schema_view, schema_view_of, graph_view, add_degrees, statistics_view, memory_view, element, subgraph, element_view, drawn, incident_edges, queries, query, count_kind, catalog_text, compressions, compression, indexes, index, run_changes, rollback_run return Result<_, GraphError>.
  • The generic helpers over a storage's element reads return Result<_, GraphError> too: CompactGraph::build, CompactGraph::add_degrees, display::element_of (Result<Option<_>, _>), display::node_of, display::edge_of, display::collect_subgraph (Result<Option<_>, _>), views::graph_view, create::drawn_in, create::incident_edges (Result<Option<usize>, _>), edit::element_view.
  • SessionStore: read_only_reason, damage_found, damage_policy, last_auto_checkpoint_error, user_jobs return Result<_, PersistError> like Store; the trait gains models, import_models_from_packed and export_packed_with (embedding models in a Store), implemented for every Store<S>.
  • The generic helpers compressions_in, compression_in, indexes_in, index_in, queries_in, query_in, count_kind, catalog_text, views::schema_view, schema_view_of, statistics_view, memory_usage return Result<_, GraphError> (they read through the GraphStorage methods that now return one).
  • store::found_damage_value -> Result<Value, PersistError>; StoreError is #[non_exhaustive] (build it with StoreError::new, bad_request, conflict, refused, internal, with_data, or From a SessionError, PersistError or GraphError).
  • The Store menu's JSON gains compactionError (beside compaction: null when the advice cannot be computed).

graphersal-wasm (internal JS API): info, getSchema, inferSchema, schema, graphView, memoryUsage, statistics, tickJobs, jobs, listQueries, getQuery, saveCatalog, listCompressions, listIndexes throw the error instead of answering an empty value.

Python: Store.close() raises on a poisoned store lock (was "already closed"), Graph.execute raises on a poisoned limits lock (was the default limits).

Release 0.3.0

A minor release. The engine learns what its graph holds and how it is used, and acts on it: workload statistics, scheduled jobs, a memory report and a storage advisor with an Optimize panel in the playground. Dates and times reach nanosecond resolution, the in-memory graph takes markedly less memory, and the DSL spells Graphersal's own extensions in snake_case only.

It is not a drop-in update for every caller: read "Upgrading from 0.2" first.

Upgrading from 0.2

  • Graphersal's own DSL functions are snake_case only. The camelCase twins of 63 extensions are removed (createIndex, defineQuery, memoryReport, removeProperty, globPath, addLabel, setLabel, dropLabel, toJson, toTable, toMermaid, toPlantUML, firstName, dateTrunc, localDateTime, ...). TinkerPop's steps and functions keep both spellings (hasLabel and has_label), as do five names of the Java API (containsKey, isEmpty, toMap, Set.ofList, UUID.fromString). A script that still calls a removed name fails with a help that names the snake_case function (Writing Queries). Rendering in camelCase (render.spelling) keeps these names in snake_case, so the text still runs.
  • File format version 3. Every file this version writes (snapshots, journal segments, .gsnap, backups) is of format version 3, which holds the new temporal values. 0.3.0 reads every older file; 0.2.x refuses a version 3 file with a clear "unsupported version" error (never as damage). Keep a backup made by 0.2.x if you may need to go back. The store format version is unchanged (Format Versions and Upgrade).
  • Temporal values hold nanoseconds (were microseconds); see "Dates and times" below.
  • Rust API: the DT token gained DT::Nanosecond as its first unit, so the numeric values of its variants moved (only code casting a DT with as sees it; cargo-semver-checks reports nothing else). Every other change is an addition: new modules advisor, jobs and workload, new methods (Graph::advise, Graph::attach_workload_stats, memory_report, ...) and #[non_exhaustive] structs.

Added

  • Memory report (Memory and Profiling): g.memory_report() (REPL /memory, MCP memory_report, dev server POST /api/memory/report, Python memory_report()): one row per label and property with the bytes it takes, value types, a size histogram, distinct strings, what is compressed or indexed, and the structure's own share (slots, ids, labels, shapes, indexes). Sampled on large labels.
  • Workload statistics (Workload Statistics): a store counts what its queries do, per minute, hour and day (kept for 60 minutes, 48 hours and 90 days, persisted in the sidecar file WORKLOAD): queries by normalized plan (a pg_stat_statements analogue), how each property is used (filtered by a scan or an index, read, ordered, compared by similarity, written), the graph lock's wait and hold times, and the scheduled jobs; per channel (playground, MCP, CLI, Python, job, host). The playground's own drawing and panels are not counted. Read through GET /api/workload[?history=minutes|hours|days], the MCP tool workload_statistics, REPL /workload, Python workload_report(); their memory shows as workload_bytes in g.memory_usage().
  • Scheduled jobs (Scheduled Jobs): a cron scheduler the host ticks (no thread in the engine; the dev server and the browser playground tick it). System jobs (stats_flush, compact) whose schedule and switch can be changed, and jobs of users as catalog definitions (kind job): g.define_job(#{name, schedule, action, ...}) runs a saved query with fixed arguments, a checkpoint or a backup, with the definer's rights checked once and stored as the job's effects; limits per run (timeout, memory); every run recorded. Managed in the playground's Catalog ▸ Scheduled jobs, over /api/jobs*, MCP list_jobs.
  • Storage advisor and the Optimize panel (Optimize): recommendations from the memory report, the workload statistics and the catalog: create an index for a key filtered often by a full scan, drop an index no query used, compress or deduplicate large strings (savings measured on the data), stop compressing a key read often. Each names the catalog command that applies it; Apply runs it, Snooze and Dismiss hide it, and an applied one reports what it changed for 30 days. The playground's Optimize panel also shows the workload statistics as tables with sparklines and charts, and the memory report. Over HTTP /api/advise*, MCP advise, Rust Graph::advise (module graphersal::advisor).
  • Process memory in the statistics: process.memory (resident set size where the system reports it, the live heap, WebAssembly memory), loaded models and the AI Chat history, beside the graph's own footprint (playground Profile ▸ Statistics).
  • Dates and times (Dates and Times): nanosecond resolution for time, localdatetime, datetime and duration; offsettime; a zone name given to a datetime is kept; the whole java.time.Duration range; ISO GQL temporal literals and clocks; Python returns nanosecond values as pandas.Timestamp / pandas.Timedelta where pandas is installed.
  • Playground: a filter for the drawn graph (labels and property conditions), a compact Graph toolbar with a Display menu (vertex size by degree), in/out degree in the inspector, reloads throttled while the graph changes fast, shape bytes on the Statistics tab, four subgraph() examples; the Share link is hidden with the dev server (it cannot carry a server's graph).
  • OpenAPI description of the dev server's HTTP API (EXPERIMENTAL, The HTTP API): crates/graphersal-cli/openapi.json in the repository, served by graphersal --server at GET /openapi.json, its version the release's; a test keeps it in step with the router.
  • CLI and dev server: --args-file FILE / @FILE (a JSON file of arguments), --mcp-instructions FILE (operator notes in the MCP instructions); MCP answers are compact JSON, cut at whole results, with offset paging; the AI Chat accepts a custom system_prompt, reports lenient keys with hints, and shows each answer's time.

Changed

  • Less memory for the same graph. Stored property maps share their key lists (property shapes), the id index keeps no second copy of an id, vertex and edge slots are an own topology (petgraph is no longer a dependency) with interned label sets, and a load leaves no spare capacity. On the project's own knowledge graph (40k vertices, 190k edges) the graph took about half the memory of 0.2.3.
  • GQL MERGE without an index finds its match through a scan lookup, about ten times faster.
  • The MCP instructions and tool descriptions prefer GQL for reading and writing data.

Format

  • File format version 3 (format spec, section 3): new value tags for the nanosecond temporal values; versions 1 and 2 stay readable.
  • The workload statistics sidecar WORKLOAD (format spec, section 4.4, version 2): instance data, never in the journal, a snapshot or a backup; an unreadable or newer file means the statistics start anew. It also keeps the system jobs' settings and the advisor's marks.
  • Catalog kind 4: a scheduled job of a user (format spec, section 6.3).

Release 0.2.3

A patch release of the 0.2 line. GQL (still experimental) can now write, call saved queries and work with dates and times, and the playground gains GQL query tabs. It changes no format: stores, snapshots and journals of 0.2.2 are read and written exactly as before. Its API additions are additive (new methods, constants and #[non_exhaustive] error variants); three Gremlin behaviours are fixed (see "Fixed").

Added

  • GQL writes (experimental) (Writing with GQL): g.gql(query) is no longer read-only. A query is one unit: it commits as a whole or leaves nothing, and the commit hooks, the journal, schema defaults and coercion, permissions, resource limits and cancellation apply as they do to Gremlin writes.
    • INSERT (Cypher spelling CREATE) creates nodes and edges once per row; SET and REMOVE change properties and labels (n.k = e, n = map, n += map, n:A:B, REMOVE n.k); [DETACH | NODETACH] DELETE removes nodes, edges and paths; MERGE [p =] <pattern> with ON CREATE SET / ON MATCH SET finds or creates one pattern per row.
    • A query whose last clause writes may end there and returns no rows; FINISH ends any query without a result.
    • Writes run through internal steps (gql:insert_node, gql:set, gql:delete, gql:merge, ...) that ask the same permissions as their Gremlin twins; a saved query that writes is recorded with its effects.
    • Not yet: FOREACH (use FOR x IN list INSERT ...), a write inside a UNION operand, a path variable in INSERT, a nested SET / REMOVE target such as n.a.b (Not yet).
  • Saved queries written in GQL (Saved Queries): g.define_query(#{name, language: "gql", body, params}) stores a GQL query, read with $name parameters and parsed, bound and planned when it is saved. A query that reads is recorded in the dialect graphersal-gql/1, one that writes in graphersal-gql/2 with its effects (catalog::GQL_QUERY_DIALECT, catalog::GQL_WRITING_QUERY_DIALECT, QueryDefinition::language()); queries() and get_query() report language and dialect. New errors for an undeclared or unused $parameter. A version that does not know GQL saved queries (0.2.2 and older) lists them as not runnable and keeps them unchanged.
  • CALL of a saved GQL query (Calling saved queries): CALL folder.name(args) [YIELD ..], standalone or once per row inside a query (OPTIONAL CALL, YIELD .. WHERE, a VOID call may end a query). A saved query in Rhai and a call inside EXISTS / COUNT / COLLECT are not supported yet.
  • GQL dates and times (Dates in GQL, The Supported Subset): date(), local_time(), local_datetime(), datetime() and duration() (Cypher spellings localtime(), localdatetime() accepted) from ISO 8601 text, a map of fields or another temporal value; components (d.year, ...), arithmetic with durations, comparison, the clocks (.statement, .transaction; one instant per execution, inside a script the script's now()), X.truncate(unit, value), datetime.fromepoch(millis) and duration.between / inMonths / inDays / inSeconds. Values hold microseconds (finer input is refused, never cut), a zone name is turned into its offset, and zoned time() is not supported yet; every difference from Neo4j is listed on Semantics.
  • More GQL expressions and clauses: list indexing and slicing (x[i], x[a..b], m[k]), + of a list and one value, the power operator x ^ y, percentile_cont / percentile_disc, chained comparisons, a constant LIMIT / SKIP, non-reserved words as names, ORDER BY over expressions of returned aggregates, a LET / WITH value as a pattern node or edge, RETURN * in name order. Equality across kinds is FALSE, lists are ordered, float division follows IEEE 754 (NaN, Infinity). A construct that is meaningless for its operand kinds is refused with a static error. The deliberate differences from Neo4j and ISO are collected in Semantics and Conformance.
  • openCypher TCK harness (TCK Compliance): the openCypher TCK 2024.3 is vendored unmodified (crates/graphersal/tests/opencypher/, not part of the published crate) and run by cargo test --test opencypher_tck against the compatibility forms GQL accepts, with a ratchet baseline and a generated compliance page. At this release 3216 of 3818 in-scope cases pass (84.2 %, 95.7 % without the temporal group) and the wrong behaviour of supported constructs is 0; the rest is missing constructs. The kit measures the Cypher compatibility forms that GQL accepts.
  • Playground (Web Playground): query tabs can be GQL (highlighting, completion, parameters, error spans, "Save as query..." from a g.gql(..) tab), the saved-query editor has a language switch and completes the declared $parameters, the new Examples panel has search, collapsible groups and GQL subgroups (including write examples), element details collapse long values, and the panel header wraps on narrow screens. The book's GQL run buttons open GQL tabs. The MCP tool gql and the AI Chat can write (read-only under --mcp-read-only; the AI Chat only when asked), and the session reports a change summary.

Changed

  • g.gql() is no longer read-only: a query with a write clause that used to be refused now runs. A host that relied on the refusal restricts it with an Authorizer / AccessPolicy (writes ask Create, Update and Delete on Data like their Gremlin twins) or --mcp-read-only.
  • GQL answers that were wrong or too strict now follow the TCK (cross-kind equality, ordering of lists, NaN, WITH ... WHERE seeing the dropped names, and more); a query that relied on such an answer may return a different one.
  • Result JSON writes NaN, Infinity and -Infinity as GraphSON typed doubles ({"@type": "g:Double", "@value": "NaN"}) in the playground, the dev server, MCP, to_json() and --format json; they used to fail with "non-finite float cannot be represented in JSON". The strict writers (GraphML, the plain serde of a value) stay strict.

Fixed

  • where(P.eq("x")) compares by logical value (Predicates): where(P.eq(..)), where(P.neq(..)), the end label of where(__.as("x")), where(P.eq(..)).by(..) and where(P.within(..)) compared the current object with the labelled one structurally, so a computed value (inject, constant, math) never equalled a lazily read property, two properties of different elements never matched, and 1 never equalled 1.0. Scalars now compare by the rules P.eq applies to a literal, elements by identity, containers by value.
  • merge_v() and merge_e() ask Read on what they search (Permissions): they asked only Create and Update, so a policy that denied reading could still probe for existence through them. A policy that allows writes but not reads now denies them.
  • A cross product is checked against the traverser limit before it is built: MATCH (a), (b) (and a mid-traversal v()) on a large graph reserved the whole product up front and could abort the process. It now fails with memory.allocation and a Help: line when it exceeds traversal.max_traversers or the memory budget, and capacities taken from query data are capped.

Release 0.2.2

A patch release of the 0.2 line. It brings GQL read queries, marked experimental, and fixes how value filters treat a string that names a step label. It changes no format: stores, snapshots and journals of 0.2.1 are read and written exactly as before. Its API additions are additive (a new feature, new methods, a new #[non_exhaustive] error variant).

Added

  • GQL read queries (experimental) (GQL Queries): g.gql(query) runs a query in GQL, the ISO graph query language (ISO/IEC 39075), on the same graph and engine as Gremlin. The query is compiled into an ordinary traversal plan, so the optimizer, property indexes, profile(), resource limits, cancellation, permissions and custom storages apply as they do to Gremlin; each result row is a map from column name to value (Result Shape). Experimental means: gql() only reads (every write clause is refused), the supported subset grows from version to version, and the rows, errors and plans of a construct may still change in a later version. Gremlin stays the complete, stable interface.
    • Supported (The Supported Subset): MATCH and OPTIONAL MATCH, WHERE, LET, FILTER, Cypher's WITH, RETURN with aggregation, GROUP BY, DISTINCT, ORDER BY, OFFSET/LIMIT; FOR (Cypher UNWIND) with WITH ORDINALITY/OFFSET; queries that start without MATCH; node and edge patterns, label expressions, quantified edges (-[:knows]->{1,3}) and quantified path patterns ((a) ((x)-[:created]->(s)<-[:created]-(y)){1,2} (b)), path variables (trail semantics: no edge bound twice in a match); EXISTS subqueries and Cypher pattern predicates; map projections, list and pattern comprehensions and RECORD {..} for JSON-shaped answers; Cypher's COUNT { }, COLLECT { }, all()/any()/none()/single() and reduce(); composite queries (UNION, UNION ALL, NEXT); CALL { } subqueries run per row (OPTIONAL CALL); parameters ($name); three-valued logic; the GQL scalar functions (strings, numbers, CAST) and the common openCypher ones (toInteger, substring, split, round, keys, nodes(p), ...).
    • ISO first, Cypher spellings accepted (Cypher Aliases): where GQL and Cypher differ, GQL wins; unambiguous Cypher spellings with the same meaning are accepted as aliases (SKIP, !=, toUpper(), -->, ...). There is no Graphersal-only syntax.
    • Errors (Errors): a query that does not parse or bind fails before anything runs, with a GQLSTATUS code, a caret under the offending text and a Help: line; constructs outside the subset are refused by name with an alternative (Refused Constructs). Size limits (pattern edges, subqueries, nesting) are errors, never a cut result.
    • Plans (Plans and Performance): a GQL query and its Gremlin twin get the same plan where they mean the same; profile() shows the internal gql:* steps; an equality on an indexed property and an id lookup per row are served directly.
    • Everywhere: Rust GraphTraversalSource::gql and gql_with(query, params) (feature gql, off by default, no dependencies, builds for wasm32), the Rhai DSL g.gql(query) / g.gql(query, params), the CLI and REPL, Python (graph.query("g.gql(...)")), the playground (GQL examples), and the MCP server's tool gql. New error TraverserError::Gql with GqlErrorKind.
    • Not yet: writes (INSERT, SET, DELETE, ...), EXCEPT/INTERSECT, path modes and shortest paths, a quantifier nested in a quantified path pattern (Conformance, Current Limitations).

Changed

  • A value filter compares a string as a value, never as a step label (Predicates): has(key, P.eq("a")), is("a"), has_value, their P forms, any/all/none and a jpath has compared a string that named a step label (as("a")) with the labelled element instead of the string itself, so g.v(1).as("vadas").out("knows").has("name", P.eq("vadas")) returned nothing. They now compare the literal, as TinkerPop does; only where(P) and where(P).by(..) read step labels. A traversal that relied on the old behaviour should use where(P.eq("a")). As a side effect, a property index now also serves a string P.eq inside child traversals and union() operands.
  • The profile table's Step column is as wide as the longest step text (Profiling): at least 60 characters (70 with nested steps), at most 160, then .... It was cut at 60/70, which hid annotations such as [index: ..]. The playground's Text view uses the same rule.

Release 0.2.1

Warning: do not use 0.2.0 on a store written by 0.2.1. Graphersal 0.2.0 reads a store that holds a compression rule with the codec dedup (new in 0.2.1) as damaged from the commit that defined the rule on: it opens it in maintenance mode, reports the commits from there on as lost, and graphersal store repair run from 0.2.0 would really drop them, although nothing on disk is damaged. Do not open such a store with 0.2.0 and never run graphersal store repair from 0.2.0 on it. Upgrade to 0.2.1; 0.2.0 is not recommended. From 0.2.1 on, what a newer version writes is never read as damage (see "Changed" below).

A patch release of the 0.2 line. It changes no format: stores, snapshots and journals of 0.2.0 are read and written exactly as before. Its additions are additive API (a new GraphStorage method with a default, new #[non_exhaustive] types).

Added

  • Saved queries that write (#11; Queries that read and queries that write): a saved query may now change data. Its effects (which elements of which labels it may create, update or delete) are inferred from its body when it is saved, never declared; a call asks the permission check for the whole effect set first and runs as one unit, so a failing call changes nothing. Schema, catalog and file writes, and writes the inference cannot see (behind Fn, call, eval, import or a computed query name), are refused when the query is saved. g.queries() lists writes and effects; the playground marks queries R/O or R/W and previews a writing call before it runs; the MCP server lists the effects, hides writing queries in its read-only mode, and the AI Chat runs one only after the user confirmed it. A writing query is stored in the dialect graphersal-rhai/2; read-only queries stay graphersal-rhai/1, so 0.2.0 still runs them and lists a writing one as not runnable (Unavailable queries and older versions).
  • Estimate a compression rule before defining it (#12; Estimating the gain): g.estimate_compression(#{label, path, element?, codec?, min_bytes?, dictionary?}) measures the candidate rules (lz4 without and with a dictionary at min_bytes 64 to 1024, plus the rule that covers the path today) on the current values and reports per candidate the values it would compress, plain, stored and dictionary bytes, the net saving, the ratio and the measured compression and read (decompression) speed, plus the values found at the path, how many are strings, a size histogram to choose min_bytes, the best candidate and warnings for a label that does not exist, a path without values and values that are not strings. The graph is not changed (no commit, no catalog change). The trial dictionary is built by the rule's own code, so the estimate of a candidate is what the rule holds after it is defined on the same data; above 100,000 strings or 16 MiB of text a deterministic sample is measured and extrapolated (sampled: true). It asks for Read on the label's data, so read-only policies, the MCP read-only mode and saved queries may estimate. Rust GraphTraversalSource::estimate_compression(&CompressionEstimateRequest) (graphersal::catalog; storages implement GraphStorage::estimate_compression, default Unsupported), Python Graph.estimate_compression(label, path, ...), the playground's Estimate button in the compression rule form (a table of the candidates with saving bars, the best highlighted, Use fills the form), the dev server's POST /api/compression/estimate and the MCP tool estimate_compression. The help of an out-of-range min_bytes names it.
  • A dedup codec for repeated values (#13; Deduplicating repeated values): g.define_compression(#{name, label, path, codec: "dedup"}) stores every distinct value at the rule's path once, in a table of the rule, and every element keeps only a reference. For long values repeated across many elements (file paths, URLs, addresses, category texts); strings of at most 24 bytes are stored inline and never shared (the default min_bytes of a dedup rule is 25), and dictionary: true with dedup is refused with a help that names the fix. Reads stay plain and cost nothing extra, query results never change, change sets, exports and files hold plain values (no format change: a load shares the values again). g.compressions() reports the shared values (compressed_values), distinct_values, plain and stored bytes (each distinct text once plus 32 bytes); g.memory_usage() adds deduped_values, deduped_plain_bytes and dedup_table_bytes (each shared text once, part of property_bytes). The estimate measures dedup with codec: "dedup" or codec: ["lz4", "dedup"] (exact, never sampled; per candidate distinct_values; the warning high_cardinality when the values are mostly distinct) and includes a dedup rule that covers the path today. Rust Codec::Dedup, CompressionCandidate::dedup/matching_codecs, Python define_compression(..., codec="dedup") and estimate_compression(..., codec=[...]), the playground's codec choice and dedup rows in the estimate table, the MCP tools define_compression/estimate_compression. A 0.2.0 reader cannot decode a dedup rule (it reports the definition as damage, see the warning at the top): drop dedup rules before opening a store with 0.2.0.

Changed

  • What a newer version writes is never damage (format spec 16 rule 9): content behind a valid checksum that this version cannot interpret is kept or refused, never reported as damage and never offered for a repair that would drop it.
    • A compression rule whose codec or element this version does not know, or whose path it cannot parse, is kept and written back byte for byte through every store path (journal, checkpoint, fork, backup, ZIP, repair), not applied (its values stay plain), and listed with served: false and a reason by g.compressions(), Python, the session, MCP's list_compressions and the playground (a not applied badge); g.recompress refuses it with the reason. New: CompressionDefinition::unserved_reason, codec_name, element_name.
    • A property index of an unknown element kind is handled like one of an unknown type: kept, not served, listed with the reason, refused when created (PropertyIndexDefinition::element_name).
    • A saved query whose stored parameters this version cannot read (a schema keyword of a newer version) is kept, listed with the reason and refused when called (QueryDefinition::unsupported_reason).
    • A definition of a known kind whose payload fields this version cannot read is kept opaque, byte for byte, like a definition of an unknown kind.
    • A graph schema this version cannot parse (in a snapshot or a WAL record) opens the store read-only with the reason (the data without the schema); a checkpoint, fork or repair of it is refused, a backup copies it as it is.
    • An unknown interrupted operation (INTENT), an unknown GRAPH state value and a well-formed backup archive entry this version does not know are refused as unsupported.
    • A block compressed with zstd, read by a build without the persist-zstd feature, is reported as unsupported (format spec 2.1), no longer as damage.
    • New error PersistError::UnsupportedContent (written by a newer Graphersal, not damage); graphersal store verify lists such content as a note:, not as damage.

Fixed

  • A traversal where a step takes values is refused (#9): an anonymous traversal given to an argument that takes ids, labels, property keys or values (has_value(__.is("marko")), has_label(__..), out(__..), values(__..), ...) was silently turned into a string and matched nothing. It is now an error whose help names the step that runs a traversal there. New: has(T.id, traversal) and has(T.label, traversal), as in TinkerPop.
  • g.memory_usage() counts the hash index of every map. It counted a property map, a nested object, a value map and the id and label indexes by their entries only and missed the hash table beside them, so property_bytes and index_bytes were 10-20 % low. They now match the bytes the allocator measures (the large sample graph: 74.2 MiB before, 92.0 MiB now). Nothing grew: the figure was wrong, not the memory.

Release 0.2.0

The second minor release of Graphersal. It brings date and time values, property indexes, schema defaults that are applied when an element is created, and vectors with exact similarity search and embedders that turn text into vectors inside the engine (a built-in one, Model2Vec models and your own, for GraphRAG). It changes the storage format and a few APIs: read Breaking changes and the upgrade guide before you move a store or a storage implementation to it. What 0.2.0 does not do yet is on Current Limitations.

Highlights

  • Dates and times (#3; Dates and Times): five value types modelled on PostgreSQL and the SQL standard, datetime (an instant with its UTC offset), localdatetime, date, time and duration (months, days and microseconds kept apart, like interval), with microsecond resolution over the years -9999 to 9999. Time zones come from the bundled IANA database (Time Zones): date_add and date_trunc in a zone, at_zone, as_local, daylight-saving gaps and overlaps resolved as PostgreSQL does. Calendar-correct arithmetic (date_add, date_diff, age), truncation and parts, conversions, now() and today() (one time per script or unit), comparison and sorting, and the schema formats date-time, date, local-date-time, time and duration with formatMinimum/formatMaximum (Dates in a Schema). TinkerPop's datetime(), asDate(), dateAdd(), dateDiff() and DT behave as TinkerPop 3.8 specifies them (TinkerPop Compatibility). Dates are values in Rust, Rhai, Python (datetime objects and graphersal.Interval), GraphSON (the java.time types), the persistence format and the playground's editors (Storage and Exchange). A string that looks like a date stays a string: a date comes from a constructor, a conversion, a schema declaration or a typed value, never from guessing.
  • Property indexes (#4; Property Indexes): g.create_index(..) declares an ordered index on a label's top-level property; the new optimizer rule property_index answers has() equality, P.within and range filters from it (.profile() shows [index: ..]), with the same results as a scan. The declaration is stored in the catalog and travels with the graph; the entries are rebuilt at every load. Every index has a type: memory-ordered is the one type of 0.2 (an index type a later version adds is kept and listed as not served, never misread), and an index on a key the schema declares as a vector, list or map is refused with a clear message (Index types). An index may carry the transform to_lower for case-insensitive search: it keys the lowered text of string values and serves has("name", __.to_lower().is("alice")) (equality, P.within, ranges; default name <label>_<key>_to_lower; a plain index on the same key coexists) (Case-insensitive search). Python Graph.create_index (transform=), the playground's Catalog ▸ Property indexes, the dev server's /api/indexes and MCP tools.
  • has(key, traversal) follows TinkerPop: has("name", __.to_lower().is("alice")) is filter(values("name").to_lower().is("alice")) (the child runs on the property's value; an element without the property is filtered out), also with a jpath key and in the three-argument form has(label, key, traversal). Before, the anonymous traversal was silently compared as a string and matched nothing. Rust has_traversal(key, traversal).
  • Schema defaults on create (#5; Defaults on create): a schema's default now has SQL DEFAULT semantics on a label's top-level properties, and the new keyword defaultFunction fills uuidv4, uuidv7 (time-ordered, RFC 9562), now or today. add_v/add_e, mergeV/mergeE on create and the playground's create dialog fill every missing default before the element is checked, in mode open and closed; explicit values (null too) win, and existing data is never changed.
  • Vectors (Vectors): a value type for embeddings with f32, f16, i8 (scalar quantization) and bit components, up to 65 536 of them; vector([..]), as_vector(), quantize(kind), GType.VECTOR, and the schema form {"type": "array", "format": "vector", "element": .., "dimension": .., "metric": ..}, which coerces a list of numbers on write and can store a property quantized from the start. Exact search with similarity(), nearest() and vector_mean() over cosine, dot product, L2 and Hamming, combined freely with graph steps (filtered search, GraphRAG, recommendations). Vectors are values in Python (graphersal.Vector, also from a numpy array), the playground, GraphSON, GraphML (through the schema) and the persistence format. Embeddings and Vector Search walks through it, in the playground without a model and from Python with one, and the playground's Examples have an Embeddings (vectors) group.
  • Embedders (Vectors): the step embed() / embed(key) and the function embed(text) turn text into vectors through the embedders the host registered (g.embedders() lists them); the built-in hash-ngram/1 (hashed words and character n-grams: fuzzy, lexical similarity, no model file, the same bits on every target) is always there, also in the browser playground. Hosts plug in their own Embedder (a Rust trait with batching and cancellation) through Embedders::builder() and GraphTraversalSource::with_embedders, the script entry points or the session; each embedder carries a stable model identity besides its registry name. Running an embedder is Execute on the new permission resource Embedder. A computed vector is stored as a plain value: replay, recovery and loads never call an embedder.
  • Embedding a property and text queries (Vectors): the job g.embed_property(#{label, from, to, ..}) embeds a property of many elements page by page, without holding the graph's lock while the embedder runs (a concurrent writer goes on; a text changed meanwhile is skipped), restartable with only_missing; Rust Graph::embed_property / EmbedJob::run_in. The vector schema keyword embedder records per label and property which model produced the vectors; the job needs an attached schema (mode open or closed), declares the property or its embedder in the unit of its first page, and refuses another model or dimension (another element kind is quantized on write). nearest(key, "text", k) and similarity(key, "text") then take the query as text and embed it with the registered embedder of the declared model, once per execution. diff_schema reports an embedder change as embedder_changed.
  • Real embedding models: Model2Vec (Embeddings): graphersal embed-model download <repo> fetches a Model2Vec static embedding model from Hugging Face (SHA-256 checked, a manifest beside it; the only network access of the tool) and embed-model list shows the downloaded ones; --embedder NAME=PATH|REPO and --default-embedder NAME register a model for every mode (one-shot, REPL, dev server, MCP, AI Chat tools), run locally on the CPU. Its model identity is model2vec/<repo>@<hash of the files>, never a path. In Rust it is graphersal::vector::Model2Vec behind the new feature model2vec (off by default, native only, loads from a local directory only); the CLI has it on by default.
  • Embedders in Python (Python Quick Start: Embedders): graphersal.Embedder(name, fn, dimension=..) makes any Python model an embedder (fn(texts) returns the rows or one 2-D numpy array, read without a numpy dependency), and graphersal.Model2Vec(name, path, model="minishlab/potion-base-8M") loads a Model2Vec model from a directory the developer downloaded (the library never downloads; the identity equals the command line's download of the same files). Every graph constructor, loader and Store opener takes embedders=[..] and default_embedder=; graph.register_embedder, graph.embedders() and graph.embed_property(label=.., source=.., target=..) (GIL released, Ctrl+C cancels between pages, EmbedPropertyError.report on failure) complete it, and scripts and text queries use the registry. Rust: Embedders::scope gives the script entry points that build their own engine a host's registry, Model2VecOptions::with_repo names the repository of a host-downloaded model.
  • Playground: the schema editor's tables edit defaultFunction and a vector's element, dimension, metric and embedder; the Graph and Mermaid drawings always show the schema the tables show (also a draft); the Mermaid diagram parses whatever labels and property names hold; the Detailed drawing zooms by mouse wheel as fast as the Fast one; a click on a panel's title collapses it; the header shows the engine version and the build.
  • Properties named id or label (#1; Properties Named id or label) are read as properties, never as the element's id or label, and vertices and edges returned by a terminal are values with their id, label and properties apart (#2; Vertices and Edges as Values).
  • Store upgrade: graphersal store upgrade (Rust Store::upgrade, Python Store.upgrade) converts a store, backup or single-file store of 0.1.x to the 0.2 format with this binary alone, keeping the whole history (Format Versions and Upgrade).
  • Files of a newer Graphersal are refused, never taken for damage (#6), as in 0.1.1; which older versions are upgraded, and how, is one table in the code, shown on Format Versions and Upgrade.
  • Prebuilt binaries (Installation): every release has archives of the graphersal command-line tool for Linux (x86_64, aarch64), macOS (Apple silicon, Intel) and Windows (x86_64), with SHA256SUMS and GitHub build-provenance attestations; cargo binstall graphersal-cli installs them. The Linux binaries are statically linked with musl and run on any distribution, but are slower on allocation-heavy queries than a source build (Performance of the prebuilt Linux binaries).

TinkerPop conformance

The vendored Apache TinkerPop 3.8.2 suite: 1631 of 1675 in-scope scenarios pass (97.4 %, 0.1.x: 1599, 95.5 %), 39 are unsupported (0.1.x: 71) and 0 supported steps behave differently from the specification. The date and time features (DateTime, AsDate, DateAdd, DateDiff) pass completely; the remaining gaps are mainly call() and the set type (TinkerPop Compliance).

Breaking changes

0.2.0 is a minor release before 1.0 and may break the 0.1 API (Releases and Versioning). Every break, and what to do:

Stored data and files

  • Store format version 3, file format version 2. 0.2.0 writes new snapshot, WAL and packed snapshot files of file format version 2 (the value tags of the date and time types and of vectors) and marks its stores with store format version 3. It reads every 0.1.x file as it is: a .gsnap of 0.1.x loads unchanged. A store of 0.1.x (store format version 2) is refused with OlderFormat until it is upgraded once with graphersal store upgrade (below); nothing is changed until you do.
  • There is no way back. An upgraded store, and every store or file 0.2.0 writes, is refused by 0.1.x. 0.1.1 refuses it cleanly as "written by a newer Graphersal" in every operation. 0.1.0 does not: it refuses to open such a store, but store info calls it corrupt, store verify lists damage, and a newer snapshot or WAL file can make it open a store in maintenance mode and offer a repair that loses data. Replace 0.1.0 with 0.1.1 wherever a 0.2 store or backup may be seen by an older binary.

Behaviour

  • A schema's default is applied. In 0.1.x default was an annotation only. Now a top-level default of a label is stored when an element is created without that property, in mode open and closed. Check the schemas you keep before you upgrade: remove a default that was only meant as documentation, or move it into description. set_schema, patch_schema and validate_schema now refuse a default that is not a valid value of its property (a stored schema with one still loads, but creating an element would then fail its check: run g.validate_schema(g.get_schema())). diff_schema reports default_changed.
  • Vertices and edges returned as values (#2). to_list()/next() return VertexValue/EdgeValue in Rust, Vertex/Edge in Rhai and graphersal.Vertex/graphersal.Edge in Python, instead of a flat map of id, label and properties. Read v.id, v.label and v["name"] (Python: v.id, v.label, v["name"]), v.properties for the map. The JSON form (playground, MCP, to_json()) is untyped GraphSON 3: a vertex {id, label, properties}, an edge {id, label, inVLabel, outVLabel, inV, outV, properties}; _from/_to are gone (use outV/inV). g.inject(v) of an element value emits the stored element and asks the authorizer for Read on Data.
  • id and label as property names (#1). by("label")/by("id") read a property, as in TinkerPop: use by(T.label)/by(T.id) for the element's own. select("id")/select("label") on an elementMap()/valueMap(true) result read a property only: use select(T.id)/select(T.label). An edge's elementMap() has Direction.OUT/Direction.IN entries.
  • GraphSON converts dates instead of skipping them. g:Date, g:Timestamp, gx:Instant, gx:OffsetDateTime, gx:ZonedDateTime (zone id dropped, reported), gx:LocalDate, gx:LocalDateTime, gx:LocalTime, gx:Duration and gx:Period become date and time values; 0.1.x skipped them, so the same file now yields properties that were absent before. A date-time text without an offset is refused, never read as UTC. The export writes the java.time tags (GraphSON).

API for storage implementers (EXPERIMENTAL)

  • insert_* is the storage primitive, add_* applies defaults (#5). The required GraphStorage methods are renamed: implement insert_vertex/insert_edge (formerly add_vertex/add_edge, same arguments), which store exactly what they are given. add_vertex/add_edge are now provided methods that fill the schema's create-time defaults and then call insert_*; do not override them. add_vertex_with/add_edge_with take a CreateContext (graphersal::storage: the time now/today store, from CreateContext::for_storage) and are the one override point per kind. Code that copies or replays data (imports, apply_change_set, recovery) calls insert_*. TraversalGraph::add_vertex/add_edge apply defaults too; insert_vertex/insert_edge are added. graphersal-storage-tests has the new item add_applies_schema_defaults_insert_does_not.
  • New provided trait methods (defaults keep a storage compiling): property_indexes() and the index lookups, unit_started_at(); StorageCapabilities::property_indexes; MemoryStats::property_index_bytes.
  • ElementProperty and ValueType have new variants (dates, vectors), and ElementProperty::Vertex/Edge carry VertexValue/EdgeValue. Downstream matches need a _ arm, as the enums are #[non_exhaustive].

Upgrading from 0.1.x

  1. Replace any 0.1.0 binary with 0.1.1 on machines that may meet an upgraded store or backup (see There is no way back).
  2. Back up the store with 0.1.x while it is closed: graphersal store backup my_store/ backup_0_1/ (or a copy of the closed directory or .gstore file).
  3. Upgrade it with 0.2.0, into a new store (the old one is only read): graphersal store upgrade my_store/ my_store_0_2/, or in place: graphersal store upgrade my_store/ --in-place. The store is verified first; everything is carried, history, marks, attic and creation parameters included, and only GRAPH is rewritten. A backup directory stays a backup (store upgrade old_backup/ new_backup/), a ZIP backup is upgraded as it is restored (store restore old_backup.zip new_store/). In Python: graphersal.Store.upgrade("my_store", "my_store_0_2") or in_place=True. Details: Format Versions and Upgrade and store upgrade.
  4. Review the stored schema's defaults (above): graphersal --graph my_store_0_2/ -e 'g.validate_schema(g.get_schema())'.
  5. Update code that reads returned elements: maps become Vertex/Edge values; by("label") becomes by(T.label) where the element's label is meant. In Python, result["name"] keeps working on a graphersal.Vertex, while result["id"]/result["label"] now read properties (a KeyError when there is none): use result.id/result.label.
  6. GraphSON files with java.time values now import them as dates; a query that relied on their absence, or a schema that declared them as string, needs a look. Packed snapshots (.gsnap) of 0.1.x need no step.
  7. Storage implementers: rename add_vertex/add_edge to insert_vertex/insert_edge, pin graphersal = "=0.2.0" and graphersal-storage-tests = "=0.2.0", and run the conformance suite (Custom Storages).

Dependencies

  • jiff (time zone rules and the bundled IANA database; the only new dependency of the default build).
  • Feature model2vec only: model2vec-rs (MIT), tokenizers (Apache-2.0, with the pure-Rust fancy-regex backend: no C or C++ code) and safetensors (Apache-2.0), with their own dependencies (ndarray, half, rayon, fancy-regex, ...). The CLI's embed-model download uses the ureq client it already has and ring (already in its tree through rustls) for SHA-256.
  • rustls 0.23.46 and ruzstd at least 0.9.1 (RustSec advisories), as in 0.1.1.

Compatibility

  • Minimum supported Rust version: 1.88.
  • Python 3.10+ (abi3 wheels).
  • Versioning and what is stable in 0.2.x: Releases and Versioning.

Release 0.1.1

A patch release of the 0.1 line. It changes no format and no API; valid stores, snapshots and journals of 0.1.0 are read and written exactly as before.

Fixed

  • Files of a newer Graphersal are refused, never taken for damage (#6). 0.1.0 refused a store whose GRAPH file has a newer store format version only when it opened it; graphersal store info read the snapshot manifests first and called such a store corrupt, store verify listed DAMAGE, and a store whose snapshot or WAL files carried a newer file format version opened in maintenance mode and offered a repair that would have lost data. Now every operation (open, read-only open, info, verify, the damage report, repair, fork, checkpoint, backup into or from it, restore incl. ZIP, prune, convert, the attic commands, listings and exports; the CLI, the dev server and Python alike) refuses a store, backup or single-file store with a newer GRAPH (either copy), a newer snapshot manifest, snapshot segment or WAL segment anywhere in it (the attic too), or a newer single-file container, with PersistError::UnsupportedVersion ("written by a newer Graphersal"), before it takes a lock, reads data or writes anything. A packed snapshot or journal stream of a newer file format version is refused the same way. The rule is in the format specification, section 15 and on Format Versions.

Dependencies

  • rustls 0.23.46 in the lock file (RUSTSEC-2026-0346, -0347, -0348 and a ServerHello downgrade advisory; used only by the CLI's AI Chat client, --ai).
  • ruzstd at least 0.9.1 (RUSTSEC-2026-0344, a decompression bomb; used only with the feature persist-zstd, whose chunk sizes are bounded before decoding).

Release 0.1.0

The first public release of Graphersal: an in-memory graph traversal engine in Rust, modelled on Apache TinkerPop Gremlin, with a durable store, a command line, a Python binding and a browser playground. What 0.1.0 does not do yet is on Current Limitations.

The engine and the query language

  • Gremlin traversals in Rust and in a Rhai script DSL, in both spellings (has_label and hasLabel), with a rule-based optimizer, bulk traversers, sacks, repeat() loops, upserts (mergeV/mergeE), math(), nested property paths (jpath), UUID values and multi-label vertices.
  • TinkerPop conformance: the vendored Apache TinkerPop 3.8.2 Gherkin suite runs on every test run. More than 95 % of the in-scope scenarios pass and no supported step behaves differently from the specification; the numbers and every deliberate difference are on TinkerPop Compliance and TinkerPop Deviations.
  • Every traversal is atomic: a failing traversal leaves nothing behind; explicit transactions, dry runs, change capture and commit hooks are in the Rust API (Transactions).
  • Profiling of the optimized plan with timings, traverser counts and optional exact memory figures; execute() returns results, error and profile of one run without throwing.
  • Schemas: one format everywhere (a strict subset of JSON Schema 2020-12 per label), enforced in open or closed mode, inferred from data, diffed and patched; a schema change is a database change.
  • Saved queries and compressed properties live in a catalog stored with the graph.
  • Safe for untrusted queries: resource limits, an optional memory budget, cancellation, and a pluggable authorizer; no query may crash the engine (a fuzzer checks it).

Data in and out

  • GraphSON 3.0 import and export (TinkerGraph reads the export), and GraphML with logical types restored from a stored schema.
  • Persistence: lossless packed snapshots, a write-ahead journal and the Store: one directory (or one file) per graph with recovery on open, checkpoints, marks, point-in-time reads, fork, rollback with an attic, verified full and incremental backups, verify, damage detection with a read-only maintenance mode and repair. The format is a public specification.

Front ends

  • Command line graphersal: a REPL with completion and help, a scriptable one-shot runner with bounded display and exit codes, and graphersal store to operate stores (Command Cheat Sheet).
  • Web playground: the real engine compiled to WebAssembly, with a graph drawing, a schema editor, saved queries, a store in memory and Share link (a query and a small graph in one link, for example in a bug report); the same UI runs over the dev server (graphersal --server), which can also serve MCP to AI clients and an experimental AI Chat.
  • Python: the graphersal package (abi3 wheels for Python 3.10+) with graphs, schemas and the Store (Python).

For integrators

  • The GraphStorage trait lets a host run the engine, the DSL, saved queries and the Store over its own storage (Custom Storages); graphersal-storage-tests checks an implementation (Storage Conformance). Both are experimental in 0.1.x.

Compatibility

  • Minimum supported Rust version: 1.88.
  • Versioning and what is stable in 0.1.x: Releases and Versioning.
  • Date and time values and the TinkerPop date steps are planned for 0.2.0.