Skip to content

feat(shacl): validate against additional data graphs (f:additionalDataSource) - #2264

Merged
bplatz merged 5 commits into
mainfrom
feat/shacl-union-graphs
Nov 11, 2026
Merged

bplatz merged 5 commits into
mainfrom
feat/shacl-union-graphs

Conversation

@bplatz

@bplatz bplatz commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

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, so sh:class ex:Commodity could never pass. It proposed f:classMembershipSource, which adds graphs to the sh:class type lookup.

This PR succeeds #2204. It covers the same use case with a more general setting. f:additionalDataSource lists graphs that are read with the validated graph, as one graph, by every constraint rather than only class membership:

  • sh:class finds a value's type, and its superclass edges, in the catalog;
  • a property path such as ( ex:product ex:price ) steps from a record into the catalog;
  • sh:node checks the referenced node's own properties there;
  • sh:minCount, sh:maxCount and sh:closed see its facts;
  • sh:sparql runs with the union as its default graph.
<urn:config:shacl> f:shaclEnabled true ;
  f:shapesSource [ a f:GraphRef ; f:graphSource [ f:graphSelector <http://example.org/shapes> ] ] ;
  f:additionalDataSource [ a f:GraphRef ; f:graphSource [ f:graphSelector <http://example.org/catalog> ] ] .

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

  • Added, not substituted. The validated graph is always read. Shapes still come only from f:shapesSource.
  • Targeting is unchanged. A transaction checks the records it writes, and which shapes apply is decided from the written graph. A type, or a sh:targetSubjectsOf / sh:targetObjectsOf edge, that only a source holds does not make a shape apply. Nodes in a source are not validated because another graph reads them.
  • One graph. A fact stored in several graphs counts once. A source can make a record fail as well as pass.
  • Checked when written. A catalog edit does not re-check the records that read it. fluree validate --graph finds the ones it left non-conforming.
  • The transaction's own changes count. This includes a transaction that creates a listed graph: sources resolve through its graph delta.
  • Per graph. An f:graphOverrides list replaces the ledger-wide list for that graph. It is not added to it the way f:constraintsSource is, because adding a graph to a union can make a record fail, so a merged list could tighten or loosen.
  • Errors, not skips.
    • An unknown graph fails the write.
    • The config and txn-meta graphs are refused.
    • f:ledger, f:atT, f:trustPolicy and f:rollbackGuard are refused.
    • Sources are same-ledger only, and they work with a cross-ledger 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.
  • Full reads. Checks read the sources whatever the writer's policy allows. This is documented, since a violation can show a value from a graph the writer cannot read.
  • Every entry point. Inline transaction shapes and the validate API, ad-hoc shapes included, read the same graphs.

Implementation

  • DataView (fluree-db-shacl/src/data_view.rs) holds the validated graph plus its sources. Its range reads the union, dedups by Flake equality (which ignores the graph and t), and returns index order. The checking functions in validate.rs and path.rs read through it. Targeting and the choice of focus nodes keep the single-graph GraphDbRef.
  • sh:sparql runs over an implicit DataSet whose default graph is the union.
  • sh:class reads a value's types from the union. The subclass walk reads the default graph, the f:shapesSource graphs and the listed graphs; the validated graph's own edges count only when it lists itself.
  • Transactions: ShaclGraphPolicy carries each graph's resolved sources, from resolve_additional_data_g_ids in tx.rs. membership_g_ids is back to main's behaviour.
  • Validate API: it now always reads the ledger config, ad-hoc shapes included. A config read failure is ConfigUnavailable (500), as on the transaction path. It used to validate as if the ledger had no config, which would drop the sources and report conforms: true on data that fails.

Docs

  • A new walkthrough, 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.
  • The reference section "Validating against other graphs" in cookbook-shacl.md.
  • Updates to setting-groups.md, override-control.md, vocabulary.md, writing-config.md, the /validate endpoint and fluree validate pages, and compatibility.md.

Tests

  • it_shacl_additional_data, 15 tests, one for each of:
    • each constraint kind above;
    • a fact in two graphs counting once;
    • the transaction's own changes;
    • a catalog edit not re-checking records;
    • the write that creates a source graph;
    • refused system graphs;
    • per-graph replacement;
    • subclass edges in a source, including a source written to itself;
    • graph-local targeting by type and by predicate;
    • the validate API.
  • 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:sparql dataset, resolving graphs created in the same transaction, per-graph replacement, the sh:class source lookup, the subclass walk, self-listing, graph-local targeting and the fail-closed config read.

Supersedes #2204.

…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]>
@bplatz
bplatz force-pushed the feat/shacl-union-graphs branch from 0d17a09 to 45bfaee Compare November 5, 2026 01:20
…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 aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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: ✔ DataView is a single chokepoint for reads; the config side extends read_graph_source_refs, CONFIG_EDGES and MergeableGroup; f:shapesSource resolution moved onto the shared helpers. ⚠️ sh:class's fast path reads snapshot.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 shared existing_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 RangeMatch clone), 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, -transact and -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, and wasm32 and wasm-smoke are green on this head.
  • Testing: ⚠️ 15 integration tests plus the cross-ledger and fail-closed-config tests, wired into grp_graphsource and the lib and run by name in CI on this head; Claude's mutation checks of the dedup and the sh:sparql dataset 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.

Comment thread fluree-db-shacl/src/validate.rs Outdated
// 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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:Assam written 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 lists Assam under Commodity).
  • p2: ledger-wide list [<catalog>], <org-b>'s own list [<org-b-catalog>]; ex:Spice rdfs:subClassOf ex:Commodity in the catalog, ex:saffron a ex:Spice in org-b-catalog. A saffron listing in <org-b> is a violation before the build and commits after it.
  • p3 (main has this too): a default-graph edge, indexed, then retracted with DELETE 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):

Suggested change
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread docs/guides/cookbook-shacl.md Outdated

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread fluree-db-shacl/src/data_view.rs Outdated
test: RangeTest,
match_val: RangeMatch,
) -> Result<Vec<Flake>> {
let mut flakes = self.graph.range(index, test, match_val.clone()).await?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 + extra

This 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread docs/guides/cookbook-shacl.md Outdated
- **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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@bplatz

bplatz commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Everything is in 05152c7, including headline note (2): docs/security/policy-in-transactions.md now has the full-reads sentence next to the identity-invariance line. It says that SHACL reads the written graph, the shapes graph and any f:additionalDataSource graph in full, whatever the writer's policy allows, so list only graphs every writer may see, or accept that.

@bplatz
bplatz merged commit 7d2a04e into main Nov 11, 2026
19 checks passed
@bplatz
bplatz deleted the feat/shacl-union-graphs branch November 11, 2026 03:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants