Skip to content

fix(indexer): recover a ledger wedged at max novelty - #1662

Merged
bplatz merged 11 commits into
fluree:mainfrom
christophediprima:fix/indexer-periodic-catchup
Sep 3, 2026
Merged

bplatz merged 11 commits into
fluree:mainfrom
christophediprima:fix/indexer-periodic-catchup

Conversation

@christophediprima

Copy link
Copy Markdown
Contributor

A ledger that reaches reindex_max_bytes of accumulated novelty cannot recover on its own, and the reason is a cycle rather than a slow path.

at_max_novelty gates on the ledger's accumulated novelty, not on the size of the incoming transaction, so once a ledger is over the line it rejects every write — including a tiny one. Only the indexer can drain novelty. But every index trigger in the api layer fires after a successful commit, and those hooks are in-process, so a restart does not replace them.

So the one condition that most needs an index build is the one condition guaranteed not to request one. The ledger stays wedged until someone reindexes it by hand.

Why this is reachable in an ordinary deployment

catch_up_sweep is the only path that indexes a ledger without a fresh commit, and it was reachable only from run_event_subscriber — which run() spawns only when a caller supplies an event bus. In practice the only production caller that does is the raft leader task. Every embedded and standalone deployment therefore ran with no catch-up sweep at all, not even at start-up.

We hit this on a multi-ledger deployment: several ledgers stopped advancing entirely and stayed stopped, while the indexer looked perfectly healthy — it was servicing, in a tight loop, the one ledger that still had headroom to commit. The ledgers that could not commit were never scheduled, because nothing scheduled them. Nothing logged an error: the rejection is a WARN, and a caller that defers on backpressure is behaving correctly.

What this changes

Three independent recovery paths, deliberately overlapping, because each covers a case the others do not:

  • At start-up — run catch_up_sweep from the worker rather than only from the event subscriber, so a process that begins with an unindexed backlog recovers without needing an event bus.
  • On a timer — re-sweep ledgers whose commit_t has stalled, which covers a ledger that falls behind after start-up and then stops receiving the commits that would trigger it.
  • Immediately — have the rejected write itself ask for a build. This is the only path with O(1) latency: the sweeps recover a wedged ledger at start-up or within up to two sweep intervals, whereas the write that is actually blocked knows straight away.

Plus --indexer-catchup-interval-secs / FLUREE_INDEXER_CATCHUP_INTERVAL_SECS so the sweep is tunable on a running deployment. 0 disables the re-sweep; it deliberately does not disable the start-up sweep, and the help text says so, because that one is the deadlock fix.

Three details that are load-bearing

The nudge is fire-and-forget, and must be. Only the indexer can drain novelty, so a caller that holds the ledger while waiting starves the very build it is waiting for. trigger_if_idle registers no waiter and yields to anything already in flight, which also rate-limits it to once per idle window however fast rejections arrive, and avoids resetting a failing build's retry backoff into a hot loop.

It is not fired for NoveltyWouldExceed. That rejection is already self-healing — callers halve the batch and retry — so nudging on it would fire on every split.

The timer sweep could not simply call catch_up_sweep. That predicate is merely "behind", and process_ledger builds whenever commit_t > index_t with no byte gate, so a periodic sweep of it would force an extra index build per behind-ledger per interval on a busy deployment. NsRecord carries no novelty byte count, so the sweep cannot re-apply the operator's reindex_min_bytes threshold either. The stalled-ledger predicate exists to avoid that cost.

Testing

fmt and clippy --all --all-features --all-targets -- -D warnings clean; fluree-db-indexer and fluree-db-api --lib suites pass.

Seven new tests, including that the stalled-ledger predicate selects frozen ledgers only and queues the most-behind first — the ordering matters, because a sweep that starts with the least-behind ledger leaves the worst one waiting longest.

christophediprima and others added 5 commits August 18, 2026 10:47
…the subscriber

`catch_up_sweep` is the only path that indexes a ledger without a fresh commit,
and it was reachable only from `run_event_subscriber` — which `run()` spawns only
when a caller supplied an event bus. The only production caller that does is the
raft leader task, so every embedded and standalone deployment started with no
catch-up sweep at all, not even at startup.

That is a deadlock, not a slow path. `at_max_novelty` gates on the ledger's
accumulated novelty rather than on the size of the incoming transaction, so a
ledger loaded with a backlog already past `reindex_max_bytes` rejects every
write. No commit is published, so the post-commit hooks in the api layer never
fire — and those hooks are in-process, so a restart does not replace them. The
one thing that can drain novelty is gated behind the one thing novelty blocks,
and no smaller write can break in.

Observed on a 24-ledger materialize fan-out: ledgers sitting at commit_t 597 /
index_t 251 with no index build ever attempted, for hours, across a fresh
process. A materialize job's watermark cannot advance while any of its fan-out
targets is behind, so single wedged targets froze 13 source tables behind them.

The sweep consumes only `nameservice.all_records()`, so it never needed a bus:
move it into `run()` and make it unconditional. Subscribing the worker to the bus
instead would be a regression — `process_ledger` builds whenever
`commit_t > index_t` with no byte gate, so triggering off every
`LedgerCommitPublished` would index after every commit and quietly discard the
`reindex_min_bytes` threshold the operator configured. `NsRecord` carries no
novelty byte count, so a subscriber cannot re-apply that threshold.

Under raft this is behaviour-neutral: both paths swept once per leadership
acquisition, and the nameservice is no longer listed twice at start-up.

The new test pins the property the old one missed. `catch_up_sweep_triggers_only_behind_ledgers`
covers the sweep as a function; nothing asserted that `run()` ever calls it.
The start-up sweep fixes a process that begins with an unindexed backlog. It
cannot help a ledger that falls behind afterwards and then stops receiving the
commits that would trigger it — a rebase writing past the per-commit gate, or an
indexer process that does not write the storage it indexes and so has no trigger
source at all. Both leave the ledger wedged until a restart or a manual reindex.

The obvious fix — call `catch_up_sweep` on a timer — is not affordable as-is. Its
predicate is "behind", and `process_ledger` builds whenever `commit_t > index_t`
with no byte gate, so on a busy deployment a periodic sweep would force an extra
index build per behind ledger per interval. `NsRecord` carries no novelty byte
count, so the sweep cannot re-apply the operator's `reindex_min_bytes` threshold
either.

So require a second condition: `commit_t` unchanged since the previous sweep. A
ledger that is still committing is already served by the post-commit trigger; a
wedged one is frozen by definition. `stalled_ledgers` is a pure function over
`(records, last_seen)` so that decision is testable without a nameservice, a
worker, or a timer, and it orders most-behind first — on a deployment starting
with a backlog, the ledger blocking writes should be queued ahead of one lagging
by a single commit.

The predicate can misfire once, on a ledger whose commits straddle two sweeps at
the same `commit_t`. That costs one extra build and then converges: afterwards
`index_t == commit_t` and it is not swept again until it falls behind.

`trigger_if_idle` is new because `trigger` is wrong for a timer. `trigger` clears
`cancelled` and zeroes the retry backoff, which is correct for an explicit
request and harmful on a schedule: it would resurrect work an operator
deliberately cancelled, reset a failing build's backoff every interval, and start
a build underneath a reindex holding the ledger quiesced. `trigger_if_idle`
declines in all three cases and registers no waiter, so the entry converges back
to Idle on success with nothing to resolve.

`catchup_interval` lives on `IndexerConfig`, which the worker already holds,
defaulting to 300 s — a safety net, not a scheduler, and well above the 30 s
retry-backoff ceiling so a sweep never races a build that is already retrying.
`Duration::ZERO` disables it. It does NOT disable the start-up sweep: that one is
a deadlock fix rather than a tuning knob, and an operator reaching for an off
switch should not be able to turn it off by accident.
… novelty

`at_max_novelty` gates on the ledger's accumulated novelty rather than on the
size of the incoming transaction, so a ledger holding a backlog past
`reindex_max_bytes` rejects every write — including a 71-row one. The rejection
returns an error and does nothing else, and every index trigger in the api layer
is post-*successful*-commit. So the one condition that most needs an index build
is the one condition guaranteed not to request one.

Have the rejected write request it. This is the only recovery path with O(1)
latency: the sweeps added alongside it recover a wedged ledger at start-up or
after up to two sweep intervals, whereas the write that is actually blocked knows
immediately.

Fire and forget — never wait. Only the indexer can drain novelty, and a caller
that holds the ledger while waiting starves the build it waits for;
`graph_source::r2rml_materialize` records the production deadlock that caused
(zero builds for six minutes, recovering only when the wait was removed).
`trigger_if_idle` registers no waiter and yields to anything already in flight,
so this is rate-limited to once per idle window however fast the rejections
arrive — and it will not reset a failing build's retry backoff, which a client
retrying at speed would otherwise do into a hot loop.

Not fired for `NoveltyWouldExceed`: that rejection is already self-healing,
because callers halve the batch and retry, so nudging on it would fire on every
split.

Three staging seams, one per entry family: owned-state insert/upsert/transact
(the materialize path), the guarded view path (the HTTP transact route and SPARQL
UPDATE), and credential transact. The credential path's hard-coded 400 is
preserved as-is — novelty backpressure surfacing as `InvalidTransaction` rather
than a 503 is a real problem and a separate one.
Mirrors `--reindex-min-bytes` through the same three layers: the clap flag with
its `FLUREE_INDEXER_CATCHUP_INTERVAL_SECS` env var, the `[server.indexing]`
config-file section with the default-detection entry that lets the file override
it, and the builder call in `build_direct_fluree`.

The re-sweep ships with a safe default, so this is operator surface rather than a
fix — but without it the only way to change or disable the sweep on a running
deployment is a new binary, which is the wrong answer for a background task that
lists the nameservice on a timer.

`0` disables the re-sweep. It does not disable the start-up sweep, and the flag's
help text says so: that one is a deadlock fix, and an operator reaching for an off
switch should not be able to turn it off by accident.
…e indexer

The clap default named `fluree_db_indexer::DEFAULT_CATCHUP_INTERVAL_SECS`
directly. `fluree-db-server` takes `fluree-db-indexer` as an OPTIONAL dependency
gated behind the `raft` feature, and the default feature set does not enable it,
so that reference compiles under `--all-features` and fails the default build:

    error[E0433]: cannot find module or crate `fluree_db_indexer`
      --> fluree-db-server/src/config.rs:436

Which is how it reached CI: the checks I ran locally were all `--all-features`,
and CI's clippy and test jobs are not.

`fluree-db-api` depends on the indexer unconditionally, and the server already
sources its other clap defaults from `fluree_db_api::server_defaults`, so
re-export the constant there and reference it the same way. One definition, one
import path, and the value stays owned by the indexer crate.

Verified under BOTH feature sets this time: `clippy --all --all-targets
-D warnings` (default) and the same with `--all-features`, plus `fmt --check`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

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

@christophediprima the deadlock analysis here is good: the accumulated-novelty gate, the post-commit-only triggers, and the bus-only sweep really do compose into "this condition where we need an index build is the one that doesn't request one," and I verified the flagship test goes red the moment the startup sweep is removed.

The three-path design (startup, stalled-timer, rejected-write nudge) with trigger_if_idle's careful decline semantics is the right shape, and the stalled predicate is a smarter invariant than "behind" for a periodic sweep.

One scoping note so this reads accurately: the deadlock is confined to the bundled indexing composition (that is, the indexing_enabled background worker and standalone fluree-db-server) and not to the api surface. The levers an external operator needs all pre-exist and work: NoveltyAtMax/NoveltyWouldExceed are typed and reach the caller, admin::trigger_index/admin::reindex are public, and an operator layered around fluree-db-api cannot wedge this way.

The bug, then, is that an operator who delegated indexing to the bundled worker got no self-recovery in exactly the state that needs it, which is why the fix belongs in the worker, and why this PR's placement (sweeps in the worker, the tx.rs nudge gated on IndexingMode::Background, error propagation to the caller unchanged) draws the right boundary.

I think my only blockers here have to do with the RAFT claim: "behaviour-neutral under raft" only models the leader-scope worker, but RAFT mode also spawns the node-scope worker on every node (api/src/lib.rs:2717 via build_direct_fluree), and this PR turns that previously-passive worker into an active sweeper. That is, the leader gets two independently-sweeping workers with no cross-worker dedupe (duplicate concurrent builds of the same ledger, ongoing), and followers start initiating builds the repo's own leader-only comment says they should not (server/src/lib.rs:993-996). @zonotope -- perhaps this PR would benefit from your review as you're much more familiar with the RAFT & consensus mechanics/logics than I am.

Relatedly, the new --indexer-catchup-interval-secs never reaches the leader-scope worker (IndexerConfig::default() at server/src/lib.rs:967), so under RAFT the advertised "off-switch" doesn't govern the sweep that runs. Both have small fixes: gate the node-scope worker (or its sweeps) in RAFT mode, and thread the flag into the leader-scope config. I've provided details inline.

Adherence to repo commitments:

  • Patterns/abstractions: ⚠️ extends the existing sweep/trigger machinery well (no parallel constructs; trigger_if_idle is a disciplined sibling of trigger), but the deployment survey missed the second worker RAFT runs.
  • Performance (speed first, memory second): ⚠️ no query hot path; sweeps are one nameservice listing per tick and builds stay serialized per worker (verified), but the RAFT shape doubles concurrent builds on the leader, which is the expensive resource here.
  • Testing: ✔ seven new tests, all verified running by name; the flagship one is mutation-checked (verified: removing the startup sweep fails it); the pure-function predicate is testable exactly as claimed. The untested seam is the raft double-worker interleaving — which is the blocking finding.
  • Conventions: ✔ exemplary multi-line commit bodies; fmt/clippy clean (verified package-scoped; CI all-features green); config plumbed through flag+env+file with default-detection.

Verified locally at branch HEAD: fluree-db-indexer 393/393, the tx seam test green, cargo check -p fluree-db-server --all-targets (default features) clean, startup-sweep mutation kills run_sweeps_behind_ledgers_without_an_event_bus, and the pre-fix commit's CI failure log confirmed as the default-features E0433.

The embedded/standalone fix is exactly right and I'd like it in, just be sure the RAFT story is made true (or made safe and stated) and the flag reaches the worker that sweeps before this merges; both look like small diffs and I'm happy to re-review as they're fixed.

Comment thread fluree-db-indexer/src/orchestrator.rs Outdated
// The same task then re-sweeps on a timer, for the residual the start-up
// sweep cannot cover: a ledger that falls behind later and stops
// receiving the commits that would trigger it.
let _sweep_guard = {

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.

🔴 Blocking — "Under raft this is behaviour-neutral" is not true: every raft node now runs an actively-sweeping worker, and the leader runs two.

The commit closes with "Under raft this is behaviour-neutral: both paths swept once per leadership acquisition." That accounts for the leader-scope worker only. Raft mode builds its api-layer Fluree through build_fluree_with_nameservice → build_direct_fluree, and with indexing_enabled (the default) that spawns a second, node-scope BackgroundIndexerWorker on every raft node (fluree-db-api/src/lib.rs:2717) — bus-less, so pre-PR it never initiated work on its own; it only reacted to local post-commit triggers. This PR makes run() sweep unconditionally, so post-PR that node-scope worker sweeps at process start and then every catchup_interval on every node, leader and followers alike.

Consequence, two-fold. On the leader: two workers (node-scope + leader-scope) with independent states maps and no cross-worker dedupe — trigger_if_idle's "declines when already Pending/InProgress" only sees its own map — so the same behind/stalled ledger gets queued and built twice, concurrently, in one process, at startup and again on every stall (two independent timers; the leader-scope one is pinned to the 300 s default because it's built from IndexerConfig::default() at fluree-db-server/src/lib.rs:967). Index builds are the most expensive thing the indexer does; doubling them on the node that's already struggling is the wrong direction, and concurrent duplicate builds of the same ledger publishing through the raft nameservice is an interleaving I don't believe anything tests. On followers: they now initiate builds where the repo's own comment says indexing is leader-only precisely because "it publishes through the nameservice, which under Raft proposes to the state machine" (fluree-db-server/src/lib.rs:993-996) — either those publishes work (and the leader-only invariant is quietly gone) or they fail and every follower grinds retry-backoff loops per behind ledger, forever.

I may be missing a guard somewhere — if there's a reason the node-scope worker's builds are safe/idempotent under raft (a monotonic publish CAS, say), the waste is still real but the correctness half softens. But as it stands the premise the commit asserts is the thing I'd want proven before this merges. Fix options, cheapest first: (a) in build_direct_fluree, don't enable the node-scope background indexer when a raft nameservice was supplied (the leader-scope worker is the raft indexer by design — this also makes the new flag's story coherent, see the config.rs comment); (b) gate the sweeps (startup + timer) behind a builder knob the raft path can turn off, keeping post-commit triggering intact; (c) if follower/duplicate builds are actually intended and safe, say so in the commit and add the test that pins the double-build interleaving. Happy to talk through which of these fits the raft roadmap best.

(Commenting on the sweep block because the topology that makes it bite — api/src/lib.rs:2717, server/src/lib.rs:808, server/src/state.rs:505-514 — is not in this diff.)

/// deployment pays one nameservice listing per interval and nothing else.
/// `0` disables the re-sweep; the sweep performed at start-up always runs.
#[arg(long, env = "FLUREE_INDEXER_CATCHUP_INTERVAL_SECS", default_value_t = server_defaults::DEFAULT_INDEXER_CATCHUP_INTERVAL_SECS)]
pub indexer_catchup_interval_secs: u64,

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.

🟠 High — --indexer-catchup-interval-secs silently does not govern the raft leader's sweeping worker.

The new flag/env/config-file key is plumbed into build_direct_fluree's node-scope worker only. The leader-scope worker — under raft, the one that's supposed to sweep — is constructed from IndexerConfig::default() (fluree-db-server/src/lib.rs:967, not in this diff), so under raft the operator's interval (including 0 to disable) applies to the wrong worker and the leader keeps a hard-coded 300 s timer no flag can touch.

Pre-existing pattern for the other indexer knobs, granted — but this flag is new operator surface introduced by this PR, and its help text promises a tunable that raft deployments don't actually get. If the raft blocker resolves as "node-scope worker doesn't run under raft," then this becomes the only sweep raft has, and the flag governs nothing there at all.

Minimal fix: thread config.indexer_catchup_interval_secs (and while you're there, arguably reindex_min_bytes) into the leader-scope IndexerConfig.

/// two sweeps at the same `commit_t`. That costs one extra build and then
/// converges: afterwards `index_t == commit_t`, `has_novelty()` is false, and it
/// is not swept again until it falls behind.
fn stalled_ledgers(records: &[NsRecord], last_seen: &HashMap<String, i64>) -> Vec<(String, i64)> {

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.

Nit. The comparator calls records.iter().find() per comparison, so the sort is O(S·log S·R). It's a background sweep over a usually-small stalled set, so I don't think it matters in practice — but a precomputed HashMap<&str, i64> of gaps is three lines and removes the quadratic-ish shape entirely. It's small — if you agree, I'd rather see it folded in now than tracked.

/// one is a deadlock fix, not a tuning knob.
///
/// Default: 300 s.
pub catchup_interval: Duration,

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.

Observation, more question than suggestion. A ledger that commits a small write (below reindex_min_bytes) and then goes idle will be swept two ticks later and force-built — the sweep can't see novelty bytes, so the operator's min-bytes batching is bypassed once per stall. It converges (one build, then has_novelty() is false) and arguably draining the tail is desired, but on a multi-tenant deployment with hundreds of mostly-idle ledgers this is a steady trickle of small forced builds the operator thought they'd deferred. Worth a sentence in the flag's help text at minimum.

Comment thread fluree-db-api/src/tx.rs
// alive past the `ledger` move into `stage_with_config_shacl`.
let ledger_id_owned: String = ledger.snapshot.ledger_id.to_string();
// Captured before `ledger` moves into staging, so a max-novelty
// rejection can name the t the indexer should build to.

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.

Praise. The rejection's error propagation is preserved byte-for-byte in all three families (I read each), NoveltyWouldExceed is correctly left alone, and the fire-and-forget rationale (waiter starvation, backoff preservation, once-per-idle-window rate limiting) is exactly right. The trigger_if_idle decline table — cancelled, pending, in-progress, maintenance-held — with a test per row is how this kind of primitive should land.


pub const DEFAULT_INDEXING_ENABLED: bool = true;

/// Re-exported from `fluree-db-indexer` so the server can reference it under

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.

Accuracy nit, no action needed. The follow-up commit's body says "CI's clippy and test jobs are not [--all-features]" — they are (ci.yml:50, :78); what caught the break is the test job's default-features cargo check --workspace --all-targets backstop (ci.yml:85-86). The fix itself (routing the constant through server_defaults) is the right shape and verified compiling under default features at HEAD.

The sweeps added alongside the deadlock fix run in `BackgroundIndexerWorker::run`,
which every deployment reaches. That is right for embedded and standalone, and
wrong for raft: a raft process runs TWO workers against one nameservice. Every
node builds a node-scope worker through `build_direct_fluree`, and the leader
additionally runs the leader-scope worker `Server::run` spawns inside
`leader_tasks` — the bus-wired one, started and stopped with leadership.

Unconditional sweeping breaks both halves of that. On the leader, two workers
sweep over independent `states` maps, so `trigger_if_idle` cannot see the other's
claim and the same ledger is queued and built concurrently.

On followers it is worse than duplication, because a follower's build cannot
land. `RaftNameService::publish_index` calls `client_write`, which on a
non-leader returns `ForwardToLeader` — openraft does not auto-forward — and that
arm returns `Ok(())`. The build therefore does the full work (CPU, memory, index
leaves and branches and root written to shared CAS), is told the publish
succeeded, and advances no index head; the artifacts orphan until GC. The
swallow is right for what it was written for, a stepped-down leader's straggling
publish where the new leader will build again, and wrong for a worker that was
never the leader and would sweep on every interval forever.

`IndexerConfig::catchup_sweeps_enabled` says who owns catch-up. It skips both
sweeps and nothing else: post-commit triggers, `trigger_if_idle`, admin reindex,
cancel and maintenance holds all route through `IndexerHandle` and keep working.
That distinction is the reason it is not `without_indexing()`, which would answer
`ApiError::IndexingDisabled` from `admin::trigger_index` and `admin::reindex`,
drop the cancel + wait_for_idle quiesce that ledger drop and branch purge rely
on, and silently no-op the max-novelty nudge — turning off manual reindex on
every raft node to fix an automatic-sweep problem.

Distinct from `catchup_interval == ZERO`, deliberately: that is an operator
tuning knob and leaves the start-up sweep alone, because the start-up sweep is
the deadlock fix. This is a statement about deployment topology.

Also threads `--indexer-catchup-interval-secs` into the leader-scope worker,
which was built from `IndexerConfig::default()`. Under raft that is now the only
worker that sweeps, so without this the flag governed nothing there — including
`0`, the documented off switch.

The new test is mutation-checked in both directions: forcing the gate off fails
`run_sweeps_behind_ledgers_without_an_event_bus`, forcing it on fails
`a_worker_that_does_not_own_catchup_never_sweeps`.
…hs too

The max-novelty nudge landed on three seams, described as "one per entry
family". Two families were missed, because they reach `at_max_novelty` through
`stage_flakes` rather than through `stage`:

- `stage_turtle_insert` — Turtle and TriG, reached from `TxBuilder` and so from
  every Turtle-shaped write the server accepts.
- `stage_commit_flakes` — commit replication in `commit_transfer`. A follower
  whose novelty is past `reindex_max_bytes` rejects every incoming commit and
  never asks for the build that would drain it.

Missing a seam is not a correctness bug: the catch-up sweeps still recover the
ledger. It costs that family the O(1) path and leaves it wedged for up to two
sweep intervals — which for the Turtle path is the whole point, since that is
how a bulk ingest wedges in the first place.

`stage_commit_flakes` flattened `TransactError` into `PushError::Invalid(String)`
before returning, which makes novelty backpressure indistinguishable from any
other staging failure. It now returns the typed error and the mapping moves to
`push_error_for_stage` at the call site, where the variant is still visible.

The doc on `request_index_after_novelty_rejection` now names all four
`at_max_novelty` checks in fluree-db-transact and the five api-layer families
they surface through, so the next seam added has something to check against.

`reindex_max_bytes: 0` makes the gate fire on any ledger, which pins the Turtle
seam without accumulating real novelty; the worker is built for its handle and
never spawned, so nothing drains the queue underneath the assertion. Removing
the nudge fails the test.
…l sort

Three review items on the sweep machinery.

**Subscribe before sweeping.** The catch-up sweep and `bus.subscribe()` used to
be sequential statements in one task, which is what made the old comment
("subscribe before the catch-up sweep so events arriving during the sweep are
buffered, not lost") true. Moving the sweep into `run` made them separate tasks
and left the `subscribe()` inside the subscriber, so a commit published between
the sweep's `all_records()` and the subscriber's first poll could reach neither.
`run` now subscribes synchronously and hands the `Subscription` to the task, so
the broadcast buffers from before the sweep starts whatever order the tasks are
polled in. This also makes `subscriber_translates_commit_published_into_trigger`
deterministic — it was yielding five times hoping the subscribe had landed.

**`stalled_ledgers` sort.** The comparator called `records.iter().find()` per
comparison, making the sort O(S log S * R). The gap is now carried through the
sort alongside the id.

**The `reindex_min_bytes` bypass is documented.** Neither sweep can honour the
soft threshold: `NsRecord` carries no novelty byte count, so "behind" is the
only predicate available and a ledger the operator deliberately left unindexed
is built anyway once a sweep reaches it. The post-commit trigger does gate on
`should_reindex`, so the sweeps are the one path that bypasses that batching —
an index build per behind ledger on every process start, plus one per ledger
that goes idle while behind. Builds are serialized per worker, so the cost is
throughput rather than a stampede, but on a deployment with many small idle
ledgers it is worth knowing about before turning the interval down. Said in the
`--indexer-catchup-interval-secs` help text and on `IndexerConfig`, and the
start-up sweep now logs the count it queued so the scale is visible rather than
inferred from disk traffic.
The comments added with the sweep-ownership gate said followers must not build
because an index publish "proposes to the state machine". It does not get that
far. `RaftNameService::publish_index` calls `client_write`, which on a
non-leader returns `ForwardToLeader` — openraft does not auto-forward — and the
arm handling it returns `Ok(())`.

So a follower's build is not a dangerous write, it is a silent no-op: full cost
paid (CPU, memory, index leaves and branches and root written to shared CAS),
success reported to the indexer, no index head advanced, artifacts orphaned
until GC. That is a stronger reason for the gate than the one the comments gave,
and it is the accurate one.

The swallow itself is correct for the case it documents — a stepped-down
leader's straggling publish, where the new leader builds again. It is only wrong
as a steady state, which is what an always-sweeping follower would make it.

Comments only; no behaviour change.
@bplatz bplatz added bug Something isn't working as expected area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches labels Sep 3, 2026
@bplatz

bplatz commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Thanks for a really well-argued diagnosis here — the deadlock analysis holds up, and the shape of the fix (start-up sweep, stalled-timer re-sweep, rejected-write nudge, with trigger_if_idle's decline table) is right. I've pushed four commits addressing @aaj3f's review rather than sending it back, so this is ready to merge once CI is green.

Merged main in first — the only conflict was mechanical (stage_with_config_shacl gained a 6th @context argument).

The two blockers

Raft double-sweep and follower sweeping. The review was right that "behaviour-neutral under raft" only accounted for the leader-scope worker. Every node also builds a node-scope worker through build_direct_fluree, and making run() sweep unconditionally turned that previously-passive worker into an active sweeper on every node.

Fixed with IndexerConfig::catchup_sweeps_enabled, surfaced as FlureeBuilder::without_indexer_catchup_sweeps() and applied in build_direct_fluree through an explicit CatchupSweeps::{Owned,Delegated} enum, so the raft path states its intent rather than inferring it from nameservice.is_some(). It skips both sweeps and nothing else — post-commit triggers, trigger_if_idle, admin reindex, cancel and maintenance holds all route through IndexerHandle and keep working.

I deliberately did not take the review's option (a), "don't enable the node-scope worker under raft". That leaves IndexingMode::Disabled, which also makes admin::trigger_index and admin::reindex answer ApiError::IndexingDisabled, drops the cancel + wait_for_idle quiesce that ledger drop and branch purge depend on, and silently no-ops this PR's own max-novelty nudge. It would turn off manual reindex on every raft node to fix an automatic-sweep problem.

While confirming the follower half I found something worth knowing, which is pre-existing and not caused by this PR: RaftNameService::publish_index swallows the ForwardToLeader that client_write returns on a non-leader as Ok(()). A follower's build therefore pays its full cost, is told it succeeded, and advances no index head. Filed as #1768 — it is the reason the gate is the right call rather than merely a tidiness one.

The flag never reached the sweeping worker. Also correct. --indexer-catchup-interval-secs was plumbed into the node-scope worker only, while the leader-scope worker came from IndexerConfig::default(). Now that catch-up under raft belongs exclusively to the leader-scope worker, that was the one config that had to reach it. Threaded. (The rest of IndexerConfig is still defaulted there — data_dir, run_budget_bytes, the GC knobs, the fulltext/attachment/warm-cache providers — which is pre-existing; noted in a comment at the site rather than expanded into this PR.)

The smaller review items

  • stalled_ledgers comparator — agreed, folded in now rather than tracked. The gap is carried through the sort instead of being recomputed by records.iter().find() per comparison.
  • reindex_min_bytes and the sweeps — this is real and I'd put it slightly more strongly than the review did: the start-up sweep is the unconditional one, and it now reaches every embedded and standalone deployment. NsRecord has no novelty byte count, so "behind" is the only predicate available, while the post-commit trigger does gate on should_reindex. So on every process start, every behind ledger is built regardless of the soft threshold — repeating on each rolling deploy. Builds are serialized per worker, so it's throughput rather than a stampede. Documented on the flag help text and on IndexerConfig, and the start-up sweep now logs the count it queued so the scale is visible rather than inferred from disk traffic.

Two more I found

  • The nudge missed two write families. at_max_novelty is also reached through stage_flakes, by stage_turtle_insert (Turtle/TriG, via TxBuilder) and stage_commit_flakes (commit replication). Not a correctness gap — the sweeps still recover — but those families lost the O(1) path, and for bulk Turtle ingest that's precisely how a ledger wedges. Both now nudge. stage_commit_flakes flattened TransactError into PushError::Invalid(String) before returning, which makes backpressure unrecognisable by variant, so the mapping moved to push_error_for_stage at the call site.
  • Subscribe/sweep ordering. Moving the sweep out of run_event_subscriber also moved it out from behind bus.subscribe(), which is what made "events arriving during the sweep are buffered, not lost" true. They were separate tasks with the subscribe() still inside the subscriber, so a commit published in between could reach neither. run now subscribes synchronously and hands the Subscription to the task. Side benefit: subscriber_translates_commit_published_into_trigger no longer yields five times hoping the subscribe landed.

Verification

cargo fmt --all --check clean. cargo clippy --all --all-targets clean under both default and --all-features. cargo check --workspace --all-targets on default features clean — the backstop that caught the earlier E0433.

Tests: fluree-db-indexer 396, fluree-db-api --lib 789, grp_index 89, grp_transact 190, grp_ledger 160, fluree-db-transact 294, fluree-db-server 13 suites. Zero failures.

Both new gates are mutation-checked in both directions: forcing the sweep gate off fails your run_sweeps_behind_ledgers_without_an_event_bus, forcing it on fails the new a_worker_that_does_not_own_catchup_never_sweeps, and removing the Turtle nudge fails its test.

Follow-up: #1768

`fluree-db-api` takes `fluree-db-indexer` as a
`cfg(not(target_arch = "wasm32"))` dependency, so on wasm the indexer is not
linked at all and `wasm_compat` supplies stand-in `IndexerHandle` /
`IndexerConfig` types. Every api-to-indexer call therefore needs a stub twin.

That seam did not exist when this branch was written. `wasm_compat.rs` landed on
main on 2026-08-25 and the `wasm32` CI job on 2026-08-26, both after this
branch's last commit, so its three new indexer touchpoints were never checked
against the wasm target. Merging main is what surfaced them:

    error[E0599]: no method named `trigger_if_idle` found for reference
                  `&wasm_compat::stubs::IndexerHandle`
    error[E0599]: no method named `with_catchup_interval` found for struct
                  `wasm_compat::stubs::IndexerConfig`
    error[E0599]: no method named `with_catchup_sweeps` found for struct
                  `wasm_compat::stubs::IndexerConfig`
    error[E0433]: cannot find module or crate `fluree_db_indexer`
                  --> fluree-db-api/src/server_defaults.rs

under `cargo clippy --target wasm32-unknown-unknown -p fluree-db-api
--no-default-features`.

The first three get stub methods alongside the existing `trigger` / `cancel_all`
/ `wait_all_idle`, and the config stub carries the two catch-up fields so
`FlureeBuilder`'s setters compile for both targets without a `cfg` at each call
site. The fourth is the same mistake one layer down from the one it was fixing:
`server_defaults` moved the constant off `fluree_db_indexer::` so the SERVER's
default-feature build would stop failing E0433, but naming the indexer from
`fluree-db-api` fails the wasm32 build for exactly the same reason. Routed
through `wasm_compat`, which is where `DEFAULT_MAX_OLD_INDEXES` already goes.

The stubs restate constants the indexer owns and nothing cross-compiles the two,
so `stub_drift` pins the real constants to the literals the stubs carry. It runs
on native and fails if an indexer default moves — the only signal that the wasm
stub needs updating too.

Verified natively (fmt, clippy, 790 lib tests). The wasm32 target itself is not
buildable on this machine: `zstd-sys` needs a clang with a WebAssembly backend
and `scripts/wasm-clang.sh` finds no Homebrew LLVM here, so it falls through to
Apple clang, which has none. That gate is checked by CI, not locally.
@bplatz

bplatz commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

One more push — 36e390092 — for a break the main merge exposed rather than anything in the review.

What broke

cargo clippy --target wasm32-unknown-unknown -p fluree-db-api --no-default-features failed with four errors:

error[E0599]: no method named `trigger_if_idle` found for reference
              `&wasm_compat::stubs::IndexerHandle`
error[E0599]: no method named `with_catchup_interval` found for struct
              `wasm_compat::stubs::IndexerConfig`
error[E0599]: no method named `with_catchup_sweeps` found for struct
              `wasm_compat::stubs::IndexerConfig`
error[E0433]: cannot find module or crate `fluree_db_indexer`
              --> fluree-db-api/src/server_defaults.rs

Nothing to do with wasm features. It is a dependency shape: fluree-db-api/Cargo.toml declares fluree-db-indexer under [target.'cfg(not(target_arch = "wasm32"))'.dependencies], so on wasm the indexer is not linked at all and wasm_compat supplies stand-in IndexerHandle / IndexerConfig types. Every api-to-indexer call needs a stub twin or the wasm32 build stops compiling.

Why it did not show up before

That seam did not exist when this branch was written. wasm_compat.rs landed on main on 2026-08-25 (#1714) and the wasm32 CI job on 2026-08-26 — both after this branch's last commit on 08-18. So the three new indexer touchpoints here were never checked against the wasm target, and CI on a54f59d3 passed because the job did not exist yet. Merging main is what made the gate apply.

Worth knowing for anything else in flight from around that date: the same trap is waiting for any PR that adds an api-to-indexer call and was branched before 08-25.

The fix

The three missing methods get stubs alongside the existing trigger / cancel_all / wait_all_idle, and the config stub carries the two catch-up fields so FlureeBuilder's setters compile for both targets without a cfg at each call site.

The E0433 is the same mistake one layer below the one it was fixing, which I thought was worth calling out rather than quietly patching. server_defaults took the constant off fluree_db_indexer:: so the server's default-feature build would stop failing E0433 — but naming the indexer from fluree-db-api fails the wasm32 build for exactly the same reason. Now routed through wasm_compat, which is where DEFAULT_MAX_OLD_INDEXES already goes.

That routing means the stubs restate constants the indexer owns, and nothing cross-compiles the two, so nothing would catch them drifting. Added stub_drift, a native test pinning the real constants to the literals the stubs carry — it fails if an indexer default moves, which is the only signal that the wasm stub needs updating too.

Verification

Native is green: fmt --check, clippy --all --all-targets under both default and --all-features, cargo check --workspace --all-targets on default features, and fluree-db-api --lib at 790.

The wasm32 target itself I could not build locally — zstd-sys needs a clang with a WebAssembly backend, and scripts/wasm-clang.sh finds no Homebrew LLVM on my machine so it falls through to Apple clang, which has none. I am installing LLVM now to confirm it locally, but as it stands that specific gate is CI-verified only, so please read it off the checks rather than off this comment.

The earlier comment covers the responses to @aaj3f's review items; this one is only the merge fallout.

@bplatz
bplatz merged commit 1aae890 into fluree:main Sep 3, 2026
16 checks passed
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 bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants