Repository navigation
feat(shacl): validate against additional data graphs (f:additionalDataSource) - #2264
Conversation
…ated one SHACL checks a record against the graph it is written to, so a shape whose rules depend on data kept in another graph (a shared catalog, a price list) fails even when the data is right. `f:additionalDataSource` on `f:shaclDefaults` lists graphs to read with the validated graph, as one graph, for every constraint: `sh:class`, property paths, `sh:node`, cardinality, `sh:closed` and `sh:sparql`. - DataView (fluree-db-shacl/src/data_view.rs) is the validated graph plus its sources. Its range reads the union, keeps a fact stored in several graphs once, and returns index order. The checking functions in validate.rs and path.rs read through it; targeting and the choice of focus nodes stay on the written graph. - sh:sparql runs over an implicit dataset whose default graph is the union. - sh:class reads a value's types from the union, and the subclass walk reads the listed graphs, the validated graph included when it lists itself. - The setting is per graph: an f:graphOverrides list replaces the ledger-wide list. Sources resolve through the transaction's graph delta, so a write may create a listed graph. An unknown graph, the config and txn-meta graphs, and f:ledger / f:atT / f:trustPolicy / f:rollbackGuard are errors. A cross-ledger f:shapesSource works with local sources. - Inline transaction shapes and the validate API read the same graphs. The validate API now always reads the ledger config, and a config read failure fails validation (ConfigUnavailable, 500) as it fails a transaction, instead of validating as if there were no config. Docs: a walkthrough guide (docs/guides/cookbook-shacl-across-graphs.md), the reference section in cookbook-shacl.md, and the setting in setting-groups, override-control, vocabulary, writing-config, the validate endpoint and CLI pages, and the compatibility notes. Tests: it_shacl_additional_data (15), it_shapes_cross_ledger::cross_ledger_shapes_read_local_additional_data_sources, and shacl_tests::validate_report_fails_when_the_config_cannot_be_read. Co-authored-by: mrpraneeth <[email protected]>
0d17a09 to
45bfaee
Compare
…drops need Main renamed GraphRegistry::graph_id_for_iri to assigned_graph_id and has configured sources ask existing_graph_id, so a graph a drop took is not read. The merge left resolve_shacl_graph_source without the t that lookup needs, and resolve_additional_data_g_ids on the old name. Both now take t and resolve through existing_source_graph: f:shapesSource as main does, and f:additionalDataSource the same way, still falling back to a graph the transaction itself creates.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is really nice, and at a design level no pushback from me: DataView as the one place every constraint reads from (the signature change means the compiler put every read through it), targeting staying on the written graph, and the walkthrough guide are pretty much what I'd hoped for when #2204 came in. I'm also glad the cross-ledger f:shapesSource combination works rather than being refused. A few headline notes:
(1) The one thing I don't think should merge as-is: the sh:class fast path (validate.rs:2836) still reads the last index build's hierarchy, which the indexer extracts from every graph and which keeps a retracted edge until the next build. That's the same split you closed for targeting, policy and GraphQL in 3e44a8ffe, and this read wasn't part of it. Your code didn't introduce it, but the rules this PR documents depend on it: an unlisted graph's own subclass edges are ignored, and a per-graph list replaces the ledger's. Claude's probes show both flip after an index build (a listing that fails before the build commits after it), and reading the engine's current hierarchy instead is a one-line fix. Details inline.
(2) On full reads: I'm on board with listed graphs being read in full, past the writer's policy. It keeps validation identity-invariant, the way policy-in-transactions.md already says shapes are, and listing a graph is a config writer's call. The cookbook and the walkthrough say it plainly. One small ask: let's put the same sentence in docs/security/policy-in-transactions.md, next to the identity-invariance line, since that's where someone configuring policy will look. Something like: SHACL reads the written graph, the shapes graph and any f:additionalDataSource graph in full, so a violation can show a writer a value their policy hides; list only graphs every writer may see, or accept that.
(3) Thanks for e803f6ba7: now that #2251 is on main, resolving f:additionalDataSource through existing_source_graph as of t is the split I'd asked for there, so a dropped catalog fails like an unknown one instead of reading as empty. No textual conflicts with #2249 or my #2214.
(Approving to unblock you, as you've been waiting on my review for over a week)
Full review below:
🔄 Request changes.
This is carefully built, @bplatz: the union lives in one read type the compiler forces every constraint through, targeting stays on the written graph, the config side reuses the existing resolver shapes (and f:shapesSource keeps its error text), and the tests read like a spec of the semantics section. One thing needs to land first: the sh:class fast path reading the index root's hierarchy, inline with a one-line fix, plus an indexed test and a compatibility line. The rest is optional.
Adherence to repo commitments:
- Patterns/abstractions: ✔
DataViewis a single chokepoint for reads; the config side extendsread_graph_source_refs,CONFIG_EDGESandMergeableGroup;f:shapesSourceresolution moved onto the shared helpers.⚠️ sh:class's fast path readssnapshot.schema_hierarchy()where targeting, policy and reasoning read the current hierarchy (inline), and source resolution adds one more per-site selector match, now through the sharedexisting_source_graph(headline note 3). - Performance (speed first, memory second): ✔ No regression for a ledger without the setting: the added work is per transaction or per range read (an empty-map lookup, one
RangeMatchclone), never per flake. With K listed graphs each read becomes K+1 scans plus a dedup that clones the validated graph's result: opt-in and linear in K, with two cheap trims inline (optional). No SHACL bench exists. - Deployment targets: ✔ Shared code in
fluree-db-shacl,-transactand-api, so the embedded library, the server and wasm32 all run it; nothing reaches for a task, a process-lifetime cache, a clock or the filesystem, andwasm32andwasm-smokeare green on this head. - Testing:
⚠️ 15 integration tests plus the cross-ledger and fail-closed-config tests, wired intogrp_graphsourceand the lib and run by name in CI on this head; Claude's mutation checks of the dedup and thesh:sparqldataset turn their tests red. All of them run on novelty only, which is how the hierarchy case got through (inline). - Conventions: ✔ Thorough multi-line commit body, co-author credit for #2204, a self-describing title, and docs across the cookbook, the walkthrough, setting groups, override control, vocabulary, the validate endpoint and CLI pages, and compatibility.
⚠️ cookbook-shacl.md:524's subclass sentence holds only before an index build (inline).
Verified at branch HEAD (45bfaee9e): CI's test job (15,654 tests, all passed), clippy, fmt, wasm32 and testsuite-sparql are green on this SHA. On an EC2 box Claude added four probe tests (write, index, reload, write again): two show the documented subclass rules flipping after an index build, one shows a retracted edge still counting, and one shows the union reads holding over indexed sources. With the one-line fix all four pass, as do fluree-db-shacl and fluree-db-transact (537 tests) and fluree-db-api's lib plus seven grp_* suites and it_unenforced_shapes_warning (3,284 tests, the probes included). Removing the dedup or the sh:sparql dataset turns the matching tests red.
Requesting changes for the sh:class hierarchy; with that in, I'm happy to approve. Happy to talk through any of these.
| // indexed-schema hierarchy. Misses novelty-added subclass relations; | ||
| // we fall through to `is_subclass_of` (a db walk) for those. | ||
| let hierarchy = db.snapshot.schema_hierarchy(); | ||
| let hierarchy = db.graph.snapshot.schema_hierarchy(); |
There was a problem hiding this comment.
Blocking: the sh:class fast path reads the last index build's hierarchy, so the subclass-edge rules this PR documents hold only until the next index build.
validate_class_constraint seeds hierarchy_accepted from db.graph.snapshot.schema_hierarchy(), the index root's schema. The indexer extracts that from every graph's rdfs:subClassOf edges (fluree-db-indexer/src/run_index/resolve/resolver.rs:1409, and the incremental refresh at build/incremental.rs:3659, neither filters by graph), and it drops a retracted edge only at the next build. That's the split you closed for targeting, policy and GraphQL in 3e44a8ffe ("an edge in a named graph counted after an index build and not before one"), and this read wasn't part of it. Your code didn't introduce it, but the PR now documents two rules that depend on it: a graph's own subclass edges count only when it lists itself (cookbook-shacl.md:524), and a per-graph list replaces the ledger-wide one.
Claude ran three probes on a file-backed ledger: write, support::rebuild_and_publish_index, reload, write again.
- p1:
ex:Assam rdfs:subClassOf ex:Commodity . ex:tea a ex:Assamwritten to<org-a>, which isn't listed. A listing of tea in<org-a>is a violation before the build and commits after it (the index root listsAssamunderCommodity). - p2: ledger-wide list
[<catalog>],<org-b>'s own list[<org-b-catalog>];ex:Spice rdfs:subClassOf ex:Commodityin the catalog,ex:saffron a ex:Spicein org-b-catalog. A saffron listing in<org-b>is a violation before the build and commits after it. - p3 (
mainhas this too): a default-graph edge, indexed, then retracted withDELETE DATA; a listing that needs it still commits.
The fix is one line: read the hierarchy the engine already holds, the current default-graph one targeting reads (and update the "indexed-schema hierarchy" comment just above):
| let hierarchy = db.graph.snapshot.schema_hierarchy(); | |
| let hierarchy = class_ctx.and_then(|c| c.hierarchy); |
With it, p1–p3 fail as documented, a fourth probe (union reads over indexed sources) still passes, and fluree-db-shacl, fluree-db-transact, and fluree-db-api's lib plus grp_graphsource, grp_ledger, grp_misc, grp_policy, grp_query_reason, grp_reasoning and grp_transact pass on Claude's box. Two things go with it: an indexed variant of sh_class_follows_subclass_edges_in_a_source (write the edge, rebuild_and_publish_index, then the listing), since every new test runs on novelty only; and a line in compatibility.md beside 1f453a6cf's, since sh:class stops counting a named graph's edge after a build on ledgers that don't use the setting either.
There was a problem hiding this comment.
Fixed in 05152c7: applied the suggestion and updated the comments that said "indexed". I added three indexed tests, one per probe (write, rebuild_and_publish_index, reload, write): sh_class_subclass_edges_after_an_index_build (an unlisted graph's own edge), a_per_graph_list_replaces_the_ledger_list_after_an_index_build, and a_retracted_indexed_subclass_edge_stops_counting. With the old line put back, all three fail. The compatibility.md note sits next to the 3e44a8ffe hierarchy paragraph.
|
|
||
| 1. **Fast path**: the ledger's indexed schema hierarchy (`SchemaHierarchy`). Expanded at engine build time so same-class and descendant-class matches are O(1) hashmap hits. | ||
| 2. **Live fallback**: when the subclass relation was asserted in the current transaction (or any earlier unindexed commit), the fast path misses. The engine then walks `rdfs:subClassOf` via a BFS on the database's SPOT index. This walk is **scoped to the default graph** regardless of the subject's own graph — matching how `SchemaHierarchy` is built and preventing cross-graph issues. | ||
| 2. **Live fallback**: when the subclass relation was asserted in the current transaction (or any earlier unindexed commit), the fast path misses. The engine then walks `rdfs:subClassOf` via a BFS on the database's SPOT index. This walk reads the **default graph**, matching how `SchemaHierarchy` is built, plus the `f:shapesSource` graphs and any [`f:additionalDataSource`](#validating-against-other-graphs) graphs, so a value-set or catalog can carry its own class hierarchy. The record's own named graph is not read automatically: its subclass edges count only when it is itself listed as an `f:additionalDataSource`, as a catalog listed ledger-wide is when a record is written to the catalog. |
There was a problem hiding this comment.
Blocking (same finding as the sh:class comment). This sentence, and "Fast path: the ledger's indexed schema hierarchy" just above it, are where the docs and the code part ways today: after an index build the fast path counts every graph's subclass edges, so "the record's own named graph is not read automatically" stops being true (probe p1 inline at fluree-db-shacl/src/validate.rs:2836). With the one-line fix there, the fast path is the current default-graph hierarchy and this paragraph holds as written; the "Fast path" item would then want to say "current" rather than "indexed".
There was a problem hiding this comment.
Fixed in 05152c7: the fast path now reads "the ledger's current schema hierarchy". The fallback item says it covers edges asserted in the current transaction or kept outside the default graph.
| test: RangeTest, | ||
| match_val: RangeMatch, | ||
| ) -> Result<Vec<Flake>> { | ||
| let mut flakes = self.graph.range(index, test, match_val.clone()).await?; |
There was a problem hiding this comment.
Optional (performance). I don't think this moves anything for a ledger without the setting, but it's free to avoid: range clones the RangeMatch before its no-source early return, so every SHACL read pays a few Arc bumps it doesn't need. With sources, it also clones every validated-graph flake into the HashSet and re-sorts even when no source returned anything, which is the common case for a record's own properties (the catalog doesn't hold them). An inverse path over a hub value (every listing pointing at ex:coffee) pays that per focus node.
if self.additional.is_empty() {
return self.graph.range(index, test, match_val).await;
}
let mut flakes = self.graph.range(index, test, match_val.clone()).await?;
let mut extra = Vec::new();
for &g_id in self.additional {
let mut source = self.graph;
source.g_id = g_id;
extra.extend(source.range(index, test, match_val.clone()).await?);
}
if extra.is_empty() {
return Ok(flakes);
}
// then the existing dedup and sort over flakes + extraThis is minor and non-blocking, 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.
Folded in (05152c7) as suggested: a read with no sources returns without the clone, and the dedup and re-sort run only when a source returned flakes.
| - **One graph, so a fact counts once.** A triple stored in both graphs is one value. A fact only a listed graph holds counts too, so a listed graph can make a record fail as well as pass: `sh:maxCount` sees its values and `sh:closed` sees its properties. | ||
| - **Checked when written.** Removing an entry from the catalog does not re-check the records that reference it; a record is checked again the next time it is written. | ||
| - **The transaction's own changes count.** A transaction that adds a catalog entry and a record referencing it passes; one that removes an entry and writes a record using it fails. A transaction may create a listed graph. | ||
| - **Per graph.** An entry in `f:graphOverrides` can give a graph its own list, which replaces the ledger-wide list for that graph. List the ledger-wide graphs again if that graph should read them too. |
There was a problem hiding this comment.
Optional (docs). A per-graph group that leaves f:additionalDataSource out inherits the ledger's list (merge_over treats an empty list as "not set"), so the only way to give one graph no sources while the ledger has some is to list that graph itself. That works (it's already read, and it only adds its own subclass edges to the walk), but nobody will guess it. Maybe a clause here and in the walkthrough's troubleshooting table: "to have a graph read no other graph, list the graph itself." Minor; if you agree, I'd rather it go in with this PR.
There was a problem hiding this comment.
Added (05152c7): a sentence in the cookbook's per-graph bullet, and a troubleshooting row in the walkthrough: "An override with no list inherits the ledger-wide one. To have a graph read no other graph, list the graph itself."
| /// Which nodes are checked, and against which shapes, is decided from | ||
| /// `graph` alone. | ||
| #[derive(Clone, Copy)] | ||
| pub(crate) struct DataView<'a> { |
There was a problem hiding this comment.
Changing every checking function's signature from GraphDbRef to DataView is what makes "every constraint reads the union" true by construction: the compiler found every read site, and targeting keeps the plain GraphDbRef visibly. Claude also checked the storage state the tests don't cover: with the catalog and pricing graphs served from a published index and the record in novelty, a fact in both counts once, a second catalog value trips sh:maxCount 1, the path reaches the indexed price, and sh:sparql sees the indexed typing. And removing the dedup or the sh:sparql dataset turns their tests red.
The sh:class fast path seeded its accepted classes from the index root's schema hierarchy. The indexer extracts that from every graph and keeps a retracted edge until the next build, so after an index build an unlisted graph's own subclass edge counted, a per-graph f:additionalDataSource list no longer replaced the ledger's for subclass edges, and a retracted default-graph edge still counted. It now reads the hierarchy the engine already holds, which targeting, policy and GraphQL read since 3e44a8f. DataView::range returns a source-less read without cloning the match, and skips the dedup and re-sort when no source returned a flake. Tests: three indexed variants (write, index, reload, write) of the subclass rules: an unlisted graph's own edge, per-graph replacement, and a retracted edge. Docs: compatibility note, the current-hierarchy wording, how to give a graph no sources when the ledger has some, and the full-reads sentence in the policy-in-transactions page.
|
Thanks for the review. Everything is in 05152c7, including headline note (2): |
Summary
SHACL checks a record against the graph it is written to. When the data a shape needs is kept in another graph, such as a shared catalog or a price list, validation fails even when the data is right.
#2204 ran into this with
sh:class. Its records live in per-organization graphs and reference a catalog in a named graph of its own, sosh:class ex:Commoditycould never pass. It proposedf:classMembershipSource, which adds graphs to thesh:classtype lookup.This PR succeeds #2204. It covers the same use case with a more general setting.
f:additionalDataSourcelists graphs that are read with the validated graph, as one graph, by every constraint rather than only class membership:sh:classfinds a value's type, and its superclass edges, in the catalog;( ex:product ex:price )steps from a record into the catalog;sh:nodechecks the referenced node's own properties there;sh:minCount,sh:maxCountandsh:closedsee its facts;sh:sparqlruns with the union as its default graph.The config plumbing, the shared source resolution and the use case come from #2204, and its author is credited as co-author on the commit.
Semantics
f:shapesSource.sh:targetSubjectsOf/sh:targetObjectsOfedge, that only a source holds does not make a shape apply. Nodes in a source are not validated because another graph reads them.fluree validate --graphfinds the ones it left non-conforming.f:graphOverrideslist replaces the ledger-wide list for that graph. It is not added to it the wayf:constraintsSourceis, because adding a graph to a union can make a record fail, so a merged list could tighten or loosen.f:ledger,f:atT,f:trustPolicyandf:rollbackGuardare refused.f:shapesSource. feat(shacl): consult f:classMembershipSource graphs for sh:class membership #2204 rejected that combination; it doesn't need to be, because the local lookup already runs before the model ledger is consulted.Implementation
DataView(fluree-db-shacl/src/data_view.rs) holds the validated graph plus its sources. Itsrangereads the union, dedups byFlakeequality (which ignores the graph andt), and returns index order. The checking functions invalidate.rsandpath.rsread through it. Targeting and the choice of focus nodes keep the single-graphGraphDbRef.sh:sparqlruns over an implicitDataSetwhose default graph is the union.sh:classreads a value's types from the union. The subclass walk reads the default graph, thef:shapesSourcegraphs and the listed graphs; the validated graph's own edges count only when it lists itself.ShaclGraphPolicycarries each graph's resolved sources, fromresolve_additional_data_g_idsintx.rs.membership_g_idsis back to main's behaviour.ConfigUnavailable(500), as on the transaction path. It used to validate as if the ledger had no config, which would drop the sources and reportconforms: trueon data that fails.Docs
docs/guides/cookbook-shacl-across-graphs.md: a marketplace with per-organization listings and a shared catalog, the failure without a source, re-checking after a catalog change, a per-organization list, and troubleshooting.cookbook-shacl.md.setting-groups.md,override-control.md,vocabulary.md,writing-config.md, the/validateendpoint andfluree validatepages, andcompatibility.md.Tests
it_shacl_additional_data, 15 tests, one for each of:it_shapes_cross_ledger::cross_ledger_shapes_read_local_additional_data_sources(this replaces feat(shacl): consult f:classMembershipSource graphs for sh:class membership #2204's rejection test).shacl_tests::validate_report_fails_when_the_config_cannot_be_read.Each new test fails with its mechanism removed. The mechanisms are the union read, dedup, the
sh:sparqldataset, resolving graphs created in the same transaction, per-graph replacement, thesh:classsource lookup, the subclass walk, self-listing, graph-local targeting and the fail-closed config read.Supersedes #2204.