Repository navigation
fix(json-ld): honor @vocab and @json coercion, term @language, null terms and @index maps - #2283
Conversation
…erms and @index maps Six JSON-LD context features expanded wrongly in transactions, bulk import and JSON-LD queries: - A "@type": "@vocab" term wrote its value as a string. It is now an IRI: a term, a compact IRI, or relative to @vocab, else @base. The query parser reads it the same way, so a where pattern matches what an insert wrote. - A "@type": "@JSON" term made a JSON literal only of an object: a string or number lost the datatype, and an array split into separate values, its objects becoming nodes. The whole value is now one JSON literal, and bulk import writes a number or boolean JSON literal as a JSON document rather than an xsd value, as an insert does. - A default @language with a typed term, or with a value object naming its own @type, refused the document. A datatype now excludes the default language, and a value object's own @language overrides its term's datatype; a value object naming both is still refused. - A term's "@language": null still took the default language. - A term defined as null, or with "@id": null, failed to parse. Its property is now dropped rather than expanded against @vocab. A where pattern on it is refused: matching nothing, or dropping the pattern, would each answer a different query. - An @index map's keys expanded as properties of a blank node. They now only index the values; a property-valued @index, whose keys would be data, is refused rather than dropped. The transactions overview called a string @context an external context; Fluree reads it as @vocab and fetches nothing. The JSON-LD compatibility section lists the coercions and containers, and the existing limits.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz I like the approach here: each coercion is fixed in the one expander that inserts, imports and query contexts all read, and the explicit-form equivalence test is a nice way to prove it. Two things in the review below I'd hold the merge for. The @json coercion of a string runs into the writers' "a string @value is serialized JSON" convention, so "hello" stores text that breaks every read of that subject. And @json and @index need the same where twin you gave @vocab, since queries that matched before this PR now return nothing.
On the release line: I'm fine with these landing on main rather than next, even though by the body's own test they change how working documents expand. It's what we did for reverse terms and scoped-context IRIs, and the @index and @json-array cases write silently wrong shapes today, so holding them for 5.0 feels like overkill. What I'd want with it is the Behavior-changes entry (finding 3 below), with the @vocab repair update.
Separately, this is the seventh JSON-LD expansion deviation we've found by hand since September:
a212dfe71(empty@list),f344eff5e(@reverse/@included/@nest),57d373ebf(scoped-context term IRIs),c2d6aae3e(bulk import@graphscoping),476c0f2c0onnext(blank-node graph names), this PR, #2284 (@base, propagation,@direction)
We run the W3C SPARQL suite with a skip register that can only shrink, but not the json-ld-api expand/toRdf suite, which would have caught each of these, this PR's @json string case included. Not for this PR, as the point fixes are right here, but I think a testsuite-jsonld harness is worth its own effort. The where-side gaps are #2033's class (one term parser), so the point fix here is the right altitude.
Also a heads-up for whoever merges main into next after this lands: it conflicts with #2284 in expand.rs in three hunks (the @index block vs expand_nested_node, parse_value_object's language vs direction, and the appended tests). All three are mechanical. The @index recursion needs #2284's nodes threaded through.
Full review below:
Approving w/ strong recommendation to consider at least the major/blocking items below, if not all of them
This is a really nice batch of conformance fixes, @bplatz. The @vocab, "@language": null, null-term and @index changes are each a few lines in the right place, and the @base fallback for @vocab matches on the where side too (Claude checked both the @vocab and @base-only contexts end to end). Three things need to land before merge. First, the @json coercion of a string writes a literal whose text isn't JSON, so every JSON-LD read of that subject fails, and "5" and "{\"a\":1}" silently change type (expand.rs:225). Second, @json scalars and @index maps in where now match nothing where they matched before (node_map.rs:886). Third, the data changes, including the @vocab read-side effect on existing ledgers and {"@id": null} dropping a property that used to be written, need a ### Behavior changes entry with a repair recipe, like the reverse-term one (compatibility.md).
Adherence to repo commitments:
- Patterns/abstractions: ✔ The fixes go in the shared expander, and
@vocab/nullare mirrored in the query parser.⚠️ @json/@indexaren't mirrored there; that's #2033's class, and the point fix is right for now. - Performance (speed first, memory second): ✔ Expansion only, once per document. New branches run only for the feature, and each key costs one flag check. No query-engine change, so no performance-degradation risk.
- Deployment targets: ✔ n/a. Pure in-memory parsing, shared by every host (embedded
fluree-db-api,fluree-db-server, wasm32), with no I/O, clock or process state.wasm32/wasm-smokeare green on the head. - Testing:
⚠️ Good unit coverage and a strong equivalence test, all green in CI (run 42503796797) and on a box. But no case writes a string under@jsonand no test reads a coerced value back through a query, which is where both blocking findings live. - Conventions:
⚠️ Clear multi-line commit and an accurate docs fix for the string@context. Missing the### Behavior changesentry this kind of change has always carried, and the body's "context failed to parse" is true for the barenullform only.
Verified at branch HEAD eac9be949: CI green; on an EC2 box, fluree-graph-json-ld lib tests (169 passed), the new transact and query-parser tests, and eight insert-and-read-back probes at this head and at the base eccd062a1, which are the source of every before/after quoted above.
Requesting changes for the @json string case and the where parity, both of which should be small. Happy to talk through any of these.
|
|
||
| // A term typed `@json` makes its whole value one JSON literal, | ||
| // whatever its shape. | ||
| _ if type_val == Some(&TypeValue::Json) => { |
There was a problem hiding this comment.
Blocking: A @json-typed term's string value is now stored as a JSON literal whose text is not JSON, and every JSON-LD read of that subject then fails.
This arm wraps the value as-is, so "p": "hello" expands to {"@value": "hello", "@type": "@json"}. Both writers read a string @value on an rdf:JSON literal as an already-serialized document. The transact parser canonicalizes it if it parses and otherwise stores it as written (fluree-db-transact/src/parse/jsonld.rs:2287-2296). Bulk import sends it down the string path (the comment this PR adds at adapter.rs:641). The spec's JSON literal for the string hello is the JSON text "hello", quotes included.
Claude reproduced this on a box at eac9be949, inserting through Fluree::insert under {"p": {"@id": "ex:p", "@type": "@json"}}:
| value written | base eccd062a1 stores |
this PR stores | JSON-LD read at this PR |
|---|---|---|---|
"hello" |
"hello" xsd:string |
hello rdf:JSON |
Invalid JSON in @json value: expected value at line 1 column 1 (select and crawl) |
"5" |
"5" xsd:string |
5 rdf:JSON |
the number 5 |
"{\"a\":1}" |
the string xsd:string |
{"a":1} rdf:JSON |
the object {"a":1} |
So a document that transacted fine yesterday now writes a value that breaks every query touching it, and two others silently change type. I don't think we want to change the explicit-form convention ({"@value": "{\"a\":1}", "@type": "@json"} meaning a serialized document is useful and probably relied on). That leaves the coerced arm to serialize a string before it goes in, for example:
_ if type_val == Some(&TypeValue::Json) => {
// Writers read a string `@value` as serialized JSON, so a coerced
// string goes in serialized: `"hello"` is the JSON string, not text.
let literal = match value {
JsonValue::String(_) => JsonValue::String(crate::normalize::normalize(value)),
_ => value.clone(),
};
let mut obj = Map::new();
obj.insert("@value".to_string(), literal);
obj.insert("@type".to_string(), json!("@json"));
Ok(vec![JsonValue::Object(obj)])
}The json!("text") case in json_typed_term_keeps_the_whole_value would change to expect the serialized form. It would also be worth a context_coercions_write_their_explicit_forms case pairing "d": "hello" with {"@value": "\"hello\"", "@type": "@json"}, plus one read-back through a query. The equivalence test can't see this today, because the explicit form of a string shares the bug.
There was a problem hiding this comment.
Addressed in 5c98bd1. One related thing turned up while testing it: a variable under a @json term in an update template ("doc": "?v") no longer bound at the previous head, so the delete matched nothing and the insert wrote the string. Fixed in the same commit, with json_typed_term_binds_a_template_variable.
| .as_ref() | ||
| .and_then(|e| e.type_.as_ref()) | ||
| .is_some_and(|t| matches!(t, TypeValue::Id)); | ||
| .is_some_and(|t| matches!(t, TypeValue::Id | TypeValue::Vocab)); |
There was a problem hiding this comment.
Blocking: The where side mirrors the @vocab coercion but not the @json and @index ones, so where patterns that matched before this PR now match nothing.
This line makes a @vocab term's where value an IRI, "so a where pattern matches what an insert wrote". The same reasoning applies to the other two coercions this PR changes on the insert side. A @json term's scalar in where still goes through parse_json_value as an xsd value. An @index term's map in where is still read as a nested node pattern.
Claude reproduced both, at the base and at this head:
"p": 5under a@jsonterm: the base stores5xsd:integer, and{"@id": "?s", "p": 5}returnsex:s. This PR stores5rdf:JSON, and the same query returns[]."m": {"a": "x"}under"@container": "@index": the base stores a blank node, and{"@id": "?s", "m": {"a": "x"}}returnsex:s. This PR stores"x", the same query returns[], and only"m": "x"matches.
That's silent wrong results for a query written against the same context as the insert. It's exactly the outcome the null-term comment above argues against ("matching nothing … would answer a different query than the one written"). For @json, building the literal here (the canonical JSON text, with an rdf:JSON constraint, and a string serialized as in the comment on expand.rs:225) would make the pattern match what the insert wrote. For an @index map, we could treat its values as the property's values, as the expander now does, or refuse the map form with an error the way a null term is refused. Refusing is the cheaper of the two and still honest. #2033 is the structural home for all of this (one term parser), so a point fix here is the right altitude for this PR.
There was a problem hiding this comment.
Addressed in 5c98bd1 for @json. For @index I kept a where map as a node pattern rather than refusing it: the term's values can be nodes, and "m": {"@id": "?o", "ex:q": "?q"} is a legitimate traversal that a refusal would break. It is pinned by index_term_map_in_where_is_a_node_pattern, and the Behavior changes entry says to match an index-map value by writing the value itself.
| - Other `@`-keywords on a node object are refused, by a transaction and by a bulk import alike, where the algorithm drops them with a warning. A refusal names the key, so the document can drop it or rename it. | ||
| - A type-scoped context also applies to the node objects nested in the typed node (the algorithm's default is `@propagate: false`), and a node with several types applies their scoped contexts in the order written rather than in lexicographic order. | ||
| - A term defined only in a property-scoped context, used outside it, is kept as a bare key rather than dropped. | ||
| - A remote context is not fetched. A string `@context` sets `@vocab` to that string, so `"@context": "https://schema.org"` reads bare terms as schema.org IRIs; inline any other definitions the document needs. |
There was a problem hiding this comment.
Blocking: This changes what working documents write, and on the read side what existing data matches, but there's no ### Behavior changes entry.
The PR body's "Effect on existing ledgers" section is the right content, but it lives only in the PR. Every earlier JSON-LD fix that changed what a document writes got an entry under ### Behavior changes (line 369): reverse terms and scoped-context IRIs, for instance, each with what changed and how to repair it. The changes here that need one:
- a
@vocabterm's string now writes an IRI; - a
@jsonterm's array writes one literal (it was n values, with objects becoming nodes), and its number or string writesrdf:JSON; - a term's
"@language": nullwrites untagged strings; - an
@indexmap writes its values (it was a blank node whose keys were properties); - a term defined
{"@id": null}drops its property. On the base, it wrote the key as a vocab-relative property, since the"@id"arm ignored a non-string and the id was inferred from the key, so the body's "the context failed to parse" holds only for the barenullform; - a context with a property-valued
@indexterm is refused, even when the document doesn't use it.
The @vocab change has a read-side effect that the body's "Data already stored is not rewritten" doesn't cover. A ledger that wrote "status": "Active" through a @vocab term holds the string. With this PR's node_map.rs:886, the same query with the same context looks for the IRI, so those rows stop matching after the upgrade. A repair update would be worth putting in the entry, something like:
DELETE { ?s ex:status ?old } INSERT { ?s ex:status ?new }
WHERE { ?s ex:status ?old FILTER(isLiteral(?old)) BIND(IRI(CONCAT("http://example.org/", STR(?old))) AS ?new) }Commenting here because docs/reference/compatibility.md:369 is not in this diff.
There was a problem hiding this comment.
Addressed in 5c98bd1. The @vocab repair update is in the entry and was run against a ledger. @json and @index values get delete-and-rewrite guidance: a split array does not record which values it held together, and a STRDT(..., rdf:JSON) rewrite is refused by the transactor.
| /// A string a `"@type": "@vocab"` term coerces: a term or compact IRI, else | ||
| /// relative to `@vocab`, else to `@base`. | ||
| fn vocab_value_iri(s: &str, ctx: &ParsedContext, strict: bool) -> Result<String> { | ||
| let (expanded, entry) = details(s, ctx, true); |
There was a problem hiding this comment.
(Optional) This is more of a catch than a design point. A null term used where an IRI is expected comes out as the bare key. details → match_exact returns the key when the entry has neither id nor reverse (expand.rs:16-21), so vocab_value_iri returns "gone", and parse_type does the same for "@type": "gone". Claude reproduced both under {"@vocab": "http://example.org/", "gone": null, "p": {"@type": "@vocab"}}: "p": "gone" and "@type": "gone" each insert OK and store the relative IRI gone. On the base, the context failed to parse, so this path is new with this PR. The spec's IRI expansion returns null for a null-mapped term, so the value (or type) would be dropped, like the property is at :786. A null_mapping check in vocab_value_iri and in parse_type's expansion would cover it. It's minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
| .or_else(|| context.language.clone()); | ||
| }), | ||
| }; | ||
| let lang = match type_iri { |
There was a problem hiding this comment.
(Optional) I may be wrong about how much this matters in practice, but "@language": null on a term reaches bare strings and not value objects. Claude reproduced this under {"@language": "en", "t": {"@id": "ex:t", "@language": null}} with "t": ["plain", {"@value": "obj"}]. plain is stored untagged, but obj is stored @en. Your code didn't introduce this. The root is that parse_value_object applies the default language to value objects at all, where the spec applies the default language only to bare strings (value expansion), never to an explicit @value object. But since this PR rewrote exactly these lines, it seems like the cheap moment to make the None arm use only explicit_language. That also makes the term's "@language": null moot here. It's minor, but I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Agreed, and the same function also applies the term's datatype to a value object, which should change with it. Both change what working documents write, so filed as #2356 for 5.0.
| } | ||
| // An index map's keys would become values of this | ||
| // property; refused rather than dropped. | ||
| "@index" => { |
There was a problem hiding this comment.
(Optional) Refusing a property-valued @index is right, but refusing it at context parse means a document is refused when its context merely carries such a term. Claude reproduced this: a context with "idx": {"@id": "ex:idx", "@container": "@index", "@index": "ex:q"} and a body that only writes ex:p inserts fine on the base and is refused at this head (term 'idx': a property-valued @index is not supported). Shared contexts tend to be bigger than any one document. We could record the property on the entry and refuse in the @index arm of parse_node_value when a value actually uses it. It's minor and non-blocking, but if you agree, I'd rather see it in this PR than lost in the backlog.
| // whatever its shape. | ||
| _ if type_val == Some(&TypeValue::Json) => { | ||
| let mut obj = Map::new(); | ||
| obj.insert("@value".to_string(), value.clone()); |
There was a problem hiding this comment.
(Optional) Two edge cases on the "whatever its shape" claim, both reproduced by Claude at this head. First, "p": null under a @json term is dropped, because the JsonValue::Null arm above runs first. In the 1.1 expansion algorithm, the @json step comes before the step that drops a null value, so the expected result is the JSON literal null. Moving this arm above Null would need a matching Value::Null case in the adapter's rdf:JSON arm. Second, with "@container": "@list", a @json term's [1, 2] is stored as one non-list literal, because this early return skips the array arm's list wrapping. The spec makes it a one-element list holding the literal. Both are obscure, so I'm not hung up on them. I'd still rather see them folded in now if you agree.
| /// default language, a term's `"@language": null` no language, a `null` | ||
| /// term nothing, and an `@index` map the values under its keys. | ||
| #[test] | ||
| fn context_coercions_write_their_explicit_forms() { |
There was a problem hiding this comment.
I really like this test's shape: each coerced form has to write exactly what its explicit equivalent writes, and against the old expander all six cases differ. It's a much stronger property than asserting expanded JSON. Adding a @json string case here (see the comment on expand.rs:225) would have caught the one hole.
…ll-term values A string under a `@json`-typed term was wrapped as written, and the writers read a string `@value` on a JSON literal as a serialized document: `"hello"` stored text that is not JSON and broke every read of the subject, and `"5"` became the number. The expander now serializes a coerced string. A `where` pattern under a `@json` term builds the same canonical `rdf:JSON` literal, so it matches what an insert wrote. A variable under such a term in an update template binds again; it was written as the JSON string of its name. A `@vocab` value or `@type` naming a term defined as `null` is dropped rather than stored as the bare key. A property-valued `@index` is refused where an index map uses it, not when a context carries it. A map in `where` stays a node pattern under an `@index` term, pinned by a parser test. The compatibility reference gains the behavior-changes entry and the repair note for values earlier releases wrote.
|
Filed #2358 for the |
Six JSON-LD context features expanded wrongly in transactions, bulk import and JSON-LD queries. Each now follows JSON-LD 1.1.
"@type": "@vocab"term@vocab(else@base)"@type": "@json"term"5"is not the number@languagewith a typed term, or with a value object that has its own@type@typeand@languageis still refused"@language": nullnull(or"@id": null)nullform failed to parse. The"@id": nullform wrote the key as a property relative to@vocab@vocabvalue or@typethat names the term@container: @indexRelated changes:
@vocab-typed term's value as an IRI and a@json-typed term's value as the canonical JSON literal, so awherepattern matches what an insert wrote. JSON-LD queries have their own term parser (One JSON-LD term parser for values, where patterns and SPARQL parameters #2033 tracks merging the two).@jsonterm.wherepattern on a term defined asnullis refused. Matching nothing, or dropping the pattern, would each answer a different query than the one written.wherestays a node pattern under an@indexterm, because the term's values can be nodes and a pattern has to reach into them. A value written through an index map is matched by writing the value itself.@json-typed term binds, as it did before; it is not written as the JSON string of its name.@jsonliteral whose@valueis a number or boolean is now stored as a JSON document, as an insert already stores it, rather than as anxsdvalue.@index: an index map under a term with"@index": "<property>"is refused instead of silently losing its keys. A context that only carries such a term is accepted.@contextas an external context. Fluree reads it as@vocaband fetches nothing.@id,@typeand@graphcontainers.Effect on existing ledgers
Documents that use these features now write different values: IRIs instead of strings for
@vocabterms, one JSON literal for any value of a@jsonterm, untagged strings under"@language": null, and the values of an@indexmap instead of a blank node.Data already stored is not rewritten. Values an earlier release wrote through a
@vocab,@jsonor@indexterm keep their old shape, and the same context now reads and writes the new one, so awherepattern, delete or upsert written through the term no longer reaches them.docs/reference/compatibility.mdhas the Behavior changes entry and the repair update for@vocabvalues.Left for
nextResolving
@baseper RFC 3986, and stopping type-scoped contexts at nested nodes, both change how documents that already work today expand. They belong in the major release.Follow-ups
@languageand the term's datatype; targeted at 5.0, since it changes what working documents write)@jsonterm'snullvalue and@listcontainer)json-ld-apiexpand and toRdf suites)Performance
Expansion changes, and it runs once per document. The query parser gains one type comparison per
whereproperty; query execution is untouched. The new branches run only when a document uses the feature. Each property key gains a single flag check for thenullmapping.Tests
fluree-graph-json-ld(expansion):vocab_typed_term_expands_strings_as_iris,datatype_excludes_the_default_language,value_object_language_overrides_the_term_datatype,term_language_null_clears_the_default,null_term_drops_its_property,null_term_names_no_value_iri,index_container_keys_only_index_the_values,json_typed_term_keeps_the_whole_value.fluree-graph-json-ld(adapter):json_literal_of_a_scalar_is_a_json_document.fluree-db-transact:context_coercions_write_their_explicit_formschecks that each coerced form writes the same insert templates as its explicit equivalent.fluree-db-query:vocab_typed_term_value_is_an_iri,json_typed_term_value_is_a_json_literal,index_term_map_in_where_is_a_node_patternandnull_term_in_where_is_refused.fluree-db-api:json_typed_term_values_round_trip_through_whereinserts each JSON shape through a@jsonterm and reads it back through awhereunder the same context; it fails with either the expander or the query-parser change removed.json_typed_term_binds_a_template_variablecovers the update template.