Compare commits

...

8 Commits

Author SHA1 Message Date
姚章浩 864a1632e0 test(snapshot): 增加真实测试源只读诊断并记录孤立索引阻塞
build / build (push) Successful in 1m11s
2026-10-28 08:32:23 +08:00
姚章浩 9f990158b9 test(snapshot): 联合验证真实隔离存储与暂停恢复链
build / build (push) Successful in 1m8s
2026-10-28 08:22:21 +08:00
姚章浩 3dc854de4b fix(snapshot): 阻止旧策略作业重放冒充新验收口径
build / build (push) Successful in 1m6s
2026-10-28 08:05:39 +08:00
姚章浩 76f687b52d feat(snapshot): 按已确认口径保留索引产物并标记验收策略
build / build (push) Successful in 1m12s
2026-10-28 08:01:46 +08:00
姚章浩 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
16 changed files with 880 additions and 31 deletions
+42
View File
@@ -1,5 +1,47 @@
# Changelog
## 开发快照 snapshot/v0.1.105 - 2026-10-28
### Fixed
- 修复成功作业重放遗漏验收策略检查的问题:旧快照缺少当前策略标识时明确拒绝,不静默升级验收口径,不返回成功状态或快照 ID,也不重新暂停测试写入服务。
- 新策略的正常重放与跨库、归档丢失等保护保持有效;此修复不代表内容/问答/性能验收绑定或整库业务链已经完成。
## 开发快照 snapshot/v0.1.104 - 2026-10-28
### Changed
- 按已确认的验收口径 A,正文索引作为原始产物保留,不再因无法从数据库反推临时生成上下文而拒绝候选归档;身份、覆盖、摘要及持久化生成问题的精确核验保持不变。
- 候选清单加入受支持的验收策略标识并纳入快照身份。候选归档不代表语义验收或生产放行;真实冻结接线、快照绑定的内容/问答/性能验收与完整同步恢复仍待完成。
## 开发快照 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
+30 -1
View File
@@ -6,6 +6,15 @@
现有文档包发布与执行级补偿只能作为复用基础,不能作为本清单完成证据。静态样图不作为产品运行证据。组织绩效与周报外发不在本次范围。
## 已确认:验收口径 A(原始产物)
用户选择不修改 WeKnora,以冻结的完整知识版本绑定内容、问答与性能验收。源端索引可能含未持久化的生成上下文,不再要求从 PostgreSQL 正文反推每条正文索引的生成过程。
- 原样归档索引内容与向量,不重新生成;继续校验库/文档/分块身份关联、覆盖、数量、资源及摘要。已持久化生成问题仍按 ID 和原文精确校验。
- 新候选清单记录 `validation_policy=artifact-acceptance-v1`,该字段纳入内容寻址身份;历史无该字段的快照不冒称执行了新口径。
- 候选归档成功不证明冻结、内容质量、问答正确性或性能通过。测试验收必须绑定具体快照身份;旧快照验收不得放行新快照。生产发布仍须独立授权。
- 本次只完成候选产物保留和口径记录,真实冻结业务接线与持久化验收绑定尚未完成,不能因此放行生产。
## 已确认:封存隔离方案 A
用户选择封存期间自动暂停测试 WeKnora 服务,封存后恢复,不修改 WeKnora 源码。测试问答在暂停期间暂不可用,停用时长须实测;不暂停生产服务,也不因此取得生产同步、恢复或真实清理授权。
@@ -85,6 +94,26 @@
4. 生产预备份、独立恢复演练、持久化协调作业、授权 API、真实进度、发布页面与完整存储治理仍未交付;以上验收项目保持待验证。
5. 基础模块已随 `0.1.96 / 9105f8316cc870a62b5ddacd1496f0cb0f798d87` 提交、推送并部署到本地测试治理平台;运行 API/worker 的二进制摘要已读回校验。该部署不等于业务功能接线或完整验收通过;未执行生产同步、恢复或真实业务清理。完整验收仍受本节及下述缺失接线阻塞。
## 真实测试源只读诊断(未通过)
`TestLibrarySourceReadOnlyDiagnostic` 仅在明确 opt-in 下运行,数据库连接强制只读;只调用 ES 查询/PIT 和 OSS 对象读取,不执行生产操作、源数据清理或服务暂停。测试凭据仅通过子进程环境注入,不记录配置值。
本次实际执行退出码 1:对内库 125 条索引记录中有 13 条关联到未被完整文档集合纳入的分块;进一步只读查询定位为 4 个未删除分块(3 个 text、1 个 summary)缺少同租户的父文档,不是临时上下文内容比较失败。现有身份校验保持拒绝,没有忽略这些记录或据此放行。独立 OSS 读取校验覆盖 21 个资源、53,490,166 字节。对外库读到 0 文档、0 分块、1 个 Wiki 页面,候选结构归档可读回,但未冻结且模型兼容身份为明确诊断占位,不能当作版本验收通过。
证据:`backups/library-source-readonly-20261028/`。真实源诊断失败与默认 CI 的环境跳过分别记录;此次发现不授权清理这批分块或索引,之前仅限死信 ID 1 的授权不扩展使用。
## 联合隔离捕获验收
新增 `TestLibraryCaptureIsolatedStack`,在同一次 `CaptureLibrary` 调用中连接真实隔离 PostgreSQL、随机 Elasticsearch 索引、真实 Docker 暂停/恢复控制器和本地资源文件读取器。写入服务使用无网络、无宿主挂载的 busybox 夹具,不是实际 WeKnora;资源读取不是实际 OSS/S3 验收。
- 非空文档、分块、资源、Wiki 正文及字符串状态归档后读回;检查无跨租户记录或会话数据泄漏。
- 删除真实夹具索引记录后,新捕获必须失败,原运行容器仍恢复健康。
- 删除源资源文件、修改源 PostgreSQL、删除源 ES 文档后,成功作业重放仍返回原快照,不再调用源端就绪检查或资源读取;归档重新加载通过。
- 反向自检使用 Go overlay 仅关闭 legacy 索引覆盖检查:同一联合用例退出码 1,明确报 `missing real index accepted`;未修改的实现复跑退出码 0。
- `make verify` 与三包 race 回归退出码 0;新用例在默认 CI 中显式声明环境跳过,本地单独实际执行。夹具索引和容器删除后读回不存在,随机隔离数据库已删除。
证据:`backups/library-stack-acceptance-20261028/`。该联合用例补充捕获协调证据,不证明真实源全部写入者受控、Wiki 撤销语义、内容/问答/性能验收绑定或生产同步恢复已经完成。
## 方案 A:暂停与恢复原语的实测证据
新增 `internal/libraryfreeze/`,包含持久化作业日志、源服务组互斥、暂停前原运行状态、不可变容器 ID、恢复读回,以及本地 Unix socket Docker 控制器。Docker 控制器只接受对应 source 且 `environment=test`、`freeze-role=writer` 的容器;不按模糊名称选取,不控制数据库/索引存储,不使用远程默认 Docker context。运行容器必须有健康检查。
@@ -101,4 +130,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。
+14 -7
View File
@@ -20,6 +20,9 @@ import (
)
const Format = "weknora-library-snapshot/v1"
// ArtifactAcceptancePolicy requires separate snapshot-bound semantic acceptance.
const ArtifactAcceptancePolicy = "artifact-acceptance-v1"
const maxManifestBytes = 16 * 1024 * 1024
type Part struct {
@@ -39,13 +42,14 @@ type Compatibility struct {
}
type Manifest struct {
Compatibility Compatibility `json:"compatibility"`
Format string `json:"format"`
Scope string `json:"scope"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
CreatedAt time.Time `json:"created_at"`
Parts []Part `json:"parts"`
ValidationPolicy string `json:"validation_policy,omitempty"`
Compatibility Compatibility `json:"compatibility"`
Format string `json:"format"`
Scope string `json:"scope"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
CreatedAt time.Time `json:"created_at"`
Parts []Part `json:"parts"`
}
type Archive struct {
root, blobs, versions *os.Root
@@ -361,6 +365,9 @@ func identifier(s string) bool {
}
func encodeManifest(m Manifest) ([]byte, error) {
if m.ValidationPolicy != "" && m.ValidationPolicy != ArtifactAcceptancePolicy {
return nil, errors.New("unsupported snapshot validation policy")
}
c := m.Compatibility
if c.WeKnoraVersion != releasebundle.WeKnoraVersionV071 || c.SchemaVersion != releasebundle.WeKnoraMigrationV071 || c.RetrieverEngine != "elasticsearch_v8" || !identifier(c.EmbeddingModel) || c.EmbeddingDimension != releasebundle.EmbeddingDimensionV071 || !validDigest(c.IndexMappingSHA256) {
return nil, errors.New("unsupported snapshot compatibility contract")
+62 -16
View File
@@ -24,7 +24,7 @@ func ArchiveLibraryCandidate(ctx context.Context, archive *librarysnapshot.Archi
if es.MappingSHA256 != contract.IndexMappingSHA256 {
return "", errors.New("library mapping contract mismatch")
}
manifest := librarysnapshot.Manifest{Format: librarysnapshot.Format, Scope: scope, TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, CreatedAt: createdAt, Compatibility: contract}
manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy, Format: librarysnapshot.Format, Scope: scope, TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, CreatedAt: createdAt, Compatibility: contract}
put := func(kind, name string, count int64, data []byte) error {
if err := ctx.Err(); err != nil {
return err
@@ -105,18 +105,22 @@ 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"`
ChunkStatus int `json:"-"`
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 validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es SearchSnapshot) error {
@@ -156,12 +160,26 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
// use strings. Decode chunk metadata only for its owning table.
if table.Name == "chunks" {
var metadata struct {
Status int `json:"status"`
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) {
@@ -233,6 +251,7 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
}
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] {
@@ -240,18 +259,45 @@ 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")
}
indexedChunks[row.ChunkID] = true
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 {
// Preserve the captured artifact; transient generation context is not
// reconstructible from PG. This is not semantic acceptance or release approval.
if strings.TrimSpace(row.Content) == "" {
return errors.New("empty library index content")
}
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")
}
@@ -0,0 +1,86 @@
package v071
import (
"bytes"
"context"
"encoding/json"
"io"
"os"
"testing"
"time"
"knowledge-governance/internal/librarysnapshot"
)
func TestLibraryCandidateArtifactPolicyPreservesContextIndex(t *testing.T) {
pg, es, objects := libraryCandidateFixture()
es.Documents[0].Source = json.RawMessage(`{"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","chunk_id":"chunk-safe","source_id":"chunk-safe","content":"Title\nTransient heading\n\nchunk","embedding":[0.1,0.2]}`)
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
expected, err := json.Marshal(es.Documents)
if err != nil {
t.Fatal(err)
}
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("artifact candidate rejected because generation cannot be reconstructed: %v", err)
}
m, err := archive.Load(id)
if err != nil {
t.Fatal(err)
}
encoded, err := json.Marshal(m)
if err != nil {
t.Fatal(err)
}
var fields map[string]any
if err = json.Unmarshal(encoded, &fields); err != nil {
t.Fatal(err)
}
if fields["validation_policy"] != "artifact-acceptance-v1" {
t.Fatal("candidate lacks explicit artifact acceptance policy")
}
found := false
for _, part := range m.Parts {
if part.Kind != "index" {
continue
}
found = true
r, e := archive.OpenPart(part)
if e != nil {
t.Fatal(e)
}
got, e := io.ReadAll(r)
r.Close()
if e != nil {
t.Fatal(e)
}
if !bytes.Equal(got, expected) {
t.Fatal("archived index content or vector rewritten")
}
}
m.ValidationPolicy = "unsupported-policy"
if _, err := archive.Seal(m); err == nil {
t.Fatal("unknown policy accepted")
}
m.ValidationPolicy = ""
legacyID, err := archive.Seal(m)
if err != nil {
t.Fatal(err)
}
if legacyID == id {
t.Fatal("validation policy was not bound into snapshot identity")
}
if !found {
t.Fatal("index missing")
}
}
@@ -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
}
@@ -58,6 +64,9 @@ func CaptureLibrary(ctx context.Context, freeze *libraryfreeze.Coordinator, arch
if err != nil {
return libraryfreeze.Result{}, errors.New("captured library archive no longer verifies")
}
if saved.ValidationPolicy != librarysnapshot.ArtifactAcceptancePolicy {
return libraryfreeze.Result{}, errors.New("library capture validation policy conflicts with existing job")
}
if saved.Scope != req.Scope || saved.TenantID != req.Identity.TenantID || saved.KnowledgeBaseID != req.Identity.KnowledgeBaseID || saved.Compatibility != req.Compatibility || !saved.CreatedAt.Equal(req.CreatedAt) {
return libraryfreeze.Result{}, errors.New("library capture request conflicts with existing job")
}
@@ -0,0 +1,241 @@
package v071
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/libraryfreeze"
"knowledge-governance/internal/librarysnapshot"
)
// The writer is a real disposable Docker process, not a deployed WeKnora.
// This tests capture orchestration, not production readiness or Wiki semantics.
func TestLibraryCaptureIsolatedStack(t *testing.T) {
dsn, base := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL"), os.Getenv("KG_LIBRARY_TEST_ELASTIC_URL")
if dsn == "" || base == "" || os.Getenv("KG_FREEZE_DOCKER_ISOLATED") != "1" {
t.Skip("requires isolated PG, ES and disposable Docker opt-in")
}
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
t.Fatal("isolated database required")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
db, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal("open isolated PG")
}
defer db.Close()
if _, err = db.Exec(ctx, libraryTestSchema); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `ALTER TABLE resources ADD COLUMN provider text DEFAULT 's3', ADD COLUMN size bigint DEFAULT 8;
ALTER TABLE wiki_pages ADD COLUMN status text DEFAULT 'published';
ALTER TABLE wiki_page_issues ADD COLUMN status text DEFAULT 'open';`); err != nil {
t.Fatal(err)
}
token := make([]byte, 8)
if _, err = rand.Read(token); err != nil {
t.Fatal(err)
}
source := "kg-freeze-test-" + hex.EncodeToString(token)
index := "kg_library_test_" + hex.EncodeToString(token)
client := &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
request := func(method, path, body string, want int) {
t.Helper()
r, e := http.NewRequestWithContext(ctx, method, base+path, strings.NewReader(body))
if e != nil {
t.Fatal("fixture request")
}
r.Header.Set("Content-Type", "application/json")
resp, e := client.Do(r)
if e != nil {
t.Fatal("fixture HTTP failed")
}
defer resp.Body.Close()
if resp.StatusCode != want {
t.Fatalf("fixture HTTP %d, expected %d", resp.StatusCode, want)
}
}
request("PUT", "/"+index, `{"mappings":{"properties":{"tenant_id":{"type":"long"},"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"}}}}`, 200)
defer func() { request("DELETE", "/"+index, "", 200); request("HEAD", "/"+index, "", 404) }()
body := `{"tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","chunk_id":"chunk-safe","source_id":"chunk-safe","content":"Temporary context\nchunk","embedding":[0.1,0.2]}`
request("PUT", "/"+index+"/_doc/chunk-safe?refresh=true", body, 201)
search, err := NewSearchExporter(SearchExporterConfig{BaseURL: base, Index: index, PageSize: 1, HTTPClient: client})
if err != nil {
t.Fatal(err)
}
mapping, err := search.inspectMapping(ctx)
if err != nil {
t.Fatal(err)
}
docker := func(args ...string) string {
t.Helper()
c, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
out, e := exec.CommandContext(c, "docker", append([]string{"--host", "unix:///var/run/docker.sock"}, args...)...).CombinedOutput()
if e != nil {
t.Fatalf("fixture Docker failed: %v", e)
}
return strings.TrimSpace(string(out))
}
image := docker("image", "inspect", "busybox:1.36", "--format", "{{.Id}}")
id := docker("create", "--name", source, "--network", "none", "--read-only", "--tmpfs", "/tmp:rw,noexec,nosuid,size=1m", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--memory", "32m", "--cpus", "0.1", "--label", "io.knowledge-governance.freeze-source="+source, "--label", "io.knowledge-governance.environment=test", "--label", "io.knowledge-governance.freeze-role=writer", "--health-cmd", "test -f /tmp/ready", "--health-interval", "1s", "--health-timeout", "1s", "--health-retries", "3", image, "sh", "-c", "trap 'exit 0' TERM; touch /tmp/ready; while :; do sleep 1 & wait $!; done")
defer func() {
docker("rm", "-f", id)
if docker("ps", "-aq", "--filter", "label=io.knowledge-governance.freeze-source="+source) != "" {
t.Error("Docker fixture remains")
}
}()
controller, err := libraryfreeze.NewDockerController("/var/run/docker.sock", source, 10*time.Second)
if err != nil {
t.Fatal(err)
}
defer controller.Close()
if err = controller.Start(ctx, id); err != nil {
t.Fatal(err)
}
privateDir := func() string {
t.Helper()
p := t.TempDir()
if e := os.Chmod(p, 0700); e != nil {
t.Fatal(e)
}
return p
}
freeze, err := libraryfreeze.Open(privateDir(), source, controller)
if err != nil {
t.Fatal(err)
}
defer freeze.Close()
archive, err := librarysnapshot.Open(privateDir(), 1024*1024)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
objectPath := filepath.Join(privateDir(), "source.txt")
if err = os.WriteFile(objectPath, []byte("resource"), 0600); err != nil {
t.Fatal(err)
}
objects := &captureFileReader{path: objectPath}
checks := 0
ready := func(ctx context.Context) error {
items, e := controller.Inventory(ctx)
if e != nil {
return e
}
if len(items) != 1 {
return fmt.Errorf("unexpected fixture group")
}
checks++
if items[0].Running != (checks%2 == 1) {
return fmt.Errorf("wrong writer state at readiness boundary")
}
return nil
}
req := LibraryCaptureRequest{JobID: "stack-capture", 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.Now().UTC(), MaxDocuments: 100}
result, err := CaptureLibrary(ctx, freeze, archive, db, search, objects, ready, req)
if err != nil || result.State != "succeeded" {
t.Fatalf("capture failed: %v state=%s", err, result.State)
}
assertHealthy := func() {
t.Helper()
items, e := controller.Inventory(ctx)
if e != nil || len(items) != 1 || !items[0].Running || !items[0].Healthy {
t.Fatal("fixture writer not restored healthy")
}
}
assertHealthy()
saved, err := archive.Load(result.SnapshotID)
if err != nil {
t.Fatal(err)
}
seen := map[string]bool{}
for _, part := range saved.Parts {
r, e := archive.OpenPart(part)
if e != nil {
t.Fatal(e)
}
data, e := io.ReadAll(r)
r.Close()
if e != nil {
t.Fatal(e)
}
if strings.Contains(string(data), "private-session-marker") || strings.Contains(string(data), "other-scope") {
t.Fatal("unrelated data leaked")
}
switch {
case part.Kind == "index":
var docs []SearchDocument
if e = json.Unmarshal(data, &docs); e != nil {
t.Fatal(e)
}
if len(docs) != 1 || !strings.Contains(string(docs[0].Source), "Temporary context") {
t.Fatal("captured index lost")
}
seen["index"] = true
case part.Kind == "resource":
if string(data) != "resource" {
t.Fatal("resource mismatch")
}
seen["object"] = true
case part.Name == "wiki_pages":
if !strings.Contains(string(data), "old-content") || !strings.Contains(string(data), "published") {
t.Fatal("Wiki content/status lost")
}
seen["wiki"] = true
}
}
if len(seen) != 3 || saved.ValidationPolicy != librarysnapshot.ArtifactAcceptancePolicy {
t.Fatalf("incomplete captured evidence: %v", seen)
}
request("DELETE", "/"+index+"/_doc/chunk-safe?refresh=true", "", 200)
req.JobID = "stack-missing-index"
failed, err := CaptureLibrary(ctx, freeze, archive, db, search, objects, ready, req)
if err == nil || failed.State == "succeeded" {
t.Fatal("missing real index accepted")
}
assertHealthy()
if err = os.Remove(objectPath); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `UPDATE knowledges SET parse_status='processing'; UPDATE wiki_pages SET content='later-content'`); err != nil {
t.Fatal(err)
}
req.JobID = "stack-capture"
beforeCalls, beforeChecks := objects.calls, checks
replay, err := CaptureLibrary(ctx, freeze, archive, db, search, objects, ready, req)
if err != nil || replay.SnapshotID != result.SnapshotID || objects.calls != beforeCalls || checks != beforeChecks {
t.Fatal("sealed replay touched changed source")
}
assertHealthy()
if _, err = archive.Load(replay.SnapshotID); err != nil {
t.Fatal("archive depended on deleted source object")
}
t.Log("real PG + ES + Docker capture and failed-capture restoration passed; source object removed, PG changed, ES document deleted; immutable replay verified")
}
type captureFileReader struct {
path string
calls int
}
func (r *captureFileReader) Open(_ context.Context, provider, key string) (io.ReadCloser, error) {
r.calls++
if provider != "s3" || key != "source.txt" {
return nil, fmt.Errorf("unexpected synthetic resource")
}
return os.Open(r.path)
}
@@ -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
@@ -126,6 +133,24 @@ func TestLibraryCaptureMaintenanceOwnsArchiveAndRestoresOnFailure(t *testing.T)
if got, err := CaptureLibrary(context.Background(), freeze, archive, db, search, &libraryCandidateReader{}, ready, req); err == nil || got.State == "succeeded" {
t.Fatal("missing archive returned a successful candidate")
}
// Simulate a durable successful job created before the policy marker.
// Replaying it must not silently upgrade its validation contract.
saved.ValidationPolicy = ""
legacyID, err := archive.Seal(saved)
if err != nil {
t.Fatal(err)
}
req.JobID = "legacy-capture-job"
if _, err := freeze.RunPrepared(context.Background(), req.JobID, func(context.Context) error { return nil }, func(context.Context) (string, error) { return legacyID, nil }); err != nil {
t.Fatal(err)
}
stops, previousChecks := writer.stops, checks
if got, err := CaptureLibrary(context.Background(), freeze, archive, db, search, &libraryCandidateReader{}, ready, req); err == nil || got.State == "succeeded" || got.SnapshotID != "" {
t.Fatal("legacy policy replay silently upgraded to artifact acceptance")
}
if writer.stops != stops || checks != previousChecks {
t.Fatal("policy conflict touched current source")
}
})
}
}
@@ -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,42 @@
package v071
import (
"encoding/json"
"testing"
)
// Scheme A archives artifact bytes; these cases do not certify semantic quality.
func TestLibraryCandidatePreservesArtifactContentWithoutReconstruction(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", true},
{"missing body", "text", "chunk", "Document title\n", true},
{"different body", "text", "chunk", "Document title\nchanged", true},
{"unverifiable context header", "text", "chunk", "Document title\nTransient heading\n\nchunk", true},
{"nontext transform not assumed", "faq", "chunk", "Document title\nchunk", true},
{"empty artifact content", "text", "chunk", " \n", 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("empty 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,153 @@
package v071
import (
"context"
"encoding/json"
"os"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/librarysnapshot"
)
// Live read-only diagnostic, not a cross-system frozen version or release gate.
// Credentials are injected into this process only; never logged or persisted.
func TestLibrarySourceReadOnlyDiagnostic(t *testing.T) {
if os.Getenv("KG_LIBRARY_SOURCE_READONLY") != "1" {
t.Skip("requires explicit read-only test-source credentials")
}
var config struct {
DatabaseURL string
TenantID uint64
Scopes map[string]string
Search SearchExporterConfig
Object S3ObjectStoreConfig
}
if json.Unmarshal([]byte(os.Getenv("KG_LIBRARY_SOURCE_CONFIG")), &config) != nil || config.TenantID == 0 || len(config.Scopes) != 2 || config.Scopes["internal"] == "" || config.Scopes["external"] == "" {
t.Fatal("invalid read-only diagnostic configuration")
}
cfg, err := pgxpool.ParseConfig(config.DatabaseURL)
if err != nil {
t.Fatal("invalid diagnostic PG configuration")
}
cfg.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "30000"
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
db, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal("open diagnostic PG")
}
defer db.Close()
var readOnly string
if err = db.QueryRow(ctx, "SHOW default_transaction_read_only").Scan(&readOnly); err != nil || readOnly != "on" {
t.Fatal("read-only session not enforced")
}
if err = checkLibrarySourceSettlement(ctx, db); err != nil {
t.Fatal(err)
}
search, err := NewSearchExporter(config.Search)
if err != nil {
t.Fatal("invalid diagnostic search configuration")
}
objects, err := NewS3ObjectStore(config.Object)
if err != nil {
t.Fatal("invalid diagnostic object configuration")
}
for _, scope := range []string{"internal", "external"} {
t.Run(scope, func(t *testing.T) {
identity := PostgresIdentity{TenantID: config.TenantID, KnowledgeBaseID: config.Scopes[scope]}
pg, err := ExportLibrary(ctx, db, identity)
if err != nil {
t.Fatal(err)
}
es, err := search.ExportLibrary(ctx, SearchIdentity{TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID}, 100000)
if err != nil {
t.Fatal(err)
}
if err = validateLibraryCandidate(identity, pg, es); err != nil {
missing, deleted, wrongParent := 0, 0, 0
reasons := map[string]int{}
chunks := map[string]libraryRow{}
for _, raw := range pg.Table("chunks").Rows {
var r libraryRow
if json.Unmarshal(raw, &r) != nil {
t.Fatal("invalid diagnostic chunk")
}
chunks[r.ID] = r
}
for _, doc := range es.Documents {
var r libraryRow
if json.Unmarshal(doc.Source, &r) != nil {
t.Fatal("invalid diagnostic index")
}
if c, ok := chunks[r.ChunkID]; ok {
if r.KnowledgeID != c.KnowledgeID {
wrongParent++
}
continue
}
var exists bool
if e := db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chunks WHERE id=$1 AND tenant_id=$2)`, r.ChunkID, identity.TenantID).Scan(&exists); e != nil {
t.Fatal("diagnostic relation query failed")
}
if exists {
deleted++
var reason string
if e := db.QueryRow(ctx, `SELECT CASE WHEN c.deleted_at IS NOT NULL THEN 'chunk_soft_deleted' WHEN k.id IS NULL THEN 'parent_missing' WHEN k.deleted_at IS NOT NULL THEN 'parent_soft_deleted' ELSE 'scope_mismatch' END FROM chunks c LEFT JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id WHERE c.id=$1 AND c.tenant_id=$2`, r.ChunkID, identity.TenantID).Scan(&reason); e != nil {
t.Fatal("diagnostic exclusion query failed")
}
reasons[reason]++
} else {
missing++
}
}
t.Errorf("candidate rejected: %v; index_records=%d absent_chunk_records=%d existing_but_excluded_chunk_records=%d wrong_parent_records=%d", err, len(es.Documents), missing, deleted, wrongParent)
t.Logf("index exclusion reasons: %v", reasons)
probe, e := NewObjectExporter(objects, ObjectExporterLimits{MaxObjectBytes: 64 * 1024 * 1024, MaxTotalBytes: 256 * 1024 * 1024})
if e != nil {
t.Fatal(e)
}
assets, e := probe.Export(ctx, pg)
if e != nil {
t.Errorf("independent read-only resource probe: %v", e)
} else {
t.Logf("independent resource probe objects=%d bytes=%d", len(assets.Objects), assets.TotalBytes)
}
return
}
t.Logf("READONLY_DIAGNOSTIC frozen=false scope=%s documents=%d chunks=%d resources=%d wiki_pages=%d index_records=%d", scope, pg.Table("knowledges").RowCount, pg.Table("chunks").RowCount, pg.Table("resources").RowCount, pg.Table("wiki_pages").RowCount, len(es.Documents))
root := t.TempDir()
if err = os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
archive, err := librarysnapshot.Open(root, 64*1024*1024)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
// The model name is an explicit diagnostic placeholder, not deployment compatibility evidence.
compatibility := librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "diagnostic-unverified-model", EmbeddingDimension: 1024, IndexMappingSHA256: es.MappingSHA256}
id, err := ArchiveLibraryCandidate(ctx, archive, scope, identity, compatibility, pg, es, objects, time.Now().UTC())
if err != nil {
t.Fatal(err)
}
manifest, err := archive.Load(id)
if err != nil {
t.Fatal(err)
}
var count, bytes int64
for _, part := range manifest.Parts {
if part.Kind == "resource" {
count++
bytes += part.Bytes
}
}
if count != int64(pg.Table("resources").RowCount) {
t.Fatal("resource archive coverage mismatch")
}
t.Logf("READONLY_DIAGNOSTIC frozen=false scope=%s archived_resources=%d resource_bytes=%d archive_verified=true compatibility_verified=false", scope, count, bytes)
})
}
}
@@ -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)`
+10
View File
@@ -9,6 +9,16 @@
"⚠️ 文件缺失或解析不了 ⇒ 门禁红:范围声明不出来时,不许默认放行。"
],
"optional": [
{
"package": "knowledge-governance/internal/releaseadapter/v071",
"test": "TestLibrarySourceReadOnlyDiagnostic",
"reason": "仅明确只读测试源授权及进程内凭据下运行;真实 PG、ES、OSS 不冻结,属于诊断而非一致性或生产放行;默认 CI 不注入测试源凭据,实际失败必须另行保留而非算通过"
},
{
"package": "knowledge-governance/internal/releaseadapter/v071",
"test": "TestLibraryCaptureIsolatedStack",
"reason": "显式隔离 PG、随机 ES 索引和无网络 Docker 夹具的联合捕获验收;默认 CI 不连接这些服务,本地另行运行并做索引覆盖变异反向验证;不代表真实 WeKnora 写入隔离或 Wiki 语义验收"
},
{
"package": "knowledge-governance/internal/libraryfreeze",
"test": "TestFreezeIsolatedDocker",