Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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<EntityReference> 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<EntityReference> 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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -165,7 +165,7 @@ private static void putIfPresent(Map<String, Object> pill, String key, Object va
private static Map<String, Object> runSearch(
String query, Map<String, Object> params, CatalogSecurityContext securityContext) {
Map<String, Object> result;
OpenSearchVectorService vectorService = OpenSearchVectorService.getInstance();
VectorIndexService vectorService = Entity.getSearchRepository().getVectorIndexService();
if (!Entity.getSearchRepository().isVectorEmbeddingEnabled() || vectorService == null) {
result =
errorResponse(
Expand All @@ -178,7 +178,7 @@ private static Map<String, Object> runSearch(
}

private static Map<String, Object> search(
OpenSearchVectorService vectorService,
VectorIndexService vectorService,
String query,
Map<String, Object> params,
CatalogSecurityContext securityContext) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String, Object> params = new HashMap<>();
params.put("query", "refund policy");
Map<String, Object> 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<OpenSearchVectorService> vectorMock =
mockStatic(OpenSearchVectorService.class);
MockedStatic<DefaultAuthorizer> authorizerMock = mockStatic(DefaultAuthorizer.class)) {
vectorMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService);
try (MockedStatic<DefaultAuthorizer> authorizerMock = mockStatic(DefaultAuthorizer.class)) {
authorizerMock
.when(() -> DefaultAuthorizer.getSubjectContext(any()))
.thenReturn(mock(SubjectContext.class));
Expand Down Expand Up @@ -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<OpenSearchVectorService> vectorMock =
mockStatic(OpenSearchVectorService.class);
MockedStatic<DefaultAuthorizer> authorizerMock = mockStatic(DefaultAuthorizer.class)) {
vectorMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService);
try (MockedStatic<DefaultAuthorizer> authorizerMock = mockStatic(DefaultAuthorizer.class)) {
authorizerMock
.when(() -> DefaultAuthorizer.getSubjectContext(securityContext))
.thenReturn(mock(SubjectContext.class));
Expand Down Expand Up @@ -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<OpenSearchVectorService> vectorMock =
mockStatic(OpenSearchVectorService.class);
MockedStatic<DefaultAuthorizer> authorizerMock = mockStatic(DefaultAuthorizer.class)) {
vectorMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService);
try (MockedStatic<DefaultAuthorizer> authorizerMock = mockStatic(DefaultAuthorizer.class)) {
authorizerMock
.when(() -> DefaultAuthorizer.getSubjectContext(securityContext))
.thenReturn(subjectContext);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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', "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -305,12 +304,23 @@ public void storeEntities(List<User> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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\":")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,19 @@ public static boolean assignTeamsFromClaim(User user, List<String> 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
Expand Down Expand Up @@ -364,8 +377,12 @@ private static User retrieveWithAuthMechanism(User user) {
EntityRepository<User> 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;
Expand Down
Loading
Loading