From 5872a7ae6da7de1b487d307bef5d061f1803e801 Mon Sep 17 00:00:00 2001 From: Joao Amaral <7281460+joaopamaral@users.noreply.github.com> Date: Thu, 14 May 2026 15:58:08 -0300 Subject: [PATCH 1/5] fix(bots): skip bot upsert when nothing changed to stop team-strip + reindex loop on boot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BotResource.initialize() runs UserUtil.addOrUpdateBotUser(user) for every bot on every OM boot. The in-memory User built by UserUtil.user(...) does not have the teams field populated, so the PUT path through userRepository.createOrUpdate -> UserUpdater.entitySpecificUpdate runs updateTeams(original, updated) with original.teams = [Organization] (or the bot's real stored teams) and updated.teams = null. updateTeams then executes deleteTo(user, HAS, TEAM) + assignTeams(null), which strips every stored team membership the bot had, bumps the user version, and triggers an ES reindex of both the user and each affected team. With several bots this fires on every restart and produces the reindex storm plus "Circular dependency detected in team hierarchy for team: Organization" warnings we see in the boot logs. Short-circuit when the incoming bot has no real change vs. the persisted row: compare description, displayName, and roles. If they all match, return the original user and skip the PUT entirely — no UserUpdater, no team strip, no version bump, no reindex. Two adjustments to make the guard actually fire: - retrieveWithAuthMechanism now also loads "roles" (was loading only "authenticationMechanism"); description and displayName are scalar JSON-column fields and were already populated by the base read. - Compare roles via listOrEmpty(...) on both sides because the database-loaded original returns an empty list while the freshly built in-memory user returns null, and Objects.equals(null, []) is false. Adds UserUtilBotTest.addOrUpdateBotUserDoesNotStripTeams as a regression test. The test creates a real (non-Organization) team, assigns the bot to it, calls addOrUpdateBotUser with a fresh User object that does not carry the teams field (matching what BotResource.initialize passes on boot), then asserts the bot is still in the real team. Before this fix the assertion fails with "Got: [Organization]" — the real team has been wiped and only the virtual default remains. Co-Authored-By: Claude Opus 4.7 (1M context) (cherry picked from commit 7fd62f825087dedec3a9067f96e5377dfb3f9ed8) --- .../openmetadata/service/util/UserUtil.java | 19 ++- .../service/util/UserUtilBotTest.java | 117 ++++++++++++++++++ 2 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/util/UserUtilBotTest.java 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/util/UserUtilBotTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/util/UserUtilBotTest.java new file mode 100644 index 000000000000..cac9e5e8cb3b --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/util/UserUtilBotTest.java @@ -0,0 +1,117 @@ +/* + * Copyright 2026 Collate + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openmetadata.service.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.UUID; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.service.Entity; +import org.openmetadata.service.OpenMetadataApplicationTest; +import org.openmetadata.service.jdbi3.UserRepository; + +/** + * 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. + */ +@Slf4j +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class UserUtilBotTest extends OpenMetadataApplicationTest { + + @Test + void addOrUpdateBotUserDoesNotStripTeams() throws Exception { + UserRepository userRepository = + (UserRepository) Entity.getEntityRepository(Entity.USER); + + String suffix = String.valueOf(System.currentTimeMillis()); + String botName = "bot-team-strip-regression-" + suffix; + String email = botName + "@open-metadata.org"; + + // 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. + org.openmetadata.service.jdbi3.TeamRepository teamRepository = + (org.openmetadata.service.jdbi3.TeamRepository) + Entity.getEntityRepository(Entity.TEAM); + org.openmetadata.schema.entity.teams.Team realTeam = + teamRepository.create( + null, + new org.openmetadata.schema.entity.teams.Team() + .withId(UUID.randomUUID()) + .withName("bot-strip-team-" + suffix) + .withTeamType(org.openmetadata.schema.api.teams.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 java.util.ArrayList<>(List.of(realTeam.getEntityReference()))); + User stored = 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 UserUtil.addOrUpdateBotUser is called with + // on every OM boot — the in-memory User from configuration carries id/name/email and a + // few scalar fields, but never teams. + // Build the in-memory User the same way BotResource.initialize does on boot: + // UserUtil.user(name, domain, updatedBy).withIsBot(true). Note that the result does NOT + // have `teams` populated. + 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 Organization team. With the + // bug present, this fails with teams=null (or empty), exactly matching the production logs + // we observed (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); + } +} From 882884e56ffd2537913fcbe5caa89704ea6619a8 Mon Sep 17 00:00:00 2001 From: Joao Amaral <7281460+joaopamaral@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:40:59 -0300 Subject: [PATCH 2/5] test(bots): move the bot upsert regression test to the integration-tests module 2.0.7 removed OpenMetadataApplicationTest from openmetadata-service, so the service test module can no longer boot the application. The integration-tests module runs in-process with repository access (TestNamespaceExtension pattern), so UserUtilBotTest becomes UserUtilBotIT there with the same scenario: a bot in a real team, then the boot-time addOrUpdateBotUser call with a User that carries no teams, asserting the membership survives. Co-Authored-By: Claude Fable 5.1 --- .../openmetadata/it/tests/UserUtilBotIT.java | 78 +++++++++---------- 1 file changed, 37 insertions(+), 41 deletions(-) rename openmetadata-service/src/test/java/org/openmetadata/service/util/UserUtilBotTest.java => openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserUtilBotIT.java (61%) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/util/UserUtilBotTest.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserUtilBotIT.java similarity index 61% rename from openmetadata-service/src/test/java/org/openmetadata/service/util/UserUtilBotTest.java rename to openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserUtilBotIT.java index cac9e5e8cb3b..ce18e875beed 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/util/UserUtilBotTest.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserUtilBotIT.java @@ -10,22 +10,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openmetadata.service.util; +package org.openmetadata.it.tests; -import static org.junit.jupiter.api.Assertions.assertEquals; 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 lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; +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.OpenMetadataApplicationTest; +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. @@ -39,35 +43,31 @@ * {@code fieldsDeleted=[FieldChange[name=teams, oldValue=[Organization], newValue=null]]} on * every boot, each one triggering an Elasticsearch reindex of the bot user. */ -@Slf4j -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -class UserUtilBotTest extends OpenMetadataApplicationTest { +@ExtendWith(TestNamespaceExtension.class) +public class UserUtilBotIT { @Test - void addOrUpdateBotUserDoesNotStripTeams() throws Exception { - UserRepository userRepository = - (UserRepository) Entity.getEntityRepository(Entity.USER); + void addOrUpdateBotUserDoesNotStripTeams(final TestNamespace namespace) { + UserRepository userRepository = (UserRepository) Entity.getEntityRepository(Entity.USER); + TeamRepository teamRepository = (TeamRepository) Entity.getEntityRepository(Entity.TEAM); - String suffix = String.valueOf(System.currentTimeMillis()); - String botName = "bot-team-strip-regression-" + suffix; - String email = botName + "@open-metadata.org"; + 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. - org.openmetadata.service.jdbi3.TeamRepository teamRepository = - (org.openmetadata.service.jdbi3.TeamRepository) - Entity.getEntityRepository(Entity.TEAM); - org.openmetadata.schema.entity.teams.Team realTeam = - teamRepository.create( - null, - new org.openmetadata.schema.entity.teams.Team() - .withId(UUID.randomUUID()) - .withName("bot-strip-team-" + suffix) - .withTeamType(org.openmetadata.schema.api.teams.CreateTeam.TeamType.GROUP) - .withUpdatedBy("admin") - .withUpdatedAt(System.currentTimeMillis())); + 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 @@ -77,12 +77,11 @@ void addOrUpdateBotUserDoesNotStripTeams() throws Exception { User initialBot = UserUtil.user(botName, "open-metadata.org", botName) .withIsBot(true) - .withTeams(new java.util.ArrayList<>(List.of(realTeam.getEntityReference()))); - User stored = userRepository.create(null, initialBot); + .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")); + 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( @@ -90,22 +89,19 @@ void addOrUpdateBotUserDoesNotStripTeams() throws Exception { "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 UserUtil.addOrUpdateBotUser is called with - // on every OM boot — the in-memory User from configuration carries id/name/email and a - // few scalar fields, but never teams. - // Build the in-memory User the same way BotResource.initialize does on boot: - // UserUtil.user(name, domain, updatedBy).withIsBot(true). Note that the result does NOT - // have `teams` populated. + // 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 Organization team. With the - // bug present, this fails with teams=null (or empty), exactly matching the production logs - // we observed (fieldsDeleted=[teams: oldValue=[Organization], newValue=null]). - User afterBoot = - userRepository.getByName(null, botName, userRepository.getFields("teams")); + // 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, From 3c4a788d2553f175431ba565079e88ae9634be3b Mon Sep 17 00:00:00 2001 From: Joao Amaral <7281460+joaopamaral@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:00:40 -0300 Subject: [PATCH 3/5] fix(search): clamp kNN num_candidates to the Elasticsearch maximum of 10,000 Backport of upstream #35652 (fixes #35640) to 2.0.7. num_candidates was max(100, k * knnNumCandidatesMultiplier) with no upper bound, so any k above 10,000 / multiplier made Elasticsearch reject the kNN query and the vector search endpoint and the MCP semantic_search tool return 500. With a multiplier of 50 that is any k above 200, including the REST endpoint's default k of 1,000. Only the query builder and its tests are backported; the upstream schema description and generated UI types are unchanged here. Co-Authored-By: Claude Opus 5.5 --- .../vector/VectorSearchQueryBuilder.java | 8 ++- .../vector/VectorSearchQueryBuilderTest.java | 65 ++++++++++++++++++- 2 files changed, 68 insertions(+), 5 deletions(-) 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/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 From c6c03df107b5781f5bf2876aad8b3d535469ef40 Mon Sep 17 00:00:00 2001 From: Mostafa Abdelsalam Date: Wed, 4 Nov 2026 11:34:11 +0100 Subject: [PATCH 4/5] Fixes #36463: Fix find_context and company_context on Elasticsearch (#36548) AIContextFinder and CompanyContextTool read OpenSearchVectorService.getInstance(), which is only initialised when searchType is OpenSearch. On Elasticsearch it is always null, so find_context silently returned an empty result and company_context reported "Semantic search is not enabled" even with embeddings present. Read the backend-neutral SearchRepository.getVectorIndexService() instead, as SemanticSearchTool already does. On OpenSearch it returns the same OpenSearchVectorService instance as before. Co-authored-by: Pere Miquel Brull (cherry picked from commit 961fb5f9200d4159c266303fccd9e6f86406097b) Backport to 2.0.7: import-only conflict in AIContextFinder (2.0.7 has no MetricRepository import); AIContextFinderTest keeps the 2.0.7 tests and adds only the test this commit introduced. --- .../mcp/tools/CompanyContextTool.java | 6 +-- .../mcp/tools/CompanyContextToolTest.java | 43 ++++++++++++------- .../service/aicontext/AIContextFinder.java | 4 +- .../aicontext/AIContextFinderTest.java | 43 +++++++++++++++++++ 4 files changed, 75 insertions(+), 21 deletions(-) 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/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 = From e5f947a95785f1697bc3018558354b0199098d57 Mon Sep 17 00:00:00 2001 From: Joao Amaral <7281460+joaopamaral@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:03:59 -0300 Subject: [PATCH 5/5] Record user logins with a direct update instead of a JSON patch updateUserLastLoginTime applied a JSON patch through the full entity update path. lastLoginTime is excluded from change descriptions, so the patch produced no version, 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 `owns`, at one lookup per entity owned by the user's teams. For a user whose teams own ~300 assets that is ~2,600 queries and ~9 s per login, against ~150 queries and ~1 s for the first login of a session. Update the row with a single JSON_SET / jsonb_set statement, like lastActivityTime already does, and invalidate the entity cache entry so reads see the new value. Co-Authored-By: Claude Fable 5.1 --- .../service/jdbi3/CollectionDAO.java | 11 ++++++++++ .../service/jdbi3/UserRepository.java | 22 ++++++++++++++----- 2 files changed, 27 insertions(+), 6 deletions(-) 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