WeKnora/internal/handler/knowledge_spans_test.go

272 lines
12 KiB
Go
Raw Normal View History

test(knowledge): add coverage and protect housekeeping from false-killing long stages Addresses three review concerns from the prior PR: 1. No tests existed for any of the stuck-parsing fixes (PR① / PR②.5). This commit adds coverage for the four most regression-prone surfaces: span repo upsert/cascade/attempt isolation, span tracker cascade-cancel and cross-process LookupStage, housekeeping false-kill protection, and handler tree assembly. 2. Housekeeping was using only knowledge.updated_at as its staleness signal, but knowledge.updated_at advances only at parse_status transitions — a long DocReader call (or large embedding batch) can run for an hour with no updated_at change, so a tight DocumentProcessTimeout setting would falsely flip an actively running parse to "failed". The sweep now does a two-stage check: candidates by knowledge updated_at, then filtered by MAX(spans.updated_at). Every SpanTracker Begin/End/Fail/Skip now also pokes knowledge.updated_at as a side-channel heartbeat, so the filter sees recent activity even when no parse_status transition has fired. 3. parseHeartbeatTime accepts the timestamp formats both Postgres and SQLite emit for an aggregated MAX() column (the SQLite driver doesn't auto-cast aggregates to time.Time the way Postgres does), so the same code path works in Lite mode. The new TestHousekeeping_NoFalseKill_ActiveSpan is the regression test for the user-flagged scenario: a 3-hour-stale knowledge.updated_at combined with a 2-minute-fresh span row must NOT be killed.
2026-05-27 07:01:54 +00:00
package handler
import (
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
)
// TestBuildSpanTree_AssemblesParentChild covers the basic shape: a root
// with stage children and an image generation grandchild. The handler's
// JSON contract depends on this tree topology; if the linking logic
// regresses, the UI sees a flat list and renders nothing.
func TestBuildSpanTree_AssemblesParentChild(t *testing.T) {
now := time.Now()
rows := []types.KnowledgeProcessingSpan{
{KnowledgeID: "kid", Attempt: 1, SpanID: "root", Name: "knowledge_processing", Kind: types.SpanKindRoot, Status: types.SpanStatusRunning, StartedAt: &now},
{KnowledgeID: "kid", Attempt: 1, SpanID: "doc", ParentSpanID: "root", Name: types.StageDocReader, Kind: types.SpanKindStage, Status: types.SpanStatusDone, StartedAt: &now},
{KnowledgeID: "kid", Attempt: 1, SpanID: "mm", ParentSpanID: "root", Name: types.StageMultimodal, Kind: types.SpanKindStage, Status: types.SpanStatusRunning, StartedAt: &now},
{KnowledgeID: "kid", Attempt: 1, SpanID: "img0", ParentSpanID: "mm", Name: "multimodal.image[0]", Kind: types.SpanKindGeneration, Status: types.SpanStatusRunning, StartedAt: &now},
}
tree, currentStage, lastFail := buildSpanTree("kid", 1, rows, types.ParseStatusProcessing)
test(knowledge): add coverage and protect housekeeping from false-killing long stages Addresses three review concerns from the prior PR: 1. No tests existed for any of the stuck-parsing fixes (PR① / PR②.5). This commit adds coverage for the four most regression-prone surfaces: span repo upsert/cascade/attempt isolation, span tracker cascade-cancel and cross-process LookupStage, housekeeping false-kill protection, and handler tree assembly. 2. Housekeeping was using only knowledge.updated_at as its staleness signal, but knowledge.updated_at advances only at parse_status transitions — a long DocReader call (or large embedding batch) can run for an hour with no updated_at change, so a tight DocumentProcessTimeout setting would falsely flip an actively running parse to "failed". The sweep now does a two-stage check: candidates by knowledge updated_at, then filtered by MAX(spans.updated_at). Every SpanTracker Begin/End/Fail/Skip now also pokes knowledge.updated_at as a side-channel heartbeat, so the filter sees recent activity even when no parse_status transition has fired. 3. parseHeartbeatTime accepts the timestamp formats both Postgres and SQLite emit for an aggregated MAX() column (the SQLite driver doesn't auto-cast aggregates to time.Time the way Postgres does), so the same code path works in Lite mode. The new TestHousekeeping_NoFalseKill_ActiveSpan is the regression test for the user-flagged scenario: a 3-hour-stale knowledge.updated_at combined with a 2-minute-fresh span row must NOT be killed.
2026-05-27 07:01:54 +00:00
require := assert.New(t)
require.NotNil(tree)
require.Equal("root", tree.SpanID)
require.Equal(types.StageMultimodal, currentStage,
"running stage span surfaces as current_stage")
require.Nil(lastFail)
// The 5 canonical stages must all appear under root (real or
// synthesized placeholder).
stageNames := map[string]string{}
for _, child := range tree.Children {
if child.Kind == types.SpanKindStage {
stageNames[child.Name] = child.Status
}
}
for _, name := range types.AllStages {
_, ok := stageNames[name]
require.True(ok, "stage %s must appear in tree", name)
}
require.Equal(types.SpanStatusDone, stageNames[types.StageDocReader])
require.Equal(types.SpanStatusRunning, stageNames[types.StageMultimodal])
require.Equal(types.SpanStatusPending, stageNames[types.StageEmbedding],
"missing stage rows must synthesize as pending placeholders")
// The image subspan must hang under multimodal, not at root level.
var mmNode *types.SpanTreeNode
for _, c := range tree.Children {
if c.Name == types.StageMultimodal {
mmNode = c
break
}
}
require.NotNil(mmNode)
require.Len(mmNode.Children, 1, "image generation subspan must be a child of multimodal stage")
require.Equal("multimodal.image[0]", mmNode.Children[0].Name)
}
// TestBuildSpanTree_NoRows_SynthesizesPlaceholderRoot ensures the API
// keeps a stable shape for fresh / never-parsed knowledge: the frontend
// always gets a `trace` with five pending stage children, never a
// nil/empty response.
func TestBuildSpanTree_NoRows_SynthesizesPlaceholderRoot(t *testing.T) {
tree, currentStage, lastFail := buildSpanTree("kid-empty", 0, nil, "")
test(knowledge): add coverage and protect housekeeping from false-killing long stages Addresses three review concerns from the prior PR: 1. No tests existed for any of the stuck-parsing fixes (PR① / PR②.5). This commit adds coverage for the four most regression-prone surfaces: span repo upsert/cascade/attempt isolation, span tracker cascade-cancel and cross-process LookupStage, housekeeping false-kill protection, and handler tree assembly. 2. Housekeeping was using only knowledge.updated_at as its staleness signal, but knowledge.updated_at advances only at parse_status transitions — a long DocReader call (or large embedding batch) can run for an hour with no updated_at change, so a tight DocumentProcessTimeout setting would falsely flip an actively running parse to "failed". The sweep now does a two-stage check: candidates by knowledge updated_at, then filtered by MAX(spans.updated_at). Every SpanTracker Begin/End/Fail/Skip now also pokes knowledge.updated_at as a side-channel heartbeat, so the filter sees recent activity even when no parse_status transition has fired. 3. parseHeartbeatTime accepts the timestamp formats both Postgres and SQLite emit for an aggregated MAX() column (the SQLite driver doesn't auto-cast aggregates to time.Time the way Postgres does), so the same code path works in Lite mode. The new TestHousekeeping_NoFalseKill_ActiveSpan is the regression test for the user-flagged scenario: a 3-hour-stale knowledge.updated_at combined with a 2-minute-fresh span row must NOT be killed.
2026-05-27 07:01:54 +00:00
a := assert.New(t)
a.NotNil(tree)
a.Equal(types.SpanKindRoot, tree.Kind)
a.Equal(types.SpanStatusPending, tree.Status)
a.Equal("", currentStage, "no rows means no running stage")
a.Nil(lastFail)
// All 5 stages must be present as pending placeholders so the UI
// renders a complete timeline even pre-parse.
a.Len(tree.Children, len(types.AllStages))
for _, child := range tree.Children {
a.Equal(types.SpanStatusPending, child.Status)
a.Equal(types.SpanKindStage, child.Kind)
}
}
// TestBuildSpanTree_LegacyCompletedRendersAsDone records the regression
// for historical knowledge parsed before span tracking was wired: rows
// is empty but parse_status is "completed", so the synthesized timeline
// must reflect the actual terminal state instead of looking forever
// "pending". Same contract for failed parses — synthesizes "failed".
func TestBuildSpanTree_LegacyCompletedRendersAsDone(t *testing.T) {
a := assert.New(t)
completedTree, _, _ := buildSpanTree("kid-legacy", 0, nil, types.ParseStatusCompleted)
a.Equal(types.SpanStatusDone, completedTree.Status,
"legacy completed knowledge with no rows must render the synthesized root as done")
a.Len(completedTree.Children, len(types.AllStages))
for _, child := range completedTree.Children {
a.Equal(types.SpanStatusDone, child.Status,
"legacy completed knowledge: every synthesized stage placeholder must be done, not pending")
}
failedTree, _, _ := buildSpanTree("kid-legacy-fail", 0, nil, types.ParseStatusFailed)
a.Equal(types.SpanStatusFailed, failedTree.Status)
for _, child := range failedTree.Children {
a.Equal(types.SpanStatusFailed, child.Status)
}
}
test(knowledge): add coverage and protect housekeeping from false-killing long stages Addresses three review concerns from the prior PR: 1. No tests existed for any of the stuck-parsing fixes (PR① / PR②.5). This commit adds coverage for the four most regression-prone surfaces: span repo upsert/cascade/attempt isolation, span tracker cascade-cancel and cross-process LookupStage, housekeeping false-kill protection, and handler tree assembly. 2. Housekeeping was using only knowledge.updated_at as its staleness signal, but knowledge.updated_at advances only at parse_status transitions — a long DocReader call (or large embedding batch) can run for an hour with no updated_at change, so a tight DocumentProcessTimeout setting would falsely flip an actively running parse to "failed". The sweep now does a two-stage check: candidates by knowledge updated_at, then filtered by MAX(spans.updated_at). Every SpanTracker Begin/End/Fail/Skip now also pokes knowledge.updated_at as a side-channel heartbeat, so the filter sees recent activity even when no parse_status transition has fired. 3. parseHeartbeatTime accepts the timestamp formats both Postgres and SQLite emit for an aggregated MAX() column (the SQLite driver doesn't auto-cast aggregates to time.Time the way Postgres does), so the same code path works in Lite mode. The new TestHousekeeping_NoFalseKill_ActiveSpan is the regression test for the user-flagged scenario: a 3-hour-stale knowledge.updated_at combined with a 2-minute-fresh span row must NOT be killed.
2026-05-27 07:01:54 +00:00
// TestBuildSpanTree_LastFailureSurfaces records that a failed stage is
// reported as last_error so the UI can highlight the responsible step
// even if a later stage was cancelled by cascade.
func TestBuildSpanTree_LastFailureSurfaces(t *testing.T) {
now := time.Now()
finished := now.Add(5 * time.Second)
rows := []types.KnowledgeProcessingSpan{
{KnowledgeID: "kid", Attempt: 1, SpanID: "root", Name: "knowledge_processing", Kind: types.SpanKindRoot, Status: types.SpanStatusFailed, StartedAt: &now, FinishedAt: &finished},
{KnowledgeID: "kid", Attempt: 1, SpanID: "doc", ParentSpanID: "root", Name: types.StageDocReader, Kind: types.SpanKindStage, Status: types.SpanStatusFailed, ErrorCode: "DOCREADER_TIMEOUT", ErrorMessage: "slow", StartedAt: &now, FinishedAt: &finished},
{KnowledgeID: "kid", Attempt: 1, SpanID: "chunk", ParentSpanID: "root", Name: types.StageChunking, Kind: types.SpanKindStage, Status: types.SpanStatusCancelled, ErrorCode: "UPSTREAM_FAILED"},
}
_, _, lastFail := buildSpanTree("kid", 1, rows, types.ParseStatusFailed)
test(knowledge): add coverage and protect housekeeping from false-killing long stages Addresses three review concerns from the prior PR: 1. No tests existed for any of the stuck-parsing fixes (PR① / PR②.5). This commit adds coverage for the four most regression-prone surfaces: span repo upsert/cascade/attempt isolation, span tracker cascade-cancel and cross-process LookupStage, housekeeping false-kill protection, and handler tree assembly. 2. Housekeeping was using only knowledge.updated_at as its staleness signal, but knowledge.updated_at advances only at parse_status transitions — a long DocReader call (or large embedding batch) can run for an hour with no updated_at change, so a tight DocumentProcessTimeout setting would falsely flip an actively running parse to "failed". The sweep now does a two-stage check: candidates by knowledge updated_at, then filtered by MAX(spans.updated_at). Every SpanTracker Begin/End/Fail/Skip now also pokes knowledge.updated_at as a side-channel heartbeat, so the filter sees recent activity even when no parse_status transition has fired. 3. parseHeartbeatTime accepts the timestamp formats both Postgres and SQLite emit for an aggregated MAX() column (the SQLite driver doesn't auto-cast aggregates to time.Time the way Postgres does), so the same code path works in Lite mode. The new TestHousekeeping_NoFalseKill_ActiveSpan is the regression test for the user-flagged scenario: a 3-hour-stale knowledge.updated_at combined with a 2-minute-fresh span row must NOT be killed.
2026-05-27 07:01:54 +00:00
a := assert.New(t)
a.NotNil(lastFail)
a.Equal(types.StageDocReader, lastFail.Name,
"last_error must point at the actually-failed span, not the cascade-cancelled downstream")
a.Equal("DOCREADER_TIMEOUT", lastFail.ErrorCode)
}
func TestKnowledgeSpansLastError_PrefersSpanFailure(t *testing.T) {
now := time.Now()
spanFail := &types.KnowledgeProcessingSpan{
Name: types.StageDocReader,
ErrorCode: "DOCREADER_TIMEOUT",
ErrorMessage: "slow",
FinishedAt: &now,
}
got := knowledgeSpansLastError(2, 2, types.ParseStatusFailed, "recovery blew up", now, spanFail)
a := assert.New(t)
a.Equal(types.StageDocReader, got["name"])
a.Equal("DOCREADER_TIMEOUT", got["error_code"])
a.Equal("slow", got["error_message"])
}
func TestKnowledgeSpansLastError_RecoveryFallbackUsesKnowledgeMessage(t *testing.T) {
now := time.Now()
got := knowledgeSpansLastError(2, 2, types.ParseStatusFailed, "wiki ingest timed out", now, nil)
a := assert.New(t)
a.NotNil(got)
a.Equal("knowledge_processing", got["name"])
a.Equal("UNKNOWN", got["error_code"])
a.Equal("wiki ingest timed out", got["error_message"])
a.Equal(now, got["finished_at"])
}
func TestKnowledgeSpansLastError_ClassifiesServerRestart(t *testing.T) {
now := time.Now()
got := knowledgeSpansLastError(2, 2, types.ParseStatusFailed,
"Task interrupted due to application restart", now, nil)
a := assert.New(t)
a.NotNil(got)
a.Equal("SERVER_RESTART", got["error_code"])
a.Equal("SERVER_RESTART", got["code"])
}
func TestKnowledgeSpansLastError_SkipsRecoveryFallbackForHistoricalAttempt(t *testing.T) {
now := time.Now()
got := knowledgeSpansLastError(1, 2, types.ParseStatusFailed, "wiki ingest timed out", now, nil)
assert.Nil(t, got)
}
func TestKnowledgeSpansLastError_SkipsRecoveryFallbackWithoutMessage(t *testing.T) {
now := time.Now()
got := knowledgeSpansLastError(2, 2, types.ParseStatusFailed, "", now, nil)
assert.Nil(t, got)
}
fix(knowledge): stop synthesizing never-run stages as failed Closes #3452. buildSpanTree fills every canonical stage that has no span row using a status inferred from knowledge.parse_status, so a failed parse painted all of them "failed". That status carries information it cannot know: it cannot tell "this stage ran and failed" from "this stage never ran". The frontend picks the focused stage with the first failed one in canonical order, so whenever the real failure left an earlier stage rowless, the UI named the earlier stage. On main today a text passage is chunked without ever opening a docreader stage, so an embedding failure reports 文档解析 / docreader as the broken step for content that has no document to parse, and four of five segments render as failures. Once a stage has actually recorded a failure its position is known, so missing stages are now resolved against it: - downstream of the failure, per StageDependencies or canonical order → cancelled, which is what the status is documented to mean - before it → skipped; the stage either did not apply or its row was never written, and neither of those is a failure With no failed row anywhere the parse_status fallback stands unchanged, which is the case it was written for: legacy knowledge parsed before span tracking existed still renders done/failed rather than five pending segments. Also maps parse_status "cancelled" to a cancelled placeholder; it fell through the switch to pending, so a cancelled document showed spinners on the stages it never reached. The DAG walk is redundant with canonical order for today's stage list, where every dependency points at an earlier stage. It is there so the answer stays right if the list is reordered or a stage gains an upstream that is not its predecessor. No frontend change: skipped and cancelled already render, with localized labels in every locale.
2026-09-20 06:10:52 +00:00
// stageStatuses maps each canonical stage to the status it renders as.
func stageStatuses(t *testing.T, tree *types.SpanTreeNode) map[string]string {
t.Helper()
got := map[string]string{}
for _, child := range tree.Children {
if child.Kind == types.SpanKindStage {
got[child.Name] = child.Status
}
}
return got
}
// #3452: a text passage has no docreader stage, so an embedding failure used to
// synthesize docreader as failed and the UI named it as the broken step.
fix(knowledge): stop synthesizing never-run stages as failed Closes #3452. buildSpanTree fills every canonical stage that has no span row using a status inferred from knowledge.parse_status, so a failed parse painted all of them "failed". That status carries information it cannot know: it cannot tell "this stage ran and failed" from "this stage never ran". The frontend picks the focused stage with the first failed one in canonical order, so whenever the real failure left an earlier stage rowless, the UI named the earlier stage. On main today a text passage is chunked without ever opening a docreader stage, so an embedding failure reports 文档解析 / docreader as the broken step for content that has no document to parse, and four of five segments render as failures. Once a stage has actually recorded a failure its position is known, so missing stages are now resolved against it: - downstream of the failure, per StageDependencies or canonical order → cancelled, which is what the status is documented to mean - before it → skipped; the stage either did not apply or its row was never written, and neither of those is a failure With no failed row anywhere the parse_status fallback stands unchanged, which is the case it was written for: legacy knowledge parsed before span tracking existed still renders done/failed rather than five pending segments. Also maps parse_status "cancelled" to a cancelled placeholder; it fell through the switch to pending, so a cancelled document showed spinners on the stages it never reached. The DAG walk is redundant with canonical order for today's stage list, where every dependency points at an earlier stage. It is there so the answer stays right if the list is reordered or a stage gains an upstream that is not its predecessor. No frontend change: skipped and cancelled already render, with localized labels in every locale.
2026-09-20 06:10:52 +00:00
func TestBuildSpanTree_MissingStagesAroundRealFailure(t *testing.T) {
now := time.Now()
finished := now.Add(2 * time.Second)
rows := []types.KnowledgeProcessingSpan{
{KnowledgeID: "kid", Attempt: 1, SpanID: "root", Name: "knowledge_processing", Kind: types.SpanKindRoot, Status: types.SpanStatusFailed, StartedAt: &now, FinishedAt: &finished},
{KnowledgeID: "kid", Attempt: 1, SpanID: "chunk", ParentSpanID: "root", Name: types.StageChunking, Kind: types.SpanKindStage, Status: types.SpanStatusDone, StartedAt: &now, FinishedAt: &finished},
{KnowledgeID: "kid", Attempt: 1, SpanID: "emb", ParentSpanID: "root", Name: types.StageEmbedding, Kind: types.SpanKindStage, Status: types.SpanStatusFailed, ErrorCode: "EMBED_UNREACHABLE", StartedAt: &now, FinishedAt: &finished},
}
tree, _, lastFail := buildSpanTree("kid", 1, rows, types.ParseStatusFailed)
a := assert.New(t)
got := stageStatuses(t, tree)
a.Equal(types.SpanStatusFailed, got[types.StageEmbedding],
"the stage that actually failed keeps its real row")
a.Equal(types.SpanStatusSkipped, got[types.StageDocReader],
"a stage before the failure with no row never ran; a text passage has no document to parse")
a.Equal(types.SpanStatusCancelled, got[types.StageMultimodal],
"a stage after the failure with no row was abandoned, not broken")
a.Equal(types.SpanStatusCancelled, got[types.StagePostProcess],
"postprocess depends on embedding, so it is cancelled rather than failed")
// The UI focuses the first failed stage in canonical order.
fix(knowledge): stop synthesizing never-run stages as failed Closes #3452. buildSpanTree fills every canonical stage that has no span row using a status inferred from knowledge.parse_status, so a failed parse painted all of them "failed". That status carries information it cannot know: it cannot tell "this stage ran and failed" from "this stage never ran". The frontend picks the focused stage with the first failed one in canonical order, so whenever the real failure left an earlier stage rowless, the UI named the earlier stage. On main today a text passage is chunked without ever opening a docreader stage, so an embedding failure reports 文档解析 / docreader as the broken step for content that has no document to parse, and four of five segments render as failures. Once a stage has actually recorded a failure its position is known, so missing stages are now resolved against it: - downstream of the failure, per StageDependencies or canonical order → cancelled, which is what the status is documented to mean - before it → skipped; the stage either did not apply or its row was never written, and neither of those is a failure With no failed row anywhere the parse_status fallback stands unchanged, which is the case it was written for: legacy knowledge parsed before span tracking existed still renders done/failed rather than five pending segments. Also maps parse_status "cancelled" to a cancelled placeholder; it fell through the switch to pending, so a cancelled document showed spinners on the stages it never reached. The DAG walk is redundant with canonical order for today's stage list, where every dependency points at an earlier stage. It is there so the answer stays right if the list is reordered or a stage gains an upstream that is not its predecessor. No frontend change: skipped and cancelled already render, with localized labels in every locale.
2026-09-20 06:10:52 +00:00
var firstFailed string
for _, name := range types.AllStages {
if got[name] == types.SpanStatusFailed {
firstFailed = name
break
}
}
a.Equal(types.StageEmbedding, firstFailed,
"the timeline must name embedding, not an earlier stage that never ran")
a.NotNil(lastFail)
a.Equal(types.StageEmbedding, lastFail.Name)
}
// No failed row means no position to reason from, so the fallback still applies.
fix(knowledge): stop synthesizing never-run stages as failed Closes #3452. buildSpanTree fills every canonical stage that has no span row using a status inferred from knowledge.parse_status, so a failed parse painted all of them "failed". That status carries information it cannot know: it cannot tell "this stage ran and failed" from "this stage never ran". The frontend picks the focused stage with the first failed one in canonical order, so whenever the real failure left an earlier stage rowless, the UI named the earlier stage. On main today a text passage is chunked without ever opening a docreader stage, so an embedding failure reports 文档解析 / docreader as the broken step for content that has no document to parse, and four of five segments render as failures. Once a stage has actually recorded a failure its position is known, so missing stages are now resolved against it: - downstream of the failure, per StageDependencies or canonical order → cancelled, which is what the status is documented to mean - before it → skipped; the stage either did not apply or its row was never written, and neither of those is a failure With no failed row anywhere the parse_status fallback stands unchanged, which is the case it was written for: legacy knowledge parsed before span tracking existed still renders done/failed rather than five pending segments. Also maps parse_status "cancelled" to a cancelled placeholder; it fell through the switch to pending, so a cancelled document showed spinners on the stages it never reached. The DAG walk is redundant with canonical order for today's stage list, where every dependency points at an earlier stage. It is there so the answer stays right if the list is reordered or a stage gains an upstream that is not its predecessor. No frontend change: skipped and cancelled already render, with localized labels in every locale.
2026-09-20 06:10:52 +00:00
func TestBuildSpanTree_MissingStagesWithoutFailureKeepFallback(t *testing.T) {
now := time.Now()
rows := []types.KnowledgeProcessingSpan{
{KnowledgeID: "kid", Attempt: 1, SpanID: "root", Name: "knowledge_processing", Kind: types.SpanKindRoot, Status: types.SpanStatusRunning, StartedAt: &now},
{KnowledgeID: "kid", Attempt: 1, SpanID: "doc", ParentSpanID: "root", Name: types.StageDocReader, Kind: types.SpanKindStage, Status: types.SpanStatusDone, StartedAt: &now},
}
tree, _, _ := buildSpanTree("kid", 1, rows, types.ParseStatusProcessing)
got := stageStatuses(t, tree)
a := assert.New(t)
a.Equal(types.SpanStatusPending, got[types.StageChunking],
"a run still in flight keeps pending placeholders")
a.Equal(types.SpanStatusPending, got[types.StagePostProcess])
}
// parse_status "cancelled" fell through to pending, leaving spinners on
// stages the document never reached.
fix(knowledge): stop synthesizing never-run stages as failed Closes #3452. buildSpanTree fills every canonical stage that has no span row using a status inferred from knowledge.parse_status, so a failed parse painted all of them "failed". That status carries information it cannot know: it cannot tell "this stage ran and failed" from "this stage never ran". The frontend picks the focused stage with the first failed one in canonical order, so whenever the real failure left an earlier stage rowless, the UI named the earlier stage. On main today a text passage is chunked without ever opening a docreader stage, so an embedding failure reports 文档解析 / docreader as the broken step for content that has no document to parse, and four of five segments render as failures. Once a stage has actually recorded a failure its position is known, so missing stages are now resolved against it: - downstream of the failure, per StageDependencies or canonical order → cancelled, which is what the status is documented to mean - before it → skipped; the stage either did not apply or its row was never written, and neither of those is a failure With no failed row anywhere the parse_status fallback stands unchanged, which is the case it was written for: legacy knowledge parsed before span tracking existed still renders done/failed rather than five pending segments. Also maps parse_status "cancelled" to a cancelled placeholder; it fell through the switch to pending, so a cancelled document showed spinners on the stages it never reached. The DAG walk is redundant with canonical order for today's stage list, where every dependency points at an earlier stage. It is there so the answer stays right if the list is reordered or a stage gains an upstream that is not its predecessor. No frontend change: skipped and cancelled already render, with localized labels in every locale.
2026-09-20 06:10:52 +00:00
func TestBuildSpanTree_CancelledParseRendersCancelled(t *testing.T) {
tree, _, _ := buildSpanTree("kid-cancelled", 0, nil, types.ParseStatusCancelled)
a := assert.New(t)
a.Equal(types.SpanStatusCancelled, tree.Status)
a.Len(tree.Children, len(types.AllStages))
for _, child := range tree.Children {
a.Equal(types.SpanStatusCancelled, child.Status,
"a cancelled parse must not render its unreached stages as pending")
}
}
// Failure at the first stage: nothing precedes it, so nothing is skipped.
fix(knowledge): stop synthesizing never-run stages as failed Closes #3452. buildSpanTree fills every canonical stage that has no span row using a status inferred from knowledge.parse_status, so a failed parse painted all of them "failed". That status carries information it cannot know: it cannot tell "this stage ran and failed" from "this stage never ran". The frontend picks the focused stage with the first failed one in canonical order, so whenever the real failure left an earlier stage rowless, the UI named the earlier stage. On main today a text passage is chunked without ever opening a docreader stage, so an embedding failure reports 文档解析 / docreader as the broken step for content that has no document to parse, and four of five segments render as failures. Once a stage has actually recorded a failure its position is known, so missing stages are now resolved against it: - downstream of the failure, per StageDependencies or canonical order → cancelled, which is what the status is documented to mean - before it → skipped; the stage either did not apply or its row was never written, and neither of those is a failure With no failed row anywhere the parse_status fallback stands unchanged, which is the case it was written for: legacy knowledge parsed before span tracking existed still renders done/failed rather than five pending segments. Also maps parse_status "cancelled" to a cancelled placeholder; it fell through the switch to pending, so a cancelled document showed spinners on the stages it never reached. The DAG walk is redundant with canonical order for today's stage list, where every dependency points at an earlier stage. It is there so the answer stays right if the list is reordered or a stage gains an upstream that is not its predecessor. No frontend change: skipped and cancelled already render, with localized labels in every locale.
2026-09-20 06:10:52 +00:00
func TestBuildSpanTree_DocReaderFailureCancelsEverythingAfter(t *testing.T) {
now := time.Now()
rows := []types.KnowledgeProcessingSpan{
{KnowledgeID: "kid", Attempt: 1, SpanID: "root", Name: "knowledge_processing", Kind: types.SpanKindRoot, Status: types.SpanStatusFailed, StartedAt: &now},
{KnowledgeID: "kid", Attempt: 1, SpanID: "doc", ParentSpanID: "root", Name: types.StageDocReader, Kind: types.SpanKindStage, Status: types.SpanStatusFailed, ErrorCode: "DOCREADER_TIMEOUT", StartedAt: &now},
}
tree, _, _ := buildSpanTree("kid", 1, rows, types.ParseStatusFailed)
got := stageStatuses(t, tree)
a := assert.New(t)
a.Equal(types.SpanStatusFailed, got[types.StageDocReader])
for _, name := range []string{types.StageChunking, types.StageEmbedding, types.StageMultimodal, types.StagePostProcess} {
a.Equal(types.SpanStatusCancelled, got[name],
"%s follows the failed docreader and never ran", name)
}
a.NotContains(got, types.SpanStatusSkipped)
}