- 同作业号重跑读持久日志+已封存清单按首次请求重放(source_read=false, writers_stopped=false),换范围/绑定库或清单校验失败即拒绝 - 归档用量按跨版本去重统计内容字节,清单/未引用 blob/实际分配单列, 不再用各版本 unique 之和冒充归档占用 - 冻结窗口内复核来源契约,不一致即中止;拒绝组外同镜像运行容器 - 补齐整库只读接口的 OpenAPI 契约 - 按用户确认取消 A06:文档/页面/接口不再把效果测试列为封版门槛
This commit is contained in:
+162
-28
@@ -224,11 +224,10 @@ type sourceConfig struct {
|
||||
ObjectDetail string
|
||||
}
|
||||
|
||||
func discoverSource(ctx context.Context, opts options) (sourceConfig, error) {
|
||||
func discoverSource(ctx context.Context, opts options, binding map[string]string) (sourceConfig, error) {
|
||||
var config sourceConfig
|
||||
binding, err := readRoutingBindings(ctx, opts.governancePG)
|
||||
if err != nil {
|
||||
return config, err
|
||||
if binding == nil {
|
||||
return config, errors.New("routing bindings are required")
|
||||
}
|
||||
config.Scopes = binding
|
||||
app, err := containerEnv(ctx, opts.sourceApp)
|
||||
@@ -385,7 +384,14 @@ func openArchive(opts options) (*librarysnapshot.Archive, error) {
|
||||
|
||||
func runStatus(ctx context.Context, opts options) error {
|
||||
report := map[string]any{}
|
||||
config, err := discoverSource(ctx, opts)
|
||||
binding, bindingErr := readRoutingBindings(ctx, opts.governancePG)
|
||||
var config sourceConfig
|
||||
var err error
|
||||
if bindingErr != nil {
|
||||
err = bindingErr
|
||||
} else {
|
||||
config, err = discoverSource(ctx, opts, binding)
|
||||
}
|
||||
if err != nil {
|
||||
report["source_discovery"] = err.Error()
|
||||
} else {
|
||||
@@ -471,7 +477,11 @@ func runPreflight(ctx context.Context, opts options) error {
|
||||
if opts.scope != "internal" && opts.scope != "external" {
|
||||
return errors.New("-scope must be internal or external")
|
||||
}
|
||||
config, err := discoverSource(ctx, opts)
|
||||
binding, err := readRoutingBindings(ctx, opts.governancePG)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
config, err := discoverSource(ctx, opts, binding)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -547,7 +557,41 @@ func runCapture(ctx context.Context, opts options) error {
|
||||
if job == "" {
|
||||
job = "lib-" + opts.scope + "-" + time.Now().UTC().Format("20060102T150405")
|
||||
}
|
||||
config, err := discoverSource(ctx, opts)
|
||||
archive, err := openArchive(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
coordinator, control, err := openFreeze(ctx, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer coordinator.Close()
|
||||
defer control.Close()
|
||||
if err = coordinator.Recover(ctx); err != nil {
|
||||
return fmt.Errorf("pending freeze requires recovery: %w", err)
|
||||
}
|
||||
// Replay is answered from the persisted journal + sealed archive: the same job
|
||||
// re-used with the same scope/binding returns the original candidate without
|
||||
// reading the source or stopping a writer, and a job re-used with different
|
||||
// parameters is refused instead of silently sealing under a stale identity.
|
||||
existing, found, err := coordinator.Inspect(job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
binding, err := readRoutingBindings(ctx, opts.governancePG)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
scopedKB := binding[opts.scope]
|
||||
if found {
|
||||
manifest, err := replayCapture(job, opts.scope, scopedKB, existing, archive)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printCapture(job, existing.SnapshotID, manifest, true)
|
||||
}
|
||||
config, err := discoverSource(ctx, opts, binding)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -573,23 +617,24 @@ func runCapture(ctx context.Context, opts options) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
archive, err := openArchive(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
// The contract above is read before the maintenance window. Re-read it inside
|
||||
// the stopped window and refuse if a model/index change happened in between:
|
||||
// sealing a candidate whose contract no longer matches the source would hide
|
||||
// exactly the change a later production sync cannot reproduce.
|
||||
verifyContract := func(ctx context.Context) error {
|
||||
live, err := compatibilityContract(ctx, pool, search, config.SearchIndex, tenant, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if live != contract {
|
||||
return errors.New("source contract changed between preflight and the frozen window; capture aborted")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
defer archive.Close()
|
||||
coordinator, control, err := openFreeze(ctx, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer coordinator.Close()
|
||||
defer control.Close()
|
||||
if err = coordinator.Recover(ctx); err != nil {
|
||||
return fmt.Errorf("pending freeze requires recovery: %w", err)
|
||||
}
|
||||
// sourceReady proves the *group* is complete and consistent. Recorded work
|
||||
// settlement is enforced separately by CaptureLibrary; neither check can see
|
||||
// unrecorded or remote work.
|
||||
// sourceReady proves the declared writer group is complete and no other
|
||||
// running container uses a declared writer image. Recorded work settlement is
|
||||
// enforced separately by CaptureLibrary; neither check can see unrecorded or
|
||||
// remote work, so this is not a cross-system consistency proof.
|
||||
sourceReady := func(ctx context.Context) error {
|
||||
items, err := control.Inventory(ctx)
|
||||
if err != nil {
|
||||
@@ -598,12 +643,21 @@ func runCapture(ctx context.Context, opts options) error {
|
||||
if len(items) == 0 {
|
||||
return errors.New("writer group is empty")
|
||||
}
|
||||
return nil
|
||||
declared := make(map[string]bool, len(items))
|
||||
for _, item := range items {
|
||||
declared[item.ID] = true
|
||||
}
|
||||
images, err := writerImageIDs(ctx, items)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return checkNoUndeclaredWriter(ctx, images, declared)
|
||||
}
|
||||
result, err := v071.CaptureLibrary(ctx, coordinator, archive, pool, search, objects, sourceReady,
|
||||
v071.LibraryCaptureRequest{JobID: job, Scope: opts.scope,
|
||||
Identity: v071.PostgresIdentity{TenantID: tenant, KnowledgeBaseID: kb},
|
||||
Compatibility: contract, CreatedAt: time.Now().UTC(), MaxDocuments: opts.maxDocuments})
|
||||
Compatibility: contract, CreatedAt: time.Now().UTC(), MaxDocuments: opts.maxDocuments,
|
||||
VerifyContract: verifyContract})
|
||||
if err != nil {
|
||||
printJSON(map[string]any{"job": job, "state": result.State, "snapshot_id": result.SnapshotID, "error": err.Error()})
|
||||
return err
|
||||
@@ -612,6 +666,32 @@ func runCapture(ctx context.Context, opts options) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printCapture(job, result.SnapshotID, manifest, false)
|
||||
}
|
||||
|
||||
// replayCapture answers a repeated job from persisted state. It never reads the
|
||||
// source and never stops a writer; conflicting parameters are refused.
|
||||
func replayCapture(job, scope, expectedKB string, result libraryfreeze.Result, archive *librarysnapshot.Archive) (librarysnapshot.Manifest, error) {
|
||||
if result.State != "succeeded" || result.SnapshotID == "" {
|
||||
return librarysnapshot.Manifest{}, fmt.Errorf("job %q already exists with state %q: recover it or use a new job id", job, result.State)
|
||||
}
|
||||
manifest, err := archive.Load(result.SnapshotID)
|
||||
if err != nil {
|
||||
return librarysnapshot.Manifest{}, errors.New("captured library archive no longer verifies")
|
||||
}
|
||||
if manifest.ValidationPolicy != librarysnapshot.ArtifactAcceptancePolicy {
|
||||
return librarysnapshot.Manifest{}, errors.New("existing job was sealed under a different validation policy")
|
||||
}
|
||||
if manifest.Scope != scope {
|
||||
return librarysnapshot.Manifest{}, fmt.Errorf("job %q was captured for scope %q, not %q", job, manifest.Scope, scope)
|
||||
}
|
||||
if manifest.KnowledgeBaseID != expectedKB {
|
||||
return librarysnapshot.Manifest{}, fmt.Errorf("job %q was captured for knowledge base %q, which is no longer the %q binding", job, manifest.KnowledgeBaseID, scope)
|
||||
}
|
||||
return manifest, nil
|
||||
}
|
||||
|
||||
func printCapture(job, snapshotID string, manifest librarysnapshot.Manifest, replay bool) error {
|
||||
parts := make([]map[string]any, 0, len(manifest.Parts))
|
||||
var total int64
|
||||
for _, part := range manifest.Parts {
|
||||
@@ -621,13 +701,58 @@ func runCapture(ctx context.Context, opts options) error {
|
||||
sort.Slice(parts, func(i, j int) bool {
|
||||
return fmt.Sprint(parts[i]["kind"])+fmt.Sprint(parts[i]["name"]) < fmt.Sprint(parts[j]["kind"])+fmt.Sprint(parts[j]["name"])
|
||||
})
|
||||
printJSON(map[string]any{"job": job, "state": result.State, "snapshot_id": result.SnapshotID,
|
||||
printJSON(map[string]any{"job": job, "state": "succeeded", "snapshot_id": snapshotID,
|
||||
"scope": manifest.Scope, "knowledge_base_id": manifest.KnowledgeBaseID, "tenant_id": manifest.TenantID,
|
||||
"compatibility": manifest.Compatibility, "parts": parts, "logical_bytes": total,
|
||||
"validation_policy": manifest.ValidationPolicy, "writers_restored": true})
|
||||
"validation_policy": manifest.ValidationPolicy, "writers_restored": true,
|
||||
"replay": replay, "source_read": !replay, "writers_stopped": !replay})
|
||||
return nil
|
||||
}
|
||||
|
||||
func writerImageIDs(ctx context.Context, items []libraryfreeze.Service) ([]string, error) {
|
||||
images := make([]string, 0, len(items))
|
||||
seen := map[string]bool{}
|
||||
for _, item := range items {
|
||||
image, err := containerImageOf(ctx, item.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !seen[image] {
|
||||
seen[image] = true
|
||||
images = append(images, image)
|
||||
}
|
||||
}
|
||||
return images, nil
|
||||
}
|
||||
|
||||
// checkNoUndeclaredWriter refuses to run when a running container uses a declared
|
||||
// writer image but is not part of the declared group: such a container could keep
|
||||
// writing during the maintenance window.
|
||||
func checkNoUndeclaredWriter(ctx context.Context, images []string, declared map[string]bool) error {
|
||||
for _, image := range images {
|
||||
out, err := dockerOutput(ctx, "ps", "-q", "--filter", "ancestor="+image)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, id := range strings.Fields(out) {
|
||||
if !declared[id] {
|
||||
return fmt.Errorf("container %s uses a declared writer image but is not in the declared writer group", id[:12])
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func containerImageOf(ctx context.Context, id string) (string, error) {
|
||||
image, err := dockerOutput(ctx, "inspect", "--format", "{{.Image}}", id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if image == "" {
|
||||
return "", errors.New("declared writer has no image identity")
|
||||
}
|
||||
return image, nil
|
||||
}
|
||||
func runList(opts options) error {
|
||||
archive, err := openArchive(opts)
|
||||
if err != nil {
|
||||
@@ -638,6 +763,10 @@ func runList(opts options) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
total, err := archive.ContentUsage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items := make([]map[string]any, 0, len(usage))
|
||||
for _, item := range usage {
|
||||
manifest, err := archive.Load(item.VersionID)
|
||||
@@ -649,7 +778,12 @@ func runList(opts options) error {
|
||||
"logical_bytes": item.LogicalBytes, "unique_bytes": item.UniqueBytes, "shared_bytes": item.SharedBytes,
|
||||
"parts": len(manifest.Parts), "policy": manifest.ValidationPolicy})
|
||||
}
|
||||
printJSON(map[string]any{"archive": opts.archiveRoot, "snapshots": items})
|
||||
printJSON(map[string]any{"archive": opts.archiveRoot, "snapshots": items,
|
||||
// 跨版本去重后的内容字节;文件系统事实单列,任何一项都不是可回收空间。
|
||||
"versions": total.Versions, "content_bytes": total.ContentBytes,
|
||||
"blob_file_bytes": total.BlobFileBytes, "blob_allocated_bytes": total.BlobAllocatedBytes,
|
||||
"unreferenced_blobs": total.UnreferencedBlobs, "unreferenced_bytes": total.UnreferencedBytes,
|
||||
"manifest_file_bytes": total.ManifestFileBytes, "manifest_allocated_bytes": total.ManifestAllocatedBytes})
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// sealedFixture writes one complete sealed candidate and returns its ID.
|
||||
func sealedFixture(t *testing.T, archive *librarysnapshot.Archive, scope, knowledgeBaseID string, createdAt time.Time) string {
|
||||
t.Helper()
|
||||
rows := func(count int) string {
|
||||
if count == 0 {
|
||||
return "[]"
|
||||
}
|
||||
items := make([]string, count)
|
||||
for i := range items {
|
||||
items[i] = fmt.Sprintf(`{"id":"00000000-0000-4000-8000-%012d"}`, i)
|
||||
}
|
||||
return "[" + strings.Join(items, ",") + "]"
|
||||
}
|
||||
parts := []struct {
|
||||
kind, name string
|
||||
count int64
|
||||
}{
|
||||
{"database", "knowledges", 4},
|
||||
{"database", "chunks", 38},
|
||||
{"database", "resources", 0},
|
||||
{"database", "resource_bindings", 0},
|
||||
{"database", "knowledge_tags", 0},
|
||||
{"database", "knowledge_tag_relations", 0},
|
||||
{"index", "chunks", 122},
|
||||
{"wiki", "wiki_pages", 31},
|
||||
{"wiki", "wiki_folders", 21},
|
||||
{"wiki", "wiki_page_issues", 0},
|
||||
{"wiki", "wiki_log_entries", 11},
|
||||
}
|
||||
manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy,
|
||||
Format: librarysnapshot.Format, Scope: scope, TenantID: 10000, KnowledgeBaseID: knowledgeBaseID,
|
||||
CreatedAt: createdAt, Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1",
|
||||
SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4",
|
||||
EmbeddingDimension: 1024, IndexMappingSHA256: strings.Repeat("b", 64)}}
|
||||
for _, part := range parts {
|
||||
stored, err := archive.Put(bytes.NewReader([]byte(rows(int(part.count)))))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored.Kind, stored.Name, stored.Count = part.kind, part.name, part.count
|
||||
manifest.Parts = append(manifest.Parts, stored)
|
||||
}
|
||||
id, err := archive.Seal(manifest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func fixtureArchive(t *testing.T) (*librarysnapshot.Archive, string) {
|
||||
t.Helper()
|
||||
root, err := os.MkdirTemp(os.TempDir(), "kglc-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(root) })
|
||||
if err = os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive, err := librarysnapshot.Open(root, 1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { archive.Close() })
|
||||
return archive, root
|
||||
}
|
||||
|
||||
const fixtureKB = "0c84a098-d3ed-4b82-a165-e6de9691d6a8"
|
||||
|
||||
// A repeated job with the same parameters must return the original candidate
|
||||
// without touching the source or stopping a writer (this function has no access
|
||||
// to either), instead of failing with a conflicting-request error.
|
||||
func TestReplayCaptureReturnsOriginalCandidate(t *testing.T) {
|
||||
archive, _ := fixtureArchive(t)
|
||||
created := time.Date(2026, 10, 28, 3, 34, 57, 0, time.UTC)
|
||||
id := sealedFixture(t, archive, "internal", fixtureKB, created)
|
||||
manifest, err := replayCapture("lib-internal-1", "internal", fixtureKB,
|
||||
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !manifest.CreatedAt.Equal(created) || manifest.Compatibility.EmbeddingModel != "text-embedding-v4" {
|
||||
t.Fatalf("replay lost the original request identity: %+v", manifest)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplayCaptureRejectsChangedParameters(t *testing.T) {
|
||||
archive, root := fixtureArchive(t)
|
||||
id := sealedFixture(t, archive, "internal", fixtureKB, time.Date(2026, 10, 28, 3, 34, 57, 0, time.UTC))
|
||||
// Different scope.
|
||||
if _, err := replayCapture("lib-internal-1", "external", fixtureKB,
|
||||
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive); err == nil {
|
||||
t.Fatal("scope conflict was accepted")
|
||||
}
|
||||
// Binding moved to another knowledge base.
|
||||
if _, err := replayCapture("lib-internal-1", "internal", "aec3dfc9-4ad3-4a39-926b-5bfa5d6a9654",
|
||||
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive); err == nil {
|
||||
t.Fatal("knowledge base binding change was accepted")
|
||||
}
|
||||
// A job that never succeeded must not be answered as success.
|
||||
if _, err := replayCapture("lib-internal-1", "internal", fixtureKB,
|
||||
libraryfreeze.Result{State: "failed"}, archive); err == nil {
|
||||
t.Fatal("failed job replayed as success")
|
||||
}
|
||||
// A sealed candidate that no longer verifies must not be reported as replay.
|
||||
if err := os.Remove(root + "/versions/" + id + ".json"); err == nil {
|
||||
if _, err := replayCapture("lib-internal-1", "internal", fixtureKB,
|
||||
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive); err == nil {
|
||||
t.Fatal("missing sealed candidate replayed as success")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user