fix(tasks): 单片/单文件读不到跳过它,缺数据不许冒充已收齐

三处"一颗坏项拖垮整批"与一处假绿本体:

- BrandTaskStorageService:一片载荷读不到就整份聚合丢掉,而三个调用方
  (finalizeTask/abort/tryRecoverCompletedRunningTask)都没有就地 try;改逐片跳过长
  WARN,并把 receivedChunkCount/completed 的判据从 chunks.size()(DB 行数)改成
  真正读到的片数——拿行数比 chunkTotal 正是"118/119 行没数据仍判已完成"的形状;
  解析缓存与汇总状态两处同型"整批抛出"一并改成逐条跳过。
- AppearancePatentLlmBatchPipeline:候选收集跑在批循环之前,一抛就走不到循环体内
  那道 finally releaseRowInspection,本轮已申领的行要挂满处理中 TTL(15 分钟),
  且 terminalizeRoundExhaustedRows 跟着不执行(轮次到顶的行因此永不判死);改逐片容错。
- TransientPayloadStorageService:跨实例判据枚成 public 常量并提供 cause 链走法。
  resolvePayload 会把真实原因 rewrap 成「<errorMessage>: <pointer>」,消费端只摸顶层
  消息时「only exists on instance=」「does not exist」两处判定恒 false——跨实例留痕
  从未下过笔、"跳过该分片"分支是死代码。消费端(ChunkPayloadSupport/
  HistoryAssembler/ResultRowReader)全部改走共享常量+cause 链。
- SimilarAsinHistoryAssemblerTest 的假绿桩删除:改前它桩的是生产者早已不再产出的
  英文旧串,断言照旧绿;现在跑真实 resolvePayload 取异常(只 mock RustFS 边界),
  改前 15 跑 1 红、改后 15/15 绿。
- SimilarAsinStaleReopenSupport:客户端卡死尾句枚成常量、整句文案唯一出口,生产者
  与重开白名单共用;此前只是碰巧被前缀命中,生产者一改前缀就会"永不重开"。
This commit is contained in:
2026-10-27 15:09:41 +08:00
parent f3445c21c8
commit 07f973d9df
14 changed files with 1027 additions and 44 deletions
@@ -0,0 +1,213 @@
package com.nanri.aiimage.modules.appearancepatent.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.config.AppearancePatentProperties;
import com.nanri.aiimage.config.InstanceMetadata;
import com.nanri.aiimage.config.StorageProperties;
import com.nanri.aiimage.config.TransientStorageProperties;
import com.nanri.aiimage.modules.appearancepatent.client.AppearancePatentLlmClient;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentParsedPayloadDto;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentLlmBatchPipeline;
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentResultRowReader;
import com.nanri.aiimage.modules.file.service.object.RustfsObjectStorageService;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 候选收集阶段的「一片坏了不许拖垮整轮」(2026-10-27 生产误判后的用户口径:整表都要跑完,
* 单项有问题就跳过它继续下一项,不能因为一个坏项影响全部)。
*
* <p>{@code collectPendingLlmCandidates} 跑在批循环<b>之前</b>,而批循环里的
* {@code finally releaseRowInspection} 只在循环体内——collect 一抛就永远走不到那道释放:
* <ul>
* <li>本轮已申领的行挂在处理中标记上,要等 {@code IN_FLIGHT_TTL}(15 分钟)自己过期;</li>
* <li>{@code terminalizeRoundExhaustedRows} 收的是 collect 的返回值,collect 抛出时它也一并跳过,
* 轮次到顶的行因此永不判死。</li>
* </ul>
*
* <p>读失败的异常由<b>真实</b>的 {@link AppearancePatentResultRowReader} +
* {@link TransientPayloadStorageService#resolvePayload} 产出,不在测试里手写文案——
* 手写桩造的正是生产者早已不再产出的旧字面量(货源侧那支假绿用例的成因)。
*/
class AppearancePatentCandidateCollectionFaultToleranceTest {
private static final Long TASK_ID = 31610L;
private static final String SCOPE_HASH = "scope-a";
private static final String READABLE_HEAD =
"[{\"rowToken\":\"r1\",\"id\":\"1\",\"asin\":\"B0A0000001\",\"country\":\"US\","
+ "\"title\":\"RUNNING SHOE\",\"url\":\"http://img/1.jpg\",\"groupKey\":\"g1\"}]";
private static final String READABLE_TAIL =
"[{\"rowToken\":\"r3\",\"id\":\"3\",\"asin\":\"B0A0000003\",\"country\":\"US\","
+ "\"title\":\"COTTON BAG\",\"url\":\"http://img/3.jpg\",\"groupKey\":\"g3\"}]";
/** 归另一台实例的 local 指针:resolvePayload 抛中文「临时载荷仅存在于实例 …」,reader 再包成 BusinessException。 */
private static final String CROSS_INSTANCE_CHUNK =
"local:i/server-110/task-chunk/APPEARANCE_PATENT/" + TASK_ID + "/" + SCOPE_HASH + "/chunk-2.json";
private static final String MISSING_OBJECT_KEY =
"task-chunk/APPEARANCE_PATENT/" + TASK_ID + "/" + SCOPE_HASH + "/chunk-2.json";
private AppearancePatentTaskCacheService taskCacheService;
private AppearancePatentResultRowReader reader;
private AppearancePatentLlmBatchPipeline pipeline;
@BeforeEach
void setUp() {
taskCacheService = mock(AppearancePatentTaskCacheService.class);
// 载荷读不到的那一片走真实存储层(跨实例中文原文由它产出),其余两片按裸 JSON 直读
RustfsObjectStorageService rustfs = mock(RustfsObjectStorageService.class);
when(rustfs.isConfigured()).thenReturn(true);
when(rustfs.readObjectBytes(MISSING_OBJECT_KEY)).thenThrow(new IllegalStateException(
"The specified key does not exist. (Service: S3, Status Code: 404)"));
when(rustfs.listObjectKeysNewestFirst(anyString(), org.mockito.ArgumentMatchers.anyInt())).thenReturn(List.of());
TransientPayloadStorageService storage = new TransientPayloadStorageService(
mock(TransientStorageProperties.class), mock(StorageProperties.class), rustfs,
mock(OssStorageService.class), new ObjectMapper(), instanceMetadata("server-1"),
mock(TaskChunkMapper.class), mock(TaskScopeStateMapper.class));
reader = new AppearancePatentResultRowReader(
AppearancePatentTaskService.MODULE_TYPE, new ObjectMapper(), storage, mock(TaskChunkMapper.class),
value -> value == null ? "" : value.trim(), task -> new AppearancePatentParsedPayloadDto());
pipeline = pipeline(reader);
}
/**
* 中间那片读不到:跳过它,第三片仍要进候选。改前 collect 直接抛 BusinessException,
* 于是第一片已申领的 r1 挂在处理中标记上(15 分钟)、第三片根本没被读过。
*/
@Test
void unreadableChunkDoesNotAbortCandidateCollection() {
when(taskCacheService.beginRowInspection(eq(TASK_ID), anyString())).thenReturn(true);
List<AppearancePatentResultRowDto> candidates = pipeline.collectPendingLlmCandidates(
List.of(chunk(1, READABLE_HEAD), chunk(2, CROSS_INSTANCE_CHUNK), chunk(3, READABLE_TAIL)),
new AppearancePatentLlmBatchPipeline.ChunkRowKeyIndex());
assertEquals(List.of("r1", "r3"), rowTokens(candidates),
"坏的那一片要跳过,其余两片照常进候选");
}
/**
* 核心不变量(逐片容错与「异常路径统一 release」两种合法修法都满足,唯独现状不满足):
* 凡是申领成功的行,要么进候选、要么被显式 release,**不许**挂在处理中标记上等 TTL 自己过期。
*/
@Test
void claimedRowsAreNeverLeftInFlightWhenAChunkFails() {
when(taskCacheService.beginRowInspection(eq(TASK_ID), anyString())).thenReturn(true);
List<String> collected;
String thrown = null;
try {
collected = rowTokens(pipeline.collectPendingLlmCandidates(
List.of(chunk(1, READABLE_HEAD), chunk(2, CROSS_INSTANCE_CHUNK)),
new AppearancePatentLlmBatchPipeline.ChunkRowKeyIndex()));
} catch (RuntimeException ex) {
thrown = ex.getClass().getSimpleName() + ": " + ex.getMessage();
collected = List.of();
}
ArgumentCaptor<String> claimed = ArgumentCaptor.forClass(String.class);
verify(taskCacheService, atLeastOnce()).beginRowInspection(eq(TASK_ID), claimed.capture());
Set<String> released = releasedKeys();
assertTrue(claimed.getAllValues().contains("r1"), "夹具没能让第一片真的申领到行");
for (String key : claimed.getAllValues()) {
assertTrue(collected.contains(key) || released.contains(key),
"行 " + key + " 已申领却既没进候选也没释放——会挂满处理中 TTL 15 分钟;"
+ "抛出=" + thrown + ",候选=" + collected + ",已释放=" + released);
}
}
/** 对象缺失(NoSuchKey)那一种 reader 自己就跳了,collect 不得因它丢其余分片。 */
@Test
void missingObjectChunkIsSkippedAndCollectionContinues() {
when(taskCacheService.beginRowInspection(eq(TASK_ID), anyString())).thenReturn(true);
List<AppearancePatentResultRowDto> candidates = pipeline.collectPendingLlmCandidates(
List.of(chunk(1, READABLE_HEAD), chunk(2, "rustfs:" + MISSING_OBJECT_KEY), chunk(3, READABLE_TAIL)),
new AppearancePatentLlmBatchPipeline.ChunkRowKeyIndex());
assertEquals(List.of("r1", "r3"), rowTokens(candidates));
}
/**
* reader 侧契约不变:跨实例失败照旧抛出(它只放行「重试也没用」的对象缺失)。
* 这一支钉的是「容错做在 collect 那一边,没有把 reader 的判据一起放宽」。
*/
@Test
void readerStillThrowsForCrossInstanceChunkPayload() {
BusinessException thrown = assertThrows(BusinessException.class,
() -> reader.readChunkRows(chunk(2, CROSS_INSTANCE_CHUNK)));
assertTrue(thrown.getMessage().contains("读取外观专利结果分片失败"), "实际: " + thrown.getMessage());
}
// ===== 夹具 =====
private AppearancePatentLlmBatchPipeline pipeline(AppearancePatentResultRowReader rowReader) {
return new AppearancePatentLlmBatchPipeline(
mock(AppearancePatentProperties.class),
mock(AppearancePatentLlmClient.class),
taskCacheService,
mock(TaskFileJobService.class),
row -> row == null || row.getRowToken() == null ? "" : row.getRowToken(),
row -> true,
rowReader::readChunkRows,
taskId -> List.of(),
taskId -> false,
taskId -> {
},
task -> "prompt",
task -> "sk-test",
(taskId, scopeHash, chunkIndex, rows) -> List.of(),
(preferred, fallback) -> preferred == null || preferred.isBlank() ? fallback : preferred);
}
private Set<String> releasedKeys() {
ArgumentCaptor<List<String>> captor = ArgumentCaptor.forClass(List.class);
verify(taskCacheService, atLeast(0)).releaseRowInspection(anyLong(), captor.capture());
return captor.getAllValues().stream().flatMap(List::stream).collect(Collectors.toSet());
}
private static List<String> rowTokens(List<AppearancePatentResultRowDto> rows) {
return rows.stream().map(AppearancePatentResultRowDto::getRowToken).toList();
}
private static InstanceMetadata instanceMetadata(String instanceId) {
InstanceMetadata metadata = mock(InstanceMetadata.class);
when(metadata.getInstanceId()).thenReturn(instanceId);
return metadata;
}
private static TaskChunkEntity chunk(int index, String payloadJson) {
TaskChunkEntity chunk = new TaskChunkEntity();
chunk.setId((long) index);
chunk.setTaskId(TASK_ID);
chunk.setModuleType(AppearancePatentTaskService.MODULE_TYPE);
chunk.setScopeHash(SCOPE_HASH);
chunk.setChunkIndex(index);
chunk.setPayloadJson(payloadJson);
chunk.setPayloadHash("hash-" + index);
return chunk;
}
}