From 414749681f163a97818b7855376fe7b562d9b802 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Wed, 27 May 2026 15:01:54 +0800 Subject: [PATCH] test(knowledge): add coverage and protect housekeeping from false-killing long stages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .../repository/knowledge_span_repo_test.go | 182 ++++++++++++++++ .../service/knowledge_housekeeping.go | 140 ++++++++++++- .../service/knowledge_housekeeping_test.go | 188 +++++++++++++++++ .../service/knowledge_span_tracker.go | 42 +++- .../service/knowledge_span_tracker_test.go | 196 ++++++++++++++++++ internal/handler/knowledge_spans_test.go | 100 +++++++++ 6 files changed, 836 insertions(+), 12 deletions(-) create mode 100644 internal/application/repository/knowledge_span_repo_test.go create mode 100644 internal/application/service/knowledge_housekeeping_test.go create mode 100644 internal/application/service/knowledge_span_tracker_test.go create mode 100644 internal/handler/knowledge_spans_test.go diff --git a/internal/application/repository/knowledge_span_repo_test.go b/internal/application/repository/knowledge_span_repo_test.go new file mode 100644 index 00000000..482996e8 --- /dev/null +++ b/internal/application/repository/knowledge_span_repo_test.go @@ -0,0 +1,182 @@ +package repository + +import ( + "context" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +// spansTestDDL mirrors migration 000053 for SQLite — same column order +// minus the JSONB type (SQLite stores JSON as TEXT, the JSONMap Scanner +// handles the round trip transparently). Inlined for the same reason +// knowledgebase_sqlite_test.go inlines its DDL: GORM AutoMigrate doesn't +// reproduce our PostgreSQL-flavoured schema cleanly. +const spansTestDDL = ` +CREATE TABLE IF NOT EXISTS knowledge_processing_spans ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + knowledge_id VARCHAR(64) NOT NULL, + attempt INTEGER NOT NULL DEFAULT 1, + span_id VARCHAR(64) NOT NULL, + parent_span_id VARCHAR(64), + name VARCHAR(64) NOT NULL, + kind VARCHAR(16) NOT NULL, + status VARCHAR(16) NOT NULL, + input TEXT, + output TEXT, + metadata TEXT, + error_code VARCHAR(64), + error_message TEXT, + error_detail TEXT, + started_at DATETIME, + finished_at DATETIME, + duration_ms BIGINT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE (knowledge_id, attempt, span_id) +); +` + +func setupSpanTestRepo(t *testing.T) (KnowledgeSpanRepository, *gorm.DB) { + t.Helper() + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.Exec(spansTestDDL).Error) + return NewKnowledgeSpanRepository(db), db +} + +// TestKnowledgeSpanRepo_UpsertAndList covers the round-trip: a Begin +// followed by an End for the same (kid, attempt, span_id) updates the +// existing row in place, leaving exactly one row queryable by +// ListByAttempt with the latest state. +func TestKnowledgeSpanRepo_UpsertAndList(t *testing.T) { + repo, _ := setupSpanTestRepo(t) + ctx := context.Background() + kid := "kid-1" + now := time.Now() + row := &types.KnowledgeProcessingSpan{ + KnowledgeID: kid, + Attempt: 1, + SpanID: "span-A", + Name: types.StageDocReader, + Kind: types.SpanKindStage, + Status: types.SpanStatusRunning, + StartedAt: &now, + } + require.NoError(t, repo.Upsert(ctx, row)) + + // Second Upsert with same (kid, attempt, span_id) flips status and + // sets finished_at — must overwrite, not insert a duplicate. + finished := now.Add(2 * time.Second) + row.Status = types.SpanStatusDone + row.FinishedAt = &finished + row.DurationMs = 2000 + require.NoError(t, repo.Upsert(ctx, row)) + + rows, err := repo.ListByAttempt(ctx, kid, 1) + require.NoError(t, err) + require.Len(t, rows, 1, "Upsert must replace, not append") + assert.Equal(t, types.SpanStatusDone, rows[0].Status) + assert.Equal(t, int64(2000), rows[0].DurationMs) +} + +// TestKnowledgeSpanRepo_NextAttempt confirms that NextAttempt allocates +// a fresh number per knowledge, isolating reparse history. Critical +// because the API layer renders attempt history by this number. +func TestKnowledgeSpanRepo_NextAttempt(t *testing.T) { + repo, _ := setupSpanTestRepo(t) + ctx := context.Background() + kid := "kid-2" + + a, err := repo.NextAttempt(ctx, kid) + require.NoError(t, err) + assert.Equal(t, 1, a, "first NextAttempt for fresh knowledge must be 1") + + now := time.Now() + require.NoError(t, repo.Upsert(ctx, &types.KnowledgeProcessingSpan{ + KnowledgeID: kid, Attempt: 1, SpanID: "root-1", + Name: "knowledge_processing", Kind: types.SpanKindRoot, + Status: types.SpanStatusRunning, StartedAt: &now, + })) + a, err = repo.NextAttempt(ctx, kid) + require.NoError(t, err) + assert.Equal(t, 2, a, "after one attempt exists, NextAttempt must be 2") + + // Cross-knowledge isolation: a different kid stays at 1. + other, err := repo.NextAttempt(ctx, "kid-other") + require.NoError(t, err) + assert.Equal(t, 1, other, "NextAttempt must scope to the knowledge_id") +} + +// TestKnowledgeSpanRepo_CancelDescendants verifies the cascade walk: +// failing a stage cancels every pending/running descendant in its +// subtree, while terminal states (done/skipped/failed) are left intact. +func TestKnowledgeSpanRepo_CancelDescendants(t *testing.T) { + repo, _ := setupSpanTestRepo(t) + ctx := context.Background() + kid := "kid-3" + now := time.Now() + + // Tree: chunking → embedding (running) → batch[0] (running) + // → multimodal (running) → image[0] (done) + for _, r := range []*types.KnowledgeProcessingSpan{ + {KnowledgeID: kid, Attempt: 1, SpanID: "chunking", Name: types.StageChunking, Kind: types.SpanKindStage, Status: types.SpanStatusRunning, StartedAt: &now}, + {KnowledgeID: kid, Attempt: 1, SpanID: "embedding", ParentSpanID: "chunking", Name: types.StageEmbedding, Kind: types.SpanKindStage, Status: types.SpanStatusRunning, StartedAt: &now}, + {KnowledgeID: kid, Attempt: 1, SpanID: "batch0", ParentSpanID: "embedding", Name: "embedding.batch[0]", Kind: types.SpanKindGeneration, Status: types.SpanStatusRunning, StartedAt: &now}, + {KnowledgeID: kid, Attempt: 1, SpanID: "multimodal", ParentSpanID: "chunking", Name: types.StageMultimodal, Kind: types.SpanKindStage, Status: types.SpanStatusRunning, StartedAt: &now}, + {KnowledgeID: kid, Attempt: 1, SpanID: "image0", ParentSpanID: "multimodal", Name: "multimodal.image[0]", Kind: types.SpanKindGeneration, Status: types.SpanStatusDone, StartedAt: &now}, + } { + require.NoError(t, repo.Upsert(ctx, r)) + } + + affected, err := repo.CancelDescendants(ctx, kid, 1, "chunking", "test reason") + require.NoError(t, err) + // Expected cancellations: embedding, batch0, multimodal (3 rows). + // The done image0 is terminal and left alone. + assert.Equal(t, int64(3), affected, "must cancel exactly the 3 pending/running descendants") + + rows, err := repo.ListByAttempt(ctx, kid, 1) + require.NoError(t, err) + statusBy := map[string]string{} + for _, r := range rows { + statusBy[r.SpanID] = r.Status + } + assert.Equal(t, types.SpanStatusRunning, statusBy["chunking"], "the failed span itself stays untouched (FailSpan layer flips it)") + assert.Equal(t, types.SpanStatusCancelled, statusBy["embedding"]) + assert.Equal(t, types.SpanStatusCancelled, statusBy["batch0"]) + assert.Equal(t, types.SpanStatusCancelled, statusBy["multimodal"]) + assert.Equal(t, types.SpanStatusDone, statusBy["image0"], "terminal states must not be touched") +} + +// TestKnowledgeSpanRepo_ListAttemptIsolation guarantees that different +// attempts of the same knowledge stay queryable independently — the +// foundation for the "show history" UI navigation (?attempt=N). +func TestKnowledgeSpanRepo_ListAttemptIsolation(t *testing.T) { + repo, _ := setupSpanTestRepo(t) + ctx := context.Background() + kid := "kid-history" + now := time.Now() + + for _, attempt := range []int{1, 2} { + require.NoError(t, repo.Upsert(ctx, &types.KnowledgeProcessingSpan{ + KnowledgeID: kid, Attempt: attempt, SpanID: "root", + Name: "knowledge_processing", Kind: types.SpanKindRoot, + Status: types.SpanStatusDone, StartedAt: &now, + })) + } + a1, err := repo.ListByAttempt(ctx, kid, 1) + require.NoError(t, err) + require.Len(t, a1, 1) + a2, err := repo.ListByAttempt(ctx, kid, 2) + require.NoError(t, err) + require.Len(t, a2, 1) + + all, err := repo.ListByAttempt(ctx, kid, 0) + require.NoError(t, err) + assert.Len(t, all, 2, "attempt=0 returns all attempts (used by housekeeping)") +} diff --git a/internal/application/service/knowledge_housekeeping.go b/internal/application/service/knowledge_housekeeping.go index b6434623..d3258875 100644 --- a/internal/application/service/knowledge_housekeeping.go +++ b/internal/application/service/knowledge_housekeeping.go @@ -102,21 +102,60 @@ func (h *HousekeepingService) runSweep(ctx context.Context) { cutoff := time.Now().Add(-threshold) // Sweep A: knowledge stuck in "processing". - resKnowledge := h.db.WithContext(ctx).Model(&types.Knowledge{}). + // + // Two-stage check is critical here: knowledge.updated_at advances + // only at parse_status transitions, but a long stage (DocReader on + // a 500MB PDF, embedding 5K chunks) can run for an hour with no + // status change. Using updated_at alone would falsely kill that + // run. So we OR-combine knowledge.updated_at with the most recent + // span row's updated_at — every Begin/End/Fail/Skip from + // SpanTracker bumps the span row, so an actively-progressing + // pipeline always has a recent span heartbeat even when the + // parent knowledge row is "frozen" mid-stage. + // + // Knowledge rows with no spans at all (lite mode, in-flight tasks + // from before this code shipped) fall back to the simple + // updated_at check — they have no heartbeat to consult. + var candidates []types.Knowledge + if err := h.db.WithContext(ctx). Where("parse_status = ? AND updated_at < ?", types.ParseStatusProcessing, cutoff). - Updates(map[string]interface{}{ - "parse_status": types.ParseStatusFailed, - "error_message": "task stuck in processing > " + threshold.String() + ", recovered by housekeeping", - }) - if resKnowledge.Error != nil { - logger.Warnf(ctx, "[Housekeeping] knowledge sweep failed: %v", resKnowledge.Error) - } else if resKnowledge.RowsAffected > 0 { - logger.Infof(ctx, "[Housekeeping] recovered %d stuck knowledge rows (threshold=%s)", - resKnowledge.RowsAffected, threshold) + Find(&candidates).Error; err != nil { + logger.Warnf(ctx, "[Housekeeping] knowledge candidate query failed: %v", err) + return + } + + stuck := h.filterByLastSpanActivity(ctx, candidates, cutoff) + 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 = ?", stuckIDs, types.ParseStatusProcessing). + Updates(map[string]interface{}{ + "parse_status": types.ParseStatusFailed, + "error_message": "task stuck in processing > " + threshold.String() + ", recovered by housekeeping", + }) + if res.Error != nil { + logger.Warnf(ctx, "[Housekeeping] knowledge sweep update failed: %v", res.Error) + } else if res.RowsAffected > 0 { + logger.Infof(ctx, "[Housekeeping] recovered %d stuck knowledge rows (threshold=%s)", + res.RowsAffected, threshold) + } + } + if active := len(candidates) - len(stuck); active > 0 { + // Visibility into "we considered killing N rows but their + // span tree showed they're still progressing". Ops can grep + // for this if they suspect housekeeping over- or under-fires. + logger.Infof(ctx, + "[Housekeeping] %d candidate(s) skipped — span heartbeat within threshold", + active) } // Sweep B: knowledge summary stuck. Summary is post-parse; threshold // is shorter because summary tasks are bounded by a single LLM call. + // No span heartbeat exists for the summary stage (it lives in a + // downstream asynq task), so we accept the original simple check. summaryCutoff := time.Now().Add(-1 * time.Hour) resSummary := h.db.WithContext(ctx).Model(&types.Knowledge{}). Where("summary_status = ? AND updated_at < ?", types.SummaryStatusProcessing, summaryCutoff). @@ -128,6 +167,87 @@ func (h *HousekeepingService) runSweep(ctx context.Context) { } } +// filterByLastSpanActivity returns the subset of candidates whose most +// recent span row predates `cutoff` — i.e. genuinely stuck. Candidates +// 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 { + if len(candidates) == 0 { + return candidates + } + ids := make([]string, 0, len(candidates)) + for _, k := range candidates { + ids = append(ids, k.ID) + } + + // We scan MAX(updated_at) as string then parse client-side. That + // dodges the SQLite driver's well-known refusal to auto-convert + // aggregate datetime values into time.Time on its own — Postgres + // happily round-trips, but the same query shape must work in + // Lite mode too. Since we only compare against a cutoff, the + // parse layer below tries the formats both Postgres and SQLite + // emit and takes the first that parses. + type spanHeartbeat struct { + KnowledgeID string `gorm:"column:knowledge_id"` + LastSeen string `gorm:"column:last_seen"` + } + var beats []spanHeartbeat + err := h.db.WithContext(ctx). + Table("knowledge_processing_spans"). + Select("knowledge_id, MAX(updated_at) AS last_seen"). + Where("knowledge_id IN ?", ids). + Group("knowledge_id"). + Find(&beats).Error + if err != nil { + // On query failure, fail safe — assume nothing has a + // 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 + } + heartbeat := make(map[string]time.Time, len(beats)) + for _, b := range beats { + if t, ok := parseHeartbeatTime(b.LastSeen); ok { + heartbeat[b.KnowledgeID] = t + } + } + + out := candidates[:0] + for _, k := range candidates { + if last, ok := heartbeat[k.ID]; ok && last.After(cutoff) { + // Active span heartbeat — leave alone. + continue + } + out = append(out, k) + } + return out +} + +// 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 diff --git a/internal/application/service/knowledge_housekeeping_test.go b/internal/application/service/knowledge_housekeeping_test.go new file mode 100644 index 00000000..f79a4f1a --- /dev/null +++ b/internal/application/service/knowledge_housekeeping_test.go @@ -0,0 +1,188 @@ +package service + +import ( + "context" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/config" + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +// knowledgeTestDDL is the minimal subset of the knowledge schema this +// suite needs. We avoid AutoMigrate because Knowledge carries multiple +// JSONB-tagged fields whose SQLite mapping is fragile. +// +// Table name is `knowledges` (plural) — that's what migration 000000 +// creates and what GORM's default pluralization expects when the +// service code uses Model(&types.Knowledge{}). +const knowledgeTestDDL = ` +CREATE TABLE IF NOT EXISTS knowledges ( + id VARCHAR(64) PRIMARY KEY, + tenant_id INTEGER NOT NULL DEFAULT 0, + knowledge_base_id VARCHAR(64), + parse_status VARCHAR(32) NOT NULL DEFAULT 'pending', + summary_status VARCHAR(32) NOT NULL DEFAULT 'none', + error_message TEXT, + title TEXT, + file_type TEXT, + enable_status TEXT NOT NULL DEFAULT 'enabled', + type TEXT NOT NULL DEFAULT 'document', + embedding_model_id TEXT NOT NULL DEFAULT '', + storage_size BIGINT NOT NULL DEFAULT 0, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + deleted_at DATETIME +); +` + +const housekeepingSpansDDL = ` +CREATE TABLE IF NOT EXISTS knowledge_processing_spans ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + knowledge_id VARCHAR(64) NOT NULL, + attempt INTEGER NOT NULL DEFAULT 1, + span_id VARCHAR(64) NOT NULL, + parent_span_id VARCHAR(64), + name VARCHAR(64) NOT NULL, + kind VARCHAR(16) NOT NULL, + status VARCHAR(16) NOT NULL, + input TEXT, + output TEXT, + metadata TEXT, + error_code VARCHAR(64), + error_message TEXT, + error_detail TEXT, + started_at DATETIME, + finished_at DATETIME, + duration_ms BIGINT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE (knowledge_id, attempt, span_id) +); +` + +func setupHousekeepingDB(t *testing.T) *gorm.DB { + t.Helper() + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.Exec(knowledgeTestDDL).Error) + require.NoError(t, db.Exec(housekeepingSpansDDL).Error) + return db +} + +// insertKnowledge writes a knowledge row at the given updated_at. We +// can't pass updated_at through GORM defaults since CURRENT_TIMESTAMP +// would override our test fixture; raw SQL keeps the timestamp. +func insertKnowledge(t *testing.T, db *gorm.DB, id, status string, updatedAt time.Time) { + t.Helper() + require.NoError(t, db.Exec( + `INSERT INTO knowledges (id, parse_status, updated_at) VALUES (?, ?, ?)`, + id, status, updatedAt, + ).Error) +} + +func insertSpan(t *testing.T, db *gorm.DB, kid string, attempt int, spanID, status string, updatedAt time.Time) { + t.Helper() + require.NoError(t, db.Exec( + `INSERT INTO knowledge_processing_spans (knowledge_id, attempt, span_id, name, kind, status, updated_at) + VALUES (?, ?, ?, 'docreader', 'stage', ?, ?)`, + kid, attempt, spanID, status, updatedAt, + ).Error) +} + +func newHousekeepingSvcForTest(db *gorm.DB) *HousekeepingService { + cfg := &config.Config{KnowledgeBase: &config.KnowledgeBaseConfig{ + // 1h floor + 10min buffer = 70min cutoff. Tight enough to keep + // the test's relative timestamps in seconds; the production + // default of 2h+10min is just a constant scale factor. + DocumentProcessTimeout: 1 * time.Hour, + }} + return NewHousekeepingService(db, cfg) +} + +// TestHousekeeping_RecoversAbandoned exercises the happy path: a +// knowledge stuck at "processing" with no recent heartbeat (no spans, +// stale knowledge.updated_at) MUST be flipped to failed. +func TestHousekeeping_RecoversAbandoned(t *testing.T) { + db := setupHousekeepingDB(t) + svc := newHousekeepingSvcForTest(db) + stale := time.Now().Add(-3 * time.Hour) // well past 70min cutoff + insertKnowledge(t, db, "kid-abandoned", types.ParseStatusProcessing, stale) + + svc.runSweep(context.Background()) + + var status, errMsg string + require.NoError(t, db.Raw( + `SELECT parse_status, error_message FROM knowledges WHERE id = ?`, "kid-abandoned", + ).Row().Scan(&status, &errMsg)) + assert.Equal(t, types.ParseStatusFailed, status) + assert.Contains(t, errMsg, "stuck in processing") +} + +// TestHousekeeping_NoFalseKill_ActiveSpan is the regression test for +// the "long DocReader silently runs longer than DocumentProcessTimeout" +// scenario the user flagged. A knowledge whose knowledge.updated_at +// looks stale BUT whose span tree shows recent activity must NOT be +// killed. +func TestHousekeeping_NoFalseKill_ActiveSpan(t *testing.T) { + db := setupHousekeepingDB(t) + svc := newHousekeepingSvcForTest(db) + stale := time.Now().Add(-3 * time.Hour) + insertKnowledge(t, db, "kid-active", types.ParseStatusProcessing, stale) + // Span heartbeat well within the 70min cutoff — it represents + // "we're STILL working, the worker just hasn't transitioned the + // parse_status column yet". + insertSpan(t, db, "kid-active", 1, "docreader-1", types.SpanStatusRunning, time.Now().Add(-2*time.Minute)) + + svc.runSweep(context.Background()) + + var status string + require.NoError(t, db.Raw( + `SELECT parse_status FROM knowledges WHERE id = ?`, "kid-active", + ).Row().Scan(&status)) + assert.Equal(t, types.ParseStatusProcessing, status, + "knowledge with recent span heartbeat must NOT be flipped to failed") +} + +// TestHousekeeping_NoFalseKill_StaleSpanRecovers confirms the inverse: +// a knowledge whose span tree has ALSO gone silent past the threshold +// is genuinely stuck and must be recovered. +func TestHousekeeping_NoFalseKill_StaleSpanRecovers(t *testing.T) { + db := setupHousekeepingDB(t) + svc := newHousekeepingSvcForTest(db) + stale := time.Now().Add(-3 * time.Hour) + insertKnowledge(t, db, "kid-stuck", types.ParseStatusProcessing, stale) + // Span row stale by the same amount — no recent activity anywhere. + insertSpan(t, db, "kid-stuck", 1, "docreader-1", types.SpanStatusRunning, stale) + + svc.runSweep(context.Background()) + + var status string + require.NoError(t, db.Raw( + `SELECT parse_status FROM knowledges WHERE id = ?`, "kid-stuck", + ).Row().Scan(&status)) + assert.Equal(t, types.ParseStatusFailed, status, + "genuinely stuck knowledge (knowledge AND spans both stale) must still be recovered") +} + +// TestHousekeeping_PreservesRecentlyTouched: any knowledge whose +// updated_at is within the cutoff is left alone — that's the cheap +// fast path that doesn't even consult the spans table. +func TestHousekeeping_PreservesRecentlyTouched(t *testing.T) { + db := setupHousekeepingDB(t) + svc := newHousekeepingSvcForTest(db) + insertKnowledge(t, db, "kid-fresh", types.ParseStatusProcessing, time.Now().Add(-30*time.Second)) + + svc.runSweep(context.Background()) + + var status string + require.NoError(t, db.Raw( + `SELECT parse_status FROM knowledges WHERE id = ?`, "kid-fresh", + ).Row().Scan(&status)) + assert.Equal(t, types.ParseStatusProcessing, status, + "knowledge updated within the cutoff must be left alone") +} diff --git a/internal/application/service/knowledge_span_tracker.go b/internal/application/service/knowledge_span_tracker.go index fe13b4e8..d1e4fabe 100644 --- a/internal/application/service/knowledge_span_tracker.go +++ b/internal/application/service/knowledge_span_tracker.go @@ -34,6 +34,7 @@ import ( "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/types" "github.com/google/uuid" + "gorm.io/gorm" ) // Span is the in-memory handle the pipeline holds while a stage / subspan @@ -96,6 +97,11 @@ type SpanTracker interface { type spanTracker struct { repo repository.KnowledgeSpanRepository + // db is held purely for the heartbeat side-channel: every span + // state transition pokes knowledge.updated_at so the housekeeping + // sweep can tell "actively running long stage" from "abandoned". + // nil-safe — when missing (test harness) the heartbeat is skipped. + db *gorm.DB // startsMu guards the in-process duration cache. Cross-process // workers won't find their parent's start here — that's fine, @@ -106,17 +112,43 @@ type spanTracker struct { } // NewSpanTracker constructs the GORM-backed tracker. A nil repo collapses -// to a no-op so test harnesses don't need to spin up a database. -func NewSpanTracker(repo repository.KnowledgeSpanRepository) SpanTracker { +// to a no-op so test harnesses don't need to spin up a database. The db +// is optional too: it's used only for the housekeeping heartbeat (see +// touchKnowledgeHeartbeat) and a nil db just disables that side-channel. +func NewSpanTracker(repo repository.KnowledgeSpanRepository, db *gorm.DB) SpanTracker { if repo == nil { return noopSpanTracker{} } return &spanTracker{ repo: repo, + db: db, starts: make(map[string]time.Time), } } +// touchKnowledgeHeartbeat advances knowledge.updated_at to the current +// wall-clock so the housekeeping sweep treats this row as actively +// progressing. Called on every span Begin/End/Fail/Skip — the cost is +// one indexed UPDATE per transition (≤ a few dozen per knowledge), which +// is dwarfed by the work the stages themselves do. +// +// Best-effort. We deliberately do NOT bump status here: the parse_status +// column remains under the pipeline's control. Only the timestamp gets +// nudged, which is exactly what housekeeping reads. +func (t *spanTracker) touchKnowledgeHeartbeat(ctx context.Context, knowledgeID string) { + if t.db == nil || knowledgeID == "" { + return + } + if err := t.db.WithContext(ctx).Model(&types.Knowledge{}). + Where("id = ?", knowledgeID). + Update("updated_at", time.Now()).Error; err != nil { + // Don't log every failure — heartbeat is best-effort and + // noisy logs would drown out real errors. Single line at + // warn level is enough for ops to spot a chronic outage. + logger.Warnf(ctx, "[SpanTracker] heartbeat update failed kid=%s: %v", knowledgeID, err) + } +} + func newSpanID() string { // Stripping the dashes saves 4 bytes per row — JSON parsers don't // care, and operators paste these into queries / Langfuse where a @@ -167,6 +199,7 @@ func (t *spanTracker) OpenAttempt(ctx context.Context, knowledgeID, langfuseTrac return nil, attempt, err } t.recordStart(rootID, now) + t.touchKnowledgeHeartbeat(ctx, knowledgeID) return &Span{ KnowledgeID: knowledgeID, Attempt: attempt, @@ -230,6 +263,7 @@ func (t *spanTracker) BeginStage(ctx context.Context, knowledgeID string, attemp return nil } t.recordStart(id, now) + t.touchKnowledgeHeartbeat(ctx, knowledgeID) return &Span{ KnowledgeID: knowledgeID, Attempt: attempt, @@ -267,6 +301,7 @@ func (t *spanTracker) BeginSubSpan(ctx context.Context, parent *Span, name, kind return nil } t.recordStart(id, now) + t.touchKnowledgeHeartbeat(ctx, parent.KnowledgeID) return &Span{ KnowledgeID: parent.KnowledgeID, Attempt: parent.Attempt, @@ -300,6 +335,7 @@ func (t *spanTracker) EndSpan(ctx context.Context, span *Span, output types.JSON if err := t.repo.Upsert(ctx, row); err != nil { logger.Warnf(ctx, "[SpanTracker] EndSpan failed span=%s: %v", span.SpanID, err) } + t.touchKnowledgeHeartbeat(ctx, span.KnowledgeID) } func (t *spanTracker) FailSpan(ctx context.Context, span *Span, errorCode, errorMessage string, errorDetail error) { @@ -351,6 +387,7 @@ func (t *spanTracker) FailSpan(ctx context.Context, span *Span, errorCode, error if span.Kind == types.SpanKindStage { t.cascadeDependentStages(ctx, span, reason) } + t.touchKnowledgeHeartbeat(ctx, span.KnowledgeID) } func (t *spanTracker) SkipSpan(ctx context.Context, span *Span, reason string) { @@ -373,6 +410,7 @@ func (t *spanTracker) SkipSpan(ctx context.Context, span *Span, reason string) { if err := t.repo.Upsert(ctx, row); err != nil { logger.Warnf(ctx, "[SpanTracker] SkipSpan failed span=%s: %v", span.SpanID, err) } + t.touchKnowledgeHeartbeat(ctx, span.KnowledgeID) } func (t *spanTracker) LookupStage(ctx context.Context, knowledgeID string, attempt int, stage string) *Span { diff --git a/internal/application/service/knowledge_span_tracker_test.go b/internal/application/service/knowledge_span_tracker_test.go new file mode 100644 index 00000000..2667ad85 --- /dev/null +++ b/internal/application/service/knowledge_span_tracker_test.go @@ -0,0 +1,196 @@ +package service + +import ( + "context" + "errors" + "testing" + + "github.com/Tencent/WeKnora/internal/application/repository" + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +// span tracker tests use a real GORM-backed repo against an in-memory +// SQLite DB. We do this instead of a stub repo because the cascade / +// LookupStage logic interacts non-trivially with the persistence layer +// (UPSERT, MAX(attempt), parent IN ...) — a stub would let regressions +// in those queries slip through. +// +// We DDL-define the spans table inline (same content as the repo test's +// spansTestDDL — kept duplicated rather than exported because a service +// test crossing into the repository test file's identifiers couples the +// two too tightly). +const spanTrackerTestDDL = ` +CREATE TABLE IF NOT EXISTS knowledge_processing_spans ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + knowledge_id VARCHAR(64) NOT NULL, + attempt INTEGER NOT NULL DEFAULT 1, + span_id VARCHAR(64) NOT NULL, + parent_span_id VARCHAR(64), + name VARCHAR(64) NOT NULL, + kind VARCHAR(16) NOT NULL, + status VARCHAR(16) NOT NULL, + input TEXT, + output TEXT, + metadata TEXT, + error_code VARCHAR(64), + error_message TEXT, + error_detail TEXT, + started_at DATETIME, + finished_at DATETIME, + duration_ms BIGINT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE (knowledge_id, attempt, span_id) +); +` + +func setupSpanTrackerTest(t *testing.T) (SpanTracker, *gorm.DB) { + t.Helper() + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.Exec(spanTrackerTestDDL).Error) + // Pass nil for the heartbeat db: these tests don't exercise + // heartbeat side-effects (those are covered in the housekeeping + // suite). Keeping it nil also avoids needing the knowledges + // table just to validate span behaviour. + repo := repository.NewKnowledgeSpanRepository(db) + return NewSpanTracker(repo, nil), db +} + +// TestSpanTracker_OpenAttempt_AllocatesFreshNumbers covers the contract +// that drives reparse history: each OpenAttempt must hand out a strictly +// increasing attempt number per knowledge, and previous attempts' +// rows must remain queryable (via a separate ?attempt=N navigation). +func TestSpanTracker_OpenAttempt_AllocatesFreshNumbers(t *testing.T) { + tracker, db := setupSpanTrackerTest(t) + ctx := context.Background() + + root1, n1, err := tracker.OpenAttempt(ctx, "kid", "trace-1") + require.NoError(t, err) + require.NotNil(t, root1) + assert.Equal(t, 1, n1) + + root2, n2, err := tracker.OpenAttempt(ctx, "kid", "trace-2") + require.NoError(t, err) + require.NotNil(t, root2) + assert.Equal(t, 2, n2, "second OpenAttempt must allocate attempt 2") + assert.NotEqual(t, root1.SpanID, root2.SpanID, "each attempt has its own root span ID") + + // Both roots must persist — a reparse must NOT erase the previous + // attempt's history. + var count int64 + require.NoError(t, db.Table("knowledge_processing_spans"). + Where("knowledge_id = ? AND kind = 'root'", "kid"). + Count(&count).Error) + assert.Equal(t, int64(2), count, "previous attempt's root must remain after reparse") +} + +// TestSpanTracker_FailSpan_CascadesDownstream verifies that failing a +// stage flips its dependent stages to "cancelled" so the UI shows a +// clear blast radius instead of orphan spinners. This is the central +// guarantee of the DAG model — without it, a Chunking failure leaves +// Embedding/Multimodal/PostProcess as pending forever. +func TestSpanTracker_FailSpan_CascadesDownstream(t *testing.T) { + tracker, db := setupSpanTrackerTest(t) + ctx := context.Background() + + _, attempt, err := tracker.OpenAttempt(ctx, "kid", "") + require.NoError(t, err) + require.Equal(t, 1, attempt) + + // Begin every stage so the cascade has something to cancel. + docreader := tracker.BeginStage(ctx, "kid", attempt, types.StageDocReader, nil) + tracker.EndSpan(ctx, docreader, nil) + chunking := tracker.BeginStage(ctx, "kid", attempt, types.StageChunking, nil) + embedding := tracker.BeginStage(ctx, "kid", attempt, types.StageEmbedding, nil) + multimodal := tracker.BeginStage(ctx, "kid", attempt, types.StageMultimodal, nil) + postprocess := tracker.BeginStage(ctx, "kid", attempt, types.StagePostProcess, nil) + + // Fail Chunking. Embedding/Multimodal/PostProcess must cascade. + tracker.FailSpan(ctx, chunking, "CHUNKING_FAILED", "synthetic", errors.New("boom")) + + statusBy := map[string]string{} + type row struct { + Name, Status string + } + var rows []row + require.NoError(t, db.Table("knowledge_processing_spans"). + Select("name, status"). + Where("knowledge_id = ? AND attempt = ?", "kid", attempt). + Find(&rows).Error) + for _, r := range rows { + statusBy[r.Name] = r.Status + } + + assert.Equal(t, types.SpanStatusDone, statusBy[types.StageDocReader], "upstream stage stays done") + assert.Equal(t, types.SpanStatusFailed, statusBy[types.StageChunking], "the failed stage itself stays failed") + assert.Equal(t, types.SpanStatusCancelled, statusBy[types.StageEmbedding], "direct dependent must cascade") + assert.Equal(t, types.SpanStatusCancelled, statusBy[types.StageMultimodal], "sibling dependent must cascade") + assert.Equal(t, types.SpanStatusCancelled, statusBy[types.StagePostProcess], "transitive dependent must cascade") + + // Quiet the unused-variable check: embedding / multimodal / + // postprocess pointers were used to seed the table; their state + // is now in statusBy. Linter still wants them "consumed". + _ = embedding + _ = multimodal + _ = postprocess +} + +// TestSpanTracker_LookupStage_FindsAcrossProcesses simulates the +// cross-process bridge an asynq worker uses: the upstream pipeline +// creates the multimodal stage span, then a separate worker process +// must locate it by (kid, attempt, name) to attach its image subspan. +func TestSpanTracker_LookupStage_FindsAcrossProcesses(t *testing.T) { + tracker, _ := setupSpanTrackerTest(t) + ctx := context.Background() + + _, attempt, err := tracker.OpenAttempt(ctx, "kid", "") + require.NoError(t, err) + mm := tracker.BeginStage(ctx, "kid", attempt, types.StageMultimodal, nil) + require.NotNil(t, mm) + + // Pretend we're a different process — the in-memory `starts` + // cache is the same map here, but the cross-process semantics + // don't depend on it; LookupStage hits the DB. + found := tracker.LookupStage(ctx, "kid", attempt, types.StageMultimodal) + require.NotNil(t, found) + assert.Equal(t, mm.SpanID, found.SpanID, "LookupStage must return the same span row") + + // A different stage must not be confused with multimodal. + other := tracker.LookupStage(ctx, "kid", attempt, types.StageEmbedding) + assert.Nil(t, other, "LookupStage(missing) must return nil") +} + +// TestSpanTracker_BeginSubSpan_HangsUnderParent confirms multimodal / +// embedding fan-out subspans reference the parent stage's span_id — +// the structural invariant the buildSpanTree handler walks. +func TestSpanTracker_BeginSubSpan_HangsUnderParent(t *testing.T) { + tracker, db := setupSpanTrackerTest(t) + ctx := context.Background() + + _, attempt, err := tracker.OpenAttempt(ctx, "kid", "") + require.NoError(t, err) + parent := tracker.BeginStage(ctx, "kid", attempt, types.StageMultimodal, nil) + require.NotNil(t, parent) + + sub := tracker.BeginSubSpan(ctx, parent, "multimodal.image[0]", types.SpanKindGeneration, types.JSONMap{ + "image_url": "x", + }) + require.NotNil(t, sub) + + type row struct { + Name, Kind, ParentSpanID string + } + var rows []row + require.NoError(t, db.Table("knowledge_processing_spans"). + Select("name, kind, parent_span_id"). + Where("knowledge_id = ? AND name = ?", "kid", "multimodal.image[0]"). + Find(&rows).Error) + require.Len(t, rows, 1) + assert.Equal(t, types.SpanKindGeneration, rows[0].Kind) + assert.Equal(t, parent.SpanID, rows[0].ParentSpanID, "subspan must reference parent stage's span_id") +} diff --git a/internal/handler/knowledge_spans_test.go b/internal/handler/knowledge_spans_test.go new file mode 100644 index 00000000..20e343bf --- /dev/null +++ b/internal/handler/knowledge_spans_test.go @@ -0,0 +1,100 @@ +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) + 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) + 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_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) + 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) +}