diff --git a/docs/decisions/2026-10-11-rdf-freshness-watermarks-have-one-writer-per-table.md b/docs/decisions/2026-10-11-rdf-freshness-watermarks-have-one-writer-per-table.md new file mode 100644 index 000000000000..335dfceb1179 --- /dev/null +++ b/docs/decisions/2026-10-11-rdf-freshness-watermarks-have-one-writer-per-table.md @@ -0,0 +1,42 @@ +# RDF freshness inputs have one writer each: retire for queue rows, RdfRebuildStore for the active dataset + +- **Status:** Accepted +- **Revisions:** v1 2026-10-11 (initial) +- **Deciders:** Sriharsha Chintalapani +- **Guard:** `RdfLiveWriteRecoveryIT#aDeliveredWriteFromAnOlderServerStaysInTheEnqueuedWatermark`, + `RdfLiveWriteRecoveryIT#aDeadLetteredWriteFromAnOlderServerStaysInTheEnqueuedWatermark`, + `RdfSourceRevisionIT`, and `RdfBlueGreenRebuildIT` +- **Related:** [#35198](https://github.com/open-metadata/OpenMetadata/issues/35198), + [#35199](https://github.com/open-metadata/OpenMetadata/pull/35199), + [#34975](https://github.com/open-metadata/OpenMetadata/pull/34975), + `docs/plans/2026-10-07-fuseki-native-reasoning.md` (mutations, generations, and freshness) + +## Context + +A reasoning result is `CURRENT` only while the serving generation in `rdf_active_dataset` is +unchanged and its live-write watermark covers the highest enqueued queue ID +(`ReasoningFreshness`). `enqueuedWatermark()` is the greater of +`rdf_projection_health.enqueuedWatermark` and the highest ID still in `rdf_live_write_queue`. +Servers that predate the column enqueue without raising it, so their queue row is the only trace +of a write until it is removed; removing it without raising the column lets an older result be +reported `CURRENT`. Likewise, a promotion that changes the dataset without a new generation +leaves results from the old dataset `CURRENT`. + +## Decision + +- **Queue rows leave only through `RdfLiveWriteStore.retire`**, which deletes the row and raises + `enqueuedWatermark` to its ID in the same transaction. Delivery, dead-lettering and + `recordUntrackedWrite` all use it; no other code deletes from `rdf_live_write_queue`. +- **`RdfRebuildStore` is the only writer of `rdf_active_dataset`.** It assigns a new generation + UUID at every promotion, including back to a reused physical dataset name, and assigns one to + a pointer written before the column existed. The unused DAO writers that could change the + dataset without a generation were removed. + +## Consequences + +Freshness stays exact for writes from servers on the previous version once they are drained, and +every dataset change is visible as a generation change. A new path that removes queue rows (a +purge, a retention job) or moves the active dataset must go through these two owners, or it +silently makes stale results look current. Two gaps remain during a rolling upgrade and are +documented in `docs/rdf-production-setup.md`: an older server draining its own write, and an +older server promoting a blue/green build with the previous `UPDATE`, which keeps the generation. diff --git a/docs/decisions/2026-10-11-rdf-reasoning-job-requests-carry-the-fields-their-operation-needs.md b/docs/decisions/2026-10-11-rdf-reasoning-job-requests-carry-the-fields-their-operation-needs.md new file mode 100644 index 000000000000..697ee9d9a698 --- /dev/null +++ b/docs/decisions/2026-10-11-rdf-reasoning-job-requests-carry-the-fields-their-operation-needs.md @@ -0,0 +1,41 @@ +# RDF reasoning job requests carry the fields their operation needs, enforced by the schema + +- **Status:** Accepted +- **Revisions:** v1 2026-10-11 (initial) +- **Deciders:** Sriharsha Chintalapani +- **Guard:** `RdfReasoningContractTest#theContractRejects` and + `RdfReasoningContractTest#aConsistencyCheckTakesNoExpression`; in open-metadata/jena, + `JobRequestTest` runs the same cases against the store's validator +- **Related:** [#35198](https://github.com/open-metadata/OpenMetadata/issues/35198), + [#35199](https://github.com/open-metadata/OpenMetadata/pull/35199), + [open-metadata/jena#2](https://github.com/open-metadata/jena/pull/2), + `openmetadata-spec/src/main/resources/json/schema/api/rdf/rdfReasoningJobRequest.json` + +## Context + +`rdfReasoningJobRequest.json` is the contract between OpenMetadata, which submits reasoning jobs, +and the RDF store's job API in the `openmetadata/fuseki` image, which validates them without +OpenMetadata's jars. Which fields each operation needs was stated only in field descriptions, so a +store validating against the schema accepted a CHECK without `check` or a REFRESH without +`ruleBundleDigest`. + +## Decision + +The schema enforces the per-operation fields with draft 2020-12 `allOf` / `if` / `then`: + +- `REFRESH` requires `ruleBundleDigest`. +- `CHECK` requires `ontologyIri` and `check`; `EXPLAIN` requires `ontologyIri` and `explain`. +- A check of kind `SATISFIABILITY` requires `classExpression`; `SUBSUMPTION` requires + `classExpression` and `superClassExpression`; `ENTAILMENT` requires `statement`; + `CONSISTENCY` takes no expression. + +The rules only add validation: the generated Java and TypeScript models do not change, so both +sides keep reading the same shape. + +## Consequences + +Every producer and consumer of the request follows the same rules, and a request that breaks one +fails validation on either side instead of reaching an engine. A new operation or check kind must +add its rule here and to the schema in the same change, and the store's copy of the schema +(`openmetadata/fuseki/extension/src/test/resources/openmetadata-contract/` in open-metadata/jena) +must be refreshed. diff --git a/docs/plans/2026-10-07-fuseki-native-reasoning.md b/docs/plans/2026-10-07-fuseki-native-reasoning.md index cc2fbeeedd4c..c8483f8e1338 100644 --- a/docs/plans/2026-10-07-fuseki-native-reasoning.md +++ b/docs/plans/2026-10-07-fuseki-native-reasoning.md @@ -407,6 +407,10 @@ journal replays writes into a blue/green target. Reuse these instead of a Fuseki when any of them does not. The metadata commit and queue insert are separate transactions, so a crash between them is invisible to freshness, exactly as it is to projection; a full rebuild repairs both. +- **Rolling upgrades.** Servers before 2.1.0 enqueue without recording the enqueued watermark, + so delivering or dead-lettering a row records its ID too. An older server that drains its own + write, or promotes a blue/green build without assigning a generation, can still leave an earlier + result `CURRENT`; results are trustworthy again after a refresh once every server runs 2.1.0. - **Dirty flags** use a captured-revision compare-and-set instead of the unconditional `markMaterialized`. Changes during a run stay pending and coalesce into the next refresh. diff --git a/docs/rdf-production-setup.md b/docs/rdf-production-setup.md index 8f772f22886e..cd84f06a0482 100644 --- a/docs/rdf-production-setup.md +++ b/docs/rdf-production-setup.md @@ -209,6 +209,14 @@ short interval, or a SQL outage that prevents enqueueing, is outside the queue's Enqueue failures are logged and degrade projection health when SQL is available; a failed health write is retried while that process remains alive. This is not a transactional metadata outbox. +During a rolling upgrade from a release before 2.1.0, reasoning freshness can report results as +current that are not. Older servers enqueue without recording +`rdf_projection_health.enqueuedWatermark`. A 2.1.0 server that delivers or dead-letters such a +write records its ID, but an older server that drains it removes the only trace of that write. An +older server's blue/green promotion also switches datasets without assigning a new generation. +Avoid blue/green rebuilds until every server runs 2.1.0, and refresh reasoning after the last older +server stops. + ## Write throughput TDB2 is a single-writer store, and the indexing pipeline is built around that fact: reader diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfLiveWriteRecoveryIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfLiveWriteRecoveryIT.java index 19ea34a10e93..5ffc400e527b 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfLiveWriteRecoveryIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfLiveWriteRecoveryIT.java @@ -383,6 +383,39 @@ void aDeadLetteredWriteMovesTheWatermarkOnAndLeavesTheGraphDegraded( } } + @ParameterizedTest + @EnumSource(RdfTestDatabase.Backend.class) + void aDeliveredWriteFromAnOlderServerStaysInTheEnqueuedWatermark( + final RdfTestDatabase.Backend backend) { + try (Fixture fixture = new Fixture(backend)) { + final long legacy = fixture.enqueueWithoutRecordingTheWatermark(insert(1)); + assertEquals(legacy, fixture.other.enqueuedWatermark()); + + assertTrue(fixture.primary.processNext(fixture::apply)); + + assertEquals(0, fixture.other.pendingWrites()); + assertEquals(legacy, fixture.other.enqueuedWatermark()); + } + } + + @ParameterizedTest + @EnumSource(RdfTestDatabase.Backend.class) + void aDeadLetteredWriteFromAnOlderServerStaysInTheEnqueuedWatermark( + final RdfTestDatabase.Backend backend) { + try (Fixture fixture = new Fixture(backend)) { + final long legacy = fixture.enqueueWithoutRecordingTheWatermark("malformed"); + for (int attempt = 1; attempt < 10; attempt++) { + assertFalse(fixture.primary.processNext(fixture::apply)); + fixture.clock.advance(60_000); + } + + assertTrue(fixture.primary.processNext(fixture::apply)); + + assertEquals(1, fixture.deadLetters()); + assertEquals(legacy, fixture.other.enqueuedWatermark()); + } + } + @ParameterizedTest @EnumSource(RdfTestDatabase.Backend.class) void anExhaustedWriteCannotBeReplayedAfterALaterDelete(final RdfTestDatabase.Backend backend) { @@ -504,6 +537,23 @@ RdfLiveWriteStore newStore() { return new RdfLiveWriteStore(database.jdbi(), clock); } + /** Enqueues as a server that predates rdf_projection_health.enqueuedWatermark does. */ + long enqueueWithoutRecordingTheWatermark(final String payload) { + return database + .jdbi() + .withHandle( + handle -> + handle + .createUpdate( + "INSERT INTO rdf_live_write_queue (payload, createdAt) " + + "VALUES (:payload, :createdAt)") + .bind("payload", payload) + .bind("createdAt", clock.millis()) + .executeAndReturnGeneratedKeys("id") + .mapTo(Long.class) + .one()); + } + void apply(final String payload) { JsonUtils.readValue(payload, RdfMutation.class).apply(storage); } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfSourceRevisionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfSourceRevisionIT.java index 5aa9c0172c67..e2e77d1b2ae5 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfSourceRevisionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfSourceRevisionIT.java @@ -17,17 +17,21 @@ import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.api.Assumptions.assumeTrue; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.io.UncheckedIOException; import java.net.URI; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.time.Clock; import java.time.Duration; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.UUID; +import java.util.stream.LongStream; import org.awaitility.Awaitility; +import org.jdbi.v3.core.Handle; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -47,14 +51,16 @@ import org.openmetadata.schema.entity.data.Pipeline; import org.openmetadata.schema.entity.data.PipelineStatus; import org.openmetadata.schema.type.StatusType; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.network.HttpClient; import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.rdf.RdfLiveWriteStore; import org.openmetadata.service.rdf.RdfUpdater; /** * Writes that reach the serving graph without the live-write queue must still move the enqueued * watermark, or reasoning results computed before them would pass for current. Isolated, so no - * other test enqueues writes while one is measured. + * other test records a write outside the queue while one is measured. */ @Execution(ExecutionMode.SAME_THREAD) @Isolated @@ -62,7 +68,7 @@ public class RdfSourceRevisionIT { private static final String APP_NAME = "RdfIndexApp"; private static final String BASE_URI = "https://open-metadata.org/"; - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private static final String GRAPH = BASE_URI + "graph/it/source-revision"; private static final java.net.http.HttpClient HTTP_CLIENT = java.net.http.HttpClient.newHttpClient(); @@ -83,21 +89,13 @@ static void enableLiveProjection() { } @Test - void anAdminSparqlUpdateMovesTheWatermark() throws Exception { - final long before = enqueuedWatermark(); - - update( - "INSERT DATA { GRAPH <" - + BASE_URI - + "graph/it/source-revision> { \"" - + UUID.randomUUID() - + "\" } }"); - - assertTrue(enqueuedWatermark() > before); + void anAdminSparqlUpdateRecordsOneUntrackedWrite() { + assertEquals( + 1, untrackedWritesDuring(() -> assertEquals(200, update(insertData()).statusCode()))); } @Test - void aPipelineRunRecordedInTheGraphMovesTheWatermark(final TestNamespace ns) { + void aPipelineRunRecordedInTheGraphRecordsOneUntrackedWrite(final TestNamespace ns) { final Pipeline pipeline = SdkClients.adminClient() .pipelines() @@ -106,61 +104,105 @@ void aPipelineRunRecordedInTheGraphMovesTheWatermark(final TestNamespace ns) { .withName(ns.prefix("pipeline")) .withService( PipelineServiceTestFactory.createAirflow(ns).getFullyQualifiedName())); - final long before = enqueuedWatermark(); - SdkClients.adminClient() - .pipelines() - .addPipelineStatus( - pipeline.getFullyQualifiedName(), - new PipelineStatus() - .withExecutionStatus(StatusType.Successful) - .withTimestamp(System.currentTimeMillis())); + final long recorded = + untrackedWritesDuring( + () -> + SdkClients.adminClient() + .pipelines() + .addPipelineStatus( + pipeline.getFullyQualifiedName(), + new PipelineStatus() + .withExecutionStatus(StatusType.Successful) + .withTimestamp(System.currentTimeMillis()))); - assertTrue(enqueuedWatermark() > before); + assertEquals(1, recorded); } @Test - void anInPlaceReindexMovesTheWatermarkBeforeAndAfterItWrites() { + void anInPlaceReindexRecordsAWriteBeforeAndAfterItWrites() { assumeFalse( TestSuiteBootstrap.isK8sEnabled(), "App trigger is not compatible with K8s pipelines"); final HttpClient client = SdkClients.adminClient().getHttpClient(); final AppRunRecord previous = awaitNoRunInFlight(client); - final long before = enqueuedWatermark(); + final AppRunRecord[] run = new AppRunRecord[1]; - trigger(client); - final AppRunRecord run = awaitRunAfter(client, previous); + final long recorded = + untrackedWritesDuring( + () -> { + trigger(client); + run[0] = awaitRunAfter(client, previous); + }); assertTrue( - Set.of("completed", "success").contains(status(run)), () -> "Reindex failed: " + run); - assertTrue(enqueuedWatermark() >= before + 2); + Set.of("completed", "success").contains(status(run[0])), () -> "Reindex failed: " + run[0]); + assertEquals(2, recorded); + } + + /** + * Counts the queue IDs handed out during {@code action} that left no row to deliver. Delivery is + * paused by holding the drain guard, so every live write enqueued meanwhile stays in the queue and + * is told apart from untracked writes, whose rows are gone as soon as they commit. + */ + private static long untrackedWritesDuring(final Runnable action) { + try (Handle drainGuard = TestSuiteBootstrap.getJdbi().open()) { + drainGuard.begin(); + try { + drainGuard + .createQuery("SELECT id FROM rdf_live_write_guard WHERE id = 'drain' FOR UPDATE") + .mapTo(String.class) + .one(); + final RdfLiveWriteStore liveWrites = + new RdfLiveWriteStore(TestSuiteBootstrap.getJdbi(), Clock.systemUTC()); + final long before = liveWrites.enqueuedWatermark(); + action.run(); + final long after = liveWrites.enqueuedWatermark(); + final Set queued = Set.copyOf(queuedAfter(before)); + return LongStream.rangeClosed(before + 1, after).filter(id -> !queued.contains(id)).count(); + } finally { + drainGuard.rollback(); + } + } } - private static long enqueuedWatermark() { + private static List queuedAfter(final long id) { return TestSuiteBootstrap.getJdbi() .withHandle( handle -> handle - .createQuery( - "SELECT GREATEST(enqueuedWatermark, " - + "COALESCE((SELECT MAX(id) FROM rdf_live_write_queue), 0)) " - + "FROM rdf_projection_health WHERE id = 'active'") + .createQuery("SELECT id FROM rdf_live_write_queue WHERE id > :id") + .bind("id", id) .mapTo(Long.class) - .one()); + .list()); + } + + private static String insertData() { + return "INSERT DATA { GRAPH <" + + GRAPH + + "> { \"" + + UUID.randomUUID() + + "\" } }"; } - private static void update(final String update) throws Exception { - final String body = OBJECT_MAPPER.writeValueAsString(new SparqlQuery().withQuery(update)); + private static HttpResponse update(final String update) { final HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(SdkClients.getServerUrl() + "/v1/rdf/sparql/update")) .header("Authorization", "Bearer " + SdkClients.getAdminToken()) .header("Content-Type", "application/json") .timeout(Duration.ofSeconds(30)) - .POST(HttpRequest.BodyPublishers.ofString(body)) + .POST( + HttpRequest.BodyPublishers.ofString( + JsonUtils.pojoToJson(new SparqlQuery().withQuery(update)))) .build(); - final HttpResponse response = - HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - assertEquals(200, response.statusCode(), response.body()); + try { + return HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + } catch (IOException exception) { + throw new UncheckedIOException(exception); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(exception); + } } private static void trigger(final HttpClient client) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PipelineRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PipelineRepository.java index da46bff673ba..8ff330d0ef4d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PipelineRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PipelineRepository.java @@ -1363,9 +1363,12 @@ private void storePipelineExecutionInRdf(Pipeline pipeline, PipelineStatus pipel sparql.append("}"); - // Execute the SPARQL update - rdfRepository.executeSparqlUpdate(sparql.toString()); - RdfUpdater.recordUntrackedWrite(); + try { + rdfRepository.executeSparqlUpdate(sparql.toString()); + } finally { + // A failure can arrive after Fuseki applied the update, such as a timeout on the response. + RdfUpdater.recordUntrackedWrite(); + } } catch (Exception e) { LOG.error("Failed to store pipeline execution in RDF", e); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java index da6ea6018231..ec8fceb7cd1a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java @@ -645,44 +645,6 @@ interface RdfActiveDatasetDAO { @SqlQuery("SELECT datasetName FROM rdf_active_dataset WHERE id = '" + POINTER_ID + "'") String getActiveDataset(); - - /** - * Points serving at {@code datasetName} under a new generation, as every switch must: results - * computed from the previous dataset must never pass for current, even when the name repeats. - */ - default void setActiveDataset( - final String datasetName, final long updatedAt, final String updatedBy) { - upsertActiveDataset(datasetName, UUID.randomUUID().toString(), updatedAt, updatedBy); - } - - @ConnectionAwareSqlUpdate( - value = - "INSERT INTO rdf_active_dataset (id, datasetName, generation, updatedAt, updatedBy) " - + "VALUES ('" - + POINTER_ID - + "', :datasetName, :generation, :updatedAt, :updatedBy) " - + "ON DUPLICATE KEY UPDATE datasetName = VALUES(datasetName), " - + "generation = VALUES(generation), updatedAt = VALUES(updatedAt), " - + "updatedBy = VALUES(updatedBy)", - connectionType = MYSQL) - @ConnectionAwareSqlUpdate( - value = - "INSERT INTO rdf_active_dataset (id, datasetName, generation, updatedAt, updatedBy) " - + "VALUES ('" - + POINTER_ID - + "', :datasetName, :generation, :updatedAt, :updatedBy) " - + "ON CONFLICT (id) DO UPDATE SET datasetName = EXCLUDED.datasetName, " - + "generation = EXCLUDED.generation, updatedAt = EXCLUDED.updatedAt, " - + "updatedBy = EXCLUDED.updatedBy", - connectionType = POSTGRES) - void upsertActiveDataset( - @Bind("datasetName") String datasetName, - @Bind("generation") String generation, - @Bind("updatedAt") long updatedAt, - @Bind("updatedBy") String updatedBy); - - @SqlUpdate("DELETE FROM rdf_active_dataset WHERE id = '" + POINTER_ID + "'") - void clearActiveDataset(); } /** diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfLiveWriteStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfLiveWriteStore.java index 773b39f4f55d..0de6a1207af4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfLiveWriteStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfLiveWriteStore.java @@ -58,8 +58,7 @@ public long recordUntrackedWrite() { handle -> { lockEnqueue(handle); final long id = insert(handle, ""); - handle.execute("DELETE FROM rdf_live_write_queue WHERE id = ?", id); - handle.execute(RECORD_ENQUEUED, id); + retire(handle, id); return id; }); } @@ -141,10 +140,21 @@ private boolean processHead(final Handle handle, final Consumer write) { } catch (RuntimeException exception) { return recordFailure(handle, entry, exception); } - handle.execute("DELETE FROM rdf_live_write_queue WHERE id = ?", entry.id()); + retire(handle, entry.id()); return true; } + /** + * Removes a delivered or dead-lettered row, keeping its ID in the enqueued watermark. Servers that + * predate the column enqueue without recording it, so the queue row is the only trace of their + * write until it is retired here. No other code deletes queue rows; see + * ADR:2026-10-11-rdf-freshness-watermarks-have-one-writer-per-table. + */ + private static void retire(final Handle handle, final long id) { + handle.execute("DELETE FROM rdf_live_write_queue WHERE id = ?", id); + handle.execute(RECORD_ENQUEUED, id); + } + private boolean recordFailure( final Handle handle, final Entry entry, final RuntimeException failure) { final int attempts = Math.min(entry.attempts(), Integer.MAX_VALUE - 1) + 1; @@ -176,7 +186,7 @@ private void deadLetter( attempts, clock.millis(), reason); - handle.execute("DELETE FROM rdf_live_write_queue WHERE id = ?", entry.id()); + retire(handle, entry.id()); LOG.error( "Live RDF write {} exhausted {} attempts; dead-lettered for reconciliation", entry.id(), diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfSparqlService.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfSparqlService.java index 6410010d1400..697f152b6eaf 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfSparqlService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfSparqlService.java @@ -76,8 +76,12 @@ public void update(final String sparql) { } federationGuard.enforceUpdate(request); requireSingleWhereBearingOperation(request); - repository.executeSparqlUpdate(sparql); - RdfUpdater.recordUntrackedWrite(); + try { + repository.executeSparqlUpdate(sparql); + } finally { + // A failure can arrive after Fuseki applied the update, such as a timeout on the response. + RdfUpdater.recordUntrackedWrite(); + } } private static void requireSingleWhereBearingOperation(UpdateRequest request) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/rebuild/RdfRebuildStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/rebuild/RdfRebuildStore.java index f23dea6c6ffb..06ece37738fb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/rebuild/RdfRebuildStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/rebuild/RdfRebuildStore.java @@ -23,7 +23,11 @@ import org.jdbi.v3.core.transaction.TransactionIsolationLevel; import org.openmetadata.service.rdf.storage.RdfWriteOutcomeUnknownException; -/** Durable journal and database fences shared by every OpenMetadata server. */ +/** + * Durable journal and database fences shared by every OpenMetadata server. The only writer of + * {@code rdf_active_dataset}, so every promotion gets a new generation; see + * ADR:2026-10-11-rdf-freshness-watermarks-have-one-writer-per-table. + */ public final class RdfRebuildStore { public static final long LEASE_MILLIS = 120_000; public static final JournalLimits DEFAULT_LIMITS = new JournalLimits(256L * 1024 * 1024, 100_000); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfReasoningContractTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfReasoningContractTest.java index a7ea91260d9b..5cc168dff088 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfReasoningContractTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfReasoningContractTest.java @@ -32,6 +32,7 @@ import java.util.Map; import java.util.function.Consumer; import java.util.stream.Stream; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -45,6 +46,9 @@ * The reasoning protocol between OpenMetadata and the RDF store. Each example under {@code * rdf/reasoning/} must satisfy its JSON Schema and survive the generated Java model unchanged, * because the store implements the protocol from the schemas, not from these classes. + * + *

The per-operation rules are recorded in + * ADR:2026-10-11-rdf-reasoning-job-requests-carry-the-fields-their-operation-needs. */ class RdfReasoningContractTest { private static final String SCHEMA_BASE = "https://open-metadata.org/schema/"; @@ -136,6 +140,62 @@ static Stream violations() { Contract.REQUEST, request -> request.put("ontologyUrl", "https://example.org/remote.owl"), "additionalProperties"), + violation( + "a REFRESH without a rule bundle digest", + "refresh-request", + Contract.REQUEST, + request -> request.remove("ruleBundleDigest"), + "required"), + violation( + "a CHECK without an ontology", + "check-subsumption-request", + Contract.REQUEST, + request -> request.remove("ontologyIri"), + "required"), + violation( + "a CHECK without a question", + "check-subsumption-request", + Contract.REQUEST, + request -> request.remove("check"), + "required"), + violation( + "an EXPLAIN without an ontology", + "explain-request", + Contract.REQUEST, + request -> request.remove("ontologyIri"), + "required"), + violation( + "an EXPLAIN without a statement to justify", + "explain-request", + Contract.REQUEST, + request -> request.remove("explain"), + "required"), + violation( + "a SUBSUMPTION without a superclass", + "check-subsumption-request", + Contract.REQUEST, + request -> object(request, "check").remove("superClassExpression"), + "required"), + violation( + "a SATISFIABILITY without a class", + "check-subsumption-request", + Contract.REQUEST, + request -> { + final ObjectNode check = object(request, "check"); + check.put("kind", "SATISFIABILITY"); + check.remove(List.of("classExpression", "superClassExpression")); + }, + "required"), + violation( + "an ENTAILMENT without a statement", + "check-subsumption-request", + Contract.REQUEST, + request -> { + final ObjectNode check = object(request, "check"); + check.put("kind", "ENTAILMENT"); + check.remove(List.of("classExpression", "superClassExpression")); + }, + "required"), violation( "more rules than one bundle may carry", "refresh-request-with-rule", @@ -180,6 +240,16 @@ static Stream violations() { "pattern")); } + @Test + void aConsistencyCheckTakesNoExpression() { + final ObjectNode request = (ObjectNode) read("check-subsumption-request"); + final ObjectNode check = object(request, "check"); + check.put("kind", "CONSISTENCY"); + check.remove(List.of("classExpression", "superClassExpression")); + + assertEquals(List.of(), messages(Contract.REQUEST.validate(request))); + } + @ParameterizedTest(name = "{0}") @MethodSource("violations") void theContractRejects( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfSparqlServiceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfSparqlServiceTest.java index bfb7640b9482..f0061e45c300 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfSparqlServiceTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfSparqlServiceTest.java @@ -18,11 +18,13 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.lang.reflect.Field; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.openmetadata.service.rdf.federation.SparqlFederationGuard; @@ -132,6 +134,28 @@ void allowsOneWhereBearingOperationWithDataOnlyOperations() { verify(repository).executeSparqlUpdate(update); } + @Test + void recordsAnUpdateWhoseOutcomeIsUnknownAsAnUntrackedWrite() + throws ReflectiveOperationException { + RdfRepository repository = mock(RdfRepository.class); + String update = "INSERT DATA { }"; + doThrow(new IllegalStateException("Timed out after Fuseki applied the update")) + .when(repository) + .executeSparqlUpdate(update); + RdfLiveWriteStore store = mock(RdfLiveWriteStore.class); + Field storeField = RdfUpdater.class.getDeclaredField("liveWriteStore"); + storeField.setAccessible(true); + Object originalStore = storeField.get(null); + storeField.set(null, store); + try { + assertThrows(IllegalStateException.class, () -> service(repository).update(update)); + + verify(store).recordUntrackedWrite(); + } finally { + storeField.set(null, originalStore); + } + } + @Test void ownsFormatAndInferenceValidationForEveryTransport() { RdfRepository repository = mock(RdfRepository.class); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfUpdaterTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfUpdaterTest.java index 9380c6fdaef4..7124eb2b19ae 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfUpdaterTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfUpdaterTest.java @@ -16,23 +16,32 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.openmetadata.schema.api.rdf.RdfReasoningFreshness; +import org.openmetadata.schema.api.rdf.RdfReasoningInput; +import org.openmetadata.schema.api.rdf.RdfSourceRevision; import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.EntityRelationship; import org.openmetadata.schema.type.Relationship; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; +import org.openmetadata.service.rdf.reasoning.ReasoningFreshness; import org.openmetadata.service.util.PostCommitActionQueue; class RdfUpdaterTest { @@ -139,6 +148,50 @@ void typedGlossaryRemovalIsCaptured() { List.of(new RdfLiveWrite.GlossaryRelationChange(fromId, toId, "broader", true)), submitted); } + @Test + void anUntrackedWriteThatCannotBeRecordedLeavesReasoningFreshnessUnknown() + throws ReflectiveOperationException { + final AtomicLong failures = new AtomicLong(); + final RdfLiveWriteStore store = mock(RdfLiveWriteStore.class); + when(store.recordUntrackedWrite()).thenThrow(new IllegalStateException("SQL unavailable")); + doAnswer( + invocation -> { + failures.incrementAndGet(); + return null; + }) + .when(store) + .markDegraded(anyString()); + when(store.isDegraded()).thenAnswer(invocation -> failures.get() > 0); + final Field storeField = RdfUpdater.class.getDeclaredField("liveWriteStore"); + storeField.setAccessible(true); + final Object originalStore = storeField.get(null); + storeField.set(null, store); + RdfProjectionHealth.initialize(store); + try { + final UUID generation = UUID.randomUUID(); + final RdfReasoningInput input = + new RdfReasoningInput() + .withSourceRevision( + new RdfSourceRevision() + .withDatasetGeneration(generation) + .withLiveWriteWatermark(0L)); + + RdfUpdater.recordUntrackedWrite(); + + assertTrue(RdfProjectionHealth.isDegraded()); + assertEquals( + RdfReasoningFreshness.UNKNOWN, + ReasoningFreshness.of( + input, + new ReasoningFreshness.Serving( + generation, 0, RdfProjectionHealth.isDegraded(), null, null))); + } finally { + storeField.set(null, originalStore); + RdfProjectionHealth.initialize(null); + RdfProjectionHealth.markReady(); + } + } + @Test void disabledUpdaterDoesNotCaptureWrites() throws ReflectiveOperationException { queueField.set(null, null); diff --git a/openmetadata-spec/src/main/resources/json/schema/api/rdf/rdfReasoningJobRequest.json b/openmetadata-spec/src/main/resources/json/schema/api/rdf/rdfReasoningJobRequest.json index a2f2f3bd0720..2ba90ebae451 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/rdf/rdfReasoningJobRequest.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/rdf/rdfReasoningJobRequest.json @@ -37,7 +37,30 @@ } }, "required": ["kind"], - "additionalProperties": false + "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { "kind": { "const": "SATISFIABILITY" } }, + "required": ["kind"] + }, + "then": { "required": ["classExpression"] } + }, + { + "if": { + "properties": { "kind": { "const": "SUBSUMPTION" } }, + "required": ["kind"] + }, + "then": { "required": ["classExpression", "superClassExpression"] } + }, + { + "if": { + "properties": { "kind": { "const": "ENTAILMENT" } }, + "required": ["kind"] + }, + "then": { "required": ["statement"] } + } + ] }, "explain": { "javaType": "org.openmetadata.schema.api.rdf.RdfReasoningExplain", @@ -103,5 +126,28 @@ } }, "required": ["requestId", "operation", "sourceRevision", "ontologySelection"], - "additionalProperties": false + "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { "operation": { "const": "REFRESH" } }, + "required": ["operation"] + }, + "then": { "required": ["ruleBundleDigest"] } + }, + { + "if": { + "properties": { "operation": { "const": "CHECK" } }, + "required": ["operation"] + }, + "then": { "required": ["ontologyIri", "check"] } + }, + { + "if": { + "properties": { "operation": { "const": "EXPLAIN" } }, + "required": ["operation"] + }, + "then": { "required": ["ontologyIri", "explain"] } + } + ] }