Skip to content

fix: @json opacity, var-length edge identity, commit-id spelling, reserved-graph contract - #1838

Merged
aaj3f merged 26 commits into
mainfrom
feat/claims-followups
Sep 15, 2026
Merged

aaj3f merged 26 commits into
mainfrom
feat/claims-followups

Conversation

@aaj3f

@aaj3f aaj3f commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Running the claims scenario end to end surfaced six defects. The first pass at this branch fixed all six, and a design audit afterwards found that five of them were fixed where the symptom appeared rather than where the rule lives — two did not accomplish what they claimed, one created a new silent defect, and one collided with a gate the same author had added three weeks earlier. This replaces that approach rather than patching it.

The shape was the same every time. A rule exists, it is written down somewhere, and it is enforced only at the sites whoever needed it happened to touch:

symptom fixed at… …where the rule actually lives
one of three call sites of the annotation-keyword scanner the concept "opaque subtree", shared by four walkers
a query-wide set of variable names the lowering site that knows rel.var
a hand-rolled commit walk inside run_local Fluree::commit_log, which the server already uses
one resolver (parse_graph_ref) the family of reserved-graph gates
the abbreviation width the id encoding

The process rule that would have caught all of it is git log -S on a construct before changing it. Applied here it found four prior decisions — and three of them turned out to support the change rather than block it, which is most of why this PR is smaller in spirit than it looks.


@json payload opacity is a property of the document, not of one walker

JSON-LD 1.1 defines the @value of a @json literal as a document carried verbatim. The transaction parser read into it. Four walkers do that; the first pass guarded one.

One predicate, opaque_subtree(map, ctx), is now consulted by the three walkers that read into documents — the f:reifies* firewall, the lowering gate, and the keyword scanner. The fourth, the delete pre-pass, early-returns on the wider is_jsonld_value_object instead, mirroring the assertion-side walker: a value/list/variable wrapper is not a node map, so its structural keys are not predicates and its contents are not delete templates. (That is a deliberate asymmetry, not an oversight; the wider rule costs nothing here, because the first pass's predicate filter already skips @-prefixed keys, so the two predicates select identically on every shape reachable at that point.) Only @value is skipped: a sibling of the payload is ordinary JSON-LD the parser owns, so a deferred keyword nested in one is still refused, and a wrapper's own keys are checked before the skip, so an @annotation on a wrapper is refused exactly as before. Making a payload opaque must not widen what the wrapper around it may be.

It also uses the same definition of @json the expander uses: the keyword, the absolute rdf:JSON IRI, or any compact IRI expanding to it via expand_datatype_iri — read through the context's type_key alias, as ensure_subject_id already reads id_key. A context aliasing @type, among the most common things a JSON-LD context does, previously defeated the check entirely.

This closes a defect the first pass introduced. With a @json rule stored, deleting it silently no-opped: the delete pre-pass lifted @annotation out of the opaque payload and stripped the enclosing predicate, so the template that reached staging no longer described the literal. It committed, so there was no signal. Two rules differing only in whether the payload contains @annotation, given identical deletes, went 1→0 and 1→1.

Variable-length relationship hops carry their own edge identity

This finishes 9f837575e rather than reworking anything. That commit implemented per-hop property filters on bounded variable-length relationships — "each hop of the fixed-chain expansion becomes an EdgeAnnotation whose body carries the property values … one row per matching annotation, matching the single-hop property-filter semantics" — and deferred exactly one shape: "the combination with a rel/path binding". That deferred shape is what this closes, with the same mechanism.

A bounded, single-typed, directed range already expands to real triple patterns over synthetic node variables, so every hop has ordinary row variables for its endpoints. The elements were being built with MakeRel, which hardcodes reifier: None. Each hop now gets the Optional([EdgeAnnotation]) + coalesce(?ann, MakeRel(s,p,o)) shape a single -[r:T]-> hop has had since 9e72f0499. Reified hop: the element is the reifier node, so r.prop, properties(r) and keys(r) resolve through the evaluator's existing node arm. Unreified hop: it degrades to the synthesized value. No executor work and no IR change were needed.

relationships(p) over such a path resolves to that identity list, and a projecting WITH carries the list forward alongside the path variable — without which size(relationships(p)) after WITH p would have regressed from 2 to null. An aggregating WITH deliberately drops it instead: the list is not a group key, so carrying it would deliver a grouped binding to the RETURN, and relationships(p) coalesces back to the path value there.

Performance. Each per-hop probe is an edge-annotation operator, and each one used to drain the three f:reifies* predicates into its own maps — so a bounded range cost one full sidecar drain per hop, triangular in the range, paid even by queries that only bind the variable and never read a property. That memo now lives on ExecutionContext beside the other per-query caches, scoped so it resets wherever snapshot, overlay, to_t or the policy enforcer can change. Drain counts for *1..1 / *1..3 / *1..5 go from 1 / 6 / 15 to 1 / 1 / 1, measured at the operator rather than inferred from the clock. On an indexed ledger with 20,000 reified edges, one release profile on both sides: *1..3 292 ms → 49 ms (−83%), *1..5 740 ms → 51 ms (−93%). The zero-probe and single-probe shapes are unchanged — a fix-vs-fix run on the same binary puts this box's noise band at ±3.6%, which is where those two sit. A bench covering the shape is included.

Enumerated ranges (unbounded, untyped, undirected, *0.., or over 16 hops) still refuse the read, because the enumeration operator does not retain per-hop edge identity and every property read would answer null. The refusal follows renames — a WITH … AS alias and an UNWIND alias both resolve back to the variable the pattern bound, to a fixpoint so an alias of an alias composes — and it now also covers a fixed multi-hop path (p = (a)-[:T]->(b)-[:T]->(c)), which never carried per-hop identity either and answered null over genuinely annotated edges. Binding each hop's own relationship variable is the remedy in both cases, and p stays bound alongside them. The refusal now names the specific edit that fixes the pattern in hand — "name a relationship type", "give the range an upper bound", "give the pattern a direction", "start the range at 1 rather than 0" — instead of describing an artifact. The previous message sent users to a form that was itself refused.

A commit has one retypeable spelling: the hex digest

ContentId::Display is base32 CIDv1. The indexed commit subject, the on-disk blob path and the #txn-meta IRI are all hex. fluree log printed base32; both prefix resolvers scan hex. So nothing fluree log printed could be pasted into fluree show.

The first pass diagnosed this correctly — its own comment says "a commit address here is a multibase-encoded CID whose first dozen or so characters … are identical for every commit in every ledger" — and then changed the abbreviation width rather than the encoding. A width chosen from what is on screen cannot fix a constant prefix, because the constant is in every candidate:

fluree log -n 1 prints distinguishing pasteable
before bagaybq no — identical for every commit ever no
first pass bagaybqabci no — still identical, just longer no
this PR b6888dc89bb2 yes yes

Base32 packs 5 bits per character after a 56-bit constant header, so a 13-character abbreviation carries 4 bits and clearing the resolvers' 6-hex floor needs 17 characters; hex gets there at 7. Teaching the resolvers base32 is not merely more work, its output is unusable.

normalize_commit_ref is now the single normalizer both resolvers call, so they cannot diverge, and it accepts a full CID — which previously only fluree show did. ContentId::parse_canonical accepts a CID only in the spelling Display emits, which is what keeps a hex digest beginning with f from being decoded as base16 multibase; Display itself is untouched, since it is simultaneously the JSON API format and indexed ledger content. const _: () = assert!(ABBREV_LEN >= COMMIT_PREFIX_MIN_LEN) makes width drift a build failure rather than a test failure.

run_local now calls Fluree::commit_log, deleting the hand-rolled nameservice lookup, branched store and DAG walk, so fluree log --direct and the auto-routed fluree log are byte-identical — they previously gave different answers to the same command, and only one could exhaust memory. Default limit 100 matches the server, with --all to opt out. Peak RSS on a 40-commit chain: 22.5 MB before, 73.7 MB on the first pass, 21.1 MB now.

The ambiguity message was also structurally unable to do its job. It rendered candidates through a hardcoded seven characters, and the candidates are the digests that matched the queried prefix — so for any query of seven characters or more, every candidate is guaranteed to share those seven. Ambiguous commit prefix '0a9ccca1e1bc': matches ["0a9ccca", "0a9ccca"] was structural, not bad luck.

The reserved-graph access contract

Reachability is explicitness; policy is the access control. A reserved graph may be read when the author names it in full. It may never appear implicitly, be enumerated, be destroyed, or seed governance.

surface #config #txn-meta
ledger address (L#config, --ledger, db()) reachable reachable
FROM / FROM NAMED, JSON-LD from/from-named by full IRI only by full IRI only
GRAPH <iri> with no FROM NAMED blocked (returns empty, not an error) blocked
GRAPH ?g enumeration blocked blocked
GRAPH <iri> under an explicit FROM NAMED reachable reachable
GRAPH <iri> in a transaction writable, per docs/ledger-config/ refused
graph-management verbs refused refused
cross-ledger f:graphSelector / f:schemaSource / owl:imports refused refused

One caveat on that table worth knowing about, found while probing this and unrelated to the PR: fluree export --format trig/--format nquads omit named graphs entirely (Follow-up: #1847), so none of this survives an export round-trip today regardless.

Four mechanisms produced the split and all four are fixed: parse_graph_ref had a "txn-meta" arm and no "config" arm; GraphSelector had no Config variant, so the JSON-LD {"graph": "config"} form broke identically; two server matches! lists omitted "config", so a bare "from": "config" was sent to the nameservice as a ledger name; and resolve_within_ledger_graph filtered on >= FIRST_USER_GRAPH_ID.

#txn-meta is no longer a write target

INSERT DATA { GRAPH <urn:fluree:{ledger}#txn-meta> { … } } committed, and the triples landed in g_id 1 beside genuine commit provenance. That matters because both commit-prefix resolvers answer a user-typed prefix by scanning exactly the fluree:commit:sha256:<hex> subjects in that graph, and they trust what they find. Injecting a record whose digest shares a real commit's 12-character prefix permanently shadows that commit: fluree show <prefix> returns "Ambiguous commit prefix", and --at, @commit:, fluree history and branch create --at stop resolving it. It needs only ordinary write access and survives indexing. Real commits stay loadable by full id and the DAG is intact, so this is availability of the commit-lookup surface, not corruption of history.

The rule was already decided three times, once per channel, each in that channel's own vocabulary: graph management by a g_id comparison (1cb3e8cb2), graph sync by IRI shape (0bb792a97), and the txn-meta sidecar by a predicate-namespace allowlist (parse/txn_meta.rs). The plain GRAPH <iri> { … } data write predates all three and belonged to nobody, which is why no feature commit reached it. The guard goes where write targets are decided — txn.graph_delta, at the top of stage() — rather than becoming a fourth dialect of the same rule. USING/WHERE-side graph references travel on the where clause, so this refuses writes without touching reads.

#config is deliberately not covered: docs/ledger-config/ documents maintaining configuration through an ordinary transaction. The asymmetry is intentional and commented as such at the guard.

This stops new injections; it does not clean existing ones, and there is no migration. Replay and push go through stage_flakes rather than stage(), so a ledger already holding a forged record stays loadable rather than stranded.


For @bplatz — this reverses 8d8870ba1, your review finding in #1462

8d8870ba1 ("Review finding (bplatz)") added the >= FIRST_USER_GRAPH_ID filter to resolve_within_ledger_graph, so FROM <urn:fluree:{ledger}#config> is rejected on the ledger-scoped path. This PR admits it again when the clause names the graph in full. The archaeology, re-run independently rather than taken from the audit:

The cited code does not say what the citation claims. 8d8870ba1's reasoning is "the plain GRAPH <iri> path blocks them via single_db_user_graph_id's >= FIRST_USER_GRAPH_ID filter. Gate both resolution legs on the same filter." But that function opens if self.dataset.is_some() || iri == ledger_id { return None; }, and its own doc says it returns None "when a dataset scopes the named set (FROM NAMED)". The enumeration filter excuses itself precisely when an explicit FROM clause is in play. Addressing and enumeration are different surfaces; they were assumed alike because they resolve through adjacent code.

It regressed nothing that ever shipped. git merge-base --is-ancestor puts both 2d3cd5e90 (the capability) and 8d8870ba1 (the gate) on f084a1ee1^2 — the #1462 side of the merge. Before 2d3cd5e90 the surface documented that FROM/FROM NAMED would be rejected and had a test pinning it. No released version ever had within-ledger FROM <…#config> working.

The threat does not hold. There is no config-specific read exemption: grep -rn CONFIG_GRAPH_ID fluree-db-policy/src fluree-db-query/src fluree-db-api/src/policy_view.rs is empty, and the only read-path bypass, is_schema_flake, covers rdfs:subClassOf/subPropertyOf/domain/range and schema-typed rdf:type only. Policy governs it, demonstrated on one ledger with one variable: with no f:policyDefaults, FROM <urn:fluree:open:main#config> returns 3 rows; after adding f:policyDefaults [ f:defaultAllow false ], the identical query returns 0.

The capability has been open on the connection path the whole time. At origin/main, {"@id": L, "graph": "<full config IRI>"} returns the config graph's contents. Same IRI, same ledger, opposite answers on two surfaces — because load_view_from_source resolves a dataset source through parse_graph_ref while the ledger-scoped path uses resolve_within_ledger_graph.

The asymmetry was never decided. git log -S '"txn-meta" => Ok((ledger_id, GraphRef::TxnMeta))' --all returns exactly one commit, 5985d0f01 "fluree v4 baseline", whose parent is the Clojure v3 tree. No commit, PR or issue explains why txn-meta got a fragment arm and config did not. And cf1c74291 (PR #1292, closing issue #1279), which introduced single_db_user_graph_id, is explicitly about GRAPH <iri>/GRAPH ?g resolution and ends "Connection-scoped FROM <ledger> is deferred."

GRAPH ?g enumeration and bare GRAPH <…#config> remain blocked, byte-for-byte unchanged, and there is a negative test pinning that which is non-vacuous only under the opposite mutation. If you disagree, the fallback is a one-line correction to docs/ledger-config/writing-config.md:182-191, which has documented this as working since the v4 baseline and never has.


Stated semantics

These are contracts, not implementation notes.

Variable-length row multiplicity. Pattern::EdgeAnnotation is one row per (matched_edge, attached_annotation) pair, so a hop with two parallel claims multiplies rows and a k-hop chain multiplies k-fold. That is the correct Cypher answer — parallel relationships are distinct relationships — and it is what 9f837575e already decided for the inline filter form. A single-hop assertion sits in the same test to show var-length now matches the contract one hop already had.

The Optional wrapper is load-bearing. A bare EdgeAnnotation drops any path containing an unreified hop. all(…) would drop them anyway, but [r IN rs | r.conf] and any(…) must not. An unreified hop reads null; it never reads some other edge's value.

Reserved-graph reachability is the table above. A blocked GRAPH <reserved> returns empty, not an error.

Commit id spelling and width. Hex digest everywhere a user retypes something; 12 characters, fixed. Fixed rather than screen-derived because an id unique among displayed rows can be ambiguous ledger-wide, and both resolvers error on ambiguity — the screen-derived width is also what forced buffering the whole chain into memory.

Fixed in passing — for release notes

A Cypher variable-name collision across UNION branches silently dropped rows. annotation_dependent was one flat, statement-wide set of variable names, shared across union_tail and CallSubquery. push_rel_triple branches on it: not in the set gives base triple + Optional(EdgeAnnotation) + Coalesce, matching plain unreified edges; in the set gives a bare EdgeAnnotation, matching only reified ones. A false positive therefore picked a plan with a smaller result set. MATCH (a:Person {name:"Alice"})-[r:knows]->(b) RETURN b.name UNION ALL MATCH (r:Person {name:"Alice"}) RETURN r.name lost the first branch's row; renaming the tail variable to q restored it. The scan is now per-Query scope. Introduced by 9e72f0499 as a plan-selection device, never designed to gate anything.

ledger-info could report another graph's statistics when a graph was selected by IRI. LedgerInfoBuilder::for_graph_iri matched the reserved system graphs by IRI suffix, so any graph whose IRI ended in #config or #txn-meta — a user graph named http://example.org/x#config, or another ledger's config graph — resolved to the queried ledger's config (g_id 2) or transaction-metadata (g_id 1) graph and returned that graph's name and statistics instead of its own. Now compared exactly against the ledger's own IRIs; resolution without a binary store still works for this ledger's own reserved graphs. The fluree info CLI and the ledger-info HTTP route select by name and were never affected; this reaches library consumers that select a graph by IRI. Present since the v4 baseline.

Binding a path variable now multiplies rows on parallel claims. MATCH p = (a)-[:KNOWS*1..2]->(b) RETURN b.name returns one row per (path, attached claim) pair where it previously returned one per path — the same contract a single hop has had, now applied to the path form. Visible on reified ledgers to queries that bind p without reading any property; the unbound form is unchanged.

Two format flags accepted more spellings than their errors admitted. --format on insert accepted five and named two; on update, seven and named three. So --format ttl, json-ld, json, sparql-update and opencypher all worked while the only text telling a user what to type said they did not exist. Found because the fixed docs/ledger-config/README.md command lands a reader on exactly that error.

The TriG-through-insert trap is documented, not fixed. fluree insert routes a file to the streaming Turtle parser, which has no GRAPH keyword, so a TriG file reports expected subject, found KwGraph and fluree upsert is the path that reads it. The root cause — the insert_turtle fast path skipping GRAPH-block extraction — is Follow-up: #1832, and the note in docs/transactions/turtle.md now points at the working spelling rather than presenting the limitation as a rule.

Documentation that could not be run. docs/cli/log.md was fabricated end to end — ids in a shape the system never produces, a commit-message column the code says is not persisted, and a one-line format that does not match the code. Both fluree commands in docs/ledger-config/README.md were unrunnable: insert --format trig is a usage error, and without the flag the file hits the TriG trap. Everything here was regenerated from executed output.

Deferred, with the reason

A --first-parent commit walk for fluree log. collect_first_parent_cids exists, but 900215a2b states the current division explicitly — "The DAG walkers keep their behavior for reachability: common ancestors, blob copying, ancestry checks, drop, pack, verify, transfer, CLI sync and log, and merge-preview summaries." So this is a recorded decision, not an omission, and changing what fluree log means across merges is a product decision rather than an implementation detail. The default limit plus CommitSummary captures the memory win without touching it.

Bulk import is not covered by the txn-meta write guard, and is measured rather than assumed. import.rs builds graph_delta itself and bypasses stage(). A TriG import naming <urn:fluree:L#txn-meta> is not refused and the triples are persisted in the commit — but they land outside the graph registry and are unreachable from every read surface including the commit-prefix resolver, before and after a genuine re-index. So the forgery is not reachable through import, and bulk import is genesis-only (fluree create --from is the only surface). The unreachable-persisted-data behaviour is its own defect — Follow-up: #1846.

Later pass — what a second look changed

An independent adversarial review of the rework turned up three defects in the Cypher lowering, all now fixed here. Two are worth stating because the shape of the mistake is the same one this PR is about, one level down.

An aggregating WITH carried the identity list as a grouped binding, tripping the engine's Grouped binding in filter evaluation assertion — a panic in every dev/test/CI build, silently Ok(None) in release. The comment on the coalesce rewrite already described the correct fallback ("an aggregating one, whose group keys we cannot extend"); the augmentation simply did not implement it. A prose invariant with no enforcing branch is a latent bug with an alibi: a reviewer who reads the comment concludes the case is handled.

The enumeration refusal was bypassed by a WITH … AS rename, returning [] silently — the spelling this PR's own body claimed was refused. Notably the fix is not the obvious symmetry with the existing UNWIND handling: an UNWIND alias names a row variable and a WITH alias names the list, so they land in different sets, and the symmetric-looking implementation would have compiled, read correctly, and fixed nothing.

The third was the probe cost model, covered in the performance paragraph above.

Also folded in: a WITH/UNWIND alias no longer leaks a list iteration's loop variable into the scope's annotation set; an element extracted from a relationship list (properties(rs[0])) is recognised as a property read by both refusals, closing a hole they shared through the scan rather than through either guard; and the two fluree log corrections noted above.

One residual stated rather than closed: the abbreviated-CID diagnostic ('bagaybq…' is an abbreviated CID; this takes the hex digest) still reaches the CLI as Internal error: Query error: and the server as a 500, for a user typing the wrong thing — the same class this PR fixes for TriG. NotFound is the wrong alternative, because build_source_view rewrites it to "ledger not found", so the right fix is a taxonomy decision rather than a patch and is deliberately not made here.

Verification

Every regression test here was checked non-vacuous by reverting only its own fix and confirming it goes red — 34 mutations, each also confirming the crate actually recompiled, since an mtime-fresh artifact reports the opposite of the truth. Four needed a second look, and in every case the first reading was a false verdict rather than a real gap: two looked vacuous until run against the suite that actually owns the pinning test, one is a compile failure rather than a test failure, and one was a malformed mutation that failed to build.

Two pairs pin opposite edges and are worth knowing about before re-running them: reverting the reserved-graph fix leaves sparql_reserved_graphs_stay_unreachable_when_not_named_in_full green — correctly, because it pins that nothing was opened. It only goes red when admission is widened to a suffix match. The same holds for the ledger_info exact-match pair.

Locally: cargo fmt --all --check, cargo check --workspace --all-targets, cargo clippy --all --all-features --all-targets -- -D warnings, and cargo test --workspace --all-features --doc all clean; cargo nextest run --workspace --all-features passes 12,731 of 12,733 with two forward-pack-compaction tests hitting the 360s cap under local contention — they pass in isolation at 82s and 105s, contain no reference to anything this PR touches, and are green on CI for main at this base.

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

Approving so this isn't held up, but @aaj3f please work through the inline comments before merging. Three of them (the fluree log abbreviation, the var-length refusal coverage, and the #config gate) affect whether those fixes do what the description says.

Comment thread fluree-db-cli/src/commands/log.rs Outdated
/// shortest prefix that separates them, with a floor so short lists still
/// look like ids and a widening step so a near-collision grows rather than
/// truncates.
fn abbrev_len(ids: &[String]) -> usize {

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.

These abbreviations still can't be pasted into fluree show. show resolves a prefix of the hex SHA-256 digest (resolve_commit_prefix in fluree-db-api/src/ledger_view.rs), but this abbreviates the base32 CID string. With the CLI built from this branch:

$ fluree log --oneline
t=3     bagaybqabciqlb  …
t=2     bagaybqabciqn5  …
t=1     bagaybqabciqhs  …
$ fluree show bagaybqabciqlb
error: Not found: No commit found with prefix: bagaybqabciqlb
$ fluree show b0b156e          # first 7 hex chars of the same commit's digest
{ "id": "bagaybqabciqlbmkw5…", "t": 3, … }

Two more problems with computing the width from the displayed ids:

  • The first 12 characters of every CID are constant (b + CIDv1, codec 0x300001, sha2-256, length 32). The 10-char floor is shorter than that, so fluree log -n 1 prints bagaybqabci, which is all header.
  • The width depends on which rows are displayed, so -n 3 and -n 50 print different lengths. Uniqueness is only checked against the rows on screen, not the ledger, so the headroom character doesn't keep output stable.

Suggest printing the first 7 chars of ContentId::digest_hex() instead (remote rows can parse commit_id as a ContentId first). The digest is uniformly distributed, so the git habit carries over; show accepts 6+ chars; and abbrev_len can go away. The test here uses fabricated ids and never feeds the result back through commit-prefix resolution, which is the property that matters.

Comment thread fluree-db-cli/src/commands/log.rs Outdated
let mut shown = 0usize;
let limit = count.unwrap_or(usize::MAX);

let mut rows = Vec::new();

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 collects whole Commits, including each commit's flakes vector, for the entire chain before printing anything. --count defaults to usize::MAX, so the comment below ("limit already bounds how many there can be") only holds when -n is passed. On a large ledger, a plain fluree log now holds every commit's flakes in memory and prints nothing until the walk finishes; before this change it streamed.

If the width computation goes away (see the comment on abbrev_len), this can go back to streaming. Otherwise keep only (t, id, time, flake count) per row.

Comment thread fluree-db-cypher/src/lower/pattern.rs Outdated
// suggests filtering "via WHERE on the bound relationships instead",
// which is this shape. Refuse it by name too.
if let Some(var) = rel.var.as_ref() {
if ctx.is_list_element_annotation_dependent(&var.name) {

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 only catches the shape where the list is the bare relationship variable: note_element_property in annotation_use.rs requires Expr::Var, and this check looks at rel.var but not path_var. The other common spellings still give the same silent wrong answer. On Alice -[:KNOWS {confidence: 0.9}]-> Bob -[:KNOWS {confidence: 0.95}]-> Carol, where the correct answer to the filter is Bob and Carol:

query result on this branch
…-[rs:KNOWS*1..2]->(b) WHERE all(r IN rs WHERE r.confidence > 0.8) refused ✓
p = (a)-[:KNOWS*1..2]->(b) WHERE all(r IN relationships(p) WHERE r.confidence > 0.8) []
p = … RETURN [r IN relationships(p) | r.confidence] [null], [null, null]
…-[rs:KNOWS*1..2]->(b) UNWIND rs AS r RETURN r.confidence all nulls
… WITH b, rs AS xs WHERE all(r IN xs WHERE r.confidence > 0.8) []
p = shortestPath(…) WHERE all(r IN relationships(p) WHERE …) []
[r IN rs | type(r)] works ✓ (no false positive)

relationships(p) is arguably the more common way to write this query. Name matching at lowering time can't follow the list through UNWIND or WITH, so the durable fix is probably at evaluation: a property read on a synthesized relationship value with no annotation behind it raises instead of yielding null. If this stays in lowering, it should at least cover relationships(<path var>) and check path_var here.

// registered under its full `urn:fluree:<ledger>#config`
// IRI — so every `FROM <urn:fluree:mydb:main#config>` in
// the docs failed with "Unknown named graph '#config'".
"config" => Ok((ledger_id, GraphRef::Config)),

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 reopens part of what 8d8870ba1 (from the #1462 review) closed on purpose. That commit made FROM <urn:fluree:{ledger}#config> stop resolving because it "exposed the governance/config graph to any query". Its test (sparql_from_rejects_reserved_system_graphs) still passes because it only covers the view path, and this PR's test only covers fluree.db(), so CI doesn't see the conflict. After this change the surfaces disagree:

surface result on this branch
query_connection_sparql with FROM <…#config>, CLI fluree query, FROM <L@t:2#config>, JSON-LD from: "L#config" resolves (new)
JSON-LD from: {"@id": L, "graph": "config"} Unknown named graph '#config': GraphSelector::from_str only special-cases txn-meta
fluree.query(&view, "… FROM <…#config> …") rejected by the 8d8870ba1 gate in resolve_within_ledger_graph
server /query/{ledger} with FROM <…#config> from reading the code, still rejected, since the fragment goes through GraphSelector::from_str (didn't run this one)
JSON-LD graph: "<full config IRI>" resolves, and already did before this PR (select_graph's Named arm has no reserved-graph filter)

So the gate was already leaky, and the ledger-config docs contradict it. I think this needs a decision before the arm lands:

  • Config is readable under policy: relax the 8d8870ba1 gate and its test, and add config wherever txn-meta is special-cased (GraphSelector::from_str, the ambiguity check in parse_graph_selector_field, the server's looks_like_graph_selector_only), with a test on a query surface rather than only fluree.db().
  • Config stays reserved: drop this arm, close the full-IRI route in select_graph, and fix the docs that query it.

.map(|(a, _)| *a)
.map(|((_, a), _)| *a)
.collect();
offenders.dedup();

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.

dedup() only removes adjacent duplicates, and offenders comes out of a HashMap in arbitrary order, so an annotation that is multi-target in two graphs will usually be counted twice. Sort first, then dedup.

It only affects the count in the warning, but the new per-graph key is what makes duplicates possible here, and none of the new tests cover an annotation that offends in two graphs.

Comment thread docs/transactions/turtle.md Outdated
reifier, joined. On an edge with two claims that returns four rows rather than
two, silently, because each unit matches every claim.

**TriG goes through `upsert`, not `insert`.** `fluree insert` routes a file to

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 documents a bug as a rule. #1832 describes the same root cause (the insert_turtle fast path skips GRAPH-block extraction) and calls it worth its own issue. I'd file that and reference it with Follow-up: #N rather than telling users to route around it.

Relatedly, docs/ledger-config/README.md:208 still says fluree insert --ledger mydb:main --format trig config.trig. That fails the same way (expected subject, found KwGraph), and insert --format only accepts turtle or jsonld. The query example right below it uses --format sparql, which isn't a valid output format either.

Comment thread docs/transactions/turtle.md Outdated

Sending a claims file through `upsert` replaces each claim's body (`ex:confidence`) the way upsert replaces any other predicate value, while the edge and its attachment stay put — the natural way to keep a claims file in sync with a ledger.

**Write the reifier before the annotation block.** `s p o ~ ?claim {| … |}` binds

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 note is about query patterns (?claim is a variable, and the effect described is a row count), but it's in the Turtle transactions doc, where variables aren't legal. It would fit better with the SPARQL/query side of the edge-annotation docs. If the write side has its own version of the trap (s p o {| … |} ~ ex:r producing two reifiers), that would be the thing to say here.

/// Detection mirrors the transactor's expanded-value parser: presence
/// of `@value`, `@language`, `@list`, or `@variable` makes this a
/// value-class object.
/// A JSON-LD `@json` literal: `{"@type": "@json", "@value": <anything>}`.

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.

The new function was inserted between is_jsonld_value_object's doc comment and the function itself, so rustdoc attaches both paragraphs to is_json_literal and is_jsonld_value_object loses its doc. Moving this block above line 1596 fixes it.

// is not JSON-LD at all, so any `@json` document that happens to use
// the key `@annotation` was refused — including the documented shape
// for a stored datalog rule, whose body reads annotations. The
// wrapper's own siblings are still scanned, so an `@annotation`

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.

These two comments contradict each other. This one says an @annotation alongside @value "is caught as before"; the inner one says an @annotation on a @json literal is supported. In practice intercept_annotations_for_predicate has already removed @annotation from the map before this runs, and the new loop only scans values, not keys, so a leftover @annotation key wouldn't be caught here anyway. Worth collapsing to one accurate sentence.

/// Collect, in one traversal, the variables used on the annotation surface
/// anywhere in the query — including UNION tails, CALL subqueries, and nested
/// patterns — in both the direct and the list-element form.
/// Both surfaces, from one traversal.

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.

Doc comments got merged here: the old annotation_dependent_vars doc and a second summary line both landed on the struct, and scan below has none.

More generally, many of the new comments in this PR tell the story of the fix ("the first attempt at the fix did exactly that", "without this arm #config fell through…", "a correct ledger warned about itself after any copy"). That history is already in the commit messages; in code, a one-line why will age better.

@aaj3f
aaj3f force-pushed the feat/claims-followups branch from 4e46aa1 to e0c78df Compare September 15, 2026 13:54
@aaj3f aaj3f added the bug Something isn't working as expected label Sep 15, 2026
@aaj3f aaj3f changed the title Close the gaps a real run of the claims scenario found fix: @json opacity, var-length edge identity, commit-id spelling, reserved-graph contract Sep 15, 2026
`detect_multi_target_annotations` counted live edges per annotation IRI
across every graph, so `COPY <g1> TO <g2>` — which duplicates annotated
edges with their reifier IRIs — made a correct ledger warn about itself,
and the warning claimed the transaction path rejects the shape when it
does not. The staging twin, `enforce_single_target_reifiers`, has keyed by
`(graph, reifier)` since #1823 for the same reason; this is the read-side
half that was never aligned. A comment now points each at the other so the
two rationales cannot drift apart again.

The offender list needed one further correction. It is built from a map
keyed by `(graph, reifier)` but reports reifiers, so a reifier that offends
in two graphs arrives twice; `dedup` ran before `sort_unstable`, and
`Vec::dedup` only collapses adjacent equals. With `HashMap::iter` as the
source — reseeded per map — the pair was collapsed only when the hash order
happened to put the entries side by side, and one fixed input reported 2 or
3 offenders depending on the run. Sorting first makes the dedup total.

`the_offender_count_does_not_vary_between_runs` loops 500 times precisely
because a single pass passes under the bug better than half the time: as a
one-shot assertion it would have been a flaky test rather than a failing
one. Reverting only the two-line swap fails it at `left: 3, right: 2`.
Both were hit running the claims scenario end to end, and both commit or
return rows rather than erroring, so nothing tells the author.

`s p o {| ... |} ~ ?claim` is not `s p o ~ ?claim {| ... |}` with the parts
in a different order. The reversed form is two independent annotation units
on one edge — one matching the body, one binding a reifier — joined. On an
edge carrying two claims the correct order returns the two paired rows and
the reversed order returns their cross product:

    ~ ?claim {| ex:confidence ?conf |}   ->  claim1/0.8  claim2/0.9
    {| ex:confidence ?conf |} ~ ?claim   ->  claim1/0.8  claim2/0.8
                                             claim1/0.9  claim2/0.9

`fluree insert` routes a file to the streaming Turtle parser, which has no
GRAPH keyword: a TriG file reports `expected subject, found KwGraph` at the
first block. `fluree upsert -f file.trig` reads it.

The added paragraph states the rule that decides which of these gets prose
and which gets a refusal, because the same question comes up for the
variable-length property read this PR refuses in Cypher. The reversed
annotation form is well-formed SPARQL-star and four rows is the correct
answer to what was written, so no parser can know the author meant the
other thing. A property read on an enumerated variable-length relationship
has no correct answer at all. A right answer to the wrong question gets a
warning in the docs; no right answer gets an error.

Rewrapped to the file's one-line-per-paragraph convention.
JSON-LD 1.1 defines the `@value` of a `@json` literal as a document carried
verbatim: the transactor serializes the whole thing into one `rdf:JSON` flake
value, so no key inside it is a keyword this parser owns. Four walkers in
`parse/edge_annotations.rs` read into documents, and each one is its own wrong
answer:

- `scan_nested_annotation_keywords` applied the annotation-of-annotation
  deferral to whatever it found inside a payload, so any `@json` document
  containing `@annotation` was refused — including the documented shape for a
  stored datalog rule, whose body reads claims.
- `walk_delete_for_annotations` descended through `@value`, lifted the
  payload's `@annotation` out of it, and stripped the predicate that carried
  it. The delete template that reached staging no longer described the stored
  literal, so the transaction committed and retracted nothing: no error, no
  signal, wrong answer.
- `scan_user_authored_reifies_iris` refused a payload key that expanded to an
  `f:reifies*` IRI, and parsed a payload key named `@context` as if it were
  this parser's.
- `document_has_annotation_keys` counted keywords inside payloads, so one that
  existed only in an opaque document bought a document clone and two walks
  that find nothing.

The wrong turn was to fix this where the symptom surfaced. The first attempt
added a `@json` branch at one of `scan_nested_annotation_keywords`' three call
sites — the value-object early return in `lower_object_with_subject`. That
left the other three walkers reading; it left a `@json` literal inside `@list`
or inside an annotation body still refused, because at those positions the
wrapper reached the scanner from somewhere else; and it relaxed the
wrapper-key check that `38f31ce8a` put at that exact line on review, whose
message says the early return "was early-returning for any
`is_jsonld_value_object` map without scanning its contents".

The rule is a property of the document, so `opaque_subtree` states it once and
every walker consults it. Its accepted `@type` spellings mirror the
transactor's own literal parser rather than a raw string comparison: the
keyword `@json`, or any IRI expanding to `rdf:JSON`, read through the
context's `@type` alias. `{"type": "@type"}` is among the most ordinary things
a JSON-LD context does, and a predicate comparing the raw `"@type"` key
disagrees with the expander on exactly that document — the original bug
survives under the alias.

Skipping only `@value` is deliberate. A sibling of the payload is ordinary
JSON-LD, so a deferred keyword nested in one is still refused; and the
wrapper's own keys are checked before the skip, so an `@annotation` *on* a
wrapper is refused exactly as on main. Making a payload opaque must not widen
what the wrapper around it may be.

Narrowing the firewall is safe for the one reason that matters: a `@json`
payload never becomes triples. It is serialized whole into a single literal
value, so no key inside it can carry a system predicate into the store.

The scanner now takes the map its callers already hold. Routing through
`&Value` meant cloning a whole subtree at three sites just to borrow it back,
and the wrapper-key check makes iterating the map directly a different
function rather than an inlining of the same one.

Tests. `it_json_literal_opacity.rs` runs at the lowering entry point, where
each document position and each `@type` spelling is one assertion; every one
of its seven tests goes red under exactly one reverted piece of this change
and no other. The end-to-end contract is in `it_datalog_rules_annotations.rs`:
a stored rule that reads claims is storable, and deletable afterwards. The
delete pair carries a control differing only by the keyword in the payload,
because "`@json` deletion is broken" and "this one keyword breaks it" call for
different fixes. The third delete test exists because the lowering gate and
the delete walker are each independently sufficient for the simple shape —
only a transaction that opens the pass for an unrelated reason holds the
delete walker to its own rule.
A bounded, single-typed, directed range expands to a fixed chain of real
triple patterns over synthetic node variables, so every hop already has
ordinary row variables for its endpoints. It was still bound with
`MakeList([MakeRel(s, p, o), …])`, and `MakeRel` hardcodes `reifier: None`
— so `all(r IN rs WHERE r.confidence > 0.8)` over a fully reified chain
returned zero rows, and `[r IN rs | r.confidence]` returned a list of
nulls. No error either way.

Bind each hop through the same two-way shape a single `-[r:T]->` hop has
used since 9e72f04: a per-hop `Optional([EdgeAnnotation])` probe and
`coalesce(?ann, MakeRel(s, p, o))`. A reified hop's element IS the
reifier node, so `r.prop`, `properties(r)` and `keys(r)` resolve through
the evaluator's node arm; an unreified hop degrades to the synthesized
value, whose property surface is empty.

Two consequences are contracts, and are pinned:

- The `Optional` wrapper is load-bearing. A bare `EdgeAnnotation` drops
  every path containing an unreified hop — `all(…)` would exclude those
  paths anyway, but `any(…)` and `[r IN rs | r.p]` must still see them.
- Row multiplicity follows edge multiplicity: a hop carrying two parallel
  claims doubles the rows and a k-hop chain multiplies k-fold. Parallel
  relationships are distinct relationships, and this is what one hop
  already did.

`relationships(p)` over such a path resolves to the identity-carrying
list rather than to the path value, whose `edges: Vec<(Sid, Sid, Sid)>`
has no reifier slot. It coalesces back to the path-derived list so an
aggregating `WITH` that drops the list degrades to today's answer instead
of reading null, and a projecting `WITH` carries the list forward
alongside the path variable.

The ranges resolved by path enumeration — unbounded, untyped,
undirected, a zero lower bound, or deeper than 16 hops — genuinely cannot
do this: hops are discovered inside the operator and probing per hop per
enumerated path is un-batched work under no path-count bound. Refuse the
read there, naming the specific edit that moves the pattern onto the
bounded route. The inline `-[rs:T*1..3 {p: v}]->` refusal used to point
at "filter via WHERE on the bound relationships instead", which then
answered null; it now names the spelling that works.

Scope the annotation-surface scan while here, because the guard needs it
and because the scan was dropping rows on its own. `annotation_dependent`
was one query-wide set of variable NAMES: `scan_query` recursed into
`union_tail` with the same accumulator, so

    MATCH (a:Person {name:"Alice"})-[r:knows]->(b) RETURN b.name AS out
    UNION ALL MATCH (r:Person {name:"Alice"}) RETURN r.name AS out

put `r` in the set from the second branch, and the first branch lowered
to a bare `Pattern::EdgeAnnotation` — which matches only reified edges.
Bob vanished from a query over plain-RDF data, silently. Renaming the
second branch's variable brought him back.

The set is now computed per `Query` node and installed in
`lower_single_branch`, the one place every `Query` passes through — top
level, UNION branch and `CALL` body alike. UNION branches are independent
scopes; a `CALL` body may read imported outer variables, so its reads
still propagate up. The module comment called the over-approximation
"conservative"; it is not, in either direction. A false positive drops
unreified rows; a false negative binds a synthesized value whose later
property triple fails to constrain and reports another edge's value
(reproduced by forcing the predicate false: two untyped-rel tests go red
with a fabricated `w`). Both failure modes are now written down there,
along with the two residuals that need a scope-chain walk.

`[n IN nodes(p) | n.name]` stays allowed on every route — path nodes are
real subjects, not edges — which is why the element scan distinguishes
list expressions that yield relationships from ones that yield nodes.

Each new test was checked by reverting only its own fix: the union test
goes red on restoring the `union_tail` recursion, the hop-annotation
tests on suppressing the probe, the unreified-hop test on unwrapping the
`Optional`, the `relationships(p)` test on dropping the rewrite and again
on dropping the `WITH` augmentation, and the refusal test on disabling
the guard and again on removing the `nodes()` exemption.
Both routes were reasoned about but not run. `tail(rs)` and `reverse(rs)`
rewrap the same list elements, so on the bounded route each element still
carries its own hop's reifier and reads the right value; on the
enumeration route the guard must see through the wrapper to `rs` rather
than treat the call as an opaque list.

It does, because the element scan collects the variables of the whole
list expression rather than requiring a bare `Expr::Var` — which is the
same reason `relationships(p)` is covered. Assert both directions so the
next person changing that collector finds out.
A commit has two canonical spellings and only one can be pasted back in.
`ContentId` displays as a base32 CIDv1 — that is the JSON API wire format and
the `db:address` flake value — but the indexed commit subject is minted as
`Sid::new(FLUREE_COMMIT, cid.digest_hex())`, the blob path is hex, and the
`#txn-meta` IRI is `fluree:commit:sha256:<hex>`. Both prefix resolvers scan
hex. `fluree log` printed base32, so nothing it printed resolved: pasting a row
into `fluree show` returned "No commit found with prefix".

Abbreviating base32 cannot fix that. A CIDv1 opens with seven header bytes, so
after the `b` multibase marker eleven payload characters are 55 bits of header
and character thirteen carries the digest's first four bits. The first twelve
characters of every commit CID are the constant `bagaybqabciq`, and clearing
the resolvers' six-character floor would take seventeen. Hex carries four bits
from the first character.

So `commit_id_of` decodes a CID to its hex digest, and the width is a fixed
twelve — 48 bits, already the prefix width `it_graph_commit.rs` uses to address
a commit. Computing a width from the ids on screen answers the wrong question
regardless: an id unique among the displayed rows can be ambiguous
ledger-wide, and both resolvers reject an ambiguous prefix. A `const`
assertion ties `ABBREV_LEN` to `COMMIT_PREFIX_MIN_LEN` so the printed width
cannot drift below what the scan will accept — a compile error, because a
width that separates the rows on screen and is still unusable looks correct
from every other angle.

The two resolvers now share `normalize_commit_ref`. `--at`, `@commit:`,
`fluree history` and `branch create --at` accept a full CID, which previously
only `fluree show` did, and an abbreviated CID is refused by name instead of
being reported as a prefix that matched nothing.

A CID counts only in its canonical spelling. `f` is base16 in the multibase
table, so `f01550003000102` is all hex, parses as a valid CID, and would
otherwise resolve a commit nobody named — the identity multihash makes a valid
CID out of very few bytes. `ContentId::parse_canonical` is that check, in core
so the three sites that need it cannot drift: the normalizer, `CommitRef::parse`
(which had the same hole), and `fluree log`'s own address handling. It is the
same split `resolve_head` hit against the `.fir6` index nodes in 9c49573,
where a healthy ledger was reported as 100% orphaned.

`run_local` calls `Fluree::commit_log`, which the server's log endpoint already
used, and drops its own nameservice lookup, branched store and commit walk.
The local lane gains `total`, so it prints the truncation line the remote lane
prints, and the two lanes now produce identical output. The limit defaults to
100, matching the server: `fluree log --direct` walked the whole chain while
the identical auto-routed command returned 100, and only one of them could
exhaust memory. `--all` asks for the rest.

`walk_commit_summaries` loads one full commit blob per shown row instead of
retaining every `Commit` with its flakes. Measured on 40 commits of ~5000
flakes each, peak RSS is 22 MB against 74 MB. It still reads an envelope per
commit in the DAG in order to sort by `t`; bounding that means walking the
first-parent lineage, which changes which commits appear across a merge and is
a decision about what `fluree log` means.

docs/cli/log.md was fabricated end to end — `bafybeig2k5…` ids where real ones
are hex, a commit-message column the code says is not persisted, and a
one-line format that never matched the code. Rewritten from real output. The
`commit_id` example in docs/api/endpoints.md is a real base32 CID now, with a
note on why it is not the spelling `fluree log` prints.
The reserved graphs -- #txn-meta (g_id 1) and #config (g_id 2) -- were
reachable as a ledger address on some surfaces and refused as a FROM clause
on others, for the same IRI. Establish one contract instead: reachability is
explicitness; policy is the access control. A reserved graph may be read when
the author names it in full; it may never appear implicitly, be enumerated,
be destroyed, or seed governance. The table is written down on
`resolve_within_ledger_graph` and mirrored in it_reserved_graph_contract.rs.

Four mechanisms produced the split.

parse_graph_ref had a "txn-meta" fragment arm and no "config" arm, so #config
fell through to an exact-IRI lookup for the bare word "config" -- which cannot
match the registered urn:fluree:{ledger}#config. `--ledger mydb:main#config`
and the connection path's FROM <urn:fluree:mydb:main#config> both failed with
"Unknown named graph '#config'". The asymmetry is a v4-baseline artifact
(5985d0f, the only commit to touch that arm; its parent is the Clojure
tree); no commit, PR, or issue explains it.

GraphSelector likewise had no Config variant, so the JSON-LD
{"@id": L, "graph": "config"} form broke the same way. SPARQL and JSON-LD
share an IR, so the twin is fixed here rather than later.

refreshable_ledger_id/-_and_t listed only "default" | "txn-meta", so a bare
"from": "config" was treated as a ledger named "config" and sent to the
nameservice. (looks_like_graph_selector_only already classified it correctly,
but by accident, via its "no : @ or #" fallback; "config" is now named there
too so the intent is explicit.)

resolve_within_ledger_graph filtered >= FIRST_USER_GRAPH_ID (8d8870b, a
review finding in PR #1462). That filter is the ENUMERATION filter, applied
to an ADDRESSING surface. single_db_user_graph_id itself distinguishes the
two -- it returns None outright when dataset.is_some(), i.e. it excuses
itself exactly when an explicit FROM/FROM NAMED clause is in play. Admit a
reserved graph here only when the clause IRI is this ledger's exact
config_graph_iri/txn_meta_graph_iri, so a bare `config`, a relative
`#config`, and another ledger's reserved IRI all still fall through to the
"not in this ledger" rejection.

Nothing deliberately closed is opened. GRAPH ?g still enumerates user graphs
only, and GRAPH <reserved> with no FROM NAMED still resolves to nothing --
both pinned by sparql_reserved_graphs_stay_unreachable_when_not_named_in_full,
which goes red if the admission is widened to a suffix match. The threat the
filter was added against does not hold: there is no config-specific read
exemption (is_schema_flake covers only rdfs:subClassOf/subPropertyOf/domain/
range and schema-typed rdf:type), and adding f:policyDefaults
[f:defaultAllow false] takes the same FROM query from three rows to zero.
ledger_info::resolve_graph_selector recognized the reserved graphs with
iri.ends_with("#config") / ("#txn-meta") so that ledger-info would work
before an index exists. Any graph IRI ending that way therefore resolved to
this ledger's g_id 2 / 1. A user graph named http://evil.example/x#config
reported the governance graph's name and stats in place of its own, and
another ledger's reserved IRI silently resolved to this one's.

Shipping bug, not caused by this branch: git log -S 'ends_with("#config")'
names only 5985d0f, the v4 baseline, so it has been present for the whole
life of the v4 line.

Compare against config_graph_iri(ledger_id) / txn_meta_graph_iri(ledger_id)
instead, which needs the ledger id -- hence the new parameter and the
one-line update at the profile.rs call site, which already had it in hand.
Pre-index resolution of this ledger's own reserved IRIs is preserved; a
non-matching IRI now falls through to the store lookup and resolves to
itself.
convert_named_graphs_to_templates refused the system-controlled f:reifies*
predicates with ApiError::query, which the server renders as
"Internal error: Query error: ...". The input is user-authored and refused at
write time, so it reads as an engine bug rather than a problem with the
statement. ApiError::Transact maps to errors::INVALID_TRANSACTION / HTTP 422
(fluree-db-server/src/error.rs), which is what this is.

Ported unchanged in substance from the branch under review.
Neither command in the "CLI usage" block could run.

`fluree insert --ledger mydb:main --format trig config.trig` fails twice
over: --format accepts only turtle/ttl/jsonld/json-ld/json, so 'trig' is a
hard usage error ("unknown data format 'trig'", exit 2); and without the flag
`insert` hits the TriG trap ("expected subject, found KwGraph") while
`upsert` silently commits. writing-config.md:36 already documents this and
gives the working SPARQL UPDATE recipe -- the README is the outlier, so point
it the same way.

`fluree query --ledger mydb:main --format sparql '...'` also fails: on
`fluree query`, --format selects the OUTPUT format (json/table/csv/...), not
the input language, which is auto-detected. Drop the flag.

Both replacements were run end to end, as were the reachability claims added
alongside them: FROM <config> and FROM <#config> are rejected, GRAPH ?g
returns no reserved graph, and adding f:policyDefaults [f:defaultAllow false]
takes the FROM query from three rows to zero.
`resolve_commit_prefix` rendered its candidates through its own hardcoded
`&h[..7]`. Every candidate in that list matched the prefix the user just typed,
so any query of seven characters or more printed the same seven-character stub
once per candidate:

    error: Ambiguous commit prefix '0a9ccca1e1bc': matches ["0a9ccca", "0a9ccca"]

The one message whose entire job is to say which commits collided was
structurally incapable of saying it. Its twin in `commit_to_t` did not truncate
at all and printed `fluree:commit:sha256:<full hex>` instead, so the two
resolvers also described the same situation differently.

Both now build the message through one `ambiguous_commit_prefix`, printing full
hex digests — the spelling `normalize_commit_ref` accepts and `fluree log`
prints, so a candidate can be pasted straight back in. Neither caller scans
past a second match, so the message says "at least" rather than implying it
enumerated them.

The regression test asserts that the rendered candidates differ from each
other, which is the property a fixed width at or below the queried length
cannot have.
The command output in docs/cli/log.md and the endpoint response in
docs/api/endpoints.md were captured from a CLI built in a CARGO_TARGET_DIR
shared with three other worktrees, where the bin artifact is one filename and
the dep-info source paths are relative. Whichever tree built last owned the
binary, so those literals had no verifiable provenance even though their shape
was right.

Recaptured from a CLI built in a private target dir nothing else writes to.
No prose changed; only the ids, timestamps and the one endpoint response.
The redesign hand-off says the branch adds no test for the `#config` arm. It
does: 4e46aa1 adds the_config_graph_is_addressable_by_its_full_iri, which
covers `db()` on both spellings -- `urn:fluree:{ledger}#config` and the bare
`{ledger}#config`. Port it unchanged rather than rewriting it; it is the one
row the branch got right, and its comment states the mechanism correctly.

Narrow the contract file's overlapping test to the other entry point and the
rows the ported one does not reach: `db_with_default_context` (what the server
route and CLI use, and which also loads the default context and re-resolves
config after selection), `#txn-meta`, the no-fragment default, and the
negative for an unknown ledger. Cross-reference both ways so a reader knows
why there are two.

Note for anyone extending the ported test: it uses FlureeBuilder::memory(),
so the ledger is never indexed -- but that cannot weaken it, because
`GraphRef::Config` resolves to the CONFIG_GRAPH_ID constant with no registry
or binary-store lookup, unlike `GraphRef::Named`. The store-backed leg is
exercised instead by ledger_info_resolves_reserved_graphs_by_exact_iri_not_suffix,
which publishes an index first.
`--format` accepted five data-format spellings and advertised two; the
update twin accepted seven and advertised three. So `--format ttl`,
`json-ld`, `json`, `sparql-update` and `opencypher` all worked while the
only text telling a user what to type said they did not exist.

The failure mode is specific to where this message appears. A user reading
it has already guessed wrong once, has no other enumeration of the valid
values, and will pick from the list in front of them — so a list shorter
than the code accepts converts a working spelling into a second wrong
guess. Both messages now name the aliases alongside the canonical form.

Found while fixing `docs/ledger-config/README.md`, whose broken
`fluree insert --format trig` lands a reader on exactly this error. Two
tests pin each message against its own match arms, so an arm added without
updating the text fails rather than silently hiding a spelling.
`INSERT DATA { GRAPH <urn:fluree:{ledger}#txn-meta> { … } }` committed, and the
triples landed in g_id 1 beside genuine commit provenance. That matters because
`ledger_view::resolve_commit_prefix` and `time_resolve::commit_to_t` answer a
user-typed commit prefix by scanning exactly the `fluree:commit:sha256:<hex>`
subjects in that graph, and they trust what they find. Injecting a record whose
digest shares a real commit's 12-character prefix permanently shadows that
commit: `fluree show <prefix>` returns "Ambiguous commit prefix", and `--at`,
`@commit:`, `fluree history` and `branch create --at` stop resolving it. It
needs only ordinary write access and survives indexing. Real commits stay
loadable by full id and the DAG is intact, so this is availability of the
commit-lookup surface, not corruption of history.

The rule was already decided twice. `1cb3e8cb2` introduced
`TransactError::ReservedGraphTarget` for graph management (CLEAR/DROP/COPY/MOVE/ADD
target, source and destination); `0bb792a97` extended it to graph sync, checking
by IRI shape independently of registration so a ledger whose registry never
seeded its system graphs still refuses them. `parse/txn_meta.rs` states the same
rule a third time for the txn-meta sidecar, as a reserved-predicate-namespace
allowlist. Each commit guarded the channel it was building. Ordinary
`GRAPH <iri> { … }` data writes were nobody's channel, so they were never
covered — the wrong turn is that the rule was re-implemented per feature instead
of being placed where write targets are decided.

Guard `txn.graph_delta` at the top of `stage()`, which is where a user-supplied
graph IRI first becomes routable. `graph_delta` is a write-target set: a GRAPH
block, a `WITH` default, a sync target, a `CREATE GRAPH`. WHERE-side references
(`USING [NAMED]`, a `GRAPH` pattern inside a WHERE) ride on the where clause
instead, so this refuses writes without touching reads. The system's own
provenance write cannot reach it: commit metadata is synthesized in
`finalize_state_with_base` and appended to `all_flakes` after staging, never
building a `Txn`. Graph management dispatches to `stage_graph_mgmt` before this
point, so the four pre-existing sites are untouched, and replay/push goes
through `stage_flakes`, so an existing ledger holding a forged record stays
loadable rather than being stranded.

Matched by IRI shape and by what the IRI routes to, so any spelling resolving to
g_id 1 is refused. `#config` (g_id 2) is deliberately NOT covered here:
`docs/ledger-config/` documents maintaining configuration through an ordinary
transaction, so refusing it would contradict shipped docs. Whole-graph verbs
still refuse both, because they destroy or re-home a graph rather than adding
facts to one. `ReservedGraphTarget` is reused and its message generalized from
"graph-management operation targets…" to "transaction targets…"; its doc comment
now records both coverage levels and why they differ.

Tests (it_reserved_graph_writes.rs): the SPARQL spellings, the JSON-LD twin, and
TriG — which reaches `graph_delta` through a different parser and so gets its own
case rather than being assumed covered — are each refused with the graph named,
every one paired with a user-graph control. The prefix-collision defect is pinned
end to end through `LedgerView::resolve_commit`, asserting the real commit still
resolves BEFORE asserting the write was refused, so reverting the guard fails on
the symptom rather than the mechanism. `#config` stays writable, pinning the
asymmetry against a later tidy-up; commit provenance still lands in txn-meta; and
the whole-graph verbs plus sync still refuse both reserved graphs.

Non-vacuity: the four refusal/defect tests go red when only this guard is
reverted. The provenance test goes red when `stamp_graph_on_commit_flakes` is
no-opped, so it detects a broken system write rather than passing vacuously; the
two "did not disturb" tests stay green under both mutations, which is their role.
`cargo clippy --all --all-features --all-targets -- -D warnings` rejects
`uninlined_format_args`, and this helper interpolated `prefix` inline while
passing `candidates` positionally. Cosmetic; the rendered message is
unchanged.

Worth noting how it got in: the workspace clippy gate was green before this
commit's parent was cherry-picked, and the rebase onto origin/main was
conflict-free. Neither told us anything — the helper simply had not been in
the tree when the earlier gate ran.
`parse_graph_selector_field` refused `{"@id": "L#txn-meta", "graph": …}` as
ambiguous — the identifier already picked a graph, so an explicit selector
contradicts it — but read only that one fragment. `#config` addresses a
reserved graph the same way, so the same contradiction silently took one of
the two and ran.

The selector's own error message had the matching gap: it named `'default'`
and `'txn-meta'` while `GraphSelector::from_str` now accepts `config` too.
Same shape as the two CLI `--format` messages in this PR — a list shorter
than what the code accepts, in the one place a user reads to find out.

Raised in review by bplatz, who named this site specifically alongside
`GraphSelector::from_str` and the server's `looks_like_graph_selector_only`.
The other two were already covered; this one was not.
`convert_named_graphs_to_templates` rejects three kinds of user-authored
TriG, and two of them still went out through `ApiError::query`, so a
mistake in a file arrived as `Internal error: Query error: undefined
prefix: ex` — which reads like a fault in Fluree rather than a problem with
the input, and maps to the wrong HTTP class. `ApiError::Transact(_)` is
what `fluree-db-server/src/error.rs` maps to `errors::INVALID_TRANSACTION`
/ 422.

The three tests assert the error *variant* rather than the message. That is
the point: the rendered message is identical either way, so the existing
text assertion passed whichever type came back and pinned nothing. The
reserved-predicate refusal had been retyped earlier in this PR with no test
at all behind it; it has one now.

Raised in review by bplatz, who noted both that nothing pinned the retyping
and that the sibling refusals in the same function still rendered as query
errors.
@aaj3f
aaj3f force-pushed the feat/claims-followups branch 2 times, most recently from b83a1af to 4072042 Compare September 15, 2026 15:32
@aaj3f

aaj3f commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

@bplatz — thank you for this, and sorry for the awkward timing: the branch you reviewed no longer exists. I force-pushed a near-total rework over it a few hours after you approved, so every one of your inline comments is now anchored to a commit that isn't in the history.

The short version is that I wasn't happy with how the first Claude Code session had gone at this, and as I (human Andrew) was reviewing it, I believed the PR to be a bit willy-nilly about some patterns that we as maintainers have been deliberate about. It fixed all six of the things a real run of the claims scenario turned up, and every fix was sited where the symptom showed up rather than where the rule that governs it actually lives. So I had a second session do a design pass over it before doing anything else, and the rework that came out of that replaces the approach rather than patching it — one predicate consulted by all four walkers instead of a guard on one; the commit-id encoding instead of the abbreviation width; the reserved-graph contract written down as a contract; and so on.

What's genuinely striking, and the reason I wanted to write this out rather than just say "reworked, please re-review", is how much of your review and that design pass landed on the same things independently. Going through yours in order:

log.rs:249 — the abbreviation can't be pasted into fluree show. Same finding, and you got there with a cleaner repro than we did. You also independently spotted both of the things that made the first attempt not-a-fix: that the first ~12 characters are constant header, so -n 1 prints pure header; and that a width computed from the displayed rows is unstable and only checks uniqueness against what's on screen rather than the ledger. Your suggested direction is what the rework does — ContentId::digest_hex(), abbrev_len deleted entirely. We went with 12 hex characters rather than 7, mostly because 12 is already the repo's canonical prefix length elsewhere and it leaves margin over the resolvers' 6-character floor; happy to go to 7 if you'd rather match the git habit more closely. And you were right that the test was the tell — fabricated ids, never fed back through prefix resolution. The replacement asserts round-trip through the resolver and includes the single-id case, which is exactly where the old code failed.

log.rs:178 — buffering the whole chain. Same finding, and your "if the width computation goes away, this can go back to streaming" is precisely how it resolved. run_local now calls Fluree::commit_log and the hand-rolled nameservice lookup, branched store and DAG walk are gone. Measured peak RSS on a 40-commit chain: 22.5 MB before, 73.7 MB on the branch you reviewed, 21.1 MB now. A side effect worth knowing: --direct and the auto-routed path are now byte-identical, where before they gave different answers to the same command and only one of them could OOM.

pattern.rs:626 — the var-length refusal only catches the bare rel var. Your table and ours are nearly the same table, down to relationships(p) being the more common spelling and UNWIND/WITH being unreachable from name-matching at lowering time. Where we ended up differs from your suggestion, and I'd like your read on it. You proposed making the evaluator raise on a property read against a synthesized relationship value with no annotation behind it. What the rework does instead is make the read work: a bounded single-typed directed range already expands to real triple patterns over row variables, so each hop now gets the same Optional([EdgeAnnotation]) + coalesce(?ann, MakeRel(…)) shape a single -[r:T]-> hop has had since 9e72f0499, and the element becomes the reifier node rather than a reconstruction of it. relationships(p), [r IN rs | r.p] and UNWIND rs AS r … r.p then all resolve, without a discriminator for any of them, because they all bottom out in the same Binding::Sid arm. The refusal survives only for genuinely enumerated ranges, where there's no per-hop identity to hand back. Your evaluator-level suggestion would still be the right backstop for that route, and I didn't build it.

Worth adding, since it reframes the whole item: git log -S on the message I was replacing turned up 9f837575e, where you'd already decided the row-multiplicity contract for the inline {p: v} form — "one row per matching annotation, matching the single-hop property-filter semantics" — and deferred exactly "the combination with a rel/path binding". That deferred shape is the one this closes, by the same mechanism. So this is less a rework of var-length semantics than finishing that commit, which I've said in the PR body.

fluree_ext.rs:79 — this reopens what 8d8870ba1 closed. You called for a decision before the arm lands, and laid out two options. The rework takes your first one, essentially item for item: the 8d8870ba1 gate relaxed (admitting a reserved graph only when the clause names this ledger's exact config_graph_iri/txn_meta_graph_iri), its test inverted into a positive plus a new negative, and config added wherever txn-meta was special-cased — GraphSelector::from_str, the server's refreshable_ledger_id, and, after your comment, parse_graph_selector_field's ambiguity check, which we'd missed. There's a section in the PR body addressed to you specifically with the archaeology, but the part I'd most like you to check is this: single_db_user_graph_id opens with if self.dataset.is_some() || iri == ledger_id { return None; }, and its own doc says it returns None "when a dataset scopes the named set (FROM NAMED)". So the enumeration filter that 8d8870ba1 cites as justification excuses itself precisely when an explicit FROM clause is in play. If I'm reading that right, then addressing and enumeration were never the same surface and the gate was arguing from a function that doesn't apply to it — but you know that code far better than I do, and if I've got it wrong the fallback is a one-line correction to docs/ledger-config/writing-config.md:182-191, which has documented this as working since the v4 baseline and never has.

Also: you were right that CI couldn't see the conflict, and right about why. GRAPH ?g enumeration and bare GRAPH <…#config> stay blocked, and there's now a negative test pinning that — which, for what it's worth, is only non-vacuous under the opposite mutation. Reverting the fix leaves it green, correctly, since what it pins is that nothing was opened; it only goes red if admission is widened to a suffix match.

bundle.rs:299 — dedup() before sort(). Same finding, same fix, and you were also right that none of the tests covered an annotation offending in two graphs. The new one loops 500 times, because the count varies with HashMap iteration order and a single-pass assertion would have been a flaky test rather than a failing one.

edge_annotations.rs:1610 — aliased @type defeats the check. Same finding. opaque_subtree now reads the key through ParsedContext's type_key the way the node walker does, and accepts the keyword, the absolute rdf:JSON IRI, or any compact IRI expanding to it via the same expand_datatype_iri the literal parser uses.

edge_annotations.rs:1605 — doc comment attached to the wrong function. Fixed; is_jsonld_value_object has its own doc back.

edge_annotations.rs:1656 — the two contradictory comments. Resolved by deletion rather than by rewording — that call-site special case is gone entirely, since once the scanner owns the rule it's redundant. The behavior it encoded (a deferred keyword in a non-@value sibling is still refused) is now pinned by a test, which it wasn't before.

turtle.md:480 — documenting a bug as a rule, and #1832. Taken, and thank you for the pointer to #1832; I hadn't connected them. The doc now points at the spelling that works rather than presenting the limitation as a rule, and the PR body carries Follow-up: #1832 for the root cause. You were also right about both commands in docs/ledger-config/README.md:208 — the insert --format trig one and the --format sparql query below it. Both are fixed. Chasing that turned up something slightly worse, which I've fixed in the same PR: --format on insert accepted five spellings and its error named two, and on update accepted seven and named three. So --format ttl and --format opencypher both worked while the only text telling a user what to type said they didn't exist.

tx.rs:2399 — nothing pins the retyping, and the siblings still render as query errors. Both halves taken, and both folded into this PR rather than punted. You were exactly right about the test: it only checked message text, and the message is identical whichever type comes back, so it passed either way and pinned nothing — the retyping had in fact been carried over into the rework with no test behind it at all. The three tests now assert the variant. And undefined prefix and named graph triple missing subject are transact errors too, so a mistake in a TriG file no longer arrives as Internal error: Query error: undefined prefix: ex. Reverting either retyping turns its own test red, which I checked rather than assumed.

Two of yours I have not addressed, and I'd rather name them than let them disappear with the force-push:

  • turtle.md:473 — your point that a note about query patterns doesn't belong in the Turtle transactions doc is well taken and I didn't move it. What I did do is add a sentence explaining why that trap gets prose while the var-length property read gets a hard refusal, which is a different question than the one you asked. Happy to relocate it to the query-side edge-annotation docs.
  • annotation_use.rs:29, and the general note about comments telling the story of the fix — the merged doc comments are fixed, but the broader point stands and this rework arguably makes it worse, not better. There are some long "why" comments in the new guard and around the reserved-graph contract. My defence, such as it is, is that a couple of them are recording a contract that had been re-derived three times in three different vocabularies rather than narrating a debugging session — but you're right that "the first attempt did exactly that" belongs in a commit message, and I'll take another pass with your one-line-why test in mind.

On process, so this doesn't happen again: I should have told you the branch was under rework before you spent time on it. The commits you reviewed are recoverable from the force-push record if you want to see any of them alongside the replacement. No obligation to re-review the whole thing — but the #config section is the one place where the rework reverses a decision of yours on purpose, and I'd genuinely like your read on whether the single_db_user_graph_id argument holds before this merges.

The case for re-admitting `FROM <urn:fluree:{ledger}#config>` is that
reachability is explicitness and policy decides who may read. The measurement
behind that claim was taken on the connection path; the gate being relaxed is
the ledger-scoped one, so the claim was argued on a different surface from the
one it defends.

`policy_still_governs_a_reserved_graph_admitted_by_full_iri` asserts it where
it matters: same ledger, same query, one variable. Unwrapped, `FROM <#config>`
returns CONFIG-MARKER — the control, without which a zero-row result below
would prove nothing. Wrapped in the ledger's own `f:defaultAllow false`, it
returns nothing. Removing the policy triples turns the second assertion red.

Also two corrections in `fluree log`:

`commit_id_of`'s final `address.to_string()` was unreachable — `rsplit('/')`
always yields at least one item, so the `if let Some(..)` always matched and
the fallback below it could never run.

`print_truncation` told a caller who had just passed `--all` to pass `--all`.
The server applies its own cap regardless, so for that caller the honest line
names the cap rather than repeating the flag they used.
`scan_list_iteration` scans an `all/any/none/single`, `[x IN L | …]` or
`reduce` body into its own `ScopeUses` and folds the result into the enclosing
scope. That carried the loop variable's NAME up with it, so a same-named
relationship variable bound elsewhere in the same scope was lowered
annotation-dependent — the bare `Pattern::EdgeAnnotation` lane, which matches
only reified edges — and its unreified rows disappeared with no signal.

The loop variable cannot legitimately name a row variable: `lower/expr.rs`
binds it with `bind_local` at all three iteration sites, so it is loop-local by
construction. Drop it from the body's annotation set after the `contains` check
that licenses the element-property conclusion, and before the fold.

The removal also closes the shadowed-nesting case in the other direction:
`[x IN rs | [x IN ys | x.p]]` no longer marks `rs` element-property dependent
on the strength of a read that belongs to `ys`.

The module doc listed the scan's residuals and this was a third one; it now
records the loop-local rule instead.
`augment_select_with_path_rel_lists` pushed a bounded fixed-chain expansion's
identity-carrying relationship list into the `WITH`'s select list whenever a
projected variable had one, with no check on the projection. By that point
`Grouping::assemble` has already fixed the group keys, so on an aggregating
`WITH` the list is neither a group key nor an aggregate output: it reaches the
RETURN as a `Binding::Grouped`, and `Expression::Var` only short-circuits
`List`/`Map` bindings in `try_eval_to_binding`, so any read of it falls through
to the comparable path and trips `debug_assert!(false, "Grouped binding in
filter evaluation")` (`fluree-db-query/src/eval.rs:245`). That panics in every
dev, test and CI build; in a release build the assertion is compiled out and
`coalesce` silently falls back, so the defect was invisible to shipped binaries.

`WITH p, count(*) AS c RETURN c, [r IN relationships(p) | r.confidence]`
reproduced it, as did `size(relationships(p))` and the fixed one-hop path form
`p = (a)-[:KNOWS]->(b)`, which re-enters the same machinery as `*1..1`.

Gate the augmentation on the projection: an aggregating `WITH` drops the list,
which is exactly the fallback the `coalesce` rewrite in `lower/expr.rs` already
documented — "a `WITH` that projects the path variable without the list (an
aggregating one, whose group keys we cannot extend) drops the list". The
comment described behaviour the code did not implement; it does now. The path
value still answers `size()`, `type()` and the endpoints, and the per-hop
properties read null.

`has_aggregates` is captured alongside `list_outputs`, before `aggregates` is
moved into `Grouping::assemble`. `Grouping::assemble` returns `None` when both
`group_by` and `aggregates` are empty and `lower_with` only populates
`group_keys` when aggregates exist, so a non-empty `aggregates` is exactly the
condition under which a grouping stage exists here.

The test also pins the documented workaround — reading the properties into a
projected value before the grouping `WITH` — so the doc advice is CI-enforced.
The enumeration-route refusal keys on `reads_element_properties`, and
`scope_uses` only ever mapped an `UNWIND` alias back to its source list. A
`WITH … AS` rename was invisible to it, so `WITH b, rs AS xs WHERE all(r IN xs
WHERE r.confidence > 0.8)` attributed the element reads to `xs`, left `rs`
unmarked, and lowered the pattern onto the enumeration route — which retains no
per-hop edge identity and answers `[]`. That is the silent wrong answer the
guard exists to prevent, reached by renaming the list.

The two aliases need different keys, because they rename different things. An
`UNWIND` alias is a *row* variable, so it lands in `annotation`; a `WITH` alias
is the *list*, so it lands in `element_property`. Walk each `WITH` item that
has an alias and, when the alias is element-property dependent, add the
variables its expression names.

Reusing `collect_rel_list_vars` for that walk — rather than reading the alias
itself — is what keeps `WITH nodes(p) AS ns … [n IN ns | n.name]` allowed: the
walk skips `nodes()`, so aliasing a node list contributes nothing and does not
drag `p` into the refusal.

Iterate to a fixpoint. `rs AS xs` … `xs AS ys` and a `WITH` alias later
consumed by an `UNWIND` both need the renames to compose, and clause order does
not guarantee a single pass resolves them. Each pass only inserts, over a name
set bounded by the statement's own identifiers, so it terminates.

Over-approximating here stays safe for the same reason the module doc already
gives: `element_property` has exactly one consumer, a refusal, so a false
positive costs an actionable error rather than a wrong answer.

The test adds the four alias spellings plus two assertions that the walk does
not over-refuse — the bounded route still answers through the same alias, and
an aliased `nodes()` list stays readable.
`lower_multi_hop_path` binds `p` with `MakePathHops` over the chain's node refs
and per-hop `MakeRel` values. A synthesized relationship value has no reifier
slot, so `[r IN relationships(p) | r.confidence]` over
`p = (a)-[:KNOWS]->(b)-[:KNOWS]->(c)` answers `[null, null]` even when both
edges carry annotations — while the same two paths written `-[:KNOWS*2..2]->`
answer `[0.9, 0.95]`, and the one-hop path form answers `[0.9]`, because
`single_fixed_hop` re-enters the var-length machinery and this route does not.

That is a wrong answer, not a missing feature, and `docs/query/cypher.md` now
states that edge properties are present for a reified edge — which this route
made false. Refuse the read instead, the way `lower_enumerate_path` already
refuses it for the other identity-less route.

The refusal is scoped to the element *property* surface. `nodes(p)`,
`length(p)`, `size(relationships(p))` and `type(r)` over the elements all
answer correctly here and stay available; only the read that could not be
answered is rejected.

The message names a remedy that costs the user nothing: binding each hop's
relationship variable keeps `p` bound alongside them, and every fixed hop
already takes the annotation lane through `push_rel_triple`, so
`(a)-[r1:KNOWS]->(b)-[r2:KNOWS]->(c)` reads 0.9 and 0.95. When every hop shares
one type it also names the equivalent bounded range; a mixed-type chain has no
single range that expresses it, so the message does not invent one.

The alternative — giving this route identity — is the same per-hop
`Optional([EdgeAnnotation])` probe the bounded expansion emits, and belongs on
top of that probe's cost model rather than adding a second caller of it. When
that lands, this refusal becomes dead code and comes out.

Residual, stated: `reads_element_properties` does not see
`properties(relationships(p)[0])`, which lands in the `annotation` set instead.
The enumeration guard has the identical hole; widening one without the other
would let the two routes diverge.
Binding a path variable alone — no relationship variable, no property read
anywhere — allocates the identity-carrying list too (`rel_list_var` falls
through to `fresh_synth` when `path_var_id` is set), so the per-hop probes fire
and a hop carrying parallel claims multiplies the rows. On the parallel-claims
fixture `MATCH p = (a)-[:KNOWS*1..2]->(b) RETURN b.name` goes from
`[Bob, Carol]` to `[Bob, Bob, Carol, Carol]`.

That is consistent with the stated contract and with the one-hop path form, but
it is a visible change to existing path queries over reified ledgers and the
test pinned only the rel-var spelling. Assert the path-only form, and assert
alongside it that the form binding neither `p` nor a relationship variable
still answers once per reachable node — which is the spelling to reach for when
the claims are not wanted.

Verified non-vacuous by removing the `path_var_id` arm of `rel_list_var`: the
path-only assertion then reports exactly the pre-change `[Bob, Carol]`.
Closes the residual stated in 098e0a401, and closes it for both identity guards
at once rather than patching each.

`properties(rs[0])`, `keys(head(rs))` and `properties(last(relationships(p)))`
read a single hop out of a relationship list, which is an element-property read
— the conclusion `scan_list_iteration` already draws for a loop body, reached
here without a loop variable. The scan filed those variables under
`annotation`, and that set is keyed on ROW variables: for the list or path
variable named here it is inert, so nothing consulted it and the read reached a
route with no per-hop reifier and answered null.

Measured on the claims chain before this change: `properties(rs[0])` on a
bounded range returns `{"confidence": 0.9}`, while the same read over an
enumerated range returns null on every row — the silent asymmetry the guards
exist to make visible.

The fix is one predicate in the scan, not one per guard. `element_extraction_source`
recognises the extraction and routes the LIST's variables into
`element_property`, which both `lower_enumerate_path` and `lower_multi_hop_path`
already consult, so they close together by construction.

It is additive: `annotation` is left exactly as it was, so no lowering lane
changes and no row can be dropped by it. `element_property`'s only consumers
are the two refusals, so the worst case is an actionable error.

Deliberately narrow. `tail(rs)` and a bare `rs` yield a list rather than an
element, so `properties(rs)` stays unmarked — it is not an element read, and
answering it with the identity refusal would name a remedy unrelated to what
was asked. `nodes()` is skipped by `collect_rel_list_vars`, so
`properties(nodes(p)[0])` keeps reading its node's properties on every route.

The `.prop` spelling needed nothing: a property accessor already requires a
bare-variable target, so `relationships(p)[0].confidence` is an actionable
error everywhere. `properties()` and `keys()` carry no such restriction, which
is what left this one open.
Each `Pattern::Optional([EdgeAnnotation])` probe planned to its own
`AnnotationValueOptionalBuilder`, which drained the three `f:reifies*`
predicates into its own hash maps. That drain is O(#annotations in the
ledger) and independent of the result size, and a bounded variable-length
Cypher range emits one probe per hop of per chain: `*1..1` one, `*1..3`
six, `*1..5` fifteen. Binding `rs` in `-[rs:T*1..5]->` therefore paid for
the whole sidecar fifteen times, including on queries that bind the
variable and never read an edge property.

Move the memo from the operator up to the `ExecutionContext`, beside
`const_sid_cache` and the other per-run memos, with the same scoping:
shared across `with_active_graph` / `with_default_graph`, reset by
`with_graph_ref`, which is where snapshot, overlay, `to_t` and the policy
enforcer can change. The required lane
(`HashAnnotationEdgeProbeOperator`) goes through the same entry point, so
a query mixing the two lanes drains once between them rather than once
each.

The key is what a drain FILTERS on, not the patterns verbatim. Variable
positions collapse — each reifies triple is planned as a standalone
unseeded single-pattern scan, so a variable filters nothing and the maps
it builds are keyed by `Sid`, not by the variable a value was read out of
— while constant positions, `dtc`s, the graph id and the planning context
are all kept. Keying on the three reifies patterns alone would serve a
`LIKES` probe from a `KNOWS` drain and answer a reified edge as
unreified; that is what
`cypher_var_length_probes_of_different_types_do_not_share_a_drain` pins.

Release build, indexed ledger, 20k reified edges:
`-[rs:KNOWS*1..3]->` 292 ms -> 49.0 ms, `-[rs:KNOWS*1..5]->` 735 ms ->
49.7 ms, against 49.3 ms for a single bound hop. The unbound form is
untouched at 125 us: `annotation_probe_possible` emits no probe, so no
lookup happens. New bench `annotation_varlength_probe` holds the shape.
@aaj3f
aaj3f merged commit 9a0b9d5 into main Sep 15, 2026
16 checks passed
@aaj3f
aaj3f deleted the feat/claims-followups branch September 15, 2026 20:52
bplatz added a commit that referenced this pull request Sep 15, 2026
…iple-term

Brings in #1838. Two resolutions:

- docs/transactions/turtle.md: union of both TriG sections; main's copy of
  the claims-file upsert paragraph is dropped, as this branch already has it.
- fluree-db-api/src/tx.rs: #1838's two new NamedGraphBlock tests gain the
  `reified: Vec::new()` field this branch added (auto-merged but did not
  compile).
giodamelio pushed a commit to giodamelio/db that referenced this pull request Sep 29, 2026
Bulk import bypasses `stage()`, so fluree#1838's data-write reserved-graph guard
never sees a `GRAPH <urn:fluree:{ledger}#txn-meta> { ... }` block. The parser
assumes otherwise -- `parse/trig_meta.rs` notes that "a write to the ledger's
full txn-meta IRI is refused in `stage()`" -- and that holds for every write
surface except this one.

The result was a record that is correct and invisible. The import path
allocates the reserved g_id correctly (the shared graph allocator is pre-seeded
with both reserved IRIs), and the commit writer encodes the flakes faithfully.
The loss happens afterwards, in the index builder, which is graph-scoped: each
pass filters records against a single `target_g_id`, `g_id 1` is built only
from the synthetic commit-metadata chunk, and `g_id 2` has no pass at all. A
correctly-routed record from a data chunk is therefore filtered out of every
index segment while staying durable in the commit blob.

Refuse both reserved IRIs at the top of the named-graph loop, by literal IRI
and again by the g_id the block resolves to. `#txn-meta` reuses
`ReservedGraphTarget`, so the message matches every other refusing surface.
`#config` gets a new `ConfigGraphImportUnsupported` variant instead: ordinary
transactions may write ledger configuration, so refusing it at import is a
capability gap rather than a policy, and the two must not read alike.

The `<#txn-meta>` sentinel spelling is untouched: `parse_trig_phase1` routes it
to the commit envelope's `txn_meta` field, so legitimate commit metadata never
reaches this loop. A test pins that, so the guard cannot later be "tightened"
to match the fragment.

Cost on the common path is zero. The guard is per graph block, not per triple
or per flake, and a single-graph import never executes it at all --
`import_trig_commit` early-returns to `import_commit` before the loop exists
when a file names no graphs.

Tests assert the end-to-end property rather than a local one: for a TriG file
naming any graph, the import is either refused or the block reads back, never
committed-and-unreachable. That is the shape that catches this class, since the
write path is correct. Coverage includes `#config`, which the issue never
tested, and an unindexed reload -- on an indexed ledger the dropped records
read as "absent", so an indexed-only test reports the benign answer.

Fixes fluree#1846
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants