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 @@ -6366,9 +6366,14 @@ void test_upsertOfGatedFieldIsHeldForApproval(TestNamespace ns) throws Exception
.withName("upsertTerm")
.withGlossary(glossary.getFullyQualifiedName())
.withDescription(published));
// The term has a reviewer the creator is not, so the seeded glossary approval workflow moves
// it to In Review asynchronously. An upsert staged before that write lands is refused as a
// concurrent change; the term is quiet once it waits on that review.
awaitGlossaryTermStatus(client, term, EntityStatus.IN_REVIEW);

deployHookWorkflow(
client, "glossaryTerm", term.getFullyQualifiedName(), List.of("description"));
String hookWorkflowId =
deployHookWorkflow(
client, "glossaryTerm", term.getFullyQualifiedName(), List.of("description"));

// An upsert body carries no id; the stored term must be matched as the same asset.
client
Expand All @@ -6382,8 +6387,11 @@ void test_upsertOfGatedFieldIsHeldForApproval(TestNamespace ns) throws Exception
.withDescription("proposed via upsert"),
RequestOptions.builder().build());

awaitOpenApprovalTaskAssignedTo(
client, term.getFullyQualifiedName(), SharedEntities.get().USER1.getId());
// The seeded review also has a task for USER1, so only the gate's own task proves the hold.
Task gateTask =
awaitOpenApprovalTaskOf(
client, term.getFullyQualifiedName(), UUID.fromString(hookWorkflowId));
assertTrue(assigneeIds(gateTask).contains(SharedEntities.get().USER1.getId()));
assertEquals(
published, client.glossaryTerms().get(term.getId().toString(), "").getDescription());
JsonNode request = onlyChangeRequest(client, term.getId());
Expand Down Expand Up @@ -16223,6 +16231,18 @@ private static void awaitDomainStatus(
status, admin.domains().get(domain.getId().toString()).getEntityStatus()));
}

private static void awaitGlossaryTermStatus(
OpenMetadataClient admin, GlossaryTerm term, EntityStatus status) {
await("glossary term %s to reach %s".formatted(term.getName(), status))
.atMost(Duration.ofSeconds(60))
.pollInterval(Duration.ofSeconds(1))
.untilAsserted(
() ->
assertEquals(
status,
admin.glossaryTerms().get(term.getId().toString(), "").getEntityStatus()));
}

/** A lifecycle playbook whose only gate never opens, so whatever it enrols stays put. */
private static final String HOLDING_PLAYBOOK =
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,14 @@ private Task resolveWorkflowTask(
"Flowable runtime task for workflow-managed task '%s' is unavailable; retry the resolution",
taskId));
}
// Settle before anything is written to the workflow: process variables set on a runtime task
// Flowable cannot see yet are dropped without an error, so a task still not visible after the
// wait is refused while nothing has reached the workflow and a retry is safe.
if (!requiresRuntimeTaskReadiness
&& isRuntimeTaskStillBeingCommitted(workflowHandler, task)
&& !awaitActiveRuntimeTask(workflowHandler, taskId)) {
throw workflowStillPreparing(taskId);
}
if (ontologyReview) {
OntologyApprovalWorkflow.validateRuntime(task);
}
Expand Down Expand Up @@ -389,16 +397,19 @@ private Task resolveWorkflowTask(
// its runtime task has not finished creating it. Closing the task directly would leave the
// workflow waiting on a task nobody can resolve any more.
if (isWorkflowStillRunning(task)) {
throw TaskStateConflictException.of(
String.format(
"The workflow is still preparing task '%s'; retry the resolution", taskId));
throw workflowStillPreparing(taskId);
}
LOG.warn(
"[TaskWorkflowHandler] No active Flowable runtime task found for '{}'; applying direct task resolution fallback",
taskId);
return applyTaskResolution(
task, resolutionType, selectedTransition, newValue, resolvedPayload, comment, user);
}
// The variable lookup ran before the runtime task committed and nothing reached the
// workflow, so the caller can retry against the task that now exists.
if (namespacedVariables == null) {
throw workflowStillPreparing(taskId);
}
throw TaskStateConflictException.of(
String.format(
"Workflow resolution failed for task '%s' on transition '%s'",
Expand Down Expand Up @@ -1476,6 +1487,20 @@ public boolean supportsMultiApproval(Task task) {
return WorkflowHandler.getInstance().hasMultiApprovalSupport(task.getId());
}

// CreateTask commits the task row on its own connection before the workflow command that
// creates the runtime task commits, so a caller can list the task and resolve it in between.
private static boolean isRuntimeTaskStillBeingCommitted(
WorkflowHandler workflowHandler, Task task) {
return !TaskRepository.isTerminalStatus(task.getStatus())
&& !workflowHandler.hasActiveRuntimeTask(task.getId())
&& isWorkflowStillRunning(task);
}

private static TaskStateConflictException workflowStillPreparing(UUID taskId) {
return TaskStateConflictException.of(
String.format("The workflow is still preparing task '%s'; retry the resolution", taskId));
}

private static boolean isWorkflowStillRunning(Task task) {
return task.getWorkflowInstanceId() != null
&& ((WorkflowInstanceRepository)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
Expand Down Expand Up @@ -459,6 +460,144 @@ void testRunningWorkflowRefusesToCloseATaskItHasNotFinishedCreating() {
}
}

@Test
void testResolveWaitsForTheRuntimeTaskItsRunningWorkflowIsStillCommitting() {
UUID taskId = UUID.randomUUID();
UUID instanceId = UUID.randomUUID();
Task task =
new Task()
.withId(taskId)
.withWorkflowInstanceId(instanceId)
.withStatus(TaskEntityStatus.Open)
.withType(TaskEntityType.RequestApproval);
Task refreshedTask = new Task().withId(taskId).withStatus(TaskEntityStatus.Open);
EntityUtil.Fields fields = new EntityUtil.Fields(Set.of("about"));
// The task row is listed before Flowable commits the runtime task: the first lookup misses
// and every lookup after the commit finds it.
AtomicInteger flowableLookups = new AtomicInteger();

WorkflowHandler workflowHandler = mock(WorkflowHandler.class);
TaskRepository taskRepository = mock(TaskRepository.class);
WorkflowInstanceRepository instances = mock(WorkflowInstanceRepository.class);

try (MockedStatic<WorkflowHandler> workflowMock = Mockito.mockStatic(WorkflowHandler.class);
MockedStatic<Entity> entityMock = Mockito.mockStatic(Entity.class)) {
workflowMock.when(WorkflowHandler::getInstance).thenReturn(workflowHandler);
when(workflowHandler.hasActiveRuntimeTask(taskId))
.thenAnswer(invocation -> flowableLookups.incrementAndGet() > 1);
when(workflowHandler.transformToNodeVariables(eq(taskId), any()))
.thenAnswer(
invocation ->
flowableLookups.incrementAndGet() > 1 ? invocation.getArgument(1) : null);
when(workflowHandler.resolveTask(eq(taskId), any())).thenReturn(true);
when(workflowHandler.isAwaitingAdditionalVotes(taskId)).thenReturn(true);
entityMock.when(() -> Entity.getEntityRepository(Entity.TASK)).thenReturn(taskRepository);
entityMock
.when(() -> Entity.getEntityTimeSeriesRepository(Entity.WORKFLOW_INSTANCE))
.thenReturn(instances);
when(instances.isRunning(instanceId)).thenReturn(true);
when(taskRepository.getFields(anyString())).thenReturn(fields);
when(taskRepository.get(isNull(), eq(taskId), eq(fields))).thenReturn(refreshedTask);

Task result =
new TaskWorkflowHandler(3, 0)
.resolveTask(task, "approve", TaskResolutionType.Approved, null, null, null, "alice");

assertSame(refreshedTask, result);
verify(workflowHandler).resolveTask(eq(taskId), any());
}
}

@Test
void testRejectionIsNotWrittenToARuntimeTaskThatNeverBecameVisible() {
UUID taskId = UUID.randomUUID();
UUID instanceId = UUID.randomUUID();
Task task =
new Task()
.withId(taskId)
.withWorkflowInstanceId(instanceId)
.withStatus(TaskEntityStatus.Open)
.withType(TaskEntityType.RequestApproval);

WorkflowHandler workflowHandler = mock(WorkflowHandler.class);
TaskRepository taskRepository = mock(TaskRepository.class);
WorkflowInstanceRepository instances = mock(WorkflowInstanceRepository.class);

try (MockedStatic<WorkflowHandler> workflowMock = Mockito.mockStatic(WorkflowHandler.class);
MockedStatic<Entity> entityMock = Mockito.mockStatic(Entity.class)) {
workflowMock.when(WorkflowHandler::getInstance).thenReturn(workflowHandler);
when(workflowHandler.hasActiveRuntimeTask(taskId)).thenReturn(false);
entityMock.when(() -> Entity.getEntityRepository(Entity.TASK)).thenReturn(taskRepository);
entityMock
.when(() -> Entity.getEntityTimeSeriesRepository(Entity.WORKFLOW_INSTANCE))
.thenReturn(instances);
when(instances.isRunning(instanceId)).thenReturn(true);

TaskStateConflictException exception =
assertThrows(
TaskStateConflictException.class,
() ->
new TaskWorkflowHandler(3, 0)
.resolveTask(
task,
"reject",
TaskResolutionType.Rejected,
null,
null,
"Missing definition details",
"alice"));

// Flowable drops variables set on a runtime task it cannot see, so a rejection reason
// written now would be lost if the task committed before the resolve reached it.
assertTrue(exception.getMessage().contains("still preparing"));
verify(workflowHandler, never()).setProcessVariable(any(), anyString(), any());
verify(workflowHandler, never()).transformToNodeVariables(any(), any());
}
}

@Test
void testRuntimeTaskAppearingAfterAMissedLookupAsksTheCallerToRetry() {
UUID taskId = UUID.randomUUID();
UUID instanceId = UUID.randomUUID();
Task task =
new Task()
.withId(taskId)
.withWorkflowInstanceId(instanceId)
.withStatus(TaskEntityStatus.Open)
.withType(TaskEntityType.RequestApproval);

WorkflowHandler workflowHandler = mock(WorkflowHandler.class);
TaskRepository taskRepository = mock(TaskRepository.class);
WorkflowInstanceRepository instances = mock(WorkflowInstanceRepository.class);

try (MockedStatic<WorkflowHandler> workflowMock = Mockito.mockStatic(WorkflowHandler.class);
MockedStatic<Entity> entityMock = Mockito.mockStatic(Entity.class)) {
workflowMock.when(WorkflowHandler::getInstance).thenReturn(workflowHandler);
// The variable lookup ran before Flowable committed; the runtime task is visible by the time
// the failure is classified. Nothing reached the workflow, so the caller can safely retry.
when(workflowHandler.transformToNodeVariables(eq(taskId), any())).thenReturn(null);
when(workflowHandler.hasActiveRuntimeTask(taskId)).thenReturn(true);
entityMock.when(() -> Entity.getEntityRepository(Entity.TASK)).thenReturn(taskRepository);
entityMock
.when(() -> Entity.getEntityTimeSeriesRepository(Entity.WORKFLOW_INSTANCE))
.thenReturn(instances);
when(instances.isRunning(instanceId)).thenReturn(true);

TaskStateConflictException exception =
assertThrows(
TaskStateConflictException.class,
() ->
new TaskWorkflowHandler(1, 0)
.resolveTask(
task, "approve", TaskResolutionType.Approved, null, null, null, "alice"));

assertTrue(exception.getMessage().contains("still preparing"));
verify(workflowHandler, never()).resolveTask(any(), any());
verify(taskRepository, never())
.resolveTask(any(), any(TaskResolution.class), any(), anyString());
}
}

@Test
void testNonMetricWorkflowPreservesDirectResolutionFallback() {
UUID taskId = UUID.randomUUID();
Expand Down
Loading