Skip to content

feature: Expand bulk-import format coverage: N-Triples, N-Quads, TriG named graphs, transparent gzip/zstd - #1263

Merged
bplatz merged 5 commits into
mainfrom
feature/nt-import
May 31, 2026
Merged

bplatz merged 5 commits into
mainfrom
feature/nt-import

Conversation

@bplatz

@bplatz bplatz commented May 31, 2026

Copy link
Copy Markdown
Contributor

Closes several gaps in the bulk-import pipeline (fluree create --from, import_from_storage) — without touching the optimized single-graph .ttl hot path:

  • N-Triples (.nt) — parsed as Turtle (it's a strict subset). Pure dispatch-layer extension; the parser needed no changes.
  • N-Quads (.nq) — converted to TriG and routed through the named-graph-aware TriG path.
  • TriG (.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.
  • Transparent .gz and .zst decompression for all five RDF input formats (.ttl.gz, .nt.gz, .nq.gz, .trig.gz, .jsonld.gz, plus the .zst variants).

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 .nt file already worked via a fallback path, but directory discovery, large-file streaming-split, and remote-object acceptance all hard-coded .ttl/.trig/.jsonld allowlists and silently dropped .nt. Fixed by extending each allowlist site to treat .nt as Turtle.

2. TriG named-graph bulk import

.trig files 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:

  • Written to the commit blob but not spooled for index generation.
  • Never registered in graphs.dict / the query-time graph registry, so queries returned Unknown named graph '#<iri>'.

There were also two unreconciled graph-id allocators (the commit state.next_gid counter vs. the shared graph_alloc that 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 the dict_id + 1 = g_id convention) and SpoolContext::push_named_graph_record (spools a record under an explicit g_id by temporarily swapping the per-chunk g_id field).
  • fluree-db-transact/src/import.rs — import_trig_commit now allocates named g_ids from the spool allocator when spooling (the source of truth for graphs.dict), spools each named-graph flake, and finishes the spool only after the named-graph loop. The non-spooling fallback's ImportState::new() was shifted to start at FIRST_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_upload now runs an extra build_indexes_from_commits pass 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 through ChunkImportResult.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_objects no 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 @lang suffixes are folded into the preceding term), regroups quads by graph label, and emits equivalent TriG with GRAPH <iri> { ... } blocks. The output is byte-span sliced from the original input — no term re-serialization, so escape sequences round-trip safely.

.nq files force the serial path (has_nquads() joins has_trig / has_jsonld in the parallel-vs-serial gate) and dispatch via is_nquads(idx) → nquads_to_trig() → import_trig_commit in 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 .gz and .zst decompression

Real-world RDF dumps (DBpedia, Wikidata, every LOD-cloud archive) ship compressed. Now any of the five RDF formats above can carry a .gz or .zst suffix and is decoded transparently.

  • fluree-db-api/src/import.rs — new Compression enum + effective_extension(path) -> (Option<String>, Compression) helper strips an outer .gz/.zst/.zstd and 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_decoded wraps a file in flate2::read::MultiGzDecoder (handles concatenated streams from pigz/bgzip) or zstd::stream::read::Decoder as needed; read_decoded_to_string is the small-file path and falls back to plain fs::read_to_string for 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 fresh Box<dyn BufRead + Send>; called once on the main thread for prelude extraction (via the new extract_prefix_block_from_reader), once on the reader thread for body streaming. The reader thread replaces its lone seek(data_start) with io::copy(reader.take(data_start), &mut sink) so any source — not just seekable File — qualifies. The plain-file path keeps its original seek-backed fast path.
  • fluree-db-cli/src/detect.rs — detect_data_format now looks at the inner extension so .ttl.gz / .jsonld.zst classify as their underlying format.

Performance footprint: the single-graph .ttl hot path is untouched. The streaming large-file reader's prelude advance is now io::copy(take(N), sink) rather than seek, but N is 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

  • Remote compressed objects (e.g. .ttl.gz in S3 via import_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.
  • HTTP Content-Encoding: gzip on /insert//upsert: a separate server-middleware change. The CLI's detect_data_format was updated to recognize inner extensions so the eventual end-to-end wiring is straightforward.
  • .nq over HTTP content-type: the server's Turtle parser can't read raw N-Quads. .nq is bulk-import-only by design.

New tests

  • it_import.rs::import_single_nt_file_then_query and import_nt_directory_then_query — .nt round-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 — .nq round-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 .trig remotely" 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 1 so the streaming-split factory path is exercised end-to-end; asserts spot-check values queryable post-index.
  • parse/nquads.rs unit 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-Rust miniz_oxide backend, no system libz dependency, no new transitive crates of note).
  • zstd was already a workspace dep.

Docs touched

  • docs/cli/create.md — --from accepts all five formats plus .gz/.zst variants; named-graph queryability via #<graph-iri> fragment.
  • docs/cli/insert.md — extension detection includes .nt.
  • docs/api/endpoints.md — application/n-triples content type on /insert and /upsert.

bplatz added 2 commits May 30, 2026 15:12
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.
@bplatz
bplatz requested review from aaj3f and zonotope May 31, 2026 11:27
bplatz added 3 commits May 31, 2026 07:44
`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.
@bplatz
bplatz merged commit 042de7e into main May 31, 2026
14 checks passed
@bplatz
bplatz deleted the feature/nt-import branch May 31, 2026 17:41
bplatz added a commit that referenced this pull request Jun 1, 2026
rollup: Cumulative work from #1258, #1260, #1261, #1262, #1263 (mis-merged to solo/latest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant