Repository navigation
fix(query): compare vector literals by value, not by arena handle - #2201
Conversation
On an indexed ledger a vector object is a handle into its predicate's vector arena. Handles start at 0 for each predicate and the arena does not deduplicate, so a handle is not a term identity: distinct vectors on two predicates shared handle 0 and merged under DISTINCT, GROUP BY, COUNT(DISTINCT) and joins, and one vector stored on two subjects kept two handles and stayed apart. Novelty decodes its rows and was unaffected. Every keyed equality surface now decodes vectors as it already decoded big numbers (`normalize_for_key`, `binding_to_group_key_normalized`, `same_term`, the materializer's join key, COUNT(DISTINCT *)), and a decoded vector keys on its components without rendering them. Raw `Binding` equality and hash take `p_id` into account for both arena kinds, so a path that compares without normalizing can only fail to merge equal values. Lanes whose correctness relies on the raw index key being the value decline instead: - the partitioned GROUP BY folds vector-keyed rows through the hashed groups and stamps the decline; - the per-predicate and whole-graph distinct-object counts, the GROUP BY count top-k (and the histogram that shares it) and the object star top-k decline a predicate or graph that holds vectors; - the cross-predicate composite join count and the cyclic join treat vectors, like big numbers, as not globally identifying; the cyclic join bails with its own reason. `OType` records the vocabulary: VECTOR joins NUM_BIG_OVERFLOW as not globally identifying, and `o_key_is_predicate_identifying` names the one o_type whose key is not an identity even within its predicate.
DISTINCT, GROUP BY (hashed and partitioned), the GROUP BY count top-k, COUNT(DISTINCT), joins, the composite join count, the cyclic join, MINUS, EXISTS and VALUES, on SPARQL and JSON-LD, on an indexed ledger, in novelty and on an indexed ledger with novelty on top, with the fast paths on and off. Each lane that now declines a vector is stamped and paired with a string canary on the same ledger that it serves. The runs with the fast paths off hold the write side of a new test lock, `support::FAST_PATH_SWITCH`, and the runs with them on the read side.
Keying vectors by value decoded every row's vector into a fresh `Vec<f64>`. The graph view now keeps one shared value per distinct vector: a decode hashes and compares the arena's `f32` components in place and returns the shared `Arc<[f64]>`, so a handle whose value the view has seen allocates nothing. The memo clears past 4M components, as the view's subject memo clears past its bound. The keys stay decoded literals, so a key built through a view with the memo equals one built without it, and novelty and VALUES vectors still match indexed ones.
…by value A NumBig arena written before decimal normalization can hold one value under several handles (`1.5` and `1.50`). The partitioned GROUP BY keys each run by its encoded key, so it split such a value into a group per handle. On a graph holding such an arena it now folds every big number, encoded or decoded, through the hashed groups, which key by value, and stamps the decline with the reason `legacy-numbig-key`. `BinaryIndexStore::graph_numbig_has_duplicate_handles` answers from the resident arenas; `set_numbig_arena_for_test` installs a hand-built legacy arena for the unit test.
Three costs remained in keying vectors by value, measured on DISTINCT and GROUP BY over 2,000 64-dimension vectors: - Every lookup probed the shared shard cache (a SipHash and a moka read). The view's vector memo now keeps the shards it has read. - Hashing a vector's components through `FxHasher` left the hash's low bits independent of the data, since a widened `f32` has 29 zero low bits, so a hash table saw one tag for every vector and compared a probe with most of its neighbors. `vector_bits_hash` folds each product's high bits back down; `FlakeValue`'s `Hash`, the group key, the materializer's join key and the memo use it. - Equal decoded vectors now share one allocation, so their equality checks `Arc::ptr_eq` before comparing components.
bplatz
left a comment
There was a problem hiding this comment.
The fix itself looks right to me, comparing vectors by value on every equality surface rather than by handle, and the test matrix is thorough. Before this merges, though, I want to make sure it has no perf impact on real embedding workloads: 768+ dimension vectors at larger scales.
The perf table measures 64 distinct 64-dimension vectors over 2,000 rows, which is the shape where the memo shines. Typical embeddings are the opposite: 768, 1024, 1536 or 3072 dimensions, and one distinct vector per subject. There every decode pays a hash over all the components, a memo miss and an insert. The memo's 4M-component bound holds only ~5.4K 768-dim vectors (~2.7K at 1536), so on a large all-distinct scan it clears constantly and the hashing is all overhead. Every vector decode goes through it now, not only the equality surfaces.
What I'd like to see, against main, before merging:
- Dimensions 768 and 1536 at least (3072 if cheap), scale around 100K and 1M vectors, mostly or entirely distinct (one embedding per subject).
- Shapes:
- a plain projection or export of the vectors;
- a counted
DISTINCTandGROUP BYon them; - a flat similarity ranking (
dotProduct/cosineSimilarityORDER BY … LIMIT). It reads throughvector_slice, so it should be flat, but it's the main workload and worth confirming; - a join on
?v; - a decimal-valued join, since
join_keynow decodes NUM_BIG too.
- Instructions per query and peak RSS for each. RSS matters because of the shard pinning noted inline.
If the all-distinct case regresses, a cheap way out may be to stop memoizing once the hit rate stays low, or to bypass the memo on decode paths that don't compare.
Two more, inline: the memo's shard map is never cleared, and the legacy-decimal guard covers only the partitioned lane. Also a small one: JoinKey::Lit::p_id_for_arena is now always None, so the field can go.
Checked and sound: persisted HLL sketches hash the encoded (o_kind, o_key), not FlakeValue, so the hash change touches nothing on disk; vector_bits_hash is the one hash across FlakeValue, the group key, the join key and the memo; views aren't shared across threads, so the memo's lock is uncontended.
| components: usize, | ||
| /// Arena shards read so far, by `(p_id, shard index)`, so a lookup skips | ||
| /// the shared shard cache's probe. | ||
| shards: rustc_hash::FxHashMap<(u32, usize), Arc<crate::arena::vector::VectorShard>>, |
There was a problem hiding this comment.
by_hash clears at MAX_COMPONENTS, but shards never does, so the view keeps a strong Arc to every arena shard it has touched until the operator drops. A long streaming read of a large vector predicate (an export or an unbounded projection: 1M × 768 f32 is ~3 GB of arena) ends up pinning the whole arena outside the shared shard cache's eviction, where on main that cache bounded it. Clearing shards alongside by_hash, or keeping only the most recent shard or two (access is mostly sequential), would keep the memo's footprint at what the cache already allows.
Related, minor: arena.shard(shard_idx)? can read from disk while this mutex is held. Uncontended today since a view isn't shared across threads, but the load could move outside the lock.
There was a problem hiding this comment.
You're right: on a scan that touched the whole arena, the view held every shard until the operator dropped, outside the cache's eviction. The memo is gone now, since nothing decodes a vector to key it any more. What's left in the view is a cursor that keeps the one shard its keys read last, and it loads a shard without holding its lock.
What holds shards now, and for how long:
- A key before the predicate's identity table is built holds a slice of its shard, which is the point of keying without copying. It lives exactly as long as the operator state holding the key (
DISTINCT's seen table, aGROUP BY's groups), and keys share one copy of each shard: the view remembers, weakly, which shards it has handed to keys, so once the cache evicts a shard a key still holds, the next key reuses that copy rather than load another. - A key after the table is built holds no shard at all. Only a comparison that needs components (another arena's key or a decoded vector, on a hash match) reads them, and it pins the shard in a set the graph's tabled keys share, held weakly by the store, so it drops with the last of those keys. That set is per store and graph rather than per view because the hash join keys each batch through a fresh view; per view, every probe batch reloaded its shards (
tabled_vector_key_comparisons_share_the_shards_they_readfails if the set goes back to per view). - Nothing with the store's lifetime holds a shard; the identity table is just hashes and handles.
The bounded-cache run you suggested is what shaped both. Capped at 256 MB under a 614 MB arena (100K × 1536), instructions relative to main (149d02d81), peak RSS MB in parentheses:
| Cell | this PR, table built | this PR, not built |
|---|---|---|
SELECT DISTINCT ?v, counted |
1.02x (106) | 4.57x (716) |
GROUP BY ?v, counted |
1.05x (107) | 3.36x (725) |
join on ?v |
4.02x (760) | 5.82x (747) |
main peaks at 82, 108 and 92 MB there. With the table, DISTINCT and GROUP BY don't notice the cap, since they read nothing. The join does: it still reads the part of both arenas the cache can't hold, about 390 MB a run here, but once per query now rather than once per probe batch. Getting it lower would mean either reading single vectors rather than whole shards on a compare, or a table that names values across a graph's arenas, and I'd rather talk that through than fold it in here. Without the table, the value-keyed cells re-read shards the cache evicted before a key held them, since a subject-order scan reads handles out of order; that's the 3.4x–5.8x. The projection under that cap is 1.01x of main and peaks where it does (6,394 MB), where the first version pinned the whole arena on top of that.
| // Decided once, so a decimal's encoded and decoded forms | ||
| // take the same path. | ||
| let legacy_numbig = crate::object_binding::EqualityNorm::parts(&self.norm) | ||
| .1 | ||
| .is_some_and(|gv| gv.store().graph_numbig_has_duplicate_handles(gv.g_id())); |
There was a problem hiding this comment.
This guard covers the partitioned lane, but the same legacy arena (1.5 and 1.50 under two handles) also reaches the other lanes that key on (o_type, o_key) within one predicate: the per-predicate distinct-object count in fast_count, group_by_object_count_topk (and the Cypher histogram through group_count_v6) and group_by_object_star_topk. Those decline only for vectors, so on a legacy arena they still count the two forms as two values, the wrong answer this fixes here. Either guard them with graph_numbig_has_duplicate_handles too, or file a follow-up.
There was a problem hiding this comment.
Good catch. I reproduced it on every lane you named, plus one. I imported three decimals and overwrote the ledger's decimal arena with the bytes a pre-normalization build wrote (1.50, 1.5, 19.99 under three handles). With the fast paths on, the per-predicate COUNT(DISTINCT ?o) gave 3, and group_by_object_count_topk, group_by_object_star_topk and the whole-graph histogram each gave three groups of one. So did the whole-graph COUNT(DISTINCT ?prop) (Cypher's count(DISTINCT n.d)), which goes through the same per-predicate count. The pipeline gives 2 and [1, 2].
Fixed in 376d9454c. Rather than add the guard at each site, there's one check, BinaryIndexStore::objects_keyed_by_value(g_id, p_id): does this predicate's object key name its value one to one? count_distinct_objects_for_predicate, group_count_v6 and compute_group_by_object_star_topk all decline through it. It covers both reasons a key can fail to: a legacy decimal arena with duplicate handles, and a vector arena that holds a value twice. The partitioned lane keeps its own graph-level decision, since it has to pick one path for a decimal's encoded and decoded forms.
I looked for other lanes with the same shape. The other POST-order fast paths (fast_exists_join_count_distinct_object, fast_string_fold, fast_min_max_string) are IRI- or string-only, and the whole-graph count_distinct_objects reads the arenas through count_distinct_numbig_objects, which already normalizes, so I don't think there's another.
The test is it_numbig_legacy_identity. It checks each lane's answer with the fast paths on and off, that none of them serves the legacy arena, and, as a canary, that they all still serve the arena as imported. With the check reverted, all five fast lanes return the split answer.
A decimal arena from before normalization keeps a handle per scale variant, so 1.5 and 1.50 are two object keys of one predicate. The per-predicate COUNT(DISTINCT) lead-group count, the GROUP BY ?o count top-k (and the whole-graph histogram that shares it) and the GROUP BY ?o star top-k counted them as two values. They now decline any predicate whose object keys don't name values one to one, through one check, BinaryIndexStore::objects_keyed_by_value, which covers both vector arenas and such a legacy decimal arena. The test overwrites an imported ledger's decimal arena with the bytes a pre-normalization build wrote and checks each lane on SPARQL, with the fast paths on and off, plus a canary that the lanes still serve the arena as imported.
join_key decodes arena literals, so it only ever built the field as None.
… repeat With one embedding per subject (the usual shape) every vector key paid three full passes over its components: the memo's probe, the key's hash on insert, and the hash again each time the key's table grew. Now: - vectors hash with xxh3 over their component bytes (in memory only), 0.62x the instructions of the multiply chain and about 8x faster; - VectorKey carries its hash, and DISTINCT keeps each row's hash with it, so a growing table doesn't hash the rows again; - the per-view memo stops probing once a window of 1024 misses saw fewer than one hit in four, and decodes directly from then on; - the memo keeps only the arena shard it read last, so it never holds more of an arena than the shared shard cache allows, and it loads a shard without holding its lock.
…ith no repeats A vector's handle names its value within a predicate whenever the arena holds no value twice, which is the usual shape (one embedding per subject). BinaryIndexStore::vector_handles_name_values proves that once per store and arena, by hashing every vector (shards read without entering the shared cache) and comparing any vectors whose hashes repeat, and objects_keyed_by_value now uses it. So the per-predicate COUNT(DISTINCT), the GROUP BY ?o count top-k (and the whole-graph histogram) and the star top-k serve such a predicate again, and still decline one that holds a vector twice. The routing test pairs a vector predicate with a repeat (declined) with one without (served) on the same ledger, for all three lanes.
…ed copy Every vector key decoded its arena components into a fresh f64 copy, so DISTINCT, GROUP BY and joins over one-embedding-per-subject data held twice the arena's size in keys. Now a stored vector keys as a zero-copy slice of its shard (VectorKey's arena form) and a decoded one (novelty, VALUES, BIND) by its components. Both hash through one canonical function, vector_value_hash / vector_value_hash_f32, and compare by value: - equality is bitwise on the f64 components, as FlakeValue's is: -0.0 and 0.0 differ, a NaN equals itself, and a query literal whose component doesn't narrow to f32 (such as [0.1]) equals no stored vector; - the canonical bytes are the components narrowed to f32 when that is exact, so an arena slice hashes in place, and anything else hashes its f64 bytes under another seed. Each vector arena gets an identity table, built on first use by the whole-predicate fast paths and owned by the store: per handle, the value hash and the canonical handle (the lowest one holding an equal vector), 12 bytes per handle. It replaces the no-repeat proof, which is now its duplicate_free bit. A key reads its hash and canonical handle from the table when it has been built (it never builds it, so a small query never pays for the whole arena), and two keys of one arena then compare by canonical handle. DISTINCT keys rows that hold a vector by value in a table of their own, so rows without one keep the binding path. same_term compares two vectors through their keys. The per-view decoded-vector memo is gone: nothing decodes a vector to key it any more, and decoding for output is the plain lookup again. A view keeps only the shard its keys read last. Tests: keys agree across the arena, novelty and VALUES forms, and differ for another vector at the same offset of another arena; bitwise edge cases; the identity table's hashes match a decoded vector's; a join on a vector pairs values, not handles; and with novelty adding a copy of a stored vector, the per-predicate lanes decline and count it once.
…ithout cloning the table
Keys hold a slice of their shard. Under a cache smaller than the arena, a scan that reads handles out of order made later keys load fresh copies of shards the cache had evicted but earlier keys still held: DISTINCT over a 600 MB arena peaked at 5.1 GB with a 256 MB cache. The view now remembers, weakly, every shard it handed to a key, and reuses a copy some key still holds before loading another. That peak is 687 MB.
…e evicted shards A key's hash is the same whether or not its arena's identity table is built, canonical handles agree with comparing the vectors for every pair of an arena with repeats (including -0.0 beside 0.0), and keys with and without canonical handles compare alike. Two keys over one shard share one loaded copy even after the cache evicted it between them.
… no shard With an arena's identity table built, a stored vector's key is the table's hash and canonical handle, and keying it reads no shard. Two keys of one arena compare by canonical handle; a comparison with another arena's key or a decoded vector reads the components on demand, on a hash match. A DISTINCT or GROUP BY over a tabled predicate then never reads its arena. Without the table, a key is still a zero-copy slice of its shard, hashed in place. `same_term` surfaces a failed read; a hash-table comparison reads it as unequal, which can only fail to merge equal vectors, like a key whose arena read fails at construction. The key holds its store so it can read components; clippy.toml tells `mutable_key_type` that the store's caches don't reach the key's hash or equality.
With the identity table built, a key is the table's hash and canonical handle, so the arena's two map lookups and its shard index are only needed for a key that reads its shard.
… they read A table-resolved key holds no shard, so a comparison that needs its components (another arena's key or a decoded vector, on a hash match) read them through the shared cache. Under a cache smaller than the arena a join whose matches jump between shards then reloaded a shard per match: 47x of main's instructions at 100K x 1536 with a 256 MB cache. Those reads now pin their shard in a set the view's tabled keys share and the view holds weakly, so each shard loads once and drops with the last key. Only shards a comparison needed are pinned; a DISTINCT or GROUP BY over one tabled predicate pins none.
An operator can key each batch through a fresh graph view (the hash join does), so per-view pins dropped with each probe batch's keys and the next batch reloaded its shards. The pins are now per store and graph, held weakly by the store and its views, so they live as long as any of the graph's tabled keys.
… query A hash table's equality can't return an error. When a comparison of two tabled vector keys had to read components and the read failed, the pair counted as unequal: DISTINCT, GROUP BY and COUNT(DISTINCT) split one value in two and a join missed its match, with no error. Building a key had the same gap: a vector or big number whose arena read failed was keyed by its handle, which names the value only within one predicate's arena. Both now record the failure in a slot the query owns (`KeyReadErrors`). The query's graph views carry it, and so does every key read from them. The operators that key rows (DISTINCT, GROUP BY, the hash join's build and probe) check it after each batch, and the runner and the WHERE cursor check it after every batch as a backstop, so no row built on a failed read is returned. The first error is kept as is, so a residency miss stays a typed `NeedFetch`.
…uery Deletes the ledger's vector shard files and drops the cached shards, then runs DISTINCT, GROUP BY, COUNT(DISTINCT), a join and MINUS over two predicates that share a vector, in both lanes. Each must fail, with and without the identity tables built (a comparison reads, or the key build does). With the tables built, DISTINCT over one predicate reads nothing and still answers.
Equality against another arena's key or a decoded vector reads components through the store, so the comment no longer claims equality reads only the key's own fields. What holds is that a key's hash and equality never depend on the store's mutable caches.
|
Thanks for pushing on this. You were right to: the 64-distinct fixture was flattering, and at real embedding shapes the first version was much worse than I'd claimed. I ran the cells you listed against At those shapes the first version was 5x to 10x of So I changed how vectors key rather than tune around it:
When the table gets built matters for reading the numbers. Only the whole-predicate fast paths build it ( Instructions relative to
With the table built, A couple of things I'd want you to see, though:
The decimal controls stayed flat or improved: a decimal If any of these shapes aren't what you had in mind, I'm happy to rerun with yours.
Yep: Memoizing on a low hit rate / decode paths that don't compare I measured this first. On one-embedding-per-subject data the memo cost about 10%, and on the 64-distinct fixture it saved about 30%. In between I had a hit-rate bypass that got both. But once keys stopped decoding vectors at all (item 1), nothing needed a decoded copy to compare, so the memo went entirely rather than living on behind a bypass. Decoding for output (projection, export) is the plain lookup it is on |
main now decodes through a graph-less `TermView` and carries each arena literal's graph on the binding (`arena_g_id`), and its key paths return `Undecodable` rather than key a value they could not read. The vector keys follow both: - `TermView::arena_vector` takes the arena's graph from the literal, never from the view, and refuses a literal with no graph. The view's vector cursor (last shard, identity table, shard pins) is keyed by (graph, predicate), so a union of graphs keyed through one view never answers one graph's key from another's shard or table. - Keying a vector returns its read failure through `Undecodable`, which now keeps the `io::Error`, so a read out of fuel or needing a fetch stays that typed error. `KeyReadErrors` stays for the comparisons inside a hash table, which can't return one; `ExecutionContext::term_view` now attaches the query's slot, as `one_graph_view` does, or those failures went unchecked. - `binding::is_arena_kind` defers to `ObjKind::is_arena_handle`, and the partitioned GROUP BY stamps its vector-key decline at main's `partitioned_group_by` site. - `without_graphs` gives the derived store its own identity tables, as it does its other per-store memos. A union-scope test pins vectors over `FROM g1 FROM g2`: one handle holding a different vector in each graph, and one vector held in both.
…predicate A big number's handle names its value within one predicate's arena, which holds each value once. The cyclic join had declined every arena literal, so a one-graph pattern whose big-number object every edge reads from one predicate left the lane although its keys were right. It keys such an object by handle again. It still declines an object two predicates bind (their handles name no value across arenas), a graph whose legacy decimal arena holds `1.5` and `1.50` under two handles, and every vector, whose handle names no value even within its predicate. Tests pin the three shapes on one graph (one predicate keeps the lane; an unequal and an equal pair across two predicates decline and answer by value) and the legacy arena.
|
Re-requesting a look, since a fair bit moved under this after your review and the perf reply. Most of it came from re-merging
One perf thing you'll want to know before reading the new table: since #2214 (mine, The body has the full table and the rest. |
The identity table is built by one pass over the whole arena, the first time a whole-predicate fast path asks whether a vector predicate's handles name its values. Concurrent first callers each ran that pass and one result was kept, so a burst of value-keyed counts after an index publish read the arena once per query, through reads that bypass the shared cache. Each arena's table now sits in a once-only cell: the first caller builds it, and concurrent callers wait for that build and share its result. A build that fails leaves the cell empty, so the next caller tries again.
A comparison of table-resolved vector keys that needs components (another arena's key, or a decoded vector, on a hash match) pins the shard it reads so later comparisons reuse it. Those pins were kept per store and graph and handed to every view while any key held them, so overlapping queries shared one set. Under a steady load of such queries the set never dropped, and it kept every shard any of them had compared outside the shared cache's eviction, whatever the cache's size. The pins are now the query's. The execution context holds one `QueryShardPins`, shares it with the contexts derived from it, and attaches it to every view it builds, beside the query's key read-error slot, so the keys of every batch still share one copy of each shard. A query's pinned shards drop with the query and its keys, however many other queries are running. A view no query attaches pins to keeps its own.
… its table When two handles of an arena share a value hash, the identity table's build compares their vectors to find the canonical handle. It copied both vectors' component bits into a new `Vec` for every comparison, so an arena holding one vector many times (a default or zero embedding, say) allocated two vectors per handle in that run. The comparison is now `vector_eq_f32`, bitwise over the two slices with no copy, which `ArenaVector::same_value` also uses, so the table and the keys it resolves compare stored vectors one way.
Setting `ignore-interior-mutability` replaces clippy's default list rather than extending it, so the root config added for vector keys dropped the default `bytes::Bytes`. A map keyed by `Bytes` in a crate that reads this config would then fail `mutable_key_type`. It is listed again.
|
Pushed a few changes to get this ready for the release:
After the third change, the body's description of |
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.
Two of main's vector and decimal identity tests built their state from main's storage, which next stores differently. - vector_keys_read_no_shard_once_the_identity_table_is_built took its shards away by deleting their files. next's arenas read shards from a content store, so the test writes them to a store of its own and releases them there, leaving the shared test store's shards to the other tests. - it_numbig_legacy_identity overwrote the decimal arena an import writes. next stores a decimal of up to 17 significant digits inline, with no arena, so the fixtures' decimals and the legacy arena's scale variants carry 20. A lookup of one then goes to the arena, as every decimal's does in a v4 index, which is where a legacy arena is met. Each test fails with its guard removed: the legacy check in objects_keyed_by_value, and the cyclic join's.
On an indexed ledger, a vector literal (
f:embeddingVector) leaves the scan as its encoded key, which is a handle into the predicate's vector arena. That handle isn't a term identity in either direction: handles start at 0 for each predicate (and each graph), and the vector arena doesn't deduplicate, so one vector stored on two subjects of a predicate gets two handles. Our equality surfaces were keying vectors by that handle —Binding'sEq/Hashonly takep_idinto account forNUM_BIG, andnormalize_for_key/binding_to_group_key_normalizeddecodeNUM_BIGbut notVECTOR_ID— so distinct vectors could merge and equal ones stay apart. Novelty decodes its rows eagerly and was answering correctly, and since the fast paths on and off share the wrong answer,FLUREE_DISABLE_QUERY_FAST_PATHSdoesn't see this.What
mainreturnsFixture:
ex:a ex:v1 [1,0]andex:b ex:v2 [0,1](each predicate's handle 0), and[0.5,0.5]on bothex:candex:dunderex:w, plus[0.25,0.75]onex:e.ex:fholds one vector onex:j1andex:j2, andex:gholds different vectors on them. Indexed ledger, same answer with the fast paths on and off unless noted.main(42bb9646c)SELECT DISTINCT ?voverex:v1∪ex:v2SELECT DISTINCT ?v { ?s ex:w ?v }GROUP BY ?voverex:v1∪ex:v2GROUP BY ?voverex:w(the partitioned lane), and itsORDER BY DESC(?n) LIMITtop-k[0.5,0.5]split into two groups of 1COUNT(DISTINCT ?v)overex:v1∪ex:v2/ overex:wCOUNT(DISTINCT ?o) { ?s ?p ?o }?s ex:j1 ?v MINUS { ?t ex:j2 ?v }ex:gremoved by handle)ex:g?s ex:j1 ?v FILTER EXISTS { ?t ex:j2 ?v }ex:f,ex:gex:fCOUNT(*) { ?s ex:j1 ?o . ?s ex:j2 ?o }(fast paths on)?a ex:j1 ?v . ?b ex:j2 ?v . ?a ex:link ?b?a ex:v ?v . ?b ex:u ?v, 1,000 subjects, every tenth copieds1–s10, …)selectDistinct,groupBy,count-distincttwinsPlain joins on
?vin this fixture and aVALUESvector happen to come out right onmain, but that's the fixture taking a lane that larger inputs don't, not the join being right. With 1,000 subjects, each holding its own vector underex:vand every tenth holding a copy underex:u,?a ex:v ?v . ?b ex:u ?vonmainreturns 100 rows, but they're paired by handle:ex:s10's copy (handle 1 ofex:u) joinsex:s1(handle 1 ofex:v),ex:s100joinsex:s10, and so on. The same happens at 100K (ex:s10000withex:s0).a_join_on_a_vector_pairs_values_not_handlespins it, and it fails on42bb9646cwith exactly that pairing.Today's
main(596a4fd87) is partly different. Since #2214 its hashed key paths decode a vector and key it by its text, so the hashedDISTINCT,GROUP BY, join,MINUSandEXISTSrows above, and the 1,000-subject join, answer right there, at the cost the Perf section shows. The partitionedGROUP BYand its top-k (and the JSON-LDgroupBytwin), and the cyclic join, still answer as in themaincolumn, in both lanes. So do the per-predicate and whole-graphCOUNT(DISTINCT)and the count plan, with the fast paths on, as they are by default.The fix
The class here is "an arena handle is not a term identity", so I tried to treat it that way rather than patching the one site:
binding_to_group_key_normalizedbuilds the key, soGROUP BY(hashed, and the partitioned lane's vector side-route),COUNT(DISTINCT), the hash joins and the otherCompositeGroupKeyusers all get it;DISTINCTkeys rows holding a vector in a table of its own, so rows without one keep their binding path, andsame_termcompares two vectors through the same keys. A decoded vector (novelty,VALUES,BIND) keys by its components. Everything hashes through one canonical function (vector_value_hash, andvector_value_hash_f32for an arena's components):xxh3over the components narrowed tof32when that's exact, which every stored vector is. Equality is bitwise on thef64components, asFlakeValue's is:-0.0and0.0differ, a NaN equals itself (writes and query literals reject non-finite components anyway), and a query literal whose component doesn't narrow tof32, such as[0.1], equals no stored vector, as onmain.NUM_BIGstill keys by its decoded value.ArenaVectorForm). Before its arena's identity table is built (below), the key is a zero-copy slice of its shard, hashed in place; the view remembers, weakly, which shards it has handed to keys, so keys share one copy of each shard even after the shared cache evicts it. Once the table is built, the key is the table's hash and canonical handle and holds no shard at all. Two keys of one arena compare by canonical handle and read nothing. Only a comparison against another arena's key or a decoded vector, on a hash match, reads components, since a canonical handle only names a value within its own arena. Those reads pin their shard in a set the graph's tabled keys share (ShardPins), held weakly by the store, so each shard loads once per query and drops with the last key. It's per store and graph rather than per view because the hash join keys each batch through a fresh view; per view, every probe batch reloaded its shards. A key reads the arena of the graph its literal carries (arena_g_id), never one the view assumes, so over a union of graphs (FROM g1 FROM g2) one handle number in two graphs is two vectors and one vector in both graphs is one value; the view's last shard, identity table and pins are kept per (graph, predicate).Undecodable, which keeps the read'sio::Error, so a read that ran out of fuel or needs a fetch stays a typedFuelLimitExceededorNeedFetch). A hash table'sPartialEqcan't return an error, though, and counting the pair unequal would answer wrong with no error. So a comparison's failure goes into a slot the query owns (KeyReadErrors), which the query's views (one_graph_viewandterm_view) and every key read from them carry. The operators that key rows (DISTINCT,GROUP BY, the hash join's build and probe) check it after each batch, and the runner and the WHERE cursor check it after every batch as a backstop, so no row built on a failed read comes back. The first error is kept as is.BinaryIndexStore::objects_keyed_by_value, which the whole-predicate fast paths call: the per-predicateCOUNT(DISTINCT)(count_distinct_objects_for_predicate, which the whole-graphCOUNT(DISTINCT ?prop)also goes through),group_count_v6(the group-count top-k and the Cypher histogram) and the star top-k. Each builds it the first time it runs on that predicate, once per store, so again after a new index is published. It costs one pass over the arena: 1.7G instructions at 100K × 768, 3.4G at 100K × 1536 and 8.6G at 250K × 1536, counting the first read of the arena from disk. An ordinaryDISTINCT,GROUP BYor join never builds it, since it would pay for the whole arena even when it reads one vector. Neither building the table nor reading a vector's shard charges fuel: reading a vector isn't charged onmaineither (its fuel counts index leaflets and dictionary touches), and the table is a once-per-store build like the store's other memos. Charging vector reads would be a change of its own.BinaryIndexStore::objects_keyed_by_value: the per-predicate distinct-object count,group_by_object_count_topk(and the Cypher histogram that sharesgroup_count_v6),group_by_object_star_topk, and the whole-graphCOUNT(DISTINCT ?prop). It's false for a vector arena that holds a value twice (the identity table's no-repeats bit) and for a legacy decimal arena with scale-variant duplicates (below). The bit certifies the persisted arena only: these lanes already decline when the predicate has novelty, and a test adds a copy of a stored vector in novelty to check they do. The whole-graph distinct-object count declines any graph that holds vectors, since it keys across predicates. The partitionedGROUP BYfolds vector keys through the hashed groups and stampspartitioned_group_by/fallback:gate_declined.VECTORjoinsNUM_BIG_OVERFLOWinOType's not-globally-identifying list, which closes the composite join count, and the cyclic join bails on a vector, and on a big number it can't key within one predicate (below), underarena-literal-object.BindingEq/Hash(and the sort tie-break) include the arena's predicate and graph for both arena kinds, viaObjKind::is_arena_handle. So a path that compares without normalizing can only fail to merge equal values, never merge distinct ones.OType::o_key_is_predicate_identifyingnames the one o_type whose key isn't an identity even within its predicate.Nothing decodes a vector to key it any more, so there's no decoded-vector memo, and decoding for output (projection, export) is the plain lookup it is on
main. Because a key now holds its store (Arc<BinaryIndexStore>, whose interior mutability is caches), there's a rootclippy.tomlthat exemptsArenaVectorfrommutable_key_type: a key's hash and equality never depend on the store's mutable caches.The cyclic join keys a big number by its handle only where the handle is its value: every edge binding the object reads one predicate, and the graph's decimal arena isn't a legacy one (below). It used to key them as
(o_type, o_key, p_id), which is right within one predicate but misses equal decimals across two, so an object two predicates bind now declines and the fallback decodes and matches it. A one-predicate pattern such as?a ex:big ?v . ?b ex:big ?vkeeps the lane. Vectors always decline.I also checked the NumBig claim from the audit. Within one predicate its arena does map a value to one handle (
find_numbig_handle), except in a legacy pre-normalization arena with scale-variant duplicates (has_duplicate_handles), where1.5and1.50kept a handle each. The hashed lanes decode those anyway, but every lane that keys a predicate's objects by(o_type, o_key)split them. That covers the partitionedGROUP BY, the per-predicateCOUNT(DISTINCT),group_by_object_count_topk(and the histogram),group_by_object_star_topkand the whole-graphCOUNT(DISTINCT ?prop), and it's a wrong answer on older indexes that are still around. On such a graph the partitioned lane folds big numbers through the hashed groups (legacy-numbig-key, decided once per lane so a decimal's encoded and decoded forms take one path), and the others decline throughobjects_keyed_by_value.I'd have liked the decimal check and the vector identity table to be one mechanism, and they meet at
objects_keyed_by_value. Below that they stay two structures. The decimal arena already deduplicates exactly at load, by normalized representation (dedupplusdup_handles), so it has no hashes to build and nothing lazy about it. A decimal key also has to decode anyway, to compare across representations (1.5against1.50fromVALUES), which a canonical handle can't answer. So a shared table would only re-store what the arena already knows.Considered and not done: deduplicating vector handles at index build (an on-disk format change), having every keyed query build the identity table (an O(arena) spike on a query that reads one vector), and one identity table across a graph's arenas, which would let a join across two predicates compare without reading but makes the table a cross-predicate structure that every arena's build has to agree on. Happy to talk through any of these.
Tests
it_vector_term_identityingrp_index: every query above, on SPARQL and JSON-LD, on a bulk-imported (indexed) ledger, in novelty, and on an indexed ledger with a third copy of[0.5,0.5]in novelty, each with the fast paths on and off. The oracle is the hand-derived answer. A routing test pairs each declining lane with a string canary on the same ledger that the lane does serve (COUNT(DISTINCT),group_by_object_count_topk,count-plan, the partitioned span), and checks thepartitioned GROUP BYstamp and the cyclicarena-literal-objectbail. Against42bb9646c's sources the indexed, mixed and routing tests failed (37 wrong answers). Against today'smain(596a4fd87) the indexed and mixed runs give 17, on the lanes above, and the routing test fails on the same lanes. The novelty test and the union-of-graphs test below pass on both, as controls. With only the partitioned lane's change disabled, the partitionedGROUP BYcases fail on their own.The runs with the fast paths off hold the write side of a new
support::FAST_PATH_SWITCH, and the runs with them on hold the read side.Unit tests:
OType's point/range agreement now covers both exceptions, the cyclic join's encoder declines arena literals, andpartitioned_group_by_folds_legacy_numbig_scale_variants_by_valueruns the partitioned lane over a hand-built legacy arena (the sameNBA1shape asnumbig.rs's legacy test, installed with a test-onlyset_numbig_arena_for_test, since no current build writes one). It counts1.5/1.50as one group; with the legacy check forced off it counts three groups of one.it_numbig_legacy_identity(ingrp_index) imports three decimals, overwrites the ledger's decimal arena with the bytes a pre-normalization build wrote (1.50,1.5,19.99under three handles), and reopens it. Each object-keyed lane, with the SPARQL forms of the Cypher whole-graph shapes, must answer by value with the fast paths on and off, and must not serve that arena. A canary checks that the same lanes still serve the arena as imported. With the check reverted, all five fast lanes return the split answer. The cyclic join declines that arena too (the_cyclic_join_declines_a_legacy_decimal_arena); keyed by handle, it pairs none of the subjects that hold1.5.cyclic_lane_keys_big_numbers_within_one_predicate(ingrp_query): on one graph, a big-number triangle over one predicate keeps the cyclic lane, and two across predicates decline it and answer by value: an unequal pair whose handles coincide stays apart, and an equal pair is found. Keyed by handle across predicates, the unequal pair joins; with every big number declined, the one-predicate case leaves the lane.it_vector_term_identityalso pins:vectors_compare_by_value_with_the_identity_tables_built);vectors_over_a_union_of_graphs_compare_by_value): one handle number holding a different vector in each graph, and one vector held in both, throughDISTINCT,GROUP BY,COUNT(DISTINCT)and joins, on SPARQL and JSON-LD, in novelty, indexed, and indexed with all four identity tables built, with the fast paths on and off. With the view's cursor blind to the graph, the two vectors under one handle merge; with vectors keyed by handle, the one vector in both graphs splits;DISTINCT,GROUP BY,COUNT(DISTINCT), a join andMINUSover two predicates that share a vector, in both lanes, and each must error. With the tables built, the failing read is the comparison's (a_failed_vector_read_inside_a_hash_table_fails_the_query); without them, it's the key build's (a_failed_vector_read_while_keying_fails_the_query). With the tables built, aDISTINCTover one predicate reads nothing and still answers. With the check stubbed out, the hash table's equality not recording, the key build dropping its read error, orterm_viewbuilt without the query's slot, the queries answern=4instead ofn=3.VALUESforms, and with and without the identity table (equal and equal-hashed), and differ for another vector at the same offset of another arena; keys of two tabled arenas compare components; a tabled key holds no shard; keys over an evicted shard share one copy, and tabled keys made through separate views share the shards their comparisons read; equality stays bitwise (-0.0against0.0,[0.1]asf64against the storedf320.1, NaN against itself in a hash set); and the identity table's hashes equal a decoded vector's, gives a repeat its canonical handle, and is 12 bytes per handle. One predicate's arenas in two graphs, keyed through one view and read alternately, each answer their own handles, with the tables built and without; a literal with no graph is refused.Perf
The first version of this section measured 64 distinct 64-dimension vectors over 2,000 rows, where the old memo did best. Real embeddings are the other shape: 768 to 3072 dimensions and one distinct vector per subject. There the first version was 5x to 10x of
mainonDISTINCT,GROUP BYand a join on?v, thousands of times slower onCOUNT(DISTINCT ?v), and 10–20xmain's peak memory. The keying above is what replaced it.Today's
mainkeys a decoded vector by its text, so it's a low bar for the vector cells. Since #2214 (8ab3a22ad),main's key paths decode an arena literal and key it by its value. For a vector, that value falls throughbinding_to_group_key_ownedto its catch-all arm,format!("{val:?}"): theDebugtext of every component. In a profile ofmain'sGROUP BY ?v, 81% of the samples are in<Arc<[f64]> as Debug>::fmt. The answers are right, but aGROUP BYor a join on?vcosts about 0.8M instructions a row and holds a ~15 KB string per key. Measured on the same box:mainjust before #2214 (b38268f33) took 633M instructions for aGROUP BY ?vat 100K × 768, and the #2214 merge (88c3cf134) took 82.9G. This PR keys vectors without decoding them, so it replaces that path. So the table gives each vector cell against bothmain(596a4fd87, this head's merge base) andb38268f33, which keyed a vector by its handle: cheap, and wrong (it's the answer this PR fixes).b38268f33measures within 1% of149d02d81, themainthis section used before.Method: a quiet
c7i.8xlargeEC2 box (32 vCPU, 64 GB, Amazon Linux 2023), with nothing else running while it measured, and every binary built and measured there. A file-backed ledger bulk-imported per size: each subject gets one distinct vector onex:vand a distinct decimal onex:d, and every tenth also gets copies of both onex:u/ex:d2, so the cross-predicate joins return n/10 rows. Each cell runs in its own process: a load, one warm-up, then 3 timed runs (2 at 250K and for the projection), with the binaries alternating in each of 3 rounds (2 at 250K and for the projection). I report the median instructions retired (user and kernel, aperf_event_opencounter on every thread of the process, summed) and the process's peak RSS (VmHWM, which includes the load and the pages of the index files the store maps; the allocator's peak live heap is in the TSVs too and tells the same story). As a check on the counter,perf stat -e instructionsover whole processes, taking the difference between 1 and 11 timed runs, agrees with it within 0.1% onDISTINCTfor both builds and onmain's join. On this PR's join it shows about 35M more per run (work that finishes after the timed call returns). Dev-fast profile, default cache. "Table built" runs the same cell after aCOUNT(DISTINCT ?v)onex:vand onex:uin the same process has built both identity tables.Vector cells: instructions relative to each base
SELECT DISTINCT ?v, countedb38268f33mainb38268f33mainmain/b38268f33/ not built / builtGROUP BY ?v, countedb38268f33mainb38268f33mainmain/b38268f33/ not built / built?vacross two predicates †b38268f33mainb38268f33mainmain/b38268f33/ not built / built†
b38268f33's join returns the right number of rows, but the wrong rows.The other cells, against
main(596a4fd87), with peak RSS in MB where it moves (main→ this PR)COUNT(DISTINCT ?v)dotProducttop-10cosineSimilaritytop-10?xSELECT DISTINCT ?x, countedGROUP BY ?x, countedSELECT DISTINCT ?s, countedSELECT ?s ?vAbsolute counts for scale, at 100K × 1536 (
main/b38268f33/ this PR without the table / with it):DISTINCT1,905M / 406M / 866M / 407M;GROUP BY163,852M / 625M / 1,113M / 656M; the join 176,758M / 439M / 1,026M / 529M. Every run's numbers are in the TSVs in the work folder.DISTINCTandGROUP BYdon't read the arena at all, so they sit at 1.00x–1.06x ofb38268f33and peak close to it. What's left is building the key and its row in the table.b38268f33with both tables built, and peaks at about the two arenas, because a match across two predicates has to compare components: a canonical handle only names a value within its own arena. So every probe that hits reads both vectors, and with every tenth subject copied, that touches every shard ofex:v. The shards are shared across the query's keys and drop when it finishes.f32is 307 MB, plus 31 MB of copies onex:u), and the gap is onexxh3pass over each key's bytes plus building the key.DISTINCTis 3.07G instructions here againstb38268f33's 447M at 100K × 1536 when the table isn't built (5.05G onmain).b38268f33's lane never reads them.DISTINCTkeeps each row's hash, so a growing table doesn't hash its rows again, which matters for a decodedBigDecimal. A subjectDISTINCTand a decimalGROUP BYare flat, and so is the projection.b38268f33match the ones this section had against149d02d81within 0.02x on every vector cell, so the merges didn't move this PR's cost.A shared cache smaller than the arena. Capped at 256 MB, at 100K × 1536 (a 614 MB arena, plus 61 MB on
ex:u):mainb38268f33main/b38268f33/ built / not builtmainSELECT DISTINCT ?v, countedb38268f33GROUP BY ?v, countedb38268f33?v†b38268f33With the table built,
DISTINCTandGROUP BYdon't notice the cap, since they read nothing. The join does: each query reads the part of both arenas the cache can't hold, once per query rather than once per probe batch. That's the same compare-components cost as above, paid in disk reads at shard granularity. Without the table, the value-keyed cells re-read shards the cache evicted before a key held them, since a subject-order scan reads handles out of order; that's the 3.3x–5.3x. The projection sits wheremain's does, in instructions and memory.The small fixture from the first version (2,000 rows, 64 distinct 64-dim vectors),
main(596a4fd87) → this PR, median of 3 runs:mainThe vector rows return 64 values on both sides, except
main's partitionedGROUP BYwithout the count, which still returns 2,000 (one per handle).Gates
On an EC2
c7i.8xlarge, atfcca2191f(main596a4fd87merged in), all of these are clean:cargo fmt --all --check, and testsuite-sparql's fmt;cargo clippy --all --all-features --all-targets -D warnings;cargo check --workspace --all-targets, and the server's no-default-features check;cargo nextest run --workspace --all-features: 16,471 of 16,471 passed (46 skipped), testcontainers included. Doctests: 48 passed. The wasm32 runtime smoke passes under Node 22, the version CI uses. Not run here: the W3C SPARQL run and the browser job, which CI runs.