Skip to content

Cypher WITH/RETURN cannot re-project a bound name — ORDER BY resolves aliases by surface expression, not by variable #1870

Open

Description

@aaj3f

Follow-up from #1857. That fix takes the right immediate call — reject an alias that collides with a name already bound in the incoming scope, rather than shadow it and silently drop the value — and it also rejects two projection items assigning the same output name, which is what was producing {"cols":["x","x"]} — two header slots backed by a single VarId, a collision any client keying results by column name would have taken silently. Both of those stop being reachable, the second with a message that names the fix:

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`).

What it does not do, and cannot do cheaply, is make the colliding alias work. This is the follow-up for that, because the blocker is structural and worth having written down before someone picks it up expecting a one-liner.

The structural bit

VarRegistry is a name-to-id bijection (fluree-db-query/src/var_registry.rs:49-70), so an alias whose text equals an already-bound variable's name simply is that variable — same VarId, by construction, with no scope boundary between the MATCH and the RETURN. And the Cypher column header is literally result.vars.name(v) (fluree-db-api/src/format/cypher.rs:67, and cypher_typed.rs:129).

Those two facts together mean a fresh VarId cannot carry a display name. ir::Column (fluree-db-query/src/ir/projection.rs:249-257) has two variants and no label field, so there is nowhere to put one. Re-projection needs four things, not one:

  1. a fresh VarId for the colliding alias;
  2. a name-to-VarId rebinding layer in LoweringContext so later clauses resolve the new binding;
  3. the old binding dropped from scope at the WITH boundary;
  4. a column-label channel in the shared IR — the expensive one, since it reaches the SPARQL and JSON-LD formatters too, not just Cypher.

Roughly 3× the size of the #1857 fix, and it is a shared-IR change rather than a Cypher-front-end one.

What it costs us until then

MATCH (n) WITH n.name AS n RETURN n is a well-known, legal, and widely-used Cypher idiom that Fluree will now reject with a clear error. That is a deliberate, temporary divergence from openCypher, and I think it is plainly the right trade against the current behaviour (zero rows, or a silent no-op SET on the write path) — an error beats a wrong answer, and our own docs promise exactly that at docs/query/cypher.md:724-726. But it is a real portability cost and a Neo4j-migrating user will hit it early, so it should be named in the docs rather than discovered.

Worth being precise about where we diverge and where we don't, since it cuts both ways: Neo4j rejects two projection items sharing one output name ("Multiple result columns with the same name are not supported"), so on the duplicate-alias case the #1857 fix actually moves us onto Neo4j's behaviour. The divergence is only on shadowing — WITH n.name AS n, which Neo4j allows and we will not. Neo4j's own shadowing error (GQL 42N07) is scoped to subquery scopes (CALL {}, EXISTS {}, COUNT {}, pattern comprehensions) rather than to a top-level projection, and Fluree already has that subquery rule.

I should flag that the Neo4j half of this is documented-and-reasoned, not measured — there was no Neo4j instance in the loop to run it against, so it is read off the Cypher manual rather than observed.

One loose end I could not pin down

On the fluree load --cypher path, a colliding alias leaks an internal error rather than a user-facing one:

$ fluree load w2 --from people.csv --cypher 'MERGE (n:P {id: row.id}) WITH n, row.nm AS n SET n.nm = n'
  error: Query error: Batch error: Duplicate VarId VarId(1) in schema

which is consistent with the same bijection — carrying n and aliasing onto n puts one VarId in the WITH subquery's select list twice. Do not bank this as part of the same bug, though: the identical template with a fresh alias also fails on that path with an unrelated "MERGE re-bind matched no rows" error, while the MERGE … SET baseline without a WITH loads fine. So either MERGE … WITH … SET is broken on the load path independently of any of this, or it shares a cause, and I could not separate the two. Noting it here so it isn't lost; it probably deserves its own look.

The decision inside this

Whether a temporary divergence from openCypher is acceptable at all. I think yes, for the reasons above — but if the answer is no, then the fix is the full re-projection above and it needs scheduling as a shared-IR change rather than a Cypher nicety. That is the call worth making explicitly rather than letting the divergence become permanent by default.

Activity

  1. added
    enhancement
    P3
    area:query
    on Sep 16, 2026
  2. aaj3f commented on Sep 16, 2026

    @aaj3f
    ContributorAuthor

    Closing out the loose end above: it is separated now, and it is not this bug. Split out as #1873.

    Two things settled it. The no-alias form MERGE (n:P {id:"x"}) WITH n SET n.nm = "b" fails identically, and it carries no alias at all — so the VarRegistry bijection that causes #1857 cannot be involved. And the actual mechanism turns out to be a parser hoist: Update is a fixed read_clauses / write_clauses shape with nowhere to record that a clause came after a write, so a post-MERGE WITH gets hoisted in front of the MERGE, and the written order and the explicitly-hoisted order then fail byte-identically.

    The reason it read as un-isolatable from here is mundane and worth recording — the probes reused one ledger, so the no-WITH baseline came back Commit conflict: expected t=2, head_t=1 and looked like a failure rather than the success it actually is. On separate ledgers the split is obvious.

    The Duplicate VarId VarId(0) in schema leak is #1857-shaped, and it is carried in #1873 as a sub-note: the RowSchema assertion fires before #1867's new lowering guard on that path, so the user gets an internal error where everywhere else they now get a clear one. Worth re-checking once the hoist is fixed.

  3. aaj3f commented on Sep 17, 2026

    @aaj3f
    ContributorAuthor

    Restating the scope on this, because the shared-IR question came back smaller than I wrote it — and located somewhere slightly different.

    The diagnosis holds. QueryResult lives in the api crate, format::cypher::table reads result.vars.name(v), and ir::Column has no label field. All confirmed.

    But "the shared IR has no column-label channel" overstates the work, and the title is the part that is wrong. A Cypher-only channel already exists as precedent: Query::cypher_vocab: Option<Arc<str>> (fluree-db-query/src/ir/query.rs:310), set by Cypher lowering and read only on the Cypher side. So a label channel is a field alongside an existing one, not a redesign of the IR — which is a materially smaller thing than this issue asks for.

    Of the three places I expected resistance, two give way and one does not:

    • Grouping keys off VarId and does not care.
    • Bolt appears to inherit the api-side channel for free — there is no vars.name call anywhere in fluree-db-bolt/src. I should flag that this one is inferred from the absence of a call site, not traced end to end, so treat it as the likely case rather than a settled one.
    • ORDER BY genuinely resists. align_order_by_with_projection (lower/stmt.rs:757) matches by surface expression, so RETURN n.name AS n ORDER BY n falls through to interning the original n rather than the alias. That forces a name→VarId rebinding layer — but note that layer is Cypher-lowering-local, not shared-IR, which is again smaller than the issue implies.

    So: the blocker is smaller than stated, and larger than "just add a field". Items 1–3 of the four I listed all survive — the fresh VarId, the rebinding layer, and dropping the old binding at the WITH boundary are all still real work. It is item 4, the one I called "the expensive one", that turns out to be cheap.

    P3 still looks right to me on that basis: the scope moved but the shape did not, and the failure mode after #1867 is still a clear error rather than a wrong answer.

    I have not retitled it. If someone wants to, something like "Cypher WITH/RETURN cannot re-project a bound name — needs a Cypher-side label channel and an ORDER BY rebinding layer" would describe it better than what is there now.

  4. changed the title [-]Cypher `WITH`/`RETURN` cannot re-project a bound name, because the shared IR has no column-label channel[/-] [+]Cypher `WITH`/`RETURN` cannot re-project a bound name — ORDER BY resolves aliases by surface expression, not by variable[/+] on Sep 17, 2026
  5. aaj3f commented on Sep 17, 2026

    @aaj3f
    ContributorAuthor

    The title changed, and this comment is the evidence behind it. Point 4 of the body above — "a column-label channel in the shared IR, the expensive one, since it reaches the SPARQL and JSON-LD formatters too" — is the part that turned out wrong. It is left in place because the rest of the analysis is sound and the correction is more useful next to it than silently replacing it.

    Traced during #1867 (a4046a933), which corrected docs/query/cypher.md accordingly.

    What holds. ir::Column genuinely has no label field (fluree-db-query/src/ir/projection.rs:249), so the observation that a fresh VarId cannot carry the display name is correct.

    What does not. QueryResult lives in the api crate (fluree-db-api/src/query/mod.rs:112), and the Cypher formatter reads headers from result.vars.name(v) (fluree-db-api/src/format/cypher.rs:67). So a Cypher-only column-label channel can live api-side and never reach the SPARQL or JSON-LD formatters.

    And there is precedent for exactly this shape, which is what moves it from speculative to routine. Query::cypher_vocab (fluree-db-query/src/ir/query.rs:310) is already a Cypher-only field on the shared IR Query, set after lowering and read only Cypher-side. Checked who reads it: all four fluree-db-sparql occurrences are cypher_vocab: None initializers, never reads, and fluree-db-api/src/format/ has none. The mechanism is a field, in a pattern this codebase already uses here — not a new seam.

    The cost is those initializers. A new field means every Query struct literal across the front-ends gains a line. Mechanical rather than semantic, but it is not nothing, and it is the honest price of the approach.

    Of the three places a fresh synthetic VarId could have been resisted:

    Grouping Keys off VarId; indifferent.
    Bolt No vars.name call anywhere in fluree-db-bolt/src, so it appears to inherit the api-side channel — inferred, not traced end to end.
    ORDER BY Resists, and is the real remainder.

    align_order_by_with_projection (fluree-db-cypher/src/lower/stmt.rs:757) matches ORDER BY expressions against projection items by surface expression. So RETURN n.name AS n ORDER BY n would not match the projection item, would fall through to interning the original node variable, and would sort by the node rather than by the re-projection.

    Verdict: the blocker is Cypher-lowering-local, not shared-IR — smaller than filed, but not absent. True re-projection still needs a name-to-variable rebinding layer in lowering, which is genuine work, so the P3 sizing stays defensible even though the reasoning behind it has changed.

    One caveat for anyone sizing this. The Bolt row above is the weakest link in the chain: the conclusion rests on the absence of a call rather than on following a value through. Absence of a vars.name call is consistent with inheriting the channel and also consistent with Bolt building headers somewhere nobody looked. Trace it before committing to an estimate, particularly since the api-side argument is what makes this small.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3area:queryenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions