feat: 知识治理平台(含已验证发布/回滚契约)
全栈知识治理平台首次入库(P1-P10 + 发布链路模拟验证闭环): - 治理核心:源目录/变更集/人工审核/发布批次/发布执行(fail-closed 闸口) - 测试通道:WeKnora 测试 KB 上传/轮询/验收;poll 完成时写入 parser_generation/index_generation,修复 manual/seed 路径发布闸口永久拦截 - 发布适配器 v071(本地 source=测试角色 / 云端 target=生产角色 模拟验证通过): * ES 导出/导入 mapping 自适应(.keyword 子字段、可选 tenant_id) * OSS locator 支持嵌套 scheme;chunks.seq_id 由目标序列分配 * bundle 归档同身份重试原子替换;verifier 按 bundle chunk_type 计数 * 回滚 job payload 支持 prior_execution_id(strict 解码) - 三通道发布+回滚演练实测:publish 4/4 verified,检索命中, rollback 4/4 rolled_back,目标端 PG is_enabled=false、ES is_enabled=false - 前端 A·Data-console 风格全站统一,120 用例通过 - 门禁:go vet / go test 全包通过,gofmt 干净
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
package pp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
type LegacyStatus string
|
||||
|
||||
const (
|
||||
StatusCompleted LegacyStatus = "completed"
|
||||
StatusContentAlias LegacyStatus = "content_alias"
|
||||
StatusOverLimit LegacyStatus = "over_limit"
|
||||
)
|
||||
|
||||
type Item struct {
|
||||
KBID string `json:"kb_id"`
|
||||
SourceURLHash string `json:"source_url_hash"`
|
||||
SourceIDs []string `json:"source_ids"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status LegacyStatus `json:"status"`
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
CanonicalSourceURLHash string `json:"canonical_source_url_hash"`
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
KBID string
|
||||
EventCount int
|
||||
UnresolvedCount int
|
||||
Items []Item
|
||||
}
|
||||
|
||||
func FoldLedger(reader io.Reader) (Snapshot, error) {
|
||||
scanner := bufio.NewScanner(reader)
|
||||
scanner.Buffer(make([]byte, 64*1024), 1024*1024)
|
||||
terminal := make(map[string]Item)
|
||||
seen := make(map[string]struct{})
|
||||
result := Snapshot{}
|
||||
for scanner.Scan() {
|
||||
result.EventCount++
|
||||
var item Item
|
||||
if err := json.Unmarshal(scanner.Bytes(), &item); err != nil {
|
||||
return Snapshot{}, fmt.Errorf("decode ledger line %d: %w", result.EventCount, err)
|
||||
}
|
||||
if result.KBID == "" {
|
||||
result.KBID = item.KBID
|
||||
} else if item.KBID != result.KBID {
|
||||
return Snapshot{}, fmt.Errorf("ledger contains multiple knowledge bases at line %d", result.EventCount)
|
||||
}
|
||||
if item.SourceURLHash != "" {
|
||||
seen[item.SourceURLHash] = struct{}{}
|
||||
}
|
||||
if item.Status == StatusCompleted || (item.Status == StatusContentAlias && item.KnowledgeID != "") {
|
||||
if err := validateTerminalItem(item); err != nil {
|
||||
return Snapshot{}, fmt.Errorf("invalid terminal ledger record at line %d: %w", result.EventCount, err)
|
||||
}
|
||||
terminal[item.SourceURLHash] = item
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return Snapshot{}, fmt.Errorf("read ledger: %w", err)
|
||||
}
|
||||
result.Items = make([]Item, 0, len(terminal))
|
||||
for _, item := range terminal {
|
||||
result.Items = append(result.Items, item)
|
||||
}
|
||||
result.UnresolvedCount = len(seen) - len(terminal)
|
||||
sort.Slice(result.Items, func(i, j int) bool {
|
||||
return result.Items[i].SourceURLHash < result.Items[j].SourceURLHash
|
||||
})
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func validateTerminalItem(item Item) error {
|
||||
if item.KBID == "" {
|
||||
return fmt.Errorf("kb_id is required")
|
||||
}
|
||||
if !governance.ValidSHA256(item.SourceURLHash) {
|
||||
return fmt.Errorf("source_url_hash must be a canonical hash")
|
||||
}
|
||||
if len(item.SourceIDs) == 0 {
|
||||
return fmt.Errorf("source_ids are required")
|
||||
}
|
||||
for _, sourceID := range item.SourceIDs {
|
||||
if sourceID == "" {
|
||||
return fmt.Errorf("source_ids cannot contain an empty value")
|
||||
}
|
||||
}
|
||||
if item.Bytes < 0 {
|
||||
return fmt.Errorf("bytes cannot be negative")
|
||||
}
|
||||
if item.SHA256 != "" && !governance.ValidSHA256(item.SHA256) {
|
||||
return fmt.Errorf("sha256 must be empty or a canonical hash")
|
||||
}
|
||||
if item.KnowledgeID == "" {
|
||||
return fmt.Errorf("knowledge_id is required")
|
||||
}
|
||||
if item.Status == StatusContentAlias && !governance.ValidSHA256(item.CanonicalSourceURLHash) {
|
||||
return fmt.Errorf("canonical_source_url_hash must be a canonical hash")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateSnapshot(snapshot Snapshot) error {
|
||||
if snapshot.UnresolvedCount != 0 {
|
||||
return fmt.Errorf("snapshot contains %d unresolved source keys", snapshot.UnresolvedCount)
|
||||
}
|
||||
bySourceHash := make(map[string]Item, len(snapshot.Items))
|
||||
for _, item := range snapshot.Items {
|
||||
if item.Status == StatusOverLimit {
|
||||
if item.Bytes <= LegacyMaxBytes {
|
||||
return fmt.Errorf("over-limit item does not exceed the legacy size limit")
|
||||
}
|
||||
bySourceHash[item.SourceURLHash] = item
|
||||
continue
|
||||
}
|
||||
if !governance.ValidSHA256(item.SHA256) {
|
||||
return fmt.Errorf("snapshot item is missing a verified SHA-256")
|
||||
}
|
||||
bySourceHash[item.SourceURLHash] = item
|
||||
}
|
||||
for _, item := range snapshot.Items {
|
||||
if item.Status != StatusContentAlias {
|
||||
continue
|
||||
}
|
||||
canonical, ok := bySourceHash[item.CanonicalSourceURLHash]
|
||||
if !ok || canonical.Status != StatusCompleted {
|
||||
return fmt.Errorf("alias does not reference a canonical completed item")
|
||||
}
|
||||
if item.SHA256 != canonical.SHA256 || item.KnowledgeID != canonical.KnowledgeID {
|
||||
return fmt.Errorf("alias metadata does not match canonical completed item")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package pp
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFoldLedgerKeepsLatestTerminalRecordPerSourceURLHash(t *testing.T) {
|
||||
sourceA := strings.Repeat("a", 64)
|
||||
sourceB := strings.Repeat("b", 64)
|
||||
sha := strings.Repeat("c", 64)
|
||||
ledger := strings.Join([]string{
|
||||
`{"kb_id":"kb-1","source_url_hash":"` + sourceA + `","source_ids":["pp-1"],"bytes":10,"sha256":"` + sha + `","status":"uploaded","knowledge_id":"knowledge-old"}`,
|
||||
`{"kb_id":"kb-1","source_url_hash":"` + sourceA + `","source_ids":["pp-1"],"bytes":10,"sha256":"` + sha + `","status":"completed","knowledge_id":"knowledge-1"}`,
|
||||
`{"kb_id":"kb-1","source_url_hash":"` + sourceA + `","source_ids":["pp-1"],"bytes":10,"sha256":"` + sha + `","status":"parse_timeout","knowledge_id":"knowledge-1"}`,
|
||||
`{"kb_id":"kb-1","source_url_hash":"` + sourceB + `","source_ids":["pp-2"],"bytes":10,"sha256":"` + sha + `","status":"content_alias","knowledge_id":"knowledge-1","canonical_source_url_hash":"` + sourceA + `"}`,
|
||||
}, "\n")
|
||||
|
||||
snapshot, err := FoldLedger(strings.NewReader(ledger))
|
||||
if err != nil {
|
||||
t.Fatalf("FoldLedger() error = %v", err)
|
||||
}
|
||||
if snapshot.EventCount != 4 || snapshot.KBID != "kb-1" || len(snapshot.Items) != 2 {
|
||||
t.Fatalf("FoldLedger() snapshot = %#v", snapshot)
|
||||
}
|
||||
if snapshot.Items[0].SourceURLHash != sourceA || snapshot.Items[0].Status != StatusCompleted || snapshot.Items[0].KnowledgeID != "knowledge-1" {
|
||||
t.Fatalf("completed item = %#v", snapshot.Items[0])
|
||||
}
|
||||
if snapshot.Items[1].SourceURLHash != sourceB || snapshot.Items[1].Status != StatusContentAlias || snapshot.Items[1].CanonicalSourceURLHash != sourceA {
|
||||
t.Fatalf("alias item = %#v", snapshot.Items[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestFoldLedgerReportsUnresolvedSourceKeys(t *testing.T) {
|
||||
source := strings.Repeat("a", 64)
|
||||
sha := strings.Repeat("c", 64)
|
||||
ledger := `{"kb_id":"kb-1","source_url_hash":"` + source + `","source_ids":["pp-1"],"bytes":10,"sha256":"` + sha + `","status":"uploaded","knowledge_id":"knowledge-1"}`
|
||||
|
||||
snapshot, err := FoldLedger(strings.NewReader(ledger))
|
||||
if err != nil {
|
||||
t.Fatalf("FoldLedger() error = %v", err)
|
||||
}
|
||||
if snapshot.UnresolvedCount != 1 {
|
||||
t.Fatalf("UnresolvedCount = %d, want 1", snapshot.UnresolvedCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSnapshotRejectsUnresolvedSourceKeys(t *testing.T) {
|
||||
err := ValidateSnapshot(Snapshot{KBID: "kb-1", UnresolvedCount: 1})
|
||||
if err == nil || !strings.Contains(err.Error(), "unresolved") {
|
||||
t.Fatalf("ValidateSnapshot() error = %v, want unresolved source error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFoldLedgerRejectsMixedKnowledgeBases(t *testing.T) {
|
||||
sourceA := strings.Repeat("a", 64)
|
||||
sourceB := strings.Repeat("b", 64)
|
||||
sha := strings.Repeat("c", 64)
|
||||
ledger := strings.Join([]string{
|
||||
`{"kb_id":"kb-1","source_url_hash":"` + sourceA + `","source_ids":["pp-1"],"bytes":10,"sha256":"` + sha + `","status":"completed","knowledge_id":"knowledge-1"}`,
|
||||
`{"kb_id":"kb-2","source_url_hash":"` + sourceB + `","source_ids":["pp-2"],"bytes":10,"sha256":"` + sha + `","status":"completed","knowledge_id":"knowledge-2"}`,
|
||||
}, "\n")
|
||||
|
||||
_, err := FoldLedger(strings.NewReader(ledger))
|
||||
if err == nil || !strings.Contains(err.Error(), "multiple knowledge bases") {
|
||||
t.Fatalf("FoldLedger() error = %v, want mixed knowledge base error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFoldLedgerRejectsInvalidTerminalSourceHash(t *testing.T) {
|
||||
sha := strings.Repeat("c", 64)
|
||||
ledger := `{"kb_id":"kb-1","source_url_hash":"not-a-hash","source_ids":["pp-1"],"bytes":10,"sha256":"` + sha + `","status":"completed","knowledge_id":"knowledge-1"}`
|
||||
|
||||
_, err := FoldLedger(strings.NewReader(ledger))
|
||||
if err == nil || !strings.Contains(err.Error(), "source_url_hash") {
|
||||
t.Fatalf("FoldLedger() error = %v, want source hash validation error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFoldLedgerRejectsIncompleteTerminalRecord(t *testing.T) {
|
||||
source := strings.Repeat("a", 64)
|
||||
sha := strings.Repeat("c", 64)
|
||||
tests := []struct {
|
||||
name string
|
||||
ledger string
|
||||
}{
|
||||
{"missing knowledge base", `{"source_url_hash":"` + source + `","source_ids":["pp-1"],"bytes":10,"sha256":"` + sha + `","status":"completed","knowledge_id":"knowledge-1"}`},
|
||||
{"missing source IDs", `{"kb_id":"kb-1","source_url_hash":"` + source + `","source_ids":[],"bytes":10,"sha256":"` + sha + `","status":"completed","knowledge_id":"knowledge-1"}`},
|
||||
{"negative bytes", `{"kb_id":"kb-1","source_url_hash":"` + source + `","source_ids":["pp-1"],"bytes":-1,"sha256":"` + sha + `","status":"completed","knowledge_id":"knowledge-1"}`},
|
||||
{"invalid optional SHA", `{"kb_id":"kb-1","source_url_hash":"` + source + `","source_ids":["pp-1"],"bytes":10,"sha256":"bad","status":"completed","knowledge_id":"knowledge-1"}`},
|
||||
{"missing knowledge ID", `{"kb_id":"kb-1","source_url_hash":"` + source + `","source_ids":["pp-1"],"bytes":10,"sha256":"` + sha + `","status":"completed"}`},
|
||||
{"missing alias canonical hash", `{"kb_id":"kb-1","source_url_hash":"` + source + `","source_ids":["pp-1"],"bytes":10,"sha256":"` + sha + `","status":"content_alias","knowledge_id":"knowledge-1"}`},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if _, err := FoldLedger(strings.NewReader(tt.ledger)); err == nil {
|
||||
t.Fatal("FoldLedger() error = nil, want terminal record validation error")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverMissingSHA256RequiresVerifiedManifestArtifact(t *testing.T) {
|
||||
content := []byte("verified PP artifact")
|
||||
contentDigest := sha256.Sum256(content)
|
||||
contentHash := hex.EncodeToString(contentDigest[:])
|
||||
url := "https://source.invalid/document"
|
||||
urlDigest := sha256.Sum256([]byte(url))
|
||||
sourceHash := hex.EncodeToString(urlDigest[:])
|
||||
path := filepath.Join(t.TempDir(), "document.bin")
|
||||
if err := os.WriteFile(path, content, 0o600); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
manifest := `{"results":[{"url":"` + url + `","local_path":"` + path + `","bytes":20,"sha256":"` + contentHash + `"}]}`
|
||||
snapshot := Snapshot{KBID: "kb-1", Items: []Item{{
|
||||
KBID: "kb-1",
|
||||
SourceURLHash: sourceHash,
|
||||
SourceIDs: []string{"pp-1"},
|
||||
Bytes: 20,
|
||||
Status: StatusCompleted,
|
||||
KnowledgeID: "knowledge-1",
|
||||
}}}
|
||||
|
||||
recovered, report, err := RecoverMissingSHA256(snapshot, strings.NewReader(manifest))
|
||||
if err != nil {
|
||||
t.Fatalf("RecoverMissingSHA256() error = %v", err)
|
||||
}
|
||||
if report.Recovered != 1 || report.VerifiedBytes != int64(len(content)) {
|
||||
t.Fatalf("RecoverMissingSHA256() report = %#v", report)
|
||||
}
|
||||
if recovered.Items[0].SHA256 != contentHash {
|
||||
t.Fatalf("recovered SHA256 = %q, want %q", recovered.Items[0].SHA256, contentHash)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverMissingSHA256RejectsArtifactOverLegacyLimit(t *testing.T) {
|
||||
url := "https://source.invalid/oversized"
|
||||
urlDigest := sha256.Sum256([]byte(url))
|
||||
sourceHash := hex.EncodeToString(urlDigest[:])
|
||||
contentHash := strings.Repeat("c", 64)
|
||||
oversized := int64(50*1024*1024 + 1)
|
||||
manifest := `{"results":[{"url":"` + url + `","local_path":"/not-opened","bytes":` + "52428801" + `,"sha256":"` + contentHash + `"}]}`
|
||||
snapshot := Snapshot{KBID: "kb-1", Items: []Item{{
|
||||
KBID: "kb-1",
|
||||
SourceURLHash: sourceHash,
|
||||
SourceIDs: []string{"pp-1"},
|
||||
Bytes: oversized,
|
||||
Status: StatusCompleted,
|
||||
KnowledgeID: "knowledge-1",
|
||||
}}}
|
||||
|
||||
_, _, err := RecoverMissingSHA256(snapshot, strings.NewReader(manifest))
|
||||
if err == nil || !strings.Contains(err.Error(), "50 MiB") {
|
||||
t.Fatalf("RecoverMissingSHA256() error = %v, want legacy size limit error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSnapshotRejectsAliasWithoutCanonicalCompletedItem(t *testing.T) {
|
||||
sourceAlias := strings.Repeat("b", 64)
|
||||
missingCanonical := strings.Repeat("a", 64)
|
||||
sha := strings.Repeat("c", 64)
|
||||
snapshot := Snapshot{KBID: "kb-1", Items: []Item{{
|
||||
KBID: "kb-1",
|
||||
SourceURLHash: sourceAlias,
|
||||
SourceIDs: []string{"pp-2"},
|
||||
Bytes: 10,
|
||||
SHA256: sha,
|
||||
Status: StatusContentAlias,
|
||||
KnowledgeID: "knowledge-1",
|
||||
CanonicalSourceURLHash: missingCanonical,
|
||||
}}}
|
||||
|
||||
err := ValidateSnapshot(snapshot)
|
||||
if err == nil || !strings.Contains(err.Error(), "canonical completed item") {
|
||||
t.Fatalf("ValidateSnapshot() error = %v, want missing canonical error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSnapshotRejectsAliasMetadataMismatch(t *testing.T) {
|
||||
sourceCanonical := strings.Repeat("a", 64)
|
||||
sourceAlias := strings.Repeat("b", 64)
|
||||
sha := strings.Repeat("c", 64)
|
||||
canonical := Item{KBID: "kb-1", SourceURLHash: sourceCanonical, SourceIDs: []string{"pp-1"}, Bytes: 10, SHA256: sha, Status: StatusCompleted, KnowledgeID: "knowledge-1"}
|
||||
alias := Item{KBID: "kb-1", SourceURLHash: sourceAlias, SourceIDs: []string{"pp-2"}, Bytes: 10, SHA256: sha, Status: StatusContentAlias, KnowledgeID: "knowledge-1", CanonicalSourceURLHash: sourceCanonical}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*Item)
|
||||
}{
|
||||
{"SHA mismatch", func(item *Item) { item.SHA256 = strings.Repeat("d", 64) }},
|
||||
{"knowledge mismatch", func(item *Item) { item.KnowledgeID = "knowledge-2" }},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
candidate := alias
|
||||
tt.mutate(&candidate)
|
||||
err := ValidateSnapshot(Snapshot{KBID: "kb-1", Items: []Item{canonical, candidate}})
|
||||
if err == nil || !strings.Contains(err.Error(), "alias metadata") {
|
||||
t.Fatalf("ValidateSnapshot() error = %v, want alias metadata error", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSnapshotRequiresRecoveredSHA256(t *testing.T) {
|
||||
source := strings.Repeat("a", 64)
|
||||
snapshot := Snapshot{KBID: "kb-1", Items: []Item{{
|
||||
KBID: "kb-1",
|
||||
SourceURLHash: source,
|
||||
SourceIDs: []string{"pp-1"},
|
||||
Bytes: 10,
|
||||
Status: StatusCompleted,
|
||||
KnowledgeID: "knowledge-1",
|
||||
}}}
|
||||
|
||||
err := ValidateSnapshot(snapshot)
|
||||
if err == nil || !strings.Contains(err.Error(), "verified SHA-256") {
|
||||
t.Fatalf("ValidateSnapshot() error = %v, want missing SHA error", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package pp
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
type RecoveryReport struct {
|
||||
Recovered int
|
||||
VerifiedBytes int64
|
||||
}
|
||||
|
||||
const LegacyMaxBytes int64 = 50 * 1024 * 1024
|
||||
|
||||
type manifestDocument struct {
|
||||
Results []manifestItem `json:"results"`
|
||||
}
|
||||
|
||||
type manifestItem struct {
|
||||
URL string `json:"url"`
|
||||
LocalPath string `json:"local_path"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
SourceIDs []string `json:"source_ids"`
|
||||
}
|
||||
|
||||
func RecoverMissingSHA256(snapshot Snapshot, reader io.Reader) (Snapshot, RecoveryReport, error) {
|
||||
var manifest manifestDocument
|
||||
if err := json.NewDecoder(reader).Decode(&manifest); err != nil {
|
||||
return Snapshot{}, RecoveryReport{}, fmt.Errorf("decode download manifest: %w", err)
|
||||
}
|
||||
bySourceHash := make(map[string]manifestItem, len(manifest.Results))
|
||||
for _, item := range manifest.Results {
|
||||
digest := sha256.Sum256([]byte(item.URL))
|
||||
bySourceHash[hex.EncodeToString(digest[:])] = item
|
||||
}
|
||||
|
||||
result := snapshot
|
||||
result.Items = append([]Item(nil), snapshot.Items...)
|
||||
report := RecoveryReport{}
|
||||
for index := range result.Items {
|
||||
item := &result.Items[index]
|
||||
if item.SHA256 != "" {
|
||||
continue
|
||||
}
|
||||
artifact, ok := bySourceHash[item.SourceURLHash]
|
||||
if !ok {
|
||||
return Snapshot{}, RecoveryReport{}, fmt.Errorf("missing manifest artifact for source hash %s", item.SourceURLHash)
|
||||
}
|
||||
if !governance.ValidSHA256(artifact.SHA256) {
|
||||
return Snapshot{}, RecoveryReport{}, fmt.Errorf("manifest artifact has invalid SHA-256 for source hash %s", item.SourceURLHash)
|
||||
}
|
||||
if artifact.Bytes != item.Bytes {
|
||||
return Snapshot{}, RecoveryReport{}, fmt.Errorf("manifest size differs from ledger for source hash %s", item.SourceURLHash)
|
||||
}
|
||||
if artifact.Bytes > LegacyMaxBytes {
|
||||
return Snapshot{}, RecoveryReport{}, fmt.Errorf("manifest artifact exceeds the legacy 50 MiB limit for source hash %s", item.SourceURLHash)
|
||||
}
|
||||
file, err := os.Open(artifact.LocalPath)
|
||||
if err != nil {
|
||||
return Snapshot{}, RecoveryReport{}, fmt.Errorf("open manifest artifact for source hash %s: %w", item.SourceURLHash, err)
|
||||
}
|
||||
digest := sha256.New()
|
||||
bytesRead, copyErr := io.Copy(digest, file)
|
||||
closeErr := file.Close()
|
||||
if copyErr != nil {
|
||||
return Snapshot{}, RecoveryReport{}, fmt.Errorf("hash manifest artifact for source hash %s: %w", item.SourceURLHash, copyErr)
|
||||
}
|
||||
if closeErr != nil {
|
||||
return Snapshot{}, RecoveryReport{}, fmt.Errorf("close manifest artifact for source hash %s: %w", item.SourceURLHash, closeErr)
|
||||
}
|
||||
if bytesRead != artifact.Bytes {
|
||||
return Snapshot{}, RecoveryReport{}, fmt.Errorf("manifest artifact size mismatch for source hash %s", item.SourceURLHash)
|
||||
}
|
||||
actual := hex.EncodeToString(digest.Sum(nil))
|
||||
if actual != artifact.SHA256 {
|
||||
return Snapshot{}, RecoveryReport{}, fmt.Errorf("manifest artifact SHA-256 mismatch for source hash %s", item.SourceURLHash)
|
||||
}
|
||||
item.SHA256 = actual
|
||||
report.Recovered++
|
||||
report.VerifiedBytes += bytesRead
|
||||
}
|
||||
return result, report, nil
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package pp
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
)
|
||||
|
||||
type OverLimitReport struct {
|
||||
Added int
|
||||
}
|
||||
|
||||
func MergeOverLimitManifest(snapshot Snapshot, reader io.Reader) (Snapshot, OverLimitReport, error) {
|
||||
var manifest manifestDocument
|
||||
if err := json.NewDecoder(reader).Decode(&manifest); err != nil {
|
||||
return Snapshot{}, OverLimitReport{}, fmt.Errorf("decode download manifest: %w", err)
|
||||
}
|
||||
|
||||
result := snapshot
|
||||
result.Items = append([]Item(nil), snapshot.Items...)
|
||||
seen := make(map[string]struct{}, len(result.Items))
|
||||
for _, item := range result.Items {
|
||||
seen[item.SourceURLHash] = struct{}{}
|
||||
}
|
||||
report := OverLimitReport{}
|
||||
for _, artifact := range manifest.Results {
|
||||
if artifact.Status != string(StatusOverLimit) {
|
||||
continue
|
||||
}
|
||||
if artifact.URL == "" || len(artifact.SourceIDs) == 0 || artifact.Bytes <= LegacyMaxBytes {
|
||||
return Snapshot{}, OverLimitReport{}, fmt.Errorf("invalid over-limit manifest record")
|
||||
}
|
||||
digest := sha256.Sum256([]byte(artifact.URL))
|
||||
sourceHash := hex.EncodeToString(digest[:])
|
||||
if _, exists := seen[sourceHash]; exists {
|
||||
continue
|
||||
}
|
||||
result.Items = append(result.Items, Item{
|
||||
KBID: snapshot.KBID,
|
||||
SourceURLHash: sourceHash,
|
||||
SourceIDs: append([]string(nil), artifact.SourceIDs...),
|
||||
Bytes: artifact.Bytes,
|
||||
Status: StatusOverLimit,
|
||||
})
|
||||
seen[sourceHash] = struct{}{}
|
||||
report.Added++
|
||||
}
|
||||
sort.Slice(result.Items, func(i, j int) bool {
|
||||
return result.Items[i].SourceURLHash < result.Items[j].SourceURLHash
|
||||
})
|
||||
return result, report, nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package pp
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMergeOverLimitManifestAddsBlockedSourceItem(t *testing.T) {
|
||||
canonicalSource := strings.Repeat("a", 64)
|
||||
contentHash := strings.Repeat("c", 64)
|
||||
url := "https://source.invalid/large-document"
|
||||
urlDigest := sha256.Sum256([]byte(url))
|
||||
overLimitSource := hex.EncodeToString(urlDigest[:])
|
||||
snapshot := Snapshot{KBID: "kb-1", Items: []Item{{
|
||||
KBID: "kb-1",
|
||||
SourceURLHash: canonicalSource,
|
||||
SourceIDs: []string{"pp-1"},
|
||||
Bytes: 20,
|
||||
SHA256: contentHash,
|
||||
Status: StatusCompleted,
|
||||
KnowledgeID: "knowledge-1",
|
||||
}}}
|
||||
manifest := `{"results":[` +
|
||||
`{"url":"https://source.invalid/existing","status":"existing","bytes":20,"source_ids":["pp-1"]},` +
|
||||
`{"url":"` + url + `","local_path":"/not-opened","status":"over_limit","bytes":52428801,"source_ids":["pp-2"]}` +
|
||||
`]}`
|
||||
|
||||
merged, report, err := MergeOverLimitManifest(snapshot, strings.NewReader(manifest))
|
||||
if err != nil {
|
||||
t.Fatalf("MergeOverLimitManifest() error = %v", err)
|
||||
}
|
||||
if report.Added != 1 {
|
||||
t.Fatalf("Added = %d, want 1", report.Added)
|
||||
}
|
||||
if len(merged.Items) != 2 {
|
||||
t.Fatalf("items = %d, want 2", len(merged.Items))
|
||||
}
|
||||
var blocked Item
|
||||
for _, item := range merged.Items {
|
||||
if item.SourceURLHash == overLimitSource {
|
||||
blocked = item
|
||||
}
|
||||
}
|
||||
if blocked.Status != StatusOverLimit || blocked.Bytes != 52428801 || blocked.SHA256 != "" {
|
||||
t.Fatalf("blocked item = %#v", blocked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSnapshotAcceptsOverLimitItemWithoutContentHash(t *testing.T) {
|
||||
snapshot := Snapshot{KBID: "kb-1", Items: []Item{{
|
||||
KBID: "kb-1",
|
||||
SourceURLHash: strings.Repeat("a", 64),
|
||||
SourceIDs: []string{"pp-1"},
|
||||
Bytes: LegacyMaxBytes + 1,
|
||||
Status: StatusOverLimit,
|
||||
}}}
|
||||
|
||||
if err := ValidateSnapshot(snapshot); err != nil {
|
||||
t.Fatalf("ValidateSnapshot() error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package pp
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
type ImportPlan struct {
|
||||
Connection governance.SourceConnection
|
||||
SourceItems []governance.SourceItem
|
||||
ContentObjects []governance.ContentObject
|
||||
Versions []governance.SourceItemVersion
|
||||
Publications []governance.Publication
|
||||
}
|
||||
|
||||
func BuildImportPlan(snapshot Snapshot) (ImportPlan, error) {
|
||||
if err := ValidateSnapshot(snapshot); err != nil {
|
||||
return ImportPlan{}, err
|
||||
}
|
||||
connectionID := stableID("sc", snapshot.KBID)
|
||||
plan := ImportPlan{
|
||||
Connection: governance.SourceConnection{
|
||||
ID: connectionID,
|
||||
Type: governance.SourceTypePP,
|
||||
Name: "PP legacy " + connectionID,
|
||||
SecretRef: "",
|
||||
Enabled: false,
|
||||
},
|
||||
SourceItems: make([]governance.SourceItem, 0, len(snapshot.Items)),
|
||||
ContentObjects: make([]governance.ContentObject, 0),
|
||||
Versions: make([]governance.SourceItemVersion, 0, len(snapshot.Items)),
|
||||
Publications: make([]governance.Publication, 0),
|
||||
}
|
||||
contentBySHA := make(map[string]governance.ContentObject)
|
||||
publicationByKnowledgeID := make(map[string]struct{})
|
||||
for _, item := range snapshot.Items {
|
||||
itemID := stableID("si", connectionID, item.SourceURLHash)
|
||||
sizeBytes := item.Bytes
|
||||
revision := item.SHA256
|
||||
if item.Status == StatusOverLimit {
|
||||
revision = metadataRevision(item)
|
||||
}
|
||||
plan.SourceItems = append(plan.SourceItems, governance.SourceItem{
|
||||
ID: itemID,
|
||||
SourceConnectionID: connectionID,
|
||||
StableExternalID: item.SourceURLHash,
|
||||
CanonicalURIHash: item.SourceURLHash,
|
||||
Title: "",
|
||||
ItemType: governance.ItemTypeDocument,
|
||||
SizeBytes: &sizeBytes,
|
||||
Revision: revision,
|
||||
Visibility: governance.VisibilityExternal,
|
||||
VisibilityOrigin: governance.VisibilityOriginPPPublicTag,
|
||||
SourceChange: governance.SourceChangeUnchanged,
|
||||
})
|
||||
|
||||
rawSummary := map[string]any{
|
||||
"legacy_status": item.Status,
|
||||
"source_ids": item.SourceIDs,
|
||||
}
|
||||
if item.Status == StatusContentAlias {
|
||||
rawSummary["canonical_source_url_hash"] = item.CanonicalSourceURLHash
|
||||
}
|
||||
rawJSON, err := json.Marshal(rawSummary)
|
||||
if err != nil {
|
||||
return ImportPlan{}, fmt.Errorf("marshal legacy record summary: %w", err)
|
||||
}
|
||||
versionID := stableID("sv", itemID, revision)
|
||||
if item.Status == StatusOverLimit {
|
||||
plan.Versions = append(plan.Versions, governance.SourceItemVersion{
|
||||
ID: versionID,
|
||||
SourceItemID: itemID,
|
||||
Revision: revision,
|
||||
ContentState: governance.ContentOverLimit,
|
||||
DownloadError: "legacy_50_mib_limit",
|
||||
RawRecordSummary: rawJSON,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
content, ok := contentBySHA[item.SHA256]
|
||||
if !ok {
|
||||
content = governance.ContentObject{
|
||||
ID: stableID("co", item.SHA256),
|
||||
SHA256: item.SHA256,
|
||||
SizeBytes: item.Bytes,
|
||||
State: governance.ContentVerified,
|
||||
}
|
||||
contentBySHA[item.SHA256] = content
|
||||
plan.ContentObjects = append(plan.ContentObjects, content)
|
||||
} else if content.SizeBytes != item.Bytes {
|
||||
return ImportPlan{}, fmt.Errorf("same SHA-256 has conflicting byte sizes")
|
||||
}
|
||||
|
||||
contentID := content.ID
|
||||
plan.Versions = append(plan.Versions, governance.SourceItemVersion{
|
||||
ID: versionID,
|
||||
SourceItemID: itemID,
|
||||
Revision: item.SHA256,
|
||||
ContentObjectID: &contentID,
|
||||
ContentState: governance.ContentVerified,
|
||||
RawRecordSummary: rawJSON,
|
||||
})
|
||||
if item.Status != StatusCompleted {
|
||||
continue
|
||||
}
|
||||
if _, exists := publicationByKnowledgeID[item.KnowledgeID]; exists {
|
||||
return ImportPlan{}, fmt.Errorf("completed records share a knowledge ID")
|
||||
}
|
||||
publicationByKnowledgeID[item.KnowledgeID] = struct{}{}
|
||||
plan.Publications = append(plan.Publications, governance.Publication{
|
||||
ID: stableID("tp", snapshot.KBID, item.KnowledgeID),
|
||||
SourceItemVersionID: versionID,
|
||||
TestKBID: snapshot.KBID,
|
||||
KnowledgeID: item.KnowledgeID,
|
||||
IngestState: governance.IngestUploaded,
|
||||
ProcessingState: governance.ProcessingCompleted,
|
||||
RetrievalState: governance.RetrievalUnpublished,
|
||||
})
|
||||
}
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
func stableID(prefix string, parts ...string) string {
|
||||
digest := sha256.New()
|
||||
for _, part := range parts {
|
||||
_, _ = digest.Write([]byte{0})
|
||||
_, _ = digest.Write([]byte(part))
|
||||
}
|
||||
return prefix + "-" + hex.EncodeToString(digest.Sum(nil))[:32]
|
||||
}
|
||||
|
||||
func metadataRevision(item Item) string {
|
||||
sourceIDs := append([]string(nil), item.SourceIDs...)
|
||||
sort.Strings(sourceIDs)
|
||||
parts := []string{item.SourceURLHash, strconv.FormatInt(item.Bytes, 10)}
|
||||
parts = append(parts, sourceIDs...)
|
||||
digest := sha256.New()
|
||||
for _, part := range parts {
|
||||
_, _ = digest.Write([]byte{0})
|
||||
_, _ = digest.Write([]byte(part))
|
||||
}
|
||||
return "metadata-sha256:" + hex.EncodeToString(digest.Sum(nil))
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package pp
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
func TestBuildImportPlanSharesAliasContentWithoutDuplicatePublication(t *testing.T) {
|
||||
sourceCanonical := strings.Repeat("a", 64)
|
||||
sourceAlias := strings.Repeat("b", 64)
|
||||
contentHash := strings.Repeat("c", 64)
|
||||
snapshot := Snapshot{KBID: "kb-1", Items: []Item{
|
||||
{KBID: "kb-1", SourceURLHash: sourceCanonical, SourceIDs: []string{"pp-1"}, Bytes: 10, SHA256: contentHash, Status: StatusCompleted, KnowledgeID: "knowledge-1"},
|
||||
{KBID: "kb-1", SourceURLHash: sourceAlias, SourceIDs: []string{"pp-2"}, Bytes: 10, SHA256: contentHash, Status: StatusContentAlias, KnowledgeID: "knowledge-1", CanonicalSourceURLHash: sourceCanonical},
|
||||
}}
|
||||
|
||||
plan, err := BuildImportPlan(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildImportPlan() error = %v", err)
|
||||
}
|
||||
if len(plan.SourceItems) != 2 || len(plan.Versions) != 2 || len(plan.ContentObjects) != 1 || len(plan.Publications) != 1 {
|
||||
t.Fatalf("BuildImportPlan() counts = items:%d versions:%d content:%d publications:%d", len(plan.SourceItems), len(plan.Versions), len(plan.ContentObjects), len(plan.Publications))
|
||||
}
|
||||
if plan.Connection.Enabled || plan.Connection.SecretRef != "" || plan.Connection.Type != governance.SourceTypePP {
|
||||
t.Fatalf("connection safety defaults = %#v", plan.Connection)
|
||||
}
|
||||
if plan.Publications[0].RetrievalState != governance.RetrievalUnpublished || plan.Publications[0].ProcessingState != governance.ProcessingCompleted {
|
||||
t.Fatalf("publication states = %#v", plan.Publications[0])
|
||||
}
|
||||
if *plan.Versions[0].ContentObjectID != plan.ContentObjects[0].ID || *plan.Versions[1].ContentObjectID != plan.ContentObjects[0].ID {
|
||||
t.Fatal("canonical and alias versions must reference the same content object")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildImportPlanMapsOverLimitWithoutContentOrPublication(t *testing.T) {
|
||||
snapshot := Snapshot{KBID: "kb-1", Items: []Item{{
|
||||
KBID: "kb-1",
|
||||
SourceURLHash: strings.Repeat("a", 64),
|
||||
SourceIDs: []string{"pp-1"},
|
||||
Bytes: LegacyMaxBytes + 1,
|
||||
Status: StatusOverLimit,
|
||||
}}}
|
||||
|
||||
plan, err := BuildImportPlan(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildImportPlan() error = %v", err)
|
||||
}
|
||||
if len(plan.SourceItems) != 1 || len(plan.Versions) != 1 || len(plan.ContentObjects) != 0 || len(plan.Publications) != 0 {
|
||||
t.Fatalf("plan counts = source:%d version:%d content:%d publication:%d", len(plan.SourceItems), len(plan.Versions), len(plan.ContentObjects), len(plan.Publications))
|
||||
}
|
||||
if !strings.HasPrefix(plan.SourceItems[0].Revision, "metadata-sha256:") {
|
||||
t.Fatalf("source revision = %q, want metadata revision", plan.SourceItems[0].Revision)
|
||||
}
|
||||
version := plan.Versions[0]
|
||||
if version.ContentObjectID != nil || version.ContentState != governance.ContentOverLimit || version.DownloadError != "legacy_50_mib_limit" {
|
||||
t.Fatalf("over-limit version = %#v", version)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package pp
|
||||
|
||||
import "fmt"
|
||||
|
||||
type CurrentItem struct {
|
||||
Revision string
|
||||
}
|
||||
|
||||
type ReconciliationSummary struct {
|
||||
Unchanged int
|
||||
Adopted int
|
||||
OverLimit int
|
||||
UploadRequired int
|
||||
}
|
||||
|
||||
func PlanReconciliation(snapshot Snapshot, current map[string]CurrentItem) (ReconciliationSummary, error) {
|
||||
if err := ValidateSnapshot(snapshot); err != nil {
|
||||
return ReconciliationSummary{}, fmt.Errorf("validate reconciliation snapshot: %w", err)
|
||||
}
|
||||
summary := ReconciliationSummary{}
|
||||
for _, item := range snapshot.Items {
|
||||
if item.Status == StatusOverLimit {
|
||||
summary.OverLimit++
|
||||
continue
|
||||
}
|
||||
stored, exists := current[item.SourceURLHash]
|
||||
if !exists {
|
||||
summary.Adopted++
|
||||
continue
|
||||
}
|
||||
if stored.Revision == item.SHA256 {
|
||||
summary.Unchanged++
|
||||
continue
|
||||
}
|
||||
summary.UploadRequired++
|
||||
}
|
||||
return summary, nil
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package pp
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPlanReconciliationSchedulesNoUploadForAdoptedSnapshot(t *testing.T) {
|
||||
completedSource := strings.Repeat("a", 64)
|
||||
overLimitSource := strings.Repeat("b", 64)
|
||||
contentHash := strings.Repeat("c", 64)
|
||||
overLimit := Item{
|
||||
KBID: "kb-1",
|
||||
SourceURLHash: overLimitSource,
|
||||
SourceIDs: []string{"pp-2"},
|
||||
Bytes: LegacyMaxBytes + 1,
|
||||
Status: StatusOverLimit,
|
||||
}
|
||||
snapshot := Snapshot{KBID: "kb-1", Items: []Item{
|
||||
{KBID: "kb-1", SourceURLHash: completedSource, SourceIDs: []string{"pp-1"}, Bytes: 10, SHA256: contentHash, Status: StatusCompleted, KnowledgeID: "knowledge-1"},
|
||||
overLimit,
|
||||
}}
|
||||
current := map[string]CurrentItem{
|
||||
completedSource: {Revision: contentHash},
|
||||
overLimitSource: {Revision: metadataRevision(overLimit)},
|
||||
}
|
||||
|
||||
summary, err := PlanReconciliation(snapshot, current)
|
||||
if err != nil {
|
||||
t.Fatalf("PlanReconciliation() error = %v", err)
|
||||
}
|
||||
if summary.UploadRequired != 0 || summary.Unchanged != 1 || summary.OverLimit != 1 {
|
||||
t.Fatalf("summary = %#v", summary)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanReconciliationSchedulesUploadWhenSameSourceContentChanges(t *testing.T) {
|
||||
source := strings.Repeat("a", 64)
|
||||
oldHash := strings.Repeat("b", 64)
|
||||
newHash := strings.Repeat("c", 64)
|
||||
snapshot := Snapshot{KBID: "kb-1", Items: []Item{{
|
||||
KBID: "kb-1",
|
||||
SourceURLHash: source,
|
||||
SourceIDs: []string{"pp-1"},
|
||||
Bytes: 10,
|
||||
SHA256: newHash,
|
||||
Status: StatusCompleted,
|
||||
KnowledgeID: "knowledge-1",
|
||||
}}}
|
||||
|
||||
summary, err := PlanReconciliation(snapshot, map[string]CurrentItem{source: {Revision: oldHash}})
|
||||
if err != nil {
|
||||
t.Fatalf("PlanReconciliation() error = %v", err)
|
||||
}
|
||||
if summary.UploadRequired != 1 || summary.Unchanged != 0 {
|
||||
t.Fatalf("summary = %#v", summary)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user