Compare commits

...

4 Commits

Author SHA1 Message Date
姚章浩 8d838d9cb4 feat(library): 整库发布身份、写集合与收尾边界
build / build (push) Successful in 1m45s
执行时真实时钟与持久授权回读(撤销/过期即停并保留预备份)、写集合写前落盘、
租约与 attempt 身份、恢复队列与原发送身份分离、成功收尾必须释放维护后再登记终态。
2026-11-01 11:35:10 +08:00
姚章浩 5afd8c0140 docs: 更新整库数据契约与变更记录 2026-11-01 11:35:10 +08:00
姚章浩 8febe12d7d test(library): 隔离数据契约与 r11 身份自然键矩阵
真实本机 PG/ES/MinIO:v071 目录镜像 10 模式、结构引用/游标 15 模式、
8 表×2 外部范围身份矩阵、13 模式自然键(含软删除与合法同 parent 正例)、
备份期间三注入、收尾故障与授权撤销两个真实治理 PG 用例。

需隔离服务的用例在 test-scope.json 显式声明:普通 CI 跳过不算通过。
2026-11-01 11:35:09 +08:00
姚章浩 5eef13b615 feat(object-gateway): 统一对象写网关与不可变治理日志
方案A:所有对象写入经 loopback 网关,持久计划/grant/intent/逐版本 receipt 与
attempt→grant delivery 落在治理 PG;scope 由 provider+endpoint+bucket 决定,
同一物理桶只允许一个写域。版本 append 不等于 CAS,未锚定计划在首笔业务写前拒绝。

本提交只含网关与其适配层接线、协议文档;生产独占、凭据切换与桶设置未改动。
2026-11-01 11:35:05 +08:00
176 changed files with 15637 additions and 718 deletions
+97
View File
@@ -1,5 +1,98 @@
# Changelog
## 开发快照(源契约绑定与引用闭包)
### Fixed
- 新源捕获在同一只读事务中封存表结构、约束、索引与序列定义;发布前核源/目标目录一致性。旧快照与V1台账不改写、不重算历史摘要。
- 写前验证归档关系闭包与目标已有关系;源导出拒绝被JOIN掩盖的缺父、跨父和未知资源owner,不靠删除孤儿消除差异。
- 目标预备份、计数与恢复统一覆盖knowledge/Wiki正文及嵌套metadata的稳定资源引用;保留历史孤儿和共享资源原值,未知引用表示明确拒绝。
- 恢复前重新检查本次新建资源的未知绑定和外库正文/metadata引用;有计划外读者时在任何索引/对象/PG修改前held,父键锁内再次检查所有正文和绑定,防止先删对象才发现不可恢复。
- 实时模型准入拒绝空模型名,避免将未知模型误判为可兼容。
### Security
- 数据契约仅在一次性本机PG/ES/MinIO验证;正常业务租约、云权限、WeKnora源码及业务Schema不改。clean未知仍held,不降低所有权证明。[逐表契约与覆盖边界](docs/library-data-contract.md)。
## 开发快照(独立恢复请求与索引恢复归属)
### Fixed
- 独立恢复队列与原发布发送身份分离,可信控制源核持久请求、当前租约、原 operation、来源、目标、预备份和 WriteSet;恢复意图不再被原发布自动接管抢跑,恢复中断由新执行代次继续。
- 索引 before-image 恢复写入采用绑定原计划的暂态标记;真实提交但丢响应后,仅完整标记正文和CAS证据匹配才允许收尾,不重发已提交的标记写入。完成回执同时校验精确代次。
### Security
- 发布或恢复的 clean-finalization 丢失响应时,相同干净正文不能证明写入归属,继续 held;旧恢复unknown缺少写前标记证据也不自动认领。
- 自动授权只读角色增加 jobs 表 SELECT 核验;仍禁止其治理写权限。正式独立恢复与故障链仅为本机隔离验收,正常租约未缩短,未部署业务或变更云侧凭据/ACL/网络;整体验收未闭合前不发布。[身份、证据与剩余边界](docs/object-write-gateway.md)。
## 开发快照(可信控制交付与发送身份接管)
### Added
- 正式 worker 在持久化原写集合摘要后,通过数据身份向网关申请绑定当前执行代次的授权;可信控制域独立读取治理锚点和原计划,普通 worker 不持有控制凭据。
- 网关持久保存不可变 attempt/grant 交付记录;发送身份与当前授权 epoch 分离,新执行代次可以对账原发送并继续未发送对象,未知请求仍阻断交接。
### Changed
- **破坏性**:关闭旧 ObjectImporter staging/promotion、legacy release-worker 和写型诊断/E2E 入口;正式发布 stack 对所有对象 provider 强制网关,不回退直写。只读 capture 保留。[接入与回退边界](docs/object-write-gateway.md)。
### Security
- 自动授权核验原预备份锚点、目标、有效 attempt/owner/租约及原计划内容;拒绝跨代次替换计划。控制读取使用独立 SELECT-only 登录角色,旧手动控制端点在自动模式关闭。
- 正式 worker 已在专属本机隔离栈完成 PG 后、对象提交后两次 SIGKILL 与原计划接管;独立读回验证三代授权、一份原发送回执和唯一对象版本。演练仅在显式隔离构建中缩短租约,正常构建维持10分钟,不接受环境变量缩短。真实部署独占与整模块验收尚未完成,仍禁止部署部分候选;未切生产凭据、ACL 或网络,未新增云对象写入。
## 开发快照(统一对象写入网关候选)
### Added
- 新增对象写入网关与独立控制客户端:冻结逐key允许集合、持久epoch/intent/精确版本回执、同key串行化与未知请求阻断交接;网关模式拒绝无计划Put/Copy和直写回退。保持资源UUID、物理路径及历史摘要不变。
### Fixed
- 已确认归属及CAS代次的索引补偿删除,在真实删除成功却丢失响应后可按精确缺失完成恢复;重新创建的文档代次仍拒绝接管,不盲重发删除。
### Security
- 网关逐请求绑定协议与目标,控制/数据身份分离;拒绝不完整回执、无持久日志、只读或失败的日志事务、未登记计划及缺失/过期的审核签名。治理证据禁止更新、删除和截断。
- 此候选尚未完成正式worker控制grant自动交付、跨新epoch接管及真实写入口独占验证,禁止部署部分业务实现;生产凭据/ACL/网络未改,未进行网关云OSS端到端写。[配置、信任边界与剩余项](docs/object-write-gateway.md)。
## 开发快照(旧封存来源关联与归档持久性)
### Added
- 管理员可从发布页选择历史快照,核验原捕获执行器身份、期望指纹及清单后关联当前来源。关联只追加治理审计证据,不重新封存、不修改原摘要,也不代替发布授权。
### Fixed
- 归档初始化同步根目录及父目录,目录同步失败时拒绝继续,避免仅同步文件仍遗漏目录项持久性。
## 开发快照(存储回执与隔离恢复)
### Fixed
- 每次同步冻结实际目标预备份与独立计划;重复 Wiki slug 在写前拒绝,晚期失败仍清理本次新增对象并保留复用资源。
- 索引逐 ID 记录不可变回执;带操作归属标记的写入在真实服务提交后丢失响应时,可由新进程确认并补偿,不凭相同正文猜测归属。
- 对象阶段进程中断验证覆盖实际 MinIO 提交后、回执落盘前的 SIGKILL 与持久计划恢复。
- 不可变副作用证据拒绝祖先软链接,并逐级同步新目录的父目录;同步错误返回失败,不再只同步最末两级。
### Changed
- 增加原生 OSS 精确版本协议及显式隔离测试入口,已完成明确隔离前缀内的真实版本写入、精确读回与无残留清理,尚未替代生产条件创建路径;无充分证据的 unknown 分支、跨域 fencing 和全部验收仍未闭合,禁止发布部分实现。[兼容与未完成边界](docs/library-migration-contract.md)。
## 开发快照(发布身份与不可变计划基础)
### Fixed
- 整库发布保留 UUID 和复合键,Wiki 数值身份与大整数内容不再经过浮点数;chunks、标签与 Wiki 日志使用持久化的目标本地编号映射,接管时校验来源和映射覆盖。
- worker 装饰器转发既有写集合接管能力;写集合及资源复用证据不可覆盖,返回前同步文件与目录。
- 预备份保留实际范围内的软删除行和关联;同租户异知识库不再被误判为来源残留,关系表按精确二元组识别。
- 索引按全局文档 ID 拒绝跨知识库覆盖,采用 create/乐观并发条件写入并检查逐项结果;共享资源内容差异写前拒绝,相同资源按证据只读复用。
### Changed
- 本开发快照尚未完成整模块验收,禁止据此开启发布写门:对象版本化精确清理仅完成 MinIO 局部验证,OSS 适配、执行栅栏、来源候选/UI 和真实 worker 连续两次中断验证仍待闭合。[兼容与未完成边界](docs/library-migration-contract.md)。
## 开发快照(云对象存储寻址兼容)
### Fixed
@@ -1170,6 +1263,10 @@
### Fixed
- 发布在预备份后、规划前与首笔写入前按治理库授权行重新判定:授权被撤销或过期即停,保留预备份且不写目标;不再只信内存里的有效期。
- 整库发布绑定序列归属及完整迁移目录,识别分块与 Wiki 的规范嵌套引用;未知结构或跨父引用在写入前拒绝,保留正常资料的发布与恢复路径。
- 发布使用执行时真实时钟,在预备份后与首个业务阶段前复核授权;预备份绑定对象精确版本,拒绝读取期间被替换的对象(包括同字节新版本)。
- 修复钉钉新登记来源仍按旧离线目录身份取件的问题:从当前来源配置读取空间坐标,实时枚举所在目录并严格匹配节点身份;同名文件不替代、目录不完整不误报删除。修复解析监控遗漏 `version_id` 取件任务及缺少业务元数据的失败记录,正确显示失败原因、重试入口与历史。
- 修复通过带端口的 HTTP 地址访问问答运营时,正常同源操作被误报“拒绝跨站配置请求”:网页代理保留原始 Host 及端口,使缺少 Fetch Metadata 的浏览器也能正确执行 Origin 校验。保留后端跨站、异端口、伪造转发头与缺失操作意图的拒绝保护。
+56
View File
@@ -832,6 +832,62 @@
}
}
},
"/api/v1/library/source-associations": {
"post": {
"tags": [
"Runtime"
],
"operationId": "associateLegacyLibrarySource",
"summary": "管理员核验原捕获证据并关联旧封存来源;不修改快照、不发布内容",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": false,
"required": [
"scope",
"snapshot_id"
],
"properties": {
"scope": {
"type": "string",
"enum": [
"internal",
"external"
]
},
"snapshot_id": {
"type": "string"
}
}
}
}
}
},
"responses": {
"200": {
"description": "已持久关联并读回;associated=true,published=false,返回准确snapshot_id/source_id/source_identity"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"403": {
"description": "需要管理员登录身份"
},
"409": {
"description": "原捕获证据缺失、来源/指纹/清单不符或已有不可变关联冲突"
},
"500": {
"$ref": "#/components/responses/InternalError"
},
"503": {
"description": "来源配置或关联存储不可用"
}
}
}
},
"/api/v1/library/captures": {
"get": {
"tags": [
+4
View File
@@ -221,6 +221,10 @@ func run(ctx context.Context, getenv func(string) string) error {
LibraryTargetJournalRoot: config.LibraryTargetJournalRoot,
LibrarySourceInstance: config.SourceInstance(),
LibrarySourceProject: config.SourceProject(),
LibrarySourceApp: config.LibrarySourceApp,
LibrarySourceTenantID: config.LibrarySourceTenantID,
LibrarySourceInternalKB: config.LibrarySourceInternalKB,
LibrarySourceExternalKB: config.LibrarySourceExternalKB,
LibraryAgentSocket: config.LibraryAgentSocket,
LibraryExecutorStatusMaxAge: config.LibraryExecutorStatusMaxAge,
LibraryCapacityBudgetBytes: config.LibraryCapacityBudgetBytes,
+61
View File
@@ -0,0 +1,61 @@
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"time"
"knowledge-governance/internal/libraryrelease"
"knowledge-governance/internal/objectgateway"
v071 "knowledge-governance/internal/releaseadapter/v071"
)
// This command belongs to the separately authenticated controller. It must not
// be installed with control credentials in an ordinary data worker container.
func main() {
if e := run(); e != nil {
fmt.Fprintln(os.Stderr, e)
os.Exit(1)
}
}
func run() error {
path := flag.String("plan", "", "exact frozen write-set JSON")
directory := flag.String("grant-directory", "", "private durable grant output directory")
expected := flag.Int64("expected-epoch", -1, "previous epoch from the frozen controller intent; never guessed")
flag.Parse()
if *path == "" || *directory == "" || *expected < 0 || flag.NArg() != 0 {
return errors.New("exact plan, grant directory and expected epoch required")
}
f, e := os.Open(*path)
if e != nil {
return errors.New("frozen gateway plan unavailable")
}
defer f.Close()
var set libraryrelease.WriteSet
d := json.NewDecoder(io.LimitReader(f, 16<<20))
d.DisallowUnknownFields()
if d.Decode(&set) != nil || d.Decode(&struct{}{}) != io.EOF {
return errors.New("frozen gateway plan invalid")
}
provider, endpoint, bucket := os.Getenv("OBJECT_GATEWAY_PROVIDER"), os.Getenv("OBJECT_GATEWAY_ENDPOINT"), os.Getenv("OBJECT_GATEWAY_BUCKET")
if provider == "" || endpoint == "" || bucket == "" {
return errors.New("exact gateway target configuration required")
}
scope := objectgateway.Digest([]byte(provider + "\x00" + endpoint + "\x00" + bucket))
client, e := objectgateway.NewClient(os.Getenv("OBJECT_GATEWAY_URL"), os.Getenv("OBJECT_GATEWAY_CONTROL_TOKEN"), scope)
if e != nil {
return e
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
if e = v071.PrepareObjectGatewayGrant(ctx, client, set, *expected, provider, bucket, *directory); e != nil {
return e
}
fmt.Printf("gateway grant persisted: plan=%s epoch=%d\n", set.Digest, *expected+1)
return nil
}
+82
View File
@@ -0,0 +1,82 @@
package main
import (
"context"
"crypto/ed25519"
"encoding/base64"
"errors"
"log"
"net"
"net/http"
"os"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/objectgateway"
v071 "knowledge-governance/internal/releaseadapter/v071"
)
func main() {
if err := run(); err != nil {
log.Print(err)
os.Exit(1)
}
}
func run() error {
ctx := context.Background()
addr := os.Getenv("OBJECT_GATEWAY_LISTEN")
host, _, e := net.SplitHostPort(addr)
// A reviewed TLS terminator may expose this loopback-only listener. Never bind
// authenticated plaintext to a LAN address by an accidental config default.
if e != nil || (host != "127.0.0.1" && host != "::1") {
return errors.New("gateway_requires_loopback_listener")
}
data, control := os.Getenv("OBJECT_GATEWAY_DATA_TOKEN"), os.Getenv("OBJECT_GATEWAY_CONTROL_TOKEN")
if len(data) < 32 || len(control) < 32 || data == control {
return errors.New("gateway_distinct_tokens_required")
}
pub, e := base64.StdEncoding.DecodeString(os.Getenv("OBJECT_GATEWAY_AUDIT_PUBLIC_KEY"))
if e != nil || len(pub) != ed25519.PublicKeySize {
return errors.New("gateway_auditor_key_required")
}
provider, endpoint, bucket := os.Getenv("OBJECT_GATEWAY_PROVIDER"), os.Getenv("OBJECT_GATEWAY_ENDPOINT"), os.Getenv("OBJECT_GATEWAY_BUCKET")
scope := objectgateway.Digest([]byte(provider + "\x00" + endpoint + "\x00" + bucket))
pool, e := pgxpool.New(ctx, os.Getenv("OBJECT_GATEWAY_DATABASE_URL"))
if e != nil {
return objectgateway.ErrPersistence
}
defer pool.Close()
backend, e := v071.NewGatewayBackend(v071.S3ObjectStoreConfig{Provider: provider, Endpoint: endpoint, Bucket: bucket, Region: os.Getenv("OBJECT_GATEWAY_REGION"), AccessKeyID: os.Getenv("OBJECT_GATEWAY_ACCESS_KEY"), SecretAccessKey: os.Getenv("OBJECT_GATEWAY_SECRET_KEY"), MaxObjectBytes: 256 * 1024 * 1024})
if e != nil {
return errors.New("gateway_backend_configuration_invalid")
}
g := &objectgateway.Gateway{Pool: pool, Scope: scope, Backend: backend, MaxBytes: 256 * 1024 * 1024, Isolation: objectgateway.AuditVerifier{Path: os.Getenv("OBJECT_GATEWAY_AUDIT_FILE"), PublicKey: pub, Scope: scope, GatewayID: os.Getenv("OBJECT_GATEWAY_ID")}}
if governanceURL := os.Getenv("OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL"); governanceURL != "" {
cfg, e := pgxpool.ParseConfig(governanceURL)
if e != nil {
return errors.New("gateway_control_authority_unavailable")
}
cfg.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
cfg.MaxConns = 4
governancePool, e := pgxpool.NewWithConfig(ctx, cfg)
if e != nil {
return errors.New("gateway_control_authority_unavailable")
}
defer governancePool.Close()
authority := &v071.GatewayGovernanceAuthority{Pool: governancePool, ArchiveRoot: os.Getenv("OBJECT_GATEWAY_ARCHIVE_ROOT"), TargetID: os.Getenv("OBJECT_GATEWAY_TARGET_ID"), Provider: provider, Bucket: bucket}
if e = authority.Ready(ctx); e != nil {
return e
}
g.Authority = authority
}
probe, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
if e = g.Ready(probe); e != nil {
return e
}
server := &http.Server{Addr: addr, Handler: objectgateway.HTTPServer{Gateway: g, DataToken: data, ControlToken: control}, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 3 * time.Minute, WriteTimeout: 3 * time.Minute, IdleTimeout: 30 * time.Second}
if server.ListenAndServe() != nil {
return errors.New("gateway_listener_stopped")
}
return nil
}
+4
View File
@@ -81,6 +81,10 @@ func secret(path string) string {
}
func main() {
if err := v071.CheckLegacyObjectWrites(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
configPath := flag.String("config", "", "release config json")
knowledgeID := flag.String("knowledge", "", "knowledge id to release")
mode := flag.String("mode", "publish", "publish | withdraw | rollback")
+4
View File
@@ -69,6 +69,10 @@ func secret(path string) string {
}
func main() {
if err := v071.CheckLegacyObjectWrites(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
configPath := flag.String("config", "", "release config json")
knowledgeID := flag.String("knowledge", "", "knowledge id to diagnose")
flag.Parse()
+19
View File
@@ -0,0 +1,19 @@
package main
import (
"context"
v071 "knowledge-governance/internal/releaseadapter/v071"
"testing"
)
func TestLegacyReleaseRuntimeRefusesBeforeCredentials(t *testing.T) {
// Empty credential paths would fail differently if route assembly were reached.
runtime, e := buildReleaseRuntime(context.Background(), releaseRuntimeConfig{})
if runtime != nil || e == nil || e.Error() != v071.CheckLegacyObjectWrites().Error() {
t.Fatal("legacy runtime did not fail at the no-write gate", e)
}
route, pools, e := buildReleaseRoute(context.Background(), "", releaseTargetSnapshotConfig{}, releaseRouteConfig{})
if route != nil || len(pools) != 0 || e == nil || e.Error() != v071.CheckLegacyObjectWrites().Error() {
t.Fatal("direct route bypassed the no-write gate", e)
}
}
+6
View File
@@ -31,6 +31,9 @@ func (runtime *releaseRuntime) Close() {
}
func buildReleaseRuntime(ctx context.Context, config releaseRuntimeConfig) (*releaseRuntime, error) {
if err := v071.CheckLegacyObjectWrites(); err != nil {
return nil, err
}
runtime := &releaseRuntime{}
publishers := make(map[string]releaseworkflow.Publisher, len(config.Routes))
for _, route := range config.Routes {
@@ -52,6 +55,9 @@ func buildReleaseRuntime(ctx context.Context, config releaseRuntimeConfig) (*rel
}
func buildReleaseRoute(ctx context.Context, archiveRoot string, snapshot releaseTargetSnapshotConfig, route releaseRouteConfig) (releaseworkflow.Publisher, []*pgxpool.Pool, error) {
if err := v071.CheckLegacyObjectWrites(); err != nil {
return nil, nil, err
}
sourceDatabaseURL, err := readRestrictedValue(route.Source.DatabaseURLFile)
if err != nil {
return nil, nil, errors.New("read source database credential")
+8
View File
@@ -0,0 +1,8 @@
//go:build !kg_isolated_drill
package main
import "time"
// Production timing is not controllable through test environment variables.
const libraryAttemptLease = 10 * time.Minute
@@ -0,0 +1,26 @@
//go:build kg_isolated_drill
package main
import (
"net/url"
"os"
"strings"
"time"
)
// Only an explicitly tagged executable can shorten the real lease clock. It
// refuses non-disposable DBs; no production binary recognizes this injection.
const libraryAttemptLease = 4 * time.Second
func init() {
if os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
panic("isolated drill build requires explicit opt-in")
}
for _, name := range []string{"DATABASE_URL", "LIBRARY_PRODUCTION_DATABASE_URL"} {
u, e := url.Parse(os.Getenv(name))
if e != nil || (u.Hostname() != "127.0.0.1" && u.Hostname() != "localhost") || !strings.HasPrefix(u.Path, "/kg_library_test_r8_") {
panic("isolated drill build refuses non-disposable database")
}
}
}
+16
View File
@@ -0,0 +1,16 @@
//go:build !kg_isolated_drill
package main
import (
"testing"
"time"
)
func TestProductionAttemptTimingIgnoresDrillEnvironment(t *testing.T) {
t.Setenv("KG_LIBRARY_TEST_ISOLATED", "1")
t.Setenv("WORKER_LEASE_DURATION", "1ms")
if libraryAttemptLease != 10*time.Minute {
t.Fatal("production lease shortened by drill injection")
}
}
+6 -4
View File
@@ -111,10 +111,12 @@ func runLibraryBaseline(ctx context.Context, base *postgresstore.Store, config a
if _, admitErr := admitLibraryJob(ctx, base, job, payload.LibraryJobID, payload.Scope, governance.LibraryJobBaseline, true); admitErr != nil {
return admitErr
}
writer, attemptErr := beginLibraryWriter(ctx, base, payload.LibraryJobID, libraryQueueOwner(config.WorkerID, job, payload.LibraryJobID))
if attemptErr != nil {
return attemptErr
}
return runOwnedLibraryAttempt(ctx, base, config, job, payload.LibraryJobID, func(runCtx context.Context, writer *libraryAttemptWriter) error {
return runLibraryBaselineAttempt(runCtx, writer, config, payload)
})
}
func runLibraryBaselineAttempt(ctx context.Context, writer *libraryAttemptWriter, config appconfig.Config, payload libraryBaselinePayload) error {
store := writer
now := time.Now().UTC()
recorder := libraryStageRecorder{store: store, jobID: payload.LibraryJobID, scope: payload.Scope,
@@ -0,0 +1,51 @@
package main
import (
"context"
"errors"
"testing"
"time"
"knowledge-governance/internal/libraryrelease"
)
type contractAdoptingTarget struct {
plainTarget
adopted int
planned int
reject error
}
func (t *contractAdoptingTarget) AdoptWriteSet(set libraryrelease.WriteSet) error {
t.adopted++
return t.reject
}
func (t *contractAdoptingTarget) PlanWriteSet(context.Context, libraryrelease.WriteSetPlan) (libraryrelease.WriteSet, error) {
t.planned++
return libraryrelease.WriteSet{}, errors.New("must not replan")
}
func TestContractWorkerWrapperReplaysPersistedPlan(t *testing.T) {
for _, reject := range []bool{false, true} {
inner := &contractAdoptingTarget{}
if reject {
inner.reject = errors.New("binding mismatch")
}
wrapped := &contentTrackedTarget{inner: inner, jobID: "job-1", onApply: func() {}}
set := sealedLedger(t, "")
now := time.Now().UTC()
request := libraryrelease.Request{JobID: "job-1", Target: "internal", SnapshotID: "target-snap", ParamsDigest: "digest", Now: now,
Grant: libraryrelease.Grant{Target: "internal", SnapshotID: "target-snap", ParamsDigest: "digest", ExpiresAt: now.Add(time.Hour), AuthorizedBy: "test"}}
backup := ledgerBackupStore{ref: libraryrelease.BackupRef{ID: "backup-1", SnapshotID: "backup-snap", Bytes: 4096}, write: &set}
result := libraryrelease.Run(context.Background(), request, wrapped, backup, nil)
if inner.adopted != 1 || inner.planned != 0 {
t.Fatalf("real wrapper lost adoption: adopted=%d planned=%d result=%+v", inner.adopted, inner.planned, result)
}
if reject && (inner.applied != 0 || result.State == "succeeded") {
t.Fatal("adoption failure must be zero-write")
}
if !reject && result.State != "succeeded" {
t.Fatalf("replay: %+v", result)
}
}
}
@@ -0,0 +1,197 @@
package main
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"time"
"knowledge-governance/internal/governance"
postgresstore "knowledge-governance/internal/platform/postgres"
)
// B28:内容已通过校验之后的两类收尾故障必须只补收尾、不重写目标,且绝不伪报成功。
//
// 这里用真实治理 PG(维护行、作业行、版本事件行都是真表),故障只注入在
// “释放 scope 维护占用”这一个步骤上;其余调用照旧打到真库。
type r11FinishFaultStore struct {
*postgresstore.Store
applies *int
failOnRelease bool
releaseFailure error
}
func (s *r11FinishFaultStore) ReleaseLibraryMaintenance(ctx context.Context, scope, ownerJobID string, now time.Time) error {
if s.failOnRelease {
return s.releaseFailure
}
return s.Store.ReleaseLibraryMaintenance(ctx, scope, ownerJobID, now)
}
type r11HealthyTarget struct{ err error }
func (h r11HealthyTarget) VerifyRunning(context.Context) error { return h.err }
func TestR11FinalizeFailureAfterTerminalHoldsThenRepairsWithoutRewrite(t *testing.T) {
store, _ := openLedgerStore(t)
ctx := context.Background()
now := time.Now().UTC()
const (
scope = "internal"
instance = "kgseal-r11-finalize"
jobID = "libsync-r11-finalize"
target = "target-snap-r11-finalize"
backup = "backup-snap-r11-finalize"
operation = "libop-r11-finalize"
)
if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ID: jobID, Scope: scope,
Kind: governance.LibraryJobSync, IdempotencyKey: "library.sync:internal:r11-finalize",
RequestDigest: "digest-r11-finalize", Actor: "admin", TargetSnapshotID: target},
governance.SyncStages(), now); err != nil {
t.Fatalf("create library job: %v", err)
}
// 生效事件必须引用真实 operation:登记前先落这条执行意图(真表,不是夹具)。
if _, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ID: operation, Scope: scope,
Kind: governance.LibraryJobSync, TargetSnapshotID: target, RequestDigest: "digest-r11-finalize",
OperationKey: "r11-finalize", Actor: "admin", CreatedAt: now}); err != nil {
t.Fatalf("ensure library operation: %v", err)
}
// 这次作业确实持有两把维护锁:收尾失败后必须仍然持有(页面显示维护中)。
if _, err := store.AcquireLibraryMaintenance(ctx, postgresstore.LibraryMaintenance{Scope: scope,
OwnerJobID: jobID, TargetIdentity: "scope=" + scope, Level: "library", State: "acquired",
IngressState: "closed", Services: []string{"app"}}, now); err != nil {
t.Fatalf("acquire library maintenance: %v", err)
}
if _, err := store.AcquireInstanceMaintenance(ctx, postgresstore.LibraryInstanceMaintenance{Instance: instance,
OwnerJobID: jobID, OwnerScope: scope, TargetFingerprint: "fingerprint-r11",
Level: "instance", Services: []string{"app"}, IngressState: "closed", State: "acquired"}, now); err != nil {
t.Fatalf("acquire instance maintenance: %v", err)
}
// 完整锚点:真实字节数与写集合摘要。缺任何一项,收尾都该拒绝登记而不是补一份空台账。
if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{
ID: governance.LibraryVersionID(governance.LibraryVersionProductionPrebackup, scope, backup),
Scope: scope, Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: backup,
SourceJobID: jobID, CreatedBy: "tester",
Evidence: map[string]any{"backup_snapshot": backup, "backup_bytes": float64(4096),
"writeset_digest": "writeset-digest-r11", "writeset_rows": float64(7)},
CreatedAt: now,
}); err != nil {
t.Fatalf("record prebackup version: %v", err)
}
// 目标内容落盘且计数:任何“再来一次”的重写都会让计数增长。
root := t.TempDir()
published := filepath.Join(root, "target-content.txt")
if err := os.WriteFile(published, []byte("published-v1"), 0o600); err != nil {
t.Fatal(err)
}
applies := 1 // 内容写入(含校验)已经发生过一次
writer := &libraryAttemptWriter{Store: store, attempt: governance.LibraryAttempt{
OperationID: operation, JobID: jobID, Owner: "queue-r11-finalize"}}
recorder := libraryStageRecorder{store: store, jobID: jobID, scope: scope, operationID: operation}
payload := libraryReleasePayload{LibraryJobID: jobID, Scope: scope, TargetSnapshotID: target, FinalizeOnly: true}
previous := governance.LibraryJob{ID: jobID, Scope: scope, Kind: governance.LibraryJobSync,
SnapshotID: backup, TargetSnapshotID: target}
grant := governance.LibraryReleaseAuthorization{AuthorizedBy: "admin", Scope: scope, SnapshotID: target}
// 1) 事件登记失败(这里用真实数据缺口:锚点里没有写集合摘要)必须拒绝登记,
// 不写生效版本、不进入终态、不重写目标。
if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{
ID: governance.LibraryVersionID(governance.LibraryVersionProductionPrebackup, scope, backup+"-noanchor"),
Scope: scope, Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: backup + "-noanchor",
SourceJobID: jobID + "-noanchor", CreatedBy: "tester",
Evidence: map[string]any{"backup_snapshot": backup + "-noanchor"},
CreatedAt: now,
}); err != nil {
t.Fatalf("record anchorless prebackup: %v", err)
}
badBoundary := payload
badBoundary.TargetSnapshotID = target + "-noanchor"
badPrevious := previous
badPrevious.SnapshotID = backup + "-noanchor"
if _, err := rebuildSuccessBoundary(ctx, writer, recorder, badBoundary, badPrevious,
governance.LibraryJobSync, grant); err == nil {
t.Fatal("anchorless prebackup was accepted as a success boundary")
}
if _, found, err := store.LibraryVersionByRef(ctx, scope, governance.LibraryVersionProductionEffective,
jobID, target+"-noanchor"); err != nil || found {
t.Fatalf("refused registration still wrote an effective version: found=%v err=%v", found, err)
}
if job, err := store.LibraryJob(ctx, jobID); err != nil || job.State == governance.LibraryJobSucceeded {
t.Fatalf("refused registration reported success: state=%v err=%v", job.State, err)
}
// 2) journal 终态之后、释放维护占用这一步失败:不许报成功,锁必须继续持有。
failing := &r11FinishFaultStore{Store: store, applies: &applies, failOnRelease: true,
releaseFailure: errors.New("injected: scope maintenance release failed after terminal journal")}
boundary := successBoundary{Ready: true, Backup: backup, Target: target, FinishedAt: now}
if err := finishLibrarySuccess(ctx, failing, r11HealthyTarget{}, instance, scope, jobID, boundary); err == nil {
t.Fatal("finish reported success even though the maintenance release failed")
}
if job, err := store.LibraryJob(ctx, jobID); err != nil || job.State != governance.LibraryJobFailed {
t.Fatalf("job must be failed after finalize failure: state=%v err=%v", job.State, err)
}
held, err := store.LibraryMaintenanceOf(ctx, scope)
if err != nil || held == nil || held.OwnerJobID != jobID || held.ReleasedAt != nil {
t.Fatalf("scope maintenance must stay held by this job: %+v err=%v", held, err)
}
if held.State != "needs_restore" {
t.Fatalf("held maintenance state = %q, want needs_restore", held.State)
}
if applies != 1 {
t.Fatalf("finalize failure rewrote target content: applies=%d", applies)
}
content, err := os.ReadFile(published)
if err != nil || string(content) != "published-v1" {
t.Fatalf("target bytes changed during finalize failure: %q err=%v", content, err)
}
// 3) 修复只补收尾:同一个持久凭据再收尾一次即可成功,且仍然不重写。
repaired := &r11FinishFaultStore{Store: store, applies: &applies}
if err := finishLibrarySuccess(ctx, repaired, r11HealthyTarget{}, instance, scope, jobID, boundary); err != nil {
t.Fatalf("finalize-only repair failed: %v", err)
}
if job, err := store.LibraryJob(ctx, jobID); err != nil || job.State != governance.LibraryJobSucceeded {
t.Fatalf("job not succeeded after repair: state=%v err=%v", job.State, err)
}
released, err := store.LibraryMaintenanceOf(ctx, scope)
if err != nil || released == nil || released.ReleasedAt == nil {
t.Fatalf("scope maintenance not released after repair: %+v err=%v", released, err)
}
if applies != 1 {
t.Fatalf("finalize-only repair rewrote target content: applies=%d", applies)
}
content, err = os.ReadFile(published)
if err != nil || string(content) != "published-v1" {
t.Fatalf("target bytes changed during repair: %q err=%v", content, err)
}
// 4) current/event 与实际内容一致:补登记的生效版本恰好一条,重复收尾不再新增。
if _, err := rebuildSuccessBoundary(ctx, writer, recorder, payload, previous,
governance.LibraryJobSync, grant); err != nil {
t.Fatalf("rebuild boundary after repair: %v", err)
}
if _, err := rebuildSuccessBoundary(ctx, writer, recorder, payload, previous,
governance.LibraryJobSync, grant); err != nil {
t.Fatalf("idempotent rebuild: %v", err)
}
current, found, err := store.LibraryCurrentVersion(ctx, scope)
if err != nil || !found || current.SnapshotID != target || current.SourceJobID != jobID {
t.Fatalf("current does not point at the repaired snapshot: %+v found=%v err=%v", current, found, err)
}
versions, err := store.LibraryVersionsBySnapshot(ctx, scope, target)
if err != nil {
t.Fatalf("read effective versions: %v", err)
}
same := 0
for _, version := range versions {
if version.Kind == governance.LibraryVersionProductionEffective {
same++
}
}
if same != 1 {
t.Fatalf("effective version rows for %s = %d, want exactly 1", target, same)
}
}
@@ -0,0 +1,102 @@
package main
import (
"context"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/libraryrelease"
)
// r11RevokingBackups 在真实预备份完成之后撤销授权:这正是"排空之后、首次写之前"
// 被撤销的那个窗口,不是凭空造一个失败。
type r11RevokingBackups struct {
inner libraryrelease.BackupStore
after func()
}
func (b r11RevokingBackups) Prepare(ctx context.Context, id string, current libraryrelease.CurrentState) (libraryrelease.BackupRef, error) {
ref, err := b.inner.Prepare(ctx, id, current)
if err == nil && b.after != nil {
b.after()
}
return ref, err
}
// B30:授权在预备份之后被撤销,必须一笔目标写都不发生;同一链路在没有撤销时
// 正常完成(正例对照,证明这条门不是靠"永远失败"通过的)。
func TestR11RevokedAuthorizationStopsBeforeFirstWrite(t *testing.T) {
store, _ := openLedgerStore(t)
ctx := context.Background()
now := time.Now().UTC()
const (
scope = "internal"
jobID = "libsync-r11-revoke"
snapshot = "control-snap-r11-revoke"
target = "target-snap-r11-revoke"
params = "params-r11-revoke"
operation = "libop-r11-revoke"
backup = "backup-snap-r11-revoke"
authID = "libauth-r11-revoke"
)
if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ID: jobID, Scope: scope,
Kind: governance.LibraryJobSync, IdempotencyKey: "library.sync:internal:r11-revoke",
RequestDigest: params, Actor: "admin", TargetSnapshotID: target}, governance.SyncStages(), now); err != nil {
t.Fatalf("create library job: %v", err)
}
if _, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ID: operation, Scope: scope,
Kind: governance.LibraryJobSync, TargetSnapshotID: target, RequestDigest: params,
OperationKey: "r11-revoke", Actor: "admin", CreatedAt: now}); err != nil {
t.Fatalf("ensure library operation: %v", err)
}
if err := store.CreateLibraryAuthorization(ctx, governance.LibraryReleaseAuthorization{ID: authID, Scope: scope,
SnapshotID: target, ParamsDigest: params, AuthorizedBy: "admin", ExpiresAt: now.Add(time.Hour), CreatedAt: now}); err != nil {
t.Fatalf("create authorization: %v", err)
}
grant := libraryrelease.Grant{Target: scope, SnapshotID: target, ParamsDigest: params,
ExpiresAt: now.Add(time.Hour), AuthorizedBy: "admin"}
request := libraryrelease.Request{JobID: jobID, Target: scope, SnapshotID: target,
ParamsDigest: params, Now: now, Grant: grant}
backups := ledgerTestBackups{ref: libraryrelease.BackupRef{ID: "backup-" + backup, SnapshotID: backup,
Bytes: 4096, Universe: map[string]libraryrelease.TableFingerprint{"resources": {Count: 1, Digest: "universe"}}}}
// 正例对照:授权有效时同一条链路写完四个阶段。
control := &planningTarget{}
controlTarget := &contentTrackedTarget{inner: control, jobID: jobID, onApply: func() {},
revalidateGrant: revalidateLibraryGrant(store)}
if out := libraryrelease.Run(ctx, request, controlTarget, backups, nil); out.State != "succeeded" {
t.Fatalf("control run did not succeed with a live authorization: %+v", out)
}
if control.applied != 4 {
t.Fatalf("control run applied %d stages, want 4", control.applied)
}
// 撤销后:预备份成功、授权随即失效,写集合都不该被算出来(那会分配序列)。
guarded := &planningTarget{}
guardedTarget := &contentTrackedTarget{inner: guarded, jobID: jobID, onApply: func() {},
revalidateGrant: revalidateLibraryGrant(store)}
revoking := r11RevokingBackups{inner: backups, after: func() {
if err := store.RevokeLibraryAuthorization(ctx, authID, time.Now().UTC()); err != nil {
t.Fatalf("revoke authorization: %v", err)
}
}}
out := libraryrelease.Run(ctx, request, guardedTarget, revoking, nil)
if out.State != "failed" {
t.Fatalf("revoked authorization still produced state %q: %+v", out.State, out)
}
if !strings.Contains(out.Error, "持久授权") {
t.Fatalf("refusal reason does not name the persisted authorization: %q", out.Error)
}
if guarded.applied != 0 || guarded.planned != 0 {
t.Fatalf("revoked authorization wrote target: applied=%d planned=%d", guarded.applied, guarded.planned)
}
if out.Backup.SnapshotID != backup || !strings.Contains(out.Recovery, "预备份保留") {
t.Fatalf("prebackup must be preserved for a retry: backup=%+v recovery=%q", out.Backup, out.Recovery)
}
// 撤销是持久的:再读一次仍然查不到有效授权。
if _, ok, err := store.ActiveLibraryAuthorization(ctx, scope, target, params, time.Now().UTC()); err != nil || ok {
t.Fatalf("revocation did not persist: ok=%v err=%v", ok, err)
}
}
+62 -14
View File
@@ -43,6 +43,40 @@ type contentTrackedTarget struct {
inner libraryrelease.Target
jobID string
onApply func()
// revalidateGrant 由 runLibraryRelease 无条件接线:每笔副作用前按治理库里的
// 授权行重新判定(撤销/过期即停)。测试夹具可以显式传 nil 表示"这份夹具没有
// 持久授权行",但真实发布路径不允许为空 —— 那里的空值等于回到只信内存快照。
revalidateGrant func(context.Context, libraryrelease.Grant) error
}
// revalidateLibraryGrant 是"授权没有被中途撤销/过期"的唯一判定实现:
// 真实发布链路与测试都走它,避免测试自己写一份看起来相同的查询。
func revalidateLibraryGrant(store *postgresstore.Store) func(context.Context, libraryrelease.Grant) error {
return func(ctx context.Context, current libraryrelease.Grant) error {
// 权威来源是治理库里的授权行:参数摘要一变就查不到,撤销/过期立即消失。
found, ok, err := store.ActiveLibraryAuthorization(ctx, current.Target, current.SnapshotID,
current.ParamsDigest, time.Now().UTC())
if err != nil {
return fmt.Errorf("读取持久授权失败:%w", err)
}
if !ok {
return errors.New("当前授权已撤销或已过期")
}
if found.AuthorizedBy != current.AuthorizedBy {
return errors.New("持久授权与本次执行身份不一致")
}
return nil
}
}
func (t *contentTrackedTarget) RevalidateGrant(ctx context.Context, grant libraryrelease.Grant) error {
if t.revalidateGrant != nil {
return t.revalidateGrant(ctx, grant)
}
if inner, ok := t.inner.(libraryrelease.GrantRevalidator); ok {
return inner.RevalidateGrant(ctx, grant)
}
return nil
}
func (t *contentTrackedTarget) Current(ctx context.Context) (libraryrelease.CurrentState, error) {
@@ -91,6 +125,20 @@ func (t *contentTrackedTarget) PlanWriteSet(ctx context.Context, plan libraryrel
return set, err
}
func (t *contentTrackedTarget) AdoptWriteSet(set libraryrelease.WriteSet) error {
adopter, ok := t.inner.(libraryrelease.WriteSetAdopter)
if !ok {
return errors.New("目标实现不支持接管已持久化写集合,拒绝重建计划")
}
if set.JobID != t.jobID {
return errors.New("写集合与 worker 作业身份不符")
}
return adopter.AdoptWriteSet(set)
}
var _ libraryrelease.WriteSetPlanner = (*contentTrackedTarget)(nil)
var _ libraryrelease.WriteSetAdopter = (*contentTrackedTarget)(nil)
// libraryReleasePayload 是同步与恢复共用的队列载荷形状。
type libraryReleasePayload struct {
LibraryJobID string `json:"library_job_id"`
@@ -117,19 +165,13 @@ func runLibraryRelease(ctx context.Context, base *postgresstore.Store, config ap
if _, admitErr := admitLibraryJob(ctx, base, job, payload.LibraryJobID, payload.Scope, kind, true); admitErr != nil {
return admitErr
}
// 执行代次:这一次投递是一个确定的执行者身份。所有治理写入都走 writer
// (同名方法带 epoch 守卫),失租的旧执行从此写不进业务状态/维护锁(F13)。
writer, attemptErr := beginLibraryWriter(ctx, base, payload.LibraryJobID, libraryQueueOwner(config.WorkerID, job, payload.LibraryJobID))
if attemptErr != nil {
return attemptErr
}
defer func() {
if err != nil {
writer.finish(context.WithoutCancel(ctx), governance.LibraryAttemptFailed, err.Error())
return
}
writer.finish(context.WithoutCancel(ctx), governance.LibraryAttemptCompleted, "")
}()
return runOwnedLibraryAttempt(ctx, base, config, job, payload.LibraryJobID, func(runCtx context.Context, writer *libraryAttemptWriter) error {
return runLibraryReleaseAttempt(runCtx, writer, config, kind, payload)
})
}
func runLibraryReleaseAttempt(ctx context.Context, writer *libraryAttemptWriter, config appconfig.Config,
kind governance.LibraryJobKind, payload libraryReleasePayload) (err error) {
store := writer
now := time.Now().UTC()
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobRunning, "prebackup", "", "", "", "", now)
@@ -320,7 +362,8 @@ func runLibraryRelease(ctx context.Context, base *postgresstore.Store, config ap
}
pending := successBoundary{}
tracked := &contentTrackedTarget{inner: target, jobID: payload.LibraryJobID,
onApply: func() { contentState = contentHalfWritten }}
onApply: func() { contentState = contentHalfWritten },
revalidateGrant: revalidateLibraryGrant(store.Store)}
allowRestore := func(error) bool {
return contentState == contentUntouched || contentState == contentSucceeded || contentState == contentRolledBack
}
@@ -549,6 +592,11 @@ func runLibraryRelease(ctx context.Context, base *postgresstore.Store, config ap
// 已经持久化预备份的重新排队(同一个业务作业 id,阶段与备份都接着用),
// 连预备份都没完成的才判失败——那种情况没有可回滚的基线,不能盲写。
func resumeInterruptedLibraryJobs(ctx context.Context, store libraryResumeStore, config appconfig.Config) (int, int, error) {
if recoveries, ok := store.(interface{ ResumeExpiredLibraryRecoveryQueues(context.Context) error }); ok {
if err := recoveries.ResumeExpiredLibraryRecoveryQueues(ctx); err != nil {
return 0, 0, err
}
}
interrupted, err := store.InterruptedLibraryJobs(ctx)
if err != nil {
return 0, 0, err
+44
View File
@@ -0,0 +1,44 @@
package main
import (
"context"
"errors"
"time"
)
// Run remains synchronous: cancellation is a request, not proof that the last
// network write has stopped. The caller may release ownership only after run
// and its cleanup have actually returned, and the renewal goroutine is joined.
func runWithLibraryLease(parent context.Context, interval time.Duration, renew func(context.Context) error, run func(context.Context) error) error {
ctx, cancel := context.WithCancelCause(parent)
defer cancel(nil)
stop := make(chan struct{})
done := make(chan error, 1)
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-stop:
done <- nil
return
case <-ctx.Done():
done <- context.Cause(ctx)
return
case <-ticker.C:
bounded, finish := context.WithTimeout(ctx, interval)
err := renew(bounded)
finish()
if err != nil {
cancel(err)
done <- err
return
}
}
}
}()
err := run(ctx)
close(stop)
leaseErr := <-done
return errors.Join(err, leaseErr, context.Cause(ctx))
}
+61
View File
@@ -0,0 +1,61 @@
package main
import (
"context"
"errors"
"testing"
"time"
)
func TestContractLeaseLossWaitsForActualWriteExit(t *testing.T) {
lost := errors.New("lease lost")
entered := make(chan struct{})
cancelled := make(chan struct{})
release := make(chan struct{})
finished := make(chan error, 1)
go func() {
finished <- runWithLibraryLease(context.Background(), time.Millisecond, func(context.Context) error { <-entered; return lost }, func(ctx context.Context) error { close(entered); <-ctx.Done(); close(cancelled); <-release; return nil })
}()
select {
case <-cancelled:
case <-time.After(time.Second):
t.Fatal("loss did not cancel actual writer")
}
select {
case <-finished:
t.Fatal("returned while actual write still running")
default:
}
close(release)
select {
case err := <-finished:
if !errors.Is(err, lost) {
t.Fatalf("loss hidden: %v", err)
}
case <-time.After(time.Second):
t.Fatal("writer not joined")
}
}
func TestContractLeaseRenewsDuringLongWrite(t *testing.T) {
renewed := make(chan struct{}, 1)
err := runWithLibraryLease(context.Background(), time.Millisecond, func(context.Context) error {
select {
case renewed <- struct{}{}:
default:
}
return nil
}, func(ctx context.Context) error {
select {
case <-renewed:
return nil
case <-time.After(time.Second):
return errors.New("no renewal")
case <-ctx.Done():
return ctx.Err()
}
})
if err != nil {
t.Fatal(err)
}
}
+40
View File
@@ -0,0 +1,40 @@
package main
import (
"context"
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/objectgateway"
postgresstore "knowledge-governance/internal/platform/postgres"
"time"
)
// All target-changing handlers share one execution lock, not one lock per job or
// scope. Lease loss cancels work but cannot release ownership before cleanup joins.
func runOwnedLibraryAttempt(ctx context.Context, base *postgresstore.Store, config appconfig.Config, queue jobs.Job, jobID string, run func(context.Context, *libraryAttemptWriter) error) error {
return base.WithLibraryExecution(ctx, config.LibraryTargetInstance, func(ctx context.Context, ping func(context.Context) error) (err error) {
writer, err := beginLibraryWriter(ctx, base, jobID, libraryQueueOwner(config.WorkerID, queue, jobID))
if err != nil {
return err
}
defer func() {
finishCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
if err != nil {
writer.finish(finishCtx, governance.LibraryAttemptFailed, err.Error())
} else {
writer.finish(finishCtx, governance.LibraryAttemptCompleted, "")
}
}()
return runWithLibraryLease(ctx, libraryAttemptLease/10, func(probe context.Context) error {
if err := ping(probe); err != nil {
return err
}
return base.RenewLibraryAttempt(probe, writer.attempt, libraryAttemptLease, time.Now().UTC())
}, func(runCtx context.Context) error {
runCtx = objectgateway.WithClaim(runCtx, objectgateway.Claim{JobID: writer.attempt.JobID, OperationID: writer.attempt.OperationID, AttemptEpoch: int64(writer.attempt.Epoch), Owner: writer.attempt.Owner})
return run(runCtx, writer)
})
})
}
+103 -89
View File
@@ -10,10 +10,12 @@ import (
"log"
"time"
"bytes"
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/libraryrelease"
"knowledge-governance/internal/objectgateway"
postgresstore "knowledge-governance/internal/platform/postgres"
v071 "knowledge-governance/internal/releaseadapter/v071"
)
@@ -21,8 +23,13 @@ import (
// libraryRecoveryPayload 是"按预备份恢复并校验"的队列载荷。
// 它只说明动哪个窗口;恢复目标快照由 journal 里持久化的那份决定,调用方改不了。
type libraryRecoveryPayload struct {
Scope string `json:"scope"`
WindowJobID string `json:"window_job_id"`
Scope string `json:"scope"`
WindowJobID string `json:"window_job_id"`
SourceSnapshot string `json:"source_snapshot_id,omitempty"`
TargetID string `json:"target_id,omitempty"`
OriginalOperation string `json:"original_operation_id,omitempty"`
BackupSnapshot string `json:"backup_snapshot_id,omitempty"`
PlanDigest string `json:"plan_digest,omitempty"`
}
// runLibraryRecovery 是"内容风险未验证"窗口的唯一收尾入口:
@@ -30,10 +37,15 @@ type libraryRecoveryPayload struct {
// 只有校验通过才恢复服务、开入口、释放占用。失败则保持维护。
func runLibraryRecovery(ctx context.Context, store *postgresstore.Store, config appconfig.Config, job jobs.Job) error {
var payload libraryRecoveryPayload
if err := json.Unmarshal(job.Payload, &payload); err != nil ||
decoder := json.NewDecoder(bytes.NewReader(job.Payload))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&payload); err != nil ||
(payload.Scope != "internal" && payload.Scope != "external") || payload.WindowJobID == "" {
return errors.New("invalid library recovery payload")
}
if err := store.ValidateLibraryRecoveryQueue(ctx, job, payload.Scope, payload.WindowJobID); err != nil {
return err
}
manager, err := openLibraryMaintenance(config)
if err != nil {
return fmt.Errorf("目标维护未接线,不能做恢复:%w", err)
@@ -62,93 +74,95 @@ func runLibraryRecovery(ctx context.Context, store *postgresstore.Store, config
if admitErr != nil {
return admitErr
}
// 恢复是一次**新执行代次**:它接管这个窗口,旧代次从此不能写业务状态/释放锁(F13)。
writer, attemptErr := beginLibraryWriter(ctx, store, payload.WindowJobID, libraryQueueOwner(config.WorkerID, job, payload.WindowJobID))
if attemptErr != nil {
return fmt.Errorf("无法取得恢复窗口的执行权:%w", attemptErr)
}
guarded := writer
prebackup := windowJob.SnapshotID
if prebackup == "" {
return errors.New("原作业没有持久化预备份,无法证明恢复到哪一份")
}
// 恢复是**新意图**(kind=recover):内容更旧、意图更新。把恢复事实挂在失败作业的旧
// operation 上会被 current 的次序(按意图创建时间)判成迟到事实而拒绝——F06 就治不好。
recoveryDigest, digestErr := governance.LibraryRequestDigest(payload.Scope, governance.LibraryJobRecover,
map[string]any{"window_job": payload.WindowJobID, "backup_snapshot": prebackup})
if digestErr != nil {
return fmt.Errorf("无法计算恢复意图摘要:%w", digestErr)
}
recoveryKey := fmt.Sprintf("%s#%d", payload.WindowJobID, writer.attempt.Epoch)
recoveryOp, _, opErr := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{
ID: governance.LibraryOperationID(payload.Scope, governance.LibraryJobRecover, recoveryKey),
Scope: payload.Scope, Kind: governance.LibraryJobRecover, TargetSnapshotID: prebackup,
RequestDigest: recoveryDigest, OperationKey: recoveryKey, Actor: job.LeaseOwner,
CreatedAt: time.Now().UTC(),
return runOwnedLibraryAttempt(ctx, store, config, job, payload.WindowJobID, func(ctx context.Context, writer *libraryAttemptWriter) error {
guarded := writer
prebackup := windowJob.SnapshotID
if prebackup == "" {
return errors.New("原作业没有持久化预备份,无法证明恢复到哪一份")
}
// 恢复必须带着"这次作业写了什么"的持久记录:没有它就只能按目标现状推断残渣,
// 而那会误删历史孤儿/其它知识库暂未绑定的资源(快照里没有这些行,删了回不来)。
ledger, ledgerErr := loadWriteSetForJob(ctx, store, config.LibraryArchiveRoot, payload.Scope,
payload.WindowJobID, prebackup)
if ledgerErr != nil {
note := "恢复缺少持久化的写集合记录,目标保持维护:" + ledgerErr.Error()
_ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, time.Now().UTC())
_ = guarded.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.WindowJobID, "needs_restore", note, time.Now().UTC())
return errors.New(note)
}
for _, pair := range [][2]string{{payload.SourceSnapshot, ledger.TargetSnapshotID}, {payload.TargetID, config.LibraryTargetIdentity()}, {payload.OriginalOperation, windowJob.OperationID}, {payload.BackupSnapshot, prebackup}, {payload.PlanDigest, ledger.Digest}} {
if pair[0] != "" && pair[0] != pair[1] {
return errors.New("recovery supplied identity differs from original immutable binding")
}
}
recoveryDigest, digestErr := governance.LibraryRecoveryDigest(payload.Scope, job.ID, payload.WindowJobID, windowJob.OperationID, config.LibraryTargetIdentity(), ledger.TargetSnapshotID, prebackup, ledger.Digest)
if digestErr != nil {
return digestErr
}
recoveryOp, _, opErr := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{
ID: governance.LibraryOperationID(payload.Scope, governance.LibraryJobRecover, job.ID),
Scope: payload.Scope, Kind: governance.LibraryJobRecover, TargetSnapshotID: prebackup,
RequestDigest: recoveryDigest, OperationKey: job.ID, Actor: job.LeaseOwner, CreatedAt: job.CreatedAt,
})
if opErr != nil {
return opErr
}
claim := objectgateway.ClaimFromContext(ctx)
if claim.JobID == "" {
return errors.New("recovery attempt context missing")
}
claim.RecoveryJobID, claim.RecoveryOperationID = job.ID, recoveryOp.ID
ctx = objectgateway.WithClaim(ctx, claim)
knownMapping := knownIndexMapping(ctx, store, payload.Scope)
target, _, wireErr := buildLibraryProductionStack(ctx, config, payload.Scope, prebackup, knownMapping)
if wireErr != nil {
return fmt.Errorf("恢复目标装配失败:%w", wireErr)
}
defer target.Close()
coordinator, control, openErr := manager.Open(config.LibraryTargetJournalRoot)
if openErr != nil {
return fmt.Errorf("维护协调器不可用:%w", openErr)
}
defer control.Close()
defer coordinator.Close()
restorer := recoveryRestorer{target: target, expected: prebackup, writeSet: ledger}
verifier := recoveryVerifier{target: target, expected: prebackup}
result, recoverErr := coordinator.RecoverWindow(ctx, payload.WindowJobID, restorer, verifier)
now := time.Now().UTC()
if recoverErr != nil {
note := "恢复/校验未通过,目标保持维护:" + recoverErr.Error()
_ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, now)
_ = guarded.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.WindowJobID, "needs_restore", note, now)
return recoverErr
}
if result.State != "recovered" {
note := "恢复流程结束但状态不是 recovered:" + result.State
_ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, now)
return errors.New(note)
}
// 恢复事实必须落成**新事件并推进 current**(F06)。旧实现只释放锁:物理内容已经
// 是预备份那份,页面/差异/后续作业却仍以为失败的新版本生效,下一步就会拿错基线决策。
// 事件是追加的,不改写原来那条失败作业与失败版本。
digest := result.Digest
if digest == "" {
return errors.New("恢复完成但没有校验摘要:拒绝登记恢复事实(无法证明恢复到了哪一份内容)")
}
if err := recordRecoveryEvent(ctx, writer, recoveryOp, payload.Scope, payload.WindowJobID, result.SnapshotID,
digest, "按预备份恢复并逐类校验通过"); err != nil {
return fmt.Errorf("恢复已完成但恢复事实登记失败:%w", err)
}
// 收尾顺序:先登记事实,再释放占用。反过来会出现"锁已放、current 还指向失败版本"
// 的窗口——那正是页面把恢复成功显示成待恢复的状态。
if err := releaseWindowLocks(ctx, guarded, identity.Instance, payload.Scope, payload.WindowJobID,
"按预备份恢复并逐类校验通过,目标已按原运行状态恢复", now); err != nil {
return fmt.Errorf("恢复已验证,但维护占用释放失败:%w", err)
}
log.Printf("library recovery succeeded window=%s scope=%s backup=%s digest=%s",
payload.WindowJobID, payload.Scope, prebackup, digest)
return nil
})
if opErr != nil {
return fmt.Errorf("无法登记恢复意图:%w", opErr)
}
// 恢复必须带着"这次作业写了什么"的持久记录:没有它就只能按目标现状推断残渣,
// 而那会误删历史孤儿/其它知识库暂未绑定的资源(快照里没有这些行,删了回不来)。
ledger, ledgerErr := loadWriteSetForJob(ctx, store, config.LibraryArchiveRoot, payload.Scope,
payload.WindowJobID, prebackup)
if ledgerErr != nil {
note := "恢复缺少持久化的写集合记录,目标保持维护:" + ledgerErr.Error()
_ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, time.Now().UTC())
_ = guarded.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.WindowJobID, "needs_restore", note, time.Now().UTC())
return errors.New(note)
}
knownMapping := knownIndexMapping(ctx, store, payload.Scope)
target, _, wireErr := buildLibraryProductionStack(ctx, config, payload.Scope, prebackup, knownMapping)
if wireErr != nil {
return fmt.Errorf("恢复目标装配失败:%w", wireErr)
}
defer target.Close()
coordinator, control, openErr := manager.Open(config.LibraryTargetJournalRoot)
if openErr != nil {
return fmt.Errorf("维护协调器不可用:%w", openErr)
}
defer control.Close()
defer coordinator.Close()
restorer := recoveryRestorer{target: target, expected: prebackup, writeSet: ledger}
verifier := recoveryVerifier{target: target, expected: prebackup}
result, recoverErr := coordinator.RecoverWindow(ctx, payload.WindowJobID, restorer, verifier)
now := time.Now().UTC()
if recoverErr != nil {
note := "恢复/校验未通过,目标保持维护:" + recoverErr.Error()
_ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, now)
_ = guarded.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.WindowJobID, "needs_restore", note, now)
return recoverErr
}
if result.State != "recovered" {
note := "恢复流程结束但状态不是 recovered:" + result.State
_ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, now)
return errors.New(note)
}
// 恢复事实必须落成**新事件并推进 current**(F06)。旧实现只释放锁:物理内容已经
// 是预备份那份,页面/差异/后续作业却仍以为失败的新版本生效,下一步就会拿错基线决策。
// 事件是追加的,不改写原来那条失败作业与失败版本。
digest := result.Digest
if digest == "" {
return errors.New("恢复完成但没有校验摘要:拒绝登记恢复事实(无法证明恢复到了哪一份内容)")
}
if err := recordRecoveryEvent(ctx, writer, recoveryOp, payload.Scope, payload.WindowJobID, result.SnapshotID,
digest, "按预备份恢复并逐类校验通过"); err != nil {
return fmt.Errorf("恢复已完成但恢复事实登记失败:%w", err)
}
// 收尾顺序:先登记事实,再释放占用。反过来会出现"锁已放、current 还指向失败版本"
// 的窗口——那正是页面把恢复成功显示成待恢复的状态。
if err := releaseWindowLocks(ctx, guarded, identity.Instance, payload.Scope, payload.WindowJobID,
"按预备份恢复并逐类校验通过,目标已按原运行状态恢复", now); err != nil {
return fmt.Errorf("恢复已验证,但维护占用释放失败:%w", err)
}
writer.finish(context.WithoutCancel(ctx), governance.LibraryAttemptCompleted, "recovered")
log.Printf("library recovery succeeded window=%s scope=%s backup=%s digest=%s",
payload.WindowJobID, payload.Scope, prebackup, digest)
return nil
}
// recoveryRestorer 只按"作业记录里那份预备份"恢复:协调器传进来的 id 与它不一致
+34
View File
@@ -0,0 +1,34 @@
package main
import (
"errors"
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/librarysnapshot"
)
func configuredCaptureSource(config appconfig.Config, scope string) governance.LibrarySourceIdentity {
kb := config.LibrarySourceInternalKB
if scope == "external" {
kb = config.LibrarySourceExternalKB
}
return governance.LibrarySourceIdentity{Project: config.SourceProject(), App: config.LibrarySourceApp, Scope: scope, TenantID: config.LibrarySourceTenantID, KnowledgeBaseID: kb}
}
func verifyCapturedSource(root, snapshotID string, source governance.LibrarySourceIdentity) error {
if _, err := source.ID(); err != nil {
return err
}
archive, err := librarysnapshot.Open(root, 256*1024*1024)
if err != nil {
return err
}
defer archive.Close()
manifest, err := archive.Load(snapshotID)
if err != nil {
return err
}
if manifest.Scope != source.Scope || manifest.TenantID != source.TenantID || manifest.KnowledgeBaseID != source.KnowledgeBaseID {
return errors.New("captured manifest differs from configured source")
}
return nil
}
+1 -1
View File
@@ -37,7 +37,7 @@ func beginLibraryWriter(ctx context.Context, store *postgresstore.Store, jobID,
// 迁移前的历史作业没有 operation:仍然取租约(防止双执行),但没有代次可守卫。
log.Printf("library job %s has no operation id (pre-identity row): guarded writes fall back to lease only", jobID)
}
attempt, err := store.BeginLibraryAttempt(ctx, jobID, owner, 10*time.Minute, time.Now().UTC())
attempt, err := store.BeginLibraryAttempt(ctx, jobID, owner, libraryAttemptLease, time.Now().UTC())
if err != nil {
return nil, err
}
+10 -2
View File
@@ -344,6 +344,11 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
"未停任何写入者;补齐来源身份配置后重试", "", "", time.Now().UTC())
return expectErr
}
source := configuredCaptureSource(config, payload.Scope)
sourceID, sourceErr := source.ID()
if sourceErr != nil {
return sourceErr
}
result, err := libraryagent.CaptureReleased(ctx, agentConfig, payload.Scope, payload.CaptureJob, released, expectation)
finishedAt := time.Now().UTC()
if err != nil {
@@ -362,18 +367,21 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
"快照已产生但来源身份不符,未登记为测试封存;核对执行器后重新封存", "", "", finishedAt)
return identityErr
}
if err := verifyCapturedSource(config.LibraryArchiveRoot, result.SnapshotID, source); err != nil {
return err
}
// 封存产物成版本记录:只登记"测试封存",绝不写成生产生效版本。
versionErr := store.RecordLibraryVersion(ctx, governance.LibraryVersion{
ID: governance.LibraryVersionID(governance.LibraryVersionTestSealed, payload.Scope, result.SnapshotID),
Scope: payload.Scope,
Kind: governance.LibraryVersionTestSealed, SnapshotID: result.SnapshotID, SourceJobID: libraryJobID,
Evidence: map[string]any{"capture_job": payload.CaptureJob, "replay": result.Replay,
Evidence: map[string]any{"source_id": sourceID, "source_identity": source, "capture_job": payload.CaptureJob, "replay": result.Replay,
"requested_by": payload.RequestedBy, "expectation_fingerprint": expectationFingerprint(expectation),
"agent_result": json.RawMessage(result.Payload)},
CreatedBy: payload.RequestedBy, CreatedAt: finishedAt,
})
if versionErr != nil {
log.Printf("library seal job %s cannot record version: %v", libraryJobID, versionErr)
return fmt.Errorf("library seal job %s cannot record version: %w", libraryJobID, versionErr)
}
_ = store.UpdateLibraryStage(ctx, libraryJobID, "export", "succeeded", nil, nil, nil, nil,
"已封存快照 "+result.SnapshotID, finishedAt)
+72
View File
@@ -0,0 +1,72 @@
# v0.7.1 整库发布的数据契约与覆盖边界
这是候选代码的契约,不是部署许可。真实隔离执行证据在交付目录 `data-contract-r10.md`、`test-summary-r10.json` 及其 raw 索引。PG/ES/MinIO 均为本机隔离真实服务;发布/恢复测试直接调用适配器;B22 另走实际 `librarystack.OpenProductionStack` 和 HTTP 网关。网关的独占审核是测试夹具,不代表生产已隔离;B22 控制读取角色是真实 SELECT-only PG 角色。
## 1. 源 schema、历史身份与准入
- 新 `ExportLibraryWithReleases` 在读取内容的同一 REPEATABLE READ / READ ONLY 事务中读取 columns、constraints、indexes、triggers、relations、sequences;非普通表、RLS/继承/分区、自定义触发器或未知入边 FK 拒绝。
- 新归档增加一个内容寻址的 `schema/migration-catalog` 部件。归档核 JSON 目录结构、计数、大小和 SHA256;来源清单摘要绑定该部件。PlanWriteSet 在分配序列或执行任何业务写前要求其摘要与当前目标目录一致。序列定义属于目录,last_value/is_called 不属于 DDL 指纹。
- 旧快照没有该部件:不追加字段、不重新 seal、不改历史 hash;继续走原目标 catalog 和逐行字段/身份检查。它不能被称为“原捕获时已有 schema 证明”。旧V1台账的 canonical 规则不变。
- 目录严格一致不是自动迁移方案。源/目标定义不同会拒绝,需要单独评审兼容性,不能在业务库上临时 DDL 绕过。
- 实际 stack 准入读取目标模型、维度、schema 和 graph 状态。同维不同模型、模型行缺失、空模型名、graph 开启、schema dirty 均拒绝;不重算 embedding、不关闭 graph。正例和负例都比较 PG、ES正文/CAS、对象精确版本与网关 journal,证明准入无业务副作用。
## 2. 逐表身份、闭包和保真规则
|表|身份及本轮已执行的边界|保真/未闭合范围|
|---|---|---|
|knowledges|稳定字符串 ID;租户与KB按计划映射;正文/file_path/metadata 中规范资源引用进入闭包|其余原始列保留;模型/存储定位只按已冻结目标策略改写。不声称已穷尽全部业务 metadata 中非资源ID的语义|
|chunks|稳定 ID;knowledge_id 必须存在且同租户同KB;源 scoped 孤儿不能被 JOIN 静默丢掉;seq_id 使用固定数值映射|chunk_index 排序、按tenant+seq_id查询实跑;规范pre_chunk_id/next_chunk_id/parent_chunk_id要求同knowledge;tag_id及relation_chunks/indirect_relation_chunks要求在范围内,父树拒绝环;不把任意metadata数字猜成seq引用|
|knowledge_tags|稳定 ID;租户/KB必须匹配;seq_id按源数值大小分配并固定|sort_order ASC、created_at DESC、seq_id DESC 的并列排序实跑;原数值在恢复时回原,不回拨共享序列|
|knowledge_tag_relations|精确(knowledge_id,tag_id)元组;任一父可证明范围;缺knowledge、缺tag、跨KB/租户在源、入站及目标规划处拒绝|不通过内连接删除异常关系、不把元组拼成单列。非空正常/既存元组由完整隔离套件执行|
|resources|稳定 ID/22字符handle;引用资源必须存在,原对象字节、精确版本保真;目标正文引用也进入before-image和验证范围|共享资源仍按原不可变before-image/来源证明判断复用,不放宽成“字节相同即认领”。无本次归属的历史孤儿保持不动|
|resource_bindings|稳定 ID;resource_id必须在来源闭包;owner仅knowledge/chunk,必须可解析且租户一致|未知owner_type、NULL owner_type、缺owner及跨租户拒绝。被本次引用资源上的所有绑定都核验,包括指向其它KB的共享绑定;合法共享允许、未知共享归属拒绝|
|wiki_folders|稳定 ID、tenant/KB保真;整行JSON的规范资源字符串参与识别|parent_id必须在本次目录闭包且无环;目录ID碰撞写前拒绝;未知外部持久路径仍不声明支持|
|wiki_pages|稳定 ID;正文和嵌套metadata资源在无binding时也捕获/备份/发布/恢复|页面内容原样保留;按真实字段source_refs(含knowledgeID|title旧形状)、chunk_refs、folder_id检查闭包;不按不存在的source_knowledge_ids字段推断支持|
|wiki_page_issues|稳定 ID、tenant/KB保真;整行资源字符串参与识别|原v071按slug引用/展示的问题记录原样保留;未知扩展字段不自动映射数值ID,不能当作任意插件引用支持|
|wiki_log_entries|BIGINT正整数,不经float64;按源数值大小映射(2在100之前),映射绑定原计划|id DESC和cursor id<实际SQL实跑;恢复原id。旧外部持久游标不能跨映射直接复用,原A04此项仍需决策/验收|
|resource_access_grants(非迁移表)|唯一已审核的resources外部FK入边;不搬运、不删除授权|新建资源清理/Restore前若出现授权,持父键锁拒绝删除;恢复入口另核未知绑定/计划外绑定和外库正文metadata引用,有引用时在ES/对象/PG写前held,锁内再次核全部正文/绑定;当前完整隔离测试读回grant、PG、ES、原对象版本均未变。其它未知入边/触发器拒绝|
既有目标历史软删除行按原 destructive predicate 进入 before-image,不用来源活跃行过滤规则裁剪恢复数据。来源导出只包含活跃内容;可归属于本库的异常边在过滤前检查。完全没有任何父或范围锚的历史记录不能猜成属于本库:不全局扫出后删除、不自动迁移;这不是“所有历史孤儿已修复”。
## 3. 资源引用的实际格式
只读参考源码:`WeKnora-v0.7.1-dev/internal/types/resource.go` 中 `ResourceHandleLength=22` 与 `ParseResourcePath`;本轮没有修改WeKnora源码。
支持并真实执行:
- knowledge或Wiki正文里的 `resource://` 加22个URL-safe字符,包含Markdown图片语法;
- 嵌套JSON对象/数组字符串值里的同一规范引用,例如metadata.image_info[].url;
- 无binding的上述四种组合:源捕获、目标before-image、发布、恢复;完整PG及精确对象版本含历史孤儿比对。
实现先解码JSON再递归扫描字符串,不将JSON数字转为float64,也不重写正文。所有迁移行的字符串参与资源发现。目标 SQL 选择覆盖所有带tenant/KB的迁移表整行JSON,并与严格解析/完整引用存在性检查配合,不再只认chunk.content。
明确拒绝本轮实测的未知表示:短handle、过长handle、URI query/path/fragment后缀、再次转义的resource协议串;不截取22字符前缀冒充合法引用。未知owner独立拒绝。
覆盖边界:这不是任意富文本、任意编码或所有插件格式解析器。不承诺识别不含规范协议标识的opaque/base64内容、插件自定义裸UUID引用或全部非资源语义ID。新增格式需给出真实生产/读消费者契约、负例与保真证据后再支持;当前总体验收保持INCOMPLETE。
## 4. 数值序列与消费者
- chunks.seq_id、knowledge_tags.seq_id、wiki_log_entries.id:正常分配、落后于已占值、耗尽、源显式NULL分别真实执行。后3类在业务阶段前拒绝;所有序列的last_value/is_called、PG全文、ES正文/CAS、S3版本/删除标记不变。
- 正常分配是明确副作用,会推进序列;必须先固化P0/预备份,不能称只读。新target接管同一WriteSet再Apply不再取号;恢复原行但不rewind序列,合法空洞不等于身份丢失。
- v071消费者位置:repository/tag.go(sort_order/created_at/seq_id排序)、repository/chunk.go(seq_id读取及chunk_index排序)、repository/wiki_log_entry.go(id DESC、cursor id<)。本轮执行其SQL语义,不声称启动了完整WeKnora UI或所有外部消费者。
## 5. 后续门与安全边界
- 真实v071历史catalog镜像对照及UUID/自然键矩阵在r11执行,隔离结论与外部当前目录采样分开。A04已识别嵌套引用有有限支持,旧外部cursor仍不自动转换,不因内部结构正例而升级整项。
- r8/r9进程恢复历史证据只在原发送协议、不可变计划/receipt及相应场景前提不变时复用。本轮对schema/引用准入有收紧,不能把历史执行日志称为当前源码正式进程全链重跑;完整当前隔离适配器回归单列。
- clean-finalization unknown保持held是安全行为,但未满足全部自动收敛要求。若要求自动完成,需要能绑定原写入、完整内容和代次的充分服务端证据;相同干净正文、人工猜测归属或放宽共享规则均不可替代。
- 最终提交/push、远端CI、父复核和本机部署为明确下一门;整体安全验收未齐不部署。生产独占/ACL网络凭据、网关OSS业务端到端与宿主重启/断电是另行授权的部署/破坏性验收,不能作为停止本机授权开发的借口。
## 6. 目录与唯一键的有限支持矩阵
`testdata/catalog-v071-r11.json` 来自既存只读取证 `source-schema-live-r3b.json`,不是当前线上目录新采样。隔离镜像按原列、约束、索引、关系和触发器定义重建并逐项比较;sequence定义和OWNED BY归属独立绑定,不将last_value伪装成只读DDL。未知外部入边、外部出边、迁移表内部数值FK扩展不能因为源/目标同样扩展就默认放行。
稳定主键:knowledges、chunks、knowledge_tags、resources、resource_bindings、wiki_folders、wiki_pages、wiki_page_issues按同租户异KB/异租户碰撞检查;knowledge_tag_relations使用父身份元组;三个本地数值身份按固定WriteSet映射而非稳定UUID处理。资源共享的合法同ID复用仍依赖原before-image和所有权证明。
自然键以实际catalog的unique/partial indexes为基准:资源handle、有效tenant/location_hash、资源绑定复合键、tag tenant/KB/name、目录KB/parent/name、wiki KB/slug,以及provider/physical_path的应用层排他。wiki_page_issues在该目录中只有主键,没有额外自然唯一键。partial predicate按有效/软删除判定,并验证不同parent的正常目录;不能无差别拒绝全部正常资料。具体逐键DDL、正负例对应表见交付 `data-contract-r11.md`。
Wiki日志pages_affected仅支持消费者已有的字符串slug数组和{slug,title}对象数组;已删除页面/knowledge的历史日志是展示事实,不以缺现存父强删/拒绝历史日志。数字数组、对象中新增log_id等未知结构拒绝。普通metadata数字原样保存,不推断为日志ID。
旧外部cursor是明确剩余风险:目标新游标可正确分页,但源数字cursor或发布前旧cursor不能直接带入目标新映射。原A04“改本地ID不破坏引用/语义”没有豁免条款,所以仍未整项通过;本模块不擅改上游WeKnora,也不把“刷新页面即可”当作已经实现的自动失效协议。
授权以执行时真实时钟为准;完成预备份及持久计划登记后均再验。目标实现 `GrantRevalidator` 时按治理库授权行回读:`ActiveLibraryAuthorization` 只返回未撤销、未过期且参数摘要一致的记录,撤销后连写集合都不计算(避免序列分配),预备份保留待重新授权。真实发布 wrapper 无条件接线;未接线不等于安全,只是本机历史证据的边界。
+43
View File
@@ -0,0 +1,43 @@
# 发布身份与不可变计划:开发检查点
本批是统一修复的未完成检查点,不是发布就绪版本。不得依据本地门禁通过开启发布写门或部署云执行器。
## 已实现边界
- 显式逐表身份解析:字符串稳定身份、关系二元组、Wiki bigint;未知非空表、缺身份、错误整数类型和重复身份拒绝。
- chunks.seq_id、knowledge_tags.seq_id、wiki_log_entries.id 使用目标 sequence 分配并落入不可变写集合。接管校验来源 manifest、映射覆盖及 Wiki 写身份;回滚保留原始编号,不回退共享 sequence。
- 原始目标 before-image 与源候选导出分离,保留范围谓词内的软删除行和关联。resource_access_grants 外部级联入边已保护;尚未证明全部 FK/trigger 级联闭包。
- worker 包装器转发 AdoptWriteSet。不可变证据先同步文件,再同步目录;并发写者不能替换已存在的不同字节。
- ES 写前按全索引 ID 查归属,冻结逐 ID before/after/CAS 并持久化不可变 effect。维护窗口内使用既有 content 字段的暂态操作归属标记,不新增业务 mapping;确认归属后按 CAS 写入干净正文。标记写入成功但响应丢失时,新进程可从计划、完整内容、标记和 CAS 自动确认并补偿。无归属标记、内容或代次不符、清除标记后的未知结果、删除/补偿的未知结果仍拒绝,不能据此宣布完成恢复。
- 同 ID 资源即使在 before-image 内也必须证明等价才能只读复用;差异拒绝。已有 catalog 驱动自然唯一键预检及物理键绑定;完整负例矩阵仍未齐。
- 内容 canonicalization 保留大整数及失效期;孤儿查询错误向上传播。
## 兼容与回退
不修改旧 manifest/blob,也不改变其 hash。本批未增加或修改业务 schema、治理迁移。
新执行计划使用 V2,历史 V1 canonical 字节保持不变,并拒绝在 V1 中添加新执行字段;旧 V1 仅可读取诊断,不能把缺失副作用证据的旧计划当作安全执行计划。V2 当前仍不是完整跨存储协议:带归属标记的 ES unknown 已有真实跨进程补偿证据,所有无充分证据的分支仍保持维护,原生 OSS 条件创建协议仍未闭合。复用证据的 V2 before-image 等价证明与写集合版本独立。
一旦新计划被用于真实副作用,不得直接降级旧执行器消费新计划;须先证明没有在飞操作并完成原备份恢复和验证。当前没有部署,也未启动任何云作业。
## 阻止发布的剩余项
1. D0 完整源/目标 schema 指纹、FK 入出边、trigger、应用引用和序列消费者闭合。
2. 对象精确计划/intent/归属回执及版本化 MinIO 清理已局部实现并运行;MinIO 忽略 Delete IfMatch 的反例已记录,改用精确 versionId。业务桶不自动启用版本控制,无版本桶/未经验证的 OSS 适配写前拒绝。对象计划绑定与完整 adapter 隔离回归已复验;原生 OSS 版本协议已在明确授权测试前缀完成两个真实版本的精确写/读/清理,并列举确认版本与删除标记均无残留;严格条件创建与业务集成仍未闭合,不能放行。
3. ES 未记录的干净 finalization、删除与恢复网络结果不明时的进一步对账;不得将 fail-closed 状态算作完成。
4. 自然唯一键、resource_access_grants 与未知引用闭包。
5. 完整执行权续租、失权取消并等待写结束、跨执行域 fencing,以及队列提交补偿。
6. source candidate 精确查询与 API/UI 提交接线已测;旧 seal 显式证据关联已接管理员API/UI:核验原捕获响应/期望指纹与原manifest后只追加治理证据,不改快照hash;四种模式及真实页面闭环仍缺。
7. 两次连续真实 worker 中断,55 项完整验收、最终提交/远端 CI 与父独立复核。
已授权的云专用 KB 发布/恢复及测试 App 短停仍属于父独立审查后的后续阶段,无需重复索要开发授权;宿主重启与生产不在本批范围。
## 原生 OSS 的具体差异
原生版本协议实现提供 versioning 只读确认、带归属 metadata 的显式 append、精确 versionId 读取、完整回执比对后精确删除及再次读取验证。它不是 conditionalObjectStore 的替代,未接成生产 CreateObject。官方 PutObject 文档说明:桶启用/暂停版本控制时,x-oss-forbid-overwrite 无效。因此不能把版本 append 包装成原子仅新建,也不能用 S3 If-None-Match 的本机 MinIO 测试代替 OSS 证明。
真实测试只在 KG_OSS_VERSION_TEST_ALLOW=1、明确获准的 KG_OSS_VERSION_TEST_PREFIX、私有持久证据目录及测试凭据齐全时运行。默认不发云写;允许的测试桶固定为 dobot-weknora-test,端点固定深圳 OSS,只操作随机子键及精确版本,不改桶配置。未知 append 留下 intent,不盲扫桶猜测孤儿。限定前缀 kg-library-test-r4/ 已获明确授权并完成真实协议测试;生产条件创建的安全协议仍是实现缺口,不以版本 append 冒充严格仅新建,也不请求降低既有保护。
### 证据目录持久性边界
不可变 sidecar 的目录创建逐级检查真实目录,拒绝祖先软链接,逐级 fsync 父目录并传播错误;文件与最终目录仍同步。已验证祖先软链接写前拒绝、逐级同步调用覆盖和同步错误传播。这不是实际断电/文件系统崩溃测试,也不等于完整 F12:归档初始化现同步根目录及其父目录,任一fsync失败即拒绝返回可用归档,已做故障注入;PG锚点失败和跨节点介质策略仍需单独验收。
+93
View File
@@ -0,0 +1,93 @@
# 对象写入网关(开发候选,尚不可部署业务)
## 协议与持久化
`cmd/object-gateway` 提供 `kg-object-gateway-v1`,只监听 loopback;外部接入需要另行审核的 TLS 终结与网络隔离。治理 PG 保存不可变计划、grant、intent、逐版本 receipt 和 attempt→grant delivery。部署迁移身份显式应用 `internal/objectgateway/schema.sql`;启动不自动迁移。运行身份只授必要 SELECT/INSERT 和 scope 行 UPDATE,不授 DDL/TRUNCATE/证据修改或业务库写权限。
scope 是 provider、原 endpoint、bucket 的 NUL 分隔 SHA256。同一物理桶只能有一个受审核 scope 和一套共享 journal,不能用 endpoint 别名或另一日志库建立平行写域。
数据认证端点:`POST /v1/acquire`、`/v1/resolve`、`/v1/execute`、`/v1/reconcile`、`/v1/observe`,以及 `GET /v1/capabilities`。所有请求核验协议和 scope。`capabilities.automatic_grants` 必须为真,正式 stack 才接受自动授权能力;未接控制源、只读角色权限异常、协议不符或不可达均拒绝,无直写回退。
PG 行锁负责原子准入,不是远端存储 fence。intent 必须持久提交后才发送一次请求;连接死亡、租约过期不清除未知 intent。任何未终态 intent 均阻止 scope 换 epoch。重复 operation 只读回执或精确对账,不重发 PUT;暂时查不到版本仍 held。删除必须绑定已确认 create 的精确 VersionID,不删 latest、不生成删除标记。
不可变证据表拒绝 UPDATE/DELETE/TRUNCATE。Ready 核 fsync、synchronous_commit、full_page_writes、主库可写及必要表/触发器;管理员与迁移身份仍是可信边界,触发器不能抵御 DBA 的 DDL。
## 正式控制交付路径
生产代码路径已接入,并已在专属本机隔离栈运行正式 worker 的两次 SIGKILL 接管;这不是生产部署验收:
`cmd/worker.runOwnedLibraryAttempt → attempt context → librarystack → GatewayObjectStore(Automatic) → ProductionLibraryTarget.Apply → EnsureObjectGrant → /v1/acquire → GatewayGovernanceAuthority → 原持久 WriteSet → journal delivery → 数据 execute`。
冻结/采用计划时只保存自校验后的 WriteSet,不提前索取 grant;observer 先把摘要锚定到原预备份事件,首笔业务 PG Apply 前才请求授权。worker 只提交 job/operation/attempt epoch/owner/plan digest,不提交可替换的 key/body allowlist,也不能选择网关 epoch。
可信控制域使用独立 SELECT-only 治理连接,核对目标身份、job/operation、当前 attempt、owner、有效租约、running 状态和原预备份事件中的摘要、job、backup、目标快照;再从归档加载并验 hash、范围、provider/bucket。客户端自述不能替代这些持久事实。控制读角色不得是 superuser、CREATEDB、CREATEROLE,不能写/截断/建触发器到这些治理表。每次加载和能力查询重验角色。
网关在 scope 锁内再次核对授权事实,原子写入 grant、当前 epoch、不可变 delivery。同一 attempt 重试返回原 grant;owner/operation/plan 替换拒绝;同一 job 的后续 attempt 必须沿用原 operation 和 plan。旧发送未终态时,新 attempt 可先只读对账,但无充分证据仍 held,不能交接。
控制服务配置了治理 authority 后,旧 `/v1/plans`、`/v1/advance` 手动控制端点关闭,控制 token 也不能绕过原计划绑定。旧 `cmd/object-gateway-control` 仅保留离线/协议兼容路径,不是正式 worker 的交付方案。
## 独立恢复请求
`library.recover` 的队列ID由原窗口job确定;它具有独立恢复operation与request digest,绑定scope、queue、原window/operation、target、source、backup和原WriteSet。原计划的job、operation和摘要不改写。Claim中的`recovery_job_id`与`recovery_operation_id`仅为独立授权上下文,原`job_id`/`operation_id`仍是发送域。网关重新读取持久队列payload、running状态、当前owner/attempt/有效租约与恢复operation,不信任worker自行声明。可选显式来源/目标/backup/plan字段只能收紧原绑定,不能覆盖它。
SELECT-only治理角色需要读取`library_jobs`、`library_operations`、`library_attempts`、`library_versions`、`jobs`,均不能INSERT/UPDATE/DELETE/TRUNCATE/TRIGGER。已有原窗口恢复请求时不自动重启原发布;过期running恢复队列只在相同target、未释放维护窗口、原业务租约也过期时重新投递,业务attempt/epoch仍重新申请。
## 索引unknown恢复边界
原冻结before-image非空时,恢复先持久化`restore-mark-intent`,再以原CAS(或确认缺失的create)写入包含原计划/index/id归属标记的完整before-image。丢响应后仅匹配完整标记正文及有效CAS才能登记`restore-claimed`并CAS去标记;已知回执的代次不一致拒绝。恢复完成的`restored`回执仍须匹配正文和CAS,不能接受同正文的新代次。
去标记前持久化`restore-finalize-intent`。发布clean-finalization或恢复clean-finalization已提交但响应丢失时,当前干净正文并非充分归属证据;继续held,不盲删、不重发、不把相同外观当回执。旧unknown缺少写前标记intent亦不自动升级认领。本候选没有服务端可验证的clean提交关联凭证,因此这部分自动收敛仍是明确缺口,不是可部署完整恢复保证。
## 跨 epoch 的不可变发送身份
`Request.Grant` 继续代表首次发送的不可变身份,后端 claim、intent 和 receipt 都不改。新 `ExecuteRequest.authorization` 仅代表本次准入权限。`/v1/resolve` 根据相同 operation/key/action/hash/length/owner/plan 取回旧请求;只允许 epoch 差异,不能换内容。
新 attempt 获得新 grant 后,已发送 key 沿用旧 request/claim,未发送 key 使用新授权 epoch 建立首次 intent。当前授权必须匹配 journal 的当前 epoch;旧 epoch 的新写拒绝。新 epoch 补偿删除仍使用原 create 回执和精确版本,删除本身有独立不可变发送身份。
## 配置与凭据归属
网关进程环境:
- `OBJECT_GATEWAY_LISTEN`:仅 `127.0.0.1:<port>` 或 `[::1]:<port>`。
- `OBJECT_GATEWAY_DATABASE_URL`:独立 journal 连接,迁移与运行角色分离。
- `OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL`:仅可信网关持有的 SELECT-only 治理读连接;独立于 journal 运行身份和普通 worker 身份。
- `OBJECT_GATEWAY_ARCHIVE_ROOT`:原持久计划所在归档绝对路径,部署只读挂载。
- `OBJECT_GATEWAY_TARGET_ID`:与正式 worker `LibraryTargetIdentity()` 完全相同的逻辑目标身份;不能用另一个环境的值。
- `OBJECT_GATEWAY_PROVIDER`、`OBJECT_GATEWAY_ENDPOINT`、`OBJECT_GATEWAY_BUCKET`、`OBJECT_GATEWAY_REGION`:精确存储身份。
- `OBJECT_GATEWAY_ACCESS_KEY`、`OBJECT_GATEWAY_SECRET_KEY`:仅网关持有的对象写凭据。
- `OBJECT_GATEWAY_DATA_TOKEN`、`OBJECT_GATEWAY_CONTROL_TOKEN`:不同且至少 32 字节;普通 worker 仅持有 data token。
- `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`:独立审核者的 Ed25519 签名隔离证据,绑定协议、scope、gateway ID、时间窗及 writer/policy/拒写/排空摘要。审核私钥不能交给 worker 或网关。
秘密只经服务环境/私有文件注入,不进 argv、URL 或日志。所有调用端错误都使用固定原因码。
正式 worker 使用 `LIBRARY_OBJECT_GATEWAY_URL` 和 `LIBRARY_OBJECT_GATEWAY_TOKEN`;不再依赖预先生成的 grant 文件。`LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY` 保留旧离线兼容用途,不是自动模式的授权来源。发布 stack 对所有对象 provider 强制网关;S3 构造仍用于只读捕获/预备份,部署必须使用独立只读凭据。
## 已关闭的本仓旁路
- `ObjectImporter.Stage/Promote` 无条件拒绝,不留配置开关,不执行 PUT/COPY。
- legacy `release-worker` runtime/route 在读凭据及连接目标前拒绝。
- `release-diag`、`release-channel-e2e` 旧写型入口启动即非零退出,避免 probe PUT 或文档级旁路。
- `librarystack` 不再为缺网关的 MinIO/S3 返回直写 writer。
- `libraryctl` capture 的 S3 构造与读取保留;未把读取当作写入口禁用。
这不等于已经撤销运行环境旧进程的凭据;源码变更尚未部署。`librarydrill` 等无 owned-attempt 的旧写型工具不能靠静态 grant 绕过自动模式,需补正式执行身份后才可用于写入。低层 S3 adapter 仍用于网关后端、读取及显式隔离夹具;部署权限才负责防止外部旧进程直接调用存储。
## 实测与未完成边界
已实跑:真实治理 PG(独立 SELECT-only 登录角色)、原 archive、数据 HTTP、业务 PG 与 MinIO 的自动授权/跨 epoch 链;未锚定计划在第一笔 PG 前拒绝,接管保持原发送身份且不增加 PUT。另有真实网关二进制的两次中断验证。隔离审计 authority/故障注入仍是测试设施,不是生产权限证明。
正式 worker 隔离进程证据:真实 Docker 入口闸门/队列、只读 worker 对象身份、独立治理读取角色、网关与业务 PG/ES/MinIO;首次 PG 后和对象提交后两次 SIGKILL,同一原 job/operation/plan 的三代 attempt 完成发布,原对象发送 epoch 与回执不变。隔离构建标签 `kg_isolated_drill` 仅把真实租约缩短至4秒,并拒绝非 loopback 一次性 r8 库;正常构建仍为10分钟。维护上游是无业务凭据的独立 HTTP 夹具,不是运行中的 WeKnora;签名证据绑定本次真实拒写/排空材料,不代表生产独占审核。
已补独立 `library.recover` 正式worker链、恢复中再次SIGKILL、完整before-image/CAS/精确版本读回,以及来源/目标/原job/计划/operation/任意队列身份拒绝。ES故障代理只转发真实ES并丢弃已提交响应,未伪造服务响应。
尚未完成:clean-finalization unknown的充分归属与自动收敛;独立运行环境只读对象凭据、ACL/网络和全部writer排空;网关真实OSS端到端;原D0/F11/F12与55项其余缺口。测试/隔离验收与真实部署独占分列,不把生产变更授权当成本机开发授权的前置。
维护隔离、独占审核与 grant 是独立前置。配置 true、健康 200、测试自签 authority 都不能代替已部署拒写/排空证据。目前未签发真实环境独占证明,未改生产权限或上游 WeKnora 源码/Schema。
## 部署与回退(未执行)
未来测试主机 `120.76.217.51`、生产 `120.76.218.137` 各自独立批准。每批先冻结主机、桶、全部角色/STS/预签名写入口、端口/网络规则、影响、维护窗口与回滚;当前没有执行这些外部变更。
先关新写准入→排空并对账旧请求→撤旧直写权限/切只读身份并实测拒写→独立审核→批准的新限定对象验收→父复核,才可切业务客户端。r5 的已完成 OSS 测试授权不能重复使用。
回退先关准入并保留 journal;所有已发送请求有终态才可撤网关,unknown 继续 held。不得因网关故障自动恢复旧直写凭据。权限/网络回退须另批。当前整模块 INCOMPLETE,禁止部署部分候选。
+60 -54
View File
@@ -81,12 +81,15 @@ type Config struct {
LibraryProductionExternalKB string
// LibraryProductionS3Provider 必须与生产库 resources.provider 的取值一致:
// 对象路径按 provider 路由,写错会在上传时被拒绝(而不是写错桶)。
LibraryProductionS3Provider string
LibraryProductionS3Endpoint string
LibraryProductionS3Region string
LibraryProductionS3Bucket string
LibraryProductionS3AccessKey string
LibraryProductionS3SecretKey string
LibraryProductionS3Provider string
LibraryProductionS3Endpoint string
LibraryProductionS3Region string
LibraryProductionS3Bucket string
LibraryProductionS3AccessKey string
LibraryProductionS3SecretKey string
LibraryObjectGatewayURL string
LibraryObjectGatewayToken string
LibraryObjectGatewayGrantDirectory string
// LibraryEmbeddingModel 是整库发布使用的向量模型声明(快照契约缺失时的回落值)。
LibraryEmbeddingModel string
// LibraryWorkerRole 决定这个进程消费哪一段队列(见 LibraryWorkerRole 说明)。
@@ -203,54 +206,57 @@ func Load(getenv func(string) string) (Config, error) {
TestAcceptancePolicyVersion: valueOrDefault(getenv("TEST_ACCEPTANCE_POLICY_VERSION"), "structural-v1"),
TestAutoReviewPolicy: valueOrDefault(getenv("TEST_AUTO_REVIEW_POLICY"), string(governance.AutoReviewInternal)),
// 整库逻辑备份的目标主机:三项同时给出才接线(脚本目录/备份根有默认值)。
BackupHostSSHConfig: strings.TrimSpace(getenv("BACKUP_HOST_SSH_CONFIG")),
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
LibraryArchiveRoot: strings.TrimSpace(getenv("LIBRARY_ARCHIVE_ROOT")),
LibraryAgentSocket: strings.TrimSpace(getenv("LIBRARY_AGENT_SOCKET")),
LibraryProductionDatabaseURL: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_DATABASE_URL")),
LibraryProductionElasticURL: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_ELASTIC_URL")),
LibraryProductionIndex: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_INDEX")), "weknora_full_chunks"),
LibraryProductionTenantID: uint64(tenantID),
LibraryProductionInternalKB: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_KB_INTERNAL")),
LibraryProductionExternalKB: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_KB_EXTERNAL")),
LibraryProductionS3Provider: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_PROVIDER")), "s3"),
LibraryProductionS3Endpoint: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_ENDPOINT")),
LibraryProductionS3Region: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_REGION")), "us-east-1"),
LibraryProductionS3Bucket: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_BUCKET")),
LibraryProductionS3AccessKey: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_ACCESS_KEY")),
LibraryProductionS3SecretKey: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_SECRET_KEY")),
LibraryTargetInstance: strings.TrimSpace(getenv("LIBRARY_TARGET_INSTANCE")),
LibrarySourceInstance: strings.TrimSpace(getenv("LIBRARY_SOURCE_INSTANCE")),
LibrarySourceProject: strings.TrimSpace(getenv("LIBRARY_SOURCE_PROJECT")),
LibrarySourceApp: strings.TrimSpace(getenv("LIBRARY_SOURCE_APP")),
LibrarySourceTenantID: uint64(sourceTenantID),
LibrarySourceInternalKB: strings.TrimSpace(getenv("LIBRARY_SOURCE_KB_INTERNAL")),
LibrarySourceExternalKB: strings.TrimSpace(getenv("LIBRARY_SOURCE_KB_EXTERNAL")),
LibraryTargetProject: strings.TrimSpace(getenv("LIBRARY_TARGET_PROJECT")),
LibraryTargetWriters: splitList(getenv("LIBRARY_TARGET_WRITERS")),
LibraryTargetNonWriters: splitDeclarations(getenv("LIBRARY_TARGET_NON_WRITERS")),
LibraryTargetDockerSocket: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_TARGET_DOCKER_SOCKET")), "/var/run/docker.sock"),
LibraryTargetIngressURL: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_URL")),
LibraryTargetIngressService: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_SERVICE")),
LibraryTargetIngressDrainFile: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_DRAIN_FILE")),
LibraryTargetRedisAddr: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_ADDR")),
LibraryTargetRedisPassword: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_PASSWORD")),
LibraryTargetRedisDB: valueOrDefaultInt(getenv("LIBRARY_TARGET_REDIS_DB"), 0),
LibraryTargetJournalRoot: strings.TrimSpace(getenv("LIBRARY_TARGET_JOURNAL_ROOT")),
LibraryEmbeddingModel: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_MODEL")), "text-embedding-v4"),
LibraryEmbeddingDimension: embeddingDimension,
LibraryCapacityBudgetBytes: capacityBudget,
LibraryRetentionVersions: retentionVersions,
LibraryRetentionDays: retentionDays,
LibraryExecutorStatusMaxAge: 2 * time.Minute,
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
VersionHistoryHTTPTimeout: 15 * time.Second,
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
BackupHostSSHConfig: strings.TrimSpace(getenv("BACKUP_HOST_SSH_CONFIG")),
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
LibraryArchiveRoot: strings.TrimSpace(getenv("LIBRARY_ARCHIVE_ROOT")),
LibraryAgentSocket: strings.TrimSpace(getenv("LIBRARY_AGENT_SOCKET")),
LibraryProductionDatabaseURL: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_DATABASE_URL")),
LibraryProductionElasticURL: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_ELASTIC_URL")),
LibraryProductionIndex: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_INDEX")), "weknora_full_chunks"),
LibraryProductionTenantID: uint64(tenantID),
LibraryProductionInternalKB: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_KB_INTERNAL")),
LibraryProductionExternalKB: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_KB_EXTERNAL")),
LibraryProductionS3Provider: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_PROVIDER")), "s3"),
LibraryProductionS3Endpoint: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_ENDPOINT")),
LibraryProductionS3Region: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_REGION")), "us-east-1"),
LibraryProductionS3Bucket: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_BUCKET")),
LibraryProductionS3AccessKey: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_ACCESS_KEY")),
LibraryProductionS3SecretKey: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_SECRET_KEY")),
LibraryObjectGatewayURL: strings.TrimSpace(getenv("LIBRARY_OBJECT_GATEWAY_URL")),
LibraryObjectGatewayToken: strings.TrimSpace(getenv("LIBRARY_OBJECT_GATEWAY_TOKEN")),
LibraryObjectGatewayGrantDirectory: strings.TrimSpace(getenv("LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY")),
LibraryTargetInstance: strings.TrimSpace(getenv("LIBRARY_TARGET_INSTANCE")),
LibrarySourceInstance: strings.TrimSpace(getenv("LIBRARY_SOURCE_INSTANCE")),
LibrarySourceProject: strings.TrimSpace(getenv("LIBRARY_SOURCE_PROJECT")),
LibrarySourceApp: strings.TrimSpace(getenv("LIBRARY_SOURCE_APP")),
LibrarySourceTenantID: uint64(sourceTenantID),
LibrarySourceInternalKB: strings.TrimSpace(getenv("LIBRARY_SOURCE_KB_INTERNAL")),
LibrarySourceExternalKB: strings.TrimSpace(getenv("LIBRARY_SOURCE_KB_EXTERNAL")),
LibraryTargetProject: strings.TrimSpace(getenv("LIBRARY_TARGET_PROJECT")),
LibraryTargetWriters: splitList(getenv("LIBRARY_TARGET_WRITERS")),
LibraryTargetNonWriters: splitDeclarations(getenv("LIBRARY_TARGET_NON_WRITERS")),
LibraryTargetDockerSocket: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_TARGET_DOCKER_SOCKET")), "/var/run/docker.sock"),
LibraryTargetIngressURL: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_URL")),
LibraryTargetIngressService: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_SERVICE")),
LibraryTargetIngressDrainFile: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_DRAIN_FILE")),
LibraryTargetRedisAddr: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_ADDR")),
LibraryTargetRedisPassword: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_PASSWORD")),
LibraryTargetRedisDB: valueOrDefaultInt(getenv("LIBRARY_TARGET_REDIS_DB"), 0),
LibraryTargetJournalRoot: strings.TrimSpace(getenv("LIBRARY_TARGET_JOURNAL_ROOT")),
LibraryEmbeddingModel: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_MODEL")), "text-embedding-v4"),
LibraryEmbeddingDimension: embeddingDimension,
LibraryCapacityBudgetBytes: capacityBudget,
LibraryRetentionVersions: retentionVersions,
LibraryRetentionDays: retentionDays,
LibraryExecutorStatusMaxAge: 2 * time.Minute,
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
VersionHistoryHTTPTimeout: 15 * time.Second,
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
}
if config.DatabaseURL == "" {
return Config{}, errors.New("DATABASE_URL is required")
+16
View File
@@ -0,0 +1,16 @@
package governance
import "encoding/json"
func LibraryQueueRequest(handoff bool, jobID, scope, snapshotID, releaseType string) (string, string, []byte, error) {
payload := map[string]string{"library_job_id": jobID, "scope": scope, "target_snapshot_id": snapshotID}
queueID := QueueJobIDFor(jobID)
queueType := releaseType
if handoff {
payload["next_type"] = releaseType
queueID = LibraryHandoffQueueJobID(jobID)
queueType = "library.snapshot.handoff"
}
raw, err := json.Marshal(payload)
return queueID, queueType, raw, err
}
@@ -0,0 +1,20 @@
package governance
import (
"crypto/sha256"
"encoding/hex"
)
// The recovery request has its own queue identity and stable operation. It
// borrows the original window's fence, never its immutable sending identity.
func LibraryRecoveryQueueID(windowJob string) string {
sum := sha256.Sum256([]byte(windowJob))
return "lrec-" + hex.EncodeToString(sum[:14])
}
func LibraryRecoveryDigest(scope, queue, window, operation, target, source, backup, plan string) (string, error) {
return LibraryRequestDigest(scope, LibraryJobRecover, map[string]any{
"recovery_queue": queue, "window_job": window, "original_operation": operation,
"target_id": target, "source_snapshot": source, "backup_snapshot": backup, "writeset_digest": plan,
})
}
@@ -0,0 +1,30 @@
package governance
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
)
// SourceIdentity binds an immutable capture to its configured origin, not to a
// target or a page of mixed version history. It does not modify snapshot hashes.
type LibrarySourceIdentity struct {
Project string `json:"project"`
App string `json:"app"`
Scope string `json:"scope"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
}
func (s LibrarySourceIdentity) ID() (string, error) {
if s.Project == "" || s.App == "" || (s.Scope != "internal" && s.Scope != "external") || s.TenantID == 0 || s.KnowledgeBaseID == "" {
return "", errors.New("source project/app/scope/tenant/knowledge base binding incomplete")
}
raw, err := json.Marshal(s)
if err != nil {
return "", err
}
sum := sha256.Sum256(raw)
return hex.EncodeToString(sum[:]), nil
}
+1 -1
View File
@@ -99,7 +99,7 @@ func isAuthEndpoint(method, path string) bool {
// classify maps a request to the minimum role required.
func classifyRole(method, path string) string {
if path == "/api/v1/source-connections/audit" {
if path == "/api/v1/source-connections/audit" || path == "/api/v1/library/source-associations" {
return roleAdmin
}
// The member roster exposes account identities and roles: admin-only for
+2 -23
View File
@@ -9,7 +9,6 @@ import (
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
)
@@ -107,12 +106,12 @@ func libraryBaselineEnqueue(w http.ResponseWriter, r *http.Request, config Confi
return
}
now := time.Now().UTC()
job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
job, reused, err := store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{
ID: fmt.Sprintf("libbase-%s-%d", request.Scope, now.UnixNano()), Scope: request.Scope,
Kind: governance.LibraryJobBaseline,
IdempotencyKey: "library.baseline:" + request.Scope + ":" + now.Format("20060102T150405.000000000"),
RequestDigest: digest, Actor: identity.Username,
}, governance.BaselineStages(), now)
}, governance.BaselineStages(), false, now)
if errors.Is(err, governance.ErrLibraryJobActive) {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_write_active",
"error": "该目标已有在飞的写作业(同步/恢复/基线互斥),等它结束再发起"})
@@ -131,26 +130,6 @@ func libraryBaselineEnqueue(w http.ResponseWriter, r *http.Request, config Confi
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true})
return
}
payload, err := json.Marshal(map[string]string{"library_job_id": job.ID, "scope": request.Scope})
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build baseline payload"})
return
}
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
ID: governance.QueueJobIDFor(job.ID), Type: libraryBaselineJobType, Payload: payload,
AvailableAt: now, MaxAttempts: 1, IdempotencyKey: "library.baseline.queue:" + job.ID,
}, now)
if err != nil || queueJob == nil {
// 作业先落库、队列投递失败就把作业取消:不留下"看起来在跑"的空作业,
// 否则它会一直占着该 scope 的写互斥。
_ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始建立基线", now)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue baseline job"})
return
}
if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach baseline job"})
return
}
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false,
"target_counts": counts})
}
@@ -45,6 +45,21 @@ func (s *baselineMutexStore) CreateLibraryJob(ctx context.Context, job governanc
return s.fakeLibraryStore.CreateLibraryJob(ctx, job, stages, now)
}
func (s *baselineMutexStore) CreateLibraryDispatch(ctx context.Context, job governance.LibraryJob, stages []string, handoff bool, now time.Time) (governance.LibraryJob, bool, error) {
if s.activeByScope == nil {
s.activeByScope = map[string]string{}
}
if s.activeByScope[job.Scope] != "" {
return governance.LibraryJob{}, false, governance.ErrLibraryJobActive
}
created, reused, err := s.fakeLibraryStore.CreateLibraryDispatch(ctx, job, stages, handoff, now)
if err == nil {
s.activeByScope[job.Scope] = created.ID
s.enqueues++
}
return created, reused, err
}
func (s *baselineMutexStore) Enqueue(ctx context.Context, request jobs.EnqueueRequest, now time.Time) (*jobs.Job, error) {
s.enqueues++
return s.fakeLibraryStore.fakeJobStore.Enqueue(ctx, request, now)
@@ -0,0 +1,33 @@
package httpapi
import (
"context"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"time"
)
// In-memory API fixture mirrors dispatch shape; atomicity is tested against PG.
func (s *fakeLibraryStore) CreateLibraryDispatch(ctx context.Context, job governance.LibraryJob, stages []string, handoff bool, now time.Time) (governance.LibraryJob, bool, error) {
created, reused, err := s.CreateLibraryJob(ctx, job, stages, now)
if err != nil {
return created, reused, err
}
if reused && (created.State != governance.LibraryJobPending || created.QueueJobID != "") {
return created, reused, nil
}
id, kind, payload, err := governance.LibraryQueueRequest(handoff, created.ID, created.Scope, created.TargetSnapshotID, "library."+string(created.Kind))
if err != nil {
return created, reused, err
}
queued, err := s.Enqueue(ctx, jobs.EnqueueRequest{ID: id, Type: kind, Payload: payload, AvailableAt: now, MaxAttempts: 1, IdempotencyKey: kind + ".queue:" + created.ID}, now)
if err != nil {
s.lastJob = governance.LibraryJob{}
return governance.LibraryJob{}, false, err
}
if err = s.AttachLibraryQueueJob(ctx, created.ID, queued.ID, now); err != nil {
return created, reused, err
}
created.QueueJobID = queued.ID
return created, reused, nil
}
+18 -44
View File
@@ -2,12 +2,9 @@ package httpapi
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strings"
"time"
@@ -360,6 +357,7 @@ type libraryVersionRef struct {
}
type libraryJobStore interface {
CreateLibraryDispatch(context.Context, governance.LibraryJob, []string, bool, time.Time) (governance.LibraryJob, bool, error)
CreateLibraryJob(ctx context.Context, job governance.LibraryJob, stages []string, now time.Time) (governance.LibraryJob, bool, error)
// EnsureLibraryOperation 幂等登记"一次明确意图":同键+同摘要 ⇒ 同一次意图(客户端重放),
// 换键 ⇒ 新意图。作业是意图的执行代次,不能反过来用"历史成功作业"回答新意图(F01)。
@@ -470,8 +468,7 @@ func libraryMaintenanceRecoverHandler(w http.ResponseWriter, r *http.Request, co
}
// 队列作业 id 与幂等键都按窗口固定:重复点击只会得到同一个恢复作业。
// 队列 id 有长度上限(36),窗口作业 id 比它还长,所以按窗口摘要取短 id。
sum := sha256.Sum256([]byte(held.OwnerJobID))
queueID := "lrec-" + hex.EncodeToString(sum[:14])
queueID := governance.LibraryRecoveryQueueID(held.OwnerJobID)
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
ID: queueID, Type: libraryRecoverJobType, Payload: payload,
AvailableAt: now, MaxAttempts: 1, IdempotencyKey: "library.recover:" + held.OwnerJobID,
@@ -727,7 +724,11 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
return
}
if archiveReadable {
overview.TestSealed, overview.TestSealedReason = testSealedOf(versions, byID)
var candidateErr error
overview.TestSealed, candidateErr = currentSourceCandidate(r.Context(), config, scope)
if candidateErr != nil {
overview.TestSealedReason = candidateErr.Error()
}
}
overview.Production = libraryKnownView{State: "unknown", Reason: "还没有生产验证通过的生效版本记录"}
overview.Prebackup = libraryKnownView{State: "unknown", Reason: "这个范围还没有任何生产预备份"}
@@ -873,6 +874,7 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
// OperationKey 是客户端重放键:同一次意图重发要命中同一个 operation。
// 不传就是一次新意图(同一个快照再发布一次也必须真的执行)。
OperationKey string `json:"operation_key"`
SourceID string `json:"source_id"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&request); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
@@ -939,6 +941,11 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
return
}
candidate, candidateErr := currentSourceCandidate(r.Context(), config, request.Scope)
if candidateErr != nil || request.SourceID == "" || candidate == nil || candidate.SourceID != request.SourceID || candidate.SnapshotID != request.Target {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_source_candidate_changed", "error": "来源候选已变化或身份未绑定,请刷新后重试", "detail": errString(candidateErr)})
return
}
// 走到这里说明闸口与证据都齐了才真正建作业;互斥与幂等由数据库索引保证。
digest, err := governance.LibraryRequestDigest(request.Scope, governance.LibraryJobSync,
map[string]any{"target_snapshot_id": request.Target})
@@ -965,11 +972,11 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot register library intent"})
return
}
job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
job, reused, err := store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{
ID: jobID, Scope: request.Scope, Kind: governance.LibraryJobSync,
IdempotencyKey: intent.JobKey, RequestDigest: digest, OperationID: intent.Operation.ID,
TargetSnapshotID: request.Target, Actor: actor,
}, governance.SyncStages(), now)
}, governance.SyncStages(), config.LibraryHandoffEnabled, now)
if errors.Is(err, governance.ErrLibraryJobActive) {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_active",
"error": "该目标已有在飞的生产写作业(同步与恢复互斥)"})
@@ -986,13 +993,13 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
// 上一次同意图请求失败/被取消后,幂等键不能再把新请求塞回那个死作业里:
// 在**同一个 operation** 下开一个新的执行作业(重试代次),旧作业保留为审计记录。
if reused && (job.State == governance.LibraryJobFailed || job.State == governance.LibraryJobCancelled) {
job, reused, err = store.CreateLibraryJob(r.Context(), governance.LibraryJob{
job, reused, err = store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{
ID: fmt.Sprintf("libsync-%s-%d", request.Scope, time.Now().UTC().UnixNano()), Scope: request.Scope,
Kind: governance.LibraryJobSync,
IdempotencyKey: intent.JobKey + ":retry:" + now.Format("20060102T150405.000000000"),
RequestDigest: digest, OperationID: intent.Operation.ID,
TargetSnapshotID: request.Target, Actor: actor,
}, governance.SyncStages(), now)
}, governance.SyncStages(), config.LibraryHandoffEnabled, now)
if err != nil || reused {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_retry_conflict",
"error": "无法为重试创建新作业", "detail": errString(err)})
@@ -1003,27 +1010,6 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true})
return
}
// 业务作业先落库,再投递队列:投递失败就把作业标失败,不留下"看起来在跑"的空作业。
queueID, queueType, payload, err := libraryQueueRequest(config.LibraryHandoffEnabled, job.ID,
request.Scope, request.Target, librarySyncJobType)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build sync payload"})
return
}
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
ID: queueID, Type: queueType, Payload: payload, AvailableAt: now,
MaxAttempts: 1, IdempotencyKey: queueType + ".queue:" + job.ID,
}, now)
if err != nil || queueJob == nil {
log.Printf("library sync enqueue failed job=%s: %v", job.ID, err)
_ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始同步", now)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue sync job"})
return
}
if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach sync job"})
return
}
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false})
}
@@ -1033,17 +1019,5 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
// 由它在成功后再入 releaseType;搬运未接线时保持原样。两种情况下 releaseType
// 作业的 ID 都是 QueueJobIDFor(jobID),所以接管/续作的既有路径不受影响。
func libraryQueueRequest(handoff bool, jobID, scope, snapshotID, releaseType string) (string, string, []byte, error) {
payload := map[string]string{"library_job_id": jobID, "scope": scope, "target_snapshot_id": snapshotID}
queueID := governance.QueueJobIDFor(jobID)
queueType := releaseType
if handoff {
payload["next_type"] = releaseType
queueID = governance.LibraryHandoffQueueJobID(jobID)
queueType = libraryHandoffJobType
}
raw, err := json.Marshal(payload)
if err != nil {
return "", "", nil, err
}
return queueID, queueType, raw, nil
return governance.LibraryQueueRequest(handoff, jobID, scope, snapshotID, releaseType)
}
+8
View File
@@ -18,6 +18,7 @@ import (
// 复用既有 fakeJobStore 提供 Store 的其余方法,只覆盖整库作业这几个。
type fakeLibraryStore struct {
sourceCandidate *governance.LibraryVersion
fakeJobStore
grant *governance.LibraryReleaseAuthorization
versions []governance.LibraryVersion
@@ -345,8 +346,11 @@ func TestLibrarySyncEnqueueCreatesJobOnlyWithGrant(t *testing.T) {
store.enqueueEchoRequestedID = true
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int", LibraryCapacityBudgetBytes: 1 << 40}
sourceID := bindSourceFixture(t, &config, store, &target)
digest, _ = librarySyncParamsDigest("internal", target)
body := `{"scope":"internal","target_snapshot_id":"` + target + `"}`
body = sourceRequestBody(t, body, sourceID)
// 先没有授权
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
@@ -393,6 +397,7 @@ func TestLibraryOverviewShowsLatestPrebackupWhenTargetDiffers(t *testing.T) {
SnapshotID: sealed, CreatedAt: now.Add(-2 * time.Hour)},
}}
config := Config{Store: store, LibraryArchiveRoot: root, LibraryCapacityBudgetBytes: 1 << 30}
bindSourceFixture(t, &config, store, &sealed)
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/overview?scope=internal", nil)
recorder := httptest.NewRecorder()
libraryOverviewHandler(recorder, request, config)
@@ -510,7 +515,10 @@ func TestLibrarySyncEnqueueUsesExactCurrentVersionBeyondWindow(t *testing.T) {
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
LibraryCapacityBudgetBytes: 1 << 40}
sourceID := bindSourceFixture(t, &config, store, &target)
digest, _ = librarySyncParamsDigest("internal", target)
body := `{"scope":"internal","target_snapshot_id":"` + target + `"}`
body = sourceRequestBody(t, body, sourceID)
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
if recorder.Code != http.StatusAccepted {
+14 -5
View File
@@ -18,7 +18,8 @@ import (
// 判据:换 operation_key ⇒ 新 operation(ID 不同、作业幂等键不同);
// 同一个 operation_key ⇒ 同一 operation(重放)。
func TestLibrarySyncNewIntentReExecutesInsteadOfReusingHistory(t *testing.T) {
target := "snap-1"
root := libraryFixtureRoot(t)
target := sealSharedVersions(t, root, 1, 4)[0]
digest, err := librarySyncParamsDigest("internal", target)
if err != nil {
t.Fatal(err)
@@ -36,14 +37,19 @@ func TestLibrarySyncNewIntentReExecutesInsteadOfReusingHistory(t *testing.T) {
return store
}
config := func(store *fakeLibraryStore) Config {
return Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
c := Config{Store: store, LibraryArchiveRoot: root, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
LibraryCapacityBudgetBytes: 1 << 40}
bindSourceFixture(t, &c, store, &target)
return c
}
post := func(store *fakeLibraryStore, body string) *httptest.ResponseRecorder {
c := config(store)
id, _ := configuredLibrarySource(c, "internal").ID()
body = sourceRequestBody(t, body, id)
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs",
strings.NewReader(body)), config(store))
strings.NewReader(body)), c)
return recorder
}
withKey := `{"scope":"internal","target_snapshot_id":"` + target + `","operation_key":"%s"}`
@@ -85,7 +91,8 @@ func TestLibrarySyncNewIntentReExecutesInsteadOfReusingHistory(t *testing.T) {
// 同一个意图键配上不同快照 = 冲突,不能悄悄共享谱系。
func TestLibrarySyncIntentKeyReusedWithAnotherSnapshotConflicts(t *testing.T) {
target := "snap-1"
root := libraryFixtureRoot(t)
target := sealSharedVersions(t, root, 1, 4)[0]
digest, _ := librarySyncParamsDigest("internal", target)
now := time.Now().UTC()
store := &fakeLibraryStore{current: &governance.LibraryVersion{ID: "ver-prod", Scope: "internal",
@@ -101,7 +108,9 @@ func TestLibrarySyncIntentKeyReusedWithAnotherSnapshotConflicts(t *testing.T) {
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
LibraryCapacityBudgetBytes: 1 << 40}
body := `{"scope":"internal","target_snapshot_id":"` + target + `","operation_key":"intent-1"}`
config.LibraryArchiveRoot = root
sourceID := bindSourceFixture(t, &config, store, &target)
body := sourceRequestBody(t, `{"scope":"internal","target_snapshot_id":"`+target+`","operation_key":"intent-1"}`, sourceID)
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
if recorder.Code != http.StatusConflict {
+48
View File
@@ -0,0 +1,48 @@
package httpapi
import (
"context"
"encoding/json"
"io"
"knowledge-governance/internal/governance"
"net/http"
"time"
)
type libraryLegacySourceBinder interface {
BindLegacyLibrarySource(context.Context, string, string, governance.LibrarySourceIdentity, string, time.Time) error
}
func libraryLegacySourceBind(w http.ResponseWriter, r *http.Request, config Config) {
identity, ok := sessionFrom(r.Context())
if !ok || identity.Role != roleAdmin || identity.Username == "" {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "administrator session required"})
return
}
var input struct {
Scope string `json:"scope"`
SnapshotID string `json:"snapshot_id"`
}
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096))
decoder.DisallowUnknownFields()
if decoder.Decode(&input) != nil || decoder.Decode(new(any)) != io.EOF || (input.Scope != "internal" && input.Scope != "external") || input.SnapshotID == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "exact snapshot and scope required"})
return
}
source := configuredLibrarySource(config, input.Scope)
sourceID, err := source.ID()
if err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": err.Error()})
return
}
store, ok := config.Store.(libraryLegacySourceBinder)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "source association store unavailable"})
return
}
if err = store.BindLegacyLibrarySource(r.Context(), input.SnapshotID, config.LibraryArchiveRoot, source, identity.Username, time.Now().UTC()); err != nil {
writeJSON(w, http.StatusConflict, map[string]string{"error": err.Error()})
return
}
writeJSON(w, http.StatusOK, map[string]any{"snapshot_id": input.SnapshotID, "source_id": sourceID, "source_identity": source, "associated": true, "published": false})
}
@@ -0,0 +1,67 @@
package httpapi
import (
"context"
"errors"
"knowledge-governance/internal/governance"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
type legacySourceAPIStore struct {
fakeLibraryStore
calls int
actor string
source governance.LibrarySourceIdentity
err error
}
func (s *legacySourceAPIStore) BindLegacyLibrarySource(_ context.Context, _ string, _ string, source governance.LibrarySourceIdentity, actor string, _ time.Time) error {
s.calls++
s.actor = actor
s.source = source
return s.err
}
func TestContractLegacySourceAssociationAPI(t *testing.T) {
for _, role := range []string{roleViewer, roleEngineer, roleAdmin} {
store := &legacySourceAPIStore{}
config := Config{Store: store, LibrarySourceProject: "configured-project", LibrarySourceApp: "configured-app", LibrarySourceTenantID: 10000, LibrarySourceInternalKB: "configured-kb"}
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/source-associations", strings.NewReader(`{"scope":"internal","snapshot_id":"exact-snapshot"}`))
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "real-session-actor", Role: role}))
response := httptest.NewRecorder()
libraryLegacySourceBind(response, request, config)
if role == roleAdmin {
if response.Code != 200 || store.calls != 1 || store.actor != "real-session-actor" || store.source.Project != "configured-project" || store.source.KnowledgeBaseID != "configured-kb" {
t.Fatal("association contract", response.Code, response.Body.String())
}
} else if response.Code != 403 || store.calls != 0 {
t.Fatal("non-admin associated source")
}
}
if classifyRole("POST", "/api/v1/library/source-associations") != roleAdmin {
t.Fatal("route is not administrator only")
}
}
func TestContractLegacySourceAssociationAPIRejectsSpoofAndEvidenceFailure(t *testing.T) {
for _, body := range []string{`{"scope":"internal","snapshot_id":"x","actor":"forged"}`, `{"scope":"internal","snapshot_id":"x","source_identity":{"project":"forged"}}`, `{"scope":"internal","snapshot_id":"x"} {}`} {
store := &legacySourceAPIStore{}
req := httptest.NewRequest("POST", "/", strings.NewReader(body))
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "admin", Role: roleAdmin}))
out := httptest.NewRecorder()
libraryLegacySourceBind(out, req, Config{Store: store})
if out.Code != 400 || store.calls != 0 {
t.Fatal("spoofed or trailing payload accepted")
}
}
store := &legacySourceAPIStore{err: errors.New("original proof mismatch")}
req := httptest.NewRequest("POST", "/", strings.NewReader(`{"scope":"internal","snapshot_id":"x"}`))
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "admin", Role: roleAdmin}))
out := httptest.NewRecorder()
libraryLegacySourceBind(out, req, Config{Store: store, LibrarySourceProject: "p", LibrarySourceApp: "app", LibrarySourceTenantID: 1, LibrarySourceInternalKB: "kb"})
if out.Code != 409 {
t.Fatal("unproven association reported success")
}
}
@@ -30,6 +30,7 @@ func TestEmptyTargetOverviewAndEnqueueAgree(t *testing.T) {
}
return true, nil, nil
}}
sourceID := bindSourceFixture(t, &config, store, &target)
rec := httptest.NewRecorder()
libraryOverviewHandler(rec, httptest.NewRequest(http.MethodGet, "/api/v1/library/overview?scope=internal", nil), config)
var overview libraryOverview
@@ -40,7 +41,7 @@ func TestEmptyTargetOverviewAndEnqueueAgree(t *testing.T) {
t.Fatalf("failed=%v gate=%+v", failed, overview.Gate)
}
rec = httptest.NewRecorder()
librarySyncEnqueue(rec, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(`{"scope":"internal","target_snapshot_id":"`+target+`"}`)), config)
librarySyncEnqueue(rec, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(sourceRequestBody(t, `{"scope":"internal","target_snapshot_id":"`+target+`"}`, sourceID))), config)
if failed {
if rec.Code != http.StatusServiceUnavailable || store.createN != 0 {
t.Fatalf("unreachable target enqueued: %d %s", rec.Code, rec.Body.String())
+4 -23
View File
@@ -104,12 +104,12 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot register restore intent"})
return
}
job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
job, reused, err := store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{
ID: jobID, Scope: request.Scope, Kind: governance.LibraryJobRestore,
IdempotencyKey: intent.JobKey,
RequestDigest: digest, OperationID: intent.Operation.ID, TargetSnapshotID: request.SnapshotID,
Actor: identity.Username,
}, governance.SyncStages(), now)
}, governance.SyncStages(), config.LibraryHandoffEnabled, now)
if errors.Is(err, governance.ErrLibraryJobActive) {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_restore_active", "error": "该目标已有在飞作业"})
return
@@ -123,12 +123,12 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
return
}
if reused && (job.State == governance.LibraryJobFailed || job.State == governance.LibraryJobCancelled) {
job, reused, err = store.CreateLibraryJob(r.Context(), governance.LibraryJob{
job, reused, err = store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{
ID: jobID + "-retry", Scope: request.Scope, Kind: governance.LibraryJobRestore,
IdempotencyKey: intent.JobKey + ":retry:" + strconv.FormatInt(now.UnixNano(), 10),
RequestDigest: digest, OperationID: intent.Operation.ID, TargetSnapshotID: request.SnapshotID,
Actor: identity.Username,
}, governance.SyncStages(), now)
}, governance.SyncStages(), config.LibraryHandoffEnabled, now)
if err != nil || reused {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_restore_retry_conflict", "error": "无法为重试创建新作业"})
return
@@ -138,25 +138,6 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true})
return
}
queueID, queueType, payload, err := libraryQueueRequest(config.LibraryHandoffEnabled, job.ID,
request.Scope, request.SnapshotID, libraryRestoreJobType)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build restore payload"})
return
}
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
ID: queueID, Type: queueType, Payload: payload, AvailableAt: now,
MaxAttempts: 1, IdempotencyKey: queueType + ".queue:" + job.ID,
}, now)
if err != nil || queueJob == nil {
_ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始恢复", now)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue restore job"})
return
}
if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach restore job"})
return
}
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false})
}
+16 -13
View File
@@ -8,6 +8,7 @@ import (
"strings"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/librarysnapshot"
)
@@ -28,19 +29,21 @@ type librarySnapshotPart struct {
}
type librarySnapshotView struct {
SnapshotID string `json:"snapshot_id"`
Scope string `json:"scope"`
KnowledgeBaseID string `json:"knowledge_base_id"`
TenantID uint64 `json:"tenant_id"`
CreatedAt time.Time `json:"created_at"`
ValidationPolicy string `json:"validation_policy"`
Format string `json:"format"`
Compatibility librarysnapshot.Compatibility `json:"compatibility"`
Parts []librarySnapshotPart `json:"parts"`
LogicalBytes int64 `json:"logical_bytes"`
UniqueBytes int64 `json:"unique_bytes"`
SharedBytes int64 `json:"shared_bytes"`
Totals map[string]int64 `json:"totals"`
SourceID string `json:"source_id,omitempty"`
SourceIdentity *governance.LibrarySourceIdentity `json:"source_identity,omitempty"`
SnapshotID string `json:"snapshot_id"`
Scope string `json:"scope"`
KnowledgeBaseID string `json:"knowledge_base_id"`
TenantID uint64 `json:"tenant_id"`
CreatedAt time.Time `json:"created_at"`
ValidationPolicy string `json:"validation_policy"`
Format string `json:"format"`
Compatibility librarysnapshot.Compatibility `json:"compatibility"`
Parts []librarySnapshotPart `json:"parts"`
LogicalBytes int64 `json:"logical_bytes"`
UniqueBytes int64 `json:"unique_bytes"`
SharedBytes int64 `json:"shared_bytes"`
Totals map[string]int64 `json:"totals"`
// Verified 只在这一份版本的每个部件都被重新哈希并核对通过时为 true。
// 列表口径下它恒为 false:枚举只证明清单可读,不是"完整性已验证"。
Verified bool `json:"verified"`
@@ -0,0 +1,58 @@
package httpapi
import (
"context"
"errors"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/librarysnapshot"
)
type librarySourceCandidateStore interface {
LibrarySourceCandidate(context.Context, string, string) (governance.LibraryVersion, bool, error)
}
func configuredLibrarySource(config Config, scope string) governance.LibrarySourceIdentity {
kb := config.LibrarySourceInternalKB
if scope == "external" {
kb = config.LibrarySourceExternalKB
}
return governance.LibrarySourceIdentity{Project: config.LibrarySourceProject, App: config.LibrarySourceApp, Scope: scope, TenantID: config.LibrarySourceTenantID, KnowledgeBaseID: kb}
}
func currentSourceCandidate(ctx context.Context, config Config, scope string) (*librarySnapshotView, error) {
source := configuredLibrarySource(config, scope)
id, err := source.ID()
if err != nil {
return nil, err
}
store, ok := config.Store.(librarySourceCandidateStore)
if !ok {
return nil, errors.New("source candidate exact query unavailable")
}
candidate, found, err := store.LibrarySourceCandidate(ctx, scope, id)
if err != nil {
return nil, err
}
if !found {
return nil, errors.New("当前来源没有已绑定封存;旧快照须以原捕获证据核验关联,不能继承其他来源")
}
if candidate.Kind != governance.LibraryVersionTestSealed || candidate.Scope != scope || candidate.Evidence["source_id"] != id {
return nil, errors.New("candidate source binding mismatch")
}
archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024)
if err != nil {
return nil, err
}
defer archive.Close()
manifest, err := archive.Load(candidate.SnapshotID)
if err != nil {
return nil, err
}
if manifest.Scope != scope || manifest.TenantID != source.TenantID || manifest.KnowledgeBaseID != source.KnowledgeBaseID {
return nil, errors.New("candidate manifest differs from configured source")
}
view := librarySnapshotViewOfNoUsage(candidate.SnapshotID, manifest)
view.SourceID = id
view.SourceIdentity = &source
return &view, nil
}
@@ -0,0 +1,23 @@
package httpapi
import (
"knowledge-governance/internal/governance"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestContractSyncRejectsUnboundSourceBeforeCreatingJob(t *testing.T) {
store := &fakeLibraryStore{current: &governance.LibraryVersion{SnapshotID: "current"}, grant: &governance.LibraryReleaseAuthorization{Scope: "internal", SnapshotID: "foreign", ExpiresAt: time.Now().Add(time.Hour)}}
digest, _ := librarySyncParamsDigest("internal", "foreign")
store.grant.ParamsDigest = digest
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true, LibraryProductionDatabaseURL: "postgres://unreachable.invalid/db", LibraryCapacityBudgetBytes: 1 << 40}
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(`{"scope":"internal","target_snapshot_id":"foreign"}`))
response := httptest.NewRecorder()
librarySyncEnqueue(response, request, config)
if store.createN != 0 {
t.Fatalf("unbound foreign source created %d jobs; response=%s", store.createN, response.Body.String())
}
}
@@ -0,0 +1,63 @@
package httpapi
import (
"context"
"encoding/json"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/librarysnapshot"
"testing"
)
func (f *fakeLibraryStore) LibrarySourceCandidate(_ context.Context, scope, sourceID string) (governance.LibraryVersion, bool, error) {
if f.sourceCandidate != nil && f.sourceCandidate.Scope == scope && f.sourceCandidate.Evidence["source_id"] == sourceID {
return *f.sourceCandidate, true, nil
}
return governance.LibraryVersion{}, false, nil
}
// These fixtures now contain the same capture identity and real immutable
// manifest required by the production admission path. No production bypass.
func bindSourceFixture(t *testing.T, config *Config, store *fakeLibraryStore, target *string) string {
t.Helper()
if config.LibraryArchiveRoot == "" {
config.LibraryArchiveRoot = libraryFixtureRoot(t)
*target = sealSharedVersions(t, config.LibraryArchiveRoot, 1, 4)[0]
}
archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
manifest, err := archive.Load(*target)
if err != nil {
t.Fatal(err)
}
config.LibrarySourceProject = "fixture-project"
config.LibrarySourceApp = "fixture-app"
config.LibrarySourceTenantID = manifest.TenantID
config.LibrarySourceInternalKB = manifest.KnowledgeBaseID
source := configuredLibrarySource(*config, "internal")
id, err := source.ID()
if err != nil {
t.Fatal(err)
}
store.sourceCandidate = &governance.LibraryVersion{Scope: "internal", Kind: governance.LibraryVersionTestSealed, SnapshotID: *target, Evidence: map[string]any{"source_id": id}}
if store.grant != nil {
store.grant.SnapshotID = *target
store.grant.ParamsDigest, _ = librarySyncParamsDigest("internal", *target)
}
return id
}
func sourceRequestBody(t *testing.T, body, id string) string {
t.Helper()
var v map[string]any
if err := json.Unmarshal([]byte(body), &v); err != nil {
t.Fatal(err)
}
v["source_id"] = id
raw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
return string(raw)
}
+8 -1
View File
@@ -167,7 +167,11 @@ type Config struct {
LibraryAgentSocket string
// LibrarySourceProject 是执行器应指向的实例名(agent -project,封存源)。
// 与它不一致时按"封错库"处理:不可发起,并说明差在哪。
LibrarySourceProject string
LibrarySourceProject string
LibrarySourceApp string
LibrarySourceTenantID uint64
LibrarySourceInternalKB string
LibrarySourceExternalKB string
// LibraryExecutorStatusMaxAge 是执行器观测的有效期;超过即"无法确认"。
LibraryExecutorStatusMaxAge time.Duration
// LibraryCapacityBudgetBytes 是整库归档容量预算;0 = 未设置(容量门禁不放行)。
@@ -449,6 +453,9 @@ func NewHandler(config Config) (http.Handler, error) {
librarySnapshotDetail(w, r, config)
})
// 页面发起封存:只投递作业(主机侧 agent 执行),并回读作业真实状态。
mux.HandleFunc("POST /api/v1/library/source-associations", func(w http.ResponseWriter, r *http.Request) {
libraryLegacySourceBind(w, r, config)
})
mux.HandleFunc("POST /api/v1/library/captures", func(w http.ResponseWriter, r *http.Request) {
libraryCaptureEnqueue(w, r, config)
})
@@ -127,7 +127,7 @@ func TestRecoverWindowRequiresPersistedBackup(t *testing.T) {
}
}
// 目标换了(指纹不一致)就不许拿旧窗口收尾。
// 目标换了(指纹不一致)就不许拿旧窗口收尾:另一个目标上不许有任何写/停动作。
func TestRecoverWindowRejectsDifferentTarget(t *testing.T) {
_, c, e := instanceFixture(t)
stopAllServices(c)
@@ -137,11 +137,15 @@ func TestRecoverWindowRejectsDifferentTarget(t *testing.T) {
if err := e.save(heldJournal("job-other", strings.Repeat("a", 64), strings.Repeat("b", 64))); err != nil {
t.Fatal(err)
}
restored, verified := false, false
if _, err := e.RecoverWindow(context.Background(), "job-other",
restorerFunc(func(context.Context, string) error { return nil }),
verifierFunc(func(context.Context, string) (string, error) { return "x", nil })); err == nil {
restorerFunc(func(context.Context, string) error { restored = true; return nil }),
verifierFunc(func(context.Context, string) (string, error) { verified = true; return "x", nil })); err == nil {
t.Fatal("recovery accepted another target's journal")
}
if restored || verified {
t.Fatalf("recovery touched another target: restored=%v verified=%v", restored, verified)
}
}
// 后台任务还在跑时不许开窗口(HTTP 排空覆盖不到它们)。
+14
View File
@@ -0,0 +1,14 @@
package libraryrelease
import "encoding/json"
// IndexWrite freezes the exact index/ID, original bytes and CAS generation.
// After=nil is an explicit removal, never a scope-wide delete-by-query.
type IndexWrite struct {
Index string `json:"index"`
ID string `json:"id"`
Before json.RawMessage `json:"before,omitempty"`
SeqNo *int64 `json:"seq_no,omitempty"`
PrimaryTerm *int64 `json:"primary_term,omitempty"`
After json.RawMessage `json:"after,omitempty"`
}
+18
View File
@@ -0,0 +1,18 @@
package libraryrelease
// ObjectWrite identifies a physical object, not a row ID or a guessed orphan.
// Existing objects are read-only. This protocol refuses differing overwrites.
type ObjectWrite struct {
BeforeVersionID string `json:"before_version_id,omitempty"`
ResourceID string `json:"resource_id"`
Provider string `json:"provider"`
BackendID string `json:"backend_id"`
Bucket string `json:"bucket"`
Key string `json:"key"`
Locator string `json:"locator"`
SHA256 string `json:"sha256"`
Bytes int64 `json:"bytes"`
Existing bool `json:"existing"`
BeforeETag string `json:"before_etag,omitempty"`
OwnerToken string `json:"owner_token"`
}
+42
View File
@@ -115,6 +115,16 @@ type Recorder interface {
Stage(ctx context.Context, stage string, state string, detail string)
}
// GrantRevalidator 让编排在每笔副作用前按**持久授权**回读。
//
// 内存里的 Grant 只是一个快照:它既不能延长有效期,也不能掩盖中途撤销。
// 目标实现了这个接口就必须给出权威答案(读治理库的授权行);返回错误即拒绝继续。
// 未实现时行为不变(只核静态有效期),所以这不是给"忘记接线"留的后门 ——
// 生产目标的 wrapper 由 runLibraryRelease 无条件接线。
type GrantRevalidator interface {
RevalidateGrant(ctx context.Context, grant Grant) error
}
// BackupObserver 让调用方在预备份完成时立刻持久化快照身份:
// worker 被杀后重启必须能接管这份预备份,而不是重新备份覆盖它。
type BackupObserver interface {
@@ -184,6 +194,8 @@ func Run(ctx context.Context, request Request, target Target, backups BackupStor
if recorder == nil {
recorder = NoopRecorder{}
}
// Request.Now is a diagnostic input, not a clock authority for execution.
request.Now = time.Now().UTC()
if err := ValidateGrant(request); err != nil {
outcome.Error = err.Error()
recorder.Stage(ctx, "prebackup", "failed", err.Error())
@@ -217,6 +229,33 @@ func Run(ctx context.Context, request Request, target Target, backups BackupStor
}
recorder.Stage(ctx, "prebackup", "succeeded", "预备份 "+backup.ID)
// Backup may outlive the grant. Recheck before planning (which may allocate
// numbers), and again after durable plan registration before the first apply.
// With a GrantRevalidator the check is authoritative: a revoked or expired
// authorization row stops the run even though the in-memory grant still looks
// valid, and a stale in-memory expiry cannot be extended either.
checkLiveGrant := func() bool {
request.Now = time.Now().UTC()
if e := ValidateGrant(request); e != nil {
outcome.Error = e.Error()
outcome.Recovery = "预备份保留;需要有效的新授权后继续"
recorder.Stage(ctx, "prebackup", "failed", outcome.Error)
return false
}
if revalidator, ok := target.(GrantRevalidator); ok {
if e := revalidator.RevalidateGrant(ctx, request.Grant); e != nil {
outcome.Error = "持久授权已失效,未继续写入:" + e.Error()
outcome.Recovery = "预备份保留;重新签发授权后按原预备份继续"
recorder.Stage(ctx, "prebackup", "failed", outcome.Error)
return false
}
}
return true
}
if !checkLiveGrant() {
return outcome
}
// 写集合必须在第一笔写入之前落盘并登记:恢复只按"这次明确写了什么"清理,
// 不按目标现状推断残渣(那会把历史孤儿/共享资源当成本次残留删掉)。
existingPlan := backup.WriteSet != nil
@@ -265,6 +304,9 @@ func Run(ctx context.Context, request Request, target Target, backups BackupStor
}
}
if !checkLiveGrant() {
return outcome
}
for _, stage := range Stages() {
recorder.Stage(ctx, string(stage), "running", "")
if err = target.Apply(ctx, stage, request.SnapshotID); err != nil {
+2 -1
View File
@@ -119,7 +119,8 @@ func TestRunRefusesExpiredOrMismatchedGrantBeforeTouchingTarget(t *testing.T) {
mutate func(*Request)
want error
}{
{"expired", func(r *Request) { r.Now = r.Grant.ExpiresAt.Add(time.Minute) }, ErrGrantExpired},
// Run uses the live clock, not the caller's diagnostic timestamp.
{"expired", func(r *Request) { r.Grant.ExpiresAt = time.Now().Add(-time.Minute) }, ErrGrantExpired},
{"other target", func(r *Request) { r.Target = "external-prod" }, ErrGrantTarget},
{"other snapshot", func(r *Request) { r.SnapshotID = "snap-2" }, ErrGrantSnapshot},
{"params changed", func(r *Request) { r.ParamsDigest = "digest-2" }, ErrGrantParams},
+58 -11
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"sort"
"strconv"
"time"
)
@@ -15,6 +16,9 @@ import (
// 宁可保持维护,也不要用一份"格式变了但看起来还能读"的记录去删目标数据。
const WriteSetVersion = 1
// MigrationWriteSetVersion rejects reinterpretation by old V1 executors.
const MigrationWriteSetVersion = 2
// WriteSetRow 是台账里的一行:本次发布明确要写的精确身份 + 写前状态。
//
// 为什么需要"写前状态":恢复不能在目标里按"没人引用"推断残渣。历史孤儿资源、
@@ -75,17 +79,33 @@ type PriorSnapshot struct {
// WriteSet 是"这一次发布的写集合 + 写前整实例内容证据",内容寻址、可校验、
// 与 job/target/backup 绑定。恢复只读它,不读目标现状去推断。
// LocalIDMapping is operation-local source lineage. Decimal strings are used
// only inside this typed sidecar; archived row values remain JSON integers.
type LocalIDMapping struct {
Table string `json:"table"`
Column string `json:"column"`
Source string `json:"source"`
Target string `json:"target"`
}
type WriteSet struct {
Version int `json:"version"`
JobID string `json:"job_id"`
Target string `json:"target"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
BackupSnapshotID string `json:"backup_snapshot_id"`
TargetSnapshotID string `json:"target_snapshot_id"`
CreatedAt time.Time `json:"created_at"`
Rows []WriteSetRow `json:"rows"`
Universe map[string]TableFingerprint `json:"universe"`
Index []IndexWrite `json:"index,omitempty"`
Objects []ObjectWrite `json:"objects,omitempty"`
SchemaDigest string `json:"schema_digest,omitempty"`
ContractVersion int `json:"contract_version,omitempty"`
SourceTenantID uint64 `json:"source_tenant_id,omitempty"`
SourceKnowledgeBaseID string `json:"source_knowledge_base_id,omitempty"`
LocalIDs []LocalIDMapping `json:"local_ids,omitempty"`
Version int `json:"version"`
JobID string `json:"job_id"`
Target string `json:"target"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
BackupSnapshotID string `json:"backup_snapshot_id"`
TargetSnapshotID string `json:"target_snapshot_id"`
CreatedAt time.Time `json:"created_at"`
Rows []WriteSetRow `json:"rows"`
Universe map[string]TableFingerprint `json:"universe"`
// Digest 是对除本字段外全部内容的 sha256:落盘文件名与治理库里的引用都用它,
// 记录被改一个字节就对不上。
Digest string `json:"digest"`
@@ -111,6 +131,12 @@ func (w *WriteSet) Seal() error {
// CanonicalBytes 是不含摘要字段的规范字节:摘要覆盖的就是它,落盘文件另外
// 带上摘要本身(便于自描述),读回时用同一份规范字节重新推导。
func (w WriteSet) CanonicalBytes() ([]byte, error) {
if w.Version == WriteSetVersion && (w.ContractVersion != 0 || w.SourceTenantID != 0 || w.SourceKnowledgeBaseID != "" || len(w.LocalIDs) != 0 || w.SchemaDigest != "" || len(w.Objects) != 0 || len(w.Index) != 0) {
return nil, errors.New("historical V1 cannot carry migration contract fields")
}
if w.Version != WriteSetVersion && w.Version != MigrationWriteSetVersion {
return nil, errors.New("unsupported write set format")
}
copied := w
copied.Digest = ""
rows := make([]WriteSetRow, len(w.Rows))
@@ -142,7 +168,28 @@ func (w *WriteSet) computeDigest() (string, error) {
// Verify 校验摘要与必备身份。缺任一身份都必须失败:没有绑定就没有"这份记录属于
// 这个作业/目标/预备份"的证明,拿它去删目标数据无法追责。
func (w *WriteSet) Verify() error {
if w.Version != WriteSetVersion {
if w.ContractVersion != 0 && w.ContractVersion != 1 {
return errors.New("unsupported migration contract version")
}
if len(w.LocalIDs) > 0 && (w.ContractVersion != 1 || w.SourceTenantID == 0 || w.SourceKnowledgeBaseID == "") {
return errors.New("local mapping lacks source contract binding")
}
sources, targets := map[string]bool{}, map[string]bool{}
for _, m := range w.LocalIDs {
valid := (m.Table == "chunks" || m.Table == "knowledge_tags") && m.Column == "seq_id" || m.Table == "wiki_log_entries" && m.Column == "id"
a, e1 := strconv.ParseInt(m.Source, 10, 64)
b, e2 := strconv.ParseInt(m.Target, 10, 64)
if !valid || e1 != nil || e2 != nil || a <= 0 || b <= 0 || strconv.FormatInt(a, 10) != m.Source || strconv.FormatInt(b, 10) != m.Target {
return errors.New("invalid typed local mapping")
}
source, target := m.Table+"/"+m.Source, m.Table+"/"+m.Target
if sources[source] || targets[target] {
return errors.New("duplicate typed local mapping")
}
sources[source] = true
targets[target] = true
}
if w.Version != WriteSetVersion && w.Version != MigrationWriteSetVersion {
return fmt.Errorf("写集合记录版本 %d 不受支持(当前 %d)", w.Version, WriteSetVersion)
}
if w.JobID == "" || w.BackupSnapshotID == "" || w.TargetSnapshotID == "" {
@@ -0,0 +1,43 @@
package libraryrelease
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"testing"
)
// Literal canonical bytes follow d0c6d57's V1 field order, not today's struct.
const historicalV1Canonical = `{"version":1,"job_id":"job-v1","target":"internal","tenant_id":10001,"knowledge_base_id":"kb-target","backup_snapshot_id":"before","target_snapshot_id":"source","created_at":"2026-01-01T00:00:00Z","rows":[],"universe":{"chunks":{"count":0,"digest":"empty"}},"digest":""}`
func TestContractHistoricalV1CanonicalBytesFrozen(t *testing.T) {
var set WriteSet
if err := json.Unmarshal([]byte(historicalV1Canonical), &set); err != nil {
t.Fatal(err)
}
raw, err := set.CanonicalBytes()
if err != nil {
t.Fatal(err)
}
if string(raw) != historicalV1Canonical {
t.Fatalf("V1 bytes changed: %s", raw)
}
hash := sha256.Sum256([]byte(historicalV1Canonical))
set.Digest = hex.EncodeToString(hash[:])
if err := set.Verify(); err != nil {
t.Fatal(err)
}
}
func TestContractV1CannotCarryNewExecutionSemantics(t *testing.T) {
var set WriteSet
if err := json.Unmarshal([]byte(historicalV1Canonical), &set); err != nil {
t.Fatal(err)
}
set.ContractVersion = 1
set.SourceTenantID = 10000
set.SourceKnowledgeBaseID = "source"
if err := set.Seal(); err == nil {
t.Fatal("new execution fields were sealed as historical V1")
}
}
+37 -1
View File
@@ -57,6 +57,10 @@ type Archive struct {
}
func Open(root string, maxBlobBytes int64) (*Archive, error) {
return openArchive(root, maxBlobBytes, syncRoot)
}
func openArchive(root string, maxBlobBytes int64, syncDirectory func(*os.Root) error) (*Archive, error) {
if !filepath.IsAbs(root) || maxBlobBytes < 1 || maxBlobBytes == math.MaxInt64 {
return nil, errors.New("invalid archive configuration")
}
@@ -94,6 +98,22 @@ func Open(root string, maxBlobBytes int64) (*Archive, error) {
a.versions = sub
}
}
// File and child-directory fsync cannot persist their parent entries. The
// archive root links blobs/versions, and its parent links the archive itself.
if err := syncDirectory(r); err != nil {
a.Close()
return nil, err
}
parent, err := os.OpenRoot(filepath.Dir(root))
if err != nil {
a.Close()
return nil, err
}
err = errors.Join(syncDirectory(parent), parent.Close())
if err != nil {
a.Close()
return nil, err
}
return a, nil
}
func (a *Archive) Close() error {
@@ -282,6 +302,22 @@ func (a *Archive) countRows(p Part, resources map[string]bool) (int64, error) {
}
defer f.Close()
dec := json.NewDecoder(io.LimitReader(f, a.maxBlobBytes+1))
if p.Kind == "schema" {
var catalog map[string][]map[string]json.RawMessage
if err := dec.Decode(&catalog); err != nil || len(catalog) != 6 {
return 0, errors.New("invalid source schema catalog")
}
for _, key := range []string{"columns", "constraints", "indexes", "triggers", "relations", "sequences"} {
if rows, ok := catalog[key]; !ok || rows == nil {
return 0, errors.New("incomplete source schema catalog")
}
}
var extra any
if dec.Decode(&extra) != io.EOF {
return 0, errors.New("trailing source schema catalog data")
}
return 1, nil
}
token, err := dec.Token()
if err != nil || token != json.Delim('[') {
return 0, errors.New("snapshot component must be a JSON row array")
@@ -401,7 +437,7 @@ func encodeManifest(m Manifest) ([]byte, error) {
seen := map[string]bool{}
for _, p := range m.Parts {
key := p.Kind + "/" + p.Name
if (!required[key] && !(p.Kind == "resource" && identifier(p.Name) && p.Count == 1)) || seen[key] || !validDigest(p.SHA256) || p.Bytes < 0 || p.Count < 0 {
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 {
return nil, errors.New("invalid or nonknowledge snapshot component")
}
seen[key] = true
@@ -0,0 +1,40 @@
package librarysnapshot
import (
"errors"
"os"
"testing"
)
func TestArchiveOpenPersistsDirectoryEntriesAndPropagatesSyncFailure(t *testing.T) {
root := t.TempDir()
if err := os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
calls := 0
archive, err := openArchive(root, 1024*1024, func(r *os.Root) error { calls++; return syncRoot(r) })
if err != nil {
t.Fatal(err)
}
archive.Close()
if calls != 2 {
t.Fatalf("root and root-parent durability missing: sync calls=%d", calls)
}
for _, failAt := range []int{1, 2} {
injected := errors.New("directory fsync failed")
n := 0
archive, err = openArchive(root, 1024*1024, func(r *os.Root) error {
n++
if n == failAt {
return injected
}
return syncRoot(r)
})
if !errors.Is(err, injected) || archive != nil {
if archive != nil {
archive.Close()
}
t.Fatal("directory fsync failure did not block archive publication", err)
}
}
}
+18 -1
View File
@@ -16,6 +16,7 @@ import (
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/librarymaintenance"
"knowledge-governance/internal/librarysnapshot"
"knowledge-governance/internal/objectgateway"
v071 "knowledge-governance/internal/releaseadapter/v071"
"knowledge-governance/internal/releasebundle"
)
@@ -93,9 +94,25 @@ func newTarget(ctx context.Context, config appconfig.Config, scope scopeConfig)
if err != nil {
return nil, errors.New("生产对象存储配置无效")
}
if config.LibraryObjectGatewayURL == "" {
return nil, errors.New("对象写入网关未配置:发布目标不允许直写对象存储")
}
var writer v071.ObjectStore = objects
if config.LibraryObjectGatewayURL != "" || config.LibraryObjectGatewayToken != "" || config.LibraryObjectGatewayGrantDirectory != "" {
identity := objectgateway.Digest([]byte(scope.s3.Provider + "\x00" + scope.s3.Endpoint + "\x00" + scope.s3.Bucket))
client, err := objectgateway.NewClient(config.LibraryObjectGatewayURL, config.LibraryObjectGatewayToken, identity)
if err != nil {
return nil, err
}
gateway := &v071.GatewayObjectStore{Automatic: true, Claim: objectgateway.ClaimFromContext(ctx), Client: client, Provider: scope.s3.Provider, Bucket: scope.s3.Bucket, GrantDirectory: config.LibraryObjectGatewayGrantDirectory}
if err := gateway.ConditionalCapability(ctx); err != nil {
return nil, err
}
writer = gateway
}
return v071.NewProductionLibraryTarget(ctx, v071.ProductionLibraryConfig{
Postgres: config.LibraryProductionDatabaseURL, SearchURL: config.LibraryProductionElasticURL,
SearchIndex: config.LibraryProductionIndex, Objects: objects, ObjectsReader: objects,
SearchIndex: config.LibraryProductionIndex, Objects: writer, ObjectsReader: objects,
ArchiveRoot: config.LibraryArchiveRoot,
ObjectsBucket: config.LibraryProductionS3Bucket,
MaxDocuments: 200000,
+159
View File
@@ -0,0 +1,159 @@
package objectgateway
import (
"bytes"
"context"
"encoding/json"
"errors"
"github.com/jackc/pgx/v5"
"math"
)
// Claim names an already persisted application attempt and write-set anchor.
// It never carries keys, bodies, a replacement plan or a chosen gateway epoch.
type Claim struct {
JobID string `json:"job_id"`
OperationID string `json:"operation_id"`
AttemptEpoch int64 `json:"attempt_epoch"`
Owner string `json:"owner"`
PlanDigest string `json:"plan_digest"`
RecoveryJobID string `json:"recovery_job_id,omitempty"`
RecoveryOperationID string `json:"recovery_operation_id,omitempty"`
}
type PlanAuthority interface {
Load(context.Context, Claim) (Plan, error)
}
func (g *Gateway) Acquire(ctx context.Context, c Claim) (Grant, error) {
if g.Authority == nil {
return Grant{}, ErrAuthority
}
if c.JobID == "" || c.OperationID == "" || c.Owner == "" || c.AttemptEpoch < 1 || !validHash(c.PlanDigest) {
return Grant{}, ErrEpoch
}
if e := g.Ready(ctx); e != nil {
return Grant{}, e
}
plan, e := g.Authority.Load(ctx, c)
if e != nil {
return Grant{}, e
}
if plan.Digest != c.PlanDigest || plan.Owner != Digest([]byte(c.JobID)) {
return Grant{}, ErrConflict
}
if e = g.InstallPlan(ctx, plan); e != nil {
return Grant{}, e
}
// Recover only sends in this exact frozen plan. No absent observation can
// settle an unknown send; the locked advancement below still checks all intents.
rows, e := g.Pool.Query(ctx, `SELECT i.request FROM kg_object_gateway_intents i
LEFT JOIN kg_object_gateway_receipts r ON r.scope=i.scope AND r.operation=i.operation
WHERE i.scope=$1 AND r.operation IS NULL`, g.Scope)
if e != nil {
return Grant{}, ErrPersistence
}
var pending []Request
for rows.Next() {
var raw []byte
var request Request
if rows.Scan(&raw) != nil || json.Unmarshal(raw, &request) != nil {
rows.Close()
return Grant{}, ErrPersistence
}
if request.Grant.Plan == plan.Digest {
pending = append(pending, request)
}
}
e = rows.Err()
rows.Close()
if e != nil {
return Grant{}, ErrPersistence
}
for _, request := range pending {
if request.Grant.Owner != plan.Owner {
return Grant{}, ErrConflict
}
if _, e = g.Reconcile(ctx, request); e != nil {
return Grant{}, e
}
}
tx, e := g.Pool.Begin(ctx)
if e != nil {
return Grant{}, ErrPersistence
}
defer tx.Rollback(ctx)
if _, e = tx.Exec(ctx, "INSERT INTO kg_object_gateway_scopes(scope) VALUES($1) ON CONFLICT DO NOTHING", g.Scope); e != nil {
return Grant{}, ErrPersistence
}
var epoch int64
if e = tx.QueryRow(ctx, "SELECT epoch FROM kg_object_gateway_scopes WHERE scope=$1 FOR UPDATE", g.Scope).Scan(&epoch); e != nil {
return Grant{}, ErrPersistence
}
// Recheck after serialization. This is admission evidence, not an OSS fence:
// a persisted uncertain object intent still prevents every epoch transition.
verified, e := g.Authority.Load(ctx, c)
if e != nil {
return Grant{}, e
}
frozen, _ := json.Marshal(plan)
again, _ := json.Marshal(verified)
if !bytes.Equal(frozen, again) {
return Grant{}, ErrConflict
}
raw, _ := json.Marshal(c)
var oldClaim, oldGrant []byte
e = tx.QueryRow(ctx, "SELECT claim,grant_body FROM kg_object_gateway_deliveries WHERE scope=$1 AND job=$2 AND attempt_epoch=$3", g.Scope, c.JobID, c.AttemptEpoch).Scan(&oldClaim, &oldGrant)
if e == nil {
var grant Grant
if !bytes.Equal(raw, oldClaim) || json.Unmarshal(oldGrant, &grant) != nil || !grant.valid() {
return Grant{}, ErrConflict
}
if grant.Epoch != epoch {
return Grant{}, ErrEpoch
}
return grant, nil
}
if !errors.Is(e, pgx.ErrNoRows) {
return Grant{}, ErrPersistence
}
var firstRaw []byte
firstErr := tx.QueryRow(ctx, "SELECT claim FROM kg_object_gateway_deliveries WHERE scope=$1 AND job=$2 ORDER BY attempt_epoch LIMIT 1", g.Scope, c.JobID).Scan(&firstRaw)
if firstErr == nil {
var first Claim
if json.Unmarshal(firstRaw, &first) != nil {
return Grant{}, ErrPersistence
}
if first.JobID != c.JobID || first.OperationID != c.OperationID || first.PlanDigest != c.PlanDigest {
return Grant{}, ErrConflict
}
} else if !errors.Is(firstErr, pgx.ErrNoRows) {
return Grant{}, ErrPersistence
}
var stale bool
if tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM kg_object_gateway_deliveries WHERE scope=$1 AND job=$2 AND attempt_epoch>=$3)", g.Scope, c.JobID, c.AttemptEpoch).Scan(&stale) != nil {
return Grant{}, ErrPersistence
}
if stale || epoch == math.MaxInt64 {
return Grant{}, ErrEpoch
}
next := Grant{Epoch: epoch + 1, Owner: plan.Owner, Plan: plan.Digest}
if e = g.advanceLocked(ctx, tx, epoch, next); e != nil {
return Grant{}, e
}
grantRaw, _ := json.Marshal(next)
if _, e = tx.Exec(ctx, "INSERT INTO kg_object_gateway_deliveries(scope,job,attempt_epoch,claim,grant_epoch,grant_body) VALUES($1,$2,$3,$4,$5,$6)", g.Scope, c.JobID, c.AttemptEpoch, raw, next.Epoch, grantRaw); e != nil {
return Grant{}, ErrPersistence
}
if tx.Commit(ctx) != nil {
return Grant{}, ErrPersistence
}
return next, nil
}
func (c *Client) Acquire(ctx context.Context, claim Claim) (Grant, error) {
var out Grant
e := c.call(ctx, "/v1/acquire", claim, &out)
if e == nil && (!out.valid() || out.Plan != claim.PlanDigest || out.Owner != Digest([]byte(claim.JobID))) {
e = ErrConflict
}
return out, e
}
@@ -0,0 +1,122 @@
package objectgateway_test
import (
"context"
"errors"
g "knowledge-governance/internal/objectgateway"
"testing"
)
type currentPlanAuthority struct {
claim g.Claim
plan g.Plan
}
func (a *currentPlanAuthority) Load(_ context.Context, c g.Claim) (g.Plan, error) {
if c != a.claim {
return g.Plan{}, g.ErrEpoch
}
return a.plan, nil
}
func TestGatewayAcquisitionPersistsAttemptDelivery(t *testing.T) {
ctx, pool, backend := fixture(t)
claim := g.Claim{JobID: "job-acquire", OperationID: "operation-acquire", AttemptEpoch: 1, Owner: "worker-1", PlanDigest: g.Digest([]byte(t.Name()))}
expected := g.Grant{Epoch: 1, Owner: g.Digest([]byte(claim.JobID)), Plan: claim.PlanDigest}
req := request("acquired-object", expected)
authority := &currentPlanAuthority{claim, planFor(expected, req)}
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20, Authority: authority}
grant, e := gateway.Acquire(ctx, claim)
if e != nil || grant != expected {
t.Fatal("anchored active attempt grant unavailable", e)
}
replay, e := gateway.Acquire(ctx, claim)
if e != nil || replay != grant {
t.Fatal("grant delivery replay changed epoch", e)
}
oldClaim := claim
claim.AttemptEpoch = 2
claim.Owner = "worker-2"
authority.claim = claim
next, e := gateway.Acquire(ctx, claim)
if e != nil || next.Epoch != 2 {
t.Fatal("next active attempt", e)
}
if _, e = gateway.Acquire(ctx, oldClaim); !errors.Is(e, g.ErrEpoch) {
t.Fatal("stale attempt acquired grant", e)
}
replacement := claim
replacement.AttemptEpoch++
replacement.PlanDigest = g.Digest([]byte("replacement-plan"))
authority.claim = replacement
authority.plan.Digest = replacement.PlanDigest
if _, e = gateway.Acquire(ctx, replacement); !errors.Is(e, g.ErrConflict) {
t.Fatal("new attempt replaced original plan", e)
}
authority.claim = claim
authority.plan.Digest = claim.PlanDigest
req.Grant = next
receipt, e := gateway.ExecuteAuthorized(ctx, next, req, []byte("gateway fixture acquired-object"))
if e != nil {
t.Fatal(e)
}
cleanup(t, ctx, gateway, receipt)
var count int
if e = pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_deliveries WHERE scope=$1", gateway.Scope).Scan(&count); e != nil || count != 2 {
t.Fatal("immutable delivery count", count, e)
}
for _, statement := range []string{"UPDATE kg_object_gateway_deliveries SET job=job", "DELETE FROM kg_object_gateway_deliveries", "TRUNCATE kg_object_gateway_deliveries"} {
if _, e = pool.Exec(ctx, statement); e == nil {
t.Fatal("mutable grant delivery", statement)
}
}
}
func TestGatewayAcquisitionCannotHandOverUnknownSend(t *testing.T) {
ctx, pool, real := fixture(t)
backend := &stoppedBeforeSend{Backend: real}
claim := g.Claim{JobID: "job-held", OperationID: "operation-held", AttemptEpoch: 1, Owner: "worker-first", PlanDigest: g.Digest([]byte(t.Name()))}
expected := g.Grant{Epoch: 1, Owner: g.Digest([]byte(claim.JobID)), Plan: claim.PlanDigest}
req := request("acquire-held", expected)
body := []byte("gateway fixture acquire-held")
authority := &currentPlanAuthority{claim, planFor(expected, req)}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20, Authority: authority}
if _, e := gateway.Acquire(ctx, claim); e != nil {
t.Fatal(e)
}
if _, e := gateway.ExecuteAuthorized(ctx, expected, req, body); !errors.Is(e, g.ErrHeld) {
t.Fatal(e)
}
claim.AttemptEpoch++
claim.Owner = "worker-next"
authority.claim = claim
for i := 0; i < 2; i++ {
if _, e := gateway.Acquire(ctx, claim); !errors.Is(e, g.ErrHeld) {
t.Fatal("absent send handed over", e)
}
}
if backend.calls != 1 {
t.Fatal("control acquisition re-sent PUT")
}
var count int
if e := pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_deliveries WHERE scope=$1", gateway.Scope).Scan(&count); e != nil || count != 1 {
t.Fatal("unknown send advanced delivery", count, e)
}
// Deliver the previously uncertain request late, using its exact immutable claim.
if _, e := real.Put(ctx, req.Key, body, req.Claim()); e != nil {
t.Fatal(e)
}
next, e := gateway.Acquire(ctx, claim)
if e != nil || next.Epoch != 2 {
t.Fatal("committed send was not reconciled before handover", e)
}
receipt, e := gateway.ExecuteAuthorized(ctx, next, req, body)
if e != nil || receipt.Request != req {
t.Fatal(e)
}
if backend.calls != 1 {
t.Fatal("reconciled send was retried")
}
receipt.Request.Grant = next
cleanup(t, ctx, gateway, receipt)
t.Log("new controller attempt stayed held while absent; late committed original recovered without replay PUT")
}
+57
View File
@@ -0,0 +1,57 @@
package objectgateway
import (
"context"
"crypto/ed25519"
"encoding/json"
"os"
"time"
)
// Attestation is issued by an independent deployment auditor, never by a worker.
// Its signature authenticates an audit, not the truth of self-reported config.
// Runtime cutover must invalidate/replace the audit whenever writer rights change.
type Attestation struct {
Protocol string `json:"protocol"`
Scope string `json:"scope"`
GatewayID string `json:"gateway_id"`
IssuedAt time.Time `json:"issued_at"`
ExpiresAt time.Time `json:"expires_at"`
WriterInventory string `json:"writer_inventory_sha256"`
PolicyEvidence string `json:"policy_evidence_sha256"`
DenialEvidence string `json:"denial_evidence_sha256"`
DrainEvidence string `json:"drain_evidence_sha256"`
}
type SignedAttestation struct {
Payload json.RawMessage `json:"payload"`
Signature []byte `json:"signature"`
}
type AuditVerifier struct {
Path string
PublicKey ed25519.PublicKey
Scope, GatewayID string
}
func (v AuditVerifier) Verify(ctx context.Context) error {
if ctx.Err() != nil {
return ErrIsolation
}
st, e := os.Lstat(v.Path)
if e != nil || !st.Mode().IsRegular() || st.Size() > 16384 || st.Mode().Perm()&0022 != 0 {
return ErrIsolation
}
raw, e := os.ReadFile(v.Path)
if e != nil {
return ErrIsolation
}
var signed SignedAttestation
var a Attestation
if json.Unmarshal(raw, &signed) != nil || len(v.PublicKey) != ed25519.PublicKeySize || !ed25519.Verify(v.PublicKey, signed.Payload, signed.Signature) || json.Unmarshal(signed.Payload, &a) != nil {
return ErrIsolation
}
now := time.Now()
if a.Protocol != Protocol || a.Scope != v.Scope || a.GatewayID != v.GatewayID || a.GatewayID == "" || a.IssuedAt.After(now) || !a.ExpiresAt.After(now) || a.ExpiresAt.Sub(a.IssuedAt) > time.Hour || !validHash(a.WriterInventory) || !validHash(a.PolicyEvidence) || !validHash(a.DenialEvidence) || !validHash(a.DrainEvidence) {
return ErrIsolation
}
return nil
}
+59
View File
@@ -0,0 +1,59 @@
package objectgateway_test
import (
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/json"
g "knowledge-governance/internal/objectgateway"
"os"
"path/filepath"
"testing"
"time"
)
func TestGatewayAuditCannotBeConfigurationBoolean(t *testing.T) {
pub, priv, e := ed25519.GenerateKey(rand.Reader)
if e != nil {
t.Fatal(e)
}
dir := t.TempDir()
path := filepath.Join(dir, "audit.json")
verifier := g.AuditVerifier{Path: path, PublicKey: pub, Scope: "target", GatewayID: "gateway"}
if verifier.Verify(context.Background()) == nil {
t.Fatal("missing audit accepted")
}
if os.WriteFile(path, []byte(`{"isolated":true,"ready":true}`), 0600) != nil {
t.Fatal("fixture")
}
if verifier.Verify(context.Background()) == nil {
t.Fatal("boolean accepted as isolation proof")
}
a := g.Attestation{Protocol: g.Protocol, Scope: "target", GatewayID: "gateway", IssuedAt: time.Now().Add(-time.Minute), ExpiresAt: time.Now().Add(30 * time.Minute), WriterInventory: g.Digest([]byte("inventory")), PolicyEvidence: g.Digest([]byte("policy")), DenialEvidence: g.Digest([]byte("denials")), DrainEvidence: g.Digest([]byte("drain"))}
write := func(v g.Attestation) {
t.Helper()
raw, _ := json.Marshal(v)
signed, _ := json.Marshal(g.SignedAttestation{Payload: raw, Signature: ed25519.Sign(priv, raw)})
if os.WriteFile(path, signed, 0600) != nil {
t.Fatal("fixture")
}
}
write(a)
if verifier.Verify(context.Background()) != nil {
t.Fatal("valid test auditor signature rejected")
}
for _, mutate := range []func(*g.Attestation){func(v *g.Attestation) { v.Scope = "other" }, func(v *g.Attestation) { v.GatewayID = "other" }, func(v *g.Attestation) { v.ExpiresAt = time.Now().Add(-time.Second) }, func(v *g.Attestation) { v.DenialEvidence = "" }, func(v *g.Attestation) { v.IssuedAt = time.Now().Add(time.Hour) }, func(v *g.Attestation) { v.ExpiresAt = time.Now().Add(24 * time.Hour) }} {
bad := a
mutate(&bad)
write(bad)
if verifier.Verify(context.Background()) == nil {
t.Fatal("invalid isolation audit accepted")
}
}
write(a)
other, _, _ := ed25519.GenerateKey(rand.Reader)
verifier.PublicKey = other
if verifier.Verify(context.Background()) == nil {
t.Fatal("untrusted signer accepted")
}
}
+15
View File
@@ -0,0 +1,15 @@
package objectgateway
import "context"
type claimContextKey struct{}
// WithClaim is set by the owned-attempt runner, never from an HTTP caller's
// proposed plan. The controller independently checks every field against PG.
func WithClaim(ctx context.Context, c Claim) context.Context {
return context.WithValue(ctx, claimContextKey{}, c)
}
func ClaimFromContext(ctx context.Context) Claim {
c, _ := ctx.Value(claimContextKey{}).(Claim)
return c
}
+326
View File
@@ -0,0 +1,326 @@
package objectgateway
import (
"context"
_ "embed"
"encoding/json"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// Schema is applied explicitly by the migration identity, never on server startup.
//
//go:embed schema.sql
var Schema string
type Gateway struct {
Authority PlanAuthority
Pool *pgxpool.Pool
Scope string
Backend Backend
Isolation IsolationVerifier
MaxBytes int64
}
func (g *Gateway) Ready(ctx context.Context) error {
if g.Pool == nil || g.Scope == "" || g.Backend == nil || g.MaxBytes < 1 {
return ErrPersistence
}
if g.Isolation == nil || g.Isolation.Verify(ctx) != nil {
return ErrIsolation
}
var sync, fsync, full string
if g.Pool.QueryRow(ctx, "SELECT current_setting('synchronous_commit'), current_setting('fsync'), current_setting('full_page_writes')").Scan(&sync, &fsync, &full) != nil || sync != "on" || fsync != "on" || full != "on" {
return ErrPersistence
}
var journal bool
if g.Pool.QueryRow(ctx, `SELECT NOT pg_is_in_recovery() AND current_setting('transaction_read_only')='off'
AND to_regclass('kg_object_gateway_plans') IS NOT NULL
AND to_regclass('kg_object_gateway_scopes') IS NOT NULL
AND to_regclass('kg_object_gateway_grants') IS NOT NULL
AND to_regclass('kg_object_gateway_intents') IS NOT NULL
AND to_regclass('kg_object_gateway_receipts') IS NOT NULL
AND to_regclass('kg_object_gateway_deliveries') IS NOT NULL
AND (SELECT count(*)=10 FROM pg_trigger WHERE tgname IN ('kg_object_gateway_deliveries_immutable','kg_object_gateway_deliveries_no_truncate','kg_object_gateway_plans_no_truncate','kg_object_gateway_intents_no_truncate','kg_object_gateway_receipts_no_truncate','kg_object_gateway_grants_no_truncate','kg_object_gateway_plans_immutable','kg_object_gateway_intents_immutable','kg_object_gateway_receipts_immutable','kg_object_gateway_grants_immutable') AND tgenabled='O')`).Scan(&journal) != nil || !journal {
return ErrPersistence
}
if g.Backend.Ready(ctx) != nil {
return errors.New("gateway_backend_not_ready")
}
return nil
}
func (g *Gateway) Advance(ctx context.Context, expected int64, next Grant) error {
if !next.valid() || next.Epoch != expected+1 {
return ErrEpoch
}
if err := g.Ready(ctx); err != nil {
return err
}
var frozen []byte
var plan Plan
if g.Pool.QueryRow(ctx, "SELECT body FROM kg_object_gateway_plans WHERE scope=$1 AND plan=$2", g.Scope, next.Plan).Scan(&frozen) != nil {
return ErrConflict
}
if json.Unmarshal(frozen, &plan) != nil || !plan.valid() || plan.Owner != next.Owner {
return ErrConflict
}
tx, err := g.Pool.Begin(ctx)
if err != nil {
return ErrPersistence
}
defer tx.Rollback(ctx)
if _, err = tx.Exec(ctx, "INSERT INTO kg_object_gateway_scopes(scope) VALUES($1) ON CONFLICT DO NOTHING", g.Scope); err != nil {
return ErrPersistence
}
var epoch int64
if tx.QueryRow(ctx, "SELECT epoch FROM kg_object_gateway_scopes WHERE scope=$1 FOR UPDATE", g.Scope).Scan(&epoch) != nil {
return ErrPersistence
}
if err = g.advanceLocked(ctx, tx, epoch, next); err != nil {
return err
}
if tx.Commit(ctx) != nil {
return ErrPersistence
}
return nil
}
func (g *Gateway) advanceLocked(ctx context.Context, tx pgx.Tx, epoch int64, next Grant) error {
var err error
if epoch == next.Epoch {
var owner, plan string
if tx.QueryRow(ctx, "SELECT owner,plan FROM kg_object_gateway_grants WHERE scope=$1 AND epoch=$2", g.Scope, epoch).Scan(&owner, &plan) != nil {
return ErrPersistence
}
if owner != next.Owner || plan != next.Plan {
return ErrEpoch
}
return nil
}
if epoch != next.Epoch-1 {
return ErrEpoch
}
var pending bool
if tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM kg_object_gateway_intents i WHERE i.scope=$1 AND NOT EXISTS(SELECT 1 FROM kg_object_gateway_receipts r WHERE r.scope=i.scope AND r.operation=i.operation))`, g.Scope).Scan(&pending) != nil {
return ErrPersistence
}
if pending {
return ErrHeld
}
if _, err = tx.Exec(ctx, "INSERT INTO kg_object_gateway_grants(scope,epoch,owner,plan) VALUES($1,$2,$3,$4)", g.Scope, next.Epoch, next.Owner, next.Plan); err != nil {
return ErrPersistence
}
if _, err = tx.Exec(ctx, "UPDATE kg_object_gateway_scopes SET epoch=$2 WHERE scope=$1", g.Scope, next.Epoch); err != nil {
return ErrPersistence
}
return nil
}
// reserve commits an immutable may-send intent. Even a commit timeout cannot be
// followed by a send. Another process can reconcile, but cannot retry this PUT.
func (g *Gateway) reserve(ctx context.Context, r Request, authorization *Grant) (bool, error) {
tx, err := g.Pool.Begin(ctx)
if err != nil {
return false, ErrPersistence
}
defer tx.Rollback(ctx)
var epoch int64
if tx.QueryRow(ctx, "SELECT epoch FROM kg_object_gateway_scopes WHERE scope=$1 FOR UPDATE", g.Scope).Scan(&epoch) != nil {
return false, ErrEpoch
}
if authorization != nil {
var owner, plan string
if epoch != authorization.Epoch {
return false, ErrEpoch
}
if tx.QueryRow(ctx, "SELECT owner,plan FROM kg_object_gateway_grants WHERE scope=$1 AND epoch=$2", g.Scope, epoch).Scan(&owner, &plan) != nil {
return false, ErrPersistence
}
if owner != authorization.Owner || plan != authorization.Plan {
return false, ErrEpoch
}
}
raw, _ := json.Marshal(r)
var previous []byte
err = tx.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", g.Scope, r.Operation).Scan(&previous)
if err == nil {
if string(previous) != string(raw) {
return false, ErrConflict
}
return false, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
return false, ErrPersistence
}
var owner, plan string
if epoch != r.Grant.Epoch {
return false, ErrEpoch
}
if tx.QueryRow(ctx, "SELECT owner,plan FROM kg_object_gateway_grants WHERE scope=$1 AND epoch=$2", g.Scope, epoch).Scan(&owner, &plan) != nil {
return false, ErrPersistence
}
if owner != r.Grant.Owner || plan != r.Grant.Plan {
return false, ErrEpoch
}
var pending bool
if tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM kg_object_gateway_intents i WHERE i.scope=$1 AND i.key=$2 AND NOT EXISTS(SELECT 1 FROM kg_object_gateway_receipts x WHERE x.scope=i.scope AND x.operation=i.operation))`, g.Scope, r.Key).Scan(&pending) != nil {
return false, ErrPersistence
}
if pending {
return false, ErrHeld
}
var frozen []byte
var allowed Plan
if tx.QueryRow(ctx, "SELECT body FROM kg_object_gateway_plans WHERE scope=$1 AND plan=$2", g.Scope, r.Grant.Plan).Scan(&frozen) != nil {
return false, ErrPersistence
}
if json.Unmarshal(frozen, &allowed) != nil || !allowed.valid() || !allowed.allows(r) {
return false, ErrConflict
}
if r.Action == "delete" {
previous, err := g.receipt(ctx, r.CreatedBy)
if err != nil || previous.State != "committed" || previous.Request.Key != r.Key || previous.Version != r.Version {
return false, ErrConflict
}
}
if _, err = tx.Exec(ctx, "INSERT INTO kg_object_gateway_intents(scope,operation,key,request) VALUES($1,$2,$3,$4)", g.Scope, r.Operation, r.Key, raw); err != nil {
return false, ErrPersistence
}
if tx.Commit(ctx) != nil {
return false, ErrPersistence
}
return true, nil
}
func (g *Gateway) receipt(ctx context.Context, id string) (Receipt, error) {
var raw []byte
var r Receipt
err := g.Pool.QueryRow(ctx, "SELECT receipt FROM kg_object_gateway_receipts WHERE scope=$1 AND operation=$2", g.Scope, id).Scan(&raw)
if err != nil {
return r, err
}
if json.Unmarshal(raw, &r) != nil {
return r, ErrPersistence
}
return r, nil
}
func (g *Gateway) finish(ctx context.Context, r Request, state string, v Version) (Receipt, error) {
receipt := Receipt{r, state, v}
raw, _ := json.Marshal(receipt)
_, err := g.Pool.Exec(ctx, "INSERT INTO kg_object_gateway_receipts(scope,operation,receipt) VALUES($1,$2,$3) ON CONFLICT DO NOTHING", g.Scope, r.Operation, raw)
if err != nil {
return Receipt{}, ErrPersistence
}
got, err := g.receipt(ctx, r.Operation)
if err != nil {
return Receipt{}, ErrPersistence
}
if got != receipt {
return Receipt{}, ErrConflict
}
return got, nil
}
func (g *Gateway) Execute(ctx context.Context, r Request, body []byte) (Receipt, error) {
return g.execute(ctx, r, body, nil)
}
func (g *Gateway) execute(ctx context.Context, r Request, body []byte, authorization *Grant) (Receipt, error) {
if err := r.validate(); err != nil {
return Receipt{}, err
}
if r.Bytes > g.MaxBytes || r.Action == "create" && (int64(len(body)) != r.Bytes || Digest(body) != r.SHA256) || r.Action == "delete" && len(body) != 0 {
return Receipt{}, ErrConflict
}
if err := g.Ready(ctx); err != nil {
return Receipt{}, err
}
fresh, err := g.reserve(ctx, r, authorization)
if err != nil {
return Receipt{}, err
}
if !fresh {
return g.Reconcile(ctx, r)
}
if r.Action == "create" {
_, exists, err := g.Backend.Observe(ctx, r.Key, "")
if err != nil {
return Receipt{}, ErrHeld
}
if exists {
return g.finish(ctx, r, "rejected", Version{})
}
v, err := g.Backend.Put(ctx, r.Key, body, r.token())
if err != nil {
return Receipt{}, ErrHeld
}
exact, exists, err := g.Backend.Observe(ctx, r.Key, v.ID)
if err != nil || !exists || !r.matches(exact) || v != exact {
return Receipt{}, ErrHeld
}
return g.finish(ctx, r, "committed", v)
}
v, exists, err := g.Backend.Observe(ctx, r.Key, r.Version.ID)
if err != nil {
return Receipt{}, ErrHeld
}
if exists && v != r.Version {
return Receipt{}, ErrConflict
}
if exists {
if g.Backend.Delete(ctx, r.Key, r.Version) != nil {
return Receipt{}, ErrHeld
}
}
return g.Reconcile(ctx, r)
}
func (g *Gateway) Reconcile(ctx context.Context, r Request) (Receipt, error) {
if err := r.validate(); err != nil {
return Receipt{}, err
}
if err := g.Ready(ctx); err != nil {
return Receipt{}, err
}
var raw []byte
if g.Pool.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", g.Scope, r.Operation).Scan(&raw) != nil {
return Receipt{}, ErrConflict
}
want, _ := json.Marshal(r)
if string(raw) != string(want) {
return Receipt{}, ErrConflict
}
got, err := g.receipt(ctx, r.Operation)
if err == nil {
return got, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
return Receipt{}, ErrPersistence
}
if r.Action == "delete" {
_, exists, err := g.Backend.Observe(ctx, r.Key, r.Version.ID)
if err != nil || exists {
return Receipt{}, ErrHeld
}
return g.finish(ctx, r, "removed", r.Version)
}
versions, err := g.Backend.List(ctx, r.Key)
if err != nil {
return Receipt{}, ErrHeld
}
var found []Version
for _, v := range versions {
if v.Owner == r.token() {
if !r.matches(v) {
return Receipt{}, ErrHeld
}
found = append(found, v)
}
}
if len(found) != 1 {
return Receipt{}, ErrHeld
}
exact, exists, err := g.Backend.Observe(ctx, r.Key, found[0].ID)
if err != nil || !exists || exact != found[0] {
return Receipt{}, ErrHeld
}
return g.finish(ctx, r, "committed", exact)
}
@@ -0,0 +1,399 @@
package objectgateway_test
import (
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/jackc/pgx/v5/pgxpool"
g "knowledge-governance/internal/objectgateway"
)
type verifiedFixture struct{}
func (verifiedFixture) Verify(context.Context) error { return nil }
func fixture(t *testing.T) (context.Context, *pgxpool.Pool, *g.S3Backend) {
t.Helper()
dsn := os.Getenv("KG_GATEWAY_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("isolated gateway PG/MinIO opt-in required")
}
u, e := url.Parse(dsn)
if e != nil || !strings.HasPrefix(strings.TrimPrefix(u.Path, "/"), "kg_library_test_gateway_") || u.Hostname() != "127.0.0.1" {
t.Fatal("unsafe gateway test database")
}
ctx := context.Background()
pool, e := pgxpool.New(ctx, dsn)
if e != nil {
t.Fatal("PG unavailable")
}
t.Cleanup(pool.Close)
if _, e = pool.Exec(ctx, g.Schema); e != nil {
t.Fatal(e)
}
endpoint := os.Getenv("KG_GATEWAY_TEST_ENDPOINT")
if endpoint != "http://127.0.0.1:19100" {
t.Fatal("unsafe test MinIO endpoint")
}
bucket := "kg-library-test-gateway-" + g.Digest([]byte(t.Name() + time.Now().String()))[:16]
client := s3.New(s3.Options{Region: "us-east-1", BaseEndpoint: aws.String(endpoint), UsePathStyle: true, Credentials: credentials.NewStaticCredentialsProvider(os.Getenv("KG_GATEWAY_TEST_ACCESS_KEY"), os.Getenv("KG_GATEWAY_TEST_SECRET_KEY"), "")})
if _, e = client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(bucket)}); e != nil {
t.Fatal("create isolated bucket failed")
}
if _, e = client.PutBucketVersioning(ctx, &s3.PutBucketVersioningInput{Bucket: aws.String(bucket), VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusEnabled}}); e != nil {
t.Fatal(e)
}
t.Cleanup(func() {
list, e := client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(bucket)})
if e != nil {
t.Error("residue list unavailable")
return
}
if len(list.Versions) != 0 || len(list.DeleteMarkers) != 0 {
t.Errorf("preserving residue bucket %s: versions=%d markers=%d", bucket, len(list.Versions), len(list.DeleteMarkers))
return
}
if _, e = client.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(bucket)}); e != nil {
t.Error("delete empty test bucket failed")
}
t.Logf("exact sandbox %s: versions=0 markers=0; empty bucket deleted", bucket)
})
return ctx, pool, &g.S3Backend{Client: client, Bucket: bucket, MaxBytes: 1 << 20}
}
func planFor(grant g.Grant, requests ...g.Request) g.Plan {
p := g.Plan{Digest: grant.Plan, Owner: grant.Owner}
for _, r := range requests {
p.Objects = append(p.Objects, g.ObjectBinding{Operation: r.Operation, Key: r.Key, SHA256: r.SHA256, Bytes: r.Bytes})
}
return p
}
func request(label string, grant g.Grant) g.Request {
body := []byte("gateway fixture " + label)
return g.Request{Grant: grant, Operation: g.Digest([]byte(label)), Key: "unchanged/" + label, Action: "create", SHA256: g.Digest(body), Bytes: int64(len(body))}
}
func cleanup(t *testing.T, ctx context.Context, gw *g.Gateway, receipt g.Receipt) {
t.Helper()
r := receipt.Request
r.Operation = g.Digest([]byte(r.Operation + "delete"))
r.Action = "delete"
r.CreatedBy = receipt.Request.Operation
r.Version = receipt.Version
if got, e := gw.Execute(ctx, r, nil); e != nil || got.State != "removed" {
t.Fatalf("exact cleanup: %v %s", e, got.State)
}
}
func TestGatewayReadinessRequiresJournal(t *testing.T) {
ctx, pool, backend := fixture(t)
// An isolated search_path lacks the journal while PG settings remain healthy.
conn, e := pool.Acquire(ctx)
if e != nil {
t.Fatal(e)
}
conn.Release()
cfg := pool.Config()
cfg.ConnConfig.RuntimeParams["search_path"] = "pg_catalog"
other, e := pgxpool.NewWithConfig(ctx, cfg)
if e != nil {
t.Fatal(e)
}
defer other.Close()
gw := &g.Gateway{Pool: other, Scope: "missing-journal", Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
if e := gw.Ready(ctx); !errors.Is(e, g.ErrPersistence) {
t.Fatalf("missing durable journal accepted: %v", e)
}
}
func TestGatewayRealReplayAndImmutableLedger(t *testing.T) {
ctx, pool, backend := fixture(t)
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("fixed-plan"))}
gw := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
if _, exists, err := backend.Observe(ctx, "missing-key-probe", ""); err != nil || exists {
t.Fatalf("initial authoritative absence unavailable: %v exists=%v", err, exists)
}
if e := gw.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
t.Fatal(e)
}
if e := gw.Advance(ctx, 0, grant); e != nil {
t.Fatal(e)
}
req := request(t.Name(), grant)
body := []byte("gateway fixture " + t.Name())
one, e := gw.Execute(ctx, req, body)
if e != nil || one.State != "committed" {
t.Fatalf("create %v %s", e, one.State)
}
two, e := gw.Execute(ctx, req, body)
if e != nil || two != one {
t.Fatal("replay changed receipt", e)
}
bad := req
bad.Key += "-different"
if _, e = gw.Execute(ctx, bad, body); !errors.Is(e, g.ErrConflict) {
t.Fatal("operation rebound", e)
}
for _, table := range []string{"intents", "receipts", "grants", "plans"} {
if _, e = pool.Exec(ctx, "DELETE FROM kg_object_gateway_"+table+" WHERE scope=$1", gw.Scope); e == nil {
t.Fatal("immutable evidence deleted", table)
}
}
for _, table := range []string{"plans", "intents", "receipts", "grants"} {
tx, e := pool.Begin(ctx)
if e != nil {
t.Fatal(e)
}
_, e = tx.Exec(ctx, "TRUNCATE kg_object_gateway_"+table+" CASCADE")
_ = tx.Rollback(ctx)
if e == nil {
cleanup(t, ctx, gw, one)
t.Fatal("immutable evidence truncation accepted", table)
}
}
cleanup(t, ctx, gw, one)
next := grant
next.Epoch = 2
if e = gw.Advance(ctx, 1, next); e != nil {
t.Fatal(e)
}
late := request("late", grant)
if _, e = gw.Execute(ctx, late, []byte("gateway fixture late")); !errors.Is(e, g.ErrEpoch) {
t.Fatal("old epoch sent", e)
}
}
func signedAudit(t *testing.T, scope string) (string, string) {
t.Helper()
pub, priv, e := ed25519.GenerateKey(rand.Reader)
if e != nil {
t.Fatal(e)
}
// This is a test authority. It exercises verification, NOT production exclusivity.
a := g.Attestation{Protocol: g.Protocol, Scope: scope, GatewayID: "isolated-fixture", IssuedAt: time.Now().Add(-time.Minute), ExpiresAt: time.Now().Add(30 * time.Minute), WriterInventory: g.Digest([]byte("fixture inventory")), PolicyEvidence: g.Digest([]byte("fixture policy")), DenialEvidence: g.Digest([]byte("fixture denial")), DrainEvidence: g.Digest([]byte("fixture drain"))}
raw, _ := json.Marshal(a)
signed, _ := json.Marshal(g.SignedAttestation{Payload: raw, Signature: ed25519.Sign(priv, raw)})
path := filepath.Join(t.TempDir(), "audit.json")
if os.WriteFile(path, signed, 0600) != nil {
t.Fatal("audit write failed")
}
return path, base64.StdEncoding.EncodeToString(pub)
}
func startGateway(t *testing.T, env []string, client *g.Client) *exec.Cmd {
t.Helper()
binary := os.Getenv("KG_GATEWAY_TEST_BINARY")
if binary == "" {
t.Fatal("actual gateway binary is required")
}
cmd := exec.Command(binary)
cmd.Env = env
log, e := os.Create(filepath.Join(t.TempDir(), "service.log"))
if e != nil {
t.Fatal(e)
}
cmd.Stdout = log
cmd.Stderr = log
if e = cmd.Start(); e != nil {
t.Fatal(e)
}
t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait(); _ = log.Close() })
for i := 0; i < 100; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
e = client.Ready(ctx)
cancel()
if e == nil {
return cmd
}
time.Sleep(30 * time.Millisecond)
}
raw, _ := os.ReadFile(log.Name())
t.Fatalf("actual gateway not ready: %s", raw)
return nil
}
func TestGatewayActualServiceTwoInterruptions(t *testing.T) {
ctx, pool, backend := fixture(t)
upstream, _ := url.Parse(os.Getenv("KG_GATEWAY_TEST_ENDPOINT"))
proxy := httputil.NewSingleHostReverseProxy(upstream)
beforeSend := make(chan struct{}, 2)
allowSend := make(chan struct{}, 2)
committed := make(chan struct{}, 2)
release := make(chan struct{}, 2)
var puts atomic.Int32
proxy.ModifyResponse = func(resp *http.Response) error {
if resp.Request.Method == "PUT" && !strings.Contains(resp.Request.URL.RawQuery, "versioning") {
puts.Add(1)
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
committed <- struct{}{}
select {
case <-release:
case <-resp.Request.Context().Done():
}
return errors.New("injected lost response after actual MinIO commit")
}
}
return nil
}
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) { http.Error(w, "injected_transport_loss", 502) }
p := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "PUT" && !strings.Contains(r.URL.RawQuery, "versioning") {
beforeSend <- struct{}{}
select {
case <-allowSend:
case <-r.Context().Done():
return
}
}
proxy.ServeHTTP(w, r)
}))
defer p.Close()
scope := g.Digest([]byte("minio\x00" + p.URL + "\x00" + backend.Bucket))
audit, pub := signedAudit(t, scope)
listener, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal(e)
}
addr := listener.Addr().String()
listener.Close()
data := g.Digest([]byte("data " + scope))
control := g.Digest([]byte("control " + scope))
client, e := g.NewClient("http://"+addr, data, scope)
if e != nil {
t.Fatal(e)
}
admin, _ := g.NewClient("http://"+addr, control, scope)
env := append(os.Environ(), "OBJECT_GATEWAY_LISTEN="+addr, "OBJECT_GATEWAY_DATABASE_URL="+os.Getenv("KG_GATEWAY_TEST_DATABASE_URL"), "OBJECT_GATEWAY_PROVIDER=minio", "OBJECT_GATEWAY_ENDPOINT="+p.URL, "OBJECT_GATEWAY_BUCKET="+backend.Bucket, "OBJECT_GATEWAY_ACCESS_KEY="+os.Getenv("KG_GATEWAY_TEST_ACCESS_KEY"), "OBJECT_GATEWAY_SECRET_KEY="+os.Getenv("KG_GATEWAY_TEST_SECRET_KEY"), "OBJECT_GATEWAY_AUDIT_PUBLIC_KEY="+pub, "OBJECT_GATEWAY_AUDIT_FILE="+audit, "OBJECT_GATEWAY_ID=isolated-fixture", "OBJECT_GATEWAY_DATA_TOKEN="+data, "OBJECT_GATEWAY_CONTROL_TOKEN="+control)
cmd := startGateway(t, env, client)
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte("actual-worker")), Plan: g.Digest([]byte("frozen-actual-plan"))}
if e = client.InstallPlan(ctx, planFor(grant, request("actual-0", grant))); e == nil {
t.Fatal("data client installed plan")
}
if e = admin.InstallPlan(ctx, planFor(grant, request("actual-0", grant), request("actual-1", grant))); e != nil {
t.Fatal(e)
}
if e = admin.Advance(ctx, 0, grant); e != nil {
t.Fatal(e)
}
if e = client.Advance(ctx, 0, grant); e == nil {
t.Fatal("data client acquired control authority")
}
for iteration := 0; iteration < 2; iteration++ {
label := fmt.Sprintf("actual-%d", iteration)
r := request(label, grant)
body := []byte("gateway fixture " + label)
done := make(chan error, 1)
go func() { _, e := client.Execute(ctx, r, body); done <- e }()
select {
case <-beforeSend:
case <-time.After(15 * time.Second):
t.Fatal("gateway did not send to proxy")
}
if _, e = client.Reconcile(ctx, r); !errors.Is(e, g.ErrHeld) {
t.Fatal("not-yet-visible PUT treated as terminal", e)
}
blockedNext := grant
blockedNext.Epoch++
if e = admin.Advance(ctx, grant.Epoch, blockedNext); !errors.Is(e, g.ErrHeld) {
t.Fatal("epoch crossed delayed precommit request", e)
}
allowSend <- struct{}{}
select {
case <-committed:
case <-time.After(15 * time.Second):
t.Fatal("actual MinIO PUT did not commit")
}
next := grant
next.Epoch++
if e = admin.Advance(ctx, grant.Epoch, next); !errors.Is(e, g.ErrHeld) {
t.Fatal("epoch crossed in-flight write", e)
}
sameKey := r
sameKey.Operation = g.Digest([]byte(label + "other"))
if _, e = client.Execute(ctx, sameKey, body); !errors.Is(e, g.ErrHeld) {
t.Fatal("same-key competitor admitted", e)
}
if e = cmd.Process.Kill(); e != nil {
t.Fatal(e)
}
_ = cmd.Wait()
release <- struct{}{}
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("dead gateway call did not end")
}
t.Logf("actual gateway SIGKILL %d after MinIO commit before receipt", iteration+1)
cmd = startGateway(t, env, client)
receipt, e := client.Reconcile(ctx, r)
if e != nil || receipt.State != "committed" {
t.Fatalf("restart reconcile %v %s", e, receipt.State)
}
repeated, e := client.Execute(ctx, r, body)
if e != nil || receipt != repeated {
t.Fatal("restart duplicate not idempotent", e)
}
del := r
del.Action = "delete"
del.CreatedBy = r.Operation
del.Operation = g.Digest([]byte(label + "cleanup"))
del.Version = receipt.Version
cleaned, e := client.Execute(ctx, del, nil)
if e != nil || cleaned.State != "removed" {
t.Fatal("actual exact cleanup failed", e)
}
if e = admin.Advance(ctx, grant.Epoch, next); e != nil {
t.Fatal(e)
}
late := request(label+"late", grant)
if _, e = client.Execute(ctx, late, []byte("gateway fixture "+label+"late")); !errors.Is(e, g.ErrEpoch) {
t.Fatal("late stale epoch admitted", e)
}
grant = next
}
if puts.Load() != 2 {
t.Fatalf("blind PUT replay count=%d", puts.Load())
}
var n int
if pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_receipts WHERE scope=$1", scope).Scan(&n) != nil || n != 4 {
t.Fatalf("durable receipts=%d", n)
}
_ = cmd.Process.Kill()
_ = cmd.Wait()
if e = client.Ready(ctx); e == nil {
t.Fatal("unavailable gateway accepted")
}
t.Log("actual binary + HTTP + durable PG + MinIO: two kills/restarts, 2 PUTs, 4 receipts, exact cleanup")
}
func TestGatewayClientRejectsBadProtocolAndLeaks(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("secret") != "" {
t.Error("secret in URL")
}
_, _ = io.WriteString(w, `{"protocol":"other","scope":"scope","ready":true}`)
}))
defer server.Close()
c, e := g.NewClient(server.URL, strings.Repeat("x", 32), "scope")
if e != nil {
t.Fatal(e)
}
if c.Ready(context.Background()) == nil {
t.Fatal("wrong protocol accepted")
}
}
+316
View File
@@ -0,0 +1,316 @@
package objectgateway
import (
"bytes"
"context"
"crypto/subtle"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strings"
"time"
)
type ExecuteRequest struct {
Authorization *Grant `json:"authorization,omitempty"`
Request Request `json:"request"`
Body []byte `json:"body,omitempty"`
}
type AdvanceRequest struct {
Expected int64 `json:"expected"`
Grant Grant `json:"grant"`
}
type Capabilities struct {
AutomaticGrants bool `json:"automatic_grants"`
Protocol string `json:"protocol"`
Scope string `json:"scope"`
Ready bool `json:"ready"`
}
type HTTPServer struct {
Gateway *Gateway
DataToken, ControlToken string
}
func (s HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
token := s.DataToken
if r.URL.Path == "/v1/advance" || r.URL.Path == "/v1/plans" {
token = s.ControlToken
}
if len(token) < 32 || s.DataToken == s.ControlToken || subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+token)) != 1 {
http.Error(w, "gateway_unauthorized", 401)
return
}
if r.Header.Get("X-KG-Gateway-Protocol") != Protocol || r.Header.Get("X-KG-Gateway-Scope") != s.Gateway.Scope {
http.Error(w, "gateway_protocol_or_target_mismatch", 409)
return
}
fail := func(e error) {
code := 503
if errors.Is(e, ErrEpoch) || errors.Is(e, ErrConflict) || errors.Is(e, ErrHeld) {
code = 409
}
http.Error(w, e.Error(), code)
}
decode := func(v any) bool {
r.Body = http.MaxBytesReader(w, r.Body, s.Gateway.MaxBytes*2+16384)
d := json.NewDecoder(r.Body)
d.DisallowUnknownFields()
if d.Decode(v) != nil || d.Decode(&struct{}{}) != io.EOF {
http.Error(w, "gateway_bad_request", 400)
return false
}
return true
}
if r.Method == "GET" && r.URL.Path == "/v1/capabilities" {
if e := s.Gateway.Ready(r.Context()); e != nil {
fail(e)
return
}
if authority, ok := s.Gateway.Authority.(interface{ Ready(context.Context) error }); ok {
if e := authority.Ready(r.Context()); e != nil {
fail(e)
return
}
}
_ = json.NewEncoder(w).Encode(Capabilities{Protocol: Protocol, Scope: s.Gateway.Scope, Ready: true, AutomaticGrants: s.Gateway.Authority != nil})
return
}
if r.Method != "POST" {
http.Error(w, "gateway_route_not_found", 404)
return
}
switch r.URL.Path {
case "/v1/acquire":
var in Claim
if !decode(&in) {
return
}
out, e := s.Gateway.Acquire(r.Context(), in)
if e != nil {
fail(e)
return
}
_ = json.NewEncoder(w).Encode(out)
case "/v1/plans":
if s.Gateway.Authority != nil {
fail(ErrConflict)
return
}
var in Plan
if !decode(&in) {
return
}
if e := s.Gateway.InstallPlan(r.Context(), in); e != nil {
fail(e)
return
}
_ = json.NewEncoder(w).Encode(in)
case "/v1/advance":
if s.Gateway.Authority != nil {
fail(ErrConflict)
return
}
var in AdvanceRequest
if !decode(&in) {
return
}
if e := s.Gateway.Advance(r.Context(), in.Expected, in.Grant); e != nil {
fail(e)
return
}
_ = json.NewEncoder(w).Encode(in)
case "/v1/execute", "/v1/reconcile":
var in ExecuteRequest
if !decode(&in) {
return
}
var out Receipt
var e error
if r.URL.Path == "/v1/execute" {
if in.Authorization != nil {
out, e = s.Gateway.ExecuteAuthorized(r.Context(), *in.Authorization, in.Request, in.Body)
} else {
out, e = s.Gateway.Execute(r.Context(), in.Request, in.Body)
}
} else {
out, e = s.Gateway.Reconcile(r.Context(), in.Request)
}
if e != nil {
fail(e)
return
}
_ = json.NewEncoder(w).Encode(out)
case "/v1/resolve":
var in Request
if !decode(&in) {
return
}
out, e := s.Gateway.Resolve(r.Context(), in)
if e != nil {
fail(e)
return
}
_ = json.NewEncoder(w).Encode(out)
case "/v1/observe":
var in struct {
Key string `json:"key"`
Version string `json:"version"`
}
if !decode(&in) {
return
}
if in.Key == "" {
http.Error(w, "gateway_bad_key", 400)
return
}
if e := s.Gateway.Ready(r.Context()); e != nil {
fail(e)
return
}
v, exists, e := s.Gateway.Backend.Observe(r.Context(), in.Key, in.Version)
if e != nil {
http.Error(w, "gateway_backend_read_failed", 503)
return
}
_ = json.NewEncoder(w).Encode(struct {
Version Version `json:"version"`
Exists bool `json:"exists"`
}{v, exists})
default:
http.Error(w, "gateway_route_not_found", 404)
}
}
type Client struct {
Endpoint, Token, Scope string
HTTP *http.Client
}
func NewClient(endpoint, token, scope string) (*Client, error) {
u, e := url.Parse(endpoint)
if e != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Path != "" || len(token) < 32 || scope == "" {
return nil, errors.New("gateway_configuration_invalid")
}
if u.Scheme != "https" && (u.Scheme != "http" || (u.Hostname() != "127.0.0.1" && u.Hostname() != "::1")) {
return nil, errors.New("gateway_transport_requires_tls")
}
return &Client{endpoint, token, scope, &http.Client{Timeout: 2 * time.Minute, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("gateway_redirect_refused") }}}, nil
}
func (c *Client) call(ctx context.Context, path string, in, out any) error {
method := "GET"
var body io.Reader
if in != nil {
raw, e := json.Marshal(in)
if e != nil {
return ErrConflict
}
method = "POST"
body = struct{ io.Reader }{bytes.NewReader(raw)}
}
req, e := http.NewRequestWithContext(ctx, method, c.Endpoint+path, body)
if e != nil {
return errors.New("gateway_request_invalid")
}
req.Header.Set("Authorization", "Bearer "+c.Token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-KG-Gateway-Protocol", Protocol)
req.Header.Set("X-KG-Gateway-Scope", c.Scope)
resp, e := c.HTTP.Do(req)
if e != nil {
return errors.New("gateway_unreachable_or_outcome_unknown")
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 128))
reason := strings.TrimSpace(string(raw))
switch reason {
case ErrAuthority.Error():
return ErrAuthority
case ErrAuthorityPrivileges.Error():
return ErrAuthorityPrivileges
case ErrEpoch.Error():
return ErrEpoch
case ErrConflict.Error():
return ErrConflict
case ErrHeld.Error():
return ErrHeld
case ErrPersistence.Error():
return ErrPersistence
case ErrIsolation.Error():
return ErrIsolation
}
return errors.New("gateway_request_refused")
}
if json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(out) != nil {
return errors.New("gateway_response_invalid")
}
return nil
}
func (c *Client) Ready(ctx context.Context) error { return c.checkReady(ctx, false) }
func (c *Client) ReadyForAcquisition(ctx context.Context) error { return c.checkReady(ctx, true) }
func (c *Client) checkReady(ctx context.Context, automatic bool) error {
var caps Capabilities
if e := c.call(ctx, "/v1/capabilities", nil, &caps); e != nil {
return e
}
if automatic && !caps.AutomaticGrants {
return ErrAuthority
}
if caps.Protocol != Protocol || caps.Scope != c.Scope || !caps.Ready {
return errors.New("gateway_protocol_or_target_mismatch")
}
return nil
}
func (c *Client) InstallPlan(ctx context.Context, p Plan) error {
var out Plan
if e := c.call(ctx, "/v1/plans", p, &out); e != nil {
return e
}
want, _ := json.Marshal(p)
got, _ := json.Marshal(out)
if string(want) != string(got) {
return ErrConflict
}
return nil
}
func (c *Client) Advance(ctx context.Context, expected int64, g Grant) error {
var out AdvanceRequest
in := AdvanceRequest{expected, g}
if e := c.call(ctx, "/v1/advance", in, &out); e != nil {
return e
}
if in != out {
return ErrConflict
}
return nil
}
func (c *Client) Execute(ctx context.Context, r Request, body []byte) (Receipt, error) {
var out Receipt
e := c.call(ctx, "/v1/execute", ExecuteRequest{Request: r, Body: body}, &out)
if e == nil && (out.Request != r || !out.valid()) {
e = ErrConflict
}
return out, e
}
func (c *Client) Reconcile(ctx context.Context, r Request) (Receipt, error) {
var out Receipt
e := c.call(ctx, "/v1/reconcile", ExecuteRequest{Request: r}, &out)
if e == nil && (out.Request != r || !out.valid()) {
e = ErrConflict
}
return out, e
}
func (c *Client) Observe(ctx context.Context, key, id string) (Version, bool, error) {
var out struct {
Version Version `json:"version"`
Exists bool `json:"exists"`
}
e := c.call(ctx, "/v1/observe", struct {
Key string `json:"key"`
Version string `json:"version"`
}{key, id}, &out)
return out.Version, out.Exists, e
}
@@ -0,0 +1,50 @@
package objectgateway_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
g "knowledge-governance/internal/objectgateway"
)
func TestGatewayTargetIdentityOnEveryCall(t *testing.T) {
ctx, pool, backend := fixture(t)
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("fixed-plan"))}
gw := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
if e := gw.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
t.Fatal(e)
}
if e := gw.Advance(ctx, 0, grant); e != nil {
t.Fatal(e)
}
token := strings.Repeat("a", 32)
server := httptest.NewServer(g.HTTPServer{Gateway: gw, DataToken: token, ControlToken: strings.Repeat("b", 32)})
defer server.Close()
wrong, _ := g.NewClient(server.URL, token, "wrong-target")
req := request(t.Name(), grant)
receipt, e := wrong.Execute(ctx, req, []byte("gateway fixture "+t.Name()))
if e == nil {
cleanup(t, ctx, gw, receipt)
t.Fatal("mutation accepted with wrong target identity")
}
var n int
if pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_intents WHERE scope=$1", gw.Scope).Scan(&n) != nil || n != 0 {
t.Fatal("wrong target wrote intent")
}
}
func TestGatewayClientRejectsIncompleteReceipt(t *testing.T) {
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte("owner")), Plan: g.Digest([]byte("plan"))}
req := request("receipt", grant)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(g.Receipt{Request: req, State: "committed"})
}))
defer server.Close()
c, _ := g.NewClient(server.URL, strings.Repeat("a", 32), "scope")
if _, e := c.Execute(context.Background(), req, []byte("gateway fixture receipt")); e == nil {
t.Fatal("committed receipt with missing exact version accepted")
}
}
@@ -0,0 +1,44 @@
package objectgateway_test
import (
"errors"
g "knowledge-governance/internal/objectgateway"
"testing"
)
func TestGatewayIntentCommitFailureNeverSends(t *testing.T) {
ctx, pool, real := fixture(t)
backend := &stoppedBeforeSend{Backend: real}
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("plan"))}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
if e := gateway.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
t.Fatal(e)
}
if e := gateway.Advance(ctx, 0, grant); e != nil {
t.Fatal(e)
}
// Deferred failure fires on COMMIT, not on INSERT. This exercises the uncertain
// persistence boundary while confirming no provider request is sent.
_, e := pool.Exec(ctx, `CREATE FUNCTION kg_gateway_fixture_commit_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected durable commit failure'; END $$;
CREATE CONSTRAINT TRIGGER kg_gateway_fixture_commit_failure AFTER INSERT ON kg_object_gateway_intents DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION kg_gateway_fixture_commit_failure()`)
if e != nil {
t.Fatal(e)
}
t.Cleanup(func() {
_, e := pool.Exec(ctx, `DROP TRIGGER kg_gateway_fixture_commit_failure ON kg_object_gateway_intents; DROP FUNCTION kg_gateway_fixture_commit_failure()`)
if e != nil {
t.Error(e)
}
})
req := request(t.Name(), grant)
if _, e = gateway.Execute(ctx, req, []byte("gateway fixture "+t.Name())); !errors.Is(e, g.ErrPersistence) {
t.Fatal("commit error not propagated", e)
}
if backend.calls != 0 {
t.Fatal("object request after failed journal commit")
}
var n int
if pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_intents WHERE scope=$1", gateway.Scope).Scan(&n) != nil || n != 0 {
t.Fatal("failed transaction left intent")
}
}
+78
View File
@@ -0,0 +1,78 @@
package objectgateway
import (
"context"
"encoding/json"
)
// Plan is frozen by the authenticated controller, not by the data client. Digest
// is the upstream write-set digest; the controller must verify that write set.
// This allowlist prevents a valid epoch from authorizing arbitrary extra keys.
type Plan struct {
Digest string `json:"digest"`
Owner string `json:"owner"`
Objects []ObjectBinding `json:"objects"`
}
type ObjectBinding struct {
Operation string `json:"operation"`
Key string `json:"key"`
SHA256 string `json:"sha256"`
Bytes int64 `json:"bytes"`
}
func (p Plan) valid() bool {
if !validHash(p.Digest) || !validHash(p.Owner) {
return false
}
keys, ops := map[string]bool{}, map[string]bool{}
for _, o := range p.Objects {
r := Request{Grant: Grant{1, p.Owner, p.Digest}, Operation: o.Operation, Key: o.Key, Action: "create", SHA256: o.SHA256, Bytes: o.Bytes}
if r.validate() != nil || keys[o.Key] || ops[o.Operation] {
return false
}
keys[o.Key] = true
ops[o.Operation] = true
}
return true
}
func (p Plan) allows(r Request) bool {
op := r.Operation
if r.Action == "delete" {
op = r.CreatedBy
}
if p.Owner != r.Grant.Owner || p.Digest != r.Grant.Plan {
return false
}
for _, o := range p.Objects {
if o.Operation == op && o.Key == r.Key && o.SHA256 == r.SHA256 && o.Bytes == r.Bytes {
return true
}
}
return false
}
func (g *Gateway) InstallPlan(ctx context.Context, p Plan) error {
if !p.valid() {
return ErrConflict
}
for _, o := range p.Objects {
if o.Bytes > g.MaxBytes {
return ErrConflict
}
}
if e := g.Ready(ctx); e != nil {
return e
}
raw, _ := json.Marshal(p)
_, e := g.Pool.Exec(ctx, "INSERT INTO kg_object_gateway_plans(scope,plan,body) VALUES($1,$2,$3) ON CONFLICT DO NOTHING", g.Scope, p.Digest, raw)
if e != nil {
return ErrPersistence
}
var found []byte
if g.Pool.QueryRow(ctx, "SELECT body FROM kg_object_gateway_plans WHERE scope=$1 AND plan=$2", g.Scope, p.Digest).Scan(&found) != nil {
return ErrPersistence
}
if string(found) != string(raw) {
return ErrConflict
}
return nil
}
@@ -0,0 +1,37 @@
package objectgateway_test
import (
"errors"
g "knowledge-governance/internal/objectgateway"
"testing"
)
func TestGatewayGrantCannotAuthorizeUnplannedKey(t *testing.T) {
ctx, pool, backend := fixture(t)
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("fixed-plan"))}
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
if e := gateway.Advance(ctx, 0, grant); !errors.Is(e, g.ErrConflict) {
t.Fatal("unregistered plan grant", e)
}
allowed := request("allowed-plan-key", grant)
plan := planFor(grant, allowed)
if e := gateway.InstallPlan(ctx, plan); e != nil {
t.Fatal(e)
}
changed := planFor(grant, request("extra-plan-key", grant))
if e := gateway.InstallPlan(ctx, changed); !errors.Is(e, g.ErrConflict) {
t.Fatal("immutable plan rebound", e)
}
if e := gateway.Advance(ctx, 0, grant); e != nil {
t.Fatal(e)
}
req := request(t.Name(), grant)
if _, e := gateway.Execute(ctx, req, []byte("gateway fixture "+t.Name())); !errors.Is(e, g.ErrConflict) {
t.Fatal("unplanned key admitted", e)
}
receipt, e := gateway.Execute(ctx, allowed, []byte("gateway fixture allowed-plan-key"))
if e != nil || receipt.State != "committed" {
t.Fatal("valid planned key refused", e)
}
cleanup(t, ctx, gateway, receipt)
}
+109
View File
@@ -0,0 +1,109 @@
// Package objectgateway implements non-preemptive object write ownership.
package objectgateway
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"strings"
)
const Protocol = "kg-object-gateway-v1"
var (
ErrHeld = errors.New("gateway_held_unresolved_intent")
ErrEpoch = errors.New("gateway_epoch_or_plan_mismatch")
ErrConflict = errors.New("gateway_identity_conflict")
ErrPersistence = errors.New("gateway_persistence_unavailable")
ErrAuthority = errors.New("gateway_control_authority_unavailable")
ErrAuthorityPrivileges = errors.New("gateway_control_reader_privileges_invalid")
ErrIsolation = errors.New("gateway_exclusive_writer_evidence_unverified")
ErrRejected = errors.New("gateway_create_rejected_existing_object")
)
type Grant struct {
Epoch int64 `json:"epoch"`
Owner string `json:"owner"`
Plan string `json:"plan"`
}
type Version struct {
ID string `json:"version_id"`
Owner string `json:"owner"`
SHA256 string `json:"sha256"`
Bytes int64 `json:"bytes"`
ETag string `json:"etag"`
}
type Request struct {
Grant Grant `json:"grant"`
Operation string `json:"operation"`
Key string `json:"key"`
Action string `json:"action"`
SHA256 string `json:"sha256"`
Bytes int64 `json:"bytes"`
CreatedBy string `json:"created_by,omitempty"`
Version Version `json:"version,omitempty"`
}
type Receipt struct {
Request Request `json:"request"`
State string `json:"state"`
Version Version `json:"version"`
}
// Backend never retries mutations. List is complete and scoped to exactly key.
// Not finding a PUT is never evidence that its request cannot still arrive.
type Backend interface {
Ready(context.Context) error
Observe(context.Context, string, string) (Version, bool, error)
List(context.Context, string) ([]Version, error)
Put(context.Context, string, []byte, string) (Version, error)
Delete(context.Context, string, Version) error
}
type IsolationVerifier interface{ Verify(context.Context) error }
func Digest(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) }
func validHash(s string) bool {
b, e := hex.DecodeString(s)
return e == nil && len(b) == 32 && strings.ToLower(s) == s
}
func (g Grant) valid() bool { return g.Epoch > 0 && validHash(g.Owner) && validHash(g.Plan) }
func (r Request) validate() error {
if !r.Grant.valid() || !validHash(r.Operation) || r.Key == "" || len(r.Key) > 2048 || strings.ContainsAny(r.Key, "\x00\r\n") || strings.HasPrefix(r.Key, "/") || !validHash(r.SHA256) || r.Bytes < 0 {
return ErrConflict
}
if r.Action != "create" && r.Action != "delete" {
return ErrConflict
}
if r.Action == "create" && (r.CreatedBy != "" || r.Version != (Version{})) {
return ErrConflict
}
if r.Action == "delete" && (!validHash(r.CreatedBy) || !validVersion(r.Version) || r.Version.SHA256 != r.SHA256 || r.Version.Bytes != r.Bytes) {
return ErrConflict
}
return nil
}
func validVersion(v Version) bool {
return v.ID != "" && v.ID != "null" && validHash(v.Owner) && validHash(v.SHA256) && v.Bytes >= 0 && v.ETag != ""
}
// Claim binds backend ownership to the complete immutable gateway request.
func (r Request) Claim() string { return r.token() }
func (r Request) token() string { raw, _ := json.Marshal(r); return Digest(raw) }
func (r Receipt) valid() bool {
if r.Request.validate() != nil {
return false
}
switch r.State {
case "committed":
return r.Request.Action == "create" && r.Request.matches(r.Version)
case "rejected":
return r.Request.Action == "create" && r.Version == (Version{})
case "removed":
return r.Request.Action == "delete" && r.Version == r.Request.Version
}
return false
}
func (r Request) matches(v Version) bool {
return validVersion(v) && v.Owner == r.token() && v.Bytes == r.Bytes && v.SHA256 == r.SHA256
}
+102
View File
@@ -0,0 +1,102 @@
package objectgateway
import (
"bytes"
"context"
"errors"
"io"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/smithy-go"
)
// S3Backend is for independently versioned S3/MinIO stores. No SDK mutation retries.
type S3Backend struct {
Client *s3.Client
Bucket string
MaxBytes int64
}
func (s *S3Backend) Ready(ctx context.Context) error {
r, e := s.Client.GetBucketVersioning(ctx, &s3.GetBucketVersioningInput{Bucket: aws.String(s.Bucket)})
if e != nil || string(r.Status) != "Enabled" {
return errors.New("gateway_backend_versioning_unverified")
}
return nil
}
func (s *S3Backend) Observe(ctx context.Context, key, id string) (Version, bool, error) {
req := &s3.GetObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key)}
if id != "" {
req.VersionId = aws.String(id)
}
got, e := s.Client.GetObject(ctx, req)
if e != nil {
var api smithy.APIError
if errors.As(e, &api) && (api.ErrorCode() == "NoSuchKey" || api.ErrorCode() == "NoSuchVersion") {
return Version{}, false, nil
}
return Version{}, false, errors.New("gateway_backend_read_failed")
}
defer got.Body.Close()
if got.ContentLength == nil || *got.ContentLength < 0 || *got.ContentLength > s.MaxBytes {
return Version{}, false, errors.New("gateway_backend_size_invalid")
}
body, e := io.ReadAll(io.LimitReader(got.Body, s.MaxBytes+1))
if e != nil || int64(len(body)) != *got.ContentLength {
return Version{}, false, errors.New("gateway_backend_body_incomplete")
}
v := Version{aws.ToString(got.VersionId), got.Metadata["kg-release-owner"], Digest(body), int64(len(body)), aws.ToString(got.ETag)}
// Existing unowned objects are observable but cannot be claimed/deleted.
if v.ID == "" || v.ID == "null" || v.ETag == "" || id != "" && v.ID != id {
return Version{}, false, errors.New("gateway_backend_version_invalid")
}
return v, true, nil
}
func (s *S3Backend) List(ctx context.Context, key string) ([]Version, error) {
got, e := s.Client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(s.Bucket), Prefix: aws.String(key), MaxKeys: aws.Int32(1000)})
if e != nil || aws.ToBool(got.IsTruncated) {
return nil, errors.New("gateway_backend_listing_incomplete")
}
var versions []Version
for _, m := range got.DeleteMarkers {
if aws.ToString(m.Key) == key {
return nil, errors.New("gateway_backend_delete_marker_conflict")
}
}
for _, v := range got.Versions {
if aws.ToString(v.Key) == key {
one, exists, e := s.Observe(ctx, key, aws.ToString(v.VersionId))
if e != nil || !exists {
return nil, errors.New("gateway_backend_listing_changed")
}
versions = append(versions, one)
}
}
return versions, nil
}
func (s *S3Backend) Put(ctx context.Context, key string, body []byte, owner string) (Version, error) {
// SDK hashing requires a seekable body. RetryMaxAttempts=1 prevents SDK
// retries; PUT carries no HTTP idempotency header or replay authorization.
reader := bytes.NewReader(body)
got, e := s.Client.PutObject(v4.SetPayloadHash(ctx, Digest(body)), &s3.PutObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key), Body: reader, ContentLength: aws.Int64(int64(len(body))), Metadata: map[string]string{"kg-release-owner": owner}}, func(o *s3.Options) { o.RetryMaxAttempts = 1 })
if e != nil || aws.ToString(got.VersionId) == "" {
return Version{}, ErrHeld
}
v, exists, e := s.Observe(ctx, key, aws.ToString(got.VersionId))
if e != nil || !exists {
return Version{}, ErrHeld
}
return v, nil
}
func (s *S3Backend) Delete(ctx context.Context, key string, v Version) error {
if !validVersion(v) {
return ErrConflict
}
_, e := s.Client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key), VersionId: aws.String(v.ID)}, func(o *s3.Options) { o.RetryMaxAttempts = 1 })
if e != nil {
return ErrHeld
}
return nil
}
+74
View File
@@ -0,0 +1,74 @@
-- Independent governance journal; never install in a WeKnora business schema.
CREATE TABLE IF NOT EXISTS kg_object_gateway_plans (
scope text NOT NULL,
plan text NOT NULL,
body bytea NOT NULL,
PRIMARY KEY(scope,plan)
);
CREATE TABLE IF NOT EXISTS kg_object_gateway_scopes (
scope text PRIMARY KEY,
epoch bigint NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS kg_object_gateway_grants (
scope text NOT NULL REFERENCES kg_object_gateway_scopes(scope),
epoch bigint NOT NULL CHECK (epoch > 0),
owner text NOT NULL,
plan text NOT NULL,
PRIMARY KEY(scope,epoch)
);
CREATE TABLE IF NOT EXISTS kg_object_gateway_intents (
scope text NOT NULL REFERENCES kg_object_gateway_scopes(scope),
operation text NOT NULL,
key text NOT NULL,
request bytea NOT NULL,
recorded_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY(scope,operation)
);
CREATE INDEX IF NOT EXISTS kg_object_gateway_key ON kg_object_gateway_intents(scope,key);
CREATE TABLE IF NOT EXISTS kg_object_gateway_receipts (
scope text NOT NULL,
operation text NOT NULL,
receipt bytea NOT NULL,
recorded_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY(scope,operation),
FOREIGN KEY(scope,operation) REFERENCES kg_object_gateway_intents(scope,operation)
);
CREATE TABLE IF NOT EXISTS kg_object_gateway_deliveries (
scope text NOT NULL,
job text NOT NULL,
attempt_epoch bigint NOT NULL CHECK(attempt_epoch>0),
claim bytea NOT NULL,
grant_epoch bigint NOT NULL,
grant_body bytea NOT NULL,
PRIMARY KEY(scope,job,attempt_epoch),
FOREIGN KEY(scope,grant_epoch) REFERENCES kg_object_gateway_grants(scope,epoch)
);
CREATE OR REPLACE FUNCTION kg_object_gateway_immutable() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'object gateway evidence is immutable';
END;
$$;
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_deliveries_immutable') THEN
CREATE TRIGGER kg_object_gateway_deliveries_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_deliveries FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable();
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_plans_immutable') THEN
CREATE TRIGGER kg_object_gateway_plans_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_plans FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable();
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_intents_immutable') THEN
CREATE TRIGGER kg_object_gateway_intents_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_intents FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable();
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_receipts_immutable') THEN
CREATE TRIGGER kg_object_gateway_receipts_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_receipts FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable();
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_grants_immutable') THEN
CREATE TRIGGER kg_object_gateway_grants_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_grants FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable();
END IF;
END $$;
DO $$ DECLARE t text; BEGIN
FOREACH t IN ARRAY ARRAY['plans','grants','intents','receipts','deliveries'] LOOP
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_'||t||'_no_truncate') THEN
EXECUTE format('CREATE TRIGGER %I BEFORE TRUNCATE ON %I FOR EACH STATEMENT EXECUTE FUNCTION kg_object_gateway_immutable()', 'kg_object_gateway_'||t||'_no_truncate', 'kg_object_gateway_'||t);
END IF;
END LOOP;
END $$;
+60
View File
@@ -0,0 +1,60 @@
package objectgateway
import (
"context"
"encoding/json"
"errors"
"github.com/jackc/pgx/v5"
)
// Resolve preserves the immutable send epoch and backend claim of an operation.
// An absent intent is not a claim about an earlier send; Execute still reserves
// atomically and refuses stale authorizations before any new side effect.
func (g *Gateway) Resolve(ctx context.Context, desired Request) (Request, error) {
if e := desired.validate(); e != nil {
return Request{}, e
}
if e := g.Ready(ctx); e != nil {
return Request{}, e
}
var raw []byte
e := g.Pool.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", g.Scope, desired.Operation).Scan(&raw)
if errors.Is(e, pgx.ErrNoRows) {
return desired, nil
}
if e != nil {
return Request{}, ErrPersistence
}
var original Request
if json.Unmarshal(raw, &original) != nil || original.validate() != nil {
return Request{}, ErrPersistence
}
if !sameOperation(original, desired) || original.Grant.Epoch > desired.Grant.Epoch {
return Request{}, ErrConflict
}
return original, nil
}
func sameOperation(a, b Request) bool { a.Grant.Epoch = b.Grant.Epoch; return a == b }
func (g *Gateway) ExecuteAuthorized(ctx context.Context, authorization Grant, r Request, body []byte) (Receipt, error) {
if !authorization.valid() || authorization.Owner != r.Grant.Owner || authorization.Plan != r.Grant.Plan || authorization.Epoch < r.Grant.Epoch {
return Receipt{}, ErrEpoch
}
return g.execute(ctx, r, body, &authorization)
}
func (c *Client) ExecuteAuthorized(ctx context.Context, authorization Grant, r Request, body []byte) (Receipt, error) {
var out Receipt
e := c.call(ctx, "/v1/execute", ExecuteRequest{Request: r, Body: body, Authorization: &authorization}, &out)
if e == nil && (out.Request != r || !out.valid()) {
e = ErrConflict
}
return out, e
}
func (c *Client) Resolve(ctx context.Context, desired Request) (Request, error) {
var out Request
e := c.call(ctx, "/v1/resolve", desired, &out)
if e == nil && (out.validate() != nil || !sameOperation(out, desired) || out.Grant.Epoch > desired.Grant.Epoch) {
e = ErrConflict
}
return out, e
}
@@ -0,0 +1,111 @@
package objectgateway_test
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
g "knowledge-governance/internal/objectgateway"
)
func TestGatewayNewEpochPreservesOriginalSendIdentity(t *testing.T) {
ctx, pool, backend := fixture(t)
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
first := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("takeover-plan"))}
sent, unsent := request("takeover-sent", first), request("takeover-unsent", first)
if e := gateway.InstallPlan(ctx, planFor(first, sent, unsent)); e != nil {
t.Fatal(e)
}
if e := gateway.Advance(ctx, 0, first); e != nil {
t.Fatal(e)
}
old, e := gateway.Execute(ctx, sent, []byte("gateway fixture takeover-sent"))
if e != nil {
t.Fatal(e)
}
// Always clean only this test's exact original version, including on RED.
cleanupGrant := first
defer func() { copy := old; copy.Request.Grant = cleanupGrant; cleanup(t, ctx, gateway, copy) }()
var original []byte
if e = pool.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", gateway.Scope, sent.Operation).Scan(&original); e != nil {
t.Fatal(e)
}
next := first
next.Epoch++
if e = gateway.Advance(ctx, 1, next); e != nil {
t.Fatal(e)
}
cleanupGrant = next
data, control := g.Digest([]byte("takeover-data")), g.Digest([]byte("takeover-control"))
server := httptest.NewServer(g.HTTPServer{Gateway: gateway, DataToken: data, ControlToken: control})
defer server.Close()
post := func(path string, in any) (int, []byte) {
raw, _ := json.Marshal(in)
req, _ := http.NewRequestWithContext(ctx, "POST", server.URL+path, bytes.NewReader(raw))
req.Header.Set("Authorization", "Bearer "+data)
req.Header.Set("X-KG-Gateway-Protocol", g.Protocol)
req.Header.Set("X-KG-Gateway-Scope", gateway.Scope)
resp, e := http.DefaultClient.Do(req)
if e != nil {
t.Fatal(e)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
return resp.StatusCode, body
}
code, body := post("/v1/execute", map[string]any{"request": sent, "authorization": next, "body": []byte("gateway fixture takeover-sent")})
if code != 200 {
t.Fatalf("new authorization cannot replay immutable original request: status=%d", code)
}
var replay g.Receipt
if json.Unmarshal(body, &replay) != nil || replay != old {
t.Fatal("replay rewrote original receipt")
}
desired := sent
desired.Grant = next
code, body = post("/v1/resolve", desired)
var resolved g.Request
if code != 200 || json.Unmarshal(body, &resolved) != nil || resolved != sent {
t.Fatal("original send identity not resolved", code)
}
changed := sent
changed.SHA256 = g.Digest([]byte("different"))
if code, _ = post("/v1/resolve", changed); code == 200 {
t.Fatal("operation rebound body")
}
if code, _ = post("/v1/execute", map[string]any{"request": unsent, "authorization": first, "body": []byte("gateway fixture takeover-unsent")}); code == 200 {
t.Fatal("stale epoch created unsent key")
}
unsent.Grant = next
code, body = post("/v1/execute", map[string]any{"request": unsent, "authorization": next, "body": []byte("gateway fixture takeover-unsent")})
var created g.Receipt
if code != 200 || json.Unmarshal(body, &created) != nil || created.State != "committed" {
t.Fatal("new epoch did not continue unsent key", code)
}
cleanup(t, ctx, gateway, created)
var after []byte
if e = pool.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", gateway.Scope, sent.Operation).Scan(&after); e != nil || !bytes.Equal(after, original) {
t.Fatal("immutable intent changed", e)
}
versions, e := backend.List(ctx, sent.Key)
if e != nil || len(versions) != 1 || versions[0] != old.Version {
t.Fatal("replay created extra version", e)
}
// Deletion is a new send in the current epoch, not a rewritten create intent.
deletion := sent
deletion.Grant = next
deletion.Operation = g.Digest([]byte(sent.Operation + "delete"))
deletion.Action = "delete"
deletion.CreatedBy = sent.Operation
deletion.Version = old.Version
code, _ = post("/v1/execute", map[string]any{"request": deletion, "authorization": next})
if code != 200 {
t.Fatal("new epoch exact cleanup refused", code)
}
// deferred cleanup replays the same already settled delete request below.
old.Request.Grant = next
t.Log("new epoch replay retained original request/receipt/claim; unsent key committed once; stale request rejected")
}
@@ -0,0 +1,69 @@
package objectgateway_test
import (
"context"
"errors"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
g "knowledge-governance/internal/objectgateway"
)
type stoppedBeforeSend struct {
g.Backend
calls int
}
func (b *stoppedBeforeSend) Put(context.Context, string, []byte, string) (g.Version, error) {
b.calls++
return g.Version{}, errors.New("injected uncertain send with no visible version")
}
func TestGatewayAbsenceNeverSettlesUnknown(t *testing.T) {
ctx, pool, real := fixture(t)
backend := &stoppedBeforeSend{Backend: real}
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("plan"))}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
if e := gateway.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
t.Fatal(e)
}
if e := gateway.Advance(ctx, 0, grant); e != nil {
t.Fatal(e)
}
req := request(t.Name(), grant)
body := []byte("gateway fixture " + t.Name())
if _, e := gateway.Execute(ctx, req, body); !errors.Is(e, g.ErrHeld) {
t.Fatal(e)
}
restarted := *gateway
for i := 0; i < 2; i++ {
if _, e := restarted.Execute(ctx, req, body); !errors.Is(e, g.ErrHeld) {
t.Fatal("absent version treated as terminal", e)
}
}
if backend.calls != 1 {
t.Fatal("PUT replayed", backend.calls)
}
next := grant
next.Epoch++
if e := restarted.Advance(ctx, 1, next); !errors.Is(e, g.ErrHeld) {
t.Fatal("unknown operation allowed epoch handover", e)
}
var n int
if pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_receipts WHERE scope=$1", gateway.Scope).Scan(&n) != nil || n != 0 {
t.Fatal("absence wrote false terminal receipt")
}
}
func TestGatewayReadOnlyPersistenceBlocksSend(t *testing.T) {
ctx, pool, backend := fixture(t)
cfg := pool.Config()
cfg.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
other, e := pgxpool.NewWithConfig(ctx, cfg)
if e != nil {
t.Fatal(e)
}
defer other.Close()
gateway := &g.Gateway{Pool: other, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
if e = gateway.Ready(ctx); !errors.Is(e, g.ErrPersistence) {
t.Fatal("read-only persistence accepted", e)
}
}
@@ -0,0 +1,68 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"time"
)
func (s *Store) CreateLibraryDispatch(ctx context.Context, job governance.LibraryJob, stages []string, handoff bool, now time.Time) (governance.LibraryJob, bool, error) {
tx, err := s.db.Begin(ctx)
if err != nil {
return governance.LibraryJob{}, false, err
}
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
created, reused, err := NewStore(tx).WithLibraryTarget(s.libraryTargetID).createLibraryDispatch(ctx, job, stages, handoff, now)
if err != nil {
return governance.LibraryJob{}, false, err
}
if err = tx.Commit(ctx); err != nil {
return governance.LibraryJob{}, false, err
}
return created, reused, nil
}
func (s *Store) createLibraryDispatch(ctx context.Context, job governance.LibraryJob, stages []string, handoff bool, now time.Time) (governance.LibraryJob, bool, error) {
created, reused, err := s.CreateLibraryJob(ctx, job, stages, now)
if err != nil {
return created, reused, err
}
if reused && (created.State != governance.LibraryJobPending || created.QueueJobID != "") {
return created, true, nil
}
kind := "library." + string(created.Kind)
if created.Kind != governance.LibraryJobSync && created.Kind != governance.LibraryJobRestore && created.Kind != governance.LibraryJobBaseline {
return created, reused, errors.New("unsupported library dispatch kind")
}
queueID, kind, raw, err := governance.LibraryQueueRequest(handoff, created.ID, created.Scope, created.TargetSnapshotID, kind)
if err != nil {
return created, reused, err
}
var payload map[string]string
if err = json.Unmarshal(raw, &payload); err != nil {
return created, reused, err
}
queued, err := s.Enqueue(ctx, jobs.EnqueueRequest{ID: queueID, Type: kind, Payload: raw, AvailableAt: now, MaxAttempts: 1, IdempotencyKey: kind + ".queue:" + created.ID}, now)
if err != nil {
return created, reused, err
}
if queued == nil || queued.ID != queueID || queued.Type != kind {
return created, reused, errors.New("queue identity conflict")
}
var actual map[string]string
if json.Unmarshal(queued.Payload, &actual) != nil || len(actual) != len(payload) {
return created, reused, errors.New("queue payload mismatch")
}
for key, value := range payload {
if actual[key] != value {
return created, reused, errors.New("queue payload mismatch")
}
}
if err := s.AttachLibraryQueueJob(ctx, created.ID, queued.ID, now); err != nil {
return created, reused, err
}
created.QueueJobID = queued.ID
return created, reused, nil
}
@@ -0,0 +1,39 @@
package postgres
import (
"context"
"knowledge-governance/internal/governance"
"testing"
"time"
)
func TestContractDispatchAttachFailureLeavesNoQueueOrBusinessJob(t *testing.T) {
store, pool := newIdentityStore(t)
ctx := context.Background()
now := time.Now().UTC()
if _, err := pool.Exec(ctx, `CREATE FUNCTION fail_dispatch_attach() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.queue_job_id <> '' THEN RAISE EXCEPTION 'injected attach failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER fail_attach BEFORE UPDATE ON library_jobs FOR EACH ROW EXECUTE FUNCTION fail_dispatch_attach()`); err != nil {
t.Fatal(err)
}
job := governance.LibraryJob{ID: "atomic-dispatch", Scope: "internal", Kind: governance.LibraryJobSync, RequestDigest: "request", IdempotencyKey: "intent-atomic", TargetSnapshotID: "snapshot"}
if _, _, err := store.CreateLibraryDispatch(ctx, job, governance.SyncStages(), false, now); err == nil {
t.Fatal("injected attach did not fail")
}
var business, queue int
if err := pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM library_jobs),(SELECT count(*) FROM jobs)`).Scan(&business, &queue); err != nil {
t.Fatal(err)
}
if business != 0 || queue != 0 {
t.Fatalf("partial dispatch escaped transaction: business=%d queue=%d", business, queue)
}
if _, err := pool.Exec(ctx, `DROP TRIGGER fail_attach ON library_jobs`); err != nil {
t.Fatal(err)
}
first, reused, err := store.CreateLibraryDispatch(ctx, job, governance.SyncStages(), false, now)
if err != nil || reused || first.QueueJobID == "" {
t.Fatalf("dispatch after failure: %+v %v %v", first, reused, err)
}
replay, reused, err := store.CreateLibraryDispatch(ctx, job, governance.SyncStages(), false, now)
if err != nil || !reused || replay.QueueJobID != first.QueueJobID {
t.Fatalf("dispatch replay: %+v %v %v", replay, reused, err)
}
}
@@ -0,0 +1,36 @@
package postgres
import (
"context"
"errors"
"time"
)
var ErrLibraryExecutionBusy = errors.New("target already has an active executor")
func (s *Store) WithLibraryExecution(ctx context.Context, instance string, run func(context.Context, func(context.Context) error) error) error {
if instance == "" {
return errors.New("execution instance identity required")
}
// A lease expiry is not proof that the old writer has stopped. Keep a
// shared PG advisory lock until the synchronous callback (including cleanup)
// exits. No deferred unlock may run merely because ctx was cancelled.
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer func() {
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_ = tx.Rollback(cleanup)
}()
var held bool
if err = tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))`, "library-execution:"+instance).Scan(&held); err != nil {
return err
}
if !held {
return ErrLibraryExecutionBusy
}
ping := func(probe context.Context) error { var one int; return tx.QueryRow(probe, `SELECT 1`).Scan(&one) }
return run(ctx, ping)
}
@@ -0,0 +1,51 @@
package postgres
import (
"context"
"errors"
"fmt"
"testing"
"time"
)
func TestContractExecutionMutexWaitsForActualWriter(t *testing.T) {
store, _ := newIdentityStore(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
key := fmt.Sprintf("isolated-%s-%d", t.Name(), time.Now().UnixNano())
entered := make(chan struct{})
release := make(chan struct{})
finished := make(chan error, 1)
go func() {
finished <- store.WithLibraryExecution(ctx, key, func(ctx context.Context, ping func(context.Context) error) error {
if err := ping(ctx); err != nil {
return err
}
close(entered)
<-ctx.Done()
<-release
return ctx.Err()
})
}()
select {
case <-entered:
case err := <-finished:
t.Fatalf("first executor: %v", err)
case <-time.After(5 * time.Second):
t.Fatal("first executor timeout")
}
cancel()
called := false
err := store.WithLibraryExecution(context.Background(), key, func(context.Context, func(context.Context) error) error { called = true; return nil })
close(release)
if err2 := <-finished; !errors.Is(err2, context.Canceled) {
t.Fatalf("first executor exit: %v", err2)
}
if !errors.Is(err, ErrLibraryExecutionBusy) || called {
t.Fatalf("cancelled but still-writing executor was overlapped: err=%v called=%v", err, called)
}
called = false
if err = store.WithLibraryExecution(context.Background(), key, func(context.Context, func(context.Context) error) error { called = true; return nil }); err != nil || !called {
t.Fatalf("finished executor not released: %v %v", err, called)
}
}
@@ -430,6 +430,7 @@ WHERE lj.kind IN ('sync','restore','baseline')
OR (lj.state='pending' AND j.state='running' AND j.lease_until IS NOT NULL AND j.lease_until < now())
)
AND lj.target_id=$1
AND NOT EXISTS (SELECT 1 FROM jobs recovery WHERE recovery.type='library.recover' AND recovery.payload->>'window_job_id'=lj.id AND recovery.payload->>'scope'=lj.scope)
ORDER BY lj.created_at`, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("list interrupted library jobs: %w", err)
@@ -529,6 +530,7 @@ WHERE id=$1 AND state IN ('running','retry','failed','pending')
func (s *Store) ClaimLibraryJobForResume(ctx context.Context, jobID string, now time.Time) (bool, error) {
tag, err := s.db.Exec(ctx, `UPDATE library_jobs SET state='pending', updated_at=$2
WHERE id=$1 AND target_id=$3 AND state IN ('running','pending')
AND NOT EXISTS (SELECT 1 FROM jobs recovery WHERE recovery.type='library.recover' AND recovery.payload->>'window_job_id'=library_jobs.id AND recovery.payload->>'scope'=library_jobs.scope)
AND (lease_owner='' OR lease_until IS NULL OR lease_until < $2)`, jobID, now.UTC(), s.libraryTargetID)
if err != nil {
return false, fmt.Errorf("claim interrupted library job: %w", err)
@@ -0,0 +1,59 @@
package postgres
import (
"context"
"errors"
"knowledge-governance/internal/governance"
"testing"
"time"
)
func TestContractExpiredAttemptCannotRenewOrWrite(t *testing.T) {
store, pool := newIdentityStore(t)
ctx := context.Background()
now := time.Now().UTC()
seedOperationJob(t, store, pool, "internal", "contract-expired", "sync", now)
attempt, err := store.BeginLibraryAttempt(ctx, "contract-expired", "writer", time.Minute, now)
if err != nil {
t.Fatal(err)
}
if _, err = pool.Exec(ctx, `UPDATE library_jobs SET lease_until=now()-interval '1 minute'; UPDATE library_attempts SET lease_until=now()-interval '1 minute'`); err != nil {
t.Fatal(err)
}
if err = store.RenewLibraryAttempt(ctx, attempt, time.Minute, now); !errors.Is(err, governance.ErrLibraryEpochStale) {
t.Errorf("expired renewal resurrected ownership: %v", err)
}
if err = store.AdvanceLibraryJobGuarded(ctx, attempt, governance.LibraryJobRunning, "database", "", "", "", "", now); !errors.Is(err, governance.ErrLibraryEpochStale) {
t.Errorf("expired owner still writes: %v", err)
}
}
func TestContractRenewalIsAtomicAcrossJobAndAttempt(t *testing.T) {
store, pool := newIdentityStore(t)
ctx := context.Background()
now := time.Now().UTC()
op := seedOperationJob(t, store, pool, "internal", "contract-revoke", "sync", now)
attempt, err := store.BeginLibraryAttempt(ctx, "contract-revoke", "writer", time.Minute, now)
if err != nil {
t.Fatal(err)
}
if err = store.RenewLibraryAttempt(ctx, attempt, 2*time.Minute, now); err != nil {
t.Fatalf("valid renewal: %v", err)
}
if _, err = pool.Exec(ctx, `UPDATE library_jobs SET lease_owner='new-owner' WHERE id=$1`, attempt.JobID); err != nil {
t.Fatal(err)
}
var before, after time.Time
if err = pool.QueryRow(ctx, `SELECT lease_until FROM library_attempts WHERE operation_id=$1`, op).Scan(&before); err != nil {
t.Fatal(err)
}
if err = store.RenewLibraryAttempt(ctx, attempt, time.Hour, now); !errors.Is(err, governance.ErrLibraryEpochStale) {
t.Errorf("revoked job still renews: %v", err)
}
if err = pool.QueryRow(ctx, `SELECT lease_until FROM library_attempts WHERE operation_id=$1`, op).Scan(&after); err != nil {
t.Fatal(err)
}
if !before.Equal(after) {
t.Fatal("partial renewal escaped transaction")
}
}
@@ -0,0 +1,143 @@
package postgres
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"strings"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/libraryagent"
"knowledge-governance/internal/librarysnapshot"
)
// BindLegacyLibrarySource adds evidence, not a new snapshot or rewritten origin.
// Both the archived manifest and the original capture response must independently
// identify the configured source. A scope match by itself can never authorize it.
func (s *Store) BindLegacyLibrarySource(ctx context.Context, snapshotID, archiveRoot string, source governance.LibrarySourceIdentity, actor string, now time.Time) error {
sourceID, err := source.ID()
if err != nil {
return err
}
if strings.TrimSpace(actor) == "" || now.IsZero() {
return errors.New("source association requires audited actor and time")
}
archive, err := librarysnapshot.Open(archiveRoot, 256*1024*1024)
if err != nil {
return err
}
defer archive.Close()
manifest, err := archive.Load(snapshotID)
if err != nil {
return err
}
if manifest.Scope != source.Scope || manifest.TenantID != source.TenantID || manifest.KnowledgeBaseID != source.KnowledgeBaseID {
return errors.New("historical manifest differs from configured source")
}
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer func() {
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_ = tx.Rollback(cleanup)
}()
rows, err := tx.Query(ctx, `SELECT id,source_job_id,evidence FROM library_versions WHERE scope=$1 AND snapshot_id=$2 AND kind='test_sealed' AND target_id='' FOR UPDATE`, source.Scope, snapshotID)
if err != nil {
return err
}
type sealed struct {
id, job string
evidence []byte
}
items := []sealed{}
for rows.Next() {
var v sealed
if err = rows.Scan(&v.id, &v.job, &v.evidence); err != nil {
rows.Close()
return err
}
items = append(items, v)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
if len(items) != 1 || items[0].job == "" {
return errors.New("unique original captured seal required")
}
old := items[0]
commitAndVerify := func() error {
if err := tx.Commit(ctx); err != nil {
return err
}
var verifiedID string
if err := s.db.QueryRow(ctx, `SELECT evidence->>'source_id' FROM library_versions WHERE id=$1 AND scope=$2 AND snapshot_id=$3`, old.id, source.Scope, snapshotID).Scan(&verifiedID); err != nil {
return err
}
if verifiedID != sourceID {
return errors.New("committed source association readback mismatch")
}
return nil
}
var evidence map[string]json.RawMessage
if json.Unmarshal(old.evidence, &evidence) != nil || evidence == nil {
return errors.New("original capture evidence is not an object")
}
var captured struct {
SnapshotID string `json:"snapshot_id"`
Identity struct {
Project string `json:"project"`
App string `json:"source_app"`
Root string `json:"archive_root"`
Fingerprint string `json:"expectation_fingerprint"`
} `json:"agent_identity"`
}
var expected string
if json.Unmarshal(evidence["agent_result"], &captured) != nil || json.Unmarshal(evidence["expectation_fingerprint"], &expected) != nil {
return errors.New("original capture identity evidence missing")
}
identity := captured.Identity
fingerprint := libraryagent.NewExpectation(identity.Project, identity.App, identity.Root).Fingerprint
if captured.SnapshotID != snapshotID || identity.Project != source.Project || identity.App != source.App || identity.Root == "" || expected != fingerprint || identity.Fingerprint != expected {
return errors.New("original capture identity or fingerprint mismatch")
}
if raw, exists := evidence["source_id"]; exists {
var current string
var bound governance.LibrarySourceIdentity
if json.Unmarshal(raw, &current) != nil || current != sourceID || json.Unmarshal(evidence["source_identity"], &bound) != nil || bound != source {
return errors.New("sealed source association cannot be changed")
}
return commitAndVerify()
}
for _, reserved := range []string{"source_identity", "legacy_source_binding"} {
if _, exists := evidence[reserved]; exists {
return errors.New("partial source association cannot be overwritten")
}
}
sum := sha256.Sum256(old.evidence)
addition, err := json.Marshal(map[string]any{"source_id": sourceID, "source_identity": source, "legacy_source_binding": map[string]any{"snapshot_id": snapshotID, "original_event_id": old.id, "original_source_job_id": old.job, "original_evidence_sha256": hex.EncodeToString(sum[:]), "expectation_fingerprint": expected, "actor": actor, "bound_at": now.UTC()}})
if err != nil {
return err
}
tag, err := tx.Exec(ctx, `UPDATE library_versions SET evidence=evidence || $2::jsonb WHERE id=$1 AND NOT (evidence ? 'source_id')`, old.id, addition)
if err != nil {
return err
}
if tag.RowsAffected() != 1 {
return errors.New("source association changed concurrently")
}
var actual string
if err = tx.QueryRow(ctx, `SELECT evidence->>'source_id' FROM library_versions WHERE id=$1`, old.id).Scan(&actual); err != nil {
return err
}
if actual != sourceID {
return errors.New("source association readback mismatch")
}
return commitAndVerify()
}
@@ -0,0 +1,152 @@
package postgres
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/libraryagent"
"knowledge-governance/internal/librarysnapshot"
)
func legacySourceFixture(t *testing.T, store *Store) (string, string, governance.LibrarySourceIdentity) {
t.Helper()
ctx := context.Background()
root := t.TempDir()
if e := os.Chmod(root, 0700); e != nil {
t.Fatal(e)
}
archive, e := librarysnapshot.Open(root, 1024*1024)
if e != nil {
t.Fatal(e)
}
defer archive.Close()
m := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy, Format: librarysnapshot.Format, Scope: "internal", TenantID: 10000, KnowledgeBaseID: "kb-legacy", CreatedAt: time.Now().UTC(), Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", EmbeddingDimension: 1024, IndexMappingSHA256: strings.Repeat("a", 64)}}
for _, entry := range []string{"database/knowledges", "database/chunks", "database/resources", "database/resource_bindings", "database/knowledge_tags", "database/knowledge_tag_relations", "wiki/wiki_pages", "wiki/wiki_folders", "wiki/wiki_page_issues", "wiki/wiki_log_entries", "index/chunks"} {
p, e := archive.Put(strings.NewReader("[]"))
if e != nil {
t.Fatal(e)
}
x := strings.Split(entry, "/")
p.Kind = x[0]
p.Name = x[1]
m.Parts = append(m.Parts, p)
}
snapshot, e := archive.Seal(m)
if e != nil {
t.Fatal(e)
}
source := governance.LibrarySourceIdentity{Project: "historical-project", App: "historical-app", Scope: m.Scope, TenantID: m.TenantID, KnowledgeBaseID: m.KnowledgeBaseID}
exp := libraryagent.NewExpectation(source.Project, source.App, "/original/archive")
e = store.RecordLibraryVersion(ctx, governance.LibraryVersion{ID: governance.LibraryVersionID(governance.LibraryVersionTestSealed, m.Scope, snapshot), Scope: m.Scope, Kind: governance.LibraryVersionTestSealed, SnapshotID: snapshot, SourceJobID: "legacy-capture", CreatedAt: m.CreatedAt, Evidence: map[string]any{"expectation_fingerprint": exp.Fingerprint, "capture_job": "legacy", "agent_result": map[string]any{"snapshot_id": snapshot, "agent_identity": map[string]any{"project": source.Project, "source_app": source.App, "archive_root": "/original/archive", "expectation_fingerprint": exp.Fingerprint}}}})
if e != nil {
t.Fatal(e)
}
return root, snapshot, source
}
func TestContractLegacySourceAssociationPreservesOriginalEvidence(t *testing.T) {
store, _ := newIdentityStore(t)
ctx := context.Background()
root, snapshot, source := legacySourceFixture(t, store)
binder, ok := any(store).(interface {
BindLegacyLibrarySource(context.Context, string, string, governance.LibrarySourceIdentity, string, time.Time) error
})
if !ok {
t.Fatal("verified legacy source association unavailable")
}
original, e := os.ReadFile(filepath.Join(root, "versions", snapshot+".json"))
if e != nil {
t.Fatal(e)
}
if _, err := store.db.Exec(ctx, `UPDATE library_versions SET evidence=evidence || '{"large_proof":9223372036854775807}'::jsonb`); err != nil {
t.Fatal(err)
}
var originalEvidence string
if err := store.db.QueryRow(ctx, `SELECT evidence::text FROM library_versions`).Scan(&originalEvidence); err != nil {
t.Fatal(err)
}
id, _ := source.ID()
if _, found, e := store.LibrarySourceCandidate(ctx, source.Scope, id); e != nil || found {
t.Fatal("legacy unbound candidate adopted without explicit association", e)
}
now := time.Now().UTC()
if e = binder.BindLegacyLibrarySource(ctx, snapshot, root, source, "admin", now); e != nil {
t.Fatal(e)
}
candidate, found, e := store.LibrarySourceCandidate(ctx, source.Scope, id)
if e != nil || !found || candidate.SnapshotID != snapshot || candidate.SourceJobID != "legacy-capture" {
t.Fatal("association not readable", e)
}
if candidate.Evidence["capture_job"] != "legacy" {
t.Fatal("original evidence overwritten")
}
if e = binder.BindLegacyLibrarySource(ctx, snapshot, root, source, "another-admin", now.Add(time.Second)); e != nil {
t.Fatal("idempotent association", e)
}
var preserved bool
if err := store.db.QueryRow(ctx, `SELECT (evidence - 'source_id' - 'source_identity' - 'legacy_source_binding')=$1::jsonb FROM library_versions`, originalEvidence).Scan(&preserved); err != nil || !preserved {
t.Fatal("historical evidence changed, including bigint", err)
}
var bindingActor string
if err := store.db.QueryRow(ctx, `SELECT evidence->'legacy_source_binding'->>'actor' FROM library_versions`).Scan(&bindingActor); err != nil || bindingActor != "admin" {
t.Fatal("association replay rewrote audit actor", err)
}
changed := source
changed.App = "other-app"
if e = binder.BindLegacyLibrarySource(ctx, snapshot, root, changed, "admin", now); e == nil {
t.Fatal("source rebound")
}
after, e := os.ReadFile(filepath.Join(root, "versions", snapshot+".json"))
if e != nil || string(original) != string(after) {
t.Fatal("historical manifest changed", e)
}
}
func TestContractLegacySourceAssociationRejectsInsufficientProof(t *testing.T) {
for _, scenario := range []string{"project", "tenant", "fingerprint", "missing-origin", "snapshot", "partial-binding"} {
t.Run(scenario, func(t *testing.T) {
store, _ := newIdentityStore(t)
ctx := context.Background()
root, snapshot, source := legacySourceFixture(t, store)
var mutation string
switch scenario {
case "project":
source.Project = "other-project"
case "tenant":
source.TenantID++
case "fingerprint":
mutation = `UPDATE library_versions SET evidence=jsonb_set(evidence,'{expectation_fingerprint}','"wrong"'::jsonb)`
case "missing-origin":
mutation = `UPDATE library_versions SET evidence=evidence-'agent_result'`
case "snapshot":
mutation = `UPDATE library_versions SET evidence=jsonb_set(evidence,'{agent_result,snapshot_id}','"different"'::jsonb)`
case "partial-binding":
mutation = `UPDATE library_versions SET evidence=evidence || '{"source_identity":{}}'::jsonb`
}
if mutation != "" {
if _, e := store.db.Exec(ctx, mutation); e != nil {
t.Fatal(e)
}
}
var before string
if e := store.db.QueryRow(ctx, `SELECT evidence::text FROM library_versions`).Scan(&before); e != nil {
t.Fatal(e)
}
if e := store.BindLegacyLibrarySource(ctx, snapshot, root, source, "admin", time.Now()); e == nil {
t.Fatal("unproven source accepted")
}
var after string
if e := store.db.QueryRow(ctx, `SELECT evidence::text FROM library_versions`).Scan(&after); e != nil {
t.Fatal(e)
}
if before != after {
t.Fatal("rejected association changed historical evidence")
}
})
}
}
@@ -459,23 +459,35 @@ func (s *Store) LatestLibraryAttempt(ctx context.Context, operationID string) (g
// RenewLibraryAttempt 续租:失租(0 行)即返回 ErrLibraryEpochStale,调用方必须停手。
func (s *Store) RenewLibraryAttempt(ctx context.Context, attempt governance.LibraryAttempt, lease time.Duration, now time.Time) error {
until := now.Add(lease).UTC()
tag, err := s.db.Exec(ctx, `
UPDATE library_attempts SET heartbeat_at=$4, lease_until=$5
WHERE operation_id=$1 AND epoch=$2 AND owner=$3 AND state='running'`,
attempt.OperationID, attempt.Epoch, attempt.Owner, now.UTC(), until)
if lease <= 0 {
return errors.New("positive lease required")
}
tx, err := s.db.Begin(ctx)
if err != nil {
return fmt.Errorf("renew library attempt: %w", err)
return err
}
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
// Lock job first, exactly like BeginLibraryAttempt. Both leases are one fact;
// never resurrect an expired owner or commit half of a renewal.
tag, err := tx.Exec(ctx, `UPDATE library_jobs SET lease_until=clock_timestamp()+$4::interval
WHERE id=$1 AND attempt_epoch=$2 AND lease_owner=$3 AND lease_until>clock_timestamp()`, attempt.JobID, attempt.Epoch, attempt.Owner, lease.String())
if err != nil {
return err
}
if tag.RowsAffected() != 1 {
return governance.ErrLibraryEpochStale
}
if _, err := s.db.Exec(ctx, `
UPDATE library_jobs SET lease_until=$4 WHERE id=$1 AND attempt_epoch=$2 AND lease_owner=$3`,
attempt.JobID, attempt.Epoch, attempt.Owner, until); err != nil {
return fmt.Errorf("renew library job lease: %w", err)
if attempt.OperationID != "" {
tag, err = tx.Exec(ctx, `UPDATE library_attempts SET heartbeat_at=clock_timestamp(),lease_until=clock_timestamp()+$4::interval
WHERE operation_id=$1 AND epoch=$2 AND owner=$3 AND state='running' AND lease_until>clock_timestamp()`, attempt.OperationID, attempt.Epoch, attempt.Owner, lease.String())
if err != nil {
return err
}
if tag.RowsAffected() != 1 {
return governance.ErrLibraryEpochStale
}
}
return nil
return tx.Commit(ctx)
}
// guardLibraryJobEpoch 在事务内核"这次写入来自当前代次"。守卫失败一律返回
@@ -0,0 +1,42 @@
package postgres
import (
"context"
"errors"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
)
// An arbitrary queue delivery cannot borrow another job's window. Check the
// stored request AND its current delivery lease before any maintenance action.
func (s *Store) ResumeExpiredLibraryRecoveryQueues(ctx context.Context) error {
_, err := s.db.Exec(ctx, `UPDATE jobs q SET state='pending',attempt=0,lease_owner=NULL,lease_until=NULL,available_at=clock_timestamp()
FROM library_jobs j,library_instance_maintenance m
WHERE q.type='library.recover' AND q.state='running' AND q.lease_until<clock_timestamp()
AND j.id=q.payload->>'window_job_id' AND j.scope=q.payload->>'scope' AND j.target_id=$1
AND (j.lease_until IS NULL OR j.lease_until<clock_timestamp())
AND m.owner_job_id=j.id AND m.owner_scope=j.scope AND m.released_at IS NULL
AND q.id='lrec-'||substr(encode(sha256(convert_to(j.id,'UTF8')),'hex'),1,28)
AND q.idempotency_key='library.recover:'||j.id`, s.libraryTargetID)
return err
}
func (s *Store) ValidateLibraryRecoveryQueue(ctx context.Context, q jobs.Job, scope, window string) error {
if q.ID != governance.LibraryRecoveryQueueID(window) || q.Type != "library.recover" {
return errors.New("recovery queue identity mismatch")
}
var valid bool
e := s.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM jobs q JOIN library_jobs j ON j.id=$2
WHERE q.id=$1 AND q.type='library.recover' AND q.state='running'
AND q.payload=$3::jsonb AND q.payload->>'window_job_id'=j.id AND q.payload->>'scope'=j.scope
AND q.idempotency_key='library.recover:'||j.id
AND q.lease_owner=$4 AND q.attempt=$5 AND q.lease_until>clock_timestamp()
AND j.scope=$6 AND j.target_id=$7 AND j.kind IN ('sync','restore','baseline'))`, q.ID, window, q.Payload, q.LeaseOwner, q.Attempt, scope, s.libraryTargetID).Scan(&valid)
if e != nil {
return e
}
if !valid {
return errors.New("recovery request/source/target/lease mismatch")
}
return nil
}
@@ -0,0 +1,26 @@
package postgres
import (
"context"
"errors"
"knowledge-governance/internal/governance"
)
// Query the source identity before applying LIMIT: target/prebackup events and
// other source instances can never push the candidate out of a history window.
func (s *Store) LibrarySourceCandidate(ctx context.Context, scope, sourceID string) (governance.LibraryVersion, bool, error) {
if sourceID == "" {
return governance.LibraryVersion{}, false, errors.New("source identity required")
}
rows, err := s.db.Query(ctx, `SELECT id,scope,kind,snapshot_id,version_label,source_job_id,operation_id,attempt_epoch,evidence,created_by,created_at,superseded_at
FROM library_versions WHERE scope=$1 AND kind='test_sealed' AND evidence->>'source_id'=$2
ORDER BY created_at DESC,id DESC LIMIT 1`, scope, sourceID)
if err != nil {
return governance.LibraryVersion{}, false, err
}
items, err := scanLibraryVersions(rows, 1)
if err != nil || len(items) == 0 {
return governance.LibraryVersion{}, false, err
}
return items[0], true, nil
}
@@ -0,0 +1,42 @@
package postgres
import (
"context"
"fmt"
"knowledge-governance/internal/governance"
"testing"
"time"
)
func TestContractSourceCandidateBeyondHistoryWindow(t *testing.T) {
store, _ := newIdentityStore(t)
ctx := context.Background()
now := time.Now().UTC()
source := governance.LibrarySourceIdentity{Project: "source-project", App: "source-app", Scope: "internal", TenantID: 10000, KnowledgeBaseID: "kb-source"}
id, err := source.ID()
if err != nil {
t.Fatal(err)
}
for i := 0; i < 65; i++ {
sid := "other-source"
if i == 0 {
sid = id
}
snapshot := fmt.Sprintf("candidate-%d", i)
if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ID: governance.LibraryVersionID(governance.LibraryVersionTestSealed, "internal", snapshot), Scope: "internal", Kind: governance.LibraryVersionTestSealed, SnapshotID: snapshot, Evidence: map[string]any{"source_id": sid}, CreatedAt: now.Add(time.Duration(i) * time.Second)}); err != nil {
t.Fatal(err)
}
}
candidate, found, err := store.LibrarySourceCandidate(ctx, "internal", id)
if err != nil || !found || candidate.SnapshotID != "candidate-0" {
t.Fatalf("exact candidate missing: %+v %v %v", candidate, found, err)
}
source.KnowledgeBaseID = "new-kb"
newID, _ := source.ID()
if _, found, err = store.LibrarySourceCandidate(ctx, "internal", newID); err != nil || found {
t.Fatalf("new source inherited old candidate: %v %v", found, err)
}
if _, found, err = store.LibrarySourceCandidate(ctx, "external", id); err != nil || found {
t.Fatalf("cross scope candidate: %v %v", found, err)
}
}
@@ -33,6 +33,7 @@ func libraryFence(jobIDExpr string, epochParam, ownerParam int) string {
WHERE j.id = %s
AND j.attempt_epoch = $%d
AND j.lease_owner = $%d
AND j.lease_until > clock_timestamp()
AND (
j.operation_id = ''
OR EXISTS (
@@ -41,6 +42,7 @@ func libraryFence(jobIDExpr string, epochParam, ownerParam int) string {
AND a.epoch = j.attempt_epoch
AND a.owner = j.lease_owner
AND a.state IN ('claimed','running')
AND a.lease_until > clock_timestamp()
)
)
)`, jobIDExpr, epochParam, ownerParam)
@@ -0,0 +1,82 @@
package v071
import (
"context"
"net/http/httptest"
"os"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/objectgateway"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/postgres/pgtest"
)
// Exported only into the test binary, so the external-package test exercises
// librarystack.OpenProductionStack without an import cycle or duplicated fixture.
type R10AdmissionFixture struct {
Context context.Context
Config appconfig.Config
Snapshot string
Exec func(string)
State func() map[string]any
Unchanged func(map[string]any)
Save func(string, any)
}
func OpenR10AdmissionFixture(t *testing.T) R10AdmissionFixture {
t.Helper()
fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, embeddingDimension: 1024})
seedTargetData(t, fx)
r10Exec(t, fx, `ALTER TABLE knowledge_bases ADD COLUMN embedding_model_id text; ALTER TABLE knowledge_bases ADD COLUMN vector_store_id text;
CREATE TABLE models(id text PRIMARY KEY,name text,parameters jsonb,deleted_at timestamptz);
CREATE TABLE vector_stores(id text PRIMARY KEY,engine_type text,index_config jsonb,deleted_at timestamptz);
INSERT INTO models VALUES('r10-model','text-embedding-v4','{"embedding_parameters":{"dimension":1024}}',NULL);
INSERT INTO vector_stores VALUES('r10-vector','elasticsearch_v8','{}',NULL);
UPDATE knowledge_bases SET embedding_model_id='r10-model',vector_store_id='r10-vector'`)
if _, e := fx.pool.Exec(fx.ctx, `UPDATE vector_stores SET index_config=jsonb_build_object('index_name',$1::text)`, fx.index); e != nil {
t.Fatal(e)
}
dsn := pgtest.IsolatedDatabaseURL(t, os.Getenv("KG_LIBRARY_TEST_DATABASE_URL"))
governancePool, e := pgxpool.New(fx.ctx, dsn)
if e != nil {
t.Fatal(e)
}
t.Cleanup(governancePool.Close)
if e = postgresstore.ApplyMigrations(fx.ctx, governancePool); e != nil {
t.Fatal(e)
}
if _, e = governancePool.Exec(fx.ctx, objectgateway.Schema); e != nil {
t.Fatal(e)
}
reader := gatewayReadOnlyGovernance(t, fx.ctx, governancePool, dsn)
authority := &GatewayGovernanceAuthority{Pool: reader, ArchiveRoot: fx.archiveRoot, TargetID: "r10-admission", Provider: "minio", Bucket: fx.bucket}
endpoint := os.Getenv("KG_LIBRARY_TEST_S3_ENDPOINT")
scope := objectgateway.Digest([]byte("minio\x00" + endpoint + "\x00" + fx.bucket))
gateway := &objectgateway.Gateway{Pool: governancePool, Scope: scope, Backend: &objectgateway.S3Backend{Client: fx.objects.s3.client, Bucket: fx.bucket, MaxBytes: 1 << 20}, Authority: authority, Isolation: gatewayFixtureIsolation{}, MaxBytes: 1 << 20}
token := objectgateway.Digest([]byte("r10-admission-data"))
server := httptest.NewServer(objectgateway.HTTPServer{Gateway: gateway, DataToken: token, ControlToken: objectgateway.Digest([]byte("r10-admission-control"))})
t.Cleanup(server.Close)
config := appconfig.Config{LibraryProductionDatabaseURL: os.Getenv("KG_LIBRARY_TEST_DATABASE_URL"), LibraryProductionElasticURL: fx.searchBase, LibraryProductionIndex: fx.index, LibraryProductionTenantID: wsTargetTenant, LibraryProductionInternalKB: wsTargetKB, LibraryProductionS3Endpoint: endpoint, LibraryProductionS3Provider: "minio", LibraryProductionS3Bucket: fx.bucket, LibraryProductionS3AccessKey: os.Getenv("KG_LIBRARY_TEST_S3_ACCESS_KEY"), LibraryProductionS3SecretKey: os.Getenv("KG_LIBRARY_TEST_S3_SECRET_KEY"), LibraryArchiveRoot: fx.archiveRoot, LibraryObjectGatewayURL: server.URL, LibraryObjectGatewayToken: token}
snapshot := sealSourceSnapshot(t, fx, nil)
state := func() map[string]any {
out := r10State(t, fx)
for _, table := range []string{"knowledge_bases", "models", "vector_stores", "schema_migrations"} {
var raw []byte
if e := fx.pool.QueryRow(fx.ctx, "SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]') FROM "+table+" t").Scan(&raw); e != nil {
t.Fatal(e)
}
out[table] = string(raw)
}
for _, table := range []string{"kg_object_gateway_plans", "kg_object_gateway_intents", "kg_object_gateway_receipts", "kg_object_gateway_deliveries", "kg_object_gateway_grants"} {
var count int64
if e := governancePool.QueryRow(fx.ctx, "SELECT count(*) FROM "+table).Scan(&count); e != nil {
t.Fatal(e)
}
out[table] = count
}
return out
}
return R10AdmissionFixture{Context: fx.ctx, Config: config, Snapshot: snapshot, Exec: func(sql string) { r10Exec(t, fx, sql) }, State: state, Save: func(label string, value any) { r10Save(t, label, value) }}
}
@@ -0,0 +1,51 @@
package v071_test
import (
"reflect"
"strings"
"testing"
"knowledge-governance/internal/librarystack"
v071 "knowledge-governance/internal/releaseadapter/v071"
)
func TestR10ProductionAdmissionIsolated(t *testing.T) {
cases := []struct{ name, sql, want string }{
{"matching", "", ""},
{"same-dimension-other-model", `UPDATE models SET name='different-embedding-model'`, "不同"},
{"missing-model", `DELETE FROM models`, "模型"},
{"empty-model-name", `UPDATE models SET name=''`, "模型"},
{"graph-enabled", `UPDATE knowledge_bases SET indexing_strategy='{"graph_enabled":true}' WHERE id='kb-target'`, "图谱"},
{"schema-dirty", `UPDATE schema_migrations SET dirty=true`, "dirty"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
fx := v071.OpenR10AdmissionFixture(t)
if c.sql != "" {
fx.Exec(c.sql)
}
before := fx.State()
target, backups, e := librarystack.OpenProductionStack(fx.Context, fx.Config, "internal", fx.Snapshot, "")
if target != nil {
target.Close()
}
after := fx.State()
fx.Save("before", before)
fx.Save("after", after)
if !reflect.DeepEqual(before, after) {
t.Fatal("actual admission path changed PG/ES/object versions/gateway journal")
}
if c.want == "" {
if e != nil || target == nil || backups == nil {
t.Fatal("positive admission", e)
}
fx.Save("outcome", "matching contract admitted without business writes")
} else {
if e == nil || !strings.Contains(e.Error(), c.want) || target != nil || backups != nil {
t.Fatalf("wrong admission result target=%t backups=%t error=%v", target != nil, backups != nil, e)
}
fx.Save("rejection", e.Error())
}
})
}
}
@@ -0,0 +1,126 @@
package v071
import (
"bytes"
"context"
"io"
"knowledge-governance/internal/libraryrelease"
"sync"
"testing"
"time"
)
type r11BackupHook struct {
libraryrelease.BackupStore
after func()
}
func (b r11BackupHook) Prepare(ctx context.Context, id string, current libraryrelease.CurrentState) (libraryrelease.BackupRef, error) {
ref, e := b.BackupStore.Prepare(ctx, id, current)
if e == nil {
b.after()
}
return ref, e
}
type r11PlanHook struct {
libraryrelease.NoopRecorder
after func()
}
func (r r11PlanHook) WriteSetPlanned(_ context.Context, _ libraryrelease.WriteSet) error {
r.after()
return nil
}
func TestR11GrantBoundaryIsolated(t *testing.T) {
for _, mode := range []string{"stale-request-clock", "expires-during-backup", "expires-before-first-apply"} {
t.Run(mode, func(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
snapshot := sealSourceSnapshot(t, fx, nil)
target := fx.target(t)
req := requestFor(snapshot)
req.Grant.ExpiresAt = time.Now().Add(350 * time.Millisecond)
wait := func() {
if d := time.Until(req.Grant.ExpiresAt) + 10*time.Millisecond; d > 0 {
time.Sleep(d)
}
}
var backups libraryrelease.BackupStore = fx.backups(t, target)
var recorder libraryrelease.Recorder
if mode == "stale-request-clock" {
req.Now = time.Now().Add(-time.Hour)
req.Grant.ExpiresAt = time.Now().Add(-time.Second)
}
if mode == "expires-during-backup" {
backups = r11BackupHook{BackupStore: backups, after: wait}
}
if mode == "expires-before-first-apply" {
recorder = r11PlanHook{after: wait}
}
before := r10State(t, fx)
out := libraryrelease.Run(fx.ctx, req, target, backups, recorder)
r10Save(t, "outcome", out)
if out.State != "failed" || out.FailedAt != "" {
t.Errorf("expired authority performed business stages: %+v", out)
}
r10Unchanged(t, fx, before)
})
}
}
type r11ObjectReadHook struct {
*flakyStore
once sync.Once
after func(provider, path string)
}
func (r *r11ObjectReadHook) Open(ctx context.Context, provider, path string) (io.ReadCloser, error) {
stream, e := r.flakyStore.Open(ctx, provider, path)
if e != nil {
return nil, e
}
data, e := io.ReadAll(stream)
stream.Close()
if e != nil {
return nil, e
}
r.once.Do(func() { r.after(provider, path) })
return io.NopCloser(bytes.NewReader(data)), nil
}
func TestR11BackupMutationIsolated(t *testing.T) {
for _, mode := range []string{"es-body", "object-body", "object-same-bytes-new-version"} {
t.Run(mode, func(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
snapshot := sealSourceSnapshot(t, fx, nil)
target := fx.target(t)
backups := fx.backups(t, target)
var injected map[string]any
backups.objects = &r11ObjectReadHook{flakyStore: fx.objects, after: func(provider, path string) {
if mode == "es-body" {
fx.indexDoc(t, "chunk-target", wsTargetTenant, wsTargetKB, "doc-target", "external edit")
} else {
body := "87654321"
if mode == "object-same-bytes-new-version" {
body = "12345678"
}
if e := fx.objects.s3.Put(fx.ctx, provider, path, bytes.NewReader([]byte(body)), 8); e != nil {
t.Fatal(e)
}
}
injected = r10State(t, fx)
r10Save(t, "external-change", injected)
}}
out := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, backups, nil)
r10Save(t, "outcome", out)
if injected == nil {
t.Fatal("injection not reached")
}
if out.State != "failed" || out.FailedAt != "" {
t.Errorf("changed backup admitted writes: %+v", out)
}
r10Unchanged(t, fx, injected)
})
}
}
@@ -0,0 +1,243 @@
package v071
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"testing"
"knowledge-governance/internal/libraryrelease"
)
func TestR10SourceRelationClosureIsolated(t *testing.T) {
for _, mode := range []string{"missing-tag", "missing-knowledge", "cross-kb", "cross-tenant", "orphan-chunk", "unknown-owner", "missing-resource-owner", "null-owner"} {
t.Run(mode, func(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
r10Exec(t, fx, `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id) VALUES('tag-target',10001,'kb-target'),('tag-other',10001,'kb-other'),('tag-foreign',10002,'kb-foreign')`)
switch mode {
case "missing-tag":
r10Exec(t, fx, `INSERT INTO knowledge_tag_relations VALUES('doc-target','absent')`)
case "missing-knowledge":
r10Exec(t, fx, `INSERT INTO knowledge_tag_relations VALUES('absent','tag-target')`)
case "cross-kb":
r10Exec(t, fx, `INSERT INTO knowledge_tag_relations VALUES('doc-target','tag-other')`)
case "cross-tenant":
r10Exec(t, fx, `INSERT INTO knowledge_tag_relations VALUES('doc-target','tag-foreign')`)
case "orphan-chunk":
r10Exec(t, fx, `UPDATE chunks SET knowledge_id='absent' WHERE id='chunk-target'`)
case "unknown-owner":
r10Exec(t, fx, `UPDATE resource_bindings SET owner_type='unknown-v071-shape' WHERE id='bind-target'`)
case "missing-resource-owner":
r10Exec(t, fx, `UPDATE resource_bindings SET owner_id='absent-owner' WHERE id='bind-target'`)
case "null-owner":
r10Exec(t, fx, `UPDATE resource_bindings SET owner_type=NULL,owner_id='doc-other' WHERE id='bind-target'`)
}
before := r10State(t, fx)
_, e := ExportLibrary(fx.ctx, fx.pool, PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB})
r10Unchanged(t, fx, before)
if e == nil {
t.Fatal("source silently excluded a scoped unresolved relationship")
}
r10Save(t, "rejection", e.Error())
snapshot := sealSourceSnapshot(t, fx, nil)
target := fx.target(t)
result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil)
r10Save(t, "existing-target-rejection", result)
if result.State != "failed" || result.FailedAt != "" {
t.Fatalf("existing unresolved target relationship reached writes: %+v", result)
}
r10Unchanged(t, fx, before)
})
}
}
func TestR10IncomingRelationClosureIsolated(t *testing.T) {
for _, mode := range []string{"valid-new", "valid-existing", "missing-tag", "missing-knowledge", "cross-kb", "cross-tenant", "unknown-owner", "missing-resource"} {
t.Run(mode, func(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
positive := strings.HasPrefix(mode, "valid-")
if positive {
r10Exec(t, fx, `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id) VALUES('tag-target',10001,'kb-target'),('tag-other',10001,'kb-other'); INSERT INTO knowledge_tag_relations(knowledge_id,tag_id) VALUES('doc-target','tag-target'),('doc-other','tag-other')`)
}
snapshot := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) {
parts["knowledge_tags"] = []map[string]any{{"id": "tag-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB}}
parts["knowledge_tag_relations"] = []map[string]any{{"knowledge_id": "doc-src", "tag_id": "tag-src"}}
switch mode {
case "valid-existing":
parts["knowledges"][0]["id"] = "doc-target"
parts["chunks"][0]["knowledge_id"] = "doc-target"
parts["resource_bindings"][0]["owner_id"] = "doc-target"
parts["knowledge_tags"][0]["id"] = "tag-target"
parts["knowledge_tag_relations"][0] = map[string]any{"knowledge_id": "doc-target", "tag_id": "tag-target"}
case "missing-tag":
parts["knowledge_tag_relations"][0]["tag_id"] = "missing"
case "missing-knowledge":
parts["knowledge_tag_relations"][0]["knowledge_id"] = "missing"
case "cross-kb":
parts["knowledge_tags"][0]["knowledge_base_id"] = wsOtherKB
case "unknown-owner":
parts["resource_bindings"][0]["owner_type"] = "unknown-v071-shape"
case "cross-tenant":
parts["knowledge_tags"][0]["tenant_id"] = 20000
case "missing-resource":
parts["resource_bindings"][0]["resource_id"] = "absent-resource"
}
})
before := r10State(t, fx)
target := fx.target(t)
result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil)
r10Save(t, "outcome", result)
if positive {
if result.State != "succeeded" {
t.Fatalf("nonempty tuple publication: %+v", result)
}
wantID := "doc-src:tag-src"
if mode == "valid-existing" {
wantID = "doc-target:tag-target"
}
found := false
for _, row := range result.Backup.WriteSet.Rows {
if row.Table == "knowledge_tag_relations" && row.ID == wantID {
found = true
if row.Existing != (mode == "valid-existing") {
t.Fatal("tuple existence misclassified", row)
}
}
}
if !found {
t.Fatal("tuple absent from frozen write set")
}
var outside int
if e := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM knowledge_tag_relations WHERE knowledge_id='doc-other' AND tag_id='tag-other'`).Scan(&outside); e != nil || outside != 1 {
t.Fatal("outside tuple changed", e)
}
if e := target.Restore(fx.ctx, result.Backup); e != nil {
t.Fatal(e)
}
after := r10State(t, fx)
for _, key := range []string{"pg", "versions", "delete_markers"} {
if !reflect.DeepEqual(before[key], after[key]) {
t.Fatal("tuple rollback changed original data", key)
}
}
r10Save(t, "restored", after)
return
}
if result.State != "failed" || result.FailedAt != "" {
t.Fatalf("incoming unresolved reference passed preflight: %+v", result)
}
r10Unchanged(t, fx, before)
})
}
}
func TestR10BodyOnlyResourceIsolated(t *testing.T) {
for _, mode := range []string{"knowledge-content", "wiki-content", "knowledge-metadata", "wiki-metadata"} {
t.Run(mode, func(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
r10Exec(t, fx, `DELETE FROM resource_bindings WHERE owner_id='doc-target'; UPDATE chunks SET content='plain' WHERE id='chunk-target'; ALTER TABLE knowledges ADD COLUMN content text; ALTER TABLE knowledges ADD COLUMN metadata jsonb; ALTER TABLE wiki_pages ADD COLUMN metadata jsonb`)
table, column := "knowledges", "content"
if strings.HasPrefix(mode, "wiki") {
table = "wiki_pages"
}
if strings.HasSuffix(mode, "metadata") {
column = "metadata"
}
value := any("![image](resource://" + wsHandleTarget + ")")
if column == "metadata" {
raw, _ := json.Marshal(map[string]any{"image_info": []any{map[string]string{"url": "resource://" + wsHandleTarget}}})
value = string(raw)
}
if _, e := fx.pool.Exec(fx.ctx, fmt.Sprintf("UPDATE %s SET %s=$1 WHERE knowledge_base_id=$2", table, column), value, wsTargetKB); e != nil {
t.Fatal(e)
}
before := r10State(t, fx)
pg, e := ExportLibrary(fx.ctx, fx.pool, PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB})
if e != nil {
t.Fatal(e)
}
found := false
for _, row := range pg.Table("resources").Rows {
var id struct {
ID string `json:"id"`
}
_ = json.Unmarshal(row, &id)
if id.ID == "res-target" {
found = true
}
if id.ID == "res-orphan" {
t.Fatal("unowned historical resource adopted into source")
}
}
if !found {
t.Fatal("body/metadata resource not captured without binding")
}
if len(pg.Table("resource_bindings").Rows) != 0 {
t.Fatal("fixture unexpectedly had bindings")
}
r10Save(t, "captured-resources", pg.Table("resources"))
backup, e := exportLibraryBeforeImage(fx.ctx, fx.pool, PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB})
if e != nil {
t.Fatal(e)
}
found = false
for _, raw := range backup.Table("resources").Rows {
var row struct {
ID string `json:"id"`
}
_ = json.Unmarshal(raw, &row)
if row.ID == "res-target" {
found = true
}
}
if !found {
t.Fatal("body-only target resource missing from before-image")
}
r10Unchanged(t, fx, before)
snapshot := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) {
parts["resource_bindings"] = []map[string]any{}
parts["chunks"][0]["content"] = "plain source"
parts[table][0][column] = "![image](resource://" + wsHandleSource + ")"
if column == "metadata" {
parts[table][0][column] = map[string]any{"image_info": []any{map[string]string{"url": "resource://" + wsHandleSource}}}
}
})
target := fx.target(t)
result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil)
r10Save(t, "publication", result)
if result.State != "succeeded" {
t.Fatalf("body-only publication: %+v", result)
}
if err := target.Restore(fx.ctx, result.Backup); err != nil {
t.Fatal(err)
}
after := r10State(t, fx)
for _, key := range []string{"pg", "versions", "delete_markers"} {
if !reflect.DeepEqual(before[key], after[key]) {
t.Fatalf("body-only restore changed %s including historical orphans", key)
}
}
r10Save(t, "restored", after)
})
}
}
func TestR10UnknownResourceShapeIsolated(t *testing.T) {
for _, body := range []string{"resource://short", "resource://" + wsHandleTarget + "extra", "resource://" + wsHandleTarget + "?download=1", "resource:\\/\\/" + wsHandleTarget} {
t.Run(fmt.Sprint(len(body))+strings.ReplaceAll(body[len(body)-3:], "/", "_"), func(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
if _, e := fx.pool.Exec(fx.ctx, `UPDATE wiki_pages SET content=$1 WHERE id='wiki-target'`, body); e != nil {
t.Fatal(e)
}
before := r10State(t, fx)
_, e := ExportLibrary(fx.ctx, fx.pool, PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB})
r10Unchanged(t, fx, before)
if e == nil {
t.Fatal("unknown resource reference shape silently accepted")
}
r10Save(t, "rejection", e.Error())
})
}
}
@@ -0,0 +1,258 @@
package v071
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"knowledge-governance/internal/libraryrelease"
"knowledge-governance/internal/librarysnapshot"
)
func r10Save(t *testing.T, label string, value any) {
t.Helper()
root := os.Getenv("KG_R10_RUN")
if root == "" {
return
}
name := strings.NewReplacer("/", "_", " ", "_").Replace(t.Name()+"-"+label) + ".json"
data, e := json.MarshalIndent(value, "", " ")
if e != nil {
t.Fatal(e)
}
if e = os.WriteFile(filepath.Join(root, name), data, 0600); e != nil {
t.Fatal(e)
}
}
func r10Exec(t *testing.T, fx *writeSetFixture, sql string) {
t.Helper()
if _, e := fx.pool.Exec(fx.ctx, sql); e != nil {
t.Fatal(e)
}
}
func r10State(t *testing.T, fx *writeSetFixture) map[string]any {
t.Helper()
objects, e := fx.objects.s3.client.ListObjectVersions(fx.ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(fx.bucket)})
if e != nil {
t.Fatal(e)
}
if aws.ToBool(objects.IsTruncated) {
t.Fatal("truncated object evidence")
}
seq := map[string]any{}
for _, name := range []string{"chunks_seq_id_seq", "knowledge_tags_seq_id_seq", "wiki_log_entries_id_seq"} {
var exists bool
if e := fx.pool.QueryRow(fx.ctx, "SELECT to_regclass($1) IS NOT NULL", name).Scan(&exists); e != nil {
t.Fatal(e)
}
if exists {
var last int64
var called bool
if e := fx.pool.QueryRow(fx.ctx, "SELECT last_value,is_called FROM "+name).Scan(&last, &called); e != nil {
t.Fatal(e)
}
seq[name] = []any{last, called}
}
}
r10Save(t, "namespace", map[string]string{"bucket": fx.bucket, "index": fx.index})
return map[string]any{"pg": universeDump(t, fx.pool), "index": recoveryIndexReadback(t, fx), "versions": objects.Versions, "delete_markers": objects.DeleteMarkers, "sequences": seq}
}
func r10Unchanged(t *testing.T, fx *writeSetFixture, before map[string]any) {
t.Helper()
after := r10State(t, fx)
r10Save(t, "before", before)
r10Save(t, "after", after)
if !reflect.DeepEqual(before, after) {
t.Fatal("rejected contract changed rows, ES CAS, exact object versions or sequence state")
}
}
func r10Sequences(t *testing.T, fx *writeSetFixture) {
r10Exec(t, fx, `CREATE SEQUENCE chunks_seq_id_seq; ALTER TABLE chunks ADD COLUMN seq_id bigint NOT NULL DEFAULT nextval('chunks_seq_id_seq'); CREATE UNIQUE INDEX r10_chunks_seq ON chunks(seq_id);
CREATE SEQUENCE knowledge_tags_seq_id_seq; ALTER TABLE knowledge_tags ADD COLUMN seq_id bigint NOT NULL DEFAULT nextval('knowledge_tags_seq_id_seq'); CREATE UNIQUE INDEX r10_tags_seq ON knowledge_tags(seq_id);
CREATE SEQUENCE wiki_log_entries_id_seq; ALTER TABLE wiki_log_entries ALTER COLUMN id SET DEFAULT nextval('wiki_log_entries_id_seq'); ALTER SEQUENCE wiki_log_entries_id_seq OWNED BY wiki_log_entries.id; ALTER TABLE wiki_log_entries ADD PRIMARY KEY(id);
INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id) VALUES('tag-other',10001,'kb-other'); INSERT INTO wiki_log_entries(tenant_id,knowledge_base_id) VALUES(10001,'kb-other')`)
}
func r10LocalRows(parts map[string][]map[string]any) {
parts["chunks"][0]["seq_id"] = 10
parts["knowledge_tags"] = []map[string]any{{"id": "tag-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "seq_id": 10}}
parts["wiki_log_entries"] = []map[string]any{{"id": 100, "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB}, {"id": 2, "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB}}
}
func TestR10SequenceRejectionIsolated(t *testing.T) {
for _, table := range []string{"chunks", "knowledge_tags", "wiki_log_entries"} {
for _, mode := range []string{"behind", "exhausted", "explicit-null"} {
t.Run(table+"-"+mode, func(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
r10Sequences(t, fx)
column := "seq_id"
if table == "wiki_log_entries" {
column = "id"
}
sequence := table + "_" + column + "_seq"
if mode == "behind" {
r10Exec(t, fx, fmt.Sprintf("SELECT setval('%s',1,false)", sequence))
}
if mode == "exhausted" {
r10Exec(t, fx, fmt.Sprintf("SELECT setval('%s',9223372036854775807,true)", sequence))
}
snapshot := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) {
r10LocalRows(parts)
if mode == "explicit-null" {
parts[table][0][column] = nil
}
})
before := r10State(t, fx)
target := fx.target(t)
result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil)
r10Save(t, "outcome", result)
if result.State != "failed" || result.FailedAt != "" {
t.Fatalf("must reject before a business stage: %+v", result)
}
r10Unchanged(t, fx, before)
})
}
}
}
func TestR10SequenceOrderingReplayIsolated(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
r10Sequences(t, fx)
r10Exec(t, fx, `ALTER TABLE chunks ADD COLUMN chunk_index integer DEFAULT 0; ALTER TABLE knowledge_tags ADD COLUMN sort_order integer DEFAULT 0; ALTER TABLE knowledge_tags ADD COLUMN created_at timestamptz DEFAULT '2026-01-01T00:00:00Z'`)
before := universeDump(t, fx.pool)
snapshot := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) {
r10LocalRows(parts)
parts["chunks"][0]["seq_id"] = 100
parts["chunks"][0]["chunk_index"] = 0
parts["chunks"] = append(parts["chunks"], map[string]any{"id": "chunk-src-2", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "knowledge_id": "doc-src", "content": "second chunk", "seq_id": 2, "chunk_index": 1})
parts["knowledge_tags"][0]["seq_id"] = 100
parts["knowledge_tags"] = append(parts["knowledge_tags"], map[string]any{"id": "tag-src-2", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "seq_id": 2})
for _, row := range parts["knowledge_tags"] {
row["sort_order"] = 0
row["created_at"] = "2026-01-01T00:00:00Z"
}
})
target := fx.target(t)
result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil)
if result.State != "succeeded" {
t.Fatalf("normal allocation: %+v", result)
}
r10Save(t, "plan", result.Backup.WriteSet)
var newest, older int64
if e := fx.pool.QueryRow(fx.ctx, `SELECT max(id),min(id) FROM wiki_log_entries WHERE knowledge_base_id='kb-target'`).Scan(&newest, &older); e != nil {
t.Fatal(e)
}
if newest <= older {
t.Fatal("numeric log ordering collapsed")
}
var cursor int64
if e := fx.pool.QueryRow(fx.ctx, `SELECT id FROM wiki_log_entries WHERE knowledge_base_id='kb-target' AND id<$1 ORDER BY id DESC LIMIT 1`, newest).Scan(&cursor); e != nil || cursor != older {
t.Fatal("consumer cursor order", e)
}
mapped := map[string]string{}
for _, m := range result.Backup.WriteSet.LocalIDs {
if m.Table == "wiki_log_entries" {
mapped[m.Source] = m.Target
}
}
if mapped["100"] != fmt.Sprint(newest) || mapped["2"] != fmt.Sprint(older) {
t.Fatal("mapping used lexical instead of numeric order")
}
var tagOrder, chunkOrder []string
if e := fx.pool.QueryRow(fx.ctx, `SELECT array_agg(id ORDER BY sort_order ASC, created_at DESC, seq_id DESC) FROM knowledge_tags WHERE knowledge_base_id='kb-target'`).Scan(&tagOrder); e != nil {
t.Fatal(e)
}
if e := fx.pool.QueryRow(fx.ctx, `SELECT array_agg(id ORDER BY chunk_index ASC) FROM chunks WHERE knowledge_base_id='kb-target'`).Scan(&chunkOrder); e != nil {
t.Fatal(e)
}
if !reflect.DeepEqual(tagOrder, []string{"tag-src", "tag-src-2"}) || !reflect.DeepEqual(chunkOrder, []string{"chunk-src", "chunk-src-2"}) {
t.Fatal("application sort changed after numeric remapping", tagOrder, chunkOrder)
}
for _, m := range result.Backup.WriteSet.LocalIDs {
if m.Table == "chunks" {
var id string
if e := fx.pool.QueryRow(fx.ctx, `SELECT id FROM chunks WHERE tenant_id=$1 AND seq_id=$2::bigint`, wsTargetTenant, m.Target).Scan(&id); e != nil || (m.Source == "100" && id != "chunk-src") || (m.Source == "2" && id != "chunk-src-2") {
t.Fatal("seq-ID consumer disagrees with frozen map", e)
}
}
}
r10Save(t, "consumer-orders", map[string]any{"tags": tagOrder, "chunks": chunkOrder, "wiki_desc": []int64{newest, older}, "wiki_cursor": cursor})
published := r10State(t, fx)
next := fx.target(t)
if e := next.AdoptWriteSet(*result.Backup.WriteSet); e != nil {
t.Fatal(e)
}
for _, stage := range libraryrelease.Stages() {
if e := next.Apply(fx.ctx, stage, snapshot); e != nil {
t.Fatal(e)
}
}
r10Unchanged(t, fx, published)
if e := next.Restore(fx.ctx, result.Backup); e != nil {
t.Fatal(e)
}
if !reflect.DeepEqual(before, universeDump(t, fx.pool)) {
t.Fatal("rollback changed original local numbers")
}
if !reflect.DeepEqual(published["sequences"], r10State(t, fx)["sequences"]) {
t.Fatal("rollback rewound sequences")
}
}
func TestR10SourceSchemaBoundIsolated(t *testing.T) {
fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, embeddingDimension: 1024})
seedTargetData(t, fx)
r10Sequences(t, fx)
fx.indexDoc(t, "chunk-target", wsTargetTenant, wsTargetKB, "doc-target", "图:resource://"+wsHandleTarget)
before := r10State(t, fx)
pg, e := ExportLibrary(fx.ctx, fx.pool, PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB})
if e != nil {
t.Fatal(e)
}
target := fx.target(t)
es, e := target.Search().ExportLibrary(fx.ctx, SearchIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}, 100)
if e != nil {
t.Fatal(e)
}
archive, e := librarysnapshot.Open(fx.archiveRoot, 128*1024*1024)
if e != nil {
t.Fatal(e)
}
defer archive.Close()
contract := librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", EmbeddingDimension: 1024, IndexMappingSHA256: es.MappingSHA256}
id, e := ArchiveLibraryCandidate(fx.ctx, archive, "internal", PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}, contract, pg, es, fx.objects, time.Now().UTC())
if e != nil {
t.Fatal(e)
}
manifest, e := archive.Load(id)
if e != nil {
t.Fatal(e)
}
r10Save(t, "manifest", manifest)
bound := false
for _, part := range manifest.Parts {
if part.Kind == "schema" && part.Name == "migration-catalog" {
bound = true
}
}
r10Unchanged(t, fx, before)
if !bound {
t.Fatal("captured source has no snapshot-bound schema catalog")
}
if _, e := target.preflightMigrationCatalog(fx.ctx, archive, manifest); e != nil {
t.Fatal("matching source schema rejected", e)
}
r10Exec(t, fx, `ALTER TABLE chunks ADD COLUMN r10_drift text`)
drifted := r10State(t, fx)
if _, e := target.preflightMigrationCatalog(fx.ctx, archive, manifest); e == nil || !strings.Contains(e.Error(), "source/target schema catalog mismatch") {
t.Fatal("source schema drift not rejected", e)
} else {
r10Save(t, "schema-drift-rejection", e.Error())
}
r10Unchanged(t, fx, drifted)
}
@@ -0,0 +1,353 @@
package v071
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"reflect"
"sort"
"strings"
"testing"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/libraryrelease"
)
type r11Column struct {
Table string `json:"table_name"`
Name string `json:"column_name"`
Type string `json:"type"`
Default string `json:"default_expr"`
Required bool `json:"not_null"`
}
type r11Catalog struct {
Columns []r11Column `json:"columns"`
Constraints []struct {
Table string `json:"table_name"`
Name string `json:"name"`
Definition string `json:"definition"`
} `json:"constraints"`
Indexes []struct {
Name string `json:"name"`
Definition string `json:"definition"`
} `json:"indexes"`
Sequences []struct {
Name string `json:"sequence"`
Start int64 `json:"seqstart"`
} `json:"sequences"`
}
func r11CatalogData(t *testing.T) r11Catalog {
t.Helper()
raw, e := os.ReadFile("testdata/catalog-v071-r11.json")
if e != nil {
t.Fatal(e)
}
var c r11Catalog
if e = json.Unmarshal(raw, &c); e != nil {
t.Fatal(e)
}
return c
}
func r11Fill(t *testing.T, fx *writeSetFixture, table string, row map[string]any) map[string]any {
t.Helper()
if table == "resources" && row["location_hash"] == nil {
sum := sha256.Sum256([]byte(fmt.Sprint(row["physical_path"])))
row["location_hash"] = hex.EncodeToString(sum[:])
}
for _, c := range r11CatalogData(t).Columns {
if c.Table != table {
continue
}
if v, ok := row[c.Name]; ok && (v != nil || !c.Required) {
continue
}
expr := c.Default
if c.Name == "seq_id" {
expr = "10"
}
if table == "wiki_log_entries" && c.Name == "id" {
expr = "100"
}
if expr == "" {
if !c.Required {
row[c.Name] = nil
continue
}
switch c.Type {
case "bigint", "integer":
expr = "0"
case "boolean":
expr = "false"
default:
expr = "''"
}
}
var raw []byte
if e := fx.pool.QueryRow(fx.ctx, "SELECT to_jsonb(("+expr+")::"+c.Type+")").Scan(&raw); e != nil {
t.Fatal(table, c.Name, e)
}
var v any
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.UseNumber()
if e := dec.Decode(&v); e != nil {
t.Fatal(e)
}
row[c.Name] = v
}
raw, e := json.Marshal(row)
if e != nil {
t.Fatal(e)
}
var canonical []byte
if e = fx.pool.QueryRow(fx.ctx, "SELECT to_jsonb(jsonb_populate_record(NULL::"+table+",$1::jsonb))", raw).Scan(&canonical); e != nil {
t.Fatal(e)
}
dec := json.NewDecoder(strings.NewReader(string(canonical)))
dec.UseNumber()
if e = dec.Decode(&row); e != nil {
t.Fatal(e)
}
return row
}
func r11Insert(t *testing.T, fx *writeSetFixture, table string, row map[string]any) {
t.Helper()
r11Fill(t, fx, table, row)
keys := []string{}
for k := range row {
keys = append(keys, k)
}
sort.Strings(keys)
cols := []string{}
for _, k := range keys {
cols = append(cols, pgx.Identifier{k}.Sanitize())
}
raw, e := json.Marshal(row)
if e != nil {
t.Fatal(e)
}
if _, e = fx.pool.Exec(fx.ctx, "INSERT INTO "+table+"("+strings.Join(cols, ",")+") SELECT "+strings.Join(cols, ",")+" FROM jsonb_populate_record(NULL::"+table+",$1::jsonb)", raw); e != nil {
t.Fatal(table, e)
}
}
// Reconstruct only the ten migration tables from preserved real v071 catalog.
// The grant table is an inbound-FK fixture, not a claimed whole business mirror.
func r11Mirror(t *testing.T, fx *writeSetFixture) {
t.Helper()
old := universeDump(t, fx.pool)
c := r11CatalogData(t)
r10Exec(t, fx, `CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; CREATE EXTENSION IF NOT EXISTS pg_trgm; DROP TABLE IF EXISTS resource_access_grants CASCADE; DROP TABLE `+strings.Join(productionLibraryTables, ",")+` CASCADE`)
for _, s := range c.Sequences {
r10Exec(t, fx, fmt.Sprintf("CREATE SEQUENCE %s START %d", s.Name, s.Start))
}
for _, table := range productionLibraryTables {
defs := []string{}
for _, col := range c.Columns {
if col.Table != table {
continue
}
d := pgx.Identifier{col.Name}.Sanitize() + " " + col.Type
if col.Required {
d += " NOT NULL"
}
if col.Default != "" {
d += " DEFAULT " + col.Default
}
defs = append(defs, d)
}
r10Exec(t, fx, "CREATE TABLE "+table+"("+strings.Join(defs, ",")+")")
}
r10Exec(t, fx, `ALTER SEQUENCE wiki_log_entries_id_seq OWNED BY wiki_log_entries.id; CREATE TABLE resource_access_grants(id text,resource_id varchar(36))`)
names := map[string]bool{}
sort.SliceStable(c.Constraints, func(i, j int) bool {
return !strings.HasPrefix(c.Constraints[i].Definition, "FOREIGN KEY") && strings.HasPrefix(c.Constraints[j].Definition, "FOREIGN KEY")
})
for _, constraint := range c.Constraints {
r10Exec(t, fx, "ALTER TABLE "+constraint.Table+" ADD CONSTRAINT "+constraint.Name+" "+constraint.Definition)
names[constraint.Name] = true
}
for _, index := range c.Indexes {
if !names[index.Name] {
r10Exec(t, fx, index.Definition)
}
}
n := int64(100000000)
for _, table := range []string{"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations", "resources", "resource_bindings", "wiki_folders", "wiki_pages", "wiki_page_issues", "wiki_log_entries"} {
for _, raw := range old[table] {
row := map[string]any{}
dec := json.NewDecoder(strings.NewReader(raw))
dec.UseNumber()
if e := dec.Decode(&row); e != nil {
t.Fatal(e)
}
allowed := map[string]bool{}
for _, col := range c.Columns {
if col.Table == table {
allowed[col.Name] = true
}
}
for k := range row {
if !allowed[k] {
delete(row, k)
}
}
if table == "chunks" || table == "knowledge_tags" {
n++
row["seq_id"] = n
}
r11Insert(t, fx, table, row)
}
}
r10Exec(t, fx, fmt.Sprintf("SELECT setval('chunks_seq_id_seq',%d,true);SELECT setval('knowledge_tags_seq_id_seq',%d,true)", n, n))
}
func r11Source(t *testing.T, fx *writeSetFixture, tweak func(map[string][]map[string]any)) string {
return sealSourceSnapshot(t, fx, func(p map[string][]map[string]any) {
p["knowledge_tags"] = []map[string]any{{"id": "tag-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "name": "source-tag"}}
p["knowledge_tag_relations"] = []map[string]any{{"knowledge_id": "doc-src", "tag_id": "tag-src"}}
p["wiki_folders"] = []map[string]any{{"id": "folder-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "name": "folder", "parent_id": ""}}
p["wiki_pages"][0]["folder_id"] = "folder-src"
p["wiki_page_issues"] = []map[string]any{{"id": "issue-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "slug": "index", "issue_type": "review", "reported_by": "fixture", "description": "example"}}
p["wiki_log_entries"] = []map[string]any{{"id": 100, "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "action": "ingest", "knowledge_id": "doc-src", "pages_affected": []any{map[string]any{"slug": "index", "title": "historic title"}}}}
if tweak != nil {
tweak(p)
}
for table, rows := range p {
for _, row := range rows {
r11Fill(t, fx, table, row)
}
}
})
}
func r11Reject(t *testing.T, fx *writeSetFixture, snapshot string) {
t.Helper()
before := r10State(t, fx)
target := fx.target(t)
out := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil)
r10Save(t, "outcome", out)
if out.State != "failed" || out.FailedAt != "" {
t.Errorf("expected pre-stage rejection: %+v", out)
}
r10Unchanged(t, fx, before)
}
func TestR11StableIdentityMatrixIsolated(t *testing.T) {
for _, table := range []string{"knowledges", "chunks", "knowledge_tags", "resources", "resource_bindings", "wiki_folders", "wiki_pages", "wiki_page_issues"} {
for _, foreign := range []string{"same-tenant-other-kb", "other-tenant"} {
t.Run(table+"/"+foreign, func(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
r11Mirror(t, fx)
tenant := uint64(wsTargetTenant)
kb := wsOtherKB
if foreign == "other-tenant" {
tenant = 10003
kb = "kb-alien"
}
id := map[string]string{"knowledges": "doc-src", "chunks": "chunk-src", "knowledge_tags": "tag-src", "resources": "res-src", "resource_bindings": "bind-src", "wiki_folders": "folder-src", "wiki_pages": "wiki-src", "wiki_page_issues": "issue-src"}[table]
row := map[string]any{"id": id, "tenant_id": tenant, "knowledge_base_id": kb}
switch table {
case "chunks":
row["knowledge_id"] = "doc-other"
row["seq_id"] = int64(900000001)
case "resources":
delete(row, "knowledge_base_id")
row["handle"] = strings.Repeat("x", 22)
row["provider"] = "minio"
row["physical_path"] = "outside"
row["location_hash"] = "outside"
case "resource_bindings":
delete(row, "knowledge_base_id")
row["resource_id"] = "res-other"
row["owner_type"] = "knowledge"
row["owner_id"] = "doc-other"
row["relation"] = "preview"
case "wiki_pages", "wiki_page_issues":
row["slug"] = "foreign"
}
r11Insert(t, fx, table, row)
snapshot := r11Source(t, fx, nil)
r11Reject(t, fx, snapshot)
})
}
}
}
func TestR11NaturalKeyMatrixIsolated(t *testing.T) {
for _, mode := range []string{"valid", "tag-name", "tag-name-soft-deleted", "binding-tuple", "folder-name", "folder-deleted-positive", "folder-parent-distinct-positive", "page-slug", "page-deleted-positive", "resource-handle", "resource-location", "resource-location-deleted-positive", "physical-key"} {
t.Run(mode, func(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
r11Mirror(t, fx)
if mode == "resource-handle" {
r10Exec(t, fx, `UPDATE resources SET handle='`+wsHandleSource+`' WHERE id='res-other'`)
}
if strings.HasPrefix(mode, "resource-location") {
path := wsLocator("backend-target", "minio", fx.bucket, wsTargetTenant, "res-src")
sum := sha256.Sum256([]byte(path))
deleted := "NULL"
if strings.HasSuffix(mode, "positive") {
deleted = "now()"
}
r10Exec(t, fx, `UPDATE resources SET location_hash='`+hex.EncodeToString(sum[:])+`',deleted_at=`+deleted+` WHERE id='res-other'`)
}
if mode == "physical-key" {
if e := fx.objects.s3.Put(fx.ctx, "minio", wsLocator("backend-target", "minio", fx.bucket, wsTargetTenant, "res-src"), strings.NewReader("foreign-data"), 12); e != nil {
t.Fatal(e)
}
}
snapshot := r11Source(t, fx, func(p map[string][]map[string]any) {
table := ""
switch mode {
case "tag-name", "tag-name-soft-deleted":
table = "knowledge_tags"
case "binding-tuple":
table = "resource_bindings"
case "folder-name", "folder-deleted-positive", "folder-parent-distinct-positive":
table = "wiki_folders"
case "page-slug", "page-deleted-positive":
table = "wiki_pages"
}
if table == "" {
return
}
cp := map[string]any{}
for k, v := range p[table][0] {
cp[k] = v
}
cp["id"] = cp["id"].(string) + "-second"
if table == "knowledge_tags" {
cp["seq_id"] = 11
}
if strings.Contains(mode, "deleted") {
cp["deleted_at"] = "2026-01-01T00:00:00Z"
}
if mode == "folder-parent-distinct-positive" {
cp["parent_id"] = "folder-src"
}
p[table] = append(p[table], cp)
})
if mode != "valid" && !strings.HasSuffix(mode, "positive") {
r11Reject(t, fx, snapshot)
return
}
before := r10State(t, fx)
target := fx.target(t)
out := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil)
r10Save(t, "outcome", out)
if out.State != "succeeded" {
t.Fatalf("normal admitted data must succeed: %+v", out)
}
if e := target.Restore(fx.ctx, out.Backup); e != nil {
t.Fatal(e)
}
after := r10State(t, fx)
for _, key := range []string{"pg", "versions", "delete_markers"} {
if !reflect.DeepEqual(before[key], after[key]) {
t.Fatal("restore changed", key)
}
}
r10Save(t, "restored", after)
})
}
}
@@ -0,0 +1,42 @@
package v071
import (
"knowledge-governance/internal/libraryrelease"
"testing"
)
func TestR10RestoreForeignResourceReferencesIsolated(t *testing.T) {
for _, mode := range []string{"unknown-binding", "foreign-wiki-body", "foreign-knowledge-metadata"} {
t.Run(mode, func(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
r10Exec(t, fx, `ALTER TABLE knowledges ADD COLUMN metadata jsonb`)
snapshot := sealSourceSnapshot(t, fx, nil)
target := fx.target(t)
result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil)
if result.State != "succeeded" {
t.Fatalf("prepare publication: %+v", result)
}
switch mode {
case "unknown-binding":
r10Exec(t, fx, `INSERT INTO resource_bindings(id,tenant_id,resource_id,owner_type,owner_id) VALUES('binding-unknown',10001,'res-src','unknown','outside-owner')`)
case "foreign-wiki-body":
if _, e := fx.pool.Exec(fx.ctx, `INSERT INTO wiki_pages(id,tenant_id,knowledge_base_id,slug,content) VALUES('foreign-wiki',10001,'kb-other','foreign',$1)`, "![external](resource://"+wsHandleSource+")"); e != nil {
t.Fatal(e)
}
case "foreign-knowledge-metadata":
if _, e := fx.pool.Exec(fx.ctx, `UPDATE knowledges SET metadata=jsonb_build_object('image_info',jsonb_build_object('url',$1::text)) WHERE id='doc-other'`, "resource://"+wsHandleSource); e != nil {
t.Fatal(e)
}
}
before := r10State(t, fx)
e := target.Restore(fx.ctx, result.Backup)
if e == nil {
t.Error("restore deleted a resource with an out-of-plan reference")
} else {
r10Save(t, "held", e.Error())
}
r10Unchanged(t, fx, before)
})
}
}
@@ -0,0 +1,188 @@
package v071
import (
"encoding/json"
"knowledge-governance/internal/libraryrelease"
"knowledge-governance/internal/librarysnapshot"
"os"
"reflect"
"strings"
"testing"
"time"
)
func TestR11CatalogBindingIsolated(t *testing.T) {
for _, mode := range []string{"matching", "default", "unique-predicate", "sequence-definition", "sequence-ownership", "incoming-fk", "outgoing-fk", "internal-local-fk", "generated", "trigger"} {
t.Run(mode, func(t *testing.T) {
fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, embeddingDimension: 1024})
seedTargetData(t, fx)
r11Mirror(t, fx)
target := fx.target(t)
pg, e := ExportLibrary(fx.ctx, fx.pool, PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB})
if e != nil {
t.Fatal(e)
}
catalog, digest, e := target.migrationCatalog(fx.ctx)
if e != nil {
t.Fatal(e)
}
if !reflect.DeepEqual(catalog, pg.Catalog) {
t.Fatal("captured source and target catalogs differ")
}
expected := r11CatalogData(t)
var cols []r11Column
if e = json.Unmarshal(catalog["columns"], &cols); e != nil {
t.Fatal(e)
}
if !reflect.DeepEqual(cols, expected.Columns) {
t.Fatal("real v071 columns/defaults/types differ from reconstructed target")
}
var indexes []map[string]any
json.Unmarshal(catalog["indexes"], &indexes)
if len(indexes) != len(expected.Indexes) {
t.Fatal("missing actual indexes")
}
expectedRaw, e := os.ReadFile("testdata/catalog-v071-r11.json")
if e != nil {
t.Fatal(e)
}
var original map[string]json.RawMessage
json.Unmarshal(expectedRaw, &original)
for _, kind := range []string{"columns", "constraints", "indexes", "triggers", "relations"} {
var a, b any
json.Unmarshal(original[kind], &a)
json.Unmarshal(catalog[kind], &b)
if !reflect.DeepEqual(a, b) {
t.Fatal("catalog mismatch", kind)
}
}
r10Save(t, "source-catalog", pg.Catalog)
r10Save(t, "schema-digest", digest)
es, e := target.Search().ExportLibrary(fx.ctx, SearchIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}, 100)
if e != nil {
t.Fatal(e)
}
archive, e := librarysnapshot.Open(fx.archiveRoot, 128*1024*1024)
if e != nil {
t.Fatal(e)
}
defer archive.Close()
compatibility := librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", EmbeddingDimension: 1024, IndexMappingSHA256: es.MappingSHA256}
snapshot, e := ArchiveLibraryCandidate(fx.ctx, archive, "internal", PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}, compatibility, pg, es, fx.objects, time.Now().UTC())
if e != nil {
t.Fatal(e)
}
if mode == "matching" {
before := r10State(t, fx)
manifest, e := archive.Load(snapshot)
if e != nil {
t.Fatal(e)
}
got, e := target.preflightMigrationCatalog(fx.ctx, archive, manifest)
if e != nil || got != digest {
t.Fatal(got, e)
}
r10Unchanged(t, fx, before)
return
}
statements := map[string]string{
"default": `ALTER TABLE chunks ALTER COLUMN flags SET DEFAULT 7`,
"unique-predicate": `DROP INDEX idx_wiki_pages_kb_slug;CREATE UNIQUE INDEX idx_wiki_pages_kb_slug ON wiki_pages(knowledge_base_id,slug) WHERE deleted_at IS NOT NULL`,
"sequence-definition": `ALTER SEQUENCE chunks_seq_id_seq INCREMENT 2`,
"sequence-ownership": `ALTER SEQUENCE chunks_seq_id_seq OWNED BY chunks.seq_id`,
"incoming-fk": `CREATE TABLE outside_cursor(log_id bigint REFERENCES wiki_log_entries(id))`,
"outgoing-fk": `CREATE TABLE outside_models(id varchar(64) PRIMARY KEY);ALTER TABLE knowledges ADD FOREIGN KEY(embedding_model_id) REFERENCES outside_models(id)`,
"internal-local-fk": `ALTER TABLE wiki_page_issues ADD COLUMN log_id bigint REFERENCES wiki_log_entries(id)`,
"generated": `ALTER TABLE wiki_pages ADD COLUMN lower_slug text GENERATED ALWAYS AS(lower(slug)) STORED`,
"trigger": `CREATE FUNCTION r11_noop() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RETURN NEW; END';CREATE TRIGGER r11_noop BEFORE INSERT ON wiki_pages FOR EACH ROW EXECUTE FUNCTION r11_noop()`,
}
r10Exec(t, fx, statements[mode])
r11Reject(t, fx, snapshot)
// An identically extended source/target must not make an unreviewed FK safe.
if strings.Contains(mode, "fk") {
now, _, e := target.migrationCatalog(fx.ctx)
if e != nil {
t.Fatal(e)
}
if e = validateMigrationCatalog(now); e == nil {
t.Fatal("unreviewed FK admitted when both sides match")
}
r10Save(t, "unknown-fk-rejection", e.Error())
}
})
}
}
func TestR11ReferenceAndCursorIsolated(t *testing.T) {
for _, mode := range []string{"valid", "linked-valid", "legacy-pages", "historical-log", "chunk-parent", "chunk-pre", "chunk-next", "chunk-tag", "wiki-folder", "folder-parent", "folder-cycle", "wiki-source", "wiki-chunk", "log-object-id", "log-array-number"} {
t.Run(mode, func(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
r11Mirror(t, fx)
snapshot := r11Source(t, fx, func(p map[string][]map[string]any) {
switch mode {
case "linked-valid":
p["chunks"] = append(p["chunks"], map[string]any{"id": "chunk-src-2", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "knowledge_id": "doc-src", "content": "second", "seq_id": 11, "pre_chunk_id": "chunk-src", "parent_chunk_id": "chunk-src"})
p["chunks"][0]["next_chunk_id"] = "chunk-src-2"
p["chunks"][0]["tag_id"] = "tag-src"
p["wiki_pages"][0]["source_refs"] = []string{"doc-src|Source title"}
p["wiki_pages"][0]["chunk_refs"] = []string{"chunk-src-2"}
p["wiki_pages"][0]["page_metadata"] = map[string]any{"literal_number": 100, "tags": []string{"literal"}}
case "legacy-pages":
p["wiki_log_entries"][0]["pages_affected"] = []string{"index", "historic-removed-page"}
case "historical-log":
p["wiki_log_entries"][0]["knowledge_id"] = "deleted-knowledge"
p["wiki_log_entries"][0]["pages_affected"] = []any{map[string]any{"slug": "deleted-page", "title": "historic"}}
case "chunk-parent":
p["chunks"][0]["parent_chunk_id"] = "chunk-other"
case "chunk-pre":
p["chunks"][0]["pre_chunk_id"] = "chunk-other"
case "chunk-next":
p["chunks"][0]["next_chunk_id"] = "chunk-other"
case "chunk-tag":
p["chunks"][0]["tag_id"] = "tag-outside"
case "wiki-folder":
p["wiki_pages"][0]["folder_id"] = "foreign-folder"
case "folder-parent":
p["wiki_folders"][0]["parent_id"] = "foreign-folder"
case "folder-cycle":
p["wiki_folders"][0]["parent_id"] = "folder-src"
case "wiki-source":
p["wiki_pages"][0]["source_refs"] = []string{"doc-other"}
case "wiki-chunk":
p["wiki_pages"][0]["chunk_refs"] = []string{"chunk-other"}
case "log-object-id":
p["wiki_log_entries"][0]["pages_affected"] = []any{map[string]any{"slug": "index", "log_id": 100}}
case "log-array-number":
p["wiki_log_entries"][0]["pages_affected"] = []int{100}
}
})
if mode != "valid" && mode != "linked-valid" && mode != "legacy-pages" && mode != "historical-log" {
r11Reject(t, fx, snapshot)
return
}
target := fx.target(t)
out := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil)
if out.State != "succeeded" {
t.Fatal(out)
}
var actual int64
if e := fx.pool.QueryRow(fx.ctx, `SELECT id FROM wiki_log_entries WHERE knowledge_base_id=$1`, wsTargetKB).Scan(&actual); e != nil {
t.Fatal(e)
}
var sourceCursor, validCursor int
if e := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM wiki_log_entries WHERE knowledge_base_id=$1 AND id<100`, wsTargetKB).Scan(&sourceCursor); e != nil {
t.Fatal(e)
}
if e := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM wiki_log_entries WHERE knowledge_base_id=$1 AND id<$2`, wsTargetKB, actual).Scan(&validCursor); e != nil {
t.Fatal(e)
}
if actual == 100 || sourceCursor == validCursor {
t.Fatal("expected evidence of DB-local old cursor not transferable")
}
r10Save(t, "cursor-boundary", map[string]any{"source_cursor": 100, "mapped_id": actual, "source_cursor_count": sourceCursor, "mapped_cursor_count": validCursor, "policy": "fresh target cursor works; cross-source or pre-replace external cursor is not automatically translated"})
if e := target.Restore(fx.ctx, out.Backup); e != nil {
t.Fatal(e)
}
})
}
}
@@ -0,0 +1,81 @@
package v071
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
)
// This is only a faulting wire: every response, commit and CAS originates in
// the real isolated ES. Successful bodies are recorded, then one is withheld.
func formalElasticFaultProxy(t *testing.T, root, upstream, fault string) string {
t.Helper()
var mu sync.Mutex
dropped := false
events := []map[string]any{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, e := io.ReadAll(r.Body)
if e != nil {
http.Error(w, "read failed", 500)
return
}
request, e := http.NewRequestWithContext(r.Context(), r.Method, upstream+r.URL.RequestURI(), bytes.NewReader(raw))
if e != nil {
http.Error(w, "request failed", 500)
return
}
request.Header = r.Header.Clone()
response, e := http.DefaultClient.Do(request)
if e != nil {
http.Error(w, "upstream failed", 502)
return
}
body, e := io.ReadAll(response.Body)
response.Body.Close()
if e != nil {
http.Error(w, "upstream body failed", 502)
return
}
mutating := r.Method == "PUT" || r.Method == "DELETE" || strings.Contains(r.URL.Path, "_bulk")
mu.Lock()
selected := fault == "apply-clean" && strings.HasSuffix(r.URL.Path, "/_doc/chunk-src") && !bytes.Contains(raw, []byte(indexClaimPrefix))
selected = selected || (fault == "restore-write" && strings.HasSuffix(r.URL.Path, "/_create/chunk-target"))
selected = selected || (fault == "restore-clean" && r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/_doc/chunk-target") && !bytes.Contains(raw, []byte(indexRestoreClaimPrefix)))
drop := !dropped && selected && response.StatusCode >= 200 && response.StatusCode < 300
if mutating {
events = append(events, map[string]any{"method": r.Method, "path": r.URL.RequestURI(), "request": string(raw), "response": string(body), "status": response.StatusCode, "dropped": drop})
encoded, _ := json.MarshalIndent(events, "", " ")
_ = os.WriteFile(filepath.Join(root, "es-wire.json"), encoded, 0600)
}
if drop {
dropped = true
_ = os.WriteFile(filepath.Join(root, "es-response-dropped"), []byte(fault), 0600)
}
mu.Unlock()
if drop {
if hijacker, ok := w.(http.Hijacker); ok {
connection, _, err := hijacker.Hijack()
if err == nil {
connection.Close()
}
}
return
}
for k, values := range response.Header {
for _, v := range values {
w.Header().Add(k, v)
}
}
w.WriteHeader(response.StatusCode)
_, _ = w.Write(body)
}))
t.Cleanup(server.Close)
return server.URL
}
@@ -0,0 +1,340 @@
package v071
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"syscall"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
)
func recoveryIndexReadback(t *testing.T, fx *writeSetFixture) map[string]map[string]any {
t.Helper()
response, e := http.Get(fx.searchBase + "/" + fx.index + "/_search?size=100&seq_no_primary_term=true")
if e != nil {
t.Fatal(e)
}
defer response.Body.Close()
var body struct {
Hits struct {
Hits []map[string]any `json:"hits"`
} `json:"hits"`
}
if e = json.NewDecoder(response.Body).Decode(&body); e != nil {
t.Fatal(e)
}
if response.StatusCode != 200 || len(body.Hits.Hits) >= 100 {
t.Fatal("invalid independent index readback")
}
result := map[string]map[string]any{}
for _, hit := range body.Hits.Hits {
result[hit["_id"].(string)] = hit
}
return result
}
// Only the worker executable performs recovery writes. Test code submits a new
// request, kills an actual recovery process, and independently compares stores.
func runRecoveryIntentProcess(t *testing.T, root string, fx *writeSetFixture, gov *pgxpool.Pool, store *postgresstore.Store, original governance.LibraryJob, env map[string]string, start func(string, string, map[string]string) *exec.Cmd, checkpoint func(string), save func(string, any)) {
t.Helper()
ctx := context.Background()
must := func(e error) {
t.Helper()
if e != nil {
t.Fatal(e)
}
}
inventory := func() *s3.ListObjectVersionsOutput {
v, e := fx.objects.s3.client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(fx.bucket)})
must(e)
if aws.ToBool(v.IsTruncated) || len(v.DeleteMarkers) > 0 {
t.Fatal("invalid object inventory")
}
return v
}
readJSON := func(name string, out any) {
raw, e := os.ReadFile(filepath.Join(root, name))
must(e)
must(json.Unmarshal(raw, out))
}
kill := func(cmd *exec.Cmd, name string) {
must(cmd.Process.Kill())
_ = cmd.Wait()
s := cmd.ProcessState.Sys().(syscall.WaitStatus)
if !s.Signaled() || s.Signal() != syscall.SIGKILL {
t.Fatal("not SIGKILL")
}
save(name, map[string]any{"pid": cmd.Process.Pid, "exit_code": cmd.ProcessState.ExitCode(), "signal": "SIGKILL"})
}
beforeIndex := recoveryIndexReadback(t, fx)
save("index-before.json", beforeIndex)
env["KG_TEST_BARRIER_POINTS"] = "after:index"
env["WORKER_ID"] = "r9-publish"
publish := start("worker", "publish", env)
wait := func(queue, point string) string {
for i := 0; i < 600; i++ {
if point != "" {
if _, e := os.Stat(filepath.Join(root, "barriers", point+".hit")); e == nil {
return "hit"
}
}
var state, message string
must(gov.QueryRow(ctx, "SELECT state,COALESCE(last_error,'') FROM jobs WHERE id=$1", queue).Scan(&state, &message))
if state == "completed" || state == "failed" {
save("queue-"+queue+"-terminal.json", map[string]any{"state": state, "error": message})
return state
}
time.Sleep(100 * time.Millisecond)
}
checkpoint("timeout")
t.Fatal("formal process timeout", queue, point)
return "timeout"
}
queueID := original.QueueJobID
if queueID == "" {
must(gov.QueryRow(ctx, "SELECT queue_job_id FROM library_jobs WHERE id=$1", original.ID).Scan(&queueID))
}
publishResult := wait(queueID, "after-index")
if got := publishResult; got != "hit" && !(os.Getenv("KG_R9_FAULT") == "apply-clean" && got == "failed") {
checkpoint("publish-failed")
t.Fatal("publish failed", got)
}
checkpoint("published-partial")
partialPG := universeDump(t, fx.pool)
partialIndex := recoveryIndexReadback(t, fx)
partialObjects := inventory()
if publishResult == "hit" {
if reflect.DeepEqual(partialIndex, beforeIndex) || partialIndex["chunk-src"] == nil || partialIndex["chunk-target"] != nil {
t.Fatal("publish kill did not follow real index replacement")
}
}
if publishResult == "hit" {
var owner string
must(gov.QueryRow(ctx, "SELECT lease_owner FROM jobs WHERE id=$1", queueID).Scan(&owner))
kill(publish, "publish-kill.json")
must(store.FailTerminal(ctx, queueID, owner, "isolated operator requested recovery after SIGKILL", "r9_recover_requested", time.Now().UTC()))
} else {
must(publish.Process.Signal(syscall.SIGTERM))
must(publish.Wait())
if _, e := os.Stat(filepath.Join(root, "es-response-dropped")); e != nil {
t.Fatal("publish did not hit real ES commit fault")
}
}
time.Sleep(5 * time.Second)
var backup, plan, source string
must(gov.QueryRow(ctx, "SELECT snapshot_id,evidence->>'writeset_digest',evidence->>'writeset_target_snapshot' FROM library_versions WHERE kind='production_prebackup' AND source_job_id=$1", original.ID).Scan(&backup, &plan, &source))
fields := map[string]string{"scope": "internal", "window_job_id": original.ID, "source_snapshot_id": source, "target_id": env["R9_TARGET_ID"], "original_operation_id": original.OperationID, "backup_snapshot_id": backup, "plan_digest": plan}
scenario := os.Getenv("KG_R9_SCENARIO")
if scenario == "wrong-job" {
must(store.CancelLibraryJob(ctx, original.ID, "negative fixture: operator parked original publication", time.Now().UTC()))
}
if scenario != "" {
key := map[string]string{"wrong-source": "source_snapshot_id", "wrong-target": "target_id", "wrong-job": "window_job_id", "wrong-plan": "plan_digest", "wrong-operation": "original_operation_id"}[scenario]
if key != "" {
fields[key] = "wrong-identity"
} else if scenario != "arbitrary-queue" {
t.Fatal("unknown scenario", scenario)
}
}
recoverID := governance.LibraryRecoveryQueueID(fields["window_job_id"])
if scenario == "arbitrary-queue" {
recoverID = "unrelated-recovery-queue"
}
payload, e := json.Marshal(fields)
must(e)
request := jobs.EnqueueRequest{ID: recoverID, Type: "library.recover", Payload: payload, AvailableAt: time.Now().UTC(), MaxAttempts: 1, IdempotencyKey: "library.recover:" + fields["window_job_id"]}
queued, e := store.Enqueue(ctx, request, time.Now().UTC())
must(e)
save("recovery-request.json", queued)
env["KG_TEST_BARRIER_POINTS"] = "restore:index"
env["WORKER_ID"] = "r9-recover-1"
worker := start("worker", "recovery-1", env)
if scenario != "" {
if got := wait(recoverID, ""); got != "failed" {
t.Fatal("invalid recovery accepted", scenario, got)
}
must(worker.Process.Signal(syscall.SIGTERM))
must(worker.Wait())
checkpoint("rejected")
if !reflect.DeepEqual(partialPG, universeDump(t, fx.pool)) || !reflect.DeepEqual(partialIndex, recoveryIndexReadback(t, fx)) || !reflect.DeepEqual(partialObjects.Versions, inventory().Versions) {
t.Fatal("rejected request changed business stores")
}
save("recovery-result.json", map[string]any{"scenario": scenario, "rejected": true, "business_stores_unchanged": true})
return
}
if os.Getenv("KG_R9_FAULT") == "apply-clean" || os.Getenv("KG_R9_FAULT") == "restore-clean" {
if got := wait(recoverID, ""); got != "failed" {
t.Fatal("unattributable clean commit did not remain held", got)
}
must(worker.Process.Signal(syscall.SIGTERM))
must(worker.Wait())
checkpoint("clean-unknown-held")
if _, e := os.Stat(filepath.Join(root, "es-response-dropped")); e != nil {
t.Fatal("fault not exercised")
}
heldPG, heldIndex, heldObjects := universeDump(t, fx.pool), recoveryIndexReadback(t, fx), inventory()
wireBefore, e := os.ReadFile(filepath.Join(root, "es-wire.json"))
must(e)
time.Sleep(5 * time.Second)
retried, e := store.RetryLibraryRecovery(ctx, recoverID, original.ID, time.Now().UTC())
must(e)
if !retried {
t.Fatal("retry unavailable")
}
env["WORKER_ID"] = "r9-clean-held-replay"
worker = start("worker", "clean-held-replay", env)
if got := wait(recoverID, ""); got != "failed" {
t.Fatal("clean unknown replay accepted", got)
}
must(worker.Process.Signal(syscall.SIGTERM))
must(worker.Wait())
wireAfter, e := os.ReadFile(filepath.Join(root, "es-wire.json"))
must(e)
if !reflect.DeepEqual(heldPG, universeDump(t, fx.pool)) || !reflect.DeepEqual(heldIndex, recoveryIndexReadback(t, fx)) || !reflect.DeepEqual(heldObjects.Versions, inventory().Versions) || string(wireBefore) != string(wireAfter) {
t.Fatal("held replay rewrote business state or resent ES mutation")
}
var journal map[string]any
readJSON("maintenance/"+original.ID+".json", &journal)
if journal["state"] != "held" {
t.Fatal("unknown not held", journal["state"])
}
save("recovery-result.json", map[string]any{"fault": os.Getenv("KG_R9_FAULT"), "state": "held", "no_repeated_ES_mutations": true, "replay_stores_unchanged": true})
return
}
if os.Getenv("KG_R9_FAULT") == "restore-write" {
if got := wait(recoverID, ""); got != "failed" {
t.Fatal("restore response fault not observed", got)
}
checkpoint("unknown-restore-red")
must(worker.Process.Signal(syscall.SIGTERM))
must(worker.Wait())
if _, e := os.Stat(filepath.Join(root, "es-response-dropped")); e != nil {
t.Fatal("no real ES response was dropped")
}
time.Sleep(5 * time.Second)
retried, e := store.RetryLibraryRecovery(ctx, recoverID, original.ID, time.Now().UTC())
must(e)
if !retried {
t.Fatal("recovery retry not queued")
}
env["WORKER_ID"] = "r9-recover-after-unknown"
worker = start("worker", "recovery-after-unknown", env)
}
if got := wait(recoverID, "restore-index"); got != "hit" {
checkpoint("recovery-failed")
t.Fatal("recovery did not reach real restored-index boundary", got)
}
checkpoint("recovery-interrupted")
indexAtKill := recoveryIndexReadback(t, fx)
save("index-at-recovery-kill.json", indexAtKill)
kill(worker, "recovery-kill.json")
time.Sleep(5 * time.Second)
env["WORKER_ID"] = "r9-recover-2"
worker = start("worker", "recovery-2", env)
if got := wait(recoverID, ""); got != "completed" {
checkpoint("recovery-failed")
t.Fatal("recovery takeover failed", got)
}
checkpoint("recovery-complete")
if os.Getenv("KG_R9_FAULT") == "restore-write" {
var wire []map[string]any
readJSON("es-wire.json", &wire)
markedWrites := 0
droppedWrites := 0
for _, event := range wire {
if event["method"] == "PUT" && strings.Contains(event["request"].(string), indexRestoreClaimPrefix) {
markedWrites++
if event["dropped"] == true {
droppedWrites++
}
}
}
if markedWrites != 1 || droppedWrites != 1 {
t.Fatal("restore marker was resent or fault not exercised", markedWrites, droppedWrites)
}
}
var before map[string][]string
readJSON("pg-before.json", &before)
after := universeDump(t, fx.pool)
if !reflect.DeepEqual(before, after) {
t.Fatal("full PG before-image not restored")
}
finalIndex := recoveryIndexReadback(t, fx)
save("index-final.json", finalIndex)
if len(finalIndex) != len(beforeIndex) {
t.Fatal("index universe changed")
}
for id, old := range beforeIndex {
got, ok := finalIndex[id]
if !ok || !reflect.DeepEqual(old["_source"], got["_source"]) {
t.Fatal("original index source not restored", id)
}
if got["_seq_no"] == nil || got["_primary_term"] == nil {
t.Fatal("missing CAS")
}
if id == "chunk-target" && reflect.DeepEqual(old["_seq_no"], got["_seq_no"]) {
t.Fatal("restoration did not create a new CAS generation")
}
if id != "chunk-target" && !reflect.DeepEqual(old, got) {
t.Fatal("out-of-scope index CAS changed", id)
}
}
if !reflect.DeepEqual(indexAtKill, finalIndex) {
t.Fatal("replayed restoration repeated index mutations")
}
var objectsBefore s3.ListObjectVersionsOutput
readJSON("objects-before.json", &objectsBefore)
finalObjects := inventory()
if !reflect.DeepEqual(objectsBefore.Versions, finalObjects.Versions) {
t.Fatal("original exact object versions not restored")
}
var operations, events, receipts, deliveries int
must(gov.QueryRow(ctx, "SELECT count(*) FROM library_operations WHERE kind='recover'").Scan(&operations))
must(gov.QueryRow(ctx, "SELECT count(*) FROM library_versions WHERE kind='recovery_verified'").Scan(&events))
must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_receipts").Scan(&receipts))
must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_deliveries").Scan(&deliveries))
expectedDeliveries := 3
if os.Getenv("KG_R9_FAULT") == "restore-write" {
expectedDeliveries++
}
if operations != 1 || events != 1 || receipts != 2 || deliveries != expectedDeliveries {
t.Fatal("duplicate or missing durable identities", operations, events, receipts, deliveries)
}
replay, e := store.Enqueue(ctx, request, time.Now().UTC())
must(e)
if replay.ID != recoverID || replay.State != jobs.StateCompleted {
t.Fatal("recovery replay not idempotent")
}
time.Sleep(400 * time.Millisecond)
if !reflect.DeepEqual(after, universeDump(t, fx.pool)) || !reflect.DeepEqual(finalIndex, recoveryIndexReadback(t, fx)) || !reflect.DeepEqual(finalObjects.Versions, inventory().Versions) {
t.Fatal("completed request replay mutated data")
}
must(worker.Process.Signal(syscall.SIGTERM))
must(worker.Wait())
save("recovery-result.json", map[string]any{"queue_job": recoverID, "window_job": original.ID, "original_operation": original.OperationID, "state": "completed", "recovery_sigkills": 1, "recover_operations": operations, "recovery_events": events, "deliveries": deliveries, "receipts": receipts, "full_before_image_verified": true, "index_replay_CAS_unchanged": true, "worker_exit": worker.ProcessState.ExitCode()})
for _, v := range finalObjects.Versions {
_, e = fx.objects.s3.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(fx.bucket), Key: v.Key, VersionId: v.VersionId})
must(e)
}
if len(inventory().Versions) != 0 {
t.Fatal("cleanup not empty")
}
_, e = fx.objects.s3.client.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(fx.bucket)})
must(e)
save("object-cleanup.json", map[string]any{"bucket": fx.bucket, "versions": 0, "delete_markers": 0})
t.Log(fmt.Sprintf("recovery new request=%s original=%s full before-image restored", recoverID, original.ID))
}
@@ -0,0 +1,431 @@
package v071
import (
"bytes"
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"io"
"syscall"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/librarysnapshot"
"knowledge-governance/internal/objectgateway"
postgresstore "knowledge-governance/internal/platform/postgres"
)
// The harness only seeds and observes. All release writes run in cmd/worker
// executables, through the real Docker maintenance coordinator and gateway.
func TestFormalWorkerDoubleInterruption(t *testing.T) { runFormalWorkerScenario(t, false) }
func TestFormalWorkerRecoveryIntent(t *testing.T) { runFormalWorkerScenario(t, true) }
func runFormalWorkerScenario(t *testing.T, recoverIntent bool) {
root := os.Getenv("KG_R8_RUN")
if root == "" {
t.Skip("requires dedicated r8 real-process isolated deployment")
}
ctx := context.Background()
save := func(name string, value any) {
t.Helper()
raw, e := json.MarshalIndent(value, "", " ")
if e != nil {
t.Fatal(e)
}
if e = os.WriteFile(filepath.Join(root, name), raw, 0600); e != nil {
t.Fatal(e)
}
}
must := func(e error) {
t.Helper()
if e != nil {
t.Fatal(e)
}
}
archiveRoot := filepath.Join(root, "archive")
must(os.MkdirAll(archiveRoot, 0700))
must(os.MkdirAll(filepath.Join(root, "maintenance"), 0700))
fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, archiveRoot: archiveRoot, embeddingDimension: 1024})
seedTargetData(t, fx)
if recoverIntent {
fx.indexDoc(t, "chunk-other", 10001, wsOtherKB, "doc-other", "other KB unchanged")
fx.indexDoc(t, "chunk-foreign", 20000, "kb-foreign", "doc-foreign", "other tenant unchanged")
}
objectInventory := func() *s3.ListObjectVersionsOutput {
t.Helper()
v, e := fx.objects.s3.client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(fx.bucket)})
must(e)
if aws.ToBool(v.IsTruncated) || len(v.DeleteMarkers) != 0 {
t.Fatal("incomplete inventory or unexpected delete markers")
}
return v
}
originalObjects := objectInventory()
save("objects-before.json", originalObjects)
// These tables are the real stack's metadata contract, absent in the narrower
// adapter fixture. No business data/schema outside this new test DB is touched.
_, e := fx.pool.Exec(ctx, `ALTER TABLE knowledge_bases ADD COLUMN embedding_model_id text, ADD COLUMN vector_store_id text;
CREATE TABLE models(id text PRIMARY KEY,name text,parameters jsonb,deleted_at timestamptz);
CREATE TABLE vector_stores(id text PRIMARY KEY,engine_type text,index_config jsonb,deleted_at timestamptz);
INSERT INTO models VALUES('r8-model','text-embedding-v4','{"embedding_parameters":{"dimension":1024}}',NULL);
INSERT INTO vector_stores VALUES('r8-vector','elasticsearch_v8','{}',NULL);
UPDATE knowledge_bases SET embedding_model_id='r8-model',vector_store_id='r8-vector';`)
must(e)
before := universeDump(t, fx.pool)
save("pg-before.json", before)
target := fx.target(t)
mapping, e := target.Search().MappingSHA256(ctx)
must(e)
// Seal a fresh, internally consistent fixture contract; historical seals stay unchanged.
source := sealSourceSnapshot(t, fx, nil)
archive, e := librarysnapshot.Open(archiveRoot, 256<<20)
must(e)
manifest, e := archive.Load(source)
must(e)
manifest.Compatibility.EmbeddingDimension = 1024
manifest.Compatibility.IndexMappingSHA256 = mapping
snapshot, e := archive.Seal(manifest)
must(e)
archive.Close()
govDSN := os.Getenv("KG_R8_GOVERNANCE_DSN")
gov, e := pgxpool.New(ctx, govDSN)
must(e)
t.Cleanup(gov.Close)
must(postgresstore.ApplyMigrations(ctx, gov))
_, e = gov.Exec(ctx, objectgateway.Schema)
must(e)
reader := gatewayReadOnlyGovernance(t, ctx, gov, govDSN)
project := os.Getenv("KG_R8_PROJECT")
workerElastic := fx.searchBase
if recoverIntent && os.Getenv("KG_R9_FAULT") != "" {
workerElastic = formalElasticFaultProxy(t, root, fx.searchBase, os.Getenv("KG_R9_FAULT"))
}
env := map[string]string{
"KG_LIBRARY_TEST_ISOLATED": "1", "DATABASE_URL": govDSN, "LIBRARY_WORKER_ROLE": "release-executor", "WORKER_POLL_INTERVAL": "100ms", "WORKER_LEASE_DURATION": "4s",
"PRODUCTION_RELEASE_REQUESTS_ENABLED": "true", "PRODUCTION_BACKUP_RESTORE_VERIFIED": "true",
"LIBRARY_ARCHIVE_ROOT": archiveRoot, "LIBRARY_CAPACITY_BUDGET_BYTES": "1073741824",
"LIBRARY_PRODUCTION_DATABASE_URL": os.Getenv("KG_LIBRARY_TEST_DATABASE_URL"), "LIBRARY_PRODUCTION_ELASTIC_URL": workerElastic, "LIBRARY_PRODUCTION_INDEX": fx.index,
"LIBRARY_PRODUCTION_TENANT_ID": "10001", "LIBRARY_PRODUCTION_KB_INTERNAL": wsTargetKB,
"LIBRARY_PRODUCTION_S3_PROVIDER": "minio", "LIBRARY_PRODUCTION_S3_ENDPOINT": os.Getenv("KG_LIBRARY_TEST_S3_ENDPOINT"), "LIBRARY_PRODUCTION_S3_BUCKET": fx.bucket,
"LIBRARY_PRODUCTION_S3_ACCESS_KEY": os.Getenv("KG_R8_READER_KEY"), "LIBRARY_PRODUCTION_S3_SECRET_KEY": os.Getenv("KG_R8_READER_SECRET"),
"LIBRARY_TARGET_INSTANCE": project, "LIBRARY_TARGET_PROJECT": project, "LIBRARY_TARGET_WRITERS": "writer",
"LIBRARY_TARGET_NON_WRITERS": "ingress=entry gate,redis=queue,minio=object backend",
"LIBRARY_TARGET_INGRESS_URL": os.Getenv("KG_R8_INGRESS"), "LIBRARY_TARGET_INGRESS_SERVICE": "ingress", "LIBRARY_TARGET_INGRESS_DRAIN_FILE": filepath.Join(root, "gate/drain.json"),
"LIBRARY_TARGET_REDIS_ADDR": os.Getenv("KG_R8_REDIS_ADDR"), "LIBRARY_TARGET_REDIS_PASSWORD": os.Getenv("KG_R8_REDIS_PASSWORD"), "LIBRARY_TARGET_REDIS_DB": "0",
"LIBRARY_TARGET_JOURNAL_ROOT": filepath.Join(root, "maintenance"), "LIBRARY_EMBEDDING_DIMENSION": "1024",
"KG_TEST_BARRIER_DIR": filepath.Join(root, "barriers"), "KG_TEST_BARRIER_POINTS": "after:database,after:resources", "KG_TEST_BARRIER_TIMEOUT": "180s",
}
env["PRODUCTION_RELEASE_AUTHORIZER_REF"] = project
env["PRODUCTION_RELEASE_AUTH_TOKEN_FILE"] = filepath.Join(root, "authorization-token")
must(os.WriteFile(env["PRODUCTION_RELEASE_AUTH_TOKEN_FILE"], []byte(objectgateway.Digest([]byte(root+"approval"))), 0600))
cfg, e := appconfig.Load(func(k string) string { return env[k] })
must(e)
dataToken := objectgateway.Digest([]byte(root + "data"))
controlToken := objectgateway.Digest([]byte(root + "control"))
env["LIBRARY_OBJECT_GATEWAY_URL"] = "http://" + os.Getenv("KG_R8_GATEWAY_ADDR")
env["LIBRARY_OBJECT_GATEWAY_TOKEN"] = dataToken
// Independently prove worker's object identity cannot PUT, before any job exists.
readStore, e := NewS3ObjectStore(S3ObjectStoreConfig{Provider: "minio", Endpoint: env["LIBRARY_PRODUCTION_S3_ENDPOINT"], Bucket: fx.bucket, AccessKeyID: env["LIBRARY_PRODUCTION_S3_ACCESS_KEY"], SecretAccessKey: env["LIBRARY_PRODUCTION_S3_SECRET_KEY"], Region: "us-east-1", ForcePathStyle: true})
must(e)
allowedRead, e := readStore.Open(ctx, "minio", wsLocator("backend-target", "minio", fx.bucket, 10001, "res-target"))
must(e)
allowedBody, e := io.ReadAll(allowedRead)
allowedRead.Close()
must(e)
if !bytes.Equal(allowedBody, []byte("12345678")) {
t.Fatal("readonly identity could not read original bytes")
}
denied := readStore.Put(ctx, "minio", wsLocator("backend-target", "minio", fx.bucket, 10001, "r8-denied"), bytes.NewReader([]byte("denied")), 6)
if denied == nil {
t.Fatal("worker readonly identity unexpectedly wrote object")
}
save("denial.json", map[string]any{"readonly_put_denied": true})
scope := objectgateway.Digest([]byte("minio\x00" + env["LIBRARY_PRODUCTION_S3_ENDPOINT"] + "\x00" + fx.bucket))
pub, priv, e := ed25519.GenerateKey(rand.Reader)
must(e)
digestFile := func(name string) string {
raw, e := os.ReadFile(filepath.Join(root, name))
must(e)
return objectgateway.Digest(raw)
}
save("writer-inventory.json", map[string]any{"project": project, "worker_object_identity": "readonly", "gateway_only_writer": true, "bucket": fx.bucket, "index": fx.index, "target": cfg.LibraryTargetIdentity()})
save("policy.json", map[string]any{"worker": "readonly MinIO policy", "isolated_minio": os.Getenv("KG_R8_MINIO"), "scope": scope})
payload, e := json.Marshal(objectgateway.Attestation{Protocol: objectgateway.Protocol, Scope: scope, GatewayID: project, IssuedAt: time.Now().Add(-time.Second), ExpiresAt: time.Now().Add(50 * time.Minute), WriterInventory: digestFile("writer-inventory.json"), PolicyEvidence: digestFile("policy.json"), DenialEvidence: digestFile("denial.json"), DrainEvidence: digestFile("initial-drain.json")})
must(e)
signedRaw, e := json.Marshal(objectgateway.SignedAttestation{Payload: payload, Signature: ed25519.Sign(priv, payload)})
must(e)
must(os.WriteFile(filepath.Join(root, "audit.json"), signedRaw, 0600))
genv := map[string]string{"OBJECT_GATEWAY_LISTEN": os.Getenv("KG_R8_GATEWAY_ADDR"), "OBJECT_GATEWAY_DATABASE_URL": govDSN, "OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL": reader.Config().ConnString(), "OBJECT_GATEWAY_ARCHIVE_ROOT": archiveRoot, "OBJECT_GATEWAY_TARGET_ID": cfg.LibraryTargetIdentity(), "OBJECT_GATEWAY_PROVIDER": "minio", "OBJECT_GATEWAY_ENDPOINT": env["LIBRARY_PRODUCTION_S3_ENDPOINT"], "OBJECT_GATEWAY_BUCKET": fx.bucket, "OBJECT_GATEWAY_REGION": "us-east-1", "OBJECT_GATEWAY_ACCESS_KEY": os.Getenv("KG_LIBRARY_TEST_S3_ACCESS_KEY"), "OBJECT_GATEWAY_SECRET_KEY": os.Getenv("KG_LIBRARY_TEST_S3_SECRET_KEY"), "OBJECT_GATEWAY_DATA_TOKEN": dataToken, "OBJECT_GATEWAY_CONTROL_TOKEN": controlToken, "OBJECT_GATEWAY_ID": project, "OBJECT_GATEWAY_AUDIT_FILE": filepath.Join(root, "audit.json"), "OBJECT_GATEWAY_AUDIT_PUBLIC_KEY": base64.StdEncoding.EncodeToString(pub)}
processes := []map[string]any{}
start := func(binary, label string, values map[string]string) *exec.Cmd {
t.Helper()
bin := "r8-bin"
if recoverIntent {
bin = "r9-bin"
}
cmd := exec.Command(filepath.Join(filepath.Dir(root), bin, binary))
cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + os.Getenv("HOME")}
for k, v := range values {
cmd.Env = append(cmd.Env, k+"="+v)
}
f, e := os.OpenFile(filepath.Join(root, label+".log"), os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600)
must(e)
cmd.Stdout = f
cmd.Stderr = f
must(cmd.Start())
processes = append(processes, map[string]any{"label": label, "pid": cmd.Process.Pid, "binary": binary})
save("processes.json", processes)
t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait(); f.Close() })
return cmd
}
start("object-gateway", "gateway", genv)
client, e := objectgateway.NewClient(env["LIBRARY_OBJECT_GATEWAY_URL"], dataToken, scope)
must(e)
ready := false
for i := 0; i < 100; i++ {
if client.ReadyForAcquisition(ctx) == nil {
ready = true
break
}
time.Sleep(100 * time.Millisecond)
}
if !ready {
t.Fatal("gateway not ready; inspect gateway.log")
}
store := postgresstore.NewStore(gov).WithLibraryTarget(cfg.LibraryTargetIdentity())
now := time.Now().UTC()
digest, e := governance.LibraryRequestDigest("internal", governance.LibraryJobSync, map[string]any{"target_snapshot_id": snapshot})
must(e)
must(store.CreateLibraryAuthorization(ctx, governance.LibraryReleaseAuthorization{ID: project + "-auth", Scope: "internal", SnapshotID: snapshot, ParamsDigest: digest, ExpiresAt: now.Add(time.Hour), CreatedAt: now}))
op, _, e := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ID: project + "-operation", Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: snapshot, RequestDigest: digest, OperationKey: project, CreatedAt: now})
must(e)
job, _, e := store.CreateLibraryDispatch(ctx, governance.LibraryJob{ID: project + "-job", OperationID: op.ID, Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: snapshot, IdempotencyKey: project, RequestDigest: digest}, governance.SyncStages(), false, now)
must(e)
save("identity.json", map[string]any{"job": job.ID, "operation": job.OperationID, "snapshot": snapshot, "bucket": fx.bucket, "index": fx.index, "target": cfg.LibraryTargetIdentity()})
checkpoint := func(label string) {
t.Helper()
for _, table := range []string{"jobs", "library_jobs", "library_attempts", "library_operations", "library_versions", "kg_object_gateway_deliveries", "kg_object_gateway_intents", "kg_object_gateway_receipts"} {
var raw []byte
e := gov.QueryRow(ctx, "SELECT COALESCE(jsonb_agg(to_jsonb(t)),'[]') FROM "+table+" t").Scan(&raw)
must(e)
must(os.WriteFile(filepath.Join(root, label+"-"+table+".json"), raw, 0600))
}
save(label+"-pg.json", universeDump(t, fx.pool))
save(label+"-objects.json", objectInventory())
}
if recoverIntent {
env["R9_TARGET_ID"] = cfg.LibraryTargetIdentity()
runRecoveryIntentProcess(t, root, fx, gov, store, job, env, start, checkpoint, save)
return
}
for n, point := range []string{"after-database", "after-resources", "finished"} {
env["WORKER_ID"] = fmt.Sprintf("%s-worker-%d", project, n+1)
cmd := start("worker", fmt.Sprintf("worker-%d", n+1), env)
hit := false
for i := 0; i < 1200; i++ {
current, e := store.LibraryJob(ctx, job.ID)
must(e)
if point == "finished" && current.State == governance.LibraryJobSucceeded {
hit = true
break
}
if point != "finished" {
if _, e = os.Stat(filepath.Join(root, "barriers", point+".hit")); e == nil {
hit = true
break
}
}
if current.State == governance.LibraryJobFailed {
checkpoint(fmt.Sprintf("failed-%d", n+1))
t.Fatalf("formal worker %d failed: %s", n+1, current.Error)
}
time.Sleep(100 * time.Millisecond)
}
if !hit {
checkpoint(fmt.Sprintf("timeout-%d", n+1))
t.Fatalf("formal worker %d did not reach %s", n+1, point)
}
checkpoint(fmt.Sprintf("stage-%d", n+1))
if point != "finished" {
must(cmd.Process.Kill())
err := cmd.Wait()
status := cmd.ProcessState.Sys().(syscall.WaitStatus)
if !status.Signaled() || status.Signal() != syscall.SIGKILL {
t.Fatalf("expected SIGKILL: %v", err)
}
save(fmt.Sprintf("kill-%d.json", n+1), map[string]any{"pid": cmd.Process.Pid, "signal": "SIGKILL", "exit_code": cmd.ProcessState.ExitCode(), "point": point})
time.Sleep(5 * time.Second)
} else {
must(cmd.Process.Signal(syscall.SIGTERM))
must(cmd.Wait())
save("worker-final-exit.json", map[string]any{"pid": cmd.Process.Pid, "exit_code": cmd.ProcessState.ExitCode()})
}
}
// Independent final checks; exact rows outside the owned target must survive.
after := universeDump(t, fx.pool)
save("pg-final.json", after)
var docs, attempts, deliveries, receipts int
must(fx.pool.QueryRow(ctx, "SELECT count(*) FROM knowledges WHERE tenant_id=10001 AND knowledge_base_id=$1", wsTargetKB).Scan(&docs))
if docs != 1 {
t.Fatalf("target documents=%d", docs)
}
must(gov.QueryRow(ctx, "SELECT count(*) FROM library_attempts WHERE job_id=$1", job.ID).Scan(&attempts))
if attempts != 3 {
t.Fatalf("attempts=%d", attempts)
}
must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_deliveries").Scan(&deliveries))
must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_receipts").Scan(&receipts))
response, e := http.Get(fx.searchBase + "/" + fx.index + "/_search?size=100")
must(e)
defer response.Body.Close()
var search any
must(json.NewDecoder(response.Body).Decode(&search))
save("index-final.json", search)
if deliveries != 3 || receipts != 1 {
t.Fatalf("delivery/receipt count mismatch: %d/%d", deliveries, receipts)
}
var receiptRaw []byte
must(gov.QueryRow(ctx, "SELECT receipt FROM kg_object_gateway_receipts").Scan(&receiptRaw))
var receipt objectgateway.Receipt
must(json.Unmarshal(receiptRaw, &receipt))
if receipt.Request.Grant.Epoch != 2 || receipt.Request.Key != "10001/res-src/a.png" {
t.Fatal("original send identity changed", receipt.Request)
}
versions, e := (&objectgateway.S3Backend{Client: fx.objects.s3.client, Bucket: fx.bucket, MaxBytes: 1 << 20}).List(ctx, receipt.Request.Key)
must(e)
if len(versions) != 1 || versions[0] != receipt.Version {
t.Fatal("duplicate or changed object version", versions)
}
save("object-final.json", versions)
finalObjects := objectInventory()
save("objects-final.json", finalObjects)
if len(finalObjects.Versions) != len(originalObjects.Versions)+1 {
t.Fatal("unexpected object version growth")
}
for _, beforeVersion := range originalObjects.Versions {
found := false
for _, v := range finalObjects.Versions {
if aws.ToString(v.Key) == aws.ToString(beforeVersion.Key) && aws.ToString(v.VersionId) == aws.ToString(beforeVersion.VersionId) && aws.ToString(v.ETag) == aws.ToString(beforeVersion.ETag) {
found = true
}
}
if !found {
t.Fatal("out-of-plan original version changed", aws.ToString(beforeVersion.Key))
}
}
a, e := os.ReadFile(filepath.Join(root, "stage-2-kg_object_gateway_receipts.json"))
must(e)
z, e := os.ReadFile(filepath.Join(root, "stage-3-kg_object_gateway_receipts.json"))
must(e)
if !bytes.Equal(a, z) {
t.Fatal("receipt changed across replay")
}
// Original rows of other KBs, other tenants and orphan/shared resources are byte-identical.
for table, rows := range before {
for _, row := range rows {
var item map[string]any
must(json.Unmarshal([]byte(row), &item))
id, _ := item["id"].(string)
keep := id == "doc-other" || id == "chunk-other" || id == "res-other" || id == "bind-other" || id == "res-orphan" || id == "res-shared" || id == "bind-shared-other" || id == "doc-foreign" || id == "chunk-foreign" || id == "res-foreign" || id == "bind-foreign"
if keep {
found := false
for _, got := range after[table] {
if got == row {
found = true
}
}
if !found {
t.Fatalf("out-of-scope row changed: %s/%s", table, id)
}
}
}
}
for _, table := range []string{"knowledges", "chunks", "resources", "resource_bindings", "wiki_pages"} {
var duplicate int
must(fx.pool.QueryRow(ctx, "SELECT count(*) FROM (SELECT id FROM "+table+" GROUP BY id HAVING count(*)>1) x").Scan(&duplicate))
if duplicate != 0 {
t.Fatal("duplicate PG identities", table)
}
}
searchMap := search.(map[string]any)
hits := searchMap["hits"].(map[string]any)["hits"].([]any)
if len(hits) != 1 {
t.Fatalf("index documents=%d", len(hits))
}
hit := hits[0].(map[string]any)
doc := hit["_source"].(map[string]any)
if hit["_id"] != "chunk-src" || doc["knowledge_id"] != "doc-src" || doc["knowledge_base_id"] != wsTargetKB || doc["tenant_id"] != float64(wsTargetTenant) {
t.Fatal("index identity mismatch", hit)
}
var prebackups, effective, plans int
must(gov.QueryRow(ctx, "SELECT count(*) FROM library_versions WHERE kind='production_prebackup'").Scan(&prebackups))
must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_plans").Scan(&plans))
must(gov.QueryRow(ctx, "SELECT count(*) FROM library_versions WHERE source_job_id=$1 AND kind='production_effective' AND superseded_at IS NULL", job.ID).Scan(&effective))
if prebackups != 1 || plans != 1 || effective != 1 {
t.Fatalf("immutable anchors/prebackup/effective %d/%d/%d", plans, prebackups, effective)
}
// Compare delivery plans and exact attempt ownership without changing historic identity.
rows, e := gov.Query(ctx, "SELECT claim,grant_body FROM kg_object_gateway_deliveries ORDER BY attempt_epoch")
must(e)
defer rows.Close()
i := 0
for rows.Next() {
var cRaw, gRaw []byte
must(rows.Scan(&cRaw, &gRaw))
var c objectgateway.Claim
var g objectgateway.Grant
must(json.Unmarshal(cRaw, &c))
must(json.Unmarshal(gRaw, &g))
i++
if c.JobID != job.ID || c.OperationID != op.ID || c.AttemptEpoch != int64(i) || g.Epoch != int64(i) || c.PlanDigest != receipt.Request.Grant.Plan {
t.Fatal("delivery replaced original plan/operation")
}
}
must(rows.Err())
// Latest read must return the original committed bytes, not merely a matching count.
got, e := fx.objects.s3.client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(fx.bucket), Key: aws.String(receipt.Request.Key)})
must(e)
body, e := io.ReadAll(got.Body)
got.Body.Close()
must(e)
if !bytes.Equal(body, []byte("12345678")) {
t.Fatal("latest body mismatch")
}
save("result.json", map[string]any{"formal_worker_sigkills": 2, "attempts": attempts, "deliveries": deliveries, "receipts": receipts, "job": job.ID, "state": "succeeded", "snapshot": snapshot})
// Exact version cleanup only after all assertions; failures preserve the bucket.
for _, v := range finalObjects.Versions {
_, e = fx.objects.s3.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(fx.bucket), Key: v.Key, VersionId: v.VersionId})
must(e)
}
empty := objectInventory()
if len(empty.Versions) != 0 {
t.Fatal("cleanup left object versions")
}
_, e = fx.objects.s3.client.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(fx.bucket)})
must(e)
_, e = fx.objects.s3.client.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(fx.bucket)})
var status interface{ HTTPStatusCode() int }
if !errors.As(e, &status) || status.HTTPStatusCode() != 404 {
t.Fatal("bucket absence not independently confirmed", e)
}
save("object-cleanup.json", map[string]any{"bucket": fx.bucket, "versions": 0, "delete_markers": 0, "bucket_absent": true})
t.Logf("formal worker twice SIGKILL succeeded: job=%s attempts=%d deliveries=%d receipts=%d", job.ID, attempts, deliveries, receipts)
}
@@ -0,0 +1,131 @@
package v071
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/libraryrelease"
"knowledge-governance/internal/objectgateway"
"path/filepath"
)
// GatewayGovernanceAuthority runs only in the trusted gateway control domain.
// Its governance connection is SELECT-only; the ordinary worker never receives
// the gateway control credential or backend write credential. Archive contents
// are trusted only after their immutable digest is found in the original
// persisted prebackup event belonging to the currently leased attempt.
type GatewayGovernanceAuthority struct {
Pool *pgxpool.Pool
ArchiveRoot string
TargetID string
Provider string
Bucket string
}
func (a *GatewayGovernanceAuthority) Ready(ctx context.Context) error {
if a == nil || a.Pool == nil || !filepath.IsAbs(a.ArchiveRoot) || a.TargetID == "" || a.Provider == "" || a.Bucket == "" {
return objectgateway.ErrAuthority
}
var safe bool
e := a.Pool.QueryRow(ctx, `SELECT NOT rolsuper AND NOT rolcreatedb AND NOT rolcreaterole FROM pg_roles WHERE rolname=current_user`).Scan(&safe)
if e != nil || !safe {
return objectgateway.ErrAuthorityPrivileges
}
for _, table := range []string{"library_jobs", "library_operations", "library_attempts", "library_versions", "jobs"} {
e = a.Pool.QueryRow(ctx, `SELECT has_table_privilege(current_user,$1,'SELECT') AND NOT has_table_privilege(current_user,$1,'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER')`, table).Scan(&safe)
if e != nil || !safe {
return objectgateway.ErrAuthorityPrivileges
}
}
return nil
}
func (a *GatewayGovernanceAuthority) Load(ctx context.Context, c objectgateway.Claim) (objectgateway.Plan, error) {
if e := a.Ready(ctx); e != nil {
return objectgateway.Plan{}, e
}
if a == nil || a.Pool == nil || !filepath.IsAbs(a.ArchiveRoot) || a.TargetID == "" || a.Provider == "" || a.Bucket == "" {
return objectgateway.Plan{}, objectgateway.ErrAuthority
}
recovery, err := a.verifyRecoveryClaim(ctx, c)
if err != nil {
return objectgateway.Plan{}, err
}
var scope, backup, snapshot string
var matches int
e := a.Pool.QueryRow(ctx, `SELECT j.scope,v.snapshot_id,v.evidence->>'writeset_target_snapshot',count(*) OVER()
FROM library_jobs j
JOIN library_operations o ON o.id=j.operation_id AND o.target_id=j.target_id
JOIN library_attempts a ON a.operation_id=j.operation_id AND a.epoch=j.attempt_epoch AND a.job_id=j.id
JOIN library_versions v ON v.source_job_id=j.id AND v.operation_id=j.operation_id AND v.scope=j.scope AND v.kind='production_prebackup' AND v.target_id=j.target_id
WHERE j.id=$1 AND j.operation_id=$2 AND j.attempt_epoch=$3 AND j.lease_owner=$4 AND j.target_id=$6
AND j.lease_until>clock_timestamp() AND (j.state='running' OR $7)
AND a.owner=$4 AND a.state IN ('claimed','running') AND a.lease_until>clock_timestamp()
AND v.evidence->>'writeset_digest'=$5
AND v.evidence->>'job'=j.id AND v.evidence->>'backup_snapshot'=v.snapshot_id
AND (o.target_snapshot_id='' OR o.target_snapshot_id=v.evidence->>'writeset_target_snapshot')
AND NOT EXISTS(SELECT 1 FROM library_attempts newer WHERE newer.operation_id=a.operation_id AND newer.epoch>a.epoch)`, c.JobID, c.OperationID, c.AttemptEpoch, c.Owner, c.PlanDigest, a.TargetID, recovery).Scan(&scope, &backup, &snapshot, &matches)
if errors.Is(e, pgx.ErrNoRows) {
return objectgateway.Plan{}, objectgateway.ErrEpoch
}
if e != nil {
return objectgateway.Plan{}, objectgateway.ErrPersistence
}
if matches != 1 {
return objectgateway.Plan{}, objectgateway.ErrConflict
}
set, e := LoadWriteSet(a.ArchiveRoot, c.PlanDigest)
if e != nil || set == nil {
return objectgateway.Plan{}, objectgateway.ErrConflict
}
if set.Version != libraryrelease.MigrationWriteSetVersion || set.JobID != c.JobID || set.Target != scope || set.BackupSnapshotID != backup || set.TargetSnapshotID != snapshot {
return objectgateway.Plan{}, objectgateway.ErrConflict
}
for _, obj := range set.Objects {
if obj.Provider != a.Provider || obj.Bucket != a.Bucket {
return objectgateway.Plan{}, objectgateway.ErrConflict
}
}
return ObjectGatewayPlan(*set)
}
// Recovery authorization does not replace c.JobID/c.OperationID (the original
// send domain). Its separate queue and operation must both be durable, leased,
// and bound to the same before-image, source, target and frozen plan.
func (a *GatewayGovernanceAuthority) verifyRecoveryClaim(ctx context.Context, c objectgateway.Claim) (bool, error) {
if c.RecoveryJobID == "" && c.RecoveryOperationID == "" {
return false, nil
}
if c.RecoveryJobID != governance.LibraryRecoveryQueueID(c.JobID) {
return false, objectgateway.ErrConflict
}
var scope, backup, source, recorded string
e := a.Pool.QueryRow(ctx, `SELECT j.scope,v.snapshot_id,v.evidence->>'writeset_target_snapshot',o.request_digest
FROM library_jobs j JOIN library_versions v ON v.source_job_id=j.id AND v.operation_id=j.operation_id
AND v.target_id=j.target_id AND v.scope=j.scope AND v.kind='production_prebackup'
JOIN jobs q ON q.id=$3 AND q.type='library.recover' AND q.state='running'
JOIN library_operations o ON o.id=$4 AND o.kind='recover' AND o.scope=j.scope AND o.target_id=j.target_id
WHERE j.id=$1 AND j.operation_id=$2 AND j.target_id=$5
AND q.payload->>'scope'=j.scope AND q.payload->>'window_job_id'=j.id
AND COALESCE(NULLIF(q.payload->>'source_snapshot_id',''),v.evidence->>'writeset_target_snapshot')=v.evidence->>'writeset_target_snapshot'
AND COALESCE(NULLIF(q.payload->>'target_id',''),j.target_id)=j.target_id
AND COALESCE(NULLIF(q.payload->>'original_operation_id',''),j.operation_id)=j.operation_id
AND COALESCE(NULLIF(q.payload->>'backup_snapshot_id',''),v.snapshot_id)=v.snapshot_id
AND COALESCE(NULLIF(q.payload->>'plan_digest',''),$7)=$7
AND q.idempotency_key='library.recover:'||j.id AND q.lease_until>clock_timestamp()
AND q.lease_owner||'#'||q.id||'#'||q.attempt::text=$6
AND o.operation_key=q.id AND o.target_snapshot_id=v.snapshot_id
AND v.evidence->>'writeset_digest'=$7`, c.JobID, c.OperationID, c.RecoveryJobID, c.RecoveryOperationID, a.TargetID, c.Owner, c.PlanDigest).Scan(&scope, &backup, &source, &recorded)
if errors.Is(e, pgx.ErrNoRows) {
return false, objectgateway.ErrConflict
}
if e != nil {
return false, objectgateway.ErrPersistence
}
digest, e := governance.LibraryRecoveryDigest(scope, c.RecoveryJobID, c.JobID, c.OperationID, a.TargetID, source, backup, c.PlanDigest)
if e != nil || recorded != digest || c.RecoveryOperationID != governance.LibraryOperationID(scope, governance.LibraryJobRecover, c.RecoveryJobID) {
return false, objectgateway.ErrConflict
}
return true, nil
}

Some files were not shown because too many files have changed in this diff Show More