Skip to content

feat(query): opt-in query-result cache keyed on ledger state - #2403

Merged
bplatz merged 14 commits into
mainfrom
feat/query-result-cache
Nov 18, 2026
Merged

bplatz merged 14 commits into
mainfrom
feat/query-result-cache

Conversation

@bplatz

@bplatz bplatz commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

This PR brings back v3's opts.cache as an opt-in query-result cache. It is stacked on #2401.

Nothing is cached unless the request asks for it:

  • the Fluree-Cache: true header (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, or bypass; reason="…". A hit's body is byte-identical to the uncached response.

Key

v3 keyed on t. That isn't enough here:

  • a dropped and recreated ledger restarts at t 1;
  • a staged view reuses t+1;
  • a rebase can return a branch to an earlier t with different commits.

The key uses a state token instead. It is made of the ledger id, the view t, the snapshot t, the index root id, and the overlay's content_version(). That last one comes with a contract: two overlays with different contents never report the same version, and None means 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:

  • the request: SPARQL text or JSON-LD, minus opts.cache, meta and max-fuel;
  • the formatter config;
  • the default context;
  • the QueryExecutionOptions flags, and the executable's union-default-graph setting;
  • the effective policy, via 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_view and before execution, so next's per-request read checks (410 / 503) still run on a hit. query_with_options is split into lower_view_query and run_lowered_view_query. The second half takes a before_execute check 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_values and shortest-path filters. It bypasses:

  • RAND(), NOW(), TODAY, UUID(), STRUUID(), and BNODE();
  • remote or variable SERVICE;
  • BM25 search, vector search, and R2RML.

The API layer also bypasses:

  • graph-source views;
  • reasoning;
  • f:query policy and cross-ledger governance;
  • agent-JSON output;
  • pinned ledger times;
  • FROM datasets.

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 of cache_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.

  • Default: 10% of cache_max_mb. 0 disables result caching, and requests that ask report bypass; reason="result cache disabled".
  • Entry cap: one answer may take at most 1/16 of the pool. Each entry is charged an estimated 128 B overhead on top of its bytes.
  • Superseded states: answers for a state no longer read are never looked up again, so they age out of the LRU. There is no per-ledger bookkeeping.
  • Visibility: once the pool exists, the server's once-a-minute cache stats log adds a Query result cache stats line.

The setting is available everywhere settings are taken:

Channel Name
Rust FlureeBuilder::query_result_cache_max_mb, ServerBuilder::query_result_cache_max_mb
Server flag / env --query-result-cache-max-mb / FLUREE_QUERY_RESULT_CACHE_MAX_MB
Config file query_result_cache_max_mb under [server] (TOML or JSON, profiles included)
JSON-LD connection config queryResultCacheMaxMb on the Connection node (accepts ConfigurationValue)
JSON connection config cache.queryResultMaxMb

Proxy-storage peers apply it too. They still ignore cache_max_mb and disk_cache_max_mb, which is a pre-existing gap this PR does not change.

Coverage

This PR covers:

  • the ledger route (/v1/fluree/query/{ledger}): SPARQL JSON, XML and graph formats, and JSON-LD;
  • ViewQueryBuilder's formatted terminals.

Not yet covered:

  • the connection-scoped route and FromQueryBuilder, which includes datasets;
  • CSV/TSV;
  • Cypher, GraphQL and multi-query;
  • GraphQueryBuilder;
  • over HTTP, requests with an identity or policy inputs, SPARQL FROM, and graph-source aliases (they execute with no x-fdb-cache header);
  • proxy-storage peers' query paths (JSON-LD is answered from the cache with no header; SPARQL is not cached);
  • single-flight for concurrent identical misses.

User docs: docs/query/result-cache.md, the header in docs/api/headers.md, and the budget in docs/operations/configuration.md, docker.md, reference/connection-config-jsonld.md and getting-started/rust-api.md.

Breaking changes

  • fluree_db_connection::CacheConfig gains a public query_result_max_mb field, so code that builds it with a struct literal no longer compiles. Use CacheConfig::with_max_mb or Default, 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. On next it should also cover instance_bits, fence, erasure_generation and the head commit_id. Reasoning stays bypassed until the key can carry the reasoning-index generation that produced the answer.

Follow-up: #2443

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.
@bplatz bplatz added enhancement New feature or request area:query Query execution, planning, fast paths, overlay, result formatting performance Performance improvement (release notes: Performance) labels Nov 14, 2026
@bplatz
bplatz requested a review from a team November 14, 2026 19:35
…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.
Base automatically changed from fix/query-constant-bind-seeds-scan to main November 17, 2026 03:13

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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, and view_state here. 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 the GraphDb method in the view_state comment 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 main alone with git merge-tree and 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 to main on their own (fluree-db-query/src/join.rs). This head merges cleanly with current main, and it doesn't conflict with my #1887 (they share only fluree-db-api/src/lib.rs, which auto-merges).
  • Performance, for the record. Release A/B on a c7i.4xlarge, base 873262d6a vs 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-query Boxes 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. CacheConfig gains a public query_result_max_mb field (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 from nextest, and nothing in it is the PR's: 16,188 passed, 5 aws_testcontainers_test timeouts 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 on main and 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_options with a monomorphized before_execute hook rather than a parallel query path, reuses the moka / wasm_cache pool 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-api code; 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 the wasm_cache stand-in and the gate run's wasm32 clippy and runtime smoke pass.
  • Testing: ⚠️ unit and integration tests run (grp_query in 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.

Comment thread fluree-db-api/src/query/result_cache.rs Outdated
/// 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> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 862366c

Comment thread fluree-db-query/src/ir/result_cache.rs Outdated
Function::Uuid => Some("UUID()"),
Function::StrUuid => Some("STRUUID()"),
Function::Bnode => Some("BNODE()"),
_ => None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in cafd429

return Ok(with_result_cache_header(response, result_cache.as_ref()));
}

// AgentJson: execute with agent-optimized envelope format

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in eebecde

Comment thread docs/query/result-cache.md Outdated
[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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional (docs).

Two things the page says that don't match what the server does:

  1. Over HTTP, an identity- or policy-scoped request never reaches the cache: JSON-LD with an identity or policy in opts goes 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.
  2. 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_policy hashes 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in f82963c

return Ok(delimited_response(bytes, fmt));
}

if fluree_db_api::jsonld_requests_result_cache(query_json) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 87b0798

/// 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() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 7e747f5

Comment thread fluree-db-api/src/query/result_cache.rs Outdated
result: Box::new(result),
insert: None,
};
let mut h = Xxh3::new();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 8538192

h: &mut H,
) -> std::result::Result<(), &'static str> {
use std::hash::Hash;
let Self {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

bplatz commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

On the review summary:

cache_max_mb stops being the cache ceiling … the intended default?

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.

Fluree-Cache: true / x-fdb-cache … the names we ship?

Yes. Fluree-Cache matches the fluree-* request headers, and x-fdb-cache the existing x-fdb-* response headers (x-fdb-fuel, x-fdb-time, x-fdb-policy, x-fdb-reasoning, x-fdb-warning). Moving that family off X- would be its own change.

max-fuel now bounds work rather than answers … intended?

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.

One read-state token for derived caches

Follow-up: #2443

CacheConfig gains a public field

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.
@bplatz
bplatz merged commit a1d677a into main Nov 18, 2026
21 checks passed
@bplatz
bplatz deleted the feat/query-result-cache branch November 18, 2026 13:33
bplatz added a commit that referenced this pull request Nov 18, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:query Query execution, planning, fast paths, overlay, result formatting enhancement New feature or request performance Performance improvement (release notes: Performance)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants