Repository navigation
feat(reasoning): materialized reasoning indexes - #2292
Conversation
…hooks
Adds the per-branch reasoned-heads document to every nameservice backend
(memory, file, storage, Raft, DynamoDB), compare-and-swapped on its version
under the branch fence, with conformance cases. Adds the head manifest and
derived-only-set content kinds, the head storage namespace under
{branch}/@reasoned/{head_id}, the publication rules (admit), an indexer
input that folds a head's derived facts into a build after its window's
commits, and the head side of GC: manifest-chain walks, per-generation
reachable sets, and an age-guarded release plan.
Registers reasoning programs per branch, computes a program's complete closure at the branch head, and publishes it as a generation: the branch's index merged with the derived facts, folded incrementally from the previous generation (commits in the window plus derived corrections computed from the persisted derived-only set) or rebuilt from a copy of the base index. A reasoning query whose settled reasoning matches a generation at exactly its commit is answered from the head with reasoning off, reported in the tracker's reasoning tally; anything else reasons at query time as before.
The branch collector, branch drop and the sweep now count the dictionary blobs every retained generation of every reasoned head reaches, on the branch and its siblings, and defer when a head cannot be read. Branch drop deletes the branch's @Reasoned folder, and the sweep walks each retained generation as its own chain. Manifests and derived-only sets live outside a head's index folder so a sweep never takes them for orphans.
Follows commit events, refreshing one ledger's heads at a time and coalescing commits that arrive meanwhile, with a periodic catch-up scan for missed events, throttled heads and registrations made elsewhere. The server runs it where writes publish: standalone servers and the Raft leader.
reasoningFreshness (SPARQL: # PRAGMA reasoning-freshness:) picks how a reasoned head may answer: default serves a generation at exactly the queried snapshot and reasons at query time otherwise; exact also refuses a capped query-time answer; strict waits for a generation and never reasons at query time; asOf reads the whole query at the newest generation at or before the snapshot. The tracker's reasoning tally names the head, generation and basis commit that answered.
register, list, retire and refresh under /v1/fluree/reasoned-heads, admin gated and run where the ledger's writes do.
The spike example builds an OWL 2 RL head over a file-backed, indexed LUBM ledger and compares every query's complete result multiset between query-time reasoning and the head, and reports storage: index and head bytes, dictionary blobs shared with the base, and what one logical generation writes.
A dataset whose members are all graphs of the primary view's ledger at its t is answered from the head, every member swapped for the head's state with its own graph; results format through the swapped primary. Datasets that reach other ledgers reason at query time.
A generation's derived-only set is now an index of content-addressed buckets of facts by subject, stored at t 0 and sorted, so a generation that changes a few subjects writes only their buckets; the rest keep their content ids. GC reaches a generation's buckets through its index.
Local ledgers call the API directly; tracked or --remote ledgers call the server's /reasoned-heads routes.
…ve heads per branch A head retired longer than the retention window has its folder deleted, then its entry removed; the worker's catch-up scan runs it. A branch takes at most eight active heads.
A reasoning query on a ledger whose heads document was empty when last read does not read the nameservice again for 30 seconds; a registration through the same instance clears it at once.
…odes, completeness, external schema changes - A sweep holds a ledger's head builds off and waits out those that have written files they have not yet published, so a generation never publishes a root the sweep reclaimed. A refresh that finds a sweep running reports Deferred. - A head answers only a view that is the branch's committed state at its head commit, of the same ledger instance; staged and time-travel views reason at query time. asOf walks the view's own commit line. - rdfs and owl2ql stay on when a program without owl2rl is served from a head; only the materializing modes are turned off. A program that derives hierarchy edges under them publishes nothing. - An OWL 2 RL pass that fails under a positive datalog program is an explicit failure: nothing is published, and an exact query refuses it. - A refresh settles the program before deciding the head is current, and rebuilds at the same commit when a schema or rules source elsewhere changed what it settles to. The heads pointer carries the settled key.
The registered object is a reasoning index and the feature materialized
reasoning. The vocabulary is now:
- reasoning program: the registered rules and options;
- reasoning index: what a branch maintains for one program, its asserted
facts together with the program's derived facts;
- generation: one immutable build, at a basis commit;
- head: the pointer to the currently published generation.
Rust API (register_reasoning_index, refresh_reasoning_index(es),
retire_reasoning_index, reasoning_indexes, ReasoningIndexWorker),
HTTP routes (/reasoning-indexes/*), CLI (fluree reasoning-indexes, with
--index), the tracked reasoning block ("index": {"indexId", ...}), the
not-ready error type, and the persisted names (the per-branch
ReasoningIndexes document with indexes and head fields, the
{branch}/@reasoning/ storage folder, the nameservice traits, the Raft
command, DynamoDB attributes) all follow. Docs move to
docs/query/materialized-reasoning.md.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is a big piece of work and at a design level I'm on board: settling the program into a key, serving only at an exact commit and falling back to query time otherwise, putting engine semantics in the key, and storing a generation as a full merged index (speed first) are the calls I'd have wanted, and the truth maintenance, publication rules and GC held up well under review. A few headline notes; (2), (3) and (5) are what I'd want in before merge:
(1) The question I'd most like your read on first: do you want #2287 folded into this PR, or landed right after it? As this stands, a JSON-LD graph crawl (select {"?s": ["*"]}, any depth) in a reasoning query is a 400 for every restricted caller, including when reasoning comes only from the ledger's f:reasoningDefaults and including rdfs-only and property-only policies, so on a ledger with reasoning defaults that's every crawl a restricted caller makes. And for root callers the same crawl renders differently served vs at query time: Claude reproduced @type: "ex:Student" before the worker published and ["ex:Person", "ex:Student"] after, at the same commit. I'm not going to block on it either way, but if this merges without #2287 following shortly, I think some very common JSON-LD queries start failing unexpectedly, so I wanted to make sure the stakes are on the table. Your call.
(2) The worker and publication path. A generation's head is CAS'd without a sync() (the branch indexer flushes first for exactly this reason), so a crash can leave a durable head naming missing files that the index never recovers from. A failing index is retried on every tick and commit with no memo, serially, on the one worker. Every closure the worker computes stays in the global reasoning cache unread (about 1.9 GB measured for a 10.5M-fact closure), and its default 100M-fact / 1 h budget overrides the operator's and the ledger's caps. And the worker runs on every standalone server and Raft leader, reading every ledger's reasoning-indexes document every 60 s whether or not anything was ever registered. Each has a cheap fix inline.
(3) Plain queries under an f:onClass policy, with no reasoning involved, got about 6% slower; Claude bisected it to ed74d85d9, where the enforcer now collects, sorts and re-probes every flake's subject per batch even when the prefetch already cached them.
(4) On policy reading what the query reads (f:onClass judged by reasoned classes in a reasoning query, so a rule can grant as well as deny, and a caller who doesn't ask for reasoning is judged on stored facts): I'm fairly comfortable with that, and it's what write-side policy already does. We did consider two alternatives, a deny-only rule where derived classes can deny but never grant, and judging class membership under the ledger's configured reasoning regardless of the caller's reasoning flag, and I'm raising them only so we're both explicitly agreed that your design is the preference over those. If it is, no change needed.
(5) Erasure (#2280): it isn't clear to me whether gating this is already your plan, so to say it plainly, nothing gates it today: serving never checks the entry's floor, and #2280's purge doesn't reach @reasoning/, so an index copy would keep erased values. I'd like whichever of this and #2280 lands second to carry the gate (refuse to register or serve a reasoning index on a ledger with retention or erasure configured until erasure covers it), and this PR to carry the one-line floor check in try_servable. Details inline.
(6) A lot of the fix commits in here fall into the same class I flagged on #2022, "two paths do the same thing and one of them re-derives (or renders from) a different state than the other read". With a second answering lane, every entry point that decides which state a query reads is a site for it:
R2RML paths that never served (
84b6b9a5c); a planned stream that re-built an unrestricted view (3b4b2994a); a dataset checked through its primary only (191cdf721); typed Cypher nodes rendering stored facts (f8457488b); the JSON-LD crawl (#2287); Cypher never consulting the indexes (#2288)
The point fixes are right. But since this PR already touches all eleven call sites that pair build_executable_for_* with serve_*_from_reasoning_index, folding the serving decision into the executable builder (return the view to execute against alongside the executable) seems close to PR-sized and would close #2288 as a side effect. Not a blocker from me.
(7) #2271 (yours, on main) and this will meet when main next merges into next, and the resolution needs care beyond the textual conflicts in join.rs, fast_path_common.rs, optional.rs and the core overlay/range files: #2271 drops the !ctx.eager_materialization term that today keeps this PR's batched pair lane off under query-time reasoning, and its reroute_accumulator_per_row drains batched_accumulator without clearing batched_pair_objects, so a naive resolution would pair subjects with the wrong objects in release builds. Whoever merges should clear batched_pair_objects in the reroute and decide explicitly whether the pair lane admits reasoning callers. reasoning.rs also auto-merges into a compile error (self.base is now the Base enum).
Full review below:
🔄 Request changes.
@bplatz the settled-key matching, the freshness modes and the way every serving error degrades to query time are really nicely done, and the served numbers (an OWL 2 RL count going from ~75 ms to under 2 ms on the review probe) are exactly what this should buy. The design is right; what holds the merge for me is narrower: the worker and publication path (an unflushed head pointer, unmemoized retries of a failing index, closures left resident in the global cache with a default budget that overrides operator caps, and an every-ledger scan on every server), the ed74d85d9 per-batch subject re-collection (about +6% on plain f:onClass queries), and the erasure gap, where I'd like the floor check here and the registration/serving gate in whichever of this and #2280 lands second. The graph crawl (#2287 now or right after) I've left to you in the headline. The optional items are each small, and I'd rather see them folded in now than lost in the backlog. One more cleanup worth taking with it: DerivedFactsHandle (fluree-db-api/src/view/types.rs:1062) is a pre-existing placeholder documenting a materialize_derived_facts / with_derived_facts API that never existed, and this PR is the feature it was holding a place for, so it can go.
Adherence to repo commitments:
- Patterns/abstractions:
⚠️ Extends the right mechanisms (nameservice CAS documents with conformance cases on every backend, the content store, the indexer's GC and release windows, the shared IR: SPARQL# PRAGMA reasoning-freshnessand JSON-LDreasoningFreshnessboth reach it, with tests). The serving decision is re-made at eleven entry points instead of once where the executable is built, and the build-vs-reclaim latch exists twice (ReasoningIndexState::begin_write/hold_for_reclaimbeside the indexer'sGcLocks). - Performance (speed first, memory second): ✖ CRITICAL: plain
f:onClass-policy queries about +6% (bisected toed74d85d9); about 1.9 GB per worker closure left in the global cache; an O(ledgers) nameservice scan every 60 s on every server; a failing index recomputed on every commit. Nine existing criterion benches (41 scenarios) are flat or faster, and served queries are dramatically faster. - Deployment targets:
⚠️ Sharedfluree-db-apicode. Build/sweep exclusion is in-process only, so a sweep in one process can reclaim another process's unpublished generation files: the #1635 class the body already lists, with a new writer. An embedder in a short-lived host (e.g. inside AWS Lambda) gets no background maintenance and a refresh that is one long synchronous call. wasm32 compiles build/maintenance out and thewasm32/wasm-smokejobs are green. - Testing: ✔ Thorough and all of it runs: 45 + 15 + 11 reasoning-index and policy-contract tests, the incremental-closure oracle, the pair-join suite, routes, and the S3/DynamoDB lifecycle on LocalStack, all passing in CI on this SHA. The gaps are a bench for query-time policy filtering (how the class-policy regression got through) and a test retracting an
owl:sameAslink. - Conventions:
⚠️ Commit bodies are excellent. The body should carry a "Breaking changes" section for embedders:NameServiceLookupand the publisher now requireReasoningIndexesLookup/ReasoningIndexesPublisherwith no default methods (any embedder with its own nameservice stops compiling),Fluree::run_stream_querydrops itsLedgerStateargument, andReasoningTally/QueryResultgain public fields; and the storage docs should say an index holds the derived facts twice. Docs are otherwise updated throughout.
Claude verified on clean EC2 boxes at branch HEAD: criterion A/B base vs head on nine benches (two ABAB rounds), a review probe (five rounds each for the class-policy case) and a non-LTO bisect over the policy commits; three review tests reproducing the crawl behaviour (3 passed); a 6M-asserted / 10.5M-derived OWL 2 RL ledger for the worker's memory, retry and retraction costs; CI run 42611536166 green on this SHA.
Requesting changes for the worker/publication items, the class-policy regression and the erasure gate, but the core of this is close, and I'm happy to talk through any of these.
| } | ||
|
|
||
| /// Every ledger with an active index, refreshing what the worker knows. | ||
| async fn scan(&self, has_indexes: &mut HashMap<String, bool>) -> BTreeSet<String> { |
There was a problem hiding this comment.
Blocking (performance / host). The reasoning-index worker runs on every standalone server and Raft leader, and every 60 seconds it lists every ledger and reads each one's reasoning-indexes document, whether or not any index was ever registered.
scan calls all_records() and then get_reasoning_indexes per non-retracted record (worker.rs:130-168), at startup (:47) and on every DEFAULT_CATCHUP_INTERVAL tick (:22, :78). The server spawns the worker unconditionally (fluree-db-server/src/lib.rs:441-447 standalone, :913 on the Raft leader); unlike the BM25 worker beside it (Bm25WorkerOwner) there's no switch to turn it off.
So a server with N ledgers that never uses materialized reasoning now does one ledger listing plus N document reads a minute, forever. On the file nameservice that's a directory walk plus N file reads; on DynamoDB it's a GSI query plus N consistent GetItems a minute (fluree-db-storage-aws/src/dynamodb/mod.rs:752, :2049-2061), i.e. a standing read bill proportional to tenant count on a multi-tenant server, for a feature none of them opted into.
Cheapest fix I can see: have the worker idle until it knows some ledger has a registration (the registered notify already covers same-process registrations, and the commit-event path already caches has_indexes per ledger), and make the catch-up scan visit only ledgers known to carry a document, with a much slower full sweep for registrations made elsewhere. A config switch in the Bm25WorkerOwner style on top of that would let an operator turn it off entirely. Commenting here because fluree-db-server/src/lib.rs (the unconditional spawn) is in the diff too but this is where the cost lives.
| //! branch's asserted facts together with the program's derived facts, every | ||
| //! graph, stored under `{branch}/@reasoning/{index_id}/`. | ||
| //! - A **generation** is one immutable build of an index, at a basis commit. | ||
| //! - The **head** points at an index's currently published generation. |
There was a problem hiding this comment.
Blocking (durability). A generation's head pointer is published before its files are flushed. Real location: fluree-db-api/src/reasoning_index/build.rs:1155-1198 (publish_generation), which GitHub doesn't render as a patch; commenting here on the module doc that defines the head.
The generation's leaves, roots, derived-only buckets and manifest are all derived content kinds, which FileStorage writes at page-cache durability; only sync() makes them durable. The branch indexer flushes before it moves a pointer for exactly this reason (publish_index_result, fluree-db-indexer/src/lib.rs:600-612: "without this the pointer, which is durable, could name files that never reached the device"). publish_generation CASes the head with no sync(), and nothing under reasoning_index/ calls one (Claude grepped sync()\|\.sync( over fluree-db-api/src/reasoning_index/*.rs: no hits).
After an OS crash or power loss between the CAS and the flush, the durable head names a manifest or root that isn't there. Matching queries then quietly fall back to query time forever (loaded_generation, serve.rs:276, errors and servable swallows it at debug, see my note on serve.rs:101), a strict query waits out its 10 s and gets a 408, every later refresh fails at the throttle check's index_generations(...)? on the missing head manifest (build.rs:498), so the index never repairs itself, and the collector defers shared dictionary releases for the branch and its siblings on every pass because shared_refs_of_indexes can't read the head.
Fix: sync() the index store once before the CAS loop, as the indexer does; and perhaps let the throttle check treat an unreadable head manifest as "rebuild" rather than an error. (Found by code reading, not crash-reproduced.)
| ), | ||
| RefreshOutcome::Failed { reason } => tracing::warn!( | ||
| ledger = ledger_id, | ||
| index = %index_id, |
There was a problem hiding this comment.
Blocking (performance / host). A refresh that fails is retried on every catch-up tick and every commit, with no memo or backoff, on the instance's one serial worker.
A capped closure, a failed OWL pass, a program that derives hierarchy edges or a missing reasoned graph ends Failed, which logs the warn here and records nothing. The currency check that short-circuits a refresh (build.rs:466-476) only matches a published head at the same basis and settled key, which a failing index never has, so the next tick (:78) and every commit settle the program and recompute the full closure again. The worker refreshes one ledger at a time (:51), so while one failing index recomputes, every other ledger's indexes wait. Without a program reasoningBudget the cap it recomputes up to is 100M facts or 3,600 s (build.rs:68-69).
Claude ran it on a box: an OWL 2 RL program with "reasoningBudget": {"maxSeconds": 15} on a 6M-fact ledger, the worker running for 210 s with no commits, logged 5 "not refreshed … capped" warns. With no commits those retries hit the reasoning cache (one closure was computed), so the cost comes back with each commit or once the cache entry is evicted. /reasoning-indexes/list never shows the failure, so a user only sees query-time fallback.
Fix: a per-index failure memo keyed on (basis, settled, engine) in ReasoningIndexState, skipping refreshes until one of those changes (with backoff for the same inputs), and the last failure on the entry so list and the CLI can say why an index never publishes. A per-ledger fairness bound on the worker would keep one index from holding everyone else's.
| `rdfs:subClassOf` or `rdfs:subPropertyOf` facts under `rdfs` or `owl2ql` | ||
| (without `owl2rl`) publishes nothing. | ||
|
|
||
| An index publishes only complete results. A program whose closure hits its |
There was a problem hiding this comment.
Blocking (memory). The worker leaves every closure it computes resident in the process-global reasoning cache, and its default budget overrides the caps an operator or the ledger set. Real locations: fluree-db-api/src/reasoning_index/build.rs:516-521 and :1047, not rendered as a patch; commenting on the docs paragraph about budgets.
(a) complete_closure calls compute_derived_facts, whose OWL 2 RL pass inserts the result into global_reasoning_cache() (fluree-db-reasoner/src/lib.rs:277-280, a 16-entry LRU by count, not bytes). Once the generation is published, matching queries are served from the index, and the worker's budget is part of the cache key, so nothing reads that entry again. On the box, for a 10.5M-fact closure: VmRSS 4,397,212 kB after the refresh, 2,469,748 kB after clearing the cache, i.e. about 1.9 GB held by that one unread entry; up to 16 of them can stay resident.
(b) When the program has no reasoningBudget, the worker sets max_facts = 100M, max_seconds = 3600 and max_memory_mb = None (build.rs:516-521). In reasoning_budget() (fluree-db-query/src/execute/reasoning_prep.rs:37-69) the modes win over FLUREE_REASONING_MAX_FACTS, and the ledger's f:reasoningMaxFacts has already been merged into the modes and is overwritten, so only FLUREE_REASONING_MAX_MEMORY_MB still binds. The same 10.5M-fact closure peaked at 15,417,088 kB RSS in the worker; a background closure triggered by any retraction on a larger ledger can grow until the process (under Raft, the leader) is OOM-killed.
Fix: run the worker's closure on the uncached path, as reason_owl2rl_incremental already does (or evict its key after the refresh); treat the env and ledger caps as ceilings on the worker default (min), and document the worker's default budget and FLUREE_REASONING_MAX_MEMORY_MB here.
| let Some(published) = &entry.head else { | ||
| continue; | ||
| }; | ||
| if !matches!(entry.registration.state, RegistrationState::Active) |
There was a problem hiding this comment.
Blocking (cross-PR, erasure). A generation is a complete copy of the branch's asserted facts (every graph) plus what they derive, and nothing in #2280's erasure or targeted removal reaches it.
The body says generations are built at erasure epoch 0 and that erasure integration must land before the two ship together. Since next takes main by merge, they meet in next on the first sync after #2280 lands, not at a release. From the review of #2280's head (ae0f20722): its purge rewrites each holding branch's index_head_id, graph-source heads, commits and recorded garbage, so a generation under {branch}/@reasoning/{indexId}/, being referenced, is neither garbage nor a head it walks, and keeps the erased value; targeted removal retracts current values with ordinary commits and refuses history reads, but a generation built before the removal still holds the value as current, and the current-state path checks nothing. On this side, the entry's floor (fluree-db-core/src/reasoning_index.rs:186-189) gates only publication: try_servable never compares the head's basis.epoch with it, so raising the floor stops the next generation and keeps serving the current one.
It isn't clear to me from the body whether gating this is already your plan, so to say it plainly: as the PR stands, nothing gates it today, since serving never checks the floor and #2280's purge doesn't reach @reasoning/. I'd like whichever of this and #2280 lands second to carry the gate: refuse to register (and to serve) a reasoning index on a ledger with retention or erasure configured until erasure reaches reasoning indexes, so an erased fact can't live on in an index copy.
For this PR specifically, skipping a head whose basis.epoch is below its entry's floor here is a one-line guard that makes the serving side fail closed whichever lands first.
| match self.try_servable(db, reasoning, as_of).await { | ||
| Ok(served) => served, | ||
| Err(e) => { | ||
| tracing::debug!(ledger = %db.ledger_id, error = %e, "reasoning index not served"); |
There was a problem hiding this comment.
Optional (observability). Falling back on any serving error is exactly the right contract (rubric §3), but logging it at debug means a generation that can't be loaded (a blob reclaimed under it, a manifest that won't decode) silently turns every matching query into query-time reasoning, forever, while the worker sees the head as current and never rebuilds. We may want a rate-limited warn for errors that aren't "nothing to serve", and ideally a "last serve error" on the entry that /reasoning-indexes/list reports. Minor and non-blocking, but I'd rather see it in this PR than lost in the backlog.
| Until it is, queries no longer match it and reason at query time. A refresh | ||
| that finds a storage sweep of the ledger running defers to the next one. | ||
|
|
||
| A new generation of an OWL 2 RL program is computed from its predecessor |
There was a problem hiding this comment.
Optional (performance). This is more of a question than a suggestion. Any retraction in a window sends the next generation to a full recompute (build.rs:1082-1087), including one no rule can see: on the box, retracting ex:s0 ex:name "s0" (no rule reads ex:name) on the 6M-fact ledger took a 216,734 ms refresh at 15.5 GB peak, closure full, 0 added and 0 removed, against 70 ms for a one-fact insert (incremental). Since every update retracts the old value, on mutable data the incremental path will rarely run. Two cheap narrowings: drop window retractions whose predicate the program neither reads nor concludes (and that aren't rdf:type, owl:sameAs or schema vocabulary) before falling back, since the compiled rules already know that set; and when the fold comes out empty, reuse the previous derived-only set rather than re-filtering and re-encoding it (that no-op recompute still spent asserted_filter 22,302 ms, fold_diff 28,661 ms and derived_write 14,495 ms outside the closure). Relatedly, asserted_filter (build.rs:1297-1336) loads every asserted fact of each derived predicate into a HashSet; a merge against a streamed PSOT scan would bound it. Commenting on the docs because build.rs isn't rendered in this diff. Minor and non-blocking, but if you agree, I'd rather see at least the first one in this PR.
|
|
||
| An index lives inside its branch, under `{branch}/@reasoning/{indexId}/`, and | ||
| shares the ledger's dictionaries. Each generation is a complete index of the | ||
| branch — every graph — plus the derived facts, so an index costs about one |
There was a problem hiding this comment.
Optional (docs). "An index costs about one more index of the branch" understates it. On the box, after the first generation the reasoning namespace was 131,942,759 B against a 35,661,940 B branch index (3.7x), and after three generations the merged index was 90,460,527 B with another 46,706,690 B of derived-only buckets beside it: the derived facts are stored twice. Each index also re-indexes every commit, so per-commit CPU scales with the number of indexes (up to eight). Worth saying both here for whoever sizes a deployment. Minor, but I'd rather it land with the feature.
| /// while a sweep of the ledger runs. A sweep reclaims every file no | ||
| /// published generation references, so it must not plan while a build | ||
| /// has files written and not yet published. | ||
| pub(crate) fn begin_write(&self, ledger_name: &str) -> Option<IndexWrite<'_>> { |
There was a problem hiding this comment.
Optional (altitude). This is more of an observation than a recommendation. begin_write/hold_for_reclaim re-implement the indexer's build-vs-reclaim latch (GcLocks: try_begin_build, open_release_window, BuildTicket, fluree-db-indexer/src/orchestrator.rs:615), and every path takes both: builds (build.rs:677, :702) and every reclaim (admin.rs:1761, :2988, :3193), in opposite orders at admin.rs:1761 and :2988. It can't deadlock today because neither build side blocks, but two counters kept in step is the kind of thing that drifts; perhaps the API owns one GcLocks-equivalent when no indexer worker exists and both go through it. Separately, begin_write is checked only after the closure (build.rs:677), so a refresh that meets a running sweep returns Deferred and throws away a closure that took 149,356 ms on the box; waiting briefly for the hold, or taking it before the closure, avoids that. Minor and non-blocking, but if you agree, I'd rather see it folded in now.
| } | ||
| } | ||
|
|
||
| /// Collect the whole prev-index chain, newest root first./// Collect the whole prev-index chain, newest root first. |
There was a problem hiding this comment.
Nit. So minor, but the doc line is duplicated: "Collect the whole prev-index chain, newest root first./// Collect the whole prev-index chain, newest root first."
… state Retain the execution snapshot, overlay and policy through hydration so query-time and persisted reasoning render the same facts. Serve Cypher from matching generations, permit safe single-graph policy crawls and keep the multi-graph restriction, including union-default expansion. Read incremental rule definitions from assertions rather than the prior derived closure, and bump engine semantics to 4 so affected generations rebuild. Reject malformed registrations before persistence and isolate refresh failures between indexes. Sync every publication manifest before its CAS attempt. Rebuild unreadable heads at the same commit, retaining a persisted reclamation guard when repair detaches a broken chain. Fence both exact and retained generations against the registration's erasure floor. Make automatic maintenance opt-in, coalesce work in FIFO order, retry failed indexes with bounded backoff and expose process-local diagnostics. Restrict frequent polling to known indexes and reconcile all ledgers more slowly. Respect resolved reasoning budgets and bypass the query closure cache for maintenance. Use a configurable LRU for loaded generations. Clone and sort only class-cache misses, retaining state-scoped policy safety and caching completed lookups with no classes. Document resource costs, API migration and the remaining cross-PR integration requirements. Validation: 442 API integration tests; reasoner and policy suites; focused maintenance, storage, cache-isolation, HTTP and configuration tests; API/server clippy with warnings denied; workspace formatting; Raft server compile check. No new A/B performance measurements or cross-PR integration claims are made.
|
@aaj3f pushed 20196e8b0 with the review fixes. Thanks for the detailed repros. Here is what this commit addresses and what remains:
The policy contract remains “policy reads what the query reads,” including derived classes granting or denying under reasoning. I also fixed an incremental/full-closure mismatch: incremental rule definitions now come from assertions, not previously derived schema. Engine semantics is bumped to 4 to rebuild affected generations. Added the requested Validation passed locally: 442 API integration tests, the reasoner/policy suites, focused maintenance/storage/cache-isolation/HTTP/configuration tests, API/server Clippy with warnings denied, workspace formatting, and a Raft-enabled server compile check. The fresh CI run is separate from those local checks. Other optional suggestions left out of this commit: positive registration caching/strict short-circuiting, lazy |
|
Heads-up for the next main→next merge once #2271 lands on main. #2271 lets batched lanes run under reasoning (eager materialization). On
|
|
A follow-up for when #2271 and this PR meet on #2271 (b8aba38) keeps the batched lanes' translated ops on the reasoning materialization, counted toward its reasoning memory budget. When a translation won't fit, the lane runs per row and the server logs one WARN per materialization with what to change. Two places in #2271 list operator options for reasoning memory, and both leave out persisted reasoning because it isn't on
Once this PR is on
|
# Conflicts: # fluree-db-query/src/execute/reasoning_prep.rs # fluree-db-query/src/join.rs
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz thank you for turning this around so thoroughly. Nearly everything I held the merge for is fixed, and Claude mutation-checked each fix on a box: the flush before the CAS, opt-in maintenance, the uncached worker closure, the query budget precedence, the backoff and the serving floor check each have a test that goes red when the hunk is reverted. The crawl ended up better than either option I'd framed: single-graph crawls now render the reasoned state in both lanes and judge by derived classes, and Claude's re-run of the 11-09 probes shows all three holding. Thanks for confirming the policy contract too; nothing further from me there. Two narrower design notes, the repair trigger and the formatter's db/policy precedence, are inline. A few headline notes:
(1) The one new blocker is a sibling of that crawl fix. The refusal now lets a one-graph dataset through on the premise that hydration keeps the read state, but format_results_async_dataset (the public dataset formatter) builds its views from the DataSetDb, not from read_view. So a reasoning crawl formatted through it shows facts a derived-class deny hides from the rows. Claude reproduced that on the head SHA; at 3b2a385bc the shared refusal turned the same request into a 400. I don't think it's reachable over HTTP, but it's a public embedder API. It's the same "two paths, one renders from a different state" class as before, and I'm not asking you to consolidate the serving decision here; the point fix is right. Details inline; the fix looks small.
(2) Performance: the class-policy regression from ed74d85d9 is gone. Claude A/B'd it on a box, and plain f:onClass queries are back to base in both builds (release: base 122.3 to 124.9 ms, head 121.7 to 124.6). In its place, this commit adds about a microsecond to every Fluree::query call: a point lookup goes from 23.5 to 23.8 µs to 24.8 to 25.1 in the release build, mostly from the two GraphDb clones behind read_view. That's small in absolute terms, but it's every query, and moving rather than cloning, plus a slimmer read state, should take it back. Details inline.
(3) Erasure (#2280): the floor checks are in, thanks. The gate itself isn't in either PR yet; #2280 at 1a0790c5c doesn't mention reasoning indexes. Now that #2280 targets next too, my ask is the same as before: whichever of the two merges into next second carries it, in both directions as your docs now say. If that's this PR, it holds this one; if it's #2280, it doesn't. As things stand #2280 looks closer to ready, so I expect the gate to end up here.
(4) The merge brought #2271 in, and your resolution (pair lane off under eager, batched_pair_objects cleared on reroute, Base adapted) is what I'd hoped for. Two follow-throughs from your own 11-11 notes now apply in this branch: the pair-lane test the merge needs (Claude deleted the guard and nothing went red), and persisted reasoning in #2271's memory WARN and docs. The body still says the two "have not been merged or tested here", so that line can go too.
Good to merge from my side once (1) and (2) are in, with the D6 gate following whichever lands second -- approving in advance to unblock you
Full review below:
@bplatz the fix commit is careful work. The sync placed inside the CAS loop so a retried manifest is flushed too, the persisted reclamation guard on repair, maintenance on the query budgets instead of its own, and the read state carried on the result so formatting can't drift from execution are each the kind of fix I'd want, and each one has a test that goes red when its hunk is reverted. What holds the merge now is narrower than before: the dataset formatter leak (inline on view/dataset_query.rs:676), which the narrowed refusal opened., and the per-query cost the read view adds (about a microsecond on every Fluree::query call, inline on view/query.rs:538). The D6 gate holds only if this PR merges after #2280. The optional items are each small, and I'd rather see them folded in now than lost in the backlog.
Re-review, against my 11-10 review:
- Resolved:
- the unflushed head, with the repair path (M1);
- the every-ledger scan, now opt-in like BM25 (M2a);
- the resident closure (M4b) and the budget override (M5);
- the retry storm, now backoff (M3);
- the serving floor check (M6);
- the crawl: single graph folded in (M7, plus the 11-09 probes re-run);
- the
ed74d85d9class-policy regression, back to base on the box A/B; - #2288; the #2271 merge; the breaking-changes section; the LRU, warn and diagnostics, storage docs,
owl:sameAsretraction test and doc nit.
- Still open: the D6 gate (conditional on merge order); a deterministic failure retried every 5 minutes (optional); the remaining multi-graph refusal is broader than the leak (optional); a criterion bench for query-time policy filtering.
- New: the dataset formatter leak (blocking); the repair trigger's breadth, the formatter's
db/policyprecedence, three fix hunks no test pins (M2b, M4a, M8), the #2271 WARN/docs and the stale body line (optional). - Not re-raised: the optional items you left out (the positive registration cache and
strictshort-circuit, lazyasOfwalk, retraction shortcut,GcLocks,DerivedFactsHandle, serving-decision consolidation). Your reason on the registration cache is right, given the floor check.
Adherence to repo commitments:
- Patterns/abstractions:
⚠️ The read state onQueryResult, preferred byformat_results_async, is the shared chokepoint the class needed for single-view rendering, and Cypher now goes through the serving path; the public dataset formatter is still outside it, which is where the leak below comes from. - Performance (speed first, memory second): ✖ CRITICAL: this commit adds about 1 µs to every
Fluree::querycall (a point lookup +4 to 5%), mostly from the read-view clones. Otherwise the picture is good: the class-policy regression is gone (release: base 122.3 to 124.9 ms, head 121.7 to 124.6), queries of a millisecond or more are flat, and served queries are far faster. Query-time OWL 2 RL under a class policy stays about 12% slower (release 293.2 to 306.9 → 332.8 to 337.7 ms), the reasoned-view price that comes with the policy contract we agreed on. - Deployment targets:
⚠️ Sharedfluree-db-apicode. The delta helps the short-lived-host case: maintenance is explicitly opt-in, closures aren't retained, and the repair guard is persisted in the manifest rather than held in memory. N1 is an embedder-only exposure; #1635 (cross-process GC) unchanged and listed.wasm32/wasm-smokegreen on this SHA. - Testing:
⚠️ Every fix carries a test, and seven of ten mutations went red. The worker's uncached call site, the server's spawn gate and the merge's pair-lane guard are unpinned (each mutation stayed green), and N1 needs a test that formats one result through both formatters. - Conventions: ✔ The body now has storage-cost and breaking-change sections and the docs a Rust API migration section. Two small updates: the
format_results_asyncdoc comments now contradict the read-view precedence, and the body's #2271 line is out of date since5618e1d84.
Claude verified on a clean EC2 box at this SHA: re-review probes (4 + 1 passed, it_zz_rv2292b.rs, it_zz_rv2292c.rs); ten mutation checks of the fix hunks (seven red, three green as described); the delta's own tests (grp_query_reason, grp_reasoning, it_batched_pair_join, the reasoning_index lib tests, server routes and config); the review probe A/B over 32acd8986, 3b2a385bc, 20196e8b0, 369f5e92d and this SHA (five non-LTO rounds, plus five release-build rounds of base vs head), a point-lookup bisect over the PR's commits, and a GraphDb clone micro-probe; CI run 43139008175 green on this SHA.
| // Hydration currently retains one graph's policy and read state. | ||
| // With multiple graphs, that cannot safely enforce each graph's | ||
| // derived-class policies. Refuse before serving or reasoning. | ||
| if dataset.any_non_root_policy() |
There was a problem hiding this comment.
Blocking (policy). A one-graph dataset now gets past this refusal, but the public dataset formatter still hydrates from each member's stored state under its stored-class policy. A crawl formatted that way shows a member that a derived-class deny hides from the rows.
The refusal lets a restricted reasoning crawl through when the runtime dataset has one default graph and no named graphs (:676-692). The premise in the comment is that hydration "retains one graph's policy and read state". with_dataset_read_view does put it on the result, and format_async_for_view(primary) uses it. But format::format_results_async_dataset hydrates through hydration::format_async_dataset → DatasetCtx::build (fluree-db-api/src/format/hydration.rs:853-913). That builds its views from the DataSetDb it's handed, each with the member's own overlay and its non-reasoned policy, and never reads result.read_view. At 3b2a385bc the same request was a 400: build_executable_for_dataset passed any_non_root_policy() into the shared refusal in apply_reasoning_to_executable. So this is new in 20196e8b0.
Claude reproduced it on the head SHA with a review-only test (it_zz_rv2292c.rs). The ledger has ex:salary rdfs:domain ex:Earner and ex:ann a ex:Student; ex:salary 250000, and the view denies f:onClass ex:Earner (a class ann has only by derivation).
- Under
owl2rlthe rows hide ann:[]. select {"ex:ann": ["*"]}formatted withformat_async_for_viewrenders[{"@id":"ex:ann"}], for the single view and the one-graph dataset alike.- The same
query_dataset(&DataSetDb::single(view), …)result formatted withformat_results_async_datasetrenders[{"@id":"ex:ann","@type":"ex:Student","ex:name":"Ann","ex:salary":250000}].
As far as I can tell this isn't reachable over HTTP: the connection path sends a one-graph spec through the single-view lane (query/connection.rs:171-206), and history mode refuses reasoning. So the exposure is an embedder calling the public formatter on a one-graph DataSetDb.
Either fix seems small: (a) format_results_async_dataset delegates to format_results_async against the primary when result.read_view is set and the dataset has one graph; or (b) DatasetCtx::build uses the read view for the primary member when the result carries one. A test that formats one result through both entry points would pin it. Commenting here because format/hydration.rs isn't in this diff.
| db.binary_graph(), | ||
| )) | ||
| ) | ||
| .with_read_view(db, None)) |
There was a problem hiding this comment.
Blocking, CRITICAL (performance). This commit adds about a microsecond to every Fluree::query call, roughly 4 to 5% of a point lookup, and the two GraphDb clones that build read_view account for much of it.
plan_and_execute_round now returns an owned read view, db.clone() when nothing was served or reasoned (:1601). with_read_view(db, None) here then clones it again into the result (query/mod.rs:376-388), and both copies are dropped with the result. A GraphDb clone isn't just refcount bumps: default_context (a serde_json::Value), reasoning (ReasoningModes, rules as JSON) and resolved_config are deep fields, so the cost grows with the ledger's config. Claude measured 96 to 99 ns per clone on a ledger with no default context.
Claude timed a root point lookup on a box with the review probe: {"@id": "ex:p17", "ex:name": "?n"} through query_from().jsonld(…).execute_formatted(), on a 50k-person indexed ledger with novelty, 4,000 reps a round, three rounds.
- Non-LTO:
32acd898624.9 µs,3b2a385bc25.0 to 25.4,20196e8b026.0 to 26.1, the head 25.7 to 26.3,next24.6. So the step is this commit, not the merge. - Release build (fat LTO), five rounds: base 23.5 to 23.8 µs, head 24.8 to 25.1.
- Moving the owned read view into the result instead of cloning it here (one clone fewer) measured 25.5 to 25.8 µs on the head.
- Queries of a millisecond or more are flat.
We may want to move the owned read view into the result rather than clone it, and keep read_view cheap to hold: a small struct of the Arcs formatting needs (snapshot, overlay, t, graph id, policy, binary store), or an Arc<GraphDb>, rather than a whole GraphDb. A criterion case for a single-subject lookup through Fluree::query would keep this honest going forward.
There was a problem hiding this comment.
Addressed in a0f7fc6. The result holds a ReadView of shared handles, moved in. Not re-measured; query_hot_point_lookup is the criterion case.
| Ok(generation) => generation, | ||
| Err(error) => { | ||
| self.reasoning_index_state.warn_serving(ledger_id, &error); | ||
| self.reasoning_index_state.request_repair( |
There was a problem hiding this comment.
Optional (performance). Any serving error now marks the head generation for repair, and a repair is a full recompute at the same commit with the chain detached. Some of those errors say nothing about the head.
try_servable calls request_repair(…, &published.manifest, …) when as_of_generation fails (:190) and when loaded_generation fails for any candidate (:213). The next refresh takes needs_repair as proof that the head is broken (build.rs:547-555): previous becomes None, the closure is computed in full, and publish_generation drops prev_manifest and arms reclaim_not_before_ms (build.rs:1296-1301).
Three of the triggers aren't about the head at all. as_of_generation also fails when Line::walk can't read a commit envelope. In asOf mode the candidate that fails to load can be an older retained generation, released between index_generations and loaded_generation, yet the repair is requested for entry.head. And on S3, a throttled or timed-out GET is an error like any other. load_previous(…).is_err() on the refresh side (build.rs:548) is just as broad.
So one S3 timeout on a commit read during an asOf query marks a healthy head. The next refresh recomputes the whole closure, which on the 11-09 review ledger (10.5M derived facts) took 216,734 ms at 15,498,600 kB peak RSS, for a program whose budget allows it. It also drops the retained chain, so asOf queries at older commits fall back to query time until generations accumulate again.
We may want to request repair only for the head's own manifest (manifest_id == head.manifest) and only when the file is actually absent. index_generations already tells released from unreadable with store.has(&id) (fluree-db-indexer/src/gc/reasoning_indexes.rs:54). Alternatively, the refresh could re-validate a hinted head (load_previous plus the root's dictionaries) before rebuilding, rather than trusting the hint. Minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
| policy: Option<&fluree_db_policy::PolicyContext>, | ||
| tracker: Option<&Tracker>, | ||
| ) -> Result<JsonValue> { | ||
| let db = result |
There was a problem hiding this comment.
Optional (API contract). This is more of a question than a suggestion. format_results_async now formats against result.read_view and that view's policy whenever the result carries one (:587-596), and every view query now sets one (with_read_view(db, None), view/query.rs:538 and the other entry points). So the db and policy a caller passes no longer decide anything for a result a view query produced.
For to_jsonld_async(db) (query/mod.rs:689), which used to hydrate unfiltered, that's the right fix for the hydration-bypass class #1935 chased. But to_jsonld_async_with_policy(db, &narrower) now quietly uses the query view's policy instead of the one passed. And the doc comments here (:578) and on format_results_string_async (:756) still say "When policy is None, no filtering is applied."
Perhaps document the precedence on both functions and on QueryResult::read_view, with a line in the "Rust API migration" section. If you'd rather keep an explicit narrower policy meaningful, the formatter could refuse a policy argument that differs from the view's. Small, but it changes a public function's contract, so I'd rather it land with this PR than be found later.
There was a problem hiding this comment.
Addressed in a0f7fc6 (precedence documented on both functions, to_jsonld_async_with_policy and the migration section).
| These diagnostics are process-local, clear after a successful refresh, and do | ||
| not survive a restart. Rust callers can read `reasoning_index_failures`. | ||
|
|
||
| Maintenance uses the same resolved reasoning budgets as queries: built-in |
There was a problem hiding this comment.
Optional (docs). Your 11-11 note on #2271's memory WARN and the "Memory a cached result holds" docs said both should mention persisted reasoning once this PR and #2271 meet. Since 5618e1d84 merged next (which had taken main), they've met in this branch. ReasoningOps::over_budget's WARN (fluree-db-query/src/reasoning_ops.rs:186-201) and docs/query/reasoning.md:392-420 still list only the limit, the per-query budget and the env var. Adding persisted reasoning there, with your two qualifications (the build and full rebuilds still materialize the closure; use reasoningFreshness: "strict" where in-memory reasoning at query time is unaffordable), seems cheap to do now. Commenting here because neither file is in this diff. Minor, but I'd rather it land with the feature.
|
|
||
| /// Compute maintenance output without reading or retaining OWL or Datalog | ||
| /// closures in the process-wide query cache. Budget precedence matches queries. | ||
| pub async fn compute_derived_facts_uncached( |
There was a problem hiding this comment.
Optional (testing). maintenance_bypasses_and_does_not_replace_owl_or_datalog_cache_entries pins compute_derived_facts_uncached itself (Claude reverted it to the cached path on the head SHA and it went red, good). Nothing pins that the worker calls it, though. With complete_closure's call (fluree-db-api/src/reasoning_index/build.rs:1138) swapped back to the cached compute_derived_facts, all 36 reasoning_index lib tests and the 51 it_reasoning_indexes tests still passed.
A refresh-level assertion would keep the resident-closure problem (about 1.9 GB per closure on the 11-09 ledger) from coming back through a one-word change: no global_reasoning_cache() entry for the worker's key after a refresh, or a sentinel left untouched like your unit test. Commenting here because build.rs isn't rendered in this diff. Minor, but I'd rather it land with the fix it guards.
| // Reasoning indexes are built where writes publish: here when this | ||
| // server owns its ledgers, on the leader under Raft (spawned with | ||
| // the leader's tasks), never on a peer. | ||
| let reasoning_indexes_task = (self.state.config.reasoning_index_auto_refresh |
There was a problem hiding this comment.
Optional (testing). Same shape, smaller stakes: reasoning_maintenance_is_opt_in pins the flag's default, but not the gate. Claude removed reasoning_index_auto_refresh && here and the if at :914 on the head SHA, and all 232 fluree-db-server lib tests and both reasoning_indexes_routes tests still passed. A server built from ServerConfig::default() asserting no reasoning-index task (or the Raft leader's task list without it) would cover both sites. Minor and non-blocking; if you agree, I'd rather see it folded in now.
There was a problem hiding this comment.
Addressed in 9586416. Both sites now go through reasoning_worker_owner, which the test covers per consensus mode and role.
| // provenance, which only the per-row path stamps. | ||
| && !(ctx.eager_materialization && ctx.is_multi_ledger()) | ||
| // The pair lane does not decode what it emits. | ||
| && !(ctx.eager_materialization && self.batched_pair_eligible) |
There was a problem hiding this comment.
Optional (testing). The merge resolution here looks right to me. It keeps #2271's deferred overlay plan, leaves the pair lane per-row under eager materialization, clears batched_pair_objects on reroute (:2247) and adapts ReasoningOverlay to the Base enum. Thanks for taking that on in the merge itself.
One gap, though. Your 11-11 note said the merge needs a matching test in it_reasoning_batched_probe: a datalog rule head built from a pair-lane binding. Claude deleted this guard on the head SHA, and the four it_reasoning_batched_probe tests and the seven it_batched_pair_join tests still passed. So nothing today notices if a later change lets the pair lane under eager before it decodes. I'd rather that test come with the merge that introduced the guard than wait for the change that removes it.
There was a problem hiding this comment.
Addressed in 71cc943. Deleting this guard alone changes nothing: lane admission already declines the pair lane for an eager caller with an overlay, since it is not listed in batched_lane_output. The test goes red when the lane is admitted under reasoning.
| retry_at: Instant, | ||
| } | ||
|
|
||
| fn retry_delay(attempts: u32) -> Duration { |
There was a problem hiding this comment.
Optional (performance), narrowed from the 11-10 blocker. The backoff closes the retry storm I flagged, and maintenanceFailures makes it visible, thanks. One residual: a failure that's deterministic for its inputs is retried every 5 minutes forever once retry_delay reaches its 300 s cap (:29-34). That covers a capped closure, "derives hierarchy edges" and a missing reasoned graph, and each retry recomputes the closure up to the budget though nothing it depends on changed. With maintenance now on the query budgets (1M facts and 30 s unless something raises them), "a large ledger with a program that sets no budget" is exactly that case.
The memo I suggested, keyed on (revision, basis, settled, engine), would skip those retries until an input changes. It keeps your "commits don't reset backoff" property if a new basis lifts only the memo, not the backoff. Minor and non-blocking, but if you agree it's right, I'd rather see it folded in now.
|
|
||
| // A union is a multi-graph dataset even when the caller supplied one | ||
| // view. Hydration cannot yet retain each member's reasoned read state. | ||
| if !db.is_root() |
There was a problem hiding this comment.
Optional (behavior). Thanks for folding the single-graph part of #2287 in. Claude re-ran the 11-09 crawl probes on 5618e1d84, and all three now hold:
- the root crawl renders
["ex:Person","ex:Student"]both before and after the index is published; - a property-only policy's crawl runs under
rdfs,owl2rland no reasoning, withex:ssnhidden; - an
rdfs-defaults ledger's restricted crawl runs.
The remaining multi-graph refusal (here and dataset_query.rs:676-679) still keys on has_any_enabled(). So it also fires under rdfs alone, and for policies with no f:onClass or f:query condition, where rendering stored state can't let a derived-class deny through. Same narrowing as before, on a much smaller surface now. Minor and non-blocking; if you agree, I'd rather see it folded in now.
There was a problem hiding this comment.
Left as is. Narrowing loosens a refusal that guards a policy leak, for a small remaining surface; #2287 stays open for multi-graph crawls.
next brought TTL, history retention and permanent erasure (#2280). Beyond taking both sides: - Content kinds: both branches numbered a new kind 21. The retention schedule keeps it; the reasoning manifest and derived-facts kinds are 22 and 23. - Raft state machine: both appended to positionally encoded types. The reasoning-indexes state field, PushReasoningIndexes and its two responses now follow the erasure ones, and a third snapshot shape reads a snapshot taken with erasure state and before reasoning indexes. next's damaged-snapshot tests cut into the erasure state: the last byte of a snapshot is now the empty reasoning-indexes map, and cut alone it leaves a whole snapshot of the layout before. - Drop and restore keep each branch's config and its reasoning-indexes document. A drop reads no reasoning-indexes document for a branch no request can name (a legacy branch beginning with `/`). - A view carries its commit id and its fence and erasure generation; the query path runs the reasoning refusals and the removed-history check.
…h an erasure reached A reasoning index is a second copy of a branch's facts, in generations of its own, and keeps alive the shared dictionaries they name. The purge of an erasure rewrote the branch's index and released its dictionaries, and knew nothing of them: with an index registered, three dictionary files still held an erased value while the job read purged. An index already kept an erasure floor that publication and serving refuse generations below, and nothing raised it or gave a generation an epoch but zero. Now: - A generation is of the epoch its index's floor stood at when its build began, read before the state it is computed from. - A purge raises the floor of every index of each holding branch, unpublishes its head and deletes its generations, holding builds off meanwhile. A build begun before publishes nothing; the sweep that follows releases the dictionaries only they reached; the next refresh builds each index again from the branch as it now reads. - A dropped holder's saved documents lose their heads and its `@reasoning` folders go with its indexes, to be built after a restore; a frozen branch's files are deleted. - A member's cleanup after a purge drops the generations it had loaded.
A generation holds every fact its basis held. A query of the current state under `asOf` could be answered from one built before a targeted removal, which read the removed value back as current for as long as no newer generation was published. Such a generation is now skipped, as one built before a graph drop is, and the query reasons at query time.
Any error serving from an index marked its head for repair, and the next refresh took the mark as proof: a full recompute at the same commit with the retained chain detached. A commit that did not read under `asOf`, an older generation released between listing and loading, or a storage timeout said nothing about the head. A head is now repaired at once only when its manifest or root is absent or does not decode. A head a query could not load is read again by the refresh and repaired only if that fails too. A refresh that cannot read a file still in place fails and is retried, instead of computing the closure from nothing.
…uery read A restricted reasoning crawl of a one-graph dataset is no longer refused, on the ground that hydration keeps the query's read state. The dataset formatter did not: it rebuilt each member's view as stored, under the policy judging stored classes, so a crawl formatted through it showed facts a derived-class deny had hidden from the rows. It now formats a one-graph result as the single-view formatter does.
… copy of the view Every view query cloned its `GraphDb` twice to put the read view on the result: once out of the round and once into the result. A `GraphDb` clone copies the default context, the reasoning modes and the resolved config, so the cost grew with the ledger's configuration and was paid by every query, a point lookup included. The result now holds a `ReadView`: the snapshot, overlay, policy and store handles reading takes, moved into it. Typed Cypher formatting, which needs a whole view, builds one only when the result read a state other than the view it is formatted with. The async formatters' doc comments said a `None` policy filters nothing. They now say what happens: a result that carries a read view is formatted from it under the policy that judged its rows, and the `db` and `policy` arguments decide only for a result without one. Adds `query_hot_point_lookup`, a criterion case for one subject's one property through the query entry point, where a per-query cost shows.
The merge with the batched lanes left the pair lane off under eager materialization, and nothing noticed if a later change admitted it. A rule whose body closes a typed triangle, with asserted and derived closing edges, now pins the facts it derives and that the lane does not run; the same triangle without reasoning shows the fixture reaches it.
The unit test pins that the uncached closure bypasses the cache, and nothing pinned that maintenance calls it: with the refresh back on the cached path every reasoning-index test still passed, and each closure it computed stayed resident with no reader. A refresh of an OWL 2 RL and of a datalog index now asserts the ledger has no cache entry, and a query-time run of the same reasoning shows the check sees one. `ReasoningCache::holds_ledger` reads one ledger's entries, since entry counts race against whatever else shares the process-wide cache.
Both spawn sites read the flag inline, and with either check removed every server test still passed. The decision now goes through the owner function BM25's worker uses, which both sites consult and a unit test covers for each consensus mode and role.
…again until one changes Once its backoff reached five minutes, a failing index was recomputed every five minutes for good. For a closure over its budget, or a program whose output an index cannot hold, that is the same closure with the same outcome each time, up to the budget. A refresh now records what it computed from when it fails because of that: the registration revision, the basis, what the program settled to and the engine version. Maintenance settles the program, which is cheap, and skips the closure while those are unchanged. A commit lifts the record without resetting the backoff. An explicit refresh retries now.
… as a way out The warning a batched lane logs when a translation would take a cached reasoning result past its memory limit, and the docs section on what a cached result holds, listed the limit, concurrency and narrower rules. A reasoning index is the other option now that both are in one branch: queries answered from it hold no result in memory. Both say what it does not change: a build still computes the closure in memory, and a query no generation answers reasons in memory unless it is `strict`. Drops the note on integrating the batched lanes, which are merged.
…left Only the maintenance worker deleted a retired index's files, and the worker is off unless a server asks for it. On every other deployment a retired index kept its generations, and the dictionaries only they reached, for good. The refresh a caller asks for a branch now cleans up the indexes retired longer ago than the retention window, as the worker does.
…in its references The page had grown by accretion: maintenance, retries, budgets and build modes sat under "Registering a program", and storage was covered twice, once as "about one more index of the branch" and once as "several times" its size. It is now laid out by what a reader comes for: registering, keeping an index current (what a refresh reports, automatic maintenance, incremental and full builds, budgets and memory, failures), which queries an index answers, freshness, storage, erasure and removal, upgrades. Says what it left out: registering builds nothing, automatic maintenance is off by default, a full build holds the closure in memory, an index holds at most 32 superseded generations in its retention window before a refresh is throttled, and `strict` waits ten seconds. Drops a note about rebuilding generations of earlier engine versions, which no release wrote. Adds the four routes to the API reference and the server flag to the configuration reference, which had neither, and the `index` block to the `x-fdb-reasoning` header's entry. The query-time page links here from its budget section, where `exact` turns a capped answer into an error, and from its related pages.
…e prover TTL, f:noHistory, targeted removal and permanent erasure each had a reference page and no account of when to use which, no worked examples, and no operator's guide to the prover. New pages: - concepts/data-lifecycle.md: where a committed value lives, how far each feature reaches, how to choose, and how to set a ledger up for erasure. - guides/cookbook-retention.md: sessions, leases, deadlines, transaction and property lifetimes, f:noHistory, targeted removal, and reading the retention status. - guides/cookbook-erasure.md: one erasure from prover install to purge, with variations (a whole subject, signed commits, clusters, clones) and a troubleshooting table. - operations/erasure-prover.md: installing, checking, sizing and isolating the prover, a dedicated proving node, and upgrades. The reference pages gain a "when to use it" section and links to the guides. history-retention.md now says which historical reads a removal refuses: a read with a variable predicate, a graph crawl, a Cypher query or reasoning is refused at any point a removal covers, for every subject, which the page had described as answered for a different constant subject. configuration.md lists the --erasure-* flags and their environment variables, docker.md the -erasure image, and vocabulary.md the f:erasure* txn-meta predicates. The time travel cookbook and retractions.md no longer say history cannot be deleted.
Summary
Materialized reasoning persists query-time reasoning. You register a reasoning program on a branch, and an opt-in background worker keeps a reasoning index for it: a complete branch index holding the asserted facts plus the program's derived facts at one commit. Reasoning queries that match the program are then answered from the index like ordinary queries. Nothing is re-derived on restart, and no reasoning budget caps the answer. Query-time reasoning remains the fallback for any query an index cannot answer exactly.
User docs:
docs/query/materialized-reasoning.mdanddocs/cli/reasoning-indexes.md; the routes are indocs/api/endpoints.mdand the server flag indocs/operations/configuration.md.What's included
Registration and serving
register_reasoning_index), admin HTTP (/v1/fluree/reasoning-indexes/*) andfluree reasoning-indexes. A branch can have at most eight active indexes.defaultfalls back to query time;exactrejects incomplete fallback results;strictwaits for a matching complete generation;asOfanswers from the newest eligible retained generation, on one coherent snapshot. A generation built before a graph drop, or at a commit a targeted removal covers, is not eligible.ENGINE_SEMANTICSis part of the match key. A generation built under another version is not served or seeded from; it is rebuilt at its own commit.Maintenance
--reasoning-index-auto-refresh,FLUREE_REASONING_INDEX_AUTO_REFRESH=true, orserver.indexing.reasoning_index_auto_refresh = true. Explicit refresh works in either mode. The worker runs standalone and on the Raft leader, uses a coalescing FIFO queue, polls known indexes every minute and reconciles all ledgers at startup and every 15 minutes.maintenanceFailures.Storage, publication and lifecycle
asOfskips generations a removal reaches.Policy-restricted callers
strict. The generation applies the caller's policy and enforcer per request; the shared loaded generation is never modified. A dataset with any restricted member is served member by member under each member's own policy.asOfagainst an older generation falls back to query time.f:queryconditions see derived facts in a reasoning query, whether served or reasoned at query time.unionDefaultGraph, are refused. Typed Cypher nodes (BoltRETURN n) render the query's reasoned state.Reasoner and policy fixes found along the way (each with a test that fails without it)
owl:sameAsnow gives every member of an equality set every fact, not only the set's representative.ENGINE_SEMANTICSis now 4 so older generations rebuild.f:onClassderived-class deny leak and a class-cache collision. Class lookups are keyed on the index root they read. Class-prefetch clones and sorts only cache misses and caches completed empty lookups.General query and policy performance (benefits queries without reasoning indexes too)
rdf:typeclass lookups read only the leaves holding the subjects asked for, not the whole id range between them. Served LUBM Q9 under a derived-class deny: 23.8 s → 4.6 s.rdf:typekeeps the class-scan fast paths. Previously every schema predicate counted as covered.Timings are LUBM-25 on an m7a.4xlarge with
/dev/shm, warm medians, A/B against the parent commit, and predate the review fixes.query_hot_point_lookupis a new criterion case for what every query pays at the entry point.Known limits
rdfs:subPropertyOflose their language tag (owl2rl: literals derived through rdfs:subPropertyOf lose their language tag, and values that differ only by language merge #2273, pre-existing; shared with query-time reasoning)./dev/shmonly. Not yet measured: durable disk, remote backends, several indexes, sparse programs, concurrent load.Storage cost and breaking changes
Each program persists a full merged branch index plus a separate derived-only set; derived facts are stored in both, and retained generations add further cost. Storage can be several times the asserted branch size, and maintenance work scales with active programs (up to eight).
For Rust embedders:
ReasoningIndexesLookupandReasoningIndexesPublisher; these required interfaces have no default implementations.Fluree::run_stream_querydrops its formerLedgerStateargument.QueryResult,ReasoningTally, andReasoningManifesthave new public fields.QueryResult::read_viewretains the state a single-graph query read, as aReadViewof shared handles rather than a copy of the view. The async formatters format a result that carries one from that state under the policy that judged its rows, in place of thedbandpolicythey are passed; apolicyargument still applies to a result whose query ran under none.ReasoningManifest::reclaim_not_before_mspersists a repair's reclamation deadline.Partially addresses #2287 — single-graph hydration is handled; restricted multi-graph hydration remains unsupported.
Fixes #2288
Follow-up: #2289
Follow-up: #2290
Follow-up: #2291