Skip to content

fix(sparql): read and write RDF lists as RDF - #2159

Merged
bplatz merged 26 commits into
mainfrom
fix/list-model
Oct 24, 2026
Merged

bplatz merged 26 commits into
mainfrom
fix/list-model

Conversation

@bplatz

@bplatz bplatz commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

SPARQL now reads and writes an RDF list as the RDF it denotes, and JSON-LD keeps Fluree's member view. Storage is unchanged: a list is still stored compactly as positioned members (FlakeMeta.i) wherever it can be. The translation happens where each surface reads and writes.

Fixes #1694

This targets main as a breaking fix rather than waiting for the major: list support is recent and little used, and each release that keeps the old reading spreads it further.

Breaking changes

For SPARQL over list data:

  • ex:s ex:items ?o binds the list's head cell, not each member; ?s ?p ?o and COUNT(*) include the owner edge and the cells' rdf:first/rdf:rest triples.
  • DELETE DATA { ex:s ex:items 2 } no longer deletes a member, and INSERT DATA { ex:s ex:items 2 } adds a value beside the list.
  • DELETE WHERE { ex:s ?p ?o } deletes the owner's edge and leaves the list's cells, as for any RDF list.

For every surface: a second, different list on one subject and property is a second list. It used to merge into the first.

1. One list per property, and one list reader

  • Second list on a property. A second list on one (graph, subject, predicate) used to merge its positions into the first. It is now stored as an explicit rdf:first/rdf:rest chain of fresh blank nodes, because positions name no list. This applies to JSON-LD, Turtle/TriG, SPARQL ADD/COPY, and bulk import, including across import chunks.
    • Inserting a different list onto an owner that holds one adds a second list.
    • Inserting the same members in the same order restates the stored list, as re-inserting any stored fact does.
    • Upsert replaces.
  • Shared list reader. fluree_db_core::rdf_list reads either stored shape. The OWL 2 RL reasoner, the config graph and the JSON-LD crawl use it now. Before, the reasoner read only chains, so Turtle and JSON-LD list axioms were ignored.

2. SPARQL reads lists as RDF

ex:s ex:items ?o binds the list's head cell, and rdf:rest*/rdf:first walks the members. ?s ?p ?o, COUNT(*) and property paths all agree on the same graph.

  • The view. A triple pattern a list can match becomes a ListView pattern: one on a predicate that holds members, on rdf:first/rdf:rest, or with a variable predicate. Cells are blank nodes named per request (_:l{n}-{k}).

  • Planning. A list-view triple is planned with its join block, so it keeps the planner's lane choice. Its stored rows run through the chosen scan or join with members hidden (ListTeeOperator), and the list triples are added only for subjects that own a list (ListAugmentOperator). Ownership is checked exactly, from a per-leaf cache of list subjects plus novelty.

  • Which predicates hold members. These come from the index's POST leaflet directories, read once per index store, and from novelty. A leaf is opened only when one of its multi-predicate leaflets holds list rows. A ledger with no lists plans exactly as before.

  • Fast paths. COUNT(*) over ?s ?p ?o and the per-predicate GROUP BY ?p count add the view's triples to the stored counts, from a per-graph census of lists and members. They take the indexed head with no novelty, and elsewhere decline to the generic plan. The other whole-graph count lanes still stand down on a ledger holding a list.

  • Cost. In a debug-build probe on 5,000 indexed subjects, compared with the same ledger without one unrelated list:

    Query Before review Now
    COUNT(*) over ?s ?p ?o ~30–50× 1.00×
    GROUP BY ?p count ~30–50× 1.07×
    COUNT(*) of ?s ex:knows ?f . ?f ?p ?o 1.96× 1.12×
    SELECT of that join 1.24× 1.03×

    cargo bench -p fluree-db-api --bench query_hot_list_view measures the same (FLUREE_BENCH_SCALE=medium for a larger run). The planner counts the cells, which statistics never see. Without that, ?c rdf:first ?x ranked as empty and a 400-member walk took 56 s instead of 10 ms. The test pins this in fuel.

  • Graph output. CONSTRUCT, DESCRIBE and Graph Store GET write lists back as ( … ) in Turtle and @list in JSON-LD, so a GET followed by a PUT commits nothing. The rule matches JSON-LD's RDF-to-JSON-LD list conversion: only unnamed cells that nothing else references are folded. A collection named only from its own cells, or from a cycle of collections, stays as triples.

  • Everywhere a pattern appears. The view also applies:

    • inside EXISTS expressions (FILTER, BIND, grouped projections, HAVING, ORDER BY), in queries and subqueries;
    • beside a FILTER or BIND in the same group;
    • to a zero-length path, which pairs every cell and rdf:nil with itself whatever its predicate.

    Inside GRAPH <r2rml-source> the patterns are read without the view, since a graph source holds no RDF lists.

  • DESCRIBE. It also returns a described node's blank-node objects and its list cells.

  • W3C. basic#list-2..4 pass and come off the register. The harness now reads @list in CONSTRUCT results; constructlist needed this.

3. SPARQL writes lists as RDF

An update's WHERE binds cells, and its templates can change them: replace a member, append, move a list, share a cell. Each list an update touches is rebuilt from its triples:

  • Compact: when it is still an owner's edge to a chain of plain cells (crate::lists).
  • As triples: otherwise, with its cells minted as blank nodes.

Other write rules:

  • Compaction at write time. ( … ) in INSERT DATA and in templates is stored compactly. So is a list written out as rdf:first/rdf:rest over a document's own blank nodes, on Turtle, TriG and N-Triples insert and upsert. An N-Triples export therefore reads back as the lists it holds.
  • Plain triples never touch members. A plain s p o names no list member: DELETE DATA { ex:s ex:items 2 } leaves the member, and INSERT DATA adds a plain value beside the list.
  • Deleting the owner's edge leaves the cells, as for any RDF list, however each list is stored. A compact list whose edge is deleted is stored again as its cells' triples. The SPARQL guide shows how to delete a list with its cells.
  • Policy judges what changed, against the owner. Storing a list again can stage facts the write did not change as RDF: the old members of a list re-stored as triples, and the triples restating its cells. Those are not judged one by one, so a delete-only identity can still run DELETE WHERE { ex:s ?p ?o } on a subject holding a list. A post-state condition still reads everything staged. A change to a list's cells is judged as a change to its owner's property, however the list is stored:
    • a compact list the write deletes from, or states a new triple about a cell of, has its members judged as the owner's;
    • a change to a stored cell's rdf:first/rdf:rest is judged also as the owner's edge to the list, found by walking back to its head.
  • ADD and COPY keep one list. A compact list in a source graph the operation keeps is stored in both graphs as one chain of the same blank nodes. The list is the same list in both, and a second ADD commits nothing. MOVE's source goes away, so its lists move compactly.
  • Lists with hidden members. An update that edits a list holding members the request cannot read is refused (UnsupportedFeature), so a re-encoded list cannot reuse a hidden member's position.

4. Review fixes

  • Join variables. The planner's variable count now covers list-view patterns. Without it, ex:n0 ex:knows ?f . ?f ?p ?o was a cartesian product on any ledger holding a list. The match is exhaustive, so the search, R2RML and SERVICE patterns count their variables too.
  • Discovery without whole-leaf reads. List predicates come from leaf directories, as above.
  • The view's cost, through the block planning, count census and per-batch member hiding described in section 2.
  • JSON-LD. An identical re-insert restates the stored list. A crawl reads a list stored as triples as its members, and keeps the head when a policy hides any member.
  • Export. Export now resolves novelty to each fact's latest state. A fact asserted and then deleted since the last index used to panic a debug build and be exported by a release build. The bug is not list-specific, but a SPARQL list edit reached it.
  • Tests:
    • the view is now tested over an index and through a shared join variable;
    • a property-chain member-order test;
    • the list-row lane tests are now asked in JSON-LD, the reading in which those rows reach those lanes;
    • the span-capture helper no longer drops events when tests run in parallel, which had let a routing assertion pass vacuously when another test in its binary reached the callsite first.
  • Smaller fixes: join.rs's misplaced doc line, and the wasm32 build.

Not covered

  • A JSON-LD where clause binds the head of a list stored as triples, where a crawl shows its members. Storing every list compactly removes the second shape.
  • Datasets spanning several ledgers, and history queries, still see members as values. Subjects aren't comparable across ledgers, and history reads stored rows.
  • Bulk import stores ( … ) compactly, but a chain written out stays a chain. It reads the same.
  • EXPLAIN omits list-view triples from some plans. Execution is unaffected.

Follow-up: #2171 (store every well-formed list compactly, on next)
Follow-up: #2172 (list census in the index root, on next)
Follow-up: #2173 (remaining count lanes, batched joins on list predicates, carried-forward discovery)
Follow-up: #2174 (the view over datasets spanning ledgers)

A Turtle ( ... ) or JSON-LD @list on owl:unionOf, intersectionOf,
oneOf, propertyChainAxiom or hasKey is stored as members of the axiom's
subject, but the reasoner only followed rdf:first/rdf:rest chains, so it
ignored those axioms. A shared reader in fluree-db-core reads the values
of one subject and predicate as lists in either shape, and the reasoner
reads every list axiom through it.
A list is stored compactly as its members' positions on the owning
subject and predicate, and a position names no list, so two lists on one
property merged into one: ex:s ex:p (1 2), (3 4) stored 1@0 3@0 2@1 4@1,
and two lists sharing a member at one position lost it. Every list a
write produces now reaches staging as a pending list. The first on a
property is stored compactly when the ledger holds no list members there
that the write keeps; every other one is stored as an explicit chain of
fresh blank nodes.

This covers Turtle and JSON-LD inserts, the RDF-text verbs, update
templates (a fresh list per WHERE solution), upsert and sync (checked
before cancellation, so restating a list commits nothing), bulk import
(chunks share the owners they claim), inline shapes and ontologies, and
SPARQL ADD.

Config reads f:policyClass and f:allowedIdentities through the shared
list reader; a chain's head used to be read as one blank-node value.
A list stored compactly - its members values of the owner's (graph,
subject, predicate), each with its position - is, as RDF, an owner edge to
a head cell and a chain of rdf:first/rdf:rest cells. SPARQL now sees that
graph: `ex:s ex:items ?o` binds the head, `rdf:rest*/rdf:first` walks the
members, and `?s ?p ?o`, COUNT and property paths all agree. JSON-LD
queries keep the member view. Storage is unchanged.

- A triple pattern a list can match (on a predicate holding list members,
  on rdf:first/rdf:rest, or with a variable predicate) becomes a list-view
  pattern: its stored non-member rows plus the list triples, with cells as
  blank nodes named per request. Which predicates hold members comes from
  the index (POST leaves with an o_i column) and novelty, so a ledger with
  no lists plans exactly as before. Fast paths, which read stored rows,
  stand down for a query holding a list-view pattern.
- Property paths walk the cells, in either direction, in a zero-length
  match's universe and through composite steps. Each list is read once per
  request, and the planner counts the cells statistics never see, so a walk
  starts from its owner rather than from every cell.
- CONSTRUCT, DESCRIBE and a Graph Store GET write a list back as ( ... ) in
  Turtle and @list in JSON-LD, so a graph read and put back is unchanged.
  DESCRIBE also carries a described node's blank-node objects and list
  cells. Explain applies the view, as execution does.

W3C basic#list-2..4 now pass and come off the register; the harness reads
@list in CONSTRUCT results.
A SPARQL update now writes lists as it reads them. Its WHERE binds a
list's cells, and the writes that name a cell - or a blank node the
transaction mints for a ( ... ) or a chain written out - edit that list's
triples, deletions first. Each list touched is stored again: compactly
when it is still an owner's edge to a chain of plain cells, else as its
triples, its cells minted as blank nodes.

- A ( ... ) in INSERT DATA or a template is stored compactly, as the
  first list on its property, so appending, replacing a member or moving a
  list keeps it compact.
- A list written out as rdf:first/rdf:rest over a document's own blank
  nodes is stored as a list on Turtle, TriG and N-Triples insert and
  upsert, so an N-Triples export reads back as the lists it holds.
- A plain `s p o` names no list member: DELETE DATA leaves the member,
  INSERT DATA adds a value beside the list.
- Deleting an owner's edge deletes the list unless the update's
  insertions name one of its cells: the cells are unreachable, and
  deleting a subject stays a delete, which a delete-only policy permits.
@bplatz bplatz added bug Something isn't working as expected area:sparql SPARQL/Turtle/TriG/JSON-LD parsing, lowering, UPDATE semantics, W3C conformance labels Oct 21, 2026
@bplatz
bplatz requested a review from a team October 21, 2026 21:32
- Deleting an owner's edge leaves the list's cells as triples again,
  however each list is stored. What storing a list again stages without
  changing it as RDF is no change a modify policy judges, so a
  delete-only identity can still delete a subject that holds a list.
- ADD and COPY store each compact list of the source as one chain of the
  same blank nodes in both graphs: the same list in both, and a second
  ADD adds nothing.
- A collection named only from its own cells, or from a cycle of
  collections, is written as triples instead of dropped.
- An EXISTS inside a FILTER, BIND or UNWIND expression reads lists as RDF.
- The list-view operator streams the stored rows instead of buffering
  them, so a LIMIT stops a wildcard scan.
- A zero-length path pairs the cells and rdf:nil with themselves on any
  predicate.
- A variable a pattern repeats takes one term even where a row left it
  unbound.
@bplatz bplatz added the breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section label Oct 21, 2026
A sibling test can pin the join's callsite interest to "never" while this
test's subscriber installs, so the routing event goes uncaptured. Run each
query once and rebuild the interest cache before counting, as other
span-capture tests do.
…S reads

- A change to a list's cells is judged as a change to its owner's
  property however the list is stored: a compact list a write states a
  new triple about a cell of, not only one it deletes from, has its
  members judged as the owner's; a change to a stored cell's rdf:first or
  rdf:rest is judged also as the owner's edge to the list, found by
  walking back to its head.
- A post-state policy condition reads everything the write stages; only
  the facts it judges leave out a list stored again unchanged.
- An EXISTS in a grouped projection, a HAVING or an ORDER BY, in a query
  or a subquery, reads lists as RDF too.

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@bplatz the SPARQL reading here is the right one: a list is the RDF it denotes, list-2..4 come off the register, and the second-list merge was silent data loss that this stops. The reasoner reading list axioms in either stored shape through one reader is a real fix too. Three headline notes: (1) this is #1694's "translate at query time" option, which that issue itself called "a query-planner special case on a hot path", and as built the cost isn't confined to queries that touch a list. has_list_meta is sticky, so on any ledger that has ever held one (a single sh:in or owl:unionOf will do) every variable-predicate pattern goes through the view and loses the fast paths, a bound subject is read twice, and the first query per index store walks the whole POST branch. I wonder if the narrower shape is a view that only adds what it adds (the list triples, minus the members) while the lanes keep working on everything else; numbers below. (2) It's labeled breaking-change, and existing SPARQL over list data changes answers without an error: a member DELETE becomes a no-op, DELETE WHERE { ex:s ?p ?o } leaves the cells behind, and a JSON-LD re-insert of a @list adds a second list. docs/contributing/releasing.md puts compatibility breaks on next. Is main the target you want for this, or does it belong with the major? (3) The join bug in the must list below is the third pattern kind to fall through the _ => {} arm of collect_var_stats and lose its variables (DefaultGraphSource in ce5d0a8db, annotation chains in f3003506e, now ListView). The one-arm fix is right for this PR, and making that match exhaustive is small enough to fold in with it, so the next pattern kind is a compile error rather than a cartesian product. The other walks over Pattern in fluree-db-query that never mention ListView are worth an audit, but not in this PR.

Claude-assisted review below:


💬 Comment — 2 things need to be addressed before this merges, and headline note (2) is a question I'd want answered first.

This is a big, careful piece of work, and most of what I probed held up: the view reads correctly from a cold index as well as from novelty, the edits that leave a compact list no longer compact (dropping a member, cutting the chain, a second rdf:first, moving the list onto an owner that holds one, sharing its head) neither duplicate nor lose members, and the policy tests cover the ways a cell edit can be spelled. The two must-fixes:

  1. fluree-db-query/src/execute/where_plan.rs:822 (inline on :3163): collect_var_stats has no arm for Pattern::ListView, so a variable shared between a plain triple and a list-view pattern counts once and is pruned from the triple's scan. On any ledger that holds a list, SELECT ?p ?o WHERE { ex:n0 ex:knows ?f . ?f ?p ?o } returns every triple in the ledger instead of ?f's two. One arm fixes it; I tried it, and every shape I probed comes back right with it_sparql_lists still green.
  2. fluree-db-binary-index/src/read/binary_index_store.rs:2533: list_predicate_ids opens every POST leaf with open_leaf_handle, which under the default RemoteLeafFetch::Whole downloads each one whole, so on a remote store the first SPARQL query per index store pulls the entire POST branch. open_leaf_dir for every leaf, and a handle only for a leaf with a multi-predicate HAS_O_I leaflet.

Should address, inline below:

  • operator_tree.rs:2453: with the join fixed, a ledger that has held any list still pays for the view on every variable-predicate query (COUNT(*) over ?s ?p ?o 0.3 ms → 23 ms, a ?f ?p ?o join about 1.9×).
  • list_edits.rs:256: DELETE WHERE { ex:s ?p ?o } leaves the cells behind and they accumulate (6, 12, then 18 triples over three rounds; none on 4.2.4).
  • lists.rs:282: a JSON-LD re-insert of a @list adds a second list, and the JSON-LD side reads any list stored as a chain as a bare blank node.
  • list_view.rs:463: the same query answers differently once a second ledger joins the dataset.
  • it_sparql_lists.rs: nothing reaches the view over an index, and nothing joins a plain triple into a list-view pattern.

Two small ones are inline too (it_owl2rl_list_encodings.rs:254, join.rs:1092).

On CI: nothing from ci.yml has run on this branch yet. Every check on 010a55d66 is the Release workflow's (plan plus skipped jobs), because ci.yml only fires for PRs into main/next, so fmt, clippy -D warnings --all-features, nextest and the W3C suite (including the stale-register check behind list-2..4 coming off) will run for the first time when the stack is retargeted. cargo fmt --check is clean locally. I couldn't run the W3C suite here because the rdf-tests submodule isn't in my checkout.

Adherence to repo commitments:

  • Patterns/abstractions: ⚠️ rdf_list::read_lists is the shared reader this needed, and moving the reasoner and config onto it is right. The SPARQL view, graph-format's Collections, the JSON-LD query/crawl and SHACL's expand_rdf_lists still read lists on their own rules, and the new Pattern::ListView falls through the var-count walk (headline note 3).
  • Performance (speed first, memory second): ✖ CRITICAL: on a ledger that has ever held a list, the join bug makes ?s ex:knows ?f . ?f ?p ?o about 960× slower as well as wrong; with it fixed the same join still costs about 1.9×, COUNT(*) over ?s ?p ?o loses its fast path, and the first query per index store walks the POST branch. Ledgers that never held a list plan exactly as before (has_list_meta == Some(false) short-circuits the view).
  • Host targets: ⚠️ shared query code every host runs. The whole-branch walk is worst where leaves are remote (a server or a Lambda reading S3, the wasm residency tier). All the evidence here, mine included, is memory and local-file ledgers.
  • Testing: ⚠️ the 26 new SPARQL list tests plus the identity and OWL encoding suites pass by name for me, and reversing the shared reader's member order turns five of them red; but returning an empty list_predicate_ids leaves the whole suite green, no test joins a plain triple into a list-view pattern, and CI hasn't run any of it yet.
  • Conventions: ✔ thorough commit bodies, and the docs moved with the behavior (sparql.md, insert.md, the D-13 note in the roadmap). One stray doc line on join.rs:1092.

Verified locally at 010a55d66: the PR's list suites by name (it_sparql_lists 26, it_list_identity 6, it_owl2rl_list_encodings 5, plus the edited it_transact_list_retract, it_jsonld_empty_list, it_turtle_empty_collection, it_export_lists and it_delete_stored_facts tests); cargo fmt --check; scratch probes for each behavior quoted here (novelty and rebuilt-index ledgers, cold reload); the same reads and writes through the 4.2.4 CLI for the before side; three mutations (the shared reader's order, an empty list_predicate_ids, the one-arm fix), each restored.

I'm leaving this as a comment rather than an approval for now, since whether a breaking-change lands on main or waits for the major is a release-policy call more than a code one. Either way, the two must-fixes and a green CI run once the stack is retargeted are what I'd want in first.

i += 1;
}

Pattern::ListView(lv) => {

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.

🔴 Must address before merge — on any ledger that holds a list, a join into a variable-predicate pattern turns into a cartesian product.

collect_var_stats (where_plan.rs:703-826) counts the variables of every pattern kind it knows and ends in _ => {} (:822), which is where Pattern::ListView lands. So in ex:n0 ex:knows ?f . ?f ?p ?o, ?f counts once, emit_mask_for_triple (:3668-3671) treats it as unused unless the query projects it, the ex:n0 ex:knows ?f scan stops emitting it, and the ListViewOperator built here sees ?f unbound on every row: stored() scans the whole graph and lists() adds every list triple, once per input row.

On a ledger of 50 ex:nI ex:name "nI" ; ex:knows ex:nJ subjects plus one unrelated ex:config ex:order (ex:a ex:b), SELECT ?p ?o WHERE { ex:n0 ex:knows ?f . ?f ?p ?o } returns 105 rows (every triple in the ledger) instead of 2, and SELECT (COUNT(*) AS ?n) WHERE { ?s ex:knows ?f . ?f ?p ?o } returns 5,250 instead of 100, from novelty and from a rebuilt, cold-loaded index alike. The patterns in the other order, the same join inside OPTIONAL, and ex:n0 ex:knows ?f . ?f rdf:first ?x (2 rows instead of 0) go wrong the same way; without the list, or through JSON-LD, all of them are right. At 5,000 subjects the count is 100,025,000 instead of 20,000, and takes about 113 s instead of 0.1 s in a debug build. That's the shape of "find an entity by a key, then fetch its properties" (?s ex:email "…" . ?s ?p ?o), on every ledger that has ever stored a list.

The fix I tried is one arm, the same one Pattern::Triple has, in collect_var_stats:

Pattern::ListView(lv) => {
    for v in lv.triple.referenced_vars() {
        bump_count(counts, v);
        vars.insert(v);
    }
}

With it, all eight join shapes I tried come back right and the 26 tests in it_sparql_lists.rs still pass. The comment on the DefaultGraphSource arm a few lines above it (:792-807) describes exactly this failure for an earlier variant the walk missed, so dropping the _ => {} for an exhaustive match would make the next variant a compile error instead.

Commenting here because collect_var_stats (where_plan.rs:703-826) is not in this diff.

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.

Addressed in 016131d

};
for leaf in &branch.leaves {
let handle =
self.open_leaf_handle(&leaf.leaf_cid, leaf.sidecar_cid.as_ref(), false)?;

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.

🔴 Must address before merge — on a remote store, the first SPARQL query against a ledger that holds a list downloads every POST leaf whole.

list_predicate_ids walks every leaf of every graph's POST branch through open_leaf_handle, and under the default RemoteLeafFetch::Whole (:97-107) that open is one GET for the whole leaf, persisted to the disk cache (:1254-1258). For a leaflet with p_const this loop only needs the directory, and open_leaf_dir (:1435) reads just the header and directory under either fetch policy.

It runs from ListView::for_db (list_view.rs:83-90) in the prepare of every non-history SPARQL query (runner.rs:491) and every SPARQL update with a WHERE (stage.rs:741), once per BinaryIndexStore, whenever the root's has_list_meta isn't Some(false). That bit is sticky, so this is any ledger that has ever held a list (one sh:in or owl:unionOf is enough), plus every root that predates the flag (None). On S3 that's a sequential download of one of the four orderings, in full, before the first query plans: once per process for a server, and once per cold start for an embedded host like a Lambda, where the only disk the cache can land on is /tmp. Under the wasm residency tier the same open goes through open_resident_leaf_handle (:1179), so every POST leaf has to become resident first. Nothing else on the read path walks a whole branch (this is the only for leaf in &branch.leaves in the file), and no test reaches this function (see my note on it_sparql_lists.rs).

Minimally: open_leaf_dir for every leaf, and open_leaf_handle + load_columns only for a leaf that has a multi-predicate leaflet with HAS_O_I set. Longer term the set probably belongs in the root, since the indexer already sees every list row when it sets has_list_meta, but that's a format change and so next material.

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.

Addressed in 6c14bb4

// that no stored row is (`crate::list_view`); every fast path reads the
// stored rows, members included, so none applies.
let list_view = crate::list_view::query_has_list_view(query);
let enable_fused_fast_paths = enable_fused_fast_paths && !list_view;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 Should address — with the join fixed, a ledger that has held any list still pays for the view on every variable-predicate query.

rewrite_pattern makes every Ref::Var predicate a list-view pattern whenever a view exists (list_view.rs:302), and a view exists whenever the root's sticky has_list_meta isn't Some(false). This line and the three !list_view guards below it (:3085, :3123, :3179) then switch off the fused fast paths, the top-k and predicate-object count lanes and the count-by-predicate stats lane for the whole query, and list_view.rs:925 reads each bound subject a second time, in full, to look for members its stored scan already read and hid.

Same 5,000-subject ledger, indexed and cold-loaded, with and without one unrelated two-member list (debug build, best of two):

  • SELECT (COUNT(*) AS ?n) WHERE { ?s ?p ?o }: 0.3 ms / fuel 1 → 23 ms / fuel 21
  • SELECT ?p (COUNT(?s) AS ?n) WHERE { ?s ?p ?o } GROUP BY ?p: 0.4 ms → 25.8 ms
  • SELECT (COUNT(*) AS ?n) WHERE { ?s ex:knows ?f . ?f ?p ?o }, with the one-arm fix from where_plan.rs:3163 applied: 107 ms / fuel 126 → 208 ms / fuel 176

The 4.2.4 CLI answers both ledgers at the same fuel. Narrowing the (Want::Node(s), Want::Any) read to (s, p) for p in view.predicates, as the (Any, Any) arm already does, brought the join to 191 ms; the rest is the operator itself.

Some of this is the design's price (a count over ?s ?p ?o has to add the list triples and drop the members), but I don't think it has to be paid in full: the count fast paths can be corrected rather than skipped (the stored count, minus the members, plus one owner edge per list and two triples per member), and the members can come from the rows the stored scan already reads. Since it's a regression on queries that never touch a list, I'd want it either won back or measured in fluree-db-api/benches so the trade is on record. If you agree it's right, I'd rather see it in this PR than lost in the backlog.

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.

Addressed in 6a5c236 and 0b8a555. The remaining count lanes and batched joins on list predicates are in #2173.

}
let (left, chained) = crate::lists::chain_lists(flakes, |sid| self.is_cell(sid));

// A WHERE cell no chain holds is stored as a blank node minted for it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 Should address — DELETE WHERE { ex:s ?p ?o } now leaves a list's cells behind, and they pile up.

Deleting the owner's edge stores the cells as triples of fresh blank nodes (here, via stored_as), so the delete-a-subject idiom over a subject holding ( 1 2 3 ) asserts six triples on a request that only deletes. I ran three rounds of a Turtle insert of ex:s ex:name "s" ; ex:items (1 2 3) followed by DELETE WHERE { ex:s ?p ?o }: this head leaves 6, then 12, then 18 triples, and a JSON-LD {"@id": "?s", "?p": "?o"} returns all of them. The same three rounds through the 4.2.4 CLI leave nothing. A list of n members leaves 2n triples each round, so a delete-and-reload loop over subjects with long lists grows the ledger without anyone noticing.

I follow the reasoning in 47f7fc5: compact and chained lists should behave alike, and as RDF the cells are triples of their own. e54db3d's first rule (delete the list unless an insertion names one of its cells) was the other option, and I wonder if it's the better default for a compact list in particular: its cells are names this request invented, nothing else can point at them, and once the edge is gone the only way to find them is a scan of rdf:first. Keeping "leaves the cells" for a list stored as a chain, whose cells really are stored, would keep RDF's reading where it's observable. If you'd rather keep it for both, I think it needs a loud line in the release notes, since sparql.md is the only place it's written down today.

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.

Addressed in de65d86. Kept as RDF semantics, since DELETE WHERE { ex:s ?p ?o } deletes only ex:s's triples, as it does for a Turtle list in any store; the SPARQL guide now says so and shows how to delete a list with its cells.

Comment thread fluree-db-transact/src/lists.rs Outdated
if !held.contains(&owner) && claimed.insert(owner) {
out.extend(list.into_compact());
} else {
out.extend(list.into_chain());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 Should address — re-inserting a JSON-LD document that holds a @list now adds a second list, and JSON-LD reads it as a bare blank node beside the members.

On this head, inserting {"@id": "ex:c", "ex:items": {"@list": [{"@id": "ex:A"}, {"@id": "ex:B"}]}} twice commits 5 assertions the second time, and the crawl comes back as "ex:items": [{"@id": "ex:A"}, {"@id": "ex:B"}, {"@id": "_:fdb-…--l0-0"}]. Through the 4.2.4 CLI the same two inserts leave [ex:A, ex:B]. The same opaque head shows up whenever a list ends up stored as a chain, and this PR adds several ways to get there: after a SPARQL INSERT { ?h ex:note "x" } WHERE { ex:s ex:items ?h }, JSON-LD's ex:items goes from [1, 2, 3] to one blank node, and so it does after a second list, after ADD/COPY, or depending on which chunk of a bulk import finishes first.

The PR body says JSON-LD keeps Fluree's member view, but that view only exists for a compact list; nothing on the JSON-LD read side reads a chain, though fluree_db_core::rdf_list::read_lists already reads both shapes. Two things I'd ask: whether re-inserting an identical list should stay idempotent for JSON-LD (it's RDF-correct that each @list is a fresh list, but JSON-LD loaders have had set semantics here, and not every loader calls upsert), and whether the JSON-LD query/crawl should render a chain through read_lists as @list, so the member view holds however the list is stored. At minimum the JSON-LD query docs should say that a list stored as triples reads as its head node.

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.

Addressed in de65d86 and 3f943a4. A JSON-LD where clause still binds the head of a list stored as triples; #2171 removes that second shape.


/// `input` joined with the list triples that match the pattern.
async fn lists(&self, ctx: &ExecutionContext<'_>, input: &Batch) -> Result<Option<Batch>> {
if ctx.is_multi_ledger() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 Should address — the same SPARQL query answers differently once a second ledger joins the dataset.

Over a dataset spanning ledgers the view is off (here, and in stored() at :454), so SELECT ?o WHERE { ex:s ex:items ?o } binds the head cell against one ledger and every member as soon as FROM names two. The body lists this as not covered, and I agree cross-ledger identity for an owner is real work. But a query whose meaning flips with the shape of its dataset is the kind of thing a user finds rather than a test, and hosts that compose datasets from several ledgers will hit it routinely.

If keying Owner by ledger as well isn't PR-sized, I wonder if refusing a list-view pattern over a multi-ledger dataset, or at least flagging it on the response, beats silently switching models. That's a call I'd leave to you, but I'd rather it be made here than discovered.

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.

Deferred to #2174; the SPARQL guide notes it meanwhile.

@@ -0,0 +1,862 @@
//! SPARQL's view of RDF lists.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 Should address — two gaps in what these tests reach: the view over an index, and a plain triple joined into a list-view pattern.

Every test in this file runs on a memory ledger's novelty, so ListView::for_db's indexed branch (list_predicate_ids reading POST leaflet directories, and its p_const vs multi-predicate split) never runs. I made list_predicate_ids return an empty set and every test here still passed (all 26, plus the identity, export and empty-list suites), while my probe over an indexed, cold-reloaded ledger went back to binding the members: ex:s ex:items ?o returned 1, 2, 3 and ?l rdf:first ?x returned nothing.

And no test joins a plain triple into a list-view pattern through a variable the query doesn't project, which is how the cartesian product on where_plan.rs:3163 got through. An indexed variant of a_list_is_its_head_and_cells, plus the ex:n0 ex:knows ?f . ?f ?p ?o family (both orders, inside OPTIONAL, and ?f rdf:first ?x) on a ledger that holds an unrelated list, would cover both. The first is coverage rather than a bug I found, but if you agree it's right, I'd rather see both folded in now than lost in the backlog.

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.

Addressed in 016131d

"@id": "ex:grandparent",
"owl:propertyChainAxiom": "LIST"
}),
members: &["ex:parents", "ex:parents"],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Optional / nit — the one order-sensitive axiom here is tested with a chain that reads the same backwards.

propertyChainAxiom is the only list axiom in this file where member order matters, and ( ex:parents ex:parents ) is a palindrome. I reversed the member order in fluree_db_core::rdf_list::read_lists (members.sort_by_key(|(index, _)| Reverse(*index))) and all five tests here still passed. Five it_sparql_lists tests did catch it, through stored_int_lists, so the reader itself is covered, just not on the reasoner's path. A chain like ( ex:hasParent ex:hasBrother ) for ex:uncle would pin the order there too. I recognize this is minor, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.

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.

Addressed in 40cc697

Comment thread fluree-db-query/src/join.rs Outdated
@@ -1079,6 +1090,16 @@ impl NestedLoopJoinOperator {
}

/// Trim output to only the specified downstream variables.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Optional / nit — this doc line belongs to with_out_schema.

hiding_list_members went in between with_out_schema's doc comment and the method, so "Trim output to only the specified downstream variables." now heads this method's doc and with_out_schema (:1103) has none. Moving the line down past this method fixes both. Trivial, but easy to fold in while you're here.

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.

Addressed in 6a5c236

Base automatically changed from fix/export-list-order to main October 24, 2026 11:18
bplatz added 13 commits October 24, 2026 07:25
main's accumulator holds a fact's assertion and retraction rather than
counting them (#2144), so FlakeAccumulator::retracts reads whether the
bucket holds a retraction.
The planner's variable count ended in a catch-all arm, and a list-view
pattern fell into it. A variable a triple shared with one counted once,
the triple stopped emitting it, and the list-view operator saw it
unbound. So `ex:n0 ex:knows ?f . ?f ?p ?o` returned every triple in a
ledger holding any list. The match is now exhaustive, so a new pattern
kind is a compile error rather than a cartesian product. The search,
R2RML and SERVICE patterns now count their variables too.

New tests run the join family (both orders, OPTIONAL, COUNT, a cell
walk) on a ledger whose only list is unrelated, from novelty and from a
reloaded index, plus an indexed variant of the head-and-cells test.
list_predicate_ids opened every POST leaf with open_leaf_handle. Under
the default RemoteLeafFetch::Whole that downloads each leaf in full, so
the first SPARQL query against a remote ledger that holds a list pulled
the whole POST branch. The walk now reads only leaf directories: POST
leaflets hold one predicate each, so a leaflet's p_const and HAS_O_I
flag answer it. A list-bearing leaflet spanning predicates, should one
exist, has its two columns range-read through open_leaf_handle_ranged,
which never fetches a whole leaf whatever the store's policy.
…s narrowly

A list-view pattern ended the inner-join block and ran as its own
operator: a nested-loop join, seeded batch by batch, without the
planner's join choice, filter bounds or projection pruning, followed by
a read of each bound subject's whole SPOT range to find its lists. On a
ledger holding any list, every variable-predicate join paid for both.

The block now plans a list-view pattern as its triple. Its scan or join
is the one build_scan_or_join picks, over the stored triples with list
members hidden. A ListTeeOperator under the join holds the input rows
whose subject may own a list, and a ListAugmentOperator above it adds
the list triples for those rows (or, with no input, for the empty
solution once). A subject is checked exactly: novelty's rows for it,
then the SPOT leaves holding its rows, whose list-bearing leaflets have
their subject and position columns read once per leaf for the store's
life. A bound subject's lists are read only for the predicates that
hold lists. Property and cyclic joins skip a block holding such
triples, and a FILTER on one's object stays a FILTER, since its list
triples bypass the scan.

On a 5,000-subject indexed ledger with one unrelated list (debug
build), `?s ex:knows ?f . ?f ?p ?o` went from 1.96x the list-free
ledger's time to 1.12x for COUNT(*) and 1.03x for SELECT. A
fixed-predicate join reads the same.
…d it

query_hot_list_view runs each scenario against two indexed ledgers that
differ in one unrelated two-member list: whole-graph and per-predicate
counts, a variable-predicate join (counted and projected), a
fixed-predicate join as the control, a bound subject, and a walk of the
list itself. A sanity check confirms the listed ledger answers through
the list view before anything is timed.
…skipping them

A query answered in SPARQL's view of lists turned every fused fast path
off, so on a ledger that had held any list, COUNT(*) over `?s ?p ?o` and
the per-predicate GROUP BY count scanned the whole graph.

The two lanes now take a single list-view pattern and add the view's
triples to the stored counts, from a list census the index store builds
once per graph: per predicate holding lists, its lists and members, read
from that predicate's PSOT leaflets flagged as holding list rows. Each
list's owner edge stands in for its members, and each member adds one
rdf:first and one rdf:rest, so the whole-graph count is the stored count
plus members plus lists. Empty lists and explicit chains are stored
triples already. Both lanes run only where their existing gate holds
(the indexed head, no novelty, one ledger, root policy) and otherwise
decline to the generic plan.

On the probe ledger, these counts went from 30-50x the list-free
ledger's time to 1.00x and 1.07x.
…ort it

The store's list_predicate_ids field used the bare OnceLock, which this
module imports only off wasm32, so the wasm32 build and wasm-smoke failed
to compile. It now names std::sync::OnceLock like the fields beside it.
The scan's row loop tested the operator's hide flag and each row's list
position. A leaflet holding no list rows loads its position column as the
constant "none", so the decision is made once per batch and the loop
tests a local.
With one dispatcher registered, tracing computes a callsite's interest
from the default subscriber of whichever thread first reaches it. A test
thread with no subscriber then cached "never" for the fast-path outcome
callsite, and a routing assertion in another test of the same binary saw
no events. init_test_tracing now keeps a second dispatcher registered for
the process, so interest comes from every live subscriber, and rebuilds
the cache. The list-count routing test reports the outcomes it saw.
The one order-sensitive axiom here was tested with (ex:parents
ex:parents), which reads the same reversed. An uncle chain, hasParent
then hasBrother, over data where the reverse derives someone else, fails
when the shared list reader reverses member order.
Clippy read 9 - 9 + 2 + 1 as a no-op. The count is five stored rows,
less three members, plus one owner edge.
Export translated the novelty overlay into cursor ops and sorted them, but
did not resolve them. Novelty holds a fact's whole lifecycle, so a fact
asserted and then deleted since the index was built reached the cursor as
an assert and a retract of one fact key. The cursor merges one op per
fact: a debug build panicked on its duplicate-key check, and a release
build emitted the assert, exporting the deleted fact. Export now resolves
the ops to each fact's latest, as every query-side caller already does.
A SPARQL edit that re-stores a list as triples reached the same path,
through the members it retracts.
…es it

Every list but one on a property is stored as an rdf:first/rdf:rest
chain, since the compact form holds one list per subject and property.
An insert of a list the property already held compactly, the same
members in the same order, therefore stored a second, identical list as
a chain, so re-running an insert, or a template over one subject in two
solutions, doubled the list. Such a list now restates the compact
members, as inserting a stored fact restates it. A different list is
still a second list, and an upsert still replaces.

The SPARQL guide also says that DELETE WHERE over a list's owner deletes
the edge alone, leaving the cells, as for any RDF list.
…mbers

A list the compact form cannot hold, a second list on a property or one
whose head a SPARQL edit gave a property, is stored as its rdf:first and
rdf:rest triples. A JSON-LD crawl rendered such a list as its head, a
blank node, where it renders a compact list as its members. The crawl
now reads a blank-node value heading a well-formed chain as that chain's
members, through the shared list reader, after the compact members. A
policy that hides any member leaves the head in place.

A JSON-LD where clause still binds such a list's head; the guide says
so.
These tests pin how the membership join and its COUNT(*) lane treat list
rows, which recur as ground triples only where a list's members are
values of their predicate. That is JSON-LD's reading; SPARQL now reads
a list as its cells, which no two lists share, and never plans list rows
into these lanes, so the SPARQL form had stopped exercising them. The
fast-path suite takes a JSON-LD query for a case whose text starts with
`{`.
A group whose triples carry a FILTER or BIND is planned as a sequential
join block, and that path built each triple as a plain scan, ignoring
the list view the triples-only block honours. A list-view triple there
read its members as values of the predicate and produced none of its
list triples, so a cell walk under a FILTER found nothing.

The block now builds a list-view triple through the list-view join, as
the triples-only block does. Its list triples join outside the scan, so
no FILTER, BIND or range semi-join is folded into it; pending ones apply
above it once their variables are bound. The one-pattern fallback builds
a list-view triple too, rather than dropping it, and a sub-SELECT counts
its list-view triples' variables among those it binds itself.
… view

On a ledger that holds a list, SPARQL wraps each pattern that may match
a list triple in a list view, a variable-predicate triple among them.
The R2RML rewrite of a GRAPH block over a graph source rewrites triples
only, so a wildcard `?s ?p ?o` inside `GRAPH <source>` was left behind
and the source was never scanned. A graph source holds no RDF lists, so
the rewrite now reads its patterns with each list view its triple again.
@bplatz

bplatz commented Oct 24, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f on (2): this stays on main as a breaking fix; the body now says why and lists the breaking changes for the release notes. On (3): collect_var_stats is exhaustive as of 016131d. An audit of the other Pattern walks found two more that skipped the view, fixed in 4a7e5e3 (a list-view triple beside a FILTER or BIND) and 6d0554b (a wildcard inside GRAPH <r2rml-source>).

The bench reconciler requires a budget for every declared bench, and the
list-view bench had none. Its numbers copy the sibling query_hot benches
until a nightly run lands a baseline. The bench tables list it too.
@bplatz
bplatz merged commit a2ba093 into main Oct 24, 2026
19 checks passed
@bplatz
bplatz deleted the fix/list-model branch October 24, 2026 17:29
bplatz added a commit that referenced this pull request Oct 24, 2026
Brings #2142, #2144, #2154, #2155, #2156, #2158, #2159, #2165, #2166 and
#2167 into next.

Where main's RDF lists (#2159) meet next's RDF 1.2 links:
- The list view walks an EdgeAnnotation's body; next has no
  AnnotationTarget.
- Export marks annotated edges skipping list rows, and writes an
  rdf:reifies row as next's @reifies block through main's JsonLdNode,
  untranslated rows included.
- The JSON-LD and import readers keep next's graph argument and
  triple-term spool records beside main's gap-free list positions and
  list chunking.
- One collection writer: main's shared module, which both JSON-LD and
  Turtle use, replaces next's Turtle-only one, and now also keeps the
  labels of blank nodes inside triple terms, of reifiers, and of blank
  graph names. A reified cell keeps its triples while the well-formed
  tail after it folds, as JSON-LD's list conversion does; next's writer
  test now says so.
- Hiding list members also turns off next's wildcard lane, which reads
  leaflets directly, and next's independent-scan count builds its right
  scan with the same hiding.

Elsewhere:
- List-predicate discovery opens a leaf ranged unless the store cannot
  read ranges, which next fetches whole.
- GC reports main's walk stop reason without next's removed artifact
  cache directory.
- Tests from main await next's async genesis_ledger, reload with
  without_storage_lock, and build stores without a cache directory.
bplatz added a commit that referenced this pull request Oct 24, 2026
`lists_as_cells` ended a push without a semicolon, which the workspace
denies (`semicolon_if_nothing_returned`), failing clippy and wasm32.

`test_a_collection_writes_to_a_ledger_as_its_text_does` read the list
with SPARQL `ex:s ex:list ?o` and expected its members. Since #2159
SPARQL reads a stored list as RDF, so that pattern binds the head cell.
The test now reads the members through JSON-LD, which also shows the
collection was stored as a list rather than as rdf:first/rdf:rest
triples, and the items through `ex:list/rdf:rest*/rdf:first`.
@aaj3f

aaj3f commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Two things from re-checking the follow-up commits after merge, filed as issues so they can be tracked against main:

The rest of my earlier notes check out at a7d259db1, or are tracked in #2171, #2173 and #2174. Thanks for turning these around so quickly, @bplatz.

aaj3f added a commit that referenced this pull request Oct 30, 2026
The parent now carries main eaa4c8e (#2159's list model among it). One
conflict, in binary_scan.rs's row loop setup: this branch prepares the
object bounds once per batch, and main decides list-member hiding once per
batch. The two are independent and both stay.

#2159 and the pushed string bounds: a FILTER on a list-view triple's
object stays a FILTER (the planner keeps it out of the bounds, since the
list triples join outside the scan), so a pushed bound never meets a list
member in SPARQL. JSON-LD sees members as values, where a bound and the
FILTER test the same term.
aaj3f added a commit that referenced this pull request Oct 30, 2026
… novelty holds

Two list fixtures for the lane matrix (#2159): lists on each lane's own
predicate in g1 and g2, one list fact in both, indexed; and the same
lists written to g2 after the index, so only novelty holds them. Every
lane shape, with the subject probe and the string bound, runs in every
scope of several graphs or none on both surfaces, and answers as the
general plan does. Under SPARQL's list view every lane's union site
names `fallback:list_view`; over the indexed lists its union site answers
JSON-LD. A SPARQL read of a list only novelty holds sees its head.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:sparql SPARQL/Turtle/TriG/JSON-LD parsing, lowering, UPDATE semantics, W3C conformance breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Turtle ingest flattens RDF collections into list metadata and drops ( ) statements entirely

2 participants