Skip to content

Fixes 35200: Reject negated EXISTS rules and keep inferred triples out of inferenceLevel=none - #35201

Merged
harshach merged 9 commits into
mainfrom
fix/rdf-inference-correctness
Oct 11, 2026
Merged

harshach merged 9 commits into
mainfrom
fix/rdf-inference-correctness

Conversation

@harshach

Copy link
Copy Markdown
Collaborator

Describe your changes:

Fixes #35200

Follow-up to phase 0 (#34963, #34970) of docs/plans/2026-10-07-fuseki-native-reasoning.md. Fixes defects found reviewing the merged inference work: a validator gap, inferenceLevel=none returning inferred triples, rule status written by runs that no longer own the result, phantom lineage edges, scheduled runs on stores that cannot materialize, and an int overflow.

Type of change:

  • Bug fix

High-level design:

  1. Negated EXISTS (FixedPointRuleCheck). EXISTS is accepted only where the whole FILTER requires it: the filter itself or one of its && conjuncts, the only position where it can only turn true as facts are added. This also catches IF, COALESCE, comparisons and BIND, not just !, and the pattern inside an accepted EXISTS is now checked too (FILTER EXISTS { … MINUS … } used to pass). Stored rules are revalidated on startup, so existing negated rules get disabled with the reason.
  2. inferenceLevel=none reads asserted data only. While materialized inference is enabled, RdfRepository.executeAssertedSparqlQuery (AssertedOnlyQueries) names every graph outside <baseUri>graph/inferred/ as FROM and FROM NAMED. Jena evaluates several FROM graphs as a de-duplicating union, so property paths across graphs behave as on the union default graph, and FROM NAMED keeps GRAPH patterns away from rule graphs. A query that declares its own dataset runs as written. The graph list is read with GRAPH ?g {} (graph names from the index, not a scan of every quad) and refreshed in the background every two minutes.
    • Switched callers: the none path of /v1/rdf/sparql and the MCP SPARQL tool, selectJsonWithoutInference (agent SPARQL), complete lineage, LineagePathFinder, and the centrality, community and co-occurrence insights.
    • Alternatives rejected: rewriting patterns to GRAPH ?g with a filter breaks cross-graph property paths and returns duplicates; a second Fuseki dataset needs a deployment change; a fixed list of OM's graphs misses graphs created by SPARQL updates.
    • Cost: with inference enabled, none queries use Jena's union view instead of TDB2's native union. Disabling inference does not clear rule graphs (documented).
  3. Lost lease. Losing the lease raises a dedicated exception; the run writes nothing to the rule rows and ends as in-progress (409, scheduled run STOPPED). A dirtyVersion guard on markFailed would not work, since the run that took over does not bump it.
  4. Superseded runs. If the pass budget runs out and any rule's dirtyVersion, or the rule set, changed since the run started, the run is superseded: rules stay dirty with no lastError, 409/STOPPED. Unchanged inputs still fail every enabled rule as before.
  5. Phantom lineage edges. The lineage loader distinguishes a deleted edge from one without details; refreshLineage removes a deleted edge instead of re-adding it.
  6. RdfInferenceApp checks RdfRepository.supportsMaterializedInference(config), so a QLever store completes an empty run instead of failing every five minutes.
  7. Triple counts as Long (existingJavaType: java.lang.Long on inferenceRuleStatus.tripleCount and the explanation schema), dropping Math.toIntExact. TS and Python models are unchanged.

Docs: rdf-production-setup.md (inference levels, lease loss, superseded runs) and rdf-ontology-contract.md.

Tests:

Use cases covered

  • !EXISTS, !(EXISTS), IF, BIND and MINUS inside EXISTS are rejected; a stored negated rule is disabled with its reason.
  • After materializing domain-membership-inheritance, the inherited om:belongsToDomain triple is visible at custom and not at none, while the asserted triple is visible at none.
  • Server A's lease expires mid-run and server B takes over: B's clean rule status stands.
  • A run whose inputs change until the pass budget runs out leaves rules dirty without an error.
  • A lineage add replayed after the delete leaves no edge; an edge without details is still projected.
  • A scheduled run on a store without materialized inference completes.

Unit tests

  • InferenceRuleValidatorTest, InferenceMaterializerTest, InferenceRuleRepositoryTest, AssertedOnlyQueriesTest (7 cases through Jena's dataset handling), RdfLiveWriteTest, new RdfInferenceAppTest. All of org.openmetadata.service.rdf.** plus RdfResourceTest and the OntologyReasoningResource tests: 1055 run, 0 failures; SparqlQueryToolTest 12, 0 failures. Each new unit test fails before its fix.

Backend integration tests

  • RdfInferenceMaterializationIT (inferenceLevelNoneLeavesOutMaterializedConclusions), RdfInferenceMultiServerIT (lease takeover).
ITs mysql-elasticsearch postgres-opensearch
RdfResourceIT, RdfInferenceMultiServerIT, RdfInferenceMaterializationIT 35 passed 35 passed
RdfResourceIT, RdfInferenceMaterializationIT after the graph-listing change 31 passed —

Manual testing performed

None beyond the tests above.

UI screen recording:

Not applicable — backend-only change.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes <issue-number>: <short explanation>
  • My PR is linked to a GitHub issue via Fixes #<issue-number> above.
  • For JSON Schema changes: tripleCount maps to java.lang.Long; generated TS and Python are unchanged.
  • I have added tests (unit / integration as applicable) and listed them above.
  • I have added a test that covers the exact scenario we are fixing.

FixedPointRuleCheck only rejected E_NotExists, but Jena parses
FILTER(!EXISTS {..}) and FILTER(!(EXISTS {..})) as E_LogicalNot(E_Exists),
so a non-monotone rule passed validation and could make the fixed point
depend on rule order.

EXISTS is now accepted only as a condition the whole FILTER requires (the
filter itself or one of its && conjuncts). That is the one position where
it can only turn true as facts are added; under !, inside IF/COALESCE, in
a comparison or bound by BIND it can flip to false. Allow-listing the
monotone position is stricter than deny-listing E_LogicalNot and also
catches those other wrappers. The pattern inside an accepted EXISTS is now
inspected as well, so MINUS or NOT EXISTS cannot hide inside it.

Stored rules go through the same validator on startup, so existing rules
that negate EXISTS are disabled with the reason recorded.
Two ways a materialization run recorded a failure it had no business
recording:

Lost lease. When a run found its lease taken over it called
recordFailure, and markFailed is an unconditional UPDATE, so it could
overwrite the status the run that took over had just written (dirty
flag and lastError on a rule that run had materialized cleanly). The
lost lease is now a dedicated exception: the run writes nothing to the
rule rows and surfaces InferenceRunInProgressException, so the
scheduled app ends STOPPED and the REST call returns 409, the same as
meeting the lock at start. A dirtyVersion CAS on markFailed would not
help here: the takeover run does not bump dirtyVersion.

Superseded run. Ongoing writes mark every rule dirty and keep adding
facts, so a run can exhaust its 64-pass budget because of the write
rate, not the rules. When the budget runs out and any rule's
dirtyVersion (or the set of rules) changed since listForRun, the run is
treated as superseded: rules are left dirty without a lastError and the
run ends with InferenceRunSupersededException (409, app STOPPED). A
budget exhausted against unchanged inputs still fails every enabled
rule as before.
RdfInferenceApp only checked materializedInferenceEnabled, so with the
flag set on a non-Fuseki store (QLever) every scheduled run went on to
InferenceMaterializer, which rejects the store as unavailable, and the
run ended FAILED each time. It now uses
RdfRepository.supportsMaterializedInference, the same predicate the
query path and status reporting use, and completes as an empty run.
inferenceRuleStatus.tripleCount and the explanation's tripleCount are
declared int64, but jsonschema2pojo generated Integer, so
InferenceRuleRepository narrowed the BIGINT lastTripleCount with
Math.toIntExact and a rule graph past 2^31-1 triples made every status
read throw. Both fields now use existingJavaType java.lang.Long, the
convention other int64 schema fields follow, and the narrowing is gone.
The TypeScript and Python models are unchanged: they already map int64
to number/int.
refreshLineage loaded the edge's details with .orElse(null), and the
loader returned empty both when the edge no longer existed and when it
existed with no stored details. A lineage add replayed after the edge
was deleted therefore re-added the edge without details, leaving a
phantom upstream/downstream edge in the knowledge graph.

The loader now returns the stored edge (with possibly null details) or
empty when the relationship row is gone. When it is gone, the replay
removes the edge, which is idempotent and leaves the graph matching the
database whatever order the add and delete replays run in.
Fuseki's tdb2:unionDefaultGraph includes every named graph, the rule
graphs under <baseUri>graph/inferred/ among them, and the NONE path ran
the query unchanged, so none returned the same derived triples as
custom.

While materialized inference is enabled, RdfRepository now runs
asserted-only reads with every non-inferred named graph as the query
dataset: FROM for the default graph and FROM NAMED so GRAPH patterns
cannot reach inferred graphs either. Jena evaluates several FROM graphs
as a distinct union, so property paths that cross graphs and triples
stored in two graphs behave as on the union default graph. A query that
declares its own dataset runs as written.

Alternatives considered:
- An algebra rewrite of default-graph patterns into
  GRAPH ?g { } FILTER(!STRSTARTS(STR(?g), prefix)) breaks property paths
  that span graphs and returns duplicates for triples held in more than
  one graph; fixing that needs per-pattern DISTINCT subqueries that
  defeat the optimizer.
- A second Fuseki dataset whose default graph unions only asserted
  graphs needs the graph set at assembly time and a deployment change,
  and asserted graphs are not a closed set (SPARQL updates and loaders
  create graphs).
- A fixed FROM list of the graphs OpenMetadata writes misses graphs
  created by SPARQL updates.

Trade-offs: the graph list is read from Fuseki (a quad-index scan) and
cached for 30 seconds in a single-entry Caffeine cache, so a graph
created in that window is missing from none until the refresh; inferred
graphs are never let in. Jena executes a multi-graph FROM dataset
through a read-only union view instead of TDB2's native union default
graph, so none queries cost more than before when inference is enabled.
With materialized inference disabled the query is not rewritten, so
rule graphs left behind must be cleared.

Callers switched to the asserted-only read: the SPARQL endpoint and MCP
tool at none, selectJsonWithoutInference (agent SPARQL; its javadoc no
longer mentions a configured default inference), the complete-lineage
endpoint, the lineage path finder and the RDF insights (centrality,
communities, co-occurrence). Inference explanations, SHACL validation,
semantic search and the MCP describe/tag tools keep reading the union.
A run now also ends with 409 when another run takes it over or when writes
keep changing the rules' inputs until it runs out of passes.
… background

SELECT DISTINCT ?g { GRAPH ?g { ?s ?p ?o } } matches every quad in the
store to name its graphs. An empty GRAPH pattern lists the graph names
directly. Refresh the asserted graph list in the background every two
minutes, so a none query never waits on the listing.
@harshach
harshach requested a review from a team as a code owner October 11, 2026 05:30
@github-actions

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

This PR cannot be merged until the following are addressed on its linked issue:

The fields live on the linked issue in the Shipping project (open the issue → right sidebar → Projects). After you set them, re-run this check (or push a commit) — issue/project changes do not re-trigger it automatically.

Maintainers can bypass this check by adding the skip-pr-checks label.

@github-actions github-actions Bot added backend safe to test Add this label to run secure Github workflows on PRs labels Oct 11, 2026
…rule

A graph OpenMetadata created, such as an insights graph, stayed out of
asserted-only reads until the periodic refresh, and a list read before
the first projection stayed empty. Writes through RdfRepository now name
the graphs they reach; one missing from the cached list, an update whose
targets cannot be read, or a blue/green promotion drops the list so the
next read relists. An empty list is never kept. Record the asserted-only
dataset rule, the refresh interval and the rejected alternatives.
@harshach

Copy link
Copy Markdown
Collaborator Author

Both findings are addressed in 9465389.

Cached graph list hides graphs OM just created. Writes through RdfRepository now go through AssertedGraphTrackingRdfStorage, which tells AssertedOnlyQueries the graphs each write reaches: the knowledge graph for entity and relationship writes, the targets a SPARQL update names (INSERT DATA, WITH/INSERT, LOAD INTO, CREATE, ADD/COPY/MOVE TO), and a Turtle load's graph. A graph missing from the cached list drops it, so the next asserted-only read relists; an update whose targets cannot be read (a GRAPH ?g variable, unparseable text) drops it too, also when the update fails, since a timed-out update may have been applied. activateDataset drops it after a promotion. An empty list is never kept. The periodic refresh remains only for graphs created by another server or written to Fuseki directly. Tests: AssertedOnlyQueriesTest#aGraphThisServerCreatesIsReadByTheNextQuery, #writesToListedOrInferredGraphsKeepTheList, #anEmptyGraphListIsNotKept, and AssertedGraphTrackingRdfStorageTest (target extraction, and a failed update still making its new graph readable).

Decision record. docs/decisions/2026-10-11-asserted-only-rdf-reads-name-every-non-inferred-graph.md records the asserted-only reads, the graph/inferred/ prefix and the empty-dataset sentinel, the caching and relisting rules with the two-minute refresh, the rejected alternatives, and the cost of Jena's union view. AssertedOnlyQueries and rdf-production-setup.md cite it.

RdfResourceIT, RdfInferenceMultiServerIT and RdfInferenceMaterializationIT on mysql-elasticsearch: 35/35.

Comment on lines +81 to +90
void graphsWritten(final Collection<String> graphs) {
final List<String> known = assertedGraphs.getIfPresent(GRAPH_LIST_KEY);
if (known == null) {
return;
}
final String prefix = inferredGraphPrefix.get();
if (graphs.stream().anyMatch(graph -> !graph.startsWith(prefix) && !known.contains(graph))) {
assertedGraphs.invalidate(GRAPH_LIST_KEY);
}
}

@gitar-bot gitar-bot Bot Oct 11, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Bug: graphsWritten skips invalidation while the first graph listing is in flight

graphsWritten returns early when getIfPresent is null, but a synchronous Caffeine LoadingCache also returns null while a load for the key is still running. Here is the race: query thread Q calls assertedGraphs.get, and its loader lists graphs from Fuseki. Meanwhile writer W commits an INSERT into a new graph (an insights graph, say) and calls graphsWritten, which sees null and returns. If Q's listing was read before W's commit, Q's list lacks the new graph, and that list stays cached until the 2-minute refresh. This is the staleness the commit set out to remove, and the ADR says a write by this server naming a missing graph "drops it so the next read relists". Fix: invalidate when known == null as well. invalidate on a key that is still computing waits for the compute and then removes the result, and it is a cheap no-op when nothing is cached.

Invalidate also when the list is absent, which covers an in-flight load:

void graphsWritten(final Collection<String> graphs) {
  final List<String> known = assertedGraphs.getIfPresent(GRAPH_LIST_KEY);
  final String prefix = inferredGraphPrefix.get();
  if (known == null
      || graphs.stream().anyMatch(graph -> !graph.startsWith(prefix) && !known.contains(graph))) {
    assertedGraphs.invalidate(GRAPH_LIST_KEY);
  }
}

Was this helpful? React with 👍 / 👎

@gitar-bot

gitar-bot Bot commented Oct 11, 2026

Copy link
Copy Markdown
Code Review 👍 Approved with suggestions 2 closed / 3 findings

🔴 High risk · Changing RDF inference materialization, graph filtering, and lineage replay could leave derived results or lineage projections inconsistent with stored data.

Adds a per-server cache of named graphs so inferenceLevel=none SPARQL queries exclude materialized inference graphs, along with lease-loss handling, superseded-run handling, lineage edge fixes, and Long triple counts. Approved with suggestions.

  • Open (minor): graphsWritten in AssertedOnlyQueries.java skips invalidation while the first graph listing is in flight, so a graph written during that load can stay missing from the cached list until the 2-minute refresh. Suggested fix: invalidate when the cached entry is null as well.

Resolved this session: the cached graph list no longer hides graphs OM itself just created (e.g. centrality), and the asserted-only dataset rule and 2-minute TTL are now recorded in docs/decisions.

💡 Bug: graphsWritten skips invalidation while the first graph listing is in flight

📄 openmetadata-service/src/main/java/org/openmetadata/service/rdf/AssertedOnlyQueries.java:81-90

graphsWritten returns early when getIfPresent is null, but a synchronous Caffeine LoadingCache also returns null while a load for the key is still running. Here is the race: query thread Q calls assertedGraphs.get, and its loader lists graphs from Fuseki. Meanwhile writer W commits an INSERT into a new graph (an insights graph, say) and calls graphsWritten, which sees null and returns. If Q's listing was read before W's commit, Q's list lacks the new graph, and that list stays cached until the 2-minute refresh. This is the staleness the commit set out to remove, and the ADR says a write by this server naming a missing graph "drops it so the next read relists". Fix: invalidate when known == null as well. invalidate on a key that is still computing waits for the compute and then removes the result, and it is a cheap no-op when nothing is cached.

Invalidate also when the list is absent, which covers an in-flight load
void graphsWritten(final Collection<String> graphs) {
  final List<String> known = assertedGraphs.getIfPresent(GRAPH_LIST_KEY);
  final String prefix = inferredGraphPrefix.get();
  if (known == null
      || graphs.stream().anyMatch(graph -> !graph.startsWith(prefix) && !known.contains(graph))) {
    assertedGraphs.invalidate(GRAPH_LIST_KEY);
  }
}
✅ 2 closed
✅ Bug: Cached graph list hides graphs OM itself just created, e.g. centrality

📄 openmetadata-service/src/main/java/org/openmetadata/service/rdf/AssertedOnlyQueries.java:55-68 📄 openmetadata-service/src/main/java/org/openmetadata/service/rdf/insights/RdfInsightsService.java:68 📄 openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfRepository.java:1663-1669
listImportantEntities now goes through executeAssertedSparqlQuery. ImportanceQueryBuilder reads om:centralityScore from the default graph and has no FROM. CentralityComputation.persistScores writes those scores with INSERT DATA { GRAPH <…/insights/centrality/table> … }. The first time that graph is created it is missing from the cached asserted-graph list, so it is left out of FROM and the scores are silently ignored until a refresh. The cache uses refreshAfterWrite, so that is two minutes, plus one more stale read when the async refresh fires. Startup has the same problem: if the first none query runs before the first rebuild has created graph/knowledge, the list is empty. Every query then runs against NO_ASSERTED_GRAPH and returns nothing until the refresh. Fix: refresh the list whenever OpenMetadata itself writes RDF (executeSparqlUpdate, loadTurtleFile, bulk stores, activateDataset), and don't cache an empty list.

✅ Quality: Asserted-only dataset rule and 2-minute TTL are not recorded in docs/decisions

📄 openmetadata-service/src/main/java/org/openmetadata/service/rdf/AssertedOnlyQueries.java:38-41 📄 openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfRepository.java:1657-1669 📄 docs/rdf-production-setup.md:542
This PR decides how inferenceLevel=none excludes inferred triples, but no record in docs/decisions/ covers it. The repository's decision-record policy requires one because the change adds a derived contract (the <baseUri>graph/inferred/ prefix that marks a graph as non-asserted, plus the sentinel urn:openmetadata:rdf:no-asserted-graph) and a judgment-call TTL (GRAPH_LIST_TTL = 2 minutes). The record would state: "While materialized inference is enabled, asserted-only reads (inferenceLevel=none, complete lineage, insights, agent SPARQL) run with every graph outside <baseUri>graph/inferred/ as FROM and FROM NAMED. The graph list is refreshed every two minutes. Queries that declare their own dataset run as written." It should also keep the rejected alternatives from the PR description ("rewriting patterns to GRAPH ?g with a filter breaks cross-graph property paths…; a second Fuseki dataset needs a deployment change; a fixed list of OM's graphs misses graphs created by SPARQL updates"). The repository squash-merges, so those alternatives will not reach git log. Fix: add a dated record under docs/decisions/ with these rules and the alternatives.

🤖 Prompt for agents
Code Review: Adds a per-server cache of named graphs so `inferenceLevel=none` SPARQL queries exclude materialized inference graphs, along with lease-loss handling, superseded-run handling, lineage edge fixes, and `Long` triple counts. Approved with suggestions.
  
  - Open (minor): `graphsWritten` in `AssertedOnlyQueries.java` skips invalidation while the first graph listing is in flight, so a graph written during that load can stay missing from the cached list until the 2-minute refresh. Suggested fix: invalidate when the cached entry is null as well.
  
  Resolved this session: the cached graph list no longer hides graphs OM itself just created (e.g. centrality), and the asserted-only dataset rule and 2-minute TTL are now recorded in `docs/decisions`.

1. 💡 Bug: graphsWritten skips invalidation while the first graph listing is in flight
   Files: openmetadata-service/src/main/java/org/openmetadata/service/rdf/AssertedOnlyQueries.java:81-90

   `graphsWritten` returns early when `getIfPresent` is null, but a synchronous Caffeine `LoadingCache` also returns null while a load for the key is still running. Here is the race: query thread Q calls `assertedGraphs.get`, and its loader lists graphs from Fuseki. Meanwhile writer W commits an INSERT into a new graph (an insights graph, say) and calls `graphsWritten`, which sees null and returns. If Q's listing was read before W's commit, Q's list lacks the new graph, and that list stays cached until the 2-minute refresh. This is the staleness the commit set out to remove, and the ADR says a write by this server naming a missing graph "drops it so the next read relists". Fix: invalidate when `known == null` as well. `invalidate` on a key that is still computing waits for the compute and then removes the result, and it is a cheap no-op when nothing is cached.

   Fix (Invalidate also when the list is absent, which covers an in-flight load):
   void graphsWritten(final Collection<String> graphs) {
     final List<String> known = assertedGraphs.getIfPresent(GRAPH_LIST_KEY);
     final String prefix = inferredGraphPrefix.get();
     if (known == null
         || graphs.stream().anyMatch(graph -> !graph.startsWith(prefix) && !known.contains(graph))) {
       assertedGraphs.invalidate(GRAPH_LIST_KEY);
     }
   }

Review coverage

📋 Rules No rules evaluated

🧪 Functional validation Not enabled · Set up

🤖 Auto-approval Not enabled · Set up

Options

Display: compact → Counting what did not apply, without listing it.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

@sonarqubecloud

Copy link
Copy Markdown

@harshach
harshach merged commit 431885d into main Oct 11, 2026
78 of 79 checks passed
@harshach
harshach deleted the fix/rdf-inference-correctness branch October 11, 2026 18:42
fmcardoso added a commit that referenced this pull request Nov 6, 2026
…ackport 2.0 #37069) (#37177)

* Fixes #36671: Live RDF entity writes send only the changed triples (backport 2.0 #37069)

Backport of #37069, adapted to 2.0:

- 2.0 has no InferenceInvalidatingRdfStorage or AssertedGraphTrackingRdfStorage (main-only,
  from #28042 and #35201), so their changes and tests are left out.
- 2.0 does not project table columns as resources, so RdfPropertyMapper keeps only the named
  list cells, and the two tests that relied on column triples use extension properties or
  the 2.0 counts instead.
- The new tests use 2.0's JsonLdTranslator constructor and JenaFusekiStorage.isTimeoutError,
  now package-private for the circuit-breaker test.
- The ADR and the production setup guide drop the inference statements that do not apply.

(cherry picked from commit d811bd7)

* Run RdfEntityDiffWriteIT on 2.0: add FusekiTestImage, wide table in custom properties

2.0 has no FusekiTestImage and does not project a table's columns, so the
wide-table test changes a table tag on a table with 200 custom properties.

* Benchmark 2.0 with tables wide in custom properties

2.0 does not project a table's columns, so the disk-growth harness builds tables
with 300 custom properties and changes one per write instead of moving a column
tag. The decision record gains the 2.0 measurement.

This branch was previously deployed

1 inactive deployment
test — 9465389a Deployed Oct 11, 2026 by harshach via RDF Playwright execution #28955
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RDF inference: negated EXISTS rules pass validation and inferenceLevel=none returns inferred triples

1 participant