fix(reconciliation): 修复僵死回收 SQL 并补齐验收缺口
build / build (push) Has been cancelled

- 回收 SQL 占位符改为 $1/$2,消除 pgx 扩展协议 42P18(手动/定时对账 500)
- 直接写入 finding 时归一空 confirmation_state,避免 23514
- 修正 R6/overview 同谓词用例夹具,两条台账各自持有 source version
- 页面顶部统一服务与队列单行状态条,删除 Embedding/LLM 常量卡
- 平台阶段筛选合并为「WeKnora 处理中」,后端支持 stage=weknora
- weknora_url 由测试 WeKnora 源构造,详情与 503 提供跳转链接
- 补 1000/页线上查询、R8 合法收养、weknora 阶段筛选用例
This commit is contained in:
Zhero & Rin
2026-12-01 14:22:06 +08:00
committed by 姚章浩
parent 629694546c
commit e855261b4d
19 changed files with 211 additions and 143 deletions
+1 -1
View File
@@ -73,7 +73,7 @@ func listMonitorTasks(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, 400, map[string]string{"error": "invalid filter"})
return
}
for _, pair := range [][2]string{{f.Scope, "|internal|external"}, {f.Action, "|add|update|remove"}, {f.Status, "|active|waiting|running|retrying|attention|completed|cancelled"}, {f.Stage, "|waiting|fetch|upload|parsing|indexing|removal|finished"}} {
for _, pair := range [][2]string{{f.Scope, "|internal|external"}, {f.Action, "|add|update|remove"}, {f.Status, "|active|waiting|running|retrying|attention|completed|cancelled"}, {f.Stage, "|waiting|fetch|upload|parsing|indexing|removal|finished|weknora"}} {
if !strings.Contains("|"+pair[1]+"|", "|"+pair[0]+"|") {
writeJSON(w, 400, map[string]string{"error": "invalid filter"})
return
+7
View File
@@ -33,6 +33,13 @@ func TestMonitorTasksRoute(t *testing.T) {
if s.filter.Status != "active" || s.filter.Offset != 40 {
t.Fatalf("filter %#v", s.filter)
}
// §8 merges 解析/索引增强 into one "WeKnora 处理中" facet.
merged := httptest.NewRequest("GET", "/api/v1/monitor/tasks?stage=weknora", nil).WithContext(req.Context())
wm := httptest.NewRecorder()
h.ServeHTTP(wm, merged)
if wm.Code != 200 || s.filter.Stage != "weknora" {
t.Fatalf("weknora stage: %d filter %#v", wm.Code, s.filter)
}
for _, query := range []string{"status=garbage", "stage=internal&scope=internal", "limit=101", "offset=-1", "since=bad"} {
r := httptest.NewRequest("GET", "/api/v1/monitor/tasks?"+query, nil).WithContext(req.Context())
rr := httptest.NewRecorder()
+3 -4
View File
@@ -306,11 +306,10 @@ func (provider *RealProvider) Services(ctx context.Context) []governance.Service
health = append(health, provider.weKnoraProbe(ctx, now))
health = append(health, provider.productionWeKnoraProbe(ctx, now))
health = append(health, provider.httpProbe(ctx, "mineru", "MinerU", provider.minerUBaseURL, now))
// Not-applicable dependencies stay explicit (embedding/llm managed by
// WeKnora, redis/mq/oss not deployed).
// Not-applicable dependencies stay explicit (redis/mq/oss not deployed).
// Embedding/LLM are managed inside WeKnora and are not platform services;
// listing them here produced two permanent "unknown" cards on the page.
health = append(health,
provider.track(classify("embedding", "Embedding模型", false, false, ProbeOutcome{ObservedAt: now})),
provider.track(classify("llm", "LLM模型", false, false, ProbeOutcome{ObservedAt: now})),
provider.track(classify("redis", "Redis / MQ", false, false, ProbeOutcome{ObservedAt: now})),
provider.track(classify("oss", "OSS", false, false, ProbeOutcome{ObservedAt: now})),
)
@@ -59,11 +59,18 @@ func TestRealServicesHealthMatrix(t *testing.T) {
if byKey["weknora-production/r"] != ReadNotConfigured || byKey["weknora-production/l"] != LiveUnknown {
t.Fatalf("unconfigured production endpoint = %v/%v", byKey["weknora-production/l"], byKey["weknora-production/r"])
}
for _, key := range []string{"redis", "oss", "embedding", "llm"} {
for _, key := range []string{"redis", "oss"} {
if byKey[key+"/r"] != ReadNotApplicable || byKey[key+"/l"] != LiveUnknown {
t.Fatalf("not-deployed %s = %v/%v", key, byKey[key+"/l"], byKey[key+"/r"])
}
}
// Embedding/LLM belong to WeKnora; the platform must not render them as
// permanent unknown cards (requirement §8).
for _, key := range []string{"embedding", "llm"} {
if _, ok := byKey[key+"/r"]; ok {
t.Fatalf("platform health still lists %s", key)
}
}
// Readiness must be blocked ONLY by configured+deployed failures: worker.
ok, blocked := overallReadiness(health)
if ok || len(blocked) != 1 || blocked[0] != "worker" {
@@ -32,10 +32,13 @@ func TestOverviewRemovalDemandAndSharedViewAgree(t *testing.T) {
exec(`INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,policy_state)
VALUES('si-recon-view','conn-recon-view','recon.md',repeat('b',64),'对账视图','file','blocked')`)
exec(`INSERT INTO source_item_versions(id,source_item_id,revision,content_state) VALUES('sv-recon-view','si-recon-view','r1','verified')`)
// test_publications is unique on (source_item_version_id,test_kb_id): a second
// publication in the same KB must point at its own version, not reuse r1.
exec(`INSERT INTO source_item_versions(id,source_item_id,revision,content_state) VALUES('sv-recon-removing','si-recon-view','r2','verified')`)
exec(`INSERT INTO test_publications(id,source_item_version_id,test_kb_id,knowledge_id,ingest_state,processing_state,retrieval_state)
VALUES('pub-recon-view','sv-recon-view','kb-recon-view','doc-recon-view','uploaded','completed','unpublished')`)
exec(`INSERT INTO test_publications(id,source_item_version_id,test_kb_id,knowledge_id,ingest_state,processing_state,retrieval_state)
VALUES('pub-recon-removing','sv-recon-view','kb-recon-view','doc-recon-removing','uploaded','completed','disabling')`)
VALUES('pub-recon-removing','sv-recon-removing','kb-recon-view','doc-recon-removing','uploaded','completed','disabling')`)
provider, err := NewRealProvider(RealProviderConfig{DB: metricsPool{pool: pool}})
if err != nil {
+1 -1
View File
@@ -145,7 +145,7 @@ const monitorTasksCTE = `WITH history_publications AS (
SELECT * FROM projected WHERE ($1='' OR strpos(lower(title || ' ' || path),lower($1))>0)
AND ($2='' OR source_id=$2) AND ($3='' OR target_scope=$3) AND ($4='' OR action=$4)
AND ($5='' OR ($5='active' AND status NOT IN ('completed','cancelled')) OR status=$5)
AND ($6='' OR stage=$6) AND ($7='' OR id=$7) AND ($10='' OR target_kb=$10)
AND ($6='' OR stage=$6 OR ($6='weknora' AND stage IN ('parsing','indexing'))) AND ($7='' OR id=$7) AND ($10='' OR target_kb=$10)
AND ($11='' OR updated_at>=NULLIF($11,'')::timestamptz) AND ($12='' OR updated_at<=NULLIF($12,'')::timestamptz)
) `
@@ -97,8 +97,8 @@ func (s *Store) ReapStaleReconciliationRuns(ctx context.Context, now time.Time,
return 0, nil
}
tag, err := s.db.Exec(ctx, `UPDATE reconciliation_runs
SET state='failed',finished_at=$2,error_code='stale_timeout'
WHERE state='running' AND started_at < $3`, now, now.Add(-threshold))
SET state='failed',finished_at=$1,error_code='stale_timeout'
WHERE state='running' AND started_at < $2`, now, now.Add(-threshold))
if err != nil {
return 0, fmt.Errorf("reap stale reconciliation runs: %w", err)
}
@@ -222,6 +222,13 @@ WHERE id=$1 AND state='running'`, run.ID, run.FinishedAt, run.LedgerCount, run.K
return ErrReconciliationNotRunning
}
for _, finding := range findings {
// The column default only applies when the insert omits the column; the
// service always fills it, but direct callers may pass "" and must not
// violate the check constraint.
confirmation := finding.ConfirmationState
if confirmation == "" {
confirmation = "confirmed"
}
if _, err := tx.Exec(ctx, `INSERT INTO reconciliation_findings
(id,run_id,finding_type,publication_id,knowledge_id,title,path,source,target_scope,
ledger_state,weknora_parse_status,normalized_state,ledger_sha256,declared_sha256,
@@ -231,7 +238,7 @@ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,'open'
finding.ID, finding.RunID, finding.Type, finding.PublicationID, finding.DocumentID,
finding.Title, finding.Path, finding.Source, finding.TargetScope, finding.LedgerState,
finding.WeKnoraParseState, finding.NormalizedState, finding.LedgerSHA256, finding.DeclaredSHA256,
finding.WeKnoraFileMD5, finding.EvidenceLevel, finding.ConfirmationState, finding.Detail,
finding.WeKnoraFileMD5, finding.EvidenceLevel, confirmation, finding.Detail,
finding.SuggestedAction, finding.WeKnoraURL, run.FinishedAt); err != nil {
return fmt.Errorf("insert reconciliation finding: %w", err)
}
+20
View File
@@ -336,6 +336,26 @@ func TestClientProvidesPaginatedInventoryChunkAndScopedSearchReads(t *testing.T)
}
}
// Acceptance #16: the reconciliation scan must be one 1000-per-page read, and
// the wire query is the evidence — not just the constant passed to the interface.
func TestListKnowledgeSendsScanPageSizeOnTheWire(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("page") != "1" || r.URL.Query().Get("page_size") != "1000" {
t.Fatalf("knowledge list query = %s", r.URL.RawQuery)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"success":true,"data":[],"total":0,"page":1,"page_size":1000}`))
}))
defer server.Close()
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: "test-api-key", Timeout: time.Second})
if err != nil {
t.Fatal(err)
}
if _, _, err := client.ListKnowledge(context.Background(), "kb-1", 1, 1000); err != nil {
t.Fatal(err)
}
}
func TestClientRejectsRedirectWithoutForwardingAPIKey(t *testing.T) {
var targetHits atomic.Int32
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+6
View File
@@ -5,6 +5,7 @@ import (
"crypto/sha256"
"encoding/hex"
"fmt"
"net/url"
"sort"
"strings"
"sync"
@@ -152,6 +153,11 @@ func (s *Service) buildFindings(ctx context.Context, run governance.Reconciliati
}
finding.ActionState = "open"
finding.ID = deterministicFindingID(run.ID, finding)
if finding.WeKnoraURL == "" && run.KBID != "" && s.weKnoraWebBase != nil {
if base := strings.TrimSpace(s.weKnoraWebBase(ctx)); base != "" {
finding.WeKnoraURL = strings.TrimSuffix(base, "/") + "/platform/knowledge-bases/" + url.PathEscape(run.KBID)
}
}
findings = append(findings, finding)
}
+5
View File
@@ -72,6 +72,9 @@ type Config struct {
ConfirmConcurrency int
KeepRuns int
MaxAge time.Duration
// WeKnoraWebBase resolves the WeKnora origin used to build the finding's
// jump link. Empty or nil leaves weknora_url empty, which the contract allows.
WeKnoraWebBase func(context.Context) string
}
type Service struct {
@@ -86,6 +89,7 @@ type Service struct {
confirmConcurrency int
keepRuns int
maxAge time.Duration
weKnoraWebBase func(context.Context) string
}
func New(config Config) (*Service, error) {
@@ -120,6 +124,7 @@ func New(config Config) (*Service, error) {
store: config.Store, remote: config.Remote, runtime: config.Runtime, queue: config.Queue,
now: config.Now, grace: config.Grace, stallAfter: config.StallAfter, staleAfter: config.StaleAfter,
confirmConcurrency: config.ConfirmConcurrency, keepRuns: config.KeepRuns, maxAge: config.MaxAge,
weKnoraWebBase: config.WeKnoraWebBase,
}, nil
}
+41 -1
View File
@@ -3,6 +3,7 @@ package reconciliation
import (
"context"
"errors"
"strings"
"testing"
"time"
@@ -203,7 +204,8 @@ func TestExecuteRunFindsR1ToR8WithoutRemoteWrites(t *testing.T) {
}
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now },
Grace: 30 * time.Minute, StallAfter: 2 * time.Hour, StaleAfter: 6 * time.Hour,
ConfirmConcurrency: 1, KeepRuns: 30, MaxAge: 90 * 24 * time.Hour})
ConfirmConcurrency: 1, KeepRuns: 30, MaxAge: 90 * 24 * time.Hour,
WeKnoraWebBase: func(context.Context) string { return "https://test.example/" }})
if err != nil {
t.Fatal(err)
}
@@ -234,6 +236,44 @@ func TestExecuteRunFindsR1ToR8WithoutRemoteWrites(t *testing.T) {
if store.completedRun.Counts["R8"] != 1 || store.completedRun.LedgerCount != len(ledger) || store.completedRun.KBCount != len(items) {
t.Fatalf("run counts = %#v", store.completedRun)
}
// Every finding carries the WeKnora jump link built from the resolved test
// origin; an empty base would leave it empty, but a resolved one must not.
for _, finding := range store.findings {
if finding.WeKnoraURL != "https://test.example/platform/knowledge-bases/kb-1" {
t.Fatalf("%s weknora_url = %q", finding.Type, finding.WeKnoraURL)
}
}
}
// Two ledger publications may legitimately hold the same bytes in one test KB
// (adoption). R8 is keyed by publication_id, so that case must stay silent.
func TestR8DoesNotFlagAdoptedDuplicatesWithDistinctPublications(t *testing.T) {
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
sha := strings.Repeat("a", 64)
md5 := strings.Repeat("b", 32)
row := func(pub, doc string) governance.ReconciliationLedgerRow {
return governance.ReconciliationLedgerRow{
PublicationID: pub, KnowledgeID: doc, ProcessingState: "completed", RetrievalState: "unpublished",
TargetScope: "internal", Title: doc, SHA256: sha, UploadMD5: md5, UpdatedAt: now.Add(-time.Hour),
}
}
ledger := []governance.ReconciliationLedgerRow{row("pub-a", "doc-a"), row("pub-b", "doc-b")}
items := []weknora.Knowledge{
{ID: "doc-a", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", FileHash: md5, Metadata: map[string]any{"publication_id": "pub-a", "content_sha256": sha}},
{ID: "doc-b", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", FileHash: md5, Metadata: map[string]any{"publication_id": "pub-b", "content_sha256": sha}},
}
service, err := New(Config{Store: &fakeReconciliationStore{}, Remote: &fakeReconciliationRemote{}, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
run := governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", StartedAt: now}
findings, err := service.buildFindings(context.Background(), run, ledger, items, false)
if err != nil {
t.Fatal(err)
}
if len(findings) != 0 {
t.Fatalf("adopted duplicates produced findings: %#v", findings)
}
}
func TestExecuteRunFailsWholeBatchWithoutFindings(t *testing.T) {