Skip to content

fix(peer): query peers serve reads while the transaction server commits - #2409

Merged
bplatz merged 22 commits into
mainfrom
fix/query-peers-shared-storage
Nov 18, 2026
Merged

bplatz merged 22 commits into
mainfrom
fix/query-peers-shared-storage

Conversation

@bplatz

@bplatz bplatz commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Query peers broke as soon as the transaction server committed during read load. Shared-storage peers returned HTTP 500 ("load cancelled") within a minute. Proxy-storage peers synced cleanly but answered every non-JSON Accept with 406. This makes both modes serve reads while writes flow, and fixes a data-integrity bug that shipped in v4.2.7.

What was wrong

A shared-storage peer wrote to the transaction server's own nameservice.

  • The peer opened the root read-write and copied each SSE record into its "local" nameservice, which is the transaction server's file.
  • The transaction server writes that file before it sends the event, so the copy conflicted on nearly every commit. The conflict path evicted the peer's cached ledger each time: a cold reload per commit, plus a 500 for every query waiting on a load.
  • When the peer was one event behind, it took the newer file for a divergence and reset it to the event's record (since 6e799d3, part of fix: a rebased branch reads its new line, and builds never extend an index of a replaced line #2296, in v4.2.7). That moved the transaction server's head and index back on disk. Its next publish then lost the compare-and-set and re-staged onto the rewound head, so commits it had already acknowledged dropped off the head and their t was handed out again. No restart is needed: under sustained writes the history forks while the transaction server runs. The fix is on the peer, so a fixed transaction server beside a v4.2.7 shared-storage peer loses commits the same way. Upgrade (or stop) every shared-storage peer before, or together with, the transaction server; the query-peers docs now say so.
  • The peer also took the root's WAL, swept its staging files, and ran a background indexer when indexing was enabled.

A proxy-storage peer took a JSON-only path through the query routes. It answered SPARQL results XML, CSV, TSV, Turtle, RDF/XML and N-Triples with 406, and /info returned only the nameservice record.

Changes

  • Shared-storage peers only read (FlureeBuilder::read_only): a read-only nameservice, no WAL and no WAL replay at startup or on a missing file (FileStorage::without_wal_replay), no staging sweep, no indexer.
  • One event path for both peer modes. PeerSyncTask is removed. Records are applied with LedgerManager::follow:
    • A record that moves the cached head forward, or names the cached head and index, is applied in place: commits added, index installed. The ledger is never evicted.
    • Any other record is judged against the nameservice's current record. That covers a head below or beside the cached one, or another index under it (one a reset took away, or read while reset_head was half-written). A record the cache has passed changes nothing. A reset (a rebase moving the head back or lowering the index, Shared-storage query peers never lower a branch's index after a rebase #2381) reloads, and the cached state keeps serving until the reload lands.
    • A record for a ledger that is still loading is followed once the load lands.
  • Index installs check the ledger's history. Each ledger handle carries a generation that a reload bumps whenever it swaps in a freshly loaded state (it may be another line). An index install records it before reading the record it plans from and skips the install if it changed. This covers follow, refresh and post-load reconciliation alike. Commits don't bump it, so a writer's index installs are unaffected.
  • Per-ledger workers on the peer. Each ledger's updates are applied in order by a worker of its own, at most eight at once, so a ledger waiting on slow storage holds up no other. Records that arrive while a worker is busy collapse to the latest. Retractions go through the same worker. Watermarks and retractions carry the connection epoch they arrived in, so nothing from before a reconnect applies after it.
  • Proxy peers take the shared query routes: every format, min_t waits, and full /info metadata.
  • /info's top-level t is the head's. Every server reported the index's t there (0 with no index), which fluree pull and sync compare with the local head.
  • The CLI and server binaries shut their runtime down with a 10 s bound, so a stuck blocking task cannot keep a peer alive after SIGTERM.

Behavior changes

  • A shared-storage peer no longer writes anything under the shared root, and runs no indexer whatever --indexing-enabled says.
  • Every peer forwards the nameservice sync endpoints (ref push, ledger init, snapshot) to the transaction server, as it does transactions. A shared-storage peer used to serve them by writing the transaction server's nameservice from its own process, and a proxy peer returned 404.
  • A shared-storage peer no longer emits nameservice events on its in-process event bus: its cache follows the transaction server's stream directly. /events is unchanged; it has returned 404 on every peer since v4.
  • /info's top-level t is the head's t on every server, where it was the index's (0 with no index). fluree pull, sync and clone now see a remote's unindexed commits; a client that read it as the indexed t sees it change.
  • Breaking for clients of a proxy peer's /info: a peer in either mode returns the same /info form as a transaction server: full metadata with commitId, indexId and stats. The proxy-only form, documented in v4.2.7 as ledger_id, t, commit_head_id and index_head_id, is gone: read commitId and indexId instead. The CLI already read commitId first.
  • The proxy-mode refusals in commit show and SHACL validate were unreachable, because every peer forwards both to the transaction server. They are removed, along with the 501 the docs listed for them.

Tests

Each new test fails with its fix removed.

  • it_rebase::a_peer_* / a_rebase_outlasts_*:
    • a record the peer has passed, however far behind, changes nothing;
    • a rebase that moves the head back, or to another head at the cached t, reloads onto the new line;
    • a reset that lowers the index reloads and drops it, while a record merely claiming a lower index does not;
    • a late record naming the peer's head with an index a reset took away does not install it;
    • a rebase sent while the branch loads is followed once the load lands;
    • an index install started by follow or refresh, or planned from a record read before a rebase, does not land after the rebase.
  • peer::subscription::tests:
    • a passed record neither writes nor evicts;
    • a new commit is applied in place;
    • a ledger stuck on storage holds up no other;
    • records behind a busy worker collapse to the latest;
    • a retraction follows the update in flight;
    • a record or retraction from before a reconnect does not apply after it.
  • peer::state::tests::a_record_that_lowers_the_index_replaces_the_watermark.
  • it_wal::a_read_only_client_leaves_the_writers_log_to_the_writer and storage::file::wal_tests::a_handle_without_replay_leaves_a_stopped_owners_tail.
  • proxy_integration::test_proxy_peer_negotiates_every_query_format: nine format and query-form combinations, byte-identical to the transaction server.
  • proxy_integration::test_proxy_peer_reports_full_ledger_info: an index-lagging ledger and an unindexed one; the top-level t is the head's.

Not in this PR

  • /info is uncached on every server. The API-level ledger-info cache keys on t, not on the commit head, so a rebase that keeps t would serve stale info.
  • On the transaction server, /info's nameservice block is the record its cached ledger last loaded or indexed from; its own commits do not refresh it.
  • Retractions that happen while a peer is disconnected are not reconciled when it reconnects.

…and writes nothing

A shared-storage peer opened the transaction server's root as a writer and
copied each event's record into the nameservice there, which is the
transaction server's own. The transaction server writes that record before
it sends the event, so the copy conflicted on nearly every commit, and the
peer evicted its cached ledger each time: a cold reload per commit, and
every query waiting on a load failed with "load cancelled". When the peer
was a commit behind the stream it took the newer record on disk for a
divergence and reset the record to the event's, moving the transaction
server's head and index back until its next commit. The peer also took the
root's WAL, swept its staging files, and ran an indexer when indexing was
enabled.

A shared-storage peer now opens the root read-only (`FlureeBuilder::read_only`):
a read-only nameservice, no WAL, no sweep, no indexer. Both storage access
modes apply events through one task, `LedgerManager::follow`, which brings
the cached ledger up to the record in place. A record the cache has passed
on its own line changes nothing. One that replaces the cached line reloads
the ledger while the cached state keeps serving: another head at the cached
t, a head below it off the cached line, or a lower or absent index under the
cached head. Each is what a rebase can publish, so the peer still follows
it. A reload that follows a rebase installs the record's head even below the
cached t. The peer's watermark follows the record down as well, and is set
after the cached ledger is updated, so a query does not race it into a
reload.
The query routes sent a proxy-storage peer down a path of its own that
rendered only JSON, and answered every other `Accept` (SPARQL results XML,
CSV, TSV, Turtle, RDF/XML, N-Triples) with 406. The path predates proxy
peers reading raw index bytes and running queries locally, which they now
do. The peer now takes the route every other server takes: the cached
ledger, checked against the peer's watermark, and the shared format
negotiation. A `min_t` wait on a proxy peer refreshes and retries as on a
shared-storage peer instead of failing at once, and explain and the
ledger-scoped SPARQL and stream routes read the cached ledger rather than
loading it per request.
Both binaries let the Tokio runtime drop at the end of `main`, and a
runtime's drop waits on its blocking tasks without limit. A query peer that
had drained on SIGTERM stayed alive with two threads parked, one of them
presumably a blocking storage task that never returned, until it was
killed. The runtime now shuts down with a 10 s bound on those tasks.
`/info` on a proxy-storage peer answered with the nameservice record alone
(id, t, and the two heads under `commit_head_id` / `index_head_id`), on the
premise that such a peer has no local ledger state. It loads the ledger
like any other server, so it now returns the full metadata, the same as the
transaction server's: stats, commit, `commitId` and `indexId`. The CLI
already read `commitId` first; `fluree sync`, which reads only `commitId`,
now finds the head on a proxy peer.

The proxy-mode refusals in commit show and SHACL validate never ran: every
peer forwards both to the transaction server first. They are removed, with
the 501 the docs listed for them.
…er never replays the WAL

`LedgerManager::follow` dropped a record for a ledger still loading. A load
that read the nameservice before a rebase then served the replaced line
until the next event, which on an idle branch may never come. The record is
now followed once the load lands.

A record more than five commits behind the cache was taken as a reset,
without walking that far, and reloaded the ledger twice, since the reload
left the cache ahead of the record again. A peer draining a backlog rebuilt
its state for every stale record. A record that neither moves the cached
head forward nor names it is now judged by the nameservice's current
record, which moves back only on a reset: one read, and no commit walk. A
record the cache has passed changes nothing however far behind it is, and a
record claiming a lower index the nameservice does not hold is no reset.

A `read_only` file client still recovered the writer's WAL at startup,
writing the files it held. `FileStorage::without_wal_replay` keeps a handle
from applying any log, at recovery or on a missing file; a `read_only`
client uses it and leaves recovery to the writer.
The top-level `t` of a ledger's info came from the cached state's
snapshot, which is the indexed t. A ledger with commits past its index, or
with none at all, reported the index's t (0 with no index) while the
nested ledger and commit metadata reported the head's. `fluree pull` and
`sync` compare this `t` with the local head and could find a remote with
newer commits up to date. The transaction server and shared-storage peers
had always reported it so; proxy-storage peers reported the record's commit
t until they took the shared route. `t` is now the head's.
…of its own

`LedgerManager::follow` spawned a task for each record that arrived while
its ledger loaded. Those tasks ran beside later records, so an index update
read before a rebase could install the replaced line's index after the
rebase was followed. They also repeated each other's commit and index
reads. Follows of one ledger now take a per-ledger lock, and a record for a
ledger still loading waits for the load rather than spawning a task.

The peer's event task applied each record before reading the next event,
so one ledger waiting on slow storage held up every other ledger, and a
backlog of records for one ledger was applied record by record. Each
ledger now has a worker of its own, at most eight at once. A record that
arrives while its ledger's worker is busy replaces any still waiting, and
the stream reads on.
The per-ledger lock on `follow` kept two follows apart, but the other paths
that bring a cached ledger up to date (post-load reconciliation, `refresh`)
install indexes too. One that read an index of the old line before a rebase
and installed it after the rebase was followed put the peer back on the old
line. A ledger handle now counts its lines: a reload that swaps in a state
it loaded bumps the count, under the state lock, and an index install
checks it there against the count it planned on. Commits leave the count
alone, so a writer's own index installs are unaffected. The lock, whose map
kept an entry for every ledger ever followed, is gone; the peer's worker
per ledger keeps its follows in order.

A retraction removed the ledger's watermark while an update to it was
still in flight, and that update then set it again. A retraction is now
queued to the ledger's worker behind that update. A record received before
a reconnect sets no watermark after the reconnect cleared them: each
carries the connection epoch it arrived in, which the watermark update
checks under the same lock the clear takes.
The line an index install is checked against was taken after `notify` read
the nameservice record, and `refresh` reads the record before calling
`notify` at all. A refresh that read the old record before a rebase, and
planned after the rebase was followed, took the new line and installed the
old line's index. `notify` now takes the line before it reads the record,
and `refresh` and `follow` take it before theirs. Lines come from one
counter across handles, so a line taken from a handle since evicted
matches no other, and a ledger not cached when its line is taken matches
none.

A retraction queued before a reconnect evicted the ledger after it, and
with it a load of the ledger begun since. A retraction now carries the
connection epoch it arrived in and is applied only in that connection,
with the watermarks held across the check and the eviction so a reconnect
cannot come between them.
@bplatz bplatz added the bug Something isn't working as expected label Nov 15, 2026
…cord

`follow` applied any record naming the cached head with a higher index as
an index update. A record sent before a reset that lowered the branch's
index, arriving after the peer had loaded the reset state, installed the
index the reset took away, until the next record. So did a record read
while a reset was half-written: `reset_head` writes the head and the index
separately. A record naming the cached head now goes straight to `notify`
only with the cached index; one with another index is judged by the
nameservice's current record, one read per index update. The cached index
is the one installed (`head_index_id`), which an install updates and the
loaded record does not.

@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 the right fix, and the design I'd have picked: a reader that structurally can't write, one in-place follow for both peer modes, and a line check on index installs. It's worse than the body says, though. Claude's box runs at the merge base lost 365 of 386 acknowledged inserts with no crash involved (0 of 400 here), and a fixed tx server next to an old peer still lost 358 of 378, so the upgrade order belongs in the docs.

A few decisions I'd like on the record are below.

These commits don't need anything under them (they cherry-pick cleanly onto main and the peer tests pass there), so my recommendation is to retarget this to main and land it before #2421 tags v4.2.8, with a release-notes line telling users to upgrade every shared-storage query peer along with the transaction server (the fix is peer-side). @bplatz, release scope is your call, and I'll defer to whatever you decide.

Full review below:


✅ Approving to unblock: please get the upgrade-order note in before merging. This is carefully built. Claude mutated each mechanism the tests claim to pin (the line check, the line bump, the cached-index check, following a loading ledger, the reset rule, collapse-to-latest, both epoch checks, retraction ordering, the watermark rule, per-ledger concurrency), and every one went red except one wiring line noted inline. The one must is a docs sentence, because the fix lives entirely on the peer.

Before merging:

  1. docs/operations/query-peers.md:75: say a v4.2.7 shared-storage peer rewinds the transaction server's head; upgrade or stop peers first.

Decisions on the record:

  • My reading is that this moves /info's top-level t from the index's t to the head's on every server. That means fluree pull, sync and clone now see a remote's unindexed commits; today an unindexed ledger can report t = 0, which clone refuses as empty. I think that makes sense, since the docs already call it the current transaction time, but I'd like your confirmation that it's the intended decision: a client that read it as the indexed t will see it change.
  • My reading is that a shared-storage peer no longer has any write or relay surface: ref-push returns 404 there, it stops relaying /events, and it runs no indexer whatever --indexing-enabled says. I think that makes sense, and the ref-push one closes a path that wrote the transaction server's own nameservice through the peer, but I'd like your confirmation it's intended, since anything subscribed to a shared-storage peer's /events (a chained peer, a browser client pointed at a peer) stops getting events.
  • My reading is that /info on a proxy peer now returns the same full metadata as every other server (commitId, indexId, stats) instead of commit_head_id and index_head_id, and that the 501s for commit show and validate go away. I think that makes sense, since the CLI already reads commitId, but I'd like your confirmation, because a client reading the snake_case fields from a proxy peer breaks. Worth a Breaking-changes line.
  • My reading is that both binaries now exit within 10 s of the server returning instead of waiting on blocking tasks without limit. A SIGTERM'd process always exits, and a blocking task still running then (a stuck storage call, an index build on the blocking pool) is abandoned the way a crash would abandon it. I think that makes sense, since writes are acknowledged only once durable, but I'd like your confirmation that it's the intended bound, for the transaction server as well as peers.

Notes:

  • The defect class. The class here is "a follower writing through a handle that resolves to the leader's storage in one deployment mode". Its instances are this root cause (the ns copy and reset, the indexer, WAL attach and staging sweep), the ref-push endpoints and the retraction handler both writing the transaction server's nameservice through a shared-storage peer, and 6e799d35c turning that into a rewind. read_only is the structural fix, and its one gap (build()) is inline. Separately, the line generation is the structural direction the #2296 review named for "a pointer derived from a line, trusted after a rewrite moved the line", here for cache installs. The writer's own rebase is the one site still outside it (inline).
  • #2423 and the browser peer. The browser peer (fluree-db-browser/src/heads.rs, whose refresh #2423 rewrites) is built the same way as a proxy peer, but it still applies head events with LedgerManager::notify. After this lands, it's the one head-stream consumer on the old rules. It keeps serving a replaced line after a rebase that moves a head back, and it drops a record that arrives mid-load. It could call follow. No textual conflict between the two (merge-tree is clean).
  • #2413 stacks on this branch and will need a rebase if this one retargets.
  • The writer re-stages onto a rewound head. That is what turns any nameservice rewind into silent loss of acknowledged commits, whatever did the rewinding (an old peer mid-upgrade, a restored ns file, a misconfigured second process). This is more of a question than a suggestion, and it's outside this diff (tx_builder.rs). A writer whose publish loses to an ancestor of a commit it acknowledged could refuse loudly instead of retrying onto it. Another writer's rebase lands on another line, not an ancestor, so the two are distinguishable.
  • fwiw, the force-follow suggestion that became 6e799d35c came from my review on #2296. That comment called the peer's nameservice "local", and on shared storage it's the transaction server's own file. That one's on me.
Adherence: Patterns ✔ · Performance ✔ · Deployment targets ⚠️ · Testing ✔ (one gap) · Conventions ⚠️ · verification
  • Patterns/abstractions: ✔ It removes PeerSyncTask rather than patching it. Both peer modes share one route set and one LedgerManager::follow, and the reader role is a NameServiceMode::ReadOnly with no write surface. ⚠️ for the read_only() flag on build() and build_async() (inline).
  • Performance (speed first, memory second): ✔ No query-engine hot path is touched. The new work is an atomic load and compare per index install under a lock already held, and one nameservice read per stale record or index event on peers, never per query. Shared-storage peers stop cold-reloading on every commit, and proxy peers query the cached ledger instead of loading per request. A cold /info on a proxy peer now loads the ledger (warm after). No performance-degradation risk.
  • Deployment targets: ⚠️ The fluree-db-api pieces (follow, the line, read_only, without_wal_replay) reach every host. The line is an in-process atomic guarding an in-process cache, so no fence is crossed, and gate-stack's wasm32 clippy and runtime-smoke jobs are green at this head. The evidence is server-shaped. An embedder building a reader with build() gets a writer (inline), and the wasm browser peer doesn't use follow (Notes).
  • Testing: ✔ The tests run and catch what they claim, with one wiring gap (it_wal.rs:507, inline). There's still no two-process test with a writer and a shared-storage peer under concurrent writes. Claude's reproduction does it in about 5 seconds.
  • Conventions: ⚠️ Thorough multi-line commits, docs updated for /info and the peer modes, gate-stack's fmt and clippy green. The upgrade order is missing from the docs (Before merging).

