Skip to content

refactor(graph-ir): mint every reserved blank-node label through one helper - #2169

Merged
bplatz merged 4 commits into
mainfrom
refactor/reserved-blank-labels
Oct 30, 2026
Merged

bplatz merged 4 commits into
mainfrom
refactor/reserved-blank-labels

Conversation

@bplatz

@bplatz bplatz commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

From the review of #2156: the rule that keeps minted blank-node labels out of the label space a user can write was applied minter by minter. Nine minters already use the same -{kind}{n} spelling, and each kept its own copy of the reasoning. They now call one helper, so a new minter gets the rule by calling it. Cypher's CREATE labels, which didn't follow the rule and could fuse nodes, now go through the helper too.

Change

fluree_graph_ir::syntax::reserved_blank_label(kind, n) returns -{kind}{n}. A BLANK_NODE_LABEL can't start with -, so no one can write the label. - is legal mid-label, so a stored fdb-{scope}-{label} id that holds it serializes as written. A debug build checks every label the helper returns against both halves of that rule, so a caller passing a kind or n that breaks it fails its own tests.

Callers:

  • SPARQL parser: -bnpl, -coll, -reif.
  • SPARQL UPDATE lowering: -anon, -ann.
  • Turtle sinks: -b{N} in FlakeSink, TemplateSink and fluree-graph-ir's collector sink, and -b{chunk}-{N} in ImportSink.
  • TriG annotation reader: -r{N}.
  • Cypher CREATE: -cyv{var}, -cya{start}_{end}, -cyr{var} and -cye{N}, through lower_cypher_update::cypher_blank_label. The write RETURN and sequential writes rebuild labels with the same function.

Every label except Cypher's is byte-for-byte what it was, so no stored id changes. fluree-db-sparql now depends on fluree-graph-ir. The lockfiles outside the workspace (testsuite-sparql, testsuite-shacl, wasm-probe) each gain that one line.

Cypher

Cypher built its labels as cy_{var}, cy_rel_{var}, cy_anon_{start}_{end} and cy_ann_{n}. The variable part is the user's, so a variable could spell another form's label, and the two nodes fused:

  • CREATE (:A), (anon_7_11:C) stored one node typed both A and C.
  • CREATE (rel_r:P)-[r:KNOWS]->(b:Q) made rel_r its own edge's annotation.
  • CREATE (ann_0:R)-[:KNOWS]->(c:S) fused ann_0 with the anonymous edge's annotation.

Each form now has its own three-letter kind, so none can spell another's label. A backticked variable name can hold any character, so names are encoded: ASCII alphanumerics stay as written, and every other byte, _ included, becomes _ and two hex digits. Any name gives a legal label, and two names never give the same one. A Cypher write takes a fresh skolem id every time, so no stored id has to be reached through the old spelling.

Not in this PR

  • JSON-LD's anonymous nodes use _:b{N} and re-parse when a user's label collides.
  • JSON-LD's annotation nodes use _:fluree_ann_N and refuse that prefix in user labels.

Users can write both spellings, and both are part of a stored blank node's identity under upsert and sync. Moving them to - would change existing ledgers' ids, so it needs its own decision.

The _:[]{N} names for DELETE WHERE and query variables are never stored, so they stay as they are.

Testing

  • a_reserved_label_cannot_be_written_but_serializes_in_a_stored_id checks both halves of the rule. With the helper's - removed, it fails. So do the existing mint checks in fluree-graph-ir's sink, the Turtle parser and the SPARQL parser.

  • a_label_that_breaks_the_rule_fails_in_a_debug_build checks that the debug-build check catches a label ending in ..

  • Stored spellings pinned. Two labels are part of stored identity across writes, and until now only their leading - was pinned:

    • anonymous_nodes_mint_the_labels_an_upsert_resolves_by pins TemplateSink's _:-b1, _:-b2, which a content-scoped upsert resolves by.
    • anonymous_nodes_mint_the_ids_a_reimport_agrees_on pins ImportSink's fdb-doc--b3-1, fdb-doc--b3-2, which a re-import agrees on.

    Both fail when the kind is renamed.

  • Cypher. a_variable_name_never_spells_another_label checks the four forms never collide and that encoded names, backticked ones included, are legal labels. transact_cypher_variables_never_spell_a_minted_label runs the three statements above and a backticked `my node`, checking labels and ids through Cypher reads. It fails on each case under the old spelling.

…helper

The SPARQL parser, SPARQL UPDATE lowering, the Turtle sinks and the TriG
annotation reader each built their `-{kind}{n}` label by hand, with a
comment explaining the `-`. They now call
fluree_graph_ir::syntax::reserved_blank_label. Its test checks both
halves of the rule: no one can write the label, and a stored `fdb-…` id
that holds it serializes. The labels themselves are unchanged.

@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.

@bplatz thank you for picking this up — it's the shape I was hoping for, and at a design level no pushback: one helper, the reasoning in one doc comment instead of nine paraphrases, and a test that checks both halves of the rule. I minted through every surface I could reach at the merge base and at this head and diffed the stored labels, and the "no stored id changes" claim holds, including the content-scoped upsert ids and the document-scoped import ids.

On the class: the JSON-LD _:b{N} and _:fluree_ann_N carve-out reads right to me, since moving them would change what a re-upsert of an existing payload resolves to, and the _:[]{N} variable names are never stored. There is one more minter outside the helper that the body doesn't list, though, and it's the one that actually collides today: Cypher's _:cy_* labels are built from user variable names (details inline). Since this PR is the class fix, I'd rather see Cypher come in here than stay the last instance.

Full review below:


✅ Approve with nits.

This is a tidy refactor, and it does what it says. A few things I checked:

  • Byte-for-byte identity. I minted through Turtle insert (FlakeSink), Turtle upsert (TemplateSink, content-scoped), TriG named-graph blocks, SPARQL UPDATE (-bnpl, -coll, -anon, -ann), bulk import (ImportSink, document-scoped) and the collector sink, at 66397e96e and at e677a3397, and diffed the stored labels: 15 of 15 identical, with the upsert and import ids compared exactly rather than normalized. -reif only reaches queries (UPDATE lowering refuses an anonymous << … >>), and the TriG reader's -r{N} I checked by reading.
  • The new dependency. fluree-graph-ir brings only fluree-vocab, serde, serde_json and thiserror, all already fluree-db-sparql deps, with no cycle, and fluree-db-core/fluree-db-query already had it in the default build. Every tracked lockfile that contains fluree-db-sparql gains the one edge; the other two (fluree-sql-bridge, scripts/local/load) don't contain it. wasm32 and wasm-smoke are green.
  • The tests have teeth. With the helper's - removed, seven tests across four crates go red: the new a_reserved_label_cannot_be_written_but_serializes_in_a_stored_id, the collector, FlakeSink and RDF-text mint checks, the Turtle parser's, the SPARQL parser's test_minted_blank_node_labels_start_with_a_dash, and test_blank_node_counter.

Two inline notes: the Cypher labels above (should address), and an optional way to keep the helper's guarantee for whoever calls it next.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ this is the shared mechanism the minters were each re-deriving; one label spelling, one doc comment, one test.
  • Performance (speed first, memory second): ✔ the same format! behind a function call, once per anonymous node. No performance-degradation risk.
  • Deployment targets: ✔ n/a — a label spelling, unchanged byte for byte; the new dependency builds for wasm32.
  • Testing: ✔ the new test runs by name in this head's nextest run, and the existing per-surface mint checks all follow the helper (see above).
  • Conventions: ✔ self-describing title and a multi-line commit body; the out-of-workspace lockfiles are updated with the crate.

Verified locally at e677a3397: the label probe at both commits, the mutation above, and the Cypher probe described inline.

Approving so you can merge when ready, but I'd love to see the Cypher labels come in with it.

/// user writes is one and a minted node never merges with a written one.
/// `-` is legal mid-label, so a stored id holding it (`fdb-{scope}-{label}`)
/// is a `BLANK_NODE_LABEL` and serializes as written.
pub fn reserved_blank_label(kind: &str, n: impl std::fmt::Display) -> String {

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.

🟠 Should address: Cypher's created-node labels are still outside the helper, and they collide with user variable names today.

fluree-db-transact/src/lower_cypher_update.rs mints _:cy_{var} (:1976), _:cy_anon_{start}_{end} (:1983), _:cy_rel_{var} (:1757) and _:cy_ann_{n} (:1990). The variable part is the user's, so a variable name can spell a minted label, and both then skolemize to one node.

I ran these at this head (the base behaves the same):

  • CREATE (:A), (anon_7_11:C) stores one node typed both A and C;
  • CREATE (rel_r:P)-[r:KNOWS]->(b:Q) makes the node rel_r its own edge's reifier (cy_rel_r f:reifiesSubject cy_rel_r);
  • CREATE (ann_0:P)-[:KNOWS]->(b:Q) fuses ann_0 with the anonymous edge's reifier.

It isn't introduced here, and those variable names are unusual, but it's silent node fusion, and it's the one instance of this class the body doesn't list. Cypher's skolem id is fresh per write (fresh_skolem_txn_id), so changing the spelling moves no stored id. The spellings are repeated in fluree-db-api/src/cypher_write.rs:731-733 (RETURN reconstruction) and fluree-db-api/src/cypher_seq.rs:541,550, so I think the fix is one Cypher label function on top of reserved_blank_label, with a distinct kind per form (variable, anonymous node, relationship variable, anonymous relationship) and no kind a prefix of another, since the suffix is the user's, used in all three places. If you agree, I'd rather see it here than as the class's last loose end.

Commenting here because fluree-db-transact/src/lower_cypher_update.rs is not in this diff.

Comment thread fluree-graph-ir/src/syntax.rs Outdated
/// `-` is legal mid-label, so a stored id holding it (`fdb-{scope}-{label}`)
/// is a `BLANK_NODE_LABEL` and serializes as written.
pub fn reserved_blank_label(kind: &str, n: impl std::fmt::Display) -> String {
format!("-{kind}{n}")

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.

🟡 Optional: two cheap ways to keep this guarantee for the next caller, since nothing stops one from passing a kind or n that breaks it (reserved_blank_label("b", "0.") ends in ., and a kind with # or [ is #1956 again).

First, a debug_assert! here, so every caller's own tests check the contract (illustrative):

let label = format!("-{kind}{n}");
debug_assert!(
    !is_blank_node_label(&label) && is_blank_node_label(&format!("x{label}")),
    "{label} is not a reserved blank-node label"
);
label

Second, exact-value pins for the two spellings that are stored identity across writes: TemplateSink's -b{N} under a content-scoped upsert or sync, and ImportSink's -b{chunk}-{N} under a document scope. I renamed ImportSink's kind to c and TemplateSink's to bn (keeping the dash) and fluree-db-transact's lib tests, it_import and it_sync_graph all stayed green, so only the leading - is pinned today. A rename there would quietly change ids: re-upserting an existing payload would mint new nodes instead of resolving to the ones it made before, and an import would stop agreeing with an earlier import of the same file.

Minor and non-blocking, but if you agree it's right I'd rather see it folded in now than lost in the backlog.

…nk-labels

# Conflicts:
#	fluree-db-transact/src/import_sink.rs
Cypher CREATE built its blank-node labels by hand: `cy_{var}`,
`cy_rel_{var}`, `cy_anon_{start}_{end}` and `cy_ann_{n}`. The variable
part is the user's, so a variable could spell another form's label, and
the two nodes then fused:

- `CREATE (:A), (anon_7_11:C)` stored one node typed both A and C.
- `CREATE (rel_r:P)-[r:KNOWS]->(b:Q)` made `rel_r` its own edge's
  annotation.
- `CREATE (ann_0:R)-[:KNOWS]->(c:S)` fused `ann_0` with the anonymous
  edge's annotation.

A backticked variable could also hold a character no blank-node label
can.

`lower_cypher_update::cypher_blank_label(CypherBlank)` now mints all
four forms through `reserved_blank_label`. Each form has its own
three-letter kind, `cyv`, `cya`, `cyr` and `cye`, so none can spell
another's label. A variable name is encoded byte by byte: ASCII
alphanumerics stay as written, and every other byte, `_` included,
becomes `_` and two hex digits. Any name gives a legal label, and two
names never give the same one.

The write `RETURN` (`cypher_write.rs`) and sequential writes
(`cypher_seq.rs`) rebuild the labels with the same function. A Cypher
write takes a fresh skolem id every time, so no stored id has to be
reached through the old spelling.

`transact_cypher_variables_never_spell_a_minted_label` runs the three
statements above and a backticked `` `my node` ``, checking labels and
ids through Cypher reads. It fails on each case under the old spelling.
The tests that matched the old spelling now match the new one.
…he stored ones

`reserved_blank_label` relied on each caller to pass a `kind` and `n`
that keep its rule: no character a label can't hold, and no trailing
`.`. A debug build now checks every label it returns, so any caller's
tests catch a label that breaks the rule. `reserved_blank_label("b",
"0.")` panics there.

Two spellings are part of stored identity across writes, but only their
leading `-` was pinned: renaming either kind kept every test green.

- `TemplateSink`'s `-b{N}`: a content-scoped upsert resolves a
  re-upserted payload to the nodes it made before only while the label
  holds. `anonymous_nodes_mint_the_labels_an_upsert_resolves_by` pins
  `_:-b1`, `_:-b2`.
- `ImportSink`'s `-b{chunk}-{N}`: a later import of a file agrees with an
  earlier one only while the id holds.
  `anonymous_nodes_mint_the_ids_a_reimport_agrees_on` pins
  `fdb-doc--b3-1`, `fdb-doc--b3-2`.

Both fail when the kind is renamed.
@bplatz
bplatz merged commit b140f8c into main Oct 30, 2026
29 of 30 checks passed
@bplatz
bplatz deleted the refactor/reserved-blank-labels branch October 30, 2026 12:28
bplatz added a commit that referenced this pull request Oct 31, 2026
Brings #2217 (SPARQL reads list members as values; CONSTRUCT writes lists),
#2218 (schema writes judged by modify policy), #2208, #2169, #2168, #2153,
#2149 and #2148 into next.

Resolutions:
- Nameservice: branch_records is the one branch listing (strict, retracted
  branches kept for GC) on every backend, resolved through next's bindings;
  Fluree::list_branches filters retracted ones. The lifecycle conformance
  suite reads live branches through a helper. DynamoDB's narrow listing is
  wired into its trait impl.
- JSON-LD adapter: main's graph scoping (Walk, Scope, node_graph, selectors)
  with next's triple terms, @annotation, @reifies, blank-label and number
  datatype handling. to_graph_events writes a JSON-LD named graph under its
  @id and refuses a graph selector. main's f:reifiesGraph anchor is dropped:
  next writes an annotation as an rdf:reifies link in its graph.
  emit_quad_list_item takes (graph, index).
- Bulk import: an annotation's link is written to the graph its slots name,
  and a triple-term statement in a named graph is spooled under that graph
  (both landed in the default graph); emit_quad_reified_triple is
  implemented. resolve_object_value keeps main's vector refusals and next's
  term-table path.
- Ledger manager: a store that fails to load fails the load or keeps the
  reloaded ledger's state (main), over next's load_decoding_root and
  activation swap rule.
- Novelty keeps main's KeptEffects without the retired arena's reifies
  capture. The pool's resolve_events_at and compaction's split_lifecycles
  follow fluree_db_core::same_t.
- Retired annotation arena files stay deleted.
- Tests from main adapted to next: one Fluree per storage directory, async
  genesis_ledger, storage-namespace content stores, u32 graph ids, a store
  broken by hiding a dictionary branch (next has no disk cache), a refused
  import leaving no ledger. next's tests that pinned bulk import refusing
  @graph and SPARQL's RDF list view now check what main changed them to.
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