Repository navigation
RDF 1.2 in Python, and RDF documents without a ledger (fluree.parse / serialize, fluree_db_api::rdf) - #2042
Conversation
A parameter takes the JSON-LD triple term {"@id": {"@id": s, p: o}},
read with the shape check the other JSON-LD surfaces share (so
fluree-graph-json-ld is now a plain dependency), and `?r rdf:reifies $t`
finds the reifiers of one triple. In an expression it is the TRIPLE()
constructor; as a subject or a reifier it is refused.
The TripleTerm doc still said a triple term was valid only under
rdf:reifies and could not nest; both have since changed.
A query or stream that bound a triple term raised "unsupported SPARQL result term", which on this branch is any `?r rdf:reifies ?t` and any `?s ?p ?o` over a ledger with an annotation. Such a binding is now a fluree.Triple(subject, predicate, object): hashable, picklable, nested where the object is a triple term, and unpacking like a tuple. A Triple is also a value to write (the JSON-LD triple term), a SPARQL parameter, and under "@reifies" the triple a node is about, which records a claim without asserting it.
A triple-term object (the rdf:reifies link of every annotation) fell
through to FlakeValue's Display, so /show, `fluree show`, merge previews
and the Python changes() printed namespace codes:
`<<( [13:carol] [13:age] 30 )>>`. It is now a ResolvedTriple whose IRIs
are resolved as the flake's are, serialized as the tuple of the triple it
names without the operation, [s, p, o, dt], with {"lang": ...} for a
tagged object; a nested triple term nests the same way.
A commit's rdf:reifies links now read back as the Triple they name, nested and language-tagged objects included. Blank-node references are told apart natively, so a triple term's blank-node subject is a BlankNode too.
…ctor TriG puts every Turtle production inside a graph block, so a collection or an annotation can belong to a named graph. GraphSink gains emit_quad_list_item and emit_quad_reified_triple beside emit_quad; like it, their defaults refuse rather than drop the graph name. GraphCollectorSink::with_named_graphs collects named graphs too, read with into_dataset. A statement that aborts rewinds every graph it wrote to and removes a graph it created. The plain collector stays triple-only, so no ingest path starts accepting named graphs.
ParserOptions::dialect selects TriG: one lexer and one set of
productions, with GRAPH g { … }, g { … } and a default-graph { … }.
A block sets the parser's current graph, and every emission already goes
through the sink_emit_* helpers, so all of Turtle inside a block lands
in its graph: property lists, collections, annotations, reified triples
and triple-term values. Graph names are IRIs and blank nodes.
A block is one statement to the sink, committed before the parser reads
past its `}`, so a lexing error in the next statement cannot roll back
a complete block. A named graph is refused up front by a sink that
cannot hold one, rather than folded into the default graph.
parse_trig is parse with the TriG dialect.
`annotationBlock ::= '{|' predicateObjectList '|}'`, but the parser
skipped the body when `|}` followed `{|`, so `s p o {| |}` parsed and
minted a reifier with nothing said about it. It is now a syntax error,
in Turtle and TriG alike. W3C trig12-bad-ann-1 caught it; Turtle's own
empty-annotation test is malformed in other ways too, so it never did.
N-Triples was read by the Turtle parser and N-Quads was regrouped into TriG for it, so both accepted Turtle: directives, prefixed names, relative IRIs, bare numbers, long strings, lists and reified triples. parse_ntriples and parse_nquads are a line scanner of their own, one statement per line, sharing the Turtle lexer's character classes and language-tag rule. They read RDF 1.2: triple terms nested in object position and base directions (`@en--ltr`), and they refuse a language subtag past 8 characters and an explicit rdf:langString or rdf:dirLangString datatype. Literals keep their lexical form. A graph label needs a quad-capable sink; a triple-only one refuses rather than drop it.
The *_reader suites run the Turtle, N-Triples, N-Quads and TriG manifests through the strict line reader and the Turtle parser's conformant Turtle and TriG, reading expected results the same way. The ingest-path suites are unchanged. Through the readers, everything the ingest registers list for the line formats and TriG passes: N-Triples 140/140, N-Quads 155/155, and in TriG the block parser's 32 gaps, blank-node graph names and numeric lexical forms. What remains is shared with ingest: the Turtle lexer's four IRI-escape and local-name cases, and the deferred annotation-of-annotation.
A relative IRI was reported at the character after its `>`, and a forbidden character at the one after it; both now point where the problem starts.
Reification's docs still said the base triple is always in the graph's triple list. A reified triple (`<< s p o >>`, `r rdf:reifies <<( … )>>`) leaves it unasserted; only an annotation asserts it.
RDF documents to and from quads with no ledger involved. parse() reads Turtle, TriG, N-Triples or N-Quads (format from a path's extension, else format=) with the standalone readers: the Turtle parser's conformant Turtle and TriG, and the strict line reader. serialize() writes those formats with the RDF text writers, declaring prefixes for Turtle and TriG. A Quad is subject, predicate, object and graph (None for the default graph); a plain str subject, predicate or graph is an IRI. RDF 1.2 is read whole: an annotation or reified triple is the quad (reifier, rdf:reifies, Triple), the annotated triple a quad of its own, and serialize() writes such quads back as annotations where the format has them. Literals are Python values, as query results are; a float is written in its shortest form, so 0.9957 stays 0.9957. Blank nodes keep the document's labels, and anonymous ones get fresh labels every format writes back. Errors name the line and column. ledger.insert(quads) and upsert(quads), and the transaction and sync writes, take a list of quads, written as TriG.
…a reification `r rdf:reifies <<( s p o )>>` in N-Triples or N-Quads is now emitted as the reifier attachment it is, as the Turtle parser emits it, in the default graph or a named one. It used to arrive as a plain triple, so the same statement had two shapes depending on the syntax it was read from, and an annotation written out as N-Quads did not read back as one. A sink that does not record reifications still gets the triple as written.
rdf::parse reads Turtle, TriG, N-Triples or N-Quads into a Dataset and rdf::serialize writes a Dataset back, with no ledger involved. RdfFormat names the formats (by name, alias or file extension); a malformed document is RdfError::Syntax with its line and column, and Turtle or N-Triples refuse a dataset with named graphs. GraphCollectorSink::into_dataset now labels anonymous blank nodes bN, stepping past labels the document used, so every parsed dataset can be written in any format. Dataset::add_quad reads r rdf:reifies <<( s p o )>> as a reification. The Python binding's parse and serialize are now thin wrappers over this module and no longer depend on the graph crates directly, and the W3C reader suites run through it.
insert(quads) is checked against an export for annotations and unasserted reifications in named graphs, reifiers of language-tagged literals and of rdf:type, nested triple terms, strings that need escaping, direction-tagged, decimal, big-integer and custom-typed literals, non-ASCII IRIs, and blank nodes in named graphs. A ledger names its graphs with IRIs, so a quad whose graph is a blank node is refused before the write, naming the quad, instead of failing in the TriG it is written as.
The RDF document functions as coroutines, reading and writing on a worker thread so a large document does not hold up the event loop. The README's parse example passed a str path, which parse reads as the document's text; it now passes a Path, and says why.
…elled With literals="lexical", fluree.parse returns every typed literal other than a plain string as a fluree.Literal carrying its lexical form, so "01"^^xsd:integer stays "01" rather than becoming 1, and serialize writes it back unchanged: a document read and written back keeps its literals exactly. The default stays Python values, as query results are. fluree.aio.parse takes the option too.
…es each IRI once An IRI or string with no escape is now sliced from the input instead of built a character at a time, falling back to the decoding loop (and its errors) only when it holds an escape or a character it cannot. The reader also keeps each IRI's term id, as the Turtle parser does, so the sink makes one term per IRI rather than one per occurrence. Reading N-Quads takes well under half the time it did.
parse_rdf returns IRIs and blank nodes as ready fluree.IRI and fluree.BlankNode objects, one per distinct term, with only literals and triple terms left as cells; parse builds its Quads and Triples without re-checking terms the reader produced. serialize converts each IRI and blank node object once per call, a triple term part by part. fluree.parse takes about half the time it did and serialize about three quarters.
…ifiers The adapter from expanded JSON-LD to graph events now emits a node's @graph as a named graph to a sink that holds quads (one that does not still gets none of it), @annotation on a value as a reifier of the triple the value completes, described by the annotation node's properties, and a node's @reifies as a reifier of the triple it names, unasserted. @reverse and @included are read too. Expansion keeps @annotation on a value object, as it already did on a node reference. A number or boolean with no @type now has the datatype JSON-LD gives it (xsd:integer, xsd:double, xsd:boolean) rather than xsd:string, an integer too large for i64 keeps its digits, and a blank node @type is a blank node rather than an IRI named _:x.
An rdf:type whose object is a literal or a triple term was dropped, since @type holds only IRIs and blank nodes. It is now written as an rdf:type property, as an annotated type already was.
RdfFormat::JsonLd reads a JSON-LD document into a Dataset (named graphs, @annotation, @reifies and triple terms included) and writes one, with the prefixes as its @context and IRIs compacted by them. A JSON syntax error is RdfError::Syntax with its line and column; an IRI expansion leaves relative is refused by name. PrefixMap::to_context gives the prefixes as a context. fluree.parse and fluree.serialize take "jsonld" (and .jsonld / .json paths), and parse also takes a JSON-LD document as a dict or list.
A reference page for fluree.parse / fluree.serialize and fluree_db_api::rdf: the five formats, how reading treats IRIs, literals and blank nodes, how each syntax writes named graphs, annotations, reified triples and triple terms, how writing chooses between them, and the JSON-LD limits (contexts are not fetched, an unmapped property is an error, @direction is not read, a JSON number typed other than xsd:integer or xsd:double loses its datatype in Rust). Linked from the reference index, the standards page, and the Rust and Python guides. The Python guide gains a JSON-LD example and the context limits, and says that the default literal conversion loses a narrower numeric datatype as well as the spelling.
17441a3 to
7c6f4f9
Compare
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is still really nice, and at a design level still no pushback from me: one Dataset carrying RDF 1.2 whole, TriG as a dialect of the Turtle parser, a strict line reader, and the W3C suites run through the public rdf API. The rebase onto next is clean, and I re-ran the parts that touch ledgers on the new head. Two headline notes:
(1) The overlap with my #2008 that I flagged on the first pass is now real on next: this head has three TriG readers. There's your Dialect::TriG (rdf::parse and Python), #2008's locator plus SegmentParser (every transaction lane), and the old block parser, which bulk import still uses. I ran 17 TriG documents through all three. The first two agree on everything except collections (rdf::parse reads them as rdf:first/rdf:rest, as it should, and the ledger lanes store lists; more on that inline) and what they refuse (a relative graph name with no base, a blank graph name). The block parser still refuses ( … ) and [ … ] inside a block, and a bare { … }. The open question is where import goes next: #2008's body says its driver, and this PR's body says your dialect. I'd rather import move once, so I think we should pick one before either of us moves it. (TemplateSink already holds quads, so if it's your dialect, the transaction lanes could follow later.) This body's "TriG insert and import still read GRAPH blocks with the separate block parser" is only true of import now.
(2) The class I raised on #2024 is unchanged here: a JSON-LD term object read as an RDF term, with each surface applying its own scalar rules. The four instances from my first pass still stand:
JSON-LD
valuesreads a u64 asxsd:double, so a triple term holding18446744073709551615matches nothing there, while the parameter, the inline term and SPARQLVALUESall match it (fluree-db-query/src/parse/values.rs:149-163);fluree insertstores that number asxsd:doubleand bulk import now storesxsd:integer(fiveas_i64sites influree-db-transact/src/parse/jsonld.rs); a triple term with a stored_:fdb-…subject works as a parameter and in JSON-LDvaluesbut not in an expression;{"@value": 5, "@type": "xsd:long"}isxsd:longthrough insert andrdf::parseandxsd:integerthrough bulk import (import_sink.rs:1190-1201)
Not this PR; the point fixes below are right here. But it's more evidence for one shared term reader in fluree-graph-json-ld that fluree-db-query and fluree-db-sparql both call.
Full review below:
✅ Approving to unblock you — with one thing that needs to be addressed before this merges.
This is still a carefully built PR, @bplatz. The rebase onto next changed none of the 23 commits beyond conflict resolution (#2008's generic parser and RelativeIris, #2036's extension feature, #1451's S3Tables export), and I checked those hunks. Dialect::TriG and #2008's SegmentParser share the one constructor and nothing else: with block scoping broken on purpose, six of the TriG tests and every_format_reads_its_own_writing fail, while #2008's segment-parser test doesn't notice. The Rust tests pass on the new head, and CI has the W3C *_reader suites by name. None of the commits touched what my first pass found, so the one must is the same:
- Bulk JSON-LD import silently drops a named graph's contents (
fluree-graph-json-ld/src/adapter.rs:226). I re-ran it on this head: a bulk import of a document holding{"@id": "ex:g", "ex:label": "G", "@graph": [{"@id": "ex:x", "ex:p": "in-g"}]}still stores the label, losesex:x ex:p "in-g", and reports success, whilerdf::parseof the same document keeps it as a quad. The case for refusing is stronger now that this PR's own TriG dialect refuses the same situation (parse_wrapped_graph,fluree-graph-turtle/src/parser.rs:665-669), asemit_reificationdoes for reifiers. The adapter is the one place that drops. Refusing here too is a few lines (details inline).
The rest, in order of how much I'd want them:
- 🟠 A JSON-LD
_:-b1still merges with the first anonymous node inrdf::parse(fluree-graph-ir/src/sink.rs:523). I re-ran it on this head and got the sameb1 q b1. Escaping a leading-in the adapter'snode_termcovers this and inline shapes. - 🟡 ❓ The quads route and the text route store a collection differently (
fluree-db-python/python/fluree/_rdf.py:119).ledger.insert(fluree.parse(doc))writes a( 1 2 )as itsrdf:first/rdf:resttriples, whereledger.insert(doc)stores an ordered list. This is new from me, not from the rebase; I missed it the first time. - 🟡 The adapter fixes are also bulk-import changes (
adapter.rs:572): big integers kept exact, a blank-node@typeread as a blank node,@reverse/@includedstored. They're right, butfluree insertstill differs on all of them, and the title reads as ledger-free, so a line in the body and in the compatibility page would help. - 🟡 A triple-term parameter with a stored
_:fdb-…subject matches as a pattern but is refused inFILTER(?t = $t)(params.rs:728). - 🟡 A line on memory:
fluree.parseof a 68.5 MB N-Quads file peaked at 683 MB on my first pass, andaio.parsestill holds the GIL while it builds the quads (docs/reference/rdf-documents.md:47).
On the follow-up: I still agree #1930 is separable, but the rebase moved it. Since #2008, a TriG insert takes ( … ) and [ … ] inside a block, so #1930 is now about bulk import alone, and which reader import moves to is headline note 1.
I also re-ran the reader differential on this head, as TriG this time: 17 documents through rdf::parse, a TriG insert, bulk import, and serialize followed by insert (graph blocks, GRAPH/graph, a bare { … }, annotations, reified triples and triple terms in a block, blank labels shared across blocks, @base and a relative graph name, prefixes redefined between blocks, braces inside literals, numbers). Apart from the collection item above, they never disagree silently. Where they differ, it's a refusal: rdf::parse refuses a relative graph name with no base (the ledger keeps it as written, for ledger ids), the ledger refuses a blank graph name, and bulk import's block parser refuses ( … ), [ … ] and a bare { … }.
Adherence to repo commitments:
- Patterns/abstractions: ✔ TriG is a dialect of the one Turtle parser,
GraphSinkgains quad variants whose defaults refuse, and four JSON-LD triple-term readers now sharetriple_term_parts.⚠️ The adapter drops named graphs where the TriG dialect andemit_reificationrefuse (item 1), andnextnow has three TriG readers (headline note 1). - Performance (speed first, memory second): ✔ No query-engine path is touched. Commit details recurse only for triple-term values, and the adapter adds one
@annotationlookup per value on the bulk-import path, which I don't think is measurable. The reader and binding commits are unchanged by the rebase, so my first-pass N-Quads numbers (3.90 s → 2.72 s on 1M lines, debug build) still describe them. No performance-degradation risk. - Deployment targets: ✔
rdfis pure CPU and memory (no filesystem, threads or clock), and thewasm32andwasm-smokejobs are green on the new head. In the Python host the GIL is released during the Rust parse andaioruns onasyncio.to_thread; memory is roughly 10× the document. For embedders,ResolvedValuegains a variant, and a triple-term object in serialized commit details is now a nested array instead of a string. - Testing: ✔ The new Rust tests pass by name on this head, the W3C
*_readersuites ran by name in CI (run 38162544333), and the threepythonjobs are green. Breaking the TriG block scoping turned seven named tests red.⚠️ Triple-term parameters have only AST-level Rust tests (end to end they're covered by the Python job), and the adapter's number typing is pinned only by therdftests influree-db-api, not by the adapter's own tests. - Conventions: ✔ Thorough multi-line commits, a reference page, and the Rust and Python guides.
⚠️ The body doesn't mention the bulk-import behavior change, and its #1930 sentence predates the rebase.
Verified locally at 7c6f4f99b: cargo test for fluree-graph-turtle, -graph-ir, -graph-json-ld, -graph-format and fluree-db-sparql, plus fluree-db-api rdf:: and it_graph_commit (1,242 passed); a block-scoping mutation in the rebased TriG code (seven tests red, then restored); a scratch probe of the @graph import, _:-b1, and a 17-document TriG differential across rdf::parse, TriG insert, bulk import and the quads route.
Approving now so you can merge without waiting on another pass from me. Just be sure the @graph refusal is in before you do, and I'd love the _:-b1 fix to ride along with it.
| // A named graph: this node names it. A sink that cannot hold | ||
| // named graphs gets none of it rather than the graph folded into | ||
| // its default graph. | ||
| "@graph" if sink.supports_quads() => { |
There was a problem hiding this comment.
🔴 Must address before merge — bulk JSON-LD import still drops a named graph's contents without a word, and this branch writes that drop down as the intended behavior.
For a sink that can't hold quads, "@graph" if sink.supports_quads() falls through to key if key.starts_with('@') => {} (:263), and the bulk importer's sink is one of those (ImportSink, fed by fluree-db-transact/src/import.rs:1252). Your code didn't introduce the drop (on next before this PR the adapter skipped every @ key but @type), but the module doc at :21-25 now describes it as the contract. Two places in this same PR make the opposite call: emit_reification (:150) errors when the sink can't hold a reifier, and the TriG dialect's parse_wrapped_graph refuses a named graph for a sink without quads, rather than "dropping the graph's name" (fluree-graph-turtle/src/parser.rs:665-669).
I've now run it on next, on the head I first reviewed, and on this rebased head. A .jsonld bulk import of a document holding the node {"@id": "ex:g", "ex:label": "G", "@graph": [{"@id": "ex:x", "ex:p": "in-g"}]} succeeds every time, stores ex:g ex:label "G", and ex:x ex:p "in-g" is gone. rdf::parse of the same document returns the quad in ex:g. FlakeSink (inline shapes and inline ontology) is the other non-quad caller and, reading the code, drops the same way.
I think this wants the reifier branch's posture: refuse when the sink can't hold a named graph, and say so in the module doc. Illustrative:
"@graph" => {
if !sink.supports_quads() {
return Err(AdapterError::InvalidStructure(
"a named graph (@graph on a node) needs a destination that holds named graphs; \
load it as TriG or N-Quads"
.to_string(),
));
}
for item in values {
process_node(item, sink, None, Some(subject_id))?;
}
}A top-level {"@context": …, "@graph": [...]} envelope is unwrapped by expansion before it gets here, so ordinary bulk imports are unaffected; only a node that names a graph would start failing, which is the point.
There was a problem hiding this comment.
Fixed in 6b269c7, with the reifier branch's posture: a sink that can't hold named graphs now refuses a node's @graph. That one arm covers bulk import, inline shapes and inline ontology. The module doc says it refuses rather than drops.
Two tests, both red with the old fall-through restored:
named_graph_is_refused_by_a_sink_without_named_graphsin the adapter, against a sink with and without named graphs.import_refuses_a_jsonld_node_naming_a_graphruns your exact document through bulk import.
import_single_jsonld_file_then_query, which imports a top-level @graph envelope, still passes. docs/cli/create.md and docs/reference/compatibility.md say JSON-LD import refuses a node naming a graph and to load named graphs as TriG or N-Quads.
| /// Anonymous blank nodes (`[]`, collections, annotations) are labeled | ||
| /// `bN` here, or `bN_k` when the document wrote `_:bN` itself, so the | ||
| /// dataset can be written back in any RDF syntax. While parsing they are | ||
| /// `-bN`, a label no document can write (see [`GraphSink::term_blank`]). |
There was a problem hiding this comment.
🟠 Should address — a JSON-LD document can write _:-b1, and in rdf::parse that node and the first anonymous node become one.
The -bN mint relies on Turtle's BLANK_NODE_LABEL never starting with - (the comment in term_blank). That holds for Turtle, TriG, N-Triples and N-Quads, but a JSON-LD blank node identifier is any string after _:, and node_term (fluree-graph-json-ld/src/adapter.rs:169) passes it through as is. So term_blank(Some("-b1")) returns the same BlankId as the first mint, and into_dataset then renames both to b1.
Repro, still the same on this head: rdf::parse(…, RdfFormat::JsonLd, None) (or fluree.parse) of {"@id": "_:-b1", "http://ex/p": {"@id": "http://ex/x"}, "http://ex/q": {"http://ex/r": "anon"}} returns b1 p x, b1 r "anon" and b1 q b1: the anonymous node's property lands on the document's node, plus a self-loop. Bulk import and fluree insert of the same document keep the two apart, and docs/reference/rdf-documents.md:45 promises the mints avoid "any label the document uses". The label is unusual, I know, but the failure is silent.
Maybe the cheapest fix is in node_term, the one place a JSON-LD id enters a sink: give a label that starts with - one more - (-b1 → --b1). That's injective and can never equal a mint -b<digits>, and it covers FlakeSink's inline shapes and ontology too, which mint -bN the same way. The writers already hex-escape --b1 on the way out, so it still writes. Minor in practice, but if you agree it's right I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Fixed in 93d8160 as you suggested: node_term gives a label that starts with - one more, so _:-b1 reads as --b1 and can't equal a mint. It's the one place a JSON-LD blank label enters a sink, so inline shapes and ontology are covered too.
blank_label_starting_with_dash_is_not_an_anonymous_node runs your document and goes red without the extra -. Since rdf-documents.md promised labels are kept, it now notes the exception.
| for quad in quads: | ||
| if isinstance(quad.graph, BlankNode): | ||
| raise InvalidRequestError(f"a ledger's named graphs are IRIs, not blank nodes: {quad!r}") | ||
| return serialize(quads, "trig") |
There was a problem hiding this comment.
🟡 ❓ This is more of a question than a suggestion: ledger.insert(fluree.parse(doc)) and ledger.insert(doc) store a collection differently.
fluree.parse reads conformantly, so ( 1 2 ) becomes the rdf:first/rdf:rest spine, and ledger_trig writes those back out as plain triples for the TriG insert. Inserting the text instead goes through the Turtle parser's list handling, which stores an ordered list. On this head, ex:s ex:list ( 1 2 ) (in the default graph or in a block) comes out as five facts with ex:s ex:list _:b through the quads route, and as two list values (1 at 0, 2 at 1) through the text. So ?s ex:list ?o answers a blank node in one ledger and 1, 2 in the other. I reproduced it through the same Rust calls ledger_trig makes (rdf::serialize as TriG, then insert_turtle), not from Python itself. I missed this on my first pass, and it isn't from the rebase.
Both are defensible: the quads route keeps quads faithful, and the text route is how a ledger reads RDF collections. test_quads_come_back_out_of_a_ledger_as_they_went_in has no collection case, so nothing pins either answer today. But nothing in rdf-documents.md or types.md says the two differ, and someone who parses a file, filters it, and inserts it will get a different ledger than inserting the file. Maybe the TriG writer could write a well-formed spine (each node used once, ending in rdf:nil) as ( … ), so the quads route stores what the text route stores. Or, if spine-in, spine-out is the contract you want, a sentence in both docs. Either way, a collection case in that test would hold it. Minor and non-blocking, but if you agree either is right, I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Went with the writer, in 5fc38c1. Turtle and TriG now write a collection as ( … ) (nested ones too) when every node of it is a blank node with one rdf:first, one rdf:rest and nothing else, used by one triple, in no reification, triple term or other graph, and the chain ends in rdf:nil. Anything else keeps its triples, and a stored _:fdb-… node keeps its label. So ledger.insert(fluree.parse(doc)) stores a list, as ledger.insert(doc) does.
test_a_collection_writes_to_a_ledger_as_its_text_doesinserts one TriG document both ways, with a list in the default graph and one in a block, and compares the list values and the two exports. It fails with list writing turned off.- The writer tests cover each case that keeps its triples, and each goes red with its guard removed.
CONSTRUCT and Graph Store output in Turtle and TriG use the same writer, so they write such lists as ( … ) too; the commit and the body say so. every_format_reads_its_own_writing now compares up to blank-node labels (2d7c6da), since a list's nodes read back under fresh ones.
| // xsd:integer for a whole number, xsd:double for any other, xsd:boolean. | ||
| let datatype = match obj.get("@type").and_then(Value::as_str) { | ||
| Some(type_iri) => Datatype::from_iri(type_iri), | ||
| None => match val { |
There was a problem hiding this comment.
🟡 Optional — these adapter fixes also change what bulk JSON-LD import stores, and the PR body only talks about rdf::parse.
The adapter is bulk import's JSON-LD reader (fluree-db-transact/src/import.rs:1252), and inline shapes and inline ontology go through it too, so 87f337473 (now 05481afbd) is a write-path change as well. I imported the same document on next and on this PR: a bare 18446744073709551615 was stored as 1.8446744073709552e19 (xsd:double) and is now exact xsd:integer; "@type": "_:t" was an IRI named _:t and is now a blank node; @reverse and @included content was dropped and is now stored. (The bare-number datatype itself doesn't reach a ledger, since the ledger sinks re-infer from the value.) All three are the right answers.
The thing I'd flag is that fluree insert of that same document still stores the xsd:double, still gives back _:t rather than a stored _:fdb-… node, and writes @reverse and @included as properties literally named @reverse and @included (that last one is pre-existing on the transaction parser). So after this the two lanes disagree on one document in more places than before.
I wouldn't hold the PR on aligning the transaction lane. But since release notes come from the title and this one reads as ledger-free, maybe a line in the body and in docs/reference/compatibility.md that bulk JSON-LD import now keeps big integers exact, reads a blank-node @type as a blank node, and stores @reverse/@included. Minor and non-blocking, but if you agree I'd rather see it in this PR than lost in the backlog.
There was a problem hiding this comment.
Agreed, and done without touching the transaction lane. The body has a Bulk import section listing what bulk import, inline shapes and inline ontology now store: big integers exact, a blank-node @type as a blank node, @reverse/@included stored, and a node's @graph refused. It also says JSON-LD transactions still differ on the first three.
compatibility.md describes the two lanes under JSON-LD 1.1 as current behavior (a4a1370).
| match value.term(var.span) { | ||
| Term::Iri(iri) => Ok(Expression::Iri(iri)), | ||
| Term::Literal(literal) => Ok(Expression::Literal(literal)), | ||
| Term::TripleTerm(triple) => crate::parse::expr::triple_term_to_expr(*triple) |
There was a problem hiding this comment.
🟡 Optional — a triple-term parameter whose subject is a stored blank node matches as a pattern but is refused in an expression.
?r rdf:reifies $t with $t = {"@id": {"@id": "_:fdb-…", "ex:p": {"@id": "ex:o"}}} finds the reifier, as the inline <<( _:fdb-… ex:p ex:o )>> does. But ?r rdf:reifies ?t FILTER(?t = $t) fails with "blank nodes are not allowed in a triple term used in an expression": triple_term_to_expr → subject_term_to_expr (parse/expr.rs:906-912) refuses every blank-node part, including the _:fdb-… ids that lower_subject (lower/term.rs:84) lowers to the stored node. Typed into the query text that's the grammar's rule (bindbnode-tripleterm, the same one that makes SPARQL VALUES refuse it), but a parameter never goes through the grammar, and JSON-LD values accepts the same term.
It's a loud refusal, not a widening, so this is minor. Maybe the parameter path could take a _:fdb- subject or object as the stored node, the way the pattern lowering already does, so "in an expression it is the TRIPLE() constructor" holds for every term a parameter accepts. If you agree it's right, I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Fixed in 6e9c1a0. In an expression a parameter now names a stored node by its _:fdb-… id, which lowers to that node as the label does in a pattern, on its own or inside a triple term at any depth. A blank node typed into the query text is refused as before.
I took it one step past the triple-term case: a bare _:fdb-… parameter in FILTER(?s = $s) works too. positions_constrain_the_term had pinned that as refused, but otherwise ?t = $t would work and ?s = $s wouldn't.
a_stored_blank_node_parameter_is_one_node_in_an_expression_too reads back a stored node's id and checks:
- the triple-term parameter finds the same reifier through the
FILTERas through the pattern, with a second reifier present so a filter that passed everything would fail; - the bare form finds only that node's name.
It failed with your exact error before the change. The parameters section of sparql.md says so.
| - **Blank nodes** keep the document's labels. An anonymous blank node (`[]`, a | ||
| collection, an annotation) is labeled `bN`, avoiding any label the document | ||
| uses. Every parsed document can therefore be written in any format. | ||
| - **Errors:** a malformed document raises an error naming its line and column. |
There was a problem hiding this comment.
🟡 Optional — a line on memory would help anyone who points this at a big file.
fluree.parse holds the document, the Dataset and every Quad at once. On a 68.5 MB, 1M-line N-Quads file (a debug wheel, on my first pass; none of the reader or binding commits changed in the rebase), peak RSS went from 35 MB to 683 MB, about 10× the file, so a 1 GB dump wants roughly 10 GB. The GIL is released while Rust parses (a Python thread kept counting the whole way through), and fluree.aio.parse does keep the event loop alive, but building a million Quads on the worker thread holds the GIL, so a 10 ms heartbeat got 249 of about 569 ticks during the parse.
Neither is a bug. I'd just say it here and in the Python guide: the document is read whole, at roughly ten times its size in memory, and bulk import is the way to load a large file into a ledger. The aio docstring's "so a large document does not hold up the event loop" could also say "holds it up less". Minor and non-blocking, but if you agree it's right I'd rather see it in this PR than lost in the backlog.
There was a problem hiding this comment.
Added in 125a621:
- a Memory bullet on the reference page: a document is read whole, at roughly ten times its size from Python, and bulk import is the way to load a large file;
- the same in the Python guide, pointing at
conn.create(name, source=…).
The aio.parse docstring and the guide's async paragraph now say the quads are built holding the GIL, so a large document still slows the event loop.
| let dt = compact_dt(compactor, dt_sid)?; | ||
| Ok((ResolvedValue::String(s.clone()), dt)) | ||
| } | ||
| FlakeValue::TripleTerm(t) => { |
There was a problem hiding this comment.
👍 Resolving triple terms here doesn't open a policy hole, and that's the thing I most wanted to check after #2017. execute filters the decoded flakes through filter_flakes_for_graph, which runs term_visible over every part of every triple term, nested ones included, before the schema exemption.
I ran it with the SSN-restriction policy from it_graph_commit.rs, on a commit holding c1 rdf:reifies <<( bob ssn … )>>, c2 rdf:reifies <<( alice ssn … )>>, doc mentions <<( x quotes <<( bob ssn … )>> )>> and an annotation on Bob's SSN. As Alice, it shows c2's link and the annotation's ex:source, and Bob's SSN appears nowhere: not the base triple, not the reifier link, not the nested mention. Please keep it on that path.
|
|
||
| /// The triple term `{"@id": {"@id": s, p: o}}`: its subject an IRI or a | ||
| /// stored node, its predicate an IRI. | ||
| fn triple(name: &str, term: &serde_json::Map<String, JsonValue>) -> Result<Self> { |
There was a problem hiding this comment.
👍 Every part of a triple-term parameter goes back through Value::parse and Self::node, so the #2024 guard holds at every depth: a plain _:x as the subject or the object is refused, and only a stored _:fdb-… id gets through. I ran the parameter against the inline term, SPARQL VALUES and FILTER(?t = $t) for an integer, the string "30" against a stored 30, i64::MAX, a u64 and a double, and a nested language-tagged term against the inline term and VALUES: they agree on all of them. A triple-term parameter as a predicate or a graph name is refused too.
`genesis_ledger` is async since the ledger lifecycle change on next.
…'t be held
The JSON-LD adapter skipped a node's `@graph` for a sink without named
graphs, and its module doc described that as the contract. Bulk JSON-LD
import, inline shapes and inline ontology are such sinks, so a node like
`{"@id": "ex:g", "ex:label": "G", "@graph": [...]}` imported its label,
lost the graph's contents, and reported success.
The adapter now refuses it, as it already refuses a reifier such a sink
can't hold and as the TriG dialect refuses a named graph. A top-level
`@graph` envelope is unwrapped by expansion and is unaffected.
Sinks mint anonymous blank nodes as `-bN`, a label no Turtle-family document can write. A JSON-LD blank-node label is any string, so a document's `_:-b1` and the first anonymous node were one node: in `rdf::parse`, the anonymous node's properties landed on the document's node, with a self-loop between them. `node_term`, where every JSON-LD blank label enters a sink, gives a label starting with `-` one more, which can never equal a mint. It covers inline shapes and ontology as well. The reference page says so.
…erently Bulk import and `rdf::parse` keep an integer past 64 bits exact, read a blank-node `@type` as a blank node and store `@reverse`/`@included`; a JSON-LD transaction does none of the three. The compatibility page says so, and the `create` page says JSON-LD import refuses a node naming a graph.
…size `fluree.parse` holds the text, the dataset and every `Quad` at once, about ten times the document's size, so a large file belongs in bulk import. And `fluree.aio.parse` releases the GIL only while Rust parses: building the quads holds it, so a large document still slows the event loop. The reference page, the Python guide and the `aio.parse` docstring say so.
… `( … )` `fluree.parse` reads `( 1 2 )` as its `rdf:first`/`rdf:rest` triples, and `ledger.insert(quads)` writes quads to the ledger as TriG. The writer wrote those triples out as they were, so the ledger stored five facts with a blank node where inserting the document's text stores an ordered list: `?s ex:list ?o` answered a blank node in one ledger and `1, 2` in the other. The Turtle and TriG writers now write a collection as `( … )`, nested ones too, when every node of it is a blank node with exactly one `rdf:first` and one `rdf:rest` and nothing else, used by exactly one triple and in no reification, triple term or other graph, and its chain ends in `rdf:nil`. That reads back as the same triples, and a ledger stores it as a list, as it stores the document's own `( … )`. Anything else keeps its triples, and a stored `_:fdb-…` node keeps its label. A graph with no `rdf:first` skips the scan. The same writer serves CONSTRUCT and Graph Store output in Turtle and TriG, which now write such lists as `( … )` too.
`?r rdf:reifies $t` found the reifier of a triple term parameter whose subject is a stored node's `_:fdb-…` id, but `FILTER(?t = $t)` refused it: "blank nodes are not allowed in a triple term used in an expression". A bare `_:fdb-…` parameter was refused in an expression the same way. So a triple term read back from one query couldn't be filtered on in the next. The refusal is the grammar's: a blank node written in an expression is a fresh node. A parameter holds only stored nodes, which a pattern already reads as the node they name. In an expression the parameter now names a stored node by its `_:fdb-…` id, which lowers to that node, on its own or inside a triple term at any depth. A blank node typed into the query text is refused as before.
|
@aaj3f on headline note 1, where bulk import's TriG reading goes: let's move import onto your locator and segment parser from #2008, not onto It already does what a ledger write needs: the
I've rewritten #1930 to match. It's now about bulk import alone, since #2008 fixed the transaction lanes, and its fix is import onto the |
TriG now writes a well-formed collection as `( … )`, whose nodes read back under fresh labels, so `every_format_reads_its_own_writing` no longer gets identical triples. It compares the round trip up to a renaming of blank nodes instead, which is what RDF promises: a small `isomorphic` check that tries every renaming of the dataset's few blank nodes, reifications and named graphs included. Writing the list's items in reverse turns it red.
Summary
Python can now represent RDF 1.2 data in full, and can read and write RDF documents without a ledger. Rust gets the same document reading and writing as
fluree_db_api::rdf.Triple terms
fluree.Triple. Query results bind triple terms asTriple, writes take them, and"@reifies"writes take them too.{"@id": {"@id": s, p: o}}). A stored blank node's_:fdb-…id in a parameter is that node in an expression too (FILTER(?t = $t)), on its own or inside a triple term, as it already was in a pattern.ResolvedValue::TripleTerm). That coversledger.changes(),fluree showand the commit endpoint.RDF documents without a ledger
fluree_db_api::rdf. It providesparse,serialize,RdfFormatandRdfError, converting Turtle, TriG, N-Triples, N-Quads and JSON-LD to and from aDataset. A malformed document isRdfError::Syntax, with its line and column.Dialect::TriG).parse_ntriplesandparse_nquads. It readsr rdf:reifies <<( s p o )>>as a reification, as Turtle does.GraphSinkgains quad list items and quad reifiers.GraphCollectorSink::with_named_graphsandinto_datasetcollect named graphs.into_datasetrelabels anonymous blank nodes so every writer can write them.Dataset::add_quadreads anrdf:reifiesquad whose object is a triple term as a reification.@graphas a named graph, for sinks that hold quads. A sink that doesn't refuses it (see Bulk import).@annotation,@reifies,@reverseand@included.@annotationon value objects.fluree.parse,fluree.serialize,fluree.Quad,fluree.aio.parseandfluree.aio.serialize.literals="lexical"keeps literals exactly as written.ledger.insert(quads)andupsert(quads)write quads. A blank-node graph name is refused, since a ledger names its graphs with IRIs.fluree_db_api::rdfand no longer depends on the graph crates directly.Fixes found along the way
{| |}).@typewas typedxsd:string. It now getsxsd:integer,xsd:doubleorxsd:boolean.@typebecame an IRI; it is now a blank node.-(_:-b1, legal only in JSON-LD) was the same node as the first anonymous node a sink minted. It now gets one more-(--b1) and stays apart.rdf:typewhose object is a literal or a triple term. Such a type is now written as anrdf:typeproperty.ledger.insert(fluree.parse(doc))stored a collection as itsrdf:first/rdf:resttriples, whereledger.insert(doc)stores an ordered list. The Turtle and TriG writers now write a well-formed collection (blank nodes used once, ending inrdf:nil) as( … ), so both store a list. CONSTRUCT and Graph Store output in Turtle and TriG write such lists as( … )too.Bulk import
The JSON-LD adapter is also bulk import's JSON-LD reader, and inline shapes and inline ontology go through it, so the adapter changes above change what those store:
xsd:integer, where it was stored asxsd:double;@typeis a blank node, where it was an IRI named_:t;@reverseand@includedcontent is stored, where it was dropped;@graphis refused, where it was stored without the graph's contents and the import reported success. A top-level@graphenvelope is unaffected. Named graphs load as TriG or N-Quads.JSON-LD transactions (insert, upsert) don't go through the adapter and still differ on the first three.
docs/reference/compatibility.mdsays where.Tests
fluree_db_api::rdf(the*_readertests intestsuite-sparql). Their skip registers are checked in both directions. The remaining gaps are the shared lexer cases and annotation-of-annotation.Docs
docs/reference/rdf-documents.mdcovers the formats and how each syntax writes named graphs, annotations, reified triples and triple terms. It also lists the JSON-LD limits.Supersedes #1555, #1569 and #1578, the earlier RDF toolkit stack. Its quad model and dataset formats are rebuilt here on
next. Its CLI commands (fluree rdf check/count/convert) are not part of this PR.Follow-up: #1930. Since #2008, a TriG insert reads
( … )and[ … ]inside a block, so #1930 is now about bulk import alone, which still readsGRAPHblocks with the separate block parser. Import moves onto #2008's locator and segment parser, the reader every transaction write path uses, so a file imported and inserted are read alike. The TriG dialect added here stays the document reader behindrdf::parseandfluree.parse.