Skip to content

perf: read encrypted storage by range within the cache budget - #2130

Merged
bplatz merged 44 commits into
nextfrom
perf/encrypted-segmented-reads
Oct 20, 2026
Merged

bplatz merged 44 commits into
nextfrom
perf/encrypted-segmented-reads

Conversation

@bplatz

@bplatz bplatz commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

On encrypted storage every read decrypted whole objects: a leaf (~721 KiB) to read one leaflet, a 16 MiB forward dictionary pack to read one value. A 10M-subject encrypted store under a 1 GiB memory limit was OOM-killed on every workload we ran. This PR writes encrypted objects in independently authenticated segments and reads local encrypted data by range, inside the existing cache budget.

Partially addresses #2113: local encrypted storage now reads by range (the storage-layer variant of option 1, fixed-size AEAD segments). Remote encrypted reads, including a remote store without a disk cache, still decrypt whole objects.

Follow-up: #2029 (stage 4, encryption above the disk cache, would let remote encrypted reads use this path).

Follow-up: #2146 (concurrent lookups in a pack read by range contend in the leaflet cache), #2147 (no benchmark covers encrypted storage, single-stream or concurrent).

Includes #2119's two commits (subject Sid without a reverse lookup), which this work was measured with. #2119 stays open against main; when it lands there, the next main → next merge finds it already applied.

What changes

Envelope version 2 (fluree-db-crypto/src/segmented.rs). A 64-byte authenticated header, then 64 KiB plaintext segments, each with its own AES-256-GCM tag. The object key is HKDF-SHA256 of the master key over the header. Segment nonces carry the segment index and a last-segment flag, so truncation, reordering, splicing and an altered length each fail authentication. Every new write is version 2; reads dispatch on the version byte, and version 1 still decrypts whole.

Ranged reads (ContentStore::get_local_ranged). A local object whose whole read is costly (encryption at rest, or a branch over an encrypted parent) returns a RangeSource that decrypts only the segments a read covers. Decrypted segments are cached in the leaflet cache, keyed by store and envelope identity. Stores without costly reads keep the whole-object path.

  • Leaves open as ranged handles. A scan reads leaflet by leaflet and never promotes to a whole-leaf read. Batched probes and the grouped-count fast path go through the same handles.
  • Forward dictionary packs (dict/pack_reader.rs, dict/allowance.rs) are read by range: the page's offsets and the value bytes. A pack is promoted whole into the dictionary allowance when two things hold. First, its recent cache misses have decrypted as many bytes as it holds; recent rent halves each time all packs together miss the allowance's size. Second, those misses covered at least half the pack. The allowance evicts in clock order with a second chance and holds packs in anonymous mappings, so evicted memory returns to the OS. Lookups find a promoted pack through a slot read with arc-swap (a new dependency), with no lock and no reference count, so lookups on several threads don't contend on it.
  • Reverse dictionary leaves (dict/reader.rs) are read whole once to index the first entry of each 4 KiB stretch. A lookup then scans one stretch in place. The indexes live in a small LRU pool of their own, so leaflet pressure can't evict an index whose rebuild is a whole-leaf decrypt.

Memory

Everything this PR adds comes out of cacheMaxMb; nothing it adds is allocated beside it. The planner's stats-view pool sits beside the budget, as it does on next: a sixteenth of the leaflet share here, of the whole budget there.

Pool Unencrypted Encrypted, as connected
Leaflet cache all of cacheMaxMb the rest
Dictionary allowance none cacheDictionaryMaxMb, default 60% of cacheMaxMb, capped at 90% with a warning
Reverse-leaf fence pool none (cacheMaxMb − allowance) / 32

An encrypted connection starts with the reservation in place. Data that can't use it gives it back to the leaflet cache for good:

  • A pack that can't be read by range (version 1, remote) lowers the allowance to the smallest level that covers what it holds. That level is the cap halved up to seven times, or nothing.
  • A reverse leaf that can't be fenced releases the fence pool, unless some leaf has already been fenced.

Why it doesn't grow on demand instead: under glibc, the heap the leaflet pool grew into stays with the allocator after a shrink. A grow-on-demand build peaked at 1052 MiB against 949 MiB for the up-front reservation. moka caches can't be resized, so each reservation stage has its own pool (read/leaflet_cache.rs, Stages):

  • Entries carry over.
  • A retired pool is drained at once.
  • A write that races a stage change is removed from the retired pool.
  • A reverse leaf fenced while the fence pool is being given back is taken out again.

Configuration

  • JSON-LD connection config: cacheDictionaryMaxMb, or dictionaryMaxMb in the cache object.
  • Server: --cache-dictionary-max-mb, FLUREE_CACHE_DICTIONARY_MAX_MB, or cache_dictionary_max_mb in the config file.
  • Rust: FlureeBuilder::cache_dictionary_max_mb.
  • FLUREE_IO_STATS (opt-in diagnostics) counts artifact reads and decryption work per process. When off it costs one atomic load per read. When on, timings aren't comparable to runs without it. It records kinds only, never addresses or plaintext.

Compatibility and migration

  • There's no migration operation. Version 1 and version 2 objects can be read side by side.
  • New writes are version 2. A reindex, which next already requires, writes the new index as version 2. A key rotation rewrites each blob on the retiring key as version 2.
  • Commits and other objects a reindex doesn't rewrite stay version 1. A rotation rewrites them only if they're on the retiring key; it skips blobs already on the current key.
  • Older binaries can't read version 2 objects, so going back to an older binary after encrypted writes isn't supported. After a key rotation, that includes commits from before the upgrade, so a rollback can't reindex from them either. On a store several processes share, every process needs this release before any of them writes with it.
  • After a reindex, a connection that had given its reservation back needs a restart to get the allowance again.

Unencrypted storage

The encryption path doesn't apply to it and reserves nothing. With #2119's fast path off, every workload matched next (point lookups 62–63 against 61–64 ms).

With #2119 on, the suite is faster: 0.77–0.78 of next at an 8 GiB cache with no workload slower, and 0.94 at 256 MiB. Point lookups inside the 256 MiB suite are slower (81 against 62 ms). Result formatting no longer does a reverse lookup per subject, which used to keep reverse leaves warm for the next query. #2119's description records that trade-off.

Measured

Setup: EC2 m7a.4xlarge, synthetic people graph, each run in a fresh process under a 1 GiB memory cgroup, with the OS page cache dropped before each run.

Workload Result
10M subjects, whole packs (version 1, or version 2 held whole) OOM-killed on every plan
10M, new subjects every pass 18.4 s per later pass (ranged-only 21.1; other admission rules 27.8–30.2)
10M, dense output final pass 2.46 s, peak anonymous memory 949 MiB, no OOM
10M, ordered working set A → B → A later passes 53–56 ms (first-come pinning: 265–280 ms for B after A)
3M subjects (fits in cache) within 1–3% of holding packs whole after warm-up
Version 1 data, 256 MiB suite time 0.76–0.83 of next

The runs above are single-stream. Lookups in a promoted pack take about 10 ns each from 1 to 10 threads at once (a microbenchmark on a laptop, not this setup); concurrent queries weren't measured end to end.

Trade-offs, accepted:

  • First pass: about 27% slower than holding packs whole while packs pay rent; 11–12% over six passes; within 1–3% after that.
  • Returning to an earlier working set: its packs rent again, about 100–130 ms extra per return.
  • Narrow hot packs: a pack whose misses keep hitting the same small region stays ranged. That's the coverage guard, which is what stops fixed scattered keys from churning.

Reviewing

The history keeps the experiment rounds, including admission rules later replaced (demand admission, cumulative rent), so the final diff reads more directly than commit by commit. The core is in:

  • fluree-db-crypto/src/segmented.rs, encrypted.rs
  • fluree-db-core storage (get_local_ranged, RangeSource)
  • fluree-db-binary-index/src/read/ (leaflet_cache.rs, cached_units.rs, binary_index_store.rs)
  • fluree-db-binary-index/src/dict/ (pack_reader.rs, allowance.rs, reader.rs)
  • fluree-db-api/src/lib.rs (make_leaflet_cache)

fluree-db-api/examples/encryption_ab.rs is the A/B harness the numbers came from.

Tests

  • Envelope: fixed vectors; full against ranged reads; segment boundaries; tampering; wrong keys; mixed versions on one store.
  • Dictionary packs: promotion, eviction, the coverage guard; eight threads promoting and evicting while the cache is dropped beneath them; lookups in a promoted pack timed on eight threads against one (nextest runs it alone).
  • Reverse leaves: fence lookups matching whole-leaf lookups; a leaf fenced while the fence pool is given back is not kept.
  • Cache budget: an allowance past 90% of the budget is capped, and the leaflet pool still caches.
  • Cache reservation, end to end (it_encrypted_cache_reservation): version 2 keeps it, version 1 gives it back, legacy data after version 2, mixed data, remote reads.
  • Migration (it_key_rotation): a version 1 store reading, taking version 2 writes, read by range after a reindex, rotated to version 2; reads during a rotation.

bplatz added 30 commits October 16, 2026 13:25
StorageRead and ContentStore gain get_local_ranged: a RangeSource for an
object on this machine that the store reads by range for less than a whole
get_local, which for storage that decrypts on read means decrypting all of
it. Every wrapper forwards it; the bridge keeps the legacy-address
fallbacks and counts served ranges under FLUREE_IO_STATS.

io_stats gains a work table for what is done with bytes after they are
read (decryption, what readers keep loaded), reported apart from reads.
…that decrypt

On a store with costly local reads that serves a ranged source:

- Leaves open as range-read handles over the local source, cached in the
  leaflet cache, with the directory decoded from the leaf's prefix. A
  leaflet the cache holds decoded reads nothing; a scan reads leaflet by
  leaflet and never promotes to a whole-leaf read; requests within one
  read unit merge. Directory walks read the prefix and keep no source.
- Forward packs open from their header and page directory, and pages
  decode on use into the leaflet cache, single-flight and validated on
  load. Warming reads no pages.
- Batched probes and the grouped-count fast path read leaflets through
  leaf handles rather than whole leaf bytes, so they take the same lane.

Stores without a ranged source keep the whole-object lanes.
Objects are encrypted as fixed-size AES-GCM segments under a per-object
HKDF-SHA256 key, with the header bound through the key derivation and each
segment's index and finality through its nonce. A reader can decrypt the
segments a range touches; a full read still verifies every segment and the
exact length. Fixed vectors were computed with an independent
implementation.

Version 1 envelopes read as before. EncryptedStorage serves segmented
envelopes as ranged local sources, keeping the ciphertext as the inner
storage holds it, and counts decryption under FLUREE_IO_STATS. Rotation
classifies and rewrites both versions.
An example that imports a synthetic people graph into plain or encrypted
file storage and runs point, traversal, dictionary-heavy, count and scan
workloads, recording latency, result digests, decrypt work, cache
occupancy by entry type and resident memory per execution. io_stats gains
snapshots of its tables for per-query deltas.
…eaflet cache

A ranged leaf source kept in the leaflet cache now reads through it one
read unit (decrypted segment) at a time, single-flight, each unit charged
at its length against the cache's one budget. Readers that load columns
without the decoded cache, as most scan fast paths do, copy the units
instead of decrypting them again. Directory walks read unwrapped.

Units are keyed by the source's cache identity: RangeSource gains
cache_identity, which EncryptedStorage derives from a random per-instance
context and the envelope header, so a re-encrypted object or another
storage over the same bytes is never served another's units.
A forward pack on a store that decrypts on read no longer assembles
512 KiB pages: a lookup reads its entry's two offsets and its value
through the leaflet cache's decrypted units. A page's entry count and
final offset are checked against its directory entry on first visit, and
every lookup bounds-checks the offsets it reads.

FLUREE_ENCRYPTED_PACKS=whole|pages|ranged selects the representation for
the A/B and goes away with it.
…se lookup

Turning a persisted subject id into a Sid read the subject's IRI from its
forward pack, then searched the reverse dictionary for that IRI to find
the Sid it is stored under. Every subject a query materializes paid both
lookups; under cache pressure each reverse lookup could decrypt or reload
a 2 MiB reverse leaf.

When the canonical split of the IRI is exactly the parts the subject is
stored under, those parts are the answer the reverse dictionary would
give, so they are returned directly. A full-IRI namespace (EMPTY,
OVERFLOW) or a split the current rules do not produce still takes the
lookup. The graph view and the export resolver share the one rule.
…d rows

A ranged dictionary lookup asked the shared cache twice per value, for
the unit holding its offsets and the unit holding its bytes. Formatting
walks rows whose ids mostly ascend, so consecutive lookups land in the
same few units.

While a UnitMemoScope is open on a thread, CachedUnits keeps the last
eight units it served there and serves repeats from them; each unit
still goes through the cache the first time the scope meets it. Units
are released when the outermost scope closes, and the scope is not Send,
so it cannot outlive an await. The result formatters open one around
their synchronous row loops. CachedUnits also reads its source's
identity, unit size and length once rather than per unit.
…lowance

A pack whose store decrypts on read is decrypted whole only if its size
can be reserved in the leaflet cache's dictionary allowance, and is read
by range otherwise. The reservation stays charged until the last reader
holding the pack drops it, and readers of the same object share one copy,
charged once. Experiment mode: FLUREE_ENCRYPTED_PACKS=bounded with
FLUREE_DICT_ALLOWANCE_MB.
…ption A/B harness

A reverse leaf can report the byte ranges a lookup reads, and the store
counts, for a batch of subject lookups, the distinct reverse leaves they
route to and the read units a lookup reading those leaves by range would
need.
… in clock order

Adaptive mode reads a pack by range until its cache misses, counted per
pack and shared by its readers, have decrypted as many bytes as it holds,
then promotes it whole into the dictionary allowance, reusing its cached
units and dropping them after. The allowance evicts its packs in clock
order to make room; an evicted pack stays charged until the last reader
holding it for a lookup drops it, and its rent starts again from nothing.
Experiment mode: FLUREE_ENCRYPTED_PACKS=adaptive.
A reverse leaf can list, for each unit-sized stretch in which an entry
starts, the first entry starting there, and look a key up within its
fenced stretch by scanning the data section or by binary-searching the
stretch's slice of the offset table, reporting what it reads. The probe
compares the units each method reads, and the fences' memory.
Adaptive promotion can also require a rental's misses to have covered a
share of the pack (FLUREE_DICT_PROMOTE_COVERAGE), counted by distinct
units at their actual size. Promoted packs can live in anonymous mappings
of their own (FLUREE_DICT_PACK_ALLOC=mmap), assembled in place, so their
memory goes back to the system when the last reader drops them. The
allowance records coverage when rent reaches a pack's size and at
promotion, and what each evicted pack served whole. The wasm cache
stand-in gains invalidate.
…nces

A single-key reverse lookup on a store whose local reads decrypt reads a
leaf whole once, keeps the first entry starting in each of its read units,
and from then on reads only the key's fenced stretch: scanned in one piece
by default, or binary-searched through its slice of the offset table. A
leaf whose entries are not laid out one after another in key order is read
whole as before. Experiment control: FLUREE_REVERSE_FENCES=scan|slice|off.
… the leaflet cache

A fenced lookup scans its stretch from the cached units in place, holding
the unit it reads and copying only an entry that spans two. Fence spacing
is set apart from the read unit, and the fence index is packed and kept in
the leaflet cache under the leaf's CID, weighed with what it holds, so
every reader of the leaf shares it across snapshots.

Experiment controls: FLUREE_REVERSE_FENCES=scan|copy|slice|off,
FLUREE_REVERSE_FENCE_SPACING=<bytes>.
Entries wholly within a held unit are read straight from its bytes; only
one crossing into the next unit goes through the cursor. The per-entry
cursor reads cost two bounds checks and a division each.
A fence index weighs a few percent of its leaf but costs a whole-leaf
decrypt to rebuild; in the leaflet pool, scans evicted it. It now has an
LRU pool sized from the leaflet budget, as stats views do.
…weigh it exactly

The fenced-leaf pool's share now comes out of the leaflet budget instead
of sitting beside it, and an entry is weighed in full: a fenced leaf
heavier than half the pool is read whole instead of being charged less
than it holds. LeafletCache::fenced_leaf_memory reports fence index bytes
apart from the sources' mapping charge.
…ir victims

FLUREE_DICT_ADMISSION=demand: a pack is weighed for admission once its
recent rent — misses halving each time all packs together have missed the
allowance's size — reaches its own size. If it does not fit, the least
recently looked-up packs that would make room are evicted for it only when
its recent lookups, counted served whole or by range and halving every
few lookups per unit the allowance holds, are at least twice theirs
together; otherwise the room stays as it is. Each pack records why it was
last turned away, under either policy.
FLUREE_DICT_ADMISSION=recent keeps the coverage policy — coverage guard,
clock eviction — but gates on recent rent, which halves each time ranged
forward-pack misses across all packs reach the allowance's size, instead
of rent since the pack was last whole. recent-compare also requires the
candidate's recent lookups to outweigh those of the victims the clock
picks; outweighed victims keep their place. Lookups are counted only for
policies that weigh them.
…only

Drops the copy, offset-slice and off modes and the spacing control.
Tests still compare fenced lookups against whole-leaf lookups at
several spacings.
A pack of a store that decrypts on read is read by range through the
leaflet cache and promoted whole once its recent rent reaches its size
and its rental has covered half of it; the allowance evicts in clock
order and backs promoted packs with anonymous mappings. Without a cache
the pack is decrypted whole, as before ranged reads.

Removes the experiment modes and their controls: whole, paged, ranged
and first-come packs, cumulative rent, demand admission and its lookup
clock, the segment-cache switch, heap backing and the coverage setting.

On encrypted storage the allowance is carved out of the cache budget,
60% by default or cache.dictionaryMaxMb (builder:
cache_dictionary_max_mb); unencrypted storage keeps the whole budget
for the leaflet cache. The rent clock advances in constant time per
miss.
New writes always use version 2 at the default segment size. Version 1
writes remain only as a hidden constructor for tests of stores older
releases wrote.
…onary reads

Readers on many threads promote and evict within the allowance; a
reload carries a promoted pack over; a retired pack leaves no meter and
gives up its room; an evicted fence index is rebuilt. End to end, a
store of version 1 envelopes reads as before, a reindex leaves the
index read by range, a rotation rewrites the rest as version 2, and
reads during a rotation see the same data.
Unencrypted storage never fences a reverse leaf, so its cache keeps the
whole leaflet budget, as before.
cache_dictionary_max_mb in the config file, --cache-dictionary-max-mb or
FLUREE_CACHE_DICTIONARY_MAX_MB; unset, it is 60% of the cache budget.
The harness's probe subcommand and the dictionary diagnostics behind it
measured fence layouts that are now settled. The in-memory fenced scan
stays as the tests' reference.
On encrypted storage the dictionary allowance and fence pool were carved
out of the cache budget whether or not the data could use them: a
version 1 store, whose packs are decrypted whole, ran its leaflet cache
at 40% of the budget with point lookups 4x slower than on next.

The cache still starts with both reserved, as measured, and gives back
what its data cannot use once that data is read. A pack that cannot be
read by range (version 1 envelope, remote read) lowers the allowance to
the smallest level, halving down from its cap, that covers what it holds
and the packs read by range before; it gives back the fence pool too
unless a reverse leaf has been fenced, as does a reverse leaf that
cannot be fenced. Nothing given back is reserved again, so version 2
data opened after legacy data reads by range without promotion.

The leaflet pool only grows: a pool that grew first and shrank as packs
opened left its high-water heap with glibc, on top of the allowance, and
a dense pass was killed under a 1 GiB cgroup. moka pools cannot be
resized, so each stage has a pool of its own; entries carry over, a
retired pool's entries are freed at once, and writes landing in a
retired pool are removed.
Describes the allowance and fence pool as given back to the leaflet cache
when the data cannot use them, says exactly what a reindex rewrites, and
documents FLUREE_IO_STATS: aggregate labels only, version 2 object and
segment counts overlap, and timings with it on are not comparable.
@bplatz bplatz added area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches performance Performance improvement (release notes: Performance) labels Oct 16, 2026
@bplatz
bplatz requested a review from a team October 16, 2026 19:29

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@bplatz this is a really carefully built piece of work, and at a design level no pushback from me: the v2 envelope is Tink's streaming-AEAD shape with the header bound through the key, and nothing I threw at it got partial plaintext out. Two headline notes. (1) The state the allowance promotes packs into doesn't hold up under concurrency: every whole-pack lookup takes a shared RwLock read, a Weak::upgrade and an Arc drop on the one HeldPack, so with 8 threads on one pack I measured about 2 µs per lookup against about 15 ns for a whole pack (on one thread they're the same). The A/B harness runs one query at a time, which is why it wouldn't show up there, and I think it needs to land before this merges (details below). (2) Not for this PR, but get_local_ranged joins permits_plaintext_cache and costly_local_reads as reader-side "ask the store how to read" probes (now at the leaf, pack and reverse-leaf openers), which is the shape #2029 is set up to retire, so it's probably worth adding it to #2029's list so stage 4 picks it up.

Full review below:


✅ Approving to unblock you — with 2 things that need to be addressed before this merges.

This is really nice, @bplatz. Reading encrypted leaves and dictionaries by authenticated segment, inside the one cache budget, is the right altitude for #2113; the give-back stages are tested at every seam I could think of; and the trade-off table in the body is honest about what it costs. I spent most of my time trying to break the envelope and the budget invariants, and these are the two things I'd want in before merge:

  1. 🔴 Promoted-pack lookups serialize under concurrency (fluree-db-binary-index/src/dict/pack_reader.rs:165, inline below). A pack held whole in the allowance is the steady state, and its lookups go from about 10 ns on one thread to about 240 ns at 2 threads and about 2 µs at 8, where next's whole packs stay flat. Fix direction: take the pack once per batch or scope and borrow it per lookup, and drop the per-lookup note_served diagnostic.
  2. 🟠 A cacheDictionaryMaxMb at or above cacheMaxMb leaves a zero-capacity leaflet pool, silently (fluree-db-binary-index/src/read/leaflet_cache.rs:885, inline below). The commented cache_dictionary_max_mb = 2048 in the config template is already over the default budget on a 4 GB host. A guard where the config is read (or a clamp with a floor), plus a test.

Two smaller notes inline: the encryption page's compatibility paragraph could say what a key rotation means for rollback, and there's a narrow race that lets the fence pool keep a leaf after its budget has gone to the leaflet pool.

On the follow-ups in the body: remote encrypted reads by range genuinely belong with #2029's stage 4 (content ids over ciphertext is a decision of its own, and it's a big change), and needing a restart to get the allowance back after a reindex follows from the "pools only grow" decision you measured, so I'm fine leaving both out of this PR.

I also went through the unencrypted path, since that's where a regression would hurt most. It gains two acquire loads per leaflet-cache access (Stages::pool()), a Writing guard per insert, a Box<dyn LeafHandle> per leaf in the batched probes, grouped count and range semijoin (which now take the cursor's lane), and one more costly_local_reads() per leaf open. None of that is per row, and your parity runs with #2119's fast path off cover it on x86, so no action from me, unless you'd like with_max_bytes to skip the stage indirection entirely, which would be cheap.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ get_local_ranged is a defaulted method on StorageRead/ContentStore, forwarded by every production wrapper (I checked TieredStorage, AddressIdentifierResolverStorage, CachedContentStore, StorageContentStore with its legacy fallbacks, BranchedContentStore and MeteredContentStore). Leaves reuse RangeReadLeafHandle, and the batched probes, grouped count and range semijoin now open leaves through LeafHandle like the cursor does. The new store probe is the #2029 shape (headline note 2).
  • Performance (speed first, memory second): 🔴 Promoted-pack lookups under concurrency (must #1). Otherwise the single-stream numbers match the body, and the unencrypted path has no per-row change (above). regression-budget.json and benches/ are untouched, and no bench covers encrypted storage: the A/B harness is an example, so nothing in CI or the nightly run would catch #1 coming back.
  • Deployment targets: ⚠️ fluree-db-server and solo's standalone binary both run encrypted file storage under concurrent requests, which is exactly where #1 lands, and the PR's evidence is single-stream runs. Remote (S3) encrypted stores write version 2 but read whole, and give the reservation back on the first pack (encrypted_remote_storage_writes_nothing_to_the_disk_cache pins that). Solo's Lambdas don't enable engine encryption, so they only see the unencrypted changes above. On wasm32 the ranged path is unreachable (no costly local reads), PackBuf falls back to the heap and the stage carry-over is cfg'd out; CI wasm32 and wasm-smoke are green on this head.
  • Testing: ✔ Thorough, and the tests have teeth: taking the header out of the HKDF info turns tampering_is_detected red, skipping the end-of-object check turns past_the_end_authenticates_the_final_segment red, dropping the retired-pool invalidation turns a_write_racing_a_stage_change_leaves_nothing_behind red, and keying units without the source identity turns units_are_not_shared_across_identities (and 14 others) red. The gap is concurrency: nothing times lookups from several threads at once (#1).
  • Conventions: ✔ Multi-line bodies throughout, and the docs and every config surface (JSON-LD, server flag, env and file, builder) change together. The history keeps the experiment rounds (demand admission, cumulative rent) by design, so they'll land in next's history with the merge.

Verified locally at f051a2fa7: cargo test -p fluree-db-crypto --lib (44 passed, plus 7 probes of my own: identical plaintexts, exact multiples of the segment size, empty and 1-byte objects, a dropped final segment, an appended segment, a read straddling a corrupt segment, and a same-salt splice, all failing closed); cargo test -p fluree-db-binary-index --lib (439 passed, every new test by name); it_encrypted_cache_reservation (4), it_key_rotation (7), it_storage_encrypted (12) and it_disk_cache_locality (7); the four mutation checks above; and the lookup timing probe behind must #1.

Approving so you're unblocked, but just be sure to get #1 and #2 in before this merges. Happy to talk through the scope-memo idea for #1 if that'd help.


/// The allowance's copy, if it holds one.
fn whole(&self) -> Option<Arc<HeldPack>> {
if let Some(pack) = self.seen.read().upgrade() {

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: a lookup in a promoted pack serializes every thread on the one HeldPack, so concurrent lookups get over 100× slower than a whole pack.

Every lookup served whole goes through whole() here: a parking_lot::RwLock read on seen, a Weak::upgrade (a CAS on the HeldPack's strong count), then note_served's two fetch_adds (:116) and the Arc drop when the lookup returns. All of that lands on the same one or two cache lines for every reader of the pack, so the lookup itself (about 8 ns) ends up queued behind cache-line ping-pong. The path before promotion has the same shape (seen.read() plus the absent_at.swap on every ranged lookup).

I measured it with a scratch test in this file's ranged tests (--profile dev-fast, one pack, T threads each doing 400k forward_lookup_into, wall ns per lookup per thread):

threads whole (PackBacking::Whole) promoted ranged (no allowance)
1 7.9 10.4 190
2 8.8 239 669
4 8.4 803 1,202
8 14.9 2,048 2,704

Taking note_served out on its own barely moves it (2,037 ns at 8 threads), so it's the refcount and lock traffic. On next an encrypted pack that fits is held whole, so a server answering several queries at once over an encrypted store that fits in memory regresses in exactly the steady state the allowance is built to reach. The A/B harness runs one query at a time, so it can't see this. I haven't measured it end to end through the server, only the lookup path.

Fix direction (illustrative, not tested): take the Arc<HeldPack> once per batch and borrow it for each lookup, for example by keeping it in the thread-local memo UnitMemoScope already opens around the formatters (re-checking only is_evicted(), which is written once, at eviction), and opening the same scope around the other per-row decode loops; or a refcount-free read such as arc_swap's load(). Either way I'd drop note_served from the per-lookup path (it's a diagnostic), and add a multi-threaded lookup test or bench so this stays pinned.

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 e22f588. A shared slot per pack, read through arc-swap (new dependency), rather than the scope memo, so lookups outside the formatters' scopes are covered too. lookups_in_a_promoted_pack_scale_across_threads pins it: eight threads against one, run alone under nextest.

.unwrap_or(
(u128::from(max_bytes) * u128::from(DEFAULT_DICTIONARY_PERCENT) / 100) as u64,
)
.min(max_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.

🟠 Should address (and I'd fold it in): a cacheDictionaryMaxMb at or above cacheMaxMb leaves the leaflet pool with zero capacity, with no error or warning.

.min(max_bytes) clamps the allowance to the whole budget, fenced_leaf_budget(0) is 1 byte, and Stages::new then builds the leaflet pool with budget.saturating_sub(budget + 1), which is 0. On a store of version 2 envelopes nothing is ever given back, so every leaflet, leaf directory, ranged-leaf source and decrypted segment is read and decrypted again on every access. A scratch test confirms it: with_reservable_budget(64 MiB, Some(64 MiB)) and Some(128 MiB) both give a pool whose max_capacity() is 0, reserved_bytes() is the budget plus one, and an inserted dict leaf isn't kept.

It's easy to get there by accident: cacheMaxMb defaults to a share of RAM, and the commented cache_dictionary_max_mb = 2048 in the config template (server_defaults.rs:434, docs/cli/server.md, docs/operations/configuration.md) is already above the default budget on a 4 GB host (40%, about 1.6 GB).

Minimally we could refuse it where the config is read (fluree-db-connection/src/config.rs and the server flag) with an error that names both values, or clamp the allowance so the leaflet pool keeps a floor, and warn; either way with a test pinning it. Small and agreed-correct, so I'd rather see it in this PR than tracked.

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 fcb7e06. Capped at 90% of cacheMaxMb with a warning rather than refused, since cacheMaxMb defaults to a share of RAM.

fits
});
if leaf.is_some() {
self.note_fenced_leaf();

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 narrow race lets the fence pool keep a leaf after its budget has gone to the leaflet pool.

holds_fences() is checked before open() runs, and note_fenced_leaf() is only stored after the whole-leaf decrypt that builds the fences. If another thread's note_unrangeable_pack() (a version 1 or remote pack) runs Stages::release in that window, it reads fenced == false, moves to a stage without fences and hands fence_budget to the leaflet pool, and then this leaf is inserted into fenced_leaves anyway. From then on holds_fences() is false, so nothing reads or evicts it until the next invalidate_all: up to fence_budget (a thirty-second of what the allowance leaves, about 1.25% of the budget at the defaults) held beside it.

It needs a mixed store and the right timing, so it's small, but it's the one way I found past "nothing is allocated beside it". (The stats-view pool also sits beside the budget, at a sixteenth of the leaflet share, but that predates this PR.) Minimally, re-checking holds_fences() after try_get_with returns and invalidating key when it has gone false would close it. 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 7b87228. The re-check runs under the stage lock: on its own it still left a window while release copies the old pool.

Comment thread docs/security/encryption.md Outdated
those releases read them. A reindex writes a new index, its leaves and
dictionaries, as version 2; commits and other objects it does not rewrite
stay version 1. A key rotation rewrites each blob on the retiring key as
version 2. Releases before this one cannot read version 2.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Optional (docs): two consequences of "releases before this one cannot read version 2" that an operator of an encrypted store would want spelled out here.

First, a key rotation on this release rewrites every blob on the retiring key as version 2, commits from before the upgrade included, so after a rotation an earlier release can't read even a ledger's history; any rollback that leans on reindexing from kept commits (as upgrading-from-4.2.md describes) stops working there. Second, on a shared store every process (Raft nodes, which write commit blobs from whichever node owns the branch, and query peers) needs this release before the first encrypted write. next's nameservice and index-format changes already imply the second, but this is the page an operator of an encrypted cluster reads.

A sentence each would do it. Minor and non-blocking, but if you agree it's right I'd rather see it in this PR than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 1f9585c.

let encoded = header.encode();
let mut info = Vec::with_capacity(INFO_PREFIX.len() + HEADER_LEN);
info.extend_from_slice(INFO_PREFIX);
info.extend_from_slice(&encoded);

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.

👍 Binding the header through the HKDF info rather than as per-segment associated data is a nice call, and it holds up. I tried flipped header bytes, swapped, duplicated, dropped and appended segments, a segment spliced in from another object under the same key (even with the same salt and only the nonce prefix different), a read straddling a corrupt boundary, and a cut final segment: every read that touched what I changed failed closed, and none returned partial plaintext. Removing this line turns tampering_is_detected red on the key-id byte.

One small observation while I was in there: with the length bound in the header, truncation is already caught through the key, so the nonce's last-segment flag is defence in depth. Forcing it to 0 turns only fixed_vectors and envelope_matches_the_reference_construction red among the envelope's tests, which is fine since they pin it.

…ted-reads

# Conflicts:
#	fluree-db-core/src/storage.rs
…a count

Every lookup in a pack the allowance held whole took a read lock,
upgraded a weak reference and counted itself on the one pack, so lookups
on several threads queued behind each other on its cache lines: about
2.7 µs a lookup at 8 threads, against 10 ns on one.

Each pack now has one slot, shared by its readers as its rent meter is,
which the allowance fills on promotion and empties on eviction, under its
lock. A lookup loads it through arc-swap and writes nothing other threads
read. A pack evicted while a lookup holds it stays charged until the
lookup lets go, as before. Lookups in a promoted pack now take about
10 ns from 1 to 10 threads.

The per-lookup served counters, a diagnostic, go with the A/B harness
fields that reported them. A test times lookups on eight threads against
one; nextest runs it alone.
…e cache

A cacheDictionaryMaxMb at or above cacheMaxMb left the leaflet pool no
capacity, with no error or warning: every leaflet, leaf directory and
decrypted segment was read and decrypted again on each access.

cacheMaxMb defaults to a share of RAM, so an allowance sized for one host
can pass the whole budget on a smaller one. Rather than refuse to start
there, the allowance is capped at 90% of the budget with a warning naming
both values, and the leaflet pool keeps the rest.
The fence pool is checked before a reverse leaf is opened, and the leaf
noted as fenced only after the whole-leaf decrypt that builds its fences.
A pack that could not be read by range, opened in between, read the leaf
as not fenced and gave the pool's budget to the leaflet pool; the leaf
was then inserted anyway, into a pool nothing reads or evicts until the
cache is invalidated.

Once the leaf is in, the loader re-checks under the stage lock and takes
it out if the pool has gone. A stage change still to come takes the same
lock, so it sees the leaf noted as fenced and keeps the pool.
After a key rotation an earlier release cannot read a ledger's history,
commits from before the upgrade included, so a rollback that reindexes
from those commits stops working; the encryption page says so and the
upgrade guide's rollback section lists it. On a store several processes
share, every process needs this release before any writes with it.
…ng it

retired_pools_release_their_entries counted the leaf's references right
after one maintenance pass. moka's map frees what it removes through
crossbeam-epoch, once every thread in the process has left the epoch it
was removed in, so under `cargo test` other tests running alongside held
it back: about one suite run in five failed with two references, the
pools holding nothing.

The test now pins and flushes the epoch, bounded, until the count drops.
A retired pool that kept the entry still fails 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