Skip to content

Reject Cypher alias collisions that silently returned zero rows - #1867

Merged
bplatz merged 17 commits into
mainfrom
fix/cypher-alias-collision
Nov 17, 2026
Merged

bplatz merged 17 commits into
mainfrom
fix/cypher-alias-collision

Conversation

@aaj3f

@aaj3f aaj3f commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1857

Update, 2026-11-17

Brought up to date with main, with two changes of scope:

  • Cypher only. The JSON-LD half (a bind, unwind or select alias onto a bound variable) is removed, so this PR no longer touches fluree-db-query and nothing changes on the JSON-LD or SPARQL path. That guard ran over every JSON-LD query's where clause at lowering, unmeasured, and next treats a JSON-LD rebind as an equality check (jsonld_bind_into_a_bound_variable_checks_it_when_only_counted). The sections below now describe the Cypher change only.
  • The CALL-body guard reads the imports after a WITH as well. A CALL seeds its imports into every row of its body, so CALL (a) { MATCH (x:Person) WITH x WITH x.name AS a RETURN a AS z } still returned 0 rows past the previous guard, which dropped the imports after a WITH. The same held for UNWIND … AS a. Both are now rejected, and pinned.

The alias guard also now shares #2096's identity rule: x AS x projects bare and never reaches it. The fresh-alias forms inside a CALL return one row per outer row on main (its CALL correlation fix), so that test now asserts the count.

The bug, in one sentence

RETURN expr AS v where v is already bound is silently WHERE v = expr, projecting v.

An alias interns through the statement-wide VarRegistry, which is a name↔id bijection (fluree-db-query/src/var_registry.rs:49), so an alias whose text equals an already-bound variable's name is that variable — same VarId, by construction. The projection emits a Pattern::Bind onto a bound variable, and BindOperator's deliberate clobber prevention (fluree-db-query/src/bind.rs:249-262) then either drops the row (the computed value differs from the existing binding) or keeps the stale value (the computed value is unbound). Everything in the issue falls out of that one sentence.

Against a three-edge KNOWS chain:

RETURN a.name AS aname          -> ["Alice"],["Bob"],["Carol"]   correct
RETURN a.name AS a              -> []
RETURN r.confidence AS r        -> []
RETURN a.name AS b              -> []
RETURN id(a) AS a               -> []
RETURN a.name AS x, b.name AS x -> []     two columns backed by one VarId
WITH a.name AS a RETURN a       -> []

The issue frames this as two failure modes split by node-vs-relationship. It is one, and the discriminator is only whether the projected expression evaluated to null. a.`@id` is unreadable today, so it computes Unbound, the matches!(computed, Binding::Unbound) arm keeps the row, and the old node binding survives — which is why RETURN a.`@id` AS a looks like it works. a.name computes a value, so every row is dropped. Proof that the node/relationship split is not the discriminator: RETURN a.name AS a — a node variable with a perfectly readable property — returns zero rows, exactly like AS r.

It is worse than reported: the write path commits and writes nothing

MATCH (p:Person)-[:KNOWS]->(q) WITH p, q.name AS qn SET p.marker = qn
  -> commits; markers = ["Bob", "Carol", "Dave"]

MATCH (p:Person)-[:KNOWS]->(q) WITH p, q.name AS q  SET p.marker = q
  -> commits with NO error; markers = []

A one-character change to an alias turns a working SET into a transaction that succeeds, returns no error, and writes nothing. Every row is dropped, so the Update's WHERE matches nothing and zero flakes are staged. Reachable through transact_cypher, and therefore Bolt and the server's Cypher write endpoint.

Why reject rather than shadow

Because this codebase already made exactly this decision, for exactly this mechanism, one function away in the same file — and simply never generalized it. fluree-db-cypher/src/lower/stmt.rs:1444-1460 on main, the CALL-subquery guard:

Cypher forbids a subquery RETURN that re-introduces ANY name already bound in the outer scope (not just an import) — the executor would treat the collision as an existing parent var and silently drop the subquery's value. Reject rather than shadow. Synthetic ?#__* vars are excluded from outer_set already, so they can't false-trigger.

Someone diagnosed the identical failure in the identical words, chose rejection, and pinned it with three assertions in it_query_cypher.rs. #1857 is that guard never reaching the top-level projection.

It is also a violation of a published contract. docs/query/cypher.md:724-726 promises that anything unsupported returns "a clear error, never a silently wrong result."

This is a deliberate and temporary divergence from openCypher. Neo4j treats WITH/RETURN … AS v as a projection into a new scope, so MATCH (n) WITH n.name AS n RETURN n is a working idiom there and a migrating user will hit this error. True re-projection needs four things, and the fourth is a column-label channel in the shared IR: VarRegistry is a name bijection and the Cypher column header is literally result.vars.name(v) (fluree-db-api/src/format/cypher.rs:67), so a fresh VarId cannot carry the display name n, and ir::Column has no label field. That was written as a shared-IR change reaching the SPARQL and JSON-LD formatters. Having checked it, that overstates the blocker, and the correction matters because #1870 is titled and sized against it.

ir::Column genuinely has no label field, but the Cypher formatter reads headers from result.vars.name(v) (fluree-db-api/src/format/cypher.rs:67) and QueryResult is defined in the api crate (fluree-db-api/src/query/mod.rs:112), so a Cypher-only channel can live there without the other formatters seeing it — and Query::cypher_vocab (fluree-db-query/src/ir/query.rs:310) is existing precedent for exactly that: a Cypher-only field set after lowering and read only Cypher-side.

Of the three places a fresh synthetic VarId could be resisted: grouping keys off VarId and is indifferent; Bolt has no vars.name call anywhere in fluree-db-bolt/src, so it inherits the api-side channel — inferred, not traced end to end; ORDER BY does resist, and it is the real remaining blocker. align_order_by_with_projection (fluree-db-cypher/src/lower/stmt.rs:757) matches an ORDER BY expression against projection items by surface expression, so RETURN n.name AS n ORDER BY n would not match the item and would fall through to interning the original node variable.

Verdict: holds partially. The blocker is Cypher-lowering-local rather than shared-IR, with the name-to-variable rebinding layer as the genuine work — so #1870's title is wrong while its P3 sizing remains defensible. docs/query/cypher.md is corrected in this PR; #1870 itself is not mine to amend. An error still beats a wrong answer in the meantime.

Follow-up: #1870

What is rejected, and what is not

Rejected: RETURN/WITH expr AS v where v is bound at clause entry; and two projection items sharing one output name (AS x, … AS x), which Neo4j also rejects.

Still legal, and pinned by tests:

  • the identity projection RETURN v AS v, and WITH a AS a, b AS b — binding a variable to itself recomputes the value it already holds, so no row can be dropped. it_query_cypher.rs:10224 depends on this.
  • aliasing a name that a later clause binds: WITH pair[0] AS x, pair[1] AS y … OPTIONAL MATCH (x)-[…]->(y). Four live tests (it_query_cypher.rs:7249, 7274, 7353, 7425) depend on it.

That second case is the subtle part. The guard keys off the scope as it stood at clause entry, not the registry — a registry-wide check would break those four tests. It also snapshots once per clause rather than per item, because add_item pushes its own auxiliary Optional/Bind patterns into the same list, so a per-item recomputation would see item N-1's own bind as "already in scope". Synthetic ?#__* vars cannot false-trigger: an alias is a user-written identifier, and visible_vars_from_patterns filters them out anyway.

I scanned every Cypher statement string in fluree-db-cypher/, fluree-db-api/tests/, fluree-db-bolt/, fluree-db-mcp/, fluree-db-cli/, fluree-bench-virtual/ and docs/ for a newly-rejected shape: zero genuine regressions.

Two guards, because there are two lowerings

  • fluree-db-cypher/src/lower/stmt.rs — ProjectionState::check_alias. Covers every read RETURN/WITH, each UNION branch, each CALL branch, and the read prefix of a sequential (MERGE) write.
  • fluree-db-transact/src/lower_cypher_update.rs — check_with_alias. Covers the single-statement write path, which builds its own WITH horizon in lower_with_clause and never reaches ProjectionState. detect_sequential only routes to the sequential driver when a MERGE is present, so MATCH … WITH … SET lands here.

The second guard is the one that fixes the silent no-op write, and it is not optional: with only the first in place, the write-path test still fails. Both were disabled independently to confirm each is load-bearing.

Reuse throughout: visible_vars_from_patterns (already used by expand_star for RETURN *) for the scope snapshot, Pattern::produced_vars() underneath it, check_select_aliases in fluree-db-sparql/src/validate/projection.rs:112-175 for the two-branch structure (assigned-twice / already-in-scope) and its early-out.

Part (b): @id and @type are rejected, not made to resolve

The issue reports this as a discoverability problem — n.`@id` reads as null, and knowing about id(n) "would save that discovery". It is worse than that: on the write path the keywords are persisted as junk data today. SET n.`@id` = "zzz" commits and leaves the node with a literal property spelled @id while its real identity is untouched. That is a wrong answer written to the ledger, not a read-side nuisance.

So the issue asks for n.`@id` to resolve. It should be rejected instead, for three reasons.

1. Resolving it would make part (a) strictly worse, which is why the ordering matters. RETURN a.`@id` AS a returns the node today only because the accessor is unreadable, so the bind computes Unbound and the stale binding survives. A bound IRI string would compare unequal to the node binding and drop every row — turning a plausible-looking wrong answer into zero rows, exactly what RETURN id(a) AS a does today. Part (a) must land with or before part (b). In this PR it does: commit 1 is the alias guard, commit 2 the keywords. Rejecting has no such interaction — the query errors on the keyword, before the alias is ever considered.

2. The write path is already storing junk. This is not merely an unhelpful null read. Measured on main:

SET n.`@id` = "zzz"           -> COMMITS; keys(n) = ["@id", "name"]; identity unchanged
SET n.`@type` = "Q"           -> COMMITS; keys(n) = ["@type", "name"]; labels(n) still ["Person"]
CREATE (n:P {`@id`: "zzz"})   -> COMMITS; fresh blank node, `@id` stored as a literal property
MERGE  (n:P {`@id`: "zzz"})   -> COMMITS; creates a new node every time, never matches by IRI

A persisted wrong answer, and a data-quality footgun rather than a read annoyance.

3. There is no coherent resolve semantics anyway. id(r) on a relationship is a blank-node reifier label (_:fdb-…-fluree_ann_0), not an identity a user can act on; properties(n)/keys(n) would have to either invent a pseudo-key @id (wrong — it is not a property) or contradict the read; and SET n.`@id` would have to stay rejected while the read resolved.

Scoped wider than the issue asks, because the same mistake is reachable from more than the accessor: @type behaves identically, and inline property maps (MATCH (a:Person {`@id`: "alice"}) — silently zero rows), annotation property maps, comprehension member access and relationship types all resolve through resolve_predicate, which already rejects Fluree's own f:reifies* system predicates. The keyword check lands beside that precedent, one call site per crate.

Node labels did not, and that was a real hole in the first version of this PR. A label lowers to the object of an rdf:type triple rather than to a predicate, so the label sites called resolve_iri directly and routed around the check. Measured: MATCH (n:`@id`) returned zero rows silently, and SET n:`@type` committed, after which labels(n) read back ["Person", "@type"] — the same persisted junk, in the one position an earlier draft of this body claimed was covered.

I enumerated the fix rather than patching the reported instances: every resolve_iri( call site in both crates, classified. Eleven in total; seven are label resolution — fluree-db-cypher/src/lower/pattern.rs:319 and six in fluree-db-transact/src/lower_cypher_update.rs (MATCH, SET n:L, REMOVE n:L, the MERGE probe guard, ON CREATE/MATCH SET, and CREATE) — and the other four are the two definitions and the two calls inside resolve_predicate itself. Hits elsewhere in fluree-db-transact (lower_sparql_update.rs, parse/trig_meta.rs) are a different function, fluree_vocab::iri::resolve_iri(base, iri), doing base-relative resolution for Turtle/TriG, and are unrelated. Each crate gains a resolve_label that delegates to resolve_predicate, so there is still one choke point per crate rather than a second copy of the check.

Every message names the accessor that works — id(n) / elementId(n), labels(n), SET n:Label — which is what the issue actually asked for: those accessors are documented at docs/query/cypher.md:248-251, but a null gives a user no way to find them.

Rejecting is safe: a bare @id is not a legal Cypher identifier, it must be backticked, so no ordinary property name can collide with the reserved set. The check runs on the bare name before @vocab expansion — with a vocab set, @id would otherwise resolve to <vocab>@id and slip through.

Errors, as rendered

RETURN alias `r` is already bound by an earlier clause — assigning onto it would silently
drop rows or discard the projected value instead of returning it. Alias to a name that is
not already bound (e.g. `AS r_value`).

RETURN assigns `x` twice — two projected columns cannot share one output name, the second
would silently overwrite the first. Give each item a distinct name (e.g. `AS x2`).

rejected: WITH alias `q` is already bound by an earlier clause — assigning onto it would
silently drop every row, so the write would commit without error and without writing
anything. Alias to a name that is not already bound (e.g. `AS q_value`).

`@id` is a reserved JSON-LD keyword, not a Cypher property — a node variable already *is*
the node; read its identity with `id(n)` or `elementId(n)`.

`@type` is a reserved JSON-LD keyword, not a Cypher property — read a node's types with
`labels(n)`, match on one with `MATCH (n:Label)`, and add one with `SET n:Label`.

LowerError::generic on the read side, so the message renders verbatim rather than under unsupported in v1: — the wrong framing for a user error. The write side uses LowerCypherError::rejected (renders rejected: <msg>), matching that file's own convention; its Generic variant is used zero times there.

Performance

Free at execution. On the Ok path neither guard touches patterns, vars, group_keys, aggregates, post_binds or the grouping — they return Ok(()) or Err. The lowered IR is byte-identical by construction: no plan change, no operator change, no new pattern, no per-row / per-batch / per-flake cost, and no fast-path stamp or differential lane implicated.

Measured at lowering time (release, lower_cypher only, 20 000 iterations after 2 000 warm-up, median of repeated runs):

Statement shape before after delta
Heavy: 2 MATCH + OPTIONAL + 2 aliased WITH + 6-item aliased RETURN 5.44 µs 6.43 µs +0.99 µs
Typical: 1 MATCH, 2 aliased RETURN items 1.92 µs 2.18 µs +0.26 µs
No alias anywhere: 5 clauses, bare-variable projections 2.43 µs 2.44 µs noise

The third row is flat because ProjectionState::new skips the scope-snapshot walk entirely when no projection item carries an alias — the same early-out check_select_aliases uses. reserved_keyword_message returns on !key.starts_with('@') before its match, so an ordinary property key costs one byte compare rather than ~20 string comparisons; that is the most frequently executed of the three additions. Both optimisations were added after measuring, not before — the first cut was +18% on lowering and that was not acceptable.

The residual is ≲1 µs once per statement, at lowering, against query execution measured here in hundreds of microseconds to seconds. No path separation is needed: nothing here trades correctness for speed.

Tests

New tests across two files — fluree-db-cypher/tests/it_lower.rs (lowering) and fluree-db-api/tests/it_query_cypher.rs (Cypher end-to-end) — with the Cypher ones in one clearly delimited block per file headed by a comment naming #1857, so other issue slates can append beside them without a conflict.

Error tests assert the message names the colliding variable or keyword (an is_err()-only assertion would pass against any unrelated error) and assert it does not carry the unsupported in v1: framing. The highest-value single test is issue1857_alias_collision_does_not_silently_noop_a_write, which nothing in the suite covered.

Every rejection test was proven non-vacuous: guards reverted in the post-cargo fmt source, test targets touched, re-run. Each failed with the recorded wrong outcome — zero rows for the read collisions, an empty marker set for the write, a committed @id property for the reserved-key write, labels(n) reading back ["Person", "@type"] for the label write. The acceptance tests (identity projection, later-bound alias, ordinary property keys, a label merely spelled like a keyword) correctly keep passing under the revert, since they guard against over-rejection rather than under-rejection. The two part-(a) guards were also disabled independently, which is what established that both are load-bearing.

Gates — what ran, and what did not

Ran, all clean: cargo fmt --all --check (after the last edit); cargo clippy --all-targets --no-deps on fluree-db-cypher, fluree-db-transact, fluree-db-query and fluree-db-api (0 warnings each, recompile confirmed rather than reported clean from cache); and cargo test across fluree-db-cypher, fluree-db-transact, fluree-db-query, fluree-db-api — 77 binaries, 5783 passed, 0 failed, 126 ignored. fluree-db-sparql/bolt/mcp (707) and fluree-db-cli (366) were green on the pre-remediation head and are untouched by the changes since.

Did not run, stated rather than implied:

  • cargo clippy -p fluree-db-api --all-features. --all-features pulls fluree-search-* → cxx v1.0.194, which fails against my local C++ toolchain (fatal error: 'algorithm' file not found). I ran it with default features instead; the file edited there is a test target and was linted. CI is the first place the --all-features variant actually executes — and it has now done so: the clippy job (--all --all-features --all-targets -- -D warnings) passed in 5m16s, as did test (nextest --workspace --all-features) in 7m52s, so this gap is closed rather than merely disclosed. I confirmed the workflow runs were genuinely created via the API before reading their status, since gh pr checks renders pending and never-ran identically.
  • testsuite-sparql's separate fmt/clippy pair — not run, and it does not need to be: nothing under testsuite-sparql/ is touched, and fluree-db-sparql has its own lowering that this change never reaches. Its Format step does reach root crates, and cargo fmt --all covers those.
  • Bolt end-to-end against a live server — not exercised. Bolt reaches this code through the same query_cypher / transact_cypher entry points the integration tests use.

One flake observed and traced, not glossed: it_join_batched_overlay::batched_subject_join_merges_novelty failed once under whole-crate concurrency. It contains zero references to Cypher, passes in isolation, and grp_misc passes 295/295 three times running; span capture is process-global, which is the plausible cause. Unrelated to this change.

Breaking changes — every shape that now errors

breaking-change on its own tells a migrating user nothing about what to grep for, so here is the complete list. Every one of these previously ran and returned a wrong answer, zero rows, or a bad write; none of them errors for a reason other than the collision it names.

Cypher — a name used twice

Was accepted, now errors What it did before Write instead
RETURN expr AS v / WITH expr AS v, v already bound 0 rows, or the stale binding any unbound name
RETURN a AS a, a · RETURN a, a · RETURN a.name, a.name two headers, one column alias one of them
UNWIND <list> AS v, v already bound 0 rows UNWIND … AS v_item
any of the above inside a CALL { … } body, onto a name the body imports 0 rows any unbound name

RETURN v AS v and WITH a AS a, b AS b are still legal — binding a name to itself cannot drop a row. So is aliasing a name a later clause binds (WITH pair[0] AS x … OPTIONAL MATCH (x)…).

One of these is wider than the defect and deliberately so: UNWIND labels(a) AS a worked before and now errors. It worked only because referencing a forced the planner to keep the Unwind below the MATCH, where the operator shadows; the same statement with an uncorrelated list (UNWIND [1,2,3] AS a, UNWIND range(1,3) AS a) dropped every row. Correctness that depends on where the planner puts an operator is an accident that has not broken yet, not a supported behaviour, so both forms error rather than one being blessed.

Cypher — reserved JSON-LD keywords, in any name position

Every @-prefixed name is now rejected as a property key, node label or relationship type, on read and write — the rule is the prefix, not a list of keywords, so @import, @annotation and names JSON-LD adds later are covered. It also checks what a name resolves to, so a ledger context aliasing an ordinary term to a keyword ({"id": "@id"}) is refused too. Grep for a backtick immediately followed by @, and for context entries whose value starts with @:

Was accepted, now errors What it did before Write instead
RETURN n.`@id` null on every row id(n) / elementId(n)
RETURN n.`@type` null on every row labels(n)
MATCH (a {`@id`: "x"}) 0 rows match on a real property
MATCH (n:`@id`) 0 rows a real label
SET n.`@id` = "x" committed a literal @id property — (identity is not writable)
SET n:`@type` committed; labels(n) read back ["Person", "@type"] SET n:RealLabel
CREATE (n:`@id` …) committed a node whose only class was @id a real label

Full prose in docs/query/cypher.md (Differences from Neo4j).

Review round (bplatz) — seven findings, all held, all fixed

Every one of them held when re-derived in source and reproduced on the branch. The shape of them is worth stating, because four were holes in the guard and a PR whose purpose is the guard should say so plainly:

  • (The JSON-LD guard in this and the next item has since been removed; see the update at the top.) One regression this PR introduced, and the most important: the JSON-LD guard rejected a working metadata-join query. The root cause is not the code, it is the comment. The guard's doc comment asserted that exactly this shape was exempt, and a confident claim of safety standing in for a check is why nobody noticed — the ["bind", …] site scan behind the blast-radius claim structurally could not see the {"@t": "?t"} spelling, and the comment gave no reason to look. The claim is retracted in place, and the replacement comment states the exemption's cost precisely rather than asserting it has none: it also admits a hand-written ["bind","?t","(t ?v)"] onto a bound ?t, which silently yields constraint semantics if the author meant to shadow. Accepted as a documented trade. Fixed and pinned.
  • Three scopes the guard did not see: a Cypher CALL { … } body, a nested JSON-LD subquery, and JSON-LD unwind. The CALL case was Cypher: a RETURN alias matching a pattern variable silently replaces the projection, and can drop every row #1857's own shape one construct in, so Fixes #1857 was overstating on the previous head — it holds now, demonstrated by a test rather than assumed.
  • Two holes from checking the wrong thing in the keyword guard: a list of names instead of the @ prefix, and the spelling instead of the resolved term. One rule closes both.
  • One doc comment spliced onto the wrong function.

Both enumeration failures are the same one this PR already named on its own label sweep — an enumeration is a floor, not a count. The keyword half now checks a property instead of a list; the scope half is a checkable property of each lowering rather than a list of call sites.

Each fix is proven non-vacuous by reverting it from post-cargo fmt source and watching its test fail. Local: fmt clean, clippy 0/0 on all four crates, 77 binaries / 5788 passed / 0 failed.

The fresh-alias form inside a CALL (CALL (a) { WITH a.name AS n RETURN n AS z }) returned 16 rows (4 × 4) when this was written; main's CALL correlation fix has since made it 4, and the test asserts that.

Deliberately out of scope

UNWIND <list> AS v where v is already bound is the same collision one clause over, and it is folded in. It silently dropped every row. The obvious boundary is wrong, and I checked before writing the guard: range(1, 3) is a runtime expression and still drops, while labels(a) works. The discriminator is whether the list expression references the alias — labels(a) does, so the planner must keep the Unwind below the MATCH where the operator shadows correctly; an uncorrelated list floats above it and the collision drops the rows instead. Routing the constant arm to Pattern::Unwind therefore does not fix it; I tried, and measured it still returning zero. The one form that works does so by accident of plan ordering, which is not something the lowering can promise, so the whole shape is rejected. No in-repo query uses it. Making it genuinely work means pinning an uncorrelated Unwind below its MATCH, which is a planner change.

Duplicate output names now cover bare and unaliased items — RETURN a, a and RETURN a.name, a.name emitted two headers backed by one VarId, which any client keying by column name reads as one column. Neo4j rejects both.

MERGE … WITH … SET is broken on the sequential write driver independently of this issue — filed separately as #1873. MERGE (n:P {id:"x"}) WITH n SET n.nm = "b", with no alias at all, fails with "MERGE re-bind matched no rows"; so does the fresh-alias form; while the no-WITH baseline and MATCH … WITH … SET both commit correctly. No alias is involved, so #1857's mechanism cannot be. The root cause is a parser hoist — Update is a fixed reads-then-writes shape, so a post-MERGE WITH moves into read_clauses and the statement executes as WITH n MERGE (n) SET …, which also flips it onto a different write driver.

Not every shape of it errors, and an earlier draft of this paragraph made it sound like they all do. MERGE (n:P {name:"Zed"}) WITH n.name AS nm SET n.marker = nm commits and writes four markers — Alice, Bob, Carol, Dave — onto the single merged node, because the hoisted WITH read n.name against the pre-MERGE graph with n unbound. That is corruption rather than a no-op, and it is in #1873.

Follow-up: #1873

Option (ii) — true re-projection and the column-label channel it needs — is filed as #1870, referenced above as Follow-up: #1870 rather than a closing keyword, since this PR deliberately does not resolve it.

Note for whoever reads #1870: its "one loose end I could not pin down" section, which could not separate the MERGE … WITH … SET failure from this issue's alias mechanism, is now separated and split out as #1873, and #1870 carries a comment saying so.

#1870 also asks that the openCypher divergence "be named in the docs rather than discovered". This PR does that — see the docs/query/cypher.md commit.

-----ISSUE 1857-----
OPEN [bug,P1,area:query] Cypher: a RETURN alias matching a pattern variable silently replaces the projection, and can drop every row
An openCypher RETURN alias that happens to match a pattern variable silently changes what the projection returns — in one case dropping every row. Nothing warns, and the wrong answers are plausible enough to be taken at face value.

Repro

Any ledger with an annotated edge; this uses two claims on ex:alice ex:knows ex:bob.

$ fluree query -l v:main --cypher -e \
    'MATCH (a)-[r:`http://example.org/knows`]->(b) RETURN a.`@id` AS aid LIMIT 2'
  → [null, null]

$ fluree query -l v:main --cypher -e \
    'MATCH (a)-[r:`http://example.org/knows`]->(b) RETURN a.`@id` AS a LIMIT 2'
  → ["http://example.org/alice", "http://example.org/alice"]

$ fluree query -l v:main --cypher -e \
    'MATCH (a)-[r:`http://example.org/knows`]->(b) RETURN r.`…/confidence` AS conf LIMIT 2'
  → ["0.8", "0.9"]

$ fluree query -l v:main --cypher -e \
    'MATCH (a)-[r:`http://example.org/knows`]->(b) RETURN r.`…/confidence` AS r LIMIT 2'
  → []            ← every row dropped

Same pattern, same projection expression, three different outcomes depending only on the alias.

What seems to be happening

When the alias collides with a bound pattern variable, the projection expression appears to be discarded in favour of the variable itself. For a node variable that yields the node (rendered as its IRI); for a relationship variable it yields nothing at all and the row count goes to zero.

The AS r case is the one that worries me most. A user writing RETURN r.confidence AS r — which rea

`RETURN expr AS v` / `WITH expr AS v` where `v` is already bound was
silently `WHERE v = expr`, projecting `v`.

An alias interns through the statement-wide `VarRegistry`, which is a
name<->id bijection, so an alias whose text equals an already-bound
variable's name *is* that variable — same VarId, by construction. The
projection therefore emitted `Pattern::Bind` onto a bound variable, and
`BindOperator`'s deliberate clobber prevention then either dropped the
row (the computed value differed from the existing binding) or kept the
stale value (the computed value was unbound).

Read path, against a three-edge KNOWS chain:

  RETURN a.name AS aname   -> 3 rows, correct
  RETURN a.name AS a       -> 0 rows
  RETURN r.confidence AS r -> 0 rows
  RETURN a.name AS b       -> 0 rows
  RETURN id(a) AS a        -> 0 rows
  RETURN a.name AS x, b.name AS x -> 0 rows, two columns on one VarId
  WITH a.name AS a         -> 0 rows

Write path, same chain, via `transact_cypher`:

  WITH p, q.name AS qn SET p.marker = qn -> commits, 3 markers
  WITH p, q.name AS q  SET p.marker = q  -> commits, 0 markers, no error

A one-character change to an alias turned a working `SET` into a
transaction that succeeded, reported nothing, and wrote nothing.

The node-vs-relationship distinction in the report is a red herring: the
discriminator is only whether the projected expression evaluated to null.
`a.`@id`` is unreadable today, so it returned Unbound and the stale node
binding survived; `a.name` returns a value, so every row was dropped.

Reject at lowering rather than shadow. This is the decision the codebase
had already made for the identical mechanism one function away — the
CALL-subquery guard in `lower/stmt.rs` diagnoses the same failure ("the
executor would treat the collision as an existing parent var and silently
drop the subquery's value. Reject rather than shadow") — it was simply
never generalized to the top-level projection. It also honours the
published contract in `docs/query/cypher.md`: anything unsupported
returns a clear error, never a silently wrong result.

Two guards, because two independent lowerings reach the same defect:

- `fluree-db-cypher/src/lower/stmt.rs` — `ProjectionState::check_alias`,
  covering every read `RETURN`/`WITH`, each UNION branch, each CALL
  branch, and the read prefix of a sequential (MERGE) write.
- `fluree-db-transact/src/lower_cypher_update.rs` — `check_with_alias`,
  covering the single-statement write path, which builds its WITH
  horizon directly and never goes through `ProjectionState`.

Both key off the scope as it stood at *clause entry*, not the registry:
`WITH pair[0] AS x … OPTIONAL MATCH (x)-[…]->(y)` is legal and four live
tests depend on it. The snapshot is taken once per clause, not per item,
because `add_item` pushes its own auxiliary patterns into the same list.
The identity projection `v AS v` stays legal — it binds v to itself, so
no row is dropped and nothing is lost.

This is a deliberate, temporary divergence from openCypher, which accepts
`WITH n.name AS n` as a re-projection into a new scope. True re-projection
needs a column-label channel in the shared IR (`VarRegistry` is a name
bijection and the Cypher column header is `result.vars.name(v)`), which is
a larger change; an error beats a wrong answer in the meantime.

Errors render verbatim and name both the collision and the fix.
`n.`@id`` returned null on every row and `n.`@type`` did the same. The
report asks for `@id` to resolve; it should be rejected instead, and the
write path makes that clearer than the read path does.

`@id` and `@type` are not Cypher properties. A Cypher node variable *is*
the node — its identity is `id(n)` / `elementId(n)` and its types are
`labels(n)`. Left unchecked the keywords lowered as ordinary predicates,
which failed silently in both directions:

  MATCH (a:Person) RETURN a.`@id` AS v   -> [null] x4
  MATCH (a:Person {`@id`: "alice"}) …    -> 0 rows

and, worse, on the write path:

  SET n.`@id` = "zzz"          -> COMMITS; keys(n) = ["@id", "name"]
  SET n.`@type` = "Q"          -> COMMITS; keys(n) = ["@type", "name"];
                                  labels(n) still ["Person"]
  CREATE (n:P {`@id`: "zzz"})  -> COMMITS; new blank-node id, `@id`
                                  stored as a literal property

That is a persisted wrong answer, not just an unhelpful read: the node's
real identity and labels are untouched while a junk predicate spelled
`@id` enters the data.

Resolving `@id` instead would also have made the alias collision in the
previous commit strictly worse. `RETURN a.`@id` AS a` returns the node
today only because the accessor is unreadable, so the bind computes
Unbound and the stale binding survives. A bound IRI string would compare
unequal to the node binding and drop every row. Rejecting has no such
interaction — the query errors on the keyword, before the alias is
considered.

Rejecting is safe: a bare `@id` is not a legal Cypher identifier, it has
to be backticked, so no ordinary property name can collide with the
reserved set. The check runs on the bare name before `@vocab` expansion
(with a vocab set, `@id` would otherwise resolve to `<vocab>@id`).

Scoped a little wider than the report: `@type` behaves identically today,
and the same mistake is reachable from inline property maps, annotation
property maps, comprehension member access, labels and relationship
types. All of them resolve through `resolve_predicate`, which already
rejects Fluree's own `f:reifies*` system predicates — so the keyword
check lands beside that precedent, one call site per crate. The message
names the working accessor, which is what the report actually asked for:
the accessors are documented, but a `null` gives a user no way to find
them.
…rence

Both land under "Differences from Neo4j", on the side that matches what
they are: the JSON-LD keywords are divergent by design (a node variable
already is the node), while re-projecting a bound name is deferred — the
one place Fluree is stricter than openCypher rather than more lenient,
which is worth saying out loud rather than leaving a user to discover.

Each entry names the working spelling and the reason, so the error
message and the reference agree.
@aaj3f aaj3f added bug Something isn't working as expected breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section P1 Next up: wrong results, live user pain, unblocks area:transact Staging, commit, import/bulk-import, novelty, retraction semantics area:query Query execution, planning, fast paths, overlay, result formatting labels Sep 16, 2026
A reserved JSON-LD keyword used as a node label bypassed the check
entirely, on both paths, because a label lowers to the OBJECT of an
`rdf:type` triple rather than to a predicate and so resolved through
`resolve_iri` instead of `resolve_predicate`.

Measured before the fix:

  MATCH (n:`@id`) RETURN n     -> 0 rows, no error
  MATCH (n:`@type`) RETURN n   -> 0 rows, no error
  SET n:`@type`                -> COMMITS; labels(n) reads ["Person", "@type"]
  CREATE (n:`@id` {name:"zz"}) -> COMMITS; the node's only class is `@id`

Same persisted-junk outcome the property-key check exists to remove, in
the one position the docs claimed was covered.

I enumerated this rather than taking the reported list: every
`resolve_iri(` call site in both crates, classified. Seven are label
resolution — `fluree-db-cypher/src/lower/pattern.rs:319` and six in
`fluree-db-transact/src/lower_cypher_update.rs` (MATCH, SET, REMOVE, the
MERGE probe guard, ON CREATE/MATCH SET, CREATE). The rest are the two
definitions and the two calls inside `resolve_predicate` itself. Hits in
`lower_sparql_update.rs` and `parse/trig_meta.rs` are a different
function — `fluree_vocab::iri::resolve_iri(base, iri)`, base-relative
resolution for Turtle/TriG — and are unrelated.

Each crate gains a `resolve_label` that delegates to `resolve_predicate`,
so there is still one choke point per crate rather than a second copy of
the check, and the label call sites read honestly. The shared message now
says "not a usable Cypher name (property key, label, or relationship
type)", which is accurate in every position it can now fire from.
Two more faces of the same collision, both silently wrong.

`UNWIND <list> AS v` where `v` is bound dropped every row. The obvious
boundary — constant list vs runtime expression — is wrong, and I checked
before writing the guard:

  UNWIND [1, 2, 3] AS a   -> 0 rows
  UNWIND range(1, 3) AS a -> 0 rows      (runtime, still drops)
  UNWIND labels(a) AS a   -> 3 rows      (works)

The real discriminator is whether the list expression REFERENCES the
alias. `labels(a)` does, so the planner must keep the `Unwind` below the
MATCH, where `UnwindOperator` shadows the column as openCypher wants. An
uncorrelated list can float above it, where the alias is not yet in the
child schema, so the operator appends a new column and the join against
the bound value matches nothing.

Routing the constant arm to `Pattern::Unwind` therefore does not fix it —
I tried that first and measured it still returning zero rows. The one
form that works does so by accident of plan ordering, which is not a
property the lowering can promise, so the whole shape is rejected. No
in-repo query uses it. Making it genuinely work means pinning an
uncorrelated `Unwind` below its MATCH, which is a planner change.

Separately, the duplicate-output-name rule only saw aliased items, so
`RETURN a, a`, `RETURN a AS a, a` and `RETURN a.name, a.name` still
emitted two headers backed by one VarId — one column as far as any client
keying by name is concerned. `claim_output` now covers bare and unaliased
items too, taking the unaliased name from `projection_label` (pure, so no
counter bump). Neo4j rejects all three.
Six new tests across the two levels, each proven non-vacuous the same way
as the rest of the slate. The write-side label cases are the sharp end:
`SET n:`@type`` and `CREATE (n:`@id` …)` both committed before this.

The docs paragraph previously implied the keyword rejection covered
labels when it did not; it now says so and is true. The Deferred entry
gains the UNWIND rule, including why the one sub-case that worked is not
being blessed, and the duplicate-name rule now says it covers bare items.
`["bind", "?alreadyBound", expr]` is the JSON-LD face of the same defect:
`BindOperator`'s clobber prevention makes it silently `FILTER(?v = expr)`,
which reads as an unexplained empty result. SPARQL rejects the shape at
parse time (`BindTargetAlreadyInScope`, §10.1); Cypher now rejects its
`AS` equivalent; JSON-LD was the only one of the three that was silent.

Deferred until now by a comment on the pinned test saying "any tightening
here needs its own decision". The archaeology says the deferral was
procedural rather than a product decision, and the provenance is in the
PR body — the short version is that the comment is a scope note from the
PR that tightened SPARQL, the behaviour underneath arrived unexamined in
a 1,568-file baseline import, and nothing outside that one test relies
on it.

Scope-correct rather than a blanket walk: a UNION branch is checked
against the set as it stood before the union, so a bind in one branch
onto a column the sibling branch produces stays legal; bodies with their
own scope (`Subquery`, `Exists`/`NotExists`, `Minus`, `Service`) are not
descended into, which can only miss a collision rather than invent one;
lowering-internal `?__` binds are exempt; and the identity bind
`["bind","?v","?v"]` is exempt because it recomputes the value it already
holds.

`fluree-db-sparql` has its own `lower_sparql` and never reaches this
function, so the W3C suite is not in play.
The commit before this closed the wrong half. It ran the check straight
after pattern lowering, which is before scalar select expressions desugar
into binds — so `["bind", "?v", …]` was caught and `(as <expr> ?v)` was
not.

That matters because the select alias, not the WHERE-clause bind, is
FQL's counterpart to the Cypher `RETURN expr AS v` bug this PR is about.
`docs/query/jsonld-query.md:181`: "Scalar select expressions desugar to a
`bind` in the WHERE pattern list." Measured at 3d89e8f:

  ["bind", "?nm", "?s"]           -> 0 rows, silent
  "select": ["(as (str ?s) ?nm)"] -> 0 rows, silent

Both reject now. The check moves after the select-expression loop.
Post-placed select binds ride in `grouping` rather than `patterns` and
are deliberately not reached — they target freshly minted aggregate
outputs.

The error names the spelling the author wrote, mirroring SPARQL's split
between V5 (`BindTargetAlreadyInScope`) and V6
(`SelectAliasAlreadyBound`): a `(as …)` alias reported as an "Invalid
where clause" sends someone to the wrong half of their query.
`jsonld_bind_on_bound_variable_accepted_as_constraint` is the only test
in the repo that changes behaviour under this PR, and it is the visible
cost of the two commits before it, so it gets its own.

The replacement asserts both spellings are refused with their own
messages, that `["filter", ["=", "?v", expr]]` still expresses the
constraint reading the old pin was really describing, and that a bind to
a fresh variable is untouched.

Its comment records the archaeology rather than asserting intent, so the
next reader can re-examine the call rather than inherit it.
D-4 obligation for a newly-rejected input shape, inherited from #1453 —
the convention is "hard error + changelog / migration note", and the repo
has no CHANGELOG.md, so it lands in the user-facing docs and in the PR
body (which drives the Breaking Changes release-notes section via the
`breaking-change` label).

Names both spellings, since `(as <expr> ?v)` desugars to a bind and a
user hitting the select-clause form will not think to look under "Bind
Patterns". Gives `filter` as the exact replacement for the filter
semantics the old behaviour backed into, and records the two shapes that
stay legal.
@aaj3f
aaj3f marked this pull request as draft September 17, 2026 03:07
The Deferred entry said re-projection "needs a column-label channel in the
shared IR". That overstates it, and the overstatement was propagating —
the same reasoning is in the PR body and is the literal subject of #1870's
title and its P3 sizing.

Checked against the three places a fresh synthetic `VarId` could be
resisted. `ir::Column` genuinely has no label field
(`fluree-db-query/src/ir/projection.rs:249`), but the Cypher formatter
reads headers from `result.vars.name(v)`
(`fluree-db-api/src/format/cypher.rs:67`) and `QueryResult` is defined in
the api crate (`fluree-db-api/src/query/mod.rs:112`), so the channel can
live there. `Query::cypher_vocab`
(`fluree-db-query/src/ir/query.rs:310`) is existing precedent for exactly
that shape: a Cypher-only field set after lowering and read only
Cypher-side.

Of the three: grouping keys off `VarId` and is indifferent; Bolt has no
`vars.name` call of its own anywhere in `fluree-db-bolt/src`, so it
inherits whatever the api-side channel yields — that one is inferred
rather than traced end to end. `ORDER BY` does resist, and that is the
real remaining blocker: `align_order_by_with_projection`
(`fluree-db-cypher/src/lower/stmt.rs:757`) matches an ORDER BY expression
against projection items by surface expression, so `RETURN n.name AS n
ORDER BY n` would not match the item and would fall through to interning
`n` — the original node variable, not the re-projection.

So the blocker is smaller than stated but not absent: Cypher-lowering-local
rather than shared-IR, with the rebinding layer as the genuine work. The
docs now say that instead.
@aaj3f aaj3f changed the title Reject a Cypher RETURN/WITH alias that collides with a bound variable Reject Cypher alias and JSON-LD bind collisions that silently returned zero rows Sep 17, 2026
@aaj3f
aaj3f marked this pull request as ready for review September 17, 2026 16:08
@aaj3f
aaj3f requested review from bplatz and zonotope September 17, 2026 16:08

@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. The diagnosis is the strongest part of this — "an alias interns through the VarRegistry, so expr AS v on a bound v is WHERE v = expr" is exactly right, and collapsing the issue's node-vs-relationship framing to a single mechanism is a better read than the issue had. The write-path find (commits, returns no error, writes nothing) is the most valuable thing here and nothing in the suite covered it.

I built the branch and exercised the guards. The core rejections work — I confirmed the read path and the write path both fire correctly, including MATCH (p)-[:KNOWS]->(q) WITH p, q WITH p.name AS q SET p.marker = q. But there are items I'd want you to look at before merging, and I'd value your own assessment of them since you have far more context on these lowerings than I do.

One working query breaks, and it isn't disclosed

Reusing one node-map metadata variable across two properties returns rows on main and is a hard parse error on this branch:

{"@id": "?s", "schema:name": {"@value": "?name", "@t": "?t"},
              "schema:age":  {"@value": "?age",  "@t": "?t"}}

main: [["Alice",1],["Brian",1],["Cam",1]] → branch: bind target ?t is already bound.

check_bind_targets's doc comment says node-map metadata accessors are ?__-prefixed and therefore exempt. They aren't — they carry the user's own variable name. Detail on the comment at lower.rs:233. This is the one I'd treat as blocking: it's not in the breaking-changes table, not in the docs, and the ["bind", …] site scan can't see the spelling.

Three places the silent-zero-rows defect survives

None of these break anything — they're the same failure still reachable by other spellings, which matters because the PR is framed as closing that class:

  • Nested subqueries (lower.rs:229) — ["query", {… ["bind","?age",…]}] with ?age bound: accepted, returns []. lower_subquery pushes the same binds and never calls the guard.
  • CALL { } bodies (stmt.rs:480) — MATCH (a:Person) CALL (a) { WITH a.name AS a RETURN a AS z } RETURN z: accepted, 0 rows. Same for UNWIND inside a CALL. Pointed, given the PR argues from the CALL guard having made this call already.
  • JSON-LD unwind (lower.rs:249) — ["unwind","?v",…] onto a bound ?v: accepted, returns [], while the Cypher twin now errors.

Smaller

  • reserved_keyword_message's _ => return None still lets SET n.`@import` = "x" commit junk (keywords.rs:52); the module's own safety argument supports rejecting the whole @ prefix.
  • A context aliasing {"id": "@id"} routes around the keyword check entirely (context.rs:234).
  • lower_with_clause lost its doc comment to a splice (lower_cypher_update.rs:451).

Checked and cleared

  • The write-path guard works; I could not construct the narrowed-bound_vars bypass I went looking for.
  • A post-placed select bind onto a group key errors via the aggregate-schema check rather than silently filtering, so the comment about it at lower.rs:154 is imprecise but there's no defect behind it.

Nothing here argues against the direction — rejecting is the right call and the archaeology justifying the JSON-LD half is convincing. The one that would bother me shipping is the metadata-variable regression, precisely because it fails the standard you set for yourself in the body ("zero genuine regressions").

Comment thread fluree-db-query/src/parse/lower.rs Outdated
/// `Service`) are not descended into. That can only miss a collision, never
/// invent one.
/// - Lowering-internal binds (`?__`-prefixed: property-path expansions,
/// node-map metadata accessors) are exempt, mirroring the Cypher guard's

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 exemption claim is not true, and a working query regresses because of it.

Node-map metadata accessors are not ?__-prefixed. add_metadata_bind_pattern (parse/node_map.rs:126-158) emits Bind{?t, t(?val)} where the variable is the user's own name, taken verbatim from the JSON — explicit_dt_var at node_map.rs:1466 is whatever the author wrote in "@type": "?dt", and lang_var / t_var come the same way. So they are not exempt, and reusing one metadata variable across two properties is now a hard parse error.

Measured, same query both sides:

{"@id": "?s",
 "schema:name": {"@value": "?name", "@t": "?t"},
 "schema:age":  {"@value": "?age",  "@t": "?t"}}
result
origin/main [["Alice",1],["Brian",1],["Cam",1]]
this branch bind target ?t is already bound by an earlier pattern

That is the natural way to ask "both properties asserted in the same transaction", and it worked. It is not in the breaking-changes table, not in docs/query/jsonld-query.md, and the 238-site scan of ["bind", …] that backs the blast-radius claim structurally cannot see it — the spelling is {"@t": "?t"}, not a bind array.

Either exempt lowering-generated metadata binds (which is what this comment already says the intent is), or add the shape to the migration table with a replacement. As written the comment asserting safety is the reason it went unnoticed.

@aaj3f aaj3f Sep 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You're right, and this is the one that matters most — it's a regression I introduced and then documented as safe, which is the worst combination. add_metadata_bind_pattern uses the author's own variable name verbatim, so the ?__ exemption my comment described never applied to these, and the comment asserting it did is exactly why it went unnoticed.

I also want to own the second half of what you said: the 238-site scan behind the blast-radius claim structurally couldn't see this, because the spelling is {"@t": "?t"} rather than a bind array. So the "zero genuine regressions" line was a true answer to a narrower question than the one I was claiming it answered.

Took your first option. Reusing a metadata variable across two properties binds onto an already-bound ?t by design — "both asserted in the same transaction" is the join — so it's now exempted structurally: a one-argument call to one of the four functions the node-map emits (datatype, t, op, lang) over a variable. I want to be exact about what that admits, because I first described it as costless and it isn't. The structural test can't tell the node-map's bind from a hand-written one, so ["bind", "?t", "(t ?v)"] onto a bound ?t gets through too. If the author meant a join, that's the documented result; if they meant to shadow ?t, they silently get constraint semantics instead — which is this guard's own defect class, let through. I've accepted that because it needs a metadata function hand-written onto a bound variable with shadowing intent, which is rare, and the trade is now documented at the guard site rather than asserted away. Carrying provenance from node_map.rs would close it properly — happy to go that way if you'd rather.

Your exact query now returns its 3 rows again, pinned by a test that also checks a genuine collision on the same shape is still refused, so the exemption is shown to be the join and not a blanket pass. Fixed in 9d5233a; test and the docs note in e940c24; the exemption's trade documented precisely in 8452767.

Comment thread fluree-db-query/src/parse/lower.rs Outdated
/// set as it stood before the union, never against its sibling branch, so
/// `["union", [{…"?nm"}], [{…}, ["bind","?nm",…]]]` — a legitimate way to
/// give both branches the same output column — still lowers.
/// - Bodies with their own scope (`Subquery`, `Exists`/`NotExists`, `Minus`,

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.

Not descending into Subquery "can only miss a collision, never invent one" is true of this function — but lower_subquery (:1420) is the only other place that pushes these Pattern::Binds, and it never calls check_bind_targets either. So nothing checks a nested select, and the defect survives one level down.

Reproduced on this branch:

["query", {"select": ["?age"],
           "where": [{"@id": "?s2", "schema:age": "?age"},
                     ["bind", "?age", ["expr", ["+", "?age", 1]]]]}]

→ accepted, returns []. The same silent empty result the top-level guard now rejects.

lower_subquery lowers its WHERE patterns and appends select-expression binds in the same shape the top-level pass does, so calling the guard on its patterns before SubqueryPattern::new would close it with the enclosing set it already has.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed — I overstated what that bullet established. "Can only miss a collision, never invent one" is true of check_bind_targets itself, but I cited it for the property that nested selects were covered, and nothing else was checking them. Reproduced your query at 0 rows before the fix.

lower_subquery now calls the guard on its own patterns before SubqueryPattern::new, with its own select-alias provenance so the error still names the spelling written. I kept the enclosing set empty there — a subquery body has its own scope and outer variables join on its projection afterwards — but let me know if you had a correlated case in mind where that's too narrow. The comment now says what actually makes not-descending safe. Fixed in 9d5233a.

Comment thread fluree-db-query/src/parse/lower.rs Outdated
let mut produced = enclosing.clone();
for pattern in patterns {
match pattern {
Pattern::Bind { var, expr } => {

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 match has no Pattern::Unwind arm, so JSON-LD's ["unwind", "?v", expr] onto a bound ?v stays silently broken while the Cypher twin of exactly that shape is rejected in this same PR.

{"where": [{"@id": "?s", "schema:name": "?name", "schema:age": "?age"},
           ["unwind", "?age", ["expr", ["range", 1, 3]]]]}

→ accepted, returns [] — while MATCH (a) UNWIND range(1,3) AS a now errors.

Pattern::Unwind already reports its target through produced_vars(), so this is a two-line arm, and it keeps the two surfaces telling the user the same thing about the same mistake.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, and the asymmetry you point out is the real problem — rejecting UNWIND … AS a in Cypher while the JSON-LD twin of the exact same shape stays silent is the kind of thing that makes a surface feel arbitrary. Reproduced at 0 rows.

Added the Pattern::Unwind arm, with its own message ("unwind target … silently filters to rows where an element happens to match") so it doesn't read as a bind error. Fixed in 9d5233a.

items: &[ProjectionItem],
) -> Self {
let in_scope = if items.iter().any(|i| i.alias.is_some()) {
visible_vars_from_patterns(ctx, patterns)

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 scope snapshot is branch-local, so a CALL { … } body is unguarded.

Inside a CALL body lower_single_branch_inner starts with patterns = [], so visible_vars_from_patterns returns nothing and an imported variable is invisible to check_alias. lower_unwind's scope is body-local for the same reason.

Reproduced on this branch — both accepted, both zero rows, no error:

MATCH (a:Person) CALL (a) { WITH a.name AS a RETURN a AS z } RETURN z
MATCH (a:Person) CALL (a) { UNWIND [1,2,3] AS a RETURN a AS z } RETURN z

The pre-existing CALL guard does not catch these either: it rejects return columns present in outer_set (z is not one) and rejects non-imported shadowed references (a is imported). a is seeded per parent row by SubqueryOperator, so the emitted Bind{a, a.name} clobber-drops every row.

Worth closing because of what this PR argues from: the case for rejecting is that the CALL-subquery guard already made this call and was never generalized. Inside the CALL body it still hasn't been. outer_scope is in hand at :273 and already passed to lower_call_subquery — seeding the projection and UNWIND snapshots from it looks like the whole fix.

@aaj3f aaj3f Sep 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This one I want to be especially clear about, because you're right about why it's pointed: the argument for rejecting in this PR is that the CALL guard had already made this call and was never generalised — and inside the CALL body it still hadn't been. Reproduced both forms at 0 rows while the identical top-level forms error.

It also meant Fixes #1857 was overstating on the previous head, since the issue's own shape was reachable one construct in. I checked that explicitly rather than assuming the findings were all adjacent to it.

Your read of the fix was right. outer_scope is now threaded into lower_with, lower_return and lower_unwind and unioned into their clause-entry snapshots, gated on the existing narrowed flag so it stops applying once a WITH narrows scope. Both of your repros are now rejected, pinned by a test covering the projection and UNWIND sides — each reverted independently to confirm it fails. Fixed in 35afb6b, so the closing keyword now holds on the current head.

One thing this surfaced that I've kept out of this PR: a fresh alias inside CALL (a) { WITH a.name AS n RETURN n AS z } returns 16 rows (4 × 4) rather than 4, and does so on main without this change too — I measured it there rather than infer it. That looks like a pre-existing CALL-correlation issue, now tracked as #1894 — which bounds it: correlation is lost exactly when a WITH inside the body narrows the imported variable out of scope.

Comment thread fluree-db-cypher/src/keywords.rs Outdated
"@graph" | "@context" | "@list" | "@set" | "@none" | "@reverse" | "@index" | "@nest"
| "@base" | "@vocab" | "@container" | "@included" | "@prefix" | "@propagate"
| "@protected" | "@version" => "it describes JSON-LD document structure, not data",
_ => return None,

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 _ => return None arm lets any unlisted @-prefixed name through, so the persisted-junk outcome this module exists to remove is still reachable on names the enumeration missed:

SET n.`@import` = "x"       -> commits a literal `@import` predicate
SET n.`@annotation` = "x"   -> same

Both are real JSON-LD 1.1 keywords. The module doc's own safety argument — "a bare @id is not a legal Cypher identifier, it has to be backticked, so no ordinary property name can collide" — supports rejecting the entire @ prefix rather than a list. Since the function already returns early on !key.starts_with('@'), a catch-all with a generic message (keeping the specific advice strings for the names that have a working accessor) is strictly safer and removes a list that otherwise has to track the JSON-LD spec.

Note the unit test currently pins "@" as not reserved, which would need to flip with it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, and I think this and your context.rs:234 note are the same mistake from two directions — I enumerated keyword names and checked the input spelling, and both holes fall out of that.

Went with the whole prefix as you suggested. The module doc's own argument already covered it: no ordinary Cypher identifier begins with @, so rejecting every @ name can't catch a real one, and it stops the list having to track the JSON-LD spec. The list now only supplies more specific advice. Flipped the unit test that pinned "@" as ordinary and added one pinning @import, @annotation and bare @ as reserved. Fixed in 1872341.

/// stores a literal predicate spelled `@id` — see
/// [`crate::keywords`] for why rejecting is safe.
pub fn resolve_predicate(&self, name: &str) -> Result<String> {
if let Some(msg) = crate::keywords::reserved_keyword_message(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.

The keyword check runs on the bare name only, so a context that aliases an ordinary term to a keyword routes straight around it.

extract_cypher_iri_mapping (fluree-db-api/src/query/helpers.rs:386-411) copies every non-@ context key into overrides, skipping only values ending in # or /. So {"id": "@id", "type": "@type"} — a standard JSON-LD aliasing idiom — yields overrides = {id -> @id, type -> @type}. Then:

  • reserved_keyword_message("id") returns None (no @ prefix)
  • resolve_iri("id") hits overrides first (:212-215) and returns "@id"

SET n.id = "x" then commits a literal @id predicate, and MATCH (n:type) resolves a class spelled @type — the exact outcome this check was added to prevent. Same hole on the write side at fluree-db-transact/src/lower_cypher_update.rs.

Checking the resolved IRI in addition to the bare name closes it, and keeps the bare-name check for the @vocab case the comment describes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right — {"id": "@id"} is a completely ordinary JSON-LD idiom, which makes this worse than an edge case. Confirmed the path in source: it passes both filters in extract_cypher_iri_mapping into overrides, and resolve_iri consults overrides first.

Both resolvers now check the resolved term as well as the bare name, and the message names both — "id resolves through the ledger's context to @id" — so it's obvious why an ordinary-looking name was refused. Kept the bare-name check too, since it's what catches @id before @vocab turns it into <vocab>@id.

Worth saying I wasn't confident the test would actually exercise this — with_default_context could plausibly not reach Cypher lowering at all — so I reverted the fix and confirmed the test fails, rather than trusting a green. Fixed in 1872341.

/// path, since aggregate calls aren't in the filter-expression surface),
/// `DISTINCT`, and `ORDER BY` / `SKIP` / `LIMIT` — these need a query-level
/// grouping or slice the single-Txn write model doesn't carry.
/// Reject a `WITH … AS v` before a write clause when `v` is already bound

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.

check_with_alias was inserted between lower_with_clause's doc comment and its signature, so the two ran together: lines 438-450 ("Lower a WITH projection that precedes a write clause… these need a query-level grouping or slice the single-Txn write model doesn't carry") and the new prose here are now one contiguous /// block attached to fn check_with_alias at :469.

Net effect: lower_with_clause (:492) has no doc comment, and check_with_alias's rustdoc opens with two paragraphs about WITH lowering, deferral lists and HAVING routing that have nothing to do with it.

Moving the new function below lower_with_clause, or the new doc block after the existing one, fixes both.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks — that's exactly what happened, and it left lower_with_clause undocumented while giving check_with_alias two paragraphs about something else. Moved the original comment back above lower_with_clause, so each function has its own again. In 1872341.

…opes it missed

Three review findings, all in `check_bind_targets`.

**A regression this PR introduced (review id 4046804425).** Reusing one
node-map metadata variable across two properties returned rows on `main`
and was a hard parse error here:

  {"@id": "?s", "schema:name": {"@value": "?name", "@t": "?t"},
                "schema:age":  {"@value": "?age",  "@t": "?t"}}

That is the natural spelling of "both asserted in the same transaction",
and it binds onto an already-bound `?t` by design — the join is the
point. The guard's doc comment claimed node-map metadata binds were
`?__`-prefixed and therefore exempt. They are not: `add_metadata_bind_pattern`
uses the author's own variable name, verbatim. The comment asserting safety
is why this went unnoticed, and the 238-site scan of `["bind", …]` behind
the blast-radius claim structurally could not see the `{"@t": "?t"}`
spelling.

Now exempted structurally — a one-argument call to one of the four
functions the node-map emits (`datatype`, `t`, `op`, `lang`) over a
variable. A user writing the same join by hand as `["bind","?t","(t ?v)"]`
is exempted too, which is consistency rather than a hole: it means the
same thing and yields the documented join, not a silent wrong answer.

**Nested subqueries (4046804441).** `lower_subquery` pushes the same binds
and never called the guard, so `["query", {… ["bind","?v",…]}]` with `?v`
bound still returned an unexplained empty result. It now calls it on its
own patterns. The comment saying not descending into `Subquery` "can only
miss a collision" was true of that function and not of the property it was
cited for; it now says what actually makes it safe.

**`unwind` (4046804447).** No `Pattern::Unwind` arm, so
`["unwind","?v",…]` onto a bound `?v` stayed silent while the Cypher twin
of that exact shape is rejected in this same PR. Added.
#1857's own shape, inside a CALL body, still dropped every row
(review id 4046804453):

  MATCH (a:Person) CALL (a) { WITH a.name AS a RETURN a AS z } RETURN z
    -> 0 rows, no error
  MATCH (a:Person) CALL (a) { UNWIND [1,2,3] AS a RETURN a AS z } RETURN z
    -> 0 rows, no error

while the identical top-level forms error. The projection and UNWIND
scope snapshots were branch-local, and a CALL body starts with
`patterns = []` — the imported `a` is seeded per parent row by
`SubqueryOperator` rather than bound by a pattern — so the imported name
was invisible to the guard and `Bind{a, a.name}` clobber-dropped every row.

The pre-existing CALL guard does not catch it either: it rejects return
columns already in the outer scope (`z` is not) and non-imported shadowed
references (`a` is imported).

This finding decides whether `Fixes #1857` holds, since the issue's defect
was reachable one construct in. `outer_scope` was already in hand in
`lower_single_branch_inner` and already passed to `lower_call_subquery`; it
is now threaded into `lower_with`, `lower_return` and `lower_unwind` and
unioned into their clause-entry snapshots, gated on the existing `narrowed`
flag so it stops applying once a `WITH` has narrowed scope. Pointedly, the
case for rejecting in this PR is that the CALL guard had already made this
call and was never generalised — inside the CALL body it still had not been.
Two holes in the reserved-keyword guard with one cause: it enumerated
keyword *names* and checked the *input spelling*.

**The list was the boundary (review id 4046804463).** `_ => return None`
let every `@` name the list missed through, so ``SET n.`@import` = "x"``
and ``SET n.`@annotation` = "x"`` — both real JSON-LD 1.1 keywords —
committed literal predicates, the persisted-junk outcome the module exists
to remove. The module's own safety argument covers the whole prefix: no
ordinary Cypher identifier begins with `@`, so rejecting all of them cannot
catch a real name. The list now only supplies more specific advice, and a
test pins `@import`, `@annotation` and bare `@` as reserved.

**The check ran on the bare name only (4046804468).**
`extract_cypher_iri_mapping` copies every non-`@` context key into the
override map, so `{"id": "@id"}` — a standard JSON-LD aliasing idiom —
resolves `id` to `@id` and routes straight around a bare-name check. Both
resolvers now also check the resolved term, and the message names both the
spelling written and what it resolved to. The bare-name check stays, since
it is what catches `@id` before `@vocab` would turn it into `<vocab>@id`.

Also restores `lower_with_clause`'s doc comment (4046804480):
`check_with_alias` had been inserted between that comment and its
signature, so the two ran together and attached to the wrong function.
One test per finding that held, each proven non-vacuous by reverting its
fix from post-`cargo fmt` source and watching it fail — including the
resolved-IRI check, which confirmed the ledger-context path genuinely
reaches Cypher lowering rather than passing because nothing exercised it.
The CALL-scope fix is covered on both its projection and its UNWIND side,
reverted independently.

The metadata-join test is paired with a genuine collision on the same shape
of query, so the exemption is shown to be the join and not a blanket pass.

One control deliberately asserts non-rejection rather than a row count. A
fresh alias inside `CALL (a) { … }` returns 16 rows (4 x 4) rather than 4,
and it does so on `main` without this change as well — measured, not
inferred. That is a pre-existing CALL-correlation behaviour outside this
PR's scope, recorded separately rather than baked into a test here.

Docs: the JSON-LD bind rule now names `unwind` and nested subqueries, and
states that reusing a metadata variable is deliberately unaffected. The
Cypher keyword rule is now the `@` prefix, checked against what a name
resolves to, and the CALL-body collision is listed alongside the rest.
The previous commit's comment said the hand-written form
`["bind", "?t", "(t ?v)"]` onto a bound `?t` was "consistent rather than a
hole … not a silent wrong answer". That is only true if the author meant a
join. If they meant to shadow `?t`, they silently get constraint semantics
instead — this guard's own defect class, let through.

So the comment claimed safety for a case it had not checked, which is the
same failure that caused the regression the exemption fixes: a confident
comment standing in for a check. It now states the trade instead — what the
structural test admits, why it cannot tell the two apart, why it is
accepted (hand-writing a metadata function onto a bound variable with
shadowing intent is rare; the idiom it protects is documented and common),
and what would close it (provenance from `node_map.rs`, judged not worth
touching every `UnresolvedPattern::Bind` construction site for).

Comment only; no behaviour change.
…ision

Drops the JSON-LD half: fluree-db-query's lower.rs, the grouping tests and
jsonld-query.md take main's versions. That guard walked every JSON-LD
query's where clause, and `next` treats a JSON-LD rebind as an equality
check.

The alias guard now shares #2096's identity rule. It also reads a CALL
body's imports after a WITH: the CALL seeds them into every row of the
body, so `CALL (a) { MATCH (x) WITH x WITH x.name AS a … }` filtered to
zero rows past the old guard. The same holds for UNWIND.
@bplatz bplatz changed the title Reject Cypher alias and JSON-LD bind collisions that silently returned zero rows Reject Cypher alias collisions that silently returned zero rows Nov 17, 2026
@bplatz

bplatz commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Brought up to date with main (a38027c), and the description is updated: see Update, 2026-11-17 at the top. In short:

  • Removed: the JSON-LD half. The bind, unwind and select-alias rejection is gone, so this PR no longer touches fluree-db-query, and nothing changes on the JSON-LD or SPARQL path. That guard ran over every JSON-LD query's where clause at lowering, unmeasured. next also treats a JSON-LD rebind as an equality check (jsonld_bind_into_a_bound_variable_checks_it_when_only_counted), so the two would have collided on the next main→next merge. lower.rs, the grouping tests and jsonld-query.md take main's versions, and the JSON-LD rows are out of the breaking-changes table.
  • Changed: a CALL body's imports stay in the guard's scope after a WITH. A CALL seeds its imports into every row of its body, so CALL (a) { MATCH (x:Person) WITH x WITH x.name AS a RETURN a AS z } still returned 0 rows past the previous guard. The same held for UNWIND … AS a. Both are rejected now, and issue1857_call_body_alias_onto_imported_var_is_rejected pins them.
  • Changed: one identity rule. The guard shares fix(cypher): x AS x projects x instead of binding it to itself #2096's x AS x short-circuit instead of keeping its own (unreachable after the merge). The fresh-alias CALL forms now return one row per outer row on main, so that test asserts the count of 4 instead of only non-rejection.

@bplatz
bplatz merged commit 2a70c17 into main Nov 17, 2026
21 checks passed
@bplatz
bplatz deleted the fix/cypher-alias-collision branch November 17, 2026 15:27
@aaj3f aaj3f mentioned this pull request Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:query Query execution, planning, fast paths, overlay, result formatting area:transact Staging, commit, import/bulk-import, novelty, retraction semantics breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section bug Something isn't working as expected P1 Next up: wrong results, live user pain, unblocks

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cypher: a RETURN alias matching a pattern variable silently replaces the projection, and can drop every row

2 participants