fix(task-board): 任务卡片假死自救——轮询失败退避重试+面板刷新按钮+补检轮进度文案

task 31769:外观专利任务后端 18:08 已 SUCCESS,但页面卡片冻在「正在组装 xlsx 92%」
一天多——Patent 轮询配的 propagate 让一次瞬时错误永久杀死轮询,且无自救出口。
- useLiveTaskBoard 摘除 pollErrorMode:失败一律吞掉重试,连续失败按倍数降频(封顶 5x)
- TaskCenterPanel 头部新增「刷新」按钮,外观专利/货源查询两页接上(强拉 history+dashboard)
- 补检轮触发时进度文案改「有 N 行未完成检测,补检中」,不再停在「正在组装 xlsx」假死
- 回归:AppearancePatentRecheckProgressMessageTest+task-board-poll-resilience.test.ts
This commit is contained in:
2026-10-22 15:34:36 +08:00
parent 973128216a
commit 6d52b95d85
7 changed files with 228 additions and 26 deletions
@@ -362,9 +362,14 @@ public class AppearancePatentResultJobSupport {
progressSupport.saveFileBuildProgress(task, job, totalProgressUnits, assembleProgress, "正在组装 xlsx");
// 补检决定必须做在出表之前:assembleResultWorkbook 一跑完就把 xlsx 传上 OSS 并挂好
// resultFileUrl,那时才发现缺口,半张表已经在用户的下载列表里了。
if (deliverySupport.requestRecheckForMissingRows(task, job, deliverySupport.measureDeliveryFacts(task, result))) {
AppearancePatentRowOutcome.Facts gap = deliverySupport.measureDeliveryFacts(task, result);
if (deliverySupport.requestRecheckForMissingRows(task, job, gap)) {
// 半张表先不发出去:撤销未完成行的检测标记、把作业排回队列补检一轮,
// 上限由行级轮次闸(llmRowMaxRounds)与补检轮次闸(recheckMaxRounds)共同兜住。
// 进度消息同步换掉「正在组装 xlsx」:补检一轮常要几十分钟,卡片停在 92% 假死
// (task 31769 实录),用户要看得见是在补检、不是卡死。百分比由快照棘轮保持不回退。
progressSupport.saveFileBuildProgress(task, job, totalProgressUnits, assembleProgress,
"有 " + gap.missingRows() + " 行未完成检测,补检中");
return false;
}
AppearancePatentRowOutcome.Facts deliveryFacts = assembleResultWorkbook(task, result);
@@ -0,0 +1,86 @@
package com.nanri.aiimage.modules.appearancepatent.service.support;
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 org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 补检轮触发时进度文案必须换掉「正在组装 xlsx」(task 31769):
* 补检一轮常要几十分钟,卡片一直停在 92%「正在组装 xlsx」,用户只能当成卡死;
* 页面轮询恰好又被一次瞬时错误杀死后,这张假死卡挂了一天多(后端实际早已 SUCCESS)。
* 这里钉住:recheck 分支要在返回 false 前把进度消息写成「有 N 行未完成检测,补检中」,
* 首条「正在组装 xlsx」保持不变(组装阶段照旧)。
*/
@ExtendWith(MockitoExtension.class)
class AppearancePatentRecheckProgressMessageTest {
@Mock private AppearancePatentDeliverySupport deliverySupport;
@Mock private AppearancePatentProgressSupport progressSupport;
@Test
void recheckRoundWritesGapProgressInsteadOfFrozenAssembleMessage() {
AppearancePatentRowOutcome.Facts gap =
new AppearancePatentRowOutcome.Facts(5, 3, 0, List.of("B0AAAA", "B0BBBB"));
when(deliverySupport.measureDeliveryFacts(task(), result())).thenReturn(gap);
when(deliverySupport.requestRecheckForMissingRows(task(), job(), gap)).thenReturn(true);
Boolean proceeded = ReflectionTestUtils.invokeMethod(support(), "completeLlmFileJob",
task(), result(), job(), 6);
assertFalse(proceeded, "补检轮触发时 completeLlmFileJob 必须返回 false(作业排回队列)");
ArgumentCaptor<String> message = ArgumentCaptor.forClass(String.class);
verify(progressSupport, times(2)).saveFileBuildProgress(eq(task()), eq(job()), eq(6), anyInt(), message.capture());
assertEquals("正在组装 xlsx", message.getAllValues().get(0));
assertEquals("有 2 行未完成检测,补检中", message.getAllValues().get(1));
}
private AppearancePatentResultJobSupport support() {
// 仅 deliverySupport / progressSupport 参与补检分支,其余协作者传 null(构造器只赋值)
return new AppearancePatentResultJobSupport(
"APPEARANCE_PATENT", 0L, null, null,
null, null, null, null, null, null, null,
null, null, null, deliverySupport, progressSupport, null,
null, null, null, null, null, null, null);
}
private FileTaskEntity task() {
FileTaskEntity task = new FileTaskEntity();
task.setId(31769L);
task.setModuleType("APPEARANCE_PATENT");
task.setStatus("RUNNING");
return task;
}
private TaskFileJobEntity job() {
TaskFileJobEntity job = new TaskFileJobEntity();
job.setId(22741L);
job.setTaskId(31769L);
job.setResultId(34819L);
job.setStatus("RUNNING");
return job;
}
private FileResultEntity result() {
FileResultEntity result = new FileResultEntity();
result.setId(34819L);
result.setTaskId(31769L);
result.setModuleType("APPEARANCE_PATENT");
return result;
}
}
@@ -37,6 +37,7 @@
<section class="right-panel">
<TaskCenterPanel
:on-batch-delete="batchDeleteHistory"
:on-refresh="refreshBoard"
title="外观专利检测"
:cards="patentCards"
:current-items="currentTaskViews"
@@ -171,8 +172,6 @@ const board = useLiveTaskBoard<AppearancePatentHistoryItem>({
}
return { taskIds, force: true }
},
// 轮询回调抛错时上抛、轮询停止(与原实现一致)
pollErrorMode: 'propagate',
getPendingParseItem: () => pendingParseItem.value,
download: {
buildUrl: (resultId) => getAppearancePatentResultDownloadUrl(resultId),
@@ -188,6 +187,16 @@ const board = useLiveTaskBoard<AppearancePatentHistoryItem>({
})
const visibleTaskSummary = computed(() => parseResult.value || queuedTaskSummary.value)
/** 手动刷新:强拉历史 + 统计 + 当前轮询任务进度(轮询意外中断后的自救出口) */
async function refreshBoard() {
await Promise.all([
board.loadDashboard(),
board.loadHistory({ force: true }),
board.refreshTaskProgress(),
])
}
const pendingParseItem = computed<AppearancePatentHistoryItem | null>(() => {
const result = parseResult.value
if (!result?.taskId) return null
@@ -77,6 +77,7 @@
<section class="right-panel">
<TaskCenterPanel
:on-batch-delete="batchDeleteHistory"
:on-refresh="refreshBoard"
title="货源查询"
:cards="asinCards"
:current-items="currentTaskViews"
@@ -221,8 +222,6 @@ const board = useLiveTaskBoard<SimilarAsinHistoryItem>({
pendingIds.forEach((taskId) => forceThrottle.markForce(taskId))
}
},
// 瞬时请求失败不打断轮询(与原实现一致)
pollErrorMode: 'swallow',
onPendingFileTaskRemoved: (taskId) => forceThrottle.clear(taskId),
getPendingParseItem: () => pendingParseItem.value,
download: {
@@ -270,6 +269,15 @@ const currentTaskViews = computed<TaskItemView[]>(() => board.currentItems.value
const historyTaskViews = computed<TaskItemView[]>(() => board.historyOnlyItems.value.map(toAsinTaskView))
/** 手动刷新:强拉历史 + 统计 + 当前轮询任务进度(轮询意外中断后的自救出口) */
async function refreshBoard() {
await Promise.all([
board.loadDashboard(),
board.loadHistory({ force: true }),
board.refreshTaskProgress(),
])
}
function itemSource(item: TaskItemView): SimilarAsinHistoryItem {
return item.source as SimilarAsinHistoryItem
}
@@ -1,7 +1,12 @@
<template>
<div class="task-center-panel">
<div class="panel-header">
<span class="panel-header__title">{{ title }}</span>
<div class="panel-header__left">
<span class="panel-header__title">{{ title }}</span>
<button v-if="onRefresh" type="button" class="panel-refresh" :disabled="refreshing" @click="handleRefresh">
{{ refreshing ? '刷新中…' : '刷新' }}
</button>
</div>
<HistoryTaskLayer
:count="historyItems.length"
:history-title="historyTitle"
@@ -45,12 +50,14 @@
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import HistoryTaskLayer from './HistoryTaskLayer.vue'
import TaskItemCard from './TaskItemCard.vue'
import TaskStatCards from './TaskStatCards.vue'
import type { TaskItemView, TaskStatCard } from './types'
withDefaults(defineProps<{
const props = withDefaults(defineProps<{
/** 面板标题(右侧 panel-header) */
title: string
/** 统计卡 */
@@ -68,6 +75,8 @@ withDefaults(defineProps<{
historyEmptyText?: string
/** 历史记录批量删除回调(传入后历史弹层支持勾选批量删除) */
onBatchDelete?: (items: TaskItemView[]) => Promise<void> | void
/** 手动刷新回调(传入后面板头部出现「刷新」按钮) */
onRefresh?: () => Promise<void> | void
}>(), {
cards: () => [],
currentItems: () => [],
@@ -77,6 +86,20 @@ withDefaults(defineProps<{
currentEmptyText: '暂无当前任务',
historyEmptyText: '暂无历史任务',
})
const refreshing = ref(false)
async function handleRefresh() {
if (!props.onRefresh || refreshing.value) return
refreshing.value = true
try {
await props.onRefresh()
} catch {
ElMessage.error('刷新失败,请稍后重试')
} finally {
refreshing.value = false
}
}
</script>
<style scoped>
@@ -96,12 +119,32 @@ withDefaults(defineProps<{
border-bottom: 1px solid #2e3a52;
}
.panel-header__left {
display: flex;
align-items: center;
gap: 10px;
}
.panel-header__title {
font-size: 15px;
font-weight: 600;
color: #c8d2e2;
}
.panel-refresh {
padding: 4px 12px;
border: 1px solid #2e3a52;
border-radius: 6px;
background: transparent;
color: #6ea8fe;
font-size: 12px;
cursor: pointer;
white-space: nowrap;
}
.panel-refresh:hover { border-color: #3498db; }
.panel-refresh:disabled { opacity: .55; cursor: not-allowed; }
.task-list-wrap {
flex: 1;
padding: 16px 20px;
@@ -20,7 +20,6 @@ import type { TaskItemView } from '../components/tasks/types'
* - 状态归一化 normalizeTaskStatus / isResultPreparing(两 Tab 语义不同)
* - 终态后是否登记 pending 文件任务、哪些任务状态参与文件结算
* - 进度批量请求的预/后处理(SimilarAsin 的 force 节流、Patent 的 light 行版本检查)
* - 轮询回调抛错时是否打断轮询(SimilarAsin 吞掉、Patent 上抛——保持原行为)
* - 下载 URL / 文件名兜底 / 进度 key 前缀、删除判定与本地清理
*
* 其余手写轮询的 Tab(QueryAsin/Withdraw 等)后续可渐进接入。
@@ -105,12 +104,6 @@ export interface UseLiveTaskBoardOptions<T extends LiveTaskHistoryItem> {
) => Promise<{ taskIds: number[]; force: boolean } | null> | { taskIds: number[]; force: boolean } | null
/** 批量进度请求后处理(SimilarAsin 的 force 节流登记)。 */
afterBatch?: (taskIds: number[], pendingFileTaskIds: number[], forced: boolean) => void
/**
* 轮询回调抛错时的处理:
* - 'swallow'(SimilarAsin):瞬时失败不打断轮询;
* - 'propagate'(Patent):异常上抛,轮询停止(与原实现一致)。
*/
pollErrorMode?: 'swallow' | 'propagate'
/** pending 文件任务被移除时的回调(SimilarAsin 的 forceThrottle.clear) */
onPendingFileTaskRemoved?: (taskId: number) => void
/** 当前任务区顶部的「解析待启动」占位条目;返回 null 表示没有 */
@@ -226,7 +219,6 @@ export function useLiveTaskBoard<T extends LiveTaskHistoryItem>(
options: UseLiveTaskBoardOptions<T>,
): UseLiveTaskBoardReturn<T> {
const timers = createCategorizedTimers(options.scope)
const pollErrorMode = options.pollErrorMode ?? 'swallow'
const pollingTaskIds = ref<number[]>([])
const pendingFileTaskIds = ref<number[]>([])
@@ -351,7 +343,13 @@ export function useLiveTaskBoard<T extends LiveTaskHistoryItem>(
savePollingIds()
}
// ---- 轮询循环(两 Tab 逐字相同;抛错处理按 pollErrorMode 参数化)----
// ---- 轮询循环 ----
// 瞬时请求失败不打断轮询(task 31769:Patent 曾配 'propagate',一次网络抖动就永久停轮询,
// 卡片冻结在「正在组装 xlsx 92%」一天多,后端实际早已 SUCCESS);连续失败时按倍数降频,
// 成功即恢复原间隔。
let consecutivePollFailures = 0
const POLL_FAILURE_STRETCH_CAP = 5
function ensurePolling() {
if (disposed) return
@@ -385,23 +383,20 @@ export function useLiveTaskBoard<T extends LiveTaskHistoryItem>(
pollTimer.value = null
if (disposed) return
if (!pollingTaskIds.value.length && !pendingFileTaskIds.value.length) return
if (pollErrorMode === 'propagate') {
try {
await refreshTaskProgress()
consecutivePollFailures = 0
} catch {
consecutivePollFailures += 1
} finally {
scheduleFollowUp()
} else {
try {
await refreshTaskProgress()
} catch {
// A transient request failure must not stop progress polling permanently.
} finally {
scheduleFollowUp()
}
}
}
function scheduleFollowUp() {
if (!disposed && pollTimer.value == null && (pollingTaskIds.value.length || pendingFileTaskIds.value.length)) {
pollTimer.value = timers.setTimeout('task-poll', runPollCycle, getTaskPollIntervalMs())
const stretch = Math.min(consecutivePollFailures, POLL_FAILURE_STRETCH_CAP)
pollTimer.value = timers.setTimeout('task-poll', runPollCycle, getTaskPollIntervalMs() * stretch)
}
}
@@ -0,0 +1,56 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
/**
* 任务面板轮询韧性守卫(task 31769):
* 外观专利的任务实际 18:08 已 SUCCESS、文件已可下载,但页面卡片冻在
* 「正在组装 xlsx 92%」一天多——因为 Patent 的轮询配了 'propagate',
* 一次瞬时请求失败就把轮询永久杀死,卡片假死且无任何自救出口。
* 这里钉住三件事:①轮询错误必须吞掉并退避重试(pollErrorMode 不得回流);
* ②面板头部必须有手动「刷新」按钮;③刷新失败要有可见出口。
*/
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
function sourceOf(rel: string) {
return readFileSync(join(ROOT, rel), 'utf8')
}
const BOARD = 'src/shared/composables/useLiveTaskBoard.ts'
const PATENT = 'src/pages/brand/components/BrandAppearancePatentTab.vue'
const SIMILAR = 'src/pages/brand/components/BrandSimilarAsinTab.vue'
const PANEL = 'src/shared/components/tasks/TaskCenterPanel.vue'
test('轮询异常必须吞掉并重试,propagate 模式不得回流', () => {
const board = sourceOf(BOARD)
assert.ok(!board.includes('pollErrorMode'),
'useLiveTaskBoard 不得再有 pollErrorMode 开关(propagate 会把轮询永久杀死)')
// catch 里必须有失败计数语句:吞掉 ≠ 空吞,连续失败要进入降频
assert.match(board, /catch\s*\{[^}]*consecutivePollFailures\s*\+=/,
'runPollCycle 的 catch 里必须累加失败计数(退避重试的依据)')
// 后续轮询间隔必须乘以失败倍数(连续失败降频,成功后计数清零恢复原速)
assert.match(board, /getTaskPollIntervalMs\(\)\s*\*\s*stretch/,
'scheduleFollowUp 必须按失败倍数拉长轮询间隔')
assert.match(board, /consecutivePollFailures\s*=\s*0/,
'轮询成功后必须清零失败计数,否则一次抖动会把间隔永久拉长')
})
test('两个任务面板页都接了手动刷新', () => {
for (const [rel, name] of [[PATENT, '外观专利'], [SIMILAR, '货源查询']] as const) {
const source = sourceOf(rel)
assert.ok(source.includes(':on-refresh="refreshBoard"'), `${name} 页没有给 TaskCenterPanel 传 on-refresh`)
assert.match(source, /async function refreshBoard\(\)/, `${name} 页缺少 refreshBoard 实现`)
assert.match(source, /loadHistory\(\{\s*force:\s*true\s*\}\)/,
`${name} 的 refreshBoard 必须强拉历史(不带 force 会被 3s 缓存挡掉)`)
}
})
test('面板刷新按钮存在且失败有可见出口', () => {
const panel = sourceOf(PANEL)
assert.match(panel, /onRefresh\?:/, 'TaskCenterPanel 缺少 onRefresh prop')
assert.match(panel, /panel-refresh/, 'TaskCenterPanel 缺少刷新按钮样式/类名')
assert.match(panel, /refreshing\s*\?\s*'刷新中/, '刷新中要有按钮态反馈')
assert.match(panel, /ElMessage\.error\('刷新失败/, '刷新失败必须给用户可见出口,不得静默')
})