Repository navigation
feat(index): small named graphs share one pooled index tree - #2140
Conversation
Five sort orders for a shared tree of small named graphs: SPOT, PSOT, POST and OPST with the graph compared last, and GSPO leading with it. Pooled leaves store 30-byte routing keys (the graph as a u32) and a graph column per leaflet; pooled branches carry the graph in each leaf bound; the root gains an optional pool section naming the pool's branches and graphs. Dedicated trees are unchanged on disk: 26-byte keys, no graph column, graphless branch bounds. Overlay ops, scan filters and column batches carry a graph, compared only by pooled orders.
…hem through it Bulk import sizes each user named graph by its rows. One above POOL_MAX_GRAPH_ROWS (4096; FLUREE_POOL_MAX_GRAPH_ROWS overrides) keeps its own tree; the rest are built into the shared pooled tree in one pass over the input, instead of one full pass per graph: GSPO comes from the (g, SPOT)-sorted commit merge, the other four orders from run files that keep each record's graph, and dedup tells graphs apart. Readers scan a pooled graph through the pool filtered to the graph: GSPO for SPOT/PSOT scans and for a POST scan of one exact value, the pooled POST/OPST (graph last) otherwise; with the graph fixed the rows arrive in the planned order. Fast paths and the batched probe lanes decline for pooled graphs; range, geo and export read the pool; history over a pooled graph errors. GRAPH ?g probes the pool once for the block's most selective required triple and skips pooled graphs with no matching row. Incremental indexing over a pooled root aborts to a full rebuild.
…e pooled GSPO Joins inside a pooled graph declined the batched lanes and probed one scan per left row. The subject lane now admits a pooled graph when the persisted rows are the whole answer (overlay-free, at the index t, policy clears the predicate): it reads the graph's GSPO rows for the batch's subject span and checks the predicate per row. The other lanes still decline for pooled graphs. Tests import TriG into the pool and check identical triples across graphs, graph-scoped reads, value search, joins within one graph and size-based placement; each fails when the pooled dedup identity, the pooled scan's graph filter, or the lane's graph bound is removed.
PropertyJoin, OPTIONAL and range-semijoin probes go through batched_subject_probe_binary; for a pooled graph it now reads the graph's GSPO rows for the probed subject span, emitting matches in the same subject-then-object order as PSOT. subject_probe_lane_plan admits a pooled graph through the same rule the join's subject lane uses (pooled_probe_lane); the object and star lanes still decline. The pooled-graph test adds an OPTIONAL inside GRAPH ?g whose only match is in another graph; it fails when the probe drops its graph bound.
…tree Incremental indexing no longer gives up on a pooled root. A window that touches only dedicated or new graphs carries the pool over unchanged. A window that writes a pooled graph reads the graph's current rows from the pooled GSPO, applies the window to them and builds the graph a dedicated tree in every order; the graph leaves the pool, the rest stay. The base rows the window touches seed Phase 3b's base presence, so the stats deltas match a full rebuild's. The pooled tree keeps no history sidecars, so a window that retracts a pooled fact still falls back to a full rebuild; pools only come from bulk import, which is append-only, and an earlier t reads a pooled graph by row t. Leaflet replay now keeps the graph column, which a time-travel read of a pooled graph lost (every row then failed the graph filter). The class-membership lookups and the wildcard cursor read a pooled graph through the pool, as the base store Phase 3b loads is pooled. Tests: an append promotes only the written graph and every graph reads back exactly; a retraction rebuilds; a pooled graph at an earlier t holds exactly the rows written by then. Each fails with its piece removed.
DictOverlay::new sized its graph base from graph_ids().len(), which collected every graph id (and, with a pool, hashed each pooled one) on every probe. With thousands of graphs that walk dominated cross-graph queries: 'GRAPH ?d' OPTIONALs paid it per row. The store now keeps the count, computed once at load; a pooled graph that also holds an arena counts once.
Per-graph stats are most of a root with many named graphs (94% at 4K graphs) and compress ~15x. The 24-byte header stays readable; the body after it is one zstd frame behind an extended-flags bit. Both root parsers inflate first, so roots written before this still decode.
A pooled leaf's sidecar (version 2) writes each history entry's graph, so its entries are 33 bytes; dedicated sidecars are unchanged. Decoders take a segment's entry width from its length, so the full-blob and range-read paths share one decoder. History routing, leaflet key widening, novelty merge and replay keep the graph: a pooled leaflet's fact identity includes it, and a restored fact lands in its own graph.
The rebuild places user named graphs by row count, as the import does, and builds the small ones into the pooled tree in one pass over the sorted commits, history included (pooled history entries now carry their graph). A reindex therefore writes the pooled format instead of one tree per graph. A write to a pooled graph promotes it with its whole log: its pooled rows, its pooled history and the window's events fold per fact into a dedicated tree with history, so a retraction stays incremental rather than forcing a full rebuild. History scans over a pooled graph read the pooled tree, keeping only that graph's rows and entries.
CID expansion walked only named-graph and legacy arena branches, so the pooled tree's leaves and history sidecars were missing from every reachable set: a storage sweep planned them as orphans, and pack, fork and drop missed them. Both the strict and tolerant expansions now walk every branch the root routes to, the pool's included.
The fact-to-handle lookup (query-time staging) and the incremental resolver's seed both read only a graph's dedicated SPOT branch, so a vector in a pooled graph had no handle to retract: deleting it left it in place, before indexing and after the graph's promotion. Both now read through graph_tree, bounded to the graph's run of the pooled GSPO.
Pruning GRAPH ?g probes the pool with an ordinary scan opened in the outer graph, and ordinary scans make graph-local deductions: an arena-backed decimal resolved to the outer graph's handle, and the outer graph's stats narrowed the datatypes a value may take. Either could rule out a pooled graph that matches. In probe mode the scan now keeps only encodings that mean the same in every graph: no datatype inferred from stats, and NumBig values as their whole datatype rather than a handle.
…aflet Replay kept the graph column only when the input batch had one. A leaflet whose every fact was retracted holds only history and starts from an empty batch, so the facts it restored lost their graph and the graph filter then dropped them: reading a pooled graph at the assert of a since-retracted sole fact returned nothing. Pooled orders now always carry the graph.
ColumnBatch::byte_size summed every column but the graph, so the leaflet cache undercharged each pooled batch by its graph column (50 KB per full 25K-row leaflet).
A differential suite: two ledgers take the same transactions, one is indexed into the pool and one never indexed. About thirty shapes (counts, distinct counts, literal/blank filters, grouping, min/max, class lookups, paths, OPTIONAL, NOT EXISTS, MINUS, VALUES, ordering, object-bound and cross-graph forms) run both inside GRAPH and with the pooled graph as the default graph, over the pooled base, the base plus novelty, and after promotion. Opening the fast-path gate to pooled graphs makes a whole-graph COUNT(*) answer 0 here.
main writes root version 2; next's single bump is version 3, which a full reindex or import writes. The compressed body and the pooled tree are part of that bump rather than a new version: only a v3 root is compressed, so an incremental build over a main-format ledger still writes a root main can read, and a pool never appears in a v2 root.
main writes root version 2; next's one bump is version 3 (now named ROOT_V6_VERSION_V5), and every root this build writes uses it: the first index of a main ledger upgrades it. The decimal policy moves from the version byte to an extended flag, so an arena-only ledger stays arena-only until it is reindexed. v2 roots still decode, which is what lets a main ledger take that first incremental index.
GraphId is u32. Everything next persists holds it at 32 bits, or at a leaflet's own width: the root's graph routing, arena list and graph IRI count, the stats wire, branch headers (version 2), pooled history entries, and the stats sketch (format 3). A pooled leaflet's graph column is 2 bytes wide unless it holds an id past u16. main's 16-bit forms (v2 roots, version 1 branches, format 2 sketches) still decode, so a main ledger's first v5 index reads them. Commits carry graph ids as varints already; decode accepts u32 and a commit may now register up to 2^20 graphs (it was 256), with the count checked before anything is allocated. Novelty holds graphs by a dense slot, which is what a FlakeId packs, rather than a vector indexed by graph id. Build-time records widen with it (RunRecordV2 is 40 bytes, was 32). A 70,000-graph import exercises it end to end: pooled reads by id and through GRAPH ?g, a write over the pool, promotion and a new graph past the old limit.
An order the base root lacks was written from the window's winning records with their ops ignored, so a fact asserted and retracted within that window came back as a live row, and the window's transitions were dropped. An order whose branch has no leaves (the default graph after a TriG import with only named graphs) took the merge path, whose slicing routes novelty only to existing leaves, so every write to it vanished. Both now fold the window per fact from absent, as a promotion folds a pooled graph's log: rows for facts that end present, sidecar entries for every transition.
…their size f:indexingDefaults carries f:graphPlacement: f:PlacementAuto (the default) lets the indexer pool a small graph, f:PlacementDedicated keeps a graph in its own trees whatever its size. On f:LedgerConfig it is the default for user named graphs; on f:GraphConfig it overrides that for one graph. The default graph and the system graphs keep their own trees regardless. One placement policy now serves the import and the full rebuild: a user graph pools unless the config pins it dedicated, its live rows exceed the row bound, or its retained history exceeds the history bound. Live rows and history are separate measures, so a long history is never read as a large graph. Before a build they are estimated from each graph's asserts and retracts; the root then records each pooled graph's exact rows and history entries, tallied as the pool's GSPO order is written. The indexer's config provider now returns the ledger's indexing config (full-text properties and graph placement) rather than full-text properties alone.
Before, only an import or a full rebuild put graphs in the pool, and the first write to a pooled graph promoted it out for good, so ordinary writes drained the pool back to a tree per graph. Each incremental build now places the graphs its window writes with the same policy as a full build. A pooled graph stays pooled while its recorded size, grown by the window, stays within bounds; a graph new to the index joins the pool on the same terms. All of a window's pooled changes land in one update per pooled order. A graph that outgrows the pool, or that the config now pins dedicated (written this window or not), is promoted with its rows and history, and the same update purges it from the pool: each identity it held rides along as a purge marker routing the merge to every leaflet that holds it. A graph with trees of its own keeps them; only a full rebuild repools. A ledger whose index has no pool starts one from the window that first writes a small graph. The pool's GSPO merge reports each graph's change in rows and history, which the root applies to its members' sizes. The merge also told one graph's superseded events from another's by triple alone, so the same triple changing in two pooled graphs within one window could attach one graph's events to the other; in the pool, graph is part of a fact.
Each named-graphs entry in ledger info now carries "placement": "pooled" when the current index holds the graph in the pooled tree, "dedicated" when it has trees of its own, and nothing while the index holds none of its rows yet. f:graphPlacement states intent and the index root records the outcome; this shows the outcome. fluree graph list prints it as a column.
…ated-only accessor IndexRoot::branches lists every branch manifest a root routes to, each named graph's own and the pooled tree's, with the tree it belongs to. Artifact reachability (all_cas_ids and the expanded walks behind GC, pack and drop) and the store's branch loading all build on it, so no walk can know one kind of tree and miss the other. BinaryIndexStore::branch_for_order becomes dedicated_branch: it returns a graph's own tree and None for a pooled graph. Readers that can scan a pooled graph go through graph_tree; the fast paths that read a graph's leaf metadata whole use dedicated_branch and decline pooled graphs.
Pooled leaves were sized like a dedicated tree's, 250,000 rows, so each pooled order of a 2,000-document pool was about three leaves. A window's writes scatter across the pool's graph-last orders (a new document lands in every predicate and value region it uses), and a touched leaf is rewritten whole, sidecar included, so nearly every incremental build rewrote most of the pool: 164-356 MB per round of 300 small writes in a sustained run, against 37-60 MB for a tree per graph, and growing with the pool. Import, full rebuild and incremental updates now size pooled leaves at one leaflet, so a build writes the leaflets it lands in. Existing pools split as their leaves are touched. Promotion also reads a pooled graph's log through graph_tree rather than the pooled GSPO branch directly.
A GRAPH ?g block runs once per named graph, planning and opening its patterns again for each; over thousands of small pooled graphs that costs far more than the rows. When the block is a join of triple patterns with bound predicates, and filters that read only variables those patterns bind and no EXISTS or full-text scoring, and the rows feeding it share none of its variables, the pooled graphs without novelty are answered together. Each pattern is one quad scan of the pooled tree that binds ?g per row (arena values decoded through the row's own graph), and the scans hash-join on their shared variables and ?g, so rows only join within a graph. The block's filters then run over the joined rows. Every other graph (one with trees of its own, a pooled one with novelty) runs through the per-graph operator as before, and so does the whole block when the quad path declines: a dataset, several ledgers, time travel before the index, history, policy, or fast paths switched off. The quad path logs "quad block engaged" when it runs.
A GRAPH ?g block whose pool probe leaves under a quarter of the pooled graphs runs per graph: visiting the few left beats scanning every pattern across the pool (a rare-entity lookup went from 0.75 ms per graph to 77 ms as quad scans). The probe taken to decide is kept for the per-graph run. The quad join keyed each row's graph by its IRI string; it now keys by the IRI's shared allocation, which every quad scan binds the graph through. On 2,000 pooled documents the quad path now runs x1 in 84 ms (per graph 93), x3 in 37 (45) and x8 in 22 (35), with identical rows.
… memory budgets A quad scan carries no transaction time or op, but a block filtering on T or OP still took the quad path and lost every row. Such filters now send the block per graph. The quad path buffered whole scans, join tables and results, and the full product with the parent rows, without charging any of it to the query's memory budget, so a block over budget kept growing instead of failing with MemoryBudgetExceeded. Each scan batch, join table and growing join result is now charged and checkpointed, intermediate buffers are released as they drop, and parent rows are paired with the results one output batch at a time. A block under a downstream row goal runs per graph, which stops early where a scan of the whole pool cannot.
GSPO still merges every build. SpotG, PsotG, PostG and OpstG keep their base branch and append the window's events as an immutable sorted run (FPD1), so a small write no longer rewrites the shared leaves its rows scatter across. Cursors over those orders fold the merged runs, resolved at their t and keyed by graph, under novelty. A build compacts an order's runs into its base at 64 runs, at max(50,000, base rows / 4) events capped at 250,000, or when a graph leaves the pool, which only the base can purge. Compacted runs become garbage; the root lists live runs, so GC, drop and pack reach them. History scans of a pooled graph read GSPO, which holds every event.
GSPO merges each indexing window on its own; a row's t is observed at that granularity. The delta runs and their compaction did not keep it: - A run held the window's raw events, so a reassertion of a present fact followed by a retraction in the same window read at its own t, where GSPO keeps the earlier one. A run now holds the window as the GSPO merge resolved it, from each fact's presence at the window's start. - Compaction folded every run into one lifecycle, where a reassertion alone in its window became a no-op: the row's t reverted to an earlier assertion, and a fact asserted in one window and reasserted in the next lost its row before the reassertion. Each window's lone assert now carries a same-t retract, which replaces the row over a present fact as the per-window merge does and cancels over an absent one. The pooled tests compare every secondary order with GSPO at every t, assertion times included, before and after compaction.
A store loads every run of every pooled secondary order before it serves, one read each: up to 256 at the run cap. Read one after another, they put a remote store's latency on the load once per run. They are now fetched together, 32 at a time, and decoded per order in run order. Cold start against an S3-compatible store with 10 ms per request, at 64 runs per order (~125K events each): delta load 2,803 ms read in turn, 139 ms concurrently; ledger ready in 3.4 s and 0.76 s against 0.44 s for the same data with no delta. At 12 runs of 240K events: 596 ms and 117 ms.
The pool probe that rules out pooled graphs for an unbound `?g` declined whenever the overlay held anything, so one unindexed write, even to the default graph, sent a selective cross-document query through every pooled graph: 1 -> 280 ms for a rare-entity lookup over 6,000 graphs. The probe now reads the persisted pool, delta runs included, at the index's `t`, and admits every pooled graph the overlay changed: novelty can add a match only in a graph it touches. Overlays list those graphs through `OverlayProvider::overlay_graph_ids`; one that can't keeps the probe off. Reading below the index's `t` still declines. A write to the default graph or one pooled graph now leaves the lookup at 1.4 ms; a write across 200 pooled graphs, 3.9 ms.
A scan kept its bindings encoded only when the overlay held nothing at all, so one unindexed write anywhere made every scan decode every row: a GROUP BY over all pooled graphs went 124 -> 275 ms after a write to the default graph or to one pooled graph. Late materialization needs the store to decode every id a scan emits. A scan of a graph the overlay holds no rows for reads only persisted ids, as does a quad scan, which covers only such graphs. The check is now `graph_has_novelty` for the scanned graph; quad scans skip it. The new test compares five cross-graph queries (GROUP BY, OPTIONAL, a join out of the graph block, DISTINCT, a selective lookup) and a JSON-LD GROUP BY, answered with writes pending in one graph and the default graph, to their answers once indexed.
`overlay_free_single_graph` gates the lanes that read persisted rows without merging the overlay: the batched subject and OPTIONAL probes, the pooled subject lane, the range semijoin's index walk and a numeric seek narrowing. It asked whether the overlay was empty, so one unindexed write anywhere sent every graph's joins through per-row probes: OPTIONALs over 3,000 pooled documents went 65 -> 148 ms after a write to the default graph. Each caller reads only the active graph, so the check is now whether the overlay holds rows for that graph. A write to one graph leaves the others on their lanes; the differential test of the previous commit fails if the check ignores the changed graph's rows.
…events at most A scan over a pooled secondary order merges every delta event in its range row by row. Near the old bound (a quarter of the base, at most 250K events) that slowed broad cross-document scans: with ~238K events per order they ran 5-40% slower than over the same data compacted, with ~128K 0-10%. Selective reads and reads of GSPO were unchanged. The bound is now a sixteenth of the base's live rows, between 16K and 64K events, so compaction runs more often under sustained writes.
A pooled secondary order's delta is folded into its base only by a build, and a build only follows a write, so the delta of a ledger that stops writing stays until its next write: every cold load fetches its runs and every scan over its range merges them. compact_pool_deltas folds every secondary order's runs into its base with no new commits; the root keeps its t, GSPO, dictionaries and stats, and the runs and replaced leaves become garbage. Fluree::maintain_index indexes pending commits (through the background indexer when there is one, directly otherwise), then compacts under the indexer's maintenance hold, skipping while a build is queued or running, and publishes the compacted root at the same t. The lifecycle housekeeping a server runs on its catch-up tick compacts a ledger whose commits and index have not moved since the previous tick, once per index root, and again on a later tick when a build or another maintenance operation deferred it.
Where no long-running indexer runs, such as a function invoked per request, nothing indexes or compacts in the background. POST /index runs Fluree::maintain_index for a scheduler to call: it reports whether it built and whether it compacted, and costs a lookup and one root read when there is nothing to do. Admin-protected like /reindex; a peer forwards it to the transaction server. fluree index runs the same maintenance locally.
Loading a store fetches every delta run, and those fetches share the storage client's request slots with every other ledger's reads. On S3, a ledger restarting with 64 runs per order (256 fetches, 32 in flight) slowed another ledger's cold reads during its load by about 28% beyond loading the same ledger compacted. Under the event bound a busy ledger compacted at 15-20 runs per order in a sustained-write run, so 32 rarely triggers; it bounds the worst case at 128 fetches.
A pooled-delta compaction (and a reindex) publishes a new root at the index's existing t. Every cached reader but the compacting connection ignored it: the update plan, the snapshot install and the peer watermarks all required a strictly greater index_t, so a reader kept the old root, whose delta runs the next sweep deletes. Another root at the same index_t is now an index update throughout: the plan installs it (alone, or after a commit catch-up), the install replaces the snapshot and keeps the novelty past t, a peer watermark records it, and freshness reports the cached state stale. The compacting connection adopts its root in place instead of dropping its cached ledger.
Folding a pooled delta read each order's runs in turn, one order after another: at the run cap that is 128 sequential reads. The runs of every order that folds are now read together, as a store load reads them, RUN_FETCH_WIDTH at a time, each order's events kept in run order.
Roots at the same t have no order, so a record read before a compaction (or reindex) still names the root it replaced, and a refresh acting on it after another refresh installed the replacement stepped the reader back: the uncompacted layout, until its next refresh. Every root links the root it replaced (prev_index); the snapshot now carries that link from both metadata decoders. One rule, InstalledIndex::is_replaced_by, decides whether a root replaces the installed one -- a newer index, or another root at the same t, never the one the installed root replaced -- and the update plan, the install (under the state lock, for a plan raced by another install) and the peer freshness check all apply it. An install that declines reports the cached state current.
# Conflicts: # fluree-db-api/src/branch_validation.rs # fluree-db-api/src/tx.rs # fluree-db-binary-index/src/lib.rs # fluree-db-query/src/binary_history.rs
#2118 (via main) and this branch both write an order with no base leaves from the window alone. The folded tree here does it for every such order, including a pooled graph's promotion, so #2118's fresh-branch builder is not carried over. Its other rules are: a graph's folded tree with nothing to hold is not published, a base root with a partial order set falls back to a full rebuild, and a dedicated graph's four tasks must agree on whether the base held its facts. The pool's orders are not checked there, since its secondary orders take writes as delta runs. The leaf merge's identity gather takes slices, as #2118 needs, and the order's identity, as the pool needs. #2118's tests pin a named graph's own trees, so they keep the graph dedicated.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is a really nice piece of work, and at a design level no pushback from me: one shared tree for the small graphs, with large graphs, the default graph and the system graphs keeping their own, is the shape I'd have asked for, and it leaves the paths that already work where they are. The two things I think need to land first are below (one is a one-line fix I ran). Two notes at a higher altitude:
(1) Replacing a root at the same t means index_t no longer orders a ledger's roots, and the PR orders them with the root's prev_index link, one hop deep. That's the same shape as #1980 and #2052: a point in time standing in for an identity that can now change without the time moving. A compaction followed by a reindex at one t leaves a two-hop case the link doesn't cover (inline at fluree-db-ledger/src/lib.rs:162). A monotonic sequence on the index head would order replacement roots outright. Not for this PR, I think the one-hop rule is the right point fix here, but it's worth naming.
(2) #2153 (open, against main) puts every lane that settles a retraction and an assertion of one fact at one t on one rule, fluree_db_core::same_t: the assertion holds. The pooled delta adds two lanes that settle such a pair, and from reading they already disagree with each other (inline at read/types.rs:255). Nothing here produces a pair on next today, so it isn't a must, but whichever of the two lands second will want these lanes on same_t too.
Claude-assisted review below:
✅ Approving to unblock you — with 2 things that need to be addressed before this merges.
The pooled tree is carefully built: the graph column only where it's needed, GSPO merged every build while the graph-last orders take delta runs, fast paths declining through one gate (active_graph_pooled), and a differential suite that compares every pooled order with GSPO at every t. I also leaned on it from outside. In a fresh instance, four pooled graphs sharing subjects, predicates and values answered ten shapes exactly (graph-scoped reads, GRAPH ?g, exact-value and range lookups, a FROM graph, joins that would pair facts across graphs if the graph filter slipped), with writes pending in one pooled graph and the default graph, after a delete of every fact in one pooled graph both before and after indexing it, and at earlier t. A graph promoted out of the pool by a retraction plus growth in one window, reasserted after promotion, shrunk, then repooled by a reindex read correctly at every t in each of those states, each read from a fresh instance. So no isolation leak that I could find. The two things to address:
- A whole read of one pooled graph opens every leaf of the pool.
use_rangeinfluree-db-query/src/binary_scan.rs:2895(and the same test influree-db-query/src/binary_range.rs:814) doesn't count the graph, soGRAPH <doc> { ?s ?p ?o }, itsCOUNT(*)andFROM <doc>scan the whole pooled GSPO. I measured 20 leaf opens against 1 for a bound predicate, and with|| filter.g_id.is_some()added it drops to 1. Details inline. This is the document-per-graph workload's basic read, so I'm treating it as a CRITICAL perf item. - Root version 3 is already spent. v5.0.0-alpha.1 writes version 3 (
ROOT_V6_VERSION_INLINE_DECIMAL) inmain's layout for a ledger's first index, imports and reindexes, and this build reads a version 3 root as the wide layout (fluree-db-binary-index/src/format/index_root.rs:211,:1035). An alpha.1 root fails to load here withtruncated at string bytes. Numbering this layout 4, or refusing alpha.1's 3 with a version error, fixes it. Details inline.
Beyond those, a few smaller things, each inline unless noted:
- Default-graph performance. The body discloses a 0.970–0.977 workload ratio on BSBM Update, and #2136 is closed without attributing it. No in-repo bench ran on this branch (
bench.ymlhas no run forfeat/pooled-named-graphs) and nothing influree-db-api/benches/exercises many small graphs, soregression-budget.jsongates neither the residual nor the new paths. Runninggh workflow run bench.yml --ref feat/pooled-named-graphs -f compare_only=truebefore merge, and adding a small bench for a pooledGRAPH ?gblock and a whole read of one pooled graph (with its budget entry), seems like cheap insurance; the first item above is exactly what such a bench would have caught. There's also a per-row graph check the default graph can't fail (inline atbinary_cursor.rs:925). - Known limitations. Two of the three paths are the same one-line swap this PR already made at
binary_scan.rs:1505(inline there). - Root decode bounds. Two widened counts allocate before any check (inline at
index_root.rs:1118). - Docs (no anchor):
POST /indexis a new route butdocs/api/endpoints.mddocuments onlyPOST /reindex(:3774);FLUREE_POOL_MAX_GRAPH_ROWS/FLUREE_POOL_MAX_GRAPH_HISTORYappear only in the PR body andgraph_scope.rs:147; and the body's line about carrying the #2133 fix is stale now that #2133 merged on 10-20 and reachednextwithcac9d92fc. I recognize these are minor and non-blocking, but if you agree they're right I'd rather see them folded in now than lost in the backlog.
Adherence to repo commitments:
- Patterns/abstractions: ✔ extends
RunSortOrder,BinaryFilter,BinaryCursorand graph routing (graph_tree) rather than standing up a parallel store; one gate for the fast paths.⚠️ the current-state scan doesn't use the graph-bounded range the history scan (gspo_leaf_range,binary_history.rs:543) and export (export.rs:140) already build. - Performance (speed first, memory second): ✖ CRITICAL: a whole read of one pooled graph is O(pool) leaf opens (item 1). The default graph's disclosed residual isn't gated by any in-repo bench. Cross-graph and import wins are large per the body's numbers, which I didn't rerun.
- Deployment targets:
⚠️ shared code every host reaches (fluree-db-apiembedded in solo's Lambdas and standalone binary,fluree-db-server; wasm32 is compile-gated). Evidence is server-shaped and file- or S3-backed. The idle-delta fold runs on a server tick that a per-request function never gets, and the docs'POST /index-on-a-schedule answer covers that; a delta stays bounded at build time (32 runs, 64K events), so no Lambda fence is crossed. Amainbinary refuses a v5 root cleanly (unsupported version 3), which the upgrade doc's every-process-together rule already covers; alpha.1 is the exception (item 2). - Testing: ✔ 31 tests in
it_import_pooled_graphs.rs(wired throughgrp_import) plusindex_maintenance_http.rs(throughgrp_http); I ran all 31 by name, green. With the per-row graph filter infilter_batchremoved, 6 of them went red, the differential suite among them, and one of my probes picked up another graph's row throughPostG.⚠️ nothing pins the leaves a whole-graph read routes, which is how item 1 got through. - Conventions: ✔ thorough multi-line commit bodies;
⚠️ the docs gaps above.
Verified locally at 99a6d5487: cargo test -p fluree-db-binary-index --lib (463 passed) plus a temporary decode probe of an alpha.1-shaped root; it_import_pooled_graphs (31 passed by name); three temporary probes (graph isolation cold and under novelty, the promotion boundary with time travel and a reindex, and leaf opens per query with a counter on open_leaf_handle); the same probes and the 31 tests with the one-line use_range fix applied (1 leaf open per whole-graph read, 31 green) and with the per-row graph filter removed (6 of the 31 red, the differential suite among them); all reverted.
Approving now so you can merge without waiting on another pass from me — just be sure the graph-bounded whole-graph scan and the root version number are in before you do.
| o_i: 0, | ||
| o_type: filter.o_type.or(range_o_type).unwrap_or(0), | ||
| g_id: self.g_id, | ||
| g_id: if self.spans_pool() { 0 } else { self.g_id }, |
There was a problem hiding this comment.
🔴 Must address before merge: a whole read of one pooled graph opens every leaf of the pooled GSPO.
These bounds already carry self.g_id, but use_range above (binary_scan.rs:2895) counts s/p/o and the object bounds, not filter.g_id. So a scan of a pooled graph with nothing else bound (GRAPH <doc> { ?s ?p ?o }, a COUNT(*) over that block, SELECT … FROM <doc> WHERE { ?s ?p ?o }) takes BinaryCursor::scan_all, which routes every leaf of the pooled GSPO (binary_cursor.rs:159). Each leaf is opened before leaflet_out_of_range can skip its one leaflet, so the read costs a leaf open per pooled leaf, O(pool) rather than O(graph). binary_range_eq_v3 makes the same test (binary_range.rs:814), so the range API's unbound read of a pooled graph does the same.
I ran it: 1,000 pooled graphs of 10 quads, imported with leaflet_rows(500) so each pooled order has 20 leaves, read from a fresh instance with a counter on open_leaf_handle. GRAPH ex:g500 { ?s ?p ?o }, the COUNT(*) form and the FROM ex:g500 form each opened 20 leaves, in both rounds; binding the predicate or the subject in the same graph opened 1. At the default 25,000-row leaflet with one leaflet per pooled leaf, the 1.42M-quad docgraphs pool in the body is ~57 GSPO leaves, so a cold whole-document read against S3 becomes ~57 sequential reads where a tree per graph needed one or two. I suspect this, more than leaf sharing, is behind the cold one-document row in the body's table.
GSPO leads with the graph, so counting the graph is enough: with these bounds the leaf range narrows to the graph's run.
|| filter.g_id.is_some()That line in both use_ranges (gated on an env var for the run) took the three whole-graph forms in the probe to 1 leaf open each, and the 31 pooled tests stayed green. The history scan (gspo_leaf_range, binary_history.rs:543) and export (export.rs:140) already bound the cursor this way. A test asserting the leaves a whole read of one pooled graph routes, next to pooled_leaves_hold_one_leaflet, would keep it.
| /// ledger upgrades it — and `main` refuses v5 outright rather than misreading | ||
| /// it. The decimal policy is an extended flag, so an arena-only ledger stays | ||
| /// arena-only until a reindex. | ||
| pub const ROOT_V6_VERSION_V5: u8 = 3; |
There was a problem hiding this comment.
🔴 Must address before merge: root version 3 is already taken by v5.0.0-alpha.1, with main's layout, and this build misreads those roots.
alpha.1 (ddbfb7536, released 2026-10-14 with binaries) defines ROOT_V6_VERSION_INLINE_DECIMAL = 3, and at that tag the full rebuild (fluree-db-indexer/src/build/rebuild.rs:291) and the bulk import (IMPORT_DECIMAL_ENCODING in fluree-db-api/src/import.rs) both write it, so a ledger's first index, every import and every reindex on alpha.1 produce a version 3 root, and incremental builds keep it. Its doc comment says that layout is byte-identical to v2 (16-bit graph ids, no compressed body). Here a version 3 root is the wide layout: wide = version == ROOT_V6_VERSION_V5 (:1035), read_graph_width in fluree-db-core/src/db.rs:786 and GraphWidth::for_root_version in fluree-db-core/src/stats_wire.rs:61 (both version >= 3).
I encoded a root in main's layout (encode_main_layout, one named graph, two graph IRIs), set byte 4 to 3 the way alpha.1 does, and decoded it: IndexRoot::decode failed with root: truncated at string bytes (need 29800 at offset 87, have 2689), and LedgerSnapshot::from_root_bytes the same. So, as far as I can tell, a ledger alpha.1 created or imported won't load on this build, with an error that reads like corruption. It fails loudly rather than silently, and reindex proceeds without a loadable ledger (admin.rs:2808), so a reindex is probably the way back, though I haven't verified that end to end.
The branch (FBR3 1 → 2), sketch (FHLL 2 → 3) and sidecar (FHS1 1 → 2) bumps in this PR each took a new number; the root is the one that reuses a number already on disk. Giving this layout 4 and reading 3 as alpha.1's narrow inline-decimal layout (or refusing it with a version error that says to reindex) keeps the version byte meaning one layout. Telling them apart by FLAG_EXT_COMPRESSED would also work, since every root this build writes is compressed, but a number is the clearer contract. It also fixes the other direction: alpha.1 accepts 3 and has no inflate step, so it would read this build's compressed root as its own layout, where a 4 it refuses cleanly. Either way it's cheapest now: once this ships, 3 means two layouts for good.
There was a problem hiding this comment.
Keeping 3. v5 alphas aren't meant to be compatible with each other: the supported upgrade is main (v4, root version 2) to v5, as one format change. So a ledger alpha.1 indexed isn't read here, and no reader or renumbering is added for it. The PR body says so under Compatibility.
| let o_i = batch.o_i.get_or(i, u32::MAX); | ||
| if filter.matches(s_id, p_id, o_type, o_key, o_i) { | ||
| if filter.matches(s_id, p_id, o_type, o_key, o_i) | ||
| && filter.matches_graph(batch.g_id.get_or(i, 0)) |
There was a problem hiding this comment.
🟠 Should address: the default graph now pays a graph check per row that it can't fail.
For a dedicated order filter.g_id is always None and the batch's graph column is AbsentDefault, but this still reads the column and calls matches_graph for every row of a filtered scan. The overlay merge does the same per row (base.g_id.get_or(ri, 0) at :752, then cmp_key_fields' extra match order), and OutRows checks its graph column on every push. Each is cheap, but they sit in the per-row loops of every default-graph scan, which is where the body's 0.970–0.977 BSBM residual would have to come from if it's real. I haven't measured whether these explain it.
Hoisting the graph test out of the loop (let check_graph = filter.g_id.is_some();, and the same pooled flag the merge already computes) costs nothing on the pooled side. More useful than my guess would be a bench.yml compare run on this branch (query_overlay_matrix, query_hot_bsbm, reindex_incremental), since none has run here. It's minor, but I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Addressed in 5217106. The bench compare run on the branch: https://github.com/fluree/db/actions/runs/40140637716
| // `Binding::Sid`/`Lit`, not `EncodedSid`/`EncodedLit`. | ||
| let late_materialize = ctx.is_some_and(|c| { | ||
| !crate::fast_path_common::overlay_has_novelty(c) && !c.eager_materialization | ||
| (self.quad.is_some() || !crate::fast_path_common::graph_has_novelty(c, self.g_id)) |
There was a problem hiding this comment.
🟡 Optional / nit: two of the three "Known limitations" paths are this same one-line swap.
Decimal inference at binary_scan.rs:2408 (!overlay_has_novelty(ctx)) and the encoded pre-filters at binary_scan.rs:3306 (!overlay_has_novelty(ctx)) both ask whether anything is pending anywhere, where this line asks about the scanned graph. Both read only persisted rows of self.g_id when they engage, for the same reason late materialization can here, so graph_has_novelty(ctx, self.g_id) (and self.quad.is_some() || for the pre-filters) looks like the same fix. The differential test from e75baf851 would cover them. The independent-scan replay lane (join.rs:1288) reads both sides, so that one may need a closer look and I'd leave it to you. Not a regression against next, which treats any novelty as global everywhere, but if you agree the two are right I'd rather see them in now than lost in the backlog.
There was a problem hiding this comment.
Addressed in 7d33d49. The replay lane stays a known limitation.
| // Per-graph specialty arenas | ||
| let arena_count = read_u16_at(data, &mut pos)? as usize; | ||
| let arena_count = read_graph_width(data, &mut pos, wide)? as usize; | ||
| let mut graph_arenas = Vec::with_capacity(arena_count); |
There was a problem hiding this comment.
🟡 Optional / nit: graph counts are 32-bit now, and two of them still size an allocation before anything checks them.
graph_iri_count is capped with .min(data.len()) above and pool members are checked with ensure_bytes, but arena_count here and named_count (:1200) go straight into Vec::with_capacity. Before this PR they were u16; now a damaged root (or an alpha.1 v3 root read wide, see :211) can ask for billions of elements, which aborts the process on allocation failure instead of returning the decode error the other counts give. .min(data.len()), as for the graph IRIs, would match. Minor, but if you agree I'd rather see it folded in now.
| /// names: at an equal `t` nothing else orders the two. | ||
| pub fn is_replaced_by(&self, t: i64, id: &ContentId) -> bool { | ||
| match &self.id { | ||
| Some(installed) if t == self.t => id != installed && self.replaced.as_ref() != Some(id), |
There was a problem hiding this comment.
🟡 Optional / nit: this refuses only the one root the installed root replaced.
With two replacements at one t (compaction A → B, then a reindex or a second maintenance pass B → C), a reader on C that acts on a record read before B (still naming A) gets is_replaced_by(t, A) == true, since A is neither C nor C's replaced (B), and steps back two hops to A. The data at A is the same t, so it's the uncompacted layout until the next refresh, or a failed load if A's runs and leaves were collected in the meantime. That's narrow, and I think the one-hop rule is right for this PR, but it's the case a monotonic sequence on the index head would close (see the headline). I didn't construct it; this is from reading the rule.
There was a problem hiding this comment.
Agreed, keeping the one-hop rule here. Follow-up: #2178.
| if e.t > to_t { | ||
| continue; | ||
| } | ||
| let better = best.is_none_or(|b| e.t > b.t || (e.t == b.t && !e.op && b.op)); |
There was a problem hiding this comment.
❓ Question: same-t ties in the pooled delta settle one way here and the other way in compaction.
resolve_events_at takes the retraction when a fact has an assertion and a retraction at one t (!e.op && b.op). Compaction reads the same runs through with_replacements and split_lifecycles, which sorts (t, op) so the assertion comes last and wins (incremental.rs:5642). A run holding such a pair would therefore read absent through PostG/OpstG/SpotG/PsotG before a compaction and present after it, and GSPO merges it on its own rule. Only a ledger written before #2109, or a pushed commit, can hold one on next, so this is a narrow window. #2153 (open, against main) makes fluree_db_core::same_t the one rule (the assertion holds) for every existing lane. Is it worth routing these two through it, whichever of the two PRs lands second, so the pooled orders keep agreeing with GSPO? I haven't constructed a pair against this branch; this is from reading.
# Conflicts: # fluree-db-api/src/export.rs # fluree-db-binary-index/src/lib.rs # fluree-db-core/src/overlay.rs # fluree-db-query/src/binary_scan.rs
The list view from `main` finds list predicates in each graph's POST tree and a list owner in its graph's SPOT leaves. The merge of `next` also reads the pooled GSPO for both: it holds every pooled row as of the index, since every build merges it. Lists written to two pooled graphs read as RDF lists in SPARQL, for a bound owner and inside `GRAPH ?g`, and as members in JSON-LD. Without the pool in `list_predicate_ids` SPARQL returns the members; without the pooled branch of `subject_holds_lists` the owner's edge is lost.
A scan of a pooled graph that bound nothing else (`GRAPH <g> { ?s ?p ?o }`,
its COUNT(*), `FROM <g>`) took `BinaryCursor::scan_all`, which routes every
leaf of the pooled GSPO, opening each before the graph filter could skip
its one leaflet: O(pool) leaf opens for an O(graph) read. The range API's
unbound read of a pooled graph did the same.
GSPO leads with the graph, so a bound graph alone now narrows the cursor
to the graph's run, as the history scan and export already did. In a pool
of 50 GSPO leaves, the three forms route 1-2 leaves instead of 50.
The scan's open event reports the leaves its cursors route, which the new
test reads.
Only a scan of one pooled graph filters on the graph column, and only the pooled tree's merge compares it, but every filtered scan read the column and tested it per row, and every overlay merge read it per row. Both are now decided once per batch, so a dedicated tree's rows pay nothing.
…he scanned graph Both read only the scanned graph's persisted rows when they engage, but both declined whenever anything was pending in any graph, so one write to a pooled graph turned them off for the default graph too. They now ask whether the scanned graph has pending writes, as late materialization does; the encoded pre-filters also run for a quad scan, which covers only graphs without pending writes. The new test answers a decimal lookup, string-prefix and range filters on the default graph with writes pending in a pooled graph, then with writes pending in the default graph itself, and compares the latter with the answers once indexed. Dropping the pending-write check from the pre-filters fails it (a pending "Alan" goes missing from the prefix filter). Dropping it from decimal inference changes no answer here, so that gate stays as conservative as before for its own graph.
Graph counts in a v5 root are 32-bit, and the arena and named-graph counts sized an allocation before anything checked them, as did the predicate and default-graph leaf counts. A damaged root could ask for billions of elements and abort on allocation failure instead of returning a decode error. Each now reserves at most the input's length, as the graph IRI count already did; a short root still fails on its first missing entry.
The endpoint reference documents `POST /index` (request fields, response, status codes) and lists it, with `/sweep`, among the admin-protected endpoints. The placement docs give the pool's bounds, 4,096 live rows and 16,384 history entries, and the configuration reference lists `FLUREE_POOL_MAX_GRAPH_ROWS` and `FLUREE_POOL_MAX_GRAPH_HISTORY`, which override them.
query_hot_pooled_graphs runs a document-per-graph ledger, ten quads per graph and every graph pooled (checked before anything is timed): a whole read of one graph, its count, a bound subject in it, a `GRAPH ?g` quad block grouped by graph, and a cross-graph value lookup. The single-graph reads should stay flat as the pool grows across scales. Its regression budget copies the sibling query_hot benches until a nightly baseline lands.
|
Docs ( |
Summary
Ledgers that keep one named graph per document end up with thousands of small graphs, and each one gets a full set of index trees. A
GRAPH ?gquery opens every graph's trees, a ledger load reads four branch files per graph, the root carries per-graph routing that is rewritten on every publish, and a bulk import builds a tree per graph.This PR gives small named graphs one shared pooled tree. Large named graphs, the default graph and the system graphs keep their own trees.
What changes
Index format. This is part of
next's single format bump.main's v2 roots still decode, and amainledger's first index upgrades it.Placement
f:graphPlacementf:PlacementDedicated, onf:LedgerConfigor per graph onf:GraphConfig(seedocs/ledger-config/setting-groups.md).Writes
clamp(base rows / 16, 16K, 64K)events;t:Fluree::maintain_index,POST /index, orfluree index. The last two now index pending commits and then compact.t(by compaction or reindex), cached readers adopt it and keep their pending commits. A reader never steps back to the root its own root replaced.Reads
GRAPH ?gblocks over pooled graphs run as quad scans. The batched subject lanes and probes read pooled graphs directly.main) finds list predicates and list owners in the pooled tree too.Results
Document workload (synthetic, document-per-graph; benchmark-db
docgraphsharness).Cold single-document reads are the one place the pool is slower: a cold read of one small graph reads a leaf it shares with other graphs. This row predates bounding a whole read of one pooled graph to that graph's own leaves (before, it opened every pooled GSPO leaf), so it may overstate the cold cost.
Sustained writes (2,000 documents, 10 rounds of 100 creates, 100 edits and 100 retracts, background indexing at the default threshold, EC2).
nextwrote 877 MB. This branch wrote 423–432 MB under the earlier, looser delta bound (64 runs, events above base ÷ 4), and 473 MB under the tighter bound in this PR, which is +9% over the looser bound.next.What the delta costs. Measured on realistic delta states against the same data fully reindexed; warm medians unless noted.
Default-graph workload (BSBM Update 100M, file storage).
nextput workload throughput at 0.970–0.977 ofnext(medians). Pairs ranged from 0.85 to 1.09.Compatibility
fluree indexandPOST /indexnow also compact a pooled delta after indexing.{"compact": false}skips the compaction.HousekeepingOptions::compact_idle_pool_deltasdefaults to on.FLUREE_POOL_MAX_GRAPH_ROWSandFLUREE_POOL_MAX_GRAPH_HISTORYoverride the placement bounds.v5.0.0-alpha.1also wrote version 3, inmain's layout, and its roots fail to load here: the supported upgrade ismain(v4) to v5, as one format change, and v5 alphas are not compatible with each other.Known limitations
tis ordered only one hop deep (Follow-up: Order index roots replaced at the same t by a sequence on the index head #2178).Testing
t, assertion times included, through incremental builds, delta runs and compaction.troot adoption, a commit catch-up past the compacted root, and a stale record or peer watermark that still names the replaced root.COUNT(*)andFROM) routes at most two of a 50-leaf pool's leaves.query_hot_pooled_graphsbenches single-graph reads, aGRAPH ?gquad block and a cross-graph lookup, with a regression budget.