Skip to content

perf(index): fewer requests for remote leaf reads; whole-leaf fetch by default - #2048

Merged
bplatz merged 8 commits into
mainfrom
perf/remote-leaf-fetch
Oct 13, 2026
Merged

bplatz merged 8 commits into
mainfrom
perf/remote-leaf-fetch

Conversation

@bplatz

@bplatz bplatz commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Reading an index leaf from remote storage (S3, HTTP) made more requests than it needed to. A remote request costs about the same for a few KB as for a whole leaf (~13 ms per GET via the SDK, ~32 ms for a whole 721 KiB leaf, both on S3 Standard), so the request count drives cold-read latency. This PR cuts it in three steps:

  1. Header and directory in one request. The range-read handle sized its first read from an estimate of 120 bytes per directory entry. Real directories are larger, so every remote open cost three GETs: an undersized read, then the header, then the directory. It now reads the header and directory together and makes a second request only when the directory overflows that first read.

  2. Whole leaf once a scan starts. A range-read handle used to make one request per leaflet it loaded, so a scan's request count grew with the number of leaflets. After three leaflet loads it now fetches the whole leaf once and serves the rest from memory.

  3. Whole leaf on first data access, by default. RemoteLeafFetch::Whole serves a leaf's first data access with one GET of the whole leaf. That GET goes through the disk cache's single-flight fetch, so concurrent readers of a cold leaf share one request and a restarted process reopens the disk copy without one. FLUREE_REMOTE_LEAF_FETCH=ranged keeps steps 1 and 2 without this one.

    Directory-only reads still fetch just the directory. Six query paths that read only a leaf's directory used to open a full leaf handle, which under this default downloads the leaf: the all-IRI and single-o_type prechecks, the boundary-leaf extents and base counts, and the partition boundaries of the count plan and vector top-k. They now use open_leaf_dir, and the two partition-boundary copies are one function.

    Every leaf a query first touches now lands in the disk cache, where before only re-opened leaves did. On Lambda that cache is /tmp.

    The trade assumes S3 Standard latencies. On a store with a few milliseconds to first byte, such as S3 Express One Zone, two small ranged GETs may beat one whole-leaf GET; that hasn't been measured, and FLUREE_REMOTE_LEAF_FETCH=ranged is the setting for it.

Two smaller changes:

  • A leaf under 64 KiB is served from its first read. The speculative header read already holds the whole leaf, so under the ranged policy its columns no longer cost more range reads.
  • The directory-size bound reads ColumnId::COUNT. The exact second read assumed six columns, and the retry that used to absorb a wrong guess is gone; a const assertion ties the count to ColumnId::from_u16.

Local and in-memory storage are unaffected. The leaf format doesn't change.

Measurements

On real S3, with an earlier version of the whole-leaf policy behind an experiment flag:

Query GETs Latency
Shortest path, cold 178 → 83 2,241 → 1,229 ms

Steps 1 and 2 alone halved the binary-index GETs of a cold traversal at today's 25K-row leaflets. They also stopped the GET count from growing with the number of leaflets per leaf.

Tests

  • header_and_directory_request_count and range_read_scan_fetches_whole_leaf_once in leaf_access.rs cover steps 1 and 2. The existing remote-open tests in binary_index_store.rs now expect exactly one range read for the header and directory, where they used to accept two or more.
  • whole_policy_fetches_a_remote_leaf_once_and_reuses_the_disk_copy: one GET, and a second store over the same cache directory makes none.
  • whole_policy_coalesces_concurrent_cold_opens: eight concurrent cold opens of one leaf issue a single GET.
  • The cursor retry test runs under both policies, over a leaf too big for the speculative read, so it still covers a column range read failing mid-leaf.
  • ranged_policy_serves_a_small_leaf_from_its_first_read: an open plus a column load of a small leaf cost one range read.

Docs

docs/operations/configuration.md documents FLUREE_REMOTE_LEAF_FETCH.

The directory estimate (120 bytes/leaflet) was below every real entry
(148-196 bytes), so each first remote leaf open paid three GETs: header,
short estimate, doubled refetch. One speculative 64 KiB read now covers
header + directory for leaves up to ~330 leaflets; larger directories
take one exact follow-up.
…n starts

A remote leaf not yet promoted served each leaflet with its own ranged
GET, so a scan cost one request per leaflet. After three range-read
loads the handle fetches the rest of the leaf in one request.
RemoteLeafFetch::Whole (default) serves a remote leaf's first data access
with one GET of the whole leaf, persisted to the disk cache, including
when its directory is already known. Ranged keeps header+directory plus
per-leaflet range reads (FLUREE_REMOTE_LEAF_FETCH=ranged). Directory-only
opens read just the prefix under either policy.

Whole-leaf reads now go through the disk cache's single-flight fetch, so
concurrent readers of a cold leaf share one GET.
@bplatz bplatz added area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches performance Performance improvement (release notes: Performance) labels Oct 10, 2026
@bplatz
bplatz requested a review from a team October 10, 2026 15:18

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@bplatz steps 1 and 2 are clear wins and I'd take them as-is. I'm on board with whole-leaf as a policy too, especially since it goes through the disk cache's single-flight fetch and keeps encrypted stores off disk. Two headline notes:

(1) The ~13 ms/GET premise: was that S3 Standard? Solo reads its indexes from S3 Express One Zone inside Lambda, where per-request latency is a few ms and bytes weigh more, so the default's trade could tip the other way for point reads. It's worth one measurement there before solo's pin picks up Whole; FLUREE_REMOTE_LEAF_FETCH=ranged is a fine fallback in the meantime.

(2) This overlaps #2035 directly. #2035 adds the same "fetch the leaf whole on first open" mechanism for stores without ranged reads, and removes fetch_cached_bytes_cid, uses_disk_cache, cache_dir and SharedLeafBytes, which this PR builds on (git merge-tree shows conflicts in binary-index/src/lib.rs and eight regions of binary_index_store.rs). Since this one targets main and #2035 next, I'd land this first and merge main into next before #2035 merges. Then #2035 absorbs Whole as one more trigger of its fetch_whole_leaf, in its own branch with its own tests, rather than having a routine main→next merge re-derive the policy. Your call, since both are yours.

Full review below:


✅ Approving to unblock you — with 1 thing that needs to be addressed before this merges.

This is a nice set of finds, @bplatz. The 120-bytes-per-entry estimate being under every real entry is exactly the kind of quiet three-GETs-per-open tax that's easy to miss for years.

Must address before merge:

  1. Four directory-only query lanes download whole leaves under the new default (binary_index_store.rs:1190). predicate_objects_all_iri (count_plan_exec.rs:3351), base_predicate_o_type (fast_post_order_limit.rs:356), driver_subject_boundaries (count_plan_exec.rs:975) and boundary_leaf_pid_extent (fast_count.rs:470) open a handle only to read its directory. Whole fetches the leaf at open, so a cold metadata walk over a predicate downloads (and disk-caches) every leaf of it. I confirmed (1 GET, 0 range) plus a disk write versus (0, 1) with a scratch test. Switching the four sites to open_leaf_dir fixes it, one line each. Details inline.

Then the rest, all optional: whether the 13 ms/GET premise holds on S3 Express from Lambda (a question, with the env switch as the fallback); keeping the whole buffer when the 64 KiB speculative read returns a small leaf entirely; and a const tie between MAX_DIR_ENTRY_BYTES and ColumnId now that the retry is gone.

Things I checked and was happy with:

  • The encrypted path. fetch_cached_bytes_cid routes a store that refuses plaintext caching to the uncached, coalesced fetch, and the existing stale_cache_entries_are_served_only_when_plaintext_cache_permitted exercises it under the new default.
  • Ranges past EOF. The 64 KiB read clamps on every backend: default read_byte_range, S3 (bytes=0-65535 only 416s when the start is past the end), File, Memory, raw proxy, and the fetcher's local/cached/disk tiers.
  • The test teeth. Collapsing the speculative read to the header and bypassing the single-flight turned seven tests red, including (8, 0) vs (1, 0) for the concurrent-open coalescing.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ Extends the existing range-read handle and disk-cache single-flight; the policy is one enum with an env switch. Dir-only callers should use the existing open_leaf_dir (the must above).
  • Performance (speed first, memory second): ⚠️ Steps 1 and 2 cut cold-read requests outright. Step 3 trades bytes for requests: measured on S3 (class unstated), unmeasured on Express/Lambda. CRITICAL until fixed: the four dir-only lanes go from a few KB to a whole leaf plus a disk-cache write per leaf on a cold remote walk. Memory is one leaf per open remote handle plus a transient copy; fine.
  • Deployment targets: ⚠️ Shared code; it matters on remote stores (solo Lambda/standalone, server with S3). No Lambda fence violated: memory is tens of MB, and /tmp is bounded by the disk-cache budget, though it now takes every first-touched leaf. The evidence is "real S3" with the class unstated, and solo's index tier is Express (question inline).
  • Testing: ✔ Request-count, scan-promotion, whole-policy persistence and coalescing tests all run, and each goes red under mutation. The cursor-retry sweep runs under both policies.
  • Conventions: ✔ Multi-line commit bodies; the env var is documented in docs/operations/configuration.md; clippy and fmt green.

Verified locally at branch HEAD (a323a0b2e): cargo test -p fluree-db-binary-index --lib -- leaf_access binary_index_store (26 passed, new tests by name). Two mutations (seven tests red, restored). A scratch test for the dir-only pattern under both policies and via open_leaf_dir. Past-EOF behavior read for every range backend. git merge-tree against origin/next (clean) and #2035 (conflicts).

Approving now so you can merge without waiting on another pass from me — just be sure the open_leaf_dir switch for those four lanes is in before you do.


if self.remote_leaf_fetch == RemoteLeafFetch::Whole {
tracing::debug!(leaf = %leaf_cid, need_replay, source = "remote_whole", "binary leaf open");
let bytes = self.fetch_remote_leaf_whole(cs, leaf_cid)?;

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.

🔴 Must address before merge: four directory-only query lanes go through open_leaf_handle, so under the new Whole default they download every leaf they inspect

The body says "Directory-only opens still read just the directory", and that's true of open_leaf_dir. But this branch fetches the whole leaf at open, before any load_columns, and these lanes open a handle only to read handle.dir().entries:

  • fluree-db-query/src/count_plan_exec.rs:3351 (predicate_objects_all_iri): every POST leaf of the predicate.
  • fluree-db-query/src/fast_post_order_limit.rs:356 (base_predicate_o_type): every POST leaf of the predicate, as the precheck for a bounded top-k tail walk.
  • fluree-db-query/src/count_plan_exec.rs:975 (driver_subject_boundaries): up to k leaves.
  • fluree-db-query/src/fast_count.rs:470 (boundary_leaf_pid_extent): one or two boundary leaves.

I checked it with a scratch test that opens a remote leaf this way and reads only the directory. Under Whole it costs (get, range) = (1, 0) and writes the leaf into the disk cache; under Ranged, or through open_leaf_dir under either policy, it costs (0, 1) and writes nothing. By the PR's own S3 numbers, a cold base_predicate_o_type over a predicate with N POST leaves goes from ~N × 13 ms and a few KB per leaf (via open_leaf_dir) to ~N × 32 ms and ~721 KiB per leaf. Every one of those leaves also lands in the disk cache, which on a Lambda's /tmp budget pushes hot leaves out to make room for a metadata check.

The fix is mechanical: those four sites should call store.open_leaf_dir(&leaf.leaf_cid)? and iterate dir.entries. That gives one range read, cached in the leaflet cache and never counted toward promotion. It's also what the open_leaf_dir doc already asks of directory-only walks. Commenting here because the fluree-db-query files aren't in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 4710471

/// as for a whole leaf, so this halves requests for a point read and
/// bounds a traversal's requests by the leaves it touches.
#[default]
Whole,

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.

❓ Question: was the ~13 ms/GET premise measured on S3 Standard? The biggest embedder reads indexes from S3 Express One Zone in Lambda

This is more of a question than a suggestion. The doc and body reason from "a remote request costs about the same for a few KB as for a whole leaf (~13 ms per GET, ~32 ms for a whole 721 KiB leaf)". On S3 Express One Zone, first-byte latency is a few ms, and a Lambda's network throughput is modest. There a point read under Whole (one GET plus ~721 KiB of transfer) could come out slower than Ranged (two small GETs), which would flip the default's trade for the most common cold read.

I don't think this blocks anything: FLUREE_REMOTE_LEAF_FETCH=ranged is a clean escape hatch, and memory is fine. One whole leaf per open handle plus a transient copy is tens of MB at realistic cursor counts, well inside a 512 MB–3 GB function. But if you have (or can get) the 178 → 83 measurement on an Express bucket, it would settle which default an embedder on Express should run. Worth a line in the body either way, since /tmp now receives every first-touched leaf rather than only re-opened ones.

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.

S3 Standard. Express isn't measured; the body now says so, with FLUREE_REMOTE_LEAF_FETCH=ranged as the setting for it, and notes that /tmp now receives every first-touched leaf.

buf = fetcher.fetch_range(leaf_cid, 0..next_size)?;
}
}
let mut buf = fetcher.fetch_range(leaf_cid, 0..SPECULATIVE_HEADER_DIR_BYTES)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Optional: a leaf under 64 KiB comes back whole from this read, and the bytes are dropped

When the read returns fewer bytes than requested, the store has handed back the whole leaf, which will be common for small ledgers. Today only the directory is kept. Under Ranged, every later leaflet load then re-fetches bytes we already held; under Whole, the same happens whenever a directory-only open came first.

Returning the buffer when buf.len() < SPECULATIVE_HEADER_DIR_BYTES (e.g. (dir, payload_base, Option<Vec<u8>>)) would let open_leaf_handle build a resident handle from it, saving one or more GETs per small cold leaf under both policies. I recognize this is minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 408333c

const SPECULATIVE_HEADER_DIR_BYTES: u64 = 64 * 1024;

/// Largest directory entry: 80 fixed + 6 column refs + 20 history bytes.
const MAX_DIR_ENTRY_BYTES: u64 = 80 + 6 * COLUMN_BLOCK_REF_SIZE as u64 + 20;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Optional / nit: the exact follow-up read assumes six columns, and the doubling retry that used to absorb a wrong guess is gone

80 + 6 × 16 + 20 = 196 matches compute_directory_size and today's six-variant ColumnId, so this is correct now. If a seventh column is ever added, every remote open of a leaf with more than ~330 leaflets would fail with "column ref truncated": the read is sized too short and nothing retries.

A const assertion tying the 6 to ColumnId's variant count, or one doubling fallback on UnexpectedEof, would make that a build error or a slow path instead of a read failure. Minor and non-blocking, but cheap to fold in now if you agree.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 408333c

… handle

Under the whole-leaf default, `open_leaf_handle` downloads the leaf at
open, so five lanes that read only `dir().entries` fetched every leaf
they inspected and wrote it into the disk cache:
`predicate_objects_all_iri`, `base_predicate_o_type`,
`boundary_leaf_pid_extent`, the overlay count's boundary-leaf base count,
and the partition boundaries of the count plan and vector top-k. They now
use `open_leaf_dir`: one range read, cached in the leaflet cache.

The two partition-boundary copies are one function,
`fast_path_common::driver_subject_boundaries`.
…irectory bound to ColumnId

A leaf under 64 KiB comes back whole from the speculative header read.
Under the ranged policy its handle now serves columns from those bytes
instead of range-reading them again. The retry sweep test moves to a
leaf too big for that read, so it still covers a column range read
failing mid-leaf.

`MAX_DIR_ENTRY_BYTES` assumed six columns, and the doubling retry that
used to absorb a wrong guess is gone. It now reads `ColumnId::COUNT`,
which a const assertion ties to `from_u16`.
@bplatz
bplatz merged commit 3269873 into main Oct 13, 2026
19 checks passed
@bplatz
bplatz deleted the perf/remote-leaf-fetch branch October 13, 2026 18:36
aaj3f added a commit that referenced this pull request Oct 13, 2026
Brings in #2019, #2044, #2048, #2049 and #2052 (main at 58b5323).

#2052 keys cross-ledger governance by the model ledger's head commit and
opens the model at that commit. Two files conflicted:

- tx.rs: this branch moved the stored-shapes pass into its own block
  (`stored_cache`), which #2052 edited in its old place. The block keeps
  this branch's shape, and its compiled-SHACL cache key carries #2052's
  commit id beside the model's t, as main's does. The shapes model opener
  and the cache key type merged without conflict.
- it_policy_cross_ledger.rs: both sides appended tests; both are kept.
bplatz added a commit that referenced this pull request Oct 13, 2026
Brings in #1980's storage roots and namespaces and, through next's merge
of main, #2048's remote leaf fetch policy.

- Storage addressing is #1980's: content stores, sweeps and the sibling
  walk take `StorageNamespace`/`StorageRoot`. The disk-cache wrapper keys
  its coalesced fetches by the namespace's branch prefix.
- Cache directories stay gone: `plan_sweep`, the sibling walk, the
  orchestrator and `BinaryIndexStore` read through the backend's
  `CachedContentStore`, not an `artifact_cache_dir` threaded beside it.
- #2048's `RemoteLeafFetch::Whole` fetches a leaf whole on first open
  through `fetch_whole_leaf`, the path a store without ranged reads takes:
  the wrapper coalesces the GET and keeps the disk copy, and the leaflet
  cache keeps the bytes. Directory-only opens stay ranged, and a small
  leaf is served from its first read. `fetch_remote_leaf_whole` and
  `SharedLeafBytes` are gone with the cache-dir reader.
- #2048's whole-policy tests run over the wrapper instead of a store
  `cache_dir`, with the same counts.
aaj3f added a commit that referenced this pull request Oct 14, 2026
…2068) into fix/write-fidelity-part2

Two conflicts, both with #2056, which fixed the same debug assertion this
branch fixed in 9b7cc1a (the resolver's reserved-namespace guard
rejected f:message, f:author and f:reverts in txn-meta):

- fluree-db-indexer/src/run_index/resolve/resolver.rs: took main's
  version, the guard deciding through fluree_vocab::txn_meta::may_hold.
  This branch's widened is_system_txn_meta_entry admitted the same five
  names and goes; the file now equals main's.
- fluree-db-api/tests/it_txn_meta.rs: kept both sides' tests, this
  branch's an_index_build_keeps_the_user_message_and_author (a file
  ledger through a full rebuild) beside #2056's.

template_sink.rs, trig_meta.rs, txn_meta.rs, admin.rs and fluree-vocab
merged cleanly: #2056's predicate check in the txn-meta path sits beside
this branch's statement hashing and does not touch it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches performance Performance improvement (release notes: Performance)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants