Repository navigation
feature: Expand bulk-import format coverage: N-Triples, N-Quads, TriG named graphs, transparent gzip/zstd - #1263
Merged
Merged
Conversation
N-Triples is a strict subset of Turtle, so the existing Turtle parser handles it; only the format-dispatch allowlists needed extending. - import.rs: accept .nt in directory discovery, format detection, large-file auto-split, and remote-object acceptance - cli detect: .nt -> Turtle - server: accept application/n-triples content-type as Turtle - docs: create/insert CLI + HTTP endpoints - tests: single-file and directory .nt import round-trips
Three related expansions to the bulk import pipeline: 1. TriG named-graph bulk import is now end-to-end queryable. The path already accepted .trig content, but named-graph flakes bypassed the spool so they never reached the Tier-2 index and the named graph wasn't registered. Fix: SpoolContext gained `graph_g_id_for_iri` / `push_named_graph_record`; import_trig_commit allocates g_ids from the shared graph allocator (reconciling with state.next_gid which now starts at FIRST_USER_GRAPH_ID); build_and_upload runs an extra build pass per user-defined g_id. Empty range for single-graph imports — zero overhead on the optimized hot path. Remote .trig is re-enabled with the now-obsolete rejection removed. 2. .nq (N-Quads) bulk import. N-Quads is not a TriG subset (per-line 4th graph term vs GRAPH blocks), so parse/nquads.rs adds a tokenizer-driven converter that regroups quads into TriG via byte-span slicing (no re-serialization, no escape hazards). The serial path then dispatches via import_trig_commit. Blank-node graph labels are rejected with a clear error. 3. Transparent .gz / .zst decompression for all five RDF input formats (.ttl, .nt, .nq, .trig, .jsonld). New helpers in api/import.rs: Compression enum, effective_extension (strips outer .gz/.zst), open_decoded, read_decoded_to_string. The streaming large-file reader gains StreamingTurtleReader::new_from_factory, which takes a closure that opens a fresh BufRead — used twice (prelude pass, body pass) so non-seekable decoders work. The body loop now uses io::copy(reader.take(data_start), &mut sink) instead of seek so any source qualifies. flate2 added as a workspace dep. Local-only for compressed inputs; HTTP/remote compression is a separate piece of work (Content-Encoding wiring). Tests: it_import (20 incl. 4 compression), it_import_remote (7 incl. remote .trig named-graph), it_named_graphs (13) all green; clippy clean across touched crates.
`is_import_path` was the gatekeeper deciding whether a `--from` file goes through the bulk-import pipeline (which decompresses transparently) or the "detect by reading content" fallback (which does raw fs::read_to_string). It only matched `.ttl` / `.jsonld` and explicitly rejected `.ttl.gz` / `.ttl.zst` / `.ttl.bz2` with a "not yet supported" message. Result: `fluree create db --from data.nt.gz` fell through to the fallback and read gzip bytes as a String, failing with "stream did not contain valid UTF-8". Plain `.nt` worked only by accident — the fallback's Turtle branch had a safety redirect back into the bulk pipeline. Expand the allowlist to cover every supported RDF format (.ttl/.nt/.nq/ .trig/.jsonld) plus the .gz/.zst suffixes the bulk pipeline already decodes. .bz2 is rejected explicitly (no bzip2 decoder linked). New regression tests cover the failing repro and the surrounding matrix: .nt, .nq, .nt.gz, .ttl.gz, .ttl.zst.
The streaming-split path for `.ttl.gz` / `.nt.gz` etc. passes
`total_bytes_hint = 0` because uncompressed size isn't known cheaply.
Two layered bugs made the Reading bar lock at "100% 0.0 GB" on the
first event:
- splitter: `file_size - data_start` underflowed u64 when file_size = 0
(file with no Turtle prelude → data_start = 0 → no underflow but
bogus 0 denominator; file with a prelude → underflow to ~u64::MAX).
Use saturating_sub so total propagates as 0 ("unknown"). Skip the
final EOF callback entirely when total is unknown — emitting (0, 0)
would tell the UI the bar reset to zero.
- CLI: the Scanning handler unconditionally called set_length(0) +
finish_with_message when bytes_read >= total_bytes — which is
always true when total_bytes = 0, so the bar locked at 100% on
the very first event. Now branches on total > 0: known total gets
the original percentage bar; unknown total shows "X.X GB read" with
length=u64::MAX so the bar never renders as complete. PreparingIndex
finalizes the bar at its last byte count (parsing is fully done by
then, so reading must be too — gives an idempotent finish for the
unknown-total path that has no natural EOF marker upstream).
Plain-file streaming paths are unaffected (file_size > 0 throughout).
Bulk import regressed ~3.9x on large datasets (390M-flake DBLP: 0.46M flakes/s vs ~1.7M). The secondary-order remap worker hooks set rdf:type p_id, which made IdStatsHook build five per-subject maps for every distinct subject (~68M x 6 workers), then merge them serially (~283s) and finalize single-threaded (~249s) -- 62% of the import. Those maps existed only to produce uncapped class ref-target stats, working around ClassBitsetTable's 64-class cap. Replace ClassBitsetTable with ClassMembership: a dense 64-class bitset that transparently promotes to a sparse per-subject class list above 64 classes (uncapped, memory-flat in class count). SpotClassStatsCollector now produces uncapped class_prop_refs directly, so import and rebuild pass None to build_class_stat_entries and no longer build per-subject id-hook maps. Worker hooks no longer set rdf:type p_id; they keep only the cheap per-property HLL / datatype / graph-flake stats. Add a per-build entry budget (MAX_CLASS_REF_LEAF_ENTRIES) that truncates the rarest class pairs instead of OOMing on pathological class graphs. Fix IdStatsHook::merge_from silently dropping subject_prop_dts/langs. Move fluree-db-memory's test module to end of file (items_after_test_module). DBLP 390M-flake import: 848s (0.46M/s) -> 215s (1.81M/s); the two id-stats phases drop from ~531s combined to near zero. <=64-class ledgers ride the dense bitset, larger ontologies use the sparse path.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes several gaps in the bulk-import pipeline (
fluree create --from,import_from_storage) — without touching the optimized single-graph.ttlhot path:.nt) — parsed as Turtle (it's a strict subset). Pure dispatch-layer extension; the parser needed no changes..nq) — converted to TriG and routed through the named-graph-aware TriG path..trig) named graphs are now queryable after bulk import. Previously only default-graph TriG worked end-to-end; named-graph flakes were silently dropped by the spool/index pipeline. Remote.trig(import_from_storage) is re-enabled..gzand.zstdecompression for all five RDF input formats (.ttl.gz,.nt.gz,.nq.gz,.trig.gz,.jsonld.gz, plus the.zstvariants).What changed and why
1. N-Triples (
.nt)N-Triples is a strict syntactic subset of Turtle (three full-IRI terms, then
.), so the Turtle parser already accepts it. The only gap was dispatch: a single.ntfile already worked via a fallback path, but directory discovery, large-file streaming-split, and remote-object acceptance all hard-coded.ttl/.trig/.jsonldallowlists and silently dropped.nt. Fixed by extending each allowlist site to treat.ntas Turtle.2. TriG named-graph bulk import
.trigfiles were already accepted, but a deeper look revealed the existing wiring only worked for default-graph content. Named-graph data — the entire point of TriG — was:graphs.dict/ the query-time graph registry, so queries returnedUnknown named graph '#<iri>'.There were also two unreconciled graph-id allocators (the commit
state.next_gidcounter vs. the sharedgraph_allocthat feeds the index), creating a sharp edge where the same graph could end up with different IDs on the commit and index sides.Fix spans three layers:
fluree-db-transact/src/import_sink.rs—SpoolContext::graph_g_id_for_iri(allocates a graph's g_id via the shared allocator, honoring thedict_id + 1 = g_idconvention) andSpoolContext::push_named_graph_record(spools a record under an explicit g_id by temporarily swapping the per-chunkg_idfield).fluree-db-transact/src/import.rs—import_trig_commitnow allocates named g_ids from the spool allocator when spooling (the source of truth forgraphs.dict), spools each named-graph flake, and finishes the spool only after the named-graph loop. The non-spooling fallback'sImportState::new()was shifted to start atFIRST_USER_GRAPH_ID(3) so it honors the reserved range (0=default, 1=txn-meta, 2=config, 3+=user) even without a spool config.fluree-db-api/src/import.rs—build_and_uploadnow runs an extrabuild_indexes_from_commitspass per user-defined named graph (g_id ≥FIRST_USER_GRAPH_ID), mirroring the existing g_id=1 (txn-meta) build and merging the resulting per-order results. The named-graph list is threaded throughChunkImportResult.named_g_ids→IndexBuildInput.named_g_ids. For single-graph imports the range is empty, so the loop is skipped entirely.With the underlying limitation gone,
resolve_remote_objectsno longer rejects remote.trig— that error path and its now-stale "TriG is not currently supported" copy have been removed.3. N-Quads (
.nq)Unlike N-Triples, N-Quads is not a TriG subset — TriG groups named graphs in
GRAPH <g> { ... }blocks, while N-Quads carries an optional 4th graph label term on each statement. So the Turtle/TriG parser cannot read it directly.Solution:
fluree-db-transact/src/parse/nquads.rs— a small converter (nquads_to_trig) that walks Turtle tokens (typed-literal^^and language-tag@langsuffixes are folded into the preceding term), regroups quads by graph label, and emits equivalent TriG withGRAPH <iri> { ... }blocks. The output is byte-span sliced from the original input — no term re-serialization, so escape sequences round-trip safely..nqfiles force the serial path (has_nquads()joinshas_trig/has_jsonldin the parallel-vs-serial gate) and dispatch viais_nquads(idx) → nquads_to_trig() → import_trig_commitin both local and remote serial arms. Blank-node graph labels (which the TriG parser doesn't accept) are rejected with a clear error rather than silently producing un-parseable TriG.4. Transparent
.gzand.zstdecompressionReal-world RDF dumps (DBpedia, Wikidata, every LOD-cloud archive) ship compressed. Now any of the five RDF formats above can carry a
.gzor.zstsuffix and is decoded transparently.fluree-db-api/src/import.rs— newCompressionenum +effective_extension(path) -> (Option<String>, Compression)helper strips an outer.gz/.zst/.zstdand returns the underlying RDF extension. Every dispatch site (is_trig,is_nquads,is_jsonld,has_jsonld,has_nquads,scan_directory_format,discover_chunks,resolve_chunk_source) now uses it.open_decodedwraps a file inflate2::read::MultiGzDecoder(handles concatenated streams frompigz/bgzip) orzstd::stream::read::Decoderas needed;read_decoded_to_stringis the small-file path and falls back to plainfs::read_to_stringfor uncompressed inputs (zero overhead).fluree-graph-turtle/src/splitter.rs—StreamingTurtleReader::new_from_factory(open_reader, total_bytes_hint, ...)takes a closure that opens a freshBox<dyn BufRead + Send>; called once on the main thread for prelude extraction (via the newextract_prefix_block_from_reader), once on the reader thread for body streaming. The reader thread replaces its loneseek(data_start)withio::copy(reader.take(data_start), &mut sink)so any source — not just seekableFile— qualifies. The plain-file path keeps its original seek-backed fast path.fluree-db-cli/src/detect.rs—detect_data_formatnow looks at the inner extension so.ttl.gz/.jsonld.zstclassify as their underlying format.Performance footprint: the single-graph
.ttlhot path is untouched. The streaming large-file reader's prelude advance is nowio::copy(take(N), sink)rather thanseek, butNis the prelude size (≤ 256 KiB) so the cost is negligible vs the chunk loop. Compressed inputs decode single-threaded (gzip and zstd are sequential), so on multi-GB compressed files the decoder will be the bottleneck — multi-stream (bgzip-style) parallel decode is a future optimization, not blocking.Deliberate scope cuts
.ttl.gzin S3 viaimport_from_storage): the local path covers the dominant use case (fluree create mydb --from dbpedia.ttl.gz). Wiring decompression into the producer/bridge thread is a natural follow-up.Content-Encoding: gzipon/insert//upsert: a separate server-middleware change. The CLI'sdetect_data_formatwas updated to recognize inner extensions so the eventual end-to-end wiring is straightforward..nqover HTTP content-type: the server's Turtle parser can't read raw N-Quads..nqis bulk-import-only by design.New tests
it_import.rs::import_single_nt_file_then_queryandimport_nt_directory_then_query—.ntround-trips for single-file and directory discovery.it_import.rs::import_trig_named_graph_is_queryable— TriG bulk import with a GRAPH block; asserts both default-graph and named-graph data are queryable post-index (the latter is the behavior the named-graph fix enables).it_import.rs::import_nquads_default_and_named_graph—.nqround-trip covering both 3-term default-graph lines and 4-term named-graph quads.it_import_remote.rs::import_from_storage_trig_named_graph_then_query— replaces the prior "reject.trigremotely" test with a positive round-trip that includes a named graph.it_import.rs::import_gzipped_ttl_small_file,import_gzipped_nt_directory,import_zstd_ttl_small_file— compressed-input round-trips covering both formats and both single-file and directory paths.it_import.rs::import_gzipped_ttl_streaming_split— ~40k synthetic triples gzipped, imported with--chunk-size-mb 1so the streaming-split factory path is exercised end-to-end; asserts spot-check values queryable post-index.parse/nquads.rsunit tests — default-graph pass-through, named-graph grouping, typed-literal and language-tag suffix preservation, unterminated-statement rejection, blank-node graph-label rejection.Dependencies
flate2 = "1"added as a workspace dep (pure-Rustminiz_oxidebackend, no system libz dependency, no new transitive crates of note).zstdwas already a workspace dep.Docs touched
docs/cli/create.md—--fromaccepts all five formats plus.gz/.zstvariants; named-graph queryability via#<graph-iri>fragment.docs/cli/insert.md— extension detection includes.nt.docs/api/endpoints.md—application/n-triplescontent type on/insertand/upsert.