Skip to content
Merged
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
Expand Up @@ -38,6 +38,8 @@
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.api.parallel.ResourceAccessMode;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.openmetadata.it.factories.APIServiceTestFactory;
Expand Down Expand Up @@ -129,6 +131,9 @@
*/
@Execution(ExecutionMode.CONCURRENT)
@ExtendWith(TestNamespaceExtension.class)
// Moving an asset replaces its domain only while "Multiple Domains are not allowed" is on; tests
// that switch the rule off hold this lock exclusively.
@ResourceLock(value = "MULTI_DOMAIN_RULE", mode = ResourceAccessMode.READ)
public class AssetsTabVersioningIT {

private static final String ACTING_USER = "shared_user1";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7778,8 +7778,13 @@ private HistoryWalk walkForward(
String after = null;
do {
JsonNode result = readHistoryPage(client, basePath, startTs, endTs, limit, "after", after);
pages.add(versionKeys(result));
lastPageBeforeCursor = cursor(result, "before");
List<String> page = versionKeys(result);
// A concurrent test can hard-delete the row that made the previous page report more,
// leaving this page empty and cursorless. The walk then ends on the last page with rows.
if (!page.isEmpty()) {
pages.add(page);
lastPageBeforeCursor = cursor(result, "before");
}
after = cursor(result, "after");
} while (after != null);
return new HistoryWalk(pages, lastPageBeforeCursor);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -917,9 +917,10 @@ private void verifyAssetsInDomainSearch(
private void verifyAssetsInDomainAssetsEndpoint(
OpenMetadataClient client, Domain domain, List<Table> expectedTables, boolean shouldExist)
throws Exception {
// Use Awaitility to poll for the expected state since search index updates are async
// The asset domains are rewritten in search during the request; when the cluster rejects that
// update under load, the search retry queue repairs the documents about half a minute later.
Awaitility.await()
.atMost(30, TimeUnit.SECONDS)
.atMost(60, TimeUnit.SECONDS)
.pollInterval(2, TimeUnit.SECONDS)
.untilAsserted(
() -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.net.URLEncoder;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Stream;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openmetadata.it.factories.UserTestFactory;
Expand Down Expand Up @@ -152,20 +154,25 @@ private static JsonNode asObject(final JsonNode node) {
return node.isTextual() ? JsonUtils.readTree(node.asText()) : node;
}

// Change events are written asynchronously once the response is sent (EventFilter), so the
// bot's event can land after the update returns.
private static JsonNode storedEventOf(final UUID userId, final long since) {
return Awaitility.await("The bot's update must be recorded as a change event")
.atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofMillis(250))
.until(() -> latestEventOf(userId, since), Optional::isPresent)
.get();
}

private static Optional<JsonNode> latestEventOf(final UUID userId, final long since) {
final List<JsonNode> events =
allRows(
SdkClients.adminClient().getHttpClient(),
"/v1/events?entityUpdated=user&limit=1000&timestamp="
+ since
+ "&endTs="
+ System.currentTimeMillis());
final Optional<JsonNode> found =
events.stream()
.filter(event -> userId.toString().equals(event.path("entityId").asText()))
.reduce((first, last) -> last);
assertTrue(found.isPresent(), "The bot's update must be recorded as a change event");
return found.get();
"/v1/events?entityUpdated=user&limit=1000&timestamp=%d&endTs=%d"
.formatted(since, System.currentTimeMillis()));
return events.stream()
.filter(event -> userId.toString().equals(event.path("entityId").asText()))
.reduce((first, last) -> last);
}

// Every row of a bounded window, following the cursor: other tests write to the same endpoints,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -705,12 +705,22 @@ private static JsonNode statusOf(JsonNode statuses, Persona target) {
}

@Test
void aiContextStatusPagesWithTheSameCursorAsThePersonaList() throws Exception {
void aiContextStatusPagesWithTheSameCursorAsThePersonaList() {
// The two lists are read one after the other, and a sibling test in the parallel lane may
// create or delete a persona in between; compare them again until both reads see one state.
Awaitility.await("status pages like the persona list")
.atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofSeconds(1))
.untilAsserted(this::assertStatusPagesLikeThePersonaList);
}

private void assertStatusPagesLikeThePersonaList() throws Exception {
JsonNode statusPage =
OBJECT_MAPPER.readTree(getResponse("personas/aiContext/status?limit=1", authToken).body());
JsonNode personaPage =
OBJECT_MAPPER.readTree(getResponse("personas?limit=1", authToken).body());
assertThat(statusPage.path("data")).hasSize(1);
assertThat(personaPage.path("data")).hasSize(1);
assertThat(statusPage.path("data").get(0).path("personaId").asText())
.isEqualTo(personaPage.path("data").get(0).path("id").asText());
assertThat(statusPage.path("paging").path("total").asInt())
Expand All @@ -725,6 +735,7 @@ void aiContextStatusPagesWithTheSameCursorAsThePersonaList() throws Exception {
JsonNode nextPersona =
OBJECT_MAPPER.readTree(getResponse("personas?limit=1&after=" + after, authToken).body());
assertThat(nextStatus.path("data")).hasSize(1);
assertThat(nextPersona.path("data")).hasSize(1);
assertThat(nextStatus.path("data").get(0).path("personaId").asText())
.isEqualTo(nextPersona.path("data").get(0).path("id").asText());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,36 @@ public static ChannelResolution of(SubscriptionDestination destination) {
String named = destination.getChannel();
String channelId = named == null ? destination.getType().value() : named;
ChannelResolution resolution = new ChannelResolution(channelId, Channels.of(channelId));
logOnce(destination, resolution, named == null ? "its type" : "its channel field");
logResolution(destination, resolution, named == null ? "its type" : "its channel field");
return resolution;
}

private static void logOnce(
private static void logResolution(
SubscriptionDestination destination, ChannelResolution resolution, String resolvedBy) {
if (resolution.channel().isEmpty()) {
warnUnregistered(destination, resolution, resolvedBy);
} else {
// Resolution runs on every save and read of every destination; at INFO a large alert
// floods the log, so only an unregistered channel, which needs action, is worth a warning.
LOG.debug(
"Destination {} is served by channel {} (resolved by {})",
destination.getId(),
resolution.channelId(),
resolvedBy);
}
}

private static void warnUnregistered(
SubscriptionDestination destination, ChannelResolution resolution, String resolvedBy) {
if (LOGGED.size() >= REMEMBERED_DESTINATIONS) {
LOGGED.clear();
}
if (LOGGED.add(destination.getId() + ":" + resolution.channelId())) {
LOG.info(
"Destination {} is served by channel {} (resolved by {}, registered: {})",
LOG.warn(
"Destination {} names channel {} (resolved by {}), which is not registered on this server",
destination.getId(),
resolution.channelId(),
resolvedBy,
resolution.channel().isPresent());
resolvedBy);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,7 @@ public static boolean attachTask(
repository.executeInTransaction(
() -> {
ChangeRequest locked = lockForUpdate(repository, snapshot);
boolean current =
isOpen(locked)
&& Objects.equals(locked.getActiveRevisionNumber(), revisionNumber);
boolean current = reviewsActiveRevision(locked, revisionNumber);
if (current) {
dao()
.changeRequestDAO()
Expand All @@ -251,6 +249,16 @@ public static boolean attachTask(
return reviewable;
}

/** Whether {@code revisionNumber} is still the active revision of an open request. */
public static boolean isActiveRevision(UUID changeRequestId, int revisionNumber) {
ChangeRequest request = dao().changeRequestDAO().findById(changeRequestId);
return request != null && reviewsActiveRevision(request, revisionNumber);
}

static boolean reviewsActiveRevision(ChangeRequest request, int revisionNumber) {
return isOpen(request) && Objects.equals(request.getActiveRevisionNumber(), revisionNumber);
}

/**
* The open review task of a pending request in workflow run {@code workflowInstanceId}, if any.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -790,7 +790,7 @@ private Task createOrUpdateTask(
return task;
}

private void supersedePriorApprovalTask(
void supersedePriorApprovalTask(
DelegateTask delegateTask,
TaskRepository taskRepository,
EntityInterface<?> entity,
Expand All @@ -807,9 +807,12 @@ private void supersedePriorApprovalTask(
// reviews survive. Every other run keeps the entity-level supersede (requesterToMatch =
// null).
String requesterToMatch = reviewsChangeRequest(delegateTask) ? updatedBy : null;
taskRepository
.listNonTerminalTasksByEntityAndCategory(entity.getFullyQualifiedName(), taskCategory)
.stream()
List<Task> priors =
reviewsStaleRevision(delegateTask)
? List.of()
: taskRepository.listNonTerminalTasksByEntityAndCategory(
entity.getFullyQualifiedName(), taskCategory);
priors.stream()
.filter(
prior ->
isSupersedablePriorApprovalTask(
Expand Down Expand Up @@ -1239,6 +1242,17 @@ private static Object linkChangeRequest(Object payload, DelegateTask delegateTas
}

// Whether this run reviews a change request: such a run carries the request in its variables.
// A change request's runs can finish out of order. The run of a revision the request has since
// replaced must leave the newer revision's live review alone; attachTask then closes its own
// task.
static boolean reviewsStaleRevision(DelegateTask delegateTask) {
return ChangeRequestRun.from(new WorkflowVariableHandler(delegateTask))
.filter(
run ->
!ChangeRequestService.isActiveRevision(run.changeRequestId(), run.revisionNumber()))
.isPresent();
}

private static boolean reviewsChangeRequest(DelegateTask delegateTask) {
return ChangeRequestRun.from(new WorkflowVariableHandler(delegateTask)).isPresent();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
Expand All @@ -43,12 +46,14 @@
import org.openmetadata.schema.type.DataAccessRequestPayload;
import org.openmetadata.schema.type.EntityReference;
import org.openmetadata.schema.type.Include;
import org.openmetadata.schema.type.TaskCategory;
import org.openmetadata.schema.type.TaskEntityStatus;
import org.openmetadata.schema.type.TaskEntityType;
import org.openmetadata.schema.type.TaskResolution;
import org.openmetadata.schema.type.TaskResolutionType;
import org.openmetadata.service.Entity;
import org.openmetadata.service.exception.EntityNotFoundException;
import org.openmetadata.service.governance.approval.ChangeRequestService;
import org.openmetadata.service.jdbi3.TaskRepository;
import org.openmetadata.service.jdbi3.WorkflowInstanceRepository;

Expand Down Expand Up @@ -997,6 +1002,72 @@ void testIsSupersedableWhenRequesterMatches() {
priorByKaran, workflowDefinitionId, UUID.randomUUID(), "karan"));
}

// ---- reviewsStaleRevision ----

@Test
void testRunOfAReplacedRevisionReviewsAStaleRevision() {
// Revision 2's run created its task first; revision 1's run finishes last and must not
// supersede it.
DelegateTask delegateTask = changeRequestRun();
try (MockedStatic<ChangeRequestService> requests = mockStatic(ChangeRequestService.class)) {
requests.when(() -> ChangeRequestService.isActiveRevision(any(), eq(1))).thenReturn(false);

assertTrue(CreateTask.reviewsStaleRevision(delegateTask));
}
}

@Test
void testRunOfTheActiveRevisionIsNotStale() {
DelegateTask delegateTask = changeRequestRun();
try (MockedStatic<ChangeRequestService> requests = mockStatic(ChangeRequestService.class)) {
requests.when(() -> ChangeRequestService.isActiveRevision(any(), eq(1))).thenReturn(true);

assertFalse(CreateTask.reviewsStaleRevision(delegateTask));
}
}

@Test
void testRunOfAReplacedRevisionLeavesTheLiveReviewAlone() {
TaskRepository taskRepository = Mockito.mock(TaskRepository.class);
try (MockedStatic<ChangeRequestService> requests = mockStatic(ChangeRequestService.class)) {
requests.when(() -> ChangeRequestService.isActiveRevision(any(), eq(1))).thenReturn(false);

supersedeFor(changeRequestRun(), taskRepository);
}

verify(taskRepository, never()).listNonTerminalTasksByEntityAndCategory(any(), any());
}

@Test
void testRunOfTheActiveRevisionSupersedesTheRequestersPriorReview() {
TaskRepository taskRepository = Mockito.mock(TaskRepository.class);
try (MockedStatic<ChangeRequestService> requests = mockStatic(ChangeRequestService.class)) {
requests.when(() -> ChangeRequestService.isActiveRevision(any(), eq(1))).thenReturn(true);

supersedeFor(changeRequestRun(), taskRepository);
}

verify(taskRepository)
.listNonTerminalTasksByEntityAndCategory("glossary", TaskCategory.Approval);
}

private static void supersedeFor(DelegateTask delegateTask, TaskRepository taskRepository) {
new CreateTask()
.supersedePriorApprovalTask(
delegateTask,
taskRepository,
new Glossary().withFullyQualifiedName("glossary"),
TaskCategory.Approval,
UUID.randomUUID(),
UUID.randomUUID(),
"karan");
}

@Test
void testRunWithoutAChangeRequestIsNeverStale() {
assertFalse(CreateTask.reviewsStaleRevision(Mockito.mock(DelegateTask.class)));
}

// ---- resolveRequester ----

@Test
Expand Down
Loading