Repository navigation
Graph import carries annotations and triple terms on next - #2263
Conversation
…ctionary A bulk build over an existing ledger now continues its triple-term dictionary instead of starting one: - relocalize_sorted_commit renumbers a chunk's term table in place, so every link and inner term still names its entry by ordinal, and keeps a link record's ordinal while renumbering its subject. - intern_term_tables_over interns every chunk's term table before the build, innermost first, one batched reverse lookup per nesting level: a term the dictionary holds keeps its handle (TermDictBuilder::keep), a new one goes above the watermarks. - remap_term_entry is the one translation of a term-table entry through a chunk's remaps, shared by TermRemapCtx, the pre-pass and relocalizing. - TermDictBuilder::new_term_entries gives an incremental append's new terms; the incremental resolver uses it too.
An import into a new named graph of an existing ledger refused a source with edge annotations or triple terms, because its splice merged no triple-term dictionary. It now extends the ledger's: - the build interns the source's terms over the ledger's dictionary, so a triple the ledger already reifies or names keeps its term, and a query for it finds both graphs' annotations; - the new terms and watermarks ride the splice's txn-meta pass, which appends them to the dictionary's packs and reverse trees; - the root's link counts add the graph's, and the root is annotated when the graph is. A ledger whose index holds annotations from before links has no dictionary to extend and is refused before the source is read, naming the reindex that writes one. Tests cover annotations into annotated and unannotated ledgers, triple terms as values (nested, language-tagged, one the ledger holds), later annotations indexed incrementally over the spliced dictionary, the pre-link refusal, and a Cypher dump's edge properties through the CLI. The graph import docs drop the annotation-arena paragraph and two flags next does not have.
…ts in handle order A chunk's sorted commit orders a subject's triple-term objects by their ordinal in the chunk's term table. The SPOT build merges those streams after the ordinals resolve to handles, and a handle is not monotone in its ordinal: a term an earlier chunk interned, or one the ledger already holds, has the lower handle. Two links of one reifier then reached the leaf writer out of order, and a lookup bound to either one found nothing, though a scan listed both. A fresh import showed it whenever a later chunk's reifier linked a new term before an earlier chunk's; a graph import, whenever it linked a new term before one the ledger holds. The merge reader now re-sorts each run of records that differ only in their term before handing them out. Other orders are built from runs sorted after the remap and were not affected.
…tatements transacted
…N-LD does The test was written when SPARQL read only an RDF list's head, so it expected one list row per driving row and the batched wildcard lane to decline. #2217 has SPARQL read a list's members as values, as a JSON-LD query does: the query now reads the name and every member, takes the lane, and agrees with the generic lane and with the JSON-LD rows.
A JSON-LD document's named graph may be named by a blank node, as a TriG or N-Quads one may, and rdf::parse read those but refused the JSON-LD form, so rdf::serialize's own JSON-LD output of such a dataset did not read back. The JSON-LD adapter refuses the name for every writer, since a ledger names its graphs with IRIs; it now has to_dataset_events, the same walk letting a blank node name a graph, for a reader that only builds a dataset. Every write path keeps the refusal.
The test read a list through ex:list/rdf:rest*/rdf:first, which SPARQL matched before #2217. A list's cells are not triples SPARQL matches now: it reads the members as values of the property, as JSON-LD does, and the path finds nothing, as docs/query/sparql.md says.
a_reload_that_cannot_load_the_store_keeps_the_ledger_it_has published a rebuilt root, then hid a file of its store and reloaded. The connection's cache listener applies a published root by itself, so when it won the race the cached store already held that file's dictionary, the reload carried it over without reading the file, and the test saw the reload succeed. It failed that way on next's CI and under a parallel local run. The store now breaks before the root is published: neither the listener nor the reload can load it, whatever order they run in.
next already reads a JSON-LD graph named by a blank node (476c0f2): node_graph keeps the name, to_graph_events writes the graph under it, and the ledger writers refuse it through iri_named_graph. This branch's to_dataset_events (d0f6a8b) did the same for rdf::parse alone, so next's adapter and graph shape are taken and rdf::parse calls to_graph_events again. Its TriG round-trip case for a blank-node graph stays.
… next next's `p/rdf:rest*/rdf:first` reaches each member of the lists p holds (dd3d0f1), so the walk over a collection written from quads or from its text returns the members rather than nothing.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is nice, and at a design level I'm on board with interning the source's terms over the ledger's own dictionary before the build. Having remap_term_entry be the one translation that the pre-pass, TermRemapCtx and relocalizing all share is the right call too. Three headline notes:
(1) The new terms reach the dictionary through index_novelty's incremental reverse-tree update, which splits an overgrown leaf in two at most. That's the thing dict_extend says it exists to avoid for an import's subjects and strings. Claude reproduced it: a large import into an annotated ledger leaves term leaves that grow with N where a reindex cuts 2 MiB ones (details below). I don't think that part should merge as-is.
(2) This is the third time a merge stream has silently lost its order:
#1651 language ids (
f5b7d4eca); #2232 subject/string ids over an existing dictionary (e905972f9); this PR's term handles (9605f8d28)
Claude tried a one-line debug-build order check in KWayMerge::next_record. It catches this PR's instance, and it also fires today in the full rebuild's stats pass (pre-existing, on main too), whose V1 .fsc streams ignore the language that V2's comparator orders by. So not this PR: the point fix here is right. But the check plus a V2-ordered stats feed seems worth its own small effort, so the next one is a test failure instead of a lookup that quietly finds nothing.
(3) Thanks for settling the overlap with #2229 in the merge (e297c1b09): keeping next's shape from 476c0f2c0 means one blank-graph path instead of two, which is all I was after. Both blockers below were found at 275ec16eb, and the merge doesn't touch either: update_reverse_tree still splits in two, and advance_to_next still carries the grouping. The merge only widens the spool record to 42 bytes.
(Approving to unblock you because you've already been waiting on my review for over a week)
Full review below:
🔄 Request changes.
This is a really nice piece of work, @bplatz. Carrying a graph's terms over the ledger's own dictionary, rather than starting one per graph, is what makes an annotation in the new graph and one in the default graph annotations of the same triple. And the SPOT ordering fix is a genuine find that fresh multi-file imports on next needed too. There are two things I'd hold the merge for. The first is how the new terms get into the dictionary: they go through the incremental reverse-tree update, which leaves oversized term leaves after a large import into an annotated ledger (reproduced, details inline on graph_import.rs:333). The second is that the SPOT merge reader now runs about 35% slower per record for every bulk import, annotations or not (measured on the reader alone, details inline on spool.rs:1044). The fix is local, so I'd like that in too. The docs clause and the pre-link question are optional, and the KWayMerge order check is a heads-up for after this PR.
Adherence to repo commitments:
- Patterns/abstractions:
⚠️ The interning extendsTermDictBuilderand shares oneremap_term_entryacross the pre-pass, the build and relocalizing, which is the right altitude. The dictionary append, though, bypassesdict_extend, the streaming mechanism #2232 built for exactly an import's new terms. - Performance (speed first, memory second): ✖ CRITICAL on the new path: term reverse leaves grow with N (about 19 bytes × N each) after an import into an annotated ledger. On the existing path, every bulk import's SPOT merge reader runs ~8.4 ns/record slower with no triple terms in the source (23.6 → 32.0 ns, reader alone), and ~18 ns with half its records links. No query hot path is touched.
- Deployment targets:
⚠️ The changed indexer/API code reaches every native host (server, CLI, Python, embedders); graph import is excluded from wasm32. The evidence is single-process local storage. No host fence is violated, but the oversized leaves cost more where the content store is remote object storage (one large GET per cold lookup, one large PUT per rewrite). - Testing: ✔ Every new test runs on this head in CI (
grp_import,grp_triple_terms, CLIintegration), and the new ordering and pre-pass tests go red under mutation.⚠️ Nothing exercises the dictionary append at a size where leaves get cut. - Conventions: ✔ Multi-line bodies except
88adcf4e1(subject only), andfmt/clippyare green. The docs are updated, with one clause worth tightening.
Verified at 275ec16eb: CI is green on that SHA (test 16108/16108 with every new test listed by name, plus testsuite-sparql, clippy, fmt, python ×3 and wasm32). Claude also reproduced the oversized leaves on a clean box (400k and 1.5M annotated edges, against a reindex and a fresh import), mutation-checked the new ordering and pre-pass tests, and measured the merge reader with and without triple terms.
Just be sure to get the dictionary append cutting proper leaves, and the plain-import reader back to its old speed, before this merges; the rest is small.
| fulltext_string_bytes: HashMap::new(), | ||
| new_terms: Vec::new(), | ||
| term_watermarks: term_watermarks.clone(), | ||
| new_terms: graph.new_terms, |
There was a problem hiding this comment.
Blocking (performance, new path): the new terms reach the ledger's dictionary through the incremental reverse-tree update, which splits an overgrown leaf in two at most.
new_terms goes into index_novelty, and its Phase 3 (fluree-db-indexer/src/build/incremental.rs:1451-1531) updates both term reverse trees through upload_incremental_reverse_tree_async_terms → update_reverse_tree (fluree-db-binary-index/src/dict/incremental.rs:367-378). Each touched leaf is merged with its share of the new keys and, past 1.5× the 2 MiB target, split into exactly two. A graph import's new terms mostly carry new subjects, so their keys land in the leaf at the tail of their namespace's range, and that one leaf becomes two leaves of ~N/2 entries each. Subjects and strings avoid exactly this by going through extend_dicts a few lines up (:181), and dict_extend.rs's module doc names the reason: apply_dict_novelty "splits an overgrown leaf in two at most: right for one index cycle's novelty, not for an import that brings tens of millions of terms".
Claude reproduced it on a box. It imported 400k annotated edges (ex:p{i} ex:knows ex:q{i} {| ex:weight … |}) into a graph of a one-annotation ledger. The spliced root ended up with two 7.25 MiB subject-first leaves and two 7.25 MiB object-first leaves. fluree reindex of the same ledger, and a fresh import of the same file, each cut seven leaves of at most 2.24 MiB. One later annotation on a new subject, indexed incrementally, rewrote 7.25 MiB per tree. At 1.5M edges it's two 27.2 MiB leaves per tree against 25 leaves of at most 2.24 MiB after a reindex, the one-annotation cycle rewrote 27.2 MiB per tree, and a cold constant-term lookup took 19 ms against 11 ms after the reindex (local disk). The leaves grow at about 19 bytes × N, so a Cypher dump with 10M edge properties (annotated by default) would leave leaves of roughly 180 MiB. The lower one stays until a reindex or until a later cycle touches its range. Meanwhile every cold constant-term lookup into it fetches the whole leaf, and every index cycle that adds a term in its range rewrites it. An unannotated ledger doesn't hit this (no base tree, so the tree is built fresh with proper cuts), which is why annotations_import_into_a_graph_of_an_unannotated_ledger looks fine.
The narrowest fix is in update_reverse_tree itself: cut an overgrown merge into as many target-size leaves as it needs, rather than two. Anything up to 2× the target still comes out as two leaves, so a normal index cycle is unchanged, and the fix covers a large transaction window too:
if estimated_bytes > split_threshold {
// As many target-size leaves as the merge needs, not just two.
let pieces = estimated_bytes.div_ceil(target_leaf_bytes).max(2);
for chunk in merged.chunks(merged.len().div_ceil(pieces)) {
branch_entries.push(encode_and_track(chunk, &mut new_leaves));
}
}The alternative that matches #2232 is streaming the terms through dict_extend's extend_reverse_tree. That wants its entries in key order, which a term's handle order isn't, so it would need a key-sorted feed. Either way, a unit test that a large batch into a one-leaf tree comes out as leaves of at most 1.5× the target would pin it. (Commenting here because incremental.rs and dict_extend.rs are not in this diff.)
| if OType::from_u16(first.o_type).decode_kind() != DecodeKind::TripleTermDict { | ||
| return Ok(()); | ||
| } | ||
| let same_group = |r: &RunRecordV2| { |
There was a problem hiding this comment.
Blocking (performance): the SPOT merge reader is slower on every record, including imports with no triple terms at all.
advance_to_next is now the whole re-sort: the pending check, the read through lookahead, the decode_kind test, and for a triple-term record a vec![first] and a read ahead. next_remapped is called from two places. That's the per-record loop of every bulk import's SPOT build, and a chunk with no term table can't even hold a triple-term record (remap_v2_record refuses one, "triple-term record in a chunk without a term table").
Claude measured the reader alone on a box: 4M records drained through MergeSource, best of 7, dev-fast, one build per variant with only advance_to_next changed.
| reader | no triple terms | half the records are links |
|---|---|---|
| before this PR (no grouping) | 23.6 ns | 122.5–124.0 ns |
| this PR | 31.8–32.0 ns | 140.6–142.6 ns |
| this PR, group buffer reused | 31.4–31.6 ns | 138.3–142.4 ns |
| this PR, skip grouping when the chunk has no term table | 30.3 ns | 141.4 ns |
this PR, grouping moved into an #[inline(never)] fn, #[inline] on the hot two |
28.4–28.5 ns | 136.8–139.4 ns |
So a plain import pays ~8.4 ns (+35%) per record in this loop, and an annotated one ~18 ns. Reusing the buffer barely moves either, and neither does skipping the grouping for a chunk with no term table on its own. Moving the grouping out of line recovers about half, so most of the cost looks like the reader losing its inlining now that advance_to_next carries the grouping. Claude hasn't measured the whole import, where the reader is one slice, but it's every bulk import's SPOT pass.
I'd like the plain path back to what it was before this merges. The cleanest shape I can see is to give only the chunks that have a term table the regrouping reader (a small wrapper or an enum picked in open_spot_commit_readers, which already knows commit.term_table), with the grouping itself out of line, so a plain import compiles to the old loop:
#[inline]
fn advance_to_next(&mut self) -> io::Result<()> {
if let Some(record) = self.pending.pop_front() {
self.current = Some(record);
return Ok(());
}
self.current = self.next_remapped()?;
match self.current {
Some(first) if OType::from_u16(first.o_type).decode_kind() == DecodeKind::TripleTermDict => {
self.collect_term_group(first) // #[inline(never)], the rest of today's body
}
_ => Ok(()),
}
}That snippet alone is the 28.4 ns row. Claude checked that it keeps a_reifier_whose_links_reorder_reads_each_one and a_lookup_bound_to_a_link_finds_it_whatever_its_handle_order green. The per-chunk split is what I'd expect to get a plain import back to the old 23.6, since its chunks would run the old reader unchanged. While you're there, reusing the group buffer (std::mem::take a Vec field, extend(group.drain(..)) into pending) drops the allocation per link.
There was a problem hiding this comment.
Addressed in 598d9c4
Reader alone on an m7a.4xlarge, 4M records drained through MergeSource, best of 7, median of 5 rotated rounds (one tree, only the reader changed; ns/record):
| reader | plain, dev-fast | plain, release | half links, dev-fast | half links, release |
|---|---|---|---|---|
| before this PR | 35.9 | 30.3 | 153.1 | 146.6 |
| this PR, before the fix | 46.5 | 43.2 | 173.5 | 169.6 |
| this PR, fixed | 35.1 | 30.8 | 174.5 | 168.6 |
A plain import is back to the old reader. With links, the regrouping costs ~20 ns/record over a reader that didn't sort them; the fix doesn't change that.
| break; | ||
| } | ||
| } | ||
| if group.len() > 1 { |
There was a problem hiding this comment.
This is more of a heads-up than a suggestion for this PR. This re-sort is the third fix of one shape: a merge stream that isn't in the order of the merge's comparator (here, and in #1651's language ids f5b7d4eca and #2232's relocalize_sorted_commit e905972f9, because a remap wasn't monotone). Each one was found through a wrong answer, because nothing checks a stream's order where it enters the merge. A debug-build check in KWayMerge::next_record, right where the winner's stream advances, would turn the next one into a test panic:
if let Some(next) = self.streams[stream_idx].peek() {
debug_assert_ne!(
(self.cmp)(&winner, next),
Ordering::Greater,
"merge stream {stream_idx} yielded a record below the one before it"
);Claude tried it on a box. With this PR's re-sort removed, it fires on both new ordering tests. But on this head it also fires in five existing tests, all in a full rebuild's stats pass (fluree-db-indexer/src/build/rebuild.rs:1107-1121), and it fires there on next before this PR too, so this PR didn't introduce it. That pass merges V1SpoolMergeAdapter streams with cmp_v2_g_spot. The V1 order (run_record.rs:231-240) ignores the language and the list index, while V2's o_type orders by language, so one subject's values of one predicate in two languages come out backwards (LANG_STRING(2) o_key 7 then LANG_STRING(1) o_key 8). It's stats only, and the same code is on main. So the check can't go in until that pass is fed in V2 order, which is why I'd call it a follow-up rather than something for this PR. The point fix here is right. (Commenting here because merge.rs and rebuild.rs are not in this diff.)
| The source holds default-graph data: Turtle, N-Triples, JSON-LD, or JSONL/NDJSON files (optionally `.gz`/`.zst`), or CSV / Cypher inputs, as a single file or a directory. TriG, N-Quads, and JSON-LD that names graphs of its own are refused, since their statements belong to other graphs. Blank nodes are minted from the ledger id and the graph IRI unless `--skolem-namespace` is given, so importing one file into two graphs gives each its own blank nodes. | ||
|
|
||
| If the source holds statement annotations (RDF 1.2 / `f:reifies`), the ledger's annotation index is set aside: annotation queries stay correct but read by scan until [`fluree reindex`](reindex.md) seals it again. The CLI prints a note when this happens. | ||
| Statement annotations and triple terms import with the graph: RDF 1.2 annotations (`{| … |}`, `<< … >>`, `~ reifier`), triple terms as values (`<<( s p o )>>`, nested ones included), JSON-LD `@annotation` / `@reifies`, and CSV / Cypher edge properties under `--edge-properties annotated`. They read at full speed once the import publishes. A triple the ledger already reifies or names keeps its term, so an annotation in the new graph and one in the default graph are annotations of the same triple, and a query for that triple finds both. |
There was a problem hiding this comment.
Not a big deal, but "a query for that triple finds both" could read as if a default-graph query also sees the new graph's annotation. The tests show it's a query spanning both graphs that does: annotations_import_into_a_graph_and_keep_the_ledgers_terms uses UNION/GRAPH, while claims(&fluree, None) stays the default graph's one annotation. Maybe "…and a query over both graphs finds both"? Minor, but if you agree, I'd rather see it in this PR than lost in the backlog.
| .map_err(storage_error)?; | ||
| // Annotations indexed before they were stored as links leave no term | ||
| // dictionary for the import's terms to extend. | ||
| if base_root.has_annotations && base_root.term_dict.is_none() { |
There was a problem hiding this comment.
This is more of a question than a suggestion. The refusal fires for every source, so a plain import (no annotations, no triple terms) into a pre-link ledger is refused too. On next before this PR that went through, since the splice touched no term dictionary. The incremental indexer's equivalent also refuses only a window that actually holds terms (fluree-db-indexer/src/run_index/build/incremental_resolve.rs:816, NeedsRebuild). Failing before the source is read is clearly right for an annotated source. Is refusing the plain case deliberate, e.g. because 5.0 requires a reindex of pre-link ledgers anyway? If so, I think it's fine as is, since the docs line already says so. If not, a check after the build on whether it interned any term would keep plain imports working.
There was a problem hiding this comment.
Addressed in 91a25e7
Not deliberate: the refusal now fires only when a spooled chunk carries a term table, so a plain source imports into a pre-link ledger as before.
| /// Translate a term-table entry through a chunk's remaps: its subject, its | ||
| /// object, and its language, as [`remap_v2_record`] does a record, except | ||
| /// that a lexical term object | ||
| /// ([`is_lexical_term_object`](fluree_db_core::triple_term::is_lexical_term_object)) |
There was a problem hiding this comment.
Really nice that this is the one translation the pre-pass, TermRemapCtx and relocalizing all share. A pre-pass that derived its keys even slightly differently would mint duplicates that the by-value queries never notice, which is exactly what the term-count and constant-term assertions are there to catch. Claude confirmed it: with the pre-pass dropped, four it_import_into_graph tests fail, each on its term-count assertion.
…ple-terms # Conflicts: # docs/cli/graph.md # fluree-db-api/src/graph_import.rs # fluree-db-api/tests/it_store_load_failure.rs
… needs update_reverse_tree split a leaf past 1.5x the target into exactly two. A graph import's new terms mostly land in the leaf at the tail of their range, so a large import into an annotated ledger left two leaves that grew with the import, rewritten whole by every later cycle touching them. Cut into ceil(bytes / target) leaves instead; up to 2x the target the cut is the same len/2 midpoint as before.
…ain loop The triple-term regrouping in SortedCommitMergeReaderV2 sat inline in advance_to_next, so every bulk import's SPOT merge paid for it, though a chunk without a term table cannot hold a triple-term record. Its state now exists only for chunks with a term table, the grouping runs out of line, and its buffer is reused instead of allocated per group.
…terms A ledger indexed before annotations were stored as links has no term dictionary to extend, but a plain source needs none. The refusal now fires once the source is spooled, and only when a chunk has a term table, so plain imports into such a ledger work as they did before. Docs: a query over both graphs, not any query, finds both annotations.
Graph import carries annotations and triple terms on
nextfluree graph import(#2232), and its server and Python entry points, adds a new named graph to a ledger by splicing a bulk-built index into the ledger's own. Onnextan annotation is anrdf:reifieslink whose object is a triple term, stored in the triple-term dictionary, and the splice merged no such dictionary. The main merge (1f7caa5) therefore refused any source with annotations or triple terms, late in the import and as anI/O:error. This PR extends the ledger's dictionary instead.What changes for users
{| … |},<< … >>,~ reifier);@annotation/@reifies;--edge-properties annotated.How
TermDictBuilder::keep) and a new one goes above the watermarks, so every lookup during the build hits.index_novelty), which already appends to the dictionary's packs and copies its reverse trees.A bulk-import bug this fixes, fresh imports included
A chunk's sorted commit orders a subject's triple-term objects by ordinal. The SPOT build merges the chunk streams after ordinals resolve to handles, and a handle is not monotone in its ordinal: a term interned by an earlier chunk, or held by the ledger, has the lower handle. Two links of one reifier then reached SPOT out of order, and a lookup bound to either link found nothing, although a scan listed both.
The SPOT merge reader now re-sorts each run of records that differ only in their term. The other orders are built from runs sorted after the remap and were not affected.
Tests
it_import_into_graph:Each runs against the root the import spliced and a full rebuild from commits, where it applies.
Elsewhere:
it_triple_term_linkspins the SPOT ordering on a fresh two-file import.Dropping the base-term pre-pass leaves every by-value query passing, but terms duplicate and a constant-term query loses the ledger's own annotation. That is why the tests check the term count and the constant-term lookup.
The
graph importdocs drop the annotation-index paragraph, which describes an indexnextdoesn't have, and two flagsnextdoesn't have.Dictionary leaves and the SPOT reader
The import's new terms reach the ledger's term dictionary through the incremental reverse-tree update. That update split an overgrown leaf into exactly two, so a large import into an annotated ledger left two leaves that grew with the import. It now cuts an overgrown merge into as many target-size leaves as it needs. Up to twice the target, the cut is the same midpoint as before, so a normal index cycle is unchanged.
The SPOT merge reader regroups triple-term records only for chunks with a term table, out of line. A chunk without one, which cannot hold a triple-term record, reads through the plain loop.
Also
next's CI fixes this PR first carried have since landed onnexton their own: the stale list expectations, blank-node JSON-LD graph names inrdf::parse, and theit_store_load_failurerace. What remains here is a blank-node-named graph inrdf.rs's round-trip test, and the Python collection test pinning both readings: the list's members as values of its property, and therdf:rest*/rdf:firstwalk.Follow-up: #2336