feat(reconciliation): 实现导入对账后端

为什么:T6a 需要一张批次/差异表、全量只读扫描、R1-R8 判定和 finding 级处置;现有解析监控只转述台账状态,无法回答库内是否一致。
做什么:迁移 000084(upload_md5、runs/findings/actions、共享 removal_candidates 视图);WeKnora 字段与 1000/页扫描;runtime 只读客户端(0400 Key、503 降级);扫描/矩阵/动作/定时/僵死回收;9 条接口与 RBAC;overview 队列与删两张常量卡。
边界:只对测试库;对账零写请求;R1/R2 单条确认;R6 复用 /removal;R2 只管理员;生产链路未改。
验证:make verify 全绿(17 项);新增矩阵/扫描 R1-R8/零写/失败整批/动作/运行时/密钥权限测试。
This commit is contained in:
Zhero & Rin
2026-12-01 12:19:54 +08:00
committed by 姚章浩
parent 580695ca2e
commit 4528a55e6a
43 changed files with 3661 additions and 122 deletions
+115
View File
@@ -0,0 +1,115 @@
package reconciliation
import "knowledge-governance/internal/governance"
type verdict int
const (
verdictSkip verdict = iota
verdictConsistent
verdictMismatch
verdictStalled
verdictDeleting
)
// classify is the single 7x7 matrix. Rows are ledger vocabulary, columns are
// normalized WeKnora parse_status. Unknown upstream values are rejected by the
// caller before this function, so there is deliberately no "other" branch.
func classify(ledger, upstream string) verdict {
switch ledger {
case "planned":
if upstream == "deleting" {
return verdictDeleting
}
return verdictMismatch
case "pending":
switch upstream {
case "pending":
return verdictConsistent
case "deleting":
return verdictDeleting
default:
return verdictMismatch
}
case "processing":
switch upstream {
case "processing":
return verdictConsistent
case "deleting":
return verdictDeleting
default:
return verdictMismatch
}
case "finalizing":
switch upstream {
case "finalizing":
return verdictConsistent
case "deleting":
return verdictDeleting
default:
return verdictMismatch
}
case "completed":
switch upstream {
case "completed":
return verdictConsistent
case "deleting":
return verdictDeleting
default:
return verdictMismatch
}
case "failed":
switch upstream {
case "failed":
return verdictConsistent
case "deleting":
return verdictDeleting
default:
return verdictMismatch
}
case "stalled":
switch upstream {
case "completed":
return verdictMismatch
case "deleting":
return verdictDeleting
default:
return verdictStalled
}
case "cancelled":
switch upstream {
case "cancelled":
return verdictConsistent
case "deleting":
return verdictDeleting
default:
return verdictMismatch
}
default:
return verdictSkip
}
}
// AllowedWriteback is the only writeback migration table. completed cannot be
// downgraded; planned is not a target; cancelled/deleting have no ledger
// counterpart.
func AllowedWriteback(current, target string) bool {
switch current {
case "pending":
return target == "processing" || target == "finalizing" || target == "completed" || target == "failed"
case "processing":
return target == "finalizing" || target == "completed" || target == "failed"
case "finalizing":
return target == "completed" || target == "failed"
case "failed":
return target == "pending" || target == "processing" || target == "completed"
case "stalled":
return target == "pending" || target == "processing" || target == "failed"
default:
return false
}
}
func normalizeParseStatus(status string) (string, bool) {
return governance.NormalizeWeKnoraParseStatus(status)
}
+137
View File
@@ -0,0 +1,137 @@
package reconciliation
import (
"context"
"strings"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/platform/weknora"
)
type RuntimeConfig struct {
BaseURL func(context.Context) string
APIKey string
Timeout time.Duration
AllowDockerHTTP bool
AllowPrivateHTTP bool
Now func() time.Time
}
type RuntimeProvider struct {
baseURL func(context.Context) string
apiKey string
timeout time.Duration
allowDockerHTTP bool
allowPrivateHTTP bool
now func() time.Time
}
func NewRuntimeProvider(config RuntimeConfig) *RuntimeProvider {
if config.Now == nil {
config.Now = time.Now
}
return &RuntimeProvider{
baseURL: config.BaseURL, apiKey: strings.TrimSpace(config.APIKey), timeout: config.Timeout,
allowDockerHTTP: config.AllowDockerHTTP, allowPrivateHTTP: config.AllowPrivateHTTP, now: config.Now,
}
}
func (p *RuntimeProvider) Available() bool {
return p != nil && p.apiKey != "" && p.baseURL != nil
}
func (p *RuntimeProvider) client(ctx context.Context) (*weknora.RuntimeClient, error) {
if !p.Available() {
return nil, ErrRuntimeUnavailable
}
baseURL := strings.TrimSpace(p.baseURL(ctx))
if baseURL == "" {
return nil, ErrRuntimeUnavailable
}
client, err := weknora.NewRuntimeClient(weknora.RuntimeClientConfig{
BaseURL: baseURL,
APIKey: p.apiKey,
Timeout: p.timeout,
AllowDockerHTTP: p.allowDockerHTTP,
AllowPrivateHTTP: p.allowPrivateHTTP,
})
if err != nil {
return nil, ErrRuntimeUnavailable
}
return client, nil
}
func (p *RuntimeProvider) Queues(ctx context.Context) (*governance.WeKnoraQueueSummary, error) {
client, err := p.client(ctx)
if err != nil {
return nil, err
}
// The overview must not hang for the full business timeout just because the
// queue endpoint is slow; a short probe is enough to decide null vs data.
queueCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
queues, err := client.Queues(queueCtx)
if err != nil {
return nil, ErrRuntimeUnavailable
}
summary := &governance.WeKnoraQueueSummary{
Available: queues.Available, QueuesError: queues.QueuesError, WorkersError: queues.WorkersError,
Queues: make([]governance.WeKnoraQueue, 0, len(queues.Queues)), Timestamp: queues.Timestamp,
}
for _, queue := range queues.Queues {
summary.Queues = append(summary.Queues, governance.WeKnoraQueue{
Name: queue.Name, Pool: queue.Pool, Pending: queue.Pending, Active: queue.Active,
Scheduled: queue.Scheduled, Retry: queue.Retry, Archived: queue.Archived,
Processed: queue.Processed, Failed: queue.Failed,
})
}
return summary, nil
}
func (p *RuntimeProvider) DocumentProgress(ctx context.Context, documentID string) (governance.ReconciliationProgress, error) {
client, err := p.client(ctx)
if err != nil {
return governance.ReconciliationProgress{}, err
}
detail, err := client.DocumentProgress(ctx, documentID)
if err != nil {
if weknora.IsNotFound(err) {
return governance.ReconciliationProgress{}, err
}
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
}
progress := governance.ReconciliationProgress{
DocumentID: detail.Document.ID, ParseStatus: detail.Document.ParseStatus,
IngestionStatus: detail.Document.IngestionStatus, WikiStatus: detail.Document.WikiStatus,
HasMoreFailures: detail.HasMoreFailures, ObservedAt: p.now().UTC(),
Stages: make([]governance.ReconciliationStage, 0, len(detail.Document.Stages)),
Failures: make([]governance.ReconciliationFailure, 0, len(detail.Failures)),
}
if progress.DocumentID == "" {
progress.DocumentID = documentID
}
for _, stage := range detail.Document.Stages {
progress.Stages = append(progress.Stages, governance.ReconciliationStage{
Name: stage.Name, Status: stage.Status, ErrorCode: stage.ErrorCode, FinishedAt: stage.FinishedAt,
})
}
for _, failure := range detail.Failures {
progress.Failures = append(progress.Failures, governance.ReconciliationFailure{
TaskType: failure.TaskType, FailCount: failure.FailCount, FailedAt: failure.FailedAt,
LastError: truncateRunes(failure.LastError, 500),
})
}
return progress, nil
}
func truncateRunes(value string, limit int) string {
if limit <= 0 {
return ""
}
runes := []rune(value)
if len(runes) <= limit {
return value
}
return string(runes[:limit])
}
+70
View File
@@ -0,0 +1,70 @@
package reconciliation
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/platform/weknora"
)
func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-API-Key") != "runtime-key" {
t.Fatalf("missing runtime key header")
}
switch r.URL.Path {
case "/api/v1/system/admin/runtime/queues":
_ = json.NewEncoder(w).Encode(map[string]any{
"available": true, "queues_error": false, "workers_error": false, "timestamp": 7,
"queues": []map[string]any{{"name": "default", "pool": "core", "pending": 3, "active": 1, "failed": 2}},
})
case "/api/v1/system/admin/runtime/documents/doc-1":
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{
"document": map[string]any{"id": "doc-1", "parse_status": "failed", "ingestion_status": "failed", "wiki_status": "none",
"stages": []map[string]any{{"name": "parse", "status": "failed", "error_code": "x"}}},
"failures": []map[string]any{{"task_type": "parse", "fail_count": 2, "failed_at": "2026-12-01T00:00:00Z", "last_error": strings.Repeat("错", 600)}},
"has_more_failures": false,
}})
default:
http.NotFound(w, r)
}
}))
defer server.Close()
provider := NewRuntimeProvider(RuntimeConfig{
BaseURL: func(context.Context) string { return server.URL },
APIKey: "runtime-key", Timeout: 5 * time.Second,
})
queues, err := provider.Queues(context.Background())
if err != nil || !queues.Available || len(queues.Queues) != 1 || queues.Queues[0].Pending != 3 {
t.Fatalf("queues=%#v err=%v", queues, err)
}
progress, err := provider.DocumentProgress(context.Background(), "doc-1")
if err != nil || progress.ParseStatus != "failed" || progress.DocumentID != "doc-1" || len(progress.Stages) != 1 {
t.Fatalf("progress=%#v err=%v", progress, err)
}
if len([]rune(progress.Failures[0].LastError)) != 500 {
t.Fatalf("last_error runes = %d", len([]rune(progress.Failures[0].LastError)))
}
}
func TestRuntimeProviderUnavailableAndNotFound(t *testing.T) {
unavailable := NewRuntimeProvider(RuntimeConfig{BaseURL: func(context.Context) string { return "https://example.test" }})
if _, err := unavailable.Queues(context.Background()); !errors.Is(err, ErrRuntimeUnavailable) {
t.Fatalf("unconfigured queues err=%v", err)
}
server := httptest.NewServer(http.NotFoundHandler())
defer server.Close()
provider := NewRuntimeProvider(RuntimeConfig{
BaseURL: func(context.Context) string { return server.URL },
APIKey: "runtime-key", Timeout: 5 * time.Second,
})
if _, err := provider.DocumentProgress(context.Background(), "missing"); err == nil || weknora.StatusCode(err) != 404 {
t.Fatalf("missing document err=%v", err)
}
}
+479
View File
@@ -0,0 +1,479 @@
package reconciliation
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"sort"
"strings"
"sync"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/platform/weknora"
)
const scanPageSize = 1000
type confirmResult struct {
item weknora.Knowledge
notFound bool
err error
}
func (s *Service) scanKnowledge(ctx context.Context, kbID string) ([]weknora.Knowledge, error) {
seen := make(map[string]bool)
out := make([]weknora.Knowledge, 0)
for page := 1; page <= 10000; page++ {
items, total, err := s.remote.ListKnowledge(ctx, kbID, page, scanPageSize)
if err != nil {
return nil, ErrRemoteFailed
}
added := 0
for _, item := range items {
if item.ID == "" {
return nil, ErrRemoteFailed
}
if item.KnowledgeBaseID != "" && item.KnowledgeBaseID != kbID {
return nil, ErrRemoteFailed
}
if seen[item.ID] {
continue
}
seen[item.ID] = true
out = append(out, item)
added++
}
if len(items) == 0 || added == 0 || len(items) < scanPageSize {
break
}
if total > 0 && int64(len(seen)) >= total {
break
}
}
return out, nil
}
// confirmAll performs the "先确认再判缺" single reads. The scan phase itself is
// strictly serial; only this stage may use the configured concurrency.
func (s *Service) confirmAll(ctx context.Context, kbID string, ids []string) map[string]confirmResult {
results := make(map[string]confirmResult, len(ids))
if len(ids) == 0 {
return results
}
type outcome struct {
id string
result confirmResult
}
jobs := make(chan string)
outcomes := make(chan outcome, len(ids))
ctx, cancel := context.WithCancel(ctx)
defer cancel()
workers := s.confirmConcurrency
if workers > len(ids) {
workers = len(ids)
}
var wait sync.WaitGroup
for i := 0; i < workers; i++ {
wait.Add(1)
go func() {
defer wait.Done()
for id := range jobs {
if ctx.Err() != nil {
return
}
item, err := s.remote.GetKnowledge(ctx, id)
result := confirmResult{item: item, err: err}
if weknora.IsNotFound(err) {
result = confirmResult{notFound: true}
} else if err == nil && item.KnowledgeBaseID != "" && item.KnowledgeBaseID != kbID {
result = confirmResult{err: ErrRemoteFailed}
}
select {
case outcomes <- outcome{id: id, result: result}:
case <-ctx.Done():
return
}
}
}()
}
go func() {
defer close(jobs)
for _, id := range ids {
select {
case jobs <- id:
case <-ctx.Done():
return
}
}
}()
go func() {
wait.Wait()
close(outcomes)
}()
for outcome := range outcomes {
results[outcome.id] = outcome.result
if outcome.result.err != nil {
cancel()
}
}
return results
}
func (s *Service) buildFindings(ctx context.Context, run governance.ReconciliationRun, ledger []governance.ReconciliationLedgerRow, items []weknora.Knowledge, overlapped bool) ([]governance.ReconciliationFinding, error) {
byID := make(map[string]weknora.Knowledge, len(items))
ledgerByPublication := make(map[string]governance.ReconciliationLedgerRow, len(ledger))
ledgerByKnowledge := make(map[string]governance.ReconciliationLedgerRow, len(ledger))
for _, item := range items {
byID[item.ID] = item
}
for _, row := range ledger {
ledgerByPublication[row.PublicationID] = row
if row.KnowledgeID != "" {
if _, exists := ledgerByKnowledge[row.KnowledgeID]; !exists {
ledgerByKnowledge[row.KnowledgeID] = row
}
}
}
findings := make([]governance.ReconciliationFinding, 0, len(ledger)+len(items)/10)
add := func(finding governance.ReconciliationFinding) {
finding.RunID = run.ID
if finding.ConfirmationState == "" {
finding.ConfirmationState = "confirmed"
}
finding.ActionState = "open"
finding.ID = deterministicFindingID(run.ID, finding)
findings = append(findings, finding)
}
// R1: expected live but absent from the full listing. A list miss is not
// evidence; only a single GET 404 is.
missing := make([]string, 0)
seenMissing := map[string]bool{}
for _, row := range ledger {
if !expectedLive(row) {
continue
}
if _, ok := byID[row.KnowledgeID]; ok {
continue
}
if !seenMissing[row.KnowledgeID] {
seenMissing[row.KnowledgeID] = true
missing = append(missing, row.KnowledgeID)
}
}
confirmations := s.confirmAll(ctx, run.KBID, missing)
for _, row := range ledger {
if !expectedLive(row) {
continue
}
if _, ok := byID[row.KnowledgeID]; ok {
continue
}
result, ok := confirmations[row.KnowledgeID]
if !ok {
return nil, ErrRemoteFailed
}
if result.err != nil {
return nil, ErrRemoteFailed
}
if result.notFound {
confirmation := "confirmed"
if overlapped {
confirmation = "pending"
}
add(governance.ReconciliationFinding{
Type: "R1", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
LedgerState: row.ProcessingState, LedgerSHA256: row.SHA256,
EvidenceLevel: "none", ConfirmationState: confirmation, SuggestedAction: "requeue_upload",
Detail: "台账认为应在库,单条读取返回 404",
})
continue
}
// The row exists but the list hid it (deleting). Use it for matrix checks.
byID[row.KnowledgeID] = result.item
}
// R2: governance-imported item with no current ledger row pointing at it.
orphans := make([]weknora.Knowledge, 0)
orphanIDs := make([]string, 0)
for _, item := range items {
if item.Channel != "governance" {
continue
}
publicationID := metadataString(item.Metadata, "publication_id")
if publicationID != "" {
if _, ok := ledgerByPublication[publicationID]; ok {
continue
}
}
if _, ok := ledgerByKnowledge[item.ID]; ok {
continue
}
orphans = append(orphans, item)
orphanIDs = append(orphanIDs, item.ID)
}
orphanConfirmations := s.confirmAll(ctx, run.KBID, orphanIDs)
for _, item := range orphans {
result, ok := orphanConfirmations[item.ID]
if !ok {
return nil, ErrRemoteFailed
}
if result.err != nil {
return nil, ErrRemoteFailed
}
if result.notFound || result.item.ParseStatus == "deleting" {
continue
}
publicationID := metadataString(item.Metadata, "publication_id")
if publicationID != "" {
if _, ok := ledgerByPublication[publicationID]; ok {
continue
}
}
if _, ok := ledgerByKnowledge[item.ID]; ok {
continue
}
confirmation := "confirmed"
if overlapped {
confirmation = "pending"
}
add(governance.ReconciliationFinding{
Type: "R2", PublicationID: publicationID, DocumentID: item.ID,
Title: item.Title, Path: item.FolderPath, Source: item.Source, TargetScope: "unknown",
WeKnoraParseState: item.ParseStatus, NormalizedState: item.ParseStatus,
WeKnoraFileMD5: normalizeMD5(item.FileHash), EvidenceLevel: "none",
ConfirmationState: confirmation, SuggestedAction: "remove_from_test",
Detail: "库内平台导入条目没有现行台账行指向它",
})
}
// R3: not imported by the platform.
for _, item := range items {
if item.Channel == "governance" {
continue
}
add(governance.ReconciliationFinding{
Type: "R3", DocumentID: item.ID, Title: item.Title, Path: item.FolderPath,
Source: item.Source, TargetScope: "unknown", WeKnoraParseState: item.ParseStatus,
NormalizedState: item.ParseStatus, WeKnoraFileMD5: normalizeMD5(item.FileHash),
EvidenceLevel: "none", SuggestedAction: "none", Detail: "非平台导入条目,仅统计",
})
}
removal, err := s.store.ListReconciliationRemovalCandidates(ctx, run.KBID)
if err != nil {
return nil, err
}
removalByPublication := make(map[string]bool, len(removal))
for _, row := range removal {
removalByPublication[row.PublicationID] = true
}
for _, row := range ledger {
if !expectedLive(row) {
continue
}
item, ok := byID[row.KnowledgeID]
if !ok {
continue
}
upstream, known := normalizeParseStatus(item.ParseStatus)
if !known {
return nil, fmt.Errorf("unsupported WeKnora parse status %q", item.ParseStatus)
}
normalized := upstream
if item.ParseStatus == "deleting" {
if age(run.StartedAt, item.UpdatedAt) > s.stallAfter {
add(r7Finding(row, item, "删除超过阈值仍未完成"))
}
continue
}
if finding, ok := s.r4Finding(row, item, normalized); ok {
add(finding)
}
if removalByPublication[row.PublicationID] && item.ParseStatus == "completed" {
add(governance.ReconciliationFinding{
Type: "R6", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus, NormalizedState: normalized,
LedgerSHA256: row.SHA256, EvidenceLevel: "none", SuggestedAction: "enter_removal",
Detail: "来源已判禁止导入,条目仍在测试库可检索",
})
}
if row.ProcessingState == "cancelled" {
if normalized != "cancelled" && ageFromPointer(run.StartedAt, row.ProcessingStartedAt, row.UpdatedAt) >= s.grace {
add(r5Finding(row, item, normalized, "none", "台账已取消,WeKnora 仍有活动状态"))
}
continue
}
verdict := classify(row.ProcessingState, normalized)
stuckAge := ageFromPointer(run.StartedAt, row.ProcessingStartedAt, row.UpdatedAt)
switch verdict {
case verdictStalled:
add(r7Finding(row, item, "台账或上游已判定停滞"))
case verdictDeleting:
if age(run.StartedAt, item.UpdatedAt) > s.stallAfter {
add(r7Finding(row, item, "删除超过阈值仍未完成"))
}
case verdictMismatch:
if (normalized == "pending" || normalized == "processing" || normalized == "finalizing") && stuckAge > s.stallAfter {
add(r7Finding(row, item, "超过阈值没有进展"))
continue
}
if item.StallState == "stalled" {
add(r7Finding(row, item, "WeKnora 判定停滞"))
continue
}
if ageFromPointer(run.StartedAt, row.ProcessingStartedAt, row.UpdatedAt) < s.grace {
continue
}
action := "writeback_state"
if !AllowedWriteback(row.ProcessingState, normalized) {
action = "none"
}
add(r5Finding(row, item, normalized, action, ""))
case verdictConsistent:
if item.StallState == "stalled" {
add(r7Finding(row, item, "WeKnora 判定停滞"))
} else if (normalized == "pending" || normalized == "processing") && stuckAge > s.stallAfter {
add(r7Finding(row, item, "超过阈值没有进展"))
}
}
}
// R8: one publication id maps to more than one live row.
grouped := make(map[string][]weknora.Knowledge)
for _, item := range items {
if item.Channel != "governance" || item.ParseStatus == "failed" || item.ParseStatus == "deleting" {
continue
}
publicationID := metadataString(item.Metadata, "publication_id")
if publicationID == "" {
continue
}
grouped[publicationID] = append(grouped[publicationID], item)
}
for publicationID, group := range grouped {
if len(group) < 2 {
continue
}
first := group[0]
add(governance.ReconciliationFinding{
Type: "R8", PublicationID: publicationID, DocumentID: first.ID,
Title: first.Title, Path: first.FolderPath, Source: first.Source, TargetScope: "unknown",
WeKnoraParseState: first.ParseStatus, NormalizedState: first.ParseStatus,
WeKnoraFileMD5: normalizeMD5(first.FileHash), EvidenceLevel: "none", SuggestedAction: "none",
Detail: fmt.Sprintf("同一台账发布标识对应 %d 条存活条目", len(group)),
})
}
sort.Slice(findings, func(i, j int) bool {
if findings[i].Type != findings[j].Type {
return findings[i].Type < findings[j].Type
}
if findings[i].PublicationID != findings[j].PublicationID {
return findings[i].PublicationID < findings[j].PublicationID
}
return findings[i].DocumentID < findings[j].DocumentID
})
return findings, nil
}
func (s *Service) r4Finding(row governance.ReconciliationLedgerRow, item weknora.Knowledge, normalized string) (governance.ReconciliationFinding, bool) {
declared := strings.ToLower(metadataString(item.Metadata, "content_sha256"))
ledgerSHA := strings.ToLower(row.SHA256)
uploadMD5 := normalizeMD5(row.UploadMD5)
fileMD5 := normalizeMD5(item.FileHash)
evidence := "none"
if declared != "" && ledgerSHA != "" {
evidence = "declared_only"
if uploadMD5 != "" && fileMD5 != "" {
evidence = "independent"
}
}
if evidence == "none" {
return governance.ReconciliationFinding{}, false
}
mismatch := declared != ledgerSHA
if evidence == "independent" && uploadMD5 != fileMD5 {
mismatch = true
}
if !mismatch {
return governance.ReconciliationFinding{}, false
}
return governance.ReconciliationFinding{
Type: "R4", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus, NormalizedState: normalized,
LedgerSHA256: ledgerSHA, DeclaredSHA256: declared, WeKnoraFileMD5: fileMD5,
EvidenceLevel: evidence, SuggestedAction: "requeue_upload",
Detail: "库内内容摘要与台账现行版本不一致",
}, true
}
func r5Finding(row governance.ReconciliationLedgerRow, item weknora.Knowledge, normalized, action, detail string) governance.ReconciliationFinding {
if detail == "" {
detail = fmt.Sprintf("台账状态 %s 与 WeKnora %s 不一致,已超过宽限期", row.ProcessingState, normalized)
}
return governance.ReconciliationFinding{
Type: "R5", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus, NormalizedState: normalized,
LedgerSHA256: row.SHA256, EvidenceLevel: "none", SuggestedAction: action, Detail: detail,
}
}
func r7Finding(row governance.ReconciliationLedgerRow, item weknora.Knowledge, detail string) governance.ReconciliationFinding {
return governance.ReconciliationFinding{
Type: "R7", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus,
NormalizedState: item.ParseStatus, LedgerSHA256: row.SHA256, EvidenceLevel: "none",
SuggestedAction: "none", Detail: detail,
}
}
func expectedLive(row governance.ReconciliationLedgerRow) bool {
return row.KnowledgeID != "" && row.ProcessingState != "failed" &&
row.RetrievalState != "disabling" && row.RetrievalState != "disabled"
}
func age(startedAt, updatedAt time.Time) time.Duration {
if updatedAt.IsZero() || startedAt.Before(updatedAt) {
return 0
}
return startedAt.Sub(updatedAt)
}
func ageFromPointer(startedAt time.Time, processingStartedAt *time.Time, updatedAt time.Time) time.Duration {
if processingStartedAt != nil && !processingStartedAt.IsZero() {
return age(startedAt, *processingStartedAt)
}
return age(startedAt, updatedAt)
}
func metadataString(metadata map[string]any, key string) string {
value, _ := metadata[key].(string)
return value
}
func normalizeMD5(value string) string {
value = strings.ToLower(strings.TrimSpace(value))
if len(value) != 32 {
return ""
}
for _, char := range value {
if (char < '0' || char > '9') && (char < 'a' || char > 'f') {
return ""
}
}
return value
}
func deterministicFindingID(runID string, finding governance.ReconciliationFinding) string {
digest := sha256.Sum256([]byte(runID + "\x00" + finding.Type + "\x00" + finding.PublicationID + "\x00" + finding.DocumentID))
return "rcf-" + hex.EncodeToString(digest[:])[:24]
}
+447
View File
@@ -0,0 +1,447 @@
package reconciliation
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
)
var (
ErrRunInProgress = errors.New("reconciliation run in progress")
ErrNotFound = errors.New("reconciliation record not found")
ErrActionConflict = errors.New("reconciliation state or identity changed")
ErrActionNotAllowed = errors.New("reconciliation action not allowed")
ErrRemoteFailed = errors.New("reconciliation remote call failed")
ErrRuntimeUnavailable = errors.New("weknora runtime read unavailable")
)
type Store interface {
ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error)
ClaimReconciliationRun(context.Context, governance.ReconciliationRun, time.Time) (governance.ReconciliationRun, error)
ClaimScheduledReconciliationRun(context.Context, governance.ReconciliationRun, time.Time, time.Time) (governance.ReconciliationRun, bool, error)
LoadReconciliationRun(context.Context, string) (governance.ReconciliationRun, error)
ListReconciliationRuns(context.Context, governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error)
ListReconciliationFindings(context.Context, governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error)
GetReconciliationFinding(context.Context, string) (governance.ReconciliationFinding, error)
LoadReconciliationLedger(context.Context, string) ([]governance.ReconciliationLedgerRow, error)
LoadPreviousReconciliationCounts(context.Context, string, time.Time) (governance.ReconciliationCounts, bool, error)
CompleteReconciliationRun(context.Context, governance.ReconciliationRun, []governance.ReconciliationFinding) error
FailReconciliationRun(context.Context, string, string, time.Time) error
CleanupReconciliationFindings(context.Context, time.Time, int, time.Duration) error
LibraryJobsActive(context.Context) (bool, error)
ListReconciliationRemovalCandidates(context.Context, string) ([]governance.ReconciliationLedgerRow, error)
LoadReconciliationActionView(context.Context, string) (governance.ReconciliationActionView, error)
ReconciliationOrphanStillUnowned(context.Context, string, string) (bool, error)
WritebackReconciliationFinding(context.Context, string, string, string, string, time.Time) (governance.ReconciliationFinding, error)
RequeueReconciliationPublication(context.Context, string, string, string, string, time.Time) (string, error)
MarkReconciliationOrphanRemoved(context.Context, string, string, string, time.Time) error
}
type Remote interface {
BeginTask(context.Context, string) (context.Context, weknora.InstanceIdentity, error)
ListKnowledge(context.Context, string, int, int) ([]weknora.Knowledge, int64, error)
GetKnowledge(context.Context, string) (weknora.Knowledge, error)
DeleteKnowledge(context.Context, string) error
}
type Runtime interface {
DocumentProgress(context.Context, string) (governance.ReconciliationProgress, error)
}
type Queue interface {
Enqueue(context.Context, jobs.EnqueueRequest, time.Time) (*jobs.Job, error)
}
type Config struct {
Store Store
Remote Remote
Runtime Runtime
Queue Queue
Now func() time.Time
Grace time.Duration
StallAfter time.Duration
StaleAfter time.Duration
ConfirmConcurrency int
KeepRuns int
MaxAge time.Duration
}
type Service struct {
store Store
remote Remote
runtime Runtime
queue Queue
now func() time.Time
grace time.Duration
stallAfter time.Duration
staleAfter time.Duration
confirmConcurrency int
keepRuns int
maxAge time.Duration
}
func New(config Config) (*Service, error) {
if config.Store == nil || config.Remote == nil {
return nil, errors.New("reconciliation store and remote client are required")
}
if config.Now == nil {
config.Now = time.Now
}
if config.Grace <= 0 {
config.Grace = 30 * time.Minute
}
if config.StallAfter <= 0 {
config.StallAfter = 2 * time.Hour
}
if config.StaleAfter <= 0 {
config.StaleAfter = 6 * time.Hour
}
if config.ConfirmConcurrency < 1 {
config.ConfirmConcurrency = 1
}
if config.ConfirmConcurrency > 8 {
config.ConfirmConcurrency = 8
}
if config.KeepRuns < 1 {
config.KeepRuns = 30
}
if config.MaxAge <= 0 {
config.MaxAge = 90 * 24 * time.Hour
}
return &Service{
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,
}, nil
}
func newID(prefix string) (string, error) {
var value [16]byte
if _, err := rand.Read(value[:]); err != nil {
return "", err
}
return prefix + hex.EncodeToString(value[:]), nil
}
func (s *Service) CreateRun(ctx context.Context, kbID, trigger string) (governance.ReconciliationRun, error) {
if kbID == "" || len(kbID) > 255 {
return governance.ReconciliationRun{}, errors.New("invalid test knowledge base")
}
now := s.now().UTC()
if _, err := s.store.ReapStaleReconciliationRuns(ctx, now, s.staleAfter); err != nil {
return governance.ReconciliationRun{}, err
}
id, err := newID("rec-")
if err != nil {
return governance.ReconciliationRun{}, err
}
run, err := s.store.ClaimReconciliationRun(ctx, governance.ReconciliationRun{
ID: id, KBID: kbID, State: "running", Trigger: trigger, StartedAt: now,
Counts: governance.ReconciliationCounts{},
}, now)
if err != nil {
if errors.Is(err, postgresstore.ErrReconciliationRunInProgress) {
return governance.ReconciliationRun{}, ErrRunInProgress
}
return governance.ReconciliationRun{}, err
}
if s.queue == nil {
_ = s.store.FailReconciliationRun(ctx, id, "queue_unavailable", now)
return governance.ReconciliationRun{}, errors.New("reconciliation queue is not configured")
}
if err := s.enqueueRun(ctx, run.ID, now); err != nil {
_ = s.store.FailReconciliationRun(ctx, run.ID, "queue_unavailable", now)
return governance.ReconciliationRun{}, err
}
return run, nil
}
// ScheduleDue claims one scheduled batch per test KB per local day. The caller
// computes `since` as today's configured wall-clock instant in the configured
// timezone; this method only enforces the claim and enqueue.
func (s *Service) ScheduleDue(ctx context.Context, kbIDs []string, since, now time.Time) (int, error) {
if _, err := s.store.ReapStaleReconciliationRuns(ctx, now, s.staleAfter); err != nil {
return 0, err
}
created := 0
seen := map[string]bool{}
for _, kbID := range kbIDs {
if kbID == "" || seen[kbID] {
continue
}
seen[kbID] = true
id, err := newID("rec-")
if err != nil {
return created, err
}
run, claimed, err := s.store.ClaimScheduledReconciliationRun(ctx, governance.ReconciliationRun{
ID: id, KBID: kbID, State: "running", Trigger: "schedule", StartedAt: now,
Counts: governance.ReconciliationCounts{},
}, since, now)
if err != nil {
return created, err
}
if !claimed {
continue
}
if err := s.enqueueRun(ctx, run.ID, now); err != nil {
_ = s.store.FailReconciliationRun(ctx, run.ID, "queue_unavailable", now)
return created, err
}
created++
}
return created, nil
}
func (s *Service) enqueueRun(ctx context.Context, runID string, now time.Time) error {
if s.queue == nil {
return errors.New("reconciliation queue is not configured")
}
payload, err := json.Marshal(map[string]string{"run_id": runID})
if err != nil {
return err
}
_, err = s.queue.Enqueue(ctx, jobs.EnqueueRequest{
ID: "job-" + runID,
Type: "reconciliation.run",
Payload: payload,
Priority: 5,
AvailableAt: now,
MaxAttempts: 1,
IdempotencyKey: "reconciliation-run:" + runID,
}, now)
return err
}
func (s *Service) ExecuteRun(ctx context.Context, runID string) error {
run, err := s.store.LoadReconciliationRun(ctx, runID)
if err != nil {
return err
}
if run.State != "running" {
return nil
}
finished := func(code string) error {
if code == "" {
return nil
}
return s.store.FailReconciliationRun(context.WithoutCancel(ctx), run.ID, code, s.now().UTC())
}
pinned, _, err := s.remote.BeginTask(ctx, run.KBID)
if err != nil {
return finished("remote_unavailable")
}
ledger, err := s.store.LoadReconciliationLedger(pinned, run.KBID)
if err != nil {
return finished("ledger_unavailable")
}
overlappedStart, err := s.store.LibraryJobsActive(pinned)
if err != nil {
return finished("overlap_check_failed")
}
items, err := s.scanKnowledge(pinned, run.KBID)
if err != nil {
if errors.Is(err, ErrRemoteFailed) {
return finished("remote_scan_failed")
}
return finished("scan_failed")
}
overlappedEnd, err := s.store.LibraryJobsActive(pinned)
if err != nil {
return finished("overlap_check_failed")
}
overlapped := overlappedStart || overlappedEnd
findings, err := s.buildFindings(pinned, run, ledger, items, overlapped)
if err != nil {
if errors.Is(err, ErrRemoteFailed) {
return finished("remote_confirm_failed")
}
return finished("scan_failed")
}
previous, hasPrevious, err := s.store.LoadPreviousReconciliationCounts(pinned, run.KBID, run.StartedAt)
if err != nil {
return finished("previous_counts_failed")
}
counts := governance.ReconciliationCounts{}
for _, finding := range findings {
counts[finding.Type]++
}
run.Counts = counts.Normalize()
if hasPrevious {
run.PreviousCounts = previous
}
run.LedgerCount = len(ledger)
run.KBCount = len(items)
run.WindowOverlapped = overlapped
finishedAt := s.now().UTC()
run.FinishedAt = &finishedAt
if err := s.store.CompleteReconciliationRun(pinned, run, findings); err != nil {
return finished("complete_failed")
}
_ = s.store.CleanupReconciliationFindings(context.WithoutCancel(ctx), s.now().UTC(), s.keepRuns, s.maxAge)
return nil
}
func (s *Service) ListRuns(ctx context.Context, filter governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) {
return s.store.ListReconciliationRuns(ctx, filter)
}
func (s *Service) GetRun(ctx context.Context, id string) (governance.ReconciliationRun, error) {
run, err := s.store.LoadReconciliationRun(ctx, id)
if errors.Is(err, postgresstore.ErrReconciliationNotFound) {
return governance.ReconciliationRun{}, ErrNotFound
}
return run, err
}
func (s *Service) ListFindings(ctx context.Context, filter governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) {
return s.store.ListReconciliationFindings(ctx, filter)
}
func (s *Service) Progress(ctx context.Context, documentID string) (governance.ReconciliationProgress, error) {
if s.runtime == nil {
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
}
progress, err := s.runtime.DocumentProgress(ctx, documentID)
switch {
case err == nil:
return progress, nil
case weknora.StatusCode(err) == 404:
return governance.ReconciliationProgress{}, ErrNotFound
default:
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
}
}
func (s *Service) Writeback(ctx context.Context, findingID, actor, reason string) (governance.ReconciliationFinding, error) {
view, err := s.actionView(ctx, findingID)
if err != nil {
return governance.ReconciliationFinding{}, err
}
if view.Finding.ActionState == "done" {
return view.Finding, nil
}
target := view.Finding.NormalizedState
if view.Finding.Type != "R5" || !AllowedWriteback(view.Finding.LedgerState, target) {
return governance.ReconciliationFinding{}, ErrActionNotAllowed
}
finding, err := s.store.WritebackReconciliationFinding(ctx, findingID, target, actor, trim(reason), s.now().UTC())
if errors.Is(err, postgresstore.ErrReconciliationConflict) {
return governance.ReconciliationFinding{}, ErrActionConflict
}
return finding, err
}
func (s *Service) Requeue(ctx context.Context, findingID, actor, reason string) (governance.ReconciliationFinding, error) {
view, err := s.actionView(ctx, findingID)
if err != nil {
return governance.ReconciliationFinding{}, err
}
if view.Finding.ActionState == "done" {
return view.Finding, nil
}
if view.Finding.Type != "R1" && view.Finding.Type != "R4" {
return governance.ReconciliationFinding{}, ErrActionNotAllowed
}
if view.Finding.DocumentID == "" {
return governance.ReconciliationFinding{}, ErrActionConflict
}
item, getErr := s.remote.GetKnowledge(ctx, view.Finding.DocumentID)
switch {
case getErr == nil:
if view.Finding.Type == "R1" {
// R1 said 404; if it is back now, a human must decide again.
return governance.ReconciliationFinding{}, ErrActionConflict
}
if item.KnowledgeBaseID != view.TestKBID {
return governance.ReconciliationFinding{}, ErrActionConflict
}
// R4 must remove the stale object first. Only a successful delete (or
// 404, handled below) allows the ledger reset.
if err := s.remote.DeleteKnowledge(ctx, view.Finding.DocumentID); err != nil && !weknora.IsNotFound(err) {
return governance.ReconciliationFinding{}, ErrRemoteFailed
}
case weknora.IsNotFound(getErr):
// R1/R4 both proceed: the old object is already gone.
default:
return governance.ReconciliationFinding{}, ErrRemoteFailed
}
if _, err := s.store.RequeueReconciliationPublication(ctx, findingID, view.Finding.DocumentID, actor, trim(reason), s.now().UTC()); err != nil {
if errors.Is(err, postgresstore.ErrReconciliationConflict) {
return governance.ReconciliationFinding{}, ErrActionConflict
}
return governance.ReconciliationFinding{}, err
}
return s.reloadFinding(ctx, findingID)
}
func (s *Service) Remove(ctx context.Context, findingID, actor, reason string) (governance.ReconciliationFinding, error) {
view, err := s.actionView(ctx, findingID)
if err != nil {
return governance.ReconciliationFinding{}, err
}
if view.Finding.ActionState == "done" {
return view.Finding, nil
}
if view.Finding.Type != "R2" || view.Finding.DocumentID == "" {
return governance.ReconciliationFinding{}, ErrActionNotAllowed
}
orphan, err := s.store.ReconciliationOrphanStillUnowned(ctx, view.Finding.PublicationID, view.Finding.DocumentID)
if err != nil {
return governance.ReconciliationFinding{}, err
}
if !orphan {
return governance.ReconciliationFinding{}, ErrActionConflict
}
item, err := s.remote.GetKnowledge(ctx, view.Finding.DocumentID)
if err != nil {
if !weknora.IsNotFound(err) {
return governance.ReconciliationFinding{}, ErrRemoteFailed
}
} else {
if item.KnowledgeBaseID != view.TestKBID {
return governance.ReconciliationFinding{}, ErrActionConflict
}
if err := s.remote.DeleteKnowledge(ctx, view.Finding.DocumentID); err != nil && !weknora.IsNotFound(err) {
return governance.ReconciliationFinding{}, ErrRemoteFailed
}
}
if err := s.store.MarkReconciliationOrphanRemoved(ctx, findingID, actor, trim(reason), s.now().UTC()); err != nil {
if errors.Is(err, postgresstore.ErrReconciliationConflict) {
return governance.ReconciliationFinding{}, ErrActionConflict
}
return governance.ReconciliationFinding{}, err
}
return s.reloadFinding(ctx, findingID)
}
func (s *Service) actionView(ctx context.Context, findingID string) (governance.ReconciliationActionView, error) {
view, err := s.store.LoadReconciliationActionView(ctx, findingID)
if errors.Is(err, postgresstore.ErrReconciliationNotFound) {
return view, ErrNotFound
}
return view, err
}
func (s *Service) reloadFinding(ctx context.Context, id string) (governance.ReconciliationFinding, error) {
finding, err := s.store.GetReconciliationFinding(ctx, id)
if errors.Is(err, postgresstore.ErrReconciliationNotFound) {
return finding, ErrNotFound
}
return finding, err
}
func trim(value string) string {
if len(value) > 500 {
return value[:500]
}
return value
}
+334
View File
@@ -0,0 +1,334 @@
package reconciliation
import (
"context"
"errors"
"testing"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/platform/weknora"
)
func TestMatrixCoversEveryLedgerAndUpstreamState(t *testing.T) {
rows := []string{"planned", "pending", "processing", "finalizing", "completed", "failed", "stalled", "cancelled"}
columns := []string{"pending", "processing", "finalizing", "completed", "failed", "cancelled", "deleting"}
for _, row := range rows {
for _, column := range columns {
verdict := classify(row, column)
if verdict == verdictSkip && row != "" {
t.Fatalf("classify(%s,%s) unexpectedly skipped", row, column)
}
if row == "completed" && column == "completed" && verdict != verdictConsistent {
t.Fatalf("completed/completed = %v", verdict)
}
if row == "stalled" && column == "completed" && verdict != verdictMismatch {
t.Fatalf("stalled/completed = %v", verdict)
}
if column == "deleting" && verdict != verdictDeleting {
t.Fatalf("%s/deleting = %v", row, verdict)
}
}
}
if classify("completed", "pending") != verdictMismatch || classify("cancelled", "cancelled") != verdictConsistent {
t.Fatal("explicit completed/cancelled rows are wrong")
}
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
}
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
}
type fakeReconciliationRemote struct {
items []weknora.Knowledge
missing map[string]bool
gets map[string]weknora.Knowledge
listErr error
pageSizes []int
deleteCalls int
listInFlight int
maxInFlight int
}
func (f *fakeReconciliationRemote) BeginTask(ctx context.Context, _ string) (context.Context, weknora.InstanceIdentity, error) {
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"}},
}
remote := &fakeReconciliationRemote{
items: items, missing: map[string]bool{"doc-r1": true},
gets: map[string]weknora.Knowledge{"doc-r2": items[0]},
}
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})
if err != nil {
t.Fatal(err)
}
if err := service.ExecuteRun(context.Background(), "run-1"); err != nil {
t.Fatal(err)
}
if store.completedRun == nil {
t.Fatal("run was not completed")
}
if remote.deleteCalls != 0 {
t.Fatalf("reconciliation wrote remotely: %d", remote.deleteCalls)
}
if len(remote.pageSizes) == 0 || remote.pageSizes[0] != scanPageSize {
t.Fatalf("page size = %v, want %d", remote.pageSizes, scanPageSize)
}
if remote.maxInFlight != 1 {
t.Fatalf("scan in-flight peak = %d, want 1", remote.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)
}
}
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)
}
}