Skip to content

rollup: Cumulative work from #1258, #1260, #1261, #1262, #1263 (mis-merged to solo/latest) - #1264

Merged
bplatz merged 83 commits into
mainfrom
solo/latest
Jun 1, 2026
Merged

bplatz merged 83 commits into
mainfrom
solo/latest

Conversation

@bplatz

@bplatz bplatz commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Rollup PR — cumulative solo/latest → main

The five PRs below were mistakenly merged into solo/latest instead of main on 2026-05-31. Because their head commits became reachable through those merges, GitHub auto-marked all five as MERGED and closed them — so they can no longer be reopened or reviewed individually. This PR re-surfaces their combined diff for review into main as a single rollup.

main has no divergent commits; solo/latest is strictly ahead, so this diff is exactly the cumulative work and nothing else.

Consolidated PRs

Follow-up commits (not part of any of the 5 PRs above)

Made directly on solo/latest later the same evening; all extend the bulk-import work in #1263:

  • d58f04b30 / 3270cc4c9 — fix: guard Turtle lexer/parser against >4GiB input overflow
  • a984205c3 — perf: rechunk directory imports by bytes (split large + coalesce small)
  • 9da6c0a00 — Merge branch 'feature/nt-import' into solo/latest

CI must pass: clippy (all features, all targets) + nextest (workspace, all features).

bplatz and others added 30 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.
…::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.
Adds an optional forward-predicate allow-list to RangeOptions and threads
it through binary_range_eq_v3 so that per-subject SPOT scans driven by
hydration (the `select: {"?x": ["ex:a", "ex:b"]}` projection path) skip
discarded predicates BEFORE the row's subject re-resolve, predicate IRI
lookup, object decode, and dict-touch fuel charge.

Previously, hydration paid the dict-touch + decode cost for every flake on
the subject, then dropped the unselected predicates at the JSON projection
step. The work and fuel were independent of the projection's field count.
With this change, narrow Explicit projections cost proportionally less
work and fuel; Wildcard projections still take the legacy
decode-everything path with zero overhead from the new filter.

The row loop also reuses the bound match_val.s subject Sid instead of
calling resolve_subject_sid per row, dropping one redundant dict touch
per scanned base row on the indexed path.

Also applied to the overlay_only_flakes fallback for parity on
novelty-only subjects.
Documents the new behaviour: an Explicit projection
(`select: {"?x": ["@id", "ex:a", "ex:b"]}`) hands the range provider a
predicate allow-list so the per-subject SPOT crawl skips dict touches
and decode work on non-listed predicates. Wildcards keep the legacy
decode-everything path.
When a projection's Explicit level lists exactly one forward predicate,
hydration routes through RangeMatch::subject_predicate instead of
RangeMatch::subject + predicate_filter. Same number of cursor descents and
same INDEX_TOUCH fuel, but the cursor's leaflet key-range narrows to the
(s, p) prefix — skipping the per-row binary_search against the filter and
the in-batch scan over the subject's other predicate rows.

K >= 2 stays on SPOT(s,*,*) + predicate_filter because two cursor descents
would each pay their own INDEX_TOUCH and beat the single-scan baseline.

Pattern repeats recursively through nested hydrations: each ref-with-
sub-spec dispatches through the same format_subject path, so nested
single-predicate selections (chain walks) all take the K=1 fast path
naturally.
Two correctness/perf gaps surfaced by review.

(1) Novelty-only predicates were silently dropped on the K>=2 path.
predicate_filter_p_ids was built from store.sid_to_p_id resolutions
only, so an overlay assert on a selected predicate that has no
persisted p_id yet (novelty-only) — surviving the overlay translator's
Sid filter and landing in the cursor stream under an ephemeral p_id
assigned by translate_one_flake_v3_pub — failed the row-loop's
persisted-id gate and got discarded. Fix: after overlay translation,
walk ephemeral_p_id_to_sid and extend the allow-set with every
ephemeral p_id whose mapped Sid is in opts.predicate_filter.

(2) Explicit projections with no forward Property items (e.g.
`["@id"]` or reverse-only) still opened the SPOT cursor, paying one
INDEX_TOUCH (0.010 fuel) per leaflet batch returned even though the
row loop dropped every row. Fix: short-circuit in format_subject —
when predicate_filter_for_level returns Some(empty), use Vec::new()
directly. `@id` and reverse properties are emitted by the dedicated
paths further down in format_subject.

Tests:
- novelty_only_predicate_survives_k_ge_2_gate: seed+reindex base,
  insert ex:noveltyPred without reindex, project ["ex:p1",
  "ex:noveltyPred"], assert both come back.
- id_only_projection_skips_forward_cursor: project ["@id"] only,
  assert just @id is emitted and fuel is measurably lower than K=1.

All 8 hydration tests pass; 11 existing novelty-adjacent tests still
pass; clippy/fmt clean.
Move the `mod tests` block to the bottom of `fluree-db-memory/src/store.rs`.
The SPARQL result parsing helpers (`parse_memories_from_sparql_results`,
`iri_to_kind`, etc.) were defined after the test module, which trips
`clippy::items_after_test_module` under `-D warnings`. Pure relocation,
no behavior change.
LedgerManager::get_or_load inserted LoadState::Loading before awaiting
the load I/O and only cleared it on the publish path. If the leader
future was dropped in between (HTTP handler dropped on client disconnect,
task abort, or an outer timeout), the Loading slot was orphaned forever —
sweep_idle deliberately never evicts Loading — so every later caller for
that ledger parked on rx.await indefinitely. A single cancelled cold load
could permanently wedge a ledger on a long-lived connection.

Add a LoadingLeaderGuard that, on drop-before-publish, reclaims the slot
via a detached task (Drop is sync, the entries lock is async). Removing
the entry drops the queued waiter senders, so waiters receive RecvError
and the next caller re-elects a leader. The leader disarms once it holds
the publish lock; there is no await between lock acquisition and disarm,
so there is no mid-publish cancellation window.

Tag each Loading slot with a generation token so the detached cleanup
removes only its own slot — if the original orphan was already cleared
(e.g. by disconnect) and a new leader inserted a fresh slot, the stale
guard leaves it untouched.

Also hoist load_and_attach_binary_store().await out from under the
entries write lock. Holding the write lock across that S3 I/O turned the
whole ledger cache into a global mutex for the duration of any cold load;
the lock is now held only for the brief, await-free publish.
TEMPORARY — revert before merge (git revert of this commit is clean).

Adds info!-level phase markers so the wedge localizes on the next deploy
with 100% repro. info! (not debug!/debug_span!) is deliberate so the
markers are visible at the Lambda's default log level; this intentionally
deviates from the debug_span! convention for the duration of this
debugging branch only.

multi_dispatch.rs run_envelope:
  mq.run_envelope.start / mq.validate.ok / mq.snapshot.resolved /
  mq.dispatch.config / mq.dispatch.complete / mq.assemble.ok
dispatch_subqueries (per alias): mq.sub.spawn / mq.sub.permit.acquired /
  mq.sub.done(status); drain: mq.drain.deadline_fired(remaining) /
  mq.drain.deadline_drained
ledger_manager.rs get_or_load: ledger.load.waiter.park /
  ledger.load.leader.begin / ledger.load.state.done(ok) /
  ledger.load.binary_store.done / ledger.load.leader.publish(ok)

Reading the last marker before silence localizes the hang:
- leader.begin without state.done  -> nameservice (DDB, no default timeout)
- state.done without binary_store.done -> S3 index/dict load
- snapshot.resolved without sub.done   -> sub-query sync block_on(S3) bridge
- sub.permit.acquired without sub.done -> that sub-query's execution wedged
- waiter.park with no leader publish   -> orphaned Loading slot
BinaryScanOperator::next_batch ran its synchronous cursor produce+decode
region inline on the tokio worker. That region bridges to async S3 via
block_on deep inside leaf reads (binary_index_store run_sync_on_runtime)
and, crucially, dict-tree reads (dict/reader fetch_remote_leaf_bytes),
which spawn an OS thread that re-injects cs.get() onto the outer runtime
and park the worker on rx.recv() with no block_in_place of their own.

On a small multi-thread runtime (AWS Lambda: 2 workers) under multi-query
fan-out, every worker parks inside those bridges with no thread left to
drive the IO reactor / time wheel, so the re-injected S3 futures never
complete and the envelope deadline never fires — a hard wedge until the
900s Lambda kill. The pre-existing block_in_place only covered the leaf
read, not the dict decode where the terminal deadlock lives.

Relocate the whole produce+decode region onto a blocking context via
tokio::task::block_in_place, gated to remote/CAS-backed stores on a
multi-thread runtime. block_in_place converts the calling worker and lets
tokio promote a replacement that keeps driving the reactor/timer, so the
bridge futures complete. It is preferred over spawn_blocking here because
the region borrows ExecutionContext and apply_inline can itself trigger
dict/S3 decode — block_in_place imposes no Send/'static bound and the
region runs to completion with no await, so there is no cancellation hole
and decode semantics are byte-for-byte unchanged. Local file / in-memory
scans keep the region inline (no per-batch hop on the all-local path).

Remoteness is plumbed via ContentStore::is_remote() (method-based:
file/memory local, everything else remote), surfaced on BinaryIndexStore
and read into BinaryScanOperator at open().

it_blocking_bridge_runtime reproduces the exact bridge fan-out on a
2-worker runtime: it completes under block_in_place and wedges without it.
The previous fix (6f4088f) wrapped BinaryScanOperator::next_batch's
produce+decode region in block_in_place for remote stores. That was the
wrong region: the terminal wedge is in the dict-tree bridge, and the cold
dict reads that wedge fire during open() (overlay translation:
translate_overlay_flakes -> resolve_subject/string_v3 -> dict lookups),
not in next_batch's drain loop — so the wrap had no effect and the
envelope still wedged (mq.sub.done = 0). Reverted, along with the now-
unused ContentStore::is_remote plumbing.

Root cause: the dict bridge (dict/reader.rs fetch_remote_leaf_bytes) and
forward-pack bridge (dict/pack_reader.rs fetch_and_load) hand-rolled
`thread::spawn` + outer `Handle::block_on` + `rx.recv()`/`join()` with no
block_in_place, re-injecting the S3 fetch onto the OUTER runtime. On a
small (2-worker, e.g. AWS Lambda) runtime under query fan-out, every
worker parks in recv()/join() with no thread left to drive the IO
reactor, so the re-injected fetch never completes — a hard deadlock,
wherever those bridges are called.

Fix at the bridge level: make run_sync_on_runtime pub(crate) and route
both dict and pack fetches through it. On a multi-thread runtime it uses
block_in_place(handle.block_on), so the calling worker is converted and
tokio promotes a replacement that keeps driving the reactor while this
thread blocks; on current-thread it uses a self-contained helper runtime
(preserving the bridges' runtime-agnostic intent). This covers every
CAS-backed dict/leaf/pack read regardless of call site (open or
next_batch), with no gate. The leaf bridge already used this helper.

run_sync_on_runtime_frees_workers_under_fanout proves a 2-worker runtime
completes 32 concurrent bridged fetches instead of wedging.
Residual after the dict/pack bridge fix: the multi-query wedge dropped
from system-wide gridlock (0/8 envelopes complete) to an isolated,
whole-envelope, container-burning wedge (~1 envelope/burst, accumulating).

Cause: moka single-flight is synchronous. When N callers contend on the
same key, one runs the initializer (now block_in_place-covered) and the
other N-1 block the calling thread waiting for it — with no block_in_place
of their own. An envelope's 4 sub-queries scanning the same ledger
contend on the same cold dict-leaf / column-batch keys, so on a 2-worker
runtime the waiters park both workers, nothing drives the IO reactor, the
leader's block_on CAS fetch never completes, and the moka key stays locked
forever — burning that container until the 900s Lambda timeout. The
envelope's drain-loop deadline never fires because its workers are gone.

Fix: peek the cache first (non-blocking get) and, only on a miss, run the
single-flight wait+init inside `in_blocking_region` (block_in_place on a
multi-thread runtime, inline otherwise). A waiting worker is then
converted so tokio promotes a replacement that keeps driving the reactor.
Applied to every single-flight method: dict leaf, V3 column batch, vector
shard, stats view, and the R1/R2 region macro. Cache hits skip the region
entirely, so the warm hot path is unchanged.

leaflet_cache_single_flight_frees_workers_under_contention exercises the
real try_get_or_load_dict_leaf: 8 callers on the same cold key complete on
a 2-worker runtime (it deadlocks without the wrap).
The mq.* / ledger.load.* phase markers added for the wedge investigation
were info! so they'd show at the Lambda's default log level. The wedge is
fixed and confirmed, so downgrade them to debug! — zero cost at the prod
info! level per the tracing guide, while keeping the instrumentation
available for future diagnosis. mq.drain.deadline_fired /
deadline_drained / mq.snapshot.err stay at warn! (abnormal conditions).
The dict-leaf and forward-pack bridges had no per-fetch ceiling — only the
storage backend's own request timeout (S3's 35s send_timeout) bounded
them. Make cas_sync_timeout() pub(crate) and wrap both bridges' fetch
futures in tokio::time::timeout(cas_sync_timeout()), matching the leaf
read path. With the bridges now block_in_place-covered the timer can
actually fire, so a stalled CAS fetch becomes a bounded error instead of a
long (or, against a future uncovered layer, unbounded) block. No-op when
the env var is unset (default).
bplatz added 7 commits May 31, 2026 13:19
Bulk import regressed ~3.9x on large datasets (390M-flake DBLP: 0.46M flakes/s vs ~1.7M). The secondary-order remap worker hooks set rdf:type p_id, which made IdStatsHook build five per-subject maps for every distinct subject (~68M x 6 workers), then merge them serially (~283s) and finalize single-threaded (~249s) -- 62% of the import. Those maps existed only to produce uncapped class ref-target stats, working around ClassBitsetTable's 64-class cap.

Replace ClassBitsetTable with ClassMembership: a dense 64-class bitset that transparently promotes to a sparse per-subject class list above 64 classes (uncapped, memory-flat in class count). SpotClassStatsCollector now produces uncapped class_prop_refs directly, so import and rebuild pass None to build_class_stat_entries and no longer build per-subject id-hook maps. Worker hooks no longer set rdf:type p_id; they keep only the cheap per-property HLL / datatype / graph-flake stats.

Add a per-build entry budget (MAX_CLASS_REF_LEAF_ENTRIES) that truncates the rarest class pairs instead of OOMing on pathological class graphs. Fix IdStatsHook::merge_from silently dropping subject_prop_dts/langs. Move fluree-db-memory's test module to end of file (items_after_test_module).

DBLP 390M-flake import: 848s (0.46M/s) -> 215s (1.81M/s); the two id-stats phases drop from ~531s combined to near zero. <=64-class ledgers ride the dense bitset, larger ontologies use the sparse path.
Token byte offsets are u32, so feeding a single >4 GiB string to the
tokenizer (e.g. a whole .ttl/.nq/.trig file on the non-streamed import
path) wrapped the offset mod 2^32 and panicked when slicing the source.

Add check_input_len() at both lexer/parser entry points (Lexer::tokenize,
Parser::new) so oversized input returns a clean TurtleError instead of a
wrapped-offset panic. Offsets stay u32: streamed .ttl/.nt chunks are
bounded well below the limit, so the per-chunk strings never overflow.

Add an integration test that forces a large plain .nt file through the
streaming-split path and queries boundary values across chunk splits.
Token byte offsets are u32, so feeding a single >4 GiB string to the
tokenizer (e.g. a whole .ttl/.nq/.trig file on the non-streamed import
path) wrapped the offset mod 2^32 and panicked when slicing the source.

Add check_input_len() at both lexer/parser entry points (Lexer::tokenize,
Parser::new) so oversized input returns a clean TurtleError instead of a
wrapped-offset panic. Offsets stay u32: streamed .ttl/.nt chunks are
bounded well below the limit, so the per-chunk strings never overflow.

Add an integration test that forces a large plain .nt file through the
streaming-split path and queries boundary values across chunk splits.
Directory imports of .ttl/.nt files previously produced one chunk per
file via the index-based Files path, which throttled parsing to 2-3
concurrent chunks (max_inflight) regardless of thread count and made
the chunk count k track the number of input files. A directory of one
huge file was a single multi-GB work item; a directory of many small
files produced one commit and a fan-out of sorted run files per file.

Route all-Turtle/N-Triples directories through a new channel-fed
LocalChunkProducer that rechunks by bytes instead of file boundaries:

- Large files (and compressed files whose estimated decoded size
  exceeds chunk_size) are sub-split at statement boundaries via
  StreamingTurtleReader, with the prefix block prepended so each
  emitted payload is a self-contained Turtle document.
- Small files are read whole and coalesced up to ~chunk_size once a
  directory holds more than coalesce_small_files_threshold (default 64)
  small files. A file containing a labeled blank node (_:) or an
  @base/BASE directive is never coalesced (it would change RDF document
  scope) and passes through as its own chunk.

LocalRechunk reuses the existing remote-parallel worker arm, so it
parses N-wide with no max_inflight throttle. Directories containing any
.trig/.nq/.jsonld continue to use the per-file serial path.

The threshold is configurable via the builder and the
FLUREE_IMPORT_COALESCE_THRESHOLD env var (0 disables coalescing).
# Conflicts:
#	fluree-db-api/tests/it_import.rs
@bplatz
bplatz requested review from aaj3f and zonotope June 1, 2026 14:27

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

PR #1264 — Review Worksheet

Two sections:

  1. Inline comments & suggested edits — grouped by severity, each with the exact
    file:line to comment on and proposed wording/fix.
  2. Top-level review submission comment — copy/paste as the review body.

Legend: 🔴 Critical (blocking) · 🟠 High · 🟡 Medium · 🔵 Low · ⚪ Nit/Info


1. Inline comments and/or suggested edits

🔴 CRITICAL-1 — Reverse-POST overlay lane returns wrong DESC order / wrong top-k under novelty

File: fluree-db-query/src/fast_post_order_limit.rs:578 (and the window at :613-619, fall-through at :646)

The overlay lane bounds each leaf's assert window with leaf_lo = leaf.first_key.o_key
(line 578), then take_while(|r| r.o_key >= leaf_lo). But first_key is the first
record of the whole leaf, and leaves are not predicate-homogeneous: leaflets
flush on p_id change (format/leaf.rs:229-233) but a leaf only flushes on
leaf_target_rows (:189). leaf_entries_for_predicate (fast_path_common.rs:292,
via find_leaves_in_range) returns the boundary leaves, whose first_key can belong
to a lower predicate sharing the leaf. So leaf_lo is an unrelated predicate's
o_key (possibly a different o_type's encoding space).

Consequence: when a shared leaf's foreign first_key.o_key is greater than some of
this predicate's assert o_keys, those asserts are excluded from the window and fall
to tail_asserts (line 646), which is emitted after every base row. A freshly
written value that should rank at/near the top of ORDER BY DESC(?o) LIMIT k is then
ordered last — and if emit_merged reaches need first (line 635), it is dropped from
the result entirely. This is wrong order and a wrong top-k set, data-dependent,
on the precise "latest feed right after a write" workload this path targets. Most acute
for small/medium predicates that fit within one shared leaf.

The production cursor does this correctly via compute_overlay_window
(binary_cursor.rs:691) using the full first_key/next_first_key at leaflet
granularity. The base lane here is fine — only the overlay window is wrong.

Fix options (pick one):

  • Correct fix: bound the window by the actual minimum o_key of this predicate's
    rows in the leaf. You already build leaf_base (DESC) by filtering
    entry.p_const == Some(p_id); use leaf_base.last().map(|r| r.o_key) as leaf_lo
    (and skip leaves where leaf_base is empty), rather than leaf.first_key.o_key.
    Equivalently, reuse compute_overlay_window semantics.
  • Safe interim: when novelty is present, return Ok(None) from the overlay lane
    and fall back to the generic top-k. Loses the fast path under novelty but is provably
    correct; ship the windowing fix as a follow-up.

Either way, add e2e regression tests (none exist for the overlay leaf-walk): a
predicate sharing a leaf with a lower-p_id predicate whose values are larger, plus a
novelty assert that should top the result; and a novelty-only-subject case.


🔴 CRITICAL-2 — Multi-query SPARQL aliases are not policy/identity enforced

Files: fluree-db-server/src/routes/query.rs:2703-2714; fluree-db-api/src/query/multi_dispatch.rs:692-730; fluree-db-api/src/query/multi_run.rs:98-130

The per-alias auth loop only runs for JSON-LD:

// query.rs:2708
if matches!(sub.language, SubqueryLanguage::JsonLd) {
    premerge_opts_into_subquery_body(...);
    apply_envelope_subquery_auth(...).await;   // impersonation gate + identity inject
}

SPARQL aliases skip the impersonation gate and identity injection. And the
dispatcher's SPARQL branch (multi_dispatch.rs:692) → run_sparql_subquery
(multi_run.rs:98) only threads TrackingOptions (time/fuel/policy tracking flags +
max_fuel) — there is no channel for identity / policy_class / policy /
policy_values. query_from().sparql() resolves to build_dataset_view (no policy),
not _with_policy.

Contrast the single-query SPARQL path (query.rs:1473-1577), which builds
QueryConnectionOptions { identity, policy_class, policy, policy_values, default_allow }
and routes through db_with_policy when has_any_policy_inputs(), and runs
resolve_sparql_identity (policy_auth.rs:148). JSON-LD aliases here are enforced
correctly; SPARQL aliases are not.

Effect: a caller authorized to reach a ledger (ledger-scope is enforced for
both languages, query.rs:2666) but whose identity should see a restricted view via
f:policyClass will see all rows/predicates of that ledger through a SPARQL alias.
Server-side impersonation decisions and fluree-policy-* headers are silently dropped.

Fix options:

  • Correct fix: build a policy context from the merged opts for SPARQL too, run the
    impersonation gate for SPARQL aliases (mirror resolve_sparql_identity), and add a
    policy-aware SPARQL execution helper (query_from().sparql().policy(ctx)).
  • Safe interim (fail-closed): reject (envelope validation error) any SPARQL alias
    when the request carries identity/policy inputs, until enforcement is wired.

Add an integration test: ledger with an f:policyClass restricting an identity →
assert a SPARQL alias under that identity returns the restricted view. (Current
multi_query_auth_integration.rs only covers ledger-scope 404.)


🟡 MEDIUM-1 — Overlay COUNT cursors project narrow columns; identity-merge is correct only because the cache always loads all columns

Files: fluree-db-query/src/fast_path_common.rs:186-233 (cursor_projection_*); fluree-db-binary-index/.../binary_cursor.rs:450-492; masked by column_loader.rs:248-251

The count-plan overlay cursors project narrow subsets (SId-only, OType+OKey).
merge_overlay_into_batch compares base rows vs overlay ops on the full V3 identity
(p_id, o_type, o_key, o_i). Unprojected columns return AbsentDefault
(p_id→0, o_i→u32::MAX), which would break the sort/identity comparison and
over/undercount. This is masked in production because
load_columns_cached_via_handle ignores the caller projection and always loads
ColumnProjection::all(), and api/server always inject a leaflet cache. A
BinaryIndexStore built without a cache (LedgerManagerConfig::default(),
leaflet_cache: None) would take the non-cached path and silently miscount under
overlay. PSOT had this shape pre-PR; this PR extends it to POST.

Recommendation: make the invariant explicit — either have
build_overlay_cursor_for_predicate augment the projection with the identity columns
(PId/OType/OI) whenever overlay ops are attached, or add a debug_assert in
BinaryCursor that the projection includes identity columns when set_overlay_ops is
non-empty. Add one overlay COUNT test on a no-cache store to lock it.


🔵 LOW / ⚪ INFO — non-blocking

  • 🔵 fluree-db-query/src/count_plan_exec.rs:989 — assert!(chain.predicates.len() >= 2, …)
    on the query path (release-mode panic) while the overlay twin (:1717) uses
    debug_assert!. Make it debug_assert! or return Ok(None).
  • 🔵 fluree-db-query/src/fast_post_order_limit.rs:77,480,639 — SCAN_BUDGET (≈200k)
    is checked per-leaf and is smaller than one default leaf (250k rows), so a single huge
    leaf is fully scanned before the bail. Not a cliff (bounded by one leaf), but worth a
    note or a per-leaflet budget check.
  • 🔵 fluree-db-api/src/query/multi.rs:403-408 — no aggregate fuel ceiling for an
    envelope (per-alias max-fuel only); 64 aliases × unbounded per-query fuel, bounded
    only by concurrency (16) + timeout (60s). Documented v1 limitation — call it out
    explicitly or add an optional aggregate cap later.
  • 🔵 fluree-db-api/src/import.rs:1259-1265 — a highly compressible "small" .gz
    (ratio ≫ the ×6 COMPRESSED_DECODE_RATIO) can be read whole above the chunk budget
    (e.g. ~128 MB gz → multi-GB String). Adversarial only; cap the whole-read or document
    the ratio as a hard assumption.
  • 🔵 fluree-db-api/src/import.rs:4174,4238 — named-graph SPOT class stats are
    discarded (let (ng_result, _) = …), so stats.graphs[user].classes is empty. Query
    correctness unaffected (planner/info estimate only; per-property graph stats still
    collected), but a completeness gap for the new named-graph feature. Merge them or
    document as default-graph-only.
  • 🔵 fluree-db-api/src/ledger_manager.rs:1147 — reload swap-skip compares total
    t() (incl. novelty), not index_t(). Conservative/data-safe (never clobbers a newer
    in-memory commit) and self-heals next reload, but can transiently forgo a newer index.
    Worth a one-line comment acknowledging index_t is sacrificed to protect novelty.
  • ⚪ fluree-db-api/src/import.rs:4215 — comment says user graphs are "g_id >= 2";
    the code correctly starts at FIRST_USER_GRAPH_ID (3). Fix the comment.
  • ⚪ fluree-db-binary-index/.../artifact_cache.rs:498-507 — coalesced-fetch disk
    re-check swallows Err(_) and re-fetches from S3. Correct for transient faults, but a
    persistent bad cache dir becomes sustained S3 traffic instead of a surfaced error.
  • ⚪ History: d58f04b30 and 3270cc4c9 are byte-identical (patch-id 5c189ad7…) —
    the >4 GiB guard committed twice. Harmless (merge dedups), but squash/drop one before
    any future replay.
  • ⚪ fluree-db-api/src/query/multi_snapshot.rs:290 — has_temporal_marker duplicates
    string_has_explicit_pin; collapse to one helper.

2. Top-level approve/disapprove review submission comment

Status: Request changes — two blocking defects, both isolated to the new surfaces;
the rest of the PR is strong and, importantly, shows no performance regression.

This is a well-engineered, well-tested rollup. I checked it specifically against the
project's performance bar and found no speed or memory regression: the no-overlay
COUNT lane reuses the original metadata iterators unchanged, the single-graph .ttl
import hot path is provably untouched (the named-graph build range is empty for
single-graph imports), the local-fs / cached-read path never enters the new
block_in_place bridge or S3 single-flight, the reverse-POST scan is bounded, and the
class-stats follow-up restores a 3.9× import regression. bench-gate is green. The
concurrency wedge fixes (#1261) are careful and defensive (RAII slot cleanup,
generation/ABA tokens, no-lock-across-IO, watchdog'd regression tests). Nicely done.

Two things must change before merge:

  1. 🔴 Correctness — reverse-POST overlay lane (fast_post_order_limit.rs:578,
    613-619). The per-leaf assert window is bounded by leaf.first_key.o_key, but
    leaves are not predicate-homogeneous, so that bound can come from a neighbor
    predicate. Under novelty this yields wrong ORDER BY DESC(?o) LIMIT k ordering and a
    wrong top-k set — exactly the write-then-read case the path targets. Fix the window to
    use this predicate's actual min o_key in the leaf (leaf_base.last()), or
    reuse compute_overlay_window. Interim: fall back to the generic top-k when novelty is
    present. The base lane is correct. Please add an e2e test with a predicate sharing a
    leaf with a larger-valued lower predicate + a novelty assert.

  2. 🔴 Security — multi-query SPARQL aliases bypass per-identity policy
    (query.rs:2708, multi_dispatch.rs:692, multi_run.rs:98). The per-alias auth gate
    runs only for JSON-LD, and the SPARQL execution path has no channel for
    identity/policy. Ledger-scope is enforced for both languages, but within-ledger
    f:policyClass filtering is silently dropped for SPARQL — a caller sees unrestricted
    data through a SPARQL alias. Thread identity/policy into the SPARQL sub-query path and
    run the impersonation gate for SPARQL too (interim: reject SPARQL aliases when
    identity/policy inputs are present). Please add a policy-enforcement integration test
    for SPARQL aliases.

Also worth addressing (non-blocking): make the overlay-COUNT narrow-projection invariant
explicit so a cache-less BinaryIndexStore can't miscount (MEDIUM-1), downgrade the
release assert! at count_plan_exec.rs:989, and the LOW/INFO items in the worksheet
(no aggregate envelope fuel cap, compressed-small-file memory, named-graph class stats,
duplicate >4 GiB commit).

Once the two 🔴 items are fixed (or fail-closed with a follow-up tracked), this is an
approve.

bplatz added 3 commits June 1, 2026 12:25
The overlay lane of the `ORDER BY DESC(?o) LIMIT k` fast path bounded each
leaf's assert window with `leaf.first_key.o_key` — the leaf's GLOBAL minimum.
But leaves are not predicate-homogeneous (a leaf flushes on row count, only
leaflets flush on `p_id` change), so `first_key` can belong to a lower-`p_id`
predicate sharing the leaf, in an unrelated value/type encoding space.

When that foreign predicate's o_key exceeds the queried predicate's novelty
asserts, those asserts were excluded from the window via
`take_while(|r| r.o_key >= leaf_lo)` and fell to `tail_asserts` (emitted after
all base rows) — or were dropped entirely past LIMIT. Result: wrong DESC order
and a wrong top-k set on the write-then-read workload this path targets.

Bound the window by THIS predicate's actual minimum o_key in the leaf
(`leaf_base.last()`, DESC-ordered), and skip leaves with no rows for the
predicate (they neither contribute base rows nor bound the window).

Adds an e2e regression test that deterministically forces a foreign lower-`p_id`
predicate with a larger o_key into the shared leaf (predicate ids follow IRI
byte-lex order, so `ex:aaa` < `ex:score`). Verified RED before the fix.
Clippy (unreadable_literal) lint fix for the reverse-POST overlay window
test. The substantive fix landed in the prior commit (already on origin);
this is just `1000000` -> `1_000_000`.
SPARQL aliases inside a multi-query envelope bypassed per-identity policy:
the per-alias impersonation gate ran only for JSON-LD, and the SPARQL
execution path had no channel for identity / policy-class / policy. A caller
authorized to reach a ledger but whose identity should see a restricted view
via f:policyClass saw ALL rows/predicates through a SPARQL alias, while the
same query as a JSON-LD alias (and single-query SPARQL) was correctly gated.

SPARQL bodies carry no `opts` block, so policy can only reach execution
explicitly. Changes:

- api: add `query_connection_sparql_with_opts` / `_tracked_with_opts`,
  mirroring JSON-LD's `query_connection` opts->policy path (build the dataset
  with policy from QueryConnectionOptions when any policy input is present).
- api: `FromQueryBuilder::connection_opts(...)` routes SPARQL through the
  opts-aware path; `run_sparql_subquery` threads the merged envelope/sub opts.
- api: the dispatcher parses identity/policy from the merged opts and passes
  them down, staying authn/authz-agnostic (mirrors JSON-LD).
- server: run the impersonation gate for SPARQL aliases too, reusing the exact
  JSON-LD gate via a synthetic {opts} object and storing the decision in
  sub.opts (which wins the dispatcher merge, so a forced identity can't be
  clobbered). Per-ledger impersonation check uses the alias's FROM ledger.

Fail-closed: when identity/policy-class is set, the policy is non-root, so an
unresolved class falls through to default_allow (false by default) -> deny.
Behaviour is at parity with single-query SPARQL.

Adds integration tests: a restricted identity sees only its permitted docs
through a SPARQL alias (verified RED before the fix); a manager identity sees
all, proving genuine filtering rather than a blanket block.
@bplatz

bplatz commented Jun 1, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f thanks for the detailed review — both blockers addressed:

  • 🔴 CRITICAL-1 (reverse-POST overlay window, fast_post_order_limit.rs:578): window now bounded by the predicate's own min o_key, not leaf.first_key; + e2e regression test — 9ec038cb6
  • 🔴 CRITICAL-2 (SPARQL aliases bypass per-identity policy): per-alias impersonation gate for SPARQL + opts→policy threading through the SPARQL connection path; + policy-enforcement integration tests — 7ea295217

LOW/INFO items noted and tracked separately.

…in assert

MEDIUM-1: the count-plan overlay cursors project narrow column subsets
(SId-only, OType+OKey), but `merge_overlay_into_batch` compares each base row
against overlay ops on the full V3 identity (s_id, p_id, o_type, o_key, o_i).
Unprojected columns read as AbsentDefault (p_id->0, o_type->0, o_i->u32::MAX),
which corrupts the sort/identity compare and over/under-counts under overlay.
This is masked in production only because the leaflet cache always loads
`ColumnProjection::all()`; a cache-less `BinaryIndexStore`
(`LedgerManagerConfig::default()`, leaflet_cache: None) takes the narrow path
and would silently miscount.

- `build_overlay_cursor_for_predicate` now forces the identity columns into the
  projection's `internal` set when an overlay merge can run (loaded for the
  merge, dropped before the returned batch — count operators' output shape is
  unchanged).
- `BinaryCursor::set_overlay_ops` debug-asserts the projection carries the full
  identity whenever ops are non-empty — a backstop for every overlay caller.
- Adds a no-cache overlay COUNT regression test documenting the invariant. The
  existing `indexed_overlay_*_count_reflects_overlay` tests run on a no-cache
  store and now panic that assert without the fix (verified).

Also downgrades the release-mode `assert!(chain.predicates.len() >= 2)` at the
`execute_chain` query path to `debug_assert!`, matching its overlay twin
`execute_chain_overlay` — a malformed chain is a planner bug, not a reason to
panic a release query.
@bplatz

bplatz commented Jun 1, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f follow-ups addressed:

  • MEDIUM-1 (overlay COUNT narrow projection — cache-less miscount): identity columns (SId/PId/OType/OKey/OI) now forced into the overlay cursor projection in build_overlay_cursor_for_predicate, with a set_overlay_ops debug-assert backstop; + no-cache overlay COUNT regression test — 4bf24256c
  • LOW (count_plan_exec.rs:989 release-mode assert!): downgraded to debug_assert! to match the overlay twin execute_chain_overlay — 4bf24256c

Remaining LOW/INFO items still tracked separately.

Non-behavioral cleanups from the PR #1264 review:

- import.rs: fix stale "g_id >= 2" comment — named-graph builds start at
  FIRST_USER_GRAPH_ID (3), not 2.
- import.rs: document that named-graph SpotClassStats are intentionally dropped
  (per-class stats are default-graph-only for now; per-property stats still flow
  through the shared IdStatsHook). Merging them is a tracked follow-up.
- ledger_manager.rs: note that the reload swap-skip compares total t() (novelty
  included), not index_t() — deliberately novelty-protective; a newer index is
  transiently forgone rather than clobber a newer in-memory commit.
- fast_post_order_limit.rs: note that SCAN_BUDGET is checked per-leaf, so one
  large leaf (up to leaf_target_rows, default 250k) may be fully scanned before
  the bail — the bound is one-leaf-granular, not exact.
- multi_snapshot.rs: collapse has_temporal_marker into the identical
  string_has_explicit_pin (single helper).
@bplatz

bplatz commented Jun 1, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f LOW/INFO cleanups addressed in 1cdb257db:

  • import.rs:4215 — corrected the stale "g_id >= 2" comment (named-graph builds start at FIRST_USER_GRAPH_ID, i.e. 3+).
  • import.rs:4238 — documented that named-graph SpotClassStats are intentionally default-graph-only for now (per-property stats still flow through the shared IdStatsHook); merging the class breakdown is a tracked follow-up.
  • ledger_manager.rs:1147 — added the note that the reload swap-skip compares total t() (novelty included), not index_t(): deliberately novelty-protective, transiently forgoing a newer index rather than clobbering a newer in-memory commit.
  • fast_post_order_limit.rs — noted SCAN_BUDGET is checked per-leaf, so one large leaf (up to leaf_target_rows, default 250k) may be fully scanned before the bail; the bound is one-leaf-granular, not exact.
  • multi_snapshot.rs — collapsed has_temporal_marker into the identical string_has_explicit_pin.

Deliberately deferred (not quick/non-behavioral): the named-graph SPOT-stats merge (planner-stats plumbing, wants its own tests), the .gz whole-read cap and per-envelope aggregate fuel cap (behavior changes to documented v1 limits), and the artifact_cache Err(_)-swallow change (S3-traffic implications). The duplicate >4 GiB-guard commit was already merged, so no squash. Happy to take any of these on if you'd like them prioritized.

Comment thread fluree-db-transact/src/parse/nquads.rs Outdated
while i < stmt.len() {
let start = stmt[i].start as usize;
let mut end = stmt[i].end as usize;
let is_string = matches!(stmt[i].kind, TokenKind::String | TokenKind::LongString);

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.

this is missing TokenKind::StringEscaped.

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.

@@ -0,0 +1,1814 @@
//! Multi-query envelope: bundle multiple independent queries against a single

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.

I think we should put the multi-query functionality in a module hierarchy. We could have a query/multi that contains query/multi/dispatch, query/multi/response, query/multi/run, and query/multi/snapshot, with the relevant bindings re-exported from the sub-modules through query/multi. That way we could build a unified multi-query api from a single module that the other components could use and we keep related functionality together.

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.

Comment thread fluree-db-transact/src/import_sink.rs Outdated
/// they enter the Tier-2 index (and the `named_graphs` routing) exactly
/// like default-graph triples. Only invoked when an import contains named
/// graphs — the single-graph hot path never touches this.
#[allow(clippy::too_many_arguments)]

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.

I think we should only override clippy as a last resort. In this case, I think the code would be more readable if we either re-used or created a type that bundled all the flake related fields like s, p, etc. together.

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.

The bulk import builds each graph's index in a separate pass (default g0,
txn-meta g1, and one per user named graph at g_id >= FIRST_USER_GRAPH_ID).
Only the default-graph pass kept its `SpotClassStats`; every named-graph pass
discarded them (`let (ng_result, _) = …`), so `stats.graphs[named].classes`
was always `None` — the planner had no class-level cardinality info for named
graphs and the `info` API under-reported their structure.

The id space is global across passes (subject/string ids assigned once at
spool and shared via each `CommitInput`'s remap; predicate ids from the single
shared `predicate_alloc`), so `SpotClassStats` — keyed by `(g_id, class_sid)`
with disjoint g_ids — can be merged by a key-wise union with no id-space hazard.

- Add `SpotClassStats::merge` (unions the four `(g_id, class) → …` maps,
  summing on any collision) + `ClassPropCountMap<K>` alias.
- Fold each named-graph build's stats into the default-graph accumulator before
  `build_class_stat_entries`. Ref-targets a pass can't resolve (e.g. a ref into
  another graph) stay counted as `@id` flakes and just don't contribute a
  target-class entry — by design, no cross-graph class resolution.
- g1 (txn-meta, a system graph) is intentionally left unmerged.

Adds a TriG import regression test asserting the named graph's class stats —
including a same-graph ref-target class — are populated (verified RED before
the merge: named-graph classes were `None`).

Both caps the reviewer's note raised are left as-is, intentionally: the 64-class
limit is already handled (ClassMembership promotes Dense→Sparse past 64), and
MAX_CLASS_REF_LEAF_ENTRIES is a 64M-entry anti-OOM guard, not a class cap.
@bplatz

bplatz commented Jun 1, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f follow-up on the one LOW item I'd deferred — the named-graph SPOT class-stats merge — now implemented in dafca1172.

Context: the bulk import builds each graph in a separate pass and only the default-graph pass kept its SpotClassStats; named-graph passes discarded them, so stats.graphs[named].classes was always None (planner had no class-level cardinality for named graphs; info under-reported them).

  • Confirmed the prerequisite first: ids are global across all build passes (subject/string ids assigned once at spool and shared via each CommitInput's remap; p_id from the single shared predicate_alloc; same commits slice feeds every pass, differing only in g_id/run_dir). So the (g_id, class_sid)-keyed SpotClassStats merge has no id-space hazard — and, separately, named-graph segments are not at risk of id mismatch.
  • SpotClassStats::merge unions the four maps; each named pass folds into the default-graph accumulator before build_class_stat_entries. Cross-graph ref-targets a pass can't resolve stay counted as @id flakes with no target-class entry (by design — no cross-graph class resolution). g1 (txn-meta, system graph) intentionally left unmerged.
  • On the cap notes from your worksheet: both are left as-is, deliberately. The 64-class limit is already handled (ClassMembership promotes Dense→Sparse past 64); MAX_CLASS_REF_LEAF_ENTRIES is a 64M-entry anti-OOM guard, not a class cap.
  • Added a TriG import regression test (named-graph class stats + same-graph ref-target class), verified RED before the merge.

That closes out the actionable items from the review.

bplatz added 3 commits June 1, 2026 14:58
`group_terms` in the N-Quads→TriG converter only treated `String` and
`LongString` tokens as string literals, but the lexer emits a distinct
`TokenKind::StringEscaped` for any literal containing `\` escapes (its slow
path). As a result an escaped literal followed by `^^<datatype>` or `@lang`
was not folded into a single term — the suffix split off into separate terms,
so the statement produced 5 terms and failed the "expected 3 or 4 terms" guard
(a hard parse error on otherwise-valid N-Quads).

Include `StringEscaped(_)` alongside `String`/`LongString`, matching the Turtle
parser (`fluree-graph-turtle/src/parser.rs:636`). Adds a regression test for an
escaped literal carrying a datatype and one carrying a language tag (verified
RED before the fix).

Reported in review by @zonotope.
…lows

Replace the seven-argument `write_record` / `push_named_graph_record` spool
write path with a single borrowing `FlakeRecord<'a>` (s, p, o, dt, lang,
list_index, t). This removes two `#[allow(clippy::too_many_arguments)]`
overrides and a third stale one on `resolve_object_value` (which only takes two
args). Zero-cost — the struct just bundles borrows — and behavior is unchanged.

Addresses review feedback (@zonotope) preferring a bundled type over suppressing
the lint, per the project's "clippy allow as last resort" convention.
Move the flat `query/multi_{dispatch,response,run,snapshot}.rs` into a
`query/multi/` hierarchy (`mod.rs` + `dispatch`/`response`/`run`/`snapshot`
submodules), keeping related functionality together. The envelope types and
validation stay in `multi/mod.rs`, which now also declares the submodules and
re-exports their headline bindings (`MultiQueryBuilder`, `MultiQueryError`,
`run_jsonld_subquery`, `run_sparql_subquery`, `SubqueryOutput`) so the whole
multi-query API is reachable from a single `crate::query::multi` surface.

Internal sibling refs use `super::{dispatch,response,run,snapshot}`; external
consumers (server, CLI, tests) now go through the re-exported `query::multi::`
paths instead of the per-file module paths. Pure reorganization — no behavior
change; git tracks all five files as renames.

Addresses review feedback (@zonotope).
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.

3 participants