@wazootech/sparql-engine 0.0.0-stage → 0.5.8-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,730 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://docs.wazoo.dev">
3
+ <img src="https://wazoo.dev/assets/wazoo.svg" alt="Wazoo Worlds" width="120" />
4
+ </a>
5
+ <br /><br />
6
+ <em>Zero-dependency SPARQL 1.1 &amp; 1.2 query and update engine over RDF/JS quad stores.</em>
7
+ <br /><br />
8
+ <a href="https://www.npmjs.com/package/@wazootech/sparql-engine"><img src="https://img.shields.io/npm/v/%40wazootech%2Fsparql-engine" alt="npm" /></a>
9
+ <a href="https://github.com/wazootech/sparql-engine"><img src="https://img.shields.io/badge/GitHub-black?logo=github" alt="GitHub" /></a>
10
+ <a href="https://deepwiki.com/wazootech/sparql-engine"><img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki" /></a>
11
+ </p>
2
12
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
13
+ Wazoo [SPARQL 1.1](https://www.w3.org/TR/sparql11-query/) & 1.2 Query & Update
14
+ Engine over RDF/JS Quad Stores.
15
+
16
+ ## Try it in your browser
17
+
18
+ [**Open the Wazoo SPARQL Playground**](https://wazootech.github.io/sparql-engine/playground/)
19
+ — run `SELECT` / `ASK` / `CONSTRUCT` / `UPDATE` queries over sample datasets
20
+ entirely in the browser, no install, nothing sent to a server. Every query you
21
+ run gets a shareable URL.
22
+
23
+ ## Compatibility
24
+
25
+ - **SPARQL 1.1 — full.** `SELECT` / `ASK` / `CONSTRUCT` / `DESCRIBE`, UPDATE,
26
+ property paths, aggregation, subqueries, `VALUES`, and filters over any RDF/JS
27
+ quad store. Gated by the [W3C](https://www.w3.org/) SPARQL 1.1 evaluation
28
+ suite (differential vs [Comunica](https://comunica.dev/)): **345/345**.
29
+ - **[SPARQL 1.2](https://www.w3.org/TR/sparql12-query/) — working-draft surface
30
+ implemented.** Direction functions (`LANGDIR`, `STRLANGDIR`, `hasLang`,
31
+ `hasLangDir`; `hasLang` is variadic, 1–3 args, as a documented superset
32
+ extension), RDF 1.2 reified triple terms (`<< s p o >>`) in patterns, paths,
33
+ and updates, and the 1.2 lexical/grammar surface (a single
34
+ Turtle/TriG/N-Triples/N-Quads superset grammar backing `LOAD`). Gated by the
35
+ W3C SPARQL 1.2 evaluation suite (**249/249**), the RDF 1.2 eval-triple-terms
36
+ gap suite (**41/41**), and the RDF 1.1/1.2 grammar gates.
37
+ - **CI-enforced.** Every gate above runs in the `w3c-parity` CI job — a
38
+ spec-required behavior that regresses fails the build rather than silently
39
+ drifting.
40
+
41
+ See [docs/05 — Verification & Testing](docs/05-testing.md) for the suite
42
+ inventory and [docs/06 — Supplemental Context](docs/06-supplemental-context.md)
43
+ for the W3C suite notes.
44
+
45
+ ## Key capabilities
46
+
47
+ - **SPARQL 1.1 & 1.2 Query Engine**: Wazoo evaluation of `SELECT`, `ASK`,
48
+ `CONSTRUCT`, and `DESCRIBE` queries over `rdfjs.Store` sources — including
49
+ SPARQL 1.2 direction functions (`LANGDIR`, `STRLANGDIR`, `hasLang`,
50
+ `hasLangDir`) and RDF 1.2 reified triple terms (`<< s p o >>`).
51
+ - **SPARQL 1.1 & 1.2 Update Engine**: Support for `INSERT DATA`, `DELETE DATA`,
52
+ `DELETE/INSERT`, `LOAD`, and atomic patch transactions, including updates over
53
+ reified triple terms.
54
+ - **W3C SPARQL 1.2 Gate**: CI runs the W3C SPARQL 1.2 evaluation suite
55
+ differentially against Comunica — currently **249/249** pass — plus **41/41**
56
+ on the RDF 1.2 eval-triple-terms gap suite.
57
+ - **Zero Runtime Dependencies**: Lightweight AST parsing via the in-repo SPARQL
58
+ parser (a maintained sparqljs 3.7.4 grammar), plus an in-repo jison
59
+ Turtle/TriG/N-Triples/N-Quads parser backing `LOAD` (including RDF 1.2 triple
60
+ terms, reifiers, and annotations); zero runtime dependencies (only type-only
61
+ `@rdfjs/types`), and no Comunica framework overhead — browser-friendly, with nothing else to install.
62
+ - **Runs on Node.js, Bun, Deno and in the browser**: Published on npm as
63
+ `@wazootech/sparql-engine`, as plain JavaScript modules with types. CI installs
64
+ the package and runs it on Node.js, Bun and Deno before every release.
65
+ - **The engine behind `@worlds/sdk`**: Implements
66
+ [`SparqlEngineInterface`](https://github.com/wazootech/sparql-engine/blob/main/src/sparql-engine-interface.ts),
67
+ which `@worlds/sdk`'s durable backend factory (`createLibsqlSdk` from
68
+ `@worlds/libsql`) wires into every `Sdk` — no adapter needed. (The SDK's
69
+ former `@worlds/sdk/comunica` adapter was removed; Comunica survives only as a
70
+ differential parity oracle in this repo.)
71
+
72
+ ## Install
73
+
74
+ ```sh
75
+ npm install @wazootech/sparql-engine # Node.js 22 or newer
76
+ bun add @wazootech/sparql-engine # Bun
77
+ deno add npm:@wazootech/sparql-engine # Deno
78
+ ```
79
+
80
+ Deno waits a day before it installs a new release. To get one sooner, add
81
+ `--minimum-dependency-age=0` to the command.
82
+
83
+ Versions up to 0.5.7 were published on JSR as `@wazoo/sparql-engine`. Only the
84
+ name and the registry changed: every import path and export is the same.
85
+
86
+ ## Usage
87
+
88
+ ```typescript
89
+ import { DataFactory } from "@wazootech/sparql-engine/data-model";
90
+ import { MemoryStore, WazooSparqlEngine } from "@wazootech/sparql-engine";
91
+
92
+ const { namedNode, literal, quad } = DataFactory;
93
+ const store = new MemoryStore();
94
+ store.addQuad(
95
+ quad(
96
+ namedNode("https://example.org/alice"),
97
+ namedNode("https://xmlns.com/foaf/0.1/name"),
98
+ literal("Alice"),
99
+ ),
100
+ );
101
+
102
+ const engine = new WazooSparqlEngine({ store });
103
+
104
+ const result = await engine.execute({
105
+ query: "SELECT ?s ?p ?o WHERE { ?s ?p ?o }",
106
+ });
107
+
108
+ if (result.kind === "select") {
109
+ console.log(result.data.results.bindings);
110
+ }
111
+ ```
112
+
113
+ ### Command line
114
+
115
+ `bun run compile` builds a standalone `sparql` binary at `dist/sparql` (no
116
+ Bun install needed to run it):
117
+
118
+ ```sh
119
+ bun run compile
120
+ ./dist/sparql --data people.ttl --query 'SELECT * WHERE { ?s ?p ?o } LIMIT 10'
121
+ ```
122
+
123
+ SELECT and ASK print SPARQL 1.1 Query Results JSON, and CONSTRUCT and DESCRIBE
124
+ print N-Quads. `bun run bench:cli` measures the binary's size, cold start,
125
+ isolated load stages, and query evaluation; see `bench/cli-bench.ts`.
126
+
127
+ ### Native binary (optional)
128
+
129
+ `bun run compile` still embeds the Bun runtime (about 111 MiB on Windows). `bun run native:build` goes further and
130
+ compiles `cli/node-main.ts` with [scriptc](https://scriptc.dev) 0.4.5 into a
131
+ single executable at `dist/sparql-node` (`dist\sparql-node.exe` on Windows) with
132
+ no runtime underneath it: no Bun, no JavaScript engine, no `node_modules`.
133
+
134
+ ```sh
135
+ bun run native:build
136
+ ./dist/sparql-node --data people.ttl --query 'SELECT * WHERE { ?s ?p ?o } LIMIT 10'
137
+ ```
138
+
139
+ `bun run native:gate` runs the whole check: `scriptc coverage` (what the
140
+ compiler can and cannot lower), the build, then the cross-host contract in
141
+ `cli/run-cli.test.ts`, which replays 12 invocations through the in-process
142
+ engine and through every built host and requires identical exit code, stdout,
143
+ and stderr. Each target test skips when its artifact is absent, so
144
+ `bun run ci` stays green on a checkout with no compiler installed.
145
+
146
+ The trade is startup and artifact size against throughput: the native binary
147
+ starts faster and is far smaller, but it reads, indexes and evaluates more
148
+ slowly per triple:
149
+
150
+ ```sh
151
+ bun run bench:cli --people 200,800,3200 --runs 9 \
152
+ --target bun-compile=dist/sparql.exe \
153
+ --target scriptc=dist/sparql-node.exe
154
+ ```
155
+
156
+ `bench:cli` runs every target once per round in a rotated order and separates
157
+ the stages by subtracting inside the round, so machine drift cannot land on one
158
+ target. At 16,000 triples, over 9 rounds (median, interquartile range), measured
159
+ with Bun 1.4.5 on Windows 11 (Intel Core Ultra 7 256V):
160
+
161
+ | Isolated operation | `bun build --compile` | `scriptc` | Ratio |
162
+ | ---------------------- | --------------------- | ------------------ | ------------- |
163
+ | cold start, no data | 63.2 ms (63-64) | 23.2 ms (22-24) | 2.7x faster |
164
+ | read + parse + index | 76.7 ms (77-81) | 235.0 ms (230-241) | 3.1x slower |
165
+ | friend-of-friend query | 40.2 ms (38-43) | 60.4 ms (51-71) | 1.4x slower |
166
+ | binary on disk | 110.9 MiB | 6.2 MiB | 17.8x smaller |
167
+
168
+ The evaluation row is a difference of two process times, so it is the noisiest;
169
+ the size-scaling fit below is the more stable comparison.
170
+
171
+ Across 1,000, 4,000 and 16,000 triples the fixed and per-triple costs separate:
172
+
173
+ | Operation | `bun build --compile` | `scriptc` |
174
+ | ---------------------- | ----------------------- | ----------------------- |
175
+ | read + parse + index | 10.8 ms + 4.1 µs/triple | 9.3 ms + 14.1 µs/triple |
176
+ | friend-of-friend query | 7.4 ms + 2.0 µs/triple | -2.1 ms + 3.9 µs/triple |
177
+
178
+ The native evaluation fit puts the fixed term below the measurement floor, which
179
+ is why it lands slightly negative; the per-triple slope is the meaningful part.
180
+
181
+ Where the native load gap comes from has not been measured stage by stage
182
+ (tracked in [#251](https://github.com/wazootech/sparql-engine/issues/251)).
183
+
184
+ An earlier revision of this section quoted load and join as 5-43% slower. That
185
+ was measured at 1,000 triples, where the fixed costs dominate, and it hid a
186
+ quadratic tokenizer: the lexer copied the remaining input once per token, which
187
+ V8's sliced strings make free and a copy-per-slice runtime does not. At 16,000
188
+ triples that cost 11.5 s natively. Matching at an offset with sticky regexes
189
+ (`src/parser/lr-runtime.ts`) brought it to 0.48 s and made the cost linear.
190
+
191
+ The native graph is fully static. `scriptc coverage` reports 6,283/6,283
192
+ statements static (100%), 0 functions signature-blocked, 0 blocker groups, and 0
193
+ likely-hot untyped reads, and `bun run native:coverage` exits non-zero if a
194
+ blocker or an SC6101 group reappears, so the gate cannot regress quietly.
195
+
196
+ 48 statements stay in scriptc's report-only dynamic tier:
197
+ code that operates on values typed only at runtime, which scriptc still lowers
198
+ to native code with checked values. The compiler's labels name the shapes —
199
+ `dyn.class` for `instanceof` and casts on interface-typed values (arbitrary
200
+ RDF/JS stores, `LrParseError`/`SparqlSyntaxError`, the injectable cost
201
+ estimator), `dyn.this` for methods reached through those values,
202
+ `dyn.hasOwn`/`dyn.hasKey` for dynamic record keys in bindings and property
203
+ reads, `dyn.objCreate` for object-shaped casts and the `{}` accumulator when a
204
+ binding is copied, and one `dynObjLit` in the CLI's error reporter. They sit at
205
+ the boundaries the package's contract defines: arbitrary stores and terms,
206
+ caught `unknown` errors, `AbortSignal` reasons, and function-valued hooks such
207
+ as join callbacks, `fetch`, and `readTextFile`.
208
+
209
+ Two JavaScript-runtime-only surfaces — RDF/JS streams and optional store statistics — never
210
+ enter the native graph. `cli/tsconfig.json` maps `src/store/quad-stream.ts` and
211
+ `src/quad-store-stream.ts` to stubs, so no RDF/JS stream is constructed or
212
+ drained natively (scans answer through `MemoryStore.getQuads`), and maps
213
+ `src/store/store-statistics.ts` and `src/planner/pattern-statistics-hook.ts` to
214
+ a stub that selects the deterministic planner fallback instead of probing a
215
+ store for an optional statistics hook. Every stub throws or returns the
216
+ documented fallback rather than emulate a JavaScript runtime.
217
+
218
+ Parity with the W3C suites is measured through the Bun build; the native host
219
+ is held to the CLI contract above plus the engine's own test suite.
220
+
221
+ #### Cross-compilation
222
+
223
+ `SCRIPTC_TARGET` cross-compiles from any host, given zig on `PATH` and the
224
+ target's runtime pack. scriptc installs only its own platform's pack, so a
225
+ cross-target build needs the target's first — either as a project dependency or
226
+ anywhere on disk through `SCRIPTC_RUNTIME_PACK`:
227
+
228
+ ```sh
229
+ npm install --prefix /tmp/scriptc-pack @scriptc/runtime-linux-x64-gnu@0.4.5
230
+
231
+ SCRIPTC_TARGET=x86_64-linux-gnu.2.36 \
232
+ SCRIPTC_RUNTIME_PACK=/tmp/scriptc-pack/node_modules/@scriptc/runtime-linux-x64-gnu \
233
+ npx scriptc@0.4.5 build cli/node-main.ts -o dist/sparql-node-linux
234
+ ```
235
+
236
+ That builds an 8.4 MiB ELF. Run under WSL (Ubuntu, glibc 2.39), it matched the
237
+ Windows host byte for byte on nine of ten cases — help, argument errors, SELECT,
238
+ ASK, CONSTRUCT, `--query-file`, an unknown flag, a syntax error, and `--query`
239
+ without a value — with identical exit codes. The tenth differs only in the
240
+ missing-file message: Windows reports the resolved absolute path, Linux reports
241
+ the path as given, both with the same `ENOENT` text.
242
+
243
+ `bun run native:build` always writes the name `cli/run-cli.test.ts` discovers
244
+ (`dist/sparql-node`, plus `.exe` on Windows), so a native build on a Linux or
245
+ macOS host joins the contract automatically. A cross-built artifact for a
246
+ different platform does not: it cannot run on the build host, so verify it on
247
+ the target, as above.
248
+
249
+ Valid targets include `x86_64-linux-gnu.<glibc>`, `aarch64-linux-gnu.<glibc>`,
250
+ `x86_64-windows-gnu`, the `-musl` variants (always linked statically), and
251
+ `wasm32-wasi` for a WebAssembly module. Two build flags are worth knowing on
252
+ x86-64: `--target-cpu=x86-64-v3`, or `--cpu-dispatch` to keep one binary
253
+ portable and select the v3 code paths at startup; and, on Linux, `--static`,
254
+ which skips the dynamic loader and should widen the startup gap above. Windows
255
+ build hosts refuse `--target-cpu native`, so name a level instead. The default
256
+ is already `release` (`-O2`), and `--optimization speed` measured no gain on
257
+ this workload.
258
+
259
+ ## Tree-shakeable subpath imports
260
+
261
+ The package also exposes five subpath entrypoints — `./term`, `./data-model`,
262
+ `./store`, `./parser`, and `./serialize` — so a consumer that only needs one
263
+ layer never loads the whole engine graph.
264
+
265
+ ### `@wazootech/sparql-engine/term` — term algebra
266
+
267
+ RDF/JS term construction, hashing, comparison, and conversion, without the
268
+ evaluator:
269
+
270
+ ```typescript
271
+ import { DataFactory } from "@wazootech/sparql-engine/data-model";
272
+ import { sameRdfTerm, termKey } from "@wazootech/sparql-engine/term";
273
+
274
+ const { literal, namedNode } = DataFactory;
275
+ const xsd = "http://www.w3.org/2001/XMLSchema#";
276
+ const a = literal("42", namedNode(xsd + "integer"));
277
+ const b = literal("42", namedNode(xsd + "integer"));
278
+
279
+ termKey(a); // stable hash key for maps/sets
280
+ sameRdfTerm(a, b); // structural equality incl. datatype → true
281
+ ```
282
+
283
+ ### `@wazootech/sparql-engine/data-model` — RDF/JS DataFactoryThe canonical import for the RDF/JS `DataFactory` — the zero-dependency term
284
+
285
+ factory under the name RDF/JS consumers expect. It is an alias of `./term`
286
+ re-exporting the same module:
287
+
288
+ ```typescript
289
+ import { DataFactory } from "@wazootech/sparql-engine/data-model";
290
+
291
+ const { blankNode, literal, namedNode, quad } = DataFactory;
292
+ const alice = quad(
293
+ namedNode("https://example.org/alice"),
294
+ namedNode("https://xmlns.com/foaf/0.1/name"),
295
+ literal("Alice"),
296
+ );
297
+ ```
298
+
299
+ `/data-model` and `/term` are the same module — importing `DataFactory` from
300
+ either yields the identical object, so the two paths can never drift.
301
+
302
+ ### `@wazootech/sparql-engine/store` — RDF/JS quad store
303
+
304
+ The zero-dependency in-memory store, implementing the full `rdfjs.Store`
305
+ interface — no query engine attached:
306
+
307
+ ```typescript
308
+ import { DataFactory } from "@wazootech/sparql-engine/data-model";
309
+ import { MemoryStore } from "@wazootech/sparql-engine/store";
310
+
311
+ const { literal, namedNode, quad } = DataFactory;
312
+ const store = new MemoryStore([
313
+ quad(
314
+ namedNode("https://example.org/alice"),
315
+ namedNode("https://xmlns.com/foaf/0.1/name"),
316
+ literal("Alice"),
317
+ ),
318
+ ]);
319
+
320
+ // `match` returns an RDF/JS stream (async iterable)
321
+ for await (const q of store.match(namedNode("https://example.org/alice"))) {
322
+ console.log(q.object.value); // "Alice"
323
+ }
324
+ ```
325
+
326
+ ### Durable SQLite store
327
+
328
+ The durable `node:sqlite` store is a separate package,
329
+ [`@worlds/sqlite`](https://github.com/wazootech/worlds-sqlite). It connects to the
330
+ engine through the `createTransaction` option; see
331
+ [Durable transactions](docs/durable-transactions.md).
332
+
333
+ `@worlds/sqlite` is still on JSR and depends on this engine under its JSR name,
334
+ `@wazoo/sparql-engine`. Until it moves to npm, use it with that one. Adding
335
+ `@wazootech/sparql-engine` to the same app would load two copies of the engine.
336
+
337
+ ### `@wazootech/sparql-engine/parser` — SPARQL AST + Turtle parsers
338
+
339
+ Parse SPARQL 1.1 & 1.2 into the sparqljs-compatible AST without loading the
340
+ evaluator, and parse Turtle-family documents into RDF/JS quads:
341
+
342
+ ```typescript
343
+ import {
344
+ parseTurtleQuads,
345
+ SparqlParser,
346
+ } from "@wazootech/sparql-engine/parser";
347
+
348
+ const ast = new SparqlParser({ sparqlStar: true }).parse(
349
+ "SELECT ?s WHERE { ?s ?p ?o }",
350
+ );
351
+ console.log(ast.type); // "query"
352
+ console.log(ast.variables); // [Variable{ value: "s" }]
353
+
354
+ // Turtle / TriG / N-Triples / N-Quads → RDF/JS quads (graphs preserved)
355
+ const quads = parseTurtleQuads(
356
+ '@prefix : <https://example.org/> . :alice :name "Alice" .',
357
+ );
358
+ console.log(quads[0].object.value); // "Alice"
359
+ ```
360
+
361
+ ### `@wazootech/sparql-engine/serialize` — results writers + Turtle writer
362
+
363
+ Serialize a
364
+ [`SparqlResponse`](https://github.com/wazootech/sparql-engine/blob/main/src/sparql-engine-interface.ts) to
365
+ SPARQL results JSON (`.srj`) or XML (`.srx`), or RDF/JS quads to
366
+ Turtle/TriG/N-Quads/N-Triples:
367
+
368
+ ```typescript
369
+ import {
370
+ serializeJsonResults,
371
+ serializeTurtle,
372
+ serializeXmlResults,
373
+ } from "@wazootech/sparql-engine/serialize";
374
+
375
+ const response = {
376
+ kind: "select",
377
+ data: {
378
+ head: { vars: ["s"] },
379
+ results: {
380
+ bindings: [{ s: { type: "uri", value: "https://example.org/alice" } }],
381
+ },
382
+ },
383
+ };
384
+
385
+ serializeJsonResults(response); // {"head":{"vars":["s"]},"results":…}
386
+ serializeXmlResults(response); // <?xml version="1.0" encoding="UTF-8"?>…
387
+
388
+ // The writer counterpart to parseTurtleQuads — lossless round-trip, incl.
389
+ // RDF 1.2 triple terms and named graphs (TriG blocks in Turtle mode).
390
+ serializeTurtle(quads, {
391
+ format: "turtle",
392
+ prefixes: { ex: "https://example.org/" },
393
+ });
394
+ serializeTurtle(quads, { format: "n-quads" });
395
+ ```
396
+
397
+ The subpaths can be mixed freely — e.g. the store above with the term layer, or
398
+ the serializers fed by `engine.execute()`'s response. Anything not re-exported
399
+ through `./term`, `./data-model`, `./store`, `./parser`, or `./serialize` (or
400
+ the root entrypoint) is private surface.
401
+
402
+ ## Parity testing
403
+
404
+ The differential test suite in `test/parity/` proves behavioral equivalence with
405
+ `@comunica/query-sparql-rdfjs-lite`, the engine this project ports 1:1. Every
406
+ case seeds both engines with identical RDF/JS stores, runs the same query
407
+ through each, and deep-compares the observable results: SELECT bindings
408
+ (projected variables and values, with ORDER BY emission order compared exactly),
409
+ ASK booleans, and CONSTRUCT quads.
410
+
411
+ Blank nodes are compared by identity, not by label. Comunica skolemizes blank
412
+ nodes from query sources into prefixed labels (`bc_<sourceId>_<label>`); the
413
+ wazoo engine returns the store's own labels. SPARQL 1.1 result semantics treat
414
+ blank node labels as scoped and opaque, so the wazoo engine deliberately does
415
+ not replicate the prefix — the harness strips it from Comunica's output before
416
+ comparing (see `test/parity/parity-harness.ts`). A test in
417
+ `test/parity/parity.test.ts` locks in this known difference against real
418
+ Comunica output, so the normalization stays verified rather than assumed.
419
+
420
+ SPARQL updates are covered the same way in `test/parity/parity-update.test.ts`:
421
+ INSERT DATA, DELETE DATA, INSERT WHERE, DELETE WHERE, and DELETE/INSERT (plain,
422
+ typed, and language-tagged literals, fresh blank nodes per solution, named graph
423
+ templates, joins in WHERE, and composite requests) run against both engines on
424
+ identical seed stores, and the final store contents are compared. Because INSERT
425
+ DATA mints fresh blank node labels per execution (`e_<label>NN` under Comunica,
426
+ `b<random>_<N>` natively), the harness canonicalizes store contents up to blank node
427
+ relabeling — two stores pass when they agree exactly modulo label identity,
428
+ which is the SPARQL contract.
429
+
430
+ ## Benchmarking
431
+
432
+ `bench/engine_bench.ts` compares query and update execution against both
433
+ `@comunica/query-sparql-rdfjs-lite` and the Oxigraph WASM engine (`oxigraph`)
434
+ over an identical generated graph. Before timing, every run asserts that all
435
+ three engines return identical results for each query, and for updates asserts
436
+ that they produce identical final store contents after mutating fresh stores (a
437
+ move update, which a broken engine that ignores updates cannot pass). The timed
438
+ update is a self-restoring delete+insert rewrite, so iterations never drift the
439
+ benchmark stores. The reorder-chain group demonstrates the dynamic join
440
+ ordering: a three-pattern chain written in worst-case order runs ~60x faster
441
+ with reordering enabled, because the planner scans each pattern once and joins
442
+ in order of estimated cost, preferring patterns whose variables are already
443
+ bound. Timings use [mitata](https://github.com/evanwashere/mitata) through the
444
+ shared harness in `bench/bench.ts` (it runs on Bun) with the wazoo
445
+ engine as the per-group baseline:
446
+
447
+ ```bash
448
+ bun run bench
449
+ ```
450
+
451
+ ### Results
452
+
453
+ A snapshot measured with Bun 1.4.5 on Windows 11 (Intel Core Ultra 7 256V),
454
+ with the wazoo engine as the per-group baseline. Each cell is the per-iteration
455
+ average; every query is cross-verified to return identical results on all three
456
+ engines before timing (computed decimals, floats and doubles compare by value).
457
+ Timings are machine-specific and move between runs, often by 15-30% on the
458
+ sub-millisecond rows, so treat close pairs as ties. Run `bun run bench` for your
459
+ own numbers.
460
+
461
+ Core joins, 400-person graph (~2,200 quads):
462
+
463
+ | query | wazoo | comunica | oxigraph |
464
+ | ---------------------------- | ------- | -------- | -------- |
465
+ | full scan | 0.41 ms | 3.0 ms | 5.5 ms |
466
+ | join (knows × name) | 1.1 ms | 3.3 ms | 1.2 ms |
467
+ | asymmetric join | 1.1 ms | 14.9 ms | 5.9 ms |
468
+ | reorder chain, written order | 82.6 ms | 2.6 ms | 1.2 ms |
469
+ | reorder chain, planner on | 1.3 ms | — | — |
470
+ | dp-join, DP plan | 20.3 ms | 106.2 ms | 2.5 s |
471
+ | dp-join, greedy plan | 19.9 ms | — | — |
472
+
473
+ EXISTS surface, 400-person graph:
474
+
475
+ | query | wazoo | comunica | oxigraph |
476
+ | ------------------- | ------- | -------- | -------- |
477
+ | `FILTER EXISTS` | 0.27 ms | 7.6 ms | 0.41 ms |
478
+ | `FILTER NOT EXISTS` | 0.32 ms | 8.8 ms | 0.42 ms |
479
+ | nested `EXISTS` | 0.42 ms | 19.7 ms | 0.55 ms |
480
+ | nested `NOT EXISTS` | 0.45 ms | 19.7 ms | 0.54 ms |
481
+
482
+ EXISTS surface, 10,000-person graph (~55,000 quads):
483
+
484
+ | query | wazoo | comunica | oxigraph |
485
+ | ------------------- | ------- | -------- | -------- |
486
+ | `FILTER EXISTS` | 10.5 ms | 197 ms | 13.2 ms |
487
+ | `FILTER NOT EXISTS` | 9.8 ms | 194 ms | 13.6 ms |
488
+ | nested `EXISTS` | 16.9 ms | 407 ms | 15.7 ms |
489
+ | nested `NOT EXISTS` | 16.1 ms | 393 ms | 16.5 ms |
490
+
491
+ Scaling the data 25x (400 → 10,000 people) grows wazoo's EXISTS cost ~36-40x,
492
+ while nesting stays within ~1.6x of the simple case at both scales: the snapshot
493
+ is drained and indexed once per query, and each probe touches only its candidate
494
+ bucket, so nesting stays cheap relative to the dataset. Across the exists
495
+ surface wazoo is ~19-48x faster than comunica, and at parity with or ahead of
496
+ oxigraph (a compiled Rust/WASM engine with native indexes).
497
+
498
+ On the core rows wazoo is fastest on the full scan and the asymmetric join, and
499
+ the plain join is within run-to-run noise of oxigraph. The reorder chain is the
500
+ exception: in written order wazoo is far behind both references, and with its
501
+ planner on it is level with oxigraph. The two dp-join plans measure the same in
502
+ this snapshot.
503
+
504
+ Join surface, 10,000-person graph (~55,000 quads) — UNION joins 10k x 20k
505
+ bindings on the shared subject (~200M candidate pairs); OPTIONAL and MINUS join
506
+ 10k x 5k (~50M pairs). The wazoo engine's hash join probes an indexed right side
507
+ per left binding instead of scanning it:
508
+
509
+ | query | wazoo | comunica | oxigraph |
510
+ | ------------------- | ------- | -------- | -------- |
511
+ | UNION (10k x 20k) | 21.1 ms | 58.9 ms | 48.9 ms |
512
+ | OPTIONAL (10k x 5k) | 9.1 ms | 253 ms | 27.7 ms |
513
+ | MINUS (10k x 5k) | 7.5 ms | 26.3 ms | 11.3 ms |
514
+
515
+ On this surface wazoo leads all three engines, and the fan-out join scaling is
516
+ sub-quadratic. When the hash join landed (measured under Deno), the same UNION
517
+ went from ~7 s per iteration with a nested loop to ~38 ms.
518
+
519
+ The same snapshot as a chart — one row per query class, three bars per row
520
+ (wazoo green, Comunica orange, Oxigraph blue), bar length proportional to avg
521
+ ms/iter within the row:
522
+
523
+ <figure>
524
+ <img src="docs/assets/chart-latency.svg" alt="Bar chart of average query latency per query class for wazoo, Comunica, and Oxigraph">
525
+ <figcaption><b>Fig — Query latency by class.</b> One row per query class;
526
+ three bars per row, bar length proportional to average ms/iter within the
527
+ row (each row normalized to its slowest engine — lower is better). The
528
+ planner-only rows (3-pattern chain, planner on) have a single wazoo bar;
529
+ Comunica and Oxigraph have no reordering equivalent. Snapshot from
530
+ `bench/latency-data.json`, regenerated by `bun run bench:latency`.</figcaption>
531
+ </figure>
532
+
533
+ ### Size & memory footprint
534
+
535
+ The speed comparison is only half the story — engines also differ by orders of
536
+ magnitude in what they cost to ship and to run. A size bar chart and a memory
537
+ treemap (length/area ∝ size) summarize both:
538
+
539
+ **Library size on disk** — what a consumer must have installed:
540
+
541
+ <figure>
542
+ <img src="docs/assets/chart-library-size.svg" alt="Bar chart of engine footprints on disk">
543
+ <figcaption><b>Fig 1 — Library size on disk.</b> One bar per engine; bar
544
+ length is proportional to total installed size (values in binary MiB, share
545
+ of the combined total in parentheses). Wazoo (green) is the whole npm
546
+ package at 1.15 MiB against comunica’s 38.30 MiB closure (orange);
547
+ oxigraph (blue) sits between.</figcaption>
548
+ </figure>
549
+
550
+ | engine | on disk | contents |
551
+ | -------- | ------------ | --------------------------------------------------------------------------------------------------------------------- |
552
+ | wazoo | **1.15 MiB** | 27 files (the whole npm package: built JavaScript and types, `README.md` and the licenses); zero runtime dependencies |
553
+ | oxigraph | 8.39 MiB | WASM runtime (8.25 MiB) + JS glue/types |
554
+ | comunica | 38.30 MiB | 367 npm packages in the transitive dependency closure |
555
+
556
+ Regenerated by `bun run bench:size`. The wazoo package is **~1.15 MiB on disk
557
+ (~0.19 MiB gzipped)**; the generated parsers are about 0.76 MiB of it. The size
558
+ comes from `npm pack`, so it counts exactly the files that ship. The durable SQLite store moved to
559
+ `@worlds/sqlite` (2026-08-17), so the root import graph is server-optional.
560
+
561
+ **Peak resident memory during execution** on the 10k-person graph (55k quads),
562
+ measured in an isolated subprocess per engine (peak
563
+ `process.memoryUsage().rss` over 5 runs). Every figure includes the shared
564
+ ~51 MiB Bun runtime and dataset baseline. Resident memory is compared because
565
+ Bun reports a `heapUsed` for oxigraph's WASM memory that is larger than the
566
+ whole process:
567
+
568
+ <figure>
569
+ <img src="docs/assets/treemap-memory.svg" alt="Treemap of peak resident memory per engine and workload">
570
+ <figcaption><b>Fig 4 — Peak resident memory during execution</b> (10k-person
571
+ graph). One panel per workload (full scan, nested EXISTS); within each, the
572
+ three engines’ tiles are scaled by their peak RSS (values in MiB).</figcaption>
573
+ </figure>
574
+
575
+ | workload | wazoo | comunica | oxigraph |
576
+ | -------------------- | ----------- | -------- | ----------- |
577
+ | full scan (55k rows) | **197 MiB** | 337 MiB | 289 MiB |
578
+ | nested EXISTS | 193 MiB | 239 MiB | **187 MiB** |
579
+
580
+ Wazoo is the smallest on disk by 7-31x (1.24 vs 8.39 vs 38.25 MiB). It uses the
581
+ least memory on the full scan, and on nested EXISTS it is within a few percent
582
+ of oxigraph and below comunica.
583
+
584
+ These are machine-specific snapshots (Bun 1.4.5, Windows 11), not guarantees.
585
+ Regenerate them with `bun run bench:size` (library sizes, from the installed
586
+ packages) and `bun run bench:memory` (peak memory, spawned per engine), which
587
+ write the SVGs into `docs/assets/`.
588
+
589
+ ## Development
590
+
591
+ ```bash
592
+ bun run ci
593
+ ```
594
+
595
+ ## Query design notes
596
+
597
+ Most performance work is the engine's job and happens automatically: greedy join
598
+ reordering, hash joins over shared variables, the positional store index, and
599
+ the once-per-query EXISTS snapshot with indexed probes. The query shapes below
600
+ are expensive **by semantics** — the cost is proportional to the result the
601
+ query itself asks for, so no engine can make them cheap without changing the
602
+ answer. Treat them as the operator's responsibility:
603
+
604
+ - **Joins with no shared variables.** A join (BGP patterns, UNION branches,
605
+ OPTIONAL, MINUS) over disjoint variable sets is a cross product — n·m rows by
606
+ definition, per SPARQL §18.2.2's natural join on an empty key. The hash join
607
+ does not change this: the result size _is_ the cost. Correlate the sides on a
608
+ shared variable (typically the subject). The same trap applies to
609
+ `OPTIONAL { ?x <pet> ?p }` whose group shares nothing with the outer query —
610
+ every outer row merges with every group row; bind the group to the outer
611
+ solution instead.
612
+ - **Property paths with both endpoints unbound.** `?a <knows>+ ?b` walks the
613
+ path forward from every graph node, because the reachable-set has to be
614
+ computed before any solution can be formed. Binding one endpoint
615
+ (`<person1> <knows>+ ?b`) turns it into one anchored walk; reflexive forms
616
+ (`?`, `*`) additionally materialize the (node, node) pair.
617
+ - **Queries whose result is the whole store.** `SELECT * WHERE { ?s ?p ?o }`
618
+ over 55k quads materializes 55k rows; the positional index makes each pattern
619
+ scan O(bucket) instead of O(store), but the result materialization is
620
+ inherent. Bind a selective subject, push FILTERs down, or use LIMIT — the
621
+ engine evaluates everything before slicing, so a small LIMIT over a huge scan
622
+ still pays the scan (streaming is tracked as
623
+ [#74](https://github.com/wazootech/sparql-engine/issues/74)).
624
+ - **Correlated EXISTS over broad scopes.** EXISTS snapshots drain and index once
625
+ per query, and probes touch only the candidate bucket — but a correlated
626
+ `FILTER EXISTS { ?s <knows> ?who }` whose correlation variable is bound
627
+ _outside_ the EXISTS still runs once per outer solution. Bind the correlation
628
+ variable in the outer query.
629
+ - **Non-selective data shapes.** If every node is connected to every node, the
630
+ compatible-candidate set for a join _is_ the whole right side, and no join
631
+ strategy beats scanning it. Prefer selective predicates on the hot path —
632
+ indexes help only when buckets are smaller than the full set.
633
+
634
+ ## Prior art & attribution
635
+
636
+ This engine's performance work (join reordering, hash joins, positional indexes,
637
+ streaming, EXISTS snapshots) and spec-driven semantics build on published
638
+ research, standards, and reference books. Citations appear inline in the source
639
+ at each technique site as stock JSDoc `@see` / `{@link}` tags; this section
640
+ collects them for reference and is kept in sync by convention: any PR that adds
641
+ a citation to the code adds the matching line here (and vice versa).
642
+
643
+ ### Research papers
644
+
645
+ - Bernstein, P. A., & Chiu, D.-M. W. "Using Semi-Joins to Solve Relational
646
+ Queries." Journal of the ACM 28(1), 1981, pp. 25–40.
647
+ https://doi.org/10.1145/322234.322238
648
+ - Goldberg, D. "What Every Computer Scientist Should Know About Floating-Point
649
+ Arithmetic." ACM Computing Surveys 23(1), 1991, pp. 5–48.
650
+ https://doi.org/10.1145/103162.103163
651
+ - Graefe, G. "Query Evaluation Techniques for Large Databases." ACM Computing
652
+ Surveys 25(2), 1993, pp. 73–170. https://doi.org/10.1145/152610.152611
653
+ - Graefe, G. "Volcano — An Extensible and Parallel Query Evaluation System."
654
+ IEEE Transactions on Knowledge and Data Engineering 6(1), 1994, pp. 120–135.
655
+ https://doi.org/10.1109/69.273032
656
+ - Gupta, A., & Mumick, I. S. "Maintenance of Materialized Views: Problems,
657
+ Techniques and Applications." IEEE Data Engineering Bulletin 18(2), 1995, pp.
658
+ 3–18. https://dblp.org/rec/journals/debu/GuptaM95.html
659
+ - Hartig, O. "Foundations of RDF* and SPARQL* (An Alternative Approach to
660
+ Statement-Level Metadata in Linked Data)." Proc. 11th Alberto Mendelzon Intl.
661
+ Workshop on Foundations of Data Management (AMW), CEUR-WS Vol-1912, 2017.
662
+ https://ceur-ws.org/Vol-1912/paper12.pdf
663
+ - Kitsuregawa, M., Tanaka, H., & Yamamori, T. "Architecture and Performance of
664
+ Relational Algebra Machine GRACE." Proc. Intl. Conf. on Parallel Processing
665
+ (ICPP), 1983, pp. 241–250.
666
+ - Kostylev, E. V., Reutter, J. L., Romero, M., & Vrgoč, D. "SPARQL with Property
667
+ Paths." Proc. 14th Intl. Semantic Web Conf. (ISWC 2015), LNCS 9366, Springer,
668
+ 2015, pp. 3–18. https://doi.org/10.1007/978-3-319-25007-6_1
669
+ - Neumann, T., & Weikum, G. "RDF-3X: A RISC-Style Engine for RDF." Proc. VLDB
670
+ Endowment 1(1), 2008, pp. 647–659. https://doi.org/10.14778/1453856.1453927
671
+ - Pérez, J., Arenas, M., & Gutierrez, C. "Semantics and Complexity of SPARQL."
672
+ ACM Transactions on Database Systems 34(3), 2009, art. 16.
673
+ https://doi.org/10.1145/1567274.1567278
674
+ - Selinger, P. G., Astrahan, M. M., Chamberlin, D. D., Lorie, R. A., & Price, T.
675
+ G. "Access Path Selection in a Relational Database Management System." Proc.
676
+ ACM SIGMOD, 1979, pp. 23–34. https://doi.org/10.1145/582095.582099
677
+ - Sellis, T. K. "Multiple-Query Optimization." ACM Transactions on Database
678
+ Systems 13(1), 1988, pp. 23–52. https://doi.org/10.1145/42201.42203
679
+ - Shapiro, L. D. "Join Processing in Database Systems with Large Main Memories."
680
+ ACM Transactions on Database Systems 11(3), 1986, pp. 239–264.
681
+ https://doi.org/10.1145/6314.6315
682
+ - Stocker, M., Seaborne, A., Bernstein, A., Kiefer, C., & Reynolds, D. "SPARQL
683
+ Basic Graph Pattern Optimization Using Selectivity Estimation." Proc. 17th
684
+ Intl. World Wide Web Conf. (WWW '08), ACM, 2008, pp. 595–604.
685
+ https://doi.org/10.1145/1367497.1367578
686
+ - Weiss, C., Karras, P., & Bernstein, A. "Hexastore: Sextuple Indexing for
687
+ Semantic Web Data Management." Proc. VLDB Endowment 1(1), 2008, pp. 1008–1019.
688
+ https://doi.org/10.14778/1453856.1453965
689
+
690
+ ### Standards & RFCs
691
+
692
+ - Harris, S., & Seaborne, A. (eds.). "SPARQL 1.1 Query Language." W3C
693
+ Recommendation, 21 March 2013. https://www.w3.org/TR/sparql11-query/
694
+ - Malhotra, A., Melton, J., & Walsh, N. (eds.). "XQuery 1.0 and XPath 2.0
695
+ Functions and Operators (Second Edition)." W3C Recommendation, 14
696
+ December 2010. https://www.w3.org/TR/2010/REC-xpath-functions-20101214/
697
+ - National Institute of Standards and Technology. "Secure Hash Standard (SHS)."
698
+ FIPS PUB 180-4, August 2015.
699
+ https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
700
+ - "RDF 1.2 Concepts and Abstract Data Model." W3C Candidate Recommendation, 7
701
+ April 2026. https://www.w3.org/TR/rdf12-concepts/
702
+ - Rivest, R. "The MD5 Message-Digest Algorithm." IETF RFC 1321, April 1992.
703
+ https://www.rfc-editor.org/rfc/rfc1321
704
+
705
+ ### Reference books
706
+
707
+ - Aho, A. V., Sethi, R., & Ullman, J. D. "Compilers: Principles, Techniques, and
708
+ Tools." Addison-Wesley, 1986, ch. 4 (syntax analysis, LR parsing).
709
+ - Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. "Introduction to
710
+ Algorithms," 3rd ed. MIT Press, 2009, §22.2 (breadth-first search).
711
+
712
+ ## Releases
713
+
714
+ Every merge to `main` runs the Publish workflow. It builds and packs the
715
+ package, installs that exact file on Node.js, Bun and Deno, and publishes it
716
+ **only when `package.json`'s `version` is not on npm yet**; it asks the registry
717
+ rather than the tree:
718
+
719
+ - **Release PR** (bumps `version`): the Publish job publishes the new version.
720
+ - **Routine PR** (no bump): the Publish job skips with a notice — this is
721
+ expected, not an error.
722
+
723
+ To ship a release, bump `version` in `package.json` (minor for additive public
724
+ API, patch for fixes) in the same PR that should publish. A version with a suffix,
725
+ such as `0.6.0-rc.0`, goes to the `next` tag instead of `latest`.
726
+
727
+ npm accepts the publish because this repository's `publish.yml` is the package's
728
+ trusted publisher, so there is no npm token to store or rotate. After publishing,
729
+ a second job installs the new version from npm and checks it. If only that job
730
+ fails, re-run it on its own.