why:审计 19 项(12 P1 / 7 P2)来自同一批根因,逐点试错会把协议撕成十几份:
· 意图与执行混为一谈(F01/F15):`library.sync:<scope>:<快照>` 是终身幂等键,
A→B→A 的第三次发布拿到第一次的历史成功作业,什么都不做;
· 版本行既是实体又是事件(F02/F09):主键只由 (kind,scope,快照) 决定、写入是
upsert,第二个作业覆盖 `source_job_id`/`evidence`/`created_at`;
· 接管没有代次(F13):两个 worker 都能认领同一 pending 作业,失租的旧执行还能
写业务状态、释放别人的维护锁;
· 早退与终态没有统一政策(F03/F04/F05/F06):半写窗口的前置检查失败会重新开门、
服务起不来也照样开入口、journal 终态后收尾不可重建、恢复成功不回写 current;
· 数据身份与准入各写一套(F07/F08/F14/F17):接管丢了复用语义、全库搬运不改
location_hash、通用入口可造 library.* 作业、目标模型从没被问过;
· 存储/容量/UI/CI 判据各自为政(F10/F11/F12/F16/F18/F19)。
what:按批准的一套协议集中实施(详见 handoffs/release-consolidated-implementation/
current-contract.md):
· operation(一次明确意图)/ attempt(epoch 代次)/ 不可变版本事件 / current 指针;
治理库迁移 76,只动治理库,不碰 WeKnora Schema/源码/镜像;
· 所有业务状态、阶段、版本事件、维护锁写入带 epoch 守卫(失租代次写不进去);
心跳失租立刻取消 handler;
· 半写窗口早退保持关闭;服务未全部健康绝不开入口;journal 终态可从持久事实重建
收尾;恢复成功登记 recovery 事件并推进 current;
· worker 在动维护前核对业务行/kind/scope/队列关联;通用入口拒绝 library.*;
· 全库搬运重算 location_hash 并与文档级导入共用实现;接管消费写集合的复用决定;
发布前核目标实时模型契约、容量门禁前置;
· 存储保护闭包改为全量依赖、类型只认显式登记、保护未知则不出可删候选;
· 页面核 HTTP 状态与结构、恢复纳入轮询、Wiki 差异覆盖标题/摘要/父级。
how:`make verify` rc=0(16 项必需检查全绿,含 go test 全量与前端 485 例);
`go vet ./...` rc=0;`npx tsc -p tsconfig.json --noEmit` rc=0;逐项负例见各包测试
(F03/F04/F08/F12/F13/F14/F16/F18/F19 都有先红后绿记录)。
未执行:治理库迁移到任何已有库、真实 PG/ES/S3/WeKnora 集成、故障注入、部署。
This commit is contained in:
@@ -782,6 +782,41 @@ func archiveRowIdentity(table string, row map[string]json.RawMessage) string {
|
||||
return value("id")
|
||||
}
|
||||
|
||||
// AdoptWriteSet 消费已持久化的写集合(接管/恢复路径)。
|
||||
//
|
||||
// 只做一件事:把"这些 resources 已证明与目标现状逐字节一致"的决定装回执行目标,
|
||||
// 让 Apply 的跳过逻辑生效。它**不重新计划**、不重新比较目标现状——那会把半写状态
|
||||
// 当成新基线,也把"共享对象没被重写"这句话变成谎话(F07)。
|
||||
//
|
||||
// 校验从严:计划必须自校验通过、绑定同一目标 tenant/KB、绑定本次要写的那份快照;
|
||||
// 任何一项不符都拒绝,因为错误的复用集合会导致该写的没写、或该跳的却重写。
|
||||
func (t *ProductionLibraryTarget) AdoptWriteSet(set libraryrelease.WriteSet) error {
|
||||
if err := set.Verify(); err != nil {
|
||||
return fmt.Errorf("写集合记录校验失败:%w", err)
|
||||
}
|
||||
if set.TenantID != t.scope.TenantID || set.KnowledgeBaseID != t.scope.KnowledgeBaseID {
|
||||
return fmt.Errorf("写集合绑定的是 %d/%s,与目标 %d/%s 不一致",
|
||||
set.TenantID, set.KnowledgeBaseID, t.scope.TenantID, t.scope.KnowledgeBaseID)
|
||||
}
|
||||
reused := map[string]bool{}
|
||||
for _, row := range set.Rows {
|
||||
if row.Table != resourceReuseTableName || !row.Reused {
|
||||
continue
|
||||
}
|
||||
if !row.Existing {
|
||||
return fmt.Errorf("写集合把资源 %s 标成复用但写前不存在:拒绝按不可信的复用集合执行", row.ID)
|
||||
}
|
||||
reused[row.ID] = true
|
||||
}
|
||||
if t.reusedResources == nil {
|
||||
t.reusedResources = map[string]bool{}
|
||||
}
|
||||
for id := range reused {
|
||||
t.reusedResources[id] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Restore 用预备份把生产整库恢复回去:走同一条 Apply 路径,可重复执行。
|
||||
//
|
||||
// 恢复必须带着"本次写集合 + 写前整实例证据"(写第一笔之前落盘、摘要登记在治理库)。
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// F08:整库搬运改了 physical_path 就必须重算 location_hash。
|
||||
//
|
||||
// oracle 用 crypto/sha256 **自己复算**,不调用被测实现里的 resourceLocationHash:
|
||||
// 写入与校验共用同一个转换函数时,自比永远成立,错误会被自己的自洽掩盖。
|
||||
func TestResourceRetargetRecomputesLocationHash(t *testing.T) {
|
||||
old := "storage://source-backend/minio://source-bucket/10001/file.pdf"
|
||||
hash := sha256.Sum256([]byte(old))
|
||||
raw, _ := json.Marshal(map[string]any{"id": "resource-one", "tenant_id": 10001,
|
||||
"physical_path": old, "location_hash": hex.EncodeToString(hash[:]),
|
||||
"provider": "minio", "storage_backend_id": "source-backend"})
|
||||
var row map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &row); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target := &ProductionLibraryTarget{
|
||||
config: ProductionLibraryConfig{ObjectsBucket: "target-bucket"},
|
||||
scope: ProductionScope{TenantID: 10002, KnowledgeBaseID: "target-kb"},
|
||||
storageBackend: "target-backend", storageProvider: "minio",
|
||||
snapshotTenant: 10001, snapshotKB: "source-kb",
|
||||
}
|
||||
if err := target.retargetRow("resources", row); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var path, got string
|
||||
_ = json.Unmarshal(row["physical_path"], &path)
|
||||
_ = json.Unmarshal(row["location_hash"], &got)
|
||||
if path == old {
|
||||
t.Fatal("夹具没有改写定位符:这条断言就没有意义")
|
||||
}
|
||||
want := sha256.Sum256([]byte(path))
|
||||
if got != hex.EncodeToString(want[:]) {
|
||||
t.Fatalf("改路径后 location_hash 仍是旧值:path=%s got=%s want=%s", path, got, hex.EncodeToString(want[:]))
|
||||
}
|
||||
// 反例:跨桶/跨租户组合下同样成立(桶段与租户段都参与最终路径)。
|
||||
for _, tc := range []struct{ name, bucket, backend string }{
|
||||
{"跨桶", "another-bucket", "target-backend"},
|
||||
{"跨后端", "target-bucket", "backend-2"},
|
||||
} {
|
||||
var other map[string]json.RawMessage
|
||||
_ = json.Unmarshal(raw, &other)
|
||||
next := *target
|
||||
next.config.ObjectsBucket = tc.bucket
|
||||
next.storageBackend = tc.backend
|
||||
if err := next.retargetRow("resources", other); err != nil {
|
||||
t.Fatalf("%s:%v", tc.name, err)
|
||||
}
|
||||
var moved, movedHash string
|
||||
_ = json.Unmarshal(other["physical_path"], &moved)
|
||||
_ = json.Unmarshal(other["location_hash"], &movedHash)
|
||||
sum := sha256.Sum256([]byte(moved))
|
||||
if movedHash != hex.EncodeToString(sum[:]) {
|
||||
t.Fatalf("%s:location_hash 与最终路径不一致:path=%s got=%s", tc.name, moved, movedHash)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -169,6 +171,17 @@ func (t *ProductionLibraryTarget) rewriteResourceIdentity(row map[string]json.Ra
|
||||
}
|
||||
row["physical_path"] = encoded
|
||||
}
|
||||
// location_hash 的契约是 sha256(最终 physical_path),不是"来源路径的哈希"。
|
||||
// 旧实现只换路径不重算哈希:目标行声明的是一个不存在的定位符,去重/按路径定位
|
||||
// 都会失效;而写入与校验复用同一个转换函数,内部自比根本发现不了(F08)。
|
||||
// 这里在同一个转换里重算,校验侧另有独立 oracle(测试里直接用 crypto/sha256 复算)。
|
||||
if _, ok := row["location_hash"]; ok {
|
||||
encoded, err := json.Marshal(resourceLocationHash(rewritten))
|
||||
if err != nil {
|
||||
return errors.New("编码目标定位符哈希失败")
|
||||
}
|
||||
row["location_hash"] = encoded
|
||||
}
|
||||
if t.storageBackend != "" {
|
||||
if _, ok := row["storage_backend_id"]; ok {
|
||||
encoded, err := json.Marshal(t.storageBackend)
|
||||
@@ -190,6 +203,15 @@ func (t *ProductionLibraryTarget) rewriteResourceIdentity(row map[string]json.Ra
|
||||
return nil
|
||||
}
|
||||
|
||||
// resourceLocationHash 是 `location_hash` 契约的**唯一实现**:sha256(最终 physical_path)。
|
||||
//
|
||||
// 全库搬运(本文件)与文档级导入(postgres_import.go)必须用同一个函数:
|
||||
// 两条路径各写一份,迟早只改一边,而目标实例正是按这个哈希去重/定位资源的。
|
||||
func resourceLocationHash(physicalPath string) string {
|
||||
sum := sha256.Sum256([]byte(physicalPath))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// retargetLocator 把 "storage://<backend>/<scheme>://<bucket>/<key>" 整体换成目标
|
||||
// 实例的真实取值:后端 id、scheme/提供方、桶名,以及对象键里的租户段。
|
||||
// 桶名为空表示目标没有配置对象存储(测试夹具),此时不动定位符。
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// LiveTargetContract 是目标知识库**此刻**的模型/索引/schema 契约。
|
||||
//
|
||||
// 为什么要单独读:旧实现直接拿"要发布的那份来源快照的 compatibility"当生产预备份的
|
||||
// 合同,于是"目标是什么模型"从来没被问过。后果是目标拿到 A 生成的向量、知识行却声明
|
||||
// 是 B——同维不同模型在 mapping 判据下完全通过(F17)。
|
||||
type LiveTargetContract struct {
|
||||
SchemaVersion int
|
||||
Dirty bool
|
||||
EmbeddingModel string
|
||||
EmbeddingDimension int
|
||||
EngineType string
|
||||
IndexName string
|
||||
MappingSHA256 string
|
||||
// ModelBound 表示 knowledge_bases → models 的 join 命中:false 时维度不可知,
|
||||
// 不能凭"看起来是同一维"放行。
|
||||
ModelBound bool
|
||||
}
|
||||
|
||||
// liveTargetContractSQL 用 LEFT JOIN 读模型:模型行缺失时仍然拿到 KB 声明的模型 id,
|
||||
// 这样"没绑模型/绑了但不可读"能被明确拒绝,而不是在发布中途才炸。
|
||||
const liveTargetContractSQL = `
|
||||
SELECT COALESCE(migration.version, 0),
|
||||
COALESCE(migration.dirty, false),
|
||||
COALESCE(model.name, ''),
|
||||
COALESCE(NULLIF(model.parameters->'embedding_parameters'->>'dimension', '')::INTEGER, 0),
|
||||
(model.id IS NOT NULL),
|
||||
COALESCE(knowledge_base.embedding_model_id, ''),
|
||||
COALESCE(vector_store.engine_type, ''),
|
||||
COALESCE(vector_store.index_config->>'index_name', '')
|
||||
FROM knowledge_bases AS knowledge_base
|
||||
LEFT JOIN models AS model
|
||||
ON model.id = knowledge_base.embedding_model_id AND model.deleted_at IS NULL
|
||||
LEFT JOIN schema_migrations AS migration ON TRUE
|
||||
LEFT JOIN vector_stores AS vector_store
|
||||
ON vector_store.id = knowledge_base.vector_store_id AND vector_store.deleted_at IS NULL
|
||||
WHERE knowledge_base.id = $1 AND knowledge_base.tenant_id = $2 AND knowledge_base.deleted_at IS NULL
|
||||
`
|
||||
|
||||
// LiveTargetContract 读目标知识库的实时契约。读不到就直接失败——**不许**回退到
|
||||
// 来源快照的声明:那正是"用来源兼容性冒充目标合同"的老毛病。
|
||||
func (t *ProductionLibraryTarget) LiveTargetContract(ctx context.Context) (LiveTargetContract, error) {
|
||||
if t.pool == nil {
|
||||
return LiveTargetContract{}, errors.New("目标数据库未接线:无法核对实时模型契约")
|
||||
}
|
||||
var (
|
||||
contract LiveTargetContract
|
||||
declared string
|
||||
indexName string
|
||||
)
|
||||
if err := t.pool.QueryRow(ctx, liveTargetContractSQL, t.scope.KnowledgeBaseID, t.scope.TenantID).Scan(
|
||||
&contract.SchemaVersion, &contract.Dirty, &contract.EmbeddingModel, &contract.EmbeddingDimension,
|
||||
&contract.ModelBound, &declared, &contract.EngineType, &indexName); err != nil {
|
||||
return LiveTargetContract{}, fmt.Errorf("读不到目标知识库 %s 的实时契约:%w", t.scope.KnowledgeBaseID, err)
|
||||
}
|
||||
if !contract.ModelBound && declared != "" {
|
||||
// KB 声明了模型但模型行不可读(未迁移/已删):维度未知,不能证明兼容。
|
||||
contract.EmbeddingModel = declared
|
||||
}
|
||||
contract.IndexName = indexName
|
||||
if t.search != nil {
|
||||
if mapping, mapErr := t.search.MappingSHA256(ctx); mapErr == nil {
|
||||
contract.MappingSHA256 = mapping
|
||||
}
|
||||
}
|
||||
return contract, nil
|
||||
}
|
||||
|
||||
// VerifySourceAgainstTarget 判断"来源快照的向量能不能直接搬进这个目标"。
|
||||
//
|
||||
// 只允许**等价模型**:名字一致、维度一致。名字不同即使维度相同也拒绝——向量是在
|
||||
// 模型 A 的语义空间里算出来的,搬进声明模型 B 的行里,检索结果会静默变错,而这
|
||||
// 种错误不会被任何"行数/摘要"校验发现(本模块不重算 embedding,也不许假装等价)。
|
||||
func VerifySourceAgainstTarget(source librarysnapshot.Compatibility, live LiveTargetContract) error {
|
||||
if live.Dirty {
|
||||
return errors.New("目标 schema 处于 dirty 状态:拒绝在该目标上写入")
|
||||
}
|
||||
if source.SchemaVersion != 0 && live.SchemaVersion != 0 && source.SchemaVersion != live.SchemaVersion {
|
||||
return fmt.Errorf("目标 schema 版本 %d 与来源快照声明 %d 不一致:拒绝搬运",
|
||||
live.SchemaVersion, source.SchemaVersion)
|
||||
}
|
||||
if !live.ModelBound || live.EmbeddingDimension < 1 {
|
||||
return errors.New("目标知识库没有可读的 embedding 模型绑定(模型行缺失或维度未知):" +
|
||||
"无法证明向量可迁移,先在目标上绑定模型")
|
||||
}
|
||||
if source.EmbeddingModel != "" && live.EmbeddingModel != "" && source.EmbeddingModel != live.EmbeddingModel {
|
||||
return fmt.Errorf("来源 embedding 模型 %q 与目标实时模型 %q 不同:不重算 embedding 就不能声称兼容",
|
||||
source.EmbeddingModel, live.EmbeddingModel)
|
||||
}
|
||||
if source.EmbeddingDimension > 0 && source.EmbeddingDimension != live.EmbeddingDimension {
|
||||
return fmt.Errorf("来源向量维度 %d 与目标模型维度 %d 不一致",
|
||||
source.EmbeddingDimension, live.EmbeddingDimension)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ContractFromLive 用目标实时状态构造预备份合同:新备份声明的是"目标现在是什么",
|
||||
// 不是"要发布的来源是什么"。
|
||||
func ContractFromLive(source librarysnapshot.Compatibility, live LiveTargetContract) librarysnapshot.Compatibility {
|
||||
contract := source
|
||||
contract.SchemaVersion = live.SchemaVersion
|
||||
contract.EmbeddingModel = live.EmbeddingModel
|
||||
contract.EmbeddingDimension = live.EmbeddingDimension
|
||||
if live.EngineType != "" {
|
||||
contract.RetrieverEngine = live.EngineType
|
||||
}
|
||||
if live.MappingSHA256 != "" {
|
||||
contract.IndexMappingSHA256 = live.MappingSHA256
|
||||
}
|
||||
return contract
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// F17:目标实时模型契约必须核,且"同维不同模型"不许放行。
|
||||
func TestVerifySourceAgainstTargetRejectsDifferentModel(t *testing.T) {
|
||||
source := librarysnapshot.Compatibility{SchemaVersion: 71, EmbeddingModel: "model-a", EmbeddingDimension: 1024}
|
||||
live := LiveTargetContract{SchemaVersion: 71, EmbeddingModel: "model-b", EmbeddingDimension: 1024, ModelBound: true}
|
||||
if err := VerifySourceAgainstTarget(source, live); err == nil {
|
||||
t.Fatal("同维不同模型必须拒绝:向量空间不同,行声明与向量会对不上")
|
||||
}
|
||||
// 等价模型(同名字同维度)放行。
|
||||
live.EmbeddingModel = "model-a"
|
||||
if err := VerifySourceAgainstTarget(source, live); err != nil {
|
||||
t.Fatalf("等价模型应放行:%v", err)
|
||||
}
|
||||
// 维度不同必须拒绝。
|
||||
live.EmbeddingDimension = 768
|
||||
if err := VerifySourceAgainstTarget(source, live); err == nil {
|
||||
t.Fatal("维度不同必须拒绝")
|
||||
}
|
||||
// 目标模型行缺失(维度未知)也必须拒绝:不能靠"看起来同维"猜。
|
||||
live = LiveTargetContract{SchemaVersion: 71, EmbeddingModel: "model-a", ModelBound: false}
|
||||
if err := VerifySourceAgainstTarget(source, live); err == nil {
|
||||
t.Fatal("目标模型不可读时必须拒绝,而不是按来源声明放行")
|
||||
}
|
||||
// dirty schema 直接拒绝。
|
||||
if err := VerifySourceAgainstTarget(source, LiveTargetContract{SchemaVersion: 71, Dirty: true,
|
||||
EmbeddingModel: "model-a", EmbeddingDimension: 1024, ModelBound: true}); err == nil {
|
||||
t.Fatal("dirty schema 必须拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
// 预备份合同必须来自目标实况:不能把来源声明当目标声明。
|
||||
func TestContractFromLiveUsesTargetState(t *testing.T) {
|
||||
source := librarysnapshot.Compatibility{WeKnoraVersion: "0.7.1", SchemaVersion: 71,
|
||||
EmbeddingModel: "model-a", EmbeddingDimension: 1024, RetrieverEngine: "elasticsearch_v8",
|
||||
IndexMappingSHA256: strings.Repeat("a", 64)}
|
||||
live := LiveTargetContract{SchemaVersion: 71, EmbeddingModel: "model-b", EmbeddingDimension: 1024,
|
||||
EngineType: "elasticsearch", MappingSHA256: strings.Repeat("b", 64), ModelBound: true}
|
||||
got := ContractFromLive(source, live)
|
||||
if got.EmbeddingModel != "model-b" || got.IndexMappingSHA256 != strings.Repeat("b", 64) {
|
||||
t.Fatalf("预备份合同必须取目标实况:%+v", got)
|
||||
}
|
||||
if got.WeKnoraVersion != source.WeKnoraVersion {
|
||||
t.Fatalf("数据格式版本仍来自来源快照:%+v", got)
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,6 @@ package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -388,11 +386,11 @@ func (importer *PostgresImporter) prepareResourceRow(raw json.RawMessage, tenant
|
||||
}
|
||||
}
|
||||
targetPath := "storage://" + importer.config.TargetStorageBackendID + "/" + providerPath
|
||||
digest := sha256.Sum256([]byte(targetPath))
|
||||
row["storage_backend_id"] = importer.config.TargetStorageBackendID
|
||||
row["provider"] = importer.config.TargetProvider
|
||||
row["physical_path"] = targetPath
|
||||
row["location_hash"] = hex.EncodeToString(digest[:])
|
||||
// 与全库搬运共用同一个哈希实现(F08):契约是 sha256(最终 physical_path)。
|
||||
row["location_hash"] = resourceLocationHash(targetPath)
|
||||
encoded, err := json.Marshal(row)
|
||||
if err != nil {
|
||||
return nil, resourceIdentityPair{}, errors.New("rewrite target resource")
|
||||
|
||||
Reference in New Issue
Block a user