Skip to content

Feature/multi query - #1258

Merged
bplatz merged 18 commits into
mainfrom
feature/multi-query
May 31, 2026
Merged

bplatz merged 18 commits into
mainfrom
feature/multi-query

Conversation

@bplatz

@bplatz bplatz commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Adds a new POST /v1/fluree/multi-query HTTP endpoint that bundles multiple independent JSON-LD and/or SPARQL queries into a single request, runs them in parallel under bounded concurrency against one resolved snapshot moment, and returns per-alias results. Adds a matching Fluree::multi_query() builder API in fluree-db-api so downstream Rust consumers can run envelopes in-process. Adds a fluree multi-query CLI subcommand that POSTs envelopes through the same transport surface as fluree query --remote and also supports in-process local execution.

What and why

Today, when a client wants N queries against the same data, they have to either issue N parallel HTTP requests (each doing its own nameservice lookup, snapshot resolution, and cache priming) and then manually coordinate "are these all at the same t?", or pre-fetch a t and pass it in N times. Both are awkward and neither composes with signed requests (you sign each one individually).

POST /multi-query accepts an envelope:

{
  "@context": { "schema": "http://schema.org/" },
  "asOf":     "2024-01-01T12:00:00Z",
  "opts":     { "meta": true, "maxConcurrency": 8 },
  "queries": {
    "alice": {
      "language": "jsonld",
      "query": { "from": "users:main", "select": ["?name"],
                 "where": { "@id": "?p", "schema:name": "?name" } }
    },
    "brian": {
      "language": "sparql",
      "query": "SELECT ?id FROM <orders:main> WHERE { ?o schema:orderId ?id }"
    }
  }
}

The server resolves a single snapshot moment, fans out per-alias dispatch through a JoinSet under a Semaphore, and returns:

{
  "status":  "ok",
  "snapshot": {
    "asOf":    "2024-01-01T12:00:00Z",
    "ledgers": { "users:main": 1042, "orders:main": 87 }
  },
  "results": { "alice": [...], "brian": {...} },
  "tracking": {
    "alice": { "time": "5ms", "fuel": 1024.0 },
    "brian": { "time": "3ms", "fuel": 210.5 }
  },
  "meta": { "fuel_total": 1234.5, "elapsed_ms": 87 }
}

Clients branch on body.status ("ok" | "partial" | "all_failed") for the aggregate; per-alias errors and timeouts land in body.errors. Per-alias telemetry (when tracking is enabled) lives in tracking, mirroring the same time/fuel/policy siblings single-query returns at the top level.

Architecture

The execution surface lives in fluree-db-api — not the server. Anyone with an Arc<Fluree> can run an envelope in-process:

let fluree: Arc<Fluree> = Arc::new(FlureeBuilder::memory().build_memory());
let response = fluree.multi_query()
    .envelope(envelope)
    .bounds(MultiQueryBounds::DEFAULT) // optional
    .execute()
    .await?;

Drop-in mirror of the existing .query_from() builder pattern. Takes &Arc<Self> because the dispatcher fans out into N tokio tasks that each need an owned reference; the server already keeps Arc<Fluree> in its app state, and other consumers wrap once at construction.

Crate layout

Layer Module Concern
fluree-db-api/src/query/multi.rs Envelope types + validation + opts/context merge helpers Pure data + wire shape
fluree-db-api/src/query/multi_snapshot.rs asOf → per-ledger t resolution; per-sub-query from rewriting Pure data + Fluree-borrowed
fluree-db-api/src/query/multi_dispatch.rs JoinSet + Semaphore + deadline select!; builder + Fluree::multi_query() Tokio execution
fluree-db-api/src/query/multi_response.rs Per-alias bucketing + running byte counting Pure data
fluree-db-api/src/query/multi_run.rs run_jsonld_subquery / run_sparql_subquery per-sub-query helpers Pure api delegation
fluree-db-server/src/routes/query.rs::multi_query HTTP handler — auth, header injection, scope check, impersonation gate, delegation Edge auth only

The server handler is ~85 LOC. Everything below the HTTP boundary lives in the api crate.

Envelope contract — design rules

Two rules cover the entire "what shadows what" surface:

  1. Mergeable fields (@context, opts): shallow merge across three layers — envelope opts ⊕ per-sub-query opts override ⊕ query-body opts (i.e. sub.query["opts"]). Body wins, then sub-query opts override, then envelope. This precedence is security-relevant — see "Auth opts merge precedence" below.
  2. Temporal pin (asOf vs any inner @t: / t / SPARQL FROM <ledger@t:...>): collision is a 4xx error, never a silent override.

opts.t is rejected at every level inside the envelope — envelope opts, sub-query opts override, AND query-body opts. The canonical place to pin sub-query time is from; envelope-wide is asOf.

Bounds

Bound Value Override surface
Max sub-queries / envelope 64 request cannot override
Max distinct ledgers / envelope 8 request cannot override
Max concurrent sub-queries 16 opts.maxConcurrency (clamped)
Envelope wall deadline 60_000 ms opts.timeoutMs (clamped)
Per-sub-query timeout min(opts.timeoutMs, remaining) opts.timeoutMs at any layer (body wins)
Response size 64 MiB request cannot override

The non-override values are compile-time defaults (MultiQueryBounds::DEFAULT) and are not server-tunable today.

Auth opts merge precedence (security-relevant)

The dispatcher's three-layer merge is not just an ergonomic detail — it's how the server's impersonation gate keeps a forced bearer identity from being clobbered.

The server handler:

  1. Runs the bearer-or-signed-credential check.
  2. Injects fluree-* headers into envelope.opts.
  3. Validates the envelope (rejects bounds violations, asOf collisions, history queries, envelope max-fuel, etc.).
  4. Walks every distinct ledger and rejects with 404 if any sub-query references a ledger outside the bearer's scope (existence-leak avoidance, matching single-query /query behaviour).
  5. Pre-merges envelope.opts ⊕ sub.opts into each sub-query's body opts (body wins) before running the impersonation gate. Without this pre-merge, an envelope-level opts.identity would bypass the gate entirely.
  6. Runs apply_auth_identity_to_opts per sub-query — gate sees the final merged opts and either honours an impersonation request (when the bearer can impersonate against that ledger) or force-rewrites opts.identity to the bearer's own DID.
  7. Delegates to state.fluree.multi_query().

The api crate's dispatcher then merges envelope.opts ⊕ sub.opts ⊕ sub.query["opts"] again with body opts winning — so the gate's decision (sitting in body opts) is the most-specific layer and survives the merge. Anything user-supplied at the envelope or sub-query opts layer (e.g. meta: true) can't clobber the forced identity.

Four merge-order regression unit tests in multi_dispatch::tests::merge_* pin this rule down so any future refactor that reverses the order fails fast.

Spans

New sub_query debug span per alias. Attributes: alias, language (jsonld | sparql), effective_timeout_ms (set at semaphore-acquisition), result_status (ok | error | timeout, set at task end). HTTP path adds a request parent (otel.name = query:multi-query); in-process callers (downstream Rust apps, fluree multi-query --direct) emit the same sub_query spans without the request parent unless the caller wraps the call themselves.

CLI subcommand

fluree multi-query envelope.json --remote origin
fluree multi-query -e '{"queries":{...}}' --remote origin
cat envelope.json | fluree multi-query --remote origin --format pretty
fluree multi-query --direct envelope.json  # in-process local execution
fluree multi-query envelope.json           # auto-route to running server or in-process fallback
  • New Commands::MultiQuery variant in fluree-db-cli/src/cli.rs with input resolution matching fluree query (positional file / -e inline / -f file / stdin).
  • New commands::multi_query module with three output formats: json (compact, default), pretty (indented), aliases (per-alias section view with colored status header).
  • New RemoteLedgerClient::multi_query() mirroring the existing query_connection_* helpers.
  • Three transport tiers resolved in priority order:
    1. --remote <name> — explicit named remote. OIDC token refresh persisted back to config.toml after the round trip.
    2. Auto-route to a locally-running fluree server when one is detected; disabled by --direct.
    3. In-process local — calls Fluree::multi_query() directly against the .fluree/ storage tree. Used when neither of the above applies, OR when --direct is set without --remote. This is the natural counterpart to fluree query running locally.
  • Full PolicyArgs flag bundle (--as, --policy-class, --policy, --policy-file, --policy-values, --policy-values-file, --default-allow) flatten onto the subcommand and ride through all three transports. Local mode injects them into envelope opts via the typed PolicyArgs accessors (--policy-class A --policy-class B correctly produces opts.policy-class = ["A", "B"]).
  • --format validated at command entry so a typo can't burn a server-side multi-query before failing locally.
  • Positional file argument no longer filters on existence; a typoed filename surfaces a clear "failed to read" error instead of silently routing to stdin.

Current limitations

These produce documented behaviour rather than silent partial success. Each is covered in detail in docs/api/multi-query.md#limitations.

  • History queries are rejected. JSON-LD bodies with to, SPARQL with FROM <…> TO <…> get 400. History spans a t-range; the envelope's shared-snapshot contract has no meaning over a range. Use single queries against /query for history.
  • Envelope-level fuel budget is rejected. opts.max-fuel / max_fuel / maxFuel at envelope level gets 400 because the dispatcher does not share a fuel budget across parallel sub-queries. Per-sub-query opts.max-fuel works unchanged.
  • Cancellation latency is bounded by in-flight storage reads. When the envelope deadline fires the dispatcher aborts the JoinSet; in-flight blocking storage reads still complete before the dropped future is observed (cache hit: under 5 ms; remote S3 range read: up to a few hundred ms). No new work starts after cancellation.
  • opts.t is rejected at every level — envelope opts, sub-query opts, AND query-body opts. Pin time via from or envelope asOf.
  • Response size cap is enforced at assembly, not throughout dispatch. Each sub-query result is checked against the per-sub-query cap once after it returns, and the assembler enforces the envelope-level cap as it stitches the response. Peak memory during dispatch is bounded by max_concurrency × max_subquery_response_bytes, which can exceed the envelope cap while individual sub-queries are running.
  • SPARQL sub-queries do not consume merged policy opts. Headers ride through and the envelope-level fold still happens, but the SPARQL dispatch path (query_from().sparql()) does not read body opts. JSON-LD sub-queries get full policy threading via apply_auth_identity_to_opts; SPARQL sub-queries observe bearer ledger-scope only. This is the same gap that exists for single-query connection-scoped SPARQL (POST /query with Content-Type: application/sparql-query and an inline FROM).

Public API surface

After a deliberate visibility audit, the api crate's committed public surface for multi-query is exactly:

  • Fluree::multi_query() — builder entry (takes &Arc<Self>)
  • MultiQueryBuilder + .envelope() + .bounds() + .execute() — builder methods
  • MultiQueryError — error type clients match on; variants map to HTTP status (Validation → 4xx, Snapshot / ResponseAssembly → 5xx)
  • ResponseAssemblyError — sits inside MultiQueryError::ResponseAssembly
  • run_jsonld_subquery / run_sparql_subquery + SubqueryOutput — per-sub-query helpers (server reuses the JSON-LD one for execute_dataset_query; SPARQL pair stays for symmetry)
  • Envelope wire types: MultiQueryRequest, MultiQueryResponse, MultiQueryStatus, MultiQueryBounds, MultiQuerySubquery, SubqueryLanguage, AsOf, SnapshotInfo, MultiQueryMeta, MultiQueryValidationError

Dispatcher internals (AliasOutcome, AliasOutcomeKind, DispatchConfig, run_envelope, dispatch_subqueries, assemble_response) are pub(crate) — they have no external consumers today and exposing them would commit us to a stable contract for implementation details. Easy to promote later if a real use case shows up.

Tests

Suite Count What
fluree-db-api lib query::multi* 98 Envelope shape, validation, merge, snapshot resolve, snapshot apply, SPARQL directive injection, dispatch-config bounds, merge-order precedence (4 regression), timeout precedence (2 regression), per-alias tracking (4), opts.t at every level (3)
fluree-db-api it_multi_query.rs (new) 8 End-to-end through Fluree::multi_query() against MemoryFluree: mixed-language headline, two-ledger snapshot, per-alias tracking under envelope-level / per-sub-query meta, typed error variants, partial failure, bounds threading
fluree-db-server multi_query_integration 17 End-to-end through the live router
fluree-db-server multi_query_auth_integration 4 Bearer ledger-scope per-distinct-ledger
fluree-db-server multi_query_tracing_integration 2 sub_query span attributes
fluree-db-server integration 47 Pre-existing — unaffected
fluree-db-cli integration 81 CLI happy path + 8 multi-query: help, invalid JSON, no transport, --direct runs in-process, unknown remote, typoed positional file, --format typo, positive local-in-process (creates ledger, inserts, runs envelope, asserts seeded value appears)
fluree-db-cli commands::multi_query::tests 5 Policy flag injection: repeated --policy-class preserved, envelope opts win over CLI flags, single value still array, default-allow only when true, no-flags no-op

Docs

  • docs/api/multi-query.md — full envelope reference with tracking field, three-layer opts merge spelled out (security-relevant), per-language SPARQL parity gap, current limitations.
  • docs/cli/multi-query.md — usage with all three transports, three worked examples, per-language policy footnote.
  • docs/api/endpoints.md — new POST /multi-query section linking to the dedicated reference.
  • docs/api/README.md — added to Core Endpoints listing.
  • docs/api/errors.md — 200 OK entry calls out the "branch on body.status, not HTTP code" rule.
  • docs/query/README.md — new "Bundling queries" section.
  • docs/cli/server-integration.md — fluree multi-query subsection covers all three transport tiers and the full --policy* flag bundle (corrected from earlier drafts that wrongly claimed multi-query doesn't take policy flags).
  • docs/operations/telemetry.md — Span Tree (Multi-query envelope) subsection.
  • docs/SUMMARY.md — links both new doc pages.

bplatz added 15 commits May 28, 2026 08:04
Adds the MultiQueryRequest / MultiQueryResponse envelope shape and the pure
validation logic for bundling N independent queries against a single shared
snapshot moment. No HTTP wiring, no dispatcher — those land separately.

Envelope shape: top-level @context, asOf (integer t or ISO 8601), opts, and
an alias-keyed queries map. Each sub-query carries its own from (so no
brittle dataset-equivalence math at the envelope level) and a language
discriminator (jsonld | sparql) so mixed-language bundles work out of the
box. AsOf is an enum, not a string, so an integer t is distinguishable from
a numeric-looking timestamp.

Two-rule inheritance model: @context and opts shallow-merge with
sub-query winning on key conflict (@context: null in a sub-query is an
explicit reset, matching JSON-LD semantics); asOf vs any inner temporal pin
(@t:/@iso:/@commit: in from, an inner t field, SPARQL FROM <…@t:…>) is a
hard collision error, never a silent override. opts.t is rejected outright
inside the envelope — the canonical place to pin sub-query time is from.

validate_envelope returns the BTreeSet of distinct ledger identifiers
(temporal suffix stripped) on success, so the dispatcher reuses the set for
snapshot resolution without re-walking the envelope. Bounds enforced:
max queries/envelope, max distinct ledgers/envelope, max concurrency
(opts.maxConcurrency clamped to static), envelope timeout
(opts.timeoutMs clamped). Integer asOf is rejected for multi-ledger
envelopes — only ISO can fan out across ledgers.

SPARQL bridge: SparqlContextDirectives extracts prefix-shaped term mappings
and @base from a merged JSON-LD context; apply_sparql_context prepends them
per-directive-class and all-or-nothing (envelope PREFIXes injected only if
the SPARQL query has none; envelope BASE injected only if the SPARQL has
none — independently, so adding a single PREFIX override doesn't strip
BASE). JSON-LD-only directives (@vocab, term definitions with @id/@type)
are silently dropped for SPARQL.

Collision detection scans angle-bracketed IRIs for @t:/@iso:/@commit:
without a regex dep — those markers are Fluree extensions and don't appear
in standard SPARQL IRIs. Coarse FROM/FROM NAMED extraction counts distinct
ledgers for bounds, falling through to the real SPARQL parser at execution
time.

33 unit tests cover deserialization, every validation branch, merge
semantics including null reset, per-directive-class SPARQL injection, and
temporal-pin detection. indexmap added at workspace level for
insertion-order-preserving alias maps.
Pulls the connection-scoped JSON-LD execution out of execute_dataset_query
into a shared helper that returns SubqueryOutput { data, tally } instead of
an axum Response. The multi-query envelope dispatcher will call the same
helper once per alias to share the connection-scoped path (state.fluree
.query_from().jsonld(...).execute_formatted/tracked()) — which already
handles dataset features, the connection-level ledger cache (so parallel
sub-queries on the same ledger share snapshot loads), and SPARQL through
its query_from().sparql() sibling.

run_jsonld_subquery is the live caller; run_sparql_subquery lands behind
#[expect(dead_code)] with a future-use comment per the project's dead-code
policy — it's the consumer of an upcoming SPARQL sub-query dispatch and
keeping it here keeps the two helpers shape-symmetric.

execute_dataset_query now delegates to the helper and rebuilds the same
HTTP response: tracked path wraps the data and tally in
TrackedQueryResponse with tracking_headers; plain path emits Json(data).
Tracker span fields (tracker_time, tracker_fuel) are still recorded from
the tally before response assembly so existing telemetry surfaces are
unchanged. Error mapping uses the same ServerError::Api wrapper and the
same set_span_error_code("error:InvalidQuery") attribution, so logs and
error codes look identical to before the extraction.

Single-query fast paths (execute_query shared-storage branch,
execute_query_proxy, execute_sparql_ledger) are left alone — they carry
performance optimizations the multi-query dispatcher doesn't need, and
forcing them through the new helper would lose load_ledger_for_query's
freshness check on the fast path.

Verified: 47 integration tests, 21 policy tests, 1 cross-ledger test all
green; 481 api lib tests including the 33 new multi.rs tests still
passing.
Five issues from review of the envelope-types/validation pass:

(1) Per-subquery 'from' emptiness was checked against the shared distinct
ledger set, so any malformed or empty from on a later sub-query slipped
through once an earlier sub-query had populated distinct. validate_jsonld
_subquery and validate_sparql_subquery now check the extracted list
locally per sub-query before merging into distinct, so each alias's
MissingFrom is detected independently.

(2) Object-form 'from' temporal pins were not detected under envelope
asOf. Replaced jsonld_from_ledger_strings with jsonld_extract_from
returning per-entry { ledger, pin_location } values. The object extractor
mirrors parse_single_graph_source in dataset.rs: identifier comes from
@id or id, and an explicit t (integer) or at (commit:HASH or ISO) field
is itself a temporal pin even when the identifier string carries no
suffix. Top-level object from is now extracted (previously only string
and array were handled), and array-of-object entries get the same pin
detection. Five new tests cover object-form combinations including the
inside-an-array case.

(3) SPARQL FROM extraction and temporal-pin detection now route through
the real parser (fluree_db_sparql::parse_sparql). sparql_extract_from
walks DatasetClause.default_graphs / named_graphs / to_graph from the
Select/Construct/Ask/Describe variants and skips prefixed IriValue
entries (which need context resolution and can't be ledger refs without
it). Substring-scanning the raw string would false-positive on FROM
inside comments / string literals and false-flag any angle-bracketed IRI
containing the markers; the AST path doesn't. When parsing fails the
extractor returns None so the downstream SPARQL parser produces the real
error rather than this layer inventing a MissingFrom.

(4) SparqlContextDirectives::from_context was emitting every string-
valued context entry as a PREFIX, which turned JSON-LD CURIE aliases like
"name": "schema:name" into PREFIX name: <schema:name> (invalid
SPARQL). Now restricted to entries where the key is a valid PN_PREFIX
(conservative ASCII subset: starts with letter/underscore, then
alphanumeric/_/-) and the value is a namespace IRI: an absolute IRI that
either uses a hierarchical scheme (://) or ends with # or /. URN-style
namespaces like urn:example:vocab# are accepted; CURIE aliases and
relative @base values are dropped.

(5) run_sparql_subquery's tracked: bool was too narrow to express
selective meta or max-fuel. Switched to tracking: Option<TrackingOptions>
and routes through .tracking(opts) on the FromQueryBuilder. None still
runs the non-tracked path; Some(opts) routes through the tracked builder
with selective time/fuel/policy flags honored.

13 new tests cover the new behaviour: jsonld object t/at fields and
identifier-suffix pins, per-sub-query empty-from detection, AST-based
pin detection that ignores markers in string literals, parse-failure
fallback, CURIE alias filtering, invalid prefix name rejection, URN
namespace acceptance, and non-absolute @base filtering. All 46 multi
tests plus 47 integration / 21 policy / 1 cross-ledger tests pass.
Two pieces that together let a multi-query envelope actually execute
against a single resolved snapshot moment with bounded parallelism.

Snapshot resolution (fluree-db-api/src/query/multi_snapshot.rs):

resolve_envelope_snapshot walks the distinct ledger set and produces an
EnvelopeSnapshot { as_of, ledgers: HashMap<String, i64> }. AsOf::T pins
the single ledger directly (multi-ledger with integer asOf was already
rejected at validation). AsOf::Iso resolves per-ledger via
time_resolve::datetime_to_t against each ledger's current snapshot,
mirroring the rounding rule in load_graph_db_at so sub-millisecond ISO
precision doesn't push us off-by-one before the intended commit. Absent
asOf captures server-now once via Utc::now() and pins each ledger to its
current t; the wall-clock moment is echoed back so the response is
reproducible. Per-ledger work is sequential in v1 — the connection-level
ledger cache (LedgerManager::get_or_load) coalesces repeated loads, so
the bounded fan-out (max_distinct_ledgers) is acceptable.

apply_snapshot_to_jsonld rewrites a sub-query body in place: string from
becomes object {@id, t}; object from gets t inserted next to its @id/id;
array entries get the same treatment recursively. Bare ledger ids are
matched against the snapshot map with temporal suffix and named-graph
fragment stripped, but the original identifier is preserved on the
written-back @id so fragment-selected named graphs still resolve.

apply_snapshot_to_sparql uses the SPARQL parser's IRI spans to do
precise byte-level splicing of FROM <iri> / FROM NAMED <iri> clauses,
appending @t:N to each ledger present in the snapshot map. Replacements
are sorted and applied right-to-left so earlier spans aren't shifted by
later edits. Span-based rewrite means IRIs inside comments or string
literals are never touched. When parsing fails the original string is
returned so the downstream parser produces the real error. IRIs that
already carry a temporal suffix are skipped defensively — validation
would have rejected the envelope before reaching here, but we don't
double-pin.

Dispatcher (fluree-db-server/src/routes/multi_dispatch.rs):

dispatch_multi_query owns a JoinSet for sub-query tasks and a Semaphore
sized to DispatchConfig::max_concurrency. Each task acquires its permit
before computing its effective timeout: min(opts.timeoutMs, remaining
envelope budget) measured at permit-acquisition time, not envelope-entry
— a sub-query that waited 30s on a 60s envelope gets <=30s regardless of
its own opts.timeoutMs. The envelope deadline is a select! arm against
sleep_until; when it fires JoinSet::abort_all() cancels in-flight tasks,
remaining slots are drained, and any task that didn't complete is
marked AliasOutcomeKind::Timeout with the envelope budget. Sub-query
errors land in ::Error with a coarse classification — task #5/#6 will
refine the code surface when assembling the HTTP response.

Per-task execution does the merge work: @context and opts merge via the
multi.rs helpers with sub-query winning; the merged context is injected
into JSON-LD bodies (or used to derive SPARQL PREFIX/BASE directives for
SPARQL sub-queries). After merge, apply_snapshot_to_jsonld /
apply_snapshot_to_sparql pin the per-ledger t and the result is passed
to run_jsonld_subquery / run_sparql_subquery — the connection-scoped
helpers from the earlier extraction. TrackingOptions is built once per
sub-query from the merged opts (track_time/fuel/policy + max_fuel) and
threaded through to the SPARQL builder; the JSON-LD path picks up
tracking from has_tracking_opts on the merged body.

Each sub-query gets its own sub_query span (alias, language,
effective_timeout_ms, result_status) as a child of whatever envelope
span the caller establishes. Span tagging happens both at task-start
(effective_timeout_ms once known) and at task-end (result_status).

Visibility: fluree-db-api's  is promoted to pub so the
server can reach query::multi and query::multi_snapshot; siblings
inside that module that were already pub mod stay accessible. The
server's mod query is promoted to pub(crate) so the new multi_dispatch
sibling can reuse the existing run_jsonld_subquery / SubqueryOutput
without duplicating their bodies.

12 snapshot unit tests cover JSON-LD application (string/object/array
from, named-graph fragment preservation, ledger not in map) and SPARQL
application (FROM and FROM NAMED rewrite, IRI inside string literal
untouched, unparseable returns original, ledger not in map, existing
suffix not overwritten). 6 dispatcher unit tests cover DispatchConfig
clamping to server bounds and the per-sub-query timeout fallback
ordering. Existing 47 server integration tests and 506 api lib tests
pass.
Four issues from the snapshot + dispatcher review:

(1) JSON-LD snapshot application was overwriting inner explicit pins.
apply_snapshot_to_jsonld stripped the @t: / @iso: / @commit: suffix to
look up in the snapshot map, then rebuilt as {@id: 'ledgerA@t:42', t:
current} — and the dataset parser lets object t override the string
suffix, so the query silently ran at current t instead of t:42.
pin_string_entry / pin_object_entry now short-circuit before pinning
when an explicit temporal pin is present: a @t:/@iso:/@commit: suffix
in the identifier string, or a t / at field on the object. The
SPARQL applier already had the equivalent defensive check.

(2) History queries are not part of the multi-query temporal model.
JSON-LD validation only inspected from for pins and ignored to;
sparql_extract_from saw to_graph but apply_snapshot_to_sparql didn't
rewrite it. Either path could produce a range that bypassed envelope
asOf. v1 scope-cut: reject history queries inside envelopes at
validation. JSON-LD checks body for a  key; SPARQL inspects
DatasetClause.to_graph via the parser. Both surface as a new
HistoryQueryInEnvelope error pointing the caller to the single-query
endpoint. Range-aware envelope semantics can come in a later version
once we've defined what asOf even means against a t-range.

(3) Envelope-level max-fuel was being multiplied per alias because
merged_opts shallow-merges envelope opts into every sub-query and the
existing fuel machinery accounts per-query. A user setting envelope
max-fuel: 1000 expects a 1000 total, not 1000 × N. Until shared-atomic
fuel lands (planned for v1.1 — needs a thread-safe budget tracker
plumbed through every fuel-charge site in the query engine), envelope
opts.max-fuel / max_fuel / maxFuel is rejected outright with
EnvelopeFuelBudgetUnsupported. Per-sub-query opts.max-fuel still works
unchanged.

(4) maxConcurrency: 0 was accepted, then created a zero-permit
semaphore so every task waited until the envelope deadline before
timing out the entire envelope. Added MaxConcurrencyZero error
alongside the existing >limit check so the bound has both an upper and
lower edge.

13 new tests cover: pinned string from with @t:/@iso: suffix left
untouched, object from with explicit t / at / @id-suffix left
untouched, mixed array where pinned entries survive and bare entries
get the envelope's t; JSON-LD and SPARQL history query rejection;
envelope max-fuel rejection in all three case styles; per-sub-query
max-fuel still allowed; maxConcurrency: 0 rejected. Existing 47
integration tests and 6 dispatcher unit tests still pass; multi-query
test suite goes from 58 to 71.
Wires the envelope contract end-to-end: a new POST
/v1/fluree/multi-query handler parses the envelope, validates against
server bounds, resolves the snapshot, dispatches sub-queries in
parallel, and assembles the per-alias response — with size-capped
serialization on the way out.

Response assembly (fluree-db-server/src/routes/multi_response.rs):

assemble_response walks the dispatcher's Vec<AliasOutcome> in
submission order, slotting Success into results and Error/Timeout into
errors. Each entry is serialized once with serde_json::to_vec and its
byte length is added to a running total alongside a small fudge for
envelope overhead and per-alias key/quote/comma framing; once the
running total crosses MultiQueryBounds::max_response_size_bytes the
assembler returns ResponseAssemblyError::ResponseSizeExceeded naming
the offending alias. Doing the cap check incrementally means a 1GB
result on alias-5 of 10 trips before we allocate all 10's JSON.

Top-level status follows the agreed three-state mapping:
- success_count > 0 and failure_count == 0 -> Ok
- success_count == 0 -> AllFailed
- otherwise -> Partial

Snapshot info echoes the resolved per-ledger t map with ledger keys
sorted for deterministic response shape (helps trace diffing and
cache locality). Aggregate meta block (fuel_total summed across
successful tallies, envelope wall-clock elapsed_ms) is included when
the caller signals opts.meta.

HTTP handler (fluree-db-server/src/routes/query.rs::multi_query):

The handler creates a request_id-keyed multi_query span, runs the
data-auth check (mirroring the single-query top-level handler), parses
the body via credential.body_json so JWS-wrapped requests work, and
deserializes into MultiQueryRequest. Status mapping per the agreed
rule:

- 4xx for any MultiQueryValidationError (envelope shape, bounds, asOf
  collision, missing from, history query, max-fuel, maxConcurrency: 0)
- 5xx for envelope infra (resolve_envelope_snapshot fails on a missing
  ledger / nameservice error; assemble_response trips the size cap)
- 200 otherwise, including all-sub-queries-failed — clients branch on
  body.status (ok | partial | all_failed) for the aggregate outcome
  rather than HTTP code

The handler captures envelope_started at handler entry and threads
the elapsed wall-clock into the assembled meta block so the response's
elapsed_ms reflects the whole envelope, not just dispatch.

Route registered at /v1/fluree/multi-query (POST only).

run_sparql_subquery loses its #[expect(dead_code)] now that the
dispatcher consumes it; the warning that surfaced is exactly the
"unused expectation" signal CLAUDE.md asks us to honor.

Integration tests (fluree-db-server/tests/multi_query_integration.rs):

14 tests covering:
- All-JSON-LD envelope -> 200 ok
- Mixed JSON-LD + SPARQL envelope -> 200 ok
- Shared @context lifts to JSON-LD sub-queries (no repeat needed)
- Shared @context injects as SPARQL PREFIX when sub-query has none
- Response echoes snapshot.asOf and snapshot.ledgers
- Two-ledger envelope: both ledgers resolved and pinned in snapshot
- Partial failure: one good JSON-LD + one syntactically broken SPARQL
  -> 200 with status: partial, errors[bad] populated
- Empty envelope -> 400
- Sub-query missing from -> 400
- asOf set + sub-query @t: pin -> 400 (collision)
- opts.max-fuel at envelope level -> 400 (v1 not supported)
- History query in envelope -> 400
- maxConcurrency: 0 -> 400
- opts.meta: true populates response.meta.elapsed_ms

Test count: 14 integration + 8 response assembler unit + 6 dispatcher
unit + 71 envelope/snapshot unit. Existing 47 server integration + 21
policy + 1 cross-ledger + 519 api lib tests still green.
New dedicated reference at docs/api/multi-query.md covering the
envelope contract end to end: request shape (envelope-level @context,
asOf, opts, queries map; per-sub-query language + query + opts), the
two-rule merge model (mergeable fields shallow-merge with sub-query
winning; asOf vs inner temporal pin is a hard collision), snapshot
semantics with the atomicity caveat spelled out plainly ("shared time
resolution, not distributed atomicity"), response shape with the
status / snapshot / results / errors / meta fields and the HTTP
status mapping, the bounds table, six worked examples (minimal
two-query, shared @context, mixed-language with PREFIX injection,
per-sub-query opts override, multi-ledger asOf pinning, partial
failure), and the explicit v1 limitations list (history queries,
envelope max-fuel, Tier-B cancellation, opts.t rejection).

Cross-references added so the doc is findable from the natural entry
points:

- docs/api/endpoints.md gets a POST /multi-query section with the
  envelope shape and a HTTP status table; the body of the section
  links straight to the dedicated reference for the rest.
- docs/api/README.md lists POST /multi-query in the Core Endpoints
  bullets and gets a dedicated "Multi-query envelope" subsection
  pointing to the new doc.
- docs/api/errors.md adds a callout to the 200 OK entry: "/multi-query
  returns 200 even when individual sub-queries fail; clients should
  branch on body.status." The full status mapping is linked from the
  multi-query doc.
- docs/query/README.md gets a "Bundling queries" section at the
  bottom directing users to the envelope when they have N queries
  that should share a snapshot or run in parallel.
- docs/SUMMARY.md links the new page under HTTP API.

Span / telemetry coverage:

- docs/operations/telemetry.md adds Span Tree (Multi-query envelope)
  alongside the existing Query, Transaction, Indexing, and Bulk
  Import trees; adds query:multi-query to the otel.name examples;
  documents the sub_query attribute set (alias, language,
  effective_timeout_ms, result_status) and when each is set.
- .claude/skills/trace-inspect/references/span-hierarchy.md gets a
  Multi-query envelope subsection under Query Traces with the full
  hierarchy and attribute table.
- .claude/skills/trace-overview/references/span-hierarchy.md gets the
  same envelope subsection in the more compact overview style.

CLAUDE.md docs table also gets a row pointing at the new reference
(local-only — CLAUDE.md is gitignored per repo policy).

No code changes in this commit. trace_common.py expected-children
and the it_tracing_spans.rs acceptance tests are tracked separately
under task #7.
Addresses four review findings against the multi-query handler and
snapshot application.

Bearer ledger scope (High #1):

The handler now walks the validated distinct_ledgers set after
validation and rejects with 404 (existence-leak avoidance) if any
ledger is outside the bearer's read scope. Matches the single-query
/query and /query/:ledger behavior exactly: an unsigned bearer that
can't read one of the envelope's ledgers gets the whole envelope
rejected, not partial results that would reveal whether the ledger
exists. Signed requests bypass this check, same as single-query.

Identity + default policy-class threading (High #2):

The handler builds a MultiQueryIdentityContext containing the
effective bearer identity (signed DID wins over bearer identity) and
the server-configured default policy class, threaded through to the
dispatcher. The dispatcher applies it per JSON-LD sub-query via
apply_auth_identity_to_opts — the same code path the single-query
JSON-LD handler uses, including the root-identity impersonation
semantic. The impersonation check binds to each sub-query's primary
ledger (first entry of its from clause), conservative for multi-
ledger sub-queries.

Headers are now injected into envelope opts BEFORE validation runs,
so a client supplying max-fuel or maxConcurrency via fluree-* headers
hits the same envelope-level rejections the body opts get.

The fluree-* headers (policy-class, policy, policy-values, identity,
default-allow, max-fuel) ride on the envelope opts and merge into
every sub-query's opts as defaults via merged_opts — sub-query opts
still win on key conflict, matching single-query behavior.

SPARQL identity threading is explicitly deferred: the existing
connection-scoped SPARQL path (/query with SPARQL FROM clauses) also
doesn't currently thread identity. v1 multi-query matches that for
parity; the docs flag this as a v1 limitation so the two paths can
land identity threading together.

SPARQL fragment-aware snapshot pinning (Medium #1):

apply_snapshot_to_sparql previously skipped any IRI whose value
differed from its bare-ledger form via the value_str != bare check,
which fired on both real temporal pins AND on named-graph fragments
(ledger#txn-meta). So an envelope-pinned SPARQL like
FROM <mq:frag#txn-meta> would run against current head instead of
the envelope's t. Fixed by gating the skip on actual temporal-marker
presence (has_temporal_marker checks for @t: / @iso: / @commit:),
and splicing @t:N BEFORE any fragment when rewriting:
<ledger#txn-meta> -> <ledger@t:42#txn-meta>. The dataset parser
separates fragment from temporal suffix and reattaches the fragment
after time-spec resolution, so the spliced form is what it expects.

Per-sub-query response size cap (Medium #4):

DispatchConfig now carries max_subquery_response_bytes. Each
sub-query's serialized result is sized once after dispatch returns;
if a single alias's result exceeds the cap it's downgraded to an
error outcome (code: "response_too_large") and the data dropped
before assembly. This catches a single runaway query before it adds
to envelope-wide memory pressure. The envelope-level cap in
assemble_response is still the strict guarantee; the per-sub-query
cap is the early-exit. The doc now spells out honestly that this is
best-effort, not an OOM guard — peak memory is bounded by
max_concurrency * max_subquery_response_bytes, not the envelope cap
alone — and per-sub-query streaming serialization is queued for v1.1.

Tests:

- 4 new auth integration tests (multi_query_auth_integration.rs):
  unauthenticated request when data auth required returns 401,
  in-scope bearer succeeds, out-of-scope JSON-LD returns 404,
  out-of-scope SPARQL returns 404.
- 1 new fragment-ledger SPARQL integration test confirms a
  SPARQL FROM <ledger#txn-meta> envelope alias runs successfully
  (regression against the unpinned-fragment bug).
- 2 new unit tests cover the SPARQL fragment splicing
  (apply_snapshot_to_sparql) for both FROM and FROM NAMED clauses.

47 server integration + 21 policy + 4 multi-query auth + 16 multi-query
core + 73 envelope/snapshot/dispatcher unit tests all green.
Programmatic counterpart to the span trees documented in
docs/operations/telemetry.md and the multi-query subsections of the
trace-inspect / trace-overview skill references. Verifies the
envelope dispatcher emits the agreed sub_query attribute set so a
future change that drops a field or renames a span fails fast in CI.

Test 1 — multi_query_emits_one_sub_query_span_per_alias:

Drives a mixed JSON-LD + SPARQL envelope through the live router via
an in-process oneshot, captures every span with a minimal inline
tracing layer, and asserts:

- Exactly two sub_query spans (one per alias).
- Each span carries alias and language fields set at span open
  (alias matches the envelope key; language is jsonld or sparql).
- Each span carries effective_timeout_ms (recorded after permit
  acquisition) and result_status (recorded at task end).
- result_status is "ok" for both aliases under the success path.

Test 2 — sub_query_span_records_error_status_on_per_alias_failure:

Mixed envelope with one valid JSON-LD alias and one syntactically
broken SPARQL alias. The handler returns 200 (envelope ran), the
sub_query span for the bad alias records result_status = "error",
and the good alias still records result_status = "ok". Covers the
"some succeeded, some failed" branch — the partial-failure case the
response body assembles as status: partial.

The inline span capture is intentional. The fluree-db-api crate has
a richer span-capture helper at tests/support/span_capture.rs, but
the dispatcher lives in fluree-db-server and consuming the api
crate's test-only helpers would require making them public — a
larger change for a one-off test. The minimal layer here is ~80 LOC
and only does what these tests need.

Verified: 47 server integration + 4 auth + 15 multi-query + 2 tracing
tests pass; 73 envelope/snapshot/dispatcher unit tests still green.

Skill-script updates for the new sub_query span (trace_common.py
EXPECTED_CHILDREN) live under .claude/ which is gitignored, so this
commit only carries the acceptance test. The doc-side coverage
landed in the earlier docs commit (telemetry.md span tree,
span-hierarchy.md in both trace-inspect and trace-overview skills).
cargo fmt --all on the multi-query work — formatting the 7 files
flagged by the CI fmt-check (envelope types, snapshot module,
dispatcher, response assembler, handler, and two test files). No
logic changes in this commit beyond whitespace normalization.

Trace-skill EXPECTED_CHILDREN for sub_query now lists both
query_execute AND sparql_execute. The table semantics is "at least
one of these must be present," and the previous single-entry set
would false-warn on SPARQL-only envelopes that produce sparql_execute
under sub_query. .claude/ is gitignored so this change is local-only.

Doc honesty pass on bounds. The Bounds table previously said the
server-side limits were tunable; v1 actually uses
MultiQueryBounds::DEFAULT unconditionally and ServerConfig wiring is
future work. Added an inline v1 status callout, retitled the
default column to "v1 value," and rewrote the override column to
list only the request-side knobs that actually work today
(opts.maxConcurrency, opts.timeoutMs) — the rest say "request cannot
override" so readers don't go hunting for a config key that isn't
there yet.

Doc cleanup on response shape. MultiQueryResponse.errors is
skip_serializing_if = JsonMap::is_empty, so a successful envelope
omits the field entirely — examples were misleadingly showing
"errors": {}. Removed those, added a "Field omission" callout
covering errors / meta / snapshot.asOf, and updated the
endpoints.md envelope example to match.

47 server integration + 4 multi-query auth + 15 multi-query
integration + 2 multi-query tracing + 73 envelope/snapshot/dispatcher
unit tests pass; cargo fmt --all -- --check clean.
Adds a top-level fluree multi-query subcommand that POSTs a
multi-query envelope (JSON) to a Fluree server's /multi-query
endpoint, with the same transport-resolution rules as the other
remote-capable subcommands.

CLI surface (fluree-db-cli/src/cli.rs Commands::MultiQuery):

  fluree multi-query [FILE] [OPTIONS]

Options:
  -e, --expr <JSON>       inline envelope
  -f, --file <PATH>       envelope file path
      --format <FMT>      json (default, compact) | pretty | aliases
      --remote <NAME>     named remote

Input resolution matches fluree query: -e wins, then positional file
(when it exists), then -f, then stdin. Output defaults to compact JSON
on stdout for shell composability; --format pretty indents it and
--format aliases prints per-alias section headers with status /
asOf / per-ledger t up top — useful when piping through less or
debugging a partial-failure envelope.

Transport (fluree-db-cli/src/commands/multi_query.rs):

Multi-query has no in-process execution path in v1: the dispatcher
lives in fluree-db-server and only the HTTP endpoint exposes it.
Resolution, in priority order:

1. --remote <name> — explicit, routes through the named remote.
2. Auto-route to a locally running fluree server — used when
   --remote is omitted and server.meta.json reports a live pid.
   Disabled by --direct.
3. No transport — the CLI errors with a clear "pass --remote or
   start a local server" message rather than hanging or producing a
   cryptic stack trace.

RemoteLedgerClient::multi_query lands alongside the existing
query_connection_* helpers in remote_client.rs — same op_url_root
construction (-> {base_url}/multi-query), same send_json plumbing,
same auth/refresh handling.

Tests (5 in tests/integration.rs):

- multi_query_help_shows_subcommand          — help output
- multi_query_invalid_json_rejected          — parse-time error
- multi_query_without_transport_surfaces_help — no remote, no server
- multi_query_direct_flag_rejects_no_remote  — --direct with no remote
- multi_query_unknown_remote_errors          — bad remote name

End-to-end testing against a real server is already covered by the
server-side integration tests in fluree-db-server/tests/; the CLI
tests verify the CLI surface (flags, error paths, transport
resolution) rather than re-testing the HTTP layer.

Docs:

- New docs/cli/multi-query.md with usage, transport rules, examples
  for inline / file / stdin / per-alias output, and a clear pointer
  to docs/api/multi-query.md for the envelope wire format.
- docs/cli/server-integration.md gets a "fluree multi-query" section
  explaining the endpoint mapping, transport requirement, and the
  three resolution branches.
- docs/SUMMARY.md links the new CLI page under HTTP CLI.
- docs/api/multi-query.md "See also" adds the CLI page.

5 CLI integration + 4 multi-query auth + 15 multi-query integration
+ 2 multi-query tracing + 47 server integration tests pass. cargo
fmt --all -- --check clean.
Three review findings on the multi-query work:

Blocking — workspace clippy.

multi_snapshot.rs:356 used edits.sort_by(|a, b| a.0.cmp(&b.0)) where
sort_by_key fits cleanly. Two further clippy items surfaced under the
workspace check:

- multi_dispatch.rs:296 select! arm used `_ = &mut deadline_sleep`
  which trips ignored_unit_patterns; switched to the explicit unit
  binding `()`.
- multi.rs test asserted on a match arm with no trailing `;`, which
  fails needs_semicolon_if_nothing_returned. Added the `;`.

`cargo clippy --workspace --all-features --all-targets -- -D warnings`
and `cargo fmt --all -- --check` are now both clean.

Medium — token persistence missing in multi-query.

fluree multi-query --remote ... can silently refresh an expired OIDC
token during a 401 retry, but the previous code never wrote the new
access_token (and rotated refresh_token, if any) back to config.toml.
That left the next remote command using stale credentials — refresh
again at best, hard failure if refresh tokens rotate.

The fix mirrors fluree query's pattern: the transport-resolution
returns an Option<String> remote_name alongside the client; on the
--remote path we capture the slug; after the multi_query round-trip
returns Ok we call context::persist_refreshed_tokens(&client,
&remote_name, dirs). The auto-route (local server) path leaves
remote_name as None, since the local server doesn't require a token
and there's no config slot to persist into.

Low — anomaly scripts re-interpreted EXPECTED_CHILDREN incorrectly.

The previous fix changed sub_query's EXPECTED_CHILDREN value to
{"query_execute", "sparql_execute"} with a comment claiming the
check is "at least one of." But trace_anomalies.py and
trace_corpus_anomalies.py both compute `expected - child_ops` — set
difference — so a JSON-LD-only sub_query would false-warn for the
missing sparql_execute and vice versa.

Adopted a backward-compatible list-of-sets convention:

  set     → all-of:  every name must be present (existing behavior)
  [set]+  → any-of:  for each set in the list, at least one of the
                     names must be present

sub_query becomes [{"query_execute", "sparql_execute"}] (a list
containing one choice set); every other entry stays a plain set and
keeps its existing all-of semantics. Both anomaly scripts now
isinstance-check expected and dispatch accordingly. Verified
manually:

  child_ops={'query_execute'}  -> no warning (correct)
  child_ops={'sparql_execute'} -> no warning (correct)
  child_ops={'other'}          -> warns missing one of:
                                  query_execute or sparql_execute

The trace_common.py and *_anomalies.py edits land under .claude/
which is gitignored, so this commit carries only the tracked-source
fixes (sort_by_key, dispatcher unit binding, multi.rs test
semicolon, and the multi-query CLI token persistence).

Tests: 73 envelope/snapshot/dispatcher unit + 5 CLI multi-query + 15
multi-query integration + 4 multi-query auth + 2 multi-query tracing
+ 47 server integration tests pass; cargo clippy --workspace
--all-features --all-targets -- -D warnings clean.
Two follow-ups on the multi-query CLI / server-integration coverage.

Policy flag forwarding from CLI -> server.

fluree multi-query previously didn't accept the PolicyArgs flag set
(--as, --policy-class, --policy[-file], --policy-values[-file],
--default-allow). That meant a user could supply those flags on
fluree query but not on fluree multi-query — a parity gap.

Commands::MultiQuery now flattens PolicyArgs the same way Query does;
the run() function takes &PolicyArgs and calls
client.with_policy(policy.clone()) on the constructed
RemoteLedgerClient. The headers then ride through the
transport (fluree-policy-class, fluree-policy, etc.); the server's
inject_headers_into_envelope folds them into the envelope's
top-level opts before validation, so the standard envelope -> sub-query
opts merge carries them into every alias automatically.

Notably this is symmetric with the existing single-query behavior on
fluree query and on POST /query — same flags, same headers, same
server-side fold-into-opts step. No client-side body injection is
needed because the envelope's opts come from the validator's view of
the envelope after header injection.

docs/cli/server-integration.md structure fix.

The previous insertion placed ### fluree multi-query between the
query family's endpoint list (### fluree query, insert, upsert,
update, track, info, exists) and the trailing paragraphs of that
section (policy-flag note, --at routing, --at --explain). Those
trailing paragraphs were written for the query family but ended up
visually attributed to multi-query. Moved the multi-query subsection
below those paragraphs so each section's body stays with its heading.

While in the doc, three substantive content adds:

1. fluree multi-query subsection now spells out that OIDC token
   refresh IS persisted back to config.toml after a successful round
   trip (matching fluree query), names the
   MaybeCredential + MaybeDataBearer extractor parity with /query,
   and is explicit that bearer ledger-scope enforcement is per-distinct
   ledger and rejects the whole envelope with 404 on any
   out-of-scope reference (not per-alias).

2. New explicit envelope-resident-knobs note: multi-query doesn't
   take --at (use envelope asOf), --track-* / --max-fuel (use
   envelope opts.meta and per-sub-query opts.max-fuel), or per-CLI
   policy injection into the body (headers only — server folds).

3. Policy Enforcement Contract gains a new paragraph for
   POST /multi-query: the CLI sends headers only (no body injection),
   the server folds headers into the envelope's top-level opts BEFORE
   validation so envelope-level rejections (max-fuel,
   maxConcurrency) catch values supplied via headers, and the
   standard envelope -> sub-query opts merge carries them into every
   alias.

docs/cli/multi-query.md options table now lists every policy flag with
descriptions matching the existing fluree query doc.

Verified: cargo clippy -p fluree-db-cli --all-features -- -D warnings,
cargo fmt --all -- --check, and the 5 CLI integration tests all green.
Three review nits on the multi-query CLI surface.

Positional file no longer routes to stdin on typos.

The previous implementation filtered the positional path through
.filter(|p| p.exists() && p.is_file()) — intended as permissive
fallback, but under a piped shell a typoed filename (fluree multi
-query missing.json | ...) silently passed through to stdin and
executed whatever was being piped in. Dropped the existence filter:
positional arg is always interpreted as a file path now, and
input::read_input surfaces a clean "failed to read <path>" error
when the file is missing.

--format validated before the network round-trip.

A typoed --format jzon would parse the envelope, build the
RemoteLedgerClient, POST to /multi-query, get a 200 response, and
only then fail locally in print_response — burning the server-side
work and the bearer's fuel. Extracted validate_format() and called
it at command entry; the print_response branch that used to return
an error is now unreachable.

Honest SPARQL policy documentation.

The previous wording in docs/cli/server-integration.md and
docs/cli/multi-query.md claimed CLI --policy* flags reach every
sub-query through the envelope opts merge. Mechanically true for the
headers — the server folds them into envelope opts and the merge
carries them into each sub-query — but operationally the SPARQL
dispatch path (query_from().sparql()) never reads body opts, so
SPARQL sub-queries only observe bearer ledger-scope, not identity /
policy-class / policy / policy-values / default-allow.

Rather than re-litigate the v1 scope-cut on SPARQL identity
threading (the same gap exists today on POST /query with
Content-Type: application/sparql-query and an inline FROM, and the
fix lands on both endpoints together), narrowed each claim:

- docs/cli/server-integration.md Policy Contract paragraph now has a
  per-language breakdown: JSON-LD sub-queries get full policy
  threading via apply_auth_identity_to_opts; SPARQL sub-queries
  match single-query connection-scoped SPARQL behavior with a
  pointer to the canonical v1 Limitations entry.
- docs/cli/multi-query.md Options table's policy footnote now spells
  out the same JSON-LD / SPARQL split.
- docs/api/multi-query.md Limitations entry renamed from "bearer
  identity / server-default policy-class" to the full opts set
  (identity, policy-class, policy, policy-values, default-allow) and
  pinned to "single-query connection-scoped SPARQL has the same
  gap; the fix lands together."

Tests:

Two new CLI integration tests in tests/integration.rs:

- multi_query_missing_positional_file_errors_clearly — typoed
  positional file name surfaces "failed to read <path>"
- multi_query_unknown_format_errors_before_network — --format typo
  errors at command entry, not after a successful HTTP round-trip

7 multi-query CLI tests now pass; cargo clippy --workspace
--all-features --all-targets -- -D warnings and cargo fmt --all --
--check both clean.
The previous limitations sections used vocabulary from our internal
investigation work that does not translate for outside readers:

- "Tier B cancellation" was a label from the cancellation-safety
  audit's three-tier classification. No reader who didn't run the
  audit knows what that means.
- "v1" / "v1.1" / "planned for a future release" / "queued for v1.1"
  are forward-looking scheduling statements. The shipping behavior is
  the only thing the docs should commit to; future work lives in
  tracking issues, not in normative reference docs.

Edits in docs/api/multi-query.md, docs/cli/multi-query.md,
docs/cli/server-integration.md, and docs/api/endpoints.md:

- Renamed the "Tier B cancellation" bullet to "Cancellation latency
  is bounded by in-flight storage reads" and described the actual
  behavior in plain English (deadline aborts the JoinSet; in-flight
  blocking reads complete; no new work starts) without classifying
  the safety tier.
- Renamed "Response size cap is best-effort, not an OOM guard" to
  "Response size cap is enforced at assembly, not throughout
  dispatch" and explained the peak-memory bound without claiming
  anything about future streaming work.
- Dropped every "planned for a future release," "v1.1," and "queued
  for" sentence. Limitations now describe shipping behavior only.
- Bounds table's "v1 status" callout now reads "the non-override
  values are compile-time defaults and not server-tunable today" —
  states the current shipping behavior, doesn't promise tuning will
  arrive.
- Renamed the section title in the body of the API doc from
  "Limitations" intro line "These are explicit v1 scope-cuts" to
  "The following are not supported and produce documented behaviour
  rather than silent partial success" — describes what the section
  contains without anchoring to a version label.
- "v1 limitations" wording in the CLI doc and server-integration doc
  cross-links changed to "current limitations."
- "in v1" qualifiers throughout the SPARQL policy parity paragraph
  removed — the gap is described as present, with the matching gap
  on connection-scoped SPARQL named for cross-reference.

Status header on docs/api/multi-query.md changed from
"v1 (envelope contract stable; some features deferred)" to
"envelope contract stable; some features explicitly out of scope."

Multi-query test suite unchanged (73 unit / 14 dispatcher /
15 integration / 4 auth / 2 tracing / 7 CLI) — this commit is
pure documentation copy-edit.
@bplatz
bplatz requested review from aaj3f and zonotope May 28, 2026 17:11
bplatz added 2 commits May 28, 2026 15:38
…::multi_query() builder, CLI local mode

Architectural fix: the multi-query envelope dispatcher, response
assembler, and per-sub-query execution helpers belonged in
fluree-db-api so downstream library consumers could call the feature
in-process. Before this change, every piece below the HTTP boundary
lived in fluree-db-server, which made `/multi-query` reachable only
via HTTP. The CLI, embedded Rust apps, custom servers, and tests all
had to round-trip through HTTP to get an envelope to execute. That
defeated the point of building multi-query as a first-class feature.

This relocates the execution surface to the api crate, exposes it as a
builder mirroring the .query_from() pattern, slims the server handler
to authn/authz plus a single delegation call, and gives the CLI a
local in-process mode that runs envelopes without any server.

# Relocation

Three files move from fluree-db-server/src/routes/ into
fluree-db-api/src/query/:

- multi_dispatch.rs — parallel JoinSet/Semaphore dispatcher with the
  envelope-deadline select! loop, span emission, and the per-
  sub-query effective-timeout computation. Signature changes from
  Arc<AppState> to Arc<Fluree>.
- multi_response.rs — response assembler with running byte-count
  size cap and per-alias outcome bucketing. Pure data shuffling, no
  server dependency.
- multi_run.rs (new) — extracted run_jsonld_subquery and
  run_sparql_subquery helpers (formerly in routes/query.rs). They
  call state.fluree.query_from().jsonld() / .sparql(), so they're
  api-native — the relocation is mechanical.

The dispatcher's existing 14 unit tests + 8 response-assembler unit
tests move with the code.

# Fluree::multi_query() builder

New public API mirroring .query_from() conventions:

  let fluree: Arc<Fluree> = Arc::new(FlureeBuilder::memory().build_memory());
  let response = fluree.multi_query()
      .envelope(envelope)
      .bounds(MultiQueryBounds::DEFAULT)  // optional
      .execute()
      .await?;

Fluree::multi_query() takes &Arc<Self> because the dispatcher needs
Arc<Fluree> to clone into each tokio task. Server use is natural
(state.fluree is already Arc<Fluree>); other consumers wrap once at
construction.

Errors surface via a typed MultiQueryError enum:
- Validation (4xx via #[from] MultiQueryValidationError)
- Snapshot (5xx via #[from] ApiError)
- ResponseAssembly (5xx via #[from] ResponseAssemblyError)
- EnvelopeRequired (programmer error)

The server handler maps each variant to its HTTP status without
losing context, exactly mirroring its prior bespoke error mapping.

# Public API audit

After the relocation an opportunistic visibility pass demoted six
items from pub to pub(crate): AliasOutcome, AliasOutcomeKind,
DispatchConfig, run_envelope, dispatch_subqueries, assemble_response.
None have external consumers today; keeping them pub would commit
us to a stable contract for implementation details. They can be
promoted later if a real use case emerges. The committed public
surface is the builder + MultiQueryError + the per-sub-query
helpers (run_jsonld_subquery / run_sparql_subquery + SubqueryOutput)
that the server's execute_dataset_query reuses for single queries.

# Server handler refactor

The /v1/fluree/multi-query handler shrinks from ~200 LOC to ~85 by
delegating execution to the api crate. Authn/authz stays at the
edge:

1. Bearer-or-signed-credential check.
2. Header injection into envelope.opts (so envelope-level rejections
   apply to header-supplied values like maxConcurrency).
3. Validation (re-run cheaply by the api crate too, but we need the
   distinct-ledger set here for the bearer-scope check).
4. Bearer ledger-scope enforcement per distinct ledger (404 on
   any out-of-scope reference, matching single-query existence-leak
   avoidance).
5. Pre-merge envelope.opts ⊕ sub.opts into each sub-query body's
   opts, then run the impersonation gate per sub-query (see
   "Auth opts merge precedence" below).
6. Single delegation: state.fluree.multi_query().envelope(...).execute().

The body's MultiQueryResponse is serialised straight through.
Per-alias error mapping, timeout reporting, snapshot echo — all
handled by the api crate now.

# CLI local in-process mode

`fluree multi-query` gains a third transport tier:

1. --remote <name> → named HTTP remote (with OIDC token refresh
   persistence as before).
2. Auto-route to running local server when --remote is omitted and
   server.meta.json reports a live pid; suppressed by --direct.
3. **In-process local** → calls Fluree::multi_query() against the
   .fluree/ storage tree directly. Used when neither --remote nor a
   running server is available, OR when --direct is set without
   --remote. This is the natural counterpart to `fluree query`
   running locally.

The previous "no transport available" error path is gone; --direct
is no longer an error condition without --remote. Policy flags ride
through to all three tiers — for in-process they fold into envelope
opts via the typed PolicyArgs accessors (single-value or repeated
--policy-class both produce the expected array shape).

A new positive integration test
(multi_query_local_in_process_against_seeded_ledger_succeeds) creates
a ledger via the CLI, inserts data, runs a multi-query envelope, and
asserts the seeded value appears in the response — end-to-end proof
that the relocation does what it set out to do.

# Per-alias tracking surface

New top-level `tracking` field on MultiQueryResponse, indexed by
alias, mirroring the existing `results` / `errors` per-alias maps.
Each entry is a TrackingTally with `time` / `fuel` / `policy`
siblings, matching what single-query TrackedQueryResponse returns at
the top level. Populated whenever a sub-query's merged opts enabled
tracking (envelope-level opts.meta: true, per-sub-query opts.meta:
true, or any opts.max-fuel). Omitted entirely from the wire
(skip_serializing_if = IndexMap::is_empty) when no sub-query
tracked, so tracking-unaware clients see no extra field.

Aggregate rollups stay in meta:
- meta.fuel_total = sum of per-alias fuel (only when envelope
  opts.meta is enabled, since envelope-level aggregation is the
  envelope's promise).
- meta.elapsed_ms = envelope wall-clock from validate-entry through
  assembly (previously this started only after snapshot resolution,
  understating the actual time).

Order in the tracking map mirrors submission order so a client can
walk tracking and results in lockstep.

# Auth opts merge precedence (security-relevant)

This is the most subtle piece of the refactor. The dispatcher merges
opts from three layers; an earlier review found two related
identity-bypass paths through the merge order:

(a) The server's impersonation gate pre-injected the forced bearer
    identity into sub.query["opts"] (the body). The api dispatcher
    then computed merged_opts(envelope, sub.opts) and OVERWROTE the
    body's opts with the result — discarding the gate's decision.
    A user could spoof identity by setting envelope.opts.meta = true
    (any envelope-level opt was enough to trigger the overwrite).

(b) The impersonation gate looked only at sub.query["opts"]["identity"]
    when deciding whether to honor body-supplied opts. Envelope-level
    opts.identity bypassed the gate entirely because the gate ran
    before any merge could surface it.

Both are fixed via two coordinated changes:

1. Server premerge_opts_into_subquery_body (before the gate runs):
   merges envelope.opts ⊕ sub.opts into each sub.query["opts"] with
   body winning, so the gate sees the final opts.identity from any
   layer before deciding.

2. Dispatcher merge order: envelope.opts ⊕ sub.opts ⊕
   sub.query["opts"], body wins. The gate's decision (written into
   the body in step 1) is the most-specific layer and survives.

The same precedence applies to sub_query_timeout_ms, which previously
only checked sub.opts and envelope.opts. A body-level opts.timeoutMs
showed up in the merged opts but didn't reach tokio::time::timeout —
now it does.

Four merge-order unit tests in multi_dispatch.rs::tests::merge_* and
two timeout-precedence tests pin the rule down so any future
refactor that reverses the order fails fast.

# opts.t rejection at every level

Validation now rejects opts.t at three levels:
- envelope.opts (added — was missed)
- sub.opts (already enforced)
- sub.query["opts"] body opts (added — the body layer's new
  primacy made this critical; before the merge-order fix it was
  practically inaccessible, but a body opts.t now wins, so silent
  override was a real bypass path)

History queries (the `to` field) similarly rejected, JSON-LD and
SPARQL alike. envelope.opts also rejects max-fuel/max_fuel/maxFuel
since shared fuel across parallel sub-queries isn't tracked yet.

# Misc fixes folded in

- meta.elapsed_ms moved to start before validation + snapshot
  resolution. The previous timer started only at dispatch entry,
  understating wall-clock by the validation + nameservice cost.
- CLI inject_policy_into_envelope rewritten against typed PolicyArgs
  fields. The previous version went through policy_headers which
  flattened the Vec<String> for --policy-class into separate header
  tuples; the dedup loop dropped all but the first value. Now
  --policy-class A --policy-class B → opts.policy-class = ["A", "B"]
  (always an array, matching FlureeHeaders::inject_into_opts).
  Single values stay arrays for consistency.
- --format validated up front (before any network round-trip) so a
  typo like --format jzon doesn't burn a server-side multi-query
  before failing locally.
- Positional path argument no longer filters on file existence; a
  typoed filename surfaces as a clear "failed to read <path>" error
  rather than silently routing to stdin under a piped shell.
- run_envelope timer covers validation through assembly, not just
  dispatch.

# Docs

- docs/api/multi-query.md
  - opts merge section now names all three layers (envelope, sub.opts,
    body) and the security relevance of the precedence.
  - Response shape gains the tracking field and the per-language
    "Tracking detail" subsection.
  - "Per-sub-query effective timeout" includes body opts in the chain.
  - opts.t rejection note covers all three layers explicitly.
- docs/cli/multi-query.md
  - Transport section rewritten to describe all three tiers (remote /
    auto-route / in-process) — previously claimed multi-query
    "requires a Fluree server."
  - Examples updated for the local-mode case.
- docs/cli/server-integration.md
  - Multi-query subsection rewritten to drop the "no in-process"
    claim and describe the third transport tier honestly.
  - "Envelope-resident knobs" paragraph corrected: multi-query DOES
    take the full --policy* flag bundle (matches the CLI surface);
    only --at and --track-* / --max-fuel are replaced by envelope
    knobs.
- docs/operations/telemetry.md unchanged — the sub_query span
  hierarchy is identical (same emit sites, just in a different
  crate).
- .claude/skills/trace-{inspect,overview}/references/span-hierarchy.md
  updated to note the relocated module path (.../fluree-db-api/...)
  and that sub_query spans now appear in any trace where
  Fluree::multi_query() runs, not only HTTP.

# Tests

- New fluree-db-api/tests/it_multi_query.rs (8 integration tests):
  builder happy path with mixed JSON-LD + SPARQL, two-ledger shared
  snapshot, envelope-meta and per-sub-query-meta tracking variants,
  validation typed-error surfacing, partial-failure per-alias
  reporting, builder envelope-required error, bounds override
  threading through to the assembler. These are the canonical
  "downstream Rust consumer" smoke tests.
- New CLI commands::multi_query::tests (5 unit tests): policy
  injection preserves repeated --policy-class, envelope opts win
  over CLI flags, single --policy-class still emits array,
  default-allow only when true, no-flags is a no-op.
- New multi_query_integration tests (2): per-alias tracking present
  under envelope opts.meta, per-sub-query opts.meta only tracks the
  opted-in alias.
- New multi_dispatch::tests merge-order regression (4): body opts
  win over envelope and sub.opts independently; envelope opts lift to
  body when no conflict; sub.opts wins over envelope.
- New sub_query_timeout regression (2): body opts.timeoutMs wins
  over both sub.opts and envelope; chain still works when no body
  opt is set.
- New multi::tests rejection (3): opts.t at envelope level, opts.t in
  body opts, history queries via to/to_graph.

Full test ledger after this change:
- 6474/6474 cargo nextest workspace tests passing
- cargo fmt --all -- --check clean
- cargo clippy --all --all-features --all-targets -- -D warnings clean

# Breaking changes

None at the wire layer. The HTTP request/response format is
unchanged; existing HTTP clients see no difference except the
additional optional `tracking` field on responses when tracking
is enabled.

Source-level changes for downstream Rust consumers of fluree-db-api:
- New public symbols (Fluree::multi_query, MultiQueryBuilder,
  MultiQueryError, run_jsonld_subquery, run_sparql_subquery,
  SubqueryOutput, MultiQueryRequest/Response and friends from
  query::multi).
- No removals from the existing single-query API surface.
…-format/--normalize-arrays/--output

Add per-alias output formatting to the multi-query envelope across the
api, server, and CLI:

- `MultiQueryBuilder::format(FormatterConfig)` mirrors the single-query
  `.format(...)` builder. TypedJson/SparqlJson/AgentJson apply across
  every alias; JsonLd applies to JSON-LD aliases (SPARQL aliases keep
  SPARQL Results JSON so `--normalize-arrays` composes cleanly with
  mixed envelopes); non-JSON formats reject at `.execute()` with
  `MultiQueryError::UnsupportedFormat`.
- Server negotiates the per-alias format from request headers with
  precedence `Fluree-Output-Format` > `Fluree-Normalize-Arrays` alone >
  `Accept`. Byte-shape Accept values (TSV/CSV/SPARQL XML/RDF XML) return
  406 only when no explicit `Fluree-Output-Format` is set. Unknown
  `Fluree-Output-Format` values return 400. Span error code reflects the
  actual error class (BadRequest vs NotAcceptable).
- CLI splits the old `--format json|pretty|aliases` into two flags
  matching `fluree query` semantics: `--format json|typed-json` for
  per-alias result shape, `--normalize-arrays` for JSON-LD array
  normalization, `--output json|pretty|aliases` for envelope display.
  Remote requests send the matching headers via the new
  `multi_query_with_headers` client method; in-process requests build
  the same `FormatterConfig` and call `.format(cfg)` directly.

Tests and docs updated accordingly.
Base automatically changed from fix/empty-objects to main May 29, 2026 19:21
@bplatz
bplatz merged commit c2460a6 into main May 31, 2026
14 checks passed
@bplatz
bplatz deleted the feature/multi-query branch May 31, 2026 17:41
bplatz added a commit that referenced this pull request Jun 1, 2026
rollup: Cumulative work from #1258, #1260, #1261, #1262, #1263 (mis-merged to solo/latest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant