fix(library): 幂等重放、跨版本去重用量与契约复核
build / build (push) Failing after 15s

- 同作业号重跑读持久日志+已封存清单按首次请求重放(source_read=false,
  writers_stopped=false),换范围/绑定库或清单校验失败即拒绝
- 归档用量按跨版本去重统计内容字节,清单/未引用 blob/实际分配单列,
  不再用各版本 unique 之和冒充归档占用
- 冻结窗口内复核来源契约,不一致即中止;拒绝组外同镜像运行容器
- 补齐整库只读接口的 OpenAPI 契约
- 按用户确认取消 A06:文档/页面/接口不再把效果测试列为封版门槛
This commit is contained in:
姚章浩
2026-10-28 12:01:09 +08:00
parent 20fc40a147
commit c5e033dd0e
15 changed files with 839 additions and 50 deletions
+29 -5
View File
@@ -15,8 +15,8 @@ import (
// 边界(刻意不做的事):
// - 不触发封存、不停/起写入者:封存需要维护窗口与来源凭据,只能由运维命令
// scripts/library-capture.sh 在目标主机执行;
// - 不把候选当版本:候选只证明"这一份内容被完整、可核验地封存了",内容/问答/
// 性能验收与生产发布是另外的、需要独立授权的事;
// - 不把完整性当发布:候选证明"这一份内容被完整、可核验地封存了"(A04 口径),
// 而授权与生产同步是另外的、需要独立授权的步骤(A06 效果测试已由用户取消);
// - 归档根没接线时返回可用性=false 与原因,不返回空表冒充"没有快照"。
type librarySnapshotPart struct {
Kind string `json:"kind"`
@@ -47,12 +47,22 @@ type librarySnapshotList struct {
Reason string `json:"reason,omitempty"`
ArchiveRoot string `json:"archive_root,omitempty"`
Snapshots []librarySnapshotView `json:"snapshots"`
StoredBytes int64 `json:"stored_bytes"`
// 归档级口径:ContentBytes 是**跨版本去重后、被版本引用的内容字节**。
// 它不是磁盘占用(清单、未引用 blob、块对齐与元数据都不在里面),
// 更不是可回收空间——清理需要保留策略、依赖保护与在线作业引用。
Versions int `json:"versions"`
ContentBytes int64 `json:"content_bytes"`
BlobFileBytes int64 `json:"blob_file_bytes"`
BlobAllocatedBytes int64 `json:"blob_allocated_bytes"`
UnreferencedBlobs int `json:"unreferenced_blobs"`
UnreferencedBytes int64 `json:"unreferenced_bytes"`
ManifestFileBytes int64 `json:"manifest_file_bytes"`
ManifestAllocatedBytes int64 `json:"manifest_allocated_bytes"`
// 页面必须能说清"封存由谁执行",不能让人以为页面上有个没实现的按钮。
CaptureNote string `json:"capture_note"`
}
const libraryCaptureNote = "封存由运维命令 scripts/library-capture.sh capture -scope internal|external 在目标主机执行(停写入者→导出→恢复)。页面只读展示已封存的候选;候选不等于验收通过或可发布。"
const libraryCaptureNote = "封存由运维命令 scripts/library-capture.sh capture -scope internal|external 在目标主机执行(停写入者→导出→恢复)。页面只读展示已封存的完整版本:它通过了数据完整性检查(身份、双向正文覆盖、生成问题、资源与摘要),这已满足封版所需的完整性口径;授权与生产同步仍是独立步骤。"
func librarySnapshotsList(w http.ResponseWriter, r *http.Request, config Config) {
view, err := readLibrarySnapshots(config.LibraryArchiveRoot)
@@ -114,10 +124,24 @@ func readLibrarySnapshots(root string) (librarySnapshotList, error) {
if err != nil {
return view, errors.New("归档用量不可读")
}
// Per-version UniqueBytes deduplicates only inside one version, so summing it
// over versions over-reports shared blobs. The archive-wide accounting below
// deduplicates across versions and keeps filesystem facts separate.
total, err := archive.ContentUsage()
if err != nil {
return view, errors.New("归档用量不可读")
}
view.Versions = total.Versions
view.ContentBytes = total.ContentBytes
view.BlobFileBytes = total.BlobFileBytes
view.BlobAllocatedBytes = total.BlobAllocatedBytes
view.UnreferencedBlobs = total.UnreferencedBlobs
view.UnreferencedBytes = total.UnreferencedBytes
view.ManifestFileBytes = total.ManifestFileBytes
view.ManifestAllocatedBytes = total.ManifestAllocatedBytes
byID := map[string]librarysnapshot.Usage{}
for _, item := range usage {
byID[item.VersionID] = item
view.StoredBytes += item.UniqueBytes
}
for id, item := range byID {
manifest, loadErr := archive.Load(id)
+7 -4
View File
@@ -101,10 +101,13 @@ func TestReadLibrarySnapshotsReportsSealedTotals(t *testing.T) {
t.Fatalf("total %s = %d, want %d", key, snapshot.Totals[key], value)
}
}
// Stored bytes are deduplicated per blob, so they can be smaller than the
// logical sum but never larger.
if snapshot.LogicalBytes <= 0 || list.StoredBytes <= 0 || list.StoredBytes > snapshot.LogicalBytes {
t.Fatalf("bytes not reported: logical=%d stored=%d", snapshot.LogicalBytes, list.StoredBytes)
// The archive-wide content figure deduplicates blobs across versions, so it
// can be smaller than a version's logical sum but never larger.
if snapshot.LogicalBytes <= 0 || list.ContentBytes <= 0 || list.ContentBytes > snapshot.LogicalBytes {
t.Fatalf("bytes not reported: logical=%d content=%d", snapshot.LogicalBytes, list.ContentBytes)
}
if list.BlobAllocatedBytes < list.BlobFileBytes || list.ManifestFileBytes <= 0 {
t.Fatalf("filesystem facts not separated: %+v", list)
}
if snapshot.Compatibility.EmbeddingDimension != 1024 || snapshot.ValidationPolicy != librarysnapshot.ArtifactAcceptancePolicy {
t.Fatalf("contract not reported: %+v", snapshot)
+19
View File
@@ -129,6 +129,25 @@ func (c *Coordinator) Recover(ctx context.Context) error {
}
return nil
}
// Inspect reports the persisted result of a job, if this coordinator ever ran it.
// A caller which re-uses a job ID needs the original request identity (time,
// scope, knowledge base, contract) to replay idempotently instead of guessing a
// fresh one, which would be rejected as a conflicting request.
func (c *Coordinator) Inspect(job string) (Result, bool, error) {
if !validID(job) {
return Result{}, false, errors.New("invalid freeze job id")
}
j, err := c.load(job)
if errors.Is(err, os.ErrNotExist) {
return Result{}, false, nil
}
if err != nil {
return Result{}, false, err
}
return j.Result, true, nil
}
func invokeCapture(ctx context.Context, capture func(context.Context) (string, error)) (id string, err error) {
defer func() {
if recover() != nil {
+131
View File
@@ -6,9 +6,11 @@ import (
"errors"
"io"
"math"
"os"
"slices"
"sort"
"strings"
"syscall"
)
type Usage struct {
@@ -97,6 +99,135 @@ func (a *Archive) Usage() ([]Usage, error) {
return result, nil
}
// ContentUsage is the archive-wide accounting of *content* bytes.
//
// It exists because per-version Usage() deduplicates only within one version: a
// blob shared by two versions is counted in both UniqueBytes, so summing those
// numbers over-reports the archive. ContentBytes here is deduplicated across
// every sealed version.
//
// It is still not filesystem occupancy: manifests, unreferenced blobs left by an
// interrupted Put and filesystem allocation (block rounding, metadata) are
// reported separately, and none of these numbers are reclaimable space. Cleanup
// needs retention/protection and live-job references from the coordinator.
type ContentUsage struct {
Versions int `json:"versions"`
ReferencedBlobs int `json:"referenced_blobs"`
ContentBytes int64 `json:"content_bytes"`
UnreferencedBlobs int `json:"unreferenced_blobs"`
UnreferencedBytes int64 `json:"unreferenced_bytes"`
BlobFileBytes int64 `json:"blob_file_bytes"`
BlobAllocatedBytes int64 `json:"blob_allocated_bytes"`
ManifestFileBytes int64 `json:"manifest_file_bytes"`
ManifestAllocatedBytes int64 `json:"manifest_allocated_bytes"`
}
// ContentUsage walks the sealed versions and the blob directory once, with the
// same "inventory must not change under us" guard as Usage.
func (a *Archive) ContentUsage() (ContentUsage, error) {
var usage ContentUsage
ids, err := a.versionIDs()
if err != nil {
return usage, err
}
referenced := map[string]int64{}
for _, id := range ids {
m, err := a.Load(id)
if err != nil {
return usage, err
}
for _, p := range m.Parts {
referenced[p.SHA256] = p.Bytes
}
}
after, err := a.versionIDs()
if err != nil {
return usage, err
}
if !slices.Equal(ids, after) {
return usage, errors.New("snapshot inventory changed; retry usage read")
}
usage.Versions = len(ids)
usage.ReferencedBlobs = len(referenced)
for _, size := range referenced {
if usage.ContentBytes > math.MaxInt64-size {
return usage, errors.New("snapshot usage overflow")
}
usage.ContentBytes += size
}
blobs, err := directoryBytes(a.blobs, func(name string) error {
if !validDigest(name) {
return errors.New("unexpected archive blob entry")
}
return nil
})
if err != nil {
return usage, err
}
usage.BlobFileBytes, usage.BlobAllocatedBytes = blobs.fileBytes, blobs.allocatedBytes
usage.UnreferencedBlobs = blobs.files - len(referenced)
usage.UnreferencedBytes = blobs.fileBytes
for _, size := range referenced {
usage.UnreferencedBytes -= size
}
if usage.UnreferencedBytes < 0 || usage.UnreferencedBlobs < 0 {
return usage, errors.New("archive blob inventory is inconsistent")
}
manifests, err := directoryBytes(a.versions, func(name string) error {
if strings.HasPrefix(name, ".pending-") {
return nil
}
if !strings.HasSuffix(name, ".json") {
return errors.New("unexpected archive version entry")
}
return nil
})
if err != nil {
return usage, err
}
usage.ManifestFileBytes, usage.ManifestAllocatedBytes = manifests.fileBytes, manifests.allocatedBytes
return usage, nil
}
type directoryUsage struct {
files int
fileBytes int64
allocatedBytes int64
}
// directoryBytes reports apparent size and allocated size (st_blocks) so callers
// can tell content size from what the filesystem actually reserved.
func directoryBytes(root *os.Root, validate func(string) error) (directoryUsage, error) {
var usage directoryUsage
dir, err := root.Open(".")
if err != nil {
return usage, err
}
defer dir.Close()
entries, err := dir.ReadDir(-1)
if err != nil {
return usage, err
}
for _, entry := range entries {
if err := validate(entry.Name()); err != nil {
return usage, err
}
info, err := entry.Info()
if err != nil {
return usage, err
}
if !info.Mode().IsRegular() {
return usage, errors.New("archive entry is not a regular file")
}
usage.files++
usage.fileBytes += info.Size()
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
usage.allocatedBytes += stat.Blocks * 512
}
}
return usage, nil
}
func (a *Archive) versionIDs() ([]string, error) {
f, err := a.versions.Open(".")
if err != nil {
@@ -0,0 +1,149 @@
package librarysnapshot
import (
"bytes"
"fmt"
"os"
"strings"
"testing"
"time"
)
// sealFixtureVersion seals one complete manifest whose parts are all derived
// from the same rows, so two versions of the same content share every blob.
func sealFixtureVersion(t *testing.T, archive *Archive, scope string, createdAt time.Time, documents int) 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
body string
}{
{"database", "knowledges", int64(documents), rows(documents)},
{"database", "chunks", int64(documents), rows(documents)},
{"database", "resources", 0, rows(0)},
{"database", "resource_bindings", 0, rows(0)},
{"database", "knowledge_tags", 0, rows(0)},
{"database", "knowledge_tag_relations", 0, rows(0)},
{"index", "chunks", int64(documents), rows(documents)},
{"wiki", "wiki_pages", 0, rows(0)},
{"wiki", "wiki_folders", 0, rows(0)},
{"wiki", "wiki_page_issues", 0, rows(0)},
{"wiki", "wiki_log_entries", 0, rows(0)},
}
manifest := Manifest{ValidationPolicy: ArtifactAcceptancePolicy, Format: Format, Scope: scope,
TenantID: 10000, KnowledgeBaseID: "kb-safe", CreatedAt: createdAt,
Compatibility: Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74,
RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024,
IndexMappingSHA256: strings.Repeat("a", 64)}}
for _, part := range parts {
stored, err := archive.Put(bytes.NewReader([]byte(part.body)))
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) (*Archive, string) {
t.Helper()
root, err := os.MkdirTemp(os.TempDir(), "kgsnap-")
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 := Open(root, 1024*1024)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { archive.Close() })
return archive, root
}
// Two sealed versions with identical content share every blob: summing the
// per-version UniqueBytes double counts them, which is the reporting bug this
// accounting fixes.
func TestContentUsageDeduplicatesAcrossVersions(t *testing.T) {
archive, _ := fixtureArchive(t)
sealFixtureVersion(t, archive, "internal", time.Date(2026, 10, 28, 1, 0, 0, 0, time.UTC), 4)
sealFixtureVersion(t, archive, "internal", time.Date(2026, 10, 28, 2, 0, 0, 0, time.UTC), 4)
perVersion, err := archive.Usage()
if err != nil {
t.Fatal(err)
}
if len(perVersion) != 2 {
t.Fatalf("expected two versions, got %d", len(perVersion))
}
sum := perVersion[0].UniqueBytes + perVersion[1].UniqueBytes
total, err := archive.ContentUsage()
if err != nil {
t.Fatal(err)
}
if total.Versions != 2 {
t.Fatalf("versions=%d", total.Versions)
}
if total.ContentBytes <= 0 {
t.Fatal("no content bytes reported")
}
if total.ContentBytes*2 != sum {
t.Fatalf("shared content not deduplicated: content=%d sum-of-versions=%d", total.ContentBytes, sum)
}
if total.UnreferencedBlobs != 0 || total.UnreferencedBytes != 0 {
t.Fatalf("unexpected unreferenced blobs: %+v", total)
}
if total.BlobFileBytes != total.ContentBytes {
t.Fatalf("blob files=%d content=%d", total.BlobFileBytes, total.ContentBytes)
}
if total.BlobAllocatedBytes < total.BlobFileBytes {
t.Fatalf("allocated=%d smaller than apparent=%d", total.BlobAllocatedBytes, total.BlobFileBytes)
}
if total.ManifestFileBytes <= 0 || total.ManifestAllocatedBytes < total.ManifestFileBytes {
t.Fatalf("manifest accounting wrong: %+v", total)
}
}
// A blob written by an interrupted capture is referenced by no manifest and must
// be reported separately, never folded into content bytes.
func TestContentUsageSeparatesUnreferencedBlobs(t *testing.T) {
archive, _ := fixtureArchive(t)
sealFixtureVersion(t, archive, "internal", time.Date(2026, 10, 28, 3, 0, 0, 0, time.UTC), 2)
before, err := archive.ContentUsage()
if err != nil {
t.Fatal(err)
}
stray, err := archive.Put(bytes.NewReader([]byte("interrupted-write")))
if err != nil {
t.Fatal(err)
}
after, err := archive.ContentUsage()
if err != nil {
t.Fatal(err)
}
if after.ContentBytes != before.ContentBytes {
t.Fatal("unreferenced blob changed content bytes")
}
if after.UnreferencedBlobs != 1 || after.UnreferencedBytes != stray.Bytes {
t.Fatalf("unreferenced accounting wrong: %+v (stray=%d)", after, stray.Bytes)
}
if after.BlobFileBytes != before.BlobFileBytes+stray.Bytes {
t.Fatal("blob file bytes do not include the unreferenced blob")
}
}
@@ -15,6 +15,11 @@ type LibraryCaptureRequest struct {
Compatibility librarysnapshot.Compatibility
CreatedAt time.Time
MaxDocuments int
// VerifyContract, when set, runs inside the stopped window immediately before
// the export. The caller re-reads the source contract and returns an error if
// it differs from Compatibility, so a model/index change between the
// preflight read and the maintenance window cannot be sealed silently.
VerifyContract func(context.Context) error
}
// CaptureLibrary connects maintenance to the actual PG/PIT/object archive path.
@@ -45,6 +50,11 @@ func CaptureLibrary(ctx context.Context, freeze *libraryfreeze.Coordinator, arch
if err := sourceReady(ctx); err != nil {
return "", err
}
if req.VerifyContract != nil {
if err := req.VerifyContract(ctx); err != nil {
return "", err
}
}
pg, err := ExportLibrary(ctx, db, req.Identity)
if err != nil {
return "", err
@@ -2,6 +2,7 @@ package v071
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -14,6 +15,8 @@ import (
"knowledge-governance/internal/librarysnapshot"
)
var errTestContractChanged = errors.New("source contract changed inside the maintenance window")
type captureWriter struct {
running atomic.Bool
db *libraryFixture
@@ -38,6 +41,85 @@ func (c *captureWriter) Stop(context.Context, string) error {
return nil
}
func (c *captureWriter) Start(context.Context, string) error { c.running.Store(true); return nil }
// The contract is read before the window and must be re-checked inside it: a
// model or mapping change between those two moments must abort, restore writers
// and seal nothing.
func TestLibraryCaptureRechecksContractInsideFrozenWindow(t *testing.T) {
writer := &captureWriter{db: newLibraryFixture()}
writer.running.Store(true)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/chunks/_mapping":
fmt.Fprint(w, `{"chunks":{"mappings":{"properties":{"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"tenant_id":{"type":"long"}}}}}`)
case "/chunks/_pit":
fmt.Fprint(w, `{"id":"fixed-pit"}`)
case "/_search":
fmt.Fprint(w, `{"timed_out":false,"_shards":{"total":1,"successful":1,"failed":0},"hits":{"total":{"value":0,"relation":"eq"},"hits":[]}}`)
case "/_pit":
fmt.Fprint(w, `{"succeeded":true}`)
default:
http.Error(w, "unexpected", 400)
}
}))
defer server.Close()
search, err := NewSearchExporter(SearchExporterConfig{BaseURL: server.URL, Index: "chunks", PageSize: 10})
if err != nil {
t.Fatal(err)
}
mapping, err := search.inspectMapping(context.Background())
if err != nil {
t.Fatal(err)
}
root := t.TempDir()
_ = os.Chmod(root, 0700)
freeze, err := libraryfreeze.Open(root, "test-source", writer)
if err != nil {
t.Fatal(err)
}
defer freeze.Close()
archiveRoot := t.TempDir()
_ = os.Chmod(archiveRoot, 0700)
archive, err := librarysnapshot.Open(archiveRoot, 1024*1024)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
req := LibraryCaptureRequest{JobID: "contract-job", Scope: "internal",
Identity: PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"},
Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74,
RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024,
IndexMappingSHA256: mapping.digest},
CreatedAt: time.Date(2026, 10, 28, 0, 0, 0, 0, time.UTC), MaxDocuments: 100}
called := 0
req.VerifyContract = func(context.Context) error {
called++
if writer.running.Load() {
t.Error("contract re-check ran before writers stopped")
}
return errTestContractChanged
}
ready := func(context.Context) error { return nil }
result, err := CaptureLibrary(context.Background(), freeze, archive, dbFixture(t, writer), search, &libraryCandidateReader{}, ready, req)
if err == nil || result.State == "succeeded" || result.SnapshotID != "" {
t.Fatalf("contract change was sealed: %+v %v", result, err)
}
if called != 1 {
t.Fatalf("contract re-check called %d times", called)
}
if !writer.running.Load() {
t.Fatal("writer left stopped after a contract abort")
}
if usage, usageErr := archive.Usage(); usageErr != nil || len(usage) != 0 {
t.Fatalf("aborted capture left an artifact: %v %v", usage, usageErr)
}
}
func dbFixture(t *testing.T, writer *captureWriter) *libraryFixture {
t.Helper()
return writer.db
}
func TestLibraryCaptureMaintenanceOwnsArchiveAndRestoresOnFailure(t *testing.T) {
for _, mode := range []string{"success", "initial-busy", "late-pending", "search-failure", "other-library-busy", "other-library-late-pending"} {
t.Run(mode, func(t *testing.T) {