fix(任务): 开机自回收改以本进程启动时刻为界,发版不再蚕食结果文件作业的重试次数

原判据是 now-max(60,staleSeconds),但 ApplicationReadyEvent 只在重启后几秒响一次,
那时遗留行的心跳也只停了几秒,条件结构上永不成立——线上"实例重启,作业已重新排队"累计 0 条。
遗骸改由 stuck 扫描按 +1 重试处理(今天 A 发了 7 版、重试预算只有 5),
20833 已被吃掉一次,20836/任务29475 就是被这条链判成"已达到最大重试次数"的。
This commit is contained in:
2026-09-28 15:59:47 +08:00
parent 2689fd5e1f
commit 7bb03466b0
7 changed files with 182 additions and 76 deletions
@@ -4,7 +4,11 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
@Slf4j
@Component
@@ -14,8 +18,16 @@ public class InstanceMetadata {
private final String hostname;
private final String source;
private final boolean stable;
/**
* 本进程的启动时刻。开机自回收用它当界:owner=本机且 status=RUNNING 的行若
* {@code updated_at} 早于这一刻,只可能是上一个进程留下的遗骸,不可能是本进程在跑的。
*/
private final LocalDateTime startedAt;
public InstanceMetadata(@Value("${aiimage.instance-id:}") String configuredInstanceId) {
this.startedAt = LocalDateTime.ofInstant(
Instant.ofEpochMilli(ManagementFactory.getRuntimeMXBean().getStartTime()),
ZoneId.systemDefault());
this.hostname = resolveHostname();
String normalizedConfiguredInstanceId = configuredInstanceId == null ? "" : configuredInstanceId.trim();
if (!normalizedConfiguredInstanceId.isBlank()) {
@@ -51,6 +63,10 @@ public class InstanceMetadata {
return stable;
}
public LocalDateTime getStartedAt() {
return startedAt;
}
private static String resolveHostname() {
try {
return InetAddress.getLocalHost().getHostName();
@@ -454,8 +454,12 @@ public class TaskFileJobService {
* 冻结一整个阈值窗口,而这批行其实早已无人持有。进程刚起来时本机不可能还在跑它们,
* 所以这一刻就能直接接回来,把等待从「阈值」压到「启动」。
*
* <p>两道保险:只取 owner 等值等于自己的行(绝不碰另一台实例在跑的),且必须已停止心跳
* 一个完整周期以上(正常心跳是 60 秒一次,误抢会让在跑的作业被双份派发)。
* <p>两道保险:只取 owner 等值等于自己的行(绝不碰另一台实例在跑的),且只取
* {@code updated_at} 早于本进程启动时刻的行——旧进程已经退出,它留下的行必然停在这个时刻之前,
* 而本进程自己派发的行只会晚于它。用「本进程启动」而不是「距今 N 秒」做界是必须的:
* 开机事件发生在重启后几秒,那时遗留行的心跳也只停了几天秒,按固定 staleness 阈值
* (曾经是 60/90 秒)**永远取不到任何行**,回收等于不存在,只能等 stuck 扫描按 +1 重试判死。
* updated_at 全部由应用侧 {@code LocalDateTime.now()} 写入(不是 DB 时钟),与本界同源,不存在跨机时钟偏移。
*
* <p>与 stuck 扫描的关键区别:**不累加 retry_count**。发版不是这个作业的错,每发一次版
* 吃掉它那 5 次重试中的一次,反复发版会把正常任务判成"已达到最大重试次数"。
@@ -463,12 +467,12 @@ public class TaskFileJobService {
* <p>刻意不加事务,与 {@link #resetStuckRunningJobsDetailed} 同理:每行都带
* status + updated_at 的 CAS 条件,逐行独立提交,锁即时释放。
*/
public int reclaimOwnedRunningJobs(String owner, long staleSeconds, int limit) {
public int reclaimOwnedRunningJobs(String owner, LocalDateTime orphanedBefore, int limit) {
String normalizedOwner = owner == null ? "" : owner.trim();
if (normalizedOwner.isBlank()) {
if (normalizedOwner.isBlank() || orphanedBefore == null) {
return 0;
}
LocalDateTime cutoff = LocalDateTime.now().minusSeconds(Math.max(60L, staleSeconds));
LocalDateTime cutoff = orphanedBefore;
int safeLimit = Math.max(1, Math.min(limit, 100));
List<TaskFileJobEntity> jobs = taskFileJobMapper.selectList(new LambdaQueryWrapper<TaskFileJobEntity>()
.eq(TaskFileJobEntity::getStatus, "RUNNING")
@@ -503,8 +507,8 @@ public class TaskFileJobService {
for (Long jobId : resetIds) {
publishDispatchEvent(refreshedById.get(jobId));
}
log.warn("[task-file-job] 开机自回收本机遗留作业 count={} owner={} staleSeconds={} limit={}",
resetIds.size(), normalizedOwner, staleSeconds, safeLimit);
log.warn("[task-file-job] 开机自回收本机遗留作业 count={} owner={} cutoff={} limit={}",
resetIds.size(), normalizedOwner, cutoff, safeLimit);
return resetIds.size();
}
@@ -18,6 +18,7 @@ import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@@ -57,10 +58,6 @@ public class TaskResultFileJobWorker {
@Value("${aiimage.result-file-job.heartbeat-interval-ms:60000}")
private long heartbeatIntervalMillis = 60000L;
/** 开机回收的"心跳已停"判据:默认 90 秒 ≈ 1.5 个心跳周期,容得下一次正常心跳延迟。 */
@Value("${aiimage.result-file-job.boot-reclaim-stale-seconds:90}")
private long bootReclaimStaleSeconds;
/** 多个结果文件 Job 并行运行时,心跳不能被单个 DB 慢调用串行阻塞。 */
private final ScheduledExecutorService jobHeartbeatExecutor = Executors.newScheduledThreadPool(4, runnable -> {
Thread thread = new Thread(runnable, "task-file-job-heartbeat");
@@ -119,16 +116,22 @@ public class TaskResultFileJobWorker {
* 本机刚起来,这些 owner=自己的 RUNNING 行不可能还在本机执行,所以此刻就能直接接回来,
* 不必等阈值;回收不消耗 retry_count(发版不是作业的错)。
*
* <p>判据用「本进程启动时刻」而不是「距今 N 秒」:开机事件只在重启后几秒响一次,
* 那时刻遗留行的心跳也只停了几秒,按固定 staleness 阈值永远筛不出它们。曾经就是这个样子,
* 结果线上 {@code 实例重启,作业已重新排队} 一条都没有,遗骸全部由 stuck 扫描按 +1 重试处理,
* 反复发版把还能补传的组装作业推上"已达到最大重试次数"。
*
* <p>只处理 owner 等于本机实例 id 的行,另一台实例在跑的作业不受影响。
*/
@EventListener(ApplicationReadyEvent.class)
public void reclaimOwnedJobsOnBoot() {
try {
LocalDateTime jvmStartedAt = instanceMetadata == null ? null : instanceMetadata.getStartedAt();
int reclaimed = taskFileJobService.reclaimOwnedRunningJobs(
currentInstanceId(), bootReclaimStaleSeconds, batchSize);
currentInstanceId(), jvmStartedAt, batchSize);
if (reclaimed > 0) {
log.warn("[task-file-job] booted and reclaimed abandoned jobs of this instance reclaimed={} instanceId={} staleSeconds={}",
reclaimed, currentInstanceId(), bootReclaimStaleSeconds);
log.warn("[task-file-job] booted and reclaimed abandoned jobs of this instance reclaimed={} instanceId={} cutoff={}",
reclaimed, currentInstanceId(), jvmStartedAt);
}
} catch (Exception ex) {
// 回收只是加速恢复;失败不影响启动,兜底仍是 stuck 扫描。