Compare commits

...

6 Commits

Author SHA1 Message Date
姚章浩 2fc6dc068b fix(snapshot): 按持久元数据核验生成问题索引
build / build (push) Successful in 1m11s
2026-10-28 01:24:32 +08:00
姚章浩 fe2e7ac4f4 fix(snapshot): 拒绝旧式分块缺失索引的候选
build / build (push) Successful in 1m10s
2026-10-28 01:17:58 +08:00
姚章浩 c4759bb61c fix(snapshot): 校验正文索引的确定性标题变换
build / build (push) Successful in 1m13s
2026-10-28 01:13:16 +08:00
姚章浩 bf049cee1f fix(snapshot): 暂停前后强制检查共享源全库任务
build / build (push) Successful in 1m12s
2026-10-28 01:05:44 +08:00
姚章浩 55fba5fc0e fix(snapshot): 按表解析状态并保留完整Wiki内容
build / build (push) Successful in 1m11s
2026-10-28 00:57:43 +08:00
姚章浩 ce2f90c1c5 fix(snapshot): 阻止已索引分块缺失时封存整库
build / build (push) Successful in 1m12s
2026-10-28 00:43:31 +08:00
14 changed files with 517 additions and 21 deletions
+42
View File
@@ -1,5 +1,47 @@
# Changelog
## 开发快照 snapshot/v0.1.103 - 2026-10-28
### Fixed
- 整库索引校验支持从分块持久元数据核验生成问题:严格匹配分块、问题 source_id 与问题原文,拒绝未知、过期或内容不一致的索引。
- 分开核验正文与生成问题的覆盖,问题记录不能掩盖正文索引缺失;元数据中已记录的问题缺少索引同样阻断。未放宽临时章节上下文或未知索引变换的检查。
## 开发快照 snapshot/v0.1.102 - 2026-10-28
### Fixed
- 阻止旧式 status=0 普通分块缺失索引时被误判完整;仅明确的上下文父分块允许没有索引,显式标记已索引的分块仍须存在。
- 缺少可核验的无索引策略时返回覆盖未证实,不推断索引已禁用;Wiki-only 无索引库的完整支持仍待实现,不因此宣称整库验收通过。
## 开发快照 snapshot/v0.1.101 - 2026-10-28
### Fixed
- 修复正常正文索引因标题前缀或正文首尾空白处理而被整库归档误拒的问题;仅按已持久化的标题与正文重建确定性内容,保持逐字核验,不使用后缀包含匹配。
- 无法由持久数据核验的临时章节上下文、非正文类型的变换及未知内容仍阻断;不将本次兼容修复视为完整索引或整库业务验收通过。
## 开发快照 snapshot/v0.1.100 - 2026-10-28
### Fixed
- 测试封存暂停共享写入服务前及暂停后,强制检查整个源数据库的解析状态、待处理任务和死信;其他库、其他租户及已删除或未知任务范围的未完成工作均阻断封存。
- 保留部署侧入口与后台作业检查;数据库任务结清不代表 Wiki 语义验收通过。本次未清理死信、未暂停实际测试 WeKnora、未执行生产发布。
## 开发快照 snapshot/v0.1.99 - 2026-10-28
### Fixed
- 修复整库归档将 Wiki 页面与问题记录的字符串状态误按分块整数状态解析的问题;分块状态仅在分块表中解析,Wiki 状态和正文原样保留。
- 候选捕获回归改用非空 Wiki 页面与问题记录,防止空表夹具漏检。本次仍不代表完整同步恢复业务已交付。
## 开发快照 snapshot/v0.1.98 - 2026-10-28
### Fixed
- 修复整库候选封存只单向校验搜索索引的问题:数据库标记为已索引的分块必须在导出索引中存在,否则拒绝封存;按分块身份而非总数量核对,避免重复索引掩盖缺失。仅存储的父分块仍允许不建索引。
- 本修复增强候选完整性,不代表整库业务入口、生产同步恢复或语义验收已经完成。
## 开发快照 snapshot/v0.1.97 - 2026-10-28
### Fixed
+1 -1
View File
@@ -101,4 +101,4 @@
已新增 `internal/releaseadapter/v071/library_capture.go`,在源服务组互斥下串起预检、暂停、停后复检、PG/ES 导出、独立归档和恢复。协调测试使用 PG/服务控制夹具与 HTTP 搜索夹具,覆盖预检忙时零停止、暂停前后新增任务阻断、搜索失败恢复、旧作业重放不重新暂停、跨 scope 复用拒绝、归档丢失不返回成功;不把这组夹具当成实际业务知识库全链路验收。最终竞态回归、隔离 Docker 重跑与 `make verify` 均退出码 0,最终日志为同目录 `kg-freeze-docker-final.log`、`kg-library-freeze-final-verify.log`。
**仍缺少的接线**:真实测试部署的全部写入者枚举及标签/健康契约、全源任务就绪检查的实际提供方、worker 调用捕获协调函数、启动恢复入口和持续恢复调度。单独的本地 Docker 控制器不能控制远端测试主机;远端场景需在测试主机运行受限执行器,不能向浏览器或普通 API 暴露 Docker socket。上述测试不能证明这些接线已完成,尚未暂停实际测试 WeKnora。
**仍缺少的接线**:真实测试部署的全部写入者枚举及标签/健康契约、部署侧入口及后台作业就绪检查的实际提供方、worker 调用捕获协调函数、启动恢复入口和持续恢复调度。`CaptureLibrary` 已强制在暂停前后检查整个源数据库的解析、pending 与 dead-letter 状态(跨库、跨租户及未知/删除范围);此检查不能代替入口隔离与 Wiki 语义验收。单独的本地 Docker 控制器不能控制远端测试主机;远端场景需在测试主机运行受限执行器,不能向浏览器或普通 API 暴露 Docker socket。上述测试不能证明这些接线已完成,尚未暂停实际测试 WeKnora。
+96 -12
View File
@@ -105,17 +105,40 @@ func ArchiveLibraryCandidate(ctx context.Context, archive *librarysnapshot.Archi
}
type libraryRow struct {
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
KnowledgeID string `json:"knowledge_id"`
ChunkID string `json:"chunk_id"`
TagID string `json:"tag_id"`
ResourceID string `json:"resource_id"`
Handle string `json:"handle"`
OwnerType string `json:"owner_type"`
OwnerID string `json:"owner_id"`
Content string `json:"content"`
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
KnowledgeID string `json:"knowledge_id"`
ChunkID string `json:"chunk_id"`
TagID string `json:"tag_id"`
ResourceID string `json:"resource_id"`
Handle string `json:"handle"`
OwnerType string `json:"owner_type"`
OwnerID string `json:"owner_id"`
Content string `json:"content"`
Title string `json:"title"`
ChunkType string `json:"chunk_type"`
ChunkStatus int `json:"-"`
SourceID string `json:"source_id"`
Questions map[string]string `json:"-"`
}
func libraryIndexContentMatches(indexContent string, chunk, knowledge libraryRow) bool {
if indexContent == chunk.Content {
return true
}
if chunk.ChunkType != "text" {
return false
}
// v0.7.1 text indexing trims the body and may prepend the title. Only
// reconstruct transformations backed by archived fields. ContextHeader is
// transient upstream; suffix matching would silently accept stale content.
body := strings.TrimSpace(chunk.Content)
if indexContent == body {
return true
}
title := strings.TrimSpace(knowledge.Title)
return title != "" && indexContent == title+"\n"+body
}
func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es SearchSnapshot) error {
@@ -151,6 +174,31 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
if json.Unmarshal(raw, &row) != nil {
return errors.New("invalid library content row")
}
// Status is table-specific: chunks use integers, Wiki pages/issues
// use strings. Decode chunk metadata only for its owning table.
if table.Name == "chunks" {
var metadata struct {
Status int `json:"status"`
Metadata struct {
GeneratedQuestions []struct {
ID string `json:"id"`
Question string `json:"question"`
} `json:"generated_questions"`
} `json:"metadata"`
}
if json.Unmarshal(raw, &metadata) != nil {
return errors.New("invalid library chunk status")
}
row.ChunkStatus = metadata.Status
row.Questions = map[string]string{}
for _, question := range metadata.Metadata.GeneratedQuestions {
sourceID := row.ID + "-" + question.ID
if row.ChunkType != "text" || !validSearchIdentifier(question.ID) || strings.TrimSpace(question.Question) == "" || row.Questions[sourceID] != "" {
return errors.New("invalid library generated question metadata")
}
row.Questions[sourceID] = question.Question
}
}
if table.Name == "knowledge_tag_relations" {
if !validSearchIdentifier(row.KnowledgeID) || !validSearchIdentifier(row.TagID) {
return errors.New("invalid library tag relation")
@@ -220,6 +268,8 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
return errors.New("invalid library index digest")
}
seen := map[string]bool{}
indexedChunks := map[string]bool{}
indexedQuestions := map[string]map[string]bool{}
for _, document := range es.Documents {
var row libraryRow
if json.Unmarshal(document.Source, &row) != nil || !validSearchIdentifier(document.ID) || seen[document.ID] {
@@ -227,12 +277,46 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
}
seen[document.ID] = true
chunk, ok := tables["chunks"][row.ChunkID]
if !ok || row.KnowledgeID != chunk.KnowledgeID || row.Content != chunk.Content {
if !ok || row.KnowledgeID != chunk.KnowledgeID {
return errors.New("library index does not match database chunks")
}
if !searchHitMatches(document.Source, SearchIdentity{TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, KnowledgeID: row.KnowledgeID}) {
return errors.New("cross-scope library index")
}
if row.SourceID != "" && row.SourceID != row.ChunkID {
question, exists := chunk.Questions[row.SourceID]
if !exists || question != row.Content {
return errors.New("library question index does not match persisted metadata")
}
if indexedQuestions[row.ChunkID] == nil {
indexedQuestions[row.ChunkID] = map[string]bool{}
}
indexedQuestions[row.ChunkID][row.SourceID] = true
} else {
if !libraryIndexContentMatches(row.Content, chunk, tables["knowledges"][chunk.KnowledgeID]) {
return errors.New("library index does not match database chunks")
}
indexedChunks[row.ChunkID] = true
}
}
// v0.7.1 ChunkStatusIndexed is 2. One chunk can have several search
// records, so compare identities rather than counts. Stored-only parent
// chunks intentionally have no index and must not be rejected as missing.
// Text ingestion also leaves indexed chunks at the legacy default status
// zero. Without an archived no-index policy, absence is unverified, not
// proof that indexing was disabled. Parent chunks are context-only.
for id, chunk := range tables["chunks"] {
for sourceID := range chunk.Questions {
if !indexedQuestions[id][sourceID] {
return errors.New("missing library generated question index")
}
}
if chunk.ChunkStatus == 0 && chunk.ChunkType != "parent_text" && !indexedChunks[id] {
return errors.New("unverified legacy library chunk index coverage")
}
if chunk.ChunkStatus == 2 && !indexedChunks[id] {
return errors.New("missing indexed library chunk")
}
}
return nil
}
@@ -88,7 +88,14 @@ func libraryCandidateFixture() (PostgresSnapshot, SearchSnapshot, *libraryCandid
newTableSnapshot("resources", []json.RawMessage{json.RawMessage(`{"id":"res-safe","tenant_id":10000,"handle":"ABCDEFGHIJKLMNOPQRSTUV","provider":"oss","physical_path":"oss://fixture/source.txt","size":4}`)}),
}
for _, name := range []string{"resource_bindings", "knowledge_tags", "knowledge_tag_relations", "wiki_folders", "wiki_pages", "wiki_page_issues", "wiki_log_entries"} {
tables = append(tables, newTableSnapshot(name, nil))
var rows []json.RawMessage
switch name {
case "wiki_pages":
rows = []json.RawMessage{json.RawMessage(`{"id":"wiki-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","status":"published","content":"complete wiki body"}`)}
case "wiki_page_issues":
rows = []json.RawMessage{json.RawMessage(`{"id":"issue-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","status":"open"}`)}
}
tables = append(tables, newTableSnapshot(name, rows))
}
es := SearchSnapshot{MappingSHA256: shaBytes([]byte("mapping")), Documents: []SearchDocument{{ID: "es-safe", Source: json.RawMessage(`{"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","chunk_id":"chunk-safe","content":"chunk"}`)}}}
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
@@ -28,6 +28,9 @@ func CaptureLibrary(ctx context.Context, freeze *libraryfreeze.Coordinator, arch
return libraryfreeze.Result{}, errors.New("invalid library capture configuration")
}
result, err := freeze.RunPrepared(ctx, req.JobID, func(ctx context.Context) error {
if err := checkLibrarySourceSettlement(ctx, db); err != nil {
return err
}
if err := sourceReady(ctx); err != nil {
return err
}
@@ -36,6 +39,9 @@ func CaptureLibrary(ctx context.Context, freeze *libraryfreeze.Coordinator, arch
_, err := ExportLibrary(ctx, db, req.Identity)
return err
}, func(ctx context.Context) (string, error) {
if err := checkLibrarySourceSettlement(ctx, db); err != nil {
return "", err
}
if err := sourceReady(ctx); err != nil {
return "", err
}
@@ -15,10 +15,11 @@ import (
)
type captureWriter struct {
running atomic.Bool
db *libraryFixture
late bool
stops int
running atomic.Bool
db *libraryFixture
late bool
lateSource bool
stops int
}
func (c *captureWriter) Inventory(context.Context) ([]libraryfreeze.Service, error) {
@@ -31,14 +32,20 @@ func (c *captureWriter) Stop(context.Context, string) error {
if c.late {
c.db.tx.pending = 1
}
if c.lateSource {
c.db.tx.sourcePending = 1
}
return nil
}
func (c *captureWriter) Start(context.Context, string) error { c.running.Store(true); return nil }
func TestLibraryCaptureMaintenanceOwnsArchiveAndRestoresOnFailure(t *testing.T) {
for _, mode := range []string{"success", "initial-busy", "late-pending", "search-failure"} {
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) {
db := newLibraryFixture()
writer := &captureWriter{db: db, late: mode == "late-pending"}
writer := &captureWriter{db: db, late: mode == "late-pending", lateSource: mode == "other-library-late-pending"}
if mode == "other-library-busy" {
db.tx.sourcePending = 1
}
writer.running.Store(true)
if mode == "initial-busy" {
db.tx.pending = 1
@@ -98,7 +105,7 @@ func TestLibraryCaptureMaintenanceOwnsArchiveAndRestoresOnFailure(t *testing.T)
if err == nil {
t.Fatal("invalid candidate succeeded")
}
if mode == "initial-busy" && writer.stops != 0 {
if (mode == "initial-busy" || mode == "other-library-busy") && writer.stops != 0 {
t.Fatal("busy source stopped")
}
return
@@ -54,6 +54,38 @@ func TestLibraryExportIsolatedPostgres(t *testing.T) {
}
}
}
t.Run("whole source settlement", func(t *testing.T) {
if err := checkLibrarySourceSettlement(ctx, db); err != nil {
t.Fatal(err)
}
for _, tc := range []struct{ name, change, restore string }{
{"other tenant document", `UPDATE knowledges SET parse_status='processing' WHERE id='other-scope'`, `UPDATE knowledges SET parse_status='completed' WHERE id='other-scope'`},
{"other library pending", `INSERT INTO task_pending_ops VALUES(20000,'wiki:ingest','knowledge_base','other-library')`, `DELETE FROM task_pending_ops`},
{"deleted scope pending", `INSERT INTO task_pending_ops VALUES(20000,'wiki:retract','knowledge','physically-deleted-doc')`, `DELETE FROM task_pending_ops`},
{"unknown scope pending", `INSERT INTO task_pending_ops VALUES(20000,'unknown:task','unknown','unknown')`, `DELETE FROM task_pending_ops`},
{"other tenant dead letter", `INSERT INTO task_dead_letters VALUES(20000,'document:process','knowledge_base','other-library')`, `DELETE FROM task_dead_letters`},
} {
t.Run(tc.name, func(t *testing.T) {
if _, err := db.Exec(ctx, tc.change); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if _, err := db.Exec(ctx, tc.restore); err != nil {
t.Error(err)
}
})
if _, err := ExportLibrary(ctx, db, scope); err != nil {
t.Fatalf("selected library unexpectedly busy: %v", err)
}
if err := checkLibrarySourceSettlement(ctx, db); err == nil {
t.Fatal("source maintenance allowed while another scope has unfinished work")
}
})
}
if err := checkLibrarySourceSettlement(ctx, db); err != nil {
t.Fatalf("settled source did not recover: %v", err)
}
})
t.Run("MVCC concurrent update", func(t *testing.T) {
wrapper := libraryHookDB{pool: db, hook: func() {
if _, err := db.Exec(ctx, `UPDATE wiki_pages SET content='new-content' WHERE id='wiki-safe'`); err != nil {
@@ -80,6 +80,7 @@ type libraryFixtureTx struct {
pgx.Tx
queries []string
committed bool
sourcePending int64
pending, failed, unsettled int64
graph bool
queryError bool
@@ -111,6 +112,10 @@ type libraryFixtureRow struct {
func (r libraryFixtureRow) Scan(dest ...any) error {
switch {
case strings.Contains(r.sql, "library-source-settlement"):
*dest[0].(*int64) = r.d.unsettled
*dest[1].(*int64) = r.d.pending + r.d.sourcePending
*dest[2].(*int64) = r.d.failed
case strings.Contains(r.sql, "schema_migrations"):
*dest[0].(*int) = 74
*dest[1].(*bool) = false
@@ -0,0 +1,71 @@
package v071
import (
"context"
"encoding/json"
"os"
"strings"
"testing"
"time"
"knowledge-governance/internal/librarysnapshot"
)
func TestLibraryCandidateIndexCompletenessUsesChunkIdentity(t *testing.T) {
for _, mode := range []string{"stored-parent", "multiple-records-one-chunk", "same-count-missing-chunk"} {
t.Run(mode, func(t *testing.T) {
pg, es, _ := libraryCandidateFixture()
rows := []json.RawMessage{json.RawMessage(`{"id":"chunk-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"chunk","status":2,"chunk_type":"text"}`)}
if mode == "stored-parent" {
rows = append(rows, json.RawMessage(`{"id":"parent-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"context","status":1,"chunk_type":"parent_text"}`))
} else {
es.Documents = append(es.Documents, SearchDocument{ID: "es-second", Source: append(json.RawMessage(nil), es.Documents[0].Source...)})
if mode == "same-count-missing-chunk" {
rows = append(rows, json.RawMessage(`{"id":"chunk-second","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"second","status":2,"chunk_type":"text"}`))
}
}
pg.Tables[1] = newTableSnapshot("chunks", rows)
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
err := validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es)
if mode == "same-count-missing-chunk" {
if err == nil || !strings.Contains(err.Error(), "missing indexed library chunk") {
t.Fatalf("same counts masked a missing chunk: %v", err)
}
} else if err != nil {
t.Fatalf("valid index shape rejected: %v", err)
}
})
}
}
func TestLibraryCandidateRejectsMissingIndexedChunk(t *testing.T) {
pg, es, objects := libraryCandidateFixture()
pg.Tables[1] = newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"chunk","status":2,"chunk_type":"text"}`)})
identity := PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}
if err := validateLibraryCandidate(identity, pg, es); err != nil {
t.Fatalf("complete indexed chunk rejected: %v", err)
}
es.Documents = nil
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
root := t.TempDir()
if err := os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
archive, err := librarysnapshot.Open(root, 1024*1024)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
contract := librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024, IndexMappingSHA256: es.MappingSHA256}
id, err := ArchiveLibraryCandidate(context.Background(), archive, "internal", identity, contract, pg, es, objects, time.Now().UTC())
if err == nil || id != "" {
t.Fatal("sealed a supposedly complete library with an indexed PostgreSQL chunk missing from Elasticsearch")
}
if !strings.Contains(err.Error(), "missing indexed library chunk") {
t.Fatalf("unexpected refusal: %v", err)
}
versions, err := os.ReadDir(root + "/versions")
if err != nil || len(versions) != 0 {
t.Fatalf("incomplete candidate became visible: versions=%d err=%v", len(versions), err)
}
}
@@ -0,0 +1,40 @@
package v071
import (
"encoding/json"
"testing"
)
func TestLibraryCandidateValidatesPersistedTextIndexTransform(t *testing.T) {
for _, tc := range []struct {
name, kind, body, index string
valid bool
}{
{"current title prefix", "text", "\n chunk \t", "Document title\nchunk", true},
{"legacy raw body", "text", "\n chunk \t", "\n chunk \t", true},
{"trimmed body", "text", "\n chunk \t", "chunk", true},
{"wrong title", "text", "chunk", "Other title\nchunk", false},
{"missing body", "text", "chunk", "Document title\n", false},
{"different body", "text", "chunk", "Document title\nchanged", false},
{"unverifiable context header", "text", "chunk", "Document title\nTransient heading\n\nchunk", false},
{"nontext transform not assumed", "faq", "chunk", "Document title\nchunk", false},
} {
t.Run(tc.name, func(t *testing.T) {
pg, es, _ := libraryCandidateFixture()
k, _ := json.Marshal(map[string]any{"id": "doc-safe", "tenant_id": 10000, "knowledge_base_id": "kb-safe", "title": " Document title\n"})
c, _ := json.Marshal(map[string]any{"id": "chunk-safe", "tenant_id": 10000, "knowledge_base_id": "kb-safe", "knowledge_id": "doc-safe", "content": tc.body, "chunk_type": tc.kind, "status": 2})
x, _ := json.Marshal(map[string]any{"knowledge_base_id": "kb-safe", "knowledge_id": "doc-safe", "chunk_id": "chunk-safe", "content": tc.index})
pg.Tables[0] = newTableSnapshot("knowledges", []json.RawMessage{k})
pg.Tables[1] = newTableSnapshot("chunks", []json.RawMessage{c})
es.Documents[0].Source = x
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
err := validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es)
if tc.valid && err != nil {
t.Fatalf("valid indexed text refused: %v", err)
}
if !tc.valid && err == nil {
t.Fatal("unverifiable index content accepted")
}
})
}
}
@@ -0,0 +1,41 @@
package v071
import (
"encoding/json"
"testing"
)
func TestLibraryCandidateLegacyChunkIndexCoverage(t *testing.T) {
for _, tc := range []struct {
name, kind string
status int
indexed, valid bool
}{
{"legacy text missing", "text", 0, false, false},
{"legacy text indexed", "text", 0, true, true},
{"legacy unknown type missing", "", 0, false, false},
{"context parent not indexed", "parent_text", 0, false, true},
{"stored parent not indexed", "parent_text", 1, false, true},
{"indexed parent missing", "parent_text", 2, false, false},
} {
t.Run(tc.name, func(t *testing.T) {
pg, es, _ := libraryCandidateFixture()
raw, err := json.Marshal(map[string]any{"id": "chunk-safe", "tenant_id": 10000, "knowledge_base_id": "kb-safe", "knowledge_id": "doc-safe", "content": "chunk", "status": tc.status, "chunk_type": tc.kind})
if err != nil {
t.Fatal(err)
}
pg.Tables[1] = newTableSnapshot("chunks", []json.RawMessage{raw})
if !tc.indexed {
es.Documents = nil
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
}
err = validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es)
if tc.valid && err != nil {
t.Fatalf("valid chunk rejected: %v", err)
}
if !tc.valid && err == nil {
t.Fatal("missing legacy index escaped completeness validation")
}
})
}
}
@@ -0,0 +1,43 @@
package v071
import (
"encoding/json"
"testing"
)
func TestLibraryCandidateGeneratedQuestionIndex(t *testing.T) {
for _, mode := range []string{"complete", "wrong-id", "wrong-content", "missing-question", "missing-body", "foreign-source", "question-as-body"} {
t.Run(mode, func(t *testing.T) {
pg, es, _ := libraryCandidateFixture()
pg.Tables[1] = newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"chunk","chunk_type":"text","status":0,"metadata":{"generated_questions":[{"id":"q1","question":"How does it work?"}]}}`)})
questionID, content := "chunk-safe-q1", "How does it work?"
if mode == "wrong-id" {
questionID = "chunk-safe-q2"
}
if mode == "wrong-content" {
content = "Different question"
}
if mode == "foreign-source" {
questionID = "foreign-q1"
}
if mode == "question-as-body" {
content = "chunk"
}
raw, _ := json.Marshal(map[string]any{"chunk_id": "chunk-safe", "knowledge_id": "doc-safe", "knowledge_base_id": "kb-safe", "source_id": questionID, "content": content})
q := SearchDocument{ID: "question-index", Source: raw}
if mode == "missing-body" {
es.Documents = []SearchDocument{q}
} else if mode != "missing-question" {
es.Documents = append(es.Documents, q)
}
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
err := validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es)
if mode == "complete" && err != nil {
t.Fatalf("valid persisted question rejected: %v", err)
}
if mode != "complete" && err == nil {
t.Fatal("incomplete or inconsistent question index accepted")
}
})
}
}
@@ -0,0 +1,38 @@
package v071
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
)
// A maintenance window stops a shared writer, not a single KB. Check its entire
// source database, including other tenants, deleted scopes and unknown task
// scopes. Restricting this query to the selected KB can interrupt another job.
// This only establishes recorded processing settlement, never Wiki semantics or
// the absence of unrecorded/remote work; CaptureLibrary still requires the
// deployment's ingress and background-worker readiness callback.
func checkLibrarySourceSettlement(ctx context.Context, db librarySnapshotDB) error {
tx, err := db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
if err != nil {
return errors.New("begin library source settlement")
}
defer tx.Rollback(context.WithoutCancel(ctx))
var unsettled, pending, failed int64
if err := tx.QueryRow(ctx, librarySourceSettlementSQL).Scan(&unsettled, &pending, &failed); err != nil {
return errors.New("read library source settlement")
}
if unsettled != 0 || pending != 0 || failed != 0 {
return errors.New("library source has unfinished or failed processing")
}
if err := tx.Commit(ctx); err != nil {
return errors.New("commit library source settlement")
}
return nil
}
const librarySourceSettlementSQL = `SELECT /* library-source-settlement */
(SELECT count(*) FROM knowledges WHERE deleted_at IS NULL AND (parse_status IS DISTINCT FROM 'completed' OR pending_subtasks_count IS NULL OR pending_subtasks_count<>0)),
(SELECT count(*) FROM task_pending_ops),
(SELECT count(*) FROM task_dead_letters)`
@@ -0,0 +1,80 @@
package v071
import (
"context"
"encoding/json"
"io"
"os"
"testing"
"time"
"knowledge-governance/internal/librarysnapshot"
)
func TestLibraryCandidateArchivesWikiStringStatuses(t *testing.T) {
for _, tc := range []struct{ table, status string }{
{"wiki_pages", "draft"}, {"wiki_pages", "published"}, {"wiki_pages", "archived"},
{"wiki_page_issues", "open"}, {"wiki_page_issues", "resolved"},
} {
t.Run(tc.table+"/"+tc.status, func(t *testing.T) {
pg, es, objects := libraryCandidateFixture()
raw := json.RawMessage(`{"id":"wiki-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","content":"complete wiki body","status":"` + tc.status + `"}`)
for i := range pg.Tables {
if pg.Tables[i].Name == tc.table {
pg.Tables[i] = newTableSnapshot(tc.table, []json.RawMessage{raw})
}
}
root := t.TempDir()
if err := os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
archive, err := librarysnapshot.Open(root, 1024*1024)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
contract := librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024, IndexMappingSHA256: es.MappingSHA256}
id, err := ArchiveLibraryCandidate(context.Background(), archive, "internal", PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, contract, pg, es, objects, time.Now().UTC())
if err != nil {
t.Fatalf("valid Wiki string status rejected: %v", err)
}
saved, err := archive.Load(id)
if err != nil {
t.Fatal(err)
}
found := false
for _, part := range saved.Parts {
if part.Name != tc.table {
continue
}
found = true
r, e := archive.OpenPart(part)
if e != nil {
t.Fatal(e)
}
data, e := io.ReadAll(r)
r.Close()
if e != nil {
t.Fatal(e)
}
var rows []json.RawMessage
if e = json.Unmarshal(data, &rows); e != nil {
t.Fatal(e)
}
if len(rows) != 1 {
t.Fatalf("wiki rows=%d", len(rows))
}
var row map[string]any
if e = json.Unmarshal(rows[0], &row); e != nil {
t.Fatal(e)
}
if row["status"] != tc.status || row["content"] != "complete wiki body" {
t.Fatal("Wiki status/body changed in archive")
}
}
if !found {
t.Fatal("Wiki part missing")
}
})
}
}