feat(knowledge): flag documents that stop making progress (#3557)

* feat(knowledge): flag documents that stop making progress

A document stuck in processing looked the same as one still working: a
spinner that polled forever, no hint of where it stopped, and, hours
later, a generic housekeeping failure.

- The batch and spans endpoints return last_activity_at for in-flight
  rows: the later of updated_at and the newest span write. updated_at
  only moves at stage transitions; span writes keep moving while a long
  stage still works.
- After 20 minutes with no progress, the list and card views show
  "may be stuck" with a tooltip. The timeline shows the stage it
  stopped at and a stop-parsing button, plus a "last progress" stat.
  Both pollers back off to 15s while everything in flight is stalled.
- When housekeeping fails a row, the error names the stalled stage and
  the time of the last progress. It closes the row's open spans with
  TASK_STALLED (the running stage fails, the rest are cancelled), so
  the timeline shows where the run stopped instead of a spinner.

* fix(knowledge): locate stalls in finalizing and tell backlog from stuck

- Housekeeping reads the stall site from the latest attempt. It takes
  the running stages, or, when none runs (post-process closes its stage
  once enrichment is fanned out), the innermost running spans, mapped
  back to their stage. Those spans fail with TASK_STALLED and are named
  in the message; every stalled stage is listed in pipeline order. The
  other open spans are cancelled. Every closed span gets a duration, and
  the message leaves out the time when the heartbeat query failed.
- The spans tree prefers a TASK_STALLED failure for last_error over a
  later subtask failure. current_stage falls back to the stage owning a
  running subspan.
- Batch and spans responses flag rows quiet past the stall hint whose
  work is still queued (waiting_in_queue), using the sweep's own probes.
  At most 20 rows are probed per request, cached for a minute. The UI
  shows these as queued, with no stop button in the banner.

* fix(knowledge): answer stall verdicts from one shared queue scan

- Probing a quiet document for a backlog rescanned the whole queue once
  per document. When the document was absent, which is exactly the
  stuck case, the scan ran to the end, and it read a Redis error as
  "nothing queued". QueuedKnowledgeIDs now collects every referenced
  knowledge ID in one pass and returns list errors. HousekeepingService
  keeps that snapshot for a minute, shared across requests and
  single-flight. A failed scan is not cached.
- With the per-request cap of 20 gone, every quiet row on a page gets a
  verdict. The response carries it as stall_state (queued or stalled),
  replacing waiting_in_queue. The UI marks a row as stuck only on a
  "stalled" verdict. A row with no verdict, because the probe failed,
  shows as ordinary processing instead of inviting a stop.
main
lyingbug 2026-09-22 21:34:08 +08:00 committed by GitHub
parent 0a99a2850b
commit 6afb6ca9d5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
27 changed files with 1378 additions and 64 deletions

View File

@ -11,6 +11,7 @@ import {
type KnowledgeTraceNode,
} from '@/utils/knowledgeTrace'
import { resolveTimelineHeaderStatus } from '@/utils/knowledgeProcessingStatus'
import { shownStall, stalledMinutes, STALLED_POLL_INTERVAL_MS } from '@/utils/knowledgeProcessingStall'
import { axisGridStepPct, buildAxisTicks, computeTraceAxis } from '@/utils/traceAxis'
import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess'
@ -32,6 +33,10 @@ interface SpansResponse {
current_stage?: string
trace: SpanNode
last_error?: LastError | null
// Latest row or span write; only sent while the parse is in flight.
last_activity_at?: string
// Server verdict once quiet past the stall hint: 'queued' or 'stalled'.
stall_state?: string
}
// IMPORTANT: Vue 3 coerces missing Boolean props to `false`, NOT
@ -484,6 +489,21 @@ async function onManualRefresh() {
const cancelling = ref(false)
// Minutes the latest attempt has gone without progress; 0 unless it looks
// stuck. Historical attempts are never "stalled".
const stalledMin = computed<number>(() => {
const d = data.value
if (!d || d.attempt !== (d.latest_attempt || d.attempt)) return 0
return stalledMinutes(d, nowTick.value)
})
const stalledStageLabel = computed(() => {
const stage = data.value?.current_stage
return stage && (STAGES as readonly string[]).includes(stage)
? t(`knowledgeStages.stage.${stage}`)
: ''
})
// Mirrors the backend CancelKnowledgeParse gate (pending / processing /
// finalizing). Uses the freshest status we have: live span data first,
// the parent's hint before the first fetch lands.
@ -572,6 +592,8 @@ onMounted(() => {
if (unmounted) return
if (fetchInFlight) return
if (!shouldPollNow()) return
// Nothing is moving on a stalled trace; check back less often.
if (stalledMin.value > 0 && Date.now() - lastFetchedAt.value < STALLED_POLL_INTERVAL_MS) return
fetchSpans()
}, POLL_INTERVAL_MS)
}
@ -1324,6 +1346,16 @@ const headStats = computed<HeadStat[]>(() => {
mono: true,
})
}
const lastActivity = parseTime(data.value.last_activity_at)
if (lastActivity !== null && isLive.value) {
out.push({
key: 'progress',
label: t('knowledgeStages.head.lastProgress'),
value: formatRelativeTime(lastActivity),
mono: false,
note: stalledMin.value > 0,
})
}
if (lastFetchedAt.value && isLive.value) {
let updated = formatRelativeTime(lastFetchedAt.value)
if (!lastFetchOk.value) {
@ -1615,6 +1647,40 @@ const processConfigLines = computed<string[]>(() => {
</button>
</div>
<div v-if="shownStall(data?.stall_state, stalledMin) === 'queued'" class="kp-stall kp-stall-queued"
role="status">
<t-icon name="time" size="16px" class="kp-stall-icon" />
<div class="kp-stall-body">
<div class="kp-stall-title">{{ t('knowledgeStages.stall.queuedTitle', { minutes: stalledMin }) }}</div>
<div class="kp-stall-hint">{{ t('knowledgeStages.stall.queuedHint') }}</div>
</div>
</div>
<div v-else-if="shownStall(data?.stall_state, stalledMin) === 'stalled'" class="kp-stall" role="status">
<t-icon name="time" size="16px" class="kp-stall-icon" />
<div class="kp-stall-body">
<div class="kp-stall-title">{{ t('knowledgeStages.stall.title', { minutes: stalledMin }) }}</div>
<div class="kp-stall-hint">
{{ stalledStageLabel
? t('knowledgeStages.stall.hintAtStage', { stage: stalledStageLabel })
: t('knowledgeStages.stall.hint') }}
</div>
</div>
<t-popconfirm
v-if="canCancelParse"
theme="warning"
:content="t('knowledgeBase.cancelParseConfirmBody', { title: props.docTitle || props.knowledgeId })"
:confirm-btn="{ content: t('knowledgeBase.cancelParse'), theme: 'danger' }"
:cancel-btn="{ content: t('common.cancel') }"
placement="bottom"
@confirm="onCancelParseConfirm"
>
<button type="button" class="kp-stall-btn" :disabled="cancelling" @click.stop>
<t-icon :name="cancelling ? 'loading' : 'close-circle'" size="14px" />
<span>{{ t('knowledgeBase.cancelParse') }}</span>
</button>
</t-popconfirm>
</div>
<div v-if="showLastError && data?.last_error" class="kp-last-error" role="alert">
<div class="kp-err-top">
<span class="kp-err-glyph" aria-hidden="true">!</span>
@ -2998,6 +3064,82 @@ const processConfigLines = computed<string[]>(() => {
color: var(--td-text-color-anti);
}
/* Same card shape as .kp-last-error in the warning tone: the run may still
finish, so this nudges rather than alarms. */
.kp-stall {
display: flex;
align-items: flex-start;
gap: 10px;
margin-top: 12px;
padding: 12px 14px;
background: var(--td-warning-color-light);
border: 1px solid var(--td-warning-color-3);
border-left: 3px solid var(--td-warning-color);
border-radius: var(--td-radius-medium);
}
/* Backlogged, not stuck: neutral tone, and no stop button to invite
cancelling work that will still finish. */
.kp-stall-queued {
background: var(--td-bg-color-secondarycontainer);
border-color: var(--td-component-border);
border-left-color: var(--td-text-color-placeholder);
}
.kp-stall-queued .kp-stall-icon {
color: var(--td-text-color-secondary);
}
.kp-stall-icon {
flex-shrink: 0;
margin-top: 2px;
color: var(--td-warning-color);
}
.kp-stall-body {
flex: 1;
min-width: 0;
}
.kp-stall-title {
font-size: var(--app-text-sm);
font-weight: 600;
color: var(--td-text-color-primary);
}
.kp-stall-hint {
margin-top: 4px;
font-size: var(--app-text-sm);
line-height: 1.5;
color: var(--td-text-color-secondary);
}
.kp-stall-btn {
display: inline-flex;
align-items: center;
gap: 5px;
flex-shrink: 0;
height: 28px;
padding: 0 12px;
border: 1px solid var(--td-warning-color);
border-radius: var(--td-radius-default);
background: var(--td-bg-color-container);
color: var(--td-warning-color-7);
font-size: var(--app-text-sm);
cursor: pointer;
transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
}
.kp-stall-btn:hover:not(:disabled) {
background: var(--td-warning-color);
color: var(--td-text-color-anti);
}
.kp-stall-btn:disabled {
cursor: default;
opacity: 0.6;
}
/* ============== DETAIL PANEL ==============
v1 gave the waterfall flex:1 and the detail a fixed 50% / 320px. On a
short trace that meant ~55% of the panel was blank whenever nothing

View File

@ -788,6 +788,10 @@ export default {
statusCompleted: 'Completed',
statusProcessing: 'Processing',
statusFinalizing: 'Optimizing',
statusStalled: 'May be stuck',
stalledHint: 'No progress for {minutes} minutes; it may be stuck. Open the trace to see where it stopped, or stop parsing and rebuild the document.',
statusQueued: 'Queued',
queuedHint: 'No progress for {minutes} minutes, but its tasks are still waiting in the queue, usually because of a backlog. It will continue on its own.',
statusFailed: 'Failed',
statusCancelled: 'Cancelled',
statusDraft: 'Draft',
@ -926,7 +930,15 @@ export default {
minutesAgo: '{n}m ago',
noActivity: 'No parsing activity yet',
totalDuration: 'Total: {d}',
stall: {
title: 'No progress for {minutes} minutes; this may be stuck',
hint: 'You can keep waiting, or stop parsing and rebuild the document. If it still makes no progress, it will be marked as failed automatically.',
hintAtStage: 'It stopped at the {stage} stage. You can keep waiting, or stop parsing and rebuild the document. If it still makes no progress, it will be marked as failed automatically.',
queuedTitle: 'No progress for {minutes} minutes; still waiting in the queue',
queuedHint: 'Tasks for this document are still queued, usually because of a backlog. It will continue on its own; no action is usually needed.'
},
head: {
lastProgress: 'Last progress',
stagesDone: 'Main stages',
stagesProgress: 'Current stage',
attempt: 'Attempt',
@ -981,6 +993,8 @@ export default {
cancelled: 'Cancelled'
},
errorCode: {
TASK_STALLED: 'Stopped after no progress',
TASK_STALLED_SUGGESTION: 'Processing made no progress past the time limit and had no task left in the queue, so it was marked as failed. Click Retry; if this keeps happening, check the service this stage depends on (document parsing, model, or vector store).',
UNKNOWN_SUGGESTION: 'Check the application logs for details.'
}
},

View File

@ -788,6 +788,10 @@ export default {
statusCompleted: '完了',
statusProcessing: '処理中',
statusFinalizing: '最適化中',
statusStalled: '停止の可能性',
stalledHint: '{minutes} 分間進捗がありません。停止している可能性があります。トレースで停止箇所を確認するか、解析を停止してドキュメントを再構築してください。',
statusQueued: '待機中',
queuedHint: '{minutes} 分間進捗がありませんが、タスクはまだキューで待機しています。通常はバックログによるもので、自動的に再開されます。',
statusFailed: '失敗',
statusCancelled: 'キャンセル済み',
statusDraft: '下書き',
@ -926,7 +930,15 @@ export default {
minutesAgo: '{n}分前',
noActivity: '解析の記録はまだありません',
totalDuration: '合計: {d}',
stall: {
title: '{minutes} 分間進捗がありません。停止している可能性があります',
hint: 'このまま待つか、解析を停止してドキュメントを再構築できます。進捗がないままの場合は自動的に失敗としてマークされます。',
hintAtStage: '「{stage}」段階で止まっています。このまま待つか、解析を停止してドキュメントを再構築できます。進捗がないままの場合は自動的に失敗としてマークされます。',
queuedTitle: '{minutes} 分間進捗がありません。キューで待機中です',
queuedHint: 'このドキュメントのタスクはまだキューで待機しています。通常はバックログによるもので、自動的に再開されるため、操作は不要です。'
},
head: {
lastProgress: '最終進捗',
stagesDone: '主要ステージ',
stagesProgress: '現在のステージ',
attempt: '試行',
@ -981,6 +993,8 @@ export default {
cancelled: 'キャンセル済み'
},
errorCode: {
TASK_STALLED: '進捗がないため自動停止しました',
TASK_STALLED_SUGGESTION: 'しきい値を超えても進捗がなく、キューにも対応するタスクがないため失敗としてマークされました。「再試行」を押してください。繰り返し発生する場合は、この段階が依存するサービス(文書解析、モデル、ベクトルストア)を確認してください。',
UNKNOWN_SUGGESTION: '詳細はアプリケーションログを確認してください。'
}
},

View File

@ -6573,6 +6573,8 @@ export default {
noActivity: '파싱 활동 없음',
totalDuration: '총 소요시간: {d}',
errorCode: {
TASK_STALLED: '진행이 없어 자동 중단됨',
TASK_STALLED_SUGGESTION: '임계 시간을 넘도록 진행이 없고 대기열에도 해당 작업이 없어 실패로 표시되었습니다. 「다시 시도」를 누르세요. 반복되면 이 단계가 의존하는 서비스(문서 파싱, 모델, 벡터 저장소)를 확인하세요.',
UNKNOWN_SUGGESTION: '자세한 내용은 애플리케이션 로그를 확인하세요.'
},
status: {
@ -6623,7 +6625,15 @@ export default {
overview: '개요',
raw: '원본 JSON'
},
stall: {
title: '{minutes}분 동안 진행이 없어 멈췄을 수 있습니다',
hint: '계속 기다리거나 파싱을 중지한 뒤 지식을 재구축할 수 있습니다. 계속 진행이 없으면 자동으로 실패 처리됩니다.',
hintAtStage: '「{stage}」 단계에서 멈춰 있습니다. 계속 기다리거나 파싱을 중지한 뒤 지식을 재구축할 수 있습니다. 계속 진행이 없으면 자동으로 실패 처리됩니다.',
queuedTitle: '{minutes}분 동안 진행이 없습니다. 아직 대기열에서 기다리는 중입니다',
queuedHint: '이 문서의 작업이 아직 대기열에 있습니다. 보통 작업 적체 때문이며 자동으로 이어지므로 대개 조치가 필요 없습니다.'
},
head: {
lastProgress: '최근 진행',
stagesDone: '주요 단계',
stagesProgress: '현재 단계',
attempt: '시도',
@ -6959,6 +6969,10 @@ export default {
statusCompleted: '완료',
statusProcessing: '처리 중',
statusFinalizing: '최적화 중',
statusStalled: '멈춤 의심',
stalledHint: '{minutes}분 동안 진행이 없습니다. 멈췄을 수 있습니다. Trace에서 멈춘 위치를 확인하거나 파싱을 중지한 뒤 지식을 재구축하세요.',
statusQueued: '대기 중',
queuedHint: '{minutes}분 동안 진행이 없지만 작업이 아직 대기열에서 기다리고 있습니다. 보통 작업 적체 때문이며 곧 자동으로 이어집니다.',
statusFailed: '실패',
statusCancelled: '취소됨',
statusDraft: '초안',

View File

@ -6573,6 +6573,8 @@ export default {
noActivity: 'Нет активности парсинга',
totalDuration: 'Всего: {d}',
errorCode: {
TASK_STALLED: 'Остановлено из-за отсутствия прогресса',
TASK_STALLED_SUGGESTION: 'Обработка не продвигалась дольше порога, и в очереди не осталось задач, поэтому она помечена как ошибочная. Нажмите «Повторить»; если это повторяется, проверьте сервис, от которого зависит этап (разбор документов, модель или векторное хранилище).',
UNKNOWN_SUGGESTION: 'Проверьте логи приложения для подробностей.'
},
status: {
@ -6623,7 +6625,15 @@ export default {
overview: 'Overview',
raw: 'Raw JSON'
},
stall: {
title: 'Нет прогресса {minutes} мин.; обработка могла зависнуть',
hint: 'Можно подождать или остановить разбор и пересобрать документ. Если прогресса так и не будет, документ будет автоматически помечен как ошибочный.',
hintAtStage: 'Обработка остановилась на этапе «{stage}». Можно подождать или остановить разбор и пересобрать документ. Если прогресса так и не будет, документ будет автоматически помечен как ошибочный.',
queuedTitle: 'Нет прогресса {minutes} мин.; задачи ещё ждут в очереди',
queuedHint: 'Задачи этого документа ещё в очереди, обычно из-за накопившихся задач. Обработка продолжится сама, обычно ничего делать не нужно.'
},
head: {
lastProgress: 'Последний прогресс',
stagesDone: 'Main stages',
stagesProgress: 'Current stage',
attempt: 'Attempt',
@ -6959,6 +6969,10 @@ export default {
statusCompleted: 'Завершено',
statusProcessing: 'Обработка',
statusFinalizing: 'Оптимизация',
statusStalled: 'Возможно, завис',
stalledHint: 'Нет прогресса {minutes} мин.; обработка могла зависнуть. Откройте трассировку, чтобы увидеть, где она остановилась, или остановите разбор и пересоберите документ.',
statusQueued: 'В очереди',
queuedHint: 'Нет прогресса {minutes} мин., но задачи документа ещё ждут в очереди — обычно из-за накопившихся задач. Обработка продолжится сама.',
statusFailed: 'Ошибка',
statusCancelled: 'Отменено',
statusDraft: 'Черновик',

View File

@ -6575,6 +6575,8 @@ export default {
noActivity: '暂无解析记录',
totalDuration: '总耗时:{d}',
errorCode: {
TASK_STALLED: '长时间无进展,已自动终止',
TASK_STALLED_SUGGESTION: '处理超过阈值仍没有任何进展,且队列中已无对应任务,已被系统标记为失败。请点击「重试」;如反复出现,请检查该阶段依赖的服务(文档解析、模型、向量库)是否正常。',
UNKNOWN_SUGGESTION: '请查看应用日志获取详细信息。'
},
status: {
@ -6625,7 +6627,15 @@ export default {
overview: '概览',
raw: '原始 JSON'
},
stall: {
title: '已 {minutes} 分钟没有进展,可能已卡住',
hint: '可以继续等待,或停止解析后重建知识。长时间仍无进展时,系统会自动将其标记为失败。',
hintAtStage: '当前停在「{stage}」阶段。可以继续等待,或停止解析后重建知识。长时间仍无进展时,系统会自动将其标记为失败。',
queuedTitle: '已 {minutes} 分钟没有进展,任务仍在排队',
queuedHint: '这篇文档还有任务在队列中等待处理,通常是任务积压导致,稍后会自动继续,一般无需操作。'
},
head: {
lastProgress: '最近进展',
stagesDone: '主流程阶段',
stagesProgress: '当前阶段',
attempt: '尝试',
@ -6961,6 +6971,10 @@ export default {
statusCompleted: '已完成',
statusProcessing: '解析中',
statusFinalizing: '优化中',
statusStalled: '疑似卡住',
stalledHint: '已 {minutes} 分钟没有进展,可能已卡住。可打开 Trace 查看停在哪一步,或停止解析后重建知识。',
statusQueued: '排队中',
queuedHint: '已 {minutes} 分钟没有进展,但仍有任务在队列中等待处理,通常是任务积压,稍后会自动继续。',
statusFailed: '失败',
statusCancelled: '已取消',
statusDraft: '草稿',

View File

@ -0,0 +1,28 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { shownStall, stalledMinutes, PROCESSING_STALL_THRESHOLD_MS } from './knowledgeProcessingStall.ts'
const now = Date.parse('2026-09-22T10:00:00Z')
const ago = (ms: number) => new Date(now - ms).toISOString()
test('in-flight document idle past the threshold reports whole minutes', () => {
assert.equal(stalledMinutes({ parse_status: 'processing', last_activity_at: ago(47 * 60000 + 30000) }, now), 47)
assert.equal(stalledMinutes({ parse_status: 'finalizing', last_activity_at: ago(PROCESSING_STALL_THRESHOLD_MS) }, now), 20)
assert.equal(stalledMinutes({ parse_status: 'pending', last_activity_at: ago(2 * 3600000) }, now), 120)
})
test('recent activity, finished rows and unknown activity are not stalled', () => {
assert.equal(stalledMinutes({ parse_status: 'processing', last_activity_at: ago(PROCESSING_STALL_THRESHOLD_MS - 1) }, now), 0)
assert.equal(stalledMinutes({ parse_status: 'completed', last_activity_at: ago(3600000) }, now), 0)
assert.equal(stalledMinutes({ parse_status: 'failed', last_activity_at: ago(3600000) }, now), 0)
assert.equal(stalledMinutes({ parse_status: 'processing' }, now), 0)
assert.equal(stalledMinutes({ parse_status: 'processing', last_activity_at: 'not a date' }, now), 0)
})
test('only a server verdict on a still-quiet document is shown', () => {
assert.equal(shownStall('queued', 25), 'queued')
assert.equal(shownStall('stalled', 25), 'stalled')
assert.equal(shownStall(undefined, 25), '', 'no verdict: the probe failed or was not run')
assert.equal(shownStall('stalled', 0), '', 'progress resumed since the verdict')
assert.equal(shownStall('bogus', 25), '')
})

View File

@ -0,0 +1,35 @@
// A stage can legitimately run for a while between span writes (one
// DocReader call on a large file, a single LLM call), so this only flags a
// document as possibly stuck; the server fails it after its own threshold.
export const PROCESSING_STALL_THRESHOLD_MS = 20 * 60 * 1000
// Once everything in flight looks stalled, poll at this slower interval.
export const STALLED_POLL_INTERVAL_MS = 15 * 1000
const IN_FLIGHT = new Set(['pending', 'processing', 'finalizing'])
export type ProcessingActivity = {
parse_status?: string
last_activity_at?: string | null
}
// stalledMinutes returns how long an in-flight document has gone without
// progress, or 0 while it is progressing, finished, or its activity is unknown.
export function stalledMinutes(item: ProcessingActivity, now: number = Date.now()): number {
if (!IN_FLIGHT.has(item.parse_status ?? '') || !item.last_activity_at) return 0
const last = Date.parse(item.last_activity_at)
if (Number.isNaN(last)) return 0
const idle = now - last
return idle >= PROCESSING_STALL_THRESHOLD_MS ? Math.floor(idle / 60000) : 0
}
export type StallVerdict = 'queued' | 'stalled' | ''
// shownStall is the stall verdict to display: the server's stall_state, and
// only while the document is still quiet past the threshold. No verdict
// (not sent, or the server could not probe the queue) shows as ordinary
// processing: calling a backlogged document stuck invites stopping it.
export function shownStall(stallState: string | undefined, minutes: number | undefined): StallVerdict {
if (!minutes) return ''
return stallState === 'queued' || stallState === 'stalled' ? stallState : ''
}

View File

@ -60,6 +60,7 @@ import {
knowledgeNeedsStatusPolling,
shouldRefreshWikiStatusAfterKnowledgePoll,
} from './wikiStatusRefresh';
import { stalledMinutes, STALLED_POLL_INTERVAL_MS } from '@/utils/knowledgeProcessingStall';
import { listMoveTargets, moveKnowledge, getKnowledgeMoveProgress } from '@/api/knowledge-base';
import { resolveKnowledgeDownloadFileName } from './knowledgeDownloadFileName';
import {
@ -1266,7 +1267,8 @@ watch(() => cardList.value, (newValue) => {
timeout = null;
}
if (analyzeList.length) {
updateStatus(analyzeList)
// The deep watch refires as stalled_minutes ticks; keep the backoff.
updateStatus(analyzeList, pollDelayFor(analyzeList))
}
}, { deep: true })
@ -1287,6 +1289,11 @@ type KnowledgeCard = {
metadata?: any;
error_message?: string;
tags?: Array<{ id: string; name: string; color?: string }>;
last_activity_at?: string;
// Minutes without progress while in flight; 0 unless it looks stuck.
stalled_minutes?: number;
// Server verdict on a quiet row: 'queued' (backlogged) or 'stalled'.
stall_state?: string;
};
// needsStatusPolling decides whether a card row is still "in flight"
// enough that the doc list should keep refreshing it. Keep in sync with
@ -1298,7 +1305,14 @@ const needsStatusPolling = (item: KnowledgeCard) => {
return knowledgeNeedsStatusPolling(item);
};
const updateStatus = (analyzeList: KnowledgeCard[]) => {
// Back off once every in-flight row looks stuck: nothing is moving, and a
// page left open on it should not keep hammering the batch endpoint.
const pollDelayFor = (items: KnowledgeCard[]) =>
items.length > 0 && items.every(item => (item.stalled_minutes ?? 0) > 0)
? STALLED_POLL_INTERVAL_MS
: 1500;
const updateStatus = (analyzeList: KnowledgeCard[], delay = 1500) => {
if (timeout !== null) {
clearTimeout(timeout);
timeout = null;
@ -1326,6 +1340,11 @@ const updateStatus = (analyzeList: KnowledgeCard[]) => {
}
}
const card = cardList.value[index];
card.last_activity_at = item.last_activity_at;
card.stall_state = item.stall_state;
card.stalled_minutes = stalledMinutes({ parse_status: parseStatus, last_activity_at: item.last_activity_at });
if (cardList.value[index].parse_status !== parseStatus ||
cardList.value[index].summary_status !== item.summary_status ||
cardList.value[index].description !== item.description) {
@ -1350,16 +1369,16 @@ const updateStatus = (analyzeList: KnowledgeCard[]) => {
// The watch will clear this timeout if it triggers.
const stillPending = cardList.value.filter(needsStatusPolling);
if (stillPending.length > 0) {
updateStatus(stillPending);
updateStatus(stillPending, pollDelayFor(stillPending));
}
}).catch((_err) => {
// 错误处理
const stillPending = cardList.value.filter(needsStatusPolling);
if (stillPending.length > 0) {
updateStatus(stillPending);
updateStatus(stillPending, pollDelayFor(stillPending));
}
});
}, 1500);
}, delay);
};

View File

@ -8,6 +8,7 @@ import DocumentFileIcon from './DocumentFileIcon.vue';
import DocumentActionMenu from './DocumentActionMenu.vue';
import FolderPickerMenu, { type FolderOption } from './FolderPickerMenu.vue';
import KnowledgeProcessingTimeline from '@/components/knowledge-processing-timeline.vue';
import { shownStall } from '@/utils/knowledgeProcessingStall';
interface KnowledgeCard {
id: string;
@ -27,6 +28,8 @@ interface KnowledgeCard {
metadata?: any;
error_message?: string;
tags?: Array<{ id: string; name: string; color?: string }>;
stalled_minutes?: number;
stall_state?: string;
source?: string;
created_at?: string;
file_size?: number | string;
@ -112,6 +115,8 @@ const isTraceMenuVisible = (item: KnowledgeCard): boolean => {
};
const inFlightCardStatusText = (item: KnowledgeCard): string => {
const stall = shownStall(item.stall_state, item.stalled_minutes);
if (stall) return t(stall === 'queued' ? 'knowledgeBase.statusQueued' : 'knowledgeBase.statusStalled');
if (item.parse_status === 'finalizing') {
if (item.summary_status === 'pending' || item.summary_status === 'processing') {
return t('knowledgeBase.generatingSummary');
@ -478,13 +483,18 @@ const handleAction = (action: 'download' | 'edit' | 'view-trace' | 'reparse' | '
<div class="card-preview" @mouseenter="onCardMouseEnter($event, item)" @mouseleave="onCardMouseLeave">
<!-- Parse status display -->
<div v-if="isParseInFlight(item.parse_status)" class="card-analyze card-analyze-trace">
<t-icon name="loading" class="card-analyze-loading"></t-icon>
<div v-if="isParseInFlight(item.parse_status)" class="card-analyze card-analyze-trace"
:class="shownStall(item.stall_state, item.stalled_minutes)">
<t-icon :name="shownStall(item.stall_state, item.stalled_minutes) ? 'time' : 'loading'"
class="card-analyze-loading"></t-icon>
<span
class="card-analyze-txt card-analyze-trace-link"
role="button"
tabindex="0"
:title="$t('knowledgeStages.viewTrace')"
:title="shownStall(item.stall_state, item.stalled_minutes)
? $t(shownStall(item.stall_state, item.stalled_minutes) === 'queued'
? 'knowledgeBase.queuedHint' : 'knowledgeBase.stalledHint', { minutes: item.stalled_minutes })
: $t('knowledgeStages.viewTrace')"
@click.stop="handleAction('view-trace', item)"
@keydown.enter.stop="handleAction('view-trace', item)"
@keydown.space.prevent.stop="handleAction('view-trace', item)"
@ -840,6 +850,8 @@ const handleAction = (action: 'download' | 'edit' | 'view-trace' | 'reparse' | '
&:hover { background: var(--td-bg-color-component-hover); }
}
.card-analyze.failure { color: var(--td-error-color); }
.card-analyze.stalled { color: var(--td-warning-color); }
.card-analyze.queued { color: var(--td-text-color-secondary); }
.card-draft { color: var(--td-warning-color); }
.card-cancelled { color: var(--td-text-color-placeholder); }
.card-draft-tip { font-size: var(--app-text-xs); }

View File

@ -6,6 +6,7 @@ import KnowledgeTagPopover from './KnowledgeTagPopover.vue';
import DocumentFileIcon from './DocumentFileIcon.vue';
import DocumentActionMenu from './DocumentActionMenu.vue';
import FolderPickerMenu, { type FolderOption } from './FolderPickerMenu.vue';
import { shownStall } from '@/utils/knowledgeProcessingStall';
interface Tag {
id: string;
@ -29,6 +30,8 @@ interface KnowledgeItem {
description?: string;
channel?: string;
isMore?: boolean;
stalled_minutes?: number;
stall_state?: string;
}
const props = defineProps<{
@ -116,8 +119,26 @@ interface StatusInfo {
theme: 'success' | 'warning' | 'danger' | 'primary' | 'default';
icon?: string;
spin?: boolean;
hint?: string;
}
const computeStatus = (item: KnowledgeItem): StatusInfo => {
const stall = shownStall(item.stall_state, item.stalled_minutes);
if (stall === 'queued') {
return {
label: t('knowledgeBase.statusQueued'),
theme: 'default',
icon: 'time',
hint: t('knowledgeBase.queuedHint', { minutes: item.stalled_minutes }),
};
}
if (stall === 'stalled') {
return {
label: t('knowledgeBase.statusStalled'),
theme: 'warning',
icon: 'time',
hint: t('knowledgeBase.stalledHint', { minutes: item.stalled_minutes }),
};
}
if (item.parse_status === 'pending' || item.parse_status === 'processing') {
return { label: t('knowledgeBase.statusProcessing'), theme: 'primary', icon: 'loading', spin: true };
}
@ -312,7 +333,8 @@ const handleAction = (action: 'download' | 'edit' | 'reparse' | 'cancel-parse' |
<div class="cell cell-status" role="cell">
<template v-if="statusByRow.get(item.id) as StatusInfo | undefined">
<t-tag v-if="statusByRow.get(item.id)!.label !== '--'" size="small" :theme="statusByRow.get(item.id)!.theme"
variant="light" class="row-status-tag" :class="`status-${statusByRow.get(item.id)!.theme}`">
variant="light" class="row-status-tag" :class="`status-${statusByRow.get(item.id)!.theme}`"
:title="statusByRow.get(item.id)!.hint">
<template v-if="statusByRow.get(item.id)!.icon" #icon>
<t-icon :name="statusByRow.get(item.id)!.icon!"
:class="{ 'icon-spin': statusByRow.get(item.id)!.spin }" />

View File

@ -44,6 +44,9 @@ type KnowledgeSpanRepository interface {
// after asynq retry or server restart so the trace tree does not
// accumulate duplicate postprocess.summary / question rows.
CancelOpenSpansByName(ctx context.Context, knowledgeID string, attempt int, name, errorCode, reason string) (int64, error)
// LastActivity returns each knowledge's most recent span write, across
// attempts. Knowledge without spans is absent from the map.
LastActivity(ctx context.Context, knowledgeIDs []string) (map[string]time.Time, error)
}
type knowledgeSpanRepository struct {
@ -269,3 +272,52 @@ func (r *knowledgeSpanRepository) CancelOpenSpansByName(
}
return res.RowsAffected, nil
}
func (r *knowledgeSpanRepository) LastActivity(
ctx context.Context, knowledgeIDs []string,
) (map[string]time.Time, error) {
out := make(map[string]time.Time, len(knowledgeIDs))
if len(knowledgeIDs) == 0 {
return out, nil
}
// MAX() comes back as a string on SQLite, so scan text and parse.
var rows []struct {
KnowledgeID string `gorm:"column:knowledge_id"`
LastSeen string `gorm:"column:last_seen"`
}
if err := r.db.WithContext(ctx).
Model(&types.KnowledgeProcessingSpan{}).
Select("knowledge_id, MAX(updated_at) AS last_seen").
Where("knowledge_id IN ?", knowledgeIDs).
Group("knowledge_id").
Scan(&rows).Error; err != nil {
return nil, err
}
for _, row := range rows {
if t, ok := ParseAggregateTime(row.LastSeen); ok {
out[row.KnowledgeID] = t
}
}
return out, nil
}
// ParseAggregateTime parses a timestamp read back through an SQL aggregate,
// in the formats Postgres and SQLite emit.
func ParseAggregateTime(s string) (time.Time, bool) {
if s == "" {
return time.Time{}, false
}
for _, layout := range []string{
time.RFC3339Nano,
time.RFC3339,
"2006-01-02 15:04:05.999999999-07:00",
"2006-01-02 15:04:05.999999999",
"2006-01-02 15:04:05.999999",
"2006-01-02 15:04:05",
} {
if t, err := time.Parse(layout, s); err == nil {
return t, true
}
}
return time.Time{}, false
}

View File

@ -2,6 +2,7 @@ package repository
import (
"context"
"fmt"
"testing"
"time"
"unicode/utf8"
@ -280,3 +281,27 @@ func TestKnowledgeSpanRepo_ListAttemptIsolation(t *testing.T) {
require.NoError(t, err)
assert.Len(t, all, 2, "attempt=0 returns all attempts (used by housekeeping)")
}
func TestKnowledgeSpanRepo_LastActivity(t *testing.T) {
_, db := setupSpanTestRepo(t)
repo := NewKnowledgeSpanRepository(db)
ctx := context.Background()
base := time.Date(2026, 9, 22, 10, 0, 0, 0, time.UTC)
for i, at := range []time.Time{base, base.Add(7 * time.Minute), base.Add(3 * time.Minute)} {
require.NoError(t, db.Exec(
`INSERT INTO knowledge_processing_spans (knowledge_id, attempt, span_id, name, kind, status, updated_at)
VALUES ('k-1', ?, ?, 'docreader', 'stage', 'running', ?)`, i+1, fmt.Sprintf("s-%d", i), at,
).Error)
}
got, err := repo.LastActivity(ctx, []string{"k-1", "k-none"})
require.NoError(t, err)
require.Contains(t, got, "k-1")
assert.True(t, got["k-1"].Equal(base.Add(7*time.Minute)), "got %s", got["k-1"])
assert.NotContains(t, got, "k-none")
empty, err := repo.LastActivity(ctx, nil)
require.NoError(t, err)
assert.Empty(t, empty)
}

View File

@ -20,12 +20,15 @@ package service
import (
"context"
"fmt"
"os"
"strings"
"sync"
"time"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/config"
werrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@ -55,8 +58,16 @@ type HousekeepingService struct {
kickMu sync.Mutex
wikiKicks map[string]time.Time
queuedMu sync.Mutex
queuedIDs map[string]struct{}
queuedAt time.Time
}
// queuedProbeTTL bounds how often QueuedWork rescans the queue; clients poll
// far more often than a backlog changes.
const queuedProbeTTL = time.Minute
// NewHousekeepingService constructs a HousekeepingService. It does NOT start
// the cron — call Start in the application bootstrap so a misconfigured
// cron schedule cannot prevent the rest of the service from coming up.
@ -153,7 +164,7 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
return
}
stuck := h.filterByLastSpanActivity(ctx, candidates, cutoff)
stuck, heartbeat := h.filterByLastSpanActivity(ctx, candidates, cutoff)
spanSkipped := len(candidates) - len(stuck)
// Second-stage gate: a row can have a stale span heartbeat yet still
@ -168,23 +179,9 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
h.rearmWikiTriggers(ctx, wikiHeld, threshold)
if len(stuck) > 0 {
stuckIDs := make([]string, 0, len(stuck))
for _, k := range stuck {
stuckIDs = append(stuckIDs, k.ID)
}
res := h.db.WithContext(ctx).Model(&types.Knowledge{}).
Where("id IN ? AND parse_status IN ?", stuckIDs,
[]string{types.ParseStatusPending, types.ParseStatusProcessing, types.ParseStatusFinalizing}).
Updates(map[string]interface{}{
"parse_status": types.ParseStatusFailed,
"error_message": "task stuck in processing > " + threshold.String() + ", recovered by housekeeping",
"pending_subtasks_count": 0,
})
if res.Error != nil {
logger.Warnf(ctx, "[Housekeeping] knowledge sweep update failed: %v", res.Error)
} else if res.RowsAffected > 0 {
if recovered := h.recoverStalled(ctx, stuck, heartbeat, threshold); recovered > 0 {
logger.Infof(ctx, "[Housekeeping] recovered %d stuck knowledge rows (threshold=%s)",
res.RowsAffected, threshold)
recovered, threshold)
}
}
if spanSkipped > 0 {
@ -280,9 +277,11 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
// with no span rows at all also pass through (they're lite-mode or
// pre-instrumentation tasks; the simple updated_at check already proved
// them stuck and we have no heartbeat to override that).
func (h *HousekeepingService) filterByLastSpanActivity(ctx context.Context, candidates []types.Knowledge, cutoff time.Time) []types.Knowledge {
func (h *HousekeepingService) filterByLastSpanActivity(
ctx context.Context, candidates []types.Knowledge, cutoff time.Time,
) ([]types.Knowledge, map[string]time.Time) {
if len(candidates) == 0 {
return candidates
return candidates, nil
}
ids := make([]string, 0, len(candidates))
for _, k := range candidates {
@ -312,11 +311,11 @@ func (h *HousekeepingService) filterByLastSpanActivity(ctx context.Context, cand
// heartbeat (so all candidates are "stuck"). This matches
// the previous-version behaviour and never under-recovers.
logger.Warnf(ctx, "[Housekeeping] span heartbeat query failed: %v (will fail safe and recover all candidates)", err)
return candidates
return candidates, nil
}
heartbeat := make(map[string]time.Time, len(beats))
for _, b := range beats {
if t, ok := parseHeartbeatTime(b.LastSeen); ok {
if t, ok := apprepo.ParseAggregateTime(b.LastSeen); ok {
heartbeat[b.KnowledgeID] = t
}
}
@ -329,7 +328,213 @@ func (h *HousekeepingService) filterByLastSpanActivity(ctx context.Context, cand
}
out = append(out, k)
}
return out
return out, heartbeat
}
// recoverStalled fails each stuck row with a message naming where it stalled
// and when it last made progress, and closes its open spans so the timeline
// points at that spot instead of spinning. heartbeat is nil when the span
// heartbeat query failed; the message then gives no time rather than the
// row's updated_at, which can predate the last span write. Returns rows
// recovered.
func (h *HousekeepingService) recoverStalled(
ctx context.Context, stuck []types.Knowledge, heartbeat map[string]time.Time, threshold time.Duration,
) int64 {
ids := make([]string, 0, len(stuck))
for _, k := range stuck {
ids = append(ids, k.ID)
}
sites := h.locateStalls(ctx, ids)
var recovered int64
for _, k := range stuck {
site := sites[k.ID]
msg := stallMessage(k, site, heartbeat, threshold)
res := h.db.WithContext(ctx).Model(&types.Knowledge{}).
Where("id = ? AND parse_status IN ?", k.ID,
[]string{types.ParseStatusPending, types.ParseStatusProcessing, types.ParseStatusFinalizing}).
Updates(map[string]interface{}{
"parse_status": types.ParseStatusFailed,
"error_message": msg,
"pending_subtasks_count": 0,
})
if res.Error != nil {
logger.Warnf(ctx, "[Housekeeping] knowledge sweep update failed for %s: %v", k.ID, res.Error)
continue
}
if res.RowsAffected == 0 {
continue
}
recovered += res.RowsAffected
if site != nil {
h.closeStalledSpans(ctx, k.ID, site, msg)
}
}
return recovered
}
// stallSite is where a stuck row stopped, read from its latest attempt.
type stallSite struct {
// stages the run stalled in, in pipeline order.
stages []string
// tasks names the stalled spans when they are below a finished stage,
// e.g. postprocess.summary while the row sits in finalizing.
tasks []string
// open holds the attempt's pending/running spans; those in failed are
// marked failed, the rest cancelled.
open []types.KnowledgeProcessingSpan
failed map[int64]bool
}
// locateStalls finds each row's stall site. The stalled spans are the running
// stages; when no stage is running (post-process closes its stage once the
// enrichment tasks are fanned out) they are the innermost running spans, and
// the stage is the one they belong to. Best-effort: a query error yields no
// sites and the rows are still failed.
func (h *HousekeepingService) locateStalls(ctx context.Context, ids []string) map[string]*stallSite {
var rows []types.KnowledgeProcessingSpan
if err := h.db.WithContext(ctx).
Select("id", "knowledge_id", "attempt", "span_id", "parent_span_id", "name", "kind", "status", "started_at").
Where("knowledge_id IN ?", ids).
Order("id").
Find(&rows).Error; err != nil {
logger.Warnf(ctx, "[Housekeeping] stalled span query failed: %v", err)
return nil
}
latest := make(map[string]int, len(ids))
for _, r := range rows {
if r.Attempt > latest[r.KnowledgeID] {
latest[r.KnowledgeID] = r.Attempt
}
}
byKnowledge := make(map[string][]types.KnowledgeProcessingSpan, len(ids))
for _, r := range rows {
if r.Attempt == latest[r.KnowledgeID] {
byKnowledge[r.KnowledgeID] = append(byKnowledge[r.KnowledgeID], r)
}
}
sites := make(map[string]*stallSite, len(byKnowledge))
for kid, spans := range byKnowledge {
sites[kid] = stallSiteOf(spans)
}
return sites
}
func stallSiteOf(spans []types.KnowledgeProcessingSpan) *stallSite {
bySpanID := make(map[string]types.KnowledgeProcessingSpan, len(spans))
runningChildren := make(map[string]int)
for _, sp := range spans {
bySpanID[sp.SpanID] = sp
if sp.Status == types.SpanStatusRunning && sp.ParentSpanID != "" {
runningChildren[sp.ParentSpanID]++
}
}
stageOf := func(sp types.KnowledgeProcessingSpan) string {
for depth := 0; depth < 64; depth++ {
if sp.Kind == types.SpanKindStage {
return sp.Name
}
parent, ok := bySpanID[sp.ParentSpanID]
if !ok {
return ""
}
sp = parent
}
return ""
}
site := &stallSite{failed: make(map[int64]bool)}
var stalled []types.KnowledgeProcessingSpan
for _, sp := range spans {
if sp.Status == types.SpanStatusPending || sp.Status == types.SpanStatusRunning {
site.open = append(site.open, sp)
}
if sp.Status == types.SpanStatusRunning && sp.Kind == types.SpanKindStage {
stalled = append(stalled, sp)
}
}
if len(stalled) == 0 {
for _, sp := range spans {
innermost := runningChildren[sp.SpanID] == 0
if sp.Status == types.SpanStatusRunning && sp.Kind != types.SpanKindRoot && innermost {
stalled = append(stalled, sp)
site.tasks = append(site.tasks, sp.Name)
}
}
}
seen := make(map[string]bool)
for _, sp := range stalled {
site.failed[sp.ID] = true
if stage := stageOf(sp); stage != "" {
seen[stage] = true
}
}
for _, stage := range types.AllStages {
if seen[stage] {
site.stages = append(site.stages, stage)
}
}
return site
}
// stallMessage is the error_message for a recovered row, e.g. "task stuck in
// finalizing at postprocess stage (postprocess.summary): no progress since
// 2026-09-22T09:37:54Z (> 2h10m0s), recovered by housekeeping".
func stallMessage(
k types.Knowledge, site *stallSite, heartbeat map[string]time.Time, threshold time.Duration,
) string {
where := ""
if site != nil && len(site.stages) > 0 {
where = " at " + strings.Join(site.stages, "/") + " stage"
if len(site.tasks) > 0 {
tasks := site.tasks
if len(tasks) > 3 {
tasks = append(tasks[:3:3], "…")
}
where += " (" + strings.Join(tasks, ", ") + ")"
}
}
if heartbeat == nil {
return fmt.Sprintf("task stuck in %s%s: no progress for > %s, recovered by housekeeping",
k.ParseStatus, where, threshold)
}
last := k.UpdatedAt
if beat, ok := heartbeat[k.ID]; ok && beat.After(last) {
last = beat
}
return fmt.Sprintf("task stuck in %s%s: no progress since %s (> %s), recovered by housekeeping",
k.ParseStatus, where, last.UTC().Format(time.RFC3339), threshold)
}
// closeStalledSpans fails the site's stalled spans and cancels its other open
// spans, all with TASK_STALLED and a duration, the way FailSpan closes a span.
// Best-effort: the row is already failed.
func (h *HousekeepingService) closeStalledSpans(
ctx context.Context, knowledgeID string, site *stallSite, msg string,
) {
now := time.Now()
for _, sp := range site.open {
status := types.SpanStatusCancelled
if site.failed[sp.ID] {
status = types.SpanStatusFailed
}
var durationMs int64
if sp.StartedAt != nil {
durationMs = now.Sub(*sp.StartedAt).Milliseconds()
}
if err := h.db.WithContext(ctx).Model(&types.KnowledgeProcessingSpan{}).
Where("id = ? AND status IN ?", sp.ID, []string{types.SpanStatusPending, types.SpanStatusRunning}).
Updates(map[string]interface{}{
"status": status,
"error_code": werrors.ErrCodeTaskStalled,
"error_message": msg,
"finished_at": now,
"duration_ms": durationMs,
"updated_at": now,
}).Error; err != nil {
logger.Warnf(ctx, "[Housekeeping] close stalled span %s of %s failed: %v", sp.SpanID, knowledgeID, err)
}
}
}
// filterOutQueued returns the subset of candidates that have NO work left
@ -410,6 +615,59 @@ func (h *HousekeepingService) filterOutQueued(
return out, skipped, wikiHeld
}
// QueuedWork reports which of ids still have work waiting in the queue or in
// the durable Wiki table, i.e. are backlogged rather than stuck, using the
// same probes as the sweep. The queue side is one shared scan (see
// queuedSnapshot), so answering a whole page costs one DB query. An error
// means the answer is unknown.
func (h *HousekeepingService) QueuedWork(ctx context.Context, ids []string) (map[string]bool, error) {
out := make(map[string]bool, len(ids))
if len(ids) == 0 {
return out, nil
}
var durableIDs []string
if err := h.db.WithContext(ctx).
Model(&types.TaskPendingOp{}).
Where("task_type = ? AND scope = ? AND op = ? AND dedup_key IN ?",
wikiTaskType, wikiTaskScope, WikiOpIngest, ids).
Distinct("dedup_key").
Pluck("dedup_key", &durableIDs).Error; err != nil {
return nil, fmt.Errorf("durable queue probe: %w", err)
}
queued, err := h.queuedSnapshot(ctx)
if err != nil {
return nil, err
}
for _, id := range ids {
_, out[id] = queued[id]
}
for _, id := range durableIDs {
out[id] = true
}
return out, nil
}
// queuedSnapshot returns the knowledge IDs referenced by queued tasks. One
// scan of the whole queue serves every caller for queuedProbeTTL; concurrent
// callers wait for the scan in flight rather than starting their own. A
// failed scan is not cached.
func (h *HousekeepingService) queuedSnapshot(ctx context.Context) (map[string]struct{}, error) {
if h.inspector == nil {
return nil, nil
}
h.queuedMu.Lock()
defer h.queuedMu.Unlock()
if h.queuedIDs != nil && time.Since(h.queuedAt) < queuedProbeTTL {
return h.queuedIDs, nil
}
ids, err := h.inspector.QueuedKnowledgeIDs(ctx)
if err != nil {
return nil, fmt.Errorf("queue probe: %w", err)
}
h.queuedIDs, h.queuedAt = ids, time.Now()
return ids, nil
}
// rearmWikiTriggers enqueues one wiki ingest trigger per KB whose stale rows
// are held only by durable Wiki ops. The trigger is ephemeral: once lost (or
// archived after its retries), nothing wakes the consumer until a restart or
@ -453,30 +711,6 @@ func (h *HousekeepingService) rearmWikiTriggers(
}
}
// parseHeartbeatTime accepts the timestamp formats Postgres and SQLite
// emit for a TIMESTAMP column read back through MAX(). Returns false if
// none parse — the caller treats unparseable rows as "no heartbeat",
// which fails safe (the row gets recovered as stuck rather than
// silently preserved).
func parseHeartbeatTime(s string) (time.Time, bool) {
if s == "" {
return time.Time{}, false
}
for _, layout := range []string{
time.RFC3339Nano,
time.RFC3339,
"2006-01-02 15:04:05.999999999-07:00",
"2006-01-02 15:04:05.999999999",
"2006-01-02 15:04:05.999999",
"2006-01-02 15:04:05",
} {
if t, err := time.Parse(layout, s); err == nil {
return t, true
}
}
return time.Time{}, false
}
// staleThreshold returns how long a "processing" row may sit untouched
// before housekeeping treats it as orphaned. The floor is 1 hour so that a
// genuinely slow large-PDF parse cannot be killed mid-flight; the ceiling

View File

@ -3,6 +3,7 @@ package service
import (
"context"
"errors"
"fmt"
"testing"
"time"
@ -154,6 +155,19 @@ func (f fakeTaskInspector) HasQueuedTasksForKnowledge(
return f.queued[knowledgeID], nil
}
func (f fakeTaskInspector) QueuedKnowledgeIDs(context.Context) (map[string]struct{}, error) {
if f.err != nil {
return nil, f.err
}
out := make(map[string]struct{})
for id, queued := range f.queued {
if queued {
out[id] = struct{}{}
}
}
return out, nil
}
func (f fakeTaskInspector) HasQueuedDeleteTasksForKnowledge(
_ context.Context, knowledgeID string,
) (bool, error) {
@ -483,3 +497,193 @@ func TestHousekeeping_NilInspectorDefersDeletingSweep(t *testing.T) {
status, _ := readKnowledgeStatus(t, db, "kid-nil-inspector")
assert.Equal(t, types.ParseStatusDeleting, status)
}
// A recovered row names the stage it stalled in and when it last moved, and
// its open spans are closed so the timeline stops showing them as running.
func TestHousekeeping_RecoveredRowNamesStalledStageAndClosesSpans(t *testing.T) {
db := setupHousekeepingDB(t)
svc := newHousekeepingSvcForTest(db)
stale := time.Now().Add(-3 * time.Hour)
lastBeat := stale.Add(30 * time.Minute)
insertKnowledge(t, db, "kid-stalled", types.ParseStatusProcessing, stale)
insertSpan(t, db, "kid-stalled", 1, "doc-1", types.SpanStatusRunning, lastBeat)
require.NoError(t, db.Exec(
`INSERT INTO knowledge_processing_spans
(knowledge_id, attempt, span_id, parent_span_id, name, kind, status, updated_at)
VALUES ('kid-stalled', 1, 'sub-1', 'doc-1', 'docreader.call', 'subspan', 'running', ?)`, stale,
).Error)
svc.runSweep(context.Background())
var status, errMsg string
require.NoError(t, db.Raw(
`SELECT parse_status, error_message FROM knowledges WHERE id = ?`, "kid-stalled",
).Row().Scan(&status, &errMsg))
assert.Equal(t, types.ParseStatusFailed, status)
assert.Contains(t, errMsg, "stuck in processing at docreader stage")
assert.Contains(t, errMsg, lastBeat.UTC().Format(time.RFC3339))
type spanState struct {
SpanID string
Status string
ErrorCode string
}
var spans []spanState
require.NoError(t, db.Raw(
`SELECT span_id, status, error_code FROM knowledge_processing_spans WHERE knowledge_id = ? ORDER BY span_id`,
"kid-stalled",
).Scan(&spans).Error)
assert.Equal(t, []spanState{
{SpanID: "doc-1", Status: types.SpanStatusFailed, ErrorCode: "TASK_STALLED"},
{SpanID: "sub-1", Status: types.SpanStatusCancelled, ErrorCode: "TASK_STALLED"},
}, spans)
}
func insertTreeSpan(
t *testing.T, db *gorm.DB, kid, spanID, parent, name, kind, status string, updatedAt time.Time,
) {
t.Helper()
started := updatedAt.Add(-5 * time.Minute)
require.NoError(t, db.Exec(
`INSERT INTO knowledge_processing_spans
(knowledge_id, attempt, span_id, parent_span_id, name, kind, status, started_at, updated_at)
VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?)`,
kid, spanID, parent, name, kind, status, started, updatedAt,
).Error)
}
type stalledSpanRow struct {
SpanID string
Status string
ErrorCode string
DurationMs int64
}
func stalledSpanRows(t *testing.T, db *gorm.DB, kid string) map[string]stalledSpanRow {
t.Helper()
var rows []stalledSpanRow
require.NoError(t, db.Raw(
`SELECT span_id, status, COALESCE(error_code, '') AS error_code, COALESCE(duration_ms, 0) AS duration_ms
FROM knowledge_processing_spans WHERE knowledge_id = ?`, kid,
).Scan(&rows).Error)
out := make(map[string]stalledSpanRow, len(rows))
for _, r := range rows {
out[r.SpanID] = r
}
return out
}
// A row stuck in finalizing has its post-process stage already closed; the
// stalled work is the enrichment subspans, which are what fail.
func TestHousekeeping_FinalizingStallFailsTheRunningSubspan(t *testing.T) {
db := setupHousekeepingDB(t)
svc := newHousekeepingSvcForTest(db)
stale := time.Now().Add(-3 * time.Hour)
insertKnowledge(t, db, "kid-fin", types.ParseStatusFinalizing, stale)
insertTreeSpan(t, db, "kid-fin", "root", "", "knowledge_processing", types.SpanKindRoot,
types.SpanStatusDone, stale)
insertTreeSpan(t, db, "kid-fin", "post", "root", types.StagePostProcess, types.SpanKindStage,
types.SpanStatusDone, stale)
insertTreeSpan(t, db, "kid-fin", "summary", "post", "postprocess.summary", types.SpanKindSubSpan,
types.SpanStatusRunning, stale)
insertTreeSpan(t, db, "kid-fin", "wiki", "post", "postprocess.wiki", types.SpanKindSubSpan,
types.SpanStatusPending, stale)
svc.runSweep(context.Background())
var errMsg string
require.NoError(t, db.Raw(`SELECT error_message FROM knowledges WHERE id = 'kid-fin'`).Scan(&errMsg).Error)
assert.Contains(t, errMsg, "stuck in finalizing at postprocess stage (postprocess.summary)")
spans := stalledSpanRows(t, db, "kid-fin")
assert.Equal(t, types.SpanStatusFailed, spans["summary"].Status)
assert.Equal(t, "TASK_STALLED", spans["summary"].ErrorCode)
assert.Positive(t, spans["summary"].DurationMs, "a closed span carries its duration")
assert.Equal(t, types.SpanStatusCancelled, spans["wiki"].Status)
assert.Equal(t, types.SpanStatusDone, spans["post"].Status, "finished spans are left alone")
assert.Equal(t, types.SpanStatusDone, spans["root"].Status)
}
// Two stages stalled together are both named, in pipeline order.
func TestHousekeeping_NamesEveryStalledStageInOrder(t *testing.T) {
db := setupHousekeepingDB(t)
svc := newHousekeepingSvcForTest(db)
stale := time.Now().Add(-3 * time.Hour)
insertKnowledge(t, db, "kid-two", types.ParseStatusProcessing, stale)
running := types.SpanStatusRunning
insertTreeSpan(t, db, "kid-two", "mm", "", types.StageMultimodal, types.SpanKindStage, running, stale)
insertTreeSpan(t, db, "kid-two", "emb", "", types.StageEmbedding, types.SpanKindStage, running, stale)
svc.runSweep(context.Background())
var errMsg string
require.NoError(t, db.Raw(`SELECT error_message FROM knowledges WHERE id = 'kid-two'`).Scan(&errMsg).Error)
assert.Contains(t, errMsg, "at embedding/multimodal stage")
spans := stalledSpanRows(t, db, "kid-two")
assert.Equal(t, types.SpanStatusFailed, spans["mm"].Status)
assert.Equal(t, types.SpanStatusFailed, spans["emb"].Status)
}
// Without a heartbeat the message gives no time: updated_at can predate the
// last span write.
func TestStallMessageOmitsTimeWithoutHeartbeat(t *testing.T) {
k := types.Knowledge{ID: "k", ParseStatus: types.ParseStatusProcessing, UpdatedAt: time.Now().Add(-5 * time.Hour)}
msg := stallMessage(k, &stallSite{stages: []string{types.StageDocReader}}, nil, 70*time.Minute)
assert.Equal(t,
"task stuck in processing at docreader stage: no progress for > 1h10m0s, recovered by housekeeping", msg)
}
// QueuedWork answers a whole batch from the durable Wiki table plus one shared
// queue scan, reuses that scan across calls, and reports a failed scan as an
// error without caching it.
func TestHousekeeping_QueuedWorkSharesOneQueueScan(t *testing.T) {
db := setupHousekeepingDB(t)
inspector := &countingTaskInspector{queued: map[string]bool{"k-queued": true}}
svc := newHousekeepingSvcWithInspector(db, inspector)
insertWikiPendingOp(t, db, "kb-1", "k-wiki")
ids := []string{"k-wiki", "k-queued"}
for i := 0; i < 40; i++ {
ids = append(ids, fmt.Sprintf("k-idle-%d", i))
}
got, err := svc.QueuedWork(context.Background(), ids)
require.NoError(t, err)
assert.Len(t, got, len(ids))
assert.True(t, got["k-wiki"])
assert.True(t, got["k-queued"])
assert.False(t, got["k-idle-39"])
assert.Equal(t, 1, inspector.scans, "one scan answers the whole batch")
_, err = svc.QueuedWork(context.Background(), []string{"k-queued"})
require.NoError(t, err)
assert.Equal(t, 1, inspector.scans, "the scan is reused within its TTL")
svc.queuedAt = time.Now().Add(-2 * queuedProbeTTL)
inspector.err = errors.New("redis down")
_, err = svc.QueuedWork(context.Background(), []string{"k-queued"})
require.Error(t, err)
inspector.err = nil
_, err = svc.QueuedWork(context.Background(), []string{"k-queued"})
require.NoError(t, err)
assert.Equal(t, 3, inspector.scans, "a failed scan is not cached")
}
type countingTaskInspector struct {
fakeTaskInspector
queued map[string]bool
err error
scans int
}
func (f *countingTaskInspector) QueuedKnowledgeIDs(context.Context) (map[string]struct{}, error) {
f.scans++
if f.err != nil {
return nil, f.err
}
out := make(map[string]struct{})
for id, queued := range f.queued {
if queued {
out[id] = struct{}{}
}
}
return out, nil
}

View File

@ -43,6 +43,10 @@ func (r *recordingKBTaskInspector) HasQueuedTasksForKnowledge(context.Context, s
return false, nil
}
func (r *recordingKBTaskInspector) QueuedKnowledgeIDs(context.Context) (map[string]struct{}, error) {
return map[string]struct{}{}, nil
}
func (r *recordingKBTaskInspector) QueueStats(context.Context) ([]types.QueueStat, bool, error) {
return nil, true, nil
}

View File

@ -56,6 +56,10 @@ const (
// timeout (whole task), not the docreader-call-level timeout.
ErrCodeTaskTimeout = "TASK_TIMEOUT"
// ErrCodeTaskStalled — housekeeping found no progress for longer than
// the stale threshold with nothing left queued, and failed the row.
ErrCodeTaskStalled = "TASK_STALLED"
// ErrCodeUnknown — fallback when a wrapped error doesn't classify.
// The full message is still recorded in error_detail so operators
// can debug; the UI shows a generic "see admin" hint.

View File

@ -12,6 +12,7 @@ import (
"github.com/Tencent/WeKnora/internal/application/access"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/filetransport"
@ -35,6 +36,40 @@ type KnowledgeHandler struct {
agentShareService interfaces.AgentShareService
asynqClient interfaces.TaskEnqueuer
spanRepo repository.KnowledgeSpanRepository
backlog backlogProbe
}
// backlogProbe tells a backlogged document (work still queued) from a stuck
// one; HousekeepingService implements it with the sweep's own probes.
type backlogProbe interface {
QueuedWork(ctx context.Context, ids []string) (map[string]bool, error)
}
// stallHintAfter is how long an in-flight row may go without progress before
// it gets a stall verdict; keep in step with PROCESSING_STALL_THRESHOLD_MS in
// the frontend.
const stallHintAfter = 20 * time.Minute
// stallVerdicts probes ids (all quiet past stallHintAfter) and returns each
// one's StallState. Nil when the probe is unavailable or failed: an unknown
// row gets no verdict rather than being called stuck.
func (h *KnowledgeHandler) stallVerdicts(ctx context.Context, ids []string) map[string]string {
if h.backlog == nil || len(ids) == 0 {
return nil
}
queued, err := h.backlog.QueuedWork(ctx, ids)
if err != nil {
logger.Warnf(ctx, "backlog probe failed: %v", err)
return nil
}
out := make(map[string]string, len(ids))
for _, id := range ids {
out[id] = types.StallStateStalled
if queued[id] {
out[id] = types.StallStateQueued
}
}
return out
}
// NewKnowledgeHandler creates a new knowledge handler instance
@ -46,8 +81,14 @@ func NewKnowledgeHandler(
agentShareService interfaces.AgentShareService,
asynqClient interfaces.TaskEnqueuer,
spanRepo repository.KnowledgeSpanRepository,
housekeeping *service.HousekeepingService,
) *KnowledgeHandler {
var backlog backlogProbe
if housekeeping != nil {
backlog = housekeeping
}
return &KnowledgeHandler{
backlog: backlog,
cfg: cfg,
kgService: kgService,
kbService: kbService,
@ -676,6 +717,15 @@ func (h *KnowledgeHandler) GetKnowledgeSpans(c *gin.Context) {
"current_stage": currentStageName,
"trace": tree,
}
if isParseInFlight(knowledge.ParseStatus) {
last := spansLastActivity(knowledge.UpdatedAt, rows)
resp["last_activity_at"] = last
if time.Since(last) >= stallHintAfter {
if verdict := h.stallVerdicts(ctx, []string{knowledge.ID})[knowledge.ID]; verdict != "" {
resp["stall_state"] = verdict
}
}
}
if lastError := knowledgeSpansLastError(
currentAttempt,
latestAttempt,
@ -814,11 +864,17 @@ func buildSpanTree(knowledgeID string, attempt int, rows []types.KnowledgeProces
if r.Status == types.SpanStatusRunning && r.Kind == types.SpanKindStage && currentStage == "" {
currentStage = r.Name
}
if r.Status == types.SpanStatusFailed {
// Housekeeping's TASK_STALLED marks where a stuck run stopped;
// an older subtask failure must not hide it.
if r.Status == types.SpanStatusFailed &&
(lastFailure == nil || !isStallFailure(lastFailure) || isStallFailure(&r)) {
cp := r
lastFailure = &cp
}
}
if currentStage == "" {
currentStage = stageOfRunningSpan(rows)
}
// Pick the synthesized stage status from parse_status. Without this,
// historical knowledge that completed before span tracking was wired
@ -1718,6 +1774,8 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
knowledges = filterKnowledgesByKBAllowSet(knowledges, allowedKBSet)
}
h.attachLastActivity(ctx, knowledges)
logger.Infof(ctx, "Batch knowledge retrieval successful, requested count: %d, returned count: %d",
len(req.IDs), len(knowledges))
@ -1727,6 +1785,99 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
})
}
func isStallFailure(span *types.KnowledgeProcessingSpan) bool {
return span.ErrorCode == errors.ErrCodeTaskStalled
}
// stageOfRunningSpan names the stage owning the newest running span, for the
// window where no stage span is running but its work still is: post-process
// closes its stage once summary / question / graph / wiki are fanned out.
func stageOfRunningSpan(rows []types.KnowledgeProcessingSpan) string {
bySpanID := make(map[string]*types.KnowledgeProcessingSpan, len(rows))
for i := range rows {
bySpanID[rows[i].SpanID] = &rows[i]
}
for i := len(rows) - 1; i >= 0; i-- {
if rows[i].Status != types.SpanStatusRunning || rows[i].Kind == types.SpanKindRoot {
continue
}
for span, depth := &rows[i], 0; span != nil && depth < 64; depth++ {
if span.Kind == types.SpanKindStage {
return span.Name
}
span = bySpanID[span.ParentSpanID]
}
}
return ""
}
// spansLastActivity is the latest of the row's updated_at and the listed
// spans' writes.
func spansLastActivity(updatedAt time.Time, rows []types.KnowledgeProcessingSpan) time.Time {
last := updatedAt
for _, row := range rows {
last = latestActivity(last, row.UpdatedAt)
}
return last
}
// attachLastActivity sets LastActivityAt on in-flight rows. updated_at only
// moves at stage transitions, so the latest span write is folded in: it
// advances with every subspan while a long stage is still working.
func (h *KnowledgeHandler) attachLastActivity(ctx context.Context, knowledges []*types.Knowledge) {
var ids []string
for _, k := range knowledges {
if k != nil && isParseInFlight(k.ParseStatus) {
ids = append(ids, k.ID)
}
}
if len(ids) == 0 {
return
}
var spanActivity map[string]time.Time
if h.spanRepo != nil {
var err error
if spanActivity, err = h.spanRepo.LastActivity(ctx, ids); err != nil {
logger.Warnf(ctx, "span last activity lookup failed: %v", err)
}
}
var quiet []*types.Knowledge
var quietIDs []string
for _, k := range knowledges {
if k == nil || !isParseInFlight(k.ParseStatus) {
continue
}
last := latestActivity(k.UpdatedAt, spanActivity[k.ID])
k.LastActivityAt = &last
if time.Since(last) >= stallHintAfter {
quiet = append(quiet, k)
quietIDs = append(quietIDs, k.ID)
}
}
verdicts := h.stallVerdicts(ctx, quietIDs)
for _, k := range quiet {
k.StallState = verdicts[k.ID]
}
}
func isParseInFlight(status string) bool {
switch status {
case types.ParseStatusPending, types.ParseStatusProcessing, types.ParseStatusFinalizing:
return true
}
return false
}
func latestActivity(times ...time.Time) time.Time {
var last time.Time
for _, t := range times {
if t.After(last) {
last = t
}
}
return last
}
// UpdateKnowledgeRequest defines the partial-update body for PUT /knowledge/:id.
// Omitted fields are left unchanged; an explicit empty description clears the summary.
type UpdateKnowledgeRequest struct {

View File

@ -0,0 +1,134 @@
package handler
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type lastActivitySpanRepo struct {
repository.KnowledgeSpanRepository
activity map[string]time.Time
err error
asked []string
}
func (r *lastActivitySpanRepo) LastActivity(_ context.Context, ids []string) (map[string]time.Time, error) {
r.asked = ids
return r.activity, r.err
}
// Only in-flight rows get last_activity_at, and a span write newer than the
// row's updated_at wins.
func TestAttachLastActivity(t *testing.T) {
base := time.Date(2026, 9, 22, 10, 0, 0, 0, time.UTC)
spans := &lastActivitySpanRepo{activity: map[string]time.Time{
"processing": base.Add(10 * time.Minute),
"finalizing": base.Add(-time.Hour),
}}
h := &KnowledgeHandler{spanRepo: spans}
rows := []*types.Knowledge{
{ID: "processing", ParseStatus: types.ParseStatusProcessing, UpdatedAt: base},
{ID: "finalizing", ParseStatus: types.ParseStatusFinalizing, UpdatedAt: base},
{ID: "pending", ParseStatus: types.ParseStatusPending, UpdatedAt: base},
{ID: "completed", ParseStatus: types.ParseStatusCompleted, UpdatedAt: base},
nil,
}
h.attachLastActivity(context.Background(), rows)
assert.Equal(t, []string{"processing", "finalizing", "pending"}, spans.asked)
require.NotNil(t, rows[0].LastActivityAt)
assert.Equal(t, base.Add(10*time.Minute), *rows[0].LastActivityAt)
require.NotNil(t, rows[1].LastActivityAt)
assert.Equal(t, base, *rows[1].LastActivityAt)
require.NotNil(t, rows[2].LastActivityAt)
assert.Equal(t, base, *rows[2].LastActivityAt)
assert.Nil(t, rows[3].LastActivityAt)
}
// A failed span lookup still reports the row's own updated_at.
func TestAttachLastActivityFallsBackToUpdatedAt(t *testing.T) {
base := time.Date(2026, 9, 22, 10, 0, 0, 0, time.UTC)
h := &KnowledgeHandler{spanRepo: &lastActivitySpanRepo{err: errors.New("db down")}}
rows := []*types.Knowledge{{ID: "k", ParseStatus: types.ParseStatusProcessing, UpdatedAt: base}}
h.attachLastActivity(context.Background(), rows)
require.NotNil(t, rows[0].LastActivityAt)
assert.Equal(t, base, *rows[0].LastActivityAt)
}
func TestSpansLastActivity(t *testing.T) {
base := time.Date(2026, 9, 22, 10, 0, 0, 0, time.UTC)
rows := []types.KnowledgeProcessingSpan{
{UpdatedAt: base.Add(-time.Minute)},
{UpdatedAt: base.Add(5 * time.Minute)},
}
assert.Equal(t, base.Add(5*time.Minute), spansLastActivity(base, rows))
assert.Equal(t, base, spansLastActivity(base, nil))
}
type fakeBacklog struct {
queued map[string]bool
err error
asked []string
}
func (f *fakeBacklog) QueuedWork(_ context.Context, ids []string) (map[string]bool, error) {
f.asked = append(f.asked, ids...)
if f.err != nil {
return nil, f.err
}
out := make(map[string]bool, len(ids))
for _, id := range ids {
out[id] = f.queued[id]
}
return out, nil
}
// Every row quiet past the stall hint gets a verdict, however many there
// are; rows still progressing are not probed.
func TestAttachLastActivityGivesEveryQuietRowAVerdict(t *testing.T) {
now := time.Now()
backlog := &fakeBacklog{queued: map[string]bool{"quiet-0": true}}
h := &KnowledgeHandler{spanRepo: &lastActivitySpanRepo{}, backlog: backlog}
rows := []*types.Knowledge{{ID: "recent", ParseStatus: types.ParseStatusProcessing, UpdatedAt: now}}
for i := 0; i < 40; i++ {
rows = append(rows, &types.Knowledge{
ID: fmt.Sprintf("quiet-%d", i), ParseStatus: types.ParseStatusProcessing, UpdatedAt: now.Add(-time.Hour),
})
}
h.attachLastActivity(context.Background(), rows)
assert.Len(t, backlog.asked, 40)
assert.Empty(t, rows[0].StallState)
assert.Equal(t, types.StallStateQueued, rows[1].StallState)
for _, k := range rows[2:] {
assert.Equal(t, types.StallStateStalled, k.StallState, k.ID)
}
}
// A failed probe leaves the verdict unknown instead of calling rows stuck.
func TestAttachLastActivityLeavesVerdictUnknownWhenProbeFails(t *testing.T) {
h := &KnowledgeHandler{
spanRepo: &lastActivitySpanRepo{},
backlog: &fakeBacklog{err: errors.New("redis down")},
}
rows := []*types.Knowledge{
{ID: "quiet", ParseStatus: types.ParseStatusProcessing, UpdatedAt: time.Now().Add(-time.Hour)},
}
h.attachLastActivity(context.Background(), rows)
require.NotNil(t, rows[0].LastActivityAt)
assert.Empty(t, rows[0].StallState)
}

View File

@ -269,3 +269,50 @@ func TestBuildSpanTree_DocReaderFailureCancelsEverythingAfter(t *testing.T) {
}
a.NotContains(got, types.SpanStatusSkipped)
}
// Post-process closes its stage once the enrichment tasks are fanned out, so
// the stage owning a still-running subspan is the current one.
func TestBuildSpanTree_CurrentStageFallsBackToRunningSubspan(t *testing.T) {
rows := []types.KnowledgeProcessingSpan{
{SpanID: "root", Name: "knowledge_processing", Kind: types.SpanKindRoot, Status: types.SpanStatusDone},
{
SpanID: "post", ParentSpanID: "root", Name: types.StagePostProcess,
Kind: types.SpanKindStage, Status: types.SpanStatusDone,
},
{
SpanID: "wiki", ParentSpanID: "post", Name: "postprocess.wiki",
Kind: types.SpanKindSubSpan, Status: types.SpanStatusRunning,
},
{
SpanID: "page", ParentSpanID: "wiki", Name: "postprocess.wiki.page[a]",
Kind: types.SpanKindSubSpan, Status: types.SpanStatusRunning,
},
}
_, currentStage, _ := buildSpanTree("kid", 1, rows, types.ParseStatusFinalizing)
assert.Equal(t, types.StagePostProcess, currentStage)
}
// A later subtask failure must not hide the stage housekeeping marked stalled.
func TestBuildSpanTree_StallFailureWinsOverLaterFailures(t *testing.T) {
rows := []types.KnowledgeProcessingSpan{
{SpanID: "root", Name: "knowledge_processing", Kind: types.SpanKindRoot, Status: types.SpanStatusRunning},
{
SpanID: "mm", ParentSpanID: "root", Name: types.StageMultimodal, Kind: types.SpanKindStage,
Status: types.SpanStatusFailed, ErrorCode: "TASK_STALLED",
},
{
SpanID: "img0", ParentSpanID: "mm", Name: "multimodal.image[0]", Kind: types.SpanKindGeneration,
Status: types.SpanStatusFailed, ErrorCode: "MULTIMODAL_VLM_FAILED",
},
}
_, _, lastFailure := buildSpanTree("kid", 1, rows, types.ParseStatusFailed)
if assert.NotNil(t, lastFailure) {
assert.Equal(t, "mm", lastFailure.SpanID)
}
rows[1].ErrorCode = "UNKNOWN"
_, _, lastFailure = buildSpanTree("kid", 1, rows, types.ParseStatusFailed)
if assert.NotNil(t, lastFailure) {
assert.Equal(t, "img0", lastFailure.SpanID, "without a stall, the latest failure still wins")
}
}

View File

@ -66,6 +66,11 @@ func (runtimeTestInspector) HasQueuedDeleteTasksForKnowledge(context.Context, st
func (runtimeTestInspector) HasQueuedTasksForKnowledge(context.Context, string) (bool, error) {
return false, nil
}
func (runtimeTestInspector) QueuedKnowledgeIDs(context.Context) (map[string]struct{}, error) {
return map[string]struct{}{}, nil
}
func (runtimeTestInspector) QueueStats(context.Context) ([]types.QueueStat, bool, error) {
return []types.QueueStat{}, true, nil
}

View File

@ -205,6 +205,41 @@ func (a *asynqTaskInspector) HasQueuedTasksForKnowledge(
return false, nil
}
// QueuedKnowledgeIDs scans every cancellable state of every queue once and
// collects the knowledge IDs its tasks reference.
func (a *asynqTaskInspector) QueuedKnowledgeIDs(_ context.Context) (map[string]struct{}, error) {
out := make(map[string]struct{})
if a == nil || a.inspector == nil {
return out, nil
}
for _, queue := range queuesScanned {
for _, state := range a.cancellableTaskStates() {
for page := 1; ; page++ {
tasks, err := state.list(queue, asynq.PageSize(listPageSize), asynq.Page(page))
if err != nil {
if isAsynqQueueNotFound(err) {
break
}
return nil, fmt.Errorf("list %s tasks in queue %s: %w", state.name, queue, err)
}
for _, task := range tasks {
if _, ok := taskTypesForKnowledgeCancel[task.Type]; !ok {
continue
}
var probe knowledgeIDProbe
if json.Unmarshal(task.Payload, &probe) == nil && probe.KnowledgeID != "" {
out[probe.KnowledgeID] = struct{}{}
}
}
if len(tasks) < listPageSize {
break
}
}
}
}
return out, nil
}
// HasQueuedDeleteTasksForKnowledge is the delete-task counterpart of
// HasQueuedTasksForKnowledge: it matches knowledge:list_delete batch
// payloads that still cover the knowledge ID. The housekeeping delete
@ -1126,6 +1161,11 @@ func (noopTaskInspector) HasQueuedTasksForKnowledge(
return false, nil
}
// QueuedKnowledgeIDs is empty in Lite mode: inline executors never queue.
func (noopTaskInspector) QueuedKnowledgeIDs(context.Context) (map[string]struct{}, error) {
return map[string]struct{}{}, nil
}
// HasQueuedDeleteTasksForKnowledge always reports false in Lite mode:
// deletes also run inline there, so a stale "deleting" row genuinely has
// no task left and the delete sweep may recover it.

View File

@ -0,0 +1,62 @@
package router
import (
"context"
"fmt"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/alicebob/miniredis/v2"
"github.com/hibiken/asynq"
"github.com/redis/go-redis/v9"
)
// One pass collects every knowledge a cancellable task references, across
// pages and states, and skips task types that are not per-knowledge.
func TestQueuedKnowledgeIDsCollectsAcrossPagesAndStates(t *testing.T) {
server := miniredis.RunT(t)
redisClient := redis.NewClient(&redis.Options{Addr: server.Addr()})
asynqClient := asynq.NewClientFromRedisClient(redisClient)
t.Cleanup(func() {
_ = asynqClient.Close()
_ = redisClient.Close()
})
inspector := &asynqTaskInspector{inspector: asynq.NewInspectorFromRedisClient(redisClient), redis: redisClient}
const pending = listPageSize + 5
for i := 0; i < pending; i++ {
enqueueTask(t, asynqClient, types.TypeDocumentProcess,
fmt.Sprintf(`{"knowledge_id":"k-%d"}`, i), fmt.Sprintf("doc-%03d", i))
}
scheduleTask(t, asynqClient, types.TypeKnowledgePostProcess, `{"knowledge_id":"k-scheduled"}`, "post")
enqueueTask(t, asynqClient, types.TypeKBClone, `{"knowledge_id":"k-kb-level"}`, "clone")
ids, err := inspector.QueuedKnowledgeIDs(context.Background())
if err != nil {
t.Fatalf("QueuedKnowledgeIDs: %v", err)
}
if len(ids) != pending+1 {
t.Fatalf("got %d ids, want %d", len(ids), pending+1)
}
for _, id := range []string{"k-0", fmt.Sprintf("k-%d", pending-1), "k-scheduled"} {
if _, ok := ids[id]; !ok {
t.Fatalf("missing %s", id)
}
}
if _, ok := ids["k-kb-level"]; ok {
t.Fatal("KB-level task types must not count")
}
}
// A Redis failure is an error, not an empty queue.
func TestQueuedKnowledgeIDsReportsBackendErrors(t *testing.T) {
server := miniredis.RunT(t)
redisClient := redis.NewClient(&redis.Options{Addr: server.Addr()})
t.Cleanup(func() { _ = redisClient.Close() })
inspector := &asynqTaskInspector{inspector: asynq.NewInspectorFromRedisClient(redisClient), redis: redisClient}
server.Close()
if _, err := inspector.QueuedKnowledgeIDs(context.Background()); err == nil {
t.Fatal("expected an error when Redis is down")
}
}

View File

@ -44,6 +44,14 @@ type TaskInspector interface {
// span/updated_at checks remain authoritative there.
HasQueuedTasksForKnowledge(ctx context.Context, knowledgeID string) (bool, error)
// QueuedKnowledgeIDs returns every knowledge ID that a pending /
// scheduled / retry / active task of those same types references, in
// one pass over the queues — for answering many documents at once
// where HasQueuedTasksForKnowledge would rescan per document. Unlike
// that probe it returns list errors instead of reading them as "no
// match". Lite mode returns an empty set.
QueuedKnowledgeIDs(ctx context.Context) (map[string]struct{}, error)
// HasQueuedDeleteTasksForKnowledge reports whether any pending /
// scheduled / retry / active knowledge:list_delete task still covers
// the given knowledge ID. The delete sweep calls it before recovering

View File

@ -198,8 +198,21 @@ type Knowledge struct {
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
// Knowledge base name (not stored in database, populated on query)
KnowledgeBaseName string `json:"knowledge_base_name" gorm:"-"`
// Most recent processing progress (row or span write) for an in-flight
// row, so clients can tell a slow stage from a stalled one. Not stored.
LastActivityAt *time.Time `json:"last_activity_at,omitempty" gorm:"-"`
// Verdict on an in-flight row gone quiet: StallStateQueued (its work is
// still queued, i.e. backlogged) or StallStateStalled (nothing left to
// run it). Empty while it is progressing or the probe failed. Not stored.
StallState string `json:"stall_state,omitempty" gorm:"-"`
}
// Stall verdicts for Knowledge.StallState.
const (
StallStateQueued = "queued"
StallStateStalled = "stalled"
)
// CustomMetadataText returns stable human-readable metadata for summaries and
// document-scoped model context. Internal ingestion metadata is intentionally
// excluded.

View File

@ -447,15 +447,16 @@ stateDiagram-v2
2. `filterByLastSpanActivity`:查 `knowledge_processing_spans` 的 `MAX(updated_at)` 心跳,心跳仍在阈值内的保留(仍在处理),无任何 span 的也判为卡死;
3. `filterOutQueued`:通过 asynq TaskInspector 检查是否仍有排队任务,有则保留(只是在排队)。
判定卡死的知识被更新为:
判定卡死的知识逐行更新为 `parse_status = 'failed'`、`pending_subtasks_count = 0`,`error_message` 写明停在哪个阶段、最后一次进展时间,例如:
```sql
UPDATE knowledge SET parse_status = 'failed',
error_message = 'task stuck in processing > [threshold], recovered by housekeeping',
pending_subtasks_count = 0
WHERE id IN (stuck_ids)
```text
task stuck in processing at docreader stage: no progress since 2026-09-22T09:37:54Z (> 2h10m0s), recovered by housekeeping
```
同时关闭该知识最新一次 attempt 中仍处于 `pending`/`running` 的 span,错误码均为 `TASK_STALLED`,并补写 `duration_ms`:卡住的位置标为 `failed`,其余标为 `cancelled`。卡住的位置是正在运行的阶段 span;没有运行中的阶段时(`finalizing` 下后处理阶段已关闭),是最内层仍在运行的子 span,文案会带上它们的名字,如 `at postprocess stage (postprocess.summary)`。span 心跳查询失败时文案不写时间点。这样时间线上会显示卡在哪里,而不是一直转圈。
前端在服务端判死之前会先给出提示:批量查询与 spans 接口为进行中的知识返回 `last_activity_at`;超过 20 分钟无进展时再返回服务端的判定 `stall_state`(与 Sweep A 的积压判定相同)。`stalled` 在列表、卡片和时间线上显示“疑似卡住”,时间线提供“停止解析”入口;`queued` 显示“排队中”,不提供停止入口;探测失败时没有判定,按普通解析中显示。安静期间轮询间隔放宽到 15 秒。
阈值 `staleThreshold() = max(1h, DocumentProcessTimeout) + 10min`。
**Sweep B —— 摘要卡死恢复**:`summary_status = 'processing' AND updated_at < 1 小时前` → 置 `failed`。

View File

@ -346,7 +346,7 @@ curl -X DELETE $BASE/api/v1/knowledge-bases/kb-1/knowledge -H "Authorization: Be
| `agent_id` | string | 否 | 共享 Agent 范围 |
| `agent_source_tenant_id` | uint64 | 否 | 共享 Agent 的来源空间选择器,与共享关系校验 |
响应:200 `{"success":true,"data":[Knowledge]}`
响应:200 `{"success":true,"data":[Knowledge]}`。处于 `pending`/`processing`/`finalizing` 的知识额外带 `last_activity_at`(RFC3339),取行的 `updated_at` 与该知识所有 span 最近一次写入中较晚的一个。超过 20 分钟无进展的知识再带 `stall_state`:`queued` 表示仍有任务在 asynq 队列或 Wiki 持久队列中等待(积压),`stalled` 表示已无任务可推进它(疑似卡住)。判定与 housekeeping 的积压判定相同;队列侧是一次全队列扫描,所有请求共享、缓存 60 秒。探测失败时不返回 `stall_state`,前端按普通解析中显示。
```bash
curl "$BASE/api/v1/knowledge/batch?ids=k-1&ids=k-2" -H "Authorization: Bearer $TOKEN"
@ -366,7 +366,9 @@ curl $BASE/api/v1/knowledge/k-1 -H "Authorization: Bearer $TOKEN"
用途:解析阶段/trace(两条路径同一 handler `GetKnowledgeSpans`)。权限:Viewer+,父 KB read。查询参数:`attempt`(int,0=最新一次)。
响应:200 `{"success":true,"data":{"knowledge_id","attempt","latest_attempt","parse_status","current_stage","trace":{...},"last_error":{...}}}`
响应:200 `{"success":true,"data":{"knowledge_id","attempt","latest_attempt","parse_status","current_stage","last_activity_at","stall_state","trace":{...},"last_error":{...}}}`
`last_activity_at` 只在解析进行中返回,取行的 `updated_at` 与本次 attempt 各 span 最近一次写入中较晚的一个;`stall_state` 含义同上。`current_stage` 是仍在运行的阶段;没有运行中的阶段时(如 `finalizing`,后处理阶段已关闭、摘要等子任务仍在跑),取仍在运行的子 span 所属的阶段。被 housekeeping 判定卡死的知识,其卡住位置的 span 会以 `TASK_STALLED` 标为失败,`last_error` 优先指向它。
```bash
curl $BASE/api/v1/knowledge/k-1/spans -H "Authorization: Bearer $TOKEN"