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:
@@ -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]
|
||||
}
|
||||
Reference in New Issue
Block a user