Repository navigation
fix: Eliminate S3-contention wedges (indexing, multi-query, reads) + multi-query envelope & indexing-fuel - #1261
Merged
Merged
Conversation
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).
reload() transitions Ready(h) -> Reloading{h, waiters} then only clears
the slot on the publish path. A dropped reload-leader future orphaned the
Reloading slot forever — unlike an orphaned Loading this doesn't wedge
query reads (get_or_load returns the still-valid handle for Reloading) but
it permanently stalls future reload()s and current_t() for that ledger.
Add ReloadLeaderGuard (mirrors LoadingLeaderGuard): on drop-before-publish
it evicts its own orphaned slot (generation match, so a stale guard can't
clobber a fresh entry), dropping the waiter senders so parked reloaders
get RecvError. Eviction is safe — the next query cold-loads fresh — and
avoids re-inserting after a concurrent disconnect. Tag Reloading with a
generation (same source as Loading) for the match.
Also hoist load_and_attach_binary_store out from under the entries write
lock, and drop the handle `state` write guard before acquiring `entries`,
so the two locks no longer overlap (removes reload's side of the
entries<->state ordering hazard with current_t).
reload()'s BecomeLeader arm held handle.lock_for_write() (the ledger `state` mutex) across the full reload I/O — LedgerState::load plus load_and_attach_binary_store (nameservice + S3 + index reads). During Reloading, get_or_load returns the still-valid stale handle, but LedgerHandle::snapshot() locks `state`, so queries for that ledger stalled behind the reload's remote I/O — the same "remote I/O blocks readers" failure mode, on the state lock. Build new_state + new_binary_store entirely off-lock, then take the state lock only for a brief coherent swap (acquire state then binary_store, set both with no .await between, so readers blocked on `state` never see a half-applied swap). The held lock had silently serialized reload against concurrent commits (a txn can take the stale handle via get_or_load's Reloading fast path and lock_for_write while we load); preserve that with a t-recheck mirroring notify's CommitCatchUp guard — if the in-memory state advanced past the reloaded storage HEAD, keep it rather than clobber the commit. reload now also never holds `state` and `entries` at once.
current_t held the entries read lock across handle.state_metrics().await (a state lock) — the entries->state acquisition order, the opposite of reload's state->entries. With reload now releasing state before entries there is no live ABBA, but normalize this too: clone the handle out and drop the entries guard before locking state, matching notify. No behavior change beyond lock scope.
…_blocking run_update_branch ran the incremental branch update inside spawn_blocking and fetched each touched leaf/sidecar on demand via handle.block_on(S3) from within that blocking-pool closure. On a blocking-pool thread block_in_place is a no-op, so that block_on still needs a tokio WORKER to drive its reactor; under slow remote storage (S3) + concurrent builds the workers can be saturated and the fetch stalls — the indexer twin of the query-path sync-bridge wedge. It is sporadic, scales with transaction volume (more novelty touches more leaves), is worse on S3 Standard than Express (latency = stall window), and never reproduces on a local filesystem (cache hits resolve instantly with no block_on). Mirror the codebase's own correct pattern (build/dicts.rs): add incremental_branch::touched_leaf_refs (the leaves update_branch will request = those with a non-empty novelty slice, via the same slicing), async-prefetch them into in-memory maps before spawn_blocking, and have update_branch's fetch closures read those maps. All CAS I/O is now on the async runtime; the blocking closure is pure CPU. Sidecar NotFound is still treated as absent. Per-leaf fetch stats are preserved. Verified by the incremental-indexing integration suites (real multi-commit build+query).
Two resilience fixes in the orchestrator: 1. Panic boundary per ledger. The worker is a single task processing ledgers sequentially with the build awaited inline; its JoinHandle is detached. A panic in any one build (or its bookkeeping) unwound out of run() and killed the worker permanently — stopping ALL indexing, which eventually wedges commits everywhere via novelty backpressure. Wrap each process_ledger in catch_unwind: on a caught panic, log, reset that ledger to Pending with a backoff retry, and keep the loop alive. 2. Bound the retry hot-loop. Three retry sites (content-store-build error, and the two "nameservice reports index_t but no index_head_id" gates) used a flat 250ms retry despite a "with backoff" comment — a permanent ~4/sec hot-spin when, e.g., a just-published root isn't yet visible on slow/eventually-consistent S3. Replace with the shared retry_backoff (100ms * 2^retry_count capped at 30s), matching schedule_retry. Note: the worker JoinHandle is still detached; external supervision (detect a truly-dead task and restart) remains a follow-up, but the panic boundary removes the realistic way the worker died.
The cancellation guards added earlier gated only the detached drop-cleanup on the slot generation; the normal publish path still removed / notified / re-cached unconditionally. A stale leader whose Loading/Reloading slot was cleared by disconnect() — and replaced by a NEWER leader's slot — would on finishing remove the newer slot, notify the newer leader's waiters with the stale result, and cache stale data. Publish now checks the current slot still carries THIS leader's generation before removing/notifying/reinserting (get_or_load: both Ok and Err; reload: both Ok and Err). A stale leader that lost ownership leaves the slot untouched and just returns its own result to the direct caller.
LazyVectorArena::ensure_on_disk (query-time vector search against remote stores) used the same dangerous bridge the dict/pack readers had: std::thread::spawn + outer Handle::block_on(cs.get) + rx.recv() with no block_in_place. On a small (e.g. 2-worker) runtime that parks a worker on recv() with no thread left to drive the reactor — the S3 fetch never completes. Route it through run_sync_on_runtime like the other read bridges. Found while sweeping for other instances of the multi-query wedge pattern.
The panic-isolation handler unconditionally set phase=Pending + retry. If a ledger was cancelled mid-build (cancel()/cancel_all() resolved its waiters and cleared pending_min_t while InProgress) and then process_ledger panicked, it was left Pending with no pending work: the run-loop collector only re-processes when pending_min_t.is_some(), and the cancel-cleanup only runs when has_pending_work(), so it never recovered and reported busy forever (wait_for_idle hangs). Mirror schedule_retry: if cancelled, resolve waiters as Cancelled, clear pending_min_t, go Idle; else retry with backoff only when work remains; otherwise go Idle rather than strand it as Pending.
The full-rebuild pipeline runs on a spawn_blocking thread (it holds non-Send dictionaries across awaits) and block_on's its S3 reads/writes via the main runtime's handle. On a blocking-pool thread block_in_place is a no-op, so that block_on's IO reactor only advances when a main worker is free — under a small-worker runtime + concurrent load the rebuild's S3 IO can stall, the same starvation class as the read-path bridges (lower exposure: a rebuild is rare and, in solo3, runs alone on the indexing lambda). Prefetch-and-hoist (the incremental-path fix) isn't viable here because the read/CPU/write phases are deeply interleaved with non-Send state. Instead drive the block_on on a small dedicated multi-thread runtime so the rebuild has its own reactor/workers, independent of main-runtime pressure. Same Handle::block_on call shape, different runtime.
…boundary Compute the run-loop retry deadline only from processable states (pending work, not cancelled) via a shared is_processable() predicate, and clear next_retry_at on every transition to Idle. A stale deadline left on an idle/cancelled state is in the past, so sleep_until returned immediately on every iteration while the state was filtered out of the processing scan, hot-spinning the worker. Normalize an orphaned InProgress entry at the single dispatch site that all process_ledger returns funnel through, so a missed terminal transition can never strand a ledger as perpetually busy. Prune fully-terminal idle entries from the states map each tick so it stays sized to the active working set rather than every ledger ever triggered. Clear the cancelled flag once a cancelled ledger reaches a terminal idle state (e.g. a build cancelled mid-flight that has since completed and been set Idle), not only when it still has queued work, so the prune can reclaim those entries too. Cap concurrent detached background-GC tasks with a semaphore and skip a pass when the cap is reached; GC re-scans the full prev-index chain on each run, so a skipped pass is reattempted after the next successful index. Document the rebuild dedicated-runtime isolation boundary: it covers the future, its timers, spawned tasks, and connections opened during the rebuild, but not connections reused from the shared SDK hyper pool, which keep their driver task and socket on the runtime that created them. Adds regression tests for the deadline filter, cancel-clears-deadline, InProgress normalization, the prune predicate, an end-to-end prune, and clearing+pruning a terminal cancelled state.
RangeBackedChunkReader::fetch_bytes bridged parquet's synchronous ChunkReader
to async storage with a bare Handle::block_on, which only avoids a panic when
called from a blocking context. The sole caller wraps it in spawn_blocking,
but a future direct caller could panic ("cannot block the current thread from
within a runtime") or deadlock/wedge depending on the runtime flavor.
Route the fetch through a flavor-aware bridge (block_on_storage_fetch):
- multi-thread runtime: block_in_place(handle.block_on) so the calling worker
is released and the reactor keeps running (a no-op under the existing
spawn_blocking caller);
- current-thread or unknown runtime: drive the future on a self-contained
current-thread runtime in a helper thread, since block_in_place would panic
and block_on would deadlock the single thread;
- no ambient runtime: block on the handle captured at construction.
Mirrors run_sync_on_runtime in fluree-db-binary-index. Adds a current-thread
regression test.
…ngle-flight Concurrent readers of the same not-yet-cached content each issued their own remote get and tmp-file write (a thundering herd): the decoded-object caches coalesce, but the raw S3 -> local-tmp-disk fetch layer did not. Add per-target single-flight at the artifact-cache boundary (DiskArtifactCache), where the "check disk -> fetch -> atomic write" path and shared per-cache-dir state already live, so one leader fetches while the rest await the shared bytes. Design: - Narrow key: the resolved cache-target path (same content + same destination), so unrelated reads never serialize. - The in-flight map lock (parking_lot) is never held across .await; the leader/waiter role is decided under the lock, which is dropped before fetching. - Bytes are shared as Arc<[u8]> during the flight; the per-caller Vec copy happens only at the API boundary, and the shared allocation is skipped when no one is waiting. - Errors are never cached: the slot is removed on completion, so the next caller retries. The post-win disk re-check is an optimization only — a miss or a transient read error both fall through to the authoritative fetch rather than failing the coalesced batch. - Cancellation/panic safe: a generation-checked FlightGuard clears the slot on completion and on drop, so a cancelled leader cannot orphan it; waiters then observe a closed channel and retry instead of hanging. - Leader double-checks disk after winning (a just-finished prior flight may have written the file), then fetches once and writes atomically. Public signatures (fetch_cached_bytes / fetch_cached_bytes_cid) are unchanged, so all hot-path and indexer callers are unaffected. Process-local only; it does not coordinate across containers. Adds tests for concurrent coalescing, error-not-cached, disk double-check, disk-read-error fall-through, cancelled- leader-no-orphan, and end-to-end CID coalescing.
The `#[cfg(test)] mod tests` block sat in the middle of store.rs with parsing helpers defined after it, tripping clippy's items_after_test_module under `-D warnings` and failing the workspace clippy gate. Move the test module to the end of the file (functions first). No behavior change.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This sits on #1258 as that helped expose and diagnose the issue.
This PR eliminates the runtime-starvation "wedge" that could stall Fluree under concurrency on object storage — most visibly the incremental-indexing stall and the multi-query stall, but also the general query read path. The root cause was a family of synchronous
block_onbridges (plus a cancellation-unsafe single-flight slot) that occupied Tokio worker threads, so the IO reactor could no longer advance and the very S3 reads each was waiting on never completed. It was worse on S3 Standard than Express and was never reproduced on the local filesystem.Every such bridge now either releases its worker with
block_in_placeor runs on a dedicated/helper runtime, single-flight coordination is made cancellation-safe, and a new process-local single-flight collapses the thundering herd of concurrent identical S3 GETs.Symptom
Under concurrent load against S3, operations could hang indefinitely: multi-query subqueries never completing, incremental indexing stalling (sporadically, and only after many transactions), and reads wedging — while the same workloads were rock-solid on the local filesystem.
Root cause
Synchronous-to-async bridges (
Handle::block_on, and hand-rolledthread::spawn + block_on + rx.recv()) ran on Tokio worker threads withoutblock_in_place. On a small (e.g. 2-worker) runtime, every worker could end up parked inside one of these blocking bridges with no thread left to drive the IO reactor/timer — so the S3 fetch each was waiting on could never complete. That is a hard, self-sustaining wedge. A cancellation-unsafe single-flight "Loading" slot could additionally orphan waiters forever, and holding the ledger-state lock across reload I/O widened the window.Wedge fixes (the bulk of this PR)
run_sync_on_runtime—block_in_place(handle.block_on)on multi-thread runtimes (frees the worker so a replacement drives the reactor), and a self-contained helper runtime on current-thread.LeafletCachesingle-flight (moka) waiters are wrapped inblock_in_place, so a coalesced waiter can no longer pin a worker.get_or_loadandreloadno longer orphan theirLoading/Reloadingslots when a caller is cancelled, and publish is gated on a slot generation token to close an ABA hole.reload()no longer holds the ledger-state lock across reload I/O;current_tclones the handle before locking.spawn_blocking, instead of callingblock_oninside the blocking closure — the specific cause of the indexing wedge.block_onon a dedicated runtime, so its IO is advanced by dedicated workers rather than the (possibly starved) main runtime.ChunkReadersync bridge is now flavor-aware (block_in_placeon multi-thread; helper runtime on current-thread), so it cannot panic or wedge if it is ever called off aspawn_blockingthread.FLUREE_CAS_SYNC_TIMEOUT_MSnow also applies to the dict/pack CAS bridges as a backstop.Net effect: the main runtime's reactor stays live under concurrency, so S3 reads always make progress. The incremental-indexing, multi-query, and read-path wedges are eliminated.
New: artifact-cache single-flight coalescing
Concurrent readers of the same not-yet-cached object previously each issued their own S3 GET and tmp-file write (a thundering herd): the decoded-object caches coalesce, but the raw S3-to-local-tmp fetch layer did not. This PR adds per-target single-flight at the artifact-cache boundary (
DiskArtifactCache), where the "check disk, fetch, atomic write" path and shared per-cache-dir state already live — one leader fetches while the rest await the shared bytes.Arc<[u8]>during the flight; the per-callerVeccopy happens only at the API boundary, and the shared allocation is skipped when no one is waiting.fetch_cached_bytes/fetch_cached_bytes_cidsignatures are unchanged, so all hot-path and indexer callers are unaffected. It is process-local by design and does not coordinate across containers.Background-indexer hardening
The single background-indexer worker is made resilient so an indexing hiccup can neither kill indexing nor wedge commits via novelty backpressure:
InProgressnormalization at the single dispatch site all returns funnel through.Risk and compatibility
fetch_cached_bytes/fetch_cached_bytes_cidand the indexer/ledger-manager public surfaces are unchanged.Config knobs
FLUREE_CAS_SYNC_TIMEOUT_MS— backstop timeout on the CAS sync bridges (now also covers dict/pack).