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
Expand Up @@ -14,6 +14,8 @@
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
Expand Down Expand Up @@ -63,6 +65,7 @@ public class DataAssetsWorkflow implements DataInsightsWorkflow {
private final int retentionDays = 30;
private final Long startTimestamp;
private final Long endTimestamp;
private final long snapshotTimestamp;
private final int batchSize;
private final SearchRepository searchRepository;
private final CollectionDAO collectionDAO;
Expand All @@ -74,6 +77,7 @@ public class DataAssetsWorkflow implements DataInsightsWorkflow {
private DataInsightsEntityEnricherProcessor entityEnricher;
private Processor entityProcessor;
private Sink searchIndexSink;
private DataInsightsExtensions extensions;
@Getter private final WorkflowStats workflowStats = new WorkflowStats("DataAssetsWorkflow");

private volatile boolean stopped = false;
Expand Down Expand Up @@ -116,6 +120,7 @@ public DataAssetsWorkflow(
}

this.batchSize = batchSize;
this.snapshotTimestamp = timestamp;
this.searchRepository = searchRepository;
this.collectionDAO = collectionDAO;
this.entityTypes = entityTypes;
Expand Down Expand Up @@ -224,6 +229,30 @@ public void process() throws SearchIndexException {
}
LOG.info("[Data Insights] Processing Data Assets Insights.");
initialize();
DataInsightsExtension.RunContext runContext =
new DataInsightsExtension.RunContext(
UUID.randomUUID().toString(),
System.currentTimeMillis(),
snapshotTimestamp,
collectionDAO,
searchRepository,
dataAssetsConfig,
() -> stopped);
try (DataInsightsExtensions runExtensions = DataInsightsExtensions.open(runContext)) {
this.extensions = runExtensions;
processSources();
if (!stopped && !workflowStats.hasFailed()) {
runExtensions.complete();
}
} catch (CancellationException ex) {
stopped = true;
LOG.info("[Data Insights] Data Assets workflow stopped: {}", ex.getMessage());
} finally {
this.extensions = null;
}
}

private void processSources() throws SearchIndexException {
Map<String, Object> contextData = new HashMap<>();

contextData.put(START_TIMESTAMP_KEY, startTimestamp);
Expand Down Expand Up @@ -284,6 +313,7 @@ private void processSource(
continue;
}

extensions.beforeBatch(batch.getData());

@gitar-bot gitar-bot Bot Nov 14, 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.

💡 Edge Case: Cancellation in beforeBatch skips the per-source stats update

extensions.beforeBatch(...) (line 316) calls requireActive(), which throws CancellationException if stop() ran between batches or if the thread was left interrupted after the InterruptedException branch at line 372, which only breaks out of the current source. The inner try only catches SearchIndexException and InterruptedException, so the exception goes straight out of processSource. That skips the trailing drainAndFlush/updateWorkflowStats/mergeEnricherStepStats block (lines 381-386), and process() swallows the exception at line 247. Before this change, a stop inside a source still ended the loop normally and recorded that source's stats. With this change, they are lost on cancellation even when no extension is registered, since requireActive() runs no matter how many sessions exist. Fix: catch CancellationException inside the batch loop (mark it stopped and break), or check stopped instead of calling requireActive() before the batch.

Treat cancellation from the extension hook as a normal stop so the per-source finalisation still runs.:

} catch (CancellationException ex) {
  stopped = true;
  break;
} catch (InterruptedException ex) {
  Thread.currentThread().interrupt();
  break;
}

Was this helpful? React with 👍 / 👎

record EntityFuture(EntityInterface entity, Future<Void> future) {}
List<EntityFuture> entityFutures = new ArrayList<>();
for (EntityInterface entity : batch.getData()) {
Expand All @@ -296,6 +326,7 @@ record EntityFuture(EntityInterface entity, Future<Void> future) {}
try {
List<Map<String, Object>> enriched =
entityEnricher.enrichSingle(entity, contextData);
enriched.forEach(extensions::enrich);
List<?> bulkOps =
(List<?>) entityProcessor.process(enriched, contextData);
EntityReference ref = entity.getEntityReference();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package org.openmetadata.service.apps.bundles.insights.workflows.dataAssets;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.function.BooleanSupplier;
import org.openmetadata.schema.EntityInterface;
import org.openmetadata.schema.entity.applications.configuration.internal.DataAssetsConfig;
import org.openmetadata.service.jdbi3.CollectionDAO;
import org.openmetadata.service.search.SearchRepository;

/** Run-scoped additions to DI snapshots and consumers of a successfully indexed DI run. */
public interface DataInsightsExtension {
Session open(RunContext context);

record RunContext(
String runId,
long capturedAt,
long snapshotTimestamp,
CollectionDAO collectionDAO,
SearchRepository searchRepository,
DataAssetsConfig configuration,
BooleanSupplier cancelled) {
public RunContext(
String runId,
long capturedAt,
long snapshotTimestamp,
CollectionDAO collectionDAO,
SearchRepository searchRepository,
DataAssetsConfig configuration) {
this(
runId,
capturedAt,
snapshotTimestamp,
collectionDAO,
searchRepository,
configuration,
() -> false);
}

public void requireActive() {
if (cancelled.getAsBoolean() || Thread.currentThread().isInterrupted()) {
throw new CancellationException(
"Data Insights run was cancelled or lost its execution lease");
}
}
}

/** Enrichment can run concurrently; completion runs once, while the DI job still owns its lease. */
interface Session extends AutoCloseable {
/** Allows bounded bulk lookups before the batch's concurrent enrichment starts. */
default void beforeBatch(List<? extends EntityInterface> entities) {}

default void enrich(Map<String, Object> snapshot) {}

default void complete() {}

@Override
default void close() {}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package org.openmetadata.service.apps.bundles.insights.workflows.dataAssets;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import org.openmetadata.schema.EntityInterface;
import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.DataInsightsExtension.RunContext;
import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.DataInsightsExtension.Session;

/** Keeps extension state local to one DI run, including cleanup after startup or indexing failure. */
public final class DataInsightsExtensions implements AutoCloseable {
private final RunContext context;
private final List<Session> sessions = new ArrayList<>();

private DataInsightsExtensions(RunContext context) {
this.context = context;
}

public static DataInsightsExtensions open(RunContext context) {
return open(context, ServiceLoader.load(DataInsightsExtension.class));
}

static DataInsightsExtensions open(
RunContext context, Iterable<DataInsightsExtension> extensions) {
DataInsightsExtensions run = new DataInsightsExtensions(context);
try {
for (DataInsightsExtension extension : extensions) {
Session session = extension.open(context);
if (session == null) {
throw new IllegalStateException(
"Data Insights extension %s returned a null session"
.formatted(extension.getClass().getName()));
}
run.sessions.add(session);
}
} catch (RuntimeException | Error failure) {
try {
run.close();
} catch (RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
}
throw failure;
}
return run;
}

public void enrich(Map<String, Object> snapshot) {
context.requireActive();
sessions.forEach(session -> session.enrich(snapshot));
}

public void complete() {
context.requireActive();
sessions.forEach(Session::complete);
}

public void beforeBatch(List<? extends EntityInterface> entities) {
context.requireActive();
sessions.forEach(session -> session.beforeBatch(entities));
}

@Override
public void close() {
RuntimeException failure = null;
for (Session session : sessions.reversed()) {
try {
session.close();
} catch (RuntimeException exception) {
if (failure == null) {
failure = exception;
} else {
failure.addSuppressed(exception);
}
}
}
if (failure != null) {
throw failure;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
package org.openmetadata.service.apps.bundles.insights.workflows.dataAssets;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CancellationException;
import org.junit.jupiter.api.Test;
import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.DataInsightsExtension.RunContext;
import org.openmetadata.service.apps.bundles.insights.workflows.dataAssets.DataInsightsExtension.Session;

class DataInsightsExtensionsTest {
private static final RunContext CONTEXT = new RunContext("run", 2000, 1000, null, null, null);

@Test
void batchPreparationPrecedesEnrichmentAndCancellationStopsCompletion() {
var cancelled = new java.util.concurrent.atomic.AtomicBoolean();
var context = new RunContext("run", 2000, 1000, null, null, null, cancelled::get);
List<String> calls = new ArrayList<>();
DataInsightsExtension extension =
ignored ->
new Session() {
@Override
public void beforeBatch(
List<? extends org.openmetadata.schema.EntityInterface> entities) {
calls.add("batch");
}

@Override
public void enrich(Map<String, Object> snapshot) {
calls.add("asset");
}

@Override
public void complete() {
calls.add("complete");
}
};
try (var run = DataInsightsExtensions.open(context, List.of(extension))) {
run.beforeBatch(List.of());
run.enrich(new HashMap<>());
cancelled.set(true);
assertThrows(CancellationException.class, run::complete);
assertThrows(CancellationException.class, () -> run.enrich(new HashMap<>()));
assertEquals(List.of("batch", "asset"), calls);
}
}

@Test
void startupAndCleanupFailuresAreBothPreserved() {
DataInsightsExtension opened =
context ->
new Session() {
@Override
public void close() {
throw new IllegalStateException("close");
}
};
DataInsightsExtension failed =
context -> {
throw new IllegalArgumentException("open");
};
var error =
assertThrows(
IllegalArgumentException.class,
() -> DataInsightsExtensions.open(CONTEXT, List.of(opened, failed)));
assertEquals("open", error.getMessage());
assertEquals("close", error.getSuppressed()[0].getMessage());
}

@Test
void nullSessionFailsFastWithProviderName() {
var error =
assertThrows(
IllegalStateException.class,
() -> DataInsightsExtensions.open(CONTEXT, List.of(new NullSessionExtension())));

assertTrue(error.getMessage().contains(NullSessionExtension.class.getName()));
}

@Test
void onlySessionsWriteToTheSnapshotAndCompletionIsExplicit() {
List<String> events = new ArrayList<>();
DataInsightsExtension extension =
context ->
new Session() {
@Override
public void enrich(Map<String, Object> snapshot) {
events.add("enriched");
snapshot.put("added", true);
}

@Override
public void complete() {
events.add("completed");
}

@Override
public void close() {
events.add("closed");
}
};
var snapshot = new HashMap<String, Object>();
try (var run = DataInsightsExtensions.open(CONTEXT, List.of(extension))) {
run.enrich(snapshot);
assertEquals(List.of("enriched"), events);
run.complete();
}

assertEquals(Map.of("added", true), snapshot);
assertEquals(List.of("enriched", "completed", "closed"), events);
}

@Test
void failedStartupClosesAlreadyOpenedSessions() {
List<String> events = new ArrayList<>();
DataInsightsExtension opened = context -> closingSession(events, "first");
DataInsightsExtension failed =
context -> {
throw new IllegalStateException("source failed");
};

assertThrows(
IllegalStateException.class,
() -> DataInsightsExtensions.open(CONTEXT, List.of(opened, failed)));
assertEquals(List.of("first"), events);
}

@Test
void failureToCloseOneSessionDoesNotLeakAnother() {
List<String> events = new ArrayList<>();
DataInsightsExtension opened = context -> closingSession(events, "first");
DataInsightsExtension failed =
context ->
new Session() {
@Override
public void close() {
throw new IllegalStateException("cleanup failed");
}
};
var run = DataInsightsExtensions.open(CONTEXT, List.of(opened, failed));

assertThrows(IllegalStateException.class, run::close);
assertEquals(List.of("first"), events);
}

private static Session closingSession(List<String> events, String event) {
return new Session() {
@Override
public void close() {
events.add(event);
}
};
}

private static final class NullSessionExtension implements DataInsightsExtension {
@Override
public Session open(RunContext context) {
return null;
}
}
}
Loading