Skip to content

feat: RDF 1.2 / SPARQL 1.2 edge annotations + GQL query operators in JSON-LD - #1357

Merged
bplatz merged 26 commits into
mainfrom
pr/2-rdf12-annotations
Jun 23, 2026
Merged

bplatz merged 26 commits into
mainfrom
pr/2-rdf12-annotations

Conversation

@bplatz

@bplatz bplatz commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

RDF 1.2 / SPARQL 1.2 edge annotations, plus the shared GQL query operators they ship alongside, exposed in JSON-LD query. Stacked on the base query-planner PR; the Cypher front-end (parser, lowering, cypher-json) lands in a follow-up PR.

Edge annotations (RDF 1.2 / SPARQL 1.2)

Attach properties to a relationship — the (subject, predicate, object) edge — without hand-modeling an intermediate node. Reads correctly as property-graph "edge properties" or as SPARQL "annotations on a quoted triple".

  • Annotation-arena storage, indexer build/seal + GC, attachment novelty
  • Core edge / annotation-index model + per-graph annotation stats
  • SPARQL 1.2 quoted-triple annotation surface ({| ... |}, ~, <<( ... )>>, VERSION "1.2") on query and UPDATE
  • JSON-LD @annotation / @edge write surface (incl. literal-valued and named-graph edges)
  • Planner edge-annotation expansion + read-side firewall for system predicates
  • CSV (neo4j-admin header convention) import to RDF 1.2 annotations

GQL query operators (exposed in JSON-LD)

Generic query constructs that came with the property-graph work, now reachable from JSON-LD (not just the Cypher front-end):

  • unwind + range / list — expand a computed list into rows (e.g. dense / gap-filled series)
  • collect / collect-distinct — gather group values into a list; inverse of unwind
  • List functions — size, head, last, tail, reverse, nth
  • shortestPath / allShortestPaths + nodes / pathPairs
  • Alternation-transitive property paths (a|b)* via @path

Docs

  • Edge-annotation concept, cookbook, vocabulary, and storage-internals design docs
  • A new Query Patterns cookbook with realistic recipes (dense series, collect/unwind round-trip, shortest path)
  • JSON-LD query reference sections for every new operator

Each operator and edge-annotation surface has integration test coverage.

bplatz added 9 commits June 19, 2026 11:28
…rators

RDF 1.2 edge-annotation support plus the shared GQL query operators it ships
with, layered on the base query-planner work. Excludes the Cypher front-end
(parser/lowering/cypher-json), which lands in a follow-up PR.

Edge annotations (RDF 1.2 / SPARQL 1.2):
- annotation-arena storage, indexer build/seal + GC, attachment novelty
- core edge / annotation-index model + per-graph annotation stats
- SPARQL 1.2 quoted-triple annotation parse + lowering surface
- transact edge-annotation write/retract path
- planner edge-annotation expansion + read-side f:reifies* firewall
- CSV (neo4j-admin header convention) import to RDF 1.2 annotations

Shared query operators (engine + IR):
- UNWIND, shortestPath / allShortestPaths (bidirectional BFS)
- collect + list functions, first-class Binding::List
- alternation-transitive property paths

JSON-LD parse surface for the operators is wired in a follow-up commit.
…bulary

- Remove the broken concepts/cypher.md SUMMARY link and reframe Cypher
  front-end references (out of scope for this PR) to property-graph terms;
  keep the @edge alias and lpgEdgeLifecycle option.
- Add guides/cookbook-edge-annotations.md: task-oriented walkthrough
  (attach, query inline/annotation-rooted, parallel edges, provenance,
  update, retract cascade, SPARQL 1.2 equivalents, named-graph writes).
- Document the seven reserved f:reifies* predicates in reference/vocabulary.md.
The reserved f:reifies* predicates are an internal storage encoding; a
customer only needs to know they exist as a constraint (reserved, can't
be hand-written, hidden from scans). Restrict mentions to that firewall
rule plus the canonical vocabulary listing and the design doc.

- Describe the retract cascade behaviorally ("the attachment linking the
  annotation to the edge") instead of naming the f:reifies* bundle.
- Trim the seven-predicate enumeration out of the JSON-LD query doc; link
  to the vocabulary reference instead.
- Condense the concept doc's bulk-import/arena-build internals to a one-
  line pointer to the design doc; reframe graph/lang stamping in behavioral
  terms.
- Point the duplicated firewall caveats at the single vocabulary entry.
Expose the UNWIND operator and the `range`/`list` list-producing functions in
JSON-LD query syntax (the engine already supported them; this wires the parse
surface).

- `["unwind", "?v", <list-expr>]` expands a list-valued expression into one row
  per element; empty/unbound/non-list yields zero rows.
- `(range start end [step])` — inclusive integer sequence; `(list a b …)` — list
  literal. Both usable in bind/select too.
- eval: a bare variable holding a List binding now evaluates to that list
  (previously collapsed to Unbound via ComparableValue), so `UNWIND ?listVar`
  and the collect→unwind round-trip preserve the list.

Headline use is a row generator over a computed list — e.g. a dense/gap-filled
series: `UNWIND range(2019,2023)` + OPTIONAL + GROUP BY yields a count for every
year including the empty ones, which neither VALUES (constants) nor triple
patterns (stored data) can produce.

Docs: UNWIND section + List Value Functions in docs/query/jsonld-query.md.
Tests: it_query_unwind.rs (range, list literal, dense-series gap-fill, empty
range, bound-list variable).
Expose the `collect` and `collect-distinct` select aggregates in JSON-LD
(engine already had AggregateFn::Collect; this wires parse + lowering +
aggregate-name detection).

- `(collect ?x)` gathers a group's non-null values into a first-class list
  value (rendered as a JSON array), keeping row-level duplicates.
- `(collect-distinct ?x)` deduplicates within the group.

collect is the inverse of UNWIND: a collect result is a list value, so a
sub-select that collects can be re-expanded with an outer `unwind` (validated
end-to-end). Note RDF stores identical triples once, so collect vs
collect-distinct differ only when a value reaches the aggregate on multiple
solution rows (e.g. via a join).

Docs: collect/collect-distinct in the Aggregation Functions reference, with the
RDF set-semantics note and the collect/unwind relationship.
Tests: it_query_collect.rs (collect keeps dups, collect-distinct dedups,
collect→unwind round-trip via sub-select).
Map the list accessor/transform functions in JSON-LD expression syntax (engine
already evaluates them; this wires the names):

- `(size ?l)` element count; `(head ?l)` / `(last ?l)` ends; `(nth ?l ?i)`
  0-based index (negatives from the end, out-of-range → null).
- `(tail ?l)` / `(reverse ?l)` return lists; compose with accessors, e.g.
  `(head (reverse ?xs))`.

Operate on lists from `range`, `list`, or `collect`. Usable in bind/filter/select.

Docs: List Value Functions expanded with accessors/transforms.
Tests: it_query_list_functions.rs (all six, composition, negative index,
out-of-range → null).
…N-LD

Expose anchored shortest-path search and the path-value functions in JSON-LD
(engine already had Pattern::ShortestPath + ShortestPathOperator; this wires the
where-clause surface):

- ["shortestPath", {from,to,via,bind,direction,minHops,maxHops}] binds one
  shortest path; ["allShortestPaths", {...}] binds every minimal-length path.
  Endpoints are vars or constant IRIs; via is a single predicate; direction is
  out|in|both. An unknown predicate IRI yields no rows.
- (nodes ?p) — ordered node list along the path (a list value, so it feeds
  unwind / list functions); (path-pairs ?p) — consecutive node pairs (size =
  hop count).

Docs: Shortest Path section + path-value functions in docs/query/jsonld-query.md.
Tests: it_query_shortest_path.rs (single/all paths, nodes+size, pathPairs edge
count, nodes unwound with ordered endpoints, maxHops bound, unknown predicate).
…@path

JSON-LD `@path` now lowers `(a|b…)+` / `(a|b…)*` to an alternation-transitive
PropertyPathPattern, matching the SPARQL surface and the engine's existing
multi-predicate closure (the operator already followed any listed predicate per
hop; only the JSON-LD lowering rejected it via expect_simple_iri).

Branches under the transitive modifier must be simple forward predicate IRIs;
inverse/compound branches still error, mirroring SPARQL lowering. Adds string-
and array-form tests plus the inverse-branch rejection case, and documents the
operator in the JSON-LD query reference.
A task-oriented guide showing realistic end-to-end recipes for the new
operators, addressing the gap where examples lived only in the reference:

- dense / gap-filled series (unwind + range + optional) — the "every year even
  with no data" pattern
- collecting values into lists; collect-distinct; the collect→unwind round-trip
- working with list values (size/head/last/nth/tail/reverse), composed
- generating sequences; shortest path + hop count + node listing

Wired into SUMMARY.md and the guides README. Cross-links property paths vs
shortestPath and edge annotations.

Also adds a regression test for the chained-bind list-value example so the
cookbook stays accurate (a list bound by `bind` survives later binds that read it).
@bplatz
bplatz requested review from aaj3f and zonotope June 19, 2026 19:58
Base automatically changed from pr/1-query-planner to main June 20, 2026 11:48
bplatz added 4 commits June 20, 2026 07:55
…e output

reorder_patterns' subquery-output deferral treated every uncorrelated
sub-SELECT's body-produced SELECT vars as WITH-pipeline outputs that later
siblings must wait for. For a grouped lookup like BSBM BI-8's
`avg(?price) ... GROUP BY ?product`, the GROUP BY key ?product — already
established by the preceding offer scan — was misclassified as a pipeline
output, deferring that scan behind a per-?product average lookup and blowing
the plan up (0.26s -> >13 min hang at 1M).

A shared GROUP BY key is a join key, not a pipeline output. Narrow the output
set (new subquery_pipeline_output_vars) to drop any GROUP BY key another
sibling also produces. Ungrouped Cypher WITH [DISTINCT] producers are
unaffected, so the producer-placement win is preserved. Verified end-to-end:
BSBM BI-8 q8 returns identical rows in 0.16s.
…ests

- regression-budget.json: add entries for the annotation_hydration and
  annotation_planner benches (declared in Cargo.toml but unbudgeted), which
  failed the workspace_reconcile gate in both the test and bench-gate jobs.
- integration.rs: remove cypher_query_and_write_round_trip and
  cypher_parameters_via_json_envelope — they exercise the `--cypher` /
  `--format cypher` CLI surface that lands in the follow-up PR, not this one.
A single deadlocked test (it_import_remote::remote_import_matches_local_flake_count)
ran for the full 6h GitHub job ceiling and got cancelled, because nextest's
default behavior only warns on slow tests and never kills them, and the test
job had no timeout-minutes cap.

- .config/nextest.toml: slow-timeout with terminate-after so a hung test is
  killed and reported as TIMEOUT after 6 min, letting the rest of the suite
  finish under --no-fail-fast instead of holding the runner.
- ci.yml: add a 45 min job-level backstop on the test job.
- policy_integration.rs: #[ignore] cypher_read_enforces_policy. It posts raw
  Cypher to an application/cypher HTTP endpoint that is not yet implemented
  (Cypher/GQL operators are only expressible inside JSON-LD query bodies);
  the raw body falls through to JSON parsing and 400s deterministically.
bplatz added 3 commits June 22, 2026 21:33
bench-gate was cancelled at its 25m cap while still in `cargo bench --no-run`
on a cold cache — the workspace's bench set (now including the consensus,
search-service, and search-httpd crates plus bollard/testcontainers deps)
no longer compiles in release within 25m cold. Give it the same headroom as
the test job; warm-cache runs stay well under it.
…0k case

The bench hardcoded counts [1, 100, 10_000] and ignored FLUREE_BENCH_SCALE.
Seeding N annotations costs N sequential commits with per-commit work that
scales with accumulated novelty (O(N²)), so the 10k case seeds for many
minutes and never returned within bench-gate's budget — the job was cancelled
mid-smoke-run on annotation_hydration. Honor current_scale() like the other
benches (fulltext_query.rs): Tiny (the per-PR gate, run via --test) now caps at
[1, 100]; Small and larger keep the full curve for real measurement runs.
bench-gate runs each crate's lib unit tests under the release `bench`
profile (debug_assertions off), where `debug_assert!` is stripped. Three new
annotation-arena tests assert that a debug_assert fires, so `#[should_panic]`
failed ("did not panic as expected") and the gate exited 101 after ~30m.
Gate them on `#[cfg(debug_assertions)]` — the same idiom binding.rs already
uses — so they run (and pass) in the debug `test` job and are simply absent
from the release bench build.

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is really exciting, although admittedly it's a lot of code to review. Almost everywhere I looked it was well-gated to not affect normal paths, though, so I think it's a lot lower risk than I initially worried it would be. A few remarks below, but otherwise things look correct & good

Comment thread fluree-db-transact/src/parse/jsonld.rs Outdated
Comment on lines +107 to +153
let mut lowered = json.clone();

// Pull `lpgEdgeLifecycle` from the transaction's `opts` block when
// the programmatic `TxnOpts::lpg_edge_lifecycle` is unset. This
// mirrors how `strictCompactIri` is read from the JSON when the
// builder doesn't override it.
//
// Resolved BEFORE the lowering passes so they can branch on it —
// an empty `@annotation: {}` is a no-op in RDF mode but mints a
// fresh property-less annotation subject in LPG mode (a Cypher
// relationship retains identity even without properties).
if opts.lpg_edge_lifecycle.is_none() {
opts.lpg_edge_lifecycle = json
.as_object()
.and_then(|m| m.get("opts"))
.and_then(|v| v.as_object())
.and_then(|o| o.get("lpgEdgeLifecycle"))
.and_then(Value::as_bool);
}
let lpg_mode = opts.lpg_edge_lifecycle.unwrap_or(false);

// Two-pass lowering for UPDATE transactions:
//
// 1. Run the user-authored `f:reifies*` firewall against the
// *original* document. Both passes synthesize `f:reifies*`
// IRIs internally; running the firewall a second time would
// falsely flag those.
// 2. Run the delete-clause pre-pass. It rewrites `@annotation`
// blocks inside `delete:` into explicit `f:reifies*` retract
// templates so the assertion-shaped lowering below doesn't
// synthesize spurious sibling nodes.
// 3. Run the standard assertion-shaped lowering on the rest of
// the document.
//
// Insert / Upsert paths skip step 2 — their docs don't carry a
// `delete` key, so the pre-pass would be a structural no-op
// anyway.
let top_ctx = super::edge_annotations::top_level_context(&lowered)?;
super::edge_annotations::run_user_authored_reifies_firewall(&lowered, &top_ctx)?;
if matches!(txn_type, TxnType::Update) {
super::edge_annotations::lower_delete_annotation_blocks(&mut lowered)?;
}
super::edge_annotations::lower_edge_annotations_after_firewall(
&mut lowered,
&top_ctx,
lpg_mode,
)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In your sibling changes to import.rs (i.e. line 962), the same work is gated by jsonld.contains("@annotation") || …("@edge") || …("@reifies"). But here, non-annotated transact ops (possibly large ones) pay for the large payload clone and the two tree walks.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 73845c4e555b41838906edd8e7ef0b1fc43328db. The firewall now runs read-only on the original document unconditionally (it is the security guard), and only the payload clone + lowering walks are gated — on a new document_has_annotation_keys scan — so a non-annotated transaction skips them.

Comment thread fluree-db-transact/src/import.rs Outdated
Comment on lines +962 to +969
if jsonld.contains("@annotation") || jsonld.contains("@edge") || jsonld.contains("@reifies")
{
let top_ctx = crate::parse::edge_annotations::top_level_context(&doc)?;
crate::parse::edge_annotations::run_user_authored_reifies_firewall(&doc, &top_ctx)?;
crate::parse::edge_annotations::lower_edge_annotations_after_firewall(
&mut doc, &top_ctx, false,
)?;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to worry about the scenario where, for example, https://ns.flur.ee/db#reifiesObject, is used instead of the keyword? Or should the firewall always run on the expanded form?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 73845c4e555b41838906edd8e7ef0b1fc43328db. The firewall gate is now deliberately broader than the lowering gate — it also fires on the bare reifies token, so a fully-expanded https://ns.flur.ee/db#reifies* IRI (which carries no @-keyword) can no longer bypass it on the bulk-import path. Regression test added.

Comment thread fluree-db-api/src/csv_import.rs Outdated
Comment on lines +170 to +171
CsvType::Date => typed_literal(raw.trim(), "date"),
CsvType::DateTime => typed_literal(raw.trim(), "dateTime"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:int, :double, and :boolean return BadValue on malformed inputs. Do we need parse-or-BadValue handling on these two as well?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 045301625b9fd9c8feab4a3b1aad262bcc4e55f1. :date/:datetime cells now validate against the same temporal parsers the downstream pipeline uses, returning BadValue on malformed input — matching :int/:double/:boolean.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are a few places in here (lines 319, mint_iri() at 282) where there's a direct xform into format!("{base_iri}{name}"). A :TYPE cell containing http://evil/p, spaces,
#, or / produces malformed or namespace-escaping IRIs (e.g. predicate
http://example.org/http://evil/p; an id value ../../x escapes the id space, etc.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in da902f131d2fb3b6e9fce04204a2ee2b749dfee3. Cell-derived IRI segments (id / :TYPE / :LABEL values) are now percent-encoded — whitespace/controls, the RFC 3987-forbidden ASCII, and the structural delimiters (/ # ? [ ] @) — so a value cannot break IRI syntax or escape base_iri (e.g. http://evil/p, ../../x). Schema-declared column names are unchanged.

bplatz added 6 commits June 23, 2026 06:19
…ated txns

Addresses review feedback on the RDF 1.2 edge-annotation PR.

The JSON-LD bulk-import path gated the user-authored f:reifies* firewall
behind the same @annotation/@edge/@reifies presence check used for
lowering. A document written with the fully-expanded
https://ns.flur.ee/db#reifies* IRI carries none of those keywords, so the
firewall was skipped and the import could inject system facts directly --
a bypass the transact path does not have. Broaden the firewall gate to the
bare `reifies` token while keeping the (mutating) lowering gated on the
keywords. Adds a regression test on the import path.

Conversely, the transact path cloned the entire payload and ran both
rewrite walks on every transaction, annotated or not. Run the read-only
firewall on the original document (it is the security guard, so it must
always run) and only clone + lower when an annotation block is actually
present, via the new document_has_annotation_keys scan.
Addresses review feedback: `:int`/`:double`/`:boolean` columns reject
malformed cells with BadValue, but `:date`/`:datetime` wrapped the raw
string in a typed `@value` object with no parse check, silently producing
an invalid typed literal. Validate against the same temporal parsers the
downstream pipeline uses, so a value accepted here is one accepted later.
…otations

- Add docs/ai hub for the AI use case, tying together Agent JSON, the MCP
  server, Fluree Memory, vector/BM25 search, and reasoning; link it from the
  root README, docs landing page, and SUMMARY.
- Remove the proposed/draft reasoning roadmap design docs (reasoning-roadmap,
  reasoning-a2-reasoned-head) so design/ holds reference docs only; trim the
  forward-looking sections from nameservice-schema-v2.
- Reconcile the design index and SUMMARY with the directory: add the missing
  edge-annotations and spatial-index entries.
- Document RDF 1.2 / SPARQL 1.2 edge annotations across the README, docs
  landing page, and datatypes concept doc; refresh the README intro, install,
  and benchmark highlights (full-Wikidata WGPB result).
Addresses review feedback: id / :TYPE / :LABEL cell values were concatenated
straight onto base_iri, so a value containing spaces, `/`, `#`, or an embedded
`http://...` produced a malformed or namespace-escaping IRI (e.g. predicate
`http://example.org/http://evil/p`, or an id `../../x` climbing out of the id
space). Percent-encode each cell-derived segment (whitespace/controls, the
RFC 3987-forbidden ASCII, and the structural delimiters that allow escape) so
every value stays a single segment under base_iri. Schema-declared column
names are unchanged. Adds tests.
bplatz added a commit that referenced this pull request Jun 23, 2026
pr/2 left this Cypher-over-HTTP policy regression test #[ignore]'d because the
application/cypher transport wasn't implemented (#1357). pr/3 added that route
(execute_cypher_ledger with policy wrapping), so the test now passes — un-ignore
it and refresh the stale doc. Not a duplicate: pr/3's cypher_http_integration.rs
has no policy coverage.
bplatz added 2 commits June 23, 2026 08:16
The embedded f:query is serialized to a standalone JSON string with no
@context, so the compact `ex:NeverMatches` could not resolve and the
policy query failed to parse. Use the full IRI form, matching the
convention in the other f:query policy tests.
The full-rebuild staging `index_dir` was keyed only on the ledger id,
while `run_dir` already carried the unique session id. Concurrent
rebuilds of the same ledger therefore shared one on-disk staging tree of
content-addressed leaf/sidecar/branch artifacts. Because `std::fs::write`
is not atomic, one rebuild's upload read-back could observe a file
another rebuild was mid-writing, surfacing as a "CID verification
failed" error (seen intermittently on CI as a history-sidecar mismatch
during index rebuild).

Scope `index_dir` to the session id like `run_dir`, and remove it on
completion. The canonical artifacts live in the ContentStore after
upload, so the staging tree is purely ephemeral.
Silences clippy::field_reassign_with_default in PR-touched test code.
bplatz added a commit that referenced this pull request Jun 23, 2026
pr/2 left this Cypher-over-HTTP policy regression test #[ignore]'d because the
application/cypher transport wasn't implemented (#1357). pr/3 added that route
(execute_cypher_ledger with policy wrapping), so the test now passes — un-ignore
it and refresh the stale doc. Not a duplicate: pr/3's cypher_http_integration.rs
has no policy coverage.
@bplatz
bplatz merged commit 52307e4 into main Jun 23, 2026
2 checks passed
@bplatz
bplatz deleted the pr/2-rdf12-annotations branch June 23, 2026 13:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants