From 410db2b551fd766307e79ae4b8f868c9752504d2 Mon Sep 17 00:00:00 2001 From: Ram Narayan Balaji Date: Tue, 3 Nov 2026 20:12:33 +0530 Subject: [PATCH 1/4] Fix merge-queue flakes: history walk, alert log flood, change-request supersede race, stale child propagation - History walk IT: a concurrent hard delete can leave the last forward page empty and cursorless; the walk now ends on the last page with rows. - ChannelResolution logged every destination at INFO; since validation decrypts unchanged destinations, StoredConfigBoundsTest wrote ~64k lines and timed out. Log at DEBUG, WARN only for an unregistered channel. - CreateTask: the run of a change-request revision that has since been replaced no longer supersedes the newer revision's live review task. - Search: watch background child propagations and reindex the parent when one fails or skips children; queue a parent id in the id column so the retry worker can resolve it. - Test fixes: UserSecretsIT waits for the async change event, PersonaAIContextIT compares both lists in one poll, AssetsTabVersioningIT takes the multi-domain rule lock, and DataProductDomainMigrationIT waits long enough for the retry queue's repair. --- ...-child-propagation-reindexes-its-parent.md | 40 ++++++ .../it/tests/AssetsTabVersioningIT.java | 5 + .../openmetadata/it/tests/BaseEntityIT.java | 9 +- .../tests/DataProductDomainMigrationIT.java | 5 +- .../openmetadata/it/tests/UserSecretsIT.java | 27 ++-- .../it/tests/mcp/PersonaAIContextIT.java | 11 +- .../alerting/channel/ChannelResolution.java | 26 +++- .../approval/ChangeRequestService.java | 8 ++ .../elements/nodes/userTask/CreateTask.java | 13 +- .../search/ChildPropagationWatcher.java | 116 ++++++++++++++++++ .../service/search/SearchIndexRetryQueue.java | 17 +++ .../search/SearchPropagationLimits.java | 6 + .../ElasticSearchEntityManager.java | 47 ++++++- .../opensearch/OpenSearchEntityManager.java | 44 ++++++- .../nodes/userTask/CreateTaskTest.java | 32 +++++ .../search/ChildPropagationWatcherTest.java | 78 ++++++++++++ .../search/SearchIndexRetryQueueTest.java | 16 +++ ...sticSearchChildPropagationOutcomeTest.java | 89 ++++++++++++++ ...OpenSearchChildPropagationOutcomeTest.java | 79 ++++++++++++ 19 files changed, 640 insertions(+), 28 deletions(-) create mode 100644 docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/search/elasticsearch/ElasticSearchChildPropagationOutcomeTest.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/OpenSearchChildPropagationOutcomeTest.java diff --git a/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md b/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md new file mode 100644 index 000000000000..5998aaf5f15a --- /dev/null +++ b/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md @@ -0,0 +1,40 @@ +# A background child propagation that leaves children stale reindexes its parent + +- **Status:** Accepted +- **Revisions:** v1 2026-11-03 (initial) +- **Deciders:** Ram Narayan Balaji +- **Guard:** `ChildPropagationWatcherTest`, `ElasticSearchChildPropagationOutcomeTest`, `OpenSearchChildPropagationOutcomeTest`, `SearchIndexRetryQueueTest` +- **Related:** `TableResourceIT.test_ownerPropagationToSearchIndex` merge-queue flake; the async child update introduced for socket timeouts on large child sets + +## Context + +Inherited fields (owners, domains, tags, ...) reach a parent's children in search through an +update-by-query submitted with `wait_for_completion=false`, so a large child set cannot trip the +client socket timeout. The cluster then runs the task after the request has returned, and nothing +read its result. Under load (`429`s, partial shard failures) or a concurrent write +(`conflicts=proceed` skips the child), children stayed stale until the next full reindex. The +fallback for a submit that failed outright queued the parent's id in the retry queue's FQN column, +which the retry worker resolves by name only, so that repair never ran either. + +## Decision + +- Each submitted child propagation is watched to completion by `ChildPropagationWatcher`, on two + daemon threads with at most 1,000 tasks waiting; past that a task goes unwatched (logged), never + blocking the request path. +- A watcher waits at most `SearchPropagationLimits.CHILD_PROPAGATION_WAIT` (15 minutes, enough for + the million-document service the rate limit is sized for). A task still running then, or whose + outcome cannot be read, is left alone. +- A finished task with failures, a timeout, or any version conflict queues its **parent** in the + search retry queue. The worker reindexes the parent and, by cascade, its children from the + database, which is correct whatever the propagation script was. +- A parent key is queued by id when it is a UUID and by FQN otherwise + (`SearchIndexRetryQueue.enqueueParent`). + +## Consequences + +Search no longer silently keeps a stale inherited field after a failed propagation; it heals +within the retry worker's cycle. The cost is one blocked watcher thread per running propagation +and a cascade reindex (capped by the worker's cascade limit) per failed one. Only parent-to-child +propagation is watched: reference-copy updates match by referenced id, and a parent reindex would +not repair them. Revisit if the retry queue shows conflict-driven requeues dominating under heavy +ingest; then drop version conflicts from the trigger. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AssetsTabVersioningIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AssetsTabVersioningIT.java index 74e60b60dd25..aeb07b3c8945 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AssetsTabVersioningIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AssetsTabVersioningIT.java @@ -38,6 +38,8 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.ResourceAccessMode; +import org.junit.jupiter.api.parallel.ResourceLock; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.openmetadata.it.factories.APIServiceTestFactory; @@ -129,6 +131,9 @@ */ @Execution(ExecutionMode.CONCURRENT) @ExtendWith(TestNamespaceExtension.class) +// Moving an asset replaces its domain only while "Multiple Domains are not allowed" is on; tests +// that switch the rule off hold this lock exclusively. +@ResourceLock(value = "MULTI_DOMAIN_RULE", mode = ResourceAccessMode.READ) public class AssetsTabVersioningIT { private static final String ACTING_USER = "shared_user1"; diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BaseEntityIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BaseEntityIT.java index 4e23fba664c5..0c81385b7769 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BaseEntityIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BaseEntityIT.java @@ -7778,8 +7778,13 @@ private HistoryWalk walkForward( String after = null; do { JsonNode result = readHistoryPage(client, basePath, startTs, endTs, limit, "after", after); - pages.add(versionKeys(result)); - lastPageBeforeCursor = cursor(result, "before"); + List page = versionKeys(result); + // A concurrent test can hard-delete the row that made the previous page report more, + // leaving this page empty and cursorless. The walk then ends on the last page with rows. + if (!page.isEmpty()) { + pages.add(page); + lastPageBeforeCursor = cursor(result, "before"); + } after = cursor(result, "after"); } while (after != null); return new HistoryWalk(pages, lastPageBeforeCursor); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductDomainMigrationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductDomainMigrationIT.java index 67f6369461c6..168683944928 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductDomainMigrationIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductDomainMigrationIT.java @@ -917,9 +917,10 @@ private void verifyAssetsInDomainSearch( private void verifyAssetsInDomainAssetsEndpoint( OpenMetadataClient client, Domain domain, List expectedTables, boolean shouldExist) throws Exception { - // Use Awaitility to poll for the expected state since search index updates are async + // The asset domains are rewritten in search during the request; when the cluster rejects that + // update under load, the search retry queue repairs the documents about half a minute later. Awaitility.await() - .atMost(30, TimeUnit.SECONDS) + .atMost(60, TimeUnit.SECONDS) .pollInterval(2, TimeUnit.SECONDS) .untilAsserted( () -> { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserSecretsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserSecretsIT.java index e0827175a303..f79ea7ddf271 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserSecretsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserSecretsIT.java @@ -7,12 +7,14 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import java.net.URLEncoder; +import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.stream.Stream; +import org.awaitility.Awaitility; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.openmetadata.it.factories.UserTestFactory; @@ -152,20 +154,25 @@ private static JsonNode asObject(final JsonNode node) { return node.isTextual() ? JsonUtils.readTree(node.asText()) : node; } + // Change events are written asynchronously once the response is sent (EventFilter), so the + // bot's event can land after the update returns. private static JsonNode storedEventOf(final UUID userId, final long since) { + return Awaitility.await("The bot's update must be recorded as a change event") + .atMost(Duration.ofSeconds(30)) + .pollInterval(Duration.ofMillis(250)) + .until(() -> latestEventOf(userId, since), Optional::isPresent) + .get(); + } + + private static Optional latestEventOf(final UUID userId, final long since) { final List events = allRows( SdkClients.adminClient().getHttpClient(), - "/v1/events?entityUpdated=user&limit=1000×tamp=" - + since - + "&endTs=" - + System.currentTimeMillis()); - final Optional found = - events.stream() - .filter(event -> userId.toString().equals(event.path("entityId").asText())) - .reduce((first, last) -> last); - assertTrue(found.isPresent(), "The bot's update must be recorded as a change event"); - return found.get(); + "/v1/events?entityUpdated=user&limit=1000×tamp=%d&endTs=%d" + .formatted(since, System.currentTimeMillis())); + return events.stream() + .filter(event -> userId.toString().equals(event.path("entityId").asText())) + .reduce((first, last) -> last); } // Every row of a bounded window, following the cursor: other tests write to the same endpoints, diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/PersonaAIContextIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/PersonaAIContextIT.java index 00c268832a57..12335904dcc1 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/PersonaAIContextIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/PersonaAIContextIT.java @@ -705,7 +705,16 @@ private static JsonNode statusOf(JsonNode statuses, Persona target) { } @Test - void aiContextStatusPagesWithTheSameCursorAsThePersonaList() throws Exception { + void aiContextStatusPagesWithTheSameCursorAsThePersonaList() { + // The two lists are read one after the other, and a sibling test in the parallel lane may + // create or delete a persona in between; compare them again until both reads see one state. + Awaitility.await("status pages like the persona list") + .atMost(Duration.ofSeconds(30)) + .pollInterval(Duration.ofSeconds(1)) + .untilAsserted(this::assertStatusPagesLikeThePersonaList); + } + + private void assertStatusPagesLikeThePersonaList() throws Exception { JsonNode statusPage = OBJECT_MAPPER.readTree(getResponse("personas/aiContext/status?limit=1", authToken).body()); JsonNode personaPage = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/alerting/channel/ChannelResolution.java b/openmetadata-service/src/main/java/org/openmetadata/service/alerting/channel/ChannelResolution.java index 53f0cd620e50..ce1d08524496 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/alerting/channel/ChannelResolution.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/alerting/channel/ChannelResolution.java @@ -37,22 +37,36 @@ public static ChannelResolution of(SubscriptionDestination destination) { String named = destination.getChannel(); String channelId = named == null ? destination.getType().value() : named; ChannelResolution resolution = new ChannelResolution(channelId, Channels.of(channelId)); - logOnce(destination, resolution, named == null ? "its type" : "its channel field"); + logResolution(destination, resolution, named == null ? "its type" : "its channel field"); return resolution; } - private static void logOnce( + private static void logResolution( + SubscriptionDestination destination, ChannelResolution resolution, String resolvedBy) { + if (resolution.channel().isEmpty()) { + warnUnregistered(destination, resolution, resolvedBy); + } else { + // Resolution runs on every save and read of every destination; at INFO a large alert + // floods the log, so only an unregistered channel, which needs action, is worth a warning. + LOG.debug( + "Destination {} is served by channel {} (resolved by {})", + destination.getId(), + resolution.channelId(), + resolvedBy); + } + } + + private static void warnUnregistered( SubscriptionDestination destination, ChannelResolution resolution, String resolvedBy) { if (LOGGED.size() >= REMEMBERED_DESTINATIONS) { LOGGED.clear(); } if (LOGGED.add(destination.getId() + ":" + resolution.channelId())) { - LOG.info( - "Destination {} is served by channel {} (resolved by {}, registered: {})", + LOG.warn( + "Destination {} names channel {} (resolved by {}), which is not registered on this server", destination.getId(), resolution.channelId(), - resolvedBy, - resolution.channel().isPresent()); + resolvedBy); } } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ChangeRequestService.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ChangeRequestService.java index fcf97e206161..adb6c72d1161 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ChangeRequestService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ChangeRequestService.java @@ -251,6 +251,14 @@ public static boolean attachTask( return reviewable; } + /** Whether {@code revisionNumber} is still the active revision of an open request. */ + public static boolean isActiveRevision(UUID changeRequestId, int revisionNumber) { + ChangeRequest request = dao().changeRequestDAO().findById(changeRequestId); + return request != null + && isOpen(request) + && Objects.equals(request.getActiveRevisionNumber(), revisionNumber); + } + /** * The open review task of a pending request in workflow run {@code workflowInstanceId}, if any. */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTask.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTask.java index 861c13b078dc..2038897f2c6e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTask.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTask.java @@ -800,7 +800,7 @@ private void supersedePriorApprovalTask( String updatedBy) { // Best-effort cleanup: failing to supersede a prior task must never abort creation of the new // approval task, so all exceptions are contained here instead of bubbling up as a BpmnError. - if (taskCategory == TaskCategory.Approval) { + if (taskCategory == TaskCategory.Approval && !reviewsStaleRevision(delegateTask)) { try { // A change request's review keeps one live approval per (entity, workflow, requester): a // new held edit supersedes only the same requester's prior review, so other requesters' @@ -1239,6 +1239,17 @@ private static Object linkChangeRequest(Object payload, DelegateTask delegateTas } // Whether this run reviews a change request: such a run carries the request in its variables. + // A change request's runs can finish out of order. The run of a revision the request has since + // replaced must leave the newer revision's live review alone; attachTask then closes its own + // task. + static boolean reviewsStaleRevision(DelegateTask delegateTask) { + return ChangeRequestRun.from(new WorkflowVariableHandler(delegateTask)) + .filter( + run -> + !ChangeRequestService.isActiveRevision(run.changeRequestId(), run.revisionNumber())) + .isPresent(); + } + private static boolean reviewsChangeRequest(DelegateTask delegateTask) { return ChangeRequestRun.from(new WorkflowVariableHandler(delegateTask)).isPresent(); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java new file mode 100644 index 000000000000..bef39b044857 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java @@ -0,0 +1,116 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.search; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.Executor; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import lombok.extern.slf4j.Slf4j; + +/** + * Inherited fields reach a parent's children through an update-by-query the cluster runs in the + * background, after the request that changed the parent has returned. A task that fails under load, + * or skips a child on a version conflict, leaves that child stale until the next reindex, and + * nothing would notice. This waits for each task and queues the parent of one that left children + * stale; the retry worker then reindexes the parent and its children from the database. + */ +@Slf4j +public final class ChildPropagationWatcher { + private static final int WATCHER_THREADS = 2; + private static final int MAX_PENDING_TASKS = 1_000; + private static final Executor WATCHERS = + new ThreadPoolExecutor( + WATCHER_THREADS, + WATCHER_THREADS, + 0L, + TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(MAX_PENDING_TASKS), + Thread.ofPlatform().name("search-child-propagation-watcher-", 0).daemon().factory(), + (task, executor) -> + LOG.warn( + "{} child propagation tasks are already being watched; not watching another", + MAX_PENDING_TASKS)); + + private ChildPropagationWatcher() {} + + /** What a background update-by-query did, once the cluster says it finished. */ + public record TaskOutcome(boolean finished, List failureReasons, long versionConflicts) { + public static TaskOutcome unfinished() { + return new TaskOutcome(false, List.of(), 0); + } + + boolean leftChildrenStale() { + return finished && (!failureReasons.isEmpty() || versionConflicts > 0); + } + + String describe() { + return failureReasons.isEmpty() + ? "%d child document(s) skipped on version conflicts".formatted(versionConflicts) + : String.join("; ", failureReasons); + } + } + + /** Blocks until the cluster reports the task finished, or its own wait times out. */ + @FunctionalInterface + public interface TaskAwaiter { + TaskOutcome await(String taskId) throws IOException; + } + + /** + * Watches the task that propagates to the children of {@code parentKey}, the parent id or FQN the + * propagation matched children on. + */ + public static void watch(String taskId, String parentKey, TaskAwaiter awaiter) { + watch(taskId, parentKey, awaiter, WATCHERS, SearchIndexRetryQueue::enqueueParent); + } + + static void watch( + String taskId, + String parentKey, + TaskAwaiter awaiter, + Executor executor, + BiConsumer repairParent) { + if (taskId != null && parentKey != null) { + executor.execute(() -> repairIfStale(taskId, parentKey, awaiter, repairParent)); + } + } + + private static void repairIfStale( + String taskId, + String parentKey, + TaskAwaiter awaiter, + BiConsumer repairParent) { + try { + TaskOutcome outcome = awaiter.await(taskId); + if (outcome.leftChildrenStale()) { + LOG.warn( + "Child propagation task {} for parent {} left children stale ({}); reindexing them", + taskId, + parentKey, + outcome.describe()); + repairParent.accept(parentKey, "updateChildren: %s".formatted(outcome.describe())); + } + } catch (IOException | RuntimeException e) { + LOG.warn( + "Could not learn how child propagation task {} for parent {} ended: {}", + taskId, + parentKey, + e.getMessage()); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryQueue.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryQueue.java index 4be63e33fa81..8cfa17ff3247 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryQueue.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryQueue.java @@ -71,6 +71,23 @@ public static void enqueue(String entityId, String entityFqn, String failureReas enqueue(entityId, entityFqn, "", failureReason); } + /** + * Queues the parent a child propagation matched its children on, so the retry worker reindexes + * the parent and its children. Propagations match on a parent id or FQN; the worker resolves the + * FQN column by name only, so an id queued there would never resolve. + */ + public static void enqueueParent(String parentKey, String failureReason) { + ParentKey key = ParentKey.of(parentKey); + enqueue(key.entityId(), key.entityFqn(), failureReason); + } + + /** A child propagation's parent key, split into the queue column the retry worker reads it from. */ + record ParentKey(String entityId, String entityFqn) { + static ParentKey of(String parentKey) { + return isUuid(parentKey) ? new ParentKey(parentKey, null) : new ParentKey(null, parentKey); + } + } + public static void enqueue( String entityId, String entityFqn, String entityType, String failureReason) { String normalizedEntityId = normalize(entityId); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchPropagationLimits.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchPropagationLimits.java index ff14bbdc6723..b6be213d78bc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchPropagationLimits.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchPropagationLimits.java @@ -28,4 +28,10 @@ private SearchPropagationLimits() {} * completion time for cluster stability is the right way round. */ public static final float REQUESTS_PER_SECOND = 2000f; + + /** + * How long a watcher waits for a child propagation to finish before giving up on learning its + * outcome. Covers the million-document service above with room to spare. + */ + public static final String CHILD_PROPAGATION_WAIT = "15m"; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java index 4d5d9be61738..56437bb9f2b0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java @@ -14,6 +14,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import es.co.elastic.clients.elasticsearch.ElasticsearchAsyncClient; import es.co.elastic.clients.elasticsearch.ElasticsearchClient; @@ -39,6 +40,7 @@ import es.co.elastic.clients.elasticsearch.core.UpdateRequest; import es.co.elastic.clients.elasticsearch.core.bulk.BulkOperation; import es.co.elastic.clients.elasticsearch.core.search.Hit; +import es.co.elastic.clients.elasticsearch.tasks.GetTasksResponse; import es.co.elastic.clients.json.JsonData; import jakarta.ws.rs.core.Response; import java.io.IOException; @@ -71,6 +73,7 @@ import org.openmetadata.sdk.exception.SearchException; import org.openmetadata.search.IndexMapping; import org.openmetadata.service.Entity; +import org.openmetadata.service.search.ChildPropagationWatcher; import org.openmetadata.service.search.ColumnLineageReconciler; import org.openmetadata.service.search.EntityManagementClient; import org.openmetadata.service.search.SearchClient; @@ -485,8 +488,8 @@ public void updateChildren( updates); LOG.info("Successfully submitted child update in ElasticSearch for index: {}", indexName); } catch (IOException | ElasticsearchException e) { - SearchIndexRetryQueue.enqueue( - null, fieldAndValue.getValue(), SearchIndexRetryQueue.failureReason("updateChildren", e)); + SearchIndexRetryQueue.enqueueParent( + fieldAndValue.getValue(), SearchIndexRetryQueue.failureReason("updateChildren", e)); LOG.error("Failed to update children in ElasticSearch for index: {}", indexName, e); } } @@ -510,7 +513,45 @@ private void submitChildUpdate( Pair fieldAndValue, Pair> updates) throws IOException { - client.updateByQuery(buildUpdateChildrenRequest(indexNames, fieldAndValue, updates)); + UpdateByQueryResponse submitted = + client.updateByQuery(buildUpdateChildrenRequest(indexNames, fieldAndValue, updates)); + ChildPropagationWatcher.watch( + submitted.task(), fieldAndValue.getValue(), this::awaitChildPropagation); + } + + private ChildPropagationWatcher.TaskOutcome awaitChildPropagation(String taskId) + throws IOException { + GetTasksResponse task = + client + .tasks() + .get( + g -> + g.taskId(taskId) + .waitForCompletion(true) + .timeout(t -> t.time(SearchPropagationLimits.CHILD_PROPAGATION_WAIT))); + return childPropagationOutcome(task); + } + + static ChildPropagationWatcher.TaskOutcome childPropagationOutcome(GetTasksResponse task) { + ChildPropagationWatcher.TaskOutcome outcome = ChildPropagationWatcher.TaskOutcome.unfinished(); + if (task.completed()) { + JsonNode result = + task.response() == null + ? JsonUtils.getObjectNode() + : JsonUtils.readTree(task.response().toJson().toString()); + List failures = new ArrayList<>(); + if (task.error() != null) { + failures.add(task.error().reason()); + } + result.path("failures").forEach(failure -> failures.add(failure.toString())); + if (result.path("timed_out").asBoolean(false)) { + failures.add("updateChildren timed out"); + } + outcome = + new ChildPropagationWatcher.TaskOutcome( + true, failures, result.path("version_conflicts").asLong(0)); + } + return outcome; } /** diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java index 5b69fe527721..da4c6413adb9 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java @@ -47,6 +47,7 @@ import org.openmetadata.sdk.exception.SearchException; import org.openmetadata.search.IndexMapping; import org.openmetadata.service.Entity; +import org.openmetadata.service.search.ChildPropagationWatcher; import org.openmetadata.service.search.ColumnLineageReconciler; import org.openmetadata.service.search.EntityManagementClient; import org.openmetadata.service.search.SearchClient; @@ -87,6 +88,7 @@ import os.org.opensearch.client.opensearch.core.UpdateRequest; import os.org.opensearch.client.opensearch.core.bulk.BulkOperation; import os.org.opensearch.client.opensearch.core.search.Hit; +import os.org.opensearch.client.opensearch.tasks.GetTasksResponse; /** * OpenSearch implementation of entity management operations. @@ -516,8 +518,8 @@ public void updateChildren( updates); LOG.info("Successfully submitted child update in OpenSearch for index: {}", indexName); } catch (IOException | OpenSearchException e) { - SearchIndexRetryQueue.enqueue( - null, fieldAndValue.getValue(), SearchIndexRetryQueue.failureReason("updateChildren", e)); + SearchIndexRetryQueue.enqueueParent( + fieldAndValue.getValue(), SearchIndexRetryQueue.failureReason("updateChildren", e)); LOG.error("Failed to update children in OpenSearch for index: {}", indexName, e); } } @@ -541,7 +543,43 @@ private void submitChildUpdate( Pair fieldAndValue, Pair> updates) throws IOException { - client.updateByQuery(buildUpdateChildrenRequest(indexNames, fieldAndValue, updates)); + UpdateByQueryResponse submitted = + client.updateByQuery(buildUpdateChildrenRequest(indexNames, fieldAndValue, updates)); + ChildPropagationWatcher.watch( + submitted.task(), fieldAndValue.getValue(), this::awaitChildPropagation); + } + + private ChildPropagationWatcher.TaskOutcome awaitChildPropagation(String taskId) + throws IOException { + GetTasksResponse task = + client + .tasks() + .get( + g -> + g.taskId(taskId) + .waitForCompletion(true) + .timeout(t -> t.time(SearchPropagationLimits.CHILD_PROPAGATION_WAIT))); + return childPropagationOutcome(task); + } + + static ChildPropagationWatcher.TaskOutcome childPropagationOutcome(GetTasksResponse task) { + ChildPropagationWatcher.TaskOutcome outcome = ChildPropagationWatcher.TaskOutcome.unfinished(); + if (task.completed()) { + List failures = new ArrayList<>(); + if (task.error() != null) { + failures.add(task.error().reason()); + } + long versionConflicts = 0; + if (task.response() != null) { + task.response().failures().forEach(failure -> failures.add(failure.toString())); + if (task.response().timedOut()) { + failures.add("updateChildren timed out"); + } + versionConflicts = task.response().versionConflicts(); + } + outcome = new ChildPropagationWatcher.TaskOutcome(true, failures, versionConflicts); + } + return outcome; } /** diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTaskTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTaskTest.java index f8230b3bd00a..db99e20c9756 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTaskTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTaskTest.java @@ -21,6 +21,8 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -49,6 +51,7 @@ import org.openmetadata.schema.type.TaskResolutionType; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.governance.approval.ChangeRequestService; import org.openmetadata.service.jdbi3.TaskRepository; import org.openmetadata.service.jdbi3.WorkflowInstanceRepository; @@ -997,6 +1000,35 @@ void testIsSupersedableWhenRequesterMatches() { priorByKaran, workflowDefinitionId, UUID.randomUUID(), "karan")); } + // ---- reviewsStaleRevision ---- + + @Test + void testRunOfAReplacedRevisionReviewsAStaleRevision() { + // Revision 2's run created its task first; revision 1's run finishes last and must not + // supersede it. + DelegateTask delegateTask = changeRequestRun(); + try (MockedStatic requests = mockStatic(ChangeRequestService.class)) { + requests.when(() -> ChangeRequestService.isActiveRevision(any(), eq(1))).thenReturn(false); + + assertTrue(CreateTask.reviewsStaleRevision(delegateTask)); + } + } + + @Test + void testRunOfTheActiveRevisionIsNotStale() { + DelegateTask delegateTask = changeRequestRun(); + try (MockedStatic requests = mockStatic(ChangeRequestService.class)) { + requests.when(() -> ChangeRequestService.isActiveRevision(any(), eq(1))).thenReturn(true); + + assertFalse(CreateTask.reviewsStaleRevision(delegateTask)); + } + } + + @Test + void testRunWithoutAChangeRequestIsNeverStale() { + assertFalse(CreateTask.reviewsStaleRevision(Mockito.mock(DelegateTask.class))); + } + // ---- resolveRequester ---- @Test diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java new file mode 100644 index 000000000000..3d8347c501e8 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java @@ -0,0 +1,78 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.search; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.openmetadata.service.search.ChildPropagationWatcher.TaskOutcome; + +class ChildPropagationWatcherTest { + private static final String PARENT = "8f0c2a8e-1c53-4b3e-9f39-5a3c1b1d2e4f"; + + private final List repaired = new ArrayList<>(); + + @Test + void aFailedPropagationQueuesItsParentWithTheFailure() { + watch(taskId -> new TaskOutcome(true, List.of("es_rejected_execution_exception"), 0)); + + assertEquals(List.of(PARENT + " updateChildren: es_rejected_execution_exception"), repaired); + } + + @Test + void childrenSkippedOnVersionConflictsQueueTheParent() { + watch(taskId -> new TaskOutcome(true, List.of(), 2)); + + assertEquals( + List.of(PARENT + " updateChildren: 2 child document(s) skipped on version conflicts"), + repaired); + } + + @Test + void aCleanPropagationQueuesNothing() { + watch(taskId -> new TaskOutcome(true, List.of(), 0)); + + assertTrue(repaired.isEmpty()); + } + + @Test + void aPropagationStillRunningWhenTheWaitEndsQueuesNothing() { + watch(taskId -> TaskOutcome.unfinished()); + + assertTrue(repaired.isEmpty()); + } + + @Test + void anUnreadableOutcomeQueuesNothing() { + watch( + taskId -> { + throw new IOException("connection reset"); + }); + + assertTrue(repaired.isEmpty()); + } + + private void watch(ChildPropagationWatcher.TaskAwaiter awaiter) { + ChildPropagationWatcher.watch( + "node:1", + PARENT, + awaiter, + Runnable::run, + (parentKey, reason) -> repaired.add(parentKey + " " + reason)); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchIndexRetryQueueTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchIndexRetryQueueTest.java index 710570d61082..ff8522a0f112 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchIndexRetryQueueTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchIndexRetryQueueTest.java @@ -70,6 +70,22 @@ void diagnosticTruncationDoesNotTruncatePropagationContext() { .getNewValue()); } + @Test + void aParentIdIsQueuedInTheIdColumnTheWorkerResolvesById() { + String id = "8f0c2a8e-1c53-4b3e-9f39-5a3c1b1d2e4f"; + + assertEquals( + new SearchIndexRetryQueue.ParentKey(id, null), SearchIndexRetryQueue.ParentKey.of(id)); + } + + @Test + void aParentFqnIsQueuedInTheFqnColumn() { + String fqn = "service.database"; + + assertEquals( + new SearchIndexRetryQueue.ParentKey(null, fqn), SearchIndexRetryQueue.ParentKey.of(fqn)); + } + @Test void plainAndMalformedReasonsAreDistinguished() { assertNull(SearchIndexRetryQueue.getPropagationContext("plain failure")); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/elasticsearch/ElasticSearchChildPropagationOutcomeTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/elasticsearch/ElasticSearchChildPropagationOutcomeTest.java new file mode 100644 index 000000000000..a47a76107b0e --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/elasticsearch/ElasticSearchChildPropagationOutcomeTest.java @@ -0,0 +1,89 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.search.elasticsearch; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import es.co.elastic.clients.elasticsearch.tasks.GetTasksResponse; +import es.co.elastic.clients.json.jackson.JacksonJsonpMapper; +import jakarta.json.stream.JsonParser; +import java.io.StringReader; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.openmetadata.service.search.ChildPropagationWatcher.TaskOutcome; + +class ElasticSearchChildPropagationOutcomeTest { + private static final String TASK = + """ + "task": {"node": "n1", "id": 7, "type": "transport", + "action": "indices:data/write/update/byquery", "start_time_in_millis": 0, + "running_time_in_nanos": 0, "cancellable": true, "headers": {}}"""; + + @Test + void aTaskWithShardFailuresLeftChildrenStale() { + TaskOutcome outcome = + outcomeOf( + """ + {"completed": true, %s, "response": {"updated": 0, "version_conflicts": 0, + "timed_out": false, "failures": [{"index": "table_search_index", + "cause": {"type": "es_rejected_execution_exception", "reason": "rejected"}}]}}""" + .formatted(TASK)); + + assertTrue(outcome.finished()); + assertEquals(1, outcome.failureReasons().size()); + assertTrue(outcome.failureReasons().getFirst().contains("es_rejected_execution_exception")); + } + + @Test + void aTaskThatErroredLeftChildrenStale() { + TaskOutcome outcome = + outcomeOf( + """ + {"completed": true, %s, "error": {"type": "search_phase_execution_exception", + "reason": "Partial shards failure"}}""" + .formatted(TASK)); + + assertEquals(List.of("Partial shards failure"), outcome.failureReasons()); + } + + @Test + void versionConflictsAreCounted() { + TaskOutcome outcome = + outcomeOf( + """ + {"completed": true, %s, "response": {"updated": 3, "version_conflicts": 2, + "timed_out": false, "failures": []}}""" + .formatted(TASK)); + + assertTrue(outcome.failureReasons().isEmpty()); + assertEquals(2, outcome.versionConflicts()); + } + + @Test + void aTaskStillRunningHasNoOutcomeYet() { + TaskOutcome outcome = outcomeOf("{\"completed\": false, %s}".formatted(TASK)); + + assertFalse(outcome.finished()); + } + + private static TaskOutcome outcomeOf(String json) { + JacksonJsonpMapper mapper = new JacksonJsonpMapper(); + try (JsonParser parser = mapper.jsonProvider().createParser(new StringReader(json))) { + return ElasticSearchEntityManager.childPropagationOutcome( + GetTasksResponse._DESERIALIZER.deserialize(parser, mapper)); + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/OpenSearchChildPropagationOutcomeTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/OpenSearchChildPropagationOutcomeTest.java new file mode 100644 index 000000000000..0ef0baf697e2 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/OpenSearchChildPropagationOutcomeTest.java @@ -0,0 +1,79 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openmetadata.service.search.opensearch; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.json.stream.JsonParser; +import java.io.StringReader; +import org.junit.jupiter.api.Test; +import org.openmetadata.service.search.ChildPropagationWatcher.TaskOutcome; +import os.org.opensearch.client.json.jackson.JacksonJsonpMapper; +import os.org.opensearch.client.opensearch.tasks.GetTasksResponse; + +class OpenSearchChildPropagationOutcomeTest { + private static final String TASK = + """ + "task": {"node": "n1", "id": 7, "type": "transport", + "action": "indices:data/write/update/byquery", "start_time_in_millis": 0, + "running_time_in_nanos": 0, "cancellable": true, "headers": {}}"""; + + @Test + void aTaskWithShardFailuresLeftChildrenStale() { + TaskOutcome outcome = + outcomeOf( + response( + "0", + """ + [{"index": "table_search_index", "id": "x", "status": 429, + "cause": {"type": "rejected_execution_exception", "reason": "rejected"}}]""")); + + assertTrue(outcome.finished()); + assertEquals(1, outcome.failureReasons().size()); + } + + @Test + void versionConflictsAreCounted() { + TaskOutcome outcome = outcomeOf(response("2", "[]")); + + assertTrue(outcome.failureReasons().isEmpty()); + assertEquals(2, outcome.versionConflicts()); + } + + @Test + void aTaskStillRunningHasNoOutcomeYet() { + TaskOutcome outcome = outcomeOf("{\"completed\": false, %s}".formatted(TASK)); + + assertFalse(outcome.finished()); + } + + private static String response(String versionConflicts, String failures) { + return """ + {"completed": true, %s, "response": {"took": 5, "timed_out": false, "total": 3, + "updated": 1, "deleted": 0, "batches": 1, "version_conflicts": %s, "noops": 0, + "retries": {"bulk": 0, "search": 0}, "throttled_millis": 0, + "requests_per_second": -1.0, "throttled_until_millis": 0, "failures": %s}}""" + .formatted(TASK, versionConflicts, failures); + } + + private static TaskOutcome outcomeOf(String json) { + JacksonJsonpMapper mapper = new JacksonJsonpMapper(); + try (JsonParser parser = mapper.jsonProvider().createParser(new StringReader(json))) { + return OpenSearchEntityManager.childPropagationOutcome( + GetTasksResponse._DESERIALIZER.deserialize(parser, mapper)); + } + } +} From 3b60cfba2045d3e8bb6618b165ba5bbbb0d2484e Mon Sep 17 00:00:00 2001 From: Ram Narayan Balaji Date: Tue, 3 Nov 2026 20:29:51 +0530 Subject: [PATCH 2/4] Watch only inherited-field propagation, by polling task status; guard the change-request supersede gate - Poll the background task's status every 5s instead of one long-poll the client's socket timeout would cut off, so no search connection is held while a propagation runs. - Watch only propagateToEntityChildren via a new propagateInheritedFields; deletes, renames and reference rewrites stay unwatched, since a parent reindex cannot repair what they rewrite. - Check the stale revision inside the best-effort supersede, with a gate test that fails when the check is removed; rate-limit the unwatched-task warning; real-OpenSearch tests for the task outcome. --- ...-child-propagation-reindexes-its-parent.md | 29 ++-- .../it/tests/mcp/PersonaAIContextIT.java | 2 + .../elements/nodes/userTask/CreateTask.java | 13 +- .../search/ChildPropagationWatcher.java | 150 ++++++++++++------ .../search/EntityManagementClient.java | 14 ++ .../search/SearchPropagationLimits.java | 8 +- .../service/search/SearchRepository.java | 3 +- .../elasticsearch/ElasticSearchClient.java | 9 ++ .../ElasticSearchEntityManager.java | 30 ++-- .../search/opensearch/OpenSearchClient.java | 9 ++ .../opensearch/OpenSearchEntityManager.java | 30 ++-- .../nodes/userTask/CreateTaskTest.java | 39 +++++ .../search/ChildPropagationWatcherTest.java | 71 +++++++-- .../search/SearchRepositoryBehaviorTest.java | 29 ++-- .../UpdateChildrenAsyncPropagationTest.java | 53 +++++++ 15 files changed, 370 insertions(+), 119 deletions(-) diff --git a/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md b/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md index 5998aaf5f15a..20143027a54f 100644 --- a/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md +++ b/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md @@ -3,7 +3,7 @@ - **Status:** Accepted - **Revisions:** v1 2026-11-03 (initial) - **Deciders:** Ram Narayan Balaji -- **Guard:** `ChildPropagationWatcherTest`, `ElasticSearchChildPropagationOutcomeTest`, `OpenSearchChildPropagationOutcomeTest`, `SearchIndexRetryQueueTest` +- **Guard:** `ChildPropagationWatcherTest`, `ElasticSearchChildPropagationOutcomeTest`, `OpenSearchChildPropagationOutcomeTest`, `UpdateChildrenAsyncPropagationTest` (real OpenSearch), `SearchIndexRetryQueueTest` - **Related:** `TableResourceIT.test_ownerPropagationToSearchIndex` merge-queue flake; the async child update introduced for socket timeouts on large child sets ## Context @@ -18,12 +18,18 @@ which the retry worker resolves by name only, so that repair never ran either. ## Decision -- Each submitted child propagation is watched to completion by `ChildPropagationWatcher`, on two - daemon threads with at most 1,000 tasks waiting; past that a task goes unwatched (logged), never - blocking the request path. -- A watcher waits at most `SearchPropagationLimits.CHILD_PROPAGATION_WAIT` (15 minutes, enough for - the million-document service the rate limit is sized for). A task still running then, or whose - outcome cannot be read, is left alone. +- Only inherited-field propagation from a parent to its children is watched: it goes through + `EntityManagementClient.propagateInheritedFields`, called from + `SearchRepository.propagateToEntityChildren`. Every other `updateChildren` caller (deletes, + renames, reference rewrites) stays unwatched, because reindexing the key they match on would not + repair the documents they rewrite. +- `ChildPropagationWatcher` polls the task's status every 5 seconds, a short read each time, so no + search connection is held while it runs (a single long-poll would be cut off by + `socketTimeoutSecs`). One scheduler thread serves all watches; at most 1,000 are watched at once, + and a task past that goes unwatched with a rate-limited warning, never blocking the request path. +- A task is watched for at most `SearchPropagationLimits.CHILD_PROPAGATION_WAIT` (15 minutes, + enough for the million-document service the rate limit is sized for). A task still running then, + or whose status cannot be read, is left alone. - A finished task with failures, a timeout, or any version conflict queues its **parent** in the search retry queue. The worker reindexes the parent and, by cascade, its children from the database, which is correct whatever the propagation script was. @@ -33,8 +39,7 @@ which the retry worker resolves by name only, so that repair never ran either. ## Consequences Search no longer silently keeps a stale inherited field after a failed propagation; it heals -within the retry worker's cycle. The cost is one blocked watcher thread per running propagation -and a cascade reindex (capped by the worker's cascade limit) per failed one. Only parent-to-child -propagation is watched: reference-copy updates match by referenced id, and a parent reindex would -not repair them. Revisit if the retry queue shows conflict-driven requeues dominating under heavy -ingest; then drop version conflicts from the trigger. +within the retry worker's cycle. The cost is one status read per running propagation every 5 +seconds and a cascade reindex (capped by the worker's cascade limit) per failed one. Revisit if +the retry queue shows conflict-driven requeues dominating under heavy ingest; then drop version +conflicts from the trigger. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/PersonaAIContextIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/PersonaAIContextIT.java index 12335904dcc1..31b7e1f2a344 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/PersonaAIContextIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/PersonaAIContextIT.java @@ -720,6 +720,7 @@ private void assertStatusPagesLikeThePersonaList() throws Exception { JsonNode personaPage = OBJECT_MAPPER.readTree(getResponse("personas?limit=1", authToken).body()); assertThat(statusPage.path("data")).hasSize(1); + assertThat(personaPage.path("data")).hasSize(1); assertThat(statusPage.path("data").get(0).path("personaId").asText()) .isEqualTo(personaPage.path("data").get(0).path("id").asText()); assertThat(statusPage.path("paging").path("total").asInt()) @@ -734,6 +735,7 @@ private void assertStatusPagesLikeThePersonaList() throws Exception { JsonNode nextPersona = OBJECT_MAPPER.readTree(getResponse("personas?limit=1&after=" + after, authToken).body()); assertThat(nextStatus.path("data")).hasSize(1); + assertThat(nextPersona.path("data")).hasSize(1); assertThat(nextStatus.path("data").get(0).path("personaId").asText()) .isEqualTo(nextPersona.path("data").get(0).path("id").asText()); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTask.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTask.java index 2038897f2c6e..6a99da226368 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTask.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTask.java @@ -790,7 +790,7 @@ private Task createOrUpdateTask( return task; } - private void supersedePriorApprovalTask( + void supersedePriorApprovalTask( DelegateTask delegateTask, TaskRepository taskRepository, EntityInterface entity, @@ -800,16 +800,19 @@ private void supersedePriorApprovalTask( String updatedBy) { // Best-effort cleanup: failing to supersede a prior task must never abort creation of the new // approval task, so all exceptions are contained here instead of bubbling up as a BpmnError. - if (taskCategory == TaskCategory.Approval && !reviewsStaleRevision(delegateTask)) { + if (taskCategory == TaskCategory.Approval) { try { // A change request's review keeps one live approval per (entity, workflow, requester): a // new held edit supersedes only the same requester's prior review, so other requesters' // reviews survive. Every other run keeps the entity-level supersede (requesterToMatch = // null). String requesterToMatch = reviewsChangeRequest(delegateTask) ? updatedBy : null; - taskRepository - .listNonTerminalTasksByEntityAndCategory(entity.getFullyQualifiedName(), taskCategory) - .stream() + List priors = + reviewsStaleRevision(delegateTask) + ? List.of() + : taskRepository.listNonTerminalTasksByEntityAndCategory( + entity.getFullyQualifiedName(), taskCategory); + priors.stream() .filter( prior -> isSupersedablePriorApprovalTask( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java index bef39b044857..aa9bed94c01c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java @@ -14,11 +14,13 @@ package org.openmetadata.service.search; import java.io.IOException; +import java.time.Duration; import java.util.List; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.Executor; -import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; import lombok.extern.slf4j.Slf4j; @@ -26,29 +28,38 @@ * Inherited fields reach a parent's children through an update-by-query the cluster runs in the * background, after the request that changed the parent has returned. A task that fails under load, * or skips a child on a version conflict, leaves that child stale until the next reindex, and - * nothing would notice. This waits for each task and queues the parent of one that left children - * stale; the retry worker then reindexes the parent and its children from the database. + * nothing would notice. This polls each task until it finishes and queues the parent of one that + * left children stale; the retry worker then reindexes the parent and its children from the + * database (ADR:2026-11-03-a-failed-child-propagation-reindexes-its-parent). + * + *

Each poll is a short status read, so no search connection is held while a task runs. */ @Slf4j public final class ChildPropagationWatcher { - private static final int WATCHER_THREADS = 2; - private static final int MAX_PENDING_TASKS = 1_000; - private static final Executor WATCHERS = - new ThreadPoolExecutor( - WATCHER_THREADS, - WATCHER_THREADS, - 0L, - TimeUnit.MILLISECONDS, - new ArrayBlockingQueue<>(MAX_PENDING_TASKS), - Thread.ofPlatform().name("search-child-propagation-watcher-", 0).daemon().factory(), - (task, executor) -> - LOG.warn( - "{} child propagation tasks are already being watched; not watching another", - MAX_PENDING_TASKS)); - - private ChildPropagationWatcher() {} - - /** What a background update-by-query did, once the cluster says it finished. */ + static final Duration POLL_INTERVAL = Duration.ofSeconds(5); + static final int MAX_WATCHED_TASKS = 1_000; + static final int MAX_POLLS = + (int) + (SearchPropagationLimits.CHILD_PROPAGATION_WAIT.toSeconds() / POLL_INTERVAL.toSeconds()); + private static final ScheduledExecutorService POLLER = + Executors.newSingleThreadScheduledExecutor( + Thread.ofPlatform().name("search-child-propagation-watcher").daemon().factory()); + private static final ChildPropagationWatcher WATCHER = + new ChildPropagationWatcher( + (poll, delay) -> POLLER.schedule(poll, delay.toMillis(), TimeUnit.MILLISECONDS), + SearchIndexRetryQueue::enqueueParent); + + private final Scheduler scheduler; + private final BiConsumer repairParent; + private final AtomicInteger watched = new AtomicInteger(); + private final AtomicLong unwatched = new AtomicLong(); + + ChildPropagationWatcher(Scheduler scheduler, BiConsumer repairParent) { + this.scheduler = scheduler; + this.repairParent = repairParent; + } + + /** What a background update-by-query did; {@code finished} is false while it still runs. */ public record TaskOutcome(boolean finished, List failureReasons, long versionConflicts) { public static TaskOutcome unfinished() { return new TaskOutcome(false, List.of(), 0); @@ -65,52 +76,87 @@ String describe() { } } - /** Blocks until the cluster reports the task finished, or its own wait times out. */ + /** Reads a task's status once, without waiting for it to finish. */ + @FunctionalInterface + public interface TaskPoller { + TaskOutcome poll(String taskId) throws IOException; + } + @FunctionalInterface - public interface TaskAwaiter { - TaskOutcome await(String taskId) throws IOException; + interface Scheduler { + void schedule(Runnable poll, Duration delay); } + private record Watch(String taskId, String parentKey, TaskPoller poller) {} + /** * Watches the task that propagates to the children of {@code parentKey}, the parent id or FQN the * propagation matched children on. */ - public static void watch(String taskId, String parentKey, TaskAwaiter awaiter) { - watch(taskId, parentKey, awaiter, WATCHERS, SearchIndexRetryQueue::enqueueParent); + public static void watch(String taskId, String parentKey, TaskPoller poller) { + WATCHER.watchTask(taskId, parentKey, poller); } - static void watch( - String taskId, - String parentKey, - TaskAwaiter awaiter, - Executor executor, - BiConsumer repairParent) { + void watchTask(String taskId, String parentKey, TaskPoller poller) { if (taskId != null && parentKey != null) { - executor.execute(() -> repairIfStale(taskId, parentKey, awaiter, repairParent)); + if (watched.incrementAndGet() > MAX_WATCHED_TASKS) { + watched.decrementAndGet(); + reportUnwatched(); + } else { + schedulePoll(new Watch(taskId, parentKey, poller), 1); + } } } - private static void repairIfStale( - String taskId, - String parentKey, - TaskAwaiter awaiter, - BiConsumer repairParent) { + private void schedulePoll(Watch watch, int attempt) { + scheduler.schedule(() -> poll(watch, attempt), POLL_INTERVAL); + } + + private void poll(Watch watch, int attempt) { + TaskOutcome outcome = readOutcome(watch); + if (outcome.finished() || attempt >= MAX_POLLS) { + watched.decrementAndGet(); + repairIfStale(watch, outcome); + } else { + schedulePoll(watch, attempt + 1); + } + } + + // An unreadable status ends the watch: it reads as finished, with nothing known to repair. + private TaskOutcome readOutcome(Watch watch) { + TaskOutcome outcome; try { - TaskOutcome outcome = awaiter.await(taskId); - if (outcome.leftChildrenStale()) { - LOG.warn( - "Child propagation task {} for parent {} left children stale ({}); reindexing them", - taskId, - parentKey, - outcome.describe()); - repairParent.accept(parentKey, "updateChildren: %s".formatted(outcome.describe())); - } + outcome = watch.poller().poll(watch.taskId()); } catch (IOException | RuntimeException e) { LOG.warn( - "Could not learn how child propagation task {} for parent {} ended: {}", - taskId, - parentKey, + "Could not read child propagation task {} for parent {}: {}", + watch.taskId(), + watch.parentKey(), e.getMessage()); + outcome = new TaskOutcome(true, List.of(), 0); + } + return outcome; + } + + private void repairIfStale(Watch watch, TaskOutcome outcome) { + if (outcome.leftChildrenStale()) { + LOG.warn( + "Child propagation task {} for parent {} left children stale ({}); reindexing them", + watch.taskId(), + watch.parentKey(), + outcome.describe()); + repairParent.accept(watch.parentKey(), "updateChildren: %s".formatted(outcome.describe())); + } + } + + // Logged on the first and every thousandth miss, so a burst of propagations cannot flood the log. + private void reportUnwatched() { + long misses = unwatched.incrementAndGet(); + if (misses == 1 || misses % MAX_WATCHED_TASKS == 0) { + LOG.warn( + "{} child propagation task(s) went unwatched: {} were already being watched", + misses, + MAX_WATCHED_TASKS); } } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityManagementClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityManagementClient.java index ec42684fbe3f..5b9ccad82c09 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityManagementClient.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityManagementClient.java @@ -140,6 +140,20 @@ void updateChildren( Pair> updates) throws IOException; + /** + * Same as {@link #updateChildren(List, Pair, Pair)}, for an inherited-field propagation from the + * parent {@code parentMatch} names. An engine that runs it in the background reindexes that + * parent when the task fails or skips a child + * (ADR:2026-11-03-a-failed-child-propagation-reindexes-its-parent). + */ + default void propagateInheritedFields( + List indexNames, + Pair parentMatch, + Pair> updates) + throws IOException { + updateChildren(indexNames, parentMatch, updates); + } + /** * Updates child entities whose {@code field} matches ANY of {@code values} with a script across * multiple indices, in a single update-by-query. Lets a caller fan a change out to the children of diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchPropagationLimits.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchPropagationLimits.java index b6be213d78bc..bead79d4e014 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchPropagationLimits.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchPropagationLimits.java @@ -13,6 +13,8 @@ package org.openmetadata.service.search; +import java.time.Duration; + /** Bounds shared by the ElasticSearch and OpenSearch inherited-field child propagations. */ public final class SearchPropagationLimits { @@ -30,8 +32,8 @@ private SearchPropagationLimits() {} public static final float REQUESTS_PER_SECOND = 2000f; /** - * How long a watcher waits for a child propagation to finish before giving up on learning its - * outcome. Covers the million-document service above with room to spare. + * How long a child propagation is watched before its outcome is given up on. Covers the + * million-document service above with room to spare. */ - public static final String CHILD_PROPAGATION_WAIT = "15m"; + public static final Duration CHILD_PROPAGATION_WAIT = Duration.ofMinutes(15); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java index 16849456f497..e9af97a08b05 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java @@ -3019,7 +3019,8 @@ private void propagateToEntityChildren( entityType, descriptor -> !view.skippedFields().contains(descriptor.fieldName())); if (!nullOrEmpty(updates.getKey())) { - searchClient.updateChildren(withClusterAlias(group.getValue()), parentMatch, updates); + searchClient.propagateInheritedFields( + withClusterAlias(group.getValue()), parentMatch, updates); } } Pair> updates = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchClient.java index e09a6e84ef29..b31b62456f7d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchClient.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchClient.java @@ -803,6 +803,15 @@ public void updateChildren( entityManager.updateChildren(indexName, fieldAndValue, updates); } + @Override + public void propagateInheritedFields( + List indexNames, + Pair parentMatch, + Pair> updates) + throws IOException { + entityManager.propagateInheritedFields(indexNames, parentMatch, updates); + } + @Override public void updateChildren( List indexNames, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java index 56437bb9f2b0..06c2ad104148 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java @@ -513,23 +513,29 @@ private void submitChildUpdate( Pair fieldAndValue, Pair> updates) throws IOException { + client.updateByQuery(buildUpdateChildrenRequest(indexNames, fieldAndValue, updates)); + } + + @Override + public void propagateInheritedFields( + List indexNames, + Pair parentMatch, + Pair> updates) + throws IOException { + if (!isClientAvailable) { + LOG.error("ElasticSearch client is not available. Cannot propagate inherited fields."); + return; + } UpdateByQueryResponse submitted = - client.updateByQuery(buildUpdateChildrenRequest(indexNames, fieldAndValue, updates)); + client.updateByQuery(buildUpdateChildrenRequest(indexNames, parentMatch, updates)); ChildPropagationWatcher.watch( - submitted.task(), fieldAndValue.getValue(), this::awaitChildPropagation); + submitted.task(), parentMatch.getValue(), this::readChildPropagation); + LOG.info("Submitted inherited-field propagation in ElasticSearch for indices: {}", indexNames); } - private ChildPropagationWatcher.TaskOutcome awaitChildPropagation(String taskId) + private ChildPropagationWatcher.TaskOutcome readChildPropagation(String taskId) throws IOException { - GetTasksResponse task = - client - .tasks() - .get( - g -> - g.taskId(taskId) - .waitForCompletion(true) - .timeout(t -> t.time(SearchPropagationLimits.CHILD_PROPAGATION_WAIT))); - return childPropagationOutcome(task); + return childPropagationOutcome(client.tasks().get(g -> g.taskId(taskId))); } static ChildPropagationWatcher.TaskOutcome childPropagationOutcome(GetTasksResponse task) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchClient.java index b8ab20c82c72..06527b049f41 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchClient.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchClient.java @@ -772,6 +772,15 @@ public void updateChildren( entityManager.updateChildren(indexName, fieldAndValue, updates); } + @Override + public void propagateInheritedFields( + List indexNames, + Pair parentMatch, + Pair> updates) + throws IOException { + entityManager.propagateInheritedFields(indexNames, parentMatch, updates); + } + @Override public void updateChildren( List indexNames, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java index da4c6413adb9..714f2c73ddaf 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java @@ -543,23 +543,29 @@ private void submitChildUpdate( Pair fieldAndValue, Pair> updates) throws IOException { + client.updateByQuery(buildUpdateChildrenRequest(indexNames, fieldAndValue, updates)); + } + + @Override + public void propagateInheritedFields( + List indexNames, + Pair parentMatch, + Pair> updates) + throws IOException { + if (!isClientAvailable) { + LOG.error("OpenSearch client is not available. Cannot propagate inherited fields."); + return; + } UpdateByQueryResponse submitted = - client.updateByQuery(buildUpdateChildrenRequest(indexNames, fieldAndValue, updates)); + client.updateByQuery(buildUpdateChildrenRequest(indexNames, parentMatch, updates)); ChildPropagationWatcher.watch( - submitted.task(), fieldAndValue.getValue(), this::awaitChildPropagation); + submitted.task(), parentMatch.getValue(), this::readChildPropagation); + LOG.info("Submitted inherited-field propagation in OpenSearch for indices: {}", indexNames); } - private ChildPropagationWatcher.TaskOutcome awaitChildPropagation(String taskId) + private ChildPropagationWatcher.TaskOutcome readChildPropagation(String taskId) throws IOException { - GetTasksResponse task = - client - .tasks() - .get( - g -> - g.taskId(taskId) - .waitForCompletion(true) - .timeout(t -> t.time(SearchPropagationLimits.CHILD_PROPAGATION_WAIT))); - return childPropagationOutcome(task); + return childPropagationOutcome(client.tasks().get(g -> g.taskId(taskId))); } static ChildPropagationWatcher.TaskOutcome childPropagationOutcome(GetTasksResponse task) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTaskTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTaskTest.java index db99e20c9756..661b6b5e4ffc 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTaskTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/governance/workflows/elements/nodes/userTask/CreateTaskTest.java @@ -24,6 +24,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -45,6 +46,7 @@ import org.openmetadata.schema.type.DataAccessRequestPayload; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.TaskCategory; import org.openmetadata.schema.type.TaskEntityStatus; import org.openmetadata.schema.type.TaskEntityType; import org.openmetadata.schema.type.TaskResolution; @@ -1024,6 +1026,43 @@ void testRunOfTheActiveRevisionIsNotStale() { } } + @Test + void testRunOfAReplacedRevisionLeavesTheLiveReviewAlone() { + TaskRepository taskRepository = Mockito.mock(TaskRepository.class); + try (MockedStatic requests = mockStatic(ChangeRequestService.class)) { + requests.when(() -> ChangeRequestService.isActiveRevision(any(), eq(1))).thenReturn(false); + + supersedeFor(changeRequestRun(), taskRepository); + } + + verify(taskRepository, never()).listNonTerminalTasksByEntityAndCategory(any(), any()); + } + + @Test + void testRunOfTheActiveRevisionSupersedesTheRequestersPriorReview() { + TaskRepository taskRepository = Mockito.mock(TaskRepository.class); + try (MockedStatic requests = mockStatic(ChangeRequestService.class)) { + requests.when(() -> ChangeRequestService.isActiveRevision(any(), eq(1))).thenReturn(true); + + supersedeFor(changeRequestRun(), taskRepository); + } + + verify(taskRepository) + .listNonTerminalTasksByEntityAndCategory("glossary", TaskCategory.Approval); + } + + private static void supersedeFor(DelegateTask delegateTask, TaskRepository taskRepository) { + new CreateTask() + .supersedePriorApprovalTask( + delegateTask, + taskRepository, + new Glossary().withFullyQualifiedName("glossary"), + TaskCategory.Approval, + UUID.randomUUID(), + UUID.randomUUID(), + "karan"); + } + @Test void testRunWithoutAChangeRequestIsNeverStale() { assertFalse(CreateTask.reviewsStaleRevision(Mockito.mock(DelegateTask.class))); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java index 3d8347c501e8..bdc129aa96e8 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java @@ -17,20 +17,30 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; +import java.util.Queue; import org.junit.jupiter.api.Test; import org.openmetadata.service.search.ChildPropagationWatcher.TaskOutcome; class ChildPropagationWatcherTest { private static final String PARENT = "8f0c2a8e-1c53-4b3e-9f39-5a3c1b1d2e4f"; + private static final TaskOutcome CLEAN = new TaskOutcome(true, List.of(), 0); + private final Queue pendingPolls = new ArrayDeque<>(); private final List repaired = new ArrayList<>(); + private final ChildPropagationWatcher watcher = + new ChildPropagationWatcher( + (poll, delay) -> pendingPolls.add(poll), + (parentKey, reason) -> repaired.add("%s %s".formatted(parentKey, reason))); @Test void aFailedPropagationQueuesItsParentWithTheFailure() { watch(taskId -> new TaskOutcome(true, List.of("es_rejected_execution_exception"), 0)); + runPolls(); + assertEquals(List.of(PARENT + " updateChildren: es_rejected_execution_exception"), repaired); } @@ -38,41 +48,78 @@ void aFailedPropagationQueuesItsParentWithTheFailure() { void childrenSkippedOnVersionConflictsQueueTheParent() { watch(taskId -> new TaskOutcome(true, List.of(), 2)); + runPolls(); + assertEquals( List.of(PARENT + " updateChildren: 2 child document(s) skipped on version conflicts"), repaired); } @Test - void aCleanPropagationQueuesNothing() { - watch(taskId -> new TaskOutcome(true, List.of(), 0)); + void aRunningTaskIsPolledAgainUntilItFinishes() { + List outcomes = + new ArrayList<>( + List.of( + TaskOutcome.unfinished(), + TaskOutcome.unfinished(), + new TaskOutcome(true, List.of("partial shards failure"), 0))); + watch(taskId -> outcomes.removeFirst()); + + int polls = runPolls(); + + assertEquals(3, polls); + assertEquals(List.of(PARENT + " updateChildren: partial shards failure"), repaired); + } + @Test + void aTaskStillRunningAtTheDeadlineIsLeftAlone() { + watch(taskId -> TaskOutcome.unfinished()); + + int polls = runPolls(); + + assertEquals(ChildPropagationWatcher.MAX_POLLS, polls); assertTrue(repaired.isEmpty()); } @Test - void aPropagationStillRunningWhenTheWaitEndsQueuesNothing() { - watch(taskId -> TaskOutcome.unfinished()); + void aCleanPropagationQueuesNothing() { + watch(taskId -> CLEAN); + + runPolls(); assertTrue(repaired.isEmpty()); } @Test - void anUnreadableOutcomeQueuesNothing() { + void anUnreadableStatusEndsTheWatchWithoutARepair() { watch( taskId -> { throw new IOException("connection reset"); }); + assertEquals(1, runPolls()); assertTrue(repaired.isEmpty()); } - private void watch(ChildPropagationWatcher.TaskAwaiter awaiter) { - ChildPropagationWatcher.watch( - "node:1", - PARENT, - awaiter, - Runnable::run, - (parentKey, reason) -> repaired.add(parentKey + " " + reason)); + @Test + void tasksPastTheWatchLimitAreNotWatched() { + for (int i = 0; i <= ChildPropagationWatcher.MAX_WATCHED_TASKS; i++) { + watch(taskId -> CLEAN); + } + + assertEquals(ChildPropagationWatcher.MAX_WATCHED_TASKS, pendingPolls.size()); + } + + private void watch(ChildPropagationWatcher.TaskPoller poller) { + watcher.watchTask("node:1", PARENT, poller); + } + + private int runPolls() { + int polls = 0; + while (!pendingPolls.isEmpty()) { + pendingPolls.poll().run(); + polls++; + } + return polls; } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java index b88d5ce09a04..fc6d371fed82 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java @@ -986,7 +986,7 @@ void propagateInheritedFieldsToChildrenUsesServiceParentFieldForServiceDisplayNa ArgumentCaptor>> updateCaptor = ArgumentCaptor.forClass(Pair.class); verify(searchClient) - .updateChildren( + .propagateInheritedFields( eq(List.of("cluster_database")), fieldCaptor.capture(), updateCaptor.capture()); assertEquals("service.id", fieldCaptor.getValue().getLeft()); assertEquals("service-id", fieldCaptor.getValue().getRight()); @@ -1108,7 +1108,8 @@ void propagateInheritedFieldsToChildrenRoutesTagsIntoEmbeddedTimeSeriesTestCase( table); verify(searchClient) - .updateChildren(eq(List.of("cluster_tableColumn")), any(Pair.class), any(Pair.class)); + .propagateInheritedFields( + eq(List.of("cluster_tableColumn")), any(Pair.class), any(Pair.class)); ArgumentCaptor> parentMatchCaptor = ArgumentCaptor.forClass(Pair.class); ArgumentCaptor>> updatesCaptor = ArgumentCaptor.forClass(Pair.class); @@ -1197,7 +1198,7 @@ void tableTagOnlyChangeLeavesColumnDocsToTheTagCascade() throws Exception { ArgumentCaptor>> tagUpdateCaptor = ArgumentCaptor.forClass(Pair.class); verify(searchClient) - .updateChildren( + .propagateInheritedFields( eq(List.of("cluster_tableColumn")), eq(new ImmutablePair<>("table.id", tableId.toString())), tagUpdateCaptor.capture()); @@ -1305,6 +1306,8 @@ void retryPropagationDropsTagDeltaThatNoLongerMatchesTheParent() throws IOExcept repository.propagateEntityAfterRetry(table, staleDelta); verify(searchClient, never()).updateChildren(any(List.class), any(Pair.class), any(Pair.class)); + verify(searchClient, never()) + .propagateInheritedFields(any(List.class), any(Pair.class), any(Pair.class)); } @Test @@ -1344,7 +1347,7 @@ void retryPropagationKeepsOnlyTagDeltaConsistentWithTheParent() throws IOExcepti ArgumentCaptor>> updatesCaptor = ArgumentCaptor.forClass(Pair.class); verify(searchClient) - .updateChildren( + .propagateInheritedFields( eq(List.of("cluster_tableColumn")), any(Pair.class), updatesCaptor.capture()); Map params = updatesCaptor.getValue().getValue(); assertEquals( @@ -1388,7 +1391,8 @@ void propagateInheritedFieldsToChildrenOnlyTargetsNonTimeSeriesChildren() throws ArgumentCaptor>> updatesCaptor = ArgumentCaptor.forClass(Pair.class); verify(searchClient) - .updateChildren(targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); + .propagateInheritedFields( + targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); assertEquals(List.of("cluster_tableColumn"), targetsCaptor.getValue()); String entityChildScript = updatesCaptor.getValue().getLeft(); @@ -1434,7 +1438,8 @@ void propagateInheritedFieldsToChildrenKeepsTableClassificationTagsOffColumnEntr ArgumentCaptor>> updatesCaptor = ArgumentCaptor.forClass(Pair.class); verify(searchClient, times(2)) - .updateChildren(targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); + .propagateInheritedFields( + targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); Map, Map> paramsByTargets = new HashMap<>(); for (int i = 0; i < targetsCaptor.getAllValues().size(); i++) { paramsByTargets.put( @@ -1486,7 +1491,8 @@ void propagateInheritedFieldsToChildrenSendsColumnEntriesOnlyTheTermsTheyInherit ArgumentCaptor>> updatesCaptor = ArgumentCaptor.forClass(Pair.class); verify(searchClient, times(2)) - .updateChildren(targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); + .propagateInheritedFields( + targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); Map, List> addedByTargets = new HashMap<>(); for (int i = 0; i < targetsCaptor.getAllValues().size(); i++) { addedByTargets.put( @@ -1531,7 +1537,8 @@ void propagateInheritedFieldsToChildrenIncludesUnregisteredChildAliases() throws @SuppressWarnings("unchecked") ArgumentCaptor> targetsCaptor = ArgumentCaptor.forClass(List.class); - verify(searchClient).updateChildren(targetsCaptor.capture(), any(Pair.class), any(Pair.class)); + verify(searchClient) + .propagateInheritedFields(targetsCaptor.capture(), any(Pair.class), any(Pair.class)); assertEquals( List.of("cluster_unregisteredChild", "cluster_tableColumn"), targetsCaptor.getValue()); @@ -4069,7 +4076,8 @@ void bulkTimeoutCompletedDuringClosePropagatesWithoutReplayOrRetry() throws Exce propagationOrder.verify(bulkSink).close(); propagationOrder .verify(searchClient) - .updateChildren(eq(List.of("cluster_database")), any(Pair.class), any(Pair.class)); + .propagateInheritedFields( + eq(List.of("cluster_database")), any(Pair.class), any(Pair.class)); verify(searchClient, never()) .updateEntity(any(String.class), eq(serviceId), any(), any(String.class)); retryQueue.verifyNoInteractions(); @@ -4213,7 +4221,8 @@ void partiallyFailedBulkPropagatesOnlyConfirmedRoots() throws Exception { repository.updateEntitiesIndex(List.of(failedService, successfulService)); ArgumentCaptor> parentMatch = ArgumentCaptor.forClass(Pair.class); - verify(searchClient).updateChildren(any(List.class), parentMatch.capture(), any(Pair.class)); + verify(searchClient) + .propagateInheritedFields(any(List.class), parentMatch.capture(), any(Pair.class)); assertEquals(successfulService.getId().toString(), parentMatch.getValue().getValue()); verify(bulkSinks.constructed().getFirst()).close(); retryQueue.verify( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/UpdateChildrenAsyncPropagationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/UpdateChildrenAsyncPropagationTest.java index b23ca4bb0c68..158e9b98328b 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/UpdateChildrenAsyncPropagationTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/UpdateChildrenAsyncPropagationTest.java @@ -12,7 +12,10 @@ */ package org.openmetadata.service.search.opensearch; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.time.Duration; @@ -26,6 +29,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.openmetadata.schema.service.configuration.elasticsearch.ElasticSearchConfiguration; +import org.openmetadata.service.search.ChildPropagationWatcher; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.wait.strategy.Wait; @@ -142,6 +146,55 @@ void updateChildrenSubmitsAsyncTaskAndPropagates() throws Exception { .count() == CHILD_COUNT); + String taskId = response.task(); + ChildPropagationWatcher.TaskOutcome outcome = + Awaitility.await() + .atMost(60, TimeUnit.SECONDS) + .pollInterval(Duration.ofMillis(500)) + .until( + () -> + OpenSearchEntityManager.childPropagationOutcome( + lowLevel.tasks().get(g -> g.taskId(taskId))), + ChildPropagationWatcher.TaskOutcome::finished); + assertTrue(outcome.failureReasons().isEmpty(), "a clean propagation reports no failures"); + assertEquals(0, outcome.versionConflicts()); + + lowLevel.indices().delete(d -> d.index(index)); + } + + @Test + void aPropagationWhoseScriptFailsIsReportedAsLeavingChildrenStale() throws Exception { + var lowLevel = osClient.getNewClient(); + String index = "repro_children_failing"; + String parentId = UUID.randomUUID().toString(); + lowLevel.index( + idx -> + idx.index(index) + .id("0") + .document(Map.of("name", "child-0", "entityType", Map.of("id", parentId)))); + lowLevel.indices().refresh(r -> r.index(index)); + UpdateByQueryRequest request = + new OpenSearchEntityManager(lowLevel) + .buildUpdateChildrenRequest( + List.of(index), + Pair.of("entityType.id", parentId), + Pair.of("ctx._source.owners = params.missing.size();", Map.of())); + + String taskId = lowLevel.updateByQuery(request).task(); + ChildPropagationWatcher.TaskOutcome outcome = + Awaitility.await() + .atMost(60, TimeUnit.SECONDS) + .pollInterval(Duration.ofMillis(500)) + .until( + () -> + OpenSearchEntityManager.childPropagationOutcome( + lowLevel.tasks().get(g -> g.taskId(taskId))), + ChildPropagationWatcher.TaskOutcome::finished); + + assertFalse( + outcome.failureReasons().isEmpty(), + "a task the cluster failed must be reported, so its parent is reindexed"); + lowLevel.indices().delete(d -> d.index(index)); } } From 66150f734108f43e953bd01457a1d90cf5a43e22 Mon Sep 17 00:00:00 2001 From: Ram Narayan Balaji Date: Tue, 3 Nov 2026 20:47:12 +0530 Subject: [PATCH 3/4] Leave column documents and delete-path child updates unwatched; keep polling through a failed status read - tableColumn documents are built from their table and the retry worker's reindex does not rebuild them, so their propagation goes out unwatched; every other child group stays watched. - Restore the original retry-queue entry for a failed single-index updateChildren, which delete and reference rewrites use, so a failed repair is not reported as completed. - A status read that fails is retried on the next poll; a task still running at the deadline is logged. Share the active-revision check between attachTask and isActiveRevision. --- ...-child-propagation-reindexes-its-parent.md | 12 +++++---- .../approval/ChangeRequestService.java | 12 ++++----- .../search/ChildPropagationWatcher.java | 16 ++++++++--- .../service/search/SearchRepository.java | 21 +++++++++++++-- .../ElasticSearchEntityManager.java | 4 +-- .../opensearch/OpenSearchEntityManager.java | 4 +-- .../search/ChildPropagationWatcherTest.java | 12 ++++++--- .../search/SearchRepositoryBehaviorTest.java | 27 ++++++++++--------- 8 files changed, 71 insertions(+), 37 deletions(-) diff --git a/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md b/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md index 20143027a54f..18f32e8cf6f8 100644 --- a/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md +++ b/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md @@ -22,14 +22,15 @@ which the retry worker resolves by name only, so that repair never ran either. `EntityManagementClient.propagateInheritedFields`, called from `SearchRepository.propagateToEntityChildren`. Every other `updateChildren` caller (deletes, renames, reference rewrites) stays unwatched, because reindexing the key they match on would not - repair the documents they rewrite. + repair the documents they rewrite. Column documents (`tableColumn`) are unwatched too: they are + built from their table, and the retry worker's reindex does not rebuild them. - `ChildPropagationWatcher` polls the task's status every 5 seconds, a short read each time, so no search connection is held while it runs (a single long-poll would be cut off by `socketTimeoutSecs`). One scheduler thread serves all watches; at most 1,000 are watched at once, and a task past that goes unwatched with a rate-limited warning, never blocking the request path. - A task is watched for at most `SearchPropagationLimits.CHILD_PROPAGATION_WAIT` (15 minutes, - enough for the million-document service the rate limit is sized for). A task still running then, - or whose status cannot be read, is left alone. + enough for the million-document service the rate limit is sized for). A status read that fails is + retried on the next poll; a task still running at the deadline is logged and left alone. - A finished task with failures, a timeout, or any version conflict queues its **parent** in the search retry queue. The worker reindexes the parent and, by cascade, its children from the database, which is correct whatever the propagation script was. @@ -38,8 +39,9 @@ which the retry worker resolves by name only, so that repair never ran either. ## Consequences -Search no longer silently keeps a stale inherited field after a failed propagation; it heals -within the retry worker's cycle. The cost is one status read per running propagation every 5 +A failed propagation no longer leaves a parent's children stale until the next full reindex; they +heal within the retry worker's cycle. The repair is bounded by the worker's cascade limit (5,000 +entities), so a larger parent, such as a whole service, is repaired only in part. The cost is one status read per running propagation every 5 seconds and a cascade reindex (capped by the worker's cascade limit) per failed one. Revisit if the retry queue shows conflict-driven requeues dominating under heavy ingest; then drop version conflicts from the trigger. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ChangeRequestService.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ChangeRequestService.java index adb6c72d1161..4e146bf9b6dc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ChangeRequestService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ChangeRequestService.java @@ -237,9 +237,7 @@ public static boolean attachTask( repository.executeInTransaction( () -> { ChangeRequest locked = lockForUpdate(repository, snapshot); - boolean current = - isOpen(locked) - && Objects.equals(locked.getActiveRevisionNumber(), revisionNumber); + boolean current = reviewsActiveRevision(locked, revisionNumber); if (current) { dao() .changeRequestDAO() @@ -254,9 +252,11 @@ public static boolean attachTask( /** Whether {@code revisionNumber} is still the active revision of an open request. */ public static boolean isActiveRevision(UUID changeRequestId, int revisionNumber) { ChangeRequest request = dao().changeRequestDAO().findById(changeRequestId); - return request != null - && isOpen(request) - && Objects.equals(request.getActiveRevisionNumber(), revisionNumber); + return request != null && reviewsActiveRevision(request, revisionNumber); + } + + static boolean reviewsActiveRevision(ChangeRequest request, int revisionNumber) { + return isOpen(request) && Objects.equals(request.getActiveRevisionNumber(), revisionNumber); } /** diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java index aa9bed94c01c..e96c4771c77a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java @@ -114,26 +114,34 @@ private void schedulePoll(Watch watch, int attempt) { private void poll(Watch watch, int attempt) { TaskOutcome outcome = readOutcome(watch); - if (outcome.finished() || attempt >= MAX_POLLS) { + if (outcome.finished()) { watched.decrementAndGet(); repairIfStale(watch, outcome); + } else if (attempt >= MAX_POLLS) { + watched.decrementAndGet(); + LOG.warn( + "Child propagation task {} for parent {} did not finish within {}; its outcome is unknown", + watch.taskId(), + watch.parentKey(), + SearchPropagationLimits.CHILD_PROPAGATION_WAIT); } else { schedulePoll(watch, attempt + 1); } } - // An unreadable status ends the watch: it reads as finished, with nothing known to repair. + // The cluster this watches for is often the one under load, so a status read that fails is + // tried again on the next poll rather than taken as the task's outcome. private TaskOutcome readOutcome(Watch watch) { TaskOutcome outcome; try { outcome = watch.poller().poll(watch.taskId()); } catch (IOException | RuntimeException e) { - LOG.warn( + LOG.debug( "Could not read child propagation task {} for parent {}: {}", watch.taskId(), watch.parentKey(), e.getMessage()); - outcome = new TaskOutcome(true, List.of(), 0); + outcome = TaskOutcome.unfinished(); } return outcome; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java index e9af97a08b05..f68b952211b9 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java @@ -3019,8 +3019,7 @@ private void propagateToEntityChildren( entityType, descriptor -> !view.skippedFields().contains(descriptor.fieldName())); if (!nullOrEmpty(updates.getKey())) { - searchClient.propagateInheritedFields( - withClusterAlias(group.getValue()), parentMatch, updates); + propagateToChildAliases(group.getValue(), parentMatch, updates); } } Pair> updates = @@ -3031,6 +3030,24 @@ private void propagateToEntityChildren( } /** How one child index takes a change: the fields it skips, and the tag lists it narrows. */ + // Column documents are built from their table, and the reindex a failed propagation queues does + // not rebuild them, so they are updated unwatched; every other child is rebuilt by that reindex. + private void propagateToChildAliases( + List aliases, + Pair parentMatch, + Pair> updates) + throws IOException { + Map> byColumnIndex = + aliases.stream().collect(Collectors.partitioningBy(Entity.TABLE_COLUMN::equals)); + if (!byColumnIndex.get(false).isEmpty()) { + searchClient.propagateInheritedFields( + withClusterAlias(byColumnIndex.get(false)), parentMatch, updates); + } + if (!byColumnIndex.get(true).isEmpty()) { + searchClient.updateChildren(withClusterAlias(byColumnIndex.get(true)), parentMatch, updates); + } + } + private record ChildView(Set skippedFields, Set inheritedTermsOnlyFields) {} // The entity's non-time-series child aliases, grouped by how they take the propagated fields. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java index 06c2ad104148..1b73d14daf6c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java @@ -488,8 +488,8 @@ public void updateChildren( updates); LOG.info("Successfully submitted child update in ElasticSearch for index: {}", indexName); } catch (IOException | ElasticsearchException e) { - SearchIndexRetryQueue.enqueueParent( - fieldAndValue.getValue(), SearchIndexRetryQueue.failureReason("updateChildren", e)); + SearchIndexRetryQueue.enqueue( + null, fieldAndValue.getValue(), SearchIndexRetryQueue.failureReason("updateChildren", e)); LOG.error("Failed to update children in ElasticSearch for index: {}", indexName, e); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java index 714f2c73ddaf..a0f4f408ce3e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java @@ -518,8 +518,8 @@ public void updateChildren( updates); LOG.info("Successfully submitted child update in OpenSearch for index: {}", indexName); } catch (IOException | OpenSearchException e) { - SearchIndexRetryQueue.enqueueParent( - fieldAndValue.getValue(), SearchIndexRetryQueue.failureReason("updateChildren", e)); + SearchIndexRetryQueue.enqueue( + null, fieldAndValue.getValue(), SearchIndexRetryQueue.failureReason("updateChildren", e)); LOG.error("Failed to update children in OpenSearch for index: {}", indexName, e); } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java index bdc129aa96e8..65689cf76da4 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java @@ -91,14 +91,18 @@ void aCleanPropagationQueuesNothing() { } @Test - void anUnreadableStatusEndsTheWatchWithoutARepair() { + void anUnreadableStatusIsReadAgainOnTheNextPoll() { + List readFails = new ArrayList<>(List.of(true, false)); watch( taskId -> { - throw new IOException("connection reset"); + if (readFails.removeFirst()) { + throw new IOException("429 Too Many Requests"); + } + return new TaskOutcome(true, List.of("partial shards failure"), 0); }); - assertEquals(1, runPolls()); - assertTrue(repaired.isEmpty()); + assertEquals(2, runPolls()); + assertEquals(List.of(PARENT + " updateChildren: partial shards failure"), repaired); } @Test diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java index fc6d371fed82..6dde4dcb9bb8 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java @@ -25,7 +25,6 @@ import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -1108,8 +1107,7 @@ void propagateInheritedFieldsToChildrenRoutesTagsIntoEmbeddedTimeSeriesTestCase( table); verify(searchClient) - .propagateInheritedFields( - eq(List.of("cluster_tableColumn")), any(Pair.class), any(Pair.class)); + .updateChildren(eq(List.of("cluster_tableColumn")), any(Pair.class), any(Pair.class)); ArgumentCaptor> parentMatchCaptor = ArgumentCaptor.forClass(Pair.class); ArgumentCaptor>> updatesCaptor = ArgumentCaptor.forClass(Pair.class); @@ -1198,7 +1196,7 @@ void tableTagOnlyChangeLeavesColumnDocsToTheTagCascade() throws Exception { ArgumentCaptor>> tagUpdateCaptor = ArgumentCaptor.forClass(Pair.class); verify(searchClient) - .propagateInheritedFields( + .updateChildren( eq(List.of("cluster_tableColumn")), eq(new ImmutablePair<>("table.id", tableId.toString())), tagUpdateCaptor.capture()); @@ -1347,7 +1345,7 @@ void retryPropagationKeepsOnlyTagDeltaConsistentWithTheParent() throws IOExcepti ArgumentCaptor>> updatesCaptor = ArgumentCaptor.forClass(Pair.class); verify(searchClient) - .propagateInheritedFields( + .updateChildren( eq(List.of("cluster_tableColumn")), any(Pair.class), updatesCaptor.capture()); Map params = updatesCaptor.getValue().getValue(); assertEquals( @@ -1391,8 +1389,7 @@ void propagateInheritedFieldsToChildrenOnlyTargetsNonTimeSeriesChildren() throws ArgumentCaptor>> updatesCaptor = ArgumentCaptor.forClass(Pair.class); verify(searchClient) - .propagateInheritedFields( - targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); + .updateChildren(targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); assertEquals(List.of("cluster_tableColumn"), targetsCaptor.getValue()); String entityChildScript = updatesCaptor.getValue().getLeft(); @@ -1437,9 +1434,11 @@ void propagateInheritedFieldsToChildrenKeepsTableClassificationTagsOffColumnEntr @SuppressWarnings("unchecked") ArgumentCaptor>> updatesCaptor = ArgumentCaptor.forClass(Pair.class); - verify(searchClient, times(2)) + verify(searchClient) .propagateInheritedFields( targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); + verify(searchClient) + .updateChildren(targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); Map, Map> paramsByTargets = new HashMap<>(); for (int i = 0; i < targetsCaptor.getAllValues().size(); i++) { paramsByTargets.put( @@ -1490,9 +1489,11 @@ void propagateInheritedFieldsToChildrenSendsColumnEntriesOnlyTheTermsTheyInherit ArgumentCaptor> targetsCaptor = ArgumentCaptor.forClass(List.class); ArgumentCaptor>> updatesCaptor = ArgumentCaptor.forClass(Pair.class); - verify(searchClient, times(2)) + verify(searchClient) .propagateInheritedFields( targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); + verify(searchClient) + .updateChildren(targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); Map, List> addedByTargets = new HashMap<>(); for (int i = 0; i < targetsCaptor.getAllValues().size(); i++) { addedByTargets.put( @@ -1539,9 +1540,11 @@ void propagateInheritedFieldsToChildrenIncludesUnregisteredChildAliases() throws ArgumentCaptor> targetsCaptor = ArgumentCaptor.forClass(List.class); verify(searchClient) .propagateInheritedFields(targetsCaptor.capture(), any(Pair.class), any(Pair.class)); - - assertEquals( - List.of("cluster_unregisteredChild", "cluster_tableColumn"), targetsCaptor.getValue()); + assertEquals(List.of("cluster_unregisteredChild"), targetsCaptor.getValue()); + // Column documents are built from their table, so a parent reindex cannot repair them; they + // are updated unwatched. + verify(searchClient) + .updateChildren(eq(List.of("cluster_tableColumn")), any(Pair.class), any(Pair.class)); } @Test From f58d60d867d09d0f5ac932bd16e09963297e02e7 Mon Sep 17 00:00:00 2001 From: Ram Narayan Balaji Date: Tue, 3 Nov 2026 21:23:30 +0530 Subject: [PATCH 4/4] Remove the child propagation watcher The owner-propagation flake's cause is not yet reproduced, and a failed background propagation should reuse the search retry queue's propagation replay rather than a new repair path. It will be handled in its own change once reproduced. --- ...-child-propagation-reindexes-its-parent.md | 47 ----- .../search/ChildPropagationWatcher.java | 170 ------------------ .../search/EntityManagementClient.java | 14 -- .../service/search/SearchIndexRetryQueue.java | 17 -- .../search/SearchPropagationLimits.java | 8 - .../service/search/SearchRepository.java | 20 +-- .../elasticsearch/ElasticSearchClient.java | 9 - .../ElasticSearchEntityManager.java | 47 ----- .../search/opensearch/OpenSearchClient.java | 9 - .../opensearch/OpenSearchEntityManager.java | 44 ----- .../search/ChildPropagationWatcherTest.java | 129 ------------- .../search/SearchIndexRetryQueueTest.java | 16 -- .../search/SearchRepositoryBehaviorTest.java | 32 ++-- ...sticSearchChildPropagationOutcomeTest.java | 89 --------- ...OpenSearchChildPropagationOutcomeTest.java | 79 -------- .../UpdateChildrenAsyncPropagationTest.java | 53 ------ 16 files changed, 11 insertions(+), 772 deletions(-) delete mode 100644 docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md delete mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java delete mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java delete mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/search/elasticsearch/ElasticSearchChildPropagationOutcomeTest.java delete mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/OpenSearchChildPropagationOutcomeTest.java diff --git a/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md b/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md deleted file mode 100644 index 18f32e8cf6f8..000000000000 --- a/docs/decisions/2026-11-03-a-failed-child-propagation-reindexes-its-parent.md +++ /dev/null @@ -1,47 +0,0 @@ -# A background child propagation that leaves children stale reindexes its parent - -- **Status:** Accepted -- **Revisions:** v1 2026-11-03 (initial) -- **Deciders:** Ram Narayan Balaji -- **Guard:** `ChildPropagationWatcherTest`, `ElasticSearchChildPropagationOutcomeTest`, `OpenSearchChildPropagationOutcomeTest`, `UpdateChildrenAsyncPropagationTest` (real OpenSearch), `SearchIndexRetryQueueTest` -- **Related:** `TableResourceIT.test_ownerPropagationToSearchIndex` merge-queue flake; the async child update introduced for socket timeouts on large child sets - -## Context - -Inherited fields (owners, domains, tags, ...) reach a parent's children in search through an -update-by-query submitted with `wait_for_completion=false`, so a large child set cannot trip the -client socket timeout. The cluster then runs the task after the request has returned, and nothing -read its result. Under load (`429`s, partial shard failures) or a concurrent write -(`conflicts=proceed` skips the child), children stayed stale until the next full reindex. The -fallback for a submit that failed outright queued the parent's id in the retry queue's FQN column, -which the retry worker resolves by name only, so that repair never ran either. - -## Decision - -- Only inherited-field propagation from a parent to its children is watched: it goes through - `EntityManagementClient.propagateInheritedFields`, called from - `SearchRepository.propagateToEntityChildren`. Every other `updateChildren` caller (deletes, - renames, reference rewrites) stays unwatched, because reindexing the key they match on would not - repair the documents they rewrite. Column documents (`tableColumn`) are unwatched too: they are - built from their table, and the retry worker's reindex does not rebuild them. -- `ChildPropagationWatcher` polls the task's status every 5 seconds, a short read each time, so no - search connection is held while it runs (a single long-poll would be cut off by - `socketTimeoutSecs`). One scheduler thread serves all watches; at most 1,000 are watched at once, - and a task past that goes unwatched with a rate-limited warning, never blocking the request path. -- A task is watched for at most `SearchPropagationLimits.CHILD_PROPAGATION_WAIT` (15 minutes, - enough for the million-document service the rate limit is sized for). A status read that fails is - retried on the next poll; a task still running at the deadline is logged and left alone. -- A finished task with failures, a timeout, or any version conflict queues its **parent** in the - search retry queue. The worker reindexes the parent and, by cascade, its children from the - database, which is correct whatever the propagation script was. -- A parent key is queued by id when it is a UUID and by FQN otherwise - (`SearchIndexRetryQueue.enqueueParent`). - -## Consequences - -A failed propagation no longer leaves a parent's children stale until the next full reindex; they -heal within the retry worker's cycle. The repair is bounded by the worker's cascade limit (5,000 -entities), so a larger parent, such as a whole service, is repaired only in part. The cost is one status read per running propagation every 5 -seconds and a cascade reindex (capped by the worker's cascade limit) per failed one. Revisit if -the retry queue shows conflict-driven requeues dominating under heavy ingest; then drop version -conflicts from the trigger. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java deleted file mode 100644 index e96c4771c77a..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/ChildPropagationWatcher.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright 2026 Collate - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.search; - -import java.io.IOException; -import java.time.Duration; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.BiConsumer; -import lombok.extern.slf4j.Slf4j; - -/** - * Inherited fields reach a parent's children through an update-by-query the cluster runs in the - * background, after the request that changed the parent has returned. A task that fails under load, - * or skips a child on a version conflict, leaves that child stale until the next reindex, and - * nothing would notice. This polls each task until it finishes and queues the parent of one that - * left children stale; the retry worker then reindexes the parent and its children from the - * database (ADR:2026-11-03-a-failed-child-propagation-reindexes-its-parent). - * - *

Each poll is a short status read, so no search connection is held while a task runs. - */ -@Slf4j -public final class ChildPropagationWatcher { - static final Duration POLL_INTERVAL = Duration.ofSeconds(5); - static final int MAX_WATCHED_TASKS = 1_000; - static final int MAX_POLLS = - (int) - (SearchPropagationLimits.CHILD_PROPAGATION_WAIT.toSeconds() / POLL_INTERVAL.toSeconds()); - private static final ScheduledExecutorService POLLER = - Executors.newSingleThreadScheduledExecutor( - Thread.ofPlatform().name("search-child-propagation-watcher").daemon().factory()); - private static final ChildPropagationWatcher WATCHER = - new ChildPropagationWatcher( - (poll, delay) -> POLLER.schedule(poll, delay.toMillis(), TimeUnit.MILLISECONDS), - SearchIndexRetryQueue::enqueueParent); - - private final Scheduler scheduler; - private final BiConsumer repairParent; - private final AtomicInteger watched = new AtomicInteger(); - private final AtomicLong unwatched = new AtomicLong(); - - ChildPropagationWatcher(Scheduler scheduler, BiConsumer repairParent) { - this.scheduler = scheduler; - this.repairParent = repairParent; - } - - /** What a background update-by-query did; {@code finished} is false while it still runs. */ - public record TaskOutcome(boolean finished, List failureReasons, long versionConflicts) { - public static TaskOutcome unfinished() { - return new TaskOutcome(false, List.of(), 0); - } - - boolean leftChildrenStale() { - return finished && (!failureReasons.isEmpty() || versionConflicts > 0); - } - - String describe() { - return failureReasons.isEmpty() - ? "%d child document(s) skipped on version conflicts".formatted(versionConflicts) - : String.join("; ", failureReasons); - } - } - - /** Reads a task's status once, without waiting for it to finish. */ - @FunctionalInterface - public interface TaskPoller { - TaskOutcome poll(String taskId) throws IOException; - } - - @FunctionalInterface - interface Scheduler { - void schedule(Runnable poll, Duration delay); - } - - private record Watch(String taskId, String parentKey, TaskPoller poller) {} - - /** - * Watches the task that propagates to the children of {@code parentKey}, the parent id or FQN the - * propagation matched children on. - */ - public static void watch(String taskId, String parentKey, TaskPoller poller) { - WATCHER.watchTask(taskId, parentKey, poller); - } - - void watchTask(String taskId, String parentKey, TaskPoller poller) { - if (taskId != null && parentKey != null) { - if (watched.incrementAndGet() > MAX_WATCHED_TASKS) { - watched.decrementAndGet(); - reportUnwatched(); - } else { - schedulePoll(new Watch(taskId, parentKey, poller), 1); - } - } - } - - private void schedulePoll(Watch watch, int attempt) { - scheduler.schedule(() -> poll(watch, attempt), POLL_INTERVAL); - } - - private void poll(Watch watch, int attempt) { - TaskOutcome outcome = readOutcome(watch); - if (outcome.finished()) { - watched.decrementAndGet(); - repairIfStale(watch, outcome); - } else if (attempt >= MAX_POLLS) { - watched.decrementAndGet(); - LOG.warn( - "Child propagation task {} for parent {} did not finish within {}; its outcome is unknown", - watch.taskId(), - watch.parentKey(), - SearchPropagationLimits.CHILD_PROPAGATION_WAIT); - } else { - schedulePoll(watch, attempt + 1); - } - } - - // The cluster this watches for is often the one under load, so a status read that fails is - // tried again on the next poll rather than taken as the task's outcome. - private TaskOutcome readOutcome(Watch watch) { - TaskOutcome outcome; - try { - outcome = watch.poller().poll(watch.taskId()); - } catch (IOException | RuntimeException e) { - LOG.debug( - "Could not read child propagation task {} for parent {}: {}", - watch.taskId(), - watch.parentKey(), - e.getMessage()); - outcome = TaskOutcome.unfinished(); - } - return outcome; - } - - private void repairIfStale(Watch watch, TaskOutcome outcome) { - if (outcome.leftChildrenStale()) { - LOG.warn( - "Child propagation task {} for parent {} left children stale ({}); reindexing them", - watch.taskId(), - watch.parentKey(), - outcome.describe()); - repairParent.accept(watch.parentKey(), "updateChildren: %s".formatted(outcome.describe())); - } - } - - // Logged on the first and every thousandth miss, so a burst of propagations cannot flood the log. - private void reportUnwatched() { - long misses = unwatched.incrementAndGet(); - if (misses == 1 || misses % MAX_WATCHED_TASKS == 0) { - LOG.warn( - "{} child propagation task(s) went unwatched: {} were already being watched", - misses, - MAX_WATCHED_TASKS); - } - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityManagementClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityManagementClient.java index 5b9ccad82c09..ec42684fbe3f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityManagementClient.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/EntityManagementClient.java @@ -140,20 +140,6 @@ void updateChildren( Pair> updates) throws IOException; - /** - * Same as {@link #updateChildren(List, Pair, Pair)}, for an inherited-field propagation from the - * parent {@code parentMatch} names. An engine that runs it in the background reindexes that - * parent when the task fails or skips a child - * (ADR:2026-11-03-a-failed-child-propagation-reindexes-its-parent). - */ - default void propagateInheritedFields( - List indexNames, - Pair parentMatch, - Pair> updates) - throws IOException { - updateChildren(indexNames, parentMatch, updates); - } - /** * Updates child entities whose {@code field} matches ANY of {@code values} with a script across * multiple indices, in a single update-by-query. Lets a caller fan a change out to the children of diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryQueue.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryQueue.java index 8cfa17ff3247..4be63e33fa81 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryQueue.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryQueue.java @@ -71,23 +71,6 @@ public static void enqueue(String entityId, String entityFqn, String failureReas enqueue(entityId, entityFqn, "", failureReason); } - /** - * Queues the parent a child propagation matched its children on, so the retry worker reindexes - * the parent and its children. Propagations match on a parent id or FQN; the worker resolves the - * FQN column by name only, so an id queued there would never resolve. - */ - public static void enqueueParent(String parentKey, String failureReason) { - ParentKey key = ParentKey.of(parentKey); - enqueue(key.entityId(), key.entityFqn(), failureReason); - } - - /** A child propagation's parent key, split into the queue column the retry worker reads it from. */ - record ParentKey(String entityId, String entityFqn) { - static ParentKey of(String parentKey) { - return isUuid(parentKey) ? new ParentKey(parentKey, null) : new ParentKey(null, parentKey); - } - } - public static void enqueue( String entityId, String entityFqn, String entityType, String failureReason) { String normalizedEntityId = normalize(entityId); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchPropagationLimits.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchPropagationLimits.java index bead79d4e014..ff14bbdc6723 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchPropagationLimits.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchPropagationLimits.java @@ -13,8 +13,6 @@ package org.openmetadata.service.search; -import java.time.Duration; - /** Bounds shared by the ElasticSearch and OpenSearch inherited-field child propagations. */ public final class SearchPropagationLimits { @@ -30,10 +28,4 @@ private SearchPropagationLimits() {} * completion time for cluster stability is the right way round. */ public static final float REQUESTS_PER_SECOND = 2000f; - - /** - * How long a child propagation is watched before its outcome is given up on. Covers the - * million-document service above with room to spare. - */ - public static final Duration CHILD_PROPAGATION_WAIT = Duration.ofMinutes(15); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java index f68b952211b9..16849456f497 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java @@ -3019,7 +3019,7 @@ private void propagateToEntityChildren( entityType, descriptor -> !view.skippedFields().contains(descriptor.fieldName())); if (!nullOrEmpty(updates.getKey())) { - propagateToChildAliases(group.getValue(), parentMatch, updates); + searchClient.updateChildren(withClusterAlias(group.getValue()), parentMatch, updates); } } Pair> updates = @@ -3030,24 +3030,6 @@ private void propagateToEntityChildren( } /** How one child index takes a change: the fields it skips, and the tag lists it narrows. */ - // Column documents are built from their table, and the reindex a failed propagation queues does - // not rebuild them, so they are updated unwatched; every other child is rebuilt by that reindex. - private void propagateToChildAliases( - List aliases, - Pair parentMatch, - Pair> updates) - throws IOException { - Map> byColumnIndex = - aliases.stream().collect(Collectors.partitioningBy(Entity.TABLE_COLUMN::equals)); - if (!byColumnIndex.get(false).isEmpty()) { - searchClient.propagateInheritedFields( - withClusterAlias(byColumnIndex.get(false)), parentMatch, updates); - } - if (!byColumnIndex.get(true).isEmpty()) { - searchClient.updateChildren(withClusterAlias(byColumnIndex.get(true)), parentMatch, updates); - } - } - private record ChildView(Set skippedFields, Set inheritedTermsOnlyFields) {} // The entity's non-time-series child aliases, grouped by how they take the propagated fields. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchClient.java index b31b62456f7d..e09a6e84ef29 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchClient.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchClient.java @@ -803,15 +803,6 @@ public void updateChildren( entityManager.updateChildren(indexName, fieldAndValue, updates); } - @Override - public void propagateInheritedFields( - List indexNames, - Pair parentMatch, - Pair> updates) - throws IOException { - entityManager.propagateInheritedFields(indexNames, parentMatch, updates); - } - @Override public void updateChildren( List indexNames, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java index 1b73d14daf6c..4d5d9be61738 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/elasticsearch/ElasticSearchEntityManager.java @@ -14,7 +14,6 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import es.co.elastic.clients.elasticsearch.ElasticsearchAsyncClient; import es.co.elastic.clients.elasticsearch.ElasticsearchClient; @@ -40,7 +39,6 @@ import es.co.elastic.clients.elasticsearch.core.UpdateRequest; import es.co.elastic.clients.elasticsearch.core.bulk.BulkOperation; import es.co.elastic.clients.elasticsearch.core.search.Hit; -import es.co.elastic.clients.elasticsearch.tasks.GetTasksResponse; import es.co.elastic.clients.json.JsonData; import jakarta.ws.rs.core.Response; import java.io.IOException; @@ -73,7 +71,6 @@ import org.openmetadata.sdk.exception.SearchException; import org.openmetadata.search.IndexMapping; import org.openmetadata.service.Entity; -import org.openmetadata.service.search.ChildPropagationWatcher; import org.openmetadata.service.search.ColumnLineageReconciler; import org.openmetadata.service.search.EntityManagementClient; import org.openmetadata.service.search.SearchClient; @@ -516,50 +513,6 @@ private void submitChildUpdate( client.updateByQuery(buildUpdateChildrenRequest(indexNames, fieldAndValue, updates)); } - @Override - public void propagateInheritedFields( - List indexNames, - Pair parentMatch, - Pair> updates) - throws IOException { - if (!isClientAvailable) { - LOG.error("ElasticSearch client is not available. Cannot propagate inherited fields."); - return; - } - UpdateByQueryResponse submitted = - client.updateByQuery(buildUpdateChildrenRequest(indexNames, parentMatch, updates)); - ChildPropagationWatcher.watch( - submitted.task(), parentMatch.getValue(), this::readChildPropagation); - LOG.info("Submitted inherited-field propagation in ElasticSearch for indices: {}", indexNames); - } - - private ChildPropagationWatcher.TaskOutcome readChildPropagation(String taskId) - throws IOException { - return childPropagationOutcome(client.tasks().get(g -> g.taskId(taskId))); - } - - static ChildPropagationWatcher.TaskOutcome childPropagationOutcome(GetTasksResponse task) { - ChildPropagationWatcher.TaskOutcome outcome = ChildPropagationWatcher.TaskOutcome.unfinished(); - if (task.completed()) { - JsonNode result = - task.response() == null - ? JsonUtils.getObjectNode() - : JsonUtils.readTree(task.response().toJson().toString()); - List failures = new ArrayList<>(); - if (task.error() != null) { - failures.add(task.error().reason()); - } - result.path("failures").forEach(failure -> failures.add(failure.toString())); - if (result.path("timed_out").asBoolean(false)) { - failures.add("updateChildren timed out"); - } - outcome = - new ChildPropagationWatcher.TaskOutcome( - true, failures, result.path("version_conflicts").asLong(0)); - } - return outcome; - } - /** * Builds the inherited-field child propagation as an async update-by-query * ({@code wait_for_completion=false}). A synchronous update-by-query over a large child set (for diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchClient.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchClient.java index 06527b049f41..b8ab20c82c72 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchClient.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchClient.java @@ -772,15 +772,6 @@ public void updateChildren( entityManager.updateChildren(indexName, fieldAndValue, updates); } - @Override - public void propagateInheritedFields( - List indexNames, - Pair parentMatch, - Pair> updates) - throws IOException { - entityManager.propagateInheritedFields(indexNames, parentMatch, updates); - } - @Override public void updateChildren( List indexNames, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java index a0f4f408ce3e..5b69fe527721 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/opensearch/OpenSearchEntityManager.java @@ -47,7 +47,6 @@ import org.openmetadata.sdk.exception.SearchException; import org.openmetadata.search.IndexMapping; import org.openmetadata.service.Entity; -import org.openmetadata.service.search.ChildPropagationWatcher; import org.openmetadata.service.search.ColumnLineageReconciler; import org.openmetadata.service.search.EntityManagementClient; import org.openmetadata.service.search.SearchClient; @@ -88,7 +87,6 @@ import os.org.opensearch.client.opensearch.core.UpdateRequest; import os.org.opensearch.client.opensearch.core.bulk.BulkOperation; import os.org.opensearch.client.opensearch.core.search.Hit; -import os.org.opensearch.client.opensearch.tasks.GetTasksResponse; /** * OpenSearch implementation of entity management operations. @@ -546,48 +544,6 @@ private void submitChildUpdate( client.updateByQuery(buildUpdateChildrenRequest(indexNames, fieldAndValue, updates)); } - @Override - public void propagateInheritedFields( - List indexNames, - Pair parentMatch, - Pair> updates) - throws IOException { - if (!isClientAvailable) { - LOG.error("OpenSearch client is not available. Cannot propagate inherited fields."); - return; - } - UpdateByQueryResponse submitted = - client.updateByQuery(buildUpdateChildrenRequest(indexNames, parentMatch, updates)); - ChildPropagationWatcher.watch( - submitted.task(), parentMatch.getValue(), this::readChildPropagation); - LOG.info("Submitted inherited-field propagation in OpenSearch for indices: {}", indexNames); - } - - private ChildPropagationWatcher.TaskOutcome readChildPropagation(String taskId) - throws IOException { - return childPropagationOutcome(client.tasks().get(g -> g.taskId(taskId))); - } - - static ChildPropagationWatcher.TaskOutcome childPropagationOutcome(GetTasksResponse task) { - ChildPropagationWatcher.TaskOutcome outcome = ChildPropagationWatcher.TaskOutcome.unfinished(); - if (task.completed()) { - List failures = new ArrayList<>(); - if (task.error() != null) { - failures.add(task.error().reason()); - } - long versionConflicts = 0; - if (task.response() != null) { - task.response().failures().forEach(failure -> failures.add(failure.toString())); - if (task.response().timedOut()) { - failures.add("updateChildren timed out"); - } - versionConflicts = task.response().versionConflicts(); - } - outcome = new ChildPropagationWatcher.TaskOutcome(true, failures, versionConflicts); - } - return outcome; - } - /** * Builds the inherited-field child propagation as an async update-by-query * ({@code wait_for_completion=false}). A synchronous update-by-query over a large child set (for diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java deleted file mode 100644 index 65689cf76da4..000000000000 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/ChildPropagationWatcherTest.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2026 Collate - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.search; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.List; -import java.util.Queue; -import org.junit.jupiter.api.Test; -import org.openmetadata.service.search.ChildPropagationWatcher.TaskOutcome; - -class ChildPropagationWatcherTest { - private static final String PARENT = "8f0c2a8e-1c53-4b3e-9f39-5a3c1b1d2e4f"; - private static final TaskOutcome CLEAN = new TaskOutcome(true, List.of(), 0); - - private final Queue pendingPolls = new ArrayDeque<>(); - private final List repaired = new ArrayList<>(); - private final ChildPropagationWatcher watcher = - new ChildPropagationWatcher( - (poll, delay) -> pendingPolls.add(poll), - (parentKey, reason) -> repaired.add("%s %s".formatted(parentKey, reason))); - - @Test - void aFailedPropagationQueuesItsParentWithTheFailure() { - watch(taskId -> new TaskOutcome(true, List.of("es_rejected_execution_exception"), 0)); - - runPolls(); - - assertEquals(List.of(PARENT + " updateChildren: es_rejected_execution_exception"), repaired); - } - - @Test - void childrenSkippedOnVersionConflictsQueueTheParent() { - watch(taskId -> new TaskOutcome(true, List.of(), 2)); - - runPolls(); - - assertEquals( - List.of(PARENT + " updateChildren: 2 child document(s) skipped on version conflicts"), - repaired); - } - - @Test - void aRunningTaskIsPolledAgainUntilItFinishes() { - List outcomes = - new ArrayList<>( - List.of( - TaskOutcome.unfinished(), - TaskOutcome.unfinished(), - new TaskOutcome(true, List.of("partial shards failure"), 0))); - watch(taskId -> outcomes.removeFirst()); - - int polls = runPolls(); - - assertEquals(3, polls); - assertEquals(List.of(PARENT + " updateChildren: partial shards failure"), repaired); - } - - @Test - void aTaskStillRunningAtTheDeadlineIsLeftAlone() { - watch(taskId -> TaskOutcome.unfinished()); - - int polls = runPolls(); - - assertEquals(ChildPropagationWatcher.MAX_POLLS, polls); - assertTrue(repaired.isEmpty()); - } - - @Test - void aCleanPropagationQueuesNothing() { - watch(taskId -> CLEAN); - - runPolls(); - - assertTrue(repaired.isEmpty()); - } - - @Test - void anUnreadableStatusIsReadAgainOnTheNextPoll() { - List readFails = new ArrayList<>(List.of(true, false)); - watch( - taskId -> { - if (readFails.removeFirst()) { - throw new IOException("429 Too Many Requests"); - } - return new TaskOutcome(true, List.of("partial shards failure"), 0); - }); - - assertEquals(2, runPolls()); - assertEquals(List.of(PARENT + " updateChildren: partial shards failure"), repaired); - } - - @Test - void tasksPastTheWatchLimitAreNotWatched() { - for (int i = 0; i <= ChildPropagationWatcher.MAX_WATCHED_TASKS; i++) { - watch(taskId -> CLEAN); - } - - assertEquals(ChildPropagationWatcher.MAX_WATCHED_TASKS, pendingPolls.size()); - } - - private void watch(ChildPropagationWatcher.TaskPoller poller) { - watcher.watchTask("node:1", PARENT, poller); - } - - private int runPolls() { - int polls = 0; - while (!pendingPolls.isEmpty()) { - pendingPolls.poll().run(); - polls++; - } - return polls; - } -} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchIndexRetryQueueTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchIndexRetryQueueTest.java index ff8522a0f112..710570d61082 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchIndexRetryQueueTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchIndexRetryQueueTest.java @@ -70,22 +70,6 @@ void diagnosticTruncationDoesNotTruncatePropagationContext() { .getNewValue()); } - @Test - void aParentIdIsQueuedInTheIdColumnTheWorkerResolvesById() { - String id = "8f0c2a8e-1c53-4b3e-9f39-5a3c1b1d2e4f"; - - assertEquals( - new SearchIndexRetryQueue.ParentKey(id, null), SearchIndexRetryQueue.ParentKey.of(id)); - } - - @Test - void aParentFqnIsQueuedInTheFqnColumn() { - String fqn = "service.database"; - - assertEquals( - new SearchIndexRetryQueue.ParentKey(null, fqn), SearchIndexRetryQueue.ParentKey.of(fqn)); - } - @Test void plainAndMalformedReasonsAreDistinguished() { assertNull(SearchIndexRetryQueue.getPropagationContext("plain failure")); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java index 6dde4dcb9bb8..b88d5ce09a04 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java @@ -25,6 +25,7 @@ import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -985,7 +986,7 @@ void propagateInheritedFieldsToChildrenUsesServiceParentFieldForServiceDisplayNa ArgumentCaptor>> updateCaptor = ArgumentCaptor.forClass(Pair.class); verify(searchClient) - .propagateInheritedFields( + .updateChildren( eq(List.of("cluster_database")), fieldCaptor.capture(), updateCaptor.capture()); assertEquals("service.id", fieldCaptor.getValue().getLeft()); assertEquals("service-id", fieldCaptor.getValue().getRight()); @@ -1304,8 +1305,6 @@ void retryPropagationDropsTagDeltaThatNoLongerMatchesTheParent() throws IOExcept repository.propagateEntityAfterRetry(table, staleDelta); verify(searchClient, never()).updateChildren(any(List.class), any(Pair.class), any(Pair.class)); - verify(searchClient, never()) - .propagateInheritedFields(any(List.class), any(Pair.class), any(Pair.class)); } @Test @@ -1434,10 +1433,7 @@ void propagateInheritedFieldsToChildrenKeepsTableClassificationTagsOffColumnEntr @SuppressWarnings("unchecked") ArgumentCaptor>> updatesCaptor = ArgumentCaptor.forClass(Pair.class); - verify(searchClient) - .propagateInheritedFields( - targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); - verify(searchClient) + verify(searchClient, times(2)) .updateChildren(targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); Map, Map> paramsByTargets = new HashMap<>(); for (int i = 0; i < targetsCaptor.getAllValues().size(); i++) { @@ -1489,10 +1485,7 @@ void propagateInheritedFieldsToChildrenSendsColumnEntriesOnlyTheTermsTheyInherit ArgumentCaptor> targetsCaptor = ArgumentCaptor.forClass(List.class); ArgumentCaptor>> updatesCaptor = ArgumentCaptor.forClass(Pair.class); - verify(searchClient) - .propagateInheritedFields( - targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); - verify(searchClient) + verify(searchClient, times(2)) .updateChildren(targetsCaptor.capture(), any(Pair.class), updatesCaptor.capture()); Map, List> addedByTargets = new HashMap<>(); for (int i = 0; i < targetsCaptor.getAllValues().size(); i++) { @@ -1538,13 +1531,10 @@ void propagateInheritedFieldsToChildrenIncludesUnregisteredChildAliases() throws @SuppressWarnings("unchecked") ArgumentCaptor> targetsCaptor = ArgumentCaptor.forClass(List.class); - verify(searchClient) - .propagateInheritedFields(targetsCaptor.capture(), any(Pair.class), any(Pair.class)); - assertEquals(List.of("cluster_unregisteredChild"), targetsCaptor.getValue()); - // Column documents are built from their table, so a parent reindex cannot repair them; they - // are updated unwatched. - verify(searchClient) - .updateChildren(eq(List.of("cluster_tableColumn")), any(Pair.class), any(Pair.class)); + verify(searchClient).updateChildren(targetsCaptor.capture(), any(Pair.class), any(Pair.class)); + + assertEquals( + List.of("cluster_unregisteredChild", "cluster_tableColumn"), targetsCaptor.getValue()); } @Test @@ -4079,8 +4069,7 @@ void bulkTimeoutCompletedDuringClosePropagatesWithoutReplayOrRetry() throws Exce propagationOrder.verify(bulkSink).close(); propagationOrder .verify(searchClient) - .propagateInheritedFields( - eq(List.of("cluster_database")), any(Pair.class), any(Pair.class)); + .updateChildren(eq(List.of("cluster_database")), any(Pair.class), any(Pair.class)); verify(searchClient, never()) .updateEntity(any(String.class), eq(serviceId), any(), any(String.class)); retryQueue.verifyNoInteractions(); @@ -4224,8 +4213,7 @@ void partiallyFailedBulkPropagatesOnlyConfirmedRoots() throws Exception { repository.updateEntitiesIndex(List.of(failedService, successfulService)); ArgumentCaptor> parentMatch = ArgumentCaptor.forClass(Pair.class); - verify(searchClient) - .propagateInheritedFields(any(List.class), parentMatch.capture(), any(Pair.class)); + verify(searchClient).updateChildren(any(List.class), parentMatch.capture(), any(Pair.class)); assertEquals(successfulService.getId().toString(), parentMatch.getValue().getValue()); verify(bulkSinks.constructed().getFirst()).close(); retryQueue.verify( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/elasticsearch/ElasticSearchChildPropagationOutcomeTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/elasticsearch/ElasticSearchChildPropagationOutcomeTest.java deleted file mode 100644 index a47a76107b0e..000000000000 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/elasticsearch/ElasticSearchChildPropagationOutcomeTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2026 Collate - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.search.elasticsearch; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import es.co.elastic.clients.elasticsearch.tasks.GetTasksResponse; -import es.co.elastic.clients.json.jackson.JacksonJsonpMapper; -import jakarta.json.stream.JsonParser; -import java.io.StringReader; -import java.util.List; -import org.junit.jupiter.api.Test; -import org.openmetadata.service.search.ChildPropagationWatcher.TaskOutcome; - -class ElasticSearchChildPropagationOutcomeTest { - private static final String TASK = - """ - "task": {"node": "n1", "id": 7, "type": "transport", - "action": "indices:data/write/update/byquery", "start_time_in_millis": 0, - "running_time_in_nanos": 0, "cancellable": true, "headers": {}}"""; - - @Test - void aTaskWithShardFailuresLeftChildrenStale() { - TaskOutcome outcome = - outcomeOf( - """ - {"completed": true, %s, "response": {"updated": 0, "version_conflicts": 0, - "timed_out": false, "failures": [{"index": "table_search_index", - "cause": {"type": "es_rejected_execution_exception", "reason": "rejected"}}]}}""" - .formatted(TASK)); - - assertTrue(outcome.finished()); - assertEquals(1, outcome.failureReasons().size()); - assertTrue(outcome.failureReasons().getFirst().contains("es_rejected_execution_exception")); - } - - @Test - void aTaskThatErroredLeftChildrenStale() { - TaskOutcome outcome = - outcomeOf( - """ - {"completed": true, %s, "error": {"type": "search_phase_execution_exception", - "reason": "Partial shards failure"}}""" - .formatted(TASK)); - - assertEquals(List.of("Partial shards failure"), outcome.failureReasons()); - } - - @Test - void versionConflictsAreCounted() { - TaskOutcome outcome = - outcomeOf( - """ - {"completed": true, %s, "response": {"updated": 3, "version_conflicts": 2, - "timed_out": false, "failures": []}}""" - .formatted(TASK)); - - assertTrue(outcome.failureReasons().isEmpty()); - assertEquals(2, outcome.versionConflicts()); - } - - @Test - void aTaskStillRunningHasNoOutcomeYet() { - TaskOutcome outcome = outcomeOf("{\"completed\": false, %s}".formatted(TASK)); - - assertFalse(outcome.finished()); - } - - private static TaskOutcome outcomeOf(String json) { - JacksonJsonpMapper mapper = new JacksonJsonpMapper(); - try (JsonParser parser = mapper.jsonProvider().createParser(new StringReader(json))) { - return ElasticSearchEntityManager.childPropagationOutcome( - GetTasksResponse._DESERIALIZER.deserialize(parser, mapper)); - } - } -} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/OpenSearchChildPropagationOutcomeTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/OpenSearchChildPropagationOutcomeTest.java deleted file mode 100644 index 0ef0baf697e2..000000000000 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/OpenSearchChildPropagationOutcomeTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2026 Collate - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openmetadata.service.search.opensearch; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import jakarta.json.stream.JsonParser; -import java.io.StringReader; -import org.junit.jupiter.api.Test; -import org.openmetadata.service.search.ChildPropagationWatcher.TaskOutcome; -import os.org.opensearch.client.json.jackson.JacksonJsonpMapper; -import os.org.opensearch.client.opensearch.tasks.GetTasksResponse; - -class OpenSearchChildPropagationOutcomeTest { - private static final String TASK = - """ - "task": {"node": "n1", "id": 7, "type": "transport", - "action": "indices:data/write/update/byquery", "start_time_in_millis": 0, - "running_time_in_nanos": 0, "cancellable": true, "headers": {}}"""; - - @Test - void aTaskWithShardFailuresLeftChildrenStale() { - TaskOutcome outcome = - outcomeOf( - response( - "0", - """ - [{"index": "table_search_index", "id": "x", "status": 429, - "cause": {"type": "rejected_execution_exception", "reason": "rejected"}}]""")); - - assertTrue(outcome.finished()); - assertEquals(1, outcome.failureReasons().size()); - } - - @Test - void versionConflictsAreCounted() { - TaskOutcome outcome = outcomeOf(response("2", "[]")); - - assertTrue(outcome.failureReasons().isEmpty()); - assertEquals(2, outcome.versionConflicts()); - } - - @Test - void aTaskStillRunningHasNoOutcomeYet() { - TaskOutcome outcome = outcomeOf("{\"completed\": false, %s}".formatted(TASK)); - - assertFalse(outcome.finished()); - } - - private static String response(String versionConflicts, String failures) { - return """ - {"completed": true, %s, "response": {"took": 5, "timed_out": false, "total": 3, - "updated": 1, "deleted": 0, "batches": 1, "version_conflicts": %s, "noops": 0, - "retries": {"bulk": 0, "search": 0}, "throttled_millis": 0, - "requests_per_second": -1.0, "throttled_until_millis": 0, "failures": %s}}""" - .formatted(TASK, versionConflicts, failures); - } - - private static TaskOutcome outcomeOf(String json) { - JacksonJsonpMapper mapper = new JacksonJsonpMapper(); - try (JsonParser parser = mapper.jsonProvider().createParser(new StringReader(json))) { - return OpenSearchEntityManager.childPropagationOutcome( - GetTasksResponse._DESERIALIZER.deserialize(parser, mapper)); - } - } -} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/UpdateChildrenAsyncPropagationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/UpdateChildrenAsyncPropagationTest.java index 158e9b98328b..b23ca4bb0c68 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/UpdateChildrenAsyncPropagationTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/opensearch/UpdateChildrenAsyncPropagationTest.java @@ -12,10 +12,7 @@ */ package org.openmetadata.service.search.opensearch; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.time.Duration; @@ -29,7 +26,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.openmetadata.schema.service.configuration.elasticsearch.ElasticSearchConfiguration; -import org.openmetadata.service.search.ChildPropagationWatcher; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.wait.strategy.Wait; @@ -146,55 +142,6 @@ void updateChildrenSubmitsAsyncTaskAndPropagates() throws Exception { .count() == CHILD_COUNT); - String taskId = response.task(); - ChildPropagationWatcher.TaskOutcome outcome = - Awaitility.await() - .atMost(60, TimeUnit.SECONDS) - .pollInterval(Duration.ofMillis(500)) - .until( - () -> - OpenSearchEntityManager.childPropagationOutcome( - lowLevel.tasks().get(g -> g.taskId(taskId))), - ChildPropagationWatcher.TaskOutcome::finished); - assertTrue(outcome.failureReasons().isEmpty(), "a clean propagation reports no failures"); - assertEquals(0, outcome.versionConflicts()); - - lowLevel.indices().delete(d -> d.index(index)); - } - - @Test - void aPropagationWhoseScriptFailsIsReportedAsLeavingChildrenStale() throws Exception { - var lowLevel = osClient.getNewClient(); - String index = "repro_children_failing"; - String parentId = UUID.randomUUID().toString(); - lowLevel.index( - idx -> - idx.index(index) - .id("0") - .document(Map.of("name", "child-0", "entityType", Map.of("id", parentId)))); - lowLevel.indices().refresh(r -> r.index(index)); - UpdateByQueryRequest request = - new OpenSearchEntityManager(lowLevel) - .buildUpdateChildrenRequest( - List.of(index), - Pair.of("entityType.id", parentId), - Pair.of("ctx._source.owners = params.missing.size();", Map.of())); - - String taskId = lowLevel.updateByQuery(request).task(); - ChildPropagationWatcher.TaskOutcome outcome = - Awaitility.await() - .atMost(60, TimeUnit.SECONDS) - .pollInterval(Duration.ofMillis(500)) - .until( - () -> - OpenSearchEntityManager.childPropagationOutcome( - lowLevel.tasks().get(g -> g.taskId(taskId))), - ChildPropagationWatcher.TaskOutcome::finished); - - assertFalse( - outcome.failureReasons().isEmpty(), - "a task the cluster failed must be reported, so its parent is reindexed"); - lowLevel.indices().delete(d -> d.index(index)); } }