Skip to content

fix(query): compare vector literals by value, not by arena handle - #2201

Merged
bplatz merged 34 commits into
mainfrom
fix/vector-term-identity
Nov 19, 2026
Merged

bplatz merged 34 commits into
mainfrom
fix/vector-term-identity

Conversation

@aaj3f

@aaj3f aaj3f commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

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's Eq/Hash only take p_id into account for NUM_BIG, and normalize_for_key / binding_to_group_key_normalized decode NUM_BIG but not VECTOR_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_PATHS doesn't see this.

What main returns

Fixture: ex:a ex:v1 [1,0] and ex:b ex:v2 [0,1] (each predicate's handle 0), and [0.5,0.5] on both ex:c and ex:d under ex:w, plus [0.25,0.75] on ex:e. ex:f holds one vector on ex:j1 and ex:j2, and ex:g holds different vectors on them. Indexed ledger, same answer with the fast paths on and off unless noted.

Query main (42bb9646c) This PR
SELECT DISTINCT ?v over ex:v1 ∪ ex:v2 1 row 2 rows
SELECT DISTINCT ?v { ?s ex:w ?v } 3 rows 2 rows
GROUP BY ?v over ex:v1 ∪ ex:v2 one group of 2 two groups of 1
GROUP BY ?v over ex:w (the partitioned lane), and its ORDER BY DESC(?n) LIMIT top-k [0.5,0.5] split into two groups of 1 one group of 2
COUNT(DISTINCT ?v) over ex:v1 ∪ ex:v2 / over ex:w 1 / 3 2 / 2
COUNT(DISTINCT ?o) { ?s ?p ?o } 10 14
?s ex:j1 ?v MINUS { ?t ex:j2 ?v } no rows (ex:g removed by handle) ex:g
?s ex:j1 ?v FILTER EXISTS { ?t ex:j2 ?v } ex:f, ex:g ex:f
COUNT(*) { ?s ex:j1 ?o . ?s ex:j2 ?o } (fast paths on) 2 1
cyclic ?a ex:j1 ?v . ?b ex:j2 ?v . ?a ex:link ?b 2 rows 1 row
?a ex:v ?v . ?b ex:u ?v, 1,000 subjects, every tenth copied 100 rows, paired by handle (s1–s10, …) 100 rows, each subject with itself
JSON-LD selectDistinct, groupBy, count-distinct twins same as SPARQL same as SPARQL

Plain joins on ?v in this fixture and a VALUES vector happen to come out right on main, 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 under ex:v and every tenth holding a copy under ex:u, ?a ex:v ?v . ?b ex:u ?v on main returns 100 rows, but they're paired by handle: ex:s10's copy (handle 1 of ex:u) joins ex:s1 (handle 1 of ex:v), ex:s100 joins ex:s10, and so on. The same happens at 100K (ex:s10000 with ex:s0). a_join_on_a_vector_pairs_values_not_handles pins it, and it fails on 42bb9646c with 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 hashed DISTINCT, GROUP BY, join, MINUS and EXISTS rows above, and the 1,000-subject join, answer right there, at the cost the Perf section shows. The partitioned GROUP BY and its top-k (and the JSON-LD groupBy twin), and the cyclic join, still answer as in the main column, in both lanes. So do the per-predicate and whole-graph COUNT(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:

  • Every keyed equality surface keys a vector by value. binding_to_group_key_normalized builds the key, so GROUP BY (hashed, and the partitioned lane's vector side-route), COUNT(DISTINCT), the hash joins and the other CompositeGroupKey users all get it; DISTINCT keys rows holding a vector in a table of its own, so rows without one keep their binding path, and same_term compares 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, and vector_value_hash_f32 for an arena's components): xxh3 over the components narrowed to f32 when that's exact, which every stored vector is. Equality is bitwise on the f64 components, as FlakeValue's is: -0.0 and 0.0 differ, a NaN equals itself (writes and query literals reject non-finite components anyway), and a query literal whose component doesn't narrow to f32, such as [0.1], equals no stored vector, as on main. NUM_BIG still keys by its decoded value.
  • A stored vector keys without decoding, in one of two forms (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).
  • A read that fails while keying fails the query. Building a key returns the failure (Undecodable, which keeps the read's io::Error, so a read that ran out of fuel or needs a fetch stays a typed FuelLimitExceeded or NeedFetch). A hash table's PartialEq can'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_view and term_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.
  • Each vector arena has an identity table, owned by the store (its lifetime is the store's, and the arenas are immutable per store). Per handle it holds the value hash and the canonical handle, the lowest handle holding an equal vector: 12 bytes per handle, so 1.2 MB at 100K and about 12 MB at 1M. It holds no shards. When it's built: only through BinaryIndexStore::objects_keyed_by_value, which the whole-predicate fast paths call: the per-predicate COUNT(DISTINCT) (count_distinct_objects_for_predicate, which the whole-graph COUNT(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 ordinary DISTINCT, GROUP BY or 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 on main either (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.
  • Lanes that rely on the raw index key being the value check BinaryIndexStore::objects_keyed_by_value: the per-predicate distinct-object count, group_by_object_count_topk (and the Cypher histogram that shares group_count_v6), group_by_object_star_topk, and the whole-graph COUNT(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 partitioned GROUP BY folds vector keys through the hashed groups and stamps partitioned_group_by / fallback:gate_declined. VECTOR joins NUM_BIG_OVERFLOW in OType'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), under arena-literal-object.
  • Raw Binding Eq/Hash (and the sort tie-break) include the arena's predicate and graph for both arena kinds, via ObjKind::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_identifying names 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 root clippy.toml that exempts ArenaVector from mutable_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 ?v keeps 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), where 1.5 and 1.50 kept 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 partitioned GROUP BY, the per-predicate COUNT(DISTINCT), group_by_object_count_topk (and the histogram), group_by_object_star_topk and the whole-graph COUNT(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 through objects_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 (dedup plus dup_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.5 against 1.50 from VALUES), 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_identity in grp_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 the partitioned GROUP BY stamp and the cyclic arena-literal-object bail. Against 42bb9646c's sources the indexed, mixed and routing tests failed (37 wrong answers). Against today's main (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 partitioned GROUP BY cases 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, and partitioned_group_by_folds_legacy_numbig_scale_variants_by_value runs the partitioned lane over a hand-built legacy arena (the same NBA1 shape as numbig.rs's legacy test, installed with a test-only set_numbig_arena_for_test, since no current build writes one). It counts 1.5/1.50 as one group; with the legacy check forced off it counts three groups of one.

  • it_numbig_legacy_identity (in grp_index) imports three decimals, overwrites the ledger's decimal arena with the bytes a pre-normalization build wrote (1.50, 1.5, 19.99 under 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 hold 1.5.
  • cyclic_lane_keys_big_numbers_within_one_predicate (in grp_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_identity also pins:
    • each regained lane serving a vector predicate whose arena holds no value twice, and declining one that holds a value twice;
    • with novelty adding a copy of a stored vector, each lane declining and the vector counting once;
    • the same answers with the identity tables built (vectors_compare_by_value_with_the_identity_tables_built);
    • vectors over a union of graphs (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, through DISTINCT, 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;
    • the join test above;
    • a failed read failing the query. The two tests delete the ledger's vector shard files and drop the cached shards, then run DISTINCT, GROUP BY, COUNT(DISTINCT), a join and MINUS over 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, a DISTINCT over 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, or term_view built without the query's slot, the queries answer n=4 instead of n=3.
  • Unit tests: vector keys agree across the arena, novelty and VALUES forms, 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.0 against 0.0, [0.1] as f64 against the stored f32 0.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 main on DISTINCT, GROUP BY and a join on ?v, thousands of times slower on COUNT(DISTINCT ?v), and 10–20x main's peak memory. The keying above is what replaced it.

Today's main keys 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 through binding_to_group_key_owned to its catch-all arm, format!("{val:?}"): the Debug text of every component. In a profile of main's GROUP BY ?v, 81% of the samples are in <Arc<[f64]> as Debug>::fmt. The answers are right, but a GROUP BY or a join on ?v costs about 0.8M instructions a row and holds a ~15 KB string per key. Measured on the same box: main just before #2214 (b38268f33) took 633M instructions for a GROUP BY ?v at 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 both main (596a4fd87, this head's merge base) and b38268f33, which keyed a vector by its handle: cheap, and wrong (it's the answer this PR fixes). b38268f33 measures within 1% of 149d02d81, the main this section used before.

Method: a quiet c7i.8xlarge EC2 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 on ex:v and a distinct decimal on ex:d, and every tenth also gets copies of both on ex: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, a perf_event_open counter 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 instructions over whole processes, taking the difference between 1 and 11 timed runs, agrees with it within 0.1% on DISTINCT for both builds and on main'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 a COUNT(DISTINCT ?v) on ex:v and on ex:u in the same process has built both identity tables.

Vector cells: instructions relative to each base

Cell against 100K × 768 100K × 1536 250K × 1536
SELECT DISTINCT ?v, counted table built b38268f33 1.01x 1.00x 1.00x
main 0.30x 0.21x 0.19x
not built b38268f33 1.63x 2.13x 2.10x
main 0.49x 0.45x 0.40x
peak RSS MB main / b38268f33 / not built / built 938/74/390/99 1,817/82/692/108 4,516/148/1,684/216
GROUP BY ?v, counted table built b38268f33 1.06x 1.05x 1.05x
main 0.008x 0.004x 0.004x
not built b38268f33 1.45x 1.78x 1.75x
main 0.011x 0.007x 0.007x
peak RSS MB main / b38268f33 / not built / built 1,898/94/390/103 3,710/109/692/108 9,257/218/1,702/236
join on ?v across two predicates † both tables built b38268f33 1.10x 1.21x 1.20x
main 0.005x 0.003x 0.003x
not built b38268f33 1.72x 2.34x 2.33x
main 0.008x 0.006x 0.006x
peak RSS MB main / b38268f33 / not built / built 545/84/397/398 1,033/94/723/726 2,514/174/1,766/1,770

† 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)

Cell 100K × 768 100K × 1536 250K × 1536
COUNT(DISTINCT ?v) 1.01x (59 → 71) 1.00x (77 → 98) 1.00x (110 → 133)
dotProduct top-10 1.00x 1.00x 1.00x
cosineSimilarity top-10 0.99x 1.00x 1.00x
decimal join 1.00x 1.00x 1.00x
decimal join, projecting ?x 1.00x 1.00x 1.00x
decimal SELECT DISTINCT ?x, counted 0.73x 0.73x 0.62x
decimal GROUP BY ?x, counted 1.00x 1.00x 1.00x
SELECT DISTINCT ?s, counted 0.98x 0.98x 0.98x
projection SELECT ?s ?v 1.00x (3,552 → 3,551) 1.00x (6,737 → 6,737) 1.00x (16,816 → 16,816)

Absolute counts for scale, at 100K × 1536 (main / b38268f33 / this PR without the table / with it): DISTINCT 1,905M / 406M / 866M / 407M; GROUP BY 163,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.

  • With the table built, DISTINCT and GROUP BY don't read the arena at all, so they sit at 1.00x–1.06x of b38268f33 and peak close to it. What's left is building the key and its row in the table.
  • The join stays at 1.10x–1.21x of b38268f33 with 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 of ex:v. The shards are shared across the query's keys and drop when it finishes.
  • Without the table, a key holds a slice of its shard, so the peak is about the arena itself (100K × 768 f32 is 307 MB, plus 31 MB of copies on ex:u), and the gap is one xxh3 pass over each key's bytes plus building the key.
  • First query on a cold process. Value keys read the arena, so the first value-keyed query also loads its shards: DISTINCT is 3.07G instructions here against b38268f33's 447M at 100K × 1536 when the table isn't built (5.05G on main). b38268f33's lane never reads them.
  • The decimal controls got faster: DISTINCT keeps each row's hash, so a growing table doesn't hash its rows again, which matters for a decoded BigDecimal. A subject DISTINCT and a decimal GROUP BY are flat, and so is the projection.
  • The ratios against b38268f33 match the ones this section had against 149d02d81 within 0.02x on every vector cell, so the merges didn't move this PR's cost.
  • I didn't run 1M. At 1536 dims that's 6 GB of arena per copy, and the 100K → 250K numbers scale linearly.

A shared cache smaller than the arena. Capped at 256 MB, at 100K × 1536 (a 614 MB arena, plus 61 MB on ex:u):

Cell (cache 256 MB) main b38268f33 this PR, table built this PR, not built peak RSS MB main / b38268f33 / built / not built
projection 100.8G — — 1.00x of main 6,396 / — / — / 6,395
SELECT DISTINCT ?v, counted 56.1G 406M 1.00x of b38268f33 4.43x 1,536 / 83 / 108 / 710
GROUP BY ?v, counted 218.1G 626M 1.05x of b38268f33 3.26x 3,412 / 103 / 108 / 710
join on ?v † 250.0G 439M 4.59x of b38268f33 5.32x 708 / 93 / 742 / 712

With the table built, DISTINCT and GROUP BY don'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 where main'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:

Scenario main this PR ratio
vector DISTINCT, counted 18,265,319 7,729,952 0.423x
vector GROUP BY (partitioned), counted 114,263,209 8,107,527 0.071x
vector GROUP BY (hashed), counted 120,297,006 14,061,166 0.117x
string DISTINCT 5,472,741 5,464,998 0.999x
string GROUP BY (partitioned) 8,504,851 8,466,809 0.996x
string GROUP BY (hashed) 14,393,809 14,394,224 1.000x
integer GROUP BY (partitioned) 4,154,127 4,152,943 1.000x

The vector rows return 64 values on both sides, except main's partitioned GROUP BY without the count, which still returns 2,000 (one per handle).

Gates

On an EC2 c7i.8xlarge, at fcca2191f (main 596a4fd87 merged 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;
  • both wasm32 clippy lines;
  • testsuite-sparql's clippy and its own tests.

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.

aaj3f added 5 commits October 28, 2026 01:12
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.
@aaj3f aaj3f added bug Something isn't working as expected area:query Query execution, planning, fast paths, overlay, result formatting labels Oct 28, 2026
@aaj3f
aaj3f requested a review from bplatz October 28, 2026 12:46

@bplatz bplatz 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.

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 DISTINCT and GROUP BY on them;
    • a flat similarity ranking (dotProduct / cosineSimilarity ORDER BY … LIMIT). It reads through vector_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_key now 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>>,

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.

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.

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.

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, a GROUP 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_read fails 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.

Comment thread fluree-db-query/src/group_aggregate.rs Outdated
Comment on lines +1146 to +1150
// 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()));

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.

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.

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.

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.

aaj3f added 20 commits October 30, 2026 14:55
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.
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.
@aaj3f

aaj3f commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

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 main on a quiet EC2 box (c7i.8xlarge, both built and measured there). The ledgers were file-backed and bulk-imported, with one distinct vector per subject: 100K at 768 and 1536 dims, plus 250K × 1536 as a scaling run. Each cell ran in its own process, and I report median instructions retired (every thread, user and kernel; perf stat agrees within 0.1% on DISTINCT) and the process's peak RSS.

At those shapes the first version was 5x to 10x of main on DISTINCT, GROUP BY and a join on ?v, and thousands of times slower on COUNT(DISTINCT ?v), because it declined the per-predicate fast path for every vector predicate. Its peak memory was 10–20x main's too. Most of that was hashing every component, more than once per row, and every key holding a decoded f64 copy of its vector.

So I changed how vectors key rather than tune around it:

  • Nothing decodes or copies a vector to key it any more, so the per-view memo is gone. A decoded vector (novelty, VALUES, BIND) keys by its components. Everything hashes through one canonical function (vector_value_hash / vector_value_hash_f32, xxh3 over the components narrowed to f32 when that's exact), and equality stays bitwise on the f64 components, as FlakeValue's is.
  • Each vector arena gets an identity table, owned by the store: per handle, the value hash and the canonical handle (the lowest handle holding an equal vector). It's 12 bytes per handle, so 1.2 MB at 100K and about 12 MB at 1M. Its no-repeats bit lets the per-predicate COUNT(DISTINCT), the group-count top-k (and the histogram), the star top-k and the whole-graph COUNT(DISTINCT ?prop) serve a vector predicate whose arena holds no value twice, which is the usual embedding shape.
  • A stored vector keys by that table once it's built, and holds no shard. Two keys of one arena compare by canonical handle. Only a comparison against another arena's key or a decoded vector, on a hash match, reads components, and those reads pin their shard in a set the graph's keys share, so it loads once per query and drops with the last key. Before the table is built, a stored vector keys as a zero-copy slice of its arena shard, hashed in place.
  • A read that fails while keying or comparing fails the query. A hash table's equality can't return an error, and calling the pair unequal would be a quiet wrong answer, so the failure goes into a slot the query owns and the operators that key rows check it after each batch (with the runner as a backstop). Building a key had the same gap, on main too: a vector or big number whose read failed got keyed by its handle. a_failed_vector_read_inside_a_hash_table_fails_the_query and a_failed_vector_read_while_keying_fails_the_query delete the shard files and expect an error from DISTINCT, GROUP BY, COUNT(DISTINCT), a join and MINUS.
  • DISTINCT keys rows holding a vector in a table of their own, so rows without one keep the binding path, and same_term compares vectors through the same keys.

When the table gets built matters for reading the numbers. Only the whole-predicate fast paths build it (count_distinct_objects_for_predicate, group_count_v6, the star top-k, through objects_keyed_by_value), the first time one of them runs on that predicate. An ordinary DISTINCT, GROUP BY or join never builds it, since building reads the whole arena: a DISTINCT over one subject's vector would otherwise pay for 100K. It costs one pass over the arena, about 1.7G instructions at 100K × 768, 3.4G at 100K × 1536 and 8.6G at 250K × 1536 (including that first read of the arena from disk), once per store (so again after a new index is published). So the "table built" rows are a process that has run, say, a COUNT(DISTINCT ?v) on that predicate, and the others are a cold one that hasn't.

Instructions relative to main (149d02d81), peak RSS MB in parentheses (main → this PR):

Cell 100K × 768 100K × 1536 250K × 1536
COUNT(DISTINCT ?v) 1.01x (59 → 69) 1.01x (77 → 97) 1.02x (109 → 132)
SELECT DISTINCT ?v, counted table built 1.02x (72 → 97) 1.02x (81 → 106) 1.01x (147 → 214)
not built 1.64x (72 → 389) 2.14x (81 → 691) 2.11x (147 → 1,683)
GROUP BY ?v, counted table built 1.06x (94 → 102) 1.05x (102 → 107) 1.06x (216 → 235)
not built 1.45x (94 → 389) 1.78x (102 → 691) 1.76x (216 → 1,701)
join on ?v across two predicates † both tables built 1.10x (83 → 398) 1.21x (92 → 724) 1.21x (173 → 1,769)
not built 1.72x (83 → 396) 2.35x (92 → 722) 2.35x (173 → 1,766)
dotProduct / cosineSimilarity top-10 1.00x / 1.00x 1.00x / 1.00x 1.00x / 1.00x
decimal join (and projecting ?x) 1.01x / 1.00x 1.01x / 1.02x 1.01x / 1.01x
projection SELECT ?s ?v 1.00x 1.00x 1.00x

With the table built, DISTINCT and GROUP BY don't read the arena at all, so they peak close to main and sit at 1.01x–1.06x of its instructions; what's left is building the key and its row in the table. Without it, the peak is about the arena itself (100K × 768 f32 is 307 MB), since a key holds a slice of its shard rather than a copy, and the gap is one xxh3 pass over each key's bytes. The join is the one cell that stays above that, at 1.10x–1.21x with both tables built, and its peak stays about the two arenas: a canonical handle only names a value within its own arena, so a match across two predicates has to compare components, and with every tenth subject copied that touches every shard of ex:v.

A couple of things I'd want you to see, though:

  • main's join on ?v is wrong, not just cheaper (†). With a copy of every tenth ex:v vector on ex:u, ?a ex:v ?v . ?b ex:u ?v on main returns the right number of rows but the wrong rows: it pairs by handle, so ex:s10's copy joins ex:s1. The body said plain joins were already right on main, which only held for the small fixture (a few hundred subjects take another lane). I've corrected the body, and a_join_on_a_vector_pairs_values_not_handles pins it; it fails on main with exactly that pairing.
  • I didn't run 1M. At 1536 dims that's 6 GB of arena per copy, and 100K → 250K scales linearly with the table built, so I don't expect surprises, but happy to run it on a bench box if you'd like it measured rather than extrapolated.

The decimal controls stayed flat or improved: a decimal DISTINCT is 0.73x of main at 100K and 0.62x at 250K, since DISTINCT now keeps each row's hash instead of hashing again as its table grows. Decimal GROUP BY and a subject DISTINCT are 0.98x–1.00x.

If any of these shapes aren't what you had in mind, I'm happy to rerun with yours.

JoinKey::Lit::p_id_for_arena

Yep: join_key decodes arena literals before it gets there, so the field was only ever None. Dropped in 059fdd26c. JoinKey is re-exported from fluree-db-query, so it's technically a public variant losing a field, but nothing outside the crate builds JoinKey::Lit.

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 again: projection measures 1.00x of main at 768, 1536 and 250K × 1536, with the same peak.

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.
@aaj3f

aaj3f commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

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 main once #2214 landed (342052217, then 74712ef23 and fcca2191f for later mains). #2214 decodes keys through a graph-less TermView and carries each arena literal's graph on the binding, so the vector keys follow that now:

  • A vector key reads the arena of the graph its literal came from, never one the view assumes, and the view's last-shard / identity-table / pins cache is per (graph, predicate). vectors_over_a_union_of_graphs_compare_by_value pins it over FROM g1 FROM g2: one handle number holding a different vector in each graph, and one vector held in both.
  • Building a key now returns its read failure through fix(query): several graphs answer from the graphs they name, at lane speed; typed literals and string filters keep their terms #2214's Undecodable, which I changed to keep the io::Error so fuel and fetch errors stay typed. KeyReadErrors is only for comparisons inside a hash table now. One thing the merge would have quietly broken: term_view() didn't carry the query's slot, so a failed comparison answered n=4 instead of erroring. It does now, and a_failed_vector_read_inside_a_hash_table_fails_the_query fails without it.
  • The cyclic join is narrower than before (4f7728f6d). It keeps a big-number object when every edge binding it reads one predicate and the arena isn't a legacy one, since the handle is the value there, and it still declines across predicates, on a legacy decimal arena, and for vectors. That was the "if we'd rather scope that out" question in the body, so worth a look if you see it differently.
  • Vector shard reads and the identity-table build stay uncharged for fuel, as reading a vector is on main. Charging vector reads would be its own small PR.

One perf thing you'll want to know before reading the new table: since #2214 (mine, 8ab3a22ad), main decodes a vector on its hashed key paths and keys it by its Debug text, so a GROUP BY ?v or a join on ?v there is now 130–200x slower than it was. At 100K × 768 a GROUP BY ?v is 82.9G instructions on main against 633M just before #2214, measured on the same box. This PR replaces that path, so against main its vector cells read 0.003x–0.5x, which isn't a fair bar. The table also gives b38268f33 (main just before #2214, keyed by handle), and against it the numbers match the ones you saw within 0.02x. It probably also means this one is worth landing sooner rather than later.

The body has the full table and the rest.

@aaj3f
aaj3f requested a review from bplatz November 18, 2026 19:45
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.
@bplatz

bplatz commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Pushed a few changes to get this ready for the release:

After the third change, the body's description of ShardPins ("held weakly by the store", "per store and graph rather than per view") is out of date. The pins are per query now.

@bplatz
bplatz merged commit 67ec796 into main Nov 19, 2026
21 checks passed
@bplatz
bplatz deleted the fix/vector-term-identity branch November 19, 2026 03:46
bplatz added a commit that referenced this pull request Nov 19, 2026
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.
bplatz added a commit that referenced this pull request Nov 19, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:query Query execution, planning, fast paths, overlay, result formatting bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants