diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserUtilBotIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserUtilBotIT.java new file mode 100644 index 000000000000..ce18e875beed --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserUtilBotIT.java @@ -0,0 +1,113 @@ +/* + * 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.it.tests; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.teams.CreateTeam; +import org.openmetadata.schema.entity.teams.Team; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.TeamRepository; +import org.openmetadata.service.jdbi3.UserRepository; +import org.openmetadata.service.util.UserUtil; + +/** + * Regression coverage for the boot-time team-strip loop on bot users. + * + *

Bots are persisted with {@code teams = [Organization]} (the default parent every user gets + * when no explicit team is given). On every OM boot, {@code UserUtil.addOrUpdateBotUser} was + * called with an in-memory {@link User} that did not carry the existing {@code teams} field. The + * PUT path on {@code userRepository.createOrUpdate} then ran {@code UserUpdater.updateTeams}, + * which executed {@code deleteTo + assignTeams(null)} and wiped the bot's team membership. The + * change description recorded + * {@code fieldsDeleted=[FieldChange[name=teams, oldValue=[Organization], newValue=null]]} on + * every boot, each one triggering an Elasticsearch reindex of the bot user. + */ +@ExtendWith(TestNamespaceExtension.class) +public class UserUtilBotIT { + + @Test + void addOrUpdateBotUserDoesNotStripTeams(final TestNamespace namespace) { + UserRepository userRepository = (UserRepository) Entity.getEntityRepository(Entity.USER); + TeamRepository teamRepository = (TeamRepository) Entity.getEntityRepository(Entity.TEAM); + + String botName = namespace.prefix("bot-team-strip-regression"); + + // Create a real (non-Organization) team and assign the bot to it. Organization is a + // virtual default that UserRepository.getTeams adds back whenever there are zero stored + // relationships, so a test that only checks for Organization can't tell whether the + // upsert wiped real team membership. With this real team, a wipe is observable. + Team realTeam = + namespace.trackRoot( + Entity.TEAM, + teamRepository.create( + null, + new Team() + .withId(UUID.randomUUID()) + .withName(namespace.prefix("bot-strip-team")) + .withTeamType(CreateTeam.TeamType.GROUP) + .withUpdatedBy("admin") + .withUpdatedAt(System.currentTimeMillis()))); + + // Build the initial bot the same way the boot path does: via UserUtil.user(...). Both + // initial create and the simulated boot upsert below construct the in-memory User this + // way, so scalar fields (displayName, description) line up and the short-circuit guard + // can actually fire on the second pass. Override teams with the real team for the + // initial create only. + User initialBot = + UserUtil.user(botName, "open-metadata.org", botName) + .withIsBot(true) + .withTeams(new ArrayList<>(List.of(realTeam.getEntityReference()))); + namespace.trackRoot(Entity.USER, userRepository.create(null, initialBot)); + + // Sanity-check the bot really is in the real team. + User beforeBoot = userRepository.getByName(null, botName, userRepository.getFields("teams")); + List teamsBefore = beforeBoot.getTeams(); + assertNotNull(teamsBefore, "Setup failed: bot should have at least one team"); + assertTrue( + teamsBefore.stream().anyMatch(t -> realTeam.getName().equals(t.getName())), + "Setup failed: bot should be in real team before upsert. Got: " + teamsBefore); + + // Simulate the bootstrap path: a fresh User object describing the same bot, without the + // teams field populated. This is exactly what BotResource.initialize passes to + // UserUtil.addOrUpdateBotUser on every OM boot: the in-memory User from configuration + // carries id/name/email and a few scalar fields, but never teams. + User boundary = UserUtil.user(botName, "open-metadata.org", botName).withIsBot(true); + + // The call under test. + UserUtil.addOrUpdateBotUser(boundary); + + // After the boot upsert the bot MUST still be a member of the real team. With the bug + // present, this fails with teams=[Organization] (the real team has been wiped and only + // the virtual default remains), matching the production boot logs + // (fieldsDeleted=[teams: oldValue=[Organization], newValue=null]). + User afterBoot = userRepository.getByName(null, botName, userRepository.getFields("teams")); + List teamsAfter = afterBoot.getTeams(); + assertNotNull( + teamsAfter, + "Boot upsert stripped the bot's teams (teams field is null after addOrUpdateBotUser)"); + assertTrue( + teamsAfter.stream().anyMatch(t -> realTeam.getName().equals(t.getName())), + "Boot upsert removed the bot's real team membership. Got: " + teamsAfter); + } +} diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CompanyContextTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CompanyContextTool.java index 4cbf391929bd..f6ab7c9940d3 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CompanyContextTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CompanyContextTool.java @@ -21,7 +21,7 @@ import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.limits.Limits; import org.openmetadata.service.resources.context.ContextMemoryVisibility; -import org.openmetadata.service.search.vector.OpenSearchVectorService; +import org.openmetadata.service.search.vector.VectorIndexService; import org.openmetadata.service.search.vector.utils.DTOs.VectorSearchResponse; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.DefaultAuthorizer; @@ -165,7 +165,7 @@ private static void putIfPresent(Map pill, String key, Object va private static Map runSearch( String query, Map params, CatalogSecurityContext securityContext) { Map result; - OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance(); + VectorIndexService vectorService = Entity.getSearchRepository().getVectorIndexService(); if (!Entity.getSearchRepository().isVectorEmbeddingEnabled() || vectorService == null) { result = errorResponse( @@ -178,7 +178,7 @@ private static Map runSearch( } private static Map search( - OpenSearchVectorService vectorService, + VectorIndexService vectorService, String query, Map params, CatalogSecurityContext securityContext) { diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/CompanyContextToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/CompanyContextToolTest.java index 5b4a1627b0c9..35151bdb19dc 100644 --- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/CompanyContextToolTest.java +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/CompanyContextToolTest.java @@ -42,7 +42,7 @@ import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.jdbi3.ContextMemoryRepository; import org.openmetadata.service.search.SearchRepository; -import org.openmetadata.service.search.vector.OpenSearchVectorService; +import org.openmetadata.service.search.vector.VectorIndexService; import org.openmetadata.service.search.vector.utils.DTOs.VectorSearchResponse; import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; @@ -93,19 +93,34 @@ void blankQueryReturnsError() throws Exception { result.get("error").toString()); } + @Test + void searchReportsSemanticSearchNotEnabledWhenNoVectorServiceWasCreated() throws Exception { + SearchRepository searchRepository = mock(SearchRepository.class); + when(searchRepository.isVectorEmbeddingEnabled()).thenReturn(true); + when(searchRepository.getVectorIndexService()).thenReturn(null); + entityMock.when(Entity::getSearchRepository).thenReturn(searchRepository); + + Map params = new HashMap<>(); + params.put("query", "refund policy"); + Map result = + tool.execute(mock(Authorizer.class), mock(CatalogSecurityContext.class), params); + + assertTrue( + result.get("error").toString().contains("Semantic search is not enabled"), + result.toString()); + } + @Test void cursorThreadsOffsetIntoVectorSearchClosingThePagingGap() throws Exception { SearchRepository searchRepository = mock(SearchRepository.class); when(searchRepository.isVectorEmbeddingEnabled()).thenReturn(true); entityMock.when(Entity::getSearchRepository).thenReturn(searchRepository); - OpenSearchVectorService vectorService = mock(OpenSearchVectorService.class); + VectorIndexService vectorService = mock(VectorIndexService.class); + when(searchRepository.getVectorIndexService()).thenReturn(vectorService); VectorSearchResponse response = new VectorSearchResponse(5L, Collections.emptyList()); - try (MockedStatic vectorMock = - mockStatic(OpenSearchVectorService.class); - MockedStatic authorizerMock = mockStatic(DefaultAuthorizer.class)) { - vectorMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService); + try (MockedStatic authorizerMock = mockStatic(DefaultAuthorizer.class)) { authorizerMock .when(() -> DefaultAuthorizer.getSubjectContext(any())) .thenReturn(mock(SubjectContext.class)); @@ -145,13 +160,11 @@ void aFieldThePillDoesNotHaveIsOmittedByBothLookups() throws Exception { hit.put("fullyQualifiedName", "refunds"); hit.put("answer", "Within 30 days."); hit.put("summary", null); - OpenSearchVectorService vectorService = mock(OpenSearchVectorService.class); + VectorIndexService vectorService = mock(VectorIndexService.class); + when(searchRepository.getVectorIndexService()).thenReturn(vectorService); CatalogSecurityContext securityContext = mock(CatalogSecurityContext.class); - try (MockedStatic vectorMock = - mockStatic(OpenSearchVectorService.class); - MockedStatic authorizerMock = mockStatic(DefaultAuthorizer.class)) { - vectorMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService); + try (MockedStatic authorizerMock = mockStatic(DefaultAuthorizer.class)) { authorizerMock .when(() -> DefaultAuthorizer.getSubjectContext(securityContext)) .thenReturn(mock(SubjectContext.class)); @@ -180,15 +193,13 @@ void searchIsScopedToPillsAndCarriesTheCallersIdentity() throws Exception { when(searchRepository.isVectorEmbeddingEnabled()).thenReturn(true); entityMock.when(Entity::getSearchRepository).thenReturn(searchRepository); - OpenSearchVectorService vectorService = mock(OpenSearchVectorService.class); + VectorIndexService vectorService = mock(VectorIndexService.class); + when(searchRepository.getVectorIndexService()).thenReturn(vectorService); VectorSearchResponse response = new VectorSearchResponse(0L, Collections.emptyList()); SubjectContext subjectContext = mock(SubjectContext.class); CatalogSecurityContext securityContext = mock(CatalogSecurityContext.class); - try (MockedStatic vectorMock = - mockStatic(OpenSearchVectorService.class); - MockedStatic authorizerMock = mockStatic(DefaultAuthorizer.class)) { - vectorMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService); + try (MockedStatic authorizerMock = mockStatic(DefaultAuthorizer.class)) { authorizerMock .when(() -> DefaultAuthorizer.getSubjectContext(securityContext)) .thenReturn(subjectContext); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java index f2666a5a1b21..83fdbb33f24b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/aicontext/AIContextFinder.java @@ -31,7 +31,7 @@ import org.openmetadata.schema.type.aicontext.KnowledgeItem; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; -import org.openmetadata.service.search.vector.OpenSearchVectorService; +import org.openmetadata.service.search.vector.VectorIndexService; import org.openmetadata.service.search.vector.utils.DTOs.VectorSearchResponse; import org.openmetadata.service.security.policyevaluator.SubjectContext; import org.openmetadata.service.workflows.searchIndex.ReindexingUtil; @@ -122,7 +122,7 @@ void collectHit( private VectorSearchResponse searchKnowledge(String query, int size) { VectorSearchResponse response = null; if (Entity.getSearchRepository().isVectorEmbeddingEnabled()) { - OpenSearchVectorService service = OpenSearchVectorService.getInstance(); + VectorIndexService service = Entity.getSearchRepository().getVectorIndexService(); if (service != null) { try { // Over-fetch: collectHit dedupes chunk documents per FQN, so a long item occupying diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java index 6acdec372895..599438e68633 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java @@ -8768,6 +8768,17 @@ default User findEntityByName(String fqn, Include include) { void updateLastActivityTime( @BindFQN("nameHash") String nameHash, @Bind("lastActivityTime") long lastActivityTime); + @ConnectionAwareSqlUpdate( + value = + "UPDATE user_entity SET json = JSON_SET(json, '$.lastLoginTime', :lastLoginTime) WHERE nameHash = :nameHash AND deleted = false", + connectionType = MYSQL) + @ConnectionAwareSqlUpdate( + value = + "UPDATE user_entity SET json = jsonb_set(json, '{lastLoginTime}', to_jsonb(:lastLoginTime::bigint)) WHERE nameHash = :nameHash AND deleted = false", + connectionType = POSTGRES) + void updateLastLoginTime( + @BindFQN("nameHash") String nameHash, @Bind("lastLoginTime") long lastLoginTime); + @ConnectionAwareSqlUpdate( value = "UPDATE user_entity SET json = JSON_SET(json, '$.lastActivityTime', " diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java index 8dff02b28708..70dc64e79492 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java @@ -32,7 +32,6 @@ import io.github.resilience4j.core.IntervalFunction; import io.github.resilience4j.retry.Retry; import io.github.resilience4j.retry.RetryConfig; -import jakarta.json.JsonPatch; import jakarta.ws.rs.core.SecurityContext; import jakarta.ws.rs.core.UriInfo; import java.io.IOException; @@ -305,12 +304,23 @@ public void storeEntities(List entities) { dao.insertMany(dao.getTableName(), dao.getNameHashColumn(), fqns, jsons); } + /** + * Records a login with a single-row JSON update, the same way {@link #updateUserLastActivityTime} + * does. The previous implementation applied a JSON patch through the full entity update path. + * That path carries no useful change (lastLoginTime is excluded from change descriptions), but + * when the same user logged in again within the EntityUpdater session window (10 minutes), the + * change-consolidation step reloaded the user with every field, including {@code owns}, which + * costs one lookup per entity owned by the user's teams: ~2,600 queries and ~9 s per login for a + * user whose teams own ~300 assets, versus ~150 queries and ~1 s for the first login in a session. + */ + @Transaction public void updateUserLastLoginTime(User orginalUser, long lastLoginTime) { - User updatedUser = JsonUtils.deepCopy(orginalUser, User.class); - JsonPatch patch = - JsonUtils.getJsonPatch(orginalUser, updatedUser.withLastLoginTime(lastLoginTime)); - UserRepository userRepository = (UserRepository) Entity.getEntityRepository(USER); - userRepository.patch(null, orginalUser.getId(), orginalUser.getUpdatedBy(), patch); + String fqn = quoteName(orginalUser.getName().toLowerCase()); + LOG.debug("Updating lastLoginTime for user: {} to: {}", orginalUser.getName(), lastLoginTime); + // @BindFQN hashes the fqn, so it is passed unhashed + daoCollection.userDAO().updateLastLoginTime(fqn, lastLoginTime); + // The row changed under the entity cache: drop the cached copy so reads see the new value + invalidateCacheForEntity(USER, orginalUser.getId(), orginalUser.getFullyQualifiedName()); // Update lastActivityTime immediately on login for metrics visibility // This ensures user metrics show activity right after login diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorSearchQueryBuilder.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorSearchQueryBuilder.java index 6ef9c7f05c49..c0814a7c4a93 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorSearchQueryBuilder.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/vector/VectorSearchQueryBuilder.java @@ -21,6 +21,7 @@ public class VectorSearchQueryBuilder { private static final String ANY = "__ANY__"; private static final String NONE = "__NONE__"; public static final int DEFAULT_KNN_NUM_CANDIDATES_MULTIPLIER = 2; + public static final int ES_MAX_KNN_NUM_CANDIDATES = 10_000; /** * Consulted only for its engine-independent predicates ({@code isSubjectResolvable}) and field @@ -148,9 +149,12 @@ public static String buildNativeESQuery( int numCandidatesMultiplier, SubjectContext subjectContext) { // Compute in long to avoid int overflow when k * numCandidatesMultiplier exceeds - // Integer.MAX_VALUE; clamp to Integer.MAX_VALUE so num_candidates is always positive. + // Integer.MAX_VALUE; clamp to Elasticsearch's engine maximum of 10,000 so any admitted k + // (MAX_K = 10_000) yields a valid request — Elasticsearch rejects num_candidates above + // 10,000 with a 400. long candidatesLong = (long) k * (long) numCandidatesMultiplier; - int numCandidates = (int) Math.max(100, Math.min(candidatesLong, (long) Integer.MAX_VALUE)); + int numCandidates = + (int) Math.max(100, Math.min(candidatesLong, (long) ES_MAX_KNN_NUM_CANDIDATES)); StringBuilder sb = new StringBuilder(512) .append("{\"size\":") diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/util/UserUtil.java b/openmetadata-service/src/main/java/org/openmetadata/service/util/UserUtil.java index a3d86229b23c..d7b5f29b762e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/util/UserUtil.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/util/UserUtil.java @@ -334,6 +334,19 @@ public static boolean assignTeamsFromClaim(User user, List teamNames) { */ public static User addOrUpdateBotUser(User user) { User originalUser = retrieveWithAuthMechanism(user); + // Short-circuit when the incoming bot user has no real change vs. what's already in the + // database. Without this guard every OM boot calls into addOrUpdateUser -> + // userRepository.createOrUpdate, and UserUpdater.entitySpecificUpdate then runs + // updateTeams/updateRoles/etc. with the incoming `user.getTeams() == null`, which strips + // the bot's stored team relationships, bumps the version, and triggers an Elasticsearch + // reindex of the bot user (and any team membership change ripples into the team_search + // index too). With many bots this is a reindex storm on every restart. + if (originalUser != null + && Objects.equals(listOrEmpty(originalUser.getRoles()), listOrEmpty(user.getRoles())) + && Objects.equals(originalUser.getDescription(), user.getDescription()) + && Objects.equals(originalUser.getDisplayName(), user.getDisplayName())) { + return originalUser; + } AuthenticationMechanism authMechanism = originalUser != null ? originalUser.getAuthenticationMechanism() : null; // the user did not have an auth mechanism and auth config is present @@ -364,8 +377,12 @@ private static User retrieveWithAuthMechanism(User user) { EntityRepository userRepository = (UserRepository) Entity.getEntityRepository(Entity.USER); try { + // Include "roles" so the no-op short-circuit in addOrUpdateBotUser can compare it + // against the incoming user. description and displayName are scalar fields stored in + // the entity JSON column, so they're already populated by the base read without an + // extra field fetch. return userRepository.getByName( - null, user.getName(), new Fields(Set.of("authenticationMechanism"))); + null, user.getName(), new Fields(Set.of("authenticationMechanism", "roles"))); } catch (EntityNotFoundException e) { LOG.debug("Bot entity: {} does not exists.", user); return null; diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/aicontext/AIContextFinderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/aicontext/AIContextFinderTest.java index 64e953f79f79..f9cb74b0892e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/aicontext/AIContextFinderTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/aicontext/AIContextFinderTest.java @@ -15,12 +15,25 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; import org.openmetadata.schema.type.aicontext.KnowledgeItem; +import org.openmetadata.service.Entity; +import org.openmetadata.service.search.SearchRepository; +import org.openmetadata.service.search.vector.OpenSearchVectorService; +import org.openmetadata.service.search.vector.VectorIndexService; +import org.openmetadata.service.search.vector.utils.DTOs.VectorSearchResponse; /** * Unit tests for {@link AIContextFinder}'s pure hit-mapping helpers and the Mode-B markdown that @@ -133,6 +146,36 @@ void collectHit_keepsItemsOfDifferentTypesSharingAnFqn() { + " same item still dedupes"); } + @Test + void find_usesTheBackendNeutralVectorServiceWhenTheOpenSearchSingletonIsNull() { + Map hit = + Map.of( + "entityType", "glossaryTerm", + "fullyQualifiedName", "Business.BounceRate", + "name", "BounceRate", + "description", "Share of visits that leave after a single page."); + VectorIndexService vectorService = mock(VectorIndexService.class); + when(vectorService.search(anyString(), anyMap(), anyInt(), anyInt(), anyInt(), anyDouble())) + .thenReturn(new VectorSearchResponse(1L, List.of(hit))); + SearchRepository searchRepository = mock(SearchRepository.class); + when(searchRepository.isVectorEmbeddingEnabled()).thenReturn(true); + when(searchRepository.getVectorIndexService()).thenReturn(vectorService); + + try (MockedStatic entity = mockStatic(Entity.class); + MockedStatic openSearch = + mockStatic(OpenSearchVectorService.class)) { + entity.when(Entity::getSearchRepository).thenReturn(searchRepository); + // Elasticsearch deployments never create the OpenSearch singleton. + openSearch.when(OpenSearchVectorService::getInstance).thenReturn(null); + + AIContextFinder.FoundContext found = new AIContextFinder().find("bounce rate", 5); + + assertEquals( + List.of("Business.BounceRate"), + found.items().stream().map(KnowledgeItem::getFullyQualifiedName).toList()); + } + } + @Test void renderFound_emitsKnowledgeAndCandidateAssets() { AIContextFinder.FoundContext found = diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/VectorSearchQueryBuilderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/VectorSearchQueryBuilderTest.java index 7b0b590bb029..6c1b67ebd5fc 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/VectorSearchQueryBuilderTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/vector/VectorSearchQueryBuilderTest.java @@ -925,10 +925,11 @@ void testNativeESQueryNumCandidates() throws Exception { } @Test - void testNativeESQueryClampsNumCandidatesOnIntOverflow() throws Exception { + void testNativeESQueryClampsNumCandidatesToEngineMax() throws Exception { float[] vector = {0.1f, 0.2f}; - // k * multiplier > Integer.MAX_VALUE → must clamp, never emit a negative value. + // k * multiplier > Integer.MAX_VALUE → must clamp to the engine max, never emit a + // negative or oversized value. String query = VectorSearchQueryBuilder.buildNativeESQuery(vector, 10, 0, 1_000_000, Map.of(), 100_000); @@ -937,7 +938,65 @@ void testNativeESQueryClampsNumCandidatesOnIntOverflow() throws Exception { assertTrue(numCandidates > 0, "num_candidates must be positive even on overflow"); assertEquals( - Integer.MAX_VALUE, numCandidates, "num_candidates must clamp to Integer.MAX_VALUE"); + VectorSearchQueryBuilder.ES_MAX_KNN_NUM_CANDIDATES, + numCandidates, + "num_candidates must clamp to Elasticsearch's engine maximum of 10,000"); + } + + @Test + void testNativeESQueryNumCandidatesClampedAtAdvertisedMaxK() throws Exception { + float[] vector = {0.1f}; + + // The REST resource and MCP tool both advertise MAX_K = 10,000. With the default + // multiplier of 2, k=10,000 would produce num_candidates=20,000 which Elasticsearch + // rejects with a 400. The clamp must bring it down to 10,000. + String query = VectorSearchQueryBuilder.buildNativeESQuery(vector, 10, 0, 10_000, Map.of()); + + JsonNode root = MAPPER.readTree(query); + assertEquals( + VectorSearchQueryBuilder.ES_MAX_KNN_NUM_CANDIDATES, + root.get("knn").get("num_candidates").asInt(), + "k=10,000 with default multiplier 2 must clamp num_candidates to 10,000, not 20,000"); + assertEquals(10_000, root.get("knn").get("k").asInt(), "k itself must not be clamped"); + } + + @Test + void testNativeESQueryNumCandidatesClampedWithHighMultiplier() throws Exception { + float[] vector = {0.1f}; + + // A high multiplier must also be clamped: k=201, multiplier=50 → 10,050 → 10,000. + String query = VectorSearchQueryBuilder.buildNativeESQuery(vector, 10, 0, 201, Map.of(), 50); + + JsonNode root = MAPPER.readTree(query); + assertEquals( + VectorSearchQueryBuilder.ES_MAX_KNN_NUM_CANDIDATES, + root.get("knn").get("num_candidates").asInt(), + "k=201 with multiplier 50 produces 10,050 which must clamp to 10,000"); + } + + @Test + void testNativeESQueryNumCandidatesNeverExceedsEngineMaxForAnyAdmittedK() throws Exception { + float[] vector = {0.1f}; + + // No admitted k (1..10,000) with any reasonable multiplier can produce num_candidates + // above the engine cap. + int[] multipliers = {1, 2, 3, 5, 10, 50, 100}; + for (int k = 1; k <= 10_000; k += 73) { + for (int multiplier : multipliers) { + String query = + VectorSearchQueryBuilder.buildNativeESQuery(vector, 10, 0, k, Map.of(), multiplier); + int numCandidates = MAPPER.readTree(query).get("knn").get("num_candidates").asInt(); + assertTrue( + numCandidates <= VectorSearchQueryBuilder.ES_MAX_KNN_NUM_CANDIDATES, + "num_candidates=" + + numCandidates + + " exceeds engine max for k=" + + k + + " multiplier=" + + multiplier); + assertTrue(numCandidates >= 100, "num_candidates must be at least 100"); + } + } } @Test