Gremlin (TinkerPop): implementation reference
Implementation of the Gremlin Server protocol. For status, scores, how to connect and known gaps see the wire page Gremlin. Shared authentication rules are in Security.
1. Source layout
| File | Role |
|---|---|
src/protocol/gremlin/mod.rs |
GremlinServer: listener, WebSocket and HTTP framing, request ops, SASL auth, sessions |
src/protocol/gremlin/graphbinary.rs |
GraphBinary v1 request decoding and response encoding |
src/protocol/gremlin/bytecode.rs |
Bytecode, Instruction, GraphSON bytecode parsing, predicates |
src/protocol/gremlin/script.rs |
gremlin-lang script parser (text scripts become Bytecode) |
src/protocol/gremlin/engine.rs |
Step engine with TinkerPop 3.7 semantics (the one in use) |
src/protocol/gremlin/traversal.rs |
GremlinGraphStore (in-memory graph plus persistence), TraversalContext, execute_traversal, and a legacy per-step executor kept for unit tests |
src/protocol/gremlin/strategies.rs |
Bytecode rewrite strategies |
src/protocol/gremlin/types.rs |
GremlinValue, vertices, edges, paths, GraphSON v3 conversion, text predicates |
(source: module docs of each file)
2. Transport and framing
2.1 One port, three protocols
GremlinServer listens on [server] gremlin_port (default 8182). With TLS configured, TlsListener::accept_auto decides per connection from the first byte, so ws://, wss://, http:// and https:// share the port. The first read (up to 4 KiB) decides the protocol: a request containing Upgrade: websocket is upgraded, anything else is served as HTTP. (source: src/protocol/gremlin/mod.rs, ProtocolHandler::start, handle_connection, with_tls; src/server/mod.rs)
2.2 WebSocket
The upgrade computes Sec-WebSocket-Accept and replies 101. Frames: masked client frames are unmasked, payloads over MAX_GREMLIN_FRAME = 16 MiB are rejected, a close frame (opcode 8) ends the connection. Every server frame is a single FIN binary frame (opcode 2), because TinkerPop drivers expect binary. Fragmented messages (FIN clear) are not reassembled. (source: src/protocol/gremlin/mod.rs, read_websocket_frame, write_websocket_frame, compute_websocket_accept)
Each request frame starts with a one-byte MIME length and the MIME type, as Gremlin Server requires:
-
application/vnd.graphbinary-v1.0(graphbinary::MIME): decoded bygraphbinary::decode_request, converted to aGremlinRequest, answered withgraphbinary::encode_response. Bytecode requests are answered asTraverservalues (want_traversers). - anything else: the remainder is parsed as a GraphSON v3 JSON request message (
requestId,op,processor,args) and answered in GraphSON v3 JSON.
A request that fails to parse gets status 498 with a fresh request id (GraphBinary keeps the id when peek_request_id can read it). (source: src/protocol/gremlin/mod.rs, handle_connection, binary_request_to_gremlin, graphbinary_result_values)
Every result is sent in one response message with status 200 or 204. GremlinResponse::partial (206) exists but is not called, so there is no result batching. (source: src/protocol/gremlin/mod.rs, GremlinResponse)
2.3 GraphBinary v1
Request: 0x81, raw 16-byte UUID, op and processor as untyped strings, then a fully qualified args map. Response: 0x81, nullable UUID, status code, nullable message, attribute map, meta map, result value. Type codes implemented:
| Code | Type | Code | Type |
|---|---|---|---|
0x01 |
Int | 0x0f |
Property |
0x02 |
Long | 0x11 |
Vertex |
0x03 |
String | 0x12 |
VertexProperty |
0x04 |
Date | 0x14 |
Binding |
0x05 |
Timestamp | 0x15 |
Bytecode |
0x06 |
Class | 0x1d |
Lambda (decoded to a GraphSON g:Lambda only) |
0x07 |
Double | 0x1e |
P |
0x08 |
Float | 0x21 |
Traverser |
0x09 |
List | 0x23 |
BigInteger |
0x0a |
Map | 0x24 |
Byte |
0x0b |
Set | 0x26 |
Short |
0x0c |
UUID | 0x27 |
Boolean |
0x0d |
Edge | 0x28 |
TextP |
0x0e |
Path | 0x29 |
TraversalStrategy |
0xfe |
unspecified null |
Enum tokens (T, Direction, Order, Scope, Pop, Column, Cardinality and similar) are also decoded. Any other type code is an error rather than a guess, since a wrong byte would desynchronise the connection. (source: src/protocol/gremlin/graphbinary.rs, module doc and T_* constants)
2.4 GraphSON v3
GraphSON v3 types handled in requests and responses include g:Int32, g:Int64, g:Float, g:Double, g:UUID, g:Date, g:Timestamp, g:List, g:Set, g:Map, g:Vertex, g:Edge, g:VertexProperty, g:Property, g:Path, g:Traverser, g:Bytecode, g:Binding, g:P, g:TextP, g:T, g:Direction, g:Order, g:Scope, g:Pop, g:Column, g:Cardinality, g:Operator, g:Barrier, g:Pick, g:Merge, g:DT, g:Lambda. Vertices and edges with no properties omit properties, as gremlin-server does. Tested by test_graphson_roundtrip, test_bytecode_graphson_roundtrip (tests/protocol_gremlin.rs). (source: src/protocol/gremlin/types.rs, GremlinValue::from_graphson, to_graphson; src/protocol/gremlin/bytecode.rs; docs/status/2026-11-30-gremlin-sr-real-apps.md)
2.5 HTTP API
Plain HTTP on the same port serves Gremlin Server's HTTP endpoint:
| Method | Path | Request | Response |
|---|---|---|---|
POST |
/ or /gremlin
|
JSON object {"gremlin": "<script>", "bindings": {...}, "language": "..."}
|
200 with {"requestId", "status": {"code": 200, ...}, "result": {"data", "meta"}} in GraphSON v3 |
GET |
/ or /gremlin
|
?gremlin=<script>&bindings.<name>=<json> |
same |
Other paths return 404, other methods 405, a missing script 400. An Accept header naming a Gremlin serializer other than GraphSON v3 with types returns 400 "no serializer for requested Accept header". Auth is HTTP Basic (Authorization: Basic), checked per request. Errors map 401/407 to 401, 498/499 to 400, everything else to 500, with a gremlin-server shaped body (message, Exception-Class, requestId). Requests are keep-alive unless Connection: close. Limits: headers 64 KiB, body MAX_HTTP_BODY = 64 MiB. (source: src/protocol/gremlin/mod.rs, serve_http, http_reply, read_http_request, MAX_HTTP_BODY)
The body is read before credentials are checked (64 MiB ceiling). (source: docs/status/2026-11-29-preauth-body-limits.md)
Not verified: no unit test exercises http_reply; the HTTP path is covered by the AWS Graph Explorer harness (test-scripts/gremlin-graph-explorer/) per the status entry.
3. Request ops
| Op | Handling |
|---|---|
authentication |
SASL PLAIN: args.sasl is base64 of authzid\0user\0password; checked with verify_wire_credential("gremlin", ...)
|
eval |
args.gremlin is a gremlin-lang script, parsed by script.rs into Bytecode; args.bindings supply named values |
bytecode |
args.gremlin is GraphSON bytecode (or GraphBinary Bytecode converted to GraphSON) |
close |
Removes the named session; 204 |
gather |
Returns the side effect args.sideEffect (default default) of a session, or 204 |
keys |
Always 204 |
| anything else | 498 "Unknown operation" |
Both eval and bytecode run StrategyManager::apply on the bytecode (a failure is logged and the unmodified bytecode runs), then execute_traversal in the session's TraversalContext. An empty result is 204 NO_CONTENT; an error is 597 "Traversal error". (source: src/protocol/gremlin/mod.rs, dispatch_inner, handle_eval, handle_bytecode, handle_close, handle_gather, handle_keys)
Status codes used: 200, 204, 401, 407, 498, 597. The enum also defines 206, 403, 500, 598 and 599. (source: src/protocol/gremlin/mod.rs, StatusCode)
Sessions: SessionManager::get_or_create_session keys on args.session; requests without one share a fresh session context. All sessions share one graph. cleanup_expired exists but is not called. (source: src/protocol/gremlin/mod.rs, SessionManager)
Not verified: transactions (g.tx()), processor: "session" semantics beyond bindings and side effects. The README lists transactions as not covered. (source: README.md, Known gaps)
4. Authentication
Each WebSocket connection has a ConnAuth. It starts authenticated only if SYNERGYDB_DEV_INSECURE_AUTH is on, captured once when the connection is built. Otherwise any op other than authentication returns 407 AUTHENTICATE and is parked in ConnAuth::pending. When the SASL credential checks out, the parked request runs and its result is the reply to the authentication request, which is what TinkerPop drivers expect. A bad credential returns 401 and drops the parked request. Tested by test_gremlin_unauthenticated_gets_407, test_gremlin_bad_sasl_rejected and authentication_reply_carries_the_challenged_requests_results (unit tests in mod.rs). (source: src/protocol/gremlin/mod.rs, ConnAuth, process_request, handle_auth)
verify_wire_credential("gremlin", ...) checks the SynergyDB catalog and requires a superuser or a member of synergy_wire_gremlin or synergy_wire_all (see Security). GremlinServerConfig::authentication_enabled (default false) is not read anywhere. (source: src/protocol/gremlin/mod.rs, GremlinServerConfig)
When the audit log is on, every eval and bytecode request is recorded with the statement (8 192 chars max), bindings (2 048 max) and record count; it is classed as a write if the text contains addV, addE, property, drop, mergeV or mergeE. (source: src/protocol/gremlin/mod.rs, dispatch)
5. Steps
The step engine (engine.rs) first groups instructions into steps with their modulators (by, with, option, from, to, times, until, emit; until/emit/times placed before repeat apply to it). Child traversals run once per parent traverser. Values compare with one ordering and group with one equality, so 1 == 1L == 1.0 as in TinkerPop. (source: src/protocol/gremlin/engine.rs, module doc, compile)
Supported steps (the match in Engine::step is the source of truth):
| Group | Steps |
|---|---|
| Source and mutation |
V, E, addV, addE, inject, property, drop
|
| Filter |
has, hasLabel, hasId, hasKey, hasValue, hasNot, is, where, filter, and, or, not, dedup, simplePath, cyclicPath, coin, sample
|
| Map |
id, label, key, value, values, properties, valueMap, elementMap, propertyMap, constant, path, select, project, map, flatMap, local, unfold, loops
|
| Navigation |
out, in, both, outE, inE, bothE, outV, inV, bothV, otherV
|
| Branch |
union, coalesce, optional, choose, repeat
|
| Ordering and range |
order, limit, range, skip, tail
|
| Reduce |
fold, count, sum, min, max, mean (global and local scope) |
| Side effect |
aggregate, store, group, groupCount, sideEffect, cap, as
|
| Pass-through and terminal |
identity, barrier, discard, iterate, none
|
math() returns "math() step is not supported"; any other name returns "Unknown step: <name>". So sack, match, tree, mergeV, mergeE, subgraph, profile and explain are unsupported. Lambdas decode but no step evaluates them. (source: src/protocol/gremlin/engine.rs, Engine::step)
repeat() stops with an error after MAX_REPEAT_LOOPS = 10 000 iterations or MAX_REPEAT_TRAVERSERS = 5 000 000 live traversers. Empty reducers yield nothing except count (0), as in TinkerPop 3.5+. (source: src/protocol/gremlin/engine.rs, MAX_REPEAT_LOOPS, MAX_REPEAT_TRAVERSERS, reduce)
Predicates: P.eq, neq, lt, lte, gt, gte, between, inside, outside, within, without, and, or, not; TextP.startingWith, endingWith, containing, notStartingWith, notEndingWith, notContaining, regex, and notRegex in text scripts (the script parser turns it into a negated regex; GraphSON bytecode notRegex is rejected as "Unknown text predicate"). (source: src/protocol/gremlin/bytecode.rs, PredicateOp, text predicate parsing; src/protocol/gremlin/script.rs; src/protocol/gremlin/types.rs, TextPredicate)
Script parser coverage: g. traversals, anonymous traversals with or without __., nested traversals as arguments, single- or double-quoted strings with escapes, number suffixes L d f i n m, true/false/null, lists [a, b] and maps [k: v], predicates with or without the P./TextP. prefix and .and()/.or() chains, bare or qualified enum tokens, and bare identifiers that name bindings. (source: src/protocol/gremlin/script.rs, module doc)
Strategies registered by StrategyManager::new: FilterRankingStrategy, LazyBarrierStrategy, IndexStrategy, InlineFilterStrategy, MatchPredicateStrategy, PathRetractionStrategy, RepeatUnrollStrategy, CountStrategy, AdjacentToIncidentStrategy. They rewrite the instruction list; none reads a storage index. (source: src/protocol/gremlin/strategies.rs)
6. Storage mapping
GremlinGraphStore keeps vertices, edges, out and in adjacency lists, and vertex and edge label indexes in memory (parking_lot::RwLock maps). With storage it mirrors to two SQL tables:
| Table | Columns |
|---|---|
_gremlin_vertices |
id TEXT PRIMARY KEY, label TEXT, properties TEXT |
_gremlin_edges |
id TEXT PRIMARY KEY, out_vertex TEXT, in_vertex TEXT, label TEXT, properties TEXT |
Each write opens a new QueryEngine and runs DELETE then INSERT for that row (autocommit, one row at a time). Properties are JSON. At start-up all rows are loaded and the indexes and next-id counters rebuilt. Vertex ids are integers, strings or UUIDs (VertexId). The Gremlin graph is separate from the Bolt graph (_bolt_* tables). crate::index::graph::GraphAdjacencyIndex is imported in traversal.rs but not used. (source: src/protocol/gremlin/traversal.rs, GremlinGraphStore::with_storage, persist_vertex, persist_edge; src/protocol/gremlin/types.rs, VertexId)
Because a multi-step mutation writes row by row with no transaction, a crash during a traversal can leave part of it applied. Not verified: no crash test targets this; the restart phase of the differential (142/142) restarts between phases, not during a write.
Tested by test_gremlin_vertices_table_survives_restart, test_gremlin_edges_table_survives_restart, test_graph_store_with_storage_persists_add_vertex, test_vertices_and_edges_coexist_across_restart and the edge-case tests (test_add_edge_to_nonexistent_source_vertex, test_remove_vertex_cascades_edges and others) in tests/protocol_gremlin.rs.
7. Type mapping
GremlinValue variants: Null, Boolean, Int(i32), Long(i64), Float(f32), Double(f64), String, Uuid, Date(i64 ms), Timestamp(i64), List, Set, Map (ordered pairs), Vertex, Edge, Path, VertexProperty, Property, Token. Vertex properties carry a cardinality (single, list, set). (source: src/protocol/gremlin/types.rs, GremlinValue, Cardinality) Tested by the value tests in tests/protocol_gremlin.rs (test_int_value, test_map_value, test_update_vertex_property_list_cardinality, …).
8. Limits and configuration
| Item | Value | Source |
|---|---|---|
| Port |
[server] gremlin_port, default 8182 |
src/config.rs |
| TLS |
wss:///https:// on the same port when [tls] is configured |
GremlinServer::with_tls |
| WebSocket frame | 16 MiB | MAX_GREMLIN_FRAME |
| HTTP body / headers | 64 MiB / 64 KiB |
MAX_HTTP_BODY, read_http_request
|
| repeat() | 10 000 loops, 5 000 000 traversers | engine.rs |
| Reported version |
GREMLIN_VERSION = "3.6.0" |
mod.rs |
GremlinServerConfig (max_request_size 65 536, batch_size 64, evaluation_timeout_ms 30 000, authentication_enabled false, session_timeout_seconds 300) is constructed but none of its fields is read by the request path, so there is no evaluation timeout and no result batching. (source: src/protocol/gremlin/mod.rs, GremlinServerConfig)
9. Test coverage
| Suite | What it covers |
|---|---|
tests/protocol_gremlin.rs (83 tests) |
Graph store CRUD, cardinalities, value types, comparisons, text predicates, GraphSON round trips, legacy text parser (test_parse_*), traversal execution, persistence across restart, error cases |
Unit tests in src/protocol/gremlin/ (40) |
Request parsing, responses, sessions, eval, 407 challenge and SASL, WebSocket accept key, GraphBinary, engine steps |
test-scripts/diff-gremlin/diff_gremlin.py against gremlin-server 3.7.2 |
421/421 on 2026-11-30: GraphBinary 133/133, GraphSON v3 133/133, mutations 7/7, multi-connection 6/6, after restart 142/142 |
test-scripts/gremlin-graph-explorer/ |
AWS Graph Explorer over HTTP: 10/10 walk steps, 18/18 replayed queries, same after kill -9 |
(source: docs/proof/2026-11-30/proof-pack-a3232c9/logs/gremlin-four-phase-diff.txt; docs/status/2026-11-30-gremlin-sr-real-apps.md)