bceb7ba682
台账里会残留已被删除的测试库(test_publications.test_kb_id 聚合出下拉候选), 页面默认又取排序最靠前的一项,于是「立即对账」打在死库上,远端回 404 被统一 映射成 remote_unavailable,页面提示「检查地址与 Key」——把工程师引去改一个根本 没坏的配置。 - 后端:BeginTask 的 404 单独落 remote_kb_missing,其余仍为 remote_unavailable - 前端:新增文案「所选测试知识库已不存在」;默认选中当前绑定的测试库并在下拉里 标注(当前绑定),用户自己选过(含「全部测试库」)后不再改写
641 lines
29 KiB
Go
641 lines
29 KiB
Go
package reconciliation
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"strconv"
|
||
"strings"
|
||
"sync"
|
||
"testing"
|
||
"time"
|
||
|
||
"knowledge-governance/internal/governance"
|
||
"knowledge-governance/internal/jobs"
|
||
"knowledge-governance/internal/platform/weknora"
|
||
"knowledge-governance/internal/readiness"
|
||
"knowledge-governance/internal/weknoraaccess"
|
||
)
|
||
|
||
func TestMatrixCoversEveryLedgerAndUpstreamState(t *testing.T) {
|
||
columns := []string{"pending", "processing", "finalizing", "completed", "failed", "cancelled", "deleting"}
|
||
want := map[string][]verdict{
|
||
"planned": {verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting},
|
||
"pending": {verdictConsistent, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting},
|
||
"processing": {verdictMismatch, verdictConsistent, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting},
|
||
"finalizing": {verdictMismatch, verdictMismatch, verdictConsistent, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting},
|
||
"completed": {verdictMismatch, verdictMismatch, verdictMismatch, verdictConsistent, verdictMismatch, verdictMismatch, verdictDeleting},
|
||
"failed": {verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictConsistent, verdictMismatch, verdictDeleting},
|
||
"stalled": {verdictStalled, verdictStalled, verdictStalled, verdictMismatch, verdictStalled, verdictStalled, verdictDeleting},
|
||
"cancelled": {verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictConsistent, verdictDeleting},
|
||
}
|
||
for row, expected := range want {
|
||
for index, column := range columns {
|
||
if got := classify(row, column); got != expected[index] {
|
||
t.Fatalf("classify(%s,%s) = %v, want %v", row, column, got, expected[index])
|
||
}
|
||
}
|
||
}
|
||
if AllowedWriteback("completed", "pending") || AllowedWriteback("stalled", "completed") ||
|
||
!AllowedWriteback("failed", "pending") || AllowedWriteback("planned", "pending") ||
|
||
AllowedWriteback("pending", "cancelled") || AllowedWriteback("pending", "deleting") {
|
||
t.Fatal("writeback migration table is wrong")
|
||
}
|
||
}
|
||
|
||
type fakeReconciliationStore struct {
|
||
run governance.ReconciliationRun
|
||
ledger []governance.ReconciliationLedgerRow
|
||
removal []governance.ReconciliationLedgerRow
|
||
overlapped bool
|
||
completedRun *governance.ReconciliationRun
|
||
findings []governance.ReconciliationFinding
|
||
failCode string
|
||
actionView governance.ReconciliationActionView
|
||
actionErr error
|
||
findingAfter governance.ReconciliationFinding
|
||
writebackHit bool
|
||
requeueHit bool
|
||
removeHit bool
|
||
requeueDoc string
|
||
orphan bool
|
||
enqueued []jobs.EnqueueRequest
|
||
}
|
||
|
||
func (f *fakeReconciliationStore) ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error) {
|
||
return 0, nil
|
||
}
|
||
func (f *fakeReconciliationStore) ClaimReconciliationRun(_ context.Context, run governance.ReconciliationRun, _ time.Time) (governance.ReconciliationRun, error) {
|
||
return run, nil
|
||
}
|
||
func (f *fakeReconciliationStore) ClaimScheduledReconciliationRun(_ context.Context, run governance.ReconciliationRun, _ time.Time, _ time.Time) (governance.ReconciliationRun, bool, error) {
|
||
return run, true, nil
|
||
}
|
||
func (f *fakeReconciliationStore) LoadReconciliationRun(context.Context, string) (governance.ReconciliationRun, error) {
|
||
return f.run, nil
|
||
}
|
||
func (f *fakeReconciliationStore) ListReconciliationRuns(context.Context, governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) {
|
||
return governance.ReconciliationRunPage{}, nil
|
||
}
|
||
func (f *fakeReconciliationStore) ListReconciliationFindings(context.Context, governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) {
|
||
return governance.ReconciliationFindingPage{}, nil
|
||
}
|
||
func (f *fakeReconciliationStore) GetReconciliationFinding(context.Context, string) (governance.ReconciliationFinding, error) {
|
||
if f.findingAfter.ID != "" {
|
||
return f.findingAfter, nil
|
||
}
|
||
return governance.ReconciliationFinding{}, ErrNotFound
|
||
}
|
||
func (f *fakeReconciliationStore) LoadReconciliationLedger(context.Context, string) ([]governance.ReconciliationLedgerRow, error) {
|
||
return f.ledger, nil
|
||
}
|
||
func (f *fakeReconciliationStore) LoadPreviousReconciliationCounts(context.Context, string, time.Time) (governance.ReconciliationCounts, bool, error) {
|
||
return nil, false, nil
|
||
}
|
||
func (f *fakeReconciliationStore) CompleteReconciliationRun(_ context.Context, run governance.ReconciliationRun, findings []governance.ReconciliationFinding) error {
|
||
f.completedRun = &run
|
||
f.findings = findings
|
||
return nil
|
||
}
|
||
func (f *fakeReconciliationStore) FailReconciliationRun(_ context.Context, _ string, code string, _ time.Time) error {
|
||
f.failCode = code
|
||
return nil
|
||
}
|
||
func (f *fakeReconciliationStore) CleanupReconciliationFindings(context.Context, time.Time, int, time.Duration) error {
|
||
return nil
|
||
}
|
||
func (f *fakeReconciliationStore) LibraryJobsActive(context.Context) (bool, error) {
|
||
return f.overlapped, nil
|
||
}
|
||
func (f *fakeReconciliationStore) ListReconciliationRemovalCandidates(context.Context, string) ([]governance.ReconciliationLedgerRow, error) {
|
||
return f.removal, nil
|
||
}
|
||
func (f *fakeReconciliationStore) LoadReconciliationActionView(context.Context, string) (governance.ReconciliationActionView, error) {
|
||
if f.actionErr != nil {
|
||
return governance.ReconciliationActionView{}, f.actionErr
|
||
}
|
||
return f.actionView, nil
|
||
}
|
||
func (f *fakeReconciliationStore) ReconciliationOrphanStillUnowned(context.Context, string, string) (bool, error) {
|
||
return f.orphan, nil
|
||
}
|
||
func (f *fakeReconciliationStore) WritebackReconciliationFinding(context.Context, string, string, string, string, time.Time) (governance.ReconciliationFinding, error) {
|
||
f.writebackHit = true
|
||
return f.findingAfter, nil
|
||
}
|
||
func (f *fakeReconciliationStore) RequeueReconciliationPublication(_ context.Context, _ string, expectedDocument string, _ string, _ string, _ time.Time) (string, error) {
|
||
f.requeueHit = true
|
||
f.requeueDoc = expectedDocument
|
||
return "job-1", nil
|
||
}
|
||
func (f *fakeReconciliationStore) MarkReconciliationOrphanRemoved(context.Context, string, string, string, time.Time) error {
|
||
f.removeHit = true
|
||
return nil
|
||
}
|
||
|
||
func (f *fakeReconciliationStore) Enqueue(_ context.Context, request jobs.EnqueueRequest, _ time.Time) (*jobs.Job, error) {
|
||
f.enqueued = append(f.enqueued, request)
|
||
return &jobs.Job{ID: request.ID}, nil
|
||
}
|
||
|
||
type fakeReconciliationRemote struct {
|
||
items []weknora.Knowledge
|
||
missing map[string]bool
|
||
gets map[string]weknora.Knowledge
|
||
listErr error
|
||
beginErr error
|
||
pageSizes []int
|
||
deleteCalls int
|
||
listInFlight int
|
||
maxInFlight int
|
||
}
|
||
|
||
func (f *fakeReconciliationRemote) BeginTask(ctx context.Context, _ string) (context.Context, weknora.InstanceIdentity, error) {
|
||
if f.beginErr != nil {
|
||
return ctx, weknora.InstanceIdentity{}, f.beginErr
|
||
}
|
||
return ctx, weknora.InstanceIdentity{BaseURL: "https://test.example", TenantID: 7}, nil
|
||
}
|
||
func (f *fakeReconciliationRemote) ListKnowledge(_ context.Context, _ string, _ int, pageSize int) ([]weknora.Knowledge, int64, error) {
|
||
f.pageSizes = append(f.pageSizes, pageSize)
|
||
f.listInFlight++
|
||
if f.listInFlight > f.maxInFlight {
|
||
f.maxInFlight = f.listInFlight
|
||
}
|
||
defer func() { f.listInFlight-- }()
|
||
if f.listErr != nil {
|
||
return nil, 0, f.listErr
|
||
}
|
||
return f.items, int64(len(f.items)), nil
|
||
}
|
||
func (f *fakeReconciliationRemote) GetKnowledge(_ context.Context, id string) (weknora.Knowledge, error) {
|
||
if f.missing[id] {
|
||
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
|
||
}
|
||
if item, ok := f.gets[id]; ok {
|
||
return item, nil
|
||
}
|
||
for _, item := range f.items {
|
||
if item.ID == id {
|
||
return item, nil
|
||
}
|
||
}
|
||
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
|
||
}
|
||
func (f *fakeReconciliationRemote) DeleteKnowledge(context.Context, string) error {
|
||
f.deleteCalls++
|
||
return nil
|
||
}
|
||
|
||
func ptrTime(value time.Time) *time.Time { return &value }
|
||
|
||
func TestExecuteRunFindsR1ToR8WithoutRemoteWrites(t *testing.T) {
|
||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||
ledger := []governance.ReconciliationLedgerRow{
|
||
{PublicationID: "pub-r1", KnowledgeID: "doc-r1", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", Title: "missing", UpdatedAt: now.Add(-time.Hour)},
|
||
{PublicationID: "pub-r4", KnowledgeID: "doc-r4", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UploadMD5: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)},
|
||
{PublicationID: "pub-r5", KnowledgeID: "doc-r5", ProcessingState: "processing", RetrievalState: "unpublished", TargetScope: "internal", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)},
|
||
{PublicationID: "pub-r6", KnowledgeID: "doc-r6", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", PolicyState: "blocked", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)},
|
||
{PublicationID: "pub-r7", KnowledgeID: "doc-r7", ProcessingState: "stalled", RetrievalState: "unpublished", TargetScope: "internal", ProcessingStartedAt: ptrTime(now.Add(-3 * time.Hour)), UpdatedAt: now.Add(-3 * time.Hour)},
|
||
{PublicationID: "dup-pub", KnowledgeID: "doc-r8a", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)},
|
||
}
|
||
items := []weknora.Knowledge{
|
||
{ID: "doc-r2", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "orphan-pub"}},
|
||
{ID: "doc-r3", KnowledgeBaseID: "kb-1", Channel: "web", ParseStatus: "completed"},
|
||
{ID: "doc-r4", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", FileHash: "cccccccccccccccccccccccccccccccc", Metadata: map[string]any{"publication_id": "pub-r4", "content_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}},
|
||
{ID: "doc-r5", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-r5"}},
|
||
{ID: "doc-r6", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-r6"}},
|
||
{ID: "doc-r7", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "processing", Metadata: map[string]any{"publication_id": "pub-r7"}},
|
||
{ID: "doc-r8a", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "dup-pub"}},
|
||
{ID: "doc-r8b", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "dup-pub"}},
|
||
}
|
||
store := &fakeReconciliationStore{
|
||
run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", State: "running", Trigger: "manual", StartedAt: now},
|
||
ledger: ledger,
|
||
removal: []governance.ReconciliationLedgerRow{{PublicationID: "pub-r6"}},
|
||
}
|
||
// The ledger scan must be read-only over the wire, not merely against a fake
|
||
// that remembers it has no write methods. This server speaks the real client
|
||
// protocol and records every non-GET request.
|
||
var mu sync.Mutex
|
||
var writes []string
|
||
var pageSizes []int
|
||
listInFlight, maxInFlight := 0, 0
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
mu.Lock()
|
||
if r.Method != http.MethodGet {
|
||
writes = append(writes, r.Method+" "+r.URL.Path)
|
||
}
|
||
mu.Unlock()
|
||
path := r.URL.Path
|
||
switch {
|
||
case path == "/api/v1/knowledge-bases/kb-1":
|
||
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{"id": "kb-1", "tenant_id": 7}})
|
||
case path == "/api/v1/knowledge-bases/kb-1/knowledge":
|
||
size, _ := strconv.Atoi(r.URL.Query().Get("page_size"))
|
||
mu.Lock()
|
||
pageSizes = append(pageSizes, size)
|
||
listInFlight++
|
||
if listInFlight > maxInFlight {
|
||
maxInFlight = listInFlight
|
||
}
|
||
mu.Unlock()
|
||
defer func() {
|
||
mu.Lock()
|
||
listInFlight--
|
||
mu.Unlock()
|
||
}()
|
||
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": items, "total": len(items), "page": 1, "page_size": size})
|
||
case strings.HasPrefix(path, "/api/v1/knowledge/"):
|
||
id := strings.TrimPrefix(path, "/api/v1/knowledge/")
|
||
if id == "doc-r1" {
|
||
w.WriteHeader(http.StatusNotFound)
|
||
_ = json.NewEncoder(w).Encode(map[string]any{"success": false, "message": "not found"})
|
||
return
|
||
}
|
||
for _, item := range items {
|
||
if item.ID == id {
|
||
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": item})
|
||
return
|
||
}
|
||
}
|
||
w.WriteHeader(http.StatusNotFound)
|
||
_ = json.NewEncoder(w).Encode(map[string]any{"success": false, "message": "not found"})
|
||
default:
|
||
w.WriteHeader(http.StatusNotFound)
|
||
}
|
||
}))
|
||
defer server.Close()
|
||
remote := &weknoraaccess.Client{
|
||
Resolver: readiness.Resolver{ResolveConnection: func(context.Context) (string, string, error) {
|
||
return server.URL, "test-key", nil
|
||
}},
|
||
Timeout: 5 * time.Second,
|
||
}
|
||
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,
|
||
WeKnoraWebBase: func(context.Context) string { return "https://test.example/" }})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := service.ExecuteRun(context.Background(), "run-1"); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if store.completedRun == nil {
|
||
t.Fatalf("run was not completed: fail code %q", store.failCode)
|
||
}
|
||
mu.Lock()
|
||
defer mu.Unlock()
|
||
if len(writes) != 0 {
|
||
t.Fatalf("reconciliation wrote remotely over HTTP: %v", writes)
|
||
}
|
||
if len(pageSizes) == 0 || pageSizes[0] != scanPageSize {
|
||
t.Fatalf("page size = %v, want %d", pageSizes, scanPageSize)
|
||
}
|
||
if maxInFlight != 1 {
|
||
t.Fatalf("scan in-flight peak = %d, want 1", maxInFlight)
|
||
}
|
||
got := map[string]int{}
|
||
for _, finding := range store.findings {
|
||
got[finding.Type]++
|
||
}
|
||
for _, typ := range []string{"R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8"} {
|
||
if got[typ] != 1 {
|
||
t.Fatalf("%s count = %d, findings=%#v", typ, got[typ], store.findings)
|
||
}
|
||
}
|
||
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)
|
||
}
|
||
}
|
||
|
||
// The scan phase is serial, but confirmation may fan out up to the configured
|
||
// bound and never past it (acceptance #17).
|
||
func TestConfirmAllRespectsConfiguredConcurrency(t *testing.T) {
|
||
remote := &concurrencyRemote{}
|
||
service, err := New(Config{
|
||
Store: &fakeReconciliationStore{}, Remote: remote, ConfirmConcurrency: 2,
|
||
Now: time.Now,
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
results := service.confirmAll(context.Background(), "kb-1", []string{"doc-1", "doc-2", "doc-3", "doc-4"})
|
||
if len(results) != 4 {
|
||
t.Fatalf("results = %d", len(results))
|
||
}
|
||
for id, result := range results {
|
||
if !result.notFound {
|
||
t.Fatalf("%s = %#v", id, result)
|
||
}
|
||
}
|
||
remote.mu.Lock()
|
||
peak := remote.maxInFlight
|
||
remote.mu.Unlock()
|
||
if peak != 2 {
|
||
t.Fatalf("confirm in-flight peak = %d, want 2", peak)
|
||
}
|
||
}
|
||
|
||
type concurrencyRemote struct {
|
||
fakeReconciliationRemote
|
||
mu sync.Mutex
|
||
inFlight int
|
||
maxInFlight int
|
||
}
|
||
|
||
func (r *concurrencyRemote) GetKnowledge(context.Context, string) (weknora.Knowledge, error) {
|
||
r.mu.Lock()
|
||
r.inFlight++
|
||
if r.inFlight > r.maxInFlight {
|
||
r.maxInFlight = r.inFlight
|
||
}
|
||
r.mu.Unlock()
|
||
time.Sleep(20 * time.Millisecond)
|
||
r.mu.Lock()
|
||
r.inFlight--
|
||
r.mu.Unlock()
|
||
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
|
||
}
|
||
|
||
// 库被删掉时,远端回的是 404,不是网络故障。批次必须落成 remote_kb_missing,
|
||
// 页面才能提示「去选当前绑定的库」,而不是让人去改没坏的地址与 Key。
|
||
func TestExecuteRunReportsMissingKnowledgeBase(t *testing.T) {
|
||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||
store := &fakeReconciliationStore{run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-gone", State: "running", StartedAt: now}}
|
||
remote := &fakeReconciliationRemote{beginErr: &weknora.HTTPError{StatusCode: 404}}
|
||
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now }})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := service.ExecuteRun(context.Background(), "run-1"); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if store.failCode != "remote_kb_missing" {
|
||
t.Fatalf("fail code = %q", store.failCode)
|
||
}
|
||
}
|
||
|
||
func TestExecuteRunFailsWholeBatchWithoutFindings(t *testing.T) {
|
||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||
store := &fakeReconciliationStore{run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", State: "running", StartedAt: now}}
|
||
remote := &fakeReconciliationRemote{listErr: errors.New("remote down")}
|
||
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now }})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := service.ExecuteRun(context.Background(), "run-1"); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if store.completedRun != nil || len(store.findings) != 0 {
|
||
t.Fatal("partial findings were written on scan failure")
|
||
}
|
||
if store.failCode != "remote_scan_failed" {
|
||
t.Fatalf("fail code = %q", store.failCode)
|
||
}
|
||
}
|
||
|
||
func actionService(t *testing.T, store *fakeReconciliationStore, remote *fakeReconciliationRemote) *Service {
|
||
t.Helper()
|
||
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time {
|
||
return time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||
}})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
return service
|
||
}
|
||
|
||
func TestWritebackHonorsMigrationTableAndCompletedDowngrade(t *testing.T) {
|
||
store := &fakeReconciliationStore{
|
||
actionView: governance.ReconciliationActionView{Finding: governance.ReconciliationFinding{
|
||
ID: "f1", Type: "R5", PublicationID: "pub-1", DocumentID: "doc-1",
|
||
LedgerState: "processing", NormalizedState: "completed", ActionState: "open",
|
||
}},
|
||
findingAfter: governance.ReconciliationFinding{ID: "f1", ActionState: "done"},
|
||
}
|
||
service := actionService(t, store, &fakeReconciliationRemote{})
|
||
if _, err := service.Writeback(context.Background(), "f1", "tester", "ok"); err != nil || !store.writebackHit {
|
||
t.Fatalf("allowed writeback err=%v hit=%t", err, store.writebackHit)
|
||
}
|
||
store.writebackHit = false
|
||
store.actionView.Finding.LedgerState = "completed"
|
||
store.actionView.Finding.NormalizedState = "pending"
|
||
if _, err := service.Writeback(context.Background(), "f1", "tester", "ok"); !errors.Is(err, ErrActionNotAllowed) || store.writebackHit {
|
||
t.Fatalf("completed downgrade err=%v hit=%t", err, store.writebackHit)
|
||
}
|
||
}
|
||
|
||
func TestRequeueR1AndR4UseTheSameSnapshotAndR4DeletesFirst(t *testing.T) {
|
||
store := &fakeReconciliationStore{
|
||
actionView: governance.ReconciliationActionView{TestKBID: "kb-1", Finding: governance.ReconciliationFinding{
|
||
ID: "f1", Type: "R1", PublicationID: "pub-1", DocumentID: "doc-1",
|
||
LedgerState: "completed", ActionState: "open",
|
||
}},
|
||
findingAfter: governance.ReconciliationFinding{ID: "f1", ActionState: "done"},
|
||
}
|
||
remote := &fakeReconciliationRemote{missing: map[string]bool{"doc-1": true}}
|
||
service := actionService(t, store, remote)
|
||
if _, err := service.Requeue(context.Background(), "f1", "tester", "ok"); err != nil || !store.requeueHit || store.requeueDoc != "doc-1" {
|
||
t.Fatalf("R1 requeue err=%v hit=%t doc=%q", err, store.requeueHit, store.requeueDoc)
|
||
}
|
||
store.requeueHit = false
|
||
store.actionView.Finding.Type = "R4"
|
||
item := weknora.Knowledge{ID: "doc-1", KnowledgeBaseID: "kb-1"}
|
||
remote.items = []weknora.Knowledge{item}
|
||
remote.missing = map[string]bool{}
|
||
if _, err := service.Requeue(context.Background(), "f1", "tester", "ok"); err != nil || remote.deleteCalls != 1 || !store.requeueHit {
|
||
t.Fatalf("R4 requeue err=%v deletes=%d hit=%t", err, remote.deleteCalls, store.requeueHit)
|
||
}
|
||
}
|
||
|
||
func TestRemoveR2RechecksOwnershipAndTreats404AsSuccess(t *testing.T) {
|
||
store := &fakeReconciliationStore{
|
||
orphan: true,
|
||
actionView: governance.ReconciliationActionView{TestKBID: "kb-1", Finding: governance.ReconciliationFinding{
|
||
ID: "f1", Type: "R2", DocumentID: "doc-1", ActionState: "open",
|
||
}},
|
||
findingAfter: governance.ReconciliationFinding{ID: "f1", ActionState: "done"},
|
||
}
|
||
remote := &fakeReconciliationRemote{missing: map[string]bool{"doc-1": true}}
|
||
service := actionService(t, store, remote)
|
||
if _, err := service.Remove(context.Background(), "f1", "tester", "ok"); err != nil || !store.removeHit {
|
||
t.Fatalf("404 removal err=%v hit=%t", err, store.removeHit)
|
||
}
|
||
store.removeHit = false
|
||
store.orphan = false
|
||
if _, err := service.Remove(context.Background(), "f1", "tester", "ok"); !errors.Is(err, ErrActionConflict) || store.removeHit {
|
||
t.Fatalf("owned removal err=%v hit=%t", err, store.removeHit)
|
||
}
|
||
}
|
||
|
||
// TestExecuteRunR6UsesRemovalCandidatesViewOnly freezes 陷阱 15: R6 and
|
||
// /monitor/overview must read one implementation. An upstream document still
|
||
// processing/finalizing, or a single read that misses the listing, must not
|
||
// remove a row from the R6 set — otherwise the two pages report different
|
||
// "需下架" numbers for the same instant.
|
||
func TestExecuteRunR6UsesRemovalCandidatesViewOnly(t *testing.T) {
|
||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||
ledger := []governance.ReconciliationLedgerRow{
|
||
{PublicationID: "pub-a", KnowledgeID: "doc-a", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)},
|
||
{PublicationID: "pub-b", KnowledgeID: "doc-b", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)},
|
||
{PublicationID: "pub-c", KnowledgeID: "doc-c", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)},
|
||
}
|
||
items := []weknora.Knowledge{
|
||
{ID: "doc-a", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "processing", Metadata: map[string]any{"publication_id": "pub-a"}},
|
||
{ID: "doc-c", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-c"}},
|
||
}
|
||
store := &fakeReconciliationStore{
|
||
run: governance.ReconciliationRun{ID: "run-r6", KBID: "kb-1", State: "running", Trigger: "manual", StartedAt: now},
|
||
ledger: ledger,
|
||
// The view is the authority: it lists three rows, including one whose
|
||
// upstream document is still processing and one absent from the scan.
|
||
removal: []governance.ReconciliationLedgerRow{
|
||
{PublicationID: "pub-a", KnowledgeID: "doc-a"},
|
||
{PublicationID: "pub-b", KnowledgeID: "doc-b"},
|
||
{PublicationID: "pub-c", KnowledgeID: "doc-c"},
|
||
},
|
||
}
|
||
remote := &fakeReconciliationRemote{items: items, missing: map[string]bool{"doc-b": true}}
|
||
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,
|
||
WeKnoraWebBase: func(context.Context) string { return "https://test.example/" }})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := service.ExecuteRun(context.Background(), "run-r6"); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
r6 := map[string]governance.ReconciliationFinding{}
|
||
for _, finding := range store.findings {
|
||
if finding.Type == "R6" {
|
||
r6[finding.PublicationID] = finding
|
||
}
|
||
}
|
||
if len(r6) != len(store.removal) {
|
||
t.Fatalf("R6 count = %d, removal candidates = %d; findings=%#v", len(r6), len(store.removal), store.findings)
|
||
}
|
||
if processing, ok := r6["pub-a"]; !ok || processing.WeKnoraParseState != "processing" || processing.NormalizedState != "processing" {
|
||
t.Fatalf("R6 must keep an upstream-processing row: %#v", processing)
|
||
}
|
||
if missing, ok := r6["pub-b"]; !ok || missing.DocumentID != "doc-b" {
|
||
t.Fatalf("R6 must keep a row the scan could not list: %#v", missing)
|
||
}
|
||
if store.completedRun == nil || store.completedRun.Counts["R6"] != len(store.removal) {
|
||
t.Fatalf("run counts R6 = %#v", store.completedRun)
|
||
}
|
||
}
|
||
|
||
// TestCreateRunEnqueuesJobWithinJobIDLimit freezes the queue contract: jobs.id is
|
||
// VARCHAR(36), and the run id ("rec-" + 32 hex) already fills it. Deriving the job
|
||
// id from the run id overflowed the column, so every batch was created `failed`
|
||
// with queue_unavailable before a worker ever saw it.
|
||
func TestCreateRunEnqueuesJobWithinJobIDLimit(t *testing.T) {
|
||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||
store := &fakeReconciliationStore{
|
||
run: governance.ReconciliationRun{ID: "rec-unused", KBID: "kb-1", State: "running", Trigger: "manual", StartedAt: now},
|
||
}
|
||
service, err := New(Config{Store: store, Queue: store, Remote: &fakeReconciliationRemote{},
|
||
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,
|
||
WeKnoraWebBase: func(context.Context) string { return "https://test.example/" }})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
run, err := service.CreateRun(context.Background(), "kb-1", "manual")
|
||
if err != nil {
|
||
t.Fatalf("CreateRun error = %v", err)
|
||
}
|
||
if len(store.enqueued) != 1 {
|
||
t.Fatalf("enqueued %d jobs", len(store.enqueued))
|
||
}
|
||
request := store.enqueued[0]
|
||
if len(request.ID) != 36 {
|
||
t.Fatalf("job id %q length = %d, want exactly 36 (VARCHAR(36))", request.ID, len(request.ID))
|
||
}
|
||
if request.Type != "reconciliation.run" || request.IdempotencyKey != "reconciliation-run:"+run.ID {
|
||
t.Fatalf("enqueue request = %#v", request)
|
||
}
|
||
if string(request.Payload) != `{"run_id":"`+run.ID+`"}` {
|
||
t.Fatalf("payload = %s", request.Payload)
|
||
}
|
||
}
|
||
|
||
type failingRuntime struct{ err error }
|
||
|
||
func (runtime failingRuntime) DocumentProgress(context.Context, string) (governance.ReconciliationProgress, error) {
|
||
return governance.ReconciliationProgress{}, runtime.err
|
||
}
|
||
|
||
// Progress must not re-collapse the provider's classification: the page needs
|
||
// "no binding", "no permission" and "unreachable" to stay distinct.
|
||
func TestProgressPreservesClassifiedRuntimeErrors(t *testing.T) {
|
||
cases := []struct {
|
||
name string
|
||
err error
|
||
want error
|
||
}{
|
||
{name: "unavailable", err: ErrRuntimeUnavailable, want: ErrRuntimeUnavailable},
|
||
{name: "forbidden", err: ErrRuntimeForbidden, want: ErrRuntimeForbidden},
|
||
{name: "unreachable", err: ErrRuntimeUnreachable, want: ErrRuntimeUnreachable},
|
||
{name: "not found", err: &weknora.HTTPError{StatusCode: http.StatusNotFound}, want: ErrNotFound},
|
||
{name: "unclassified", err: errors.New("boom"), want: ErrRuntimeUnavailable},
|
||
}
|
||
for _, testCase := range cases {
|
||
t.Run(testCase.name, func(t *testing.T) {
|
||
service, err := New(Config{
|
||
Store: &fakeReconciliationStore{}, Remote: &fakeReconciliationRemote{},
|
||
Runtime: failingRuntime{err: testCase.err},
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if _, err := service.Progress(context.Background(), "doc-1"); !errors.Is(err, testCase.want) {
|
||
t.Fatalf("Progress err = %v, want %v", err, testCase.want)
|
||
}
|
||
})
|
||
}
|
||
}
|