Skip to content

feat: bulk import into a new named graph of an existing ledger - #2232

Merged
bplatz merged 10 commits into
mainfrom
feat/import-into-named-graph
Nov 4, 2026
Merged

bplatz merged 10 commits into
mainfrom
feat/import-into-named-graph

Conversation

@bplatz

@bplatz bplatz commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Fills a new named graph of a ledger that already has data and an index, using the bulk import pipeline. The rest of the ledger's index is not rebuilt. The feature is available from Rust, the CLI, the server and Python.

fluree graph import https://example.org/graphs/products --from products.ttl -l mydb

How it works

  • Commits. The import's commits continue the ledger's chain (t, db:previous), and every statement lands in the target graph. A full reindex from the commits gives the same ledger.
  • Term IDs. Existing IRIs and strings keep their dictionary IDs, and new ones are numbered above them. Joins between the existing graphs and the new one therefore work.
    • Seeded remaps are not monotone, so each chunk's sorted commit is renumbered by rank (relocalize_sorted_commit) before the SPOT merge.
  • Index. The bulk path builds the graph, which is then spliced into the ledger's index root. The import's txn-meta goes through the incremental indexer over that root (index_novelty, split out of incremental_index).
  • Concurrency. The ledger is indexed to its head first. Background indexing is held, and writes through the importing connection's cached ledger wait for the import; a writer that does not share it (another process or connection) is caught by the compare-and-set below instead.
  • Publishing. The state at the import's heads is loaded first, from the ledger's record with both heads replaced. Then, under the ledger's state lock, the commit head is published by compare-and-set against the starting head, the index after it, and the state is installed before the lock is released, as push_commits does. A fresh load never sees the new index under the old head, and this process's ledger cache never sees the new commit head without the state at it.
  • Failure. Losing the compare-and-set publishes nothing. A failure after it, an index publish that fails, is ImportError::PublishedWithoutIndex: the import is in the ledger, read from its commits until an index covers them (fluree reindex). The import logs its commit head and index root before publishing.
  • Dictionaries. Dictionary updates stream from disk (extend_dicts). The seeded vocabulary merges write their new terms to the run directory, sorted both by ID and by reverse key.
    • Each reverse tree is rewritten a leaf at a time into target-size leaves, and leaves that receive nothing keep their CIDs.
    • Forward packs are cut as they fill.
    • Peak memory stays flat with the number of new terms: about +85 MiB from 2M to 18M terms in the ignored stress_extend_memory, against +1.4 GiB at 6M with the incremental indexer's in-memory update. That update also splits an overgrown leaf only in two.
    • Forward-pack compaction moves into compact_forward_streams, shared by both paths. The incremental indexer's behaviour is unchanged.

Surfaces

  • Rust: fluree.import_into_graph(ledger, graph_iri).import(path), which returns the usual ImportBuilder.
  • CLI: fluree graph import <iri> --from <path>, with the same import options as create --from.
    • With --remote, a tracked ledger or a running local server, the file is uploaded and imported by the server. Otherwise the import runs in-process.
  • Server: the source-upload mint accepts "graph", and discovery advertises the new source-upload-graph mode.
    • An older server would ignore the field and create a ledger, so the CLI checks for the mode before uploading.
    • A bad graph IRI, a .flpack upload or a missing ledger is refused at mint, before the upload.
  • Python: Ledger.import_graph(graph, source), plus its async twin.

Behaviour changes

  • No refusal with indexing disabled. On a connection without background indexing (memory, without_indexing, Python indexing=False), a ledger whose head is ahead of its index is indexed before the import instead of refused.

  • Plain refusal messages. Refusals are ImportError::Refused and display as their message.

  • Typed Python exceptions. Python maps import errors to its typed exceptions by status. This covers create(source=...) too, and the exceptions are all still FlureeError subclasses.

  • Server-side source imports (create --remote --from, graph import through a server) import the uploaded file under its own name, so its blank nodes get the ids a direct import of that file mints; they were keyed on the upload id. A mint may carry "skolem_namespace" (discovery mode source-upload-skolem); the CLI forwards --skolem-namespace and refuses a server without the mode.

  • fluree graph drop / POST /drop-graph stage DROP GRAPH through the whole-graph scan, so a graph past FLUREE_MAX_GRAPH_SCAN_FLAKES (default 10M facts) is refused before it is read. The DELETE … WHERE they ran matched every fact first and met the novelty limit only at commit.

  • A ledger handle has a writer lock separate from its state lock (LedgerHandle::exclude_writers): the import holds writers off while queries keep reading.

Refused

  • A graph the ledger has registered, one emptied by graph drop included.
  • The default graph, including urn:default.
  • TriG and N-Quads sources, and JSON-LD that names its own graphs.

Not in this PR

  • Annotation arena. When the imported graph carries statement annotations, the ledger's sealed annotation arena is set aside (scan fallback) until a fluree reindex. The CLI says so after the import. A graph without annotations keeps the arena.
  • Single file over HTTP. Imports through the server take one file. A directory import runs in-process (--direct).
  • Graph indexes. As with a fresh import, the new graph gets no full-text or spatial arenas and no HLL sketch registers.
  • Writes during an import over HTTP. They wait for the import. A retryable 503 naming the import, for HTTP callers, is Writes during a graph import: a retryable 503 over HTTP instead of waiting #2259.
  • Dropping an imported graph. graph drop here is still one retraction per fact, under FLUREE_MAX_GRAPH_SCAN_FLAKES, so a graph larger than that cannot be dropped; and a dropped graph keeps its registration, so its IRI cannot take another import. Both are addressed in feat: DROP takes a graph and its history out of the ledger #2251, which is stacked on this PR.

