feat(library): 整库发布支持 WeKnora 0.9.0 schema 134
build / build (push) Failing after 1m32s

按 schema 版本选 profile 并以 information_schema 能力探测放行,取代写死的
version==74;未知版本、脏库、缺表缺列、跨版本搬运一律拒绝并点名原因。
0.9.0 的索引名改从部署配置解析,wiki_log_entries 按 profile 变为可选,
归档部件集合随之一致。
This commit is contained in:
姚章浩
2026-11-16 20:22:29 +08:00
parent e8bfdbbc06
commit 3f2626f621
20 changed files with 1211 additions and 62 deletions
+22
View File
@@ -1,5 +1,27 @@
# Changelog # Changelog
## 开发快照 0.1.376(WeKnora 0.9.0 整库发布 profile)
### Added
- 整库发布支持 WeKnora 0.9.0(schema 134):按版本号选中 profile,再用 information_schema
探测必需表与必需列,缺项精确报到「表」或「表.列」;未知版本、脏库一律拒绝,不做
「版本大于某值就放行」的推断。
- 0.9.0 的索引契约改从部署配置读取(该版本知识库不写 `vector_store_id`);两处来源都
拿不到时报错,而不是用空串去匹配索引;0.7.1 若两处都有但互相矛盾,同样拒绝。
- 归档部件集合随 profile 变化:0.9.0 已删除 `wiki_log_entries`,因此该部件不再要求;
其余 Wiki 部件仍是必需,空 Wiki 不能冒充完整。
### Fixed
- 采集、导入、Wiki 替换与「去使能」四条路径原先写死 schema 74,遇到 0.9.0 直接失败;
现在同版本(74↔74、134↔134)往返可用,跨版本搬运会明确拒绝而不是误放行。
### Tests
- 真实 0.9.0 schema 与真实索引映射上跑完整往返:导出 → 封存(真实清单校验)→ 导入
干净库 → 再导出逐行内容一致;另加未知版本、脏库、缺表、缺列、索引名解析不到等负例。
## 开发快照 0.1.375(工作台界面:越疆配色、页头统一与筛选批量条) ## 开发快照 0.1.375(工作台界面:越疆配色、页头统一与筛选批量条)
### Changed ### Changed
+209
View File
@@ -0,0 +1,209 @@
// Package libraryprofile 声明"某个 WeKnora schema 版本下,整库适配器可以依赖什么"。
//
// 为什么要有这一层:整库导出/导入原本把 `version != 74` 写死在四个入口里。
// 版本号本身不是契约——同一版本号在不同部署上也可能缺表;反过来,把判定放宽成
// `version > 74` 又会把"没见过的版本"当成"兼容"。所以这里同时声明两件事:
// - 该版本必须存在的表与列(导出/导入按它取数);
// - 该版本的归档部件集合(manifest 按它判定完整性)。
//
// 版本号只用来**选中** profile,真正的放行条件是随后对 information_schema 的
// 能力探测(见 releaseadapter 的 ResolveSchemaProfile)。
package libraryprofile
import "fmt"
// LegacyVersion 是 0.7.1 的 schema_migrations 版本号,也是既有内存夹具的默认值。
const LegacyVersion = 74
// V090Version 是 0.9.0 的 schema_migrations 版本号(已实测:134、dirty=false、83 表)。
const V090Version = 134
// PartRequirement 是归档部件的一项要求(kind/name 与 manifest 的部件键一致)。
type PartRequirement struct {
Kind string
Name string
}
// Profile 是一个 schema 版本的静态能力声明。
type Profile struct {
Name string
SchemaVersion int
WeKnoraVersion string
// EmbeddingDimension 为 0 表示"由目标 models.parameters 说了算";
// 非 0 表示该版本只接受这一定维度(0.7.1 的契约就是固定 1024)。
EmbeddingDimension int
RequiredTables []string
OptionalTables []string
RequiredColumns map[string][]string
// ReviewedTriggers 是该版本允许出现的 pg_get_triggerdef 原文。
// 触发器意味着"写一行还会改别的表",所以只接受逐字核对过的定义,
// 且这些定义必须在该版本上真实存在(消失也说明 schema 不是我们审过的那份)。
ReviewedTriggers []string
RequiredParts []PartRequirement
OptionalParts []PartRequirement
// IndexContractSource 说明该版本的索引名从哪里读。空值等于"读不到",
// 不允许回退成空串去匹配任何索引。
IndexContractSource string
}
var profiles = map[int]Profile{
LegacyVersion: {
Name: "v071",
SchemaVersion: LegacyVersion,
WeKnoraVersion: "v0.7.1",
EmbeddingDimension: 1024,
RequiredTables: []string{
"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations",
"resources", "resource_bindings", "wiki_folders", "wiki_pages",
"wiki_page_issues", "wiki_log_entries",
},
RequiredColumns: map[string][]string{
"knowledges": {"id", "tenant_id", "knowledge_base_id", "deleted_at", "parse_status"},
"chunks": {"id", "tenant_id", "knowledge_base_id", "knowledge_id", "content"},
"knowledge_tags": {"id", "tenant_id", "knowledge_base_id"},
"knowledge_tag_relations": {"knowledge_id", "tag_id"},
"resources": {"id", "handle", "tenant_id", "physical_path"},
"resource_bindings": {"id", "resource_id", "tenant_id", "owner_type", "owner_id"},
"wiki_pages": {"id", "tenant_id", "knowledge_base_id", "slug"},
"wiki_folders": {"id", "tenant_id", "knowledge_base_id"},
"wiki_page_issues": {"id", "tenant_id", "knowledge_base_id"},
"wiki_log_entries": {"id", "tenant_id", "knowledge_base_id"},
},
RequiredParts: []PartRequirement{
{"database", "knowledges"}, {"database", "chunks"},
{"database", "knowledge_tags"}, {"database", "knowledge_tag_relations"},
{"database", "resources"}, {"database", "resource_bindings"},
{"wiki", "wiki_folders"}, {"wiki", "wiki_pages"},
{"wiki", "wiki_page_issues"}, {"wiki", "wiki_log_entries"},
{"index", "chunks"},
},
IndexContractSource: "vector_stores.index_config.index_name",
},
V090Version: {
Name: "v090",
SchemaVersion: V090Version,
WeKnoraVersion: "v0.9.0",
// 0.9.0 的 KB 不写 vector_store_id,维度只能从 models.parameters 读。
EmbeddingDimension: 0,
RequiredTables: []string{
"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations",
"resources", "resource_bindings", "wiki_folders", "wiki_pages",
"wiki_page_issues",
},
// 0.9.0 删掉了 wiki_log_entries;部件集合随之为空,不许假装还有。
OptionalTables: []string{"wiki_log_entries"},
RequiredColumns: map[string][]string{
"knowledges": {"id", "tenant_id", "knowledge_base_id", "deleted_at", "parse_status"},
"chunks": {"id", "tenant_id", "knowledge_base_id", "knowledge_id", "content", "seq_id", "content_revision", "index_status"},
"knowledge_tags": {"id", "tenant_id", "knowledge_base_id"},
"knowledge_tag_relations": {"knowledge_id", "tag_id"},
"resources": {"id", "handle", "tenant_id", "physical_path"},
"resource_bindings": {"id", "resource_id", "tenant_id", "owner_type", "owner_id"},
"wiki_pages": {"id", "tenant_id", "knowledge_base_id", "slug"},
"wiki_folders": {"id", "tenant_id", "knowledge_base_id"},
"wiki_page_issues": {"id", "tenant_id", "knowledge_base_id"},
},
RequiredParts: []PartRequirement{
{"database", "knowledges"}, {"database", "chunks"},
{"database", "knowledge_tags"}, {"database", "knowledge_tag_relations"},
{"database", "resources"}, {"database", "resource_bindings"},
{"wiki", "wiki_folders"}, {"wiki", "wiki_pages"}, {"wiki", "wiki_page_issues"},
{"index", "chunks"},
},
OptionalParts: []PartRequirement{
{"wiki", "wiki_log_entries"},
},
// 0.9.0 的索引名来自部署配置(ELASTICSEARCH_INDEX),不是 vector_stores。
// 0.9.0 在 chunks 上挂了图片同步触发器(仅当 image_info 以 '[' 开头时触发),
// 它维护 chunk_images 派生表;定义逐字核对,任何改动都拒绝。
ReviewedTriggers: []string{
`CREATE TRIGGER trg_chunk_images_delete AFTER DELETE ON public.chunks FOR EACH ROW WHEN ((old.image_info ~~ '[%'::text)) EXECUTE FUNCTION chunk_images_sync()`,
`CREATE TRIGGER trg_chunk_images_insert AFTER INSERT ON public.chunks FOR EACH ROW WHEN ((new.image_info ~~ '[%'::text)) EXECUTE FUNCTION chunk_images_sync()`,
`CREATE TRIGGER trg_chunk_images_update AFTER UPDATE ON public.chunks FOR EACH ROW WHEN ((((old.image_info ~~ '[%'::text) OR (new.image_info ~~ '[%'::text)) AND ((old.image_info IS DISTINCT FROM new.image_info) OR (old.is_enabled IS DISTINCT FROM new.is_enabled) OR (old.status IS DISTINCT FROM new.status) OR (old.deleted_at IS DISTINCT FROM new.deleted_at) OR (old.tenant_id IS DISTINCT FROM new.tenant_id) OR ((old.knowledge_base_id)::text IS DISTINCT FROM (new.knowledge_base_id)::text) OR ((old.knowledge_id)::text IS DISTINCT FROM (new.knowledge_id)::text) OR ((old.chunk_type)::text IS DISTINCT FROM (new.chunk_type)::text) OR (old.created_at IS DISTINCT FROM new.created_at) OR (old.updated_at IS DISTINCT FROM new.updated_at)))) EXECUTE FUNCTION chunk_images_sync()`,
},
IndexContractSource: "config ELASTICSEARCH_INDEX",
},
}
// For 按版本号选中 profile。未知版本一律失败:版本号是"选哪份声明"的索引,
// 不是"能不能放行"的依据,所以绝不返回默认 profile。
func For(version int) (Profile, error) {
profile, ok := profiles[version]
if !ok {
return Profile{}, fmt.Errorf("unsupported WeKnora schema version %d: supported profiles are 74 (v071) and 134 (v090)", version)
}
return profile, nil
}
// Supported 返回已声明 profile 的版本号(用于文档与错误信息,不用于放行)。
func Supported() []int {
return []int{LegacyVersion, V090Version}
}
// TableSet 是"可能出现的表"集合:必需表 + 可选表。
func (p Profile) TableSet() map[string]bool {
set := make(map[string]bool, len(p.RequiredTables)+len(p.OptionalTables))
for _, name := range p.RequiredTables {
set[name] = true
}
for _, name := range p.OptionalTables {
set[name] = true
}
return set
}
// HasTable 报告某张表是否属于该 profile(必需或可选)。
func (p Profile) HasTable(name string) bool {
return p.TableSet()[name]
}
// IsRequiredTable 报告某张表是否必需存在。
func (p Profile) IsRequiredTable(name string) bool {
for _, candidate := range p.RequiredTables {
if candidate == name {
return true
}
}
return false
}
// PartKeys 返回 (必需, 可选) 的归档部件键,形如 "wiki/wiki_log_entries"。
func (p Profile) PartKeys() ([]string, []string) {
key := func(part PartRequirement) string { return part.Kind + "/" + part.Name }
required := make([]string, 0, len(p.RequiredParts))
for _, part := range p.RequiredParts {
required = append(required, key(part))
}
optional := make([]string, 0, len(p.OptionalParts))
for _, part := range p.OptionalParts {
optional = append(optional, key(part))
}
return required, optional
}
// RequiresPart 报告某部件键是否必需(可选部件返回 false)。
func (p Profile) RequiresPart(key string) bool {
required, _ := p.PartKeys()
for _, candidate := range required {
if candidate == key {
return true
}
}
return false
}
// AllowsPart 报告某部件键是否至少允许出现。
func (p Profile) AllowsPart(key string) bool {
required, optional := p.PartKeys()
for _, candidate := range required {
if candidate == key {
return true
}
}
for _, candidate := range optional {
if candidate == key {
return true
}
}
return false
}
+14 -9
View File
@@ -10,7 +10,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"io" "io"
"knowledge-governance/internal/releasebundle" "knowledge-governance/internal/libraryprofile"
"math" "math"
"os" "os"
"path/filepath" "path/filepath"
@@ -420,24 +420,29 @@ func encodeManifest(m Manifest) ([]byte, error) {
return nil, errors.New("unsupported snapshot validation policy") return nil, errors.New("unsupported snapshot validation policy")
} }
c := m.Compatibility 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) { // 兼容性按 schema 版本选 profile,而不是钉死 v0.7.1:未知版本必须拒绝,
// 已知版本还必须与自己的版本字符串、索引引擎、维度声明一致。
profile, err := libraryprofile.For(c.SchemaVersion)
if err != nil || c.WeKnoraVersion != profile.WeKnoraVersion || c.RetrieverEngine != "elasticsearch_v8" ||
!identifier(c.EmbeddingModel) || c.EmbeddingDimension < 1 ||
(profile.EmbeddingDimension > 0 && c.EmbeddingDimension != profile.EmbeddingDimension) ||
!validDigest(c.IndexMappingSHA256) {
return nil, errors.New("unsupported snapshot compatibility contract") return nil, errors.New("unsupported snapshot compatibility contract")
} }
if m.Format != Format || (m.Scope != "internal" && m.Scope != "external") || m.TenantID == 0 || !identifier(m.KnowledgeBaseID) || m.CreatedAt.IsZero() { if m.Format != Format || (m.Scope != "internal" && m.Scope != "external") || m.TenantID == 0 || !identifier(m.KnowledgeBaseID) || m.CreatedAt.IsZero() {
return nil, errors.New("invalid library manifest identity") return nil, errors.New("invalid library manifest identity")
} }
// 部件集合也来自 profile:0.9.0 的归档没有 wiki_log_entries 部件,
// 但 0.7.1 缺了它就是不完整。
requiredKeys, _ := profile.PartKeys()
required := map[string]bool{} required := map[string]bool{}
for _, n := range []string{"knowledges", "chunks", "resources", "resource_bindings", "knowledge_tags", "knowledge_tag_relations"} { for _, key := range requiredKeys {
required["database/"+n] = true required[key] = true
} }
for _, n := range []string{"wiki_pages", "wiki_folders", "wiki_page_issues", "wiki_log_entries"} {
required["wiki/"+n] = true
}
required["index/chunks"] = true
seen := map[string]bool{} seen := map[string]bool{}
for _, p := range m.Parts { for _, p := range m.Parts {
key := p.Kind + "/" + p.Name key := p.Kind + "/" + p.Name
if (!required[key] && !(p.Kind == "resource" && identifier(p.Name) && p.Count == 1) && !(key == "schema/migration-catalog" && p.Count == 1)) || seen[key] || !validDigest(p.SHA256) || p.Bytes < 0 || p.Count < 0 { if (!profile.AllowsPart(key) && !(p.Kind == "resource" && identifier(p.Name) && p.Count == 1) && !(key == "schema/migration-catalog" && p.Count == 1)) || seen[key] || !validDigest(p.SHA256) || p.Bytes < 0 || p.Count < 0 {
return nil, errors.New("invalid or nonknowledge snapshot component") return nil, errors.New("invalid or nonknowledge snapshot component")
} }
seen[key] = true seen[key] = true
@@ -0,0 +1,58 @@
package librarysnapshot
import (
"strings"
"testing"
"time"
)
// 归档部件的完整性按 schema 版本判定:0.9.0 没有 wiki_log_entries,
// 0.7.1 缺了它就是残包。这里直接对 manifest 编码做判定,不依赖数据库。
func TestManifestPartSetFollowsSchemaProfile(t *testing.T) {
part := func(kind, name string) Part {
return Part{Kind: kind, Name: name, SHA256: strings.Repeat("a", 64), Count: 1}
}
parts := []Part{
part("database", "knowledges"), part("database", "chunks"), part("database", "resources"),
part("database", "resource_bindings"), part("database", "knowledge_tags"),
part("database", "knowledge_tag_relations"),
part("wiki", "wiki_pages"), part("wiki", "wiki_folders"), part("wiki", "wiki_page_issues"),
part("index", "chunks"),
}
manifest := func(version int, weknora string, parts []Part) Manifest {
return Manifest{
ValidationPolicy: ArtifactAcceptancePolicy,
Format: Format,
Scope: "internal",
TenantID: 10000,
KnowledgeBaseID: "kb-v090",
CreatedAt: time.Now().UTC(),
Parts: parts,
Compatibility: Compatibility{
WeKnoraVersion: weknora, SchemaVersion: version,
RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "bge-m3",
EmbeddingDimension: 1024, IndexMappingSHA256: strings.Repeat("b", 64),
},
}
}
if _, err := encodeManifest(manifest(134, "v0.9.0", parts)); err != nil {
t.Fatalf("0.9.0 manifest without wiki_log_entries must be complete: %v", err)
}
if _, err := encodeManifest(manifest(74, "v0.7.1", parts)); err == nil || !strings.Contains(err.Error(), "incomplete") {
t.Fatalf("0.7.1 manifest missing wiki_log_entries must be refused, got %v", err)
}
withLog := append(append([]Part{}, parts...), part("wiki", "wiki_log_entries"))
if _, err := encodeManifest(manifest(74, "v0.7.1", withLog)); err != nil {
t.Fatalf("0.7.1 manifest with wiki_log_entries must pass: %v", err)
}
if _, err := encodeManifest(manifest(134, "v0.9.0", withLog)); err != nil {
t.Fatalf("0.9.0 manifest may still carry an optional wiki_log_entries part: %v", err)
}
if _, err := encodeManifest(manifest(74, "v0.9.0", withLog)); err == nil {
t.Fatal("version string and profile version must agree")
}
if _, err := encodeManifest(manifest(135, "v0.9.0", parts)); err == nil {
t.Fatal("unknown schema version must be refused")
}
}
@@ -3,10 +3,12 @@ package v071
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"strings" "strings"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"knowledge-governance/internal/libraryprofile"
"knowledge-governance/internal/releasebundle" "knowledge-governance/internal/releasebundle"
releaseworkflow "knowledge-governance/internal/workflows/release" releaseworkflow "knowledge-governance/internal/workflows/release"
) )
@@ -37,19 +39,23 @@ type TargetContractInspector struct {
config TargetContractInspectorConfig config TargetContractInspectorConfig
} }
// targetContractSQL 用 LEFT JOIN 读模型与向量库:命中不到时仍然拿得到"声明了什么",
// 这样缺字段能被点名拒绝,而不是整行查不出来只报一句"读契约失败"。
const targetContractSQL = ` const targetContractSQL = `
SELECT migration.version, SELECT COALESCE(migration.version, 0),
migration.dirty, COALESCE(migration.dirty, false),
knowledge_base.tenant_id, knowledge_base.tenant_id,
model.name, COALESCE(knowledge_base.embedding_model_id, ''),
COALESCE(model.name, ''),
COALESCE(NULLIF(model.parameters->'embedding_parameters'->>'dimension', '')::INTEGER, 0), COALESCE(NULLIF(model.parameters->'embedding_parameters'->>'dimension', '')::INTEGER, 0),
(model.id IS NOT NULL),
COALESCE(vector_store.engine_type, ''), COALESCE(vector_store.engine_type, ''),
COALESCE(vector_store.index_config->>'index_name', '') COALESCE(vector_store.index_config->>'index_name', '')
FROM knowledge_bases AS knowledge_base FROM knowledge_bases AS knowledge_base
JOIN models AS model LEFT JOIN models AS model
ON model.id = knowledge_base.embedding_model_id ON model.id = knowledge_base.embedding_model_id
AND model.deleted_at IS NULL AND model.deleted_at IS NULL
JOIN schema_migrations AS migration ON TRUE LEFT JOIN schema_migrations AS migration ON TRUE
LEFT JOIN vector_stores AS vector_store LEFT JOIN vector_stores AS vector_store
ON vector_store.id = knowledge_base.vector_store_id ON vector_store.id = knowledge_base.vector_store_id
AND vector_store.deleted_at IS NULL AND vector_store.deleted_at IS NULL
@@ -57,6 +63,25 @@ WHERE knowledge_base.id = $1
AND knowledge_base.deleted_at IS NULL AND knowledge_base.deleted_at IS NULL
` `
// resolveTargetIndexName 是"索引名从哪来"的唯一判定点。
//
// 0.9.0 的 KB 不写 vector_store_id(vector_stores 没有对应行),索引名只在部署
// 配置里(ELASTICSEARCH_INDEX)。两条来源都拿不到时**不许**回退成空串——
// 空串会让后续过滤条件匹配到任何索引。0.7.1 若两处都有,必须一致。
func resolveTargetIndexName(fromVectorStore, configured string, profile libraryprofile.Profile) (string, error) {
resolved := fromVectorStore
if resolved == "" {
resolved = configured
}
if !validSearchIdentifier(resolved) {
return "", fmt.Errorf("target WeKnora index name unresolved (contract source: %s): vector_stores.index_config->>'index_name' and the configured index are both empty", profile.IndexContractSource)
}
if fromVectorStore != "" && fromVectorStore != configured {
return "", fmt.Errorf("target WeKnora contract mismatch: vector_stores.index_config.index_name=%q does not match configured index %q", fromVectorStore, configured)
}
return resolved, nil
}
func NewTargetContractInspector(config TargetContractInspectorConfig) (*TargetContractInspector, error) { func NewTargetContractInspector(config TargetContractInspectorConfig) (*TargetContractInspector, error) {
config.KnowledgeBaseID = strings.TrimSpace(config.KnowledgeBaseID) config.KnowledgeBaseID = strings.TrimSpace(config.KnowledgeBaseID)
config.IndexName = strings.TrimSpace(config.IndexName) config.IndexName = strings.TrimSpace(config.IndexName)
@@ -85,29 +110,51 @@ func (inspector *TargetContractInspector) Contract(ctx context.Context, item rel
migrationVersion int migrationVersion int
dirty bool dirty bool
tenantID uint64 tenantID uint64
declaredModel string
embeddingModel string embeddingModel string
dimension int dimension int
modelBound bool
engineType string engineType string
indexName string indexName string
) )
if err := inspector.config.DB.QueryRow(ctx, targetContractSQL, targetKnowledgeBaseID).Scan( if err := inspector.config.DB.QueryRow(ctx, targetContractSQL, targetKnowledgeBaseID).Scan(
&migrationVersion, &dirty, &tenantID, &embeddingModel, &dimension, &engineType, &indexName, &migrationVersion, &dirty, &tenantID, &declaredModel, &embeddingModel, &dimension, &modelBound, &engineType, &indexName,
); err != nil { ); err != nil {
return releasebundle.TargetContract{}, errors.New("read target WeKnora contract") return releasebundle.TargetContract{}, errors.New("read target WeKnora contract")
} }
if migrationVersion != releasebundle.WeKnoraMigrationV071 || dirty || tenantID != inspector.config.TenantID || if dirty {
!validSearchIdentifier(embeddingModel) || dimension < 1 || return releasebundle.TargetContract{}, fmt.Errorf("target WeKnora schema_migrations.version=%d is dirty: refusing to publish", migrationVersion)
(engineType != "" && engineType != "elasticsearch") || }
(indexName != "" && indexName != inspector.config.IndexName) { // 版本号只用来选 profile;未知版本失败关闭,错误里带真实版本号。
return releasebundle.TargetContract{}, errors.New("target WeKnora contract mismatch") profile, err := libraryprofile.For(migrationVersion)
if err != nil {
return releasebundle.TargetContract{}, fmt.Errorf("target WeKnora: %w", err)
}
if tenantID != inspector.config.TenantID {
return releasebundle.TargetContract{}, fmt.Errorf("target WeKnora contract mismatch: knowledge_bases.tenant_id=%d, expected %d", tenantID, inspector.config.TenantID)
}
if !validSearchIdentifier(declaredModel) {
return releasebundle.TargetContract{}, errors.New("target WeKnora contract mismatch: knowledge_bases.embedding_model_id is empty: embedding dimension is unknowable")
}
if !modelBound {
return releasebundle.TargetContract{}, fmt.Errorf("target WeKnora contract mismatch: models row for knowledge_bases.embedding_model_id %q is missing or deleted", declaredModel)
}
if !validSearchIdentifier(embeddingModel) || dimension < 1 {
return releasebundle.TargetContract{}, fmt.Errorf("target WeKnora contract mismatch: models.parameters.embedding_parameters.dimension is missing for model %q", declaredModel)
}
if engineType != "" && engineType != "elasticsearch" {
return releasebundle.TargetContract{}, fmt.Errorf("target WeKnora contract mismatch: vector_stores.engine_type=%q is not elasticsearch", engineType)
}
if _, err := resolveTargetIndexName(indexName, inspector.config.IndexName, profile); err != nil {
return releasebundle.TargetContract{}, err
} }
mappingSHA256, err := inspector.config.Mapping.MappingSHA256(ctx) mappingSHA256, err := inspector.config.Mapping.MappingSHA256(ctx)
if err != nil || !validLowerSHA256(mappingSHA256) { if err != nil || !validLowerSHA256(mappingSHA256) {
return releasebundle.TargetContract{}, errors.New("read target Elasticsearch mapping contract") return releasebundle.TargetContract{}, errors.New("read target Elasticsearch mapping contract")
} }
return releasebundle.TargetContract{ return releasebundle.TargetContract{
WeKnoraVersion: releasebundle.WeKnoraVersionV071, WeKnoraVersion: profile.WeKnoraVersion,
MigrationVersion: releasebundle.WeKnoraMigrationV071, MigrationVersion: profile.SchemaVersion,
TenantID: tenantID, TenantID: tenantID,
KnowledgeBaseID: targetKnowledgeBaseID, KnowledgeBaseID: targetKnowledgeBaseID,
RetrieverEngine: "elasticsearch_v8", RetrieverEngine: "elasticsearch_v8",
@@ -9,7 +9,7 @@ import (
) )
func TestTargetContractInspectorReadsOnlyCompatibilityFields(t *testing.T) { func TestTargetContractInspectorReadsOnlyCompatibilityFields(t *testing.T) {
db := &contractDB{row: contractRow{values: []any{74, false, uint64(10000), "bge-m3", 1024, "elasticsearch", "chunks"}}} db := &contractDB{row: contractRow{values: []any{74, false, uint64(10000), "bge-m3", "bge-m3", 1024, true, "elasticsearch", "chunks"}}}
mapping := &mappingInspector{sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"} mapping := &mappingInspector{sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}
inspector, err := NewTargetContractInspector(TargetContractInspectorConfig{DB: db, Mapping: mapping, KnowledgeBaseID: "kb-safe", TenantID: 10000, IndexName: "chunks"}) inspector, err := NewTargetContractInspector(TargetContractInspectorConfig{DB: db, Mapping: mapping, KnowledgeBaseID: "kb-safe", TenantID: 10000, IndexName: "chunks"})
if err != nil { if err != nil {
@@ -36,7 +36,7 @@ func TestTargetContractInspectorReadsOnlyCompatibilityFields(t *testing.T) {
} }
func TestTargetContractInspectorRejectsMismatchedPlanKB(t *testing.T) { func TestTargetContractInspectorRejectsMismatchedPlanKB(t *testing.T) {
db := &contractDB{row: contractRow{values: []any{74, false, uint64(10000), "bge-m3", 1024, "elasticsearch", "chunks"}}} db := &contractDB{row: contractRow{values: []any{74, false, uint64(10000), "bge-m3", "bge-m3", 1024, true, "elasticsearch", "chunks"}}}
inspector, _ := NewTargetContractInspector(TargetContractInspectorConfig{DB: db, Mapping: &mappingInspector{sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, KnowledgeBaseID: "kb-safe", TenantID: 10000, IndexName: "chunks"}) inspector, _ := NewTargetContractInspector(TargetContractInspectorConfig{DB: db, Mapping: &mappingInspector{sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, KnowledgeBaseID: "kb-safe", TenantID: 10000, IndexName: "chunks"})
plan := releasePlanForArchive() plan := releasePlanForArchive()
plan.TestKnowledgeBaseID = "other-kb" plan.TestKnowledgeBaseID = "other-kb"
@@ -50,7 +50,7 @@ func TestTargetContractInspectorRejectsMismatchedPlanKB(t *testing.T) {
// the mapped base on the source plane made a real release fail with // the mapped base on the source plane made a real release fail with
// "source WeKnora release contract mismatch" (the target base is unknown there). // "source WeKnora release contract mismatch" (the target base is unknown there).
func TestTargetContractInspectorSidesPickTheRightBase(t *testing.T) { func TestTargetContractInspectorSidesPickTheRightBase(t *testing.T) {
row := contractRow{values: []any{74, false, uint64(10000), "bge-m3", 1024, "elasticsearch", "chunks"}} row := contractRow{values: []any{74, false, uint64(10000), "bge-m3", "bge-m3", 1024, true, "elasticsearch", "chunks"}}
mapping := &mappingInspector{sha: strings.Repeat("a", 64)} mapping := &mappingInspector{sha: strings.Repeat("a", 64)}
plan := releasePlanForArchive() plan := releasePlanForArchive()
plan.TargetKnowledgeBaseID = "prod-kb" plan.TargetKnowledgeBaseID = "prod-kb"
@@ -0,0 +1,35 @@
package v071
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
)
// IndexMappingDigest 与线上读取路径(SearchExporter.inspectMapping)用同一套规范化:
// 取 ES `/{index}/_mapping` 响应里该索引的 mappings,规范 JSON 后取 sha256。
//
// 单独暴露它是为了能用**真实抓下来的映射**证明摘要可算,并证明 0.7.1 与 0.9.0
// 的映射是两个不同契约(不能因为"都是 1024 维"就当同一份)。
func IndexMappingDigest(raw []byte) (string, error) {
var response map[string]json.RawMessage
if err := json.Unmarshal(raw, &response); err != nil || len(response) != 1 {
return "", errors.New("Elasticsearch mapping response is invalid")
}
for _, indexRaw := range response {
var index struct {
Mappings json.RawMessage `json:"mappings"`
}
if err := json.Unmarshal(indexRaw, &index); err != nil || len(index.Mappings) == 0 {
return "", errors.New("Elasticsearch mapping response is invalid")
}
canonical, err := canonicalJSON(index.Mappings)
if err != nil {
return "", errors.New("Elasticsearch mapping response is invalid")
}
digest := sha256.Sum256(canonical)
return hex.EncodeToString(digest[:]), nil
}
return "", errors.New("Elasticsearch mapping response is invalid")
}
@@ -145,13 +145,19 @@ type libraryRow struct {
} }
func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es SearchSnapshot) error { func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es SearchSnapshot) error {
required := map[string]bool{"resources": true} // 必需表来自 profile,不是固定清单:0.9.0 没有 wiki_log_entries 就不要求它,
for _, entry := range libraryContentQueries { // 但只要表在 profile 里是必需的,缺了就必须失败。
required[entry.name] = true profile, err := pg.schemaProfile()
if err != nil {
return err
}
required := map[string]bool{}
for _, name := range profile.RequiredTables {
required[name] = true
} }
tables := map[string]map[string]libraryRow{} tables := map[string]map[string]libraryRow{}
for _, table := range pg.Tables { for _, table := range pg.Tables {
if !required[table.Name] || tables[table.Name] != nil || table.RowCount != len(table.Rows) || table.SHA256 != newTableSnapshot(table.Name, table.Rows).SHA256 { if !profile.HasTable(table.Name) || tables[table.Name] != nil || table.RowCount != len(table.Rows) || table.SHA256 != newTableSnapshot(table.Name, table.Rows).SHA256 {
return errors.New("invalid library table inventory") return errors.New("invalid library table inventory")
} }
rows := map[string]libraryRow{} rows := map[string]libraryRow{}
@@ -19,15 +19,14 @@ func exportLibraryBeforeImage(ctx context.Context, db librarySnapshotDB, identit
return PostgresSnapshot{}, err return PostgresSnapshot{}, err
} }
defer tx.Rollback(context.WithoutCancel(ctx)) defer tx.Rollback(context.WithoutCancel(ctx))
var version int profile, err := ResolveSchemaProfile(ctx, tx, "before-image source")
var dirty bool if err != nil {
if err := tx.QueryRow(ctx, `SELECT version,dirty FROM schema_migrations LIMIT 1`).Scan(&version, &dirty); err != nil || version != 74 || dirty { return PostgresSnapshot{}, err
return PostgresSnapshot{}, errors.New("before-image schema contract mismatch")
} }
exporter := PostgresExporter{db: tx} exporter := PostgresExporter{db: tx}
rowsByTable := map[string][]json.RawMessage{} rowsByTable := map[string][]json.RawMessage{}
var bodies, bindings []json.RawMessage var bodies, bindings []json.RawMessage
for _, table := range productionLibraryTables { for _, table := range profile.Tables {
if table == "resources" { if table == "resources" {
continue continue
} }
@@ -50,8 +49,8 @@ func exportLibraryBeforeImage(ctx context.Context, db librarySnapshotDB, identit
return PostgresSnapshot{}, err return PostgresSnapshot{}, err
} }
rowsByTable["resources"] = resources rowsByTable["resources"] = resources
snapshot := PostgresSnapshot{} snapshot := PostgresSnapshot{SchemaVersion: profile.SchemaVersion, Profile: profile.Name}
for _, table := range productionLibraryTables { for _, table := range profile.Tables {
snapshot.Tables = append(snapshot.Tables, newTableSnapshot(table, rowsByTable[table])) snapshot.Tables = append(snapshot.Tables, newTableSnapshot(table, rowsByTable[table]))
} }
handles, err := libraryResourceHandles(bodies) handles, err := libraryResourceHandles(bodies)
+11 -7
View File
@@ -29,10 +29,10 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
return PostgresSnapshot{}, errors.New("begin library snapshot") return PostgresSnapshot{}, errors.New("begin library snapshot")
} }
defer tx.Rollback(context.WithoutCancel(ctx)) defer tx.Rollback(context.WithoutCancel(ctx))
var version int // 版本号只用来选 profile;放行条件是随后的表/列能力探测。
var dirty bool profile, err := ResolveSchemaProfile(ctx, tx, "source library")
if err := tx.QueryRow(ctx, `SELECT version,dirty FROM schema_migrations LIMIT 1`).Scan(&version, &dirty); err != nil || version != 74 || dirty { if err != nil {
return PostgresSnapshot{}, errors.New("source library schema contract mismatch") return PostgresSnapshot{}, err
} }
var graph bool var graph bool
if err := tx.QueryRow(ctx, `SELECT COALESCE((indexing_strategy->>'graph_enabled')::boolean,false) FROM knowledge_bases WHERE tenant_id=$1 AND id=$2 AND deleted_at IS NULL`, identity.TenantID, identity.KnowledgeBaseID).Scan(&graph); err != nil { if err := tx.QueryRow(ctx, `SELECT COALESCE((indexing_strategy->>'graph_enabled')::boolean,false) FROM knowledge_bases WHERE tenant_id=$1 AND id=$2 AND deleted_at IS NULL`, identity.TenantID, identity.KnowledgeBaseID).Scan(&graph); err != nil {
@@ -62,15 +62,19 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
return PostgresSnapshot{}, err return PostgresSnapshot{}, err
} }
exporter := PostgresExporter{db: tx} exporter := PostgresExporter{db: tx}
var snapshot PostgresSnapshot snapshot := PostgresSnapshot{SchemaVersion: profile.SchemaVersion, Profile: profile.Name}
snapshot.Catalog, _, err = captureMigrationCatalog(ctx, tx) snapshot.Catalog, _, err = captureMigrationCatalogFor(ctx, tx, profile.CatalogTables())
if err != nil { if err != nil {
return PostgresSnapshot{}, err return PostgresSnapshot{}, err
} }
if err = validateMigrationCatalog(snapshot.Catalog); err != nil { if err = validateMigrationCatalogFor(snapshot.Catalog, profile.CatalogTables(), profile.Profile); err != nil {
return PostgresSnapshot{}, err return PostgresSnapshot{}, err
} }
for _, entry := range libraryContentQueries { for _, entry := range libraryContentQueries {
// 0.9.0 没有 wiki_log_entries:不产生该部件,也不去查不存在的表。
if !profile.HasTable(entry.name) {
continue
}
rows, err := exporter.queryRows(ctx, entry.sql, identity.TenantID, identity.KnowledgeBaseID) rows, err := exporter.queryRows(ctx, entry.sql, identity.TenantID, identity.KnowledgeBaseID)
if err != nil { if err != nil {
return PostgresSnapshot{}, err return PostgresSnapshot{}, err
@@ -103,6 +103,10 @@ func (d *libraryFixtureTx) Query(_ context.Context, q string, _ ...any) (pgx.Row
if d.queryError { if d.queryError {
return nil, errors.New("fixture failure") return nil, errors.New("fixture failure")
} }
// 能力探测走真实 SQL:假库按 0.7.1 profile 回答,避免"桩放行"。
if strings.Contains(q, "information_schema.columns") {
return legacySchemaProbeRows(), nil
}
// 死信行按真实形状返回:解除判定必须逐字节比对指纹,空结果会让"存在即阻断"失效。 // 死信行按真实形状返回:解除判定必须逐字节比对指纹,空结果会让"存在即阻断"失效。
if strings.Contains(q, "to_jsonb(d)") && d.failed > 0 { if strings.Contains(q, "to_jsonb(d)") && d.failed > 0 {
return &jsonRows{values: []json.RawMessage{json.RawMessage(fixtureDeadLetter)}}, nil return &jsonRows{values: []json.RawMessage{json.RawMessage(fixtureDeadLetter)}}, nil
@@ -0,0 +1,182 @@
package v071
import (
"context"
"encoding/json"
"os"
"sort"
"strings"
"testing"
"time"
"knowledge-governance/internal/librarysnapshot"
)
// v090MappingDigest 读真实抓下来的 0.9.0 映射(KG_V090_MAPPING_JSON)。
func v090MappingDigest(t *testing.T) string {
t.Helper()
path := os.Getenv("KG_V090_MAPPING_JSON")
if path == "" {
t.Skip("requires KG_V090_MAPPING_JSON pointing at the captured 0.9.0 index mapping")
}
raw, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read KG_V090_MAPPING_JSON: %v", err)
}
digest, err := IndexMappingDigest(raw)
if err != nil {
t.Fatalf("mapping digest: %v", err)
}
return digest
}
// TestV090LibraryRoundTripIsolated 走完整 0.9.0 往返:
// 导出 → 封存(真实 manifest 校验)→ 导入干净 134 schema → 再导出逐行比对。
func TestV090LibraryRoundTripIsolated(t *testing.T) {
ctx := context.Background()
src := v090Pool(t, "KG_V090_SOURCE_DSN")
identity := seedV090(t, ctx, src)
mappingSHA := v090MappingDigest(t)
source, err := ExportLibrary(ctx, src, identity)
if err != nil {
t.Fatalf("export 0.9.0 library: %v", err)
}
if source.SchemaVersion != 134 || source.Profile != "v090" {
t.Fatalf("snapshot must record the 0.9.0 profile, got %d/%q", source.SchemaVersion, source.Profile)
}
// 0.9.0 没有 wiki_log_entries:不允许出现该表,也不允许空 Wiki 冒充通过。
if tablePresent(source, "wiki_log_entries") {
t.Fatal("0.9.0 export must not produce a wiki_log_entries table")
}
if source.Table("wiki_pages").RowCount < 1 || source.Table("wiki_folders").RowCount < 1 {
t.Fatalf("wiki parts must be non-empty: pages=%d folders=%d",
source.Table("wiki_pages").RowCount, source.Table("wiki_folders").RowCount)
}
if source.Table("chunks").RowCount < 2 || source.Table("knowledges").RowCount != 1 {
t.Fatalf("unexpected fixture shape: chunks=%d knowledges=%d",
source.Table("chunks").RowCount, source.Table("knowledges").RowCount)
}
es := v090IndexSnapshot(t, source, mappingSHA)
root := t.TempDir()
if err := os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
archive, err := librarysnapshot.Open(root, 64<<20)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
contract := librarysnapshot.Compatibility{
WeKnoraVersion: "v0.9.0", SchemaVersion: 134,
RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "bge-m3",
EmbeddingDimension: 1024, IndexMappingSHA256: mappingSHA,
}
sealed, err := ArchiveLibraryCandidate(ctx, archive, "internal", identity, contract, source, es,
v090Objects{"fixture/kn-v090.bin": []byte("fixture-object-bytes")}, time.Now().UTC())
if err != nil {
t.Fatalf("seal 0.9.0 archive: %v", err)
}
manifest, err := archive.Load(sealed)
if err != nil {
t.Fatalf("load sealed manifest: %v", err)
}
if manifest.Compatibility.SchemaVersion != 134 || manifest.Compatibility.WeKnoraVersion != "v0.9.0" {
t.Fatalf("manifest must record the 0.9.0 profile, got %+v", manifest.Compatibility)
}
for _, part := range manifest.Parts {
if part.Kind == "wiki" && part.Name == "wiki_log_entries" {
t.Fatal("0.9.0 archive must not contain a wiki_log_entries part")
}
}
dst := v090Pool(t, "KG_V090_TARGET_DSN")
if err := seedV090Binding(t, ctx, dst); err != nil {
t.Fatalf("seed target binding: %v", err)
}
importer, err := NewPostgresImporter(dst)
if err != nil {
t.Fatal(err)
}
document := PostgresIdentity{TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, KnowledgeID: v090Knowledge}
if err := importer.Replace(ctx, document, source); err != nil {
t.Fatalf("import 0.9.0 snapshot: %v", err)
}
reloaded, err := ExportLibrary(ctx, dst, identity)
if err != nil {
t.Fatalf("re-export imported library: %v", err)
}
compareSnapshotContent(t, source, reloaded)
// 0.9.0 新增的 NOT NULL 列在导入后必须仍是合法值,且 seq_id 由目标序列分配。
var defaults int
if err := dst.QueryRow(ctx, `SELECT count(*) FROM chunks
WHERE source_content IS NOT NULL AND content_revision IS NOT NULL
AND index_status IS NOT NULL AND context_header IS NOT NULL
AND last_editor_id IS NOT NULL AND seq_id IS NOT NULL`).Scan(&defaults); err != nil {
t.Fatal(err)
}
if defaults != source.Table("chunks").RowCount {
t.Fatalf("0.9.0 NOT NULL columns must be satisfied on every imported chunk: got %d want %d",
defaults, source.Table("chunks").RowCount)
}
var distinctSeq int
if err := dst.QueryRow(ctx, `SELECT count(DISTINCT seq_id) FROM chunks`).Scan(&distinctSeq); err != nil {
t.Fatal(err)
}
if distinctSeq != source.Table("chunks").RowCount {
t.Fatalf("target chunk seq_id must be assigned, got %d distinct", distinctSeq)
}
// 跨版本必须拒绝:0.7.1 归档不能落到 0.9.0 目标。
crossVersion := source
crossVersion.SchemaVersion = 74
crossVersion.Profile = "v071"
err = importer.Replace(ctx, document, crossVersion)
if err == nil || !strings.Contains(err.Error(), "74") || !strings.Contains(err.Error(), "134") {
t.Fatalf("cross-version import must be refused with both versions named, got %v", err)
}
}
// compareSnapshotContent 逐表逐行比对"共有列"的规范化内容。
// chunks.seq_id 是库级序列值、不是文档内容,导入时由目标分配,故排除比对。
func compareSnapshotContent(t *testing.T, source, target PostgresSnapshot) {
t.Helper()
if len(source.Tables) != len(target.Tables) {
t.Fatalf("table set changed across round trip: %d -> %d", len(source.Tables), len(target.Tables))
}
for _, table := range source.Tables {
want := tableDigests(t, table.Name, table.Rows)
got := tableDigests(t, table.Name, target.Table(table.Name).Rows)
if table.RowCount != target.Table(table.Name).RowCount || len(want) != len(got) {
t.Fatalf("%s row count changed: %d -> %d", table.Name, len(want), len(got))
}
for index := range want {
if want[index] != got[index] {
t.Fatalf("%s row %d content changed across round trip", table.Name, index)
}
}
}
}
func tableDigests(t *testing.T, name string, rows []json.RawMessage) []string {
t.Helper()
digests := make([]string, 0, len(rows))
for _, raw := range rows {
var row map[string]json.RawMessage
if err := json.Unmarshal(raw, &row); err != nil {
t.Fatalf("decode %s row: %v", name, err)
}
if name == "chunks" {
delete(row, "seq_id")
}
digest, err := canonicalRowDigest(row)
if err != nil {
t.Fatalf("digest %s row: %v", name, err)
}
digests = append(digests, digest)
}
sort.Strings(digests)
return digests
}
@@ -9,6 +9,7 @@ import (
"fmt" "fmt"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"knowledge-governance/internal/libraryprofile"
"knowledge-governance/internal/librarysnapshot" "knowledge-governance/internal/librarysnapshot"
) )
@@ -32,8 +33,15 @@ func (t *ProductionLibraryTarget) migrationCatalog(ctx context.Context) (migrati
return catalog, digest, nil return catalog, digest, nil
} }
// Source rows and their definitions must come from the same read-only transaction. // captureMigrationCatalog 是 0.7.1(既有表集合)的入口,行为保持不变。
func captureMigrationCatalog(ctx context.Context, tx pgx.Tx) (migrationCatalog, string, error) { func captureMigrationCatalog(ctx context.Context, tx pgx.Tx) (migrationCatalog, string, error) {
return captureMigrationCatalogFor(ctx, tx, productionLibraryTables)
}
// captureMigrationCatalogFor 按 profile 解析出的表集合取定义:0.9.0 没有
// wiki_log_entries,用固定清单会让整库编目在第一张不存在的表上失败。
// Source rows and their definitions must come from the same read-only transaction.
func captureMigrationCatalogFor(ctx context.Context, tx pgx.Tx, tables []string) (migrationCatalog, string, error) {
queries := map[string]string{ queries := map[string]string{
"columns": `SELECT c.relname AS table_name,a.attname AS column_name,format_type(a.atttypid,a.atttypmod) AS type,a.attnotnull AS not_null,a.attidentity AS identity,a.attgenerated AS generated,coalesce(pg_get_expr(d.adbin,d.adrelid),'') AS default_expr FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum WHERE n.nspname='public' AND c.relname=ANY($1) AND a.attnum>0 AND NOT a.attisdropped ORDER BY c.relname,a.attnum`, "columns": `SELECT c.relname AS table_name,a.attname AS column_name,format_type(a.atttypid,a.atttypmod) AS type,a.attnotnull AS not_null,a.attidentity AS identity,a.attgenerated AS generated,coalesce(pg_get_expr(d.adbin,d.adrelid),'') AS default_expr FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum WHERE n.nspname='public' AND c.relname=ANY($1) AND a.attnum>0 AND NOT a.attisdropped ORDER BY c.relname,a.attnum`,
"constraints": `SELECT ns.nspname AS namespace,c.relname AS table_name,x.conname AS name,x.contype AS type,pg_get_constraintdef(x.oid) AS definition,coalesce(r.relname,'') AS referenced_table,coalesce(rns.nspname,'') AS referenced_namespace FROM pg_constraint x JOIN pg_class c ON c.oid=x.conrelid JOIN pg_namespace ns ON ns.oid=c.relnamespace LEFT JOIN pg_class r ON r.oid=x.confrelid LEFT JOIN pg_namespace rns ON rns.oid=r.relnamespace WHERE (ns.nspname='public' AND c.relname=ANY($1)) OR (rns.nspname='public' AND r.relname=ANY($1)) ORDER BY ns.nspname,c.relname,x.conname`, "constraints": `SELECT ns.nspname AS namespace,c.relname AS table_name,x.conname AS name,x.contype AS type,pg_get_constraintdef(x.oid) AS definition,coalesce(r.relname,'') AS referenced_table,coalesce(rns.nspname,'') AS referenced_namespace FROM pg_constraint x JOIN pg_class c ON c.oid=x.conrelid JOIN pg_namespace ns ON ns.oid=c.relnamespace LEFT JOIN pg_class r ON r.oid=x.confrelid LEFT JOIN pg_namespace rns ON rns.oid=r.relnamespace WHERE (ns.nspname='public' AND c.relname=ANY($1)) OR (rns.nspname='public' AND r.relname=ANY($1)) ORDER BY ns.nspname,c.relname,x.conname`,
@@ -45,7 +53,7 @@ func captureMigrationCatalog(ctx context.Context, tx pgx.Tx) (migrationCatalog,
catalog := migrationCatalog{} catalog := migrationCatalog{}
for key, query := range queries { for key, query := range queries {
var raw []byte var raw []byte
if err := tx.QueryRow(ctx, "SELECT coalesce(jsonb_agg(to_jsonb(q)),'[]'::jsonb) FROM ("+query+") q", productionLibraryTables).Scan(&raw); err != nil { if err := tx.QueryRow(ctx, "SELECT coalesce(jsonb_agg(to_jsonb(q)),'[]'::jsonb) FROM ("+query+") q", tables).Scan(&raw); err != nil {
return nil, "", fmt.Errorf("capture migration catalog %s: %w", key, err) return nil, "", fmt.Errorf("capture migration catalog %s: %w", key, err)
} }
catalog[key] = raw catalog[key] = raw
@@ -59,12 +67,39 @@ func captureMigrationCatalog(ctx context.Context, tx pgx.Tx) (migrationCatalog,
} }
func validateMigrationCatalog(catalog migrationCatalog) error { func validateMigrationCatalog(catalog migrationCatalog) error {
var triggers []json.RawMessage profile, err := libraryprofile.For(libraryprofile.LegacyVersion)
if err != nil {
return err
}
return validateMigrationCatalogFor(catalog, productionLibraryTables, profile)
}
func validateMigrationCatalogFor(catalog migrationCatalog, tables []string, profile libraryprofile.Profile) error {
var triggers []struct {
Table string `json:"table_name"`
Name string `json:"name"`
Definition string `json:"definition"`
}
if err := json.Unmarshal(catalog["triggers"], &triggers); err != nil { if err := json.Unmarshal(catalog["triggers"], &triggers); err != nil {
return err return err
} }
if len(triggers) > 0 { // 触发器 = 写一行还会改别的表。只接受 profile 里逐字核对过的定义,
return errors.New("unreviewed migration trigger effects") // 且它们必须真实存在:消失了说明这也不是我们审过的那份 schema。
reviewed := map[string]bool{}
for _, definition := range profile.ReviewedTriggers {
reviewed[definition] = true
}
seen := map[string]bool{}
for _, trigger := range triggers {
if !reviewed[trigger.Definition] {
return fmt.Errorf("unreviewed migration trigger %s on %s", trigger.Name, trigger.Table)
}
seen[trigger.Definition] = true
}
for definition := range reviewed {
if !seen[definition] {
return errors.New("reviewed migration trigger is missing from this schema version")
}
} }
var relations []struct { var relations []struct {
Table string `json:"table_name"` Table string `json:"table_name"`
@@ -76,7 +111,7 @@ func validateMigrationCatalog(catalog migrationCatalog) error {
if err := json.Unmarshal(catalog["relations"], &relations); err != nil { if err := json.Unmarshal(catalog["relations"], &relations); err != nil {
return err return err
} }
if len(relations) != len(productionLibraryTables) { if len(relations) != len(tables) {
return errors.New("incomplete migration table catalog") return errors.New("incomplete migration table catalog")
} }
for _, r := range relations { for _, r := range relations {
@@ -10,6 +10,8 @@ import (
"sort" "sort"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"knowledge-governance/internal/libraryprofile"
) )
var resourceReferencePattern = regexp.MustCompile(`resource://([A-Za-z0-9_-]{22})`) var resourceReferencePattern = regexp.MustCompile(`resource://([A-Za-z0-9_-]{22})`)
@@ -30,6 +32,29 @@ type TableSnapshot struct {
type PostgresSnapshot struct { type PostgresSnapshot struct {
Catalog migrationCatalog `json:"catalog,omitempty"` Catalog migrationCatalog `json:"catalog,omitempty"`
Tables []TableSnapshot Tables []TableSnapshot
// SchemaVersion 是导出/导入两侧共同的 profile 标识:归档必须与目标同版本,
// 否则行里的列语义(例如 0.9.0 新增的 NOT NULL 列)不可比。
SchemaVersion int `json:"schema_version,omitempty"`
Profile string `json:"profile,omitempty"`
}
// schemaProfile 解析快照声明的 profile。0 表示既有内存夹具(0.7.1),
// 只把"没有声明版本"解释成 74,不把未知版本解释成任何 profile。
func (snapshot PostgresSnapshot) schemaProfile() (SchemaProfile, error) {
profile, err := libraryprofile.For(snapshot.SchemaVersion)
if err != nil {
if snapshot.SchemaVersion != 0 {
return SchemaProfile{}, err
}
profile, err = libraryprofile.For(libraryprofile.LegacyVersion)
if err != nil {
return SchemaProfile{}, err
}
}
resolved := SchemaProfile{Profile: profile}
resolved.Tables = append(resolved.Tables, profile.RequiredTables...)
resolved.Tables = append(resolved.Tables, profile.OptionalTables...)
return resolved, nil
} }
func (snapshot PostgresSnapshot) Table(name string) TableSnapshot { func (snapshot PostgresSnapshot) Table(name string) TableSnapshot {
+22 -13
View File
@@ -67,10 +67,13 @@ func (importer *PostgresImporter) Replace(ctx context.Context, identity Postgres
return errors.New("begin PostgreSQL document import") return errors.New("begin PostgreSQL document import")
} }
defer tx.Rollback(ctx) defer tx.Rollback(ctx)
var version int profile, err := ResolveSchemaProfile(ctx, tx, "target WeKnora")
var dirty bool if err != nil {
if err := tx.QueryRow(ctx, `SELECT version, dirty FROM schema_migrations LIMIT 1`).Scan(&version, &dirty); err != nil || version != 74 || dirty { return err
return errors.New("target WeKnora schema contract mismatch") }
// 目标版本必须与归档同 profile:0.7.1 的归档不能写进 0.9.0,反之亦然。
if err := requireSameProfile(snapshot.SchemaVersion, profile, "import"); err != nil {
return err
} }
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, identity.KnowledgeID); err != nil { if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, identity.KnowledgeID); err != nil {
return errors.New("lock target knowledge") return errors.New("lock target knowledge")
@@ -177,10 +180,12 @@ func (importer *PostgresImporter) ReplaceWiki(ctx context.Context, identity Post
return errors.New("begin PostgreSQL wiki import") return errors.New("begin PostgreSQL wiki import")
} }
defer tx.Rollback(ctx) defer tx.Rollback(ctx)
var version int profile, err := ResolveSchemaProfile(ctx, tx, "target WeKnora")
var dirty bool if err != nil {
if err := tx.QueryRow(ctx, `SELECT version, dirty FROM schema_migrations LIMIT 1`).Scan(&version, &dirty); err != nil || version != 74 || dirty { return err
return errors.New("target WeKnora schema contract mismatch") }
if err := requireSameProfile(snapshot.SchemaVersion, profile, "wiki import"); err != nil {
return err
} }
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 1))`, identity.KnowledgeBaseID); err != nil { if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 1))`, identity.KnowledgeBaseID); err != nil {
return errors.New("lock target wiki knowledge base") return errors.New("lock target wiki knowledge base")
@@ -205,10 +210,8 @@ func (importer *PostgresImporter) Disable(ctx context.Context, identity Postgres
return errors.New("begin PostgreSQL disable") return errors.New("begin PostgreSQL disable")
} }
defer tx.Rollback(ctx) defer tx.Rollback(ctx)
var version int if _, err := ResolveSchemaProfile(ctx, tx, "target WeKnora"); err != nil {
var dirty bool return err
if err := tx.QueryRow(ctx, `SELECT version, dirty FROM schema_migrations LIMIT 1`).Scan(&version, &dirty); err != nil || version != 74 || dirty {
return errors.New("target WeKnora schema contract mismatch")
} }
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, identity.KnowledgeID); err != nil { if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, identity.KnowledgeID); err != nil {
return errors.New("lock target knowledge") return errors.New("lock target knowledge")
@@ -244,9 +247,15 @@ func (importer *PostgresImporter) prepareSnapshot(identity PostgresIdentity, sna
return PostgresSnapshot{}, nil, nil, errors.New("PostgreSQL import snapshot is incomplete") return PostgresSnapshot{}, nil, nil, errors.New("PostgreSQL import snapshot is incomplete")
} }
prepared := cloneSnapshot(snapshot) prepared := cloneSnapshot(snapshot)
// 表集合按快照所属 profile 判定:0.9.0 的归档里有 wiki_page_issues,
// 面向单文档发布的白名单没有它,用白名单会把合法归档判成非法。
profile, err := snapshot.schemaProfile()
if err != nil {
return PostgresSnapshot{}, nil, nil, err
}
known := map[string]bool{} known := map[string]bool{}
for index, table := range prepared.Tables { for index, table := range prepared.Tables {
if !validReleaseTable(table.Name) || known[table.Name] || table.RowCount != len(table.Rows) || newTableSnapshot(table.Name, table.Rows).SHA256 != table.SHA256 { if !profile.HasTable(table.Name) || known[table.Name] || table.RowCount != len(table.Rows) || newTableSnapshot(table.Name, table.Rows).SHA256 != table.SHA256 {
return PostgresSnapshot{}, nil, nil, errors.New("PostgreSQL import snapshot is invalid") return PostgresSnapshot{}, nil, nil, errors.New("PostgreSQL import snapshot is invalid")
} }
known[table.Name] = true known[table.Name] = true
@@ -0,0 +1,50 @@
package v071
import (
"knowledge-governance/internal/libraryprofile"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// schemaProbeRows 给"按 SQL 打桩"的既有夹具提供 information_schema 能力探测答案。
// 0.7.1 的假库一律按 profile 声明的表/列回答,这样能力探测在单测里也是真的被走了一遍,
// 而不是被桩悄悄放行。
type schemaProbeRows struct {
pairs [][2]string
index int
}
func legacySchemaProbeRows() *schemaProbeRows {
profile, err := libraryprofile.For(libraryprofile.LegacyVersion)
if err != nil {
panic(err)
}
rows := &schemaProbeRows{}
for _, table := range profile.RequiredTables {
for _, column := range profile.RequiredColumns[table] {
rows.pairs = append(rows.pairs, [2]string{table, column})
}
}
return rows
}
func (r *schemaProbeRows) Close() {}
func (r *schemaProbeRows) Err() error { return nil }
func (r *schemaProbeRows) CommandTag() pgconn.CommandTag { return pgconn.CommandTag{} }
func (r *schemaProbeRows) FieldDescriptions() []pgconn.FieldDescription { return nil }
func (r *schemaProbeRows) RawValues() [][]byte { return nil }
func (r *schemaProbeRows) Conn() *pgx.Conn { return nil }
func (r *schemaProbeRows) Next() bool {
if r.index >= len(r.pairs) {
return false
}
r.index++
return true
}
func (r *schemaProbeRows) Scan(dest ...any) error {
*dest[0].(*string) = r.pairs[r.index-1][0]
*dest[1].(*string) = r.pairs[r.index-1][1]
return nil
}
func (r *schemaProbeRows) Values() ([]any, error) { return nil, nil }
@@ -0,0 +1,145 @@
package v071
import (
"context"
"fmt"
"sort"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/libraryprofile"
)
// SchemaProfile 是"版本号 + 能力探测"两者都通过之后的解析结果。
//
// Tables 是**实际存在**的表(必需表按声明顺序 + 存在的可选表)。导出/编目/校验
// 只按它取数:0.9.0 没有 wiki_log_entries,硬编码表清单会在第一条查询上炸,
// 而"表不存在就跳过约束"会让 0.7.1 少一个必需表也悄悄通过。
type SchemaProfile struct {
libraryprofile.Profile
Tables []string
}
// HasTable 报告解析后的表集合里是否包含该表。
func (p SchemaProfile) HasTable(name string) bool {
for _, candidate := range p.Tables {
if candidate == name {
return true
}
}
return false
}
// CatalogTables 是编目/归档用的表清单(与 Tables 同序,sorted 便于稳定摘要)。
func (p SchemaProfile) CatalogTables() []string {
tables := append([]string(nil), p.Tables...)
sort.Strings(tables)
return tables
}
type schemaProbeDB interface {
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
}
// ResolveSchemaProfile 解析并校验一侧的 schema 契约。
//
// 顺序是刻意的:先读版本(未知版本失败关闭、dirty 一律失败),再用
// information_schema 证明 profile 声明的东西真的存在。只信版本号等于把
// "迁移进度"当成"能力契约",而两者在生产上经常不同步。
func ResolveSchemaProfile(ctx context.Context, db schemaProbeDB, role string) (SchemaProfile, error) {
var version int
var dirty bool
if err := db.QueryRow(ctx, `SELECT version,dirty FROM schema_migrations ORDER BY version DESC LIMIT 1`).Scan(&version, &dirty); err != nil {
return SchemaProfile{}, fmt.Errorf("read %s schema_migrations: %w", role, err)
}
profile, err := profileForMigration(version, dirty, role)
if err != nil {
return SchemaProfile{}, err
}
columns, err := probeSchemaColumns(ctx, db, profile)
if err != nil {
return SchemaProfile{}, fmt.Errorf("%s schema version %d: %w", role, version, err)
}
return verifySchemaCapabilities(profile, columns, role, version)
}
// profileForMigration 只做"版本号 + dirty → profile"的判定,不碰数据库。
// dirty 与未知版本都必须失败:前者是半截迁移,后者是没见过的契约。
func profileForMigration(version int, dirty bool, role string) (libraryprofile.Profile, error) {
if dirty {
return libraryprofile.Profile{}, fmt.Errorf("%s schema is dirty at version %d: refusing to snapshot or write", role, version)
}
profile, err := libraryprofile.For(version)
if err != nil {
return libraryprofile.Profile{}, fmt.Errorf("%s schema: %w", role, err)
}
return profile, nil
}
// verifySchemaCapabilities 用 information_schema 的实际列集合校正 profile:
// 必需表/列缺失就精确点名,存在才进"实际表集合"。
func verifySchemaCapabilities(profile libraryprofile.Profile, columns map[string]map[string]bool, role string, version int) (SchemaProfile, error) {
resolved := SchemaProfile{Profile: profile}
for _, table := range profile.RequiredTables {
if _, ok := columns[table]; !ok {
return SchemaProfile{}, fmt.Errorf("%s schema version %d: required table %s is missing", role, version, table)
}
resolved.Tables = append(resolved.Tables, table)
}
for _, table := range profile.OptionalTables {
if _, ok := columns[table]; ok {
resolved.Tables = append(resolved.Tables, table)
}
}
for _, table := range resolved.Tables {
for _, column := range profile.RequiredColumns[table] {
if !columns[table][column] {
return SchemaProfile{}, fmt.Errorf("%s schema version %d: required column %s.%s is missing", role, version, table, column)
}
}
}
return resolved, nil
}
// probeSchemaColumns 一次读回 profile 涉及表的列集合。
func probeSchemaColumns(ctx context.Context, db schemaProbeDB, profile libraryprofile.Profile) (map[string]map[string]bool, error) {
names := make([]string, 0, len(profile.RequiredTables)+len(profile.OptionalTables))
names = append(names, profile.RequiredTables...)
names = append(names, profile.OptionalTables...)
sort.Strings(names)
rows, err := db.Query(ctx, `SELECT table_name, column_name FROM information_schema.columns WHERE table_schema='public' AND table_name=ANY($1)`, names)
if err != nil {
return nil, fmt.Errorf("probe schema capabilities: %w", err)
}
defer rows.Close()
columns := map[string]map[string]bool{}
for rows.Next() {
var table, column string
if err := rows.Scan(&table, &column); err != nil {
return nil, fmt.Errorf("probe schema capabilities: %w", err)
}
if columns[table] == nil {
columns[table] = map[string]bool{}
}
columns[table][column] = true
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("probe schema capabilities: %w", err)
}
return columns, nil
}
// requireSameProfile 拒绝跨版本搬运:0.9.0 归档不能落到 0.7.1,反之也不行。
// 本轮只支持 090↔090(以及既有 74↔74)。
func requireSameProfile(sourceVersion int, target SchemaProfile, direction string) error {
if sourceVersion == 0 {
// 老的内存夹具没有声明版本:按 0.7.1 处理,行为不变。
sourceVersion = libraryprofile.LegacyVersion
}
if sourceVersion != target.SchemaVersion {
return fmt.Errorf("%s refused: archive schema version %d cannot be applied to target schema version %d (cross-version %s is not supported)",
direction, sourceVersion, target.SchemaVersion, direction)
}
return nil
}
@@ -0,0 +1,126 @@
package v071
import (
"os"
"strings"
"testing"
"knowledge-governance/internal/libraryprofile"
)
func TestSchemaProfileFailsClosedOnUnknownVersion(t *testing.T) {
_, err := profileForMigration(135, false, "test")
if err == nil || !strings.Contains(err.Error(), "135") || !strings.Contains(err.Error(), "134") {
t.Fatalf("unknown version must fail with the real version number, got %v", err)
}
}
func TestSchemaProfileRejectsDirtySchema(t *testing.T) {
_, err := profileForMigration(134, true, "test")
if err == nil || !strings.Contains(err.Error(), "dirty") {
t.Fatalf("dirty schema must be refused, got %v", err)
}
}
func TestSchemaProfileNamesMissingTableAndColumn(t *testing.T) {
profile, err := libraryprofile.For(134)
if err != nil {
t.Fatal(err)
}
columns := map[string]map[string]bool{}
for _, table := range append(append([]string{}, profile.RequiredTables...), profile.OptionalTables...) {
columns[table] = map[string]bool{}
for _, column := range profile.RequiredColumns[table] {
columns[table][column] = true
}
}
delete(columns, "wiki_pages")
if _, err := verifySchemaCapabilities(profile, columns, "test", 134); err == nil || !strings.Contains(err.Error(), "wiki_pages") {
t.Fatalf("missing required table must be named, got %v", err)
}
columns["wiki_pages"] = map[string]bool{"id": true, "tenant_id": true, "knowledge_base_id": true}
if _, err := verifySchemaCapabilities(profile, columns, "test", 134); err == nil || !strings.Contains(err.Error(), "wiki_pages.slug") {
t.Fatalf("missing required column must be named, got %v", err)
}
columns["wiki_pages"]["slug"] = true
if _, err := verifySchemaCapabilities(profile, columns, "test", 134); err != nil {
t.Fatalf("complete capabilities must pass: %v", err)
}
}
func TestSchemaProfileV071BehaviourUnchanged(t *testing.T) {
legacy, err := libraryprofile.For(74)
if err != nil {
t.Fatal(err)
}
if !legacy.HasTable("wiki_log_entries") || !legacy.RequiresPart("wiki/wiki_log_entries") {
t.Fatal("0.7.1 must still require wiki_log_entries")
}
if legacy.EmbeddingDimension != 1024 {
t.Fatalf("0.7.1 dimension contract must stay 1024, got %d", legacy.EmbeddingDimension)
}
v090, err := libraryprofile.For(134)
if err != nil {
t.Fatal(err)
}
if v090.RequiresPart("wiki/wiki_log_entries") || !v090.AllowsPart("wiki/wiki_log_entries") {
t.Fatal("0.9.0 wiki_log_entries must be optional")
}
if v090.HasTable("wiki_log_entries") == false {
t.Fatal("optional table should still be addressable when present")
}
resolved := SchemaProfile{Profile: v090, Tables: v090.RequiredTables}
if resolved.HasTable("wiki_log_entries") {
t.Fatal("0.9.0 export table set must exclude an absent optional table")
}
}
func TestTargetIndexNameResolvesToConfigurationOnly(t *testing.T) {
profile, err := libraryprofile.For(134)
if err != nil {
t.Fatal(err)
}
name, err := resolveTargetIndexName("", "weknora_v090_chunks", profile)
if err != nil || name != "weknora_v090_chunks" {
t.Fatalf("empty vector store must fall back to the configured index, got %q/%v", name, err)
}
if _, err := resolveTargetIndexName("", "", profile); err == nil || !strings.Contains(err.Error(), "index name unresolved") {
t.Fatalf("no source must fail instead of resolving to an empty name, got %v", err)
}
if _, err := resolveTargetIndexName("idx_a", "idx_b", profile); err == nil || !strings.Contains(err.Error(), "does not match") {
t.Fatalf("conflicting index sources must be refused, got %v", err)
}
}
// 0.9.0 与 0.7.1 的映射必须算出不同摘要:同样的 1024 维不等于同一份契约。
func TestIndexMappingDigestSeparatesSchemaVersions(t *testing.T) {
legacy := []byte(`{"weknora_v071_chunks":{"mappings":{"properties":{
"chunk_id":{"type":"text","fields":{"keyword":{"type":"keyword"}}},
"knowledge_id":{"type":"text","fields":{"keyword":{"type":"keyword"}}},
"knowledge_base_id":{"type":"text","fields":{"keyword":{"type":"keyword"}}},
"embedding":{"type":"dense_vector","dims":1024}}}}}`)
legacyDigest, err := IndexMappingDigest(legacy)
if err != nil {
t.Fatal(err)
}
if path := os.Getenv("KG_V090_MAPPING_JSON"); path != "" {
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
v090Digest, err := IndexMappingDigest(raw)
if err != nil {
t.Fatalf("real 0.9.0 mapping must be digestible: %v", err)
}
if v090Digest == legacyDigest {
t.Fatal("0.9.0 and 0.7.1 mappings must not share a digest")
}
if len(v090Digest) != 64 {
t.Fatalf("unexpected digest shape %q", v090Digest)
}
}
if _, err := IndexMappingDigest([]byte(`{"a":{"mappings":{}},"b":{"mappings":{}}}`)); err == nil {
t.Fatal("multi-index mapping responses must be refused")
}
}
@@ -0,0 +1,183 @@
package v071
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"os"
"strconv"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
)
// 0.9.0 fixture:真实 pg_dump(schema_migrations=134,83 表,无 wiki_log_entries)。
// 只用于显式指定的隔离库;governance 与周报邮件库一律不许指到这里。
const v090SchemaEnv = "KG_V090_SCHEMA_SQL"
func v090SchemaSQL(t *testing.T) string {
t.Helper()
path := os.Getenv(v090SchemaEnv)
if path == "" {
t.Skip("requires " + v090SchemaEnv + " pointing at the captured WeKnora 0.9.0 schema dump")
}
raw, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", v090SchemaEnv, err)
}
lines := strings.Split(string(raw), "\n")
kept := make([]string, 0, len(lines))
for _, line := range lines {
// psql 元命令(\restrict/\unrestrict)只对 psql 有意义,驱动执行要剔除。
if strings.HasPrefix(line, "\\") {
continue
}
kept = append(kept, line)
}
// 装载会话本身也要把 search_path 还给 public,否则后续查询会找不到表。
return strings.Join(kept, "\n") + "\nSET search_path TO public, pg_catalog;\n"
}
// v090Pool 打开一个显式隔离库并重建 public schema,然后装 0.9.0 真实 schema。
func v090Pool(t *testing.T, env string) *pgxpool.Pool {
t.Helper()
dsn := os.Getenv(env)
if dsn == "" {
t.Skip("requires " + env)
}
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
t.Fatalf("%s must name an explicitly isolated kg_library_test_ database", env)
}
// dump 里有 set_config('search_path',''),新连接必须显式给回 public。
cfg.ConnConfig.RuntimeParams["search_path"] = "public, pg_catalog"
ctx := context.Background()
db, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatalf("connect: %v", err)
}
t.Cleanup(db.Close)
if _, err = db.Exec(ctx, `DROP SCHEMA public CASCADE; CREATE SCHEMA public`); err != nil {
t.Fatalf("reset schema: %v", err)
}
if _, err = db.Exec(ctx, v090SchemaSQL(t)); err != nil {
t.Fatalf("install 0.9.0 schema: %v", err)
}
// 该 dump 会把会话 search_path 置空,这里一律写全限定名。
if _, err = db.Exec(ctx, `INSERT INTO public.schema_migrations(version,dirty) VALUES (134,false)`); err != nil {
t.Fatalf("stamp schema_migrations: %v", err)
}
return db
}
const v090Tenant = 10000
const v090KB = "kb-v090"
const v090Knowledge = "kn-v090-doc"
const v090ChunkOne = "ck-v090-1"
const v090ChunkTwo = "ck-v090-2"
const v090Folder = "wf-v090-1"
const v090Page = "wp-v090-1"
const v090Tag = "tg-v090-1"
const v090Resource = "rs-v090-1"
// seedV090 造 1 KB / 1 文档 / 2 分块 / 1 wiki 页 / 1 wiki 目录 / 1 资源。
// Wiki 必须非空:空表通过等于没有验证 wiki 部件。
func seedV090(t *testing.T, ctx context.Context, db *pgxpool.Pool) PostgresIdentity {
t.Helper()
statements := []string{
`INSERT INTO models(id,tenant_id,name,type,source,parameters) VALUES ('bge-m3-v090',$1,'bge-m3','embedding','local','{"embedding_parameters":{"dimension":1024}}'::jsonb)`,
`INSERT INTO knowledge_bases(id,name,tenant_id,embedding_model_id,summary_model_id,indexing_strategy) VALUES ('` + v090KB + `','v090 fixture',$1,'bge-m3-v090','bge-m3-v090','{"graph_enabled":false}'::jsonb)`,
`INSERT INTO knowledges(id,tenant_id,knowledge_base_id,type,title,source,parse_status,pending_subtasks_count) VALUES ('` + v090Knowledge + `',$1,'` + v090KB + `','file','0.9.0 夹具','fixture://kn-v090','completed',0)`,
`INSERT INTO chunks(id,tenant_id,knowledge_base_id,knowledge_id,content,chunk_index,start_at,end_at) VALUES
('` + v090ChunkOne + `',$1,'` + v090KB + `','` + v090Knowledge + `','第一段正文',0,0,5),
('` + v090ChunkTwo + `',$1,'` + v090KB + `','` + v090Knowledge + `','第二段正文',1,5,10)`,
`INSERT INTO wiki_folders(id,tenant_id,knowledge_base_id,name,path) VALUES ('` + v090Folder + `',$1,'` + v090KB + `','夹具目录','/fixture')`,
`INSERT INTO wiki_pages(id,tenant_id,knowledge_base_id,slug,title,content,source_refs,chunk_refs,folder_id) VALUES ('` + v090Page + `',$1,'` + v090KB + `','fixture-page','夹具页','wiki 正文','["` + v090Knowledge + `"]'::jsonb,'["` + v090ChunkOne + `"]'::jsonb,'` + v090Folder + `')`,
`INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id,name) VALUES ('` + v090Tag + `',$1,'` + v090KB + `','夹具标签')`,
`INSERT INTO knowledge_tag_relations(knowledge_id,tag_id) VALUES ('` + v090Knowledge + `','` + v090Tag + `')`,
}
for _, statement := range statements {
if _, err := db.Exec(ctx, strings.ReplaceAll(statement, "$1", strconv.Itoa(v090Tenant))); err != nil {
t.Fatalf("seed: %v\n%s", err, statement)
}
}
// 资源行必须带真实的 physical_path/size/content_hash:封存会逐字节核对。
content := []byte("fixture-object-bytes")
sum := sha256.Sum256(content)
if _, err := db.Exec(ctx, `INSERT INTO resources(id,handle,tenant_id,provider,physical_path,location_hash,size,content_hash)
VALUES ($1,$2,$3,'minio','fixture/kn-v090.bin',$4,$5,$6)`,
v090Resource, "abcdefghijklmnopqrstuv", v090Tenant, "fixture-location-hash", int64(len(content)), hex.EncodeToString(sum[:])); err != nil {
t.Fatalf("seed resource: %v", err)
}
if _, err := db.Exec(ctx, `INSERT INTO resource_bindings(id,resource_id,tenant_id,owner_type,owner_id)
VALUES ('rb-v090-1',$1,$2,'knowledge',$3)`, v090Resource, v090Tenant, v090Knowledge); err != nil {
t.Fatalf("seed binding: %v", err)
}
return PostgresIdentity{TenantID: v090Tenant, KnowledgeBaseID: v090KB}
}
// seedV090Binding 只在目标库造 KB/模型绑定:导入的是文档行,不是 KB 定义。
func seedV090Binding(t *testing.T, ctx context.Context, db *pgxpool.Pool) error {
t.Helper()
for _, statement := range []string{
`INSERT INTO models(id,tenant_id,name,type,source,parameters) VALUES ('bge-m3-v090',$1,'bge-m3','embedding','local','{"embedding_parameters":{"dimension":1024}}'::jsonb)`,
`INSERT INTO knowledge_bases(id,name,tenant_id,embedding_model_id,summary_model_id,indexing_strategy) VALUES ('` + v090KB + `','v090 fixture target',$1,'bge-m3-v090','bge-m3-v090','{"graph_enabled":false}'::jsonb)`,
} {
if _, err := db.Exec(ctx, strings.ReplaceAll(statement, "$1", strconv.Itoa(v090Tenant))); err != nil {
return err
}
}
return nil
}
// v090Objects 只在测试里替代对象存储:字节来自夹具常量,不连任何 S3/OSS。
type v090Objects map[string][]byte
func (o v090Objects) Open(_ context.Context, provider, physicalPath string) (io.ReadCloser, error) {
if provider != "minio" {
return nil, errors.New("unsupported provider in fixture")
}
content, ok := o[physicalPath]
if !ok {
return nil, errors.New("fixture object missing")
}
return io.NopCloser(bytes.NewReader(content)), nil
}
// v090IndexSnapshot 按导出分块合成索引快照:本切片不做真实 ES 采集,
// 但文档/映射摘要走的是与线上同一套校验,不能凭空绕过。
func v090IndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA string) SearchSnapshot {
t.Helper()
var documents []SearchDocument
for _, raw := range pg.Table("chunks").Rows {
var chunk struct {
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
KnowledgeID string `json:"knowledge_id"`
Content string `json:"content"`
}
if err := json.Unmarshal(raw, &chunk); err != nil {
t.Fatalf("decode chunk: %v", err)
}
source, err := json.Marshal(map[string]any{
"chunk_id": chunk.ID, "tenant_id": chunk.TenantID,
"knowledge_base_id": chunk.KnowledgeBaseID, "knowledge_id": chunk.KnowledgeID,
"content": chunk.Content, "source_id": chunk.ID, "source_type": 0,
})
if err != nil {
t.Fatalf("encode index document: %v", err)
}
documents = append(documents, SearchDocument{ID: "doc-" + chunk.ID, Source: source})
}
digest, err := searchDocumentsDigest(documents)
if err != nil {
t.Fatalf("index digest: %v", err)
}
return SearchSnapshot{Documents: documents, MappingSHA256: mappingSHA, DocumentsSHA256: digest}
}
+5
View File
@@ -647,6 +647,11 @@
"package": "knowledge-governance/internal/httpapi", "package": "knowledge-governance/internal/httpapi",
"test": "TestWeeklyMailSendsHandlerReadsRealHistoryWithMessageID", "test": "TestWeeklyMailSendsHandlerReadsRealHistoryWithMessageID",
"reason": "需要一次性 PostgreSQL + 测试主密钥;验证 GET /weekly-mail/sends 在非空历史下返回 200 与真实 message_id,CI 不提供" "reason": "需要一次性 PostgreSQL + 测试主密钥;验证 GET /weekly-mail/sends 在非空历史下返回 200 与真实 message_id,CI 不提供"
},
{
"package": "knowledge-governance/internal/releaseadapter/v071",
"test": "TestV090LibraryRoundTripIsolated",
"reason": "需 KG_V090_SCHEMA_SQL 指向真实 WeKnora 0.9.0 schema dump、KG_V090_MAPPING_JSON 指向真实索引映射,以及显式隔离的 kg_library_test_* PG;普通 CI 没有这些输入,跳过不是通过"
} }
] ]
} }