Repository navigation
feat(query): opt-in query-result cache keyed on ledger state - #2403
Conversation
A request that asks (Fluree-Cache: true, JSON-LD opts.cache, or ViewQueryBuilder::result_cache) is answered from formatted bytes stored in the shared leaflet cache pool. The key is the ledger state the query reads (ledger id, t, index root, overlay content version) plus the request, format, default context, execution options and effective policy, so a commit, reindex or recreated ledger never hits an old answer. Queries whose answer depends on more than that state bypass: volatile functions, remote or variable SERVICE, graph sources and search, reasoning, f:query or cross-ledger policy, agent JSON and FROM datasets. Responses that asked carry x-fdb-cache: hit | miss | bypass.
…g the format A byte-budgeted Agent JSON format turns on deterministic scans, which the execution options read from the builder's format. The result-cache terminals took the format first, so paged Agent JSON ran with nondeterministic graph-source scans even uncached. formatted_answer now derives the options and then takes the format itself.
Cached answers move out of the shared leaflet pool into a pool of their own, sized by query_result_cache_max_mb and added on top of cache_max_mb, so they never take index cache from ordinary queries. The pool is built on the first opted-in lookup: a process that never opts in allocates nothing. The default ceiling is 10% of cache_max_mb; 0 disables result caching. Entries for superseded ledger states age out of the LRU, replacing the per-ledger key index and its unbounded metadata. The setting is available as FlureeBuilder::query_result_cache_max_mb, --query-result-cache-max-mb / FLUREE_QUERY_RESULT_CACHE_MAX_MB, the config file, JSON-LD connection config (queryResultCacheMaxMb) and JSON connection config (cache.queryResultMaxMb). The lookup now runs inside the planning round, after the executable is built: a miss executes the executable it was keyed on instead of building a second one, and the build stays inside the residency retry loop. A hit on a cancelled or timed-out request fails as execution would.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is really nice: keying on a state token instead of t, with no invalidation, a bypass walk and a lazily built pool of its own, is the design I'd have picked, and Claude's release A/B shows un-opted queries paying nothing measurable.
My reading is that cache_max_mb stops being the cache ceiling: once any client sends Fluree-Cache: true, the process can hold up to another 10% of it in answers, with no operator change. I think that's right, since answers never evict index leaves and nothing is allocated until someone asks, but I'd like your confirmation it's the intended default. The header names and fuel on a hit are below.
One altitude note: view_state is the fifth cache to hand-build its own read-state tuple (#2392's class cache, the GraphQL schema, reasoning and stats caches), and they already disagree on the index root. A shared token type would let this, #2392 and next's port widen once. Not for this PR.
Full review below:
✅ Approve. The state token is the right key, and the bypass walk, the post-build lookup and the lazily built pool all hold up under probing; nothing in the review needs to land before this merges.
Decisions on the record:
My reading is that this adds Fluree-Cache: true and opts.cache as the opt-in and x-fdb-cache: hit | miss | bypass; reason="…" as the report, beside x-fdb-fuel and the rest of that family. I think keeping the family's naming is right (moving responses off X- is a family-wide call, not this PR's), but I'd like your confirmation these are the names we ship.
My reading is that max-fuel now bounds work rather than answers: with opts.cache, a request whose uncached run would fail with "Fuel limit exceeded" gets the cached answer (Claude reproduced exactly that through the Rust API; over HTTP a max-fuel request takes the tracked path and isn't cached). I think that's right, since a hit costs nothing, but I'd like your confirmation it's intended.
Notes:
- Defect class: a derived cache keyed by a hand-picked read-state tuple. Instances: #2392's class cache (
18ad842c4,4cd88fb41,11df1007e), the GraphQL schema cache (aa44d8f7a), the reasoning cache, the store-less stats cache, andview_statehere. The structural direction is one read-state token in core, built by exhaustive destructuring, that every derived cache keys on. Not this PR: the point fix is right here, and theGraphDbmethod in theview_statecomment is the PR-sized step. - Stack and merge order. #2409 (the peer data-integrity fix stacked above this) doesn't depend on it: Claude applied its ten commits onto current
mainalone withgit merge-treeand they're clean, and its diff uses nothing this PR adds. It also deletes the proxy branches the inline proxy note is about. #2404 and #2405 don't apply tomainon their own (fluree-db-query/src/join.rs). This head merges cleanly with currentmain, and it doesn't conflict with my #1887 (they share onlyfluree-db-api/src/lib.rs, which auto-merges). - Performance, for the record. Release A/B on a c7i.4xlarge, base
873262d6avs this head, 24 round medians per row: un-opted point lookups +0.32 to +0.71 µs (+1.4% to +2.9%) and 334-row selects −12 to −23 µs (−1.0% to −2.8%) across two runs, with a control build without the two new per-queryBoxes no faster than head. Both read as layout between the two fat-LTO binaries, and all sit inside the 5% bench budget. Opted in: a miss costs ~3 µs on a point lookup and ~6% on 334 rows; a hit is ~10 µs (it still parses and plans) and 11–15 µs through the bytes terminal at 334 rows. - Breaking change for embedders.
CacheConfiggains a publicquery_result_max_mbfield (fluree-db-connection/src/config.rs:230), so an embedder building it with a struct literal no longer compiles; worth a line under a "Breaking changes" heading in the body. - Gates. CI never ran on this head, so Claude ran CI's jobs at
747990fd5; all are green apart fromnextest, and nothing in it is the PR's: 16,188 passed, 5aws_testcontainers_testtimeouts that pass 9 of 9 on a quiet rerun, and one failure,it_bounded_overlay_translation::warm_whole_product_short_circuits_and_respects_epoch, a pre-existing flake that fails at the same rate onmainand the merge base (46 and 44 of 200 runs, versus 45 here).
Adherence: patterns ✔ · performance ✔ · deployment targets ✔ · testing ⚠️ · conventions ✔ · verification
- Patterns/abstractions: ✔ extends
query_with_optionswith a monomorphizedbefore_executehook rather than a parallel query path, reuses the moka /wasm_cachepool types, and hashes options, format and policy by exhaustive destructuring; the view half of the key is hand-picked (see Notes). - Performance (speed first, memory second): ✔ the un-opted path is touched (every query now goes through
lower_view_query/run_lowered_view_query) and shows no regression attributable to the PR in a release A/B with a no-Box control; nothing is allocated for the pool until a request opts in. - Deployment targets: ✔ shared
fluree-db-apicode; a process-lifetime pool, but its correctness never depends on being shared (the key moves with the state), so separate processes (serverless instances, a fleet of peers) just hit less often; nothing outlives the response; wasm32 uses thewasm_cachestand-in and the gate run's wasm32 clippy and runtime smoke pass. - Testing:
⚠️ unit and integration tests run (grp_queryin both crates) and cover the bypass reasons, commits, recreate, identities, budgets and cancellation; the index root, formatter, default context and union-default-graph dimensions are unpinned (see the inline note on the tests). - Conventions: ✔ self-describing subjects with full bodies; fmt and clippy clean in the gate run; docs updated across headers, configuration, Docker, connection config and the Rust guide, with two gaps (inline on
result-cache.md).
Verified at 747990fd5: Claude ran CI's jobs (fmt, all-features clippy, nextest, doctests, SPARQL W3C, wasm32, wasm smoke, bridge, python wheel), the PR's 14 targeted tests plus 5 review probes on a box, a 7-mutation pass over the key and bypass walk, a two-run release A/B with a no-Box control, and merge-tree against main, #1887 and the stack.
Approving so you can merge when ready, but maybe worth considering a few of these first.
| /// The ledger state `db` reads. A new commit or index build changes it: the | ||
| /// overlay's content version is unique to its contents, and the index root | ||
| /// is content-addressed. | ||
| fn view_state(db: &GraphDb) -> std::result::Result<u128, &'static str> { |
There was a problem hiding this comment.
Optional (altitude).
This is more of a design note than a request. view_state and hash_view pick their inputs out of GraphDb by hand: eleven of its 27 fields, with nothing saying the other sixteen were considered. The three other hashes in this PR destructure exhaustively (QueryExecutionOptions, FormatterConfig, PolicyRestriction), so a new field there is a compile error; a new GraphDb field that changes answers is silent here. Your "Porting to next" already names four (instance_bits, fence, erasure_generation, the head commit_id).
It's also the fifth cache that builds its own read-state tuple: #2392's class cache (widened three times, 18ad842c4, 4cd88fb41, 11df1007e), the GraphQL schema cache (graphql.rs:288-298), the reasoning cache (reasoning_prep.rs:176-193) and the store-less stats cache (stats_cache.rs:270-309). They already disagree on the index root: this PR and the stats cache key on it, GraphQL and reasoning don't. Claude's box probe shows why it matters here: drop, recreate, reindex and reload a ledger and the two states are both t=1, index t=1, content version 0, and differ only in the root.
The class fix (one read-state token in core, built from GraphDbRef by exhaustive destructuring, that every derived cache keys on, including #2392's ClassState::of) is not for this PR. The PR-sized step is: move these field reads into a GraphDb method in view/types.rs (the only place the private fields are reachable) that destructures every field, so the next one has to decide. Minor and non-blocking, but if you agree it's right, I'd rather see that folded in now than lost in the backlog.
| Function::Uuid => Some("UUID()"), | ||
| Function::StrUuid => Some("STRUUID()"), | ||
| Function::Bnode => Some("BNODE()"), | ||
| _ => None, |
There was a problem hiding this comment.
Optional.
The module doc says the walk is "exhaustive over Pattern and Expression, so a new variant must decide here", which holds for those two, but volatile() ends in _ => None over Function. A clock or random function added later (a Cypher timestamp() or randomUUID(), say) would be cached rather than bypassed, and nothing would flag it.
Function::reads_dataset (ir/expression.rs:1280-1290) already lists every variant with no wildcard; matching that here turns the next one into a build error:
Function::Rand => Some("RAND()"),
// …
Function::Bnode => Some("BNODE()"),
Function::Eq | Function::Ne | /* every other variant */ Function::Custom(_) => None,Small, but I'd rather see it in this PR than lost in the backlog.
| return Ok(with_result_cache_header(response, result_cache.as_ref())); | ||
| } | ||
|
|
||
| // AgentJson: execute with agent-optimized envelope format |
There was a problem hiding this comment.
Optional.
The SPARQL agent-JSON branch returns before the result_cache branch and never takes the outcome, so a Fluree-Cache: true agent-JSON request gets no x-fdb-cache at all. The docs list agent JSON under "always execute and report bypass" (result-cache.md:50-51), and that's what the Rust API does (reads_beyond_the_ledger_state_bypass).
Passing the outcome into this builder when result_cache is Some and wrapping the response with with_result_cache_header would make it report bypass; reason="agent JSON", as documented. A two-line fold-in if you agree.
| [result-cache budget](#memory). | ||
| - Any request, when the result cache is disabled (`query_result_cache_max_mb = 0`). | ||
|
|
||
| Tracked requests (`fluree-track-*`, `opts.meta`) and CSV/TSV output are not served from the cache. |
There was a problem hiding this comment.
Optional (docs).
Two things the page says that don't match what the server does:
- Over HTTP, an identity- or policy-scoped request never reaches the cache: JSON-LD with an identity or policy in
optsgoes to the connection path (routes/query.rs:2910-2920), and identity-scoped SPARQL takes its own branch (:3744-3792), so neither is served from the cache nor gets the header. That probably belongs in this "not served" list. - Line 39, "Two identities share an entry only when the same policy applies to both", reads as though identities under the same policy share. They don't:
hash_view_policyhashes the identity itself unless it's unbound (evaluate.rs:130-136), so only unbound requests share. Something like "Each identity has entries of its own; requests without one share."
Minor, but it's the page operators will size hit rates from, so I'd rather fold it in now.
| return Ok(delimited_response(bytes, fmt)); | ||
| } | ||
|
|
||
| if fluree_db_api::jsonld_requests_result_cache(query_json) { |
There was a problem hiding this comment.
Optional (question).
fluree-db-server/src/routes/query.rs:3107-3170 (execute_query_proxy) and :3680-3739 (the SPARQL proxy branch): the body says proxy-storage peers are covered, and the key would be, but at this head a proxy peer is inconsistent. A JSON-LD opts.cache (or the header, which inject_into_opts turns into opts.cache) is served from the cache with no x-fdb-cache, because formatted_answer opts JSON-LD in on its own (query/builder.rs:272); SPARQL on a proxy peer is never cached.
#2409 deletes both proxy branches, so this goes away once it lands. If this PR merges well before it, a docs line saying proxy peers don't report the header yet would cover the gap. Commenting here because execute_query_proxy and the SPARQL proxy branch are not in this diff.
| /// A ledger dropped and created again under its id restarts at `t` 1, so `t` | ||
| /// alone would serve the dropped ledger's answers. | ||
| #[tokio::test] | ||
| async fn a_recreated_ledger_at_the_same_t_misses() { |
There was a problem hiding this comment.
Optional (tests).
Claude ran a mutation pass over the key on a box: removing the index root from view_state fails no test here, while Claude's reload probe, under that mutation, gets the dropped ledger's "Alice" back for the recreated ledger's "Zed". Removing the formatter hash fails only the agent-JSON bypass reason, not a format test. Removing the default context or the union-default-graph switch fails nothing.
This test covers the recreate case only while the novelty is non-empty, which the content version already separates; the case the root guards is the reloaded one. Roughly what Claude ran:
// file-backed: create, insert Alice, reindex, disconnect_ledger, db() -> cached query (miss, hit)
// drop Hard, create, insert Zed, reindex, disconnect_ledger, db()
// both views: t == 1, snapshot.t == 1, overlay.content_version() == Some(0), roots differ
assert_eq!(cached(&fluree, &b, sparql).await, (zed_answer, ResultCacheStatus::Miss));Plus the same SPARQL text under sparql_json then jsonld, and two staged views at the same t followed by the commit of one. I'd rather see those in this PR than lost in the backlog, since they're what pins the key against the next refactor.
| result: Box::new(result), | ||
| insert: None, | ||
| }; | ||
| let mut h = Xxh3::new(); |
There was a problem hiding this comment.
Optional (question).
This is more of a question than a suggestion. The key is an unseeded xxh3-128 digest, and a hit never checks anything beyond it, so a collision serves another request's answer, possibly another identity's (for an embedder with per-user policy views). Accidental collisions are not a real concern at 128 bits; xxh3 just isn't built to resist chosen inputs, and the request text is caller-controlled. Seeding the hasher with a random per-pool value at ResultCache construction would be cheap insurance against precomputed collisions. Not blocking; worth folding in if you agree.
| h: &mut H, | ||
| ) -> std::result::Result<(), &'static str> { | ||
| use std::hash::Hash; | ||
| let Self { |
There was a problem hiding this comment.
Praise.
Destructuring QueryExecutionOptions with no .. (and FormatterConfig, and each PolicyRestriction) is exactly right: the next field added to any of them has to say whether it keys the cache. This is the shape I'd love the view half to have too (see the note on view_state).
volatile() ended in a wildcard, so a clock- or random-reading function added later would be cached rather than bypassed with nothing to flag it. It now names every Function variant, as Function::reads_dataset does, and a new variant fails to compile until it decides.
The view half of the key picked 11 of GraphDb's 27 fields by hand, so a new field that changes answers would be silently left out. The key now comes from GraphDb::hash_for_result_cache, which destructures every field: each one is hashed, refused, or named as derived from the ledger state or read only under reasoning, and a new field fails to compile until it decides. The index root is hashed as its ContentId rather than formatted to a string first.
hash_input cloned the whole query to drop the opts that only control the cache or tracking, and under preserve_order Map::remove is swap_remove, which reordered the remaining opts. A query opted in by its body and the same query opted in by the Fluree-Cache header, which appends cache last, then keyed differently whenever opts held anything else, and never shared an entry. The query is now serialized straight into the hasher with those opts skipped in place, and opts is left out when nothing else is in it. The SPARQL parameters and the default context are hashed the same way rather than through a Vec, and the view, format and options are keyed before the query text, so a request that bypasses is refused before its largest input is hashed.
A hit is decided by the 128-bit key alone. xxh3 is not built to resist chosen inputs and the request text is the caller's, so an unseeded key left room for a request built offline to collide with another's key, and be served that request's answer, possibly another identity's. Each pool now draws a random seed when it is created and every key starts from it.
Over HTTP, a request with an identity or policy inputs, a SPARQL FROM and a graph-source alias take paths that do not consult the cache, so they execute with no x-fdb-cache header rather than reporting bypass; the page listed them among the bypasses. It also said two identities share an entry when the same policy applies to both, but the key hashes the identity itself: each identity's entries are its own, and only requests without one share.
…ache On a proxy-storage peer the JSON-LD path honours opts.cache (and the Fluree-Cache header that becomes it) without attaching an outcome, so an answer can come from the cache with no x-fdb-cache header, and the SPARQL path never consults the cache. The page now says so.
sorted_sids landed between ensure_ground_identity's doc comment and the function, so the comment documented sorted_sids and ensure_ground_identity had none.
The agent-JSON branch returned before the result-cache branch and never took the outcome, so a Fluree-Cache: true request got no x-fdb-cache header, though the docs list agent JSON as a reported bypass and the Rust API reports it. The branch now passes the outcome and the response says bypass; reason="agent JSON".
Dropping the index root, the output format, the default context or the view's union switch from the key failed no test, and the staged-view case the state token exists for had none either. New tests, each failing with its part of the key removed: - a ledger dropped, created again, indexed and reloaded agrees with the old one on t, index t and content version, and only the index root keeps the old answer from being served; - one query in SPARQL JSON and JSON-LD keeps two answers; - two staged views at one t, and the commit that follows at that t, never share an answer; - views differing only in their default context miss; - a unit test over GraphDb::hash_for_result_cache keys t, the graph, the default context and the union switch.
|
On the review summary:
Yes. Result caching is opt-in and most deployments won't use it, so its budget is additive: answers never take memory from the index cache, and nothing is allocated until a request opts in.
Yes.
Yes, for now: a hit executes nothing, so the cap has nothing to bound. Charging misses more and hits less would first need tracked requests served from the cache, since they are the only ones that measure fuel today.
Follow-up: #2443
Added under "Breaking changes" in the PR body. |
A hit from execute_formatted parses the stored JSON text back into a value. That returns the miss's doubles exactly only while serde_json parses with float_roundtrip; without it, about one in eight computed doubles reads back as a neighbouring double. The test computes 200 of them and requires the hit to equal the miss, so dropping the feature fails it rather than letting hits drift.
Brings #2403, the opt-in query-result cache. Resolutions that were not mechanical: - plan_and_execute_round carries main's before_execute hook and ViewRun (the cache's lookup) and next's ReadView (the reasoned read a result reports), so a round returns ViewRun<(batches, plan, exec, ReadView), T>. The lookup runs after next's serve_from_reasoning_index, on the executable that executes. - The cache key covers next's GraphDb fields, which its exhaustive destructuring requires deciding: instance_bits, the branch fence, the head commit_id, erasure_generation and historical are hashed. - The cache's bypass walk covers next's TermComponents pattern and the SPARQL 1.2 triple functions (none read beyond the ledger state); main's AnnotationTarget pattern does not exist on next. - CacheConfig carries both next's dictionary_max_mb and main's query_result_max_mb, through the builder, the JSON-LD and JSON connection configs, and the server defaults. - it_query_result_cache awaits next's genesis_ledger and names a ledger cache/committed, since next reserves the segment commit.
This PR brings back v3's
opts.cacheas an opt-in query-result cache. It is stacked on #2401.Nothing is cached unless the request asks for it:
Fluree-Cache: trueheader (any query language);"opts": {"cache": true}in JSON-LD;ViewQueryBuilder::result_cache(&outcome)in Rust.A response to a request that asked carries
x-fdb-cache: hit,miss, orbypass; reason="…". A hit's body is byte-identical to the uncached response.Key
v3 keyed on
t. That isn't enough here:t1;t+1;twith different commits.The key uses a state token instead. It is made of the ledger id, the view
t, the snapshott, the index root id, and the overlay'scontent_version(). That last one comes with a contract: two overlays with different contents never report the same version, andNonemeans bypass. Because the token changes with every new state, no invalidation hook is needed. This also covers proxy-storage peers, which see no events.Besides the token, the key includes:
opts.cache,metaandmax-fuel;QueryExecutionOptionsflags, and the executable's union-default-graph setting;PolicyContext::hash_view_policy: identity, default-allow, policy values and each view restriction. Two identities share an entry only when the same policy applies to both.The lookup happens inside the planning round, after
build_executable_for_viewand before execution, so next's per-request read checks (410 / 503) still run on a hit.query_with_optionsis split intolower_view_queryandrun_lowered_view_query. The second half takes abefore_executecheck that sees each round's executable; the uncached path passes one that never answers. A miss executes the executable it was keyed on, and the build stays inside the residency retry loop. A hit on a cancelled or timed-out request returns the same error execution would.Bypass
A query bypasses the cache when its answer depends on more than the ledger state. An exhaustive walk over the IR (
fluree-db-query/src/ir/result_cache.rs) covers SERVICE bodies, subquery modifiers,post_valuesand shortest-path filters. It bypasses:RAND(),NOW(),TODAY,UUID(),STRUUID(), andBNODE();SERVICE;The API layer also bypasses:
f:querypolicy and cross-ledger governance;Storage
Entries hold formatted bytes, never a
QueryResult, which would pin old snapshots. They live in a dedicated LRU pool (ResultCache) with its own ceiling,query_result_cache_max_mb. That ceiling comes on top ofcache_max_mb, so cached answers never take memory from the index cache. The pool is built on the first opted-in lookup, so a process that never opts in allocates nothing for it.cache_max_mb.0disables result caching, and requests that ask reportbypass; reason="result cache disabled".Query result cache statsline.The setting is available everywhere settings are taken:
FlureeBuilder::query_result_cache_max_mb,ServerBuilder::query_result_cache_max_mb--query-result-cache-max-mb/FLUREE_QUERY_RESULT_CACHE_MAX_MBquery_result_cache_max_mbunder[server](TOML or JSON, profiles included)queryResultCacheMaxMbon theConnectionnode (acceptsConfigurationValue)cache.queryResultMaxMbProxy-storage peers apply it too. They still ignore
cache_max_mbanddisk_cache_max_mb, which is a pre-existing gap this PR does not change.Coverage
This PR covers:
/v1/fluree/query/{ledger}): SPARQL JSON, XML and graph formats, and JSON-LD;ViewQueryBuilder's formatted terminals.Not yet covered:
FromQueryBuilder, which includes datasets;GraphQueryBuilder;FROM, and graph-source aliases (they execute with nox-fdb-cacheheader);User docs:
docs/query/result-cache.md, the header indocs/api/headers.md, and the budget indocs/operations/configuration.md,docker.md,reference/connection-config-jsonld.mdandgetting-started/rust-api.md.Breaking changes
fluree_db_connection::CacheConfiggains a publicquery_result_max_mbfield, so code that builds it with a struct literal no longer compiles. UseCacheConfig::with_max_mborDefault, or add the field.Porting to next
The view's part of the key is built in
GraphDb::hash_for_result_cache, which destructures every field. Onnextit should also coverinstance_bits,fence,erasure_generationand the headcommit_id. Reasoning stays bypassed until the key can carry the reasoning-index generation that produced the answer.Follow-up: #2443