Tests

  • fluree-db-api/tests/it_import_into_graph.rs (grp_import) covers:
    • A full import into an indexed ledger, checked against a reference ledger built by transactions.
    • Term sharing with the existing graphs.
    • Later writes indexing incrementally over the spliced root. This test runs the import on a spawned task, which pins the future's Send.
    • Refusals.
    • Indexing an unindexed ledger first.
    • The annotation arena, kept or dropped.
    • A ledger-cache notification made while the index publish is held finds the import installed, for an import of 1 commit (the cache's catch-up path) and of 6 (its reload path).
    • Upserts replacing imported values in the imported graph and the default graph, one staged while the import holds the ledger and one after it, read the same through the cached handle, a fresh load, an incremental index and a reindex.
    • An index publish that fails after the commit head moved: PublishedWithoutIndex, the graph readable from the commits, and a later write and a reindex on top.
  • fluree-db-indexer: unit tests for the seeded merges, relocalize_sorted_commit, new_terms and dict_extend. The dict_extend tests use multi-leaf trees with 512-byte leaves.
  • Server (flpack_import_integration): a graph source upload round trip, plus the refusals at mint.
  • CLI: graph_import_fills_a_new_graph_of_an_existing_ledger (in-process) and graph_import_runs_on_a_remote_server. The second also covers a server without the new mode.
  • Python: test_import_graph_adds_a_named_graph_to_a_ledger, on memory and file connections.

Each of these tests was checked against a deliberate break of the code it covers and fails without it. The breaks:

  • leaf cutting, range bounds and new class names;
  • the reverse-tree and forward-pack updates;
  • the server's graph dispatch and the CLI's graph field on mint;
  • indexing before the import;
  • publishing before taking the state lock (both notification tests read Reloaded), and loading the installed state from the old heads;
  • upserts treating imported subjects as absent;
  • the Send fix.

Follow-up: #2259

Pieces the bulk import needs to add a new named graph to a ledger that
already has an index, while keeping the ids of the ledger's existing terms.

- Seeded vocab merges (merge_subject_vocabs_seeded,
  merge_string_vocabs_seeded): terms already in the ledger keep their ids,
  looked up in batches against the existing reverse dictionaries; new terms
  are numbered above the watermarks.
- relocalize_sorted_commit: seeded remaps are not monotone, so a chunk's
  sorted commit no longer streams in global order. It renumbers the chunk's
  local ids by the rank of their global ids and rewrites the commit, its
  types-map sidecar, the remap files and the language remap.
- index_novelty: incremental_index split into resolve + phases 2-4, so a
  caller can run them over a root it built itself.
- apply_dict_novelty, predicate_sids, replaced_dict_cids,
  build_class_stat_entries_with, build_lang_remap_over and the disk-based
  numbig/vector arena uploads, extracted from their single callers.
fluree.import_into_graph(ledger, graph_iri).import(path) runs the bulk
import pipeline into a graph the ledger does not have yet, without
rebuilding the rest of the ledger's index.

- The import's commits continue the ledger's chain (t, db:previous), with
  every statement routed into the target graph. A full reindex from the
  commits gives the same ledger.
- Existing IRIs and strings keep their ids; new ones are numbered after
  them, so joins between the existing graphs and the new one work.
- The graph is built by the bulk path and spliced into the ledger's root;
  the import's txn-meta goes through the incremental indexer over that
  root.
- The ledger is indexed to its head first; background indexing is held and
  writes wait for the import. The commit head is published with a
  compare-and-set against the starting head, then the index.
- The sealed annotation arena is kept when the graph has no annotations
  and dropped (scan fallback until a reindex) when it has some.
- Refused: a graph the ledger already has, TriG and N-Quads sources,
  JSON-LD that names its own graphs, and, with indexing disabled, a ledger
  whose head is ahead of its index.
An import into a new graph of an indexed ledger held every new subject
and string in memory, then added them through the incremental indexer's
dictionary update, which also loads every reverse leaf it touches and
splits an overgrown leaf only in two. Fine for an index cycle's novelty;
at bulk scale it grows memory with the import and leaves huge leaves.

- The seeded vocab merges write their new terms to the run directory
  (run_index::NewTerms), sorted by id and so by reverse key too.
- extend_dicts streams them into the dictionaries: each reverse tree is
  rewritten a leaf at a time into target-size leaves, reusing every leaf
  that receives nothing, and forward packs are cut as they fill.
- Forward-pack compaction moves into compact_forward_streams, shared by
  both paths; the incremental indexer's behaviour is unchanged.
- The new graph's class stats name new classes from the new-subject file.

Peak memory of the dictionary update now stays flat with the number of
new terms (stress_extend_memory, ignored by default).
- CLI: `fluree graph import <iri> --from <path>`, with the same import
  options as `create --from`. With --remote, a tracked ledger or a local
  server running, the file is uploaded and imported by the server;
  otherwise it runs in-process.
- Server: a source upload accepts "graph" and imports into that graph of
  an existing ledger. Discovery adds the `source-upload-graph` mode, since
  an older server would ignore the field and create a ledger. A bad graph
  IRI, a flpack upload or a missing ledger is refused at mint, before the
  upload.
- Python: Ledger.import_graph(graph, source) and its async twin.
- With indexing disabled (memory connections, without_indexing), a ledger
  whose head is ahead of its index is now indexed before the import
  instead of refused.
- Refusals are ImportError::Refused, displayed as their message; Python
  maps import errors to its typed exceptions by status.
- The import future is Send again: extend_dicts' leaf prefetch borrowed
  through a closure argument, which kept it off a spawned task.
- Docs: graph import on the CLI, HTTP, Rust API and named-graph pages.
@bplatz bplatz added enhancement New feature or request area:server HTTP surface, routes, error mapping, swagger, timeouts/admission, config graph area:cli fluree CLI UX, rdf toolkit, publish/export/insert flows labels Nov 2, 2026
@bplatz
bplatz requested a review from a team November 2, 2026 01:07
…lank-node ids over uploads

- The import held the ledger handle's state lock, which query snapshots
  read, so every query waited for the whole import. A ledger handle now
  has a writer lock taken before the state lock: transactions hold both,
  and the import holds only the writer lock (exclude_writers) until it
  installs the new head. is_locked counts the writer lock, so an idle
  sweep cannot evict the handle mid-import.
- A branch forked from an indexed ledger starts on its parent's root,
  whose txn-meta and config graphs are named for the parent. The import
  names them for the importing ledger, so a later import loads the root
  an earlier one published.
- Source uploads take "skolem_namespace", advertised as the
  source-upload-skolem mode. The CLI forwards --skolem-namespace and
  refuses a server without the mode. The server imports a staged file
  under its own name, so its blank-node ids match a direct import of it.
drop_named_graph (fluree graph drop, POST /drop-graph) staged
DELETE { GRAPH <g> { ?s ?p ?o } } WHERE { GRAPH <g> { ?s ?p ?o } }, which
matches every fact in the graph with no ceiling and only then meets the
commit's novelty check. A graph of hundreds of millions of facts filled
memory before being refused. It now stages DROP GRAPH (Txn::drop_graph),
whose whole-graph scan refuses a graph past FLUREE_MAX_GRAPH_SCAN_FLAKES
before reading it, as SPARQL DROP and CLEAR already do.

@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 really nice, and at a design level no pushback from me. Continuing the chain, seeding the vocab merges against the published dictionaries, bulk-building the one graph and splicing it, and sending only txn-meta through the incremental indexer is pretty much exactly the shape I'd have hoped for. Claude traced #2230's dictionary-coverage invariant through the install and probed it, and it holds. The probes covered upserts into the imported graph and the default graph, through the swapped handle, a fresh load, an incremental index and a reindex, plus an upsert staged before the import.

The one thing I'd hold the merge for is the install at the end. The import publishes both heads and only then reloads and swaps the state, which push_commits avoids by building its state first and installing it through the guard it holds across the CAS (commit_transfer.rs:699-761). As written, the process's own cache listener sees the head move as a foreign writer and loads the import's commits back from storage. Details, and a fix Claude tried locally, are below.

On writes waiting while the import runs: I'm fine with that if you'd like to keep it, since it's the simplest contract, and it's documented and tested. One alternative I'd ask you to consider, entirely at your discretion: a write that arrives while an import holds the ledger could get the retryable 503 we already return for novelty at capacity (NoveltyAtMax / CommitContention, error.rs:718-759), naming the import, rather than waiting on the writer mutex for the whole run. That would match the existing precedent and tell the caller to retry, which an operator may prefer to having writes queue behind a long import (a waiting write behind a proxy otherwise just times out with no reason given). Either way, I'd only ask that the docs say the hold is per-process (more below).

Merge-order-wise, this sits on #2230 and needs retargeting to main once that lands; no CI has run on this head yet (ci.yml only runs PRs into main/next). One small cross-PR note: my #2227 has a "which paths do what" table for ill-typed literals, with bulk import as the one lenient path, and fluree graph import is a second bulk path that keeps them. Whichever of us lands second should add the row.

Full review below:


🔄 Request changes.

This is carefully built, @bplatz. The streaming dictionary extension in particular is really nice: target-size leaves, untouched leaves keeping their CIDs, and out-of-order or duplicate keys failing loud instead of corrupting a tree. The reference-ledger and reindex-equality tests make the whole thing easy to trust. The one blocking item is the install. Publishing both heads before installing the state makes this process's cache listener load the import's commits back into memory and reload the ledger a second time. It's about 40 lines to match what push_commits does, and I've checked that the tests stay green with it. Everything else below is optional.

Adherence to repo commitments:

  • Patterns/abstractions: ⚠️ Extends the bulk pipeline, the incremental indexer (index_novelty) and the dictionary update (compact_forward_streams is now shared); the one divergence is the install, which publishes and then reloads where push_commits prepares the state and installs it with the CAS.
  • Performance (speed first, memory second): ✖ No existing hot path regresses (lock_for_write adds one uncontended tokio::sync::Mutex per transaction; the incremental indexer's Phase 3 is extracted, not changed; graph drop does less work). On the new path, though, the post-import listener catch-up decodes up to the whole import into memory (blocking above).
  • Deployment targets: ⚠️ Shared fluree-db-api code reachable from the server, CLI, Python and embedders; excluded from wasm32. Evidence is single-process. The import runs synchronously inside the call and starts no background task, and a kill publishes nothing; the writer hold is per-process, so a write from another process fails the import at its CAS (safe, but the docs say writes wait).
  • Testing: ⚠️ The new tests are wired (grp_import, grp_proxy, CLI integration and server_memory, Python) and it_import_into_graph passes locally, but no CI has run on this head (stacked base), and nothing pins the install or an upsert into the imported graph.
  • Conventions: ✔ Multi-line commit bodies throughout; cargo fmt --check clean, and cargo clippy --all-targets -D warnings clean locally on the five crates this touches (default features; CI's --all-features run hasn't happened on this head).

Verified locally at branch HEAD: cargo test -p fluree-db-api --test grp_import (137/137, so the fresh-import path is fine too), the indexer's new unit tests (19 pass), clippy on the touched crates, plus five probe tests: upserts after import, an upsert staged during it, drop then re-import, and the listener after 2- and 6-commit imports. I also ran the candidate install fix against all of them (12/12, listener Noop).

Requesting changes just for the install: once that's in (and with whatever we settle on for writes during an import), I'm happy to approve. Happy to talk through any of these.

.await
.map_err(|e| ImportError::Storage(format!("publish index: {e}")))?;

// Writers held off resume on the new head.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Blocking (memory): the import publishes both heads before it installs its own state, so this process's cache listener treats the import as a foreign writer and loads the whole import back from storage.

import_into_graph CASes the commit head (:616) and publishes the index (:635) while the cached handle still holds the base_t state, and only then calls reload_state and swaps (:641-645). Each publish goes out on the local event bus. The cache listener skips a commit event only when handle.committed_t() >= commit_t (lib.rs:1700), which the import never advances, and it reconciles every index event, so it calls notify. notify reads the handle at base_t and the record at the import's head. With at most MAX_INCREMENTAL_COMMITS (5) import commits it plans CommitCatchUp and loads every one of them, flakes and all, outside any lock (ledger_manager.rs:2659-2675). It then waits on the writer mutex until the import installs, sees t moved, drops them and runs a full reload(). Past 5 commits it plans Reload, and if that reload's own lookup lands between the two publishes, it replays every import commit as novelty before the swap.

Concretely: a directory import is one commit per file, and files are never split, so importing three large Turtle files into a server's ledger ends, at the moment it succeeds, with the listener decoding every flake of the import into a Vec<Commit> on top of the import's own reload, and then reloading the ledger a second time. Claude caught this with tracing on the PR's own tests. Every import in it_import_into_graph is followed by plan=CommitCatchUp { gap: N }, then (with a temporary counter) loaded 2 commits, 17 flakes, outside any lock, which is the entire import, then state advanced concurrently, falling back to reload. In several runs the listener's lookup landed between the two publishes (ns_commit_t=4 ns_index_t=2), and a 6-file import planned Reload from inside that window. A fresh-ledger import never hits this, since its ledger isn't cached and notify returns NotLoaded; here the import caches the handle itself (:554-557).

The fix is to install with the publish, the way push_commits already does (commit_transfer.rs:699-761): build the post-import state before publishing, from the record you already hold with both heads replaced, take the state lock, CAS, publish the index, replace, release. The listener's state_metrics() then waits on the state lock for two nameservice writes and reads the new head (Noop), and readers of this handle never see the gap between the two refs. Roughly:

let prepared = match &handle {
    Some(_) => {
        let mut next = record.clone();
        next.commit_head_id = Some(result.commit_head_id.clone());
        next.commit_t = result.t;
        next.index_head_id = Some(root_id.clone());
        next.index_t = result.index_t;
        // LedgerState::load_with_store(<branched or plain store>, next)
        // + load_and_attach_binary_store, as reload_state does today
        Some(state_at(fluree, next).await?)
    }
    None => None,
};
let mut held = match writers {
    Some(writers) => Some(writers.lock_state().await),
    None => None,
};
// compare_and_set_ref(CommitHead) …; publish_index(…) …
if let (Some(handle), Some(guard), Some(state)) = (&handle, held.as_mut(), prepared) {
    handle.sync_binary_store_from_state(&state).await;
    guard.replace(state);
}

Claude tried this locally: all 7 tests in it_import_into_graph still pass, and every post-import notify plans Noop, including the runs whose lookup still lands between the publishes. A test that holds the cached handle through an import and asserts no catch-up or reload follows would pin it.

Commenting here because the listener in fluree-db-api/src/lib.rs and the notify catch-up at ledger_manager.rs:2648-2711 are outside this diff's hunks.

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 942b5fc

Some(_) => Some(fluree.ledger_cached(&alias).await?),
None => None,
};
let writers = match &handle {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is more of a question than a suggestion, and not a blocker. The exclusion here, and hold_quiesced just above it, is per-process. For an embedder that runs several processes over one storage (concurrent AWS Lambda invocations, say, or a direct CLI import next to a second server), another process's write isn't held off at all; the CAS at :616 is what catches it, after the whole import has run, with "nothing was published".

That fails safe, which is the right failure, but docs/cli/graph.md:86 and docs/getting-started/rust-api.md:197 say writes wait without qualification. I wonder if we should say there that the hold is per-process, and that a write from elsewhere makes the import fail at the end (the CLI already routes through a running local server for exactly this reason, which might be worth the same sentence). 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.

Addressed in 9655d90. The hold turned out to be scoped to the importing connection's cached ledger, not the process: another connection, or one built without ledger caching, isn't held either, so the docs say that.

id: Some(result.commit_head_id.clone()),
t: result.t,
};
match publisher

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.

I don't think there's a way around this one with two separate refs, so it's more an observation with a small ask. If the process dies, or the future is dropped, between this CAS and the publish_index at :635, the ledger is left with its commit head the whole import ahead of its index, and every later load replays the import as novelty until a fluree reindex.

The window is short, but it's routinely open long enough for the in-process listener to read a record inside it (see the blocking comment). Maybe log the new root_id at info before the CAS, and add a sentence to the graph-import docs that a crash at publish is recovered by fluree reindex? 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.

Addressed in 942b5fc (the log before publishing, and ImportError::PublishedWithoutIndex for an index publish that fails after the commit head moved, with a test) and 9655d90.

Comment thread docs/cli/graph.md Outdated

`fluree graph import` runs the bulk-import pipeline of `fluree create --from` over a ledger that already exists:

- **The graph must be new.** Every statement in the source lands in `<IRI>`, which the ledger must not have yet. Importing into a graph that already holds data is refused.

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.

Not a big deal, but this says a graph "that already holds data" is refused, while the check at graph_import.rs:720 refuses any graph the ledger has registered, which includes one emptied by graph drop (the drop keeps its g_id). Claude checked: import, drop_named_graph, index, then import the same IRI again → "already has the graph".

That's the right refusal technically (splicing over a g_id that has history would lose it). But together with graph drop now refusing graphs past FLUREE_MAX_GRAPH_SCAN_FLAKES (this PR's last commit), it means a big imported graph can't be dropped, and a dropped small one can't be re-imported under its IRI. We may want this line to say "a graph the ledger has registered, even one emptied by graph drop", plus a sentence on the way back out (a fresh IRI, at least). 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.

Addressed in 9655d90

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.

The two limits this leaves, a graph past FLUREE_MAX_GRAPH_SCAN_FLAKES that can't be dropped and a dropped IRI that can't take another import, are addressed in #2251 (stacked on this PR): DROP no longer scans the graph, and an_import_refills_a_dropped_graph covers the re-import.

}

#[tokio::test]
async fn later_writes_index_incrementally_over_the_spliced_root() {

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.

Totally optional: later_writes_index_incrementally_over_the_spliced_root inserts into the default graph after the import, but nothing upserts into the imported graph. Claude ran that as a probe and it passes. The probe upserted ex:widget1 and ex:bolt in the graph and ex:alice in the default graph, added new subjects in both, and checked through the swapped handle, a fresh load, an incremental index and a reindex. An upsert staged before the import also gets restaged and retracts the imported value.

So this is just regression-proofing. It's the path #2230's dictionary-coverage invariant guards, and the install fix above changes how that state gets built. If you agree it's worth it, 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.

Addressed in 942b5fc

Base automatically changed from perf/large-update-write-path to main November 3, 2026 22:34
…commit head says so

The import published both heads and only then reloaded and installed the
state. This process's ledger cache, notified of the import's commits in
between, saw the commit head move past the state it held: with up to five
commits it loaded every one of them, flakes and all, then found the state
advanced and reloaded the ledger; with more it reloaded straight away,
replaying the import as novelty if its lookup came before the index
published.

The state at the import's heads is now loaded first, from the ledger's
record with both heads replaced (`LedgerState::load_record`, which `load`
uses too, keeps the branch-aware store). The commit-head CAS and the index
publish then run under the handle's state lock, and the state is installed
before it is released, as `push_commits` does. A notification, or a query
snapshot, waits on the lock and reads the new head.

Losing the commit-head CAS still publishes nothing. A failure after it is
now `ImportError::PublishedWithoutIndex { t, .. }`, not a storage error:
the import is in the ledger, read from its commits until an index covers
them. The cached handle keeps its state, which the next write reconciles on
losing its own CAS. Before publishing, the import logs the ledger, graph,
commit head and index root (`publishing graph import`), so a stop between
the two publishes leaves them in the log.

Tests, with `PausingNameService` (now in `grp_import` too) holding or
failing the index publish:
- a notification made while the index publish is held, for an import of
  1 commit and of 6, finds the import installed (`Current`); with the lock
  taken after publishing, both are `Reloaded`, and with the state loaded
  from the old heads both fail;
- upserts replace imported values in the imported graph and the default
  graph, one staged while the import holds the ledger and one after it,
  read the same through the handle, a fresh load, an incremental index and
  a reindex; treating imported subjects as absent fails it;
- a failed index publish returns `PublishedWithoutIndex`, leaves the
  commit head at the import and the index before it, reads the graph, and
  a write through the importing connection and a reindex follow it.
… leaves

The writer hold covers writes through the connection running the import,
not every writer: another process over the same storage, another
connection, or one without ledger caching is caught by the commit-head CAS
instead, failing the import with nothing published. The docs said writes
wait without that qualification.

`graph.md` gains what a failure leaves: nothing until the last step, and
an import that is in the ledger, read from its commits until `fluree
reindex`, when its index does not publish. The server contract tells
implementers to report `PublishedWithoutIndex` as it is. The "graph must
be new" rule names a graph `graph drop` emptied, which keeps its
registration, and the way around it, a new IRI.
@bplatz

bplatz commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Kept writes waiting during an import; the body lists a retryable 503 for HTTP callers under Not in this PR. For #2227's ill-typed-literals table, whichever of the two lands second adds the row for this import path.

…error

`statements` skipped the imported graph on any query error whose message
contained "not found", meant for a ledger that does not have the graph
yet. A storage error reading the graph's index ("not found" for a blob)
read as the graph being absent, so a comparison failed with every row of
the graph gone and the cause discarded, as
`import_fills_a_new_graph_of_an_indexed_ledger` did once in CI after its
reindex and has not since, locally or there. It now skips only
`ApiError::GraphNotFound` for that graph, so such a failure reports its
error.
@bplatz
bplatz merged commit e30d163 into main Nov 4, 2026
19 checks passed
@bplatz
bplatz deleted the feat/import-into-named-graph branch November 4, 2026 01:24
bplatz added a commit that referenced this pull request Nov 4, 2026
…runs does

`fluree graph import` (#2232) fills a new graph of an existing ledger
through the bulk import pipeline, so it keeps a typed literal whose
lexical form does not fit its datatype as text under that datatype, as
`fluree create --from` does. `create.md` and `turtle.md` named
`create --from` as the one lenient path; they now name both, and the
graph import section of `graph.md` says it.
bplatz added a commit that referenced this pull request Nov 4, 2026
Brings #2247, #2232, #2246, #2248, #2245, #2230, #2205, #2231, #2255,
#2219, #2209, #2207, #2190, #2216, #2186, #2215, #2213, #2184, #2210,
#2206, #2198, #2187, #2183, #2200, #2193, #2199, #2196 and #2145 into next.

Resolutions:
- Novelty: main's fact-state trim (a cutoff plus a bounded sweep) and the
  dictionary's coverage watermark sit on next's graph slots and per-graph
  OrdMaps. A commit's reification links count toward coverage. Planner
  stats from segment sums decline under annotations, whose link deltas
  only the walk counts, and otherwise carry the indexed link counts.
- Stats-view identity: the index root's id reaches the snapshot through
  next's root decoder (`decode` takes the id, as `take_snapshot_metadata`
  does). `LedgerState::load_record` has a decoding-root form beside
  `load_decoding_root`.
- Transact: #2184's parallel-relationship check runs in next's link
  cascade, counting the `rdf:reifies` links on the retracted edge that the
  transaction does not retract itself. Main's bundle `edge_reifiers` is
  dropped, and `subjects_with_prior_rows` and
  `enforce_single_target_reifiers` stay deleted. The upsert pre-check
  takes main's dictionary probe and bounded seek.
- Query: geo search resolves the graph's POST tree once at open (pooled
  graphs keep their filter), an empty manifest when there is none.
  `branch_or_none` reads the dedicated branch, and the batched joins keep
  next's pooled lanes. The stats-view key hashes the root id.
- Indexer: `apply_dict_novelty` and `compact_forward_streams` take the
  cycle's compaction budget, so the term dictionary keeps its reserved
  share. `Prefetched` holds `ContentBytes`. `relocalize_sorted_commit`
  rewrites next's 20-byte types records.
- Disk cache: main's in-flight write registration, with an empty entry
  still read as crash debris that a write replaces. The process-wide
  eviction walk stays removed.
- Graph import (#2232): fenced CAS and publishes, the seed carries the
  record's namespace and fence, 32-bit graph ids and next's loaders. An
  import into a graph of an existing ledger refuses triple terms and edge
  annotations: the splice merges no triple-term dictionary yet.
- Iceberg: `create_iceberg_graph_source` goes with main (a source needs a
  mapping); the R2RML path keeps next's `model_instance`.
- CLI: main's shared import flags without the leaflet flags; `graph
  import` routes through next's process-wide server routing, and
  `upload_source_import` serves next's `Destination`. Doc sources read a
  ledger through the command's open instance.
- Tests: sibling ledger ids become distinct names, `genesis_ledger` is
  awaited, Cypher state dumps include each relationship's `rdf:reifies`
  link, and the graph-import arena test checks the refusal instead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli fluree CLI UX, rdf toolkit, publish/export/insert flows area:server HTTP surface, routes, error mapping, swagger, timeouts/admission, config graph enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants