Skip to content

feat: ledger lifecycle — name bindings, restorable drops, fenced writers - #1980

Merged
bplatz merged 75 commits into
nextfrom
feat/ledger-lifecycle
Oct 13, 2026
Merged

bplatz merged 75 commits into
nextfrom
feat/ledger-lifecycle

Conversation

@bplatz

@bplatz bplatz commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Why

Today a ledger is its name. Records, storage paths and caches are all keyed by the name, so a name cannot be reused safely and a drop cannot be undone:

Design

A ledger's name and its identity become separate. The name points at one ledger at a time; each ledger has an immutable instance id.

Name binding. One item per name, the authoritative claim on it: {instance, root, root_branch, state, branches[]}, with state one of creating, active, dropping, restoring. Every protocol step is a compare-and-swap of a single item, so every backend can run it: file, S3-style object stores, DynamoDB, Raft and memory.

Storage roots. A ledger created from now on stores its data under {name}/@{instance}/, and it never moves. A ledger dropped and recreated under the same name never shares a file with the one before it. Ledgers created before this keep their data at {name}/, and the binding records which root applies.

Fences. The binding lists each branch with a random fence, and the branch record carries it. Every write presents the fence it loaded with, checked inside the existing compare-and-swap or condition, so a writer holding a dropped, restored or replaced ledger is refused (409 err:db/Fenced). Resolution is strict: a record is live only under an active binding that lists its fence, and publication never creates a record.

Dropped-ledger registry. Keyed by instance. A soft drop, now the default, moves the ledger here and frees the name at once. A dropped ledger can later be restored under its name, with fresh fences, or purged.

Protocols. Create, drop, restore, purge, branch create and branch drop are written against single-item CAS. Every step is idempotent, and an interrupted operation resumes from the binding or registry entry it left behind:

  • Create. Claim the name (creating), insert the records, then activate. A long import renews its claim every minute; a claim unrenewed for ten minutes is rolled back.
  • Drop. Mark the binding dropping, freeze every branch, write the registry entry, delete the records, then free the name.
  • Branch create. List the branch as being created, insert its record, then confirm the listing. A branch's children are the listings that name it as their source, so no stored count can drift.
  • Housekeeping. Runs on the background indexer's catch-up tick. It resumes a drop, restore or purge that has not moved between two ticks, and rolls back abandoned creates and branch creates.

Late bytes. A fence stops stale publications, not stale bytes: a writer can still land a file in a folder that has since been purged. An optional orphan sweep deletes instance folders that no binding or registry entry references.

Consumers.

  • Peers. Server-sent events carry the ledger's instance, so a peer replaces a ledger recreated under a name rather than ignoring it for its lower t.
  • Graph sources. BM25 and vector indexes record the instance they indexed, and Iceberg, SQL and Delta sources record their model ledger's instance. Each is suspended while its name leads to another ledger (409 err:db/GraphSourceSuspended). Native cross-ledger f:ledger references deliberately follow the name, and the docs say so.
  • Governance cache. It is keyed by the model ledger's instance as well as its t.
  • Key rotation. It covers dropped ledgers.

Upgrade. Metadata only; no ledger data moves.

  • File and object stores. The first start copies ns@v2/ to a new address, ns@v3/, binds each ledger where its data already is, and moves ledgers that 4.2 soft-dropped into the registry. It then retires ns@v2/: it keeps each file under [email protected]/ and replaces the original with a note a 4.2 binary cannot parse. A 4.2 process left running against the store then fails instead of committing where the new release never looks; this was checked against the real 4.2.1 CLI.
  • DynamoDB. Migrates in place. The guide shows how to deny old processes write access with IAM, including a CloudFormation pattern for Lambda deployments.
  • Raft. Migrates through state-machine commands on the first upgraded leader.
  • Newer formats. A release refuses a store in a newer format, and a binding in a state it does not recognize is an error, not a free name.

The full procedure is in docs/operations/upgrading-from-4.2.md.

User-visible changes

These are the release-note items:

  • Drop keeps data by default and frees the name immediately. fluree drop is now soft; --hard --force deletes. New commands fluree dropped list|restore|purge|sweep, and new endpoints GET /dropped and POST /dropped/{restore,purge,sweep}.
  • One ledger per name. Creating name:b while name exists returns 409; use fluree branch create. A 4.2 store that has two such ledgers keeps them as two branches of one ledger.
  • New 409 errors: err:db/Fenced, err:db/LifecycleConflict, err:db/GraphSourceSuspended.
  • Additive fields:
    • the drop response gains instance, name_released and data;
    • ns-record events gain instance and storage_root, and ns-retracted gains instance;
    • GET /ledgers marks a suspended index.
  • New server option: --orphan-sweep-interval-secs, default off.
  • The upgrade is one-way without a backup, and every process sharing a store must move together. The guide covers backups and rollback per backend.

Reading guide

Start with the model, then the protocols, then the backends:

  1. fluree-db-nameservice/src/binding.rs: the types and the two store traits (LedgerRegistry, BranchRecordStore).
  2. fluree-db-nameservice/src/lifecycle.rs: every protocol.
  3. fluree-db-nameservice/src/conformance.rs: what every backend must do, run against all five.
  4. fluree-db-api/src/admin.rs and housekeeping.rs: drop, restore, purge and resumption at the API.
  5. fluree-db-nameservice/src/migration.rs and each backend's migrate: the upgrade.
  6. docs/operations/upgrading-from-4.2.md: the operator's view.

Commits, oldest first, by area:

Area Commits
Unrelated fix, stacked here 1c5621120 restore refuses a name held by a live ledger (planned as its own PR)
Storage roots (no behaviour change) 0307ad42d
Core model and switchover 585a0fbb3 bindings, fences, registry and conformance in all backends · 0129adaf2 API · f1cf94b0e write fence · f455b5ac5 server · f2e8e3d64 CLI · a57145650 migration · 54fe983e5 strict resolution
Storage cleanup and resumption d82580675 purge across tiers · f20a3caa4 orphan sweep · 43ad762cc housekeeping · 607466a6c create rollback · f9da122b8 key rotation
Consumers d4b4c17f7 BM25/vector suspension · 3ac62fc2f peer instance events · 52d94aa8d governance cache · a9eda033e virtual-source model · c56cf6bcb peers of a 4.2 server · cfdc8649d suspended staleness
Fixes from an internal review 405b47ff8 · b8f274fc6 · 0cca037a7 · 56ff64004 · 7f23c598f
Upgrade safety and docs 903cba773 · 5692686cb upgrade guide · e079f4dc6 retire ns@v2/
Other f6ce8c3d7 binding read in parallel with the record · ab0cba20a two test races

The branch is large: 519 files, +21k/−7k lines. About 7k of the added lines are tests and the conformance suite, and most of the file count is mechanical call-site changes from the storage-root refactor and strict resolution.

Feedback wanted

  • The model: binding, fence and registry, with strict resolution.
  • Drop semantics: soft by default, and the name freed at once. Also one ledger per name.
  • The upgrade: retiring ns@v2/ to stop 4.2 writers, at the cost of keeping the rollback copy in [email protected]/ rather than in place. For DynamoDB, enforcement through IAM rather than in the product.
  • Name-based references: native cross-ledger f:ledger references follow the name, while virtual sources pin the instance.

Testing

  • Conformance suite. Runs against memory, file, storage (S3-style), DynamoDB (LocalStack) and Raft. It includes pause cases for branch creates, where a creator is interrupted before its insert and then rolled back or taken over.
  • Full CI matrix locally, all features. About 13.6k tests pass, plus doc tests, workspace clippy, the default-feature check, the native server check and wasm clippy. Three exceptions, all local:
    • two index-compaction tests timed out because of a 188k-file binary cache in the local $TMPDIR; they pass in 0.2 s with a clean one;
    • one docs-embed test picked up untracked local files.
  • Upgrade against the real 4.2.1 CLI. A 4.2.1-written store opens upgraded. Afterwards, 4.2.1's list fails with a serialization error, and its query and insert report the ledger not found, while this release keeps committing. A 4.2.1-written fixture store is also migrated in CI.
  • Hot-path cost.
    • Commit: unchanged, at ~6 ms. The fence is checked inside the existing CAS or condition.
    • File-store lookup: 44–46 µs before, 43 µs now, because the binding is read concurrently with the record.
    • LocalStack DynamoDB lookup: 4.7–4.9 ms before, 3.9–4.1 ms now.
    • The instance folder level costs 0.5–1.6% on a 450-commit replay.

Known gaps

Not in this PR:

  • Crash and pause tests. A harness that fails or pauses the Nth store call across every protocol step, beyond today's branch-create cases.
  • Index GC for dropped ledgers. A soft-dropped ledger keeps its old index versions until purged.
  • Smaller review follow-ups: renewing a claim on its own task, a lease for housekeeping, and full-fidelity registry copies of status and config metadata.
  • DynamoDB, large ledgers: a ledger with roughly 900 or more branches cannot be dropped or restored as a whole, because its dropped-ledger entry would pass the 400 KB item limit. The drop or restore is refused before it changes anything. Follow-up: DynamoDB: store a dropped ledger's branch copies as their own items #2104.
  • DynamoDB, 4.2 writers: a 4.2 process left running is fenced out only by the IAM recipe in the upgrade guide, not by the upgrade itself. Follow-up: DynamoDB: make the upgrade to name bindings fence out 4.2 writers #2105.
  • Raft: holding the migration until every voter runs the new release; the rolling-upgrade procedure covers this today. The migration also rescans the replicated state on every election. Follow-up: Raft: record that the legacy-ledger migration finished #2106.
  • Peers: a proxy-mode peer following a real 4.2.1 server has not been exercised.
  • Release naming: the release name is open; the Raft docs already say v4.3.

Related

Related: #1670, #1592. The next → main PR will carry the closing references.

Targets next.

MCP admitted any token from a trusted issuer and then served every
ledger: `get_data_model` returned any ledger's schema and statistics with
no scope or policy check, and `sparql_query` ran unrestricted when the
token carried no identity. Both tools now authorize the requested ledger
against the token's `fluree.ledger.read.*` claims (falling back to
`fluree.storage.*`), the same claims and parsing the data API uses; an
uncovered ledger gets the same answer as a missing one.

`GET /ledgers` had no auth and listed every ledger even when data auth
is required. It now follows data auth like `/info` and `/exists`: a
Bearer is required when data auth is, and a token sees only the ledgers
and graph sources it can read.

Tokens that relied on issuer trust alone for MCP need
`"fluree.ledger.read.all": true` to keep reading every ledger.
A request with no policy inputs gets a ledger's configured policy
defaults on every read path, but the graph-scoped builder's graph-source
fallback returned a governed source unwrapped in that case, so
`graph(source).query()` read rows the `from`-driven builder denies for
the same request. It now applies the source's configured defaults too.

Also corrects the setting-groups docs, which still said a request without
policy inputs is never enforced and that `f:defaultAllow` only applies to
requests carrying policy inputs.
On a server with data auth `none` and no MCP issuer configured, `/mcp`
is now as open as `/query` next to it: no token needed, every ledger
readable, and a presented token ignored as the data API ignores it.
`--mcp-enabled` alone is enough to try MCP locally. Configuring an MCP
issuer (or the events-issuer fallback) still requires tokens whatever
the data auth mode, and data auth `optional`/`required` still requires
an MCP issuer at startup.

An MCP query without an identity also skipped the ledger's configured
policy defaults: it loaded the ledger through the graph builder, which
applies none, so a ledger configured `f:defaultAllow false` denied an
anonymous `/query` but answered the same SPARQL over MCP. That path was
already reachable with a token carrying no `sub` or identity, and
tokenless mode would have made it the default. Identity-less queries
now go through the same policy-defaults wrap as every other anonymous
read.
Covers trying `/mcp` locally with one flag, connecting common MCP
clients, when the endpoint requires a token, and hardening it step by
step: server-wide data auth, per-agent ledger scopes, identity-based
policy, and production notes. The configuration, authentication and
token references now describe the token requirement and link to it.
The startup error for MCP with data auth and no trusted issuer, and the
MCP guide, both pointed at `--mcp-auth-insecure`, which does not exist.
The flag is `--mcp-auth-insecure-accept-any-issuer`; only its env var is
the short `FLUREE_MCP_AUTH_INSECURE`, which the guide now also names.
`/query/<ledger>@t:5` (and `@time:`, `@iso:`, `@recorded:`, `@commit:`,
`@snapshot:`) returned 500: the route never parsed its path tail and handed
`mydb@t:5` to the ledger loader, whose id parse failed into the generic 500.

The ledger-scoped query and explain handlers now parse the path once with
`LedgerRef`, carry the base ledger and the pin separately, and key bearer
scope, min-t, refresh and the ledger cache on the base. A pinned read takes
the time-pinned load path a body pin already uses, so the whole ledger is
read as of the pin, named graphs included:

- SPARQL goes through the dataset path with the ledger's default graph at the
  pin, which keeps `GRAPH ?g` enumerating the ledger's own named graphs.
  `FROM` / `FROM NAMED` sources take the pin.
- JSON-LD has the pin written onto every `from` / `fromNamed` source (top
  level or `opts`) that names the path's ledger, or gets a pinned `from` when
  it names no dataset, and runs as a body-pinned query.
- Cypher and explain load the view with `db_at`.
- A `@t:N` pin waits for `t=N` like a body `@t:` pin does.

A time the body names for the same ledger must agree with the path pin, or
the request is a 400; so is a history (`to`) query on a pinned path, a
dataset that never reads the pinned ledger, a pin combined with a `#graph`
fragment, and a malformed pin. On explain, a SPARQL `FROM` must repeat the
path's pin because explain plans the FROM's own snapshot.

The streaming endpoint parses the path only to refuse a pin with a 400: its
dataset path does not enumerate a ledger's named graphs under `GRAPH ?g`, so
a pinned read there would silently drop them. The Graph Store `GET`/`HEAD`
reads through `/query` and so honours a pin as well.
Describe `/query/{ledger}@<pin>` and how it interacts with body pins, the
pinned forms of `/explain`, the Graph Store's pinned reads, and the streaming
endpoint's refusal. Also correct the explain section, which still said a
ledger-scoped SPARQL explain rejects every `FROM`.
A restore into `mydb:other` while `mydb:main` was live created a second
root branch under the name. If the restore then failed, its rollback
soft-dropped the whole name, taking `mydb:main` offline with it.

Restore now refuses a name that holds a live ledger on any branch, and a
failed restore purges only the record it created. Purging rather than
retracting also lets a failed restore be retried under the same name:
the retracted record used to reserve it on every backend but S3.
Every ledger artifact lives under `{name}/{branch}/` or `{name}/@shared/`,
and each path was formed from the ledger id string, so the id was also the
only thing that could say where a ledger's data is.

Add `StorageRoot`, the folder holding one ledger's artifacts, and
`StorageNamespace`, a root plus a branch, and make every path-forming API
take a namespace instead of an id: `content_store`, `content_path` and
`content_address`, `ContentAddressedWrite`, the GC sweep and collector,
drop, key rotation, restore, import, pull and clone, and the Raft commit
worker. Call sites take the namespace from the branch's nameservice record
or loaded state; graph sources keep their id-keyed layout through a
separate constructor.

`NsRecord` gains an optional `storage_root`, which the proxy lookup and
SSE events carry to peers. Every root is still the ledger's name, so no
path changes.

`set_ledger_config` and `fluree config set-origins` now look the ledger up
first and return not-found for a missing one, rather than writing the
config blob before failing.
A ledger's name was its only identity: the nameservice key, the storage
folder and the handle were one string, so a dropped name could not be
reused while any of its data had to exist.

Add the pieces that separate the name from the incarnation holding it:

- `InstanceId` and instance storage roots (`{name}/@{instance}`) in core.
- A name binding per name (instance, root, root branch, state, and each
  branch's fence), a registry of dropped ledgers keyed by instance, and a
  per-activation `Fence` on branch records, with `frozen` status.
- `LedgerRegistry` and `BranchRecordStore`: single-item compare-and-swap
  on bindings and registry entries, and branch-record writes conditional
  on the fence. Versions never repeat for a key, even across a delete,
  so a compare-and-swap from a read taken before a drop cannot match the
  binding of the ledger that reused the name.
- `lifecycle`: create (begin/activate/abandon), create branch, drop,
  restore and purge, each resumable from the state it left.
- Implementations for the memory, file, storage-backed, DynamoDB and raft
  nameservices. File and storage records carry the fence in both the
  record and its index file and are tombstoned rather than deleted; an
  index file whose fence differs from its record's is ignored. DynamoDB
  carries the fence on every item of a record. Raft adds commands for
  each operation and restores snapshots taken before this state existed.
- A conformance suite the five backends all pass, run against DynamoDB
  on LocalStack and a single-node raft.

Nothing uses these yet: ledgers are still created, loaded and dropped
through the existing paths.
Ledgers are now created under a name binding, with storage of their own
under `{name}/@{instance}/`, and the API drives the lifecycle protocols.

- create_ledger, archive restore and import claim the name, write, then
  activate. A failure releases the claim, so a failed restore or import
  leaves no ledger behind. A name still held by a ledger from before
  bindings stays taken.
- A name holds one ledger: creating `mydb:dev` while `mydb` exists is a
  conflict. Tests that used branches as separate ledgers are renamed.
- drop_ledger frees the name at once. A soft drop keeps the ledger in the
  dropped-ledger registry; a hard drop deletes it and resumes on retry.
  Rust list_dropped / restore_dropped / purge_dropped and HTTP
  GET /dropped, POST /dropped/restore, POST /dropped/purge manage the
  registry. The drop response gains instance, name_released and data.
- drop_branch marks the branch dropped in the binding and freezes its
  record. Its storage goes before it is unlisted, so its name cannot be
  reused mid-delete; a frozen branch gains no children; a branch dropped
  before its ledger comes back dropped on restore.
- Reads resolve records through their binding. A record with no binding
  predates bindings and reads as before, keeping the old drop semantics.
- Paths come from the binding root everywhere a ledger is written: the
  raft commit worker, queued transactor and envelope release included.
  The storage proxy maps instance roots back to their ledger, remote
  mounts localize them, and peer sync and raft registry adoption copy a
  record's binding with it.

Writes are not fenced yet.
Every write to a branch record now presents the fence its writer captured
when it loaded the branch, checked in the same compare-and-swap as the
write. A fenced record takes only its own fence, and nothing once frozen;
a record from before fencing takes only unfenced writes; a fenced write
to a missing record is refused rather than recreating it. So a writer
that loaded a ledger before a drop can no longer publish into it, into a
ledger that reuses its name, or into it once restored, where its expected
head would otherwise still match. The refusal is `Fenced`, a 409.

- The publisher traits' required writes are the `*_fenced` forms; the
  unfenced names remain as defaults presenting no fence.
- File and storage nameservices check both the record and its index
  file, which carries the fence from before the record exists. DynamoDB
  adds a fence clause to each item's condition. Raft wraps a fenced
  write in an appended `Fenced` command and refuses bare writes to
  fenced branches; the commit worker's queued head is already fenced by
  its queue entry.
- Writers carry the fence they loaded: `LedgerState`/`LedgerView`,
  index builds (`IndexResult::fence`), merge, rebase, revert, push,
  restore and import. Admin tools, sync, peers and remote ref pushes
  present the branch's current fence.
- The conformance suite covers every write kind on all five backends.
…h the proxy init route

The server kept its own status table and sent every ApiError variant it
did not list to 500, so a write refused by a ledger's fence, a malformed
instance id, a branch conflict and several other client errors all came
back as internal errors. Fence refusals now answer 409 with their own
`err:db/Fenced` type, and variants the server does not classify take the
status the API gives them.

A write through a cached ledger that another process dropped and
restored is refused by the fence alone, since the heads still match; the
refusal reloads the cache, so the next write succeeds. A test pins that.

The storage proxy's `init` route created a bare, unfenced branch record.
It now creates the ledger as `/create` does, under a name binding, and a
branch of a ledger that already holds the name conflicts instead of being
created standalone.
…stores and purges

`fluree drop <name>` now soft-drops, as HTTP and Rust already do: the
name is free at once and the data is kept under an instance id, which the
command prints. `--hard --force` deletes the data straight away.

`fluree dropped list`, `restore <instance>` and `purge <instance> --force`
work against a remote, a locally running server, or the local store,
like the other admin commands.
…first start

Records now live under `ns@v3/`. The first start of a file or S3 store
copies `ns@v2/` across and binds each ledger to its name where its data
already is, giving each branch record a fence; a ledger whose branches
were all retracted was soft-dropped, so it moves to the dropped-ledger
registry, where it can be restored or purged, and its name is free.
`ns@v2/` is left as it was for a rollback, and a start that finds it
written since warns: binaries from before the change see only `ns@v2/`,
so they cannot rewrite a migrated record and strip its fence.

DynamoDB tables migrate in place on first start and record the format
in an `@format` item; Raft clusters migrate on the first leader elected
after the upgrade; the Raft file-registry adoption migrates the registry
first and carries bindings and dropped ledgers across as they are.

The migration issues instance ids and fences derived from the names, so
a repeated, resumed or concurrent run writes the same result. A store in
a newer format than a binary understands is refused, and record files
keep fields this binary does not know when it rewrites them, so the next
format change can be made in place.

A store written by the released 4.2.1 binary is checked in as a test
fixture.
Every store now resolves a ledger through its name binding alone: a
branch record that no binding lists is invisible and takes no writes, and
publication never creates a record, so a write to a missing record is
refused as fenced instead of creating one. The paths that served ledgers
from before name bindings are gone: `LedgerLifecycle` (init, retract,
purge), the unfenced publisher methods, the legacy drop arms, and the
compare-and-set that created a ledger from `expected = None`. The
migration binds those ledgers on first start, so nothing reaches them.

Committing a ledger that was never created is refused as not found.
Raft keeps its legacy commands so logs written before still replay, and
refuses them where they are proposed instead. Peers mirror and unmirror
records through the lifecycle.

The DynamoDB migration now writes any item a record never had, fenced: a
ledger whose index was never published had no index item, and a fenced
publish no longer creates one.

Tests create their ledgers through the lifecycle, so the genesis helpers
are async; `fluree_db_nameservice::testing` (feature `conformance`) gives
them writes that present the record's current fence.
… tier

Purging a ledger stored under an instance folder now lists the folder
once and deletes everything in it, instead of walking each branch's
artifact folders. That also removes files no branch of the dropped
ledger names, such as those of a branch created as the ledger was
dropped. A folder that cannot be listed, a ledger stored under its name
from before instance folders, and IPFS keep the per-branch path.

`TieredStorage::list_prefix` sent any prefix that names no commits or
transactions to the index tier alone, so listing a ledger's folder, or
the whole store, missed the commit tier. It now lists both tiers and
keeps from each only the addresses it serves. Key rotation's count of
blobs left on a retired key lists the whole store, and undercounted the
same way.
`sweep_orphan_instances` (`POST /dropped/sweep`, `fluree dropped sweep`)
deletes the instance folders that neither a ledger nor a dropped ledger
references: bytes a writer stored after its ledger was purged, which the
fence keeps from being published but not from being written, and the
data of creates that never finished. A dry run (`dry_run`, `--dry-run`)
only lists them.

An instance is referenced from before its first byte is written until
after its folder is purged, and instance ids are never reused, so a
folder found unreferenced stays so. Folders come from one listing of the
whole store: the first `@` segment of a path ends the ledger name, and
is an instance folder only when it parses as an instance id, so
`@shared` and data stored under a name from before instance folders are
never touched. Each candidate is confirmed by key, since the binding and
registry listings are not one snapshot. A peer forwards the request to
the transaction server, whose nameservice knows every ledger.
…placed

An index records the instance of the ledger it was built from. When
that ledger is dropped and another is created under its name, sync and
resync refuse the index with 409 `err:db/GraphSourceSuspended` instead
of merging the new ledger into an index of the old one. Without the
check, syncing from a replacement at a lower `t` reported "already up to
date" and indexed nothing. Restoring the dropped ledger resumes the
index. An index created before this change was built over a ledger
stored under its name, so it is taken to have indexed that ledger's
legacy instance. The background workers skip a suspended index with a
warning.

Recreating an index over the replacement now works. A new
`reset_graph_source_index` (every backend; Raft appends
`ResetGraphSourceIndex`) clears a dropped index's head before the index
is published again. Before, the head refused the new index's lower `t`
and went on naming the dropped index's manifest, whose snapshots the
drop had deleted.
…er's catch-up tick

The node that owns the indexer's catch-up tick (never a peer; under Raft,
the leader) now also finishes lifecycle operations that a crash
interrupted. A drop, restore, purge or branch drop still unfinished at
the next tick is resumed, and completes as if it had not stopped. Each
resume goes through a new resume-only entry point that finishes only
the operation it saw, so an operation that finished meanwhile, and a
ledger or branch created under its name since, are left alone.

A create that has not finished is logged but not rolled back: an import
holds its create open for as long as it runs, so it looks the same as a
create that never will finish. `fluree drop <name> --hard --force` frees
the name.

`--orphan-sweep-interval-secs` (off by default) runs the orphan sweep on
the same tick, at most once per interval.

The indexer gains a `Housekeeping` hook, installed with
`IndexerHandle::set_housekeeping`; `Fluree::lifecycle_housekeeping`
provides this one, and the server installs it on the worker that owns
catch-up.
…tests

`rotation_runs_and_verifies_over_http` read the rotation status once it
said `completed` and required `active_here` to be false. The sweep
records `completed` before its task exits, so a read in between sees it
still active; the test now polls until both hold. Holding the sweep open
after its last checkpoint makes the old assertion fail every time.

`liveness_monitor_demotes_killed_follower` read the eligible voters once
after bootstrap. With `max_healthy_lag: 1`, a voter still applying the
membership change under load can be demoted, then promoted again once it
keeps pace; the test now waits for the full set.
Key rotation built its units from the live records alone, so a
soft-dropped ledger's files stayed on the retiring key and verification
ended `swept`. Removing the key after that would leave a later restore
unreadable.

The units now also cover every dropped-ledger registry entry (dropped,
restoring or purging) and every binding part way through a create, drop
or restore, per branch and shared dictionaries, never a name folder
wholesale. Branch units are keyed and ordered by prefix, which a drop or
restore leaves unchanged, so neither shifts a paused sweep's place.
…okup

Resolving a lookup read the record, then the binding it names: one more
round trip per lookup on every store. A lookup knows the name before
either read, so the file, storage and DynamoDB nameservices now issue
both together.

On local file storage a lookup took 44-46 µs before name bindings,
52-55 µs with the binding read after the record, and 43 µs with the two
together. Against LocalStack DynamoDB a lookup took 4.7-4.9 ms read in
sequence and 3.9-4.1 ms together.
A ledger dropped and created again under its name starts over at a lower
t, but events named only `name:branch` and caches compared heads by t.
A cached state of the old ledger survived the new one's records (a lower
t planned as no-op), a late retraction could remove a peer's copy of the
new ledger, and a ledger whose retraction was missed stayed cached.

- `LedgerRetracted` gains `instance`; a new `LedgerCreated { ledger_id,
  instance }` fires when a branch becomes visible (create, import,
  restore, branch create, peer copy). The notifying nameservice reads
  the binding to fill them in; Raft reads it from applied state.
- SSE: `ns-record` carries the ledger's `instance` and is also sent on
  create and restore; `ns-retracted` carries `instance` when known.
  Older clients see only extra fields.
- `LedgerManager::notify` reloads a cached state whose storage root or
  fence differs from the record's, and `reload` swaps it in whatever its
  t; a ledger that no longer resolves is evicted (`NotifyResult::Evicted`),
  as is one `refresh` cannot find.
- Peers: `unmirror_record` and the watermarks skip a retraction naming
  another instance, and a record of another instance replaces the
  watermark; the peer library does the same.
A crash between claiming a name and activating the ledger left the name
held by a `Creating` binding forever: housekeeping only logged it, since
an import holds its create open for hours and a running one looked the
same as a dead one.

- Imports and archive restores renew their claim every minute while
  they write (`while_claimed`), by writing the binding back unchanged,
  which moves its version. A lost claim stops the work.
- Housekeeping rolls back a `Creating` binding whose version has not
  moved for ten minutes (`HousekeepingOptions::abandoned_create_after`),
  timed by its own clock from when it first saw that version.
  `lifecycle::rollback_create` frees the name first, so a paused
  creator finds its claim gone and stops, then deletes the records;
  housekeeping then purges the instance folder.
- A failed import deletes what it wrote, as an archive restore already
  did, instead of leaving it for the orphan sweep.
- A creator whose claim was rolled back while it was paused could, on
  resuming, delete the live record of the ledger that took the name
  since: `insert_fenced` now deletes a foreign-fenced record only while
  the caller's binding still lists the caller's fence.
- A drop adopted any registry entry for its instance as its own earlier
  attempt, including a `Restoring` one a finished restore failed to
  forget; resuming that restore brought the dropped ledger back. The
  drop now replaces a restoring entry.
- A drop accepted a `Creating` binding, registering a "restorable"
  ledger with no genesis. It is now refused as a conflict; the create
  is rolled back instead.
- Inserting a record reset its index file before winning the main
  record, so a racing inserter could leave the winner's index file under
  its own fence and every index publish refused. The record is now
  written first, only its creator resets the index file, and an insert
  repeated under the same fence redoes the reset.
- Deleted records are tombstones, but `heads`, `get_ref`, `get_status`
  and `get_config` read them as live on the file and storage backends.
- Lifecycle conflicts (being created, restored or purged, a lost claim,
  a contended binding) are a new `NameServiceError::Conflict` rather
  than a storage error.
…nflicts with 409

- Dropping a name whose create or import has not finished rolls the
  create back, freeing the name and deleting what it wrote, instead of
  registering a dropped ledger with nothing in it. Housekeeping shares
  the same `roll_back_create`.
- A drop housekeeping resumes re-reads the binding before cancelling
  indexing: one that finished meanwhile may have handed the name to a
  new ledger.
- A failed archive restore releases its claim and then purges its
  instance folder, as a failed import does.
- `NameServiceError::Conflict` maps to 409 with
  `err:db/LifecycleConflict`, not 500.
`LedgerRegistry` and `BranchRecordStore` gave each method a default that
returned "not supported", so a backend or wrapper that missed one
compiled and failed only when the lifecycle protocols reached it. Every
backend implements them all; a test wrapper that relied on two defaults
now delegates them.
…nd registry entries

Name bindings, their branch listings and dropped-ledger entries are new
in this release, so this is the version every later one must stay
compatible with. Each now keeps fields it does not know in `extra` and
writes them back, so a rewrite by this version (a branch create, a drop)
does not lose what a later one added.

`NameBinding` and `DroppedLedger` flatten a tagged state enum, and serde
hands a flattened map every key, including the enum's; they deserialize
through a mirror struct that strips those keys, or they would be written
twice.
A branch's child count was stored on its record and only ever went up
when a create was interrupted. Taking over a create that stopped between
counting the child and inserting its record counted the child twice, and
so did the original creator if it had only paused. The parent then never
reached zero children, so a dropped parent was never purged.

Each listing now names the branch it was created from, and a branch's
children are the listings that name it. Listing a child and checking its
source is live happen in one binding write, so a dropped branch gains no
children and its drop reads an exact count. The count readers see on a
record is computed from the binding.

A branch create now lists the branch as being created, inserts its
record, then confirms the listing. An unconfirmed branch reads as absent
and cannot be dropped or branched from. Creating it again takes it over,
and housekeeping rolls it back once it has been seen unconfirmed for the
abandoned-create interval. A creator whose listing was rolled back or
taken over deletes its record and fails with a conflict. A ledger drop
does not copy an unconfirmed branch into the registry.

Finishing a branch drop decides whether to purge the parent from the
binding it wrote, and does so again when resumed after unlisting, so a
crash between the two steps no longer strands the parent.

The stored count and adjust_children are removed from every backend,
along with the Raft AdjustChildren command.
A branch drop announced itself only when it deleted the record, which a
branch with children defers until its last child goes. Raft followers kept
serving it from cache, and peers following over SSE kept a live copy.

Freezing a branch the binding lists as dropped now announces
LedgerRetracted, in the notifying nameservice and in Raft's apply events;
a ledger drop's freezes still do not. A peer that hears it keeps a copy
whose copied children need it, dropped and frozen as the owner keeps it,
and removes it when the drop is announced again after the last child.
An unborn branch's source branch and child count are held on its fence
entry until its first head moves them onto the ref entry. The admin head
set and the ref compare-and-swap did; apply_head, the path every queued
transaction takes, created the entry with no source and no children, so a
branch created from an unborn source lost its lineage on its first
transaction and merge could no longer default to its source.
A peer learned of a drop only from its ns-retracted event. One dropped
while the peer was disconnected never appeared again, so the peer kept its
copy and served it; a subscriber that fell behind the live events lost
whatever the server skipped.

The events stream now ends its snapshot with snapshot-complete, and a
subscriber that falls behind has its stream ended so it resyncs. Peers
track what the snapshot names and, at snapshot-complete, drop what they
hold in scope that it did not: a shared-storage peer its local copies and
graph sources, a proxy or browser peer its cached ledgers.

A shared-storage peer also stops treating a record that repeats its head
(the first copy, an index publish, a reconnect) as divergence; it evicted
the cached ledger and logged a force-follow each time.
The rollback a backup offers names each ledger's index as it was at the
upgrade, which the new release's index GC deletes once newer builds
replace it; such a ledger fails to load on 4.2 until reindexed. Copying
[email protected] back left it in place, and a later upgrade, which keeps a
retired file only where none is kept, would then keep the first upgrade's
state. A ledger hard-dropped or purged since comes back without its files.
A 4.2 process left running on a DynamoDB table can create a ledger after
the upgrade; it is unbound, so unseen, and blocks its name. The guide now
says how to find such ledgers, with a scan for ledger meta items without a
fence, and how to bring them in: delete the @Format item and start one
process, which runs the upgrade again.

A conformance case runs the upgrade again on a store in use on every
backend: late records are bound and listed, and what the new release
created is left alone. A DynamoDB test follows the documented steps.
…ropped

Raft runs the upgrade on every elected leader. A branch drop unlists the
branch and then deletes its record; a leader elected between the two found
a legacy-fenced record its binding did not list, took it for one an
earlier attempt had not bound, and listed it live again, with its data
already deleted. A release before name bindings never freezes a record, so
the migration now takes a frozen record as dropped, as a retracted one.
The catch-up owner's ticks were counted after a fixed 200 ms of wall
clock, which a loaded CI runner missed. The owner's count now waits for
two ticks with a 30 s deadline; the non-owner's still waits 200 ms.

@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 structural fix for "a ledger is its name", and at a design level no pushback from me: the binding/fence/registry model, written as single-item-CAS protocols that every backend can run and held to one conformance suite across all five, is what I'd have asked for (and it's the real answer to my #1592). Three notes:

(1) On your DynamoDB feedback question: file and object stores get an in-product fence against a 4.2 process (retiring ns@v2/), while DynamoDB gets an IAM recipe. Since the migration already rewrites every item to add fences, moving the head/index items to new sort keys at migration would make 4.2 fail on DynamoDB the way it fails on file stores, and the IAM recipe would become defence in depth. That matters most on Lambda, where "every process at once" is hardest, and the guide's list also misses a 4.2 writer committing into a recreated ledger (inline).

(2) The class this closes is "a ledger's name, plus a t or a per-novelty counter, used as if it named the ledger": #1670, #1592, #1962's list and #2052, and seven point fixes inside this PR (governance cache, schema bundle caches, both idempotency caches, peer watermarks, BM25/vector, virtual sources). Four instances are still open at this head: the compiled-SHACL cache (tx.rs:941, a must below), refresh(min_t)'s fast path (lib.rs:4958, a must below), the GraphQL shape cache (graphql.rs:842) and the fulltext novelty cache (fluree-db-query/src/eval/fulltext.rs:89). The structural direction is one ledger-identity key type that every process-wide cache has to take, so a name-only key stops compiling; the point fixes here are each one field, so that type can be its own effort after. Graph sources are the next layer of the same shape (b07a3f30b, 3efcd3699, this PR's own reset_graph_source_index), also not this PR.

(3) This doesn't make your #2052 redundant: #2052 also keys the data ledger's compiled-SHACL cache, which this PR leaves keyed by (model, graph, t), and I reproduced the stale enforcement here with the now-default soft drop, in the fail-open direction too. I'd land #2052 first and resolve the four conflicts here (cross_ledger/cache.rs, it_policy_cross_ledger.rs, the two governance docs); this PR's instance key on the governance cache then overlaps #2052's commit key, and one of the two can go.

The four musts below are all small; good to merge once they're in.

Full review below:


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

@bplatz this is a big and genuinely careful piece of work: every lifecycle step as a single-item compare-and-swap, resumable from the item it left behind; the fence checked inside the same CAS or condition the publish already makes, so the commit path costs nothing; and one conformance suite run against memory, file, object store, DynamoDB and Raft. The 4.2.1 fixture test (it_legacy_store) is exactly the upgrade test I'd want, and purge stays inside its own ledger even for 4.2-layout ledgers (inline). The four things that need to land first are about the record layer keeping its invariants under interruption and at scale, and about two consumers that still treat a name as a ledger:

  1. On Raft, a re-run of the migration brings back a dropped pre-upgrade branch (fluree-db-consensus/src/raft/embedded.rs:338, fix at fluree-db-nameservice/src/lifecycle.rs:1396). The migration runs on every new leader; a leader change between finish_drop_branch's unlist and its record delete leaves a frozen, legacy-fenced record that the next run re-lists as live. Reproduced on memory and on a single-node raft. Fix: dropped: record.retracted || record.frozen in bind_legacy (I tried it: housekeeping then finishes the drop, and the suite stays green), and run the raft migration once.
  2. On DynamoDB, dropping a ledger with roughly 1,000+ branches fails after taking it offline (fluree-db-storage-aws/src/dynamodb/lifecycle.rs:568). The registry entry is one item; past 400 KB its PutItem fails at step 3, after the binding is Dropping and every branch frozen. Reproduced on LocalStack with 1,500 branches: the ledger stayed unreadable, the drop unresumable, and the name held. Fix: the branch copies as their own items under the instance's partition, or refuse the drop before step 1 when the entry won't fit.
  3. refresh with a min_t answers from a dropped ledger's cached state (fluree-db-api/src/lib.rs:4958-4968). The fast path compares the cached t with min_t and returns Current before any nameservice read, but a ledger recreated under the name starts again at t 1. With two Fluree handles on one store, refresh(min_t: 1) returned (3, Current) and queries read the dropped ledger's values while the name held the new one. Solo's query Lambda calls refresh with min_t on every request that carries X-Fluree-Min-T. Fix: drop the fast path, or gate it on the caller's instance.
  4. The data ledger's compiled-SHACL cache keeps a dropped model ledger's shapes (fluree-db-api/src/tx.rs:941-949). Rekeying the governance cache doesn't reach it, so a model recreated at the same t has its predecessor's shapes enforced, or not enforced (the fail-open direction reproduces too). Land #2052 first, or add the model's instance to CachedShapeSource::CrossLedger.

Beyond those, inline: listings and the catch-up tick now read one binding per name, sequentially (binding.rs:482, plus DynamoDB list_bindings/list_dropped); DynamoDB delete_record lost its batching; fluree-search-httpd migrates the store but isn't in the guide's process list, and its /v1/search skips the suspension check; two more process-wide caches keyed by name plus counters (GraphQL shapes, fulltext novelty); a Creating hint for hosts where the housekeeping tick never runs; the dead unfenced create arms (your own "removing dead create code"); and a question on the DynamoDB upgrade fence.

On the "Known gaps": I'd fold in the dead create code now. The crash/pause harness, index GC for dropped ledgers, the claim and housekeeping leases, full-fidelity registry copies, the raft cluster-version gate and the real-4.2.1 proxy-peer run all read as genuinely separable to me (the harness is exactly what would have caught the first must, but that point fix lands here). On the split plan: it reads well, and all four musts belong with the core PR.

Adherence to repo commitments:

  • Patterns/abstractions: ⚠️ extends NameService/Publisher with two store traits rather than a parallel path, every backend implements every method with no "not supported" defaults (0cca037a7), and the consumers go through drop_ledger/restore_dropped/purge_dropped and the fenced publisher methods; but "identity in the cache key" is fixed per cache, and four consumers were missed (headline).
  • Performance (speed first, memory second): ⚠️ commit and query paths are neutral (the fence rides inside the existing CAS or condition); a lookup adds one point read, issued concurrently; listings and the housekeeping tick add one sequential read per name, and DynamoDB drops lost their batching. Admin and background paths, and both fixes are small.
  • Deployment targets: ⚠️ shared code on every host; the evidence covers memory, file, object store, DynamoDB (LocalStack, in CI) and single-node Raft. On Lambda every concurrent cold start runs the DynamoDB migration until one writes @format, the housekeeping tick can't run (process-local, nothing survives the response, though every resumption is reachable by an explicit drop/purge/restore), and must 3 only shows with two processes and no events between them, which is exactly the Lambda shape and not something db's CI runs.
  • Testing: ⚠️ the conformance suite on five backends (dynamodb_lifecycle_conformance and raft_lifecycle_conformance pass in CI on this head), the 4.2.1 fixture in grp_ledger, and the new lifecycle suites run by name (54 in grp_ledger, 7 server, 7 CLI, BM25/vector, cross-ledger policy, key rotation); the gaps are interruption between two protocol steps (must 1), refresh(min_t) across activations, and the compiled-SHACL cache after a model recreate.
  • Conventions: ✔ thorough multi-line commit bodies; docs updated for every user-visible change (upgrading-from-4.2.md, dropped.md, errors.md, endpoints); fmt, clippy and test green in CI on this head.

Verified locally at fae8f7f: fluree-db-nameservice --lib 315/315 and raft conformance green; fence_admits made to ignore the fence turns nine conformance cases red, and purge_instance_root pointed at the name turns three red; the grp_ledger lifecycle filter 54/54, server lifecycle 7/7, it_key_rotation 4/4, BM25/vector 28/28, cross-ledger policy 17/17; all four musts reproduced with scratch tests (memory and single-node raft, LocalStack, two handles on one file store, and #2052's own test ported here), and the one-line fix for the first validated.

Approving now so you can merge without waiting on another pass from me — just be sure the four above are in before you do.

/// Bind the ledgers a cluster from before name bindings left in the
/// replicated state (see
/// [`fluree_db_nameservice::lifecycle::migrate_legacy`]). Runs on each new
/// leader, since only the leader can propose; once bound, a run finds

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 Must address before merge — on Raft the migration re-runs on every new leader, and a re-run brings back a dropped pre-upgrade branch.

migrate_nameservice runs migrate_legacy on each newly elected leader with no marker ("once bound, a run finds nothing to do"). But migrate_legacy takes every record fenced with legacy_fence(id) as one an interrupted migration fenced (lifecycle.rs:1337), and bind_legacy's merge arm re-lists any such branch the binding lacks (lifecycle.rs:1411-1427), as dropped: record.retracted. finish_drop_branch unlists a branch and only then deletes its record, which here is two proposals, and FreezeBranch sets frozen, not retracted.

So: a branch that existed before the upgrade is dropped, and the leader crashes or steps down between finish_drop_branch's unlist and its DeleteBranch. The record is left frozen and unlisted (housekeeping can't see it, since it works from the binding), and the next leader's migration lists it again as a live branch: frozen, with its storage already deleted by the caller. I reproduced it with a scratch test on memory and on a single-node raft (begin_drop_branch, then just the unlisting CAS, then migrate_legacy again): the second run reports bound: ["mydb"], the binding lists dev with dropped: false, and lookup("mydb:dev") returns the frozen record.

Two small pieces, either of which closes this case. In bind_legacy, list a frozen record as dropped (dropped: record.retracted || record.frozen at lifecycle.rs:1396): an interrupted migration only ever freezes a record it lists as dropped, so this changes only the leftover case, which then reads as a dropped branch that housekeeping's resume_drop_branch finishes. I tried it: the leftover came back listed as dropped, resume_drop_branch/finish_drop_branch removed it, and the nameservice suite stayed 315/315. And run the raft migration once, recording that it finished in the replicated state the way @format does on DynamoDB, which also spares every later election a full all_raw_records scan.

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.

Fixed in f9400c5 with your fix: the migration takes a frozen record as dropped (a release from before name bindings never freezes one), so housekeeping's branch-drop resume finishes it. The conformance case a_rerun_migration_keeps_a_stopped_branch_drop_dropped runs on all five backends and fails without it. Running the Raft migration only once needs a new command and a versioned snapshot shape, so I left it out of this PR: #2106.

.await
}

async fn cas_dropped(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 Must address before merge — the dropped-ledger entry is one DynamoDB item, so dropping a ledger with roughly 1,000+ branches fails after it has already taken the ledger offline.

cas_dropped writes the whole DroppedLedger, every branch's NsRecord included, as one JSON attribute: I measured about 416 bytes per branch with a commit and an index CID, somewhat less without the index. DynamoDB caps an item at 400 KB. In drop_ledger this write is step 3, after step 1 has marked the binding Dropping and step 2 has frozen every branch.

I ran it on LocalStack: 1,500 branches, each with a commit head, then a soft drop. It failed after 45.9 s with DynamoDB PutItem failed: service error (underneath, ValidationException: Item size has exceeded the maximum allowed size; a raw 410 KB PutItem returns exactly that). Afterwards the binding stayed Dropping, lookup("big:main") returned nothing, resume_drop_ledger failed the same way, and a create under the name was refused with "a drop is in progress". So the ledger is unreadable, unwritable and unrestorable, and nothing in the product gets it out. A hard drop writes the same entry (as Purging), so it fails the same way, and a restore's Restoring { fences } entry is bigger still, though that one fails before it claims the name.

The natural DynamoDB layout is the branch copies as their own items under the instance's partition (pk = @{instance}, sk = branch#{name}), with the entry item holding the rest; the minimum is to size the entry before step 1 and refuse the drop while nothing has been frozen. A small extra while you're here: storage_err formats the SDK error with {e}, which prints only "service error"; aws_sdk_dynamodb::error::DisplayErrorContext would have put the ValidationException in front of the operator.

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.

5c0c296: LedgerRegistry::max_dropped_entry_bytes (390,000 on DynamoDB, None elsewhere; every wrapper forwards it). A drop sizes its entry before it claims the name, and a restore before it marks the entry restoring; either is refused with TooLarge (400) while nothing has changed. A LocalStack test writes an entry just under the cap, so the cap leaves room under 400 KB. DynamoDB errors now go through DisplayErrorContext everywhere in the backend. The branch copies as their own items are #2104.

Comment thread fluree-db-nameservice/src/binding.rs Outdated
let mut resolved = Vec::with_capacity(records.len());
for record in records {
if !bindings.contains_key(&record.name) {
let binding = store.get_binding(&record.name).await?.map(|v| v.value);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 Should address — all_records now reads one binding per name, one at a time, on every backend.

read_all_resolved awaits get_binding for each distinct name inside the loop, so a listing pays one more sequential round trip per ledger: a consistent GetItem on DynamoDB, a GET on an object store. all_records serves GET /ledgers and the indexer's catch-up listing, and housekeeping adds list_bindings and list_dropped on the same tick (fluree-db-api/src/housekeeping.rs:157-215), which on DynamoDB (dynamodb/lifecycle.rs:550-600) is a GSI query followed by one consistent GetItem per hit, tombstones included, since a deleted binding keeps its kind.

At a few thousand ledgers on DynamoDB that's several thousand extra sequential reads per listing and roughly twice that per catch-up tick (every 300 s by default), and it grows with every name ever created. It isn't the query path, so I don't think it's critical, but the fix is cheap: collect the distinct names and read them with bounded concurrency (futures::stream::iter(..).buffer_unordered(16), the listing counterpart of what f6ce8c3d7 did for a single lookup), and on DynamoDB use BatchGetItem (100 keys a call, ConsistentRead supported) in list_bindings/list_dropped. If you agree, I'd rather see it in this PR than 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.

0fe1e91: read_all_resolved reads the distinct names' bindings 16 at a time, and DynamoDB's list_bindings/list_dropped use consistent BatchGetItem (100 keys a call, re-asking for unprocessed keys while a call makes progress, since a response caps at 16 MB). A LocalStack test lists 130 of each.

/// written before name bindings, as the server moves it on start.
fn open_nameservice(path: impl Into<PathBuf>) -> FileNameService {
let nameservice = FileNameService::new(path);
if let Err(e) = nameservice.migrate_blocking() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 Should address — fluree-search-httpd is now a process that upgrades the store, and its own search endpoint skips the suspension check.

open_nameservice runs migrate_blocking, so a search server on this release, started against a store a 4.2 server still uses, migrates it and retires ns@v2/ underneath that server. The upgrade guide's "List every process that touches the store" (docs/operations/upgrading-from-4.2.md:109) doesn't name it.

Separately, fae8f7fa0's suspension check runs in FlureeIndexProvider::checked_record, so a search that goes through the db is refused, but POST /v1/search here loads through FileIndexLoader/FileVectorIndexLoader, which never compare the index's source_instance with the source ledger's current instance. A client calling this server directly still gets the dropped ledger's documents as hits for the new ledger, which is the bug fae8f7fa0 fixed in-process. The check (check_source_instance in fluree-db-api/src/graph_source/source_instance.rs) only needs nameservice types (GraphSourceRecord, StorageRoot, legacy_instance), but it lives in fluree-db-api, which this binary has only as a dev-dependency; moving it down next to legacy_instance would let both loaders share it rather than grow a second copy. Or, if /v1/search is only meant to be reached through the db, the server's docs could say so. Small either way, and 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.

32f8cbb: the comparison moved to fluree_db_nameservice::source_instance, the db and the search server share it, and both loaders refuse a suspended index with 409 GRAPH_SOURCE_SUSPENDED (a new protocol code, which the db's remote search clients map to GraphSourceSuspended). The upgrade guide now lists the search server among the processes that touch the store.

- a ledger it creates is not bound, and this release does not see it;
- a ledger or branch it drops is not moved to the dropped list;
- a branch it creates is not listed;
- it can commit to a branch whose drop is in progress, since it does not check

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❓ Question — on DynamoDB a 4.2 writer can do worse than commit to a branch whose drop is in progress.

4.2's publish_commit conditions only on attribute_exists(#pk) AND #ct < :t, so once a ledger has been dropped and created again under its name, a 4.2 process still holding the old one commits into the new one (whose head starts at t 0): a commit whose blob sits under the legacy root and whose parent chain is the dropped ledger's. That's the cross-incarnation write this PR exists to stop, so I think it deserves its own bullet here.

And the design question behind it: the migration already rewrites every item to add fences, so did you weigh moving the head and index items to new sort keys at migration (or changing the meta item's kind)? A 4.2 commit would then fail attribute_exists(#pk) and a 4.2 lookup find nothing, the DynamoDB counterpart of retiring ns@v2/, and the IAM recipe below would become defence in depth rather than the only fence.

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.

Added the bullet in 3dbff6b. On the design question: I hadn't weighed it, and I think it's right, since it gives DynamoDB the same in-product fence file stores get. It touches every DynamoDB access path, the migration and the rollback story, so it's #2105 rather than this PR.

Comment thread fluree-db-api/src/lib.rs Outdated
@@ -4920,7 +4970,11 @@ impl Fluree {
// Step B: Lookup nameservice record

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 Must address before merge: refresh with a min_t answers from a dropped ledger's cached state, so a warm process keeps serving the old ledger under a name that now holds a new one.

The fast path just above (lib.rs:4958-4968) compares the cached t with min_t and returns Current before any nameservice read. That was safe while a name could only ever mean one ledger, but with this PR a soft drop (now the default) frees the name at once, and the ledger created under it starts again at t 1. The PR already knows heads of two activations aren't comparable (other_activation in ledger_manager.rs:2354, which this Step B → notify path goes through), but the fast path returns before any of that runs.

I reproduced it with two Fluree handles on one file store standing in for two processes: here caches p1db:main at t=3 (values old-1..3); elsewhere soft-drops it, creates p1db:main again and commits new-1 at t=1; here.refresh("p1db:main", RefreshOpts { min_t: Some(1) }) returns (3, Current), and a query through here returns ["old-1","old-2","old-3"] while the name holds ["new-1"]. With RefreshOpts::default() it does the right thing (Reloaded, ["new-1"]). It needs two processes on one store with no events between them, which is the shape of any multi-process embedder (solo's query Lambda calls refresh with min_t on every request carrying X-Fluree-Min-T), so a warm process whose cache predates a drop-and-recreate of that name answers with the dropped ledger's data, silently.

Minimally we could drop the fast path and always fall through to Step B (one nameservice lookup per refresh(min_t)). If that lookup matters, keep the fast path only when the caller can name the activation, e.g. RefreshOpts { min_t, instance } checked against LedgerHandle::instance_bits(). Either way a sibling of refresh_follows_a_ledger_created_under_the_name_elsewhere with min_t: Some(1) would pin it.

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.

2f840ed drops the fast path: refresh always reads the record, and a cached ledger that's still current answers Current through notify as before. refresh_with_min_t_follows_a_ledger_created_under_the_name_elsewhere is the min_t: Some(1) sibling, and fails with the fast path back.

//! `resolved_t` values and therefore new keys. Old entries age out
//! under TinyLFU eviction. There is no watermark-on-write channel.
//! A ledger dropped and created again under M's name starts its `t`
//! over, so the key carries M's instance too.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 Must address before merge: keying the governance cache by instance doesn't reach the data ledger's compiled-SHACL cache, so a model ledger recreated at the same t still has its predecessor's shapes enforced, or not enforced.

tx.rs:941-949 caches compiled shapes on the data ledger's LedgerState under CachedShapeSource::CrossLedger { model_ledger_id, graph_iri, resolved_t }, and tx.rs:1196-1203 probes it before the wire is translated. The governance cache now misses for the new model (new instance), but the fresh wire it produces carries an identical origin, so the compile cache hits and the dropped model's compiled shapes are used.

I ported #2052's recreated_model_ledger_shapes_replace_the_cached_compile onto this branch, with the now-default soft drop: M requires ex:name, D rejects a nameless ex:Person (compiled and cached), M is soft-dropped and recreated at t=1 with the shape deactivated, and the same write is still rejected; it passes once I disconnect_ledger(D). Flipped (old M lax, new M strict), D accepts a write the new M's shapes reject, which is the fail-open direction, and rejects it once D's state is evicted. recreated_model_ledger_policies_replace_the_dropped_ones passes because it only covers the governance cache.

#2052 (yours, open against main) fixes exactly this by putting the commit id into WireOrigin and the compile-cache key, so I'd land it first and take it here; git merge-tree shows four textual conflicts (cross_ledger/cache.rs, tests/it_policy_cross_ledger.rs, and the two governance docs). The alternative is adding the model's instance to CachedShapeSource::CrossLedger. Either way it belongs with this PR, since this is the PR that makes drop-and-recreate the everyday path (a plain fluree drop now frees the name). Commenting here because fluree-db-api/src/tx.rs is not in this diff at those lines.

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.

fb2a43c takes the second route: the shapes wire carries the model's instance and CachedShapeSource::CrossLedger keys on it. I ported #2052's test with a soft drop, and added the fail-open direction (a lax M cached, a strict M recreated at the same t). Both fail without the field. #2052 can land on main on its own; whichever key turns out redundant can go when main reaches next.

/// ([`LedgerState::instance_bits`](fluree_db_ledger::LedgerState::instance_bits)):
/// a ledger dropped and recreated under its name reaches the same `t`
/// again, and must not be answered with the dropped one's bundle.
pub instance: u128,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 Should address: two more process-wide caches are keyed by the ledger's name plus counters that start over with a recreated ledger, the same shape this field fixes for the schema bundle.

  • fluree-db-api/src/graphql.rs:842 ShapeCacheKey { ledger_id, index_t, shacl_epoch, schema_epoch } (a static LRU): both epochs are per-novelty counters that start at 0 (fluree-db-novelty/src/lib.rs:589-592), so a ledger dropped and recreated with different shapes after the same number of shape-affecting commits, before indexing, lands on the dropped one's compiled shapes, and the GraphQL schema is derived from them. That's the "drop, edit the shapes file, reload" loop.
  • fluree-db-query/src/eval/fulltext.rs:89 NoveltyCacheKey { ledger_id_hash, epoch, to_t, g_id, p_id, .. } (a static cache): the same for the fulltext novelty delta.

I haven't reproduced either at runtime, so take these as read off the code. They're the two left on #1962's list (the stats cache keys on content_version and is fine). GraphDb already carries instance_bits from f8e6257, so the GraphQL key is one field; the fulltext one could take the instance, or the binary store's root id. These are less severe than the SHACL one, but since this PR is what makes name reuse routine, I'd rather see them folded in here than left on #1962. Commenting here because graphql.rs and fluree-db-query/src/eval/fulltext.rs are 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.

6e236a8: the GraphQL key carries the instance, and the fulltext novelty key the binary store's store_id (the prepared-query cache next to it already keyed on it). Both reproduced: the GraphQL one with a closed shape after the same number of shape commits, and the fulltext one on a persisted store, where the recreated ledger scored 0.49 against 1.02 for the same data under another name. Both tests fail without their field.

- a create, import or archive restore that stopped is rolled back: its name is freed and what it wrote is deleted. One that is still running renews its claim on the name every minute, so a create is rolled back only once its claim has gone unrenewed for ten minutes, counted from when this node first saw it. A worker of that create still writing when it is rolled back can leave files behind; only the orphan sweep reclaims them;
- a branch create that stopped before confirming the branch is rolled back ten minutes after this node first saw it, which frees a dropped branch it was created from.

Only the node that owns catch-up runs the tick: never a peer, and under Raft only the leader. It runs only where background indexing is enabled.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Optional: it may be worth saying what happens where this tick never runs, because the stuck state reads like a name collision.

Housekeeping is installed only by fluree-db-server (state.rs:579), on the catch-up owner with background indexing on. The CLI on a local store, an embedder with indexing disabled, a server with --indexer-catchup-interval-secs 0 (only run_catchup_sweeps calls it, not the start-up sweep), and Lambda hosts (the two-tick observation lives in a process-local map, and nothing survives the response) never resume or roll back anything on their own.

I left a binding in creating, as an interrupted create leaves it, with no housekeeping: ledger_exists is false, ledger() is a 404 and all_records is empty, but create_ledger is a 409 LedgerExists("stuck") ("Ledger already exists: stuck"). name_taken (fluree-db-nameservice/src/lifecycle.rs:41-47) has a hint for Dropping but not for Creating. drop_ledger then rolls it back correctly, and docs/cli/drop.md says so, but nothing in the error points there.

Maybe a Creating arm in name_taken along the lines of "(a create is in progress or was interrupted; drop the name to roll it back)", and a sentence here that without the tick, drop finishes or rolls back any of these by hand, and purge/restore resume theirs. This is minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

de4eb05: name_taken has arms for Creating ("a create is in progress, or was interrupted: dropping the name rolls it back") and Restoring, and the configuration guide says where the tick never runs and how each interrupted operation is finished by hand.

/// Delete a dropped ledger's storage, then forget its registry entry.
/// Leaves the entry in `Purging` when any deletion failed, so purging
/// again finishes the job.
async fn purge_dropped_data(

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 purge stays inside its own ledger, including for ledgers stored the 4.2 way. The instance-root case is covered by purging_a_dropped_ledger_leaves_the_one_that_reused_its_name (I pointed purge_instance_root's listing at the name instead of the instance root and it went red, with two of its neighbours), so I tried the #1592 shape on the legacy fallback here: I soft-dropped the 4.2.1 fixture's legacydb (data at legacydb/), created legacydb again (data at legacydb/@01M4…/) with a dev branch, the legacy ledger's other branch name, reindexed it, then purged the legacy instance. 83 legacy files went, the new root's 37 stayed, both new branches read back after an eviction, and a dry-run orphan sweep found nothing. It might be worth keeping as a test next to it_legacy_store, since the fixture is already there.

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.

Kept as a test in 24f0dbf: purging_a_legacy_ledger_leaves_the_one_created_under_its_name. It fails if the legacy purge lists the whole name folder.

bplatz added 11 commits October 13, 2026 10:36
…me holds

refresh's fast path answered Current whenever the cached t met min_t,
before any nameservice read. A ledger created under the name since starts
again at t 1, so a warm process whose cache predated a drop and recreate
elsewhere kept answering with the dropped ledger. refresh now always reads
the record; a cached ledger that is still current answers Current through
notify, as before.
A data ledger caches the shapes it compiled from a cross-ledger model by
the wire's origin: model, graph and resolved t. A model dropped and
created again under its name starts again at the same t, so the dropped
model's compiled shapes kept being enforced, or kept being skipped. The
shapes wire now carries the model's instance, and the cache key with it.
… first

A dropped-ledger entry copies every branch record into one registry item,
and DynamoDB caps an item at 400 KB. A drop of a ledger with about a
thousand branches failed writing it, after marking the binding dropping
and freezing every branch: the ledger stayed unreadable and the name held.

LedgerRegistry reports the largest entry a store can hold (DynamoDB only).
A drop sizes its entry before it claims the name, and a restore before it
marks the entry restoring, and either is refused with TooLarge (400)
while nothing has changed. DynamoDB errors now carry their source chain,
so a ValidationException no longer reads as "service error".
A listing of records read each name's binding one at a time, so GET
/ledgers and the indexer's catch-up listing paid one more sequential round
trip per ledger. They are now read sixteen at a time. On DynamoDB,
list_bindings and list_dropped, which housekeeping runs on every catch-up
tick, read the items their index query finds with consistent BatchGetItem
calls instead of one GetItem each.
… the upgrade list

fluree-search-httpd loads BM25 and vector indexes through its own loaders,
which never compared the instance an index recorded with the ledger its
source's name holds now, so a direct POST /v1/search answered with a
dropped ledger's documents. The comparison moves to the nameservice crate,
the db and the search server share it, and the server refuses a suspended
index with 409 GRAPH_SOURCE_SUSPENDED, which the db's remote search
clients report as GraphSourceSuspended.

The search server also upgrades the store it opens, so the upgrade guide
now lists it among the processes that touch the store.
… ledger apart

Both are process-wide caches keyed by the ledger's name plus counters that
start over with a ledger created again under the name: the GraphQL shape
cache by index t and shape and schema epochs, the fulltext novelty delta
by novelty epoch and t. A recreated ledger with other shapes or other
novelty was answered from the dropped one's. The GraphQL key now carries
the ledger's instance, and the fulltext key the binary store's id, as the
fulltext prepared-query cache already did.
delete_record deleted every item one at a time, the per-commit commit#
items included: one per commit since the last index build, so unbounded
on a ledger that is not indexed, and a soft drop, the default, runs it
for every branch. Those items carry no fence and now go 25 to a
BatchWriteItem, through the same helper the commit-index prune uses; the
fenced items keep their conditional deletes, the meta item last.
The file and object-store backends' commit publication and commit-head
compare-and-swap each kept an arm that wrote a fresh, unfenced record when
none was there. The fence check before it refuses a missing record, so the
arm could not run; it now reads as what it is, a live record or a refusal,
and an unfenced record write is nowhere left to loosen into.
4.2's publish checks only that t moves forward, and a ledger created again
under a name starts again at t 0, so a 4.2 process holding the dropped
ledger can commit into the new one, with a parent from the dropped
ledger's history.
A create that stopped leaves its binding creating: the name reads as no
ledger, yet a new create under it was refused as "Ledger already exists".
The refusal now says a create is in progress or was interrupted and that
dropping the name rolls it back, and one held by a restore says so too.
The configuration guide says where the housekeeping tick never runs and
how each interrupted operation is finished by hand there.
…r its name

The 4.2.1 fixture's legacydb, soft-dropped, has a ledger created under its
name with the legacy ledger's branch name, in an instance folder inside
the same name's folder. Purging the legacy ledger deletes its files and
none of the new ledger's; both new branches read back and an orphan sweep
finds nothing.
@bplatz
bplatz merged commit 379af5e into next Oct 13, 2026
19 checks passed
@bplatz
bplatz deleted the feat/ledger-lifecycle branch October 13, 2026 15:48
bplatz added a commit that referenced this pull request Oct 13, 2026
Conflict resolutions:

- Cross-ledger governance: the cache key keeps both protections, main's
  model head (t and commit, #2052) inside next's instance-scoped key
  (#1980); docs describe both.
- Numeric threshold fast paths: `threshold_key_interval` keeps main's
  interval and NaN semantics and covers next's order-preserving families
  (all inline integer subtypes, double and float, inline decimals) through
  `encode_numeric_threshold_for_otype`, which is infallible now that every
  double has a key. The overlay count and the star top-k dispatch rows by
  family on those intervals.
- `rdf_term_equal` keeps next's triple-term equality; main's NaN handling
  replaces the early NaN return. Bound-object encoding keeps next's
  triple-term arm and main's every-double key.

Main's new tests adapted to next's lifecycle APIs: `genesis_ledger` is
awaited, ledgers once named as branches of one name (`mq:users`,
`special-doubles:write`, ...) are separate ledgers (`mq-users:main`), and
helpers read the content store by storage namespace and publish fenced.
The recreated-model-ledger tests are main's, which also cover two
instances sharing storage; next's same-scenario copies are dropped.
bplatz added a commit that referenced this pull request Oct 13, 2026
Brings in #1980's storage roots and namespaces and, through next's merge
of main, #2048's remote leaf fetch policy.

- Storage addressing is #1980's: content stores, sweeps and the sibling
  walk take `StorageNamespace`/`StorageRoot`. The disk-cache wrapper keys
  its coalesced fetches by the namespace's branch prefix.
- Cache directories stay gone: `plan_sweep`, the sibling walk, the
  orchestrator and `BinaryIndexStore` read through the backend's
  `CachedContentStore`, not an `artifact_cache_dir` threaded beside it.
- #2048's `RemoteLeafFetch::Whole` fetches a leaf whole on first open
  through `fetch_whole_leaf`, the path a store without ranged reads takes:
  the wrapper coalesces the GET and keeps the disk copy, and the leaflet
  cache keeps the bytes. Directory-only opens stay ranged, and a small
  leaf is served from its first read. `fetch_remote_leaf_whole` and
  `SharedLeafBytes` are gone with the cache-dir reader.
- #2048's whole-policy tests run over the wrapper instead of a store
  `cache_dir`, with the same counts.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants