082f77fc18
build / build (push) Successful in 2m28s
白盒补充复核提出的三项: - P1 R6 与 /monitor/overview「需下架」计数口径不一致:R6 原先只在扫描结果里存在 且上游 parse_status=completed 时才生成,上游仍在 processing/finalizing 或单条读取 失败导致扫描缺行时,总览有数、对账无记录(陷阱 15)。改为直接由 removal_candidates 视图行生成,台账细节按 publication 回填,计数与总览同一来源;补单测覆盖 「上游 processing」「扫描未见」两种差异。 - P2 定时批失败后每个 tick 都重建:每日占位只排除 running/succeeded,failed 不占位, 一次失败当天会每分钟刷批。占位条件加入 failed,重跑改为显式手动触发;补 PG 集成用例。 - P2 队列不可用时前端显示 0 等待 · 0 运行:改为按 available 判定并显示不可用文案; 补组件用例。
523 lines
17 KiB
Go
523 lines
17 KiB
Go
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 {
|
|
break
|
|
}
|
|
if total > 0 {
|
|
if int64(len(seen)) >= total {
|
|
break
|
|
}
|
|
// Keep paging even if the instance returned a smaller page than
|
|
// requested; only the reported total ends the scan.
|
|
continue
|
|
}
|
|
if len(items) < scanPageSize {
|
|
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)
|
|
if finding.WeKnoraURL == "" && s.weKnoraWebBase != nil {
|
|
finding.WeKnoraURL = weknora.KnowledgeBaseConsoleURL(s.weKnoraWebBase(ctx), run.KBID)
|
|
}
|
|
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
|
|
}
|
|
// 「需下架」的台账细节沿用上面按 publication 建的台账索引。
|
|
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 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, "超过阈值没有进展"))
|
|
}
|
|
}
|
|
}
|
|
|
|
// R6: 应下架仍在。判定口径 = removal_candidates 视图(与 /monitor/overview 的
|
|
// 「需下架」共用同一实现,陷阱 15)。这里直接由视图行生成,不再附加「本轮扫描
|
|
// 见到该条目」「上游 parse_status=completed」这类只有对账侧才有的条件——上游仍在
|
|
// processing/finalizing、或单条读取失败导致扫描缺行时,两处数字就会永久不一致。
|
|
for _, row := range removal {
|
|
finding := governance.ReconciliationFinding{
|
|
Type: "R6", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
|
|
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
|
|
// 视图只收录 processing_state='completed' 的台账行。
|
|
LedgerState: "completed", EvidenceLevel: "none", SuggestedAction: "enter_removal",
|
|
Detail: "来源已判禁止导入,条目仍在测试库可检索",
|
|
}
|
|
if own, ok := ledgerByPublication[row.PublicationID]; ok {
|
|
if finding.DocumentID == "" {
|
|
finding.DocumentID = own.KnowledgeID
|
|
}
|
|
if finding.Title == "" {
|
|
finding.Title = own.Title
|
|
}
|
|
if finding.Path == "" {
|
|
finding.Path = own.Path
|
|
}
|
|
if finding.Source == "" {
|
|
finding.Source = own.SourceName
|
|
}
|
|
if finding.TargetScope == "" {
|
|
finding.TargetScope = own.TargetScope
|
|
}
|
|
if own.ProcessingState != "" {
|
|
finding.LedgerState = own.ProcessingState
|
|
}
|
|
finding.LedgerSHA256 = own.SHA256
|
|
}
|
|
if item, ok := byID[finding.DocumentID]; ok {
|
|
if normalized, known := normalizeParseStatus(item.ParseStatus); known {
|
|
finding.NormalizedState = normalized
|
|
}
|
|
finding.WeKnoraParseState = item.ParseStatus
|
|
finding.WeKnoraFileMD5 = normalizeMD5(item.FileHash)
|
|
} else if finding.DocumentID != "" {
|
|
finding.Detail = "来源已判禁止导入;本轮扫描未见该条目,计数仍与总览「需下架」一致"
|
|
}
|
|
add(finding)
|
|
}
|
|
|
|
// 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(strings.TrimSpace(metadataString(item.Metadata, "content_sha256")))
|
|
ledgerSHA := strings.ToLower(strings.TrimSpace(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]
|
|
}
|