fix(外观专利): 失败兜底出部分结果文件+WAIT_LLM 停放作业心跳续租(31302/31354)

线上两例死法修复,目标是「任务失败了也能下载」:
- 31354:组装作业在 WAIT_LLM 停放期执行线程已退出、Worker 执行期心跳
  已取消,job 级 stuck 扫描按 updated_at 判陈旧,5 分钟阈值×5 次重试
  耗尽后误判「文件生成任务运行超时」。客户端心跳经
  AppearancePatentTaskHeartbeatSpi#onHeartbeat 按
  dbJobTouchIntervalMillis(默认 60s,远小于 5 分钟阈值)节流续租
  (touchRunningAssembleJobsIfStale,与 SimilarAsin 同口径)。
- 31302:覆盖率闸门判红重试 5 次判死后,1196 行成品零交付且不能下载。
  接通 fallbackAssembleOnFailure 兜底钩子:作业判死后用已有分片出
  部分结果文件(validateCompleteLlmCoverage 加 allowPartial 旁路),
  写上 result.resultFileUrl 后前端下载按钮即恢复;兜底幂等(已有
  结果文件短 路)、不动任务终态、与补传恢复重跑兼容。
- 棘轮尺 STRICT_TOTAL 1003→1004、NOT_RETHROW 561→562 抬格并逐处
  记名(兜底自吞 catch 属接口契约要求的 fail-open 形状)。

全量 mvn -o test 4492 支 0 失败(9 skipped 为既有跳过)。
This commit is contained in:
2026-10-18 23:41:24 +08:00
parent 1be4d766bb
commit 49eee59a13
10 changed files with 424 additions and 8 deletions
@@ -181,6 +181,24 @@ class AppearancePatentDeliveryGateTest {
}
}
/** 失败兜底路径的 4 参口径:allowPartial=true 时覆盖率闸门放行(作业已判死,缺口不再有补齐窗口)。 */
private AppearancePatentRowOutcome.Facts validatePartial(List<AppearancePatentParsedRowVo> rows,
Map<String, AppearancePatentResultRowDto> resultMap,
boolean allowPartial)
throws Exception {
Method method = AppearancePatentTaskService.class.getDeclaredMethod(
"validateCompleteLlmCoverage", Long.class, List.class, Map.class, boolean.class);
method.setAccessible(true);
try {
return (AppearancePatentRowOutcome.Facts) method.invoke(service, TASK_ID, rows, resultMap, allowPartial);
} catch (InvocationTargetException ex) {
if (ex.getCause() instanceof RuntimeException runtime) {
throw runtime;
}
throw ex;
}
}
private boolean requestRecheck(FileTaskEntity task, TaskFileJobEntity job,
AppearancePatentRowOutcome.Facts facts) throws Exception {
Method method = AppearancePatentTaskService.class.getDeclaredMethod(
@@ -254,6 +272,24 @@ class AppearancePatentDeliveryGateTest {
assertEquals(5, facts.noDataRows());
}
@Test
void allowPartialLetsBelowFloorCoverageThroughForFailureFallback() throws Exception {
// 同一份 50% 覆盖率:常规路径判红(belowFloorThrowsWithBothCountersInTheMessage),
// 兜底路径放行——作业已判死,此刻拦下成品只会让用户连半张表都拿不到(线上任务 31302)
List<AppearancePatentParsedRowVo> rows = List.of(sheetRow("1", "B0A1"), sheetRow("2", "B0A2"),
sheetRow("3", "B0A3"));
Map<String, AppearancePatentResultRowDto> map = new LinkedHashMap<>();
map.putAll(submittedRows(List.of(sheetRow("1", "B0A1")), 1, true));
map.putAll(submittedRows(List.of(sheetRow("2", "B0A2")), 0, true));
map.putAll(submittedRows(List.of(sheetRow("3", "B0A3")), 0, false));
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(task("RUNNING"));
AppearancePatentRowOutcome.Facts facts = validatePartial(rows, map, true);
assertEquals(2, facts.expectedRows());
assertEquals(1, facts.judgedRows());
assertEquals(1, facts.missingRows());
}
// ---------- 补检出口 ----------
@Test
@@ -0,0 +1,150 @@
package com.nanri.aiimage.modules.appearancepatent.service;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.config.AppearancePatentProperties;
import com.nanri.aiimage.config.InstanceMetadata;
import com.nanri.aiimage.config.StorageProperties;
import com.nanri.aiimage.modules.appearancepatent.client.AppearancePatentLlmClient;
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService;
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.transaction.PlatformTransactionManager;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 失败兜底组装的守卫与幂等(2026-10-18,线上任务 31302/31354 死因修复)。
*
* <p>组装作业重试耗尽判死后,用户要「起码失败了也可以下载」:兜底用已有分片/结论出
* 部分结果文件。本类钉住兜底入口的分支语义;组装主体(xlsx 生成/上传)由
* AppearancePatentSheetBuilderTest/AppearancePatentResultFormatTest/交付闸门测试覆盖。
*/
class AppearancePatentFallbackAssembleTest {
private static final long TASK_ID = 31302L;
private static final long RESULT_ID = 9001L;
private static final long JOB_ID = 7001L;
private final FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
private final FileResultMapper fileResultMapper = mock(FileResultMapper.class);
private final TaskScopeStateMapper taskScopeStateMapper = mock(TaskScopeStateMapper.class);
private final TaskChunkMapper taskChunkMapper = mock(TaskChunkMapper.class);
private final LocalFileStorageService localFileStorageService = mock(LocalFileStorageService.class);
private final AppearancePatentLlmClient llmClient = mock(AppearancePatentLlmClient.class);
private final AppearancePatentTaskCacheService taskCacheService = mock(AppearancePatentTaskCacheService.class);
private final AppearancePatentProperties properties = mock(AppearancePatentProperties.class);
private final StorageProperties storageProperties = mock(StorageProperties.class);
private final TaskFileJobService taskFileJobService = mock(TaskFileJobService.class);
private final TaskProgressSnapshotService taskProgressSnapshotService = mock(TaskProgressSnapshotService.class);
private final TransientPayloadStorageService transientPayloadStorageService = mock(TransientPayloadStorageService.class);
private final PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class);
private final DistributedJobLockService distributedJobLockService = mock(DistributedJobLockService.class);
private final TaskDistributedLockService taskDistributedLockService = mock(TaskDistributedLockService.class);
private final InstanceMetadata instanceMetadata = mock(InstanceMetadata.class);
private AppearancePatentTaskService service;
@BeforeEach
void setUp() {
when(properties.getLlmCoverageMinRatio()).thenReturn(0.95D);
service = new AppearancePatentTaskService(
localFileStorageService, null,
mock(com.nanri.aiimage.common.service.ResultDownloadResolver.class),
storageProperties, fileTaskMapper, fileResultMapper,
taskScopeStateMapper, taskChunkMapper, new ObjectMapper(), llmClient, taskCacheService,
properties, taskFileJobService, taskProgressSnapshotService,
mock(TaskHeartbeatPositionService.class), transientPayloadStorageService, transactionManager,
distributedJobLockService, taskDistributedLockService, instanceMetadata,
mock(TaskProgressLightAssembler.class), mock(UserApiSecretService.class));
}
private static TaskFileJobEntity job() {
TaskFileJobEntity job = new TaskFileJobEntity();
job.setId(JOB_ID);
job.setTaskId(TASK_ID);
job.setResultId(RESULT_ID);
job.setModuleType("APPEARANCE_PATENT");
job.setStatus("FAILED");
return job;
}
private static FileResultEntity result(String resultFileUrl) {
FileResultEntity result = new FileResultEntity();
result.setId(RESULT_ID);
result.setTaskId(TASK_ID);
result.setModuleType("APPEARANCE_PATENT");
result.setResultFileUrl(resultFileUrl);
return result;
}
private static FileTaskEntity task() {
FileTaskEntity task = new FileTaskEntity();
task.setId(TASK_ID);
task.setModuleType("APPEARANCE_PATENT");
task.setStatus("FAILED");
task.setUserId(7L);
return task;
}
@Test
void incompleteJobArgumentsAreRejected() {
assertFalse(service.fallbackAssembleResultFile(null), "null 作业直接拒绝");
assertFalse(service.fallbackAssembleResultFile(new TaskFileJobEntity()), "缺 taskId/resultId 直接拒绝");
}
@Test
void missingResultRecordReturnsFalse() {
when(fileResultMapper.selectById(RESULT_ID)).thenReturn(null);
assertFalse(service.fallbackAssembleResultFile(job()), "结果记录不存在(孤儿作业)无可组装");
verify(fileTaskMapper, never()).selectById(any());
}
@Test
void existingResultFileShortCircuitsAssemble() {
// 幂等:stuck 扫描对终态失败作业每轮重入兜底钩子,已有结果文件就不再重做组装
when(fileResultMapper.selectById(RESULT_ID)).thenReturn(result("appearance-patent/existing.xlsx"));
assertTrue(service.fallbackAssembleResultFile(job()), "已有结果文件视为兜底成功");
verify(fileTaskMapper, never()).selectById(any());
verify(fileResultMapper, never()).updateById(any(FileResultEntity.class));
}
@Test
void missingTaskRecordReturnsFalse() {
when(fileResultMapper.selectById(RESULT_ID)).thenReturn(result(null));
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(null);
assertFalse(service.fallbackAssembleResultFile(job()), "任务记录不存在无可组装");
}
@Test
void emptyPayloadFailsSoftlyWithoutTouchingResult() {
// 组装抛业务异常(无可解析行)时兜底自吞:返回 false、不改写 result,作业保持终态失败
when(fileResultMapper.selectById(RESULT_ID)).thenReturn(result(null));
FileTaskEntity task = task();
task.setResultJson("{}");
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(task);
assertFalse(service.fallbackAssembleResultFile(job()), "空载荷组装失败要被吞掉");
verify(fileResultMapper, never()).updateById(any(FileResultEntity.class));
}
}
@@ -0,0 +1,73 @@
package com.nanri.aiimage.modules.appearancepatent.service;
import com.nanri.aiimage.config.AppearancePatentProperties;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* 外观专利任务心跳的组装作业续租(2026-10-18,线上任务 31354 死因修复)。
*
* <p>组装作业在 WAIT_LLM 停放期间执行线程已退出、Worker 执行期心跳已取消,若无人续命,
* job 级 stuck 扫描(stuck-timeout-minutes 默认 5 分钟)会按 updated_at 判陈旧、
* 5 次重试耗尽后误判「文件生成任务运行超时」。客户端心跳经 onHeartbeat 触发
* touchRunningAssembleJobsIfStale 按配置间隔节流续租(与 SimilarAsinTaskHeartbeatSpi 同口径)。
*/
class AppearancePatentTaskHeartbeatSpiTest {
private final AppearancePatentTaskCacheService cacheService = mock(AppearancePatentTaskCacheService.class);
private final TaskFileJobService taskFileJobService = mock(TaskFileJobService.class);
private final AppearancePatentProperties properties = new AppearancePatentProperties();
private AppearancePatentTaskHeartbeatSpi spi;
@BeforeEach
void setUp() {
spi = new AppearancePatentTaskHeartbeatSpi(cacheService, taskFileJobService, properties);
}
@Test
void onHeartbeatRenewsAssembleJobLease() {
FileTaskEntity task = new FileTaskEntity();
task.setId(31354L);
task.setModuleType("APPEARANCE_PATENT");
spi.onHeartbeat(task);
verify(taskFileJobService).touchRunningAssembleJobsIfStale(31354L, "APPEARANCE_PATENT",
properties.getDbJobTouchIntervalMillis());
}
@Test
void touchIntervalBelowStuckScanFloor() {
// 续命间隔必须小于 stuck 扫描阈值(5 分钟),否则停放作业在两跳续命之间仍会被判陈旧
org.junit.jupiter.api.Assertions.assertTrue(properties.getDbJobTouchIntervalMillis() < 5 * 60_000L,
"dbJobTouchIntervalMillis 应小于 stuck-timeout-minutes=5 分钟,实际 "
+ properties.getDbJobTouchIntervalMillis());
}
@Test
void onHeartbeatWithNullTaskTouchesNothing() {
spi.onHeartbeat(null);
FileTaskEntity task = new FileTaskEntity();
spi.onHeartbeat(task);
verifyNoInteractions(taskFileJobService);
}
@Test
void touchHeartbeatStillDelegatesToCache() {
spi.touchHeartbeat(1L, null);
verify(cacheService).touchTaskHeartbeat(1L);
}
@Test
void moduleTypeMatchesRegistry() {
org.junit.jupiter.api.Assertions.assertEquals("APPEARANCE_PATENT", spi.moduleType());
}
}
@@ -77,4 +77,21 @@ class AppearancePatentResultFileJobHandlerTest {
handler.cleanup(null);
org.mockito.Mockito.verify(appearancePatentTaskService).cleanupResultFileJob(null);
}
@Test
void fallbackAssembleDelegates() {
// 重试耗尽(含 WAIT_LLM 停放被 stuck 棘轮判死)时委托 Service 出部分结果文件
TaskFileJobEntity job = new TaskFileJobEntity();
when(appearancePatentTaskService.fallbackAssembleResultFile(job)).thenReturn(true);
assertTrue(handler.fallbackAssembleOnFailure(job, "文件生成任务运行超时,已达到最大重试次数"),
"兜底产出可下载结果时返回 true");
}
@Test
void fallbackAssembleFailureReturnsFalse() {
TaskFileJobEntity job = new TaskFileJobEntity();
when(appearancePatentTaskService.fallbackAssembleResultFile(job)).thenReturn(false);
assertFalse(handler.fallbackAssembleOnFailure(job, "结果文件生成失败"),
"兜底也失败时返回 false,不影响作业已终态失败的事实");
}
}
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.task.service;
import com.nanri.aiimage.config.AppearancePatentProperties;
import com.nanri.aiimage.config.SimilarAsinProperties;
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskCacheService;
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskHeartbeatSpi;
@@ -46,7 +47,9 @@ class TaskModuleHeartbeatSpiCoverageTest {
private static Map<String, TaskModuleHeartbeatSpi> implementationsByModuleType() {
Map<String, TaskModuleHeartbeatSpi> impls = new LinkedHashMap<>();
register(impls, new AppearancePatentTaskHeartbeatSpi(mock(AppearancePatentTaskCacheService.class)));
register(impls, new AppearancePatentTaskHeartbeatSpi(
mock(AppearancePatentTaskCacheService.class), mock(TaskFileJobService.class),
mock(AppearancePatentProperties.class)));
register(impls, new CollectDataTaskHeartbeatSpi(mock(CollectDataService.class)));
register(impls, new DeleteBrandTaskHeartbeatSpi(mock(DeleteBrandTaskCacheService.class)));
register(impls, new PatrolDeleteTaskHeartbeatSpi(mock(PatrolDeleteTaskCacheService.class)));