Skip to content

fix: parse ledger ids once at the edge and key everything by a typed id - #1958

Merged
bplatz merged 13 commits into
mainfrom
fix/ledger-id-normalization
Sep 29, 2026
Merged

bplatz merged 13 commits into
mainfrom
fix/ledger-id-normalization

Conversation

@bplatz

@bplatz bplatz commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1540

Follow-up: #1960
Follow-up: #1961
Follow-up: #1962

Why

A ledger id reaches Fluree in several spellings — mydb, mydb:main, acme/inventory (a remote mount), with optional @t:… time-travel and #graph suffixes. Normalization was done ad hoc in dozens of places with four different styles, most of them falling back to the raw string when parsing failed. Anything keyed by a ledger id — caches, maps, events, token scopes, storage paths — was keyed by whatever spelling happened to reach it. The same ledger could be missed in a cache, counted twice, authorized inconsistently, or resolved to the wrong storage namespace.

What changed

One grammar, three types (fluree-db-core).

  • LedgerId — canonical name:branch. Derefs to str for reading, but deliberately does not implement Borrow<str>: a map keyed by LedgerId cannot be looked up with an unparsed string, so a missed normalization is a compile error rather than a silent miss.
  • LedgerName — a bare ledger name, taken by whole-ledger operations (hard drop, sweep, the shared-dictionary namespace).
  • LedgerRef — a full address, [urn:fluree:]name[:branch][@spec][#graph].

The existing helpers (split_ledger_id, normalize_ledger_id, path prefixes) are rebuilt on this parser. The heuristic that treated any id containing / but no : as an already-built name/branch path is removed.

Parse at the edge, carry typed ids inward. Public Fluree methods, server routes, CLI arguments and every nameservice implementation parse once. NsRecord, LedgerSnapshot, nameservice events, the ledger cache, indexer job state and maintenance holds, worker registries, peer state, SSE filters, sync/tracking config and token scope sets are keyed by LedgerId. The storage-path functions that still take strings panic in debug builds when handed a non-canonical id; that tripwire caught two paths during this work, which are fixed here.

Fixed

  • Remote mounts: a branchless mount alias (acme/inventory) was treated as a name/branch path, so the ledger loaded from the wrong namespace and the proxy asked the origin for the wrong ledger (Remote mount: branchless lookup key poisons ledger load with legacy index-root addresses; failed load is cached until container recycle #1540). Proxy records are now always canonical.
  • Nested ledger names and cleanup: hard-dropping or sweeping test/db listed and deleted ledger test's shared dictionaries. Drop and sweep now reach only the ledger's own namespace, and skip the branch directories and shared namespace of ledgers whose storage nests under the one being cleaned. A branch drop that cannot list ledgers now fails before deleting anything, instead of keeping the files and purging the record that names them.
  • Nameservice listings: the file and storage backends guessed identity by splitting paths, which dropped or misidentified branches such as x.index, main.json, or release/v1. Those branches were invisible to the sets GC uses to decide what is live. Records now take identity from their content, and every backend (memory, file, storage, DynamoDB, raft, proxy, mount) returns canonical records. A record from an earlier release that the new grammar rejects no longer fails the listing for the whole node (see Behavior changes).
  • Authorization:
    • Connection-scoped SPARQL explain authorized only the fluree-ledger header, then explained the FROM ledgers.
    • Branch listing and merge/revert previews authorized the bare ledger name, then read any branch.
    • Token scopes are now parsed once at verification.
    • Every route authorizes the branch it actually reads.
    • Scope checks agree across spellings.
    • A SPARQL dataset that fails to parse is refused instead of skipping the scope check.
    • /whoami reports the scopes a token grants (mydb as mydb:main, invalid entries left out), and fluree token create refuses a scope that is not a ledger id.
  • One spelling everywhere:
    • SSE subscriptions such as ?ledger=mydb now receive mydb:main live events.
    • Peer freshness checks now find their watermarks.
    • The ledger cache's notify path now finds cached entries.
    • Indexer triggers and maintenance holds now agree on one job per ledger.
    • A vector index created with ledger: "docs" now auto-syncs.
    • Materialize tracking no longer creates a duplicate poller per spelling.
    • Raft graph-source lookups accept the branchless form.
    • CLI track/upstream lookups no longer miss on spelling.
    • Multi-query envelopes count mydb and mydb:main as one ledger.
    • A history FROM/TO range that spells the same ledger two ways is no longer rejected.
    • BM25, vector and SQL graph-source methods parse the id they are given, so sync_bm25_index("mysearch") acts on mysearch:main.
  • Time-pinned writes: transacting through a graph_at handle silently committed at HEAD. It is now refused.

Behavior changes

  • Ids with @ or # in the name, or more than one :, are rejected. The error names the input and the rule it broke (HTTP 400, whichever layer refuses it).
  • New branches may not contain / or #, end in .index/.snapshots, or be named commit/txn/index/config/blob. New ledger names may not contain such a segment or start with graph-sources. Existing ledgers and branches that break only these rules remain readable.
  • Records from earlier releases whose names contain @ or # are listed, synced, and kept by GC and drop, but no request can address them. A stored name with an empty or ./.. segment is skipped with a warning naming the record, because its storage path can alias another ledger's.
  • A branch containing / from before this change can share a storage prefix with a nested ledger (a:b/c and a/b:c both store under a/b/c/). Cleanup tells them apart; their token scopes stay separate.
  • A token scope of mydb means mydb:main; there is no whole-ledger scope. Branch listings show only the branches the token can read. Key rotation's --ledger mydb still covers every branch, as drop and sweep do.
  • Crate APIs take typed ids where they key state: IndexerHandle methods, LedgerManager, NsRecord::new, tracking and sync-config stores, BlockAccessScope.
  • Persisted spellings (sync config, worker dependencies) are read leniently and normalized on load. Content-addressed data and materialize watermarks are not rewritten.

Docs

  • Naming rules in docs/concepts/ledgers-and-nameservice.md, linked from the branch CLI and graph-identities references.
  • Token CLI and authentication docs: a bare scope means main, and no scope covers every branch.
  • /whoami scope reporting, and why a bare key-rotation scope covers every branch.

Testing

  • cargo nextest run --workspace --all-features: all tests pass except two forward-pack compaction tests that exceeded the 360s limit under full-suite load. In isolation they pass in the same time as on main (117s / 152s vs 117s / 151s).
  • cargo clippy --workspace --all-targets --all-features -D warnings and testsuite-sparql fmt/clippy are clean.
  • New regression tests cover the parser grammar, nameservice listing round-trips (these fail on main), nested-ledger drop and sweep, explain and branch-route authorization, scope equivalence across spellings, SSE subscription matching, worker dependency matching, raft graph-source lookups, multi-query ledger counting, and time-pinned writes. Where marked in the tests, each was checked to fail with its fix removed.
  • Review follow-ups (legacy ids, nested-ledger prefixes, drop listing, 400 mapping, graph-source ids, /whoami, mint-time scopes) each add a test that was checked to fail with its fix removed. Before merging main, the core, nameservice, indexer, consensus, storage-aws, CLI, API and server suites passed locally, apart from the same two compaction timeouts (pass in isolation) and rotation_runs_and_verifies_over_http, which failed once under load and passed alone and on rerun. After merging main, workspace clippy (native and wasm32), testsuite-sparql fmt/clippy, the ledger test group and the server suite pass; liveness_monitor_demotes_killed_follower failed once under full-suite load and passed alone five times and in its group.

Ledger ids reached the system in several spellings (`mydb`, `mydb:main`,
`acme/inventory`, with `@t:`/`#graph` suffixes) and were normalized ad hoc
in dozens of places, most falling back to the raw string on failure. Maps,
caches, events, token scopes and storage paths ended up keyed by whatever
spelling reached them, so the same ledger could be missed, double-counted,
or resolved to the wrong storage namespace.

Core now has one grammar and three types: `LedgerId` (canonical
`name:branch`), `LedgerName` (whole-ledger operations) and `LedgerRef`
(full address with time and graph selectors). `LedgerId` derefs to `str`
but does not implement `Borrow<str>`, so a map keyed by it cannot be
probed with an unparsed string. Ids are parsed at the edges — public API
methods, server routes, CLI arguments, nameservice entry points — and
carried typed inward. Storage-path seams that still take strings trip in
debug builds on a non-canonical id.

Fixed along the way:
- A branchless id with `/` (every remote-mount alias) was read as a
  `name/branch` storage path, so mounted ledgers loaded from the wrong
  namespace and the proxy asked the origin for the wrong ledger.
- Hard-dropping or sweeping a nested ledger (`test/db`) listed and deleted
  another ledger's (`test`) shared dictionaries. Drop and sweep also skip
  files owned by ledgers whose storage nests under the one being cleaned.
- Nameservice listings split paths to guess identity, dropping or
  misidentifying branches (e.g. `x.index`, `main.json`, `a/b`) from the
  sets GC uses to decide liveness; records now take identity from their
  content, and every backend returns canonical records.
- Connection-scoped SPARQL explain authorized only the `fluree-ledger`
  header while explaining the FROM ledgers; branch listing and merge/
  revert previews authorized the bare ledger name, then read any branch.
- Token scopes, SSE subscriptions, peer freshness watermarks, the ledger
  cache's notify path, indexer job state and maintenance holds, BM25 and
  vector worker registrations, materialize tracking, raft graph-source
  lookups, CLI tracked ledgers, and multi-query ledger counting now agree
  on one spelling of each ledger.
- Writing through a time-pinned `graph_at` handle silently committed at
  HEAD; it is now refused.

Stricter input: ids with `@` or `#` in the name or more than one `:` are
rejected with an error naming the rule broken. New branches may not
contain `/` or `#`, end in `.index`/`.snapshots`, or equal a storage
layout directory; new ledger names may not contain such a segment.
Existing ledgers and branches remain readable. A token scope of `mydb`
means `mydb:main`.

Fixes #1540
@bplatz bplatz added bug Something isn't working as expected breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section labels Sep 26, 2026
@bplatz
bplatz requested review from aaj3f and zonotope September 26, 2026 14:00
- Drop and sweep excluded a nested ledger's branch prefixes but not its
  `@shared/` dictionaries, which sit beside its branches. Exclude the
  nested ledger's whole name prefix instead.
- Creating or importing a ledger named its initial branch without the
  rules `create_branch` applies, so `db:main.index` or `db:release/v1`
  could still be created. Validate the branch there too.
- Re-tracking a materialize job under another spelling replaced its stored
  source/target, which key the persisted watermark. A re-track now only
  reschedules the existing job.

@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 very happy about the design direction of this PR. You'll see my Claude-assisted review below throws some red flags, but I think it's not so much the PR's effort/objective/design and has more to do with the coverage & promise fulfillment of the "become strict on create / become lenient on read (in case prior creations on older versions were not strict on create" promise. Full review below:


Two blocking findings, both narrow, and I think both are in reach.** Everything else here is me agreeing with the PR: the diagnosis is right, the grammar is right, and deliberately withholding Borrow<str> on LedgerId so a missed normalization becomes a compile error rather than a silent cache miss is the decision that makes the other 190 files tractable. That's the part I'd have most wanted to get right and it's right.

🔴 The upgrade path. read_record_at rebuilds each persisted record's identity through the new strict grammar (fluree-db-nameservice/src/storage_ns.rs:416, file.rs:359) and all_records() propagates with ? (storage_ns.rs:614), so one legacy record fails the listing for the whole deployment. The ids that trip it were creatable at the merge base — base validate_branch_name has no # check, and base create_ledger passes an unparseable name through verbatim. I patched a FileNameService record to rep@2026:main and to good:feature#1 and both turn all_records() into Err; the unmodified baseline is Ok(1). That makes "Existing ledgers and branches remain readable" untrue for this class, and the blast radius is wide: /ledgers and /nameservice/snapshot 500, sweep hard-errors, drop returns success having deleted nothing, and startup preload is skipped node-wide. The PR already has the pattern this wants — "persisted spellings … are read leniently and normalized on load" — it just isn't applied to the nameservice.

🔴 The nested-ledger exclusion in commit a6a9b4983. Keying foreign on id.name() (fluree-db-indexer/src/gc/sweep.rs:391, fluree-db-api/src/admin.rs:1510) means a ledger named exactly {parent}/{branch} produces the exclusion prefix fluree://mydb/main/, which is mydb:main's own branch directory. validate_ledger_name("mydb/main") is Ok today, so this is creatable. In a plan_sweep repro the parent's own dead index root goes from 1 orphan to 0 the moment such a record exists, and the drop half returns success with a "Kept N file(s)…" warning. It fails safe on deletion, but a hard drop that silently retains everything is its own compliance problem. Excluding id.path_prefix() plus id.ledger_name().shared_prefix() instead of the whole name still closes what commit 2 was closing.

Beyond those: the DynamoDB backend .ok()?s the same legacy record instead of erroring (fluree-db-storage-aws/src/dynamodb/mod.rs:304,:382), so three backends now behave three different ways on one input — and the vanishing case is the one the comment above storage_ns.rs:614 warns against. The storage_ledger_id debug tripwire asserts canonicality but guards a function that accepts a branchless id, so a valid mydb panics in debug and works in release. And this is a breaking-change-labelled PR with zero .md files touched, while docs/cli/token.md:38-39 and docs/security/authentication.md:106,115 still describe the pre-change scope model.

The rest I chased and could not break, so recording it as checked rather than assumed: parse_scopes fails closed on every path I could find (an all-malformed token passes has_storage_permissions() on the raw payload and then authorizes nothing, and an empty set never reads as "all"); every route in routes/mod.rs that takes a ledger authorizes the ledger it reads; all three claimed route fixes are real (explain now authorizes the header ledger and the FROM dataset, branch listing filters per-branch record and 404s when nothing is readable, and authorize_sparql_dataset propagates the parse error instead of if let Ok(..)); LedgerId::ledger_name() cannot forge a LedgerName that LedgerName::parse would reject; SPARQL USING/USING NAMED resolves against the target ledger's own graph registry, so the QueryBody::Update gap in sparql_dataset_ledger_ids isn't reachable; and the /-as-name/branch heuristic is genuinely gone everywhere I looked.

One process note, no anchor for it: the PR is currently mergeStateStatus: DIRTY against main, so it'll want a merge before the stack can move. CI on 6d341e61e is real and green — 16 check-runs including test, clippy, fmt and testsuite-sparql — so the green here does mean something, unlike the older Graphite-era stacks.

Adherence to repo commitments

  • Patterns / abstractions — ✔ Extends the shared model rather than bolting on a parallel one; LedgerName/LedgerId/LedgerRef is one grammar and the existing helpers are rebuilt on it. The lenient-on-load pattern the PR states for persisted data is the one place it isn't applied consistently (CRITICAL-1).
  • Performance (speed first, memory second) — ✔ No degradation risk found. LedgerId is Arc<str> + a usize, so clones are refcount bumps and name()/branch() are subslices; parsing lands at request edges that already allocate and then do IO. Nothing new in an operator or per-flake loop.
  • Testing — ⚠️ The new regression tests are real, well-targeted and several of them fail on main as claimed. But neither blocking finding has a test: no case covers a persisted id the old grammar allowed, and a_nested_ledgers_files_are_never_orphans uses a deeply nested name (mydb/main/index/child:main) that happens to dodge the collision, so the {parent}/{branch} shape is untested.
  • Conventions — ✔ on code: self-describing subjects, substantial multi-line bodies, clippy and fmt green in CI. ✖ on docs: a breaking-change PR that redefines a token scope with no .md change (MEDIUM-6).

Comment thread fluree-db-nameservice/src/storage_ns.rs Outdated
// Convert to NsRecord, parsing persisted CID strings
let mut record = NsRecord {
ledger_id: format_ledger_id(ledger_name, branch),
ledger_id: LedgerId::from_parts(&main.ledger.id, &main.branch)?,

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.

🔴 CRITICAL-1 — a legacy id the old grammar allowed makes all_records() fail for the whole deployment

(in-diff range 397-419). Twin at fluree-db-nameservice/src/file.rs:359.

This one is blocking, and it contradicts the "existing ledgers and branches remain readable" line in the PR body.

read_record_at rebuilds each record's identity with LedgerId::from_parts(&main.ledger.id, &main.branch)?, and all_records() propagates that with ? at storage_ns.rs:614. So the strict grammar is applied not just to input but to every record already on disk, and a single bad one takes down the entire listing rather than itself.

The ids in question were creatable at the merge base. Base split_ledger_id rejects only an empty name/branch and a second : — a @ anywhere in the name sails through. Base validate_branch_name checks :, @, NUL and .. but has no # check, so create_branch(db, "feature#1") was legal. And base create_ledger is normalize_ledger_id(id).unwrap_or_else(|_| id.to_string()) (fluree-db-api/src/ledger/loading.rs:144), which passes an unparseable name through verbatim as the ledger's identity.

I reproduced it against FileNameService by patching a v2 record on disk:

baseline               -> Ok(1 records)
name "rep@2026"        -> Err(Invalid ID format: Invalid ledger id 'rep@2026:main': ledger name cannot contain '@')
branch "feature#1"     -> Err(Invalid ID format: Invalid ledger id 'good:feature#1': branch cannot contain '#')

Blast radius from the all_records() call sites: GET /v1/fluree/ledgers → 500 (routes/ledger.rs:585), GET /v1/fluree/nameservice/snapshot → 500, the _ledgers system query, key rotation, sweep hard-errors, drop silently deletes nothing and returns success (admin.rs:1506 → return (0, warnings)), and startup ledger preload is skipped for the whole node. An operator gets no signal that points at the offending record.

On the fix — the PR already has the right pattern and just didn't apply it here. The body says "persisted spellings (sync config, worker dependencies) are read leniently and normalized on load"; the nameservice read path needs the same treatment. Something like a LedgerId::parse_persisted that accepts what the old grammar produced, used only by the record-reconstruction seams, keeps creation strict while letting an existing deployment boot. Note that simply skipping the record is the wrong answer here — the comment above storage_ns.rs:614 explains why ("callers that decide what to delete treat a missing branch as one with nothing to protect"), and that reasoning is exactly right.

Whatever the shape, a branch named feature#123 is plausible enough that I'd want either the lenient read or a migration before this lands.


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 d847843. Every backend now rebuilds a stored record with LedgerId::from_persisted_parts, which accepts the @ and # older releases allowed. Those records are listed, synced, and kept by GC and drop; no request can address them. A stored name with an empty or ./.. segment is skipped with a warning naming the record, because its storage path can alias another ledger's. The new tests patch records on disk the way your repro did.

Comment thread fluree-db-indexer/src/gc/sweep.rs Outdated
let foreign: Vec<String> = nested
.iter()
// The whole name: its branches and its `@shared/` namespace alike.
.map(|id| format!("fluree:{method}://{}/", id.name()))

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.

🔴 CRITICAL-2 — commit 2's nested-ledger exclusion swallows the parent's own branch directory

(in-diff range 357-422). Twin at fluree-db-api/src/admin.rs:1510.

nested_ledgers() returns every ledger whose name extends {parent}/, and both sweep and drop turn each one into the exclusion prefix fluree:{method}://{id.name()}/. When a ledger is named exactly {parent}/{branch}, that prefix is the parent's own branch directory.

Concretely: parent mydb:main stores at mydb/main/index/… and mydb/main/commit/…. A ledger named mydb/main produces the foreign prefix fluree://mydb/main/, which prefixes every one of those. The filter at sweep.rs:393 and the partition at admin.rs:1543 then classify all of the parent's files as belonging to a nested ledger and keep them.

The trigger is creatable today. RESERVED_LAYOUT_SEGMENTS (fluree-db-core/src/ledger_id.rs:641) is ["commit", "txn", "index", "config", "blob"], so validate_ledger_name("mydb/main") is Ok — I asserted that in the repro. The doc comment just above that constant shows the case that was reasoned about ("ledger x/main branch index lives at x/main/index/"), which is the nested ledger's branch colliding with a layout directory. What isn't covered is the nested ledger's name being the parent's branch directory.

Reproduced with a plan_sweep unit test:

AJ-C baseline orphans=1 contains_parent_orphan=true
AJ-C nested = ["mydb/main:trunk"]
AJ-C with-nested orphans=0 contains_parent_orphan=false

It fails in the safe direction — nothing is deleted that shouldn't be — but a hard drop that reports success while retaining every file is its own problem in a retention or right-to-erasure context, and the only signal is a "Kept N file(s) …" warning.

The fix looks like it wants to be the nested ledger's actual prefixes rather than its whole name:

let foreign: Vec<String> = nested
  .iter()
  .flat_map(|id| {
      [
          format!("fluree:{method}://{}/", id.path_prefix()),
          format!("fluree:{method}://{}/", id.ledger_name().shared_prefix()),
      ]
  })
  .collect();

That still closes what commit 2 set out to close — the @shared/ dictionaries sitting beside the nested ledger's branches, which path_prefix() alone missed — without claiming the parent's own directory. nested_ledgers already iterates every NsRecord, so every branch of the nested ledger is represented.


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 8519b4d. Sweep and drop now share nested_prefixes, which excludes each nested branch's path_prefix() and the nested ledger's shared_prefix(), as you suggested. The new test uses a nested ledger named mydb/main. The same commit also makes a drop that cannot list ledgers fail before deleting anything; before, it kept the files and then purged the record that named them.

// Identity from the name/branch attributes; `pk` only when an item
// predates them.
let ledger_id = LedgerId::from_parts(&name, &branch)
.or_else(|_| LedgerId::parse(pk))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 HIGH-3 — the DynamoDB backend silently drops the record the other two hard-fail on

(in-diff range 298-312). Same shape at :382 for graph sources.

LedgerId::from_parts(&name, &branch).or_else(|_| LedgerId::parse(pk)).ok()? returns None on a legacy id, so the record vanishes from all_records() rather than erroring.

Three backends now disagree about the same data: storage and file hard-fail the whole listing (CRITICAL-1), DynamoDB makes the record disappear. The vanishing case is arguably the worse of the two, and it is precisely what the comment above storage_ns.rs:614 says must not happen — nested_ledgers() won't list it, hold_ledger_for_maintenance won't hold it, and a sweep of the parent plans its files as orphans.

Whatever CRITICAL-1 settles on, I'd want all three backends to land on the same rule. This is a code read on my side, not a stood-up DynamoDB run — flagging that so it gets a second look rather than taken as established.


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 d847843. DynamoDB and raft now follow the same rule as the file and storage backends: @/# records are listed, and names whose path can alias another ledger's are skipped with a warning.

}

/// Portable storage path prefix `name/branch` (no `:` in storage paths).
pub fn path_prefix(&self) -> String {

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.

🟡 MEDIUM-4 — the debug tripwire is stricter than the function it guards

(in-diff range 77-501). The tripwire itself is fluree-db-core/src/address_path.rs:28-32, which is not in this diff.

storage_ledger_id asserts expect_canonical — which requires a : — and then calls LedgerId::parse, which happily applies DEFAULT_BRANCH to a branchless id. So a perfectly valid mydb panics in debug and test builds while working fine in release.

It's reachable from a request: POST /v1/fluree/bm25/sync {"index":"mysearch"} → load_bm25_manifest("mysearch") → content_store(&str) → storage_path_prefixes. And the PR itself adds graph_source_lookups_accept_the_branchless_spelling, so the two halves are arguing with each other.

I think the intent is "this must parse", not "this must already carry a branch" — if so, asserting parseability rather than canonicality is the one-line version. Commenting here because address_path.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 bc8be4d, though not by relaxing the tripwire: it had found a real missed parse. The BM25, vector and SQL graph-source entry points now parse the id once, so sync_bm25_index("mysearch") reaches storage as mysearch:main. The new test reproduces your bm25/sync case, and fails with the debug panic you saw when the fix is removed.

}

/// Portable storage path prefix `name/branch` (no `:` in storage paths).
pub fn path_prefix(&self) -> String {

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.

🟡 MEDIUM-5 — path_prefix() collisions are fenced for creation but not for authorization

(in-diff range 77-501).

LedgerId::parse("a:b/c") and LedgerId::parse("a/b:c") are distinct ids — distinct Hash, distinct Eq, therefore distinct token scopes — with the identical prefix a/b/c. Verified by unit test. Likewise a/b:main's @shared prefix (a/b/@shared) nests inside a:b's branch prefix.

validate_branch_name blocks / for new branches, so new-vs-new can't collide, and drop/sweep are admin-gated. The live exposure needs a legacy / branch plus a token scoped to it — at which point one storage namespace sits under two independent scopes. Commit 2 closes the cleanup half of this class; the authorization half has no guard and no test.

I don't think this needs code in this PR — but given the PR is already carrying a "behavior changes" section, a sentence saying that a pre-existing / branch and a nested ledger can share a storage prefix, and that scopes do not merge across that, seems worth having written down somewhere.


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.

Written down in the PR body under Behavior changes: a branch containing / from before this change can share a storage prefix with a nested ledger (a:b/c and a/b:c both store under a/b/c/); cleanup tells them apart, and their token scopes stay separate.

/// would place one ledger's files inside another's destructive prefix:
/// ledger `x/main` branch `index` lives at `x/main/index/`, which is
/// `x:main`'s index directory.
const RESERVED_LAYOUT_SEGMENTS: [&str; 5] = ["commit", "txn", "index", "config", "blob"];

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.

🟡 MEDIUM-6 — no docs, on a breaking-change PR that changes what a scope means

(in-diff range 633-668) — the new creation rules, as the closest changed line to where this belongs.

git diff --name-only <base>..HEAD | grep -c '\.md$' is 0.

The user-visible changes that currently have no doc anywhere: a token scope of mydb now means mydb:main and there is no whole-ledger scope; ids with @ or # or more than one : are a 400; the new branch and ledger name creation rules; branch listing switching from "403 the ledger" to "filter to readable branches". docs/cli/token.md:38-39 still reads --read-ledger <ALIAS> → "Grant data API read access to specific ledger", which now silently means one branch of it. docs/security/authentication.md:106,115 describes the old model too.

docs/reference/graph-identities.md:128 already recommends against @ and # in ids — that reads like the natural home for the new enforcement.


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 938e437. The naming rules are in docs/concepts/ledgers-and-nameservice.md, linked from the branch CLI docs and graph-identities.md, which now says @ and # are rejected. docs/cli/token.md and docs/security/authentication.md say a bare scope means its main branch and that no scope covers every branch.

/// would place one ledger's files inside another's destructive prefix:
/// ledger `x/main` branch `index` lives at `x/main/index/`, which is
/// `x:main`'s index directory.
const RESERVED_LAYOUT_SEGMENTS: [&str; 5] = ["commit", "txn", "index", "config", "blob"];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ NIT-7 — /whoami reports raw claim strings, not effective scopes

(in-diff range 633-668) — commenting here because fluree-db-server/src/routes/admin.rs is not in this diff.

parse_scopes drops an unparseable scope with a tracing::warn! and moves on (correct, and it fails closed). But /whoami (routes/admin.rs:223-228) echoes the raw claim, so a scope that was dropped still shows as granted, and the CLI (fluree-db-cli/src/commands/token.rs:85-107) doesn't validate --read-ledger at mint time either. An operator can mint a token, inspect it, see the grant, and have it authorize nothing — with the only signal in a server-side log line.

Minor and non-blocking — but if you agree it's right, I'd rather see /whoami report the parsed set than have it 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 46afbe0. /whoami now reports the scopes a token grants: mydb as mydb:main, invalid entries left out. fluree token create also refuses a scope that is not a ledger id.

/// would place one ledger's files inside another's destructive prefix:
/// ledger `x/main` branch `index` lives at `x/main/index/`, which is
/// `x:main`'s index directory.
const RESERVED_LAYOUT_SEGMENTS: [&str; 5] = ["commit", "txn", "index", "config", "blob"];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ NIT-8 — bare-name semantics now differ between token scopes and key rotation

(in-diff range 633-668).

A token scope of mydb means mydb:main — one branch. Key rotation --scope mydb still means the whole ledger (fluree-db-api/src/key_rotation.rs:259-266, whose own comment says "A bare name scopes the whole ledger"). Two surfaces, one spelling, two meanings, which is the exact class of thing this PR exists to remove. Worth either aligning or saying in the rotation docs why it's deliberately different.


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 deliberately, and now documented in ecf42d8. A bare rotation scope covers every branch, as drop and sweep do, because rotation acts on the ledger's storage, which its branches share. Token scopes govern reads, which target one branch.

/// would place one ledger's files inside another's destructive prefix:
/// ledger `x/main` branch `index` lives at `x/main/index/`, which is
/// `x:main`'s index directory.
const RESERVED_LAYOUT_SEGMENTS: [&str; 5] = ["commit", "txn", "index", "config", "blob"];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ NIT-9 — one claim, two parsings

(in-diff range 633-668) — fluree-db-server/src/extract/bearer.rs is not in this diff.

StorageProxyPrincipal.storage_ledgers became HashSet<LedgerId> (extract/storage_proxy.rs:38), but EventsPrincipal.storage_ledgers stayed HashSet<String> with a &str-taking is_storage_authorized_for_ledger (extract/bearer.rs:50,60). The method has no production call sites today, so nothing is broken — but it's a live &str scope comparison sitting in an auth type, which is what someone will reach for next. Either convert it with the rest or delete 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.

Addressed in 46afbe0. EventsPrincipal.storage_ledgers is now a HashSet<LedgerId> built with parse_scopes, like the storage proxy's, and is_storage_authorized_for_ledger takes a LedgerId.

Releases before the ledger-id grammar let `@` and `#` into ledger and
branch names. Rebuilding such a record with the strict grammar failed
`all_records()` for the whole node (ledger listing, GC, indexer catch-up,
preload, sync), while DynamoDB and raft dropped the record silently.

Record-rebuild seams now use `LedgerId::from_persisted_parts`, which
accepts those two characters and applies every other rule. The records
stay listed so GC, drop and sync account for them; no request can address
them. A stored name whose path can alias another ledger's (`/x`, `x/`,
`a/../b`) is skipped with a warning on every backend. Storage paths for a
legacy id match the ones it was written under, and `NsRecord` /
`GraphSourceRecord` deserialize them so sync peers accept an origin that
holds one. Request-edge parsing is unchanged.
…not list them

Sweep and drop excluded every file under a nested ledger's whole name. For
a ledger named `mydb/main`, that prefix is `mydb:main`'s own branch
directory, so a sweep planned none of the parent's orphans and a hard drop
kept every file. `nested_prefixes` now excludes each nested branch's
directory and the nested ledger's `@shared/` namespace, which still covers
the files the exclusion was added for.

A branch drop that could not list ledgers kept the branch's files and then
purged its nameservice record, leaving the files with nothing to name them.
The listing now happens before anything is deleted and its failure fails
the drop; a whole-ledger drop reuses the listing it already has.
`ApiError::InvalidLedgerId`, `InvalidBranch` and `NameService(InvalidId)`
had no arm in the HTTP status mapping and fell through to 500. They now
return 400 `err:api/BadRequest`, the same as an id refused at the edge.
The BM25, vector and SQL graph-source methods passed the caller's spelling
through to storage, so `sync_bm25_index("mysearch")` reached a storage path
without a branch and tripped the canonical-id check in debug builds. Each
public entry point now parses the id once.
`/whoami` echoed a token's raw ledger lists, so a scope that parses to
nothing still showed as granted. It now reports the parsed set: `mydb` as
`mydb:main`, invalid entries left out. `fluree token create` refuses a
scope that is not a ledger id instead of minting a token that lacks it.
The events principal's storage scopes are parsed like the storage proxy's.
Document the naming rules, what happens to ledgers created before them,
and that a bare-name token scope means its `main` branch. Correct the
claim that branch names can contain `/`, and restore `event_for`'s doc
comment, which the ledger-id helpers had split.
@bplatz

bplatz commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in ecf42d8

…zation

The server's error mapping keeps this branch's combined arm for invalid
ledger ids, invalid branches and invalid nameservice ids, which covers
main's new `InvalidBranch` arms. The Graph Store unauthenticated-read test
from main takes a typed `LedgerId`.
@bplatz
bplatz merged commit edfc21b into main Sep 29, 2026
16 checks passed
@bplatz
bplatz deleted the fix/ledger-id-normalization branch September 29, 2026 01:34
bplatz added a commit that referenced this pull request Sep 29, 2026
Main now rejects path-style ledger ids ("test/main") at storage seams in
debug builds (#1958). This branch's new query unit tests spelled their
snapshots that way; they now use "test:main", as #1958 did for the older
tests. The bench-list row in benches.md keeps main's longer
construct_formats entry and adds the two new benches.
bplatz added a commit that referenced this pull request Oct 11, 2026
The commits of #1958, #1963 and #1970 that this branch stacked on reached
next rebased, so files only they touched take next's reviewed versions.

Adapted to next:
- File compare-and-swap closures are now 'static (33f43b7): the fenced
  record, binding and registry writes own what they capture.
- A nested ledger owns its branches' directories and its @shared/, not its
  whole root (8519b4d): nested_namespaces replaces nested_roots, and
  nested_prefixes takes storage namespaces.
- Records rebuild their id with persisted_ledger_id (d847843), passed to
  NsFileV2::into_record.
- build and build_async run the ns@v3 migration before build_file; the
  async builder runs it without blocking.
- Merge, rebase and preview stores come from the record's storage
  namespace (branch_store, copy_commits).
- next's tests: stores from storage_namespace, fenced publishes, ledgers
  created rather than built from genesis, one ledger per name, and the
  arena drop test on a name-rooted ledger.

next's legacy-id listing tests are ported to the migration path and
ignored: a 4.2 store holding an `@` or `#` id fails the ns@v3 migration.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Remote mount: branchless lookup key poisons ledger load with legacy index-root addresses; failed load is cached until container recycle

2 participants