Verified at d577e4aa1, on a c7i.4xlarge box (all green unless noted):

  • Reproduction: a transaction server and a shared-storage peer on one root, 400 inserts with 4 peer readers.

    Run Acknowledged inserts lost after restart
    merge base 365 of 386
    v4.2.7 371 of 399
    no-peer control 0 of 400
    this head 0 of 400
    head tx + base peer 358 of 378
    base tx + head peer 0 of 400
  • strace: the peer's write syscalls under the root were 2,702 at the merge base and 0 here.

  • /info t on an unindexed 3-commit ledger: 0 at the merge base, 3 here.

  • Targeted tests: it_rebase 34, it_wal 5, core wal_tests 28, ledger_manager 34, server peer:: 24, grp_proxy 58, grp_http integration:: 91.

  • Mutations: 12 mutations of the new tests' fixes. 11 went red; the without_wal_replay wiring stayed green.

  • Probes: the writer's rebase keeps the line; read_only().build() is a writer.

  • Main: the commits cherry-pick onto main 88c3cf134 with no conflicts.

  • Gates: gate-stack ran CI's jobs at this head. fmt, clippy, wasm32 and sparql are green. nextest ran 16,218 tests: 16,214 passed, and 4 aws_testcontainers localstack tests timed out, in a crate this PR doesn't touch; a quiet rerun of that suite passes 9 of 9, so the timeouts were the box.

Approving so you can merge once the docs line is in, but maybe worth considering the inline items first.

- **Shared storage** (`--storage-access-mode shared`, default)
- The peer reads the same storage backend as the transaction server (shared filesystem, shared bucket credentials, etc.).
- Requires `--storage-path`.
- The peer only reads: the nameservice, write-ahead log, staging files and indexes on that storage are the transaction server's. A peer runs no indexer, whatever `--indexing-enabled` says.

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 (docs, small): the upgrade order needs to be written down here. The fix is entirely on the peer side, so a transaction server running this code next to an un-upgraded v4.2.7 shared-storage peer still loses acknowledged writes.

Mechanism: the old peer still resets the transaction server's nameservice record to whatever event it's handling. The transaction server's next publish then loses its compare-and-set, and its retry re-stages onto the rewound head (tx_builder.rs:2502-2527, "commit conflict under matching snapshot; reconciling and retrying"). Commits it has already acknowledged drop off the head, and it hands out their t again.

Scenario (Claude ran this on a box): a transaction server and a shared-storage peer on one root, with 400 inserts in bursts of 20.

  • Transaction server at this head, peer at the merge base: 358 of 378 acknowledged inserts were missing after a clean restart.
  • The reverse pairing (merge-base transaction server, peer at this head): 0 of 400.
  • Both at the merge base: 365 of 386. Both at the v4.2.7 tag: 371 of 399.

That's also worth correcting in the body, which says a restart is needed. It isn't: the transaction server forks its own history live under sustained writes. The usual upgrade order (transaction server first, then peers) is exactly the losing one.

Suggested wording, here or in an "Upgrading" note on this page:

  - **Upgrading from v4.2.7:** a v4.2.7 shared-storage peer writes the transaction server's nameservice record and can move its head back, losing acknowledged commits. Upgrade (or stop) every shared-storage peer before, or together with, the transaction server.

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 31b00f1 (and the PR body now says no restart is needed).

Comment thread fluree-db-api/src/lib.rs
/// opened without its WAL: the client never applies a log the writer
/// left, at startup or on a missing file, and does not sweep its staging
/// files. Those are the writer's to recover and clean up.
pub fn read_only(mut self) -> Self {

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.

read_only() only takes effect through build_client. build() and build_async() (lib.rs:2729-2744) never read the flag. They sweep staging files, replay the WAL, build a ReadWrite NotifyingNameService and start the background indexer, exactly as without it.

Claude checked it on a box: FlureeBuilder::file(p).read_only().build() returns a client whose nameservice is not read-only and has a publisher, and so does build_async(). build_client() comes back read-only.

The server goes through build_client (state.rs:546), so the peer shipped here is fine. But an embedder writing a reader process would most naturally reach for build(). That embedder gets a writer on another process's root with no error, which is the failure this PR is fixing.

We already handle the indexing-config version of this with warn_if_discarding_indexer_config (lib.rs:2820-2842). For read_only I think a refusal is the right strength:

// in open_file_storage(), or at the top of build()/build_async()
if self.read_only {
    return Err(ApiError::config(
        "read_only() is honored by build_client(); build() opens the root as its writer",
    ));
}

The other option is honoring it there the way build_client_file does. This is minor, 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 f45341a — refused in build()/build_async(), and in the IPFS and S3 builds, which ignored it the same way; build_memory and build_with, which can't fail, warn.

/// nameservice, which may be another line than the one it replaces (a
/// rebase). An index install planned before the swap is not made after
/// it; commits on the line leave it alone.
line: AtomicU64,

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.

The writer's own rebase installs another line without changing line. This field's doc says the line exists for a swap to "another line than the one it replaces (a rebase)". It is only bumped where a reload swaps state (:2245), though. apply_rebase installs the rebased (or source's) state through finalize_commit (fluree-db-api/src/rebase.rs:718-722), under the same state write lock an index install waits on (lock_for_write, :708-717), and leaves the line unchanged.

Scenario: on the writer itself, an index install for the branch's old line gets planned before a rebase starts. That can come from the local cache listener's notify after its own indexer publishes, or from refresh. The install loads outside the lock, waits on the lock the rebase holds, and then lands on the rebased state.

Claude probed it on a box:

  • On the writer's cached rb:dev: take the line, rebase with Skip, then make the install planned before the rebase. apply_index_v2 returns Ok(true) and the writer's cache reads ["alice", "alice-dev0", "alice-dev1"], the replaced line, instead of ["alice", "alice-main", "dave"].
  • The same install on a peer whose follow reloaded across the rebase returns Ok(false).

Your code didn't introduce the race (there was no fence before this PR at all). But the fence is right here and it's a one-line bump: start a new line wherever apply_rebase installs on a non-fast-forward or became_source rebase. A writer-side variant of a_rebase_outlasts_an_index_install_in_flight would pin it. Commenting here because rebase.rs is not in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 647f36d

evict: impl std::future::Future<Output = ()>,
) -> bool {
let mut ledgers = self.ledgers.write().await;
if self.epoch() != epoch {

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.

A retraction received before a reconnect is now dropped, and the dropped ledger stays served. At the merge base a retraction was applied inline, before the stream read its next event. Now it is queued behind the ledger's worker. If a reconnect bumps the epoch first, this check discards it.

The new connection's records can't say the ledger is gone; the body's "Not in this PR" notes that a reconnect doesn't reconcile retractions. So the peer keeps the dropped ledger cached and queryable.

The window is narrow: a retraction lands while that ledger's worker is busy, and the connection drops before the worker gets to it. But it's the one retraction case the old code always handled.

I think one lookup closes it without giving up the "a load begun since is not evicted" property you wanted for a re-created ledger:

LedgerUpdate::Retracted { epoch } => {
    let evict = fluree.disconnect_ledger(&ledger_id);
    if peer_state.retract_ledger_in(epoch, &ledger_id, evict).await {
        tracing::info!(ledger_id = %ledger_id, "Ledger retracted from remote");
    } else if matches!(
        fluree.nameservice().lookup(ledger_id.as_str()).await,
        Ok(None) | Ok(Some(fluree_db_nameservice::NsRecord { retracted: true, .. }))
    ) {
        // From an earlier connection: the new one's records can't say the
        // ledger is gone, so the nameservice does.
        fluree.disconnect_ledger(&ledger_id).await;
    }
    continue;
}

This is minor and non-blocking, but if you agree it's right, I'd rather see it folded in now.

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 1e6e00f

/// A `read_only` client reads a root another process writes: it applies none
/// of the writer's log, which stays for the writer to recover.
#[tokio::test(flavor = "multi_thread")]
async fn a_read_only_client_leaves_the_writers_log_to_the_writer() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This test passes with the line it's named for removed. Claude mutated it on a box: with file_storage = file_storage.without_wal_replay(); deleted from build_client_file (lib.rs:3612), a_read_only_client_leaves_the_writers_log_to_the_writer still passes.

The reason is that the read_only branch already skips startup recovery. without_wal_replay matters for the on-miss path, and only when the root has owned logs (file.rs:1372-1378), which this test's probe() writer doesn't create.

A variant with an owned writer, reading the missing file through the reader, does go red under that mutation. The read succeeds and the file reappears. At this head it's green:

let previous = FileStorage::new(dir.path())
    .with_durability(Durability::Wal)
    .with_wal_owner("node-1");
previous.recover_wal().expect("attach");
// … write, sync, simulate_crash_for_test, remove the file, build the read_only client, then:
let read = reader.admin_storage().expect("file storage").read_bytes("fluree:file://payload").await;
assert!(read.is_err(), "the reader applied the writer's log on a miss");
assert!(!dir.path().join("payload").exists(), "the reader wrote the writer's file");

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 bd8fecb


/// A shared-storage peer opens the root as a reader.
#[tokio::test(flavor = "multi_thread")]
async fn the_peer_cannot_write_the_nameservice() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This pins the type, but the claim is about the filesystem. the_peer_cannot_write_the_nameservice checks there's no publisher, which covers the nameservice. The PR's claim, though, is "writes nothing under the shared root", and the bug came in through writes the types allowed: the indexer, WAL attach and staging sweep, as well as the nameservice. Under strace, the merge-base peer made 2,702 write-mode syscalls under the root in one run, and this head made 0.

A cheap regression guard is to snapshot the root's file list and mtimes before and after SharedRoot's peer builds and applies a few events (a_new_commit_is_applied_to_the_cached_ledger already drives that), then assert the peer changed nothing. The writer's own commits have to go in before the snapshot. If you agree it's right, I'd rather see it here 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 cb50f79

Base automatically changed from perf/leaflet-cache-contention to main November 18, 2026 16:56
The fix is on the peer side. A v4.2.7 shared-storage peer still writes
the transaction server's nameservice record and can move its head back;
the transaction server's next publish then loses its compare-and-set
and re-stages onto the rewound head, dropping commits it already
acknowledged. A fixed transaction server beside an old peer loses them
just the same, so the usual order, transaction server first, is the
one that loses.

The query-peers page now says to upgrade (or stop) every shared-storage
peer before, or together with, the transaction server.
With `main` merged in, `fluree-db-api` no longer compiled with all
features: computing the layout of a cross-ledger policy query's future
overflowed rustc's query depth limit. The chain runs from the query
through `ledger_cached` and `get_or_load`, which now reaches `notify`,
into `apply_index_v2` and its novelty prefetch, whose iterator adapter
type alone is a dozen levels deep.

`notify` now boxes its two `apply_index_v2` calls. An index install
loads the index anyway, so the allocation costs nothing that matters,
and the hot `get_or_load` path stays unboxed.
…ts writer

`read_only()` took effect only through `build_client`. `build()` and
`build_async()` ignored it: they swept staging files, replayed the WAL,
built a read-write nameservice and started the background indexer, so
an embedder building a reader that way got a writer on another
process's root with no error, the failure the flag exists to prevent.
The IPFS and S3 builds ignored it the same way.

Those builds now refuse it with a config error that points at
`build_client`. `build_memory` and `build_with`, which cannot fail,
log a warning instead, as they do for an ignored indexing config:
memory storage has no other writer, and `build_with` takes the
nameservice mode from the caller.
The ledger handle's line fences index installs: one planned on a line
is not made once a reload has swapped in another. Only a reload bumped
it, though. The writer's own rebase installs the rebased (or source's)
state through `finalize_commit`, under the same write lock an index
install waits on, and left the line as it was. An install planned on
the branch's old line before the rebase, from the writer's own index
publish or from a refresh, then waited out the rebase and landed on
the rebased state, putting the cache back on the replaced commits.

`apply_rebase` now starts a new line before it installs. A writer-side
test plans an install on the old line, rebases, and checks the install
is refused and the cache keeps the rebased commits.
A retraction is queued behind its ledger's worker and carries the
connection epoch it arrived in. One still waiting when the peer
reconnects was discarded, so the new connection's records say whether
the ledger exists. They cannot say a ledger is gone, though, so a
ledger the transaction server dropped stayed cached and queryable on
the peer. Before the per-ledger workers, a retraction was applied
inline and never lost this way.

A retraction from an earlier connection now asks the nameservice: when
it has no such ledger, or has it retracted, the peer evicts it. A
ledger the nameservice still has, re-created since or loading, stays.
A test queues a retraction from before a reconnect for a ledger the
writer dropped and checks it is evicted.
`a_read_only_client_leaves_the_writers_log_to_the_writer` passed with
`without_wal_replay` removed from the read-only file client: the
read-only build already skips startup recovery, and the on-miss path
that `without_wal_replay` closes only applies a log the root owns,
which that test's writer did not create.

A second test writes through an owned log, crashes, removes the file,
and reads it through the read-only client: the read fails and the file
is not written back. With `without_wal_replay` removed, the reader
applies the log and the test fails.
`the_peer_cannot_write_the_nameservice` checks the peer has no
nameservice publisher, but the claim is about the filesystem: the
defect came in through writes the types allowed, the indexer, the WAL
attach and the staging sweep as well as the nameservice.

A new test snapshots every file under the root, with its length and
modification time, around the peer's own work: opening the root and
loading a ledger, then applying a new commit to the cached ledger. The
writer's commits go in before each snapshot. With the peer built
without `read_only()`, its indexer writes index files under the root
and the test fails.
The nameservice sync routes (ref pushes for the commit and index heads,
ledger init, and the snapshot they are read against) advance or read
the transaction server's nameservice. On a query peer they returned
404, and before the peer opened its root read-only, a shared-storage
peer served them by writing the transaction server's nameservice from
its own process.

A peer now forwards them to its transaction server, as it does
transactions and commit pushes. The handlers read the request through
typed extractors, so a router layer does the forwarding before them.
A test sends a ledger init and a snapshot through a proxy peer and
finds them served by the transaction server; without the layer both
return 404.
Its callers, the file, IPFS and S3 builds, sit behind the `native`,
`ipfs` and `aws` features. Built with none of them, as the wasm32
engine is, the function was dead code and the wasm32 clippy gate
failed.
The browser peer applied each ledger head event with
`LedgerManager::notify`, which takes a record at or below the cached
`t` for current. A rebase that moves a branch's head back, or onto
another line at the same `t`, left the peer serving the replaced
commits; a record that arrived while the ledger loaded was dropped.
The native peers apply head events with `follow`, which judges such a
record against the nameservice and reloads onto the new line, and
follows a record for a loading ledger once the load lands.

The browser peer's head sink now calls `follow` too. A native test
caches a branch on a peer, rebases it onto the source's line at the
same `t`, and checks the head event moves the cached ledger there; with
`notify` it stays on the replaced commits.
@bplatz

bplatz commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

On the decisions from the review summary:

/info's top-level t moves from the index's t to the head's.

Intended. It is now a Behavior-changes line in the PR body.

A shared-storage peer no longer has any write or relay surface: ref-push 404s, it stops relaying /events, it runs no indexer.

Intended, with one change: a peer now forwards the nameservice sync routes (ref push, ledger init, snapshot) to the transaction server, as it does transactions. Addressed in 1e7b134. /events has returned 404 on every peer since v4, so nothing that subscribes changes; the body's bullet now says so. No indexer on a shared-storage peer is intended. Waiting until the peer has applied a forwarded commit, and a status handle on timeout, are #2452.

/info on a proxy peer returns the full metadata instead of commit_head_id / index_head_id.

Intended: a peer returns the same /info form as a transaction server. The body marks it breaking for clients of a proxy peer's /info, and names the fields to read. The 501s for commit show and validate were unreachable, since every peer forwards both.

Both binaries exit within 10 s of the server returning.

Intended, for the transaction server too. Shutdown already bounds the drain, the BM25 sync and the storage close before the runtime's limit applies. A commit is acknowledged only once the write-ahead log holding it has been flushed (Durability::Wal, the default), and the next start replays that log, so what the limit can abandon is a background flush, an index build or an unanswered request, as a crash would.

Release scope: land before #2421 tags v4.2.8, with an upgrade-order note.

Yes. The upgrade order is in the query-peers docs and the PR body.

The browser peer still applies head events with notify.

It follows them now: addressed in 3506843. #2423 conflicts with it in heads.rs; the resolution is noted there.

`the_peer_writes_nothing_under_the_root` failed in CI with the
writer's commit-index file growing between the snapshots around the
peer's open and load. The file nameservice appends a commit's line to
`<branch>.commits.jsonl` in a detached task after the publish returns,
so a snapshot taken right after the insert could precede it, and the
writer's own late append read as a peer write.

The test now waits until the commit index lists each of the writer's
commits before snapshotting. A peer built without `read_only()` still
fails it, through the index files its indexer writes.
@bplatz
bplatz merged commit 1306be4 into main Nov 18, 2026
21 checks passed
@bplatz
bplatz deleted the fix/query-peers-shared-storage branch November 18, 2026 22:20
bplatz added a commit that referenced this pull request Nov 18, 2026
Brings #2409 and #2390.

Query peers: main deletes the shared-storage peer's sync task, which
wrote the transaction server's nameservice, and runs both storage
modes through one event sink that follows records with
`LedgerManager::follow`, a worker per ledger. next had taught both
tasks new events; they now live on that sink:

- A completed snapshot evicts cached ledgers the subscription covers
  but the snapshot did not name, through each ledger's worker as a
  retraction is, and retracts graph sources known before the connect.
  A snapshot that missed an erasure refresh refreshes every cached
  ledger.
- A retraction carries the ledger instance it was for: one of an
  earlier ledger under the name leaves a newer watermark, and the
  ledger it is for stays cached while the nameservice still has it.
  A watermark of another instance counts as changed.
- `LedgerRefresh` refreshes the ledger; records feed the retention
  watch; graph source updates and retractions reach the event bus, as
  the shared-storage task did.
- The sync task's local mirroring, fences and resets are gone with it:
  a peer no longer writes a nameservice.

The ledger manager: main's line (an index install planned before a
reload or rebase is not made after it), `follow`, and the planned
notify go onto next's notify, which takes the catch-up lock first; the
line is read under that lock, before the record. A reload installs a
state of another activation whatever its `t` (next) or any state when
a follow says the line was replaced (main). `follow` evicts a ledger
the nameservice no longer has, as next's notify does. `refresh` keeps
next's lookup on every call, with main's line taken before it.

A read-only client also takes no lock on the root, which next takes
by default, and `get_local` (next's replacement for
`resolve_local_path`) reports a miss without applying a writer's log.
The CLI runs main's bounded runtime shutdown on next's larger driver
thread. Peer `/info` loses next's simplified proxy form with main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants