Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 4 additions & 0 deletions docs/plans/2026-10-07-fuseki-native-reasoning.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
8 changes: 8 additions & 0 deletions docs/rdf-production-setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -47,22 +51,24 @@
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
@ExtendWith(TestNamespaceExtension.class)
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();

Expand All @@ -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> { <urn:it:revision> <urn:it:value> \""
+ 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()
Expand All @@ -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<Long> 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<Long> 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
+ "> { <urn:it:revision> <urn:it:value> \""
+ UUID.randomUUID()
+ "\" } }";
}

private static void update(final String update) throws Exception {
final String body = OBJECT_MAPPER.writeValueAsString(new SparqlQuery().withQuery(update));
private static HttpResponse<String> 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<String> 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading