diff --git a/docs/decisions/2026-10-27-lineage-semantic-zoom-drills-at-35-percent-after-settling.md b/docs/decisions/2026-10-27-lineage-semantic-zoom-drills-at-35-percent-after-settling.md index cc47b572c25e..c30d4ff9fba4 100644 --- a/docs/decisions/2026-10-27-lineage-semantic-zoom-drills-at-35-percent-after-settling.md +++ b/docs/decisions/2026-10-27-lineage-semantic-zoom-drills-at-35-percent-after-settling.md @@ -2,11 +2,12 @@ - **Status:** Accepted - **Revisions:** v1 2026-10-27 (initial); v2 2026-11-04 (a settled zoom is judged against the - zoom it last rested at) -- **Deciders:** Chirag Madlani + zoom it last rested at); v3 2026-11-12 (a zoom-out at the minimum zoom goes up a level) +- **Deciders:** Chirag Madlani; Mohit Yadav (v3) - **Guard:** `LineageMap.utils.test.ts` (threshold either side of 35%, nearest-centre box, drillable-with-children predicate); `PlatformLineage.spec.ts` (a fast zoom-in past the maximum - still drills); the settle delay and targeting are `reviewer` + still drills); `LineageMap.component.test.tsx` (wheel and button zoom-out at the minimum zoom); + the settle delay and targeting are `reviewer` - **Related:** #36363, #36370 ## Context @@ -28,8 +29,11 @@ pause would drill when a pinch overshoots while the user only zooms in to read a (`SEMANTIC_ZOOM_IN_SETTLE_MS`); any further move, a pan included, restarts that wait. When the viewport settles, it is compared with the zoom it last rested at, not with the move before: once the zoom reaches its maximum, the wheel keeps sending moves that no longer change the zoom. -- Zooming out is unchanged: it returns to the parent level as soon as the graph fills less than a - third of the canvas. +- Zooming out returns to the parent level as soon as the graph fills less than a third of the + canvas, or once the zoom reaches its minimum. At the minimum, d3-zoom drops a wheel gesture that + cannot change the zoom and the zoom-out button changes nothing, so no move arrives; a wheel-out or + zoom-out press there goes up a level directly. While a new scene settles and during the cooldown + it does nothing, so a zoom that reached the minimum then is not stuck there afterwards. ## Consequences Drilling takes about half the wheel steps it did. A user zooming in only to read a card drills a diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/LineageResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/LineageResourceIT.java index d1b44cdf5138..98606d877548 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/LineageResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/LineageResourceIT.java @@ -779,7 +779,15 @@ void testLineageMultipleColumnMappings() throws Exception { } @ParameterizedTest - @ValueSource(strings = {"{\"query\":", "{\"term\":{}}", "[\"not\",\"a\",\"query\"]"}) + @ValueSource( + strings = { + "{\"query\":", + "{\"term\":{}}", + "[\"not\",\"a\",\"query\"]", + "[1]", + "{\"term\":{\"name\":{}}}", + "{\"terms\":{}}" + }) void testLineageSceneRejectsMalformedQueryFilter(String queryFilter) { OpenMetadataClient client = SdkClients.adminClient(); RequestOptions options = @@ -799,6 +807,9 @@ void testLineageSceneRejectsMalformedQueryFilter(String queryFilter) { assertEquals(400, error.getStatusCode()); assertTrue(error.getMessage().startsWith("Invalid query_filter"), error.getMessage()); + assertFalse(error.getMessage().contains("co.elastic"), error.getMessage()); + assertFalse(error.getMessage().contains("org.opensearch"), error.getMessage()); + assertFalse(error.getMessage().contains("Exception"), error.getMessage()); } @Test diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/lineage/LineageSceneGraph.java b/openmetadata-service/src/main/java/org/openmetadata/service/lineage/LineageSceneGraph.java index 95eb9859b9f9..eb9b70d4999b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/lineage/LineageSceneGraph.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/lineage/LineageSceneGraph.java @@ -48,6 +48,7 @@ import org.openmetadata.schema.api.lineage.EsLineageData; import org.openmetadata.schema.api.lineage.LineageBand; import org.openmetadata.schema.api.lineage.LineageLens; +import org.openmetadata.schema.api.lineage.LineageLevelKind; import org.openmetadata.schema.api.lineage.LineageSceneEdge; import org.openmetadata.schema.api.lineage.LineageSceneNode; import org.openmetadata.schema.api.lineage.SearchLineageResult; @@ -167,7 +168,7 @@ private LineageSceneNode createNode(Ref ref, SceneAsset asset, boolean isGhost) .withEntityType(ref.entityType()) .withLevelKind(ref.kind()) .withBand(nodeBand(ref.kind(), band)) - .withServiceType(firstNonBlank(ref.serviceType(), asset.serviceType())) + .withServiceType(serviceType(ref, asset)) .withLabel(ref.label()) .withDisplayName(stringValue(ref.sourceEntity(), "displayName")) .withParentId(parentId(ref, asset)) @@ -183,6 +184,14 @@ private LineageSceneNode createNode(Ref ref, SceneAsset asset, boolean isGhost) .withSourceEntity(ref.sourceEntity()); } + // A domain or data product spans services, so the asset that drew its card says nothing + // about its type; without this the card reads, e.g., "CustomDatabase · data product". + private static String serviceType(Ref ref, SceneAsset asset) { + return ref.kind() == LineageLevelKind.DOMAIN || ref.kind() == LineageLevelKind.DATA_PRODUCT + ? null + : firstNonBlank(ref.serviceType(), asset.serviceType()); + } + private void mergeNodeCounts(LineageSceneNode node, Ref ref, SceneAsset asset) { Set countedAssetIds = countedAssetIdsByNode.computeIfAbsent(node.getId(), ignored -> new LinkedHashSet<>()); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/lineage/LineageSceneQuery.java b/openmetadata-service/src/main/java/org/openmetadata/service/lineage/LineageSceneQuery.java index 093e6aeaf44c..b03041da2cc0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/lineage/LineageSceneQuery.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/lineage/LineageSceneQuery.java @@ -21,7 +21,9 @@ import es.co.elastic.clients.elasticsearch._types.FieldValue; import es.co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery; import es.co.elastic.clients.elasticsearch._types.query_dsl.Query; +import es.co.elastic.clients.json.JsonpMappingException; import es.co.elastic.clients.json.jackson.JacksonJsonpMapper; +import es.co.elastic.clients.util.MissingRequiredPropertyException; import jakarta.json.JsonException; import jakarta.json.stream.JsonGenerator; import jakarta.ws.rs.BadRequestException; @@ -40,20 +42,49 @@ final class LineageSceneQuery { private LineageSceneQuery() {} + // Reasons are worded for the caller: the search client's own messages name its classes. static Query parseQueryFilter(String queryFilter) { - Query result = null; - if (!nullOrEmpty(queryFilter)) { - try { - JsonNode filter = JsonUtils.readTree(queryFilter); - JsonNode innerQuery = filter.has("query") ? filter.path("query") : filter; - if (!nullOrEmpty(innerQuery)) { - result = Query.of(clause -> clause.withJson(new StringReader(innerQuery.toString()))); - } - } catch (JsonParsingException | JsonException e) { - throw new BadRequestException("Invalid query_filter: " + e.getMessage(), e); - } + if (nullOrEmpty(queryFilter)) { + return null; + } + JsonNode filter; + try { + filter = JsonUtils.readTree(queryFilter); + } catch (JsonParsingException e) { + throw invalidQueryFilter("it is not valid JSON", e); + } + JsonNode innerQuery = filter.has("query") ? filter.path("query") : filter; + if (nullOrEmpty(innerQuery)) { + return null; + } + if (!innerQuery.isObject()) { + throw invalidQueryFilter("a query must be a JSON object", null); + } + try { + return Query.of(clause -> clause.withJson(new StringReader(innerQuery.toString()))); + } catch (JsonpMappingException e) { + throw invalidQueryFilter(mappingFailure(e), e); + } catch (MissingRequiredPropertyException e) { + throw invalidQueryFilter(missingProperty(e), e); + } catch (JsonException e) { + throw invalidQueryFilter("it is not a search query", e); } - return result; + } + + static BadRequestException invalidQueryFilter(String reason, Throwable cause) { + return new BadRequestException("Invalid query_filter: " + reason, cause); + } + + private static String mappingFailure(JsonpMappingException e) { + String reason = + e.getCause() instanceof MissingRequiredPropertyException missing + ? missingProperty(missing) + : "unexpected value"; + return nullOrEmpty(e.path()) ? reason : reason + " at '" + e.path() + "'"; + } + + private static String missingProperty(MissingRequiredPropertyException e) { + return "missing required property '" + e.getPropertyName() + "'"; } static String rootAssetQuery(LineageSceneRequest request) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/lineage/LineageSceneResolver.java b/openmetadata-service/src/main/java/org/openmetadata/service/lineage/LineageSceneResolver.java index 5d3d26a96f12..80758dd37f4b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/lineage/LineageSceneResolver.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/lineage/LineageSceneResolver.java @@ -31,6 +31,7 @@ import org.openmetadata.service.lineage.LineageSceneLoader.LoadedScene; import org.openmetadata.service.lineage.LineageSceneMapper.Ref; import org.openmetadata.service.lineage.LineageSceneMapper.SceneAsset; +import org.openmetadata.service.search.SearchEngineErrors; import org.openmetadata.service.search.SearchRepository; import org.openmetadata.service.search.lineage.LineageDomainFilter; import org.openmetadata.service.security.policyevaluator.SubjectContext; @@ -78,7 +79,16 @@ public LineageScene getScene( includeDeleted, securityContext, subjectContext); - return getScene(request); + try { + return getScene(request); + } catch (IOException | RuntimeException e) { + // A filter can be a well-formed query that the engine still refuses, e.g. a term + // query whose value is an object; that is the caller's mistake, not a server fault. + if (request.queryFilter() != null && SearchEngineErrors.isRejectedRequest(e)) { + throw LineageSceneQuery.invalidQueryFilter("the search engine rejected it as a query", e); + } + throw e; + } } private LineageScene getScene(LineageSceneRequest request) throws IOException { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchEngineErrors.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchEngineErrors.java index 60e4a62b5807..5c1d7eea8ee4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchEngineErrors.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchEngineErrors.java @@ -1,10 +1,12 @@ package org.openmetadata.service.search; +import es.co.elastic.clients.elasticsearch._types.ElasticsearchException; import jakarta.ws.rs.core.Response; import java.util.List; import org.openmetadata.sdk.exception.SearchException; import org.openmetadata.sdk.exception.SearchIndexNotFoundException; import org.openmetadata.service.Entity; +import os.org.opensearch.client.opensearch._types.OpenSearchException; /** * Translates a search engine's own HTTP failure into the status OpenMetadata reports to its caller. @@ -65,6 +67,33 @@ public static SearchException searchFailure( statusFor(upstreamStatus), String.format("Search failed due to %s", detail)); } + /** + * Whether the search engine answered {@code 400} somewhere along {@code error}'s cause chain, for + * callers that reach the engine without going through a search manager's own translation. + */ + public static boolean isRejectedRequest(Throwable error) { + for (Throwable cause = error; cause != null; cause = nextCause(cause)) { + if (upstreamStatus(cause) == BAD_REQUEST) { + return true; + } + } + return false; + } + + private static Throwable nextCause(Throwable error) { + return error.getCause() == error ? null : error.getCause(); + } + + private static int upstreamStatus(Throwable error) { + if (error instanceof ElasticsearchException elasticsearch) { + return elasticsearch.status(); + } + if (error instanceof OpenSearchException openSearch) { + return openSearch.status(); + } + return 0; + } + private static Response.Status statusFor(int upstreamStatus) { return upstreamStatus == BAD_REQUEST ? Response.Status.BAD_REQUEST diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/lineage/LineageSceneQueryTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/lineage/LineageSceneQueryTest.java index 61c4687f3b63..acd7553f1d46 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/lineage/LineageSceneQueryTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/lineage/LineageSceneQueryTest.java @@ -11,6 +11,7 @@ import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import org.openmetadata.schema.utils.JsonUtils; @@ -62,11 +63,41 @@ void normalizedFiltersPreserveInMemoryLineageMatches(String filter) { } @ParameterizedTest - @ValueSource(strings = {"{\"query\":", "{\"term\":{}}", "[\"not\",\"a\",\"query\"]"}) + @ValueSource( + strings = { + "{\"query\":", + "{\"term\":{}}", + "[\"not\",\"a\",\"query\"]", + "[1]", + "\"tables\"", + "{\"terms\":{}}", + "{\"bool\":{\"must\":5}}", + "{\"range\":{\"x\":{\"boost\":\"high\"}}}" + }) void malformedFiltersAreRejectedAsBadRequests(String filter) { BadRequestException error = assertThrows(BadRequestException.class, () -> LineageSceneQuery.parseQueryFilter(filter)); - assertTrue(error.getMessage().startsWith("Invalid query_filter"), error.getMessage()); + assertTrue(error.getMessage().startsWith("Invalid query_filter: "), error.getMessage()); + assertFalse(error.getMessage().contains("co.elastic"), error.getMessage()); + assertFalse(error.getMessage().contains("Exception"), error.getMessage()); + } + + @ParameterizedTest + @CsvSource( + delimiter = '|', + value = { + "{\"query\":|it is not valid JSON", + "[1]|a query must be a JSON object", + "{\"query\":[1]}|a query must be a JSON object", + "{\"term\":{}}|unexpected value at 'term'", + "{\"bool\":{\"must\":5}}|unexpected value at 'bool.must'", + "{\"terms\":{}}|missing required property 'field' at 'terms'" + }) + void malformedFiltersSayWhatIsWrongInTheCallersTerms(String filter, String reason) { + BadRequestException error = + assertThrows(BadRequestException.class, () -> LineageSceneQuery.parseQueryFilter(filter)); + + assertEquals("Invalid query_filter: " + reason, error.getMessage()); } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/lineage/LineageSceneResolverTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/lineage/LineageSceneResolverTest.java index 2c59e6709c61..14e571b56db3 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/lineage/LineageSceneResolverTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/lineage/LineageSceneResolverTest.java @@ -17,9 +17,18 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +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.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import com.fasterxml.jackson.databind.JsonNode; +import es.co.elastic.clients.elasticsearch._types.ElasticsearchException; +import es.co.elastic.clients.elasticsearch._types.ErrorResponse; +import jakarta.ws.rs.BadRequestException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; @@ -39,6 +48,7 @@ import org.openmetadata.schema.api.lineage.LineageSceneField; import org.openmetadata.schema.api.lineage.LineageSceneNode; import org.openmetadata.schema.api.lineage.RelationshipRef; +import org.openmetadata.schema.api.lineage.SearchLineageRequest; import org.openmetadata.schema.api.lineage.SearchLineageResult; import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.search.SearchRequest; @@ -50,6 +60,7 @@ import org.openmetadata.schema.type.lineage.NodeInformation; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; +import org.openmetadata.service.search.SearchRepository; import org.openmetadata.service.search.lineage.LineageGraphConfiguration; import org.openmetadata.service.security.policyevaluator.SubjectContext; @@ -94,6 +105,61 @@ void layerSceneAggregatesConcreteEdgesByService() { assertEquals("2", rollup.getLabel()); } + @Test + void filterTheSearchEngineRejectsIsTheCallersBadRequest() throws IOException { + LineageSceneResolver resolver = resolverWhoseSearchIsRejected(); + + BadRequestException error = + assertThrows( + BadRequestException.class, + () -> focusedOrdersScene(resolver, "{\"term\":{\"name\":{}}}")); + + assertEquals( + "Invalid query_filter: the search engine rejected it as a query", error.getMessage()); + } + + @Test + void engineRejectionWithoutAFilterStaysAServerFault() throws IOException { + LineageSceneResolver resolver = resolverWhoseSearchIsRejected(); + + assertThrows(ElasticsearchException.class, () -> focusedOrdersScene(resolver, null)); + } + + private static LineageSceneResolver resolverWhoseSearchIsRejected() throws IOException { + SearchRepository repository = mock(SearchRepository.class); + when(repository.searchLineage(any(SearchLineageRequest.class), isNull())) + .thenThrow( + new ElasticsearchException( + "search", + ErrorResponse.of( + response -> + response + .status(400) + .error( + error -> + error + .type("parsing_exception") + .reason( + "Unexpected token [FIELD_NAME] found after the main object."))))); + return new LineageSceneResolver(null, repository); + } + + private static LineageScene focusedOrdersScene(LineageSceneResolver resolver, String queryFilter) + throws IOException { + return resolver.getScene( + ORDERS, + Entity.TABLE, + LineageLens.SERVICE, + LineageBand.ASSET, + 1, + 1, + 50, + queryFilter, + false, + null, + null); + } + @Test void layerSceneKeepsAncestorWhenConcreteEdgesCollapseToSelfLoop() { SearchLineageResult lineage = @@ -242,6 +308,23 @@ void domainAndDataProductRootEntitiesUseTheirOwnLensReferences() { .get(LineageLevelKind.TABLE.value())); } + @Test + void domainAndDataProductCardsTakeNoServiceTypeFromTheirAssets() { + for (LineageLens lens : List.of(LineageLens.DOMAIN, LineageLens.DATA_PRODUCT)) { + Map orders = table(ORDERS, SNOWFLAKE_SERVICE, List.of("id")); + orders.put("domains", List.of(ref(Entity.DOMAIN, "analytics", "analytics"))); + orders.put("dataProducts", List.of(ref(Entity.DATA_PRODUCT, "customer360", "customer360"))); + + LineageScene scene = + RESOLVER.resolveScene( + null, null, lens, LineageBand.LAYER, result(List.of(orders), List.of()), 200); + + LineageSceneNode card = + nodeByFqn(scene, lens == LineageLens.DOMAIN ? "analytics" : "customer360"); + assertNull(card.getServiceType(), lens.value()); + } + } + @Test void serviceFocusedMessagingSceneSkipsAbsentDatabaseAndSchemaLevels() { SearchLineageResult lineage = diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchEngineErrorsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchEngineErrorsTest.java index 48deba1f302b..7399b3ca6f5a 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchEngineErrorsTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchEngineErrorsTest.java @@ -14,8 +14,11 @@ package org.openmetadata.service.search; 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._types.ElasticsearchException; +import es.co.elastic.clients.elasticsearch._types.ErrorResponse; import jakarta.ws.rs.core.Response; import java.util.List; import org.junit.jupiter.api.DisplayName; @@ -24,6 +27,7 @@ import org.junit.jupiter.params.provider.ValueSource; import org.openmetadata.sdk.exception.SearchException; import org.openmetadata.sdk.exception.SearchIndexNotFoundException; +import os.org.opensearch.client.opensearch._types.OpenSearchException; class SearchEngineErrorsTest { @@ -86,6 +90,42 @@ void indexNotFoundForAManagedIndexStaysServerError() { assertEquals("Failed to find index cluster_table_search_index", thrown.getMessage()); } + @Test + @DisplayName("an engine 400 anywhere in the cause chain is a rejected request") + void recognisesTheEngineRejectingARequest() { + ElasticsearchException elasticsearch = elasticsearchFailure(400); + OpenSearchException openSearch = + new OpenSearchException( + os.org.opensearch.client.opensearch._types.ErrorResponse.of( + response -> + response + .status(400) + .error(error -> error.type("parsing_exception").reason("bad query")))); + + assertTrue(SearchEngineErrors.isRejectedRequest(elasticsearch)); + assertTrue(SearchEngineErrors.isRejectedRequest(openSearch)); + assertTrue( + SearchEngineErrors.isRejectedRequest(new IllegalStateException("wrapped", elasticsearch))); + } + + @Test + @DisplayName("an engine failure the caller did not cause is not a rejected request") + void doesNotTreatOtherFailuresAsRejectedRequests() { + assertFalse(SearchEngineErrors.isRejectedRequest(elasticsearchFailure(500))); + assertFalse(SearchEngineErrors.isRejectedRequest(elasticsearchFailure(429))); + assertFalse(SearchEngineErrors.isRejectedRequest(new IllegalStateException("no engine"))); + } + + private static ElasticsearchException elasticsearchFailure(int status) { + return new ElasticsearchException( + "search", + ErrorResponse.of( + response -> + response + .status(status) + .error(error -> error.type("parsing_exception").reason("bad query")))); + } + @Test @DisplayName("no root causes leaves the engine message intact") void rendersMessageWithoutRootCauses() { diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Entity/EntityLineage/LineageControlButtons/LineageControlButtons.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Entity/EntityLineage/LineageControlButtons/LineageControlButtons.test.tsx index c95910d33de9..d76e66cd8a2b 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Entity/EntityLineage/LineageControlButtons/LineageControlButtons.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Entity/EntityLineage/LineageControlButtons/LineageControlButtons.test.tsx @@ -114,6 +114,20 @@ describe('LineageControlButtons', () => { expect(mockZoomOut).toHaveBeenCalledTimes(1); }); + it('tells the map about a zoom-out before the zoom changes', () => { + const onZoomOut = jest.fn(() => expect(mockZoomOut).not.toHaveBeenCalled()); + render( + + ); + fireEvent.click(screen.getByTestId('zoom-out')); + + expect(onZoomOut).toHaveBeenCalledTimes(1); + expect(mockZoomOut).toHaveBeenCalledTimes(1); + }); + it('does not throw without a flow instance', () => { mockLineageState.reactFlowInstance = undefined; renderControls(); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Entity/EntityLineage/LineageControlButtons/LineageControlButtons.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Entity/EntityLineage/LineageControlButtons/LineageControlButtons.tsx index ad93d3d01dc8..4590de2749a9 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Entity/EntityLineage/LineageControlButtons/LineageControlButtons.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Entity/EntityLineage/LineageControlButtons/LineageControlButtons.tsx @@ -35,11 +35,14 @@ const LineageControlButtons: FC<{ miniMapVisible?: boolean; reactFlowInstance?: ReactFlowInstance; onFitView?: () => void; + // Called with each zoom-out press, read before the zoom changes. + onZoomOut?: () => void; }> = ({ onToggleMiniMap, miniMapVisible = false, reactFlowInstance: controlledReactFlowInstance, onFitView, + onZoomOut, }) => { const { t } = useTranslation(); const providerReactFlowInstance = useLineageStore((s) => s.reactFlowInstance); @@ -51,8 +54,9 @@ const LineageControlButtons: FC<{ }, [reactFlowInstance]); const handleZoomOut = useCallback(() => { + onZoomOut?.(); reactFlowInstance?.zoomOut(); - }, [reactFlowInstance]); + }, [onZoomOut, reactFlowInstance]); const handleFitView = useCallback(() => { if (onFitView) { diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/Lineage/Lineage.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/Lineage/Lineage.tsx index 81751359d021..a4c87c200977 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/Lineage/Lineage.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/Lineage/Lineage.tsx @@ -2036,12 +2036,17 @@ export const Lineage = ({ const entityFetchArgs = entityFetchContext ? resolvePlatformViewEntityFetchArgs(platformView, entity) : undefined; + // On mount, the saved settings reach the store in the effect just before + // the one that calls this, so this render's lineageConfig can still be + // the store's reset default; fetching with it would cost an extra, deeper + // request before the one at the saved depth. + const currentLineageConfig = useLineageStore.getState().lineageConfig; if (entityFetchArgs) { fetchLineageData( entityFetchArgs.fqn, entityFetchArgs.type, - lineageConfig + currentLineageConfig ); return; @@ -2051,7 +2056,7 @@ export const Lineage = ({ const fetchKey = getLineageFetchKey( entityFetchContext.entityFqn, entityFetchContext.entityType, - lineageConfig, + currentLineageConfig, queryFilter, timeFilter ); @@ -2059,7 +2064,7 @@ export const Lineage = ({ fetchLineageData( entityFetchContext.entityFqn, entityFetchContext.entityType, - lineageConfig + currentLineageConfig ); } } @@ -2071,7 +2076,6 @@ export const Lineage = ({ platformView, isPlatformLineage, fetchLineageData, - lineageConfig, queryFilter, timeFilter, ]); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/Lineage/LineageStaleNavRepro.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/Lineage/LineageStaleNavRepro.test.tsx index 356f29f948fb..7eed11dc7eae 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/Lineage/LineageStaleNavRepro.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/Lineage/LineageStaleNavRepro.test.tsx @@ -15,7 +15,12 @@ import { ReactNode, useEffect } from 'react'; import { MemoryRouter } from 'react-router-dom'; import { ReactFlowInstance } from 'reactflow'; import { EntityType } from '../../../enums/entity.enum'; +import { + LineageLayer, + PipelineViewMode, +} from '../../../generated/configuration/lineageSettings'; import { usePersistentStorage } from '../../../hooks/currentUserStore/useCurrentUserStore'; +import { useApplicationStore } from '../../../hooks/useApplicationStore'; import { useLineageStore } from '../../../hooks/useLineageStore'; import { getLineageDataByFQN } from '../../../rest/lineageAPI'; import { SourceType } from '../../SearchedData/SearchedData.interface'; @@ -168,6 +173,9 @@ describe('Lineage stale navigation (same-type, no remount)', () => { afterEach(() => { usePersistentStorage.getState().clearUserPreference('admin'); + useApplicationStore.getState().setAppPreferences({ + lineageConfig: undefined, + }); }); it('refetches and clears the stale graph when navigating to a new entity of the same type without unmounting', async () => { @@ -236,6 +244,32 @@ describe('Lineage stale navigation (same-type, no remount)', () => { expect(useLineageStore.getState().init).toBe(true); }); + it('fetches once, at the saved depth, after the store was reset by an earlier lineage view', async () => { + (getLineageDataByFQN as jest.Mock).mockResolvedValue(emptyResponse); + useApplicationStore.getState().setAppPreferences({ + lineageConfig: { + upstreamDepth: 2, + downstreamDepth: 2, + pipelineViewMode: PipelineViewMode.Edge, + lineageLayer: LineageLayer.EntityLineage, + }, + }); + + render(renderLineage(entityA, 'svc.db.s.entityA')); + + await waitFor(() => expect(useLineageStore.getState().loading).toBe(false)); + + expect(getLineageDataByFQN).toHaveBeenCalledTimes(1); + expect(getLineageDataByFQN).toHaveBeenCalledWith( + expect.objectContaining({ + config: expect.objectContaining({ + upstreamDepth: 2, + downstreamDepth: 2, + }), + }) + ); + }); + it('does not refetch when rerendered with the same entity identity (dedup preserved)', async () => { (getLineageDataByFQN as jest.Mock).mockResolvedValue(emptyResponse); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageExportButton/LineageExportButton.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageExportButton/LineageExportButton.test.tsx index ff40b7e3c266..4a9a1844763f 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageExportButton/LineageExportButton.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageExportButton/LineageExportButton.test.tsx @@ -63,4 +63,14 @@ describe('LineageExportButton', () => { getExportViewportForNodes(MAP_NODES, 8000, 12000) ); }); + + it('leaves the date to the export dialog, which appends it to the file name', () => { + render(); + + fireEvent.click(screen.getByTestId('export-button')); + + expect(mockShowModal.mock.calls[0][0].name).not.toMatch( + /\d{4}-\d{2}-\d{2}/ + ); + }); }); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageExportButton/LineageExportButton.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageExportButton/LineageExportButton.tsx index 8cdd4b0d8f51..96f11d3f0594 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageExportButton/LineageExportButton.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageExportButton/LineageExportButton.tsx @@ -20,7 +20,6 @@ import { } from '../../../constants/Export.constants'; import { useLineageStore } from '../../../hooks/useLineageStore'; import { getLineagePngExportOptions } from '../../../utils/CanvasUtils'; -import { getCurrentISODate } from '../../../utils/date-time/DateTimeUtils'; import { useEntityExportModalProvider } from '../../Entity/EntityExportModalProvider/EntityExportModalProvider.component'; interface LineageExportButtonProps { @@ -39,8 +38,9 @@ const LineageExportButton = ({ size }: LineageExportButtonProps) => { const handleExport = () => { const { nodes, edges } = useLineageStore.getState(); + // The export dialog appends the date to the name itself. showModal({ - name: `${t('label.lineage')}_${getCurrentISODate()}`, + name: t('label.lineage'), title: t('label.lineage'), exportTypes: [ExportTypes.PNG], documentSelector: LINEAGE_EXPORT_SELECTOR, diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.component.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.component.test.tsx new file mode 100644 index 000000000000..e111155f93aa --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.component.test.tsx @@ -0,0 +1,351 @@ +/* + * 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. + */ +import { + act, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react'; +import { ReactNode, useEffect } from 'react'; +import { EntityType } from '../../../enums/entity.enum'; +import { + LineageBand, + LineageLens, + LineageLevelKind, + LineageScene, + LineageSceneNode, +} from '../../../generated/api/lineage/lineageScene'; +import { useLineageStore } from '../../../hooks/useLineageStore'; +import { getLineageScene } from '../../../rest/lineageAPI'; +import { SourceType } from '../../SearchedData/SearchedData.interface'; +import LineageMap from './LineageMap.component'; + +const mockNavigate = jest.fn(); +let mockSearch = ''; +let mockZoom = 1; +const mockFlowInstance = { + getZoom: () => mockZoom, + setViewport: jest.fn(), + fitBounds: jest.fn(), + fitView: jest.fn(), + setCenter: jest.fn(), + zoomOut: jest.fn(), + screenToFlowPosition: (point: { x: number; y: number }) => point, + getIntersectingNodes: () => [], +}; + +// A stable t, as react-i18next gives: the map's effects depend on it. +const mockT = (key: string) => key; + +jest.mock('react-i18next', () => ({ + useTranslation: () => ({ t: mockT }), +})); + +jest.mock('react-router-dom', () => ({ + useNavigate: () => mockNavigate, +})); + +jest.mock('../../../hooks/useCustomLocation/useCustomLocation', () => + jest.fn(() => ({ pathname: '/lineage', search: mockSearch })) +); + +jest.mock('../../../hooks/useDomainStore', () => ({ + useDomainStore: () => ({ + activeDomain: 'All Domains', + isDomainRestricted: false, + }), +})); + +jest.mock('../Lineage/LineageHandlersContext', () => ({ + useLineageHandlers: () => ({ onNodeClick: jest.fn() }), +})); + +jest.mock('../../../rest/lineageAPI', () => ({ + getLineageScene: jest.fn(), + getLineageEdgeDetails: jest.fn(), +})); + +jest.mock('../../../utils/ToastUtils', () => ({ + showErrorToast: jest.fn(), + showInfoToast: jest.fn(), +})); + +// React Flow needs a measured DOM; the map's own decisions are what is tested. +jest.mock('reactflow', () => { + const MockReactFlow = ({ + children, + onInit, + onWheel, + }: { + children?: ReactNode; + onInit?: (instance: unknown) => void; + onWheel?: (event: unknown) => void; + }) => { + useEffect(() => { + onInit?.(mockFlowInstance); + }, [onInit]); + + return ( +
+ {children} +
+ ); + }; + + return { + __esModule: true, + default: MockReactFlow, + applyNodeChanges: (_changes: unknown, nodes: unknown) => nodes, + Background: () => null, + MiniMap: () => null, + Panel: ({ children }: { children?: ReactNode }) =>
{children}
, + ReactFlowProvider: ({ children }: { children?: ReactNode }) => ( + <>{children} + ), + }; +}); + +jest.mock('../../../hooks/lineage/useUncontrolledNodeDrag', () => ({ + useUncontrolledNodeDrag: ( + nodes: unknown[], + onNodesChange: (changes: unknown[]) => void + ) => ({ nodes, onNodesChange }), +})); + +jest.mock( + '../../Entity/EntityLineage/CustomNodeV1.component', + () => () => null +); + +jest.mock( + '../../Entity/EntityLineage/LineageControlButtons/LineageControlButtons', + () => + ({ onZoomOut }: { onZoomOut?: () => void }) => + ( + + ) +); + +jest.mock( + '../../Entity/EntityLineage/LineageLayers/LineageLayers', + () => () => null +); + +jest.mock('../Edges/CanvasLayerWrapper/CanvasLayerWrapper', () => ({ + CanvasLayerWrapper: () => null, +})); + +jest.mock('../LineageSkeleton.component', () => () => ( +
+)); + +const FOCUS_FQN = 'svc.db.s.orders'; + +const tableNode = ( + fqn: string, + overrides: Partial = {} +): LineageSceneNode => ({ + id: `table:${fqn}`, + label: fqn.split('.').at(-1) ?? fqn, + fullyQualifiedName: fqn, + entityType: EntityType.TABLE, + band: LineageBand.Asset, + levelKind: LineageLevelKind.Table, + isExpandable: true, + ...overrides, +}); + +const sceneFor = ( + band: LineageBand, + nodes: LineageSceneNode[], + edges: LineageScene['edges'], + lens = LineageLens.Service +): LineageScene => ({ + lens, + band, + focusFqn: FOCUS_FQN, + focusEntityType: EntityType.TABLE, + breadcrumb: [ + { + id: 'root', + band: LineageBand.Layer, + label: 'All Services', + levelKind: LineageLevelKind.Service, + }, + { + id: `table:${FOCUS_FQN}`, + band, + label: 'orders', + fullyQualifiedName: FOCUS_FQN, + entityType: EntityType.TABLE, + levelKind: LineageLevelKind.Table, + }, + ], + nodes, + edges, +}); + +const sceneWithLineage = (band = LineageBand.Asset, lens?: LineageLens) => + sceneFor( + band, + [ + tableNode(FOCUS_FQN, { band, isFocus: true, isOrigin: true }), + tableNode('svc.db.s.fact_orders', { band }), + ], + [ + { + id: 'orders-to-fact', + band, + from: `table:${FOCUS_FQN}`, + to: 'table:svc.db.s.fact_orders', + }, + ], + lens + ); + +const focusedTable = { + id: 'orders-id', + name: 'orders', + fullyQualifiedName: FOCUS_FQN, +} as SourceType; + +const renderMap = () => ( + +); + +describe('LineageMap', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockSearch = ''; + mockZoom = 1; + useLineageStore.getState().reset(); + document.cookie = 'lineageMapsOnboardingSeen=true; path=/'; + }); + + it('says there is no lineage for a focused asset that has none', async () => { + (getLineageScene as jest.Mock).mockResolvedValue( + sceneFor( + LineageBand.Asset, + [tableNode(FOCUS_FQN, { isFocus: true, isOrigin: true })], + [] + ) + ); + + render(renderMap()); + + expect( + await screen.findByText('message.no-lineage-data-available') + ).toBeInTheDocument(); + expect(screen.queryByTestId('lineage-map-canvas')).not.toBeInTheDocument(); + }); + + it('replaces a drawn scene with Reload when the next scene fails to load', async () => { + (getLineageScene as jest.Mock).mockResolvedValueOnce(sceneWithLineage()); + + const { rerender } = render(renderMap()); + + expect(await screen.findByTestId('lineage-map-canvas')).toBeInTheDocument(); + + (getLineageScene as jest.Mock).mockRejectedValueOnce(new Error('down')); + mockSearch = `?lineageLens=${LineageLens.Domain}`; + rerender(renderMap()); + + const reload = await screen.findByRole('button', { name: 'label.reload' }); + + expect(screen.queryByTestId('lineage-map-canvas')).not.toBeInTheDocument(); + + (getLineageScene as jest.Mock).mockResolvedValueOnce( + sceneWithLineage(LineageBand.Asset, LineageLens.Domain) + ); + fireEvent.click(reload); + + expect(await screen.findByTestId('lineage-map-canvas')).toBeInTheDocument(); + expect(getLineageScene).toHaveBeenLastCalledWith( + expect.objectContaining({ lens: LineageLens.Domain }) + ); + }); + + describe('zooming out at the minimum zoom', () => { + const waitForSceneToSettle = async () => { + expect( + await screen.findByTestId('lineage-map-canvas') + ).toBeInTheDocument(); + + // Opening a scene holds semantic zoom off while its landing settles. + act(() => { + jest.advanceTimersByTime(1300); + }); + }; + + beforeEach(() => { + mockSearch = `?lineageBand=${LineageBand.Field}`; + (getLineageScene as jest.Mock).mockResolvedValue( + sceneWithLineage(LineageBand.Field) + ); + }); + + const parentSceneNavigation = expect.objectContaining({ + search: expect.stringContaining(`lineageBand=${LineageBand.Asset}`), + }); + + it('goes up a level on a wheel-out that can no longer change the zoom', async () => { + render(renderMap()); + await waitForSceneToSettle(); + mockZoom = 0.1; + + fireEvent.wheel(screen.getByTestId('react-flow'), { deltaY: 120 }); + + expect(mockNavigate).toHaveBeenCalledWith(parentSceneNavigation, { + replace: true, + }); + }); + + it('goes up a level from the zoom-out button', async () => { + render(renderMap()); + await waitForSceneToSettle(); + mockZoom = 0.1; + + fireEvent.click(screen.getByTestId('zoom-out')); + + expect(mockNavigate).toHaveBeenCalledWith(parentSceneNavigation, { + replace: true, + }); + }); + + it('stays on the level above the minimum zoom, on a wheel-in, and while the scene settles', async () => { + render(renderMap()); + + expect( + await screen.findByTestId('lineage-map-canvas') + ).toBeInTheDocument(); + + mockZoom = 0.1; + fireEvent.wheel(screen.getByTestId('react-flow'), { deltaY: 120 }); + + await waitForSceneToSettle(); + fireEvent.wheel(screen.getByTestId('react-flow'), { deltaY: -120 }); + mockZoom = 0.4; + fireEvent.wheel(screen.getByTestId('react-flow'), { deltaY: 120 }); + + await waitFor(() => expect(mockNavigate).not.toHaveBeenCalled()); + }); + }); +}); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.component.tsx index 78e2d3c639d2..7c178bebd301 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.component.tsx @@ -12,7 +12,6 @@ */ import { - Alert, Box, Breadcrumbs, Button, @@ -948,17 +947,11 @@ const LineageMapEmptyPlaceholder = ({ ); }; -const LineageMapStatusPanel = ({ - scene, - error, -}: { - scene: LineageScene; - error?: AxiosError; -}) => { +const LineageMapStatusPanel = ({ scene }: { scene: LineageScene }) => { const { t } = useTranslation(); const { hiddenNodeCount = 0, sampled, nodes } = scene; const hasHiddenNodes = hiddenNodeCount > 0; - if (!hasHiddenNodes && !sampled && !error) { + if (!hasHiddenNodes && !sampled) { return null; } @@ -966,27 +959,22 @@ const LineageMapStatusPanel = ({ - {(sampled || hasHiddenNodes) && ( - - - )} - {error && ( - - )} + + ); }; @@ -1755,6 +1743,20 @@ const LineageMapCanvas = ({ [pickZoomTargetNode] ); + const zoomOutOneLevel = useCallback( + (currentScene: LineageScene) => { + lastSemanticZoomAtRef.current = Date.now(); + const parentRequest = getParentSceneRequest(currentScene); + if (parentRequest) { + updateRequest(parentRequest); + + return; + } + handleBandChange(getPreviousZoomBand(currentScene.band)); + }, + [handleBandChange, updateRequest] + ); + const handleMove = useCallback( (event: ZoomGestureEvent | null, viewport: { zoom: number }) => { // Any further move, a pan included, restarts the settle window. @@ -1769,14 +1771,7 @@ const LineageMapCanvas = ({ } const nextBand = getRequestedBand(scene, event, viewport.zoom); if (nextBand !== scene.band && !isDeeperBand(scene.band, nextBand)) { - lastSemanticZoomAtRef.current = now; - const parentRequest = getParentSceneRequest(scene); - if (parentRequest) { - updateRequest(parentRequest); - - return; - } - handleBandChange(nextBand); + zoomOutOneLevel(scene); return; } @@ -1796,14 +1791,42 @@ const LineageMapCanvas = ({ }, [ getRequestedBand, - handleBandChange, handleSemanticZoomIn, isPlatformLineage, scene, - updateRequest, + zoomOutOneLevel, ] ); + // Once the zoom sits at its minimum, d3-zoom ignores a wheel gesture that + // cannot change it and the zoom-out button moves nothing, so no move reaches + // handleMove. Zooming out there still asks to go up a level, which a zoom + // that reached the minimum during the post-load cooldown otherwise never can. + // ADR:2026-10-27-lineage-semantic-zoom-drills-at-35-percent-after-settling + const handleZoomOutAtMinimum = useCallback(() => { + if (!isPlatformLineage || !scene || !reactFlowInstance) { + return; + } + const isSemanticZoomPaused = + semanticZoomSuppressedRef.current || + Date.now() - lastSemanticZoomAtRef.current < SEMANTIC_ZOOM_COOLDOWN; + if ( + !isSemanticZoomPaused && + reactFlowInstance.getZoom() <= MIN_ZOOM_VALUE + ) { + zoomOutOneLevel(scene); + } + }, [isPlatformLineage, reactFlowInstance, scene, zoomOutOneLevel]); + + const handleCanvasWheel = useCallback( + (event: React.WheelEvent) => { + if (event.deltaY > 0) { + handleZoomOutAtMinimum(); + } + }, + [handleZoomOutAtMinimum] + ); + useEffect( () => () => window.clearTimeout(semanticZoomInTimerRef.current), [] @@ -2011,7 +2034,12 @@ const LineageMapCanvas = ({ [] ); - if (!scene || scene.nodes.length === 0) { + const emptyState = getLineageMapEmptyState({ + scene, + loading, + hasError: Boolean(sceneError), + }); + if (!scene || emptyState) { const emptyStates: Record = { loading: , error: ( @@ -2031,15 +2059,7 @@ const LineageMapCanvas = ({ // keeps them to the canvas rather than the card that also holds the toolbar. return (
- { - emptyStates[ - getLineageMapEmptyState({ - scene, - loading, - hasError: Boolean(sceneError), - }) - ] - } + {emptyStates[emptyState ?? 'empty']}
); } @@ -2075,7 +2095,8 @@ const LineageMapCanvas = ({ onNodeMouseEnter={handleNodeMouseEnter} onNodeMouseLeave={handleNodeMouseLeave} onNodesChange={flow.onNodesChange} - onPaneClick={handlePaneClick}> + onPaneClick={handlePaneClick} + onWheel={handleCanvasWheel}> {loading && (
- + )} @@ -2128,6 +2149,7 @@ const LineageMapCanvas = ({ reactFlowInstance={reactFlowInstance} onFitView={handleFitView} onToggleMiniMap={() => setMiniMapVisible((visible) => !visible)} + onZoomOut={handleZoomOutAtMinimum} /> diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.utils.test.ts b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.utils.test.ts index aea8fc68e73e..a4763702c338 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.utils.test.ts +++ b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.utils.test.ts @@ -594,6 +594,25 @@ describe('LineageMap utils', () => { ); }); + it('highlights only the paths into and out of the hovered node', () => { + const index = buildLineagePathHighlightIndex([ + { id: 'raw-to-dim', source: 'raw_product', target: 'dim_product' }, + { id: 'dim-to-fact', source: 'dim_product', target: 'fact_orders' }, + { id: 'raw-to-tmp', source: 'raw_orders', target: 'tmp_enriched' }, + { id: 'tmp-to-fact', source: 'tmp_enriched', target: 'fact_orders' }, + { id: 'fact-to-report', source: 'fact_orders', target: 'report' }, + ]); + + const highlight = getConnectedLineagePathHighlight('dim_product', index); + + expect(highlight?.edgeIds).toEqual( + new Set(['raw-to-dim', 'dim-to-fact', 'fact-to-report']) + ); + expect(highlight?.nodeIds).toEqual( + new Set(['dim_product', 'raw_product', 'fact_orders', 'report']) + ); + }); + it('does not build a path highlight without a hovered node', () => { const index = buildLineagePathHighlightIndex([ { id: 'asset-a-to-asset-b', source: 'asset-a', target: 'asset-b' }, @@ -1134,12 +1153,12 @@ describe('getLineageMapEmptyState', () => { ); }); - it('shows the empty state for a scene with no nodes, even on a failed refetch', () => { + it('shows the empty state for a scene with no nodes', () => { expect( getLineageMapEmptyState({ scene: emptyScene, loading: false, - hasError: true, + hasError: false, }) ).toBe('empty'); expect( @@ -1156,4 +1175,105 @@ describe('getLineageMapEmptyState', () => { 'empty' ); }); + + const tableNode = (fqn: string, isFocus = false) => + ({ + id: `table:${fqn}`, + label: fqn, + fullyQualifiedName: fqn, + entityType: 'table', + band: LineageBand.Asset, + levelKind: LineageLevelKind.Table, + isFocus, + isOrigin: isFocus, + } as LineageSceneNode); + + const drawnScene = { + lens: LineageLens.Service, + band: LineageBand.Asset, + focusFqn: 'svc.db.s.orders', + focusEntityType: 'table', + nodes: [tableNode('svc.db.s.orders', true), tableNode('svc.db.s.fact')], + edges: [ + { + id: 'orders-to-fact', + from: 'table:svc.db.s.orders', + to: 'table:svc.db.s.fact', + }, + ], + } as unknown as LineageScene; + + it('draws a scene that has lineage', () => { + expect( + getLineageMapEmptyState({ + scene: drawnScene, + loading: false, + hasError: false, + }) + ).toBeUndefined(); + expect( + getLineageMapEmptyState({ + scene: drawnScene, + loading: true, + hasError: false, + }) + ).toBeUndefined(); + }); + + it('replaces a drawn scene with the error state when the next load fails', () => { + expect( + getLineageMapEmptyState({ + scene: drawnScene, + loading: false, + hasError: true, + }) + ).toBe('error'); + expect( + getLineageMapEmptyState({ + scene: emptyScene, + loading: false, + hasError: true, + }) + ).toBe('error'); + }); + + it('shows the skeleton while a reload after a failed load is in flight', () => { + expect( + getLineageMapEmptyState({ + scene: drawnScene, + loading: true, + hasError: true, + }) + ).toBe('loading'); + }); + + it('shows the empty state for a focused asset that has no lineage', () => { + expect( + getLineageMapEmptyState({ + scene: { + ...drawnScene, + nodes: [tableNode('svc.db.s.orders', true)], + edges: [], + }, + loading: false, + hasError: false, + }) + ).toBe('empty'); + }); + + it('draws a focused container whose assets have no lineage between them', () => { + expect( + getLineageMapEmptyState({ + scene: { + ...drawnScene, + focusFqn: 'svc.db.s', + focusEntityType: 'databaseSchema', + nodes: [tableNode('svc.db.s.orders'), tableNode('svc.db.s.fact')], + edges: [], + }, + loading: false, + hasError: false, + }) + ).toBeUndefined(); + }); }); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.utils.ts b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.utils.ts index 2ece4a77e159..fa6a0872b8ab 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.utils.ts +++ b/openmetadata-ui/src/main/resources/ui/src/components/Lineage/LineageMap/LineageMap.utils.ts @@ -286,9 +286,14 @@ interface LineageFieldPathConnection { nodeId: string; } +interface LineageNodePathConnection { + edgeId: string; + nodeId: string; +} + export interface LineagePathHighlightIndex { - edgeIdsByNodeId: Map>; - adjacentNodeIdsByNodeId: Map>; + upstreamConnectionsByNodeId: Map; + downstreamConnectionsByNodeId: Map; incomingFieldConnectionsByFieldId: Map; outgoingFieldConnectionsByFieldId: Map; nodeIdsByFieldId: Map>; @@ -336,8 +341,14 @@ export const getDrilledRootBreadcrumb = ( export const buildLineagePathHighlightIndex = ( edges: LineagePathEdge[] ): LineagePathHighlightIndex => { - const edgeIdsByNodeId = new Map>(); - const adjacentNodeIdsByNodeId = new Map>(); + const upstreamConnectionsByNodeId = new Map< + string, + LineageNodePathConnection[] + >(); + const downstreamConnectionsByNodeId = new Map< + string, + LineageNodePathConnection[] + >(); const incomingFieldConnectionsByFieldId = new Map< string, LineageFieldPathConnection[] @@ -348,19 +359,27 @@ export const buildLineagePathHighlightIndex = ( >(); const nodeIdsByFieldId = new Map>(); + const addNodeConnection = ( + connectionsByNodeId: Map, + nodeId: string, + connection: LineageNodePathConnection + ) => { + const connections = connectionsByNodeId.get(nodeId); + if (connections) { + connections.push(connection); + } else { + connectionsByNodeId.set(nodeId, [connection]); + } + }; + edges.forEach((edge) => { - [ - [edge.source, edge.target], - [edge.target, edge.source], - ].forEach(([nodeId, adjacentNodeId]) => { - const edgeIds = edgeIdsByNodeId.get(nodeId) ?? new Set(); - const adjacentNodeIds = - adjacentNodeIdsByNodeId.get(nodeId) ?? new Set(); - - edgeIds.add(edge.id); - adjacentNodeIds.add(adjacentNodeId); - edgeIdsByNodeId.set(nodeId, edgeIds); - adjacentNodeIdsByNodeId.set(nodeId, adjacentNodeIds); + addNodeConnection(upstreamConnectionsByNodeId, edge.target, { + edgeId: edge.id, + nodeId: edge.source, + }); + addNodeConnection(downstreamConnectionsByNodeId, edge.source, { + edgeId: edge.id, + nodeId: edge.target, }); if (edge.sourceHandle && edge.targetHandle) { @@ -399,14 +418,17 @@ export const buildLineagePathHighlightIndex = ( }); return { - edgeIdsByNodeId, - adjacentNodeIdsByNodeId, + upstreamConnectionsByNodeId, + downstreamConnectionsByNodeId, incomingFieldConnectionsByFieldId, outgoingFieldConnectionsByFieldId, nodeIdsByFieldId, }; }; +// A node's path is what feeds it and what it feeds: upstream is followed only +// through incoming edges and downstream only through outgoing ones, so a +// sibling that feeds the same downstream node stays off the path. export const getConnectedLineagePathHighlight = ( nodeId: string | undefined, index: LineagePathHighlightIndex @@ -417,25 +439,33 @@ export const getConnectedLineagePathHighlight = ( const edgeIds = new Set(); const nodeIds = new Set([nodeId]); - const queue = [nodeId]; - let queueIndex = 0; - - while (queueIndex < queue.length) { - const currentNodeId = queue[queueIndex]; - queueIndex += 1; - - index.edgeIdsByNodeId - .get(currentNodeId) - ?.forEach((edgeId) => edgeIds.add(edgeId)); - index.adjacentNodeIdsByNodeId - .get(currentNodeId) - ?.forEach((adjacentNodeId) => { - if (!nodeIds.has(adjacentNodeId)) { - nodeIds.add(adjacentNodeId); - queue.push(adjacentNodeId); - } - }); - } + + const traceNodes = ( + connectionsByNodeId: Map + ) => { + const visitedNodeIds = new Set([nodeId]); + const queue = [nodeId]; + let queueIndex = 0; + + while (queueIndex < queue.length) { + const currentNodeId = queue[queueIndex]; + queueIndex += 1; + + connectionsByNodeId + .get(currentNodeId) + ?.forEach(({ edgeId, nodeId: connectedNodeId }) => { + edgeIds.add(edgeId); + nodeIds.add(connectedNodeId); + if (!visitedNodeIds.has(connectedNodeId)) { + visitedNodeIds.add(connectedNodeId); + queue.push(connectedNodeId); + } + }); + } + }; + + traceNodes(index.upstreamConnectionsByNodeId); + traceNodes(index.downstreamConnectionsByNodeId); return { edgeIds, @@ -603,7 +633,17 @@ export const LINEAGE_MAP_RAIL_STOPS = [ export type LineageMapEmptyState = 'loading' | 'error' | 'empty'; -/** Which placeholder the map shows while it has no nodes to draw. */ +// A focused asset with no lineage comes back as its own card alone. +const isSceneWithoutLineage = (scene: LineageScene) => + scene.nodes.length === 0 || + (scene.edges.length === 0 && + scene.nodes.every((node) => node.isFocus || node.isOrigin)); + +/** + * Which placeholder the map shows instead of the canvas, or undefined to draw + * the scene. A failed load replaces whatever scene was drawn before it: that + * scene answered an earlier request, so keeping it would show the wrong map. + */ export const getLineageMapEmptyState = ({ scene, loading, @@ -612,15 +652,15 @@ export const getLineageMapEmptyState = ({ scene?: LineageScene; loading: boolean; hasError: boolean; -}): LineageMapEmptyState => { - if (scene) { - return 'empty'; +}): LineageMapEmptyState | undefined => { + if (hasError) { + return loading ? 'loading' : 'error'; } - if (loading) { - return 'loading'; + if (!scene) { + return loading ? 'loading' : 'empty'; } - return hasError ? 'error' : 'empty'; + return isSceneWithoutLineage(scene) ? 'empty' : undefined; }; export const getRailStop = (scene: LineageScene): LineageBand => { diff --git a/openmetadata-ui/src/main/resources/ui/src/components/discovery/personal-space/Profile/tabs/platform-settings/LineageSettings.tsx b/openmetadata-ui/src/main/resources/ui/src/components/discovery/personal-space/Profile/tabs/platform-settings/LineageSettings.tsx index 174d4dd20183..24899b3f112c 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/discovery/personal-space/Profile/tabs/platform-settings/LineageSettings.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/discovery/personal-space/Profile/tabs/platform-settings/LineageSettings.tsx @@ -11,6 +11,7 @@ * limitations under the License. */ +import { Box } from '@openmetadata/ui-core-components'; import { useTranslation } from 'react-i18next'; import { LineageLayer, @@ -19,6 +20,7 @@ import { } from '../../../../../../generated/configuration/lineageSettings'; import { SettingType } from '../../../../../../generated/settings/settings'; import { getSettingsByType } from '../../../../../../rest/settingConfigAPI'; +import SomethingWentWrongPlaceholder from '../../../../../common/EmptyPlaceholder/SomethingWentWrongPlaceholder'; import SettingsSection, { ReadOnlyRow } from '../../components/SettingsSection'; import type { PlatformSettingsPageProps } from './PlatformSettings.types'; import { SettingsSkeleton } from './SettingsFormLayout'; @@ -44,13 +46,26 @@ export const fetchLineageSettings = async () => const LineageSettings = (props: PlatformSettingsPageProps) => { const { t } = useTranslation(); - const { data: config, isLoading } = useSettingsFetch(fetchLineageSettings); - useEditHeaderAction('lineage', isLoading, props); + const { + data: config, + isLoading, + reload, + } = useSettingsFetch(fetchLineageSettings); + // Editing settings that never loaded would save over the stored ones. + useEditHeaderAction('lineage', isLoading, props, undefined, Boolean(config)); if (isLoading) { return ; } + if (!config) { + return ( + + + + ); + } + return ( diff --git a/openmetadata-ui/src/main/resources/ui/src/components/discovery/personal-space/Profile/tabs/platform-settings/LineageSettingsForm.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/discovery/personal-space/Profile/tabs/platform-settings/LineageSettingsForm.test.tsx index aa0ff9322a27..d61b1ea72eaa 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/discovery/personal-space/Profile/tabs/platform-settings/LineageSettingsForm.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/discovery/personal-space/Profile/tabs/platform-settings/LineageSettingsForm.test.tsx @@ -17,6 +17,7 @@ import { render, screen, waitFor, + within, } from '@testing-library/react'; import { LineageLayer, @@ -164,6 +165,39 @@ describe('LineageSettingsForm', () => { }); }); + it('read-only view offers Reload, not Edit, when the settings fail to load', async () => { + (getSettingsByType as jest.Mock) + .mockRejectedValueOnce(new Error('unavailable')) + .mockResolvedValueOnce(STORED); + const onSetHeaderActions = jest.fn(); + + render( + + ); + const reload = await screen.findByRole('button', { name: 'label.reload' }); + + expect( + screen.queryByTestId('upstream-depth-value') + ).not.toBeInTheDocument(); + + const { container } = render( + <>{onSetHeaderActions.mock.calls.at(-1)?.[0]} + ); + + expect( + within(container).queryByTestId('edit-button') + ).not.toBeInTheDocument(); + + fireEvent.click(reload); + + expect(await screen.findByTestId('upstream-depth-value')).toHaveTextContent( + '2' + ); + }); + it('read-only view shows the stored settings with readable labels', async () => { render( diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/PlatformLineage/PlatformLineage.test.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/PlatformLineage/PlatformLineage.test.tsx index b140ad1afbd2..3c80988b53ac 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/PlatformLineage/PlatformLineage.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/PlatformLineage/PlatformLineage.test.tsx @@ -283,6 +283,26 @@ jest.mock('../../components/common/DocumentTitle/DocumentTitle', () => ({ ), })); +jest.mock('../../components/common/EmptyPlaceholder/NoDataPlaceholder', () => ({ + __esModule: true, + default: ({ + title, + actions, + }: { + title: string; + actions?: { key: string; label: string; onPress: () => void }[]; + }) => ( +
+ {title} + {actions?.map((action) => ( + + ))} +
+ ), +})); + jest.mock('../../components/common/Loader/Loader', () => ({ __esModule: true, default: jest.fn(() =>
Loading
), @@ -571,6 +591,10 @@ describe('PlatformLineage Component Logic', () => { expect(getProps().placeholder).toBe('label.search-entity-for-lineage'); expect(getProps().value).toBeUndefined(); + // The word inside the prompt is translated too, not left in English. + expect(mockT).toHaveBeenCalledWith('label.search-entity-for-lineage', { + entity: 'label.entity-lowercase', + }); }); }); @@ -898,6 +922,54 @@ describe('PlatformLineage Component Logic', () => { expect(mockNavigate).not.toHaveBeenCalled(); }); + + it('opens a picked domain in the Domain lens', async () => { + await selectFromSearch({ + displayName: 'Finance', + value: 'Finance', + reference: { + id: 'finance-id', + type: EntityType.DOMAIN, + fullyQualifiedName: 'Finance', + }, + }); + + expect(mockNavigate).toHaveBeenCalledWith( + '/lineage/domain/Finance?lineageLens=domain' + ); + }); + }); + + describe('Unknown entity', () => { + it('does not keep the previous entity when the next one is not found', async () => { + const { rerender } = render(, { + wrapper: QueryClientProviderWrapper, + }); + + await waitFor(() => { + expect(mockLineage).toHaveBeenLastCalledWith( + expect.objectContaining({ entity: MOCK_TABLE_ENTITY }), + expect.anything() + ); + }); + + mockFqn = 'sample_data.db.schema.missing'; + mockGetEntityAPIfromSource.mockRejectedValue({ + response: { status: 404 }, + }); + mockGetEntityPermissionByFqn.mockRejectedValue({ + response: { status: 404 }, + }); + rerender(); + + expect( + await screen.findByTestId('lineage-entity-not-found') + ).toBeInTheDocument(); + expect(mockPageLayoutV1.mock.calls.at(-1)[0].pageTitle).toBe( + 'label.lineage' + ); + expect(mockShowErrorToast).not.toHaveBeenCalled(); + }); }); // Regression: on /lineage the settings modal used to write into local diff --git a/openmetadata-ui/src/main/resources/ui/src/pages/PlatformLineage/PlatformLineage.tsx b/openmetadata-ui/src/main/resources/ui/src/pages/PlatformLineage/PlatformLineage.tsx index f21d10e84a45..47462ccabbe0 100644 --- a/openmetadata-ui/src/main/resources/ui/src/pages/PlatformLineage/PlatformLineage.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/pages/PlatformLineage/PlatformLineage.tsx @@ -18,6 +18,7 @@ import { PageLayout, } from '@openmetadata/ui-core-components'; import { + Home02, PlatformLineage as PlatformLineageIcon, Settings01, } from '@openmetadata/ui-core-components/icons'; @@ -26,6 +27,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; import DocumentTitle from '../../components/common/DocumentTitle/DocumentTitle'; +import NoDataPlaceholder from '../../components/common/EmptyPlaceholder/NoDataPlaceholder'; import Loader from '../../components/common/Loader/Loader'; import { AssetsUnion } from '../../components/DataAssets/AssetsSelectionModal/AssetSelectionModal.interface'; import DataAssetAsyncSelectList from '../../components/DataAssets/DataAssetAsyncSelectList/DataAssetAsyncSelectList'; @@ -42,11 +44,13 @@ import { import PageHeader from '../../components/PageHeader/PageHeader.component'; import PageLayoutV1 from '../../components/PageLayoutV1/PageLayoutV1'; import { SourceType } from '../../components/SearchedData/SearchedData.interface'; +import { ROUTES } from '../../constants/constants'; import { LEARNING_PAGE_IDS } from '../../constants/Learning.constants'; import { PAGE_HEADERS } from '../../constants/PageHeaders.constant'; import { EntityType } from '../../enums/entity.enum'; import { ResourceEntity } from '../../enums/permissions.enum'; import { SearchIndex } from '../../enums/search.enum'; +import { LineageLens } from '../../generated/api/lineage/lineageScene'; import { EntityReference } from '../../generated/entity/type'; import { useIsAiMode } from '../../hooks/useAppMode'; import useCustomLocation from '../../hooks/useCustomLocation/useCustomLocation'; @@ -76,6 +80,7 @@ const PlatformLineage = () => { const { fqn: decodedFqn } = useFqn(); const [selectedEntity, setSelectedEntity] = useState(); + const [isEntityNotFound, setIsEntityNotFound] = useState(false); const [isEntityLoading, setIsEntityLoading] = useState(false); // Config lives in the Zustand store — Lineage's fetch effect depends on // it, so writing here triggers a refetch. Local useState here would leave @@ -98,7 +103,12 @@ const PlatformLineage = () => { ); useEffect(() => { - if (permissionsError) { + // An entity that does not exist gets its own empty state below, so its + // permission lookup's "not found" is not toasted on top of it. + if ( + permissionsError && + (permissionsError as AxiosError).response?.status !== 404 + ) { showErrorToast(permissionsError as AxiosError); } }, [permissionsError]); @@ -118,10 +128,17 @@ const PlatformLineage = () => { const handleEntitySelect = useCallback( (value: EntityReference) => { + const { entityType: selectedType } = value as SourceType; + // A domain is drawn by the Domain lens; the Service lens has no scene + // for it and would focus one of its assets instead. + const search = + selectedType === EntityType.DOMAIN + ? `?lineageLens=${LineageLens.Domain}` + : ''; void navigate( - `/lineage/${(value as SourceType).entityType}/${getEncodedFqn( + `/lineage/${selectedType}/${getEncodedFqn( value.fullyQualifiedName ?? '' - )}` + )}${search}` ); }, [navigate] @@ -140,6 +157,7 @@ const PlatformLineage = () => { ); const init = useCallback(async () => { + setIsEntityNotFound(false); if (!decodedFqn || !entityType) { setSelectedEntity(undefined); @@ -152,12 +170,14 @@ const PlatformLineage = () => { entityType as AssetsUnion )(decodedFqn); setSelectedEntity(entityResponse); - } catch { + } catch (error) { // Old code awaited this via Promise.allSettled alongside the permission fetch, so a // rejection (or a synchronous throw from an unsupported entityType) never reached a - // showErrorToast call — a settled 'rejected' result just left selectedEntity - // unset. Preserve that silently; permission-fetch errors now surface - // separately via the hook's own effect above. + // showErrorToast call. Preserve that silently; permission-fetch errors surface + // separately via the hook's own effect above. The previous entity is dropped + // so its map and title do not stay on screen for the new URL. + setSelectedEntity(undefined); + setIsEntityNotFound((error as AxiosError)?.response?.status === 404); } finally { setIsEntityLoading(false); } @@ -194,7 +214,9 @@ const PlatformLineage = () => { placeholder={ selectedEntity ? getEntityName(selectedEntity) - : t('label.search-entity-for-lineage', { entity: 'entity' }) + : t('label.search-entity-for-lineage', { + entity: t('label.entity-lowercase'), + }) } queryFilter={getLineageEntityExclusionFilter()} searchIndex={LINEAGE_SEARCH_INDEXES} @@ -270,6 +292,40 @@ const PlatformLineage = () => { return ; } + if (isEntityNotFound) { + return ( + + {isAiMode ? null : ( +
+ {header} +
+ )} +
+ navigate(ROUTES.PLATFORM_LINEAGE), + }, + ]} + icon={} + title={t('message.no-entity-found-for-name', { + entity: t('label.asset-lowercase'), + name: decodedFqn, + })} + /> +
+
+ ); + } + return ( { }, [ selectedEntity, loading, + isEntityNotFound, canEditLineage, entityType, header, decodedFqn, isAiMode, + navigate, + t, ]); // `/lineage` with no entity is the platform-wide view; the focused variant // names the entity it is centred on. - const pageTitle = decodedFqn - ? t('label.platform-type-lineage', { - platformType: getEntityName(selectedEntity) || decodedFqn, - }) - : t('label.lineage'); + const pageTitle = + decodedFqn && !isEntityNotFound + ? t('label.platform-type-lineage', { + platformType: getEntityName(selectedEntity) || decodedFqn, + }) + : t('label.lineage'); const configModal = (