Repository navigation
fix(query): Graph Store GET over lists: plan from the scan, stable cell labels, a linear and cheaper collection fold - #2383
Conversation
…ty seed needs_empty_seed admitted a leading triple, VALUES or BIND, but not a list-view triple, so a WHERE whose first pattern is one (the Graph Store GET's ?s ?p ?o over a ledger holding lists) got a synthetic EmptyOperator seed. The triple was then planned as a join against that seed, behind a list tee, instead of opening the plan with its own scan, and every choice that needs no upstream operator was lost to it.
The list view kept the predicates that hold list members in a HashSet, and a read across them (the Graph Store GET's ?s ?p ?o, or a bound subject with a variable predicate) walked that set in its per-request hash order. Lists are numbered in the order they are met, and their cells are labeled by that number, so lists on two or more predicates could swap cell labels between two runs of the same GET. That shows wherever cells are written as labels, such as N-Triples. The set is now a BTreeSet, so every read across it meets the lists in the same order.
Folding rdf:first/rdf:rest cells into ( ... ) and `@list` checked each step of a walk for a cycle with Vec::contains on the cells walked so far, so a list of n members cost n^2/2 comparisons. A Graph Store GET of one list of 300k members took over five minutes in the writer, and a CONSTRUCT that writes the list back goes through the same fold. The walk now stops once it has held every cell, which only a repeat can pass; the inbound check already stops a repeat sooner. Deciding which collections are written inline repeated a pass over every collection until nothing changed, one pass per level of nesting. It now starts from the collections named from outside any other and follows each to the ones named from inside it, once.
The JSON-LD writer kept each `@type` value once by scanning the node's types written so far, so a node with n types cost n^2/2 comparisons. It now keeps the types in a set once a node has two. A node with one type, the usual case, allocates nothing more.
Folding cells back into ( ... ) and `@list` keeps several maps keyed by the graph's terms, and the writers look up each triple's subject and object in two of them. Hashing those terms with std's SipHash was about 45% of a Graph Store GET's query time over a ledger of small lists. The maps now use hashbrown's default hasher, foldhash, which is much faster on short terms. Unlike an unseeded hasher such as Fx, foldhash is still seeded at random for each map, so terms that collide can't be worked out in advance from the data alone; these maps hold terms read from stored data. Nothing iterates these maps to decide what is written or in what order, so the output doesn't depend on the hasher. every_request_names_the_cells_alike now writes the GET's CONSTRUCT 16 times in Turtle and JSON-LD as well as N-Triples, each run with freshly seeded maps, and expects one text for each. The fold also no longer copies, per graph, the set of blank nodes other graphs of the document name; it checks that set where it is.
bplatz
left a comment
There was a problem hiding this comment.
Approving, once main is merged in: the branch conflicts in list_view.rs because its read-order fix already landed with #2315 (details inline). The planner fix, the linear fold and the @type dedupe all check out. A couple of small comments inline.
| /// Predicates whose values include list members; `None` when that is | ||
| /// not known, and any may. | ||
| predicates: Option<HashSet<Sid>>, | ||
| /// not known, and any may. Ordered, so a read across them meets the | ||
| /// lists in the same order every time, and names their cells alike. | ||
| predicates: Option<BTreeSet<Sid>>, |
There was a problem hiding this comment.
This change is already on main: fe8457afe (#2315) made predicates a BTreeSet and added it_unordered_output_order::the_list_view_reads_its_predicates_in_one_order, which is why this file conflicts. After merging main, take its version here and keep of_predicates. The PR body then needs updating, since the "read in a fixed order" bullet, the four-predicate N-Triples row (7 → 1) and the next note now describe #2315. The Turtle/JSON-LD runs in every_request_names_the_cells_alike are still worth keeping, since they pin the fold's seeded maps.
There was a problem hiding this comment.
You're right, #2315 got there first. In the merge (206e0da49) I took main's list_view.rs and kept only of_predicates, which the where_plan test needs, so this PR no longer touches the read order at all. I dropped the read-order bullet, the four-predicate N-Triples row and the next read-order note from the description. I kept the Turtle and JSON-LD runs in every_request_names_the_cells_alike like you said, since they're what holds the fold's seeded maps to one output.
| // The fold hashes every cell several times, and its output is looked up once | ||
| // per triple written. hashbrown's default hasher (foldhash) is several times | ||
| // faster than std's SipHash on short terms, and is still seeded at random, | ||
| // so terms taken from stored data can't be chosen to collide. |
There was a problem hiding this comment.
Nit: "can't be chosen to collide" overstates it. foldhash calls itself "minimally DoS-resistant" and says it "does not claim to provide HashDoS resistance against interactive attackers". Suggest just "still seeded at random". Choosing it over Fx is the right call.
There was a problem hiding this comment.
Fair, that overstated what foldhash promises. The comment now just says it's still seeded at random (98be45424). The 149cddaf1 commit message has the same overreach, but it's already pushed, so I've left it alone; the comment is what people will read going forward.
| // A list-view triple is planned as its triple, in the same block. | ||
| let needs_empty_seed = seed.is_none() | ||
| && !matches!( | ||
| patterns.first(), | ||
| Some(Pattern::Triple(_) | Pattern::Values { .. } | Pattern::Bind { .. }) | ||
| Some( | ||
| Pattern::Triple(_) | ||
| | Pattern::ListView(_) | ||
| | Pattern::Values { .. } | ||
| | Pattern::Bind { .. } | ||
| ) | ||
| ); |
There was a problem hiding this comment.
On the peak-RSS note in the description: your read is right. With no input, ListAugmentOperator::next_list_batch reads the lists only once the stored rows are exhausted (list_view.rs ~L613), so the list read's working set now stacks on rows the CONSTRUCT already holds. It's bounded by the list read, not ledger size, so fine as is.
Follow-up idea, not for this PR: for ?s ?p ?o, list_rows collects every list triple into one Vec and then copies it into a single batch, so the GET's list working set grows with the ledger's total list members and is briefly held twice. Reading it in batch-sized chunks would bound that.
There was a problem hiding this comment.
Thanks for confirming the read on the peak. On the follow-up: I looked at it, and it was contained enough to do in this PR (4f734935e), so I went ahead.
Chunking just the copy wouldn't have bought much, it turns out. CONSTRUCT keeps every batch it's handed, so the full Vec<ListTriple> would still be alive when the last chunk went out. So the triples are now made on demand instead. When an input batch arrives, PendingRows::read reads each distinct (s, p, o)'s lists (the same Arc<[List]>s the view already caches) and numbers every list up front, in the order the old code named them. ListTriples then walks owner edges, then each list's cells, rdf:first before rdf:rest, and next_list_batch hands back at most ctx.batch_size rows at a time. Numbering everything before the first batch goes out means a downstream list-view pattern reading the early batches can't shift a later list's number, so the labels and their order are what they were. list_rows and list_triples are gone; it's all inside list_view.rs.
It did more than I expected for peak memory, measured on a c7i.8xlarge (release build, each row in a fresh process, median of three; before and after this commit, on the same main):
| Query | Peak RSS rise, before → after | Instructions |
|---|---|---|
| GET of 100k three-member lists, Turtle | 352 → 176 MB | −3.4% |
| same, N-Triples | 367 → 191 MB | −3.7% |
| same, JSON-LD | 352 → 177 MB | −2.4% |
SELECT ?s ?p ?o over them (no formatting) |
266 → 49 MB | −5% |
| GET of one 300k-member list, Turtle | 381 → 311 MB | −3.8% |
| same, JSON-LD | 711 → 713 MB | −2.7% |
SELECT ?s ?p ?o over it |
287 → 109 MB | −11% |
So the list working set was most of the query's peak, and it more than undoes the 9–21 MB the planner change had added: against current main the small-lists GET now peaks at about half of its 344 MB, and the big-list GET in Turtle at 309 MB against its 363. The one row that doesn't move is the big list in JSON-LD, which stays 22 MB (3%) over main's 690 MB; I think the JSON writer's own tree sets that peak after the query is done (not traced).
a_long_list_is_answered_a_batch_at_a_time pins it: a 2,500-member list has to come in batches of at most 1,000 rows (it's one batch of 5,001 without the change), and the GET's Turtle still has to fold the whole thing back into ( 0 1 … 2499 ), which only works if the chain and its labels carry across the batches. Every GET row in the measurements writes byte-identical output before and after.
One trade-off, fwiw: a key repeated across many input rows now makes its triples again for each row, where it used to clone them out of a per-call cache. The GET has one input row, so it doesn't see this, and joins usually bind a different subject per row.
…ists list_view.rs takes main's version: its read-order change (predicates in a BTreeSet) landed in #2315. This branch keeps only the test-only of_predicates constructor there.
foldhash calls itself minimally DoS-resistant and makes no claim against an attacker who can probe it, so the comment no longer says colliding terms can't be chosen.
For `?s ?p ?o`, the Graph Store GET's read, the list view gathered every list triple in the ledger into one Vec and copied it into a single batch, so the list working set grew with the ledger's list members and was held twice while it was copied. The triples are now made on demand from the lists the request already reads, at most a batch of rows at a time. Every list a pending input matches is read and numbered before any of its triples is made, in the order the triples were made before, so the cells keep their labels and order however the batches are read in between.
|
Thanks, Brian. Merged |
Brings #2201, #2383, #1887 and the v4.2.8 release. - Release: next keeps its 5.0.0-alpha.3 version lines and lockfiles; the lockfiles gain only #2383's hashbrown. - #1887 (named-graph annotations on the base-index seal scan) does not apply: next has no annotation arena, seal scan or scan source. next's files are kept, and main's CLI test, which expects f:reifies* output under --raw-reifies, is dropped; export_resolves_named_graph_annotations covers the case. - #2201 applies: next's vector arena keys each stored fact by its own handle too. The fast-count guards take main's checks on next's call shapes; the export list keeps next's GraphTree and drops SharedLeafBytes, which next removed. The store tests write shards to next's content store. - #2383: the collection fold is main's linear walk with next's reifier, triple-term and graph-name rules, and the shared set is consulted rather than cloned per graph. The JSON-LD @type dedup keeps next's IRI-or-blank test. list_view.rs is next's, with an of_predicates for the planner test; the batch-at-a-time list read is ported in the next commit.
#2383's batch-at-a-time list read, on next's list view. For `?s ?p ?o`, the Graph Store GET's read, the view gathered every list triple the request matched into one Vec and copied it into a single batch. The triples are now made on demand, at most a batch of rows at a time. Every list a pending input matches is read and numbered before any of its triples is made, in the order they were made before, so the cells keep their labels. next's additions carry over: each read numbers its lists in the ledger its graphs are of, and a subject that is a cell reads only that cell of its own list, since a property can hold several lists.
Fixes on the Graph Store
GET's list path, carved out of the review on #2202. Since #2217 the RDF list view (owner edges plusrdf:first/rdf:restcells) only backs theGET, which reads?s ?p ?oand writes the lists back as( … )/@list. On the read, a planner gap planned that?s ?p ?oas a join against an empty seed, and the list view built every list triple into oneVecbefore copying it into one batch. In the writer, folding cells back into a list was quadratic in the list's length, which an ordinary CONSTRUCT that writes lists pays too, and once that was linear, hashing the terms was most of what was left. (This PR also had a fix for the order the view reads its list predicates in; #2315 landed the same change first, so this branch now takesmain's.)What changed
21599e128).needs_empty_seedinbuild_where_operators_seeded_with_neededadmitted a leading triple, VALUES or BIND, but notPattern::ListView, which is planned as its triple in the same block. So theGET's?s ?p ?oon any ledger holding a list got a syntheticEmptyOperatorseed and was planned asListAugment → NestedLoopJoin → ListTee → Emptyinstead ofListAugment → scan.ba36be64a).Collections::of(fluree-graph-format/src/collections.rs) checked each step of a walk down a list's cells for a cycle withchain.contains(&at)on aVec, so a list of n members cost n²/2 term comparisons. The walk now stops once it has held every cell, which only a repeat can pass (each cell has onerdf:rest); the inbound check already stops a repeat sooner, so the result is unchanged and the check allocates nothing. Deciding which collections are written inline also repeated a pass over every collection until nothing changed, one pass per level of nesting; it's now one walk from the collections nothing else names. That one didn't cost the list routes anything (their lists hold values, so nothing nests and it made two passes), but it was quadratic in nesting depth for any other graph.@typevalues are deduplicated in linear time (f9b99a1a6). The sweep of the writers for other quadratic folds found one more:add_type_valuekept each@typeonce by scanning the node's types written so far. It now keeps them in a set once a node has two, so the usual one-type node allocates nothing more. The Turtle, N-Triples and RDF/XML writers,Lists::writeandinstantiate_construct_graphare linear already.149cddaf1,98be45424). With the fold linear, a profile of just the query span of theGETover small lists put about 45% of its cycles in hashing terms with std's SipHash:Collections::ofkeeps several maps keyed by the graph's terms, and the writers look up each triple's subject and object in two of them. Those maps now use hashbrown's default hasher, foldhash, which the workspace already depends on and which is still seeded at random. On its own it took theGETover 100k small lists from 9.78G to 7.99G instructions in Turtle (−18%) and theGETof one 300k-member list from 10.38G to 8.61G (−17%). Fx, which isn't seeded, did about 3% better again (7.74G, 8.21G), so foldhash keeps 82–88% of what Fx would save. Nothing iterates these maps to decide what's written or in what order. The fold also stopped copying, per graph, the set of blank nodes other graphs name.4f734935e). For?s ?p ?o,list_rowsgathered every list triple in the ledger into oneVec<ListTriple>and copied it into a single batch, so theGET's list working set grew with the ledger's list members and was briefly held twice. The triples are now made on demand from the lists the request already reads (PendingRows,ListTriples), at mostctx.batch_sizerows at a time. Every list an input batch matches is read and numbered before its first triple is made, in the order the old code named them, so cells keep their labels and order even when a downstream list-view pattern reads the early batches first.Measurements
One EC2
c7i.8xlarge, release profile, this branch againstmainat596a4fd87, on indexed ledgers holding 300k list members. Each row is one query: theGET'sCONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }with the list view on, or the same CONSTRUCT as an ordinary query, which writes the lists back too. Instructions are user-space instructions retired on the query thread (the query runs on one thread; process CPU time matched wall time), median of 3 runs;main's one-big-list rows are a single run each, since each takes six to nine minutes. Peak is the rise of the RSS high-water mark over the query, in a fresh process after the same setup, median of three processes. Every row wrote byte-identical output on both builds.main→ this PRGETof 100k three-member lists, TurtleGETof one 300k-member list, TurtleThe same queries over the same values held as plain multi-values (no lists) are unchanged: every one is within 0.1% of
main's instructions, and the one measured for peak (the small-listsGETin Turtle) is within 1 MB.Peak memory halves on the
GETover small lists, and drops 15% on the one-big-listGETin Turtle, because the list read no longer builds every list triple in oneVecbeside the batch it copies them into.SELECT ?s ?p ?oover the same ledgers, with no formatting, shows the query phase alone: 265 → 49 MB on the small lists, 287 → 109 MB on the big one. Before the batch-at-a-time read, these rows ran 9–21 MB overmain(measured on an earlier box, at the previousmain), and that rise follows the planner change (reverting it alone took the big-listGETback tomain's peak): opened on its own scan, the list-view triple reads the lists after its stored rows, so that a LIMIT the stored rows meet reads no list, and that puts the list read on top of every stored row already held. The batch-at-a-time read more than undoes that everywhere except the one-big-listGETin JSON-LD, which stays 22 MB (3%) overmain; I think the JSON writer's own tree sets that peak after the query is done (not traced). The view-off CONSTRUCT rows don't read through the list view, and don't move.Tests
Each fix but the hasher change has a test that fails with it reverted:
execute::where_plan::tests::a_where_opening_on_a_list_view_triple_plans_its_scan_first(fluree-db-query) pins the plan shape. Without the fix it gets["ListAugmentOperator", "NestedLoopJoinOperator", "ListTeeOperator", "EmptyOperator"].collections::tests::a_long_collection_folds_in_linear_timefolds one 200k-member list, andcollections::tests::deeply_nested_collections_fold_in_linear_timefolds 20k collections each nested in the one before;jsonld::tests::many_types_are_written_once_each_in_linear_timewrites a node with 200k types plus a repeat. Each runs on a thread with a 60 s watchdog. In a debug build each takes under 2 s, and with its own fix reverted each runs past the 60 s. The two halves of the fold were reverted one at a time, and each time the other collection test still passed. The existing collection tests (nested collections, a collection named only from its own cells, a cycle of collections) pass unchanged.it_sparql_lists::a_long_list_is_answered_a_batch_at_a_time(fluree-db-api,grp_query_sparql) reads a 2,500-member list: no batch may hold more than 1,000 rows (without the change it's one batch of 5,001), and theGET's Turtle must still fold it back into the whole list, which only works if the chain and its labels carry across the batches.it_sparql_lists::every_request_names_the_cells_alikeruns theGET's CONSTRUCT 16 times over lists on four predicates, from novelty and from an index, and asserts one output each in N-Triples, Turtle and JSON-LD; the Turtle and JSON-LD runs go through the fold's freshly seeded maps each time.graph_store_http::every_get_labels_list_cells_alike(fluree-db-server,grp_http) checks the N-Triples case through theGETitself.Gates
On an EC2
c7i.8xlargewith Docker up, atca9b2a2b8:cargo fmt --check, workspace clippy--all-features --all-targets -D warnings,cargo check(default and server native) and both wasm32 clippy lanes are clean.cargo nextest run --workspace --all-features: 16,452 of 16,452 passed (46 skipped). Doc tests pass; the server's Graph Store tests 11/11; W3C 85 passed.nextcarries the planner gap, the quadratic fold and the one-Veclist read too. The planner fix and the fold should carry over on a main-to-nextmerge; the batch-at-a-time list read will need its own change there, sincenextreworkedlist_view.rs.