fix(phase-2): 任务活性与失败归因六格收口——在飞豁免/锚点分流/同源判据/回落一元化/巡检按账号分组
蓝图 docs/REFACTOR_PLAN.md Phase 2 的 ①②③④⑥ 五格+台账登记。⑤(failure_category)
未做,原因见文末,不以此笔冒充闭环。
① B74-02 卡死阈值二选一 → 选"扫描询问执行侧",没有抬阈值。
取证:B 侧 24h 批次 costMs 实测 22,988 / 85,298 / 939,172(单行批次 15.6 分钟),
A 侧今天 06:07:20 `STUCK_REQUEUE_EXHAUSTED jobId=23815 taskId=33179 stuckRequeueCount=20`,
06:08 复位恢复、09:20 同样两条=环。真因不是批次长:`startJobHeartbeat` 在父任务终态时
按 CR-08 刻意停止续期(stage=TERMINAL_STOP_RENEW),执行线程还在跑而 updated_at 冻结,
扫描每 5 分钟扣一次计数。冻结是**无限期**的,抬到 16 分钟只把 20 次计满从 100 分钟拖到
320 分钟,还把真遗骸回收拖慢 ⇒ 改为 TaskFileJobService 持内存在飞登记
(markInFlight/clearInFlight/isInFlight),扫描对"本机线程还在跑"的行不重排也不计数;
登记面随进程重启即空,遗骸回收形状不变。worker 侧登记在 activateRunningClaim 之后、
注销在 finally(finishAfterExecution 之后再注销)。
③ B74-03 判死谓词分流(先取证后动手,红线照办)。
取证:云助手只读 HGETALL+TTL 两枚 stall 键自洽——33179 pos="Linux后台抓取: 606/676"
与当前 progressText 逐字相同、at 距 now 16,058s(4.46h)、TTL 余 16,342s ⇒ 键 TTL 设定
32,400s = 9h = 窗口(180min)×3;33149 同样自洽。机制坐实:键一过期 evaluateAgainstSnapshot
就把起点重锚到 now 并直接 ADVANCING ⇒ 每 9 小时白送一轮完整豁免,沉默客户端永远封不了口
(11-02 那串"客户端仍在推进"即此形状)。改法:快照缺失/at 读不出与"指纹真变"分口,
重建锚点锚到**客户端最后一次上报时刻**(位置哈希自己的 at,此前无人读过),再走同一条
时间判据;客户端确在心跳时锚点仍新鲜 ⇒ 照旧 ADVANCING,判死线不提前(28919 教训在册)。
P0-C2 快照按"更新即登记"补 3 支:沉默超窗不得豁免/at 读不出走同一条判据/心跳中照旧放行。
② B74-01 三格:landed 与 isJudged 收成同源(mergeLlmRowsIntoChunks 认的"塞回分片"不是结论,
旧写法给只有 patentRisk 的行打 24h 标记 ⇒ 既不再是候选又无结论列);beginRowInspection 的
Redis null 由"抢到"改判"未抢到"(抛异常的真降级照旧放行,两条不同路);
deleteExtraTaskCacheKeys 原删的是从不写入的基键=删空气,改按 processed-rows:{taskId}:*
游标 SCAN 删真实逐行标记(用 SCAN 不用 KEYS)。新断言做过反向验证:摘掉 isJudged 闸门
即真红,不是白过。terminalizeRoundExhaustedRows 是按轮次上限终态化的唯一豁免,已写明。
④ B74-04 四台 JSON 回落收成唯一出处 TaskOwnerJsonFallback(result_json 正档先于 request_json;
店铺采集此前只读 request_json ⇒ 列缺失的 39 行 RUNNING 存量行在不同校验里算出两个归属)。
TaskOwnerReadSourceGuardrailTest 补回落面:四台不得再有本地回落写法,且顺序钉在那一处。
⑥ B73-03 巡检分组键按供应商账号折(供应商, 提取域, 排序后 query 的摘要——只落摘要,
链接里的账密明文不进日志/告警面)。青果整个账号只有 1 条通道,旧 moduleKey|channel|密文
让同一把 key 多开几枪就自己把用户的代理打成 channel_busy。另一半边界同样钉住:
非链接型凭据(LLM 密钥)照旧逐模块分组,否则拿 A 渠道的结论冒充 B。
台账:SourceScanTest 裸名 23→24(新增 TaskOwnerJsonFallback.java 这一枚),
与 2026-11-02 那次 22→23 同法逐笔写明是谁的哪一笔、为什么只能打在源码连线上。
门禁实录:mvn -o test 整量 **5256 例/0 失败/0 错误/19 skipped,BUILD SUCCESS**;
mvn -o test-compile rc=0;定向面另点过(56/88/34+70/63/104 例全绿);
本仓后端无 spotless/checkstyle ⇒ lint 与格式步如实登记、不是漏执行。
未做的一格(⑤ B51-R1 failure_category):取证显示 biz_file_task.error_message 的落库点
**没有单一出口**(LambdaUpdateWrapper.set(errorMessage) 15 处+setErrorMessage 若干,
合计约 25 处,且清 null 的分支也必须同步清列)。这不是"改一支方法"的量级,
拿半截双写冒充 Expand 会变成列恒为 NULL 的死代码 ⇒ 留作单独一笔,蓝图保持未勾。
This commit is contained in:
+45
-2
@@ -4,10 +4,13 @@ import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResu
|
||||
import com.nanri.aiimage.modules.task.service.AbstractPendingRowTaskCacheService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.Cursor;
|
||||
import org.springframework.data.redis.core.ScanOptions;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -36,9 +39,45 @@ public class AppearancePatentTaskCacheService extends AbstractPendingRowTaskCach
|
||||
super("appearance-patent", AppearancePatentResultRowDto.class, stringRedisTemplate, objectMapper);
|
||||
}
|
||||
|
||||
/** 单次清理最多删除多少枚逐行标记(游标侧的安全阀,防止把一次清理变成无界扫描)。 */
|
||||
private static final int ROW_MARK_DELETE_LIMIT = 20_000;
|
||||
|
||||
@Override
|
||||
protected void deleteExtraTaskCacheKeys(Long taskId) {
|
||||
stringRedisTemplate.delete(processedRowsKey(taskId));
|
||||
// B74-01:这里原本删的是 processedRowsKey(taskId)——一枚**从不被写入**的基键。
|
||||
// 真实完成标记是逐行键 ...:processed-rows:{taskId}:{rowKey},所以"清了任务缓存"
|
||||
// 一枚行标记都清不掉:任务清完后 24 小时内重建,行仍被标记挡着不再检测,
|
||||
// 声称保护但不保护。逐行键没有索引,只能按前缀游标扫;用 SCAN 而不是 KEYS
|
||||
// (KEYS 在生产 redis 上是阻塞命令)。
|
||||
String pattern = processedRowsKey(taskId) + ":*";
|
||||
List<String> found = new ArrayList<>();
|
||||
try (Cursor<String> cursor = stringRedisTemplate.scan(
|
||||
ScanOptions.scanOptions().match(pattern).count(500).build())) {
|
||||
while (cursor != null && cursor.hasNext()) {
|
||||
String key = cursor.next();
|
||||
if (key != null && !key.isBlank()) {
|
||||
found.add(key);
|
||||
}
|
||||
if (found.size() >= ROW_MARK_DELETE_LIMIT) {
|
||||
log.warn("[appearance-patent-cache] 行标记清理已达单轮上限,剩余由 TTL 兜底 "
|
||||
+ "taskId={} limit={}", taskId, ROW_MARK_DELETE_LIMIT);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
// 与本类其余降级口径一致:清不掉就报出来,别让调用方以为"已经清干净了"。
|
||||
log.warn("[appearance-patent-cache] delete row marks degraded taskId={} pattern={} msg={}",
|
||||
taskId, pattern, ex.getMessage());
|
||||
return;
|
||||
}
|
||||
if (found.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
// 逐行键一起删:基键顺手也删一次(今天它依然不存在,但形状上它是这一族的目录名)。
|
||||
found.add(processedRowsKey(taskId));
|
||||
stringRedisTemplate.delete(found);
|
||||
log.info("[appearance-patent-cache] 行标记已随任务缓存清理 taskId={} rowMarks={}",
|
||||
taskId, found.size() - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -58,7 +97,11 @@ public class AppearancePatentTaskCacheService extends AbstractPendingRowTaskCach
|
||||
}
|
||||
Boolean first = stringRedisTemplate.opsForValue().setIfAbsent(
|
||||
inFlightRowKey(taskId, rowKey), "1", IN_FLIGHT_TTL);
|
||||
return first == null || first;
|
||||
// B74-01:Redis 回 null(管道/事务态、集群未回包)不等于"抢到了"。旧写法
|
||||
// `first == null || first` 把「没抢到」读成「抢到了」,同一行可能被两个入口同时发出去
|
||||
// ——重复计费,且两路各自 CAS 同一行。读不出就按未抢到处理,让下一轮重新申领。
|
||||
// 注意这不同于 Redis 抛异常:真降级在下面的 catch 里放行,由持久化层 isJudged 兜底。
|
||||
return Boolean.TRUE.equals(first);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[appearance-patent-cache] begin row inspection degraded taskId={} rowKey={} msg={}", taskId, rowKey, ex.getMessage());
|
||||
// Redis 降级时放行,由持久化层的 AppearancePatentRowOutcome.isJudged 判据兜底去重。
|
||||
|
||||
+35
-1
@@ -208,7 +208,15 @@ public class AppearancePatentLlmBatchPipeline {
|
||||
Set<String> landedKeys = mergeLlmRowsIntoChunks(task, llmRows, batchRows, rowKeyIndex);
|
||||
// 完成标记只能打在真正落库的行上——这是「发版重启会不会丢行」的分界线
|
||||
if (batchAnswered) {
|
||||
List<String> landed = batchRowKeys.stream().filter(landedKeys::contains).toList();
|
||||
// B74-01:landed(被塞回某个分片载荷)与 isJudged(有结论列)是两套判据,
|
||||
// 谁说了算必须只有一个。候选侧(collectPendingLlmCandidates)用的是 isJudged,
|
||||
// 所以完成标记也必须只打给 isJudged 认的行——否则一行拿到 24 小时标记却没有
|
||||
// 结论列:它既不再是候选(被标记挡着),也没结论可出,只能等补检把标记连根撤掉。
|
||||
Set<String> judgedKeys = judgedRowKeys(llmRows);
|
||||
List<String> landed = batchRowKeys.stream()
|
||||
.filter(landedKeys::contains)
|
||||
.filter(judgedKeys::contains)
|
||||
.toList();
|
||||
if (!landed.isEmpty()) {
|
||||
taskCacheService.completeRowInspection(task.getId(), landed);
|
||||
}
|
||||
@@ -547,6 +555,32 @@ public class AppearancePatentLlmBatchPipeline {
|
||||
return rowKeyer.apply(row);
|
||||
}
|
||||
|
||||
/**
|
||||
* 本批里「已经有结论」的行键。候选侧({@code collectPendingLlmCandidates})与完成标记侧
|
||||
* 共用同一枚 {@link AppearancePatentRowOutcome#isJudged},这就是 B74-01 要的同源判据:
|
||||
* 「谁说了算」只能有一个,否则一行会同时「被标记挡住不再是候选」且「没有结论列可出」。
|
||||
*
|
||||
* <p>唯一的例外是 {@code terminalizeRoundExhaustedRows}:那里的行是按**轮次上限**终态化的
|
||||
* (结论列写着「重发轮次已达上限」),它的完成标记正是有界路径的收口闸门,按 isJudged 再筛
|
||||
* 会让这些行永远回到候选——那才是无界循环。
|
||||
*/
|
||||
private Set<String> judgedRowKeys(List<AppearancePatentResultRowDto> rows) {
|
||||
Set<String> keys = new LinkedHashSet<>();
|
||||
if (rows == null) {
|
||||
return keys;
|
||||
}
|
||||
for (AppearancePatentResultRowDto row : rows) {
|
||||
if (row == null || !AppearancePatentRowOutcome.isJudged(row)) {
|
||||
continue;
|
||||
}
|
||||
String key = rowKey(row);
|
||||
if (key != null && !key.isBlank()) {
|
||||
keys.add(key);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
private Map<String, AppearancePatentResultRowDto> readChunkRows(TaskChunkEntity chunk) {
|
||||
return chunkRowReader.apply(chunk);
|
||||
}
|
||||
|
||||
+4
-11
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
|
||||
import com.nanri.aiimage.config.InstanceMetadata;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.support.TaskOwnerJsonFallback;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.Objects;
|
||||
@@ -82,17 +83,9 @@ public class AppearancePatentTaskOwnership {
|
||||
if (task.getOwnerInstanceId() != null && !task.getOwnerInstanceId().isBlank()) {
|
||||
return task.getOwnerInstanceId();
|
||||
}
|
||||
if (task.getResultJson() == null || task.getResultJson().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
String owner = objectMapper.readTree(task.getResultJson()).path("ownerInstanceId").asText("");
|
||||
return owner.isBlank() ? null : owner;
|
||||
} catch (Exception ex) {
|
||||
log.warn("[appearance-patent] read task owner failed taskId={} err={}",
|
||||
task.getId(), ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
// 回落口径四台共用一处(B74-04):本台此前只读 result_json,店铺采集读 request_json,
|
||||
// 同一条列缺失的行在两台眼里会有两个归属。
|
||||
return TaskOwnerJsonFallback.ownerFrom(task, objectMapper, "appearance-patent");
|
||||
}
|
||||
|
||||
public String ownerFromScopeKey(String scopeKey) {
|
||||
|
||||
+3
-14
@@ -34,6 +34,7 @@ import com.nanri.aiimage.modules.publish.model.vo.PublishTaskBatchVo;
|
||||
import com.nanri.aiimage.modules.publish.model.vo.PublishTaskDetailVo;
|
||||
import com.nanri.aiimage.modules.publish.model.vo.PublishTaskVo;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
||||
import com.nanri.aiimage.modules.task.service.support.TaskOwnerJsonFallback;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||
@@ -1339,20 +1340,8 @@ public class PublishTaskService extends AbstractFileTaskPipeline<PublishRowDto>
|
||||
if (column != null && !column.isBlank()) {
|
||||
return column.trim();
|
||||
}
|
||||
if (task.getResultJson() == null || task.getResultJson().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode root = objectMapper.readTree(task.getResultJson());
|
||||
if (root == null) {
|
||||
return null;
|
||||
}
|
||||
String owner = root.path("ownerInstanceId").asText("");
|
||||
return owner.isBlank() ? null : owner;
|
||||
} catch (Exception ex) {
|
||||
log.warn("[publish] read task owner failed taskId={} msg={}", task.getId(), safeMessage(ex));
|
||||
return null;
|
||||
}
|
||||
// 回落口径四台共用一处(B74-04)
|
||||
return TaskOwnerJsonFallback.ownerFrom(task, objectMapper, "publish");
|
||||
}
|
||||
|
||||
private String currentInstanceId() {
|
||||
|
||||
+8
-10
@@ -30,6 +30,7 @@ import com.nanri.aiimage.modules.shopdatacrawl.model.vo.ShopDataCrawlResultItemV
|
||||
import com.nanri.aiimage.modules.shopdatacrawl.spi.DuplicateCheckRefreshPort;
|
||||
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
||||
import com.nanri.aiimage.modules.task.service.support.TaskOwnerJsonFallback;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||
@@ -3111,8 +3112,12 @@ public class ShopDataCrawlTaskService extends AbstractFileTaskPipeline<ShopDataC
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务归属实例 id:优先读显式列 owner_instance_id(Task 34 迁移),
|
||||
* 旧任务列缺失时兼容回退到 request_json.ownerInstanceId。
|
||||
* 任务归属实例 id:优先读显式列 owner_instance_id(Task 34 迁移),列缺失时走四台共用的
|
||||
* JSON 回落口径({@link TaskOwnerJsonFallback},B74-04)。
|
||||
*
|
||||
* <p>本台此前只回落到 request_json,而另外三台回落到 result_json——列缺失的存量行
|
||||
* (实测 RUNNING 任务里 39 行)因此在不同校验里会算出不同归属,这正是 2026-11-02
|
||||
* 互斥死锁的家族形状。回落顺序现在只有一个出处。
|
||||
*/
|
||||
public String ownerInstanceIdOf(FileTaskEntity task) {
|
||||
if (task != null && !blank(task.getOwnerInstanceId())) {
|
||||
@@ -3126,14 +3131,7 @@ public class ShopDataCrawlTaskService extends AbstractFileTaskPipeline<ShopDataC
|
||||
}
|
||||
|
||||
private String ownerFromJson(FileTaskEntity task) {
|
||||
if (task == null || blank(task.getRequestJson())) return null;
|
||||
try {
|
||||
String owner = objectMapper.readTree(task.getRequestJson()).path("ownerInstanceId").asText("");
|
||||
return blank(owner) ? null : owner;
|
||||
} catch (Exception ex) {
|
||||
log.warn("[shop-data-crawl] read task owner failed taskId={} msg={}", task.getId(), ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
return TaskOwnerJsonFallback.ownerFrom(task, objectMapper, "shop-data-crawl");
|
||||
}
|
||||
|
||||
private String currentInstanceId() {
|
||||
|
||||
+3
-10
@@ -12,6 +12,7 @@ import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinResultRowDto;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.support.TaskOwnerJsonFallback;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity;
|
||||
@@ -133,16 +134,8 @@ public class SimilarAsinTaskOwnershipSupport {
|
||||
if (column != null && !column.isBlank()) {
|
||||
return column.trim();
|
||||
}
|
||||
if (task.getResultJson() == null || task.getResultJson().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
String owner = objectMapper.readTree(task.getResultJson()).path("ownerInstanceId").asText("");
|
||||
return owner.isBlank() ? null : owner;
|
||||
} catch (Exception ex) {
|
||||
log.warn("[similar-asin] read task owner failed taskId={} err={}", task.getId(), ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
// 回落口径四台共用一处(B74-04)
|
||||
return TaskOwnerJsonFallback.ownerFrom(task, objectMapper, "similar-asin");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+57
-3
@@ -19,6 +19,8 @@ import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@@ -38,6 +40,12 @@ public class TaskFileJobService {
|
||||
private final TaskFileJobMapper taskFileJobMapper;
|
||||
private final ApplicationEventPublisher applicationEventPublisher;
|
||||
|
||||
/**
|
||||
* 本机执行线程正在跑的作业 id(B74-02,见 {@link #isInFlight})。
|
||||
* 只在内存里,进程重启即空——那正是需要的形状:遗骸照旧被扫描回收。
|
||||
*/
|
||||
private final Set<Long> inFlightJobIds = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public TaskFileJobEntity enqueueAssembleResult(Long taskId, String moduleType, Long resultId, String scopeKey) {
|
||||
if (taskId == null || taskId <= 0 || moduleType == null || moduleType.isBlank() || resultId == null || resultId <= 0) {
|
||||
return null;
|
||||
@@ -446,6 +454,7 @@ public class TaskFileJobService {
|
||||
.last("limit " + Math.max(1, Math.min(limit, 200))));
|
||||
int reset = 0;
|
||||
int skippedForeignOwner = 0;
|
||||
int skippedInFlight = 0;
|
||||
List<TaskFileJobEntity> exhaustedJobs = new ArrayList<>();
|
||||
List<Long> eventJobIds = new ArrayList<>();
|
||||
List<Long> exhaustedJobIds = new ArrayList<>();
|
||||
@@ -507,6 +516,12 @@ public class TaskFileJobService {
|
||||
job.getId(), job.getTaskId(), rowOwner, currentInstanceId);
|
||||
continue;
|
||||
}
|
||||
if (isInFlight(job.getId())) {
|
||||
skippedInFlight++;
|
||||
log.debug("[task-file-job] stuck reset 跳过本机正在执行的作业 jobId={} taskId={} stuckRequeueCount={}",
|
||||
job.getId(), job.getTaskId(), job.getStuckRequeueCount());
|
||||
continue;
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
int stuckCount = job.getStuckRequeueCount() == null ? 0 : job.getStuckRequeueCount();
|
||||
if (stuckCount >= MAX_STUCK_REQUEUE) {
|
||||
@@ -588,9 +603,9 @@ public class TaskFileJobService {
|
||||
exhaustedJobs.add(refreshed == null ? originalJobsById.get(jobId) : refreshed);
|
||||
}
|
||||
}
|
||||
if (skippedForeignOwner > 0) {
|
||||
log.info("[task-file-job] stuck reset 按归属跳过其它实例的 RUNNING 作业 skipped={} current={} scanned={}",
|
||||
skippedForeignOwner, currentInstanceId, jobs.size());
|
||||
if (skippedForeignOwner > 0 || skippedInFlight > 0) {
|
||||
log.info("[task-file-job] stuck reset 活性豁免 skippedForeignOwner={} skippedInFlight={} current={} scanned={}",
|
||||
skippedForeignOwner, skippedInFlight, currentInstanceId, jobs.size());
|
||||
}
|
||||
return new StuckJobResetResult(reset, List.copyOf(exhaustedJobs));
|
||||
}
|
||||
@@ -760,6 +775,45 @@ public class TaskFileJobService {
|
||||
.set(TaskFileJobEntity::getUpdatedAt, now));
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行线程进入 {@code process} 时登记(B74-02)。登记点必须在 {@code activateRunningClaim}
|
||||
* 成功之后——claim 过期没 executing 的行本来就该被扫描回收。
|
||||
*/
|
||||
public void markInFlight(Long jobId) {
|
||||
if (jobId != null && jobId > 0) {
|
||||
inFlightJobIds.add(jobId);
|
||||
}
|
||||
}
|
||||
|
||||
/** 执行线程退出(含异常与终态收口)后注销;漏注销会让这一行永远不被回收,所以调用方必须放 finally。 */
|
||||
public void clearInFlight(Long jobId) {
|
||||
if (jobId != null) {
|
||||
inFlightJobIds.remove(jobId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 「本机有线程正在跑这一行」——卡死扫描据此不重排、不累加 {@code stuck_requeue_count}。
|
||||
*
|
||||
* <p>为什么必须由扫描问执行侧,而不是把 stuck 阈值抬大(B74-02 的二选一,2026-11-03 按读数定的):
|
||||
* 心跳在<b>父任务终态</b>时按 CR-08 刻意停止续期({@code TaskResultFileJobWorker#startJobHeartbeat}
|
||||
* 的 {@code stage=TERMINAL_STOP_RENEW}),此时执行线程还在跑但 {@code updated_at} 从此冻结——
|
||||
* 冻结是<b>无限期</b>的,不是「比 5 分钟长一点」。所以阈值抬到 16 分钟也只是把 20 次计满的时间
|
||||
* 从 100 分钟拖到 320 分钟,形状不变。2026-11-03 现网实证:jobId=23815/taskId=33179
|
||||
* 06:07:20 到 {@code stuckRequeueCount=20},06:08 复位恢复、09:20 又同样两条——同一个
|
||||
* 「既不失败也不完成」的环。抬阈值还会把真遗骸的回收从 5 分钟拖到十几分钟,两头都输。
|
||||
*
|
||||
* <p>与刚收口的跨实例归属守卫是同一判据的两半:那一半管「别的机器在跑」,这一半管「本机在跑」。
|
||||
*/
|
||||
public boolean isInFlight(Long jobId) {
|
||||
return jobId != null && inFlightJobIds.contains(jobId);
|
||||
}
|
||||
|
||||
/** 供用例断言登记面;生产路径不应依赖它做决策。 */
|
||||
public int inFlightCount() {
|
||||
return inFlightJobIds.size();
|
||||
}
|
||||
|
||||
public boolean deferRunning(Long jobId, String message) {
|
||||
if (jobId == null || jobId <= 0) {
|
||||
return false;
|
||||
|
||||
+37
-1
@@ -362,10 +362,30 @@ public class TaskHeartbeatPositionService {
|
||||
long now = Instant.now().toEpochMilli();
|
||||
String storedFingerprint = stored == null ? "" : value(stored, "pos");
|
||||
long unchangedSince = stored == null ? 0L : parseMillis(stored.get("at"));
|
||||
if (!fingerprint.equals(storedFingerprint) || unchangedSince <= 0L) {
|
||||
boolean snapshotMissing = stored == null || stored.isEmpty();
|
||||
if (!snapshotMissing && !fingerprint.equals(storedFingerprint)) {
|
||||
// 指纹真的变了=客户端主线程还在干活,起点重锚在「现在」。
|
||||
writeStallSnapshot(stallKey, fingerprint, now, staleWindowMinutes);
|
||||
return StallState.ADVANCING;
|
||||
}
|
||||
if (snapshotMissing || unchangedSince <= 0L) {
|
||||
// B74-03:这两种形状原先与「指纹变了」共用同一个 ADVANCING 出口,等于把
|
||||
// 「没有证据」当成「证据表明在推进」。现网实证(2026-11-02 任务 33179,20:20–21:02
|
||||
// 每 2 分钟一条「客户端仍在推进」而 lastResultAt 已 3h48m 不动):本键 TTL 是
|
||||
// max(60, window×3)=9 小时,键一过期就重锚到 now,于是每 9 小时白送一轮完整豁免窗口,
|
||||
// 沉默的客户端永远封不了口。
|
||||
// 分流做法:锚点重建成**客户端最后一次上报**的时刻(位置哈希自己的 at,由 record()
|
||||
// 每次心跳刷新),拿不到才退回 now;随后照走同一条时间判据,豁免长度由真实沉默时长决定,
|
||||
// 而不是由「键什么时候消失」决定。客户端确在心跳时 anchor 就是新鲜的 ⇒ 仍判 ADVANCING,
|
||||
// 这一侧不会把还在采集的任务判死(28919 的教训记在 isClientAdvancing 的注释上)。
|
||||
long reportedAt = positionReportedAtMillis(taskId);
|
||||
long anchor = reportedAt > 0L ? reportedAt : now;
|
||||
log.info("[heartbeat-position] 停滞锚点重建 taskId={} reason={} anchor={} anchorAgeMs={}",
|
||||
taskId, snapshotMissing ? "snapshot-missing" : "stamp-unreadable",
|
||||
anchor, now - anchor);
|
||||
writeStallSnapshot(stallKey, fingerprint, anchor, staleWindowMinutes);
|
||||
unchangedSince = anchor;
|
||||
}
|
||||
long unchangedMillis = now - unchangedSince;
|
||||
if (unchangedMillis >= Duration.ofMinutes(staleWindowMinutes).toMillis()) {
|
||||
return StallState.STALLED;
|
||||
@@ -375,6 +395,22 @@ public class TaskHeartbeatPositionService {
|
||||
return StallState.ADVANCING;
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户端最后一次上报位置的时刻(毫秒),读不到返回 0。
|
||||
*
|
||||
* <p>与 {@link #readProgressFingerprint} 读的是同一枚哈希,只是多取一个 {@code at} 字段——
|
||||
* 那里只取计数与文本,所以这一枚时间戳此前没有任何人读过,B74-03 的锚点也就一直错到 now 上。
|
||||
*/
|
||||
private long positionReportedAtMillis(Long taskId) {
|
||||
try {
|
||||
Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(KEY_PREFIX + taskId);
|
||||
return entries == null ? 0L : parseMillis(entries.get("at"));
|
||||
} catch (Exception ex) {
|
||||
log.warn("[heartbeat-position] 读取位置上报时刻失败 taskId={} msg={}", taskId, ex.getMessage());
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 便捷判定:客户端是否仍在推进(位置文本仍在变)。
|
||||
*
|
||||
|
||||
+13
-4
@@ -269,15 +269,24 @@ public class TaskResultFileJobWorker {
|
||||
return;
|
||||
}
|
||||
AtomicBoolean parentTerminalObserved = new AtomicBoolean(false);
|
||||
// B74-02:向作业服务登记「本机线程正在跑这一行」。父任务终态时心跳会刻意停续期
|
||||
// (stage=TERMINAL_STOP_RENEW),updated_at 从此无限期冻结,卡死扫描若只看时间戳就会
|
||||
// 每 5 分钟给还在跑的执行线程记一次 stuck_requeue_count,20 次把还能出表的单判死
|
||||
// (2026-11-03 现网 jobId=23815/taskId=33179 正是这个环)。注销必须在 finally。
|
||||
taskFileJobService.markInFlight(job.getId());
|
||||
ScheduledFuture<?> heartbeat = startJobHeartbeat(job, parentTerminalObserved);
|
||||
try {
|
||||
processInternal(job);
|
||||
} finally {
|
||||
heartbeat.cancel(false);
|
||||
// CR-08:心跳只负责停续期;终态判定必须等执行线程退出后再做。
|
||||
// 此时若 markSuccess 已落库,finishAfterExecution 会保留 SUCCESS;
|
||||
// 只有执行线程没写出成功状态的行才判死并留给兜底扫描出部分结果。
|
||||
finishAfterExecution(job, parentTerminalObserved);
|
||||
try {
|
||||
// CR-08:心跳只负责停续期;终态判定必须等执行线程退出后再做。
|
||||
// 此时若 markSuccess 已落库,finishAfterExecution 会保留 SUCCESS;
|
||||
// 只有执行线程没写出成功状态的行才判死并留给兜底扫描出部分结果。
|
||||
finishAfterExecution(job, parentTerminalObserved);
|
||||
} finally {
|
||||
taskFileJobService.clearInFlight(job.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.nanri.aiimage.modules.task.service.support;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* 任务归属实例的 <b>JSON 回落</b>——四台(外观专利/相似ASIN/发布/店铺采集)共用的唯一出处(B74-04)。
|
||||
*
|
||||
* <p>列优先是铁律 28 定的:任务转交后只有 {@code owner_instance_id} 会被更新,JSON 快照停在
|
||||
* parse 那一刻。但「列缺失时读哪一枚 JSON」此前四处各写各的——三台读 {@code result_json},
|
||||
* 店铺采集读 {@code request_json}。同一条存量行(实测 RUNNING 任务里 {@code owner_instance_id}
|
||||
* 为空的有 39 行)在四台眼里因此可以算出<b>两个</b>归属,正是 2026-11-02 互斥死锁的家族形状。
|
||||
*
|
||||
* <p>顺序固定为 {@code result_json → request_json}:前者是 parse/交付快照(正档),后者是提交时
|
||||
* 最旧的一手,只有正档确实没有时才作参考,并且必须留下 WARN——它一旦生效就说明列与正档都没写上。
|
||||
*/
|
||||
@Slf4j
|
||||
public final class TaskOwnerJsonFallback {
|
||||
|
||||
/** owner 字段名:四台读取与写入侧(payload/result_json)共用同一个拼写。 */
|
||||
public static final String OWNER_FIELD = "ownerInstanceId";
|
||||
|
||||
private TaskOwnerJsonFallback() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param logTag 所属模块的日志前缀,便于现网分辨是哪一台走到了回落
|
||||
* @return 归属实例 id;两枚快照都读不出时返回 null(调用方按「无归属」放行)
|
||||
*/
|
||||
public static String ownerFrom(FileTaskEntity task, ObjectMapper objectMapper, String logTag) {
|
||||
if (task == null || objectMapper == null) {
|
||||
return null;
|
||||
}
|
||||
String fromResult = read(task.getResultJson(), objectMapper);
|
||||
if (fromResult != null) {
|
||||
return fromResult;
|
||||
}
|
||||
String fromRequest = read(task.getRequestJson(), objectMapper);
|
||||
if (fromRequest != null) {
|
||||
log.warn("[{}] 任务归属落到 request_json 提交快照 taskId={} owner={} —— "
|
||||
+ "只有 owner_instance_id 列与 result_json 都读不出时才走到这里",
|
||||
logTag, task.getId(), fromRequest);
|
||||
}
|
||||
return fromRequest;
|
||||
}
|
||||
|
||||
private static String read(String json, ObjectMapper objectMapper) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode root = objectMapper.readTree(json);
|
||||
if (root == null) {
|
||||
return null;
|
||||
}
|
||||
String owner = root.path(OWNER_FIELD).asText("");
|
||||
return owner.isBlank() ? null : owner.trim();
|
||||
} catch (Exception ex) {
|
||||
// 读不出归属=不认领,绝不抛:抛出去会把一次正常的状态检查变成 500。
|
||||
// 但必须报出来——静默返回 null 会被调用方读成"这行没有归属"从而放行。
|
||||
log.warn("[owner-fallback] 解析任务归属快照失败 msg={}", ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+56
-4
@@ -696,10 +696,12 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
String groupKey = inspectionGroupKey(row);
|
||||
// 解密提到分组之前:分组键要看链接内容才能认出「这行和那行是同一个账号」
|
||||
// (B73-03)。这是本机 AES,不走网络,代价与一次真实提取不可同日而语。
|
||||
String plainKey = normalize(cryptoService.decrypt(row.getSecretValue()));
|
||||
String groupKey = inspectionGroupKey(row, plainKey);
|
||||
UserApiSecretCheckService.CheckOutcome outcome = outcomeBySecret.get(groupKey);
|
||||
if (outcome == null) {
|
||||
String plainKey = normalize(cryptoService.decrypt(row.getSecretValue()));
|
||||
outcome = plainKey.isEmpty()
|
||||
? new UserApiSecretCheckService.CheckOutcome(
|
||||
UserApiSecretCheckService.STATUS_FAILED,
|
||||
@@ -755,12 +757,62 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
return summary;
|
||||
}
|
||||
|
||||
/** 巡检分组键:同模块 + 同密文视为同一把密钥。密文确定性加密,无需解密即可分组。 */
|
||||
private String inspectionGroupKey(UserApiSecretEntity row) {
|
||||
/**
|
||||
* 巡检分组键。
|
||||
*
|
||||
* <p><b>代理类凭据按供应商账号分组</b>(B73-03):旧写法 {@code moduleKey|channel|密文}
|
||||
* 把同一把青果 key 在多模块/多行配置时算成不同的组,每组都要真打一次提取;而青果整个账号
|
||||
* 只有 1 条通道(2026-11-02 用户在控制台核实),第一枪还占着,后面每一枪必然
|
||||
* {@code channel_busy} —— 巡检自己把用户的代理打成了「代理异常」。现在折成
|
||||
* (供应商, 提取域, 归一化 query):参数顺序不同、多余参数不同都算同一把 key,同账号只出一枪。
|
||||
*
|
||||
* <p><b>非链接型凭据照旧</b> {@code moduleKey|channel|密文}:同一串 LLM 密钥在龙抬头与贞贞上
|
||||
* 是两次独立探测,合并会拿 A 的结论冒充 B —— 那一侧不能跟着一起折。
|
||||
*
|
||||
* <p>分组键会进管理员告警的聚合面,所以账号身份只落摘要,链接里的账密明文绝不落进去。
|
||||
*/
|
||||
private String inspectionGroupKey(UserApiSecretEntity row, String plainValue) {
|
||||
String accountIdentity = proxyAccountIdentity(plainValue);
|
||||
if (accountIdentity != null) {
|
||||
return "proxy-account|" + accountIdentity;
|
||||
}
|
||||
// 渠道参与分组:同一串密钥在龙抬头与贞贞上是两次独立探测,合并会拿 A 的结论冒充 B
|
||||
return row.getModuleKey() + '|' + (row.getChannel() == null ? "" : row.getChannel()) + '|' + row.getSecretValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取链接的账号身份=(供应商, 提取域, 排序后的 query) 的摘要;不是链接型凭据时返回 null。
|
||||
*
|
||||
* <p>返回 null 是让调用方退回逐行分组,而不是硬造一个组——把 LLM 密钥误当链接合并才是真事故。
|
||||
*/
|
||||
private String proxyAccountIdentity(String plainValue) {
|
||||
if (plainValue == null || plainValue.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
URI uri;
|
||||
try {
|
||||
uri = new URI(plainValue.trim());
|
||||
} catch (Exception ex) {
|
||||
log.warn("[user-secret] 巡检分组键解析不出链接,退回逐行分组 msg={}", ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
String host = uri.getHost();
|
||||
if (host == null || !host.contains(".")) {
|
||||
return null;
|
||||
}
|
||||
ProxyProvider provider = ProxyProvider.detectFromUrl(plainValue);
|
||||
String query = uri.getQuery() == null ? "" : sortedQuery(uri.getQuery());
|
||||
return sha256Hex((provider == null ? "unknown" : provider.name())
|
||||
+ '|' + host.toLowerCase(java.util.Locale.ROOT) + '|' + query);
|
||||
}
|
||||
|
||||
/** query 参数按原文排序,好让「同一把 key 写成不同参数顺序」落到同一个组。 */
|
||||
private static String sortedQuery(String rawQuery) {
|
||||
String[] parts = rawQuery.split("&");
|
||||
java.util.Arrays.sort(parts);
|
||||
return String.join("&", parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* 巡检告警判定:欠费(insufficient_balance)→ error 级 secret_balance;
|
||||
* 密钥无效/被拒(invalid_key/forbidden)→ warning 级 secret_invalid;
|
||||
|
||||
Reference in New Issue
Block a user