095aa3ed68
build / build (push) Failing after 26s
- 为什么:白盒复检 P1——平台侧文件详情抽屉 503 只有文案,需求 §8 要求跳转链接;/monitor/tasks 行没有 URL。 - 做什么:抽出 KnowledgeBaseConsoleURL,finding 与 /monitor/tasks 共用同一拼接;handler 用当前生效测试端点填 weknora_url,前端抽屉透传给 WeKnoraProgress;openapi/需求 §7 同步。 - 补证据:stage=weknora 真库合并用例;对账扫描改为真实 HTTP 桩断言零写;progress 投影断言上游密钥字段不外泄。 - 验证:make verify 17 项 success;go test ./... exit 0;web 648 测试 + build;monitor_tasks 真库集成用例 PASS。
491 lines
16 KiB
Go
491 lines
16 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
|
|
}
|
|
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(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]
|
|
}
|