Skip to content

Planner evaluates an uncorrelated OPTIONAL after a later correlated one, changing the answer #1925

Closed

Description

@bplatz

Sibling OPTIONALs are not commutative: LeftJoin(LeftJoin(A, B), C) differs from LeftJoin(LeftJoin(A, C), B) whenever B and C bind a common variable. The planner nonetheless evaluates an OPTIONAL that shares no variable with the required pattern after a later OPTIONAL that does.

Repro

@prefix ex: <http://example.com/> .
ex:a ex:name "A" ; ex:fr ex:b .
ex:b ex:name "B" .
ex:k ex:g "k" .
PREFIX ex: <http://example.com/>
SELECT ?s ?f WHERE {
  ?s ex:name ?n .
  OPTIONAL { ex:k ex:g ?f }
  OPTIONAL { ?s ex:fr ?f }
}

Expected: (a, "k"), (b, "k"). The first OPTIONAL binds ?f = "k" on every row. The second then fails for a, because a ex:fr "k" is absent, and the row keeps "k".

Result
main (09f15cb) (a, ex:b), (b, null)
#1923 (a, ex:b), (b, "k")

Both are wrong. They differ only because #1923 makes an unmatched OPTIONAL leave ?f unbound, not Poisoned, so the late { ex:k ex:g ?f } can still bind it for b.

When both OPTIONALs are correlated with the required pattern, order is preserved. For example, OPTIONAL { ?s ex:g ?f } OPTIONAL { ?s ex:fr ?f } evaluates left to right.

Where

try_place_expander (fluree-db-query/src/planner.rs:2461 on main) only admits an expander whose pattern shares a variable with bound_vars (:2471). An uncorrelated OPTIONAL is therefore ineligible until a later OPTIONAL has bound ?f, and it is placed after it. Among eligible OPTIONALs, orig_index breaks the tie, since every OPTIONAL estimates Expander { multiplier: 1.0 } (:991). That is why the correlated case keeps its order.

Notes for whoever takes it

Activity

  1. added
    bug
    P2
    area:query
    on Sep 25, 2026
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

    P2area:querybug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions