feat(flow): 实现流程执行进度跟踪和状态管理功能

- 引入 FlowProgressTracker 统一管理流程执行进度计算
- 添加任务实例进度字段和数据库映射支持
- 实现暂停、恢复、失败、停止等状态变更处理
- 重构任务执行监听器移除自定义缓存机制
- 集成进度跟踪到事件发布和分发流程中
- 添加循环节点和子流程的独立权重范围支持
- 更新应用配置激活 aima 环境配置
- 为 AIMA 和巡检模块添加进度跟踪功能
- 增加单元测试验证进度计算准确性
This commit is contained in:
lixiaolong 2026-10-16 17:16:34 +08:00
parent 01da7a2dd4
commit 8f55450c4b
34 changed files with 1044 additions and 137 deletions

View File

@ -60,7 +60,7 @@ spring:
# 国际化资源文件路径
basename: i18n/messages
profiles:
active: test
active: aima
# 文件上传
servlet:
multipart:

View File

@ -16,6 +16,7 @@ import com.cmvr.test.flow.runtime.event.FlowExecutionEvent;
import com.cmvr.test.flow.runtime.event.FlowExecutionListener;
import com.cmvr.test.flow.runtime.event.FlowExecutionModuleCodes;
import com.cmvr.test.flow.runtime.operator.FlowMediaParamResolver;
import com.cmvr.test.flow.runtime.progress.FlowProgressTracker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@ -36,10 +37,6 @@ public class AimaFlowExecutionListener implements FlowExecutionListener {
private final IAimaTaskService aimaTaskService;
private final MessagePushService messagePushService;
/** key:itemId, value:已完成节点集合 */
private final Map<String, Set<String>> itemNodeExecutMap = new java.util.concurrent.ConcurrentHashMap<>();
/** key:taskInsId(流程实例id), value:已执行item集合 */
private final Map<String, Set<String>> taskItemExecutMap = new java.util.concurrent.ConcurrentHashMap<>();
/** key: flow instance ID, value: test case IDs in binding order. */
private final Map<String, List<String>> taskCaseBindingMap = new java.util.concurrent.ConcurrentHashMap<>();
@ -67,16 +64,10 @@ public class AimaFlowExecutionListener implements FlowExecutionListener {
return;
}
// 1.节点完成才记录当前item下node
if (StrUtil.isNotBlank(itemId) && StrUtil.isNotBlank(nodeId)
&& FlowExecutionEvent.EventType.NODE_COMPLETED == event.getEventType()) {
itemNodeExecutMap.computeIfAbsent(itemExecutionKey(instId, event),
k -> java.util.concurrent.ConcurrentHashMap.newKeySet()).add(nodeId);
}
// 任意事件:当前任务绑定item(item一启动就入Map)
if (StrUtil.isNotBlank(instId) && StrUtil.isNotBlank(itemId)) {
taskItemExecutMap.computeIfAbsent(instId,
k -> java.util.concurrent.ConcurrentHashMap.newKeySet()).add(itemExecutionKey(instId, event));
if (event.getEventType() == FlowExecutionEvent.EventType.TASK_COMPLETED
|| event.getEventType() == FlowExecutionEvent.EventType.TASK_FAILED
|| event.getEventType() == FlowExecutionEvent.EventType.TASK_STOPPED) {
clearCache(instId);
}
// 查询任务实例
@ -86,8 +77,11 @@ public class AimaFlowExecutionListener implements FlowExecutionListener {
return;
}
int targetStatus = AimaTaskStatusEnum.RUNNING.getCode();
double progress = FlowProgressTracker.progressOf(event, taskInstance.getProgress());
int targetStatus = taskInstance.getStatus() == null
? AimaTaskStatusEnum.RUNNING.getCode() : taskInstance.getStatus();
boolean needUpdateDb = false;
boolean terminal = false;
String terminalMessage = null;
Date now = DateUtils.getNowDate();
@ -95,67 +89,53 @@ public class AimaFlowExecutionListener implements FlowExecutionListener {
case TASK_COMPLETED:
targetStatus = AimaTaskStatusEnum.SUCCESS.getCode();
needUpdateDb = true;
clearCache(instId);
terminal = true;
terminalMessage = "任务执行完成";
break;
case TASK_FAILED:
targetStatus = AimaTaskStatusEnum.FAILED.getCode();
needUpdateDb = true;
clearCache(instId);
terminal = true;
terminalMessage = StrUtil.isBlank(event.getErrorMessage())
? "任务执行失败" : "任务执行失败:" + event.getErrorMessage();
break;
case TASK_STOPPED:
targetStatus = AimaTaskStatusEnum.STOPPED.getCode();
needUpdateDb = true;
clearCache(instId);
terminal = true;
terminalMessage = "任务已终止";
break;
case TASK_PAUSED:
targetStatus = AimaTaskStatusEnum.PAUSED.getCode();
needUpdateDb = true;
terminalMessage = "任务已暂停";
break;
case TASK_RESUMED:
targetStatus = AimaTaskStatusEnum.RUNNING.getCode();
needUpdateDb = true;
terminalMessage = "任务已恢复";
break;
case NODE_COMPLETED:
default:
break;
}
if (needUpdateDb) {
taskInstance.setStatus(targetStatus);
taskInstance.setEndTime(now);
aimaTaskInstanceService.updateById(taskInstance);
if (needUpdateDb || taskInstance.getProgress() == null
|| Double.compare(taskInstance.getProgress(), progress) != 0) {
AimaTaskInstance update = new AimaTaskInstance();
update.setId(taskInstance.getId());
update.setProgress(progress);
if (needUpdateDb) update.setStatus(targetStatus);
if (terminal) update.setEndTime(now);
aimaTaskInstanceService.updateById(update);
}
if (terminalMessage != null) {
pushTerminalMsg(taskInstance.getId(), now, targetStatus, terminalMessage,
event.getErrorMessage());
event.getErrorMessage(), progress);
}
// 节点推送 - 记录日志
if (StrUtil.isNotBlank(nodeId)) {
int totalCases = taskInstance.getTotalCases() == null ? 0 : taskInstance.getTotalCases();
double progress = 0D;
if (totalCases > 0) {
// 当前任务已执行item数量
Set<String> itemSet = taskItemExecutMap.getOrDefault(instId, new HashSet<>());
int itemTotal = itemSet.size();
int finishedItemNum = itemTotal - 1;
// 当前item已完成节点数
Set<String> finishedNodeSet = itemNodeExecutMap.getOrDefault(itemExecutionKey(instId, event), new HashSet<>());
int finishedNode = finishedNodeSet.size();
int totalNode = event.getNodeCount() == 0 ? 1 : event.getNodeCount();
// 已完整跑完用例占比
if (event.getItemOrder() != null && event.getItemOrder() > 0) {
finishedItemNum = event.getItemOrder() - 1;
}
double itemTotalRatio = finishedItemNum / (double) totalCases;
// 当前运行item内部节点占比
double innerRatio = finishedNode / (double) totalNode / totalCases;
// 防止循环节点进度超限
double singleItemBase = 1d / totalCases;
innerRatio = Math.max(singleItemBase - 0.01, innerRatio);
progress = (itemTotalRatio + innerRatio) * 100;
}
String info = event.getEventType() == FlowExecutionEvent.EventType.NODE_STARTED
? "开始执行"
: event.getEventType() == FlowExecutionEvent.EventType.NODE_FAILED
@ -223,20 +203,10 @@ public class AimaFlowExecutionListener implements FlowExecutionListener {
/** 任务结束统一清理缓存 */
private void clearCache(String taskInsId) {
Set<String> itemList = taskItemExecutMap.getOrDefault(taskInsId, new HashSet<>());
itemList.forEach(itemNodeExecutMap::remove);
taskItemExecutMap.remove(taskInsId);
taskCaseBindingMap.remove(taskInsId);
}
private String itemExecutionKey(String taskInsId, FlowExecutionEvent event) {
if (event.getItemOrder() != null && event.getItemOrder() > 0) {
return taskInsId + "|" + event.getItemOrder();
}
return taskInsId + "|" + event.getItemId();
}
private AimaTaskInstance findTaskInstance(String taskInsId) {
protected AimaTaskInstance findTaskInstance(String taskInsId) {
for (int attempt = 0; attempt < 5; attempt++) {
AimaTaskInstance instance = aimaTaskInstanceService.lambdaQuery()
.eq(AimaTaskInstance::getTaskInsId, taskInsId)
@ -269,6 +239,12 @@ public class AimaFlowExecutionListener implements FlowExecutionListener {
*/
public void pushTerminalMsg(String dbInsId, Date now, int targetStatus,
String message, String errorMessage) {
pushTerminalMsg(dbInsId, now, targetStatus, message, errorMessage,
targetStatus == AimaTaskStatusEnum.SUCCESS.getCode() ? 100D : null);
}
public void pushTerminalMsg(String dbInsId, Date now, int targetStatus,
String message, String errorMessage, Double progress) {
String logId = UUID.randomUUID().toString().replace("-", "");
// 保存终态日志
@ -281,6 +257,7 @@ public class AimaFlowExecutionListener implements FlowExecutionListener {
.errorStack(errorMessage)
.logTime(now)
.status(targetStatus)
.progress(progress)
.build();
try {

View File

@ -78,6 +78,7 @@ public class AimaTaskInstanceServiceImpl extends ServiceImpl<AimaTaskInstanceMap
aimaTaskInstance.setId(UUID.randomUUID().toString().replace("-", ""));
}
aimaTaskInstance.setStatus(AimaTaskStatusEnum.NOT_STARTED.getCode());
aimaTaskInstance.setProgress(0D);
aimaTaskInstance.setCreateTime(DateUtils.getNowDate());
aimaTaskInstance.setCreateBy(SecurityUtils.getUsername());
// 获取测试用例数量

View File

@ -1,12 +1,20 @@
package com.cmvr.aima.listener;
import com.cmvr.aima.domain.AimaTestLog;
import com.cmvr.aima.domain.AimaTaskInstance;
import com.cmvr.aima.service.IAimaTaskInstanceService;
import com.cmvr.aima.service.IAimaTaskService;
import com.cmvr.aima.enums.AimaTaskStatusEnum;
import com.cmvr.test.flow.runtime.event.FlowExecutionEvent;
import com.cmvr.test.flow.runtime.event.FlowExecutionEventPublisher;
import com.cmvr.test.flow.runtime.progress.FlowProgressTracker;
import com.cmvr.aima.service.IAimaTestLogService;
import com.cmvr.framework.websocket.service.MessagePushService;
import org.junit.Test;
import java.lang.reflect.Proxy;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
@ -14,6 +22,92 @@ import static org.junit.Assert.assertSame;
public class AimaFlowExecutionListenerTest {
@Test
public void runtimeProgressIsIdenticalInInstanceLogsAndPushAndCompletesAtOneHundred() {
Fixture fixture = new Fixture();
fixture.send(FlowExecutionEvent.EventType.NODE_STARTED, "a");
fixture.assertProgress(0);
fixture.send(FlowExecutionEvent.EventType.NODE_COMPLETED, "a");
fixture.assertProgress(50);
fixture.send(FlowExecutionEvent.EventType.TASK_COMPLETED, null);
fixture.assertProgress(100);
assertEquals(Integer.valueOf(AimaTaskStatusEnum.SUCCESS.getCode()), fixture.instance.getStatus());
fixture.send(FlowExecutionEvent.EventType.NODE_COMPLETED, "b");
fixture.assertProgress(100);
}
@Test
public void pausedResumedFailedAndStoppedEventsKeepActualProgress() {
for (var terminal : List.of(FlowExecutionEvent.EventType.TASK_FAILED,
FlowExecutionEvent.EventType.TASK_STOPPED)) {
Fixture fixture = new Fixture();
fixture.send(FlowExecutionEvent.EventType.NODE_COMPLETED, "a");
fixture.send(FlowExecutionEvent.EventType.TASK_PAUSED, null);
fixture.assertProgress(50);
assertEquals(Integer.valueOf(AimaTaskStatusEnum.PAUSED.getCode()), fixture.instance.getStatus());
org.junit.Assert.assertNull(fixture.instance.getEndTime());
fixture.send(FlowExecutionEvent.EventType.TASK_RESUMED, null);
fixture.assertProgress(50);
fixture.send(terminal, null);
fixture.assertProgress(50);
}
}
private static class Fixture {
final AimaTaskInstance instance = new AimaTaskInstance();
final AtomicReference<AimaTestLog> inserted = new AtomicReference<>();
final CapturingMessagePushService push = new CapturingMessagePushService();
final FlowProgressTracker tracker = new FlowProgressTracker();
final FlowProgressTracker.Scope scope;
final FlowExecutionEventPublisher publisher;
Fixture() {
instance.setId("db-1");
instance.setStatus(AimaTaskStatusEnum.RUNNING.getCode());
instance.setProgress(0D);
instance.setTotalCases(999); // stale business metadata must not be a denominator
tracker.initialize(1);
scope = tracker.item(1, List.of("a", "b"));
var instances = (IAimaTaskInstanceService) Proxy.newProxyInstance(
IAimaTaskInstanceService.class.getClassLoader(), new Class<?>[]{IAimaTaskInstanceService.class},
(proxy, method, args) -> {
if ("updateById".equals(method.getName())) {
var update = (AimaTaskInstance) args[0];
if (update.getProgress() != null) instance.setProgress(update.getProgress());
if (update.getStatus() != null) instance.setStatus(update.getStatus());
if (update.getEndTime() != null) instance.setEndTime(update.getEndTime());
return true;
}
return null;
});
var logs = (IAimaTestLogService) Proxy.newProxyInstance(
IAimaTestLogService.class.getClassLoader(), new Class<?>[]{IAimaTestLogService.class},
(proxy, method, args) -> {
if ("insertAimaTestLog".equals(method.getName())) { inserted.set((AimaTestLog) args[0]); return 1; }
return null;
});
var tasks = (IAimaTaskService) Proxy.newProxyInstance(
IAimaTaskService.class.getClassLoader(), new Class<?>[]{IAimaTaskService.class},
(proxy, method, args) -> "getCaseName".equals(method.getName()) ? "case" : null);
var listener = new AimaFlowExecutionListener(instances, logs, tasks, push) {
@Override protected AimaTaskInstance findTaskInstance(String id) { return instance; }
};
publisher = new FlowExecutionEventPublisher(List.of(listener));
}
void send(FlowExecutionEvent.EventType type, String node) {
publisher.publishEvent(FlowExecutionEvent.builder().eventType(type).instId("flow-1")
.itemId("item").nodeId(node).nodeName(node).moduleCode("AIMA")
.progressScope(scope).progressTracker(tracker).build());
}
void assertProgress(double expected) {
assertEquals(expected, instance.getProgress(), 0);
assertEquals(expected, inserted.get().getProgress(), 0);
assertSame(inserted.get(), push.payload);
}
}
@Test
public void failedTerminalLogIsPersistedAndPushed() {
AtomicReference<AimaTestLog> inserted = new AtomicReference<>();

View File

@ -2,6 +2,7 @@ package com.cmvr.inspection.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
@ -58,4 +59,8 @@ public class InspectionTaskInstance extends BaseEntity
@ApiModelProperty("点位数量")
private Integer waypointCount;
/** Read projection from persisted execution logs; no new database column. */
@TableField(exist = false)
private Double progress;
}

View File

@ -102,4 +102,7 @@ public class InspectionTaskInstanceVo extends BaseEntity
@ApiModelProperty("点位数量")
private Integer waypointCount;
@ApiModelProperty("任务工作量进度,0到100")
private Double progress;
}

View File

@ -17,6 +17,7 @@ import com.cmvr.test.flow.runtime.event.FlowExecutionEvent;
import com.cmvr.test.flow.runtime.event.FlowExecutionListener;
import com.cmvr.test.flow.runtime.event.FlowExecutionModuleCodes;
import com.cmvr.test.flow.runtime.operator.FlowMediaParamResolver;
import com.cmvr.test.flow.runtime.progress.FlowProgressTracker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@ -31,10 +32,6 @@ public class InspectionFlowExecutionListener implements FlowExecutionListener {
private final IInspectionResultService inspectionResultService;
private final InspectionAlertListenService inspectionAlertListenService;
/** key:flowInstId|itemId, value:已完成节点集合 */
private final Map<String, Set<String>> itemNodeExecutMap = new java.util.concurrent.ConcurrentHashMap<>();
/** key:taskInsId(流程实例id=taskInsId), value:已执行item集合 */
private final Map<String, Set<String>> taskItemExecutMap = new java.util.concurrent.ConcurrentHashMap<>();
public InspectionFlowExecutionListener(IInspectionTaskInstanceService inspectionTaskInstanceService,
IInspectionTaskLogService inspectionTaskLogService,
@ -66,62 +63,66 @@ public class InspectionFlowExecutionListener implements FlowExecutionListener {
if (FlowExecutionEvent.EventType.TASK_COMPLETED == event.getEventType()
|| FlowExecutionEvent.EventType.TASK_FAILED == event.getEventType()
|| FlowExecutionEvent.EventType.TASK_STOPPED == event.getEventType()) {
clearCache(instId);
inspectionAlertListenService.clearByFlowInstanceId(instId);
}
// 1.节点完成才记录当前item下node
if (StrUtil.isNotBlank(itemId) && StrUtil.isNotBlank(nodeId)
&& FlowExecutionEvent.EventType.NODE_COMPLETED == event.getEventType()) {
itemNodeExecutMap.computeIfAbsent(itemExecutionKey(instId, itemId, event.getItemOrder()),
k -> java.util.concurrent.ConcurrentHashMap.newKeySet()).add(nodeId);
}
// 任意事件:当前任务绑定item(item一启动就入Map,所以统计已完成item要-1)
if (StrUtil.isNotBlank(instId) && StrUtil.isNotBlank(itemId)) {
taskItemExecutMap.computeIfAbsent(instId,
k -> java.util.concurrent.ConcurrentHashMap.newKeySet())
.add(itemExecutionKey(instId, itemId, event.getItemOrder()));
}
InspectionTaskInstance taskInstance = findTaskInstance(instId);
if (taskInstance == null) {
log.warn("未查询到巡检实例,taskInsId:{}", instId);
return;
}
int targetStatus = TaskStatusEnum.RUNNING.getCode();
double progress = FlowProgressTracker.progressOf(event, taskInstance.getProgress());
int targetStatus = taskInstance.getStatus() == null
? TaskStatusEnum.RUNNING.getCode() : taskInstance.getStatus();
boolean needUpdateDb = false;
boolean terminal = false;
String terminalMessage = null;
Date now = DateUtils.getNowDate();
switch (event.getEventType()) {
case TASK_COMPLETED:
targetStatus = TaskStatusEnum.SUCCESS.getCode();
needUpdateDb = true;
terminal = true;
terminalMessage = "任务执行完成";
break;
case TASK_FAILED:
targetStatus = TaskStatusEnum.FAILED.getCode();
needUpdateDb = true;
terminal = true;
terminalMessage = StrUtil.isBlank(event.getErrorMessage())
? "任务执行失败" : "任务执行失败:" + event.getErrorMessage();
break;
case TASK_STOPPED:
targetStatus = TaskStatusEnum.STOPPED.getCode();
needUpdateDb = true;
terminal = true;
terminalMessage = "任务已终止";
break;
case TASK_PAUSED:
targetStatus = TaskStatusEnum.PAUSED.getCode();
needUpdateDb = true;
terminalMessage = "任务已暂停";
break;
case TASK_RESUMED:
targetStatus = TaskStatusEnum.RUNNING.getCode();
needUpdateDb = true;
terminalMessage = "任务已恢复";
break;
case NODE_COMPLETED:
default:
break;
}
if (needUpdateDb) {
taskInstance.setStatus(targetStatus);
taskInstance.setEndTime(now);
inspectionTaskInstanceService.updateById(taskInstance);
InspectionTaskInstance update = new InspectionTaskInstance();
update.setId(taskInstance.getId());
update.setStatus(targetStatus);
if (terminal) update.setEndTime(now);
inspectionTaskInstanceService.updateById(update);
}
if (terminalMessage != null) {
pushTerminalMsg(taskInstance.getId(), now, targetStatus, terminalMessage);
pushTerminalMsg(taskInstance.getId(), now, targetStatus, terminalMessage, progress);
}
if (FlowExecutionEvent.EventType.NODE_COMPLETED == event.getEventType()) {
@ -135,35 +136,6 @@ public class InspectionFlowExecutionListener implements FlowExecutionListener {
// 节点推送
if (StrUtil.isNotBlank(nodeId)) {
int waypointCount = taskInstance.getWaypointCount() == null ? 0 : taskInstance.getWaypointCount();
double progress = 0D;
if (waypointCount > 0) {
// 当前任务已执行item数量(item启动就存入集合,已完整跑完的item=总数-1)
Set<String> itemSet = taskItemExecutMap.getOrDefault(instId, new HashSet<>());
int itemTotal = itemSet.size();
int finishedItemNum = itemTotal - 1;
// 当前item已完成节点数
Set<String> finishedNodeSet = itemNodeExecutMap.getOrDefault(
itemExecutionKey(instId, itemId, event.getItemOrder()), new HashSet<>());
int finishedNode = finishedNodeSet.size();
int totalNode = event.getNodeCount() == 0 ? 1 : event.getNodeCount();
// 已完整跑完点位占比
if (event.getItemOrder() != null && event.getItemOrder() > 0) {
finishedItemNum = event.getItemOrder() - 1;
}
double itemTotalRatio = finishedItemNum / (double) waypointCount;
// 当前运行item内部节点占比
double innerRatio = finishedNode / (double) totalNode / waypointCount;
// 还原你的兜底:防止循环节点进度超限,最低不低于极小值
double singleItemBase = 1d / waypointCount;
innerRatio = Math.max(singleItemBase - 0.01, innerRatio);
progress = (itemTotalRatio + innerRatio) * 100;
}
String info = event.getEventType() == FlowExecutionEvent.EventType.NODE_STARTED
? "开始执行"
: event.getEventType() == FlowExecutionEvent.EventType.NODE_FAILED
@ -238,26 +210,10 @@ public class InspectionFlowExecutionListener implements FlowExecutionListener {
}
}
/** 任务结束统一清理缓存 */
private void clearCache(String taskInsId) {
Set<String> itemList = taskItemExecutMap.getOrDefault(taskInsId, new HashSet<>());
itemList.forEach(itemNodeExecutMap::remove);
taskItemExecutMap.remove(taskInsId);
}
private String itemExecutionKey(String taskInsId, String itemId) {
return taskInsId + "|" + itemId;
}
private String itemExecutionKey(String taskInsId, String itemId, Integer itemOrder) {
return itemOrder != null && itemOrder > 0 ? taskInsId + "|" + itemOrder
: itemExecutionKey(taskInsId, itemId);
}
/**
* 工作流是异步启动的,首个节点事件可能略早于巡检实例写入task_ins_id,短暂重试消除该竞态。
*/
private InspectionTaskInstance findTaskInstance(String taskInsId) {
protected InspectionTaskInstance findTaskInstance(String taskInsId) {
for (int attempt = 0; attempt < 5; attempt++) {
InspectionTaskInstance instance = inspectionTaskInstanceService.lambdaQuery()
.eq(InspectionTaskInstance::getTaskInsId, taskInsId)
@ -279,6 +235,11 @@ public class InspectionFlowExecutionListener implements FlowExecutionListener {
* 保存并推送任务终态信息(参数dbInsId为数据库主键ID)
*/
public void pushTerminalMsg(String dbInsId, Date now, int targetStatus, String message) {
pushTerminalMsg(dbInsId, now, targetStatus, message,
targetStatus == TaskStatusEnum.SUCCESS.getCode() ? 100D : null);
}
public void pushTerminalMsg(String dbInsId, Date now, int targetStatus, String message, Double progress) {
String logId = UUID.randomUUID().toString().replace("-", "");
// 保存终态日志
@ -288,6 +249,7 @@ public class InspectionFlowExecutionListener implements FlowExecutionListener {
.logType(InspectionLogTypeEnum.TEXT.getCode())
.logContent(message)
.status(targetStatus)
.progress(progress)
.logTime(now)
.build();

View File

@ -5,6 +5,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<mapper namespace="com.cmvr.inspection.mapper.InspectionTaskInstanceMapper">
<resultMap type="InspectionTaskInstance" id="InspectionTaskInstanceResult">
<result property="progress" column="progress"/>
<result property="id" column="id" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
@ -22,6 +23,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</resultMap>
<resultMap type="com.cmvr.inspection.domain.vo.InspectionTaskInstanceVo" id="InspectionTaskInstanceVoResult">
<result property="progress" column="progress"/>
<result property="id" column="id" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
@ -45,8 +47,19 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="waypointCount" column="waypoint_count" />
</resultMap>
<!-- SUCCESS is 0 (TaskStatusEnum). Logs are already persisted for every event.
MAX is safe because new execution progress is monotonic and reruns use new IDs. -->
<sql id="executionProgress">
case when ${instanceAlias}.status = 0 then 100
else least(99.99, greatest(0, coalesce(
(select max(pl.progress) from inspection_task_log pl
where pl.task_instance_id = ${instanceAlias}.id), 0))) end as progress
</sql>
<sql id="selectInspectionTaskInstanceVo">
select id, create_by, create_time, update_by, update_time, remark, task_id, robot_id, status, start_time, end_time, task_ins_id, waypoint_count from inspection_task_instance
select id, create_by, create_time, update_by, update_time, remark, task_id, robot_id, status, start_time, end_time, task_ins_id, waypoint_count,
<include refid="executionProgress"><property name="instanceAlias" value="inspection_task_instance"/></include>
from inspection_task_instance
</sql>
<select id="selectInspectionTaskInstanceList" parameterType="InspectionTaskInstance" resultMap="InspectionTaskInstanceResult">
@ -129,6 +142,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="selectInspectionTaskInstanceVoList" parameterType="InspectionTaskInstanceQuery" resultMap="InspectionTaskInstanceVoResult">
select ti.id, ti.create_by, ti.create_time, ti.update_by, ti.update_time, ti.remark,ti.waypoint_count,
<include refid="executionProgress"><property name="instanceAlias" value="ti"/></include>,
ti.task_id, t.task_name, t.task_code,
ti.robot_id, r.robot_name, r.robot_id as robot_identity,
r.active_map_id as robot_current_map_id, m.map_name,
@ -168,6 +182,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="selectInspectionTaskInstanceVoById" parameterType="String" resultMap="InspectionTaskInstanceVoResult">
select ti.id, ti.create_by, ti.create_time, ti.update_by, ti.update_time, ti.remark,
<include refid="executionProgress"><property name="instanceAlias" value="ti"/></include>,
ti.task_id, t.task_name, t.task_code,
ti.robot_id, r.robot_name, r.robot_id as robot_identity,
r.active_map_id as robot_current_map_id, m.map_name,

View File

@ -0,0 +1,113 @@
package com.cmvr.inspection.listener;
import com.cmvr.device.service.InspectionAlertListenService;
import com.cmvr.framework.websocket.service.MessagePushService;
import com.cmvr.inspection.domain.InspectionTaskInstance;
import com.cmvr.inspection.domain.InspectionTaskLog;
import com.cmvr.inspection.enums.TaskStatusEnum;
import com.cmvr.inspection.service.IInspectionTaskInstanceService;
import com.cmvr.inspection.service.IInspectionTaskLogService;
import com.cmvr.inspection.service.IInspectionResultService;
import com.cmvr.test.flow.runtime.event.FlowExecutionEvent;
import com.cmvr.test.flow.runtime.event.FlowExecutionEventPublisher;
import com.cmvr.test.flow.runtime.progress.FlowProgressTracker;
import org.junit.Test;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import static com.cmvr.test.flow.runtime.event.FlowExecutionEvent.EventType.*;
import static org.junit.Assert.*;
public class InspectionFlowExecutionListenerTest {
@Test
public void logsAndPushUseSharedProgressIncludingSuccessfulTerminal() {
Fixture fixture = new Fixture();
fixture.send(NODE_STARTED, "a");
fixture.assertProgress(0);
fixture.send(NODE_COMPLETED, "a");
fixture.assertProgress(50);
fixture.send(TASK_COMPLETED, null);
fixture.assertProgress(100);
assertEquals(Integer.valueOf(TaskStatusEnum.SUCCESS.getCode()), fixture.instance.getStatus());
fixture.send(NODE_COMPLETED, "b");
fixture.assertProgress(100);
}
@Test
public void failureAndStopDoNotBecomeOneHundredOrResetProgress() {
for (var terminal : List.of(TASK_FAILED, TASK_STOPPED)) {
Fixture fixture = new Fixture();
fixture.send(NODE_COMPLETED, "a");
fixture.send(TASK_PAUSED, null);
fixture.assertProgress(50);
assertNull(fixture.instance.getEndTime());
fixture.send(TASK_RESUMED, null);
fixture.assertProgress(50);
fixture.send(terminal, null);
fixture.assertProgress(50);
}
}
private static class Fixture {
final InspectionTaskInstance instance = new InspectionTaskInstance();
final AtomicReference<InspectionTaskLog> inserted = new AtomicReference<>();
final AtomicReference<Object> pushed = new AtomicReference<>();
final FlowProgressTracker tracker = new FlowProgressTracker();
final FlowProgressTracker.Scope scope;
final FlowExecutionEventPublisher publisher;
Fixture() {
instance.setId("db-1");
instance.setStatus(TaskStatusEnum.RUNNING.getCode());
instance.setWaypointCount(999);
tracker.initialize(1);
scope = tracker.item(1, List.of("a", "b"));
var instances = (IInspectionTaskInstanceService) Proxy.newProxyInstance(
IInspectionTaskInstanceService.class.getClassLoader(), new Class<?>[]{IInspectionTaskInstanceService.class},
(proxy, method, args) -> {
if ("updateById".equals(method.getName())) {
var update = (InspectionTaskInstance) args[0];
if (update.getStatus() != null) instance.setStatus(update.getStatus());
if (update.getEndTime() != null) instance.setEndTime(update.getEndTime());
return true;
}
return null;
});
var logs = (IInspectionTaskLogService) Proxy.newProxyInstance(
IInspectionTaskLogService.class.getClassLoader(), new Class<?>[]{IInspectionTaskLogService.class},
(proxy, method, args) -> {
if ("insertInspectionTaskLog".equals(method.getName())) {
inserted.set((InspectionTaskLog) args[0]); return 1;
}
return null;
});
var results = (IInspectionResultService) Proxy.newProxyInstance(
IInspectionResultService.class.getClassLoader(), new Class<?>[]{IInspectionResultService.class},
(proxy, method, args) -> null);
var push = new MessagePushService() {
@Override public void pushToChannel(String channel, Object payload) {
assertEquals("InspectionTaskInstance", channel);
pushed.set(payload);
}
};
var listener = new InspectionFlowExecutionListener(instances, logs, push, results,
new InspectionAlertListenService(null)) {
@Override protected InspectionTaskInstance findTaskInstance(String id) { return instance; }
};
publisher = new FlowExecutionEventPublisher(List.of(listener));
}
void send(FlowExecutionEvent.EventType type, String node) {
publisher.publishEvent(FlowExecutionEvent.builder().eventType(type).instId("flow-1")
.itemId("item").nodeId(node).nodeName(node).moduleCode("INSPECTION")
.progressScope(scope).progressTracker(tracker).build());
}
void assertProgress(double expected) {
assertEquals(expected, inserted.get().getProgress(), 0);
assertSame(inserted.get(), pushed.get());
}
}
}

View File

@ -0,0 +1,40 @@
package com.cmvr.inspection.listener;
import com.cmvr.inspection.domain.InspectionTaskInstance;
import com.cmvr.inspection.domain.dto.InspectionTaskInstanceQuery;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.session.Configuration;
import org.junit.Test;
import java.io.InputStream;
import java.util.Map;
import static org.junit.Assert.*;
public class InspectionProgressMapperTest {
@Test
public void everyInstanceReadIncludesPersistedProgressProjection() throws Exception {
Configuration configuration = new Configuration();
configuration.getTypeAliasRegistry().registerAlias(InspectionTaskInstance.class);
configuration.getTypeAliasRegistry().registerAlias(InspectionTaskInstanceQuery.class);
String resource = "mapper/inspection/InspectionTaskInstanceMapper.xml";
try (InputStream input = getClass().getClassLoader().getResourceAsStream(resource)) {
assertNotNull(input);
new XMLMapperBuilder(input, configuration, resource, configuration.getSqlFragments()).parse();
}
String namespace = "com.cmvr.inspection.mapper.InspectionTaskInstanceMapper.";
Map<String, Object> queries = Map.of(
"selectInspectionTaskInstanceList", new InspectionTaskInstance(),
"selectInspectionTaskInstanceById", "id",
"selectInspectionTaskInstanceVoList", new InspectionTaskInstanceQuery(),
"selectInspectionTaskInstanceVoById", "id");
for (var query : queries.entrySet()) {
String sql = configuration.getMappedStatement(namespace + query.getKey())
.getBoundSql(query.getValue()).getSql();
assertTrue(sql.contains("max(pl.progress)"));
assertTrue(sql.contains(".status = 0 then 100"));
assertTrue(sql.contains("as progress"));
assertFalse(sql.contains("${"));
}
}
}

View File

@ -3,12 +3,15 @@ package com.cmvr.test.flow.context;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONField;
import com.cmvr.test.flow.runtime.progress.FlowProgressTracker;
import com.cmvr.test.enums.RunModeEnum;
import com.cmvr.test.enums.TaskStatusEnum;
import com.cmvr.test.enums.TerminalStatusEnum;
import com.cmvr.test.flow.builder.TaskKeyBuilder;
import com.cmvr.test.model.vo.ResourceRuntimeAssignmentVO;
import lombok.Data;
import lombok.ToString;
import java.util.Collections;
import java.util.Date;
@ -23,6 +26,10 @@ import java.util.concurrent.ConcurrentHashMap;
@Data
public class TaskContext {
@JSONField(serialize = false, deserialize = false)
@ToString.Exclude
private final FlowProgressTracker progressTracker = new FlowProgressTracker();
/**
* 任务实例 ID
*/

View File

@ -101,6 +101,7 @@ public class TaskInstHolder {
// 发布任务完成事件
eventPublisher.publishEvent(FlowExecutionEvent.builder()
.eventType(FlowExecutionEvent.EventType.TASK_COMPLETED)
.progressTracker(ctx == null ? null : ctx.getProgressTracker())
.instId(instId)
.taskId(taskId)
.moduleCode(moduleCode)
@ -152,6 +153,7 @@ public class TaskInstHolder {
// 发布任务失败事件
eventPublisher.publishEvent(FlowExecutionEvent.builder()
.eventType(FlowExecutionEvent.EventType.TASK_FAILED)
.progressTracker(ctx == null ? null : ctx.getProgressTracker())
.instId(instId)
.taskId(taskId)
.moduleCode(moduleCode)
@ -199,6 +201,7 @@ public class TaskInstHolder {
case PAUSED:
eventPublisher.publishEvent(FlowExecutionEvent.builder()
.eventType(FlowExecutionEvent.EventType.TASK_PAUSED)
.progressTracker(ctx.getProgressTracker())
.instId(instId).taskId(ctx.getTaskId()).itemId(ctx.getItemId())
.itemOrder(ctx.getItemOrder()).itemOccurrence(ctx.getItemOccurrence())
.moduleCode(ctx.getModuleCode())
@ -207,6 +210,7 @@ public class TaskInstHolder {
case STOPPED:
eventPublisher.publishEvent(FlowExecutionEvent.builder()
.eventType(FlowExecutionEvent.EventType.TASK_STOPPED)
.progressTracker(ctx.getProgressTracker())
.instId(instId).taskId(ctx.getTaskId()).itemId(ctx.getItemId())
.itemOrder(ctx.getItemOrder()).itemOccurrence(ctx.getItemOccurrence())
.moduleCode(ctx.getModuleCode())
@ -225,6 +229,7 @@ public class TaskInstHolder {
if (ctx == null) return;
eventPublisher.publishEvent(FlowExecutionEvent.builder()
.eventType(FlowExecutionEvent.EventType.TASK_RESUMED)
.progressTracker(ctx.getProgressTracker())
.instId(instId).taskId(ctx.getTaskId()).itemId(ctx.getItemId())
.itemOrder(ctx.getItemOrder()).itemOccurrence(ctx.getItemOccurrence())
.moduleCode(ctx.getModuleCode())

View File

@ -77,6 +77,10 @@ public class FlowLoopNodeHandler implements FlowNodeTypeHandler {
subMessage.setLoopNum(i); // 当前 loop 第 i 次
subMessage.setIterations(newIterations); // 完整路径
subMessage.setLoopArray(loopArray);
if (message.getProgressScope() != null) {
subMessage.setProgressScope(message.getProgressScope()
.child(nodeId, i, loopCount, subGraph.allNodeIds()));
}
flowItemExecutor.executeSubGraph(subGraph, subMessage, latch::countDown, newIterations);

View File

@ -75,6 +75,10 @@ public class FlowSubFlowNodeHandler implements FlowNodeTypeHandler {
childMessage.setSubFlowRootNodeId(rootNodeId);
childMessage.setSubFlowExecutionId(executionId);
childMessage.setSubFlowOutcome(outcome);
if (message.getProgressScope() != null) {
childMessage.setProgressScope(message.getProgressScope()
.invocation(message.getNodeId(), definition.graph().allNodeIds()));
}
CountDownLatch completed = new CountDownLatch(1);
FlowItemExecutor executor = SpringUtils.getBean(FlowItemExecutor.class);

View File

@ -52,6 +52,11 @@ public class FlowItemExecutor {
TeQueryTaskDetailDTO item, Runnable onFinished) {
FlowGraph graph = FlowModelBuilder.buildExecutableGraph(item.getFlowData());
TaskContext progressContext = taskInstHolder.getContext(rootMessage.getInstId());
if (progressContext != null) {
rootMessage.setProgressScope(progressContext.getProgressTracker()
.item(rootMessage.getItemOrder(), graph.allNodeIds()));
}
String startNodeId = graph.findStartNodeId();
List<FlowParamDef> startInputDefs = graph.getStartInputParamsDefs();
startInputDefs.clear();
@ -364,6 +369,9 @@ public class FlowItemExecutor {
}
// 直接调度命中节点
if (message.getProgressScope() != null) {
message.getProgressScope().skipAbsent(graph.allNodeIds());
}
flowTaskScheduler.scheduleDirectly(
message.getInstId(),
matchedEdge.getTo(),

View File

@ -38,6 +38,7 @@ public class FlowTaskEngine {
JSONObject runParams = context.getRunParams();
int totalItemCount = items.size();
context.getProgressTracker().initialize(totalItemCount);
Map<String, Integer> itemOccurrences = new HashMap<>();
for (int i = 0; i < totalItemCount; i++) {

View File

@ -262,6 +262,7 @@ public class FlowTaskRuntimeEntry implements FlowTaskRuntimeService {
instance.setConfig(executionRequest == null ? null : JSON.toJSONString(executionRequest));
instance.setRunMode(runMode.name());
instance.setStatus(String.valueOf(TaskStatusEnum.RUNNING.getCode()));
instance.setProgress(0D);
boolean save = taskInstService.save(instance);
if (!save) {
throw new GlobalException(StrUtil.format("创建 {} 任务实例失败,任务ID {}", runMode, taskId));

View File

@ -1,6 +1,8 @@
package com.cmvr.test.flow.runtime.event;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONField;
import com.cmvr.test.flow.runtime.progress.FlowProgressTracker;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.enums.TaskStatusEnum;
import lombok.AllArgsConstructor;
@ -21,6 +23,15 @@ import java.util.List;
@AllArgsConstructor
public class FlowExecutionEvent {
/** Unified task work progress, 0..100; 100 is reserved for successful termination. */
private Double progress;
@JSONField(serialize = false, deserialize = false)
private transient FlowProgressTracker progressTracker;
@JSONField(serialize = false, deserialize = false)
private transient FlowProgressTracker.Scope progressScope;
/**
* 事件类型。
*/

View File

@ -1,8 +1,10 @@
package com.cmvr.test.flow.runtime.event;
import cn.hutool.core.util.StrUtil;
import com.cmvr.test.service.ITeTaskInstService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Collections;
import java.util.List;
@ -18,8 +20,16 @@ import java.util.List;
public class FlowExecutionEventPublisher {
private final List<FlowExecutionListener> listeners;
private final ITeTaskInstService taskInstService;
public FlowExecutionEventPublisher(List<FlowExecutionListener> listeners) {
this(listeners, null);
}
@Autowired
public FlowExecutionEventPublisher(List<FlowExecutionListener> listeners,
ITeTaskInstService taskInstService) {
this.taskInstService = taskInstService;
this.listeners = listeners != null ? listeners : Collections.emptyList();
if (!this.listeners.isEmpty()) {
log.info("已注册 {} 个流程执行监听器: {}", this.listeners.size(),
@ -33,6 +43,33 @@ public class FlowExecutionEventPublisher {
* @param event 事件对象
*/
public void publishEvent(FlowExecutionEvent event) {
if (event == null || event.getEventType() == null) return;
var tracker = event.getProgressTracker();
if (tracker == null && event.getProgressScope() != null) {
tracker = event.getProgressScope().tracker();
}
if (tracker != null) {
synchronized (tracker) {
// Late callbacks must not recreate caches or overwrite terminal state.
if (tracker.isTerminal()) return;
if (event.getProgressScope() != null && !event.getProgressScope().isActive()) return;
event.setProgress(tracker.accept(event));
dispatch(event);
}
} else {
dispatch(event);
}
}
private void dispatch(FlowExecutionEvent event) {
// Includes ordinary workflows and trial runs with no business moduleCode.
if (taskInstService != null && StrUtil.isNotBlank(event.getInstId()) && event.getProgress() != null) {
try {
taskInstService.updateProgress(event.getInstId(), event.getProgress());
} catch (Exception e) {
log.error("保存流程进度失败: instId={}, progress={}", event.getInstId(), event.getProgress(), e);
}
}
if (listeners.isEmpty()) {
return;
}

View File

@ -32,10 +32,9 @@ public class FlowAfterInterceptor extends AbstractFlowMsgPreInterceptor{
return result;
}
TaskContext taskContext = taskInstHolder.getContext(message.getInstId());
if (taskContext == null || taskContext.isStopped()) {
return null;
}
if (result == null && taskContext.isPaused()) {
// Interrupted loop handlers can return a success-shaped result during
// pause. Do not resolve the remaining loop budget until a real resume.
if (taskContext == null || taskContext.isStopped() || taskContext.isPaused()) {
return null;
}
@ -57,6 +56,8 @@ public class FlowAfterInterceptor extends AbstractFlowMsgPreInterceptor{
}
FlowExecutionEvent event = FlowExecutionEvent.builder()
.progressScope(message.getProgressScope())
.progressTracker(taskContext.getProgressTracker())
.eventType(eventType)
.nodeName(message.getNodeName())
.instId(message.getInstId())

View File

@ -36,6 +36,8 @@ public class FlowBeforeInterceptor extends AbstractFlowMsgPreInterceptor{
}
FlowExecutionEvent event = FlowExecutionEvent.builder()
.progressScope(message.getProgressScope())
.progressTracker(taskContext == null ? null : taskContext.getProgressTracker())
.eventType(FlowExecutionEvent.EventType.NODE_STARTED)
.instId(message.getInstId())
.taskId(message.getTaskId())

View File

@ -1,6 +1,8 @@
package com.cmvr.test.flow.runtime.message;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONField;
import com.cmvr.test.flow.runtime.progress.FlowProgressTracker;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.builder.FlowGraph;
import com.cmvr.test.flow.runtime.subflow.SubFlowExecutionOutcome;
@ -16,6 +18,10 @@ import java.util.List;
@Data
public class TaskNodeExecuteMessage {
/** Runtime-only graph budget; retained by pause/resume and detached analysis. */
@JSONField(serialize = false, deserialize = false)
private FlowProgressTracker.Scope progressScope;
/**
* 实例ID
*/

View File

@ -220,6 +220,7 @@ public class AsyncMediaAnalysisCoordinator {
FlowExecutionEvent.EventType eventType, JSONObject output, String error) {
int nodeCount = message.getGraph() == null ? 0 : message.getGraph().allNodeIds().size();
eventPublisher.publishEvent(FlowExecutionEvent.builder()
.progressScope(message.getProgressScope())
.eventType(eventType)
.nodeName(message.getNodeName())
.instId(message.getInstId())

View File

@ -0,0 +1,172 @@
package com.cmvr.test.flow.runtime.progress;
import com.cmvr.test.flow.runtime.event.FlowExecutionEvent;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Per-execution, hierarchical work progress (not an elapsed-time estimate).
* Items have equal budgets; each graph partitions its budget between its nodes.
* Loops/sub-flows subdivide their owning node's budget instead of adding nodes
* to another graph's denominator. All mutations and event delivery use this
* tracker's monitor, so asynchronous completions cannot publish older progress.
*/
public final class FlowProgressTracker {
/** Compatibility for callers without a runtime tracker; never invent node ratios. */
public static double progressOf(FlowExecutionEvent event, Double previous) {
if (event.getEventType() == FlowExecutionEvent.EventType.TASK_COMPLETED) return 100;
Double value = event.getProgress() == null ? previous : event.getProgress();
return value == null || !Double.isFinite(value) ? 0 : Math.max(0, Math.min(99.99, value));
}
private final Map<Integer, Scope> items = new HashMap<>();
private int totalItems;
private double progress;
private boolean paused;
private boolean terminal;
public synchronized void initialize(int totalItems) {
if (this.totalItems == 0 && !terminal) this.totalItems = Math.max(0, totalItems);
}
public synchronized Scope item(int order, Collection<String> nodes) {
if (terminal) return null;
if (order < 1 || order > totalItems) return null;
return items.computeIfAbsent(order, ignored -> new Scope(this, nodes));
}
public synchronized boolean isTerminal() {
return terminal;
}
/** Called by the publisher while holding this monitor through delivery. */
public synchronized double accept(FlowExecutionEvent event) {
if (terminal) return progress;
switch (event.getEventType()) {
case NODE_COMPLETED -> {
Scope scope = event.getProgressScope();
if (scope != null && scope.owner == this && scope.active) scope.complete(event.getNodeId());
}
case TASK_PAUSED -> paused = true;
case TASK_RESUMED -> paused = false;
default -> { }
}
if (!paused) {
double resolved = items.values().stream().mapToDouble(Scope::fraction).sum();
double calculated = totalItems == 0 ? 0 : resolved * 100 / totalItems;
// Round down: even 99.9999% must not become 100 before TASK_COMPLETED.
progress = Math.max(progress, Math.min(99.99, Math.floor(calculated * 100 + 1e-8) / 100));
}
switch (event.getEventType()) {
case TASK_COMPLETED -> {
progress = 100;
terminal = true;
}
case TASK_FAILED, TASK_STOPPED -> terminal = true;
default -> { }
}
if (terminal) items.clear();
return progress;
}
public synchronized double getProgress() {
return progress;
}
/** One graph invocation, scoped by item, parent node and loop iteration. */
public static final class Scope {
private final FlowProgressTracker owner;
private final Map<String, Unit> nodes = new HashMap<>();
private boolean active = true;
private Scope(FlowProgressTracker owner, Collection<String> nodeIds) {
this.owner = owner;
if (nodeIds != null) nodeIds.forEach(id -> nodes.putIfAbsent(id, new Unit()));
}
public FlowProgressTracker tracker() {
return owner;
}
public boolean isActive() {
synchronized (owner) {
return active && !owner.terminal;
}
}
/** Re-entering a paused logical invocation reuses its counts. */
public Scope child(String nodeId, int iteration, int totalIterations, Collection<String> nodeIds) {
synchronized (owner) {
if (owner.terminal || !active) return null;
Unit unit = nodes.get(nodeId);
if (unit == null || iteration < 1 || totalIterations < iteration) return null;
if (unit.childCount == 0) unit.childCount = totalIterations;
return unit.children.computeIfAbsent(iteration, ignored -> new Scope(owner, nodeIds));
}
}
/**
* Published sub-flows get fresh namespaced node IDs on each invocation.
* Resume restarts that invocation: replace its subtree, retain the same
* parent budget/high-water mark, and reject callbacks from the old tree.
*/
public Scope invocation(String nodeId, Collection<String> nodeIds) {
synchronized (owner) {
if (owner.terminal || !active) return null;
Unit unit = nodes.get(nodeId);
if (unit == null) return null;
unit.children.values().forEach(Scope::retire);
unit.children.clear();
unit.done = false;
unit.childCount = 1;
Scope scope = new Scope(owner, nodeIds);
unit.children.put(1, scope);
return scope;
}
}
private void retire() {
active = false;
nodes.values().forEach(unit -> unit.children.values().forEach(Scope::retire));
}
/** Branch-pruned nodes resolve their original budget; no denominator change. */
public void skipAbsent(Collection<String> activeNodes) {
synchronized (owner) {
if (owner.terminal || !active) return;
nodes.forEach((id, unit) -> {
if (!activeNodes.contains(id)) unit.skipped = true;
});
}
}
private void complete(String id) {
Unit unit = nodes.get(id);
if (unit != null) unit.done = true;
}
private double fraction() {
return nodes.isEmpty() ? 0 : nodes.values().stream().mapToDouble(Unit::fraction).sum() / nodes.size();
}
}
private static final class Unit {
private boolean done;
private boolean skipped;
private int childCount;
private final Map<Integer, Scope> children = new HashMap<>();
private double fraction() {
if (skipped) return 1;
if (childCount == 0) return done ? 1 : 0;
double resolved = children.values().stream().mapToDouble(Scope::fraction).sum();
// A successful early break resolves unvisited iterations only. Already
// started child graphs can still have pending asynchronous analysis.
if (done) resolved += Math.max(0, childCount - children.size());
double fraction = Math.min(1, resolved / childCount);
return done ? fraction : Math.min(.99, fraction);
}
}
}

View File

@ -28,6 +28,9 @@ public class TeTaskInst extends BaseEntity {
@ApiModelProperty("状态(0完成, 1执行中, 2失败, 3暂停, 4终止)")
private String status;
@ApiModelProperty("统一工作量进度,0到100,只有成功终态为100")
private Double progress;
@ApiModelProperty("运行模式(NORMAL:正常 / TRIAL:试运行)")
private String runMode;
}

View File

@ -25,6 +25,9 @@ public class TeTaskInstVO {
@ApiModelProperty("状态 (0已完成 1执行中)")
private String status;
@ApiModelProperty("统一工作量进度,0到100")
private Double progress;
@ApiModelProperty("备注")
private String remark;

View File

@ -27,6 +27,9 @@ public interface ITeTaskInstService extends IService<TeTaskInst> {
*/
public boolean updateStatus(String instId, TaskStatusEnum taskStatusEnum);
/** Persist a monotonic progress snapshot, independently of business module routing. */
void updateProgress(String instId, double progress);
List<TeNodeInst> detail(String instId);
}

View File

@ -63,9 +63,19 @@ public class TeTaskInstServiceImpl extends ServiceImpl<TeTaskInstMapper, TeTaskI
new LambdaUpdateWrapper<TeTaskInst>()
.eq(TeTaskInst::getId, instId)
.set(TeTaskInst::getStatus, taskStatusEnum.getCode())
.set(taskStatusEnum == TaskStatusEnum.SUCCESS, TeTaskInst::getProgress, 100D)
);
}
@Override
public void updateProgress(String instId, double progress) {
if (!Double.isFinite(progress) || progress < 0 || progress > 100) return;
this.update(new LambdaUpdateWrapper<TeTaskInst>()
.eq(TeTaskInst::getId, instId)
.and(query -> query.isNull(TeTaskInst::getProgress).or().lt(TeTaskInst::getProgress, progress))
.set(TeTaskInst::getProgress, progress));
}
@Override
public List<TeNodeInst> detail(String instId) {
LambdaQueryWrapper<TeNodeInst> wrapper = Wrappers.lambdaQuery(TeNodeInst.class);

View File

@ -10,6 +10,7 @@ import com.cmvr.test.flow.context.TaskInstHolder;
import com.cmvr.test.flow.context.TaskThreadRegistry;
import com.cmvr.test.flow.runtime.engine.FlowItemExecutor;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.event.FlowExecutionEvent;
import org.junit.Test;
import java.util.ArrayList;
@ -21,6 +22,49 @@ import static org.junit.Assert.assertEquals;
public class FlowLoopNodeHandlerTest {
@Test
public void loopMessagesCarrySeparateWeightedIterationScopes() {
TaskContextManager manager = new TaskContextManager();
TaskInstHolder holder = new TaskInstHolder(null, manager, null, null);
TaskContext context = new TaskContext();
context.setInstId("flow");
context.getProgressTracker().initialize(1);
var scope = context.getProgressTracker().item(1, List.of("loop", "tail"));
holder.register(context);
List<Double> progress = new ArrayList<>();
FlowItemExecutor executor = new FlowItemExecutor(null, List.of(), null, holder, null, null, null, null) {
@Override
public void executeSubGraph(FlowGraph graph, TaskNodeExecuteMessage message,
Runnable finished, List<Integer> iterations) {
progress.add(context.getProgressTracker().accept(FlowExecutionEvent.builder()
.eventType(FlowExecutionEvent.EventType.NODE_COMPLETED)
.progressScope(message.getProgressScope()).nodeId("body").build()));
finished.run();
}
};
FlowLoopNodeHandler handler = new FlowLoopNodeHandler(new TaskThreadRegistry(), holder) {
@Override protected FlowItemExecutor getFlowItemExecutor() { return executor; }
};
FlowNodeWrapper loop = new FlowNodeWrapper();
loop.setNodeId("loop");
loop.setNodeType(NodeTypeEnum.LOOP);
FlowNodeWrapper body = new FlowNodeWrapper();
body.setNodeId("body");
FlowGraph child = new FlowGraph();
child.getNodeMap().put("body", body);
loop.setSubGraph(child);
FlowGraph graph = new FlowGraph();
graph.getNodeMap().put("loop", loop);
TaskNodeExecuteMessage message = new TaskNodeExecuteMessage();
message.setInstId("flow");
message.setNodeId("loop");
message.setGraph(graph);
message.setProgressScope(scope);
message.setInputParams(new JSONObject().fluentPut("loopNum", 2));
handler.handle(message);
assertEquals(List.of(25D, 49.5D), progress);
}
@Test
public void stopsRemainingIterationsAfterTaskContextIsRemoved() {
TaskContextManager contextManager = new TaskContextManager();

View File

@ -0,0 +1,40 @@
package com.cmvr.test.flow.runtime.interceptor;
import com.cmvr.test.flow.context.TaskContext;
import com.cmvr.test.flow.context.TaskContextManager;
import com.cmvr.test.flow.context.TaskInstHolder;
import com.cmvr.test.flow.runtime.event.FlowExecutionEvent;
import com.cmvr.test.flow.runtime.event.FlowExecutionEventPublisher;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.*;
public class FlowAfterProgressTest {
@Test
public void pausedLoopSuccessDoesNotResolveUnvisitedIterations() {
TaskContext context = new TaskContext();
context.setInstId("flow");
context.setPaused(true);
context.getProgressTracker().initialize(1);
var scope = context.getProgressTracker().item(1, List.of("loop", "tail"));
var iteration = scope.child("loop", 1, 4, List.of("a"));
context.getProgressTracker().accept(FlowExecutionEvent.builder()
.eventType(FlowExecutionEvent.EventType.NODE_COMPLETED)
.progressScope(iteration).nodeId("a").build());
TaskContextManager manager = new TaskContextManager();
manager.register(context);
var publisher = new FlowExecutionEventPublisher(List.of());
var holder = new TaskInstHolder(null, manager, null, publisher);
var interceptor = new FlowAfterInterceptor(publisher, holder);
var message = new TaskNodeExecuteMessage();
message.setInstId("flow");
message.setNodeId("loop");
message.setProgressScope(scope);
assertNull(interceptor.doIntercept(message, ignored -> TaskNodeExecuteResult.success()));
assertEquals(12.5, context.getProgressTracker().getProgress(), 0);
}
}

View File

@ -46,6 +46,7 @@ public class AsyncMediaAnalysisCoordinatorTest {
assertTrue(submitted.isDeferred());
assertTrue(started.await(1, TimeUnit.SECONDS));
assertNull(fixture.context.getNodeOutput("analysis-node", Collections.emptyList()));
assertEquals(0, fixture.context.getProgressTracker().getProgress(), 0);
release.countDown();
assertTrue(fixture.coordinator.awaitAll("inst-1").isSuccess());
@ -54,6 +55,7 @@ public class AsyncMediaAnalysisCoordinatorTest {
assertTrue(fixture.nodeSucceeded.get());
assertEquals(FlowExecutionEvent.EventType.NODE_COMPLETED,
fixture.lastEvent.get().getEventType());
assertEquals(50, fixture.lastEvent.get().getProgress(), 0);
} finally {
release.countDown();
fixture.executor.shutdown();
@ -238,6 +240,8 @@ public class AsyncMediaAnalysisCoordinatorTest {
holder, nodeService, publisher, executor);
TaskNodeExecuteMessage message = message("item-1");
context.getProgressTracker().initialize(1);
message.setProgressScope(context.getProgressTracker().item(1, List.of("analysis-node", "tail")));
return new Fixture(coordinator, executor, context, message,
nodeSucceeded, nodeFailed, lastEvent);
}

View File

@ -0,0 +1,96 @@
package com.cmvr.test.flow.runtime.progress;
import com.cmvr.test.flow.runtime.event.FlowExecutionEvent;
import com.cmvr.test.flow.runtime.event.FlowExecutionEventPublisher;
import com.cmvr.test.flow.runtime.event.FlowExecutionListener;
import com.cmvr.test.service.ITeTaskInstService;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import java.lang.reflect.Proxy;
import static com.cmvr.test.flow.runtime.event.FlowExecutionEvent.EventType.*;
import static org.junit.Assert.*;
public class FlowProgressPublisherTest {
@Test
public void retiredSubflowCallbacksAreNotPersistedOrDelivered() {
List<FlowExecutionEvent> events = new ArrayList<>();
var tracker = new FlowProgressTracker();
tracker.initialize(1);
var root = tracker.item(1, List.of("call", "tail"));
var old = root.invocation("call", List.of("old"));
var nested = old.invocation("old", List.of("nested-old"));
var fresh = root.invocation("call", List.of("new"));
assertFalse(nested.isActive());
var publisher = new FlowExecutionEventPublisher(List.of(new FlowExecutionListener() {
@Override public String getModuleCode() { return "test"; }
@Override public void onEvent(FlowExecutionEvent event) { events.add(event); }
}));
publisher.publishEvent(FlowExecutionEvent.builder().eventType(NODE_COMPLETED)
.moduleCode("test").progressScope(nested).nodeId("nested-old").build());
assertTrue(events.isEmpty());
publisher.publishEvent(FlowExecutionEvent.builder().eventType(NODE_COMPLETED)
.moduleCode("test").progressScope(fresh).nodeId("new").build());
assertEquals(1, events.size());
}
@Test
public void ordinaryWorkflowsPersistProgressWithoutBusinessModuleListeners() {
List<Double> persisted = new ArrayList<>();
var service = (ITeTaskInstService) Proxy.newProxyInstance(ITeTaskInstService.class.getClassLoader(),
new Class<?>[]{ITeTaskInstService.class}, (proxy, method, args) -> {
if ("updateProgress".equals(method.getName())) {
assertEquals("flow", args[0]);
persisted.add((Double) args[1]);
}
return null;
});
var tracker = new FlowProgressTracker();
tracker.initialize(1);
var scope = tracker.item(1, List.of("a", "b"));
var publisher = new FlowExecutionEventPublisher(List.of(), service);
publisher.publishEvent(FlowExecutionEvent.builder().eventType(NODE_COMPLETED)
.instId("flow").progressScope(scope).nodeId("a").build());
publisher.publishEvent(FlowExecutionEvent.builder().eventType(TASK_COMPLETED)
.instId("flow").progressTracker(tracker).build());
assertEquals(List.of(50D, 100D), persisted);
}
@Test
public void concurrentDeliveryIsMonotonicAndTerminalIsLast() throws Exception {
var tracker = new FlowProgressTracker();
tracker.initialize(1);
List<String> nodes = IntStream.range(0, 100).mapToObj(Integer::toString).toList();
var scope = tracker.item(1, nodes);
List<Double> delivered = new ArrayList<>();
var publisher = new FlowExecutionEventPublisher(List.of(new FlowExecutionListener() {
@Override public String getModuleCode() { return "test"; }
@Override public void onEvent(FlowExecutionEvent event) { delivered.add(event.getProgress()); }
}));
var pool = Executors.newFixedThreadPool(8);
try {
var futures = nodes.stream().map(id -> pool.submit(() -> publisher.publishEvent(
FlowExecutionEvent.builder().eventType(NODE_COMPLETED).moduleCode("test")
.progressScope(scope).nodeId(id).build()))).toList();
for (var future : futures) future.get(5, TimeUnit.SECONDS);
} finally {
pool.shutdownNow();
}
assertEquals(100, delivered.size());
assertEquals(99.99, delivered.get(99), 0);
for (int i = 1; i < delivered.size(); i++) assertTrue(delivered.get(i) >= delivered.get(i - 1));
publisher.publishEvent(FlowExecutionEvent.builder().eventType(TASK_COMPLETED)
.moduleCode("test").progressTracker(tracker).build());
publisher.publishEvent(FlowExecutionEvent.builder().eventType(NODE_STARTED)
.moduleCode("test").progressScope(scope).nodeId("0").build());
publisher.publishEvent(FlowExecutionEvent.builder().eventType(TASK_FAILED)
.moduleCode("test").progressTracker(tracker).build());
assertEquals(101, delivered.size());
assertEquals(100, delivered.get(100), 0);
}
}

View File

@ -0,0 +1,207 @@
package com.cmvr.test.flow.runtime.progress;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.cmvr.test.flow.runtime.event.FlowExecutionEvent;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import org.junit.Test;
import java.util.List;
import static com.cmvr.test.flow.runtime.event.FlowExecutionEvent.EventType.*;
import static org.junit.Assert.*;
public class FlowProgressTrackerTest {
private final FlowProgressTracker tracker = new FlowProgressTracker();
private double event(FlowExecutionEvent.EventType type, FlowProgressTracker.Scope scope, String node) {
return tracker.accept(FlowExecutionEvent.builder().eventType(type).nodeId(node)
.progressScope(scope).build());
}
private double complete(FlowProgressTracker.Scope scope, String node) {
return event(NODE_COMPLETED, scope, node);
}
@Test
public void startsAtZeroAndOnlySuccessfulTaskReachesOneHundred() {
tracker.initialize(1);
var scope = tracker.item(1, List.of("a", "b"));
assertEquals(0, event(NODE_STARTED, scope, "a"), 0);
assertEquals(50, complete(scope, "a"), 0);
assertEquals(50, complete(scope, "a"), 0);
assertEquals(99.99, complete(scope, "b"), 0);
assertEquals(100, event(TASK_COMPLETED, null, null), 0);
assertTrue(tracker.isTerminal());
assertNull(tracker.item(1, List.of("a")));
}
@Test
public void repeatedItemsAndLateAnalysisAggregateInsteadOfUsingCurrentItemOrder() {
tracker.initialize(2);
var first = tracker.item(1, List.of("start", "analysis"));
var second = tracker.item(2, List.of("start", "analysis"));
assertEquals(0, event(NODE_STARTED, first, "start"), 0);
assertEquals(25, complete(first, "start"), 0);
assertEquals(25, event(NODE_STARTED, second, "start"), 0);
assertEquals(50, complete(second, "start"), 0);
assertEquals(75, complete(first, "analysis"), 0);
assertEquals(99.99, complete(second, "analysis"), 0);
}
@Test
public void everyLoopIterationUsesPartOfItsParentBudget() {
tracker.initialize(1);
var root = tracker.item(1, List.of("loop", "tail"));
var first = root.child("loop", 1, 2, List.of("same-node"));
assertEquals(25, complete(first, "same-node"), 0);
var second = root.child("loop", 2, 2, List.of("same-node"));
assertEquals(49.5, complete(second, "same-node"), 0);
assertEquals(50, complete(root, "loop"), 0);
assertEquals(99.99, complete(root, "tail"), 0);
}
@Test
public void nestedSubflowsAndLoopsCannotChangeRootDenominator() {
tracker.initialize(1);
var root = tracker.item(1, List.of("call", "tail"));
var child = root.child("call", 1, 1, List.of("loop"));
var iteration = child.child("loop", 1, 2, List.of("a", "b"));
assertEquals(12.5, complete(iteration, "a"), 0);
assertEquals(25, complete(iteration, "b"), 0);
assertEquals(25, event(NODE_STARTED, root, "tail"), 0);
assertEquals(75, complete(root, "tail"), 0);
}
@Test
public void distinctSubflowCallsWithSameNodeIdsAreIndependent() {
tracker.initialize(1);
var root = tracker.item(1, List.of("call1", "call2"));
var first = root.child("call1", 1, 1, List.of("same"));
var second = root.child("call2", 1, 1, List.of("same"));
complete(first, "same");
assertEquals(50, complete(root, "call1"), 0);
assertEquals(50, event(NODE_STARTED, second, "same"), 0);
complete(second, "same");
assertEquals(99.99, complete(root, "call2"), 0);
}
@Test
public void restartedSubflowReplacesNamespacedNodesWithoutDoubleCountingOrGoingBackwards() {
tracker.initialize(1);
var root = tracker.item(1, List.of("call", "tail"));
var old = root.invocation("call", List.of("old-a", "old-b"));
assertEquals(25, complete(old, "old-a"), 0);
var fresh = root.invocation("call", List.of("new-a", "new-b"));
assertFalse(old.isActive());
assertTrue(fresh.isActive());
assertEquals(25, complete(old, "old-b"), 0);
assertEquals(25, complete(fresh, "new-a"), 0);
assertEquals(49.5, complete(fresh, "new-b"), 0);
assertEquals(50, complete(root, "call"), 0);
}
@Test
public void parentCompletionDoesNotCompletePendingChildAnalysis() {
tracker.initialize(1);
var root = tracker.item(1, List.of("call", "tail"));
var child = root.child("call", 1, 1, List.of("sync", "analysis"));
assertEquals(25, complete(child, "sync"), 0);
assertEquals(25, complete(root, "call"), 0);
assertEquals(75, complete(root, "tail"), 0);
assertEquals(99.99, complete(child, "analysis"), 0);
}
@Test
public void earlyBreakResolvesOnlyUnvisitedIterations() {
tracker.initialize(1);
var root = tracker.item(1, List.of("loop", "tail"));
var first = root.child("loop", 1, 4, List.of("sync", "analysis"));
complete(first, "sync");
assertEquals(43.75, complete(root, "loop"), 0);
assertEquals(50, complete(first, "analysis"), 0);
}
@Test
public void branchesResolveSkippedNodesWithoutChangingDenominator() {
tracker.initialize(1);
var root = tracker.item(1, List.of("start", "branch", "unused", "tail"));
complete(root, "start");
assertEquals(50, complete(root, "branch"), 0);
root.skipAbsent(List.of("start", "branch", "tail"));
assertEquals(75, event(NODE_STARTED, root, "tail"), 0);
assertEquals(99.99, complete(root, "tail"), 0);
}
@Test
public void pauseFreezesPublishedProgressAndResumeReusesLogicalUnits() {
tracker.initialize(1);
var root = tracker.item(1, List.of("loop", "tail"));
var first = root.child("loop", 1, 2, List.of("a", "b"));
complete(first, "a");
assertEquals(12.5, event(TASK_PAUSED, null, null), 0);
assertEquals(12.5, complete(first, "b"), 0);
assertSame(first, root.child("loop", 1, 2, List.of("a", "b")));
assertEquals(25, event(TASK_RESUMED, null, null), 0);
assertEquals(25, complete(first, "a"), 0);
}
@Test
public void failureAndStopFreezeProgressAndIgnoreLateCallbacks() {
for (var terminal : List.of(TASK_FAILED, TASK_STOPPED)) {
var state = new FlowProgressTracker();
state.initialize(1);
var root = state.item(1, List.of("a", "b"));
state.accept(FlowExecutionEvent.builder().eventType(NODE_COMPLETED)
.progressScope(root).nodeId("a").build());
assertEquals(50, state.accept(FlowExecutionEvent.builder().eventType(terminal).build()), 0);
assertEquals(50, state.accept(FlowExecutionEvent.builder().eventType(NODE_COMPLETED)
.progressScope(root).nodeId("b").build()), 0);
assertEquals(50, state.accept(FlowExecutionEvent.builder().eventType(TASK_COMPLETED).build()), 0);
}
}
@Test
public void largeItemCountsDoNotUseNegativeOrFixedOnePercentOffsets() {
tracker.initialize(200);
for (int i = 1; i <= 200; i++) {
var root = tracker.item(i, List.of("a"));
assertEquals(Math.min(99.99, i * .5), complete(root, "a"), 0);
}
}
@Test
public void emptyAndUnknownEventsAreSafe() {
tracker.initialize(0);
assertNull(tracker.item(1, List.of()));
assertEquals(0, event(NODE_STARTED, null, null), 0);
assertEquals(0, event(NODE_FAILED, null, null), 0);
assertEquals(100, event(TASK_COMPLETED, null, null), 0);
}
@Test
public void beanCopiesKeepRuntimeScopeButEventJsonDoesNotExposeIt() {
tracker.initialize(1);
var root = tracker.item(1, List.of("a"));
var source = new TaskNodeExecuteMessage();
source.setProgressScope(root);
var target = new TaskNodeExecuteMessage();
BeanUtil.copyProperties(source, target);
assertSame(root, target.getProgressScope());
String json = JSON.toJSONString(FlowExecutionEvent.builder().progressTracker(tracker)
.progressScope(root).progress(25D).build());
assertFalse(json.contains("progressTracker"));
assertFalse(json.contains("progressScope"));
assertTrue(json.contains("\"progress\":25"));
}
@Test
public void legacyEventsKeepPreviousProgressInsteadOfGuessingFromNodeCount() {
var event = FlowExecutionEvent.builder().eventType(NODE_STARTED).nodeCount(null).build();
assertEquals(12.5, FlowProgressTracker.progressOf(event, 12.5), 0);
event.setProgress(Double.NaN);
assertEquals(0, FlowProgressTracker.progressOf(event, null), 0);
event.setEventType(TASK_COMPLETED);
assertEquals(100, FlowProgressTracker.progressOf(event, null), 0);
}
}

View File

@ -0,0 +1,27 @@
-- Run once per database BEFORE deploying the workflow progress changes.
-- Idempotent on MySQL; existing successful executions are normalized to 100.
-- Historical partial progress cannot be reconstructed reliably from node IDs.
SET @progress_column_exists = (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'te_task_inst' AND column_name = 'progress'
);
SET @progress_ddl = IF(@progress_column_exists = 0,
'ALTER TABLE te_task_inst ADD COLUMN progress DECIMAL(5,2) NOT NULL DEFAULT 0 COMMENT ''Workflow work progress, 0..100''',
'SELECT 1');
PREPARE progress_stmt FROM @progress_ddl;
EXECUTE progress_stmt;
DEALLOCATE PREPARE progress_stmt;
UPDATE te_task_inst SET progress = 100 WHERE status = '0' AND (progress IS NULL OR progress <> 100);
-- Some deployments do not install the Aima module.
SET @aima_progress_exists = (
SELECT COUNT(*) FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'aima_task_instance' AND column_name = 'progress'
);
SET @aima_backfill = IF(@aima_progress_exists > 0,
'UPDATE aima_task_instance SET progress = 100 WHERE status = 0 AND (progress IS NULL OR progress <> 100)',
'SELECT 1');
PREPARE aima_progress_stmt FROM @aima_backfill;
EXECUTE aima_progress_stmt;
DEALLOCATE PREPARE aima_progress_stmt;