Files
knowledge-governance/internal/releaseadapter/v071/library_target_contract.go
T
姚章浩 e6472b0ec6 feat(library): 云测试发布目标接入的角色分离、快照搬运与图谱门禁
为什么改:发布执行链是"与目标同机"假设写死的(本机 docker.sock、本机 drain.json、
本机 Redis/PG),把目标换成云测试不能只改展示 URL;直接搬整套 worker 又会抢走
本机封存/QA/周报队列并按本机配置写错目标。所以先把"谁消费哪段队列"变成显式角色,
再补齐跨主机搬运与目标侧门禁。

角色(LIBRARY_WORKER_ROLE=full/release-executor/capture)不只影响 handler 列表,
还决定是否拥有 DDL(release-executor 只读校验迁移版本,落后即拒绝启动)、
收拾哪些 library_jobs.kind、是否跑 release 接管扫描、是否起 scheduler/QA/周报/探测。
capture 保留本机原有全部业务;release-executor 只挂 sync/restore/recover/baseline。

快照跨主机:新增内容寻址的 bundle(版本清单先落、blob 按 sha256 命名、清单最后
Link 作提交点),pack/unpack 幂等且拒绝覆盖与同名不同内容;执行器使用前仍逐 blob
重算 sha256,因此传输不可变有两道证据。

目标侧门禁:目标知识库 graph_enabled=true 时拒绝发布(发布只写 PG/ES/OSS,不写
Neo4j;未知也拒绝),只读检测、不改目标配置、不做图谱迁移。

云端入口:新增 drain 感知的 ingress 闸门(建连超时与读超时分离,半关闭单向传播,
SIGTERM 排空后写 drain.json 并 exit 0/2)、compose 叠加片段(app 不再发布端口、
frontend 与 adapter 的入口收敛到闸门、指向真实网络 weknora-test-v071-network)、
执行器启动脚本与治理 PG 反向隧道脚本(默认 unix socket,不占 TCP)。

验证:deploy/cloud-test/test_gate.py 13 项全 PASS(含 12 秒静默流、半关闭、2MiB 完整、
排空 exit 0/active_at_close=1、排空超时 exit 2、上游不可达不挂住);go test 相关包全绿;
scripts/ci_checks.py 16 项全部 success(EXIT=0,1241 用例通过/0 失败/191 已声明可选集成跳过);
云测试只读预检 17 项 / 6 FAIL,FAIL 项即当前部署缺口(无闸门、app 仍发布端口、
adapter 与 frontend 仍直连 app、云端归档根未建),未部署、未改云端任何状态。
2026-10-30 18:38:38 +08:00

166 lines
7.6 KiB
Go

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
}
// graphEnabledSQL 只读知识库自己的索引策略:图谱开关是 KB 的声明,不是部署的推测值。
const graphEnabledSQL = `
SELECT COALESCE((indexing_strategy->>'graph_enabled')::boolean, false)
FROM knowledge_bases
WHERE id = $1 AND tenant_id = $2 AND deleted_at IS NULL
`
// GraphEnabled 回答"这个目标知识库是否开启了图谱索引"。
//
// 为什么要挡在发布之前:发布链路只搬 PostgreSQL / Elasticsearch / 对象存储,
// 从不动 Neo4j。目标开图谱时,写进去的文档与图谱会静默不一致——没有任何
// 行数/摘要校验能发现"图谱还是旧的"。这里只读、只拒绝,不修改目标配置,
// 也不扩写图谱迁移。
//
// 读不到(库/行不可读、值无法解析)按未知处理:未知即拒绝。
func (t *ProductionLibraryTarget) GraphEnabled(ctx context.Context) (bool, error) {
if t.pool == nil {
return false, errors.New("目标数据库未接线:无法确认图谱开关")
}
var enabled bool
if err := t.pool.QueryRow(ctx, graphEnabledSQL, t.scope.KnowledgeBaseID, t.scope.TenantID).Scan(&enabled); err != nil {
return false, fmt.Errorf("读不到目标知识库 %s 的图谱开关:%w", t.scope.KnowledgeBaseID, err)
}
return enabled, nil
}
// verifyTargetGraphGate 把"读到开 / 读到关 / 读不到"换算成发布是否允许。
// 纯函数:决定逻辑必须能被单测固定,而不是只能靠连真库才看得到。
func verifyTargetGraphGate(enabled bool, readErr error) error {
if readErr != nil {
return fmt.Errorf("目标图谱开关未知,拒绝发布:%w", readErr)
}
if enabled {
return errors.New("目标知识库开启了图谱索引(graph_enabled=true):发布链路只写 PostgreSQL/Elasticsearch/对象存储," +
"不会同步 Neo4j,写进去的内容会与图谱静默不一致;拒绝发布(在目标侧关闭图谱或先提供图谱迁移)")
}
return nil
}
// VerifyGraphGate 是发布装配处调用的门禁入口(读实时开关 + 换算成允许/拒绝)。
func (t *ProductionLibraryTarget) VerifyGraphGate(ctx context.Context) error {
enabled, err := t.GraphEnabled(ctx)
return verifyTargetGraphGate(enabled, err)
}