feat(library): 云测试发布目标接入的角色分离、快照搬运与图谱门禁

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

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

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

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

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

验证:deploy/cloud-test/test_gate.py 13 项全 PASS(含 12 秒静默流、半关闭、2MiB 完整、
排空 exit 0/active_at_close=1、排空超时 exit 2、上游不可达不挂住);go test 相关包全绿;
scripts/ci_checks.py 16 项全部 success(EXIT=0,1241 用例通过/0 失败/191 已声明可选集成跳过);
云测试只读预检 17 项 / 6 FAIL,FAIL 项即当前部署缺口(无闸门、app 仍发布端口、
adapter 与 frontend 仍直连 app、云端归档根未建),未部署、未改云端任何状态。
This commit is contained in:
姚章浩
2026-10-30 18:37:38 +08:00
parent a7d643635a
commit e6472b0ec6
24 changed files with 2409 additions and 117 deletions
+33
View File
@@ -0,0 +1,33 @@
package main
import (
"context"
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
)
// registerLibraryReleaseHandlers 注册整库发布执行器:production sync / restore /
// recover / baseline,四类且仅这四类。
//
// 为什么单独成一个函数:这是"发布执行器"角色的边界,也是唯一会让本进程写
// 目标整库的地方。它必须能被单独测试(注册了哪些、未准入时是不是明确失败),
// 而不是埋在 run() 里只能靠连库启动来验证。
func registerLibraryReleaseHandlers(handlers map[string]jobs.Handler, store *postgresstore.Store,
config appconfig.Config, admissionErr error) {
handlers[librarySyncJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
return runLibraryRelease(ctx, store, config, job, governance.LibraryJobSync)
})
handlers[libraryRestoreJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
return runLibraryRelease(ctx, store, config, job, governance.LibraryJobRestore)
})
handlers[libraryRecoverJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
return runLibraryRecovery(ctx, store, config, job)
})
// 建立目标权威基线:目标非空又没有生效版本时的唯一入口(只读捕获 + 校验 + 登记)。
handlers[libraryBaselineJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
return runLibraryBaseline(ctx, store, config, job)
})
}
+87
View File
@@ -0,0 +1,87 @@
package main
import (
"context"
"strings"
"testing"
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/versionhistory"
)
// 发布执行器必须只挂四类 release 作业:多挂一类就会抢走本机队列里别的执行者的作业。
func TestRegisterLibraryReleaseHandlersCoversOnlyReleaseJobs(t *testing.T) {
handlers := map[string]jobs.Handler{}
registerLibraryReleaseHandlers(handlers, nil, appconfig.Config{}, nil)
want := []string{librarySyncJobType, libraryRestoreJobType, libraryRecoverJobType, libraryBaselineJobType}
if len(handlers) != len(want) {
t.Fatalf("registered %d handlers, want %d: %#v", len(handlers), len(want), handlers)
}
for _, jobType := range want {
if handlers[jobType] == nil {
t.Fatalf("handler %q is not registered", jobType)
}
}
}
// 准入未通过时 handler 必须"明确失败且不做任何动作":不能靠 nil store 或进程内状态蒙过去。
func TestRegisterLibraryReleaseHandlersFailsClosedWhenNotAdmitted(t *testing.T) {
handlers := map[string]jobs.Handler{}
registerLibraryReleaseHandlers(handlers, nil, appconfig.Config{}, errNotAdmitted{})
for _, jobType := range []string{librarySyncJobType, libraryRestoreJobType, libraryRecoverJobType, libraryBaselineJobType} {
err := handlers[jobType](context.Background(), jobs.Job{})
if err == nil || !strings.Contains(err.Error(), "准入未通过") {
t.Fatalf("handler %q error = %v, want admission refusal", jobType, err)
}
}
}
type errNotAdmitted struct{}
func (errNotAdmitted) Error() string { return "fixture: target instance unknown" }
// capture 角色不能注册任何 source 之外的队列;release-executor 反之。
func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
release := appconfig.Config{
LibraryWorkerRole: appconfig.LibraryWorkerRoleReleaseExecutor,
LibraryAgentSocket: "/run/library-agent/agent.sock",
TestWeKnoraEnabled: true,
TestWeKnoraAPIKeyFile: "/nonexistent/api-key",
PPScanEnabled: true,
VersionHistoryGiteaBaseURL: "https://gitea.invalid/Weknora/knowledge-governance",
VersionHistoryAllowedOrigins: []string{"https://gitea.invalid"},
}
handlers, err := workerHandlers(postgresstore.NewStore(nil), release)
if err != nil {
t.Fatalf("release-executor workerHandlers() error = %v", err)
}
for _, forbidden := range []string{libraryCaptureJobType, "test.upload", "test.poll", "test.validate", "test.remove", "source.scan.pp", "source.catalog.refresh", "artifact.fetch", versionhistory.JobType} {
if handlers[forbidden] != nil {
t.Fatalf("release-executor registered %q", forbidden)
}
}
if handlers["demo"] == nil {
t.Fatal("demo handler must stay registered")
}
capture := appconfig.Config{
LibraryWorkerRole: appconfig.LibraryWorkerRoleCapture,
LibraryAgentSocket: "/run/library-agent/agent.sock",
TestWeKnoraEnabled: true,
TestWeKnoraAPIKeyFile: "/nonexistent/api-key",
}
if _, err := workerHandlers(nil, capture); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") {
t.Fatalf("capture role must reach the test WeKnora wiring, got %v", err)
}
capture.TestWeKnoraEnabled = false
capture.PPScanEnabled = false
handlers, err = workerHandlers(postgresstore.NewStore(nil), capture)
if err != nil {
t.Fatalf("capture workerHandlers() error = %v", err)
}
if handlers[libraryCaptureJobType] == nil {
t.Fatal("capture role must register library.capture")
}
}
+112 -110
View File
@@ -129,36 +129,51 @@ func run(ctx context.Context, getenv func(string) string) error {
if err := pool.Ping(ctx); err != nil {
return err
}
if err := postgresstore.ApplyMigrations(ctx, pool); err != nil {
return err
// 迁移也是"后台副作用":只有控制面那个进程拥有 DDL。云端发布执行器只读校验
// schema 版本,落后即拒绝启动——它不该成为治理库的第二个结构决策者。
if config.LibraryWorkerRole.ExecutesMigrations() {
if err := postgresstore.ApplyMigrations(ctx, pool); err != nil {
return err
}
} else if pending, pendingErr := postgresstore.PendingMigrations(ctx, pool); pendingErr != nil {
return fmt.Errorf("治理库 schema 版本检查失败: %w", pendingErr)
} else if len(pending) > 0 {
return fmt.Errorf("治理库 schema 落后(待应用迁移 %v):本角色不拥有 DDL,先由控制面进程完成迁移", pending)
}
store := postgresstore.NewStore(pool)
// 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败:
// 顺序反了会把可接管的作业先标失败,丢掉已完成的备份。
if resumed, failed, resumeErr := resumeInterruptedLibraryJobs(context.Background(), store, config); resumeErr != nil {
log.Printf("library job resume failed: %v", resumeErr)
} else if resumed > 0 || failed > 0 {
log.Printf("library job resume: %d resumed, %d failed without backup", resumed, failed)
}
// 运行期也要持续接管:只在启动扫一次会漏掉"worker 在两次重启之间被杀"的情况。
go func() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
resumed, failed, err := resumeInterruptedLibraryJobs(ctx, store, config)
if err != nil {
log.Printf("library job takeover sweep: %v", err)
} else if resumed > 0 || failed > 0 {
log.Printf("library job takeover sweep: %d resumed, %d failed without backup", resumed, failed)
//
// 只由"发布执行器"角色接管:release 作业的目标来自本进程配置,capture 角色的
// 进程按本机维护配置去接管云端目标的作业,等于把快照写到另一套目标上。
if config.LibraryWorkerRole.ExecutesRelease() {
if resumed, failed, resumeErr := resumeInterruptedLibraryJobs(context.Background(), store, config); resumeErr != nil {
log.Printf("library job resume failed: %v", resumeErr)
} else if resumed > 0 || failed > 0 {
log.Printf("library job resume: %d resumed, %d failed without backup", resumed, failed)
}
// 运行期也要持续接管:只在启动扫一次会漏掉"worker 在两次重启之间被杀"的情况。
go func() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
resumed, failed, err := resumeInterruptedLibraryJobs(ctx, store, config)
if err != nil {
log.Printf("library job takeover sweep: %v", err)
} else if resumed > 0 || failed > 0 {
log.Printf("library job takeover sweep: %d resumed, %d failed without backup", resumed, failed)
}
}
}
}
}()
if repaired, reconcileErr := store.ReconcileLibraryJobs(context.Background(), time.Now().UTC()); reconcileErr != nil {
}()
}
// 只收拾本角色负责的 kind:跨域"顺手收拾"会把另一台执行器的在飞作业标失败。
if repaired, reconcileErr := store.ReconcileLibraryJobs(context.Background(), time.Now().UTC(),
config.LibraryWorkerRole.LibraryJobKinds()); reconcileErr != nil {
log.Printf("library job reconcile failed: %v", reconcileErr)
} else if repaired > 0 {
log.Printf("library job reconcile: %d orphan job(s) marked failed", repaired)
@@ -167,32 +182,33 @@ func run(ctx context.Context, getenv func(string) string) error {
if err != nil {
return err
}
if syncErr := configureDirectorySync(pool, getenv, handlers); syncErr != nil {
log.Print("QA directory synchronization unavailable; handler was not registered")
}
mirrorStore, mirrorErr := configureRecordsSync(pool, getenv, config.DatabaseURL, handlers)
if mirrorErr != nil {
log.Print("QA local mirror configuration invalid; handler was not registered")
if config.LibraryWorkerRole.ExecutesSourceWork() {
if syncErr := configureDirectorySync(pool, getenv, handlers); syncErr != nil {
log.Print("QA directory synchronization unavailable; handler was not registered")
}
mirrorStore, mirrorErr := configureRecordsSync(pool, getenv, config.DatabaseURL, handlers)
if mirrorErr != nil {
log.Print("QA local mirror configuration invalid; handler was not registered")
}
if mirrorStore != nil {
go runRecordsSyncScheduler(ctx, mirrorStore, func(error) { log.Print("QA local mirror scheduler unavailable; last committed data retained") })
}
}
// 生产同步/恢复的执行器不依赖主机侧封存 agent:没有 agent socket 也要能跑。
// 这里在全部注册之后无条件覆盖一次,确保 library.sync/library.restore 一定在队列类型里。
//
// 执行域准入(R4)在这里统一判定:目标实况、旧 release 路由绑定、未释放维护窗口
// 任何一项未知或重叠 ⇒ 这些 handler 直接拒绝执行(明确失败,无任何维护动作,
// 也不停止任何既有服务)。
admissionErr := verifyLibraryExecutionDomain(context.Background(), config, store)
if admissionErr != nil {
log.Printf("library execution domain NOT admitted: %v", admissionErr)
//
// 只有"发布执行器"角色注册它们:capture 角色的进程按本机目标配置执行一条
// 指向别处目标的作业,后果是跨目标写入,不是失败重试能纠正的事。
if config.LibraryWorkerRole.ExecutesRelease() {
admissionErr := verifyLibraryExecutionDomain(context.Background(), config, store)
if admissionErr != nil {
log.Printf("library execution domain NOT admitted: %v", admissionErr)
}
registerLibraryReleaseHandlers(handlers, store, config, admissionErr)
}
handlers[librarySyncJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
return runLibraryRelease(ctx, store, config, job, governance.LibraryJobSync)
})
handlers[libraryRestoreJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
return runLibraryRelease(ctx, store, config, job, governance.LibraryJobRestore)
})
handlers[libraryRecoverJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
return runLibraryRecovery(ctx, store, config, job)
})
worker, err := jobs.NewWorker(jobs.WorkerConfig{
Queue: store,
@@ -205,19 +221,20 @@ func run(ctx context.Context, getenv func(string) string) error {
if err != nil {
return err
}
if ai := configureQAProcessing(pool, getenv, config.DatabaseURL); ai != nil {
go ai.Run(ctx, func(error) { log.Print("QA AI worker unavailable; durable work and original labels retained") })
if config.LibraryWorkerRole.ExecutesSourceWork() {
if ai := configureQAProcessing(pool, getenv, config.DatabaseURL); ai != nil {
go ai.Run(ctx, func(error) { log.Print("QA AI worker unavailable; durable work and original labels retained") })
}
go weeklyMailLoop(ctx, pool, getenv)
// 封存执行器状态:worker 是唯一能连 agent socket 的一方,它写观测、页面读观测。
go runLibraryExecutorProbe(ctx, store, config, libraryExecutorProbeInterval)
go runSourceRefreshScheduler(ctx, store, config.SourceRefreshSchedulerInterval, func(err error) {
log.Printf("worker %s source refresh scheduler error: %v", config.WorkerID, err)
})
}
if mirrorStore != nil {
go runRecordsSyncScheduler(ctx, mirrorStore, func(error) { log.Print("QA local mirror scheduler unavailable; last committed data retained") })
}
go weeklyMailLoop(ctx, pool, getenv)
// 封存执行器状态:worker 是唯一能连 agent socket 的一方,它写观测、页面读观测。
go runLibraryExecutorProbe(ctx, store, config, libraryExecutorProbeInterval)
go runSourceRefreshScheduler(ctx, store, config.SourceRefreshSchedulerInterval, func(err error) {
log.Printf("worker %s source refresh scheduler error: %v", config.WorkerID, err)
})
log.Printf("worker %s started (source refresh scheduler every %s)", config.WorkerID, config.SourceRefreshSchedulerInterval)
log.Printf("worker %s started role=%s release=%t source=%t (source refresh scheduler every %s)",
config.WorkerID, config.LibraryWorkerRole, config.LibraryWorkerRole.ExecutesRelease(),
config.LibraryWorkerRole.ExecutesSourceWork(), config.SourceRefreshSchedulerInterval)
return worker.Run(ctx, config.PollInterval)
}
@@ -229,40 +246,44 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
},
"demo.sleep": jobs.DemoSleepHandler,
}
catalogRunner, err := catalogrefresh.NewCommandRunner("/usr/bin/python3", "/app/scripts/live_catalog_refresh.py")
if err != nil {
return nil, fmt.Errorf("create catalog refresh runner: %w", err)
// 目录刷新与附件抓取属于"源侧"作业:它们读本机 spool、调本机脚本。
// 发布执行器角色在云端没有这些挂载,注册它们只会抢走本机队列里的作业。
if config.LibraryWorkerRole.ExecutesSourceWork() {
catalogRunner, err := catalogrefresh.NewCommandRunner("/usr/bin/python3", "/app/scripts/live_catalog_refresh.py")
if err != nil {
return nil, fmt.Errorf("create catalog refresh runner: %w", err)
}
catalogHandler, err := catalogrefresh.NewHandler(catalogrefresh.Config{Store: store, Runner: catalogRunner})
if err != nil {
return nil, fmt.Errorf("create catalog refresh handler: %w", err)
}
handlers["source.catalog.refresh"] = catalogHandler.Handle
ingestionRoot := config.IngestionSpoolRoot
if ingestionRoot == "" {
ingestionRoot = config.GovernanceSpoolRoot
}
if !filepath.IsAbs(ingestionRoot) || ingestionRoot == "" {
ingestionRoot = "/var/lib/governance/ingestion"
}
fetchMaxBytes := config.ArtifactFetchMaxBytes
if config.TestWeKnoraEnabled && config.TestWeKnoraMaxUploadBytes > 0 && fetchMaxBytes > config.TestWeKnoraMaxUploadBytes {
fetchMaxBytes = config.TestWeKnoraMaxUploadBytes
}
if fetchMaxBytes <= 0 {
fetchMaxBytes = 50 * 1024 * 1024
}
artifactRunner, err := artifactfetch.NewCommandRunner("/usr/bin/python3", "/app/scripts/artifact_fetch.py",
ingestionRoot, "ingestion", fetchMaxBytes)
if err != nil {
return nil, fmt.Errorf("create artifact fetch runner: %w", err)
}
artifactHandler, err := artifactfetch.NewHandler(artifactfetch.Config{Store: store, Runner: artifactRunner})
if err != nil {
return nil, fmt.Errorf("create artifact fetch handler: %w", err)
}
handlers["artifact.fetch"] = artifactHandler.Handle
}
catalogHandler, err := catalogrefresh.NewHandler(catalogrefresh.Config{Store: store, Runner: catalogRunner})
if err != nil {
return nil, fmt.Errorf("create catalog refresh handler: %w", err)
}
handlers["source.catalog.refresh"] = catalogHandler.Handle
ingestionRoot := config.IngestionSpoolRoot
if ingestionRoot == "" {
ingestionRoot = config.GovernanceSpoolRoot
}
if !filepath.IsAbs(ingestionRoot) || ingestionRoot == "" {
ingestionRoot = "/var/lib/governance/ingestion"
}
fetchMaxBytes := config.ArtifactFetchMaxBytes
if config.TestWeKnoraEnabled && config.TestWeKnoraMaxUploadBytes > 0 && fetchMaxBytes > config.TestWeKnoraMaxUploadBytes {
fetchMaxBytes = config.TestWeKnoraMaxUploadBytes
}
if fetchMaxBytes <= 0 {
fetchMaxBytes = 50 * 1024 * 1024
}
artifactRunner, err := artifactfetch.NewCommandRunner("/usr/bin/python3", "/app/scripts/artifact_fetch.py",
ingestionRoot, "ingestion", fetchMaxBytes)
if err != nil {
return nil, fmt.Errorf("create artifact fetch runner: %w", err)
}
artifactHandler, err := artifactfetch.NewHandler(artifactfetch.Config{Store: store, Runner: artifactRunner})
if err != nil {
return nil, fmt.Errorf("create artifact fetch handler: %w", err)
}
handlers["artifact.fetch"] = artifactHandler.Handle
if config.LibraryAgentSocket != "" {
if config.LibraryAgentSocket != "" && config.LibraryWorkerRole.ExecutesSourceWork() {
// 整库封存:worker 只投递请求并记录结果,真正的停机/导出/恢复发生在主机侧
// agent(同 uid unix socket)。容器里既没有 Docker socket,也没有来源凭据。
agentConfig := libraryagent.ClientConfig{Socket: config.LibraryAgentSocket, Timeout: 15 * time.Minute}
@@ -341,25 +362,6 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
payload.Scope, payload.CaptureJob, result.SnapshotID, result.Replay, payload.RequestedBy)
return nil
}
// 执行域准入(R4):注册整库发布执行器**之前**核对目标实况、旧 release 路由与
// 未释放的维护窗口。未通过时下面这些 handler 一律直接拒绝执行——明确失败,
// 不带任何维护动作,也不停止任何既有服务。
admissionErr := verifyLibraryExecutionDomain(context.Background(), config, store)
if admissionErr != nil {
log.Printf("library execution domain NOT admitted: %v", admissionErr)
}
// 生产同步:唯一入口在 API(闸口未齐不建作业)。这里仍实现执行器,
// 但默认 fail-closed:没有闸口证据就明确失败,绝不向生产写入半个字节。
handlers[librarySyncJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
return runLibraryRelease(ctx, store, config, job, governance.LibraryJobSync)
})
handlers[libraryRestoreJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
return runLibraryRelease(ctx, store, config, job, governance.LibraryJobRestore)
})
// 建立目标权威基线:目标非空又没有生效版本时的唯一入口(只读捕获 + 校验 + 登记)。
handlers[libraryBaselineJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
return runLibraryBaseline(ctx, store, config, job)
})
// A crash can leave the source writer stopped: recover before taking work,
// and keep the failure visible instead of pretending the worker is ready.
go func() {
@@ -372,7 +374,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
log.Printf("library agent reachable; freeze journals recovered")
}()
}
if config.VersionHistoryGiteaBaseURL != "" {
if config.VersionHistoryGiteaBaseURL != "" && config.LibraryWorkerRole.ExecutesSourceWork() {
// 「版本记录」同步:匿名只读远端仓库的提交/tag,写本库快照。未配置来源就不注册,
// 界面上的同步按钮也会显示"未接线",不会入队一个没人处理的作业。
client, err := versionhistory.NewGiteaClient(versionhistory.GiteaConfig{
@@ -417,7 +419,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
return nil
}
}
if config.PPScanEnabled {
if config.PPScanEnabled && config.LibraryWorkerRole.ExecutesSourceWork() {
scanner, err := sourcescan.NewFilePPScanner(sourcescan.FilePPScannerConfig{
AllowedRoot: config.PPScanAllowedRoot,
LedgerPath: config.PPScanLedgerPath,
@@ -432,7 +434,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
}
handlers["source.scan.pp"] = handler.Handle
}
if !config.TestWeKnoraEnabled {
if !config.TestWeKnoraEnabled || !config.LibraryWorkerRole.ExecutesSourceWork() {
return handlers, nil
}
apiKey, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile)