Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 910c0fcd76 | |||
| c5e033dd0e | |||
| 20fc40a147 | |||
| 045fc44f0e | |||
| 864a1632e0 | |||
| 9f990158b9 | |||
| 3dc854de4b | |||
| 76f687b52d | |||
| 2fc6dc068b | |||
| fe2e7ac4f4 | |||
| c4759bb61c | |||
| bf049cee1f |
@@ -28,6 +28,7 @@
|
||||
# Local artifacts (binaries, staging scripts, backups)
|
||||
/release-diag
|
||||
/worker
|
||||
/libraryctl
|
||||
/apply_s5_patch.py
|
||||
/tmp_*
|
||||
.style-backup-*/
|
||||
|
||||
@@ -1,5 +1,94 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 snapshot/v0.1.111 - 2026-10-28
|
||||
|
||||
### Added
|
||||
|
||||
- 主机侧封存 agent(`libraryagent` + systemd user 服务):只监听一个 0700 目录里的 0600 unix socket,校验 `SO_PEERCRED` 同 uid,固定 binary/归档/日志/项目/写入者声明,请求只能选范围与作业号。
|
||||
- 页面「发起封存」:`POST /api/v1/library/captures` 只入队 `library.capture` 作业,`GET /api/v1/library/captures` 读队列真实状态;未接线时 503 并给出原因,权限不足 403。
|
||||
- worker `library.capture` 处理器:通过挂载的 socket 调 agent,启动时先做一次 `recover`;容器内**不挂** Docker socket、**不持有**来源凭据。
|
||||
- `scripts/library-agent-install.sh`:构建、安装、启用 linger 并读回 socket 权限与服务状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 整库版本页显示封存作业的真实状态(待执行/执行中/重试/完成/失败与最后错误),完成后自动刷新快照列表。
|
||||
|
||||
## 开发快照 snapshot/v0.1.110 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 同一作业号重跑不再必然冲突:命令先读持久日志与已封存清单,按首次请求(时间、范围、契约、绑定库)幂等重放,`source_read=false`、`writers_stopped=false`;同一作业号换了范围或绑定库仍明确拒绝,已封存清单校验失败也拒绝。
|
||||
- 归档用量改按跨版本去重统计内容字节,并把清单、未被引用 blob、文件实际分配单独列出;不再把"各版本 unique 之和"当归档占用,也不再暗示可回收空间(真实两份清单:各版之和 55,309,695 字节,跨版本去重 55,309,693 字节,磁盘分配 55,373,824 字节)。
|
||||
|
||||
### Added
|
||||
|
||||
- 冻结窗口内的契约复核:窗口内重新读取来源契约,与窗口前不一致即中止(不封存、恢复写入者)。
|
||||
- 写入者组之外的同镜像容器检查:若有不属于声明组的运行中容器使用声明写入者的镜像,拒绝封存。
|
||||
- 补齐 `GET /api/v1/library/snapshots`、`GET /api/v1/library/snapshots/{id}` 的 OpenAPI 契约(上一版遗漏,契约测试可检出)。
|
||||
|
||||
### Changed
|
||||
|
||||
- 按用户确认取消 A06:文档、页面与接口说明不再把内容/问答/引用图片效果/性能测试列为封版或发布门槛;A04 数据完整性口径保留。
|
||||
|
||||
## 开发快照 snapshot/v0.1.108 - 2026-10-28
|
||||
|
||||
### Added
|
||||
|
||||
- 新增整库封存的真实业务入口 `libraryctl`(status / preflight / capture / list / verify / recover):从本机真实测试栈只读读取来源,核对处理已结清,推出兼容契约,在维护窗口内停住声明过的写入者,导出 PostgreSQL 十表、原始索引正文与向量、对象资源与 Wiki 快照,封存为内容寻址候选产物后恢复写入者并等到 healthy。
|
||||
- 新增按 Compose 项目固定身份的冻结控制器:整个项目逐服务声明,出现未声明服务或容器被重建即拒绝,只发 SIGTERM,恢复后必须 healthy。
|
||||
- 新增「整库版本」页(只读):对内/对外最新封存、分项数量与字节、摘要、兼容契约、归档占用;未接线时明确显示原因,不提供未实现的封存按钮。
|
||||
- 新增运维手册 `docs/library-capture.md`,含 2026-10-28 两次真实封存的快照 ID 与实测数字。
|
||||
|
||||
### Changed
|
||||
|
||||
- api 增加 `LIBRARY_ARCHIVE_ROOT` 与整库归档根的只读挂载(写入只发生在主机上的 libraryctl)。
|
||||
|
||||
### Not included
|
||||
|
||||
- 本快照不代表整库业务验收通过:内容/问答/性能验收未绑定,跨系统一致切点、Wiki 删除语义重算、生产预备份与恢复演练、双闸授权、整库同步协调与失败续作仍未完成。
|
||||
|
||||
## 开发快照 snapshot/v0.1.105 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复成功作业重放遗漏验收策略检查的问题:旧快照缺少当前策略标识时明确拒绝,不静默升级验收口径,不返回成功状态或快照 ID,也不重新暂停测试写入服务。
|
||||
- 新策略的正常重放与跨库、归档丢失等保护保持有效;此修复不代表内容/问答/性能验收绑定或整库业务链已经完成。
|
||||
|
||||
## 开发快照 snapshot/v0.1.104 - 2026-10-28
|
||||
|
||||
### Changed
|
||||
|
||||
- 按已确认的验收口径 A,正文索引作为原始产物保留,不再因无法从数据库反推临时生成上下文而拒绝候选归档;身份、覆盖、摘要及持久化生成问题的精确核验保持不变。
|
||||
- 候选清单加入受支持的验收策略标识并纳入快照身份。候选归档不代表语义验收或生产放行;真实冻结接线、快照绑定的内容/问答/性能验收与完整同步恢复仍待完成。
|
||||
|
||||
## 开发快照 snapshot/v0.1.103 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 整库索引校验支持从分块持久元数据核验生成问题:严格匹配分块、问题 source_id 与问题原文,拒绝未知、过期或内容不一致的索引。
|
||||
- 分开核验正文与生成问题的覆盖,问题记录不能掩盖正文索引缺失;元数据中已记录的问题缺少索引同样阻断。未放宽临时章节上下文或未知索引变换的检查。
|
||||
|
||||
## 开发快照 snapshot/v0.1.102 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 阻止旧式 status=0 普通分块缺失索引时被误判完整;仅明确的上下文父分块允许没有索引,显式标记已索引的分块仍须存在。
|
||||
- 缺少可核验的无索引策略时返回覆盖未证实,不推断索引已禁用;Wiki-only 无索引库的完整支持仍待实现,不因此宣称整库验收通过。
|
||||
|
||||
## 开发快照 snapshot/v0.1.101 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复正常正文索引因标题前缀或正文首尾空白处理而被整库归档误拒的问题;仅按已持久化的标题与正文重建确定性内容,保持逐字核验,不使用后缀包含匹配。
|
||||
- 无法由持久数据核验的临时章节上下文、非正文类型的变换及未知内容仍阻断;不将本次兼容修复视为完整索引或整库业务验收通过。
|
||||
|
||||
## 开发快照 snapshot/v0.1.100 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 测试封存暂停共享写入服务前及暂停后,强制检查整个源数据库的解析状态、待处理任务和死信;其他库、其他租户及已删除或未知任务范围的未完成工作均阻断封存。
|
||||
- 保留部署侧入口与后台作业检查;数据库任务结清不代表 Wiki 语义验收通过。本次未清理死信、未暂停实际测试 WeKnora、未执行生产发布。
|
||||
|
||||
## 开发快照 snapshot/v0.1.99 - 2026-10-28
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -812,6 +812,125 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/snapshots": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Runtime"
|
||||
],
|
||||
"operationId": "listLibrarySnapshots",
|
||||
"summary": "列出已封存的整库完整版本(只读;含分项数量/字节/摘要、跨版本去重内容字节与文件系统事实)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/captures": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Runtime"
|
||||
],
|
||||
"operationId": "listLibraryCaptures",
|
||||
"summary": "列出最近的整库封存作业(读队列,不是归档;页面据此显示真实状态)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"tags": [
|
||||
"Runtime"
|
||||
],
|
||||
"operationId": "enqueueLibraryCapture",
|
||||
"summary": "投递一次整库封存作业(需要工程师及以上;执行在主机侧 agent,容器没有 Docker/来源凭据)",
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"scope": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"internal",
|
||||
"external"
|
||||
]
|
||||
},
|
||||
"job": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"scope"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"202": {
|
||||
"description": "已入队封存作业(同一 scope+job 复用同一作业)"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"503": {
|
||||
"description": "主机侧封存 agent 未接线"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/snapshots/{id}": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Runtime"
|
||||
],
|
||||
"operationId": "getLibrarySnapshot",
|
||||
"summary": "读取单个已封存整库版本的分项与兼容契约(只读;不存在或校验失败返回 404)",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"404": {
|
||||
"description": "快照不存在或归档校验失败"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/version-history": {
|
||||
"get": {
|
||||
"tags": [
|
||||
|
||||
@@ -201,6 +201,8 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
BackupSchedule: postgresstore.NewStore(pool),
|
||||
VersionHistory: versionHistoryStore,
|
||||
VersionHistoryRepo: versionHistoryRepo,
|
||||
LibraryArchiveRoot: config.LibraryArchiveRoot,
|
||||
LibraryAgentSocket: config.LibraryAgentSocket,
|
||||
BackupHost: backuphost.New(backuphost.Config{
|
||||
SSHConfig: config.BackupHostSSHConfig,
|
||||
Target: config.BackupHostTarget,
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// Command libraryagent is the host-side execution boundary for whole-library
|
||||
// capture. It runs as the ordinary operator account, owns no network listener
|
||||
// other than one 0600 unix socket, and executes exactly one fixed command shape.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/libraryagent"
|
||||
)
|
||||
|
||||
func main() {
|
||||
home, _ := os.UserHomeDir()
|
||||
var config libraryagent.Config
|
||||
flag.StringVar(&config.Socket, "socket", filepath.Join(home, ".local/share/knowledge-governance/agent.sock"), "unix socket for capture requests")
|
||||
flag.StringVar(&config.Binary, "binary", "/home/zheromiku/knowledge-governance/libraryctl", "libraryctl binary this agent executes")
|
||||
flag.StringVar(&config.ArchiveRoot, "archive", filepath.Join(home, ".local/share/knowledge-governance/library"), "sealed artifact root")
|
||||
flag.StringVar(&config.JournalRoot, "journal", filepath.Join(home, ".local/share/knowledge-governance/freeze"), "freeze journal root")
|
||||
flag.StringVar(&config.SourceApp, "source-app", "WKNFull-app", "source container describing the stack")
|
||||
flag.StringVar(&config.SourcePG, "source-pg", "WKNFull-postgres", "source PostgreSQL container")
|
||||
flag.StringVar(&config.SourceES, "source-es", "WKNFull-elasticsearch", "source Elasticsearch container")
|
||||
flag.StringVar(&config.GovernancePG, "governance-pg", "knowledge-governance-p1-postgres-1", "governance PostgreSQL container")
|
||||
flag.StringVar(&config.Project, "project", "weknora071full", "Compose project owning the writers")
|
||||
flag.StringVar(&config.Writers, "writers", "app", "declared writer services")
|
||||
nonWriters := flag.String("non-writers", defaultNonWriters, "service=reason for every other project service")
|
||||
flag.DurationVar(&config.MaxDuration, "max-duration", 10*time.Minute, "upper bound for one operation")
|
||||
describe := flag.Bool("describe", false, "print the fixed configuration and exit")
|
||||
flag.Parse()
|
||||
config.NonWriters = *nonWriters
|
||||
|
||||
agent, err := libraryagent.New(config)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if *describe {
|
||||
log.Printf("library agent config: %+v", agent.Describe())
|
||||
return
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
log.Printf("library agent listening on %s (project %s, writers %s)", config.Socket, config.Project, config.Writers)
|
||||
if err = agent.Serve(ctx); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaultNonWriters mirrors scripts/library-capture.sh: every sibling service of
|
||||
// the source project is declared, with the reason it cannot write knowledge.
|
||||
const defaultNonWriters = "frontend=UI only; no knowledge writes" +
|
||||
",mcp=read-only MCP server" +
|
||||
",dobotai-target=alpine placeholder; no knowledge writes" +
|
||||
",docreader=parse RPC service; app persists parse output and settlement requires zero pending ops" +
|
||||
",elasticsearch=search store; not an initiator" +
|
||||
",postgres=database store; not an initiator" +
|
||||
",redis=queue/cache store; not an initiator" +
|
||||
",neo4j=graph store; not an initiator" +
|
||||
",langfuse-web=LLM observability UI" +
|
||||
",langfuse-worker=LLM observability worker; own storage" +
|
||||
",langfuse-clickhouse=observability store" +
|
||||
",langfuse-minio=observability object store" +
|
||||
",langfuse-db-init=one-shot init; exited" +
|
||||
",searxng=read-only search proxy" +
|
||||
",searxng-init=one-shot init; exited"
|
||||
@@ -0,0 +1,839 @@
|
||||
// Command libraryctl is the operator entry point for the whole-library capture
|
||||
// chain: it reads one test knowledge base (internal or external) from the real
|
||||
// WeKnora test stack, freezes its writers for the duration of the export and
|
||||
// seals a content-addressed candidate artifact.
|
||||
//
|
||||
// Boundaries this command keeps:
|
||||
// - the source is read through a read-only PostgreSQL session; no source
|
||||
// schema, data or program is modified;
|
||||
// - only SIGTERM is sent to the declared writer group, and only when every
|
||||
// service of the Compose project is declared (a new sibling container is
|
||||
// refused, not ignored);
|
||||
// - credentials are read from the running containers at the moment of the
|
||||
// call and are never printed, logged or written to disk;
|
||||
// - the sealed artifact is a *candidate*: it is not a release, and it does
|
||||
// not replace snapshot-bound content, Q&A and performance acceptance.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
v071 "knowledge-governance/internal/releaseadapter/v071"
|
||||
releaseworkflow "knowledge-governance/internal/workflows/release"
|
||||
)
|
||||
|
||||
type options struct {
|
||||
sourceApp string
|
||||
sourcePG string
|
||||
sourceES string
|
||||
governancePG string
|
||||
project string
|
||||
writers string
|
||||
nonWriters string
|
||||
archiveRoot string
|
||||
journalRoot string
|
||||
dockerSocket string
|
||||
maxDocuments int
|
||||
maxObjectBytes int64
|
||||
scope string
|
||||
job string
|
||||
dryRun bool
|
||||
snapshot string
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
command := os.Args[1]
|
||||
opts, rest, err := parseFlags(command, os.Args[2:])
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "LIBRARYCTL_FLAGS:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
_ = rest
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
||||
defer cancel()
|
||||
var runErr error
|
||||
switch command {
|
||||
case "status":
|
||||
runErr = runStatus(ctx, opts)
|
||||
case "preflight":
|
||||
runErr = runPreflight(ctx, opts)
|
||||
case "capture":
|
||||
runErr = runCapture(ctx, opts)
|
||||
case "list":
|
||||
runErr = runList(opts)
|
||||
case "verify":
|
||||
runErr = runVerify(opts)
|
||||
case "recover":
|
||||
runErr = runRecover(ctx, opts)
|
||||
default:
|
||||
usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
if runErr != nil {
|
||||
fmt.Fprintln(os.Stderr, "LIBRARYCTL_FAILED:", runErr)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func usage() {
|
||||
fmt.Fprint(os.Stderr, `libraryctl <status|preflight|capture|list|verify|recover> [flags]
|
||||
|
||||
status probe the real source and print what is configured / blocked
|
||||
preflight read the source, run settlement + candidate validation (no writes, no stop)
|
||||
capture freeze the declared writer group, archive a candidate, restore writers
|
||||
list list sealed candidates and stored bytes
|
||||
verify re-verify one sealed candidate (digests, coverage, identity)
|
||||
recover restore writers from an interrupted freeze journal
|
||||
|
||||
Flags (defaults target the local WKNFull test stack):
|
||||
-source-app WKNFull-app container whose env describes the source
|
||||
-source-pg WKNFull-postgres source PostgreSQL container (address resolution)
|
||||
-source-es WKNFull-elasticsearch
|
||||
-governance-pg knowledge-governance-p1-postgres-1 routing bindings read here
|
||||
-project weknora071full Compose project owning the writer group
|
||||
-writers WKNFull-app declared writer services (comma separated)
|
||||
-non-writers WKNFull-frontend=reason,... every other project service
|
||||
-archive ~/.local/share/knowledge-governance/library
|
||||
-journal ~/.local/share/knowledge-governance/freeze
|
||||
-docker-socket /var/run/docker.sock
|
||||
-scope internal|external (preflight/capture)
|
||||
-job <id> (capture; default: lib-<scope>-<UTC timestamp>)
|
||||
-dry-run (capture: export + validate only, no archive, no stop)
|
||||
-snapshot <id> (verify)
|
||||
`)
|
||||
}
|
||||
|
||||
func parseFlags(command string, args []string) (options, []string, error) {
|
||||
home, _ := os.UserHomeDir()
|
||||
opts := options{
|
||||
sourceApp: "WKNFull-app",
|
||||
sourcePG: "WKNFull-postgres",
|
||||
sourceES: "WKNFull-elasticsearch",
|
||||
governancePG: "knowledge-governance-p1-postgres-1",
|
||||
project: "weknora071full",
|
||||
writers: "WKNFull-app",
|
||||
archiveRoot: filepath.Join(home, ".local/share/knowledge-governance/library"),
|
||||
journalRoot: filepath.Join(home, ".local/share/knowledge-governance/freeze"),
|
||||
dockerSocket: "/var/run/docker.sock",
|
||||
maxDocuments: 100000,
|
||||
maxObjectBytes: 134217728,
|
||||
}
|
||||
set := flag.NewFlagSet(command, flag.ContinueOnError)
|
||||
set.SetOutput(os.Stderr)
|
||||
set.StringVar(&opts.sourceApp, "source-app", opts.sourceApp, "source container describing the stack")
|
||||
set.StringVar(&opts.sourcePG, "source-pg", opts.sourcePG, "source PostgreSQL container")
|
||||
set.StringVar(&opts.sourceES, "source-es", opts.sourceES, "source Elasticsearch container")
|
||||
set.StringVar(&opts.governancePG, "governance-pg", opts.governancePG, "governance PostgreSQL container")
|
||||
set.StringVar(&opts.project, "project", opts.project, "Compose project owning the writers")
|
||||
set.StringVar(&opts.writers, "writers", opts.writers, "declared writer services")
|
||||
set.StringVar(&opts.nonWriters, "non-writers", "", "service=reason for every other project service")
|
||||
set.StringVar(&opts.archiveRoot, "archive", opts.archiveRoot, "sealed artifact root")
|
||||
set.StringVar(&opts.journalRoot, "journal", opts.journalRoot, "freeze journal root")
|
||||
set.StringVar(&opts.dockerSocket, "docker-socket", opts.dockerSocket, "Docker engine socket")
|
||||
set.IntVar(&opts.maxDocuments, "max-documents", opts.maxDocuments, "maximum indexed documents per scope")
|
||||
set.Int64Var(&opts.maxObjectBytes, "max-object-bytes", opts.maxObjectBytes, "maximum bytes per stored object")
|
||||
set.StringVar(&opts.scope, "scope", "", "internal|external")
|
||||
set.StringVar(&opts.job, "job", "", "capture job id")
|
||||
set.BoolVar(&opts.dryRun, "dry-run", false, "export and validate without archiving or stopping")
|
||||
set.StringVar(&opts.snapshot, "snapshot", "", "snapshot id for verify")
|
||||
if err := set.Parse(args); err != nil {
|
||||
return opts, nil, err
|
||||
}
|
||||
return opts, set.Args(), nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- discovery
|
||||
|
||||
func dockerOutput(ctx context.Context, args ...string) (string, error) {
|
||||
bounded, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(bounded, "docker", args...).Output()
|
||||
if err != nil {
|
||||
var exit *exec.ExitError
|
||||
if errors.As(err, &exit) && len(exit.Stderr) > 0 {
|
||||
return "", fmt.Errorf("docker %s failed", args[0])
|
||||
}
|
||||
return "", fmt.Errorf("docker %s failed", args[0])
|
||||
}
|
||||
return strings.TrimSpace(string(out)), nil
|
||||
}
|
||||
|
||||
func containerEnv(ctx context.Context, name string) (map[string]string, error) {
|
||||
raw, err := dockerOutput(ctx, "inspect", "--format", "{{json .Config.Env}}", name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var entries []string
|
||||
if err := json.Unmarshal([]byte(raw), &entries); err != nil {
|
||||
return nil, errors.New("invalid container environment")
|
||||
}
|
||||
env := map[string]string{}
|
||||
for _, entry := range entries {
|
||||
if key, value, ok := strings.Cut(entry, "="); ok {
|
||||
env[key] = value
|
||||
}
|
||||
}
|
||||
return env, nil
|
||||
}
|
||||
|
||||
func containerAddress(ctx context.Context, name string) (string, error) {
|
||||
raw, err := dockerOutput(ctx, "inspect", "--format",
|
||||
"{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}", name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, field := range strings.Fields(raw) {
|
||||
if field != "" && field != "0.0.0.0" {
|
||||
return field, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("container %s has no reachable address", name)
|
||||
}
|
||||
|
||||
func containerImageID(ctx context.Context, name string) (string, error) {
|
||||
return dockerOutput(ctx, "inspect", "--format", "{{.Image}}", name)
|
||||
}
|
||||
|
||||
// sourceConfig is everything needed to read the test library. Credential fields
|
||||
// are never printed: String() masks them and no log line formats the struct.
|
||||
type sourceConfig struct {
|
||||
Scopes map[string]string
|
||||
DatabaseURL string
|
||||
Search v071.SearchExporterConfig
|
||||
Object v071.S3ObjectStoreConfig
|
||||
AppImageID string
|
||||
SearchIndex string
|
||||
ObjectDetail string
|
||||
}
|
||||
|
||||
func discoverSource(ctx context.Context, opts options, binding map[string]string) (sourceConfig, error) {
|
||||
var config sourceConfig
|
||||
if binding == nil {
|
||||
return config, errors.New("routing bindings are required")
|
||||
}
|
||||
config.Scopes = binding
|
||||
app, err := containerEnv(ctx, opts.sourceApp)
|
||||
if err != nil {
|
||||
return config, err
|
||||
}
|
||||
if app["DB_DRIVER"] != "postgres" {
|
||||
return config, errors.New("source database driver is not postgres")
|
||||
}
|
||||
if app["STORAGE_TYPE"] != "oss" {
|
||||
return config, fmt.Errorf("unsupported source storage type %q", app["STORAGE_TYPE"])
|
||||
}
|
||||
address, err := containerAddress(ctx, opts.sourcePG)
|
||||
if err != nil {
|
||||
return config, err
|
||||
}
|
||||
dsn := strings.Join([]string{
|
||||
"postgres://" + urlEscape(app["DB_USER"]) + ":" + urlEscape(app["DB_PASSWORD"]) +
|
||||
"@" + address + ":" + app["DB_PORT"] + "/" + urlEscape(app["DB_NAME"]) + "?sslmode=disable",
|
||||
}, "")
|
||||
config.DatabaseURL = dsn
|
||||
config.AppImageID, err = containerImageID(ctx, opts.sourceApp)
|
||||
if err != nil {
|
||||
return config, err
|
||||
}
|
||||
esAddress, err := containerAddress(ctx, opts.sourceES)
|
||||
if err != nil {
|
||||
return config, err
|
||||
}
|
||||
config.SearchIndex = app["ELASTICSEARCH_INDEX"]
|
||||
config.Search = v071.SearchExporterConfig{BaseURL: "http://" + esAddress + ":9200", Index: app["ELASTICSEARCH_INDEX"],
|
||||
AuthorizationToken: app["ELASTICSEARCH_PASSWORD"], PageSize: 500}
|
||||
endpoint := app["OSS_ENDPOINT"]
|
||||
if endpoint == "" {
|
||||
return config, errors.New("source object endpoint is not configured")
|
||||
}
|
||||
if !strings.Contains(endpoint, "://") {
|
||||
endpoint = "https://" + endpoint
|
||||
}
|
||||
config.Object = v071.S3ObjectStoreConfig{Provider: "oss", Endpoint: endpoint, Region: app["OSS_REGION"],
|
||||
AccessKeyID: app["OSS_ACCESS_KEY"], SecretAccessKey: app["OSS_SECRET_KEY"], Bucket: app["OSS_BUCKET_NAME"],
|
||||
Secure: strings.HasPrefix(endpoint, "https://"), MaxObjectBytes: opts.maxObjectBytes}
|
||||
config.ObjectDetail = "bucket=" + app["OSS_BUCKET_NAME"] + " region=" + app["OSS_REGION"]
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func urlEscape(value string) string {
|
||||
replacer := strings.NewReplacer("%", "%25", ":", "%3A", "@", "%40", "/", "%2F", "?", "%3F", "#", "%23", "&", "%26", " ", "%20")
|
||||
return replacer.Replace(value)
|
||||
}
|
||||
|
||||
func readRoutingBindings(ctx context.Context, container string) (map[string]string, error) {
|
||||
raw, err := dockerOutput(ctx, "exec", container, "psql", "-U", "governance", "-d", "governance", "-tAc",
|
||||
"SELECT internal_kb_id||'|'||external_kb_id FROM routing_kb_bindings WHERE id='active'")
|
||||
if err != nil {
|
||||
return nil, errors.New("read routing bindings failed")
|
||||
}
|
||||
internal, external, ok := strings.Cut(strings.TrimSpace(raw), "|")
|
||||
if !ok || internal == "" || external == "" {
|
||||
return nil, errors.New("routing bindings are incomplete")
|
||||
}
|
||||
return map[string]string{"internal": internal, "external": external}, nil
|
||||
}
|
||||
|
||||
func openSourceDatabase(ctx context.Context, config sourceConfig) (*pgxpool.Pool, error) {
|
||||
parsed, err := pgxpool.ParseConfig(config.DatabaseURL)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid source database url")
|
||||
}
|
||||
// The capture chain never writes to the source. The read-only session makes
|
||||
// that a database-enforced property rather than a convention.
|
||||
parsed.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
|
||||
parsed.ConnConfig.RuntimeParams["statement_timeout"] = "120000"
|
||||
pool, err := pgxpool.NewWithConfig(ctx, parsed)
|
||||
if err != nil {
|
||||
return nil, errors.New("open source database failed")
|
||||
}
|
||||
var readOnly string
|
||||
if err = pool.QueryRow(ctx, "SHOW default_transaction_read_only").Scan(&readOnly); err != nil || readOnly != "on" {
|
||||
pool.Close()
|
||||
return nil, errors.New("source session is not read-only")
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func tenantAndKnowledgeBase(ctx context.Context, pool *pgxpool.Pool, knowledgeBaseID string) (uint64, error) {
|
||||
var tenant uint64
|
||||
err := pool.QueryRow(ctx, "SELECT tenant_id FROM knowledge_bases WHERE id=$1 AND deleted_at IS NULL", knowledgeBaseID).Scan(&tenant)
|
||||
if err != nil || tenant == 0 {
|
||||
return 0, errors.New("knowledge base not found in source")
|
||||
}
|
||||
return tenant, nil
|
||||
}
|
||||
|
||||
func writerDeclaration(opts options) ([]string, map[string]string, error) {
|
||||
writers := []string{}
|
||||
for _, name := range strings.Split(opts.writers, ",") {
|
||||
if trimmed := strings.TrimSpace(name); trimmed != "" {
|
||||
writers = append(writers, trimmed)
|
||||
}
|
||||
}
|
||||
if len(writers) == 0 {
|
||||
return nil, nil, errors.New("no writer service declared")
|
||||
}
|
||||
nonWriters := map[string]string{}
|
||||
for _, entry := range strings.Split(opts.nonWriters, ",") {
|
||||
entry = strings.TrimSpace(entry)
|
||||
if entry == "" {
|
||||
continue
|
||||
}
|
||||
name, reason, ok := strings.Cut(entry, "=")
|
||||
if !ok || strings.TrimSpace(reason) == "" {
|
||||
return nil, nil, fmt.Errorf("non-writer %q needs service=reason", entry)
|
||||
}
|
||||
nonWriters[strings.TrimSpace(name)] = strings.TrimSpace(reason)
|
||||
}
|
||||
return writers, nonWriters, nil
|
||||
}
|
||||
|
||||
func openFreeze(ctx context.Context, opts options) (*libraryfreeze.Coordinator, *libraryfreeze.ProjectController, error) {
|
||||
writers, nonWriters, err := writerDeclaration(opts)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err = os.MkdirAll(opts.journalRoot, 0700); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err = os.Chmod(opts.journalRoot, 0700); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
control, err := libraryfreeze.NewProjectController(opts.dockerSocket, opts.project, writers, nonWriters, 2*time.Minute)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
coordinator, err := libraryfreeze.Open(opts.journalRoot, opts.project, control)
|
||||
if err != nil {
|
||||
control.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return coordinator, control, nil
|
||||
}
|
||||
|
||||
func openArchive(opts options) (*librarysnapshot.Archive, error) {
|
||||
if err := os.MkdirAll(opts.archiveRoot, 0700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.Chmod(opts.archiveRoot, 0700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return librarysnapshot.Open(opts.archiveRoot, 256*1024*1024)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- commands
|
||||
|
||||
func runStatus(ctx context.Context, opts options) error {
|
||||
report := map[string]any{}
|
||||
binding, bindingErr := readRoutingBindings(ctx, opts.governancePG)
|
||||
var config sourceConfig
|
||||
var err error
|
||||
if bindingErr != nil {
|
||||
err = bindingErr
|
||||
} else {
|
||||
config, err = discoverSource(ctx, opts, binding)
|
||||
}
|
||||
if err != nil {
|
||||
report["source_discovery"] = err.Error()
|
||||
} else {
|
||||
report["source"] = map[string]any{
|
||||
"app_image": config.AppImageID,
|
||||
"scopes": config.Scopes,
|
||||
"search_index": config.SearchIndex,
|
||||
"elasticsearch": config.Search.BaseURL,
|
||||
"object_store": config.ObjectDetail,
|
||||
"database": "postgres (read-only session, credentials withheld)",
|
||||
"credentials_logged": false,
|
||||
}
|
||||
pool, poolErr := openSourceDatabase(ctx, config)
|
||||
if poolErr != nil {
|
||||
report["database"] = poolErr.Error()
|
||||
} else {
|
||||
defer pool.Close()
|
||||
settled := "settled"
|
||||
if settleErr := v071.LibrarySourceSettled(ctx, pool); settleErr != nil {
|
||||
settled = settleErr.Error()
|
||||
}
|
||||
report["settlement"] = settled
|
||||
counts := map[string]int{}
|
||||
for _, scope := range []string{"internal", "external"} {
|
||||
kb := config.Scopes[scope]
|
||||
tenant, tenantErr := tenantAndKnowledgeBase(ctx, pool, kb)
|
||||
if tenantErr != nil {
|
||||
counts[scope+"_error"] = -1
|
||||
continue
|
||||
}
|
||||
pg, exportErr := v071.ExportLibrary(ctx, pool, v071.PostgresIdentity{TenantID: tenant, KnowledgeBaseID: kb})
|
||||
if exportErr != nil {
|
||||
counts[scope+"_error"] = -1
|
||||
continue
|
||||
}
|
||||
for _, table := range pg.Tables {
|
||||
if table.Name == "chunks" || table.Name == "knowledges" {
|
||||
counts[scope+"_"+table.Name] = len(table.Rows)
|
||||
}
|
||||
}
|
||||
_ = kb
|
||||
}
|
||||
report["postgres_rows"] = counts
|
||||
}
|
||||
}
|
||||
archive, err := openArchive(opts)
|
||||
if err != nil {
|
||||
report["archive"] = err.Error()
|
||||
} else {
|
||||
defer archive.Close()
|
||||
usage, usageErr := archive.Usage()
|
||||
if usageErr != nil {
|
||||
report["archive"] = usageErr.Error()
|
||||
} else {
|
||||
total := int64(0)
|
||||
for _, item := range usage {
|
||||
total += item.UniqueBytes
|
||||
}
|
||||
report["archive"] = map[string]any{"root": opts.archiveRoot, "snapshots": len(usage), "stored_bytes": total}
|
||||
}
|
||||
}
|
||||
if coordinator, control, freezeErr := openFreeze(ctx, opts); freezeErr != nil {
|
||||
report["freeze"] = freezeErr.Error()
|
||||
} else {
|
||||
defer coordinator.Close()
|
||||
defer control.Close()
|
||||
items, inventoryErr := control.Inventory(ctx)
|
||||
if inventoryErr != nil {
|
||||
report["freeze"] = inventoryErr.Error()
|
||||
} else {
|
||||
group := []map[string]any{}
|
||||
for _, item := range items {
|
||||
group = append(group, map[string]any{"id": item.ID, "running": item.Running, "healthy": item.Healthy})
|
||||
}
|
||||
report["freeze"] = map[string]any{"project": opts.project, "writers": group, "journal": opts.journalRoot}
|
||||
}
|
||||
}
|
||||
printJSON(report)
|
||||
return nil
|
||||
}
|
||||
|
||||
func runPreflight(ctx context.Context, opts options) error {
|
||||
if opts.scope != "internal" && opts.scope != "external" {
|
||||
return errors.New("-scope must be internal or external")
|
||||
}
|
||||
binding, err := readRoutingBindings(ctx, opts.governancePG)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
config, err := discoverSource(ctx, opts, binding)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := openSourceDatabase(ctx, config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
kb := config.Scopes[opts.scope]
|
||||
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = v071.LibrarySourceSettled(ctx, pool); err != nil {
|
||||
return err
|
||||
}
|
||||
search, err := v071.NewSearchExporter(config.Search)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
contract, err := compatibilityContract(ctx, pool, search, config.SearchIndex, tenant, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pg, err := v071.ExportLibrary(ctx, pool, v071.PostgresIdentity{TenantID: tenant, KnowledgeBaseID: kb})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
es, err := search.ExportLibrary(ctx, v071.SearchIdentity{TenantID: tenant, KnowledgeBaseID: kb}, opts.maxDocuments)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
validation := "candidate-valid"
|
||||
if err = v071.ValidateLibraryCandidateForPreflight(v071.PostgresIdentity{TenantID: tenant, KnowledgeBaseID: kb}, pg, es); err != nil {
|
||||
validation = err.Error()
|
||||
}
|
||||
tables := map[string]int{}
|
||||
for _, table := range pg.Tables {
|
||||
tables[table.Name] = len(table.Rows)
|
||||
}
|
||||
printJSON(map[string]any{"scope": opts.scope, "knowledge_base_id": kb, "tenant_id": tenant,
|
||||
"compatibility": contract, "postgres_rows": tables, "index_documents": len(es.Documents),
|
||||
"mapping_sha256": es.MappingSHA256, "validation": validation, "writes": 0, "writers_stopped": 0})
|
||||
if validation != "candidate-valid" {
|
||||
return errors.New("candidate validation failed: " + validation)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func compatibilityContract(ctx context.Context, pool *pgxpool.Pool, search *v071.SearchExporter, index string, tenant uint64, kb string) (v071.LibrarySnapshotCompatibility, error) {
|
||||
inspector, err := v071.NewTargetContractInspector(v071.TargetContractInspectorConfig{DB: pool, Mapping: search,
|
||||
KnowledgeBaseID: kb, TenantID: tenant, IndexName: index, ReadTestedBase: true})
|
||||
if err != nil {
|
||||
return v071.LibrarySnapshotCompatibility{}, err
|
||||
}
|
||||
contract, err := inspector.Contract(ctx, releaseworkflow.PlanItem{TestKnowledgeBaseID: kb})
|
||||
if err != nil {
|
||||
return v071.LibrarySnapshotCompatibility{}, err
|
||||
}
|
||||
return v071.LibrarySnapshotCompatibility{WeKnoraVersion: contract.WeKnoraVersion, SchemaVersion: contract.MigrationVersion,
|
||||
RetrieverEngine: contract.RetrieverEngine, EmbeddingModel: contract.EmbeddingModel,
|
||||
EmbeddingDimension: contract.EmbeddingDimension, IndexMappingSHA256: contract.ElasticsearchMappingSHA256}, nil
|
||||
}
|
||||
|
||||
func runCapture(ctx context.Context, opts options) error {
|
||||
if opts.scope != "internal" && opts.scope != "external" {
|
||||
return errors.New("-scope must be internal or external")
|
||||
}
|
||||
if opts.dryRun {
|
||||
return runPreflight(ctx, opts)
|
||||
}
|
||||
job := opts.job
|
||||
if job == "" {
|
||||
job = "lib-" + opts.scope + "-" + time.Now().UTC().Format("20060102T150405")
|
||||
}
|
||||
archive, err := openArchive(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
coordinator, control, err := openFreeze(ctx, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer coordinator.Close()
|
||||
defer control.Close()
|
||||
if err = coordinator.Recover(ctx); err != nil {
|
||||
return fmt.Errorf("pending freeze requires recovery: %w", err)
|
||||
}
|
||||
// Replay is answered from the persisted journal + sealed archive: the same job
|
||||
// re-used with the same scope/binding returns the original candidate without
|
||||
// reading the source or stopping a writer, and a job re-used with different
|
||||
// parameters is refused instead of silently sealing under a stale identity.
|
||||
existing, found, err := coordinator.Inspect(job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
binding, err := readRoutingBindings(ctx, opts.governancePG)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
scopedKB := binding[opts.scope]
|
||||
if found {
|
||||
manifest, err := replayCapture(job, opts.scope, scopedKB, existing, archive)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printCapture(job, existing.SnapshotID, manifest, true)
|
||||
}
|
||||
config, err := discoverSource(ctx, opts, binding)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := openSourceDatabase(ctx, config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
kb := config.Scopes[opts.scope]
|
||||
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
search, err := v071.NewSearchExporter(config.Search)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
objects, err := v071.NewS3ObjectStore(config.Object)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
contract, err := compatibilityContract(ctx, pool, search, config.SearchIndex, tenant, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// The contract above is read before the maintenance window. Re-read it inside
|
||||
// the stopped window and refuse if a model/index change happened in between:
|
||||
// sealing a candidate whose contract no longer matches the source would hide
|
||||
// exactly the change a later production sync cannot reproduce.
|
||||
verifyContract := func(ctx context.Context) error {
|
||||
live, err := compatibilityContract(ctx, pool, search, config.SearchIndex, tenant, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if live != contract {
|
||||
return errors.New("source contract changed between preflight and the frozen window; capture aborted")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// sourceReady proves the declared writer group is complete and no other
|
||||
// running container uses a declared writer image. Recorded work settlement is
|
||||
// enforced separately by CaptureLibrary; neither check can see unrecorded or
|
||||
// remote work, so this is not a cross-system consistency proof.
|
||||
sourceReady := func(ctx context.Context) error {
|
||||
items, err := control.Inventory(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return errors.New("writer group is empty")
|
||||
}
|
||||
declared := make(map[string]bool, len(items))
|
||||
for _, item := range items {
|
||||
declared[item.ID] = true
|
||||
}
|
||||
images, err := writerImageIDs(ctx, items)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return checkNoUndeclaredWriter(ctx, images, declared)
|
||||
}
|
||||
result, err := v071.CaptureLibrary(ctx, coordinator, archive, pool, search, objects, sourceReady,
|
||||
v071.LibraryCaptureRequest{JobID: job, Scope: opts.scope,
|
||||
Identity: v071.PostgresIdentity{TenantID: tenant, KnowledgeBaseID: kb},
|
||||
Compatibility: contract, CreatedAt: time.Now().UTC(), MaxDocuments: opts.maxDocuments,
|
||||
VerifyContract: verifyContract})
|
||||
if err != nil {
|
||||
printJSON(map[string]any{"job": job, "state": result.State, "snapshot_id": result.SnapshotID, "error": err.Error()})
|
||||
return err
|
||||
}
|
||||
manifest, err := archive.Load(result.SnapshotID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printCapture(job, result.SnapshotID, manifest, false)
|
||||
}
|
||||
|
||||
// replayCapture answers a repeated job from persisted state. It never reads the
|
||||
// source and never stops a writer; conflicting parameters are refused.
|
||||
func replayCapture(job, scope, expectedKB string, result libraryfreeze.Result, archive *librarysnapshot.Archive) (librarysnapshot.Manifest, error) {
|
||||
if result.State != "succeeded" || result.SnapshotID == "" {
|
||||
return librarysnapshot.Manifest{}, fmt.Errorf("job %q already exists with state %q: recover it or use a new job id", job, result.State)
|
||||
}
|
||||
manifest, err := archive.Load(result.SnapshotID)
|
||||
if err != nil {
|
||||
return librarysnapshot.Manifest{}, errors.New("captured library archive no longer verifies")
|
||||
}
|
||||
if manifest.ValidationPolicy != librarysnapshot.ArtifactAcceptancePolicy {
|
||||
return librarysnapshot.Manifest{}, errors.New("existing job was sealed under a different validation policy")
|
||||
}
|
||||
if manifest.Scope != scope {
|
||||
return librarysnapshot.Manifest{}, fmt.Errorf("job %q was captured for scope %q, not %q", job, manifest.Scope, scope)
|
||||
}
|
||||
if manifest.KnowledgeBaseID != expectedKB {
|
||||
return librarysnapshot.Manifest{}, fmt.Errorf("job %q was captured for knowledge base %q, which is no longer the %q binding", job, manifest.KnowledgeBaseID, scope)
|
||||
}
|
||||
return manifest, nil
|
||||
}
|
||||
|
||||
func printCapture(job, snapshotID string, manifest librarysnapshot.Manifest, replay bool) error {
|
||||
parts := make([]map[string]any, 0, len(manifest.Parts))
|
||||
var total int64
|
||||
for _, part := range manifest.Parts {
|
||||
parts = append(parts, map[string]any{"kind": part.Kind, "name": part.Name, "count": part.Count, "bytes": part.Bytes, "sha256": part.SHA256})
|
||||
total += part.Bytes
|
||||
}
|
||||
sort.Slice(parts, func(i, j int) bool {
|
||||
return fmt.Sprint(parts[i]["kind"])+fmt.Sprint(parts[i]["name"]) < fmt.Sprint(parts[j]["kind"])+fmt.Sprint(parts[j]["name"])
|
||||
})
|
||||
printJSON(map[string]any{"job": job, "state": "succeeded", "snapshot_id": snapshotID,
|
||||
"scope": manifest.Scope, "knowledge_base_id": manifest.KnowledgeBaseID, "tenant_id": manifest.TenantID,
|
||||
"compatibility": manifest.Compatibility, "parts": parts, "logical_bytes": total,
|
||||
"validation_policy": manifest.ValidationPolicy, "writers_restored": true,
|
||||
"replay": replay, "source_read": !replay, "writers_stopped": !replay})
|
||||
return nil
|
||||
}
|
||||
|
||||
func writerImageIDs(ctx context.Context, items []libraryfreeze.Service) ([]string, error) {
|
||||
images := make([]string, 0, len(items))
|
||||
seen := map[string]bool{}
|
||||
for _, item := range items {
|
||||
image, err := containerImageOf(ctx, item.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !seen[image] {
|
||||
seen[image] = true
|
||||
images = append(images, image)
|
||||
}
|
||||
}
|
||||
return images, nil
|
||||
}
|
||||
|
||||
// checkNoUndeclaredWriter refuses to run when a running container uses a declared
|
||||
// writer image but is not part of the declared group: such a container could keep
|
||||
// writing during the maintenance window.
|
||||
func checkNoUndeclaredWriter(ctx context.Context, images []string, declared map[string]bool) error {
|
||||
for _, image := range images {
|
||||
out, err := dockerOutput(ctx, "ps", "-q", "--filter", "ancestor="+image)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, id := range strings.Fields(out) {
|
||||
if !declared[id] {
|
||||
return fmt.Errorf("container %s uses a declared writer image but is not in the declared writer group", id[:12])
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func containerImageOf(ctx context.Context, id string) (string, error) {
|
||||
image, err := dockerOutput(ctx, "inspect", "--format", "{{.Image}}", id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if image == "" {
|
||||
return "", errors.New("declared writer has no image identity")
|
||||
}
|
||||
return image, nil
|
||||
}
|
||||
func runList(opts options) error {
|
||||
archive, err := openArchive(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
usage, err := archive.Usage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
total, err := archive.ContentUsage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items := make([]map[string]any, 0, len(usage))
|
||||
for _, item := range usage {
|
||||
manifest, err := archive.Load(item.VersionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items = append(items, map[string]any{"snapshot_id": item.VersionID, "scope": manifest.Scope,
|
||||
"knowledge_base_id": manifest.KnowledgeBaseID, "created_at": manifest.CreatedAt,
|
||||
"logical_bytes": item.LogicalBytes, "unique_bytes": item.UniqueBytes, "shared_bytes": item.SharedBytes,
|
||||
"parts": len(manifest.Parts), "policy": manifest.ValidationPolicy})
|
||||
}
|
||||
printJSON(map[string]any{"archive": opts.archiveRoot, "snapshots": items,
|
||||
// 跨版本去重后的内容字节;文件系统事实单列,任何一项都不是可回收空间。
|
||||
"versions": total.Versions, "content_bytes": total.ContentBytes,
|
||||
"blob_file_bytes": total.BlobFileBytes, "blob_allocated_bytes": total.BlobAllocatedBytes,
|
||||
"unreferenced_blobs": total.UnreferencedBlobs, "unreferenced_bytes": total.UnreferencedBytes,
|
||||
"manifest_file_bytes": total.ManifestFileBytes, "manifest_allocated_bytes": total.ManifestAllocatedBytes})
|
||||
return nil
|
||||
}
|
||||
|
||||
func runVerify(opts options) error {
|
||||
if opts.snapshot == "" {
|
||||
return errors.New("-snapshot is required")
|
||||
}
|
||||
archive, err := openArchive(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
manifest, err := archive.Load(opts.snapshot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parts := make([]map[string]any, 0, len(manifest.Parts))
|
||||
for _, part := range manifest.Parts {
|
||||
parts = append(parts, map[string]any{"kind": part.Kind, "name": part.Name, "count": part.Count, "bytes": part.Bytes, "sha256": part.SHA256})
|
||||
}
|
||||
printJSON(map[string]any{"snapshot_id": opts.snapshot, "verified": true, "format": manifest.Format,
|
||||
"policy": manifest.ValidationPolicy, "scope": manifest.Scope, "knowledge_base_id": manifest.KnowledgeBaseID,
|
||||
"tenant_id": manifest.TenantID, "created_at": manifest.CreatedAt, "compatibility": manifest.Compatibility, "parts": parts})
|
||||
return nil
|
||||
}
|
||||
|
||||
func runRecover(ctx context.Context, opts options) error {
|
||||
coordinator, control, err := openFreeze(ctx, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer coordinator.Close()
|
||||
defer control.Close()
|
||||
if err = coordinator.Recover(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
items, err := control.Inventory(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
group := []map[string]any{}
|
||||
for _, item := range items {
|
||||
group = append(group, map[string]any{"id": item.ID, "running": item.Running, "healthy": item.Healthy})
|
||||
}
|
||||
printJSON(map[string]any{"recovered": true, "writers": group})
|
||||
return nil
|
||||
}
|
||||
|
||||
func printJSON(value any) {
|
||||
encoder := json.NewEncoder(os.Stdout)
|
||||
encoder.SetIndent("", " ")
|
||||
_ = encoder.Encode(value)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// sealedFixture writes one complete sealed candidate and returns its ID.
|
||||
func sealedFixture(t *testing.T, archive *librarysnapshot.Archive, scope, knowledgeBaseID string, createdAt time.Time) string {
|
||||
t.Helper()
|
||||
rows := func(count int) string {
|
||||
if count == 0 {
|
||||
return "[]"
|
||||
}
|
||||
items := make([]string, count)
|
||||
for i := range items {
|
||||
items[i] = fmt.Sprintf(`{"id":"00000000-0000-4000-8000-%012d"}`, i)
|
||||
}
|
||||
return "[" + strings.Join(items, ",") + "]"
|
||||
}
|
||||
parts := []struct {
|
||||
kind, name string
|
||||
count int64
|
||||
}{
|
||||
{"database", "knowledges", 4},
|
||||
{"database", "chunks", 38},
|
||||
{"database", "resources", 0},
|
||||
{"database", "resource_bindings", 0},
|
||||
{"database", "knowledge_tags", 0},
|
||||
{"database", "knowledge_tag_relations", 0},
|
||||
{"index", "chunks", 122},
|
||||
{"wiki", "wiki_pages", 31},
|
||||
{"wiki", "wiki_folders", 21},
|
||||
{"wiki", "wiki_page_issues", 0},
|
||||
{"wiki", "wiki_log_entries", 11},
|
||||
}
|
||||
manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy,
|
||||
Format: librarysnapshot.Format, Scope: scope, TenantID: 10000, KnowledgeBaseID: knowledgeBaseID,
|
||||
CreatedAt: createdAt, Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1",
|
||||
SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4",
|
||||
EmbeddingDimension: 1024, IndexMappingSHA256: strings.Repeat("b", 64)}}
|
||||
for _, part := range parts {
|
||||
stored, err := archive.Put(bytes.NewReader([]byte(rows(int(part.count)))))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored.Kind, stored.Name, stored.Count = part.kind, part.name, part.count
|
||||
manifest.Parts = append(manifest.Parts, stored)
|
||||
}
|
||||
id, err := archive.Seal(manifest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func fixtureArchive(t *testing.T) (*librarysnapshot.Archive, string) {
|
||||
t.Helper()
|
||||
root, err := os.MkdirTemp(os.TempDir(), "kglc-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(root) })
|
||||
if err = os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive, err := librarysnapshot.Open(root, 1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { archive.Close() })
|
||||
return archive, root
|
||||
}
|
||||
|
||||
const fixtureKB = "0c84a098-d3ed-4b82-a165-e6de9691d6a8"
|
||||
|
||||
// A repeated job with the same parameters must return the original candidate
|
||||
// without touching the source or stopping a writer (this function has no access
|
||||
// to either), instead of failing with a conflicting-request error.
|
||||
func TestReplayCaptureReturnsOriginalCandidate(t *testing.T) {
|
||||
archive, _ := fixtureArchive(t)
|
||||
created := time.Date(2026, 10, 28, 3, 34, 57, 0, time.UTC)
|
||||
id := sealedFixture(t, archive, "internal", fixtureKB, created)
|
||||
manifest, err := replayCapture("lib-internal-1", "internal", fixtureKB,
|
||||
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !manifest.CreatedAt.Equal(created) || manifest.Compatibility.EmbeddingModel != "text-embedding-v4" {
|
||||
t.Fatalf("replay lost the original request identity: %+v", manifest)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplayCaptureRejectsChangedParameters(t *testing.T) {
|
||||
archive, root := fixtureArchive(t)
|
||||
id := sealedFixture(t, archive, "internal", fixtureKB, time.Date(2026, 10, 28, 3, 34, 57, 0, time.UTC))
|
||||
// Different scope.
|
||||
if _, err := replayCapture("lib-internal-1", "external", fixtureKB,
|
||||
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive); err == nil {
|
||||
t.Fatal("scope conflict was accepted")
|
||||
}
|
||||
// Binding moved to another knowledge base.
|
||||
if _, err := replayCapture("lib-internal-1", "internal", "aec3dfc9-4ad3-4a39-926b-5bfa5d6a9654",
|
||||
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive); err == nil {
|
||||
t.Fatal("knowledge base binding change was accepted")
|
||||
}
|
||||
// A job that never succeeded must not be answered as success.
|
||||
if _, err := replayCapture("lib-internal-1", "internal", fixtureKB,
|
||||
libraryfreeze.Result{State: "failed"}, archive); err == nil {
|
||||
t.Fatal("failed job replayed as success")
|
||||
}
|
||||
// A sealed candidate that no longer verifies must not be reported as replay.
|
||||
if err := os.Remove(root + "/versions/" + id + ".json"); err == nil {
|
||||
if _, err := replayCapture("lib-internal-1", "internal", fixtureKB,
|
||||
libraryfreeze.Result{State: "succeeded", SnapshotID: id}, archive); err == nil {
|
||||
t.Fatal("missing sealed candidate replayed as success")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,14 @@ import (
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/libraryagent"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/versionhistory"
|
||||
@@ -24,6 +26,9 @@ import (
|
||||
"knowledge-governance/internal/workflows/testweknora"
|
||||
)
|
||||
|
||||
// libraryCaptureJobType is shared with the API which enqueues it.
|
||||
const libraryCaptureJobType = "library.capture"
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
@@ -126,6 +131,40 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
return nil, fmt.Errorf("create artifact fetch handler: %w", err)
|
||||
}
|
||||
handlers["artifact.fetch"] = artifactHandler.Handle
|
||||
if config.LibraryAgentSocket != "" {
|
||||
// 整库封存:worker 只投递请求并记录结果,真正的停机/导出/恢复发生在主机侧
|
||||
// agent(同 uid unix socket)。容器里既没有 Docker socket,也没有来源凭据。
|
||||
agentConfig := libraryagent.ClientConfig{Socket: config.LibraryAgentSocket, Timeout: 15 * time.Minute}
|
||||
handlers[libraryCaptureJobType] = func(ctx context.Context, job jobs.Job) error {
|
||||
var payload struct {
|
||||
Scope string `json:"scope"`
|
||||
CaptureJob string `json:"capture_job"`
|
||||
RequestedBy string `json:"requested_by"`
|
||||
}
|
||||
if err := json.Unmarshal(job.Payload, &payload); err != nil || (payload.Scope != "internal" && payload.Scope != "external") || payload.CaptureJob == "" {
|
||||
return fmt.Errorf("invalid library capture payload")
|
||||
}
|
||||
result, err := libraryagent.Capture(ctx, agentConfig, payload.Scope, payload.CaptureJob)
|
||||
if err != nil {
|
||||
log.Printf("library capture failed scope=%s capture_job=%s: %v", payload.Scope, payload.CaptureJob, err)
|
||||
return err
|
||||
}
|
||||
log.Printf("library capture completed scope=%s capture_job=%s snapshot=%s replay=%v requested_by=%s",
|
||||
payload.Scope, payload.CaptureJob, result.SnapshotID, result.Replay, payload.RequestedBy)
|
||||
return nil
|
||||
}
|
||||
// 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() {
|
||||
recoveryCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
if _, err := libraryagent.Recover(recoveryCtx, agentConfig); err != nil {
|
||||
log.Printf("library agent recovery check failed: %v", err)
|
||||
return
|
||||
}
|
||||
log.Printf("library agent reachable; freeze journals recovered")
|
||||
}()
|
||||
}
|
||||
if config.VersionHistoryGiteaBaseURL != "" {
|
||||
// 「版本记录」同步:匿名只读远端仓库的提交/tag,写本库快照。未配置来源就不注册,
|
||||
// 界面上的同步按钮也会显示"未接线",不会入队一个没人处理的作业。
|
||||
|
||||
@@ -49,6 +49,12 @@ services:
|
||||
VERSION_HISTORY_LINK_ORIGIN: "${VERSION_HISTORY_LINK_ORIGIN:-}"
|
||||
VERSION_HISTORY_HTTP_TIMEOUT: "${VERSION_HISTORY_HTTP_TIMEOUT:-15s}"
|
||||
VERSION_HISTORY_MAX_PAGES: "${VERSION_HISTORY_MAX_PAGES:-200}"
|
||||
# 「整库版本」页:只读已封存的整库候选产物。归档根由 `libraryctl capture`
|
||||
# 在主机上写入(私有 0700),这里只挂只读;留空 = 未接线(页面降级展示原因)。
|
||||
LIBRARY_ARCHIVE_ROOT: "${LIBRARY_ARCHIVE_ROOT:-/var/lib/knowledge-governance/library}"
|
||||
# 主机侧封存 agent 的 unix socket:api 只用它判断"能不能从页面发起",
|
||||
# worker 用它投递作业。容器里没有 Docker socket,也没有来源凭据。
|
||||
LIBRARY_AGENT_SOCKET: "${LIBRARY_AGENT_SOCKET:-/run/library-agent/agent.sock}"
|
||||
# Mount this independent master-key file read-only using the deployment overlay.
|
||||
QA_AI_MASTER_KEY_FILE: "${QA_AI_MASTER_KEY_FILE:-}"
|
||||
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
|
||||
@@ -73,6 +79,8 @@ services:
|
||||
- pgpass
|
||||
- test_weknora_api_key
|
||||
volumes:
|
||||
# 整库封存产物:只读挂载,api 只读不写(写入只发生在主机上的 libraryctl)。
|
||||
- /home/zheromiku/.local/share/knowledge-governance/library:/var/lib/knowledge-governance/library:ro
|
||||
# 与 worker 共用同一份 dws 状态:refresh token 是轮换制,绝不能在两处各留一份。
|
||||
- /home/zheromiku/.dws:/data/dws
|
||||
# dws 的文件型 keychain 必须有 $HOME/.local/share/dws-cli,故挂到 DWS_HOME 下。
|
||||
@@ -136,6 +144,9 @@ services:
|
||||
volumes:
|
||||
- ./spool:/var/lib/governance/spool:ro
|
||||
- ./spool/ingestion:/var/lib/governance/ingestion
|
||||
# 整库封存 agent 的 socket 目录(由主机侧 systemd user 服务持有)。
|
||||
# 容器只拿到"投递作业"这一条通道:Docker socket 与来源凭据都不在这里。
|
||||
- /home/zheromiku/.local/share/knowledge-governance/agent:/run/library-agent
|
||||
- "${PP_SCAN_HOST_DATA_ROOT:-/home/zheromiku/dobot-portal-sync/data}:${PP_SCAN_CONTAINER_DATA_ROOT:-/home/zheromiku/dobot-portal-sync/data}:ro"
|
||||
- /home/zheromiku/dingtalk_kb_download:/sources/dingtalk:ro
|
||||
# dws 凭据:与宿主共享同一份 state(refresh token 是轮换制,不能在两处各留一份)
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
# 整库封存(libraryctl)运维手册
|
||||
|
||||
本文只讲**测试库**的整库封存链:怎么跑、它证明了什么、它**没有**证明什么。生产发布与恢复、清理不在本文范围。
|
||||
|
||||
## 它做什么
|
||||
|
||||
`libraryctl capture -scope internal|external`:
|
||||
|
||||
1. 从**本机真实测试栈**(默认 Compose 项目 `weknora071full`)读来源配置:容器环境里的数据库/检索/对象存储参数,运行时读取,不落盘、不回显。
|
||||
2. 用**只读会话**(`default_transaction_read_only=on`)连来源 PostgreSQL;连接串只在进程内存里。
|
||||
3. 核对来源已结清:所有文档 `parse_status=completed`、无待处理操作、无死信(任一不满足就拒绝,不看其他 KB 的局部状态)。
|
||||
4. 从持久数据推出兼容契约:迁移版本、dirty、租户、Embedding 模型与维度、检索引擎、索引名、索引映射摘要(`text-embedding-v4` / 1024 维 / schema 74)。
|
||||
5. 在**维护窗口**内停住声明过的写入者(只对声明为 writer 的服务发 SIGTERM,等它真的停下),导出 PostgreSQL 十表 + Elasticsearch 正文与向量 + 对象资源,做双向覆盖与摘要核验,封存为内容寻址产物。
|
||||
6. 无论成败都恢复写入者并等到 healthy;崩溃留下的日志用 `libraryctl recover` 收尾。
|
||||
7. 打印快照 ID、分项(kind/name/数量/字节/SHA256)与兼容契约。
|
||||
|
||||
## 写入者声明(安全边界)
|
||||
|
||||
`scripts/library-capture.sh` 里逐项声明了项目内**每一个**服务:一个 writer(`app`),其余每个都写了"为什么它不会写知识"。`ProjectController` 的规则:
|
||||
|
||||
- 整个 Compose 项目被枚举(含停止的),只按声明停机;
|
||||
- 项目里出现未声明的服务 → **拒绝执行**,不会"只停已知的那几个";
|
||||
- 首次清点后固定容器 ID,容器被重建(同名新实例)→ 拒绝,避免停到一个没被声明的实例;
|
||||
- 只发 SIGTERM,没有会在恢复后才触发的 SIGKILL 定时器;
|
||||
- 启动后必须等到 healthy 才算恢复。
|
||||
|
||||
## 命令
|
||||
|
||||
```bash
|
||||
# 接线与来源探针(只读,不停服务)
|
||||
./scripts/library-capture.sh status
|
||||
# 预检:读来源 + 结清检查 + 候选校验,不写盘、不停服务
|
||||
./scripts/library-capture.sh preflight -scope internal
|
||||
# 真实封存(停 app → 导出 → 恢复 app)
|
||||
./scripts/library-capture.sh capture -scope internal
|
||||
./scripts/library-capture.sh capture -scope external
|
||||
# 已封存产物
|
||||
./scripts/library-capture.sh list
|
||||
./scripts/library-capture.sh verify -snapshot <id>
|
||||
# 崩溃后的收尾(恢复写入者)
|
||||
./scripts/library-capture.sh recover
|
||||
```
|
||||
|
||||
产物默认写到 `~/.local/share/knowledge-governance/library`(0700),日志写到 `~/.local/share/knowledge-governance/freeze`(0700)。api 容器只以只读方式挂载前者,「整库版本」页据此展示。
|
||||
|
||||
同一个作业号重跑是**幂等重放**:直接返回已封存的同一份候选(`replay=true`、`source_read=false`、`writers_stopped=false`),不读来源、不停写入者;同一作业号换了 scope 或绑定库则明确拒绝。
|
||||
|
||||
## 从页面发起封存(主机侧 agent)
|
||||
|
||||
页面点「发起对内/对外封存」只是**投递一个作业**;执行发生在这台主机上的 agent:
|
||||
|
||||
- `scripts/library-agent-install.sh` 构建并安装 `libraryagent`(systemd **user** 服务),
|
||||
监听 `~/.local/share/knowledge-governance/agent/agent.sock`,目录 0700、socket 0600,
|
||||
并额外用 `SO_PEERCRED` 要求对端与 agent 同 uid。
|
||||
- agent 自己固定 `libraryctl` 的路径、归档与日志根、Compose 项目与写入者声明;
|
||||
请求只能选 `scope`(internal/external)和作业号,**不能**指定路径、项目、容器或命令。
|
||||
- 只有 worker 通过挂载的 socket 目录投递作业(`LIBRARY_AGENT_SOCKET`)。容器里
|
||||
**没有** Docker socket,**没有**来源凭据:停写入者、读来源、恢复都在主机进程里完成。
|
||||
- worker 启动时会先调一次 `recover`,把上次崩溃留下的停机窗口收尾;
|
||||
失败会记日志而不是假装就绪。
|
||||
- 同一 `scope + 作业号` 重复投递时,agent 走幂等重放,不会第二次停源。
|
||||
|
||||
安全边界要说清:socket 目录对 worker 可写,因此被攻破的 worker 可以让 agent 执行
|
||||
"封存 internal/external"这一类动作(这正是页面能力),但拿不到 Docker API、
|
||||
拿不到来源凭据,也不能重定向到别的项目或路径。
|
||||
|
||||
## 2026-10-28 实测(本机测试栈)
|
||||
|
||||
| 项 | 对内 | 对外 |
|
||||
| --- | --- | --- |
|
||||
| 快照 | `f992d64ea45bf737a0721a465b5aef2b150ef7757157eb84f3aaf8b6972d98f9` | `01343b0b310b3977c2fdda05f5b8a6272148c4f7bfa124a6c5944123cf0c51c3` |
|
||||
| 文档 / 分块 / 索引 | 4 / 38 / 122 | 0 / 0 / 0 |
|
||||
| 资源 / Wiki 页 | 21 / 31 | 0 / 1 |
|
||||
| 分项数 / 逻辑字节 | 32 / 55,309,044 | 13 / 1,121 |
|
||||
| 策略 | artifact-acceptance-v1 | artifact-acceptance-v1 |
|
||||
|
||||
两次封存都记录了 `stop_verified=true`、`restored=true`,`WKNFull-app` 恢复后 healthy;来源未做任何写操作。
|
||||
|
||||
## 它证明了什么 / 没有证明什么
|
||||
|
||||
已证明(A04 数据完整性口径):这一份整库内容在**写入者停住**之后被完整导出,PostgreSQL 与 Elasticsearch 双向覆盖、生成问题、资源与摘要逐项核验通过,产物可寻址、可复读、可校验。这正是封版所需的完整性口径。
|
||||
|
||||
用户已确认取消 A06:**不要求**内容、问答、引用/图片效果与性能测试及其报告,也不作为封版/生产发布门槛。因此这里不再把"没有做效果测试"列为缺口。
|
||||
|
||||
仍然不成立(不许把完整性通过说成这些):
|
||||
|
||||
- **跨 PG / ES / 资源的一致切点**只在维护窗口内取得;写入者组完整性有检查,但没有独立的切点证据,不能当成已验收的一致性证明;
|
||||
- **Wiki 删除贡献的语义重算**没有做;Wiki 队列空不等于语义正确;
|
||||
- 对外库当前是空的(0 文档 1 Wiki 页),这份快照只说明"它当时确实是空的";
|
||||
- 生产独立预备份、恢复演练、双闸授权、整库同步协调与失败续作都没有接线,本文不涉及;
|
||||
- 从页面发起封存、持久作业互斥、启动恢复还没有接线(封存目前只能在目标主机执行命令);
|
||||
- 上游父子分块漏正文索引的风险仍在:本次通过是因为库里现有数据已补齐,**以后再重解析**仍可能漏项,届时封存会因覆盖核验失败而阻断(这是设计如此)。
|
||||
@@ -6,6 +6,15 @@
|
||||
|
||||
现有文档包发布与执行级补偿只能作为复用基础,不能作为本清单完成证据。静态样图不作为产品运行证据。组织绩效与周报外发不在本次范围。
|
||||
|
||||
## 已确认:验收口径 A(原始产物)
|
||||
|
||||
用户选择不修改 WeKnora,以冻结的完整知识版本绑定内容、问答与性能验收。源端索引可能含未持久化的生成上下文,不再要求从 PostgreSQL 正文反推每条正文索引的生成过程。
|
||||
|
||||
- 原样归档索引内容与向量,不重新生成;继续校验库/文档/分块身份关联、覆盖、数量、资源及摘要。已持久化生成问题仍按 ID 和原文精确校验。
|
||||
- 新候选清单记录 `validation_policy=artifact-acceptance-v1`,该字段纳入内容寻址身份;历史无该字段的快照不冒称执行了新口径。
|
||||
- 候选归档成功不证明冻结、内容质量、问答正确性或性能通过。测试验收必须绑定具体快照身份;旧快照验收不得放行新快照。生产发布仍须独立授权。
|
||||
- 本次只完成候选产物保留和口径记录,真实冻结业务接线与持久化验收绑定尚未完成,不能因此放行生产。
|
||||
|
||||
## 已确认:封存隔离方案 A
|
||||
|
||||
用户选择封存期间自动暂停测试 WeKnora 服务,封存后恢复,不修改 WeKnora 源码。测试问答在暂停期间暂不可用,停用时长须实测;不暂停生产服务,也不因此取得生产同步、恢复或真实清理授权。
|
||||
@@ -85,6 +94,26 @@
|
||||
4. 生产预备份、独立恢复演练、持久化协调作业、授权 API、真实进度、发布页面与完整存储治理仍未交付;以上验收项目保持待验证。
|
||||
5. 基础模块已随 `0.1.96 / 9105f8316cc870a62b5ddacd1496f0cb0f798d87` 提交、推送并部署到本地测试治理平台;运行 API/worker 的二进制摘要已读回校验。该部署不等于业务功能接线或完整验收通过;未执行生产同步、恢复或真实业务清理。完整验收仍受本节及下述缺失接线阻塞。
|
||||
|
||||
## 真实测试源只读诊断(未通过)
|
||||
|
||||
`TestLibrarySourceReadOnlyDiagnostic` 仅在明确 opt-in 下运行,数据库连接强制只读;只调用 ES 查询/PIT 和 OSS 对象读取,不执行生产操作、源数据清理或服务暂停。测试凭据仅通过子进程环境注入,不记录配置值。
|
||||
|
||||
本次实际执行退出码 1:对内库 125 条索引记录中有 13 条关联到未被完整文档集合纳入的分块;进一步只读查询定位为 4 个未删除分块(3 个 text、1 个 summary)缺少同租户的父文档,不是临时上下文内容比较失败。现有身份校验保持拒绝,没有忽略这些记录或据此放行。独立 OSS 读取校验覆盖 21 个资源、53,490,166 字节。对外库读到 0 文档、0 分块、1 个 Wiki 页面,候选结构归档可读回,但未冻结且模型兼容身份为明确诊断占位,不能当作版本验收通过。
|
||||
|
||||
证据:`backups/library-source-readonly-20261028/`。真实源诊断失败与默认 CI 的环境跳过分别记录;此次发现不授权清理这批分块或索引,之前仅限死信 ID 1 的授权不扩展使用。
|
||||
|
||||
## 联合隔离捕获验收
|
||||
|
||||
新增 `TestLibraryCaptureIsolatedStack`,在同一次 `CaptureLibrary` 调用中连接真实隔离 PostgreSQL、随机 Elasticsearch 索引、真实 Docker 暂停/恢复控制器和本地资源文件读取器。写入服务使用无网络、无宿主挂载的 busybox 夹具,不是实际 WeKnora;资源读取不是实际 OSS/S3 验收。
|
||||
|
||||
- 非空文档、分块、资源、Wiki 正文及字符串状态归档后读回;检查无跨租户记录或会话数据泄漏。
|
||||
- 删除真实夹具索引记录后,新捕获必须失败,原运行容器仍恢复健康。
|
||||
- 删除源资源文件、修改源 PostgreSQL、删除源 ES 文档后,成功作业重放仍返回原快照,不再调用源端就绪检查或资源读取;归档重新加载通过。
|
||||
- 反向自检使用 Go overlay 仅关闭 legacy 索引覆盖检查:同一联合用例退出码 1,明确报 `missing real index accepted`;未修改的实现复跑退出码 0。
|
||||
- `make verify` 与三包 race 回归退出码 0;新用例在默认 CI 中显式声明环境跳过,本地单独实际执行。夹具索引和容器删除后读回不存在,随机隔离数据库已删除。
|
||||
|
||||
证据:`backups/library-stack-acceptance-20261028/`。该联合用例补充捕获协调证据,不证明真实源全部写入者受控、Wiki 撤销语义、内容/问答/性能验收绑定或生产同步恢复已经完成。
|
||||
|
||||
## 方案 A:暂停与恢复原语的实测证据
|
||||
|
||||
新增 `internal/libraryfreeze/`,包含持久化作业日志、源服务组互斥、暂停前原运行状态、不可变容器 ID、恢复读回,以及本地 Unix socket Docker 控制器。Docker 控制器只接受对应 source 且 `environment=test`、`freeze-role=writer` 的容器;不按模糊名称选取,不控制数据库/索引存储,不使用远程默认 Docker context。运行容器必须有健康检查。
|
||||
@@ -101,4 +130,4 @@
|
||||
|
||||
已新增 `internal/releaseadapter/v071/library_capture.go`,在源服务组互斥下串起预检、暂停、停后复检、PG/ES 导出、独立归档和恢复。协调测试使用 PG/服务控制夹具与 HTTP 搜索夹具,覆盖预检忙时零停止、暂停前后新增任务阻断、搜索失败恢复、旧作业重放不重新暂停、跨 scope 复用拒绝、归档丢失不返回成功;不把这组夹具当成实际业务知识库全链路验收。最终竞态回归、隔离 Docker 重跑与 `make verify` 均退出码 0,最终日志为同目录 `kg-freeze-docker-final.log`、`kg-library-freeze-final-verify.log`。
|
||||
|
||||
**仍缺少的接线**:真实测试部署的全部写入者枚举及标签/健康契约、全源任务就绪检查的实际提供方、worker 调用捕获协调函数、启动恢复入口和持续恢复调度。单独的本地 Docker 控制器不能控制远端测试主机;远端场景需在测试主机运行受限执行器,不能向浏览器或普通 API 暴露 Docker socket。上述测试不能证明这些接线已完成,尚未暂停实际测试 WeKnora。
|
||||
**仍缺少的接线**:真实测试部署的全部写入者枚举及标签/健康契约、部署侧入口及后台作业就绪检查的实际提供方、worker 调用捕获协调函数、启动恢复入口和持续恢复调度。`CaptureLibrary` 已强制在暂停前后检查整个源数据库的解析、pending 与 dead-letter 状态(跨库、跨租户及未知/删除范围);此检查不能代替入口隔离与 Wiki 语义验收。单独的本地 Docker 控制器不能控制远端测试主机;远端场景需在测试主机运行受限执行器,不能向浏览器或普通 API 暴露 Docker socket。上述测试不能证明这些接线已完成,尚未暂停实际测试 WeKnora。
|
||||
|
||||
@@ -69,6 +69,12 @@ type Config struct {
|
||||
VersionHistoryAllowedOrigins []string
|
||||
// VersionHistoryLinkOrigin 是**页面链接**用的 origin(给内网外的浏览器点开),
|
||||
// 留空即与抓取 origin 相同。只用于拼展示链接,不参与任何请求。
|
||||
// LibraryArchiveRoot 是整库封存产物的只读归档根(主机私有 0700 目录的只读挂载)。
|
||||
// 留空即"未接线":页面只显示原因,不显示空表冒充没有快照。
|
||||
LibraryArchiveRoot string
|
||||
// LibraryAgentSocket 是主机侧封存 agent 的 unix socket(只由 worker 连接)。
|
||||
// 留空即"未接线":页面不显示可用的封存入口,接口返回原因而不是假装已排队。
|
||||
LibraryAgentSocket string
|
||||
VersionHistoryLinkOrigin string
|
||||
VersionHistoryHTTPTimeout time.Duration
|
||||
VersionHistoryMaxPages int
|
||||
@@ -116,6 +122,8 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
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")),
|
||||
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
|
||||
VersionHistoryHTTPTimeout: 15 * time.Second,
|
||||
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
|
||||
@@ -226,6 +234,12 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if config.LibraryArchiveRoot != "" && !filepath.IsAbs(config.LibraryArchiveRoot) {
|
||||
return Config{}, errors.New("LIBRARY_ARCHIVE_ROOT 必须是绝对路径(归档根按只读目录挂载)")
|
||||
}
|
||||
if config.LibraryAgentSocket != "" && !filepath.IsAbs(config.LibraryAgentSocket) {
|
||||
return Config{}, errors.New("LIBRARY_AGENT_SOCKET 必须是绝对路径(unix socket 由主机侧 agent 持有)")
|
||||
}
|
||||
if config.TestWeKnoraHTTPTimeout, err = durationOrDefault(getenv("TEST_WEKNORA_HTTP_TIMEOUT"), config.TestWeKnoraHTTPTimeout); err != nil {
|
||||
return Config{}, fmt.Errorf("TEST_WEKNORA_HTTP_TIMEOUT: %w", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/jobs"
|
||||
)
|
||||
|
||||
// 页面发起封存:只投递一个作业,真正的停机/导出/恢复发生在主机侧 agent。
|
||||
// 这里没有任何 Docker 访问,也没有来源凭据 —— 调用方只能选择范围与作业号。
|
||||
const libraryCaptureJobType = "library.capture"
|
||||
|
||||
var libraryCaptureJobPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
|
||||
|
||||
type libraryCaptureRequest struct {
|
||||
Scope string `json:"scope"`
|
||||
Job string `json:"job"`
|
||||
}
|
||||
|
||||
func libraryCaptureEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if config.LibraryAgentSocket == "" {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
|
||||
"code": "library_capture_unwired",
|
||||
"reason": "未接线:主机侧封存 agent 没有挂载,页面无法发起封存",
|
||||
})
|
||||
return
|
||||
}
|
||||
var request libraryCaptureRequest
|
||||
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"})
|
||||
return
|
||||
}
|
||||
if request.Scope != "internal" && request.Scope != "external" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "scope must be internal or external"})
|
||||
return
|
||||
}
|
||||
// The job id is the idempotency key handed to the agent: repeating the same
|
||||
// scope+job returns the already sealed version instead of sealing twice.
|
||||
captureJob := strings.TrimSpace(request.Job)
|
||||
if captureJob == "" {
|
||||
captureJob = "lib-" + request.Scope + "-" + time.Now().UTC().Format("20060102T150405")
|
||||
}
|
||||
if !libraryCaptureJobPattern.MatchString(captureJob) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid job id"})
|
||||
return
|
||||
}
|
||||
requestedBy := ""
|
||||
if identity, ok := sessionFrom(r.Context()); ok {
|
||||
requestedBy = identity.Username
|
||||
}
|
||||
payload, err := json.Marshal(map[string]string{
|
||||
"scope": request.Scope, "capture_job": captureJob, "requested_by": requestedBy,
|
||||
})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build capture job"})
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
job, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
|
||||
ID: fmt.Sprintf("library-capture-%s-%d", request.Scope, now.UnixNano()),
|
||||
Type: libraryCaptureJobType,
|
||||
Payload: payload,
|
||||
AvailableAt: now,
|
||||
MaxAttempts: 2,
|
||||
IdempotencyKey: "library.capture:" + captureJob,
|
||||
}, now)
|
||||
if err != nil || job == nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue capture job"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{
|
||||
"job_id": job.ID, "capture_job": captureJob, "scope": request.Scope, "state": job.State,
|
||||
})
|
||||
}
|
||||
|
||||
// libraryCaptureJobs lists recent capture jobs so the page can show real state
|
||||
// instead of an optimistic spinner. It reads the queue, not the archive.
|
||||
func libraryCaptureJobs(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
queue, err := config.Store.List(r.Context(), 200)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read capture jobs"})
|
||||
return
|
||||
}
|
||||
views := make([]map[string]any, 0, 20)
|
||||
for _, job := range queue {
|
||||
if job.Type != libraryCaptureJobType || len(views) >= 20 {
|
||||
continue
|
||||
}
|
||||
var payload struct {
|
||||
Scope string `json:"scope"`
|
||||
CaptureJob string `json:"capture_job"`
|
||||
RequestedBy string `json:"requested_by"`
|
||||
}
|
||||
_ = json.Unmarshal(job.Payload, &payload)
|
||||
views = append(views, map[string]any{"job_id": job.ID, "capture_job": payload.CaptureJob,
|
||||
"scope": payload.Scope, "state": job.State, "attempt": job.Attempt,
|
||||
"last_error": job.LastError, "requested_by": payload.RequestedBy,
|
||||
"created_at": job.CreatedAt, "updated_at": job.UpdatedAt})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"available": true, "jobs": views})
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/jobs"
|
||||
)
|
||||
|
||||
func captureRequest(body string) *http.Request {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/captures", strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
return request
|
||||
}
|
||||
|
||||
// An unwired agent must refuse clearly instead of queueing a job nobody can run.
|
||||
func TestLibraryCaptureRefusedWhenAgentUnwired(t *testing.T) {
|
||||
store := &fakeJobStore{}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"internal"}`), Config{Store: store})
|
||||
if recorder.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["code"] != "library_capture_unwired" || body["reason"] == "" {
|
||||
t.Fatalf("unexpected body %v", body)
|
||||
}
|
||||
if store.enqueued.Type != "" {
|
||||
t.Fatal("unwired agent still enqueued a job")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureEnqueuesFixedJobShape(t *testing.T) {
|
||||
store := &fakeJobStore{enqueueEchoRequestedID: true}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryCaptureEnqueue(recorder, captureRequest(`{"scope":"external","job":"lib-external-review"}`),
|
||||
Config{Store: store, LibraryAgentSocket: "/run/library-agent/agent.sock"})
|
||||
if recorder.Code != http.StatusAccepted {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
enqueued := store.enqueued
|
||||
if enqueued.Type != libraryCaptureJobType {
|
||||
t.Fatalf("job type %q", enqueued.Type)
|
||||
}
|
||||
if enqueued.IdempotencyKey != "library.capture:lib-external-review" {
|
||||
t.Fatalf("idempotency key %q", enqueued.IdempotencyKey)
|
||||
}
|
||||
var payload map[string]string
|
||||
if err := json.Unmarshal(enqueued.Payload, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload["scope"] != "external" || payload["capture_job"] != "lib-external-review" {
|
||||
t.Fatalf("payload %v", payload)
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["capture_job"] != "lib-external-review" || body["scope"] != "external" {
|
||||
t.Fatalf("response %v", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureRejectsInvalidRequest(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"scope":"production"}`,
|
||||
`{"scope":"internal","job":"bad job; rm -rf /"}`,
|
||||
`not json`,
|
||||
} {
|
||||
store := &fakeJobStore{}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryCaptureEnqueue(recorder, captureRequest(body), Config{Store: store, LibraryAgentSocket: "/tmp/agent.sock"})
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("body %q status=%d", body, recorder.Code)
|
||||
}
|
||||
if store.enqueued.Type != "" {
|
||||
t.Fatalf("invalid request %q still enqueued", body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureJobsListsOnlyCaptureJobs(t *testing.T) {
|
||||
store := &fakeJobStore{listResult: []jobs.Job{
|
||||
{ID: "a", Type: libraryCaptureJobType, State: "completed",
|
||||
Payload: json.RawMessage(`{"scope":"internal","capture_job":"lib-internal-1","requested_by":"yaozhanghao"}`),
|
||||
CreatedAt: time.Date(2026, 10, 28, 3, 0, 0, 0, time.UTC)},
|
||||
{ID: "b", Type: "artifact.fetch", State: "completed"},
|
||||
}}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryCaptureJobs(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/library/captures", nil), Config{Store: store})
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d", recorder.Code)
|
||||
}
|
||||
var body struct {
|
||||
Available bool `json:"available"`
|
||||
Jobs []map[string]any `json:"jobs"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !body.Available || len(body.Jobs) != 1 || body.Jobs[0]["capture_job"] != "lib-internal-1" {
|
||||
t.Fatalf("unexpected body %+v", body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// 「整库版本」只读视图:把已经封存的候选产物(artifact-acceptance-v1)如实列出来。
|
||||
//
|
||||
// 边界(刻意不做的事):
|
||||
// - 不触发封存、不停/起写入者:封存需要维护窗口与来源凭据,只能由运维命令
|
||||
// scripts/library-capture.sh 在目标主机执行;
|
||||
// - 不把完整性当发布:候选证明"这一份内容被完整、可核验地封存了"(A04 口径),
|
||||
// 而授权与生产同步是另外的、需要独立授权的步骤(A06 效果测试已由用户取消);
|
||||
// - 归档根没接线时返回可用性=false 与原因,不返回空表冒充"没有快照"。
|
||||
type librarySnapshotPart struct {
|
||||
Kind string `json:"kind"`
|
||||
Name string `json:"name"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Count int64 `json:"count"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
type librarySnapshotList struct {
|
||||
Available bool `json:"available"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
ArchiveRoot string `json:"archive_root,omitempty"`
|
||||
Snapshots []librarySnapshotView `json:"snapshots"`
|
||||
// 归档级口径:ContentBytes 是**跨版本去重后、被版本引用的内容字节**。
|
||||
// 它不是磁盘占用(清单、未引用 blob、块对齐与元数据都不在里面),
|
||||
// 更不是可回收空间——清理需要保留策略、依赖保护与在线作业引用。
|
||||
Versions int `json:"versions"`
|
||||
ContentBytes int64 `json:"content_bytes"`
|
||||
BlobFileBytes int64 `json:"blob_file_bytes"`
|
||||
BlobAllocatedBytes int64 `json:"blob_allocated_bytes"`
|
||||
UnreferencedBlobs int `json:"unreferenced_blobs"`
|
||||
UnreferencedBytes int64 `json:"unreferenced_bytes"`
|
||||
ManifestFileBytes int64 `json:"manifest_file_bytes"`
|
||||
ManifestAllocatedBytes int64 `json:"manifest_allocated_bytes"`
|
||||
// 页面必须能说清"封存由谁执行";能不能从这里发起,取决于主机侧 agent 是否接线。
|
||||
CaptureNote string `json:"capture_note"`
|
||||
CaptureAvailable bool `json:"capture_available"`
|
||||
CaptureReason string `json:"capture_reason,omitempty"`
|
||||
}
|
||||
|
||||
const libraryCaptureNote = "封存由运维命令 scripts/library-capture.sh capture -scope internal|external 在目标主机执行(停写入者→导出→恢复)。页面只读展示已封存的完整版本:它通过了数据完整性检查(身份、双向正文覆盖、生成问题、资源与摘要),这已满足封版所需的完整性口径;授权与生产同步仍是独立步骤。"
|
||||
|
||||
func librarySnapshotsList(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
view, err := readLibrarySnapshots(config.LibraryArchiveRoot)
|
||||
view.CaptureAvailable = config.LibraryAgentSocket != ""
|
||||
if !view.CaptureAvailable {
|
||||
view.CaptureReason = "未接线:主机侧封存 agent 没有挂载,页面只能查看已封存版本"
|
||||
}
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, librarySnapshotList{Available: false,
|
||||
Reason: "归档不可读:" + err.Error(), Snapshots: []librarySnapshotView{}, CaptureNote: libraryCaptureNote})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, view)
|
||||
}
|
||||
|
||||
func librarySnapshotDetail(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
id := strings.TrimSpace(r.PathValue("id"))
|
||||
if id == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "snapshot id required"})
|
||||
return
|
||||
}
|
||||
if config.LibraryArchiveRoot == "" {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"available": false,
|
||||
"reason": "未接线:LIBRARY_ARCHIVE_ROOT 未配置,本平台没有整库归档可读"})
|
||||
return
|
||||
}
|
||||
archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, "reason": "归档不可读"})
|
||||
return
|
||||
}
|
||||
defer archive.Close()
|
||||
manifest, err := archive.Load(id)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusNotFound, map[string]any{"available": false, "reason": "快照不存在或校验失败"})
|
||||
return
|
||||
}
|
||||
usage, err := archive.Usage()
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, "reason": "归档用量不可读"})
|
||||
return
|
||||
}
|
||||
view, ok := librarySnapshotViewOf(id, manifest, usage)
|
||||
if !ok {
|
||||
view = librarySnapshotViewOfNoUsage(id, manifest)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"available": true, "snapshot": view, "capture_note": libraryCaptureNote})
|
||||
}
|
||||
|
||||
func readLibrarySnapshots(root string) (librarySnapshotList, error) {
|
||||
view := librarySnapshotList{Snapshots: []librarySnapshotView{}, CaptureNote: libraryCaptureNote}
|
||||
_ = root
|
||||
if root == "" {
|
||||
view.Reason = "未接线:LIBRARY_ARCHIVE_ROOT 未配置,本平台没有整库归档可读"
|
||||
return view, nil
|
||||
}
|
||||
view.ArchiveRoot = root
|
||||
archive, err := librarysnapshot.Open(root, 256*1024*1024)
|
||||
if err != nil {
|
||||
return view, errors.New("归档根不可用")
|
||||
}
|
||||
defer archive.Close()
|
||||
usage, err := archive.Usage()
|
||||
if err != nil {
|
||||
return view, errors.New("归档用量不可读")
|
||||
}
|
||||
// Per-version UniqueBytes deduplicates only inside one version, so summing it
|
||||
// over versions over-reports shared blobs. The archive-wide accounting below
|
||||
// deduplicates across versions and keeps filesystem facts separate.
|
||||
total, err := archive.ContentUsage()
|
||||
if err != nil {
|
||||
return view, errors.New("归档用量不可读")
|
||||
}
|
||||
view.Versions = total.Versions
|
||||
view.ContentBytes = total.ContentBytes
|
||||
view.BlobFileBytes = total.BlobFileBytes
|
||||
view.BlobAllocatedBytes = total.BlobAllocatedBytes
|
||||
view.UnreferencedBlobs = total.UnreferencedBlobs
|
||||
view.UnreferencedBytes = total.UnreferencedBytes
|
||||
view.ManifestFileBytes = total.ManifestFileBytes
|
||||
view.ManifestAllocatedBytes = total.ManifestAllocatedBytes
|
||||
byID := map[string]librarysnapshot.Usage{}
|
||||
for _, item := range usage {
|
||||
byID[item.VersionID] = item
|
||||
}
|
||||
for id, item := range byID {
|
||||
manifest, loadErr := archive.Load(id)
|
||||
if loadErr != nil {
|
||||
return view, errors.New("归档快照校验失败")
|
||||
}
|
||||
snapshot, ok := librarySnapshotViewOf(id, manifest, []librarysnapshot.Usage{item})
|
||||
if !ok {
|
||||
snapshot = librarySnapshotViewOfNoUsage(id, manifest)
|
||||
}
|
||||
view.Snapshots = append(view.Snapshots, snapshot)
|
||||
}
|
||||
sort.Slice(view.Snapshots, func(i, j int) bool {
|
||||
if view.Snapshots[i].CreatedAt.Equal(view.Snapshots[j].CreatedAt) {
|
||||
return view.Snapshots[i].SnapshotID > view.Snapshots[j].SnapshotID
|
||||
}
|
||||
return view.Snapshots[i].CreatedAt.After(view.Snapshots[j].CreatedAt)
|
||||
})
|
||||
view.Available = true
|
||||
return view, nil
|
||||
}
|
||||
|
||||
func librarySnapshotViewOf(id string, manifest librarysnapshot.Manifest, usage []librarysnapshot.Usage) (librarySnapshotView, bool) {
|
||||
snapshot := librarySnapshotViewOfNoUsage(id, manifest)
|
||||
for _, item := range usage {
|
||||
if item.VersionID == id {
|
||||
snapshot.LogicalBytes = item.LogicalBytes
|
||||
snapshot.UniqueBytes = item.UniqueBytes
|
||||
snapshot.SharedBytes = item.SharedBytes
|
||||
return snapshot, true
|
||||
}
|
||||
}
|
||||
return snapshot, false
|
||||
}
|
||||
|
||||
func librarySnapshotViewOfNoUsage(id string, manifest librarysnapshot.Manifest) librarySnapshotView {
|
||||
snapshot := librarySnapshotView{SnapshotID: id, Scope: manifest.Scope, KnowledgeBaseID: manifest.KnowledgeBaseID,
|
||||
TenantID: manifest.TenantID, CreatedAt: manifest.CreatedAt, ValidationPolicy: manifest.ValidationPolicy,
|
||||
Format: manifest.Format, Compatibility: manifest.Compatibility, Parts: make([]librarySnapshotPart, 0, len(manifest.Parts)),
|
||||
Totals: map[string]int64{}}
|
||||
for _, part := range manifest.Parts {
|
||||
snapshot.Parts = append(snapshot.Parts, librarySnapshotPart{Kind: part.Kind, Name: part.Name,
|
||||
SHA256: part.SHA256, Count: part.Count, Bytes: part.Bytes})
|
||||
snapshot.LogicalBytes += part.Bytes
|
||||
// 汇总按"数量字段"给出人看得懂的四个数字:文档/分块/索引/资源/Wiki 页。
|
||||
switch part.Name {
|
||||
case "knowledges":
|
||||
snapshot.Totals["documents"] = part.Count
|
||||
case "chunks":
|
||||
if part.Kind == "database" {
|
||||
snapshot.Totals["chunks"] = part.Count
|
||||
} else {
|
||||
snapshot.Totals["index_documents"] = part.Count
|
||||
}
|
||||
case "resources":
|
||||
snapshot.Totals["resources"] = part.Count
|
||||
case "wiki_pages":
|
||||
snapshot.Totals["wiki_pages"] = part.Count
|
||||
case "wiki_folders":
|
||||
snapshot.Totals["wiki_folders"] = part.Count
|
||||
}
|
||||
}
|
||||
sort.Slice(snapshot.Parts, func(i, j int) bool {
|
||||
if snapshot.Parts[i].Kind == snapshot.Parts[j].Kind {
|
||||
return snapshot.Parts[i].Name < snapshot.Parts[j].Name
|
||||
}
|
||||
return snapshot.Parts[i].Kind < snapshot.Parts[j].Kind
|
||||
})
|
||||
return snapshot
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// The 整库版本 page reads a sealed archive through this exact function. A
|
||||
// synthetic archive keeps the assertion about what the page shows independent of
|
||||
// whether a real capture has run on this host.
|
||||
func TestReadLibrarySnapshotsReportsSealedTotals(t *testing.T) {
|
||||
root, err := os.MkdirTemp(os.TempDir(), "kglib-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(root)
|
||||
if err = os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive, err := librarysnapshot.Open(root, 1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The archive re-derives row counts from the stored bytes, so the bodies must
|
||||
// carry exactly the declared number of rows.
|
||||
rows := func(count int) string {
|
||||
if count == 0 {
|
||||
return "[]"
|
||||
}
|
||||
items := make([]string, count)
|
||||
for i := range items {
|
||||
items[i] = fmt.Sprintf(`{"id":"00000000-0000-4000-8000-%012d"}`, i)
|
||||
}
|
||||
return "[" + strings.Join(items, ",") + "]"
|
||||
}
|
||||
parts := []struct {
|
||||
kind, name string
|
||||
count int64
|
||||
body string
|
||||
}{
|
||||
{"database", "knowledges", 4, rows(4)},
|
||||
{"database", "chunks", 38, rows(38)},
|
||||
{"database", "resources", 21, rows(21)},
|
||||
{"database", "resource_bindings", 4, rows(4)},
|
||||
{"database", "knowledge_tags", 0, rows(0)},
|
||||
{"database", "knowledge_tag_relations", 0, rows(0)},
|
||||
{"index", "chunks", 122, rows(122)},
|
||||
{"wiki", "wiki_pages", 31, rows(31)},
|
||||
{"wiki", "wiki_folders", 21, rows(21)},
|
||||
{"wiki", "wiki_page_issues", 0, rows(0)},
|
||||
{"wiki", "wiki_log_entries", 11, rows(11)},
|
||||
}
|
||||
// Every resource row must have its own archived object: the archive refuses a
|
||||
// snapshot whose resource dependencies are incomplete.
|
||||
for i := 0; i < 21; i++ {
|
||||
parts = append(parts, struct {
|
||||
kind, name string
|
||||
count int64
|
||||
body string
|
||||
}{"resource", fmt.Sprintf("00000000-0000-4000-8000-%012d", i), 1, fmt.Sprintf("object-%d", i)})
|
||||
}
|
||||
manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy,
|
||||
Format: librarysnapshot.Format, Scope: "internal", TenantID: 10000,
|
||||
KnowledgeBaseID: "0c84a098-d3ed-4b82-a165-e6de9691d6a8", CreatedAt: time.Now().UTC(),
|
||||
Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74,
|
||||
RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", EmbeddingDimension: 1024,
|
||||
IndexMappingSHA256: "137cde2965f3b56521f5fb722b4e0617f46d0e509e571b217fe01e090d5e4d01"}}
|
||||
for _, part := range parts {
|
||||
stored, err := archive.Put(bytes.NewReader([]byte(part.body)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored.Kind, stored.Name, stored.Count = part.kind, part.name, part.count
|
||||
manifest.Parts = append(manifest.Parts, stored)
|
||||
}
|
||||
snapshotID, err := archive.Seal(manifest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = archive.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
list, err := readLibrarySnapshots(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !list.Available || len(list.Snapshots) != 1 || list.Snapshots[0].SnapshotID != snapshotID {
|
||||
t.Fatalf("unexpected list %+v", list)
|
||||
}
|
||||
snapshot := list.Snapshots[0]
|
||||
want := map[string]int64{"documents": 4, "chunks": 38, "index_documents": 122, "resources": 21, "wiki_pages": 31}
|
||||
for key, value := range want {
|
||||
if snapshot.Totals[key] != value {
|
||||
t.Fatalf("total %s = %d, want %d", key, snapshot.Totals[key], value)
|
||||
}
|
||||
}
|
||||
// The archive-wide content figure deduplicates blobs across versions, so it
|
||||
// can be smaller than a version's logical sum but never larger.
|
||||
if snapshot.LogicalBytes <= 0 || list.ContentBytes <= 0 || list.ContentBytes > snapshot.LogicalBytes {
|
||||
t.Fatalf("bytes not reported: logical=%d content=%d", snapshot.LogicalBytes, list.ContentBytes)
|
||||
}
|
||||
if list.BlobAllocatedBytes < list.BlobFileBytes || list.ManifestFileBytes <= 0 {
|
||||
t.Fatalf("filesystem facts not separated: %+v", list)
|
||||
}
|
||||
if snapshot.Compatibility.EmbeddingDimension != 1024 || snapshot.ValidationPolicy != librarysnapshot.ArtifactAcceptancePolicy {
|
||||
t.Fatalf("contract not reported: %+v", snapshot)
|
||||
}
|
||||
if list.CaptureNote == "" {
|
||||
t.Fatal("page must explain who runs the capture")
|
||||
}
|
||||
if _, err = os.Stat(filepath.Join(root, "versions", snapshotID+".json")); err != nil {
|
||||
t.Fatalf("sealed manifest missing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadLibrarySnapshotsWithoutArchiveIsExplicitlyUnwired(t *testing.T) {
|
||||
list, err := readLibrarySnapshots("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if list.Available || list.Reason == "" || len(list.Snapshots) != 0 {
|
||||
t.Fatalf("empty configuration must be reported as unwired, got %+v", list)
|
||||
}
|
||||
}
|
||||
@@ -127,8 +127,12 @@ type Config struct {
|
||||
// 所在主机上读回/下发计划并触发一次整库备份(未接线时页面降级展示)。
|
||||
// VersionHistory 是「版本记录」页的只读查询面;VersionHistoryRepo 是固定的仓库标识
|
||||
// (owner/name)。两者都给才接线,否则页面降级为"未接线"(不报 500)。
|
||||
VersionHistory VersionHistoryStore
|
||||
VersionHistoryRepo string
|
||||
VersionHistory VersionHistoryStore
|
||||
VersionHistoryRepo string
|
||||
// LibraryArchiveRoot 是整库封存产物的只读归档根;留空即未接线(页面降级)。
|
||||
LibraryArchiveRoot string
|
||||
// LibraryAgentSocket 是主机侧封存 agent 的 unix socket;留空即页面不能发起封存。
|
||||
LibraryAgentSocket string
|
||||
BackupSchedule BackupScheduleStore
|
||||
BackupHost BackupHost
|
||||
BackupRuns *BackupRunTracker
|
||||
@@ -387,6 +391,20 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("GET /api/v1/build-info", func(w http.ResponseWriter, r *http.Request) {
|
||||
buildInfo(w, r)
|
||||
})
|
||||
// 整库版本(只读):列出已封存的整库候选产物与其分项数量/字节/摘要。
|
||||
mux.HandleFunc("GET /api/v1/library/snapshots", func(w http.ResponseWriter, r *http.Request) {
|
||||
librarySnapshotsList(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/library/snapshots/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
librarySnapshotDetail(w, r, config)
|
||||
})
|
||||
// 页面发起封存:只投递作业(主机侧 agent 执行),并回读作业真实状态。
|
||||
mux.HandleFunc("POST /api/v1/library/captures", func(w http.ResponseWriter, r *http.Request) {
|
||||
libraryCaptureEnqueue(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/library/captures", func(w http.ResponseWriter, r *http.Request) {
|
||||
libraryCaptureJobs(w, r, config)
|
||||
})
|
||||
// 全部 main 提交时间线(读本库缓存,不直接打 Gitea)
|
||||
mux.HandleFunc("GET /api/v1/version-history", func(w http.ResponseWriter, r *http.Request) {
|
||||
versionHistoryList(w, r, config)
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
// Package libraryagent is the least-privilege execution boundary for
|
||||
// whole-library capture on the target host.
|
||||
//
|
||||
// Why it exists: capturing a library has to stop the source writer for a few
|
||||
// seconds and read source credentials. Handing the governance containers the
|
||||
// Docker socket (a full write API) or the source credentials would be a much
|
||||
// larger privilege than that operation needs. Instead this agent runs as the
|
||||
// ordinary operator account on the host, listens on one unix socket which only
|
||||
// that account can connect to, and executes one fixed command with a fixed
|
||||
// writer declaration. A caller can choose the scope and (optionally) a job id —
|
||||
// nothing else.
|
||||
package libraryagent
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config is fixed at start-up by the operator (systemd unit / CLI flags). It is
|
||||
// never taken from a request.
|
||||
type Config struct {
|
||||
Socket string
|
||||
Binary string
|
||||
ArchiveRoot string
|
||||
JournalRoot string
|
||||
// Writer declaration passed to the binary, exactly as reviewed in
|
||||
// scripts/library-capture.sh. Clients cannot influence it.
|
||||
SourceApp string
|
||||
SourcePG string
|
||||
SourceES string
|
||||
GovernancePG string
|
||||
Project string
|
||||
Writers string
|
||||
NonWriters string
|
||||
MaxDuration time.Duration
|
||||
// Run executes the binary; replaced in tests.
|
||||
Run func(ctx context.Context, name string, args ...string) ([]byte, error)
|
||||
}
|
||||
|
||||
type request struct {
|
||||
Action string `json:"action"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
Job string `json:"job,omitempty"`
|
||||
}
|
||||
|
||||
type response struct {
|
||||
OK bool `json:"ok"`
|
||||
Action string `json:"action"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
Job string `json:"job,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Payload json.RawMessage `json:"payload,omitempty"`
|
||||
}
|
||||
|
||||
var jobPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
|
||||
|
||||
// Agent serves capture requests. Only one operation runs at a time: a library
|
||||
// capture owns the writer group, so overlapping requests would race the window.
|
||||
type Agent struct {
|
||||
config Config
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func New(config Config) (*Agent, error) {
|
||||
if !filepath.IsAbs(config.Socket) || !filepath.IsAbs(config.ArchiveRoot) || !filepath.IsAbs(config.JournalRoot) {
|
||||
return nil, errors.New("library agent paths must be absolute")
|
||||
}
|
||||
if config.Binary == "" || config.Project == "" || config.Writers == "" || !strings.Contains(config.NonWriters, "=") {
|
||||
return nil, errors.New("library agent needs a binary, project, writers and a non-writer declaration")
|
||||
}
|
||||
if config.MaxDuration <= 0 || config.MaxDuration > 30*time.Minute {
|
||||
return nil, errors.New("library agent duration bound is invalid")
|
||||
}
|
||||
return &Agent{config: config}, nil
|
||||
}
|
||||
|
||||
// Serve listens until ctx is cancelled. The socket is created 0600 inside a
|
||||
// 0700 directory and removed on shutdown.
|
||||
func (a *Agent) Serve(ctx context.Context) error {
|
||||
if err := os.MkdirAll(filepath.Dir(a.config.Socket), 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Chmod(filepath.Dir(a.config.Socket), 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = os.Remove(a.config.Socket)
|
||||
listener, err := net.Listen("unix", a.config.Socket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
listener.Close()
|
||||
_ = os.Remove(a.config.Socket)
|
||||
}()
|
||||
if err := os.Chmod(a.config.Socket, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
_ = listener.Close()
|
||||
}()
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
go a.handle(ctx, conn)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Agent) handle(ctx context.Context, conn net.Conn) {
|
||||
defer conn.Close()
|
||||
if err := peerAllowed(conn); err != nil {
|
||||
_ = json.NewEncoder(conn).Encode(response{OK: false, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
_ = conn.SetDeadline(time.Now().Add(a.config.MaxDuration + 30*time.Second))
|
||||
decoder := json.NewDecoder(bufio.NewReader(conn))
|
||||
var req request
|
||||
if err := decoder.Decode(&req); err != nil {
|
||||
_ = json.NewEncoder(conn).Encode(response{OK: false, Error: "invalid request"})
|
||||
return
|
||||
}
|
||||
result := a.execute(ctx, req)
|
||||
_ = json.NewEncoder(conn).Encode(result)
|
||||
}
|
||||
|
||||
// execute serialises operations and maps a request onto the one fixed command.
|
||||
func (a *Agent) execute(ctx context.Context, req request) response {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
out := response{Action: req.Action, Scope: req.Scope, Job: req.Job}
|
||||
var args []string
|
||||
switch req.Action {
|
||||
case "status":
|
||||
args = []string{"status"}
|
||||
case "recover":
|
||||
args = []string{"recover"}
|
||||
case "capture":
|
||||
if req.Scope != "internal" && req.Scope != "external" {
|
||||
out.Error = "scope must be internal or external"
|
||||
return out
|
||||
}
|
||||
if req.Job != "" && !jobPattern.MatchString(req.Job) {
|
||||
out.Error = "invalid job id"
|
||||
return out
|
||||
}
|
||||
args = []string{"capture", "-scope", req.Scope}
|
||||
if req.Job != "" {
|
||||
args = append(args, "-job", req.Job)
|
||||
}
|
||||
default:
|
||||
out.Error = "unsupported action"
|
||||
return out
|
||||
}
|
||||
args = append(args, a.config.declaration()...)
|
||||
bounded, cancel := context.WithTimeout(ctx, a.config.MaxDuration)
|
||||
defer cancel()
|
||||
payload, err := a.config.run(bounded, a.config.Binary, args...)
|
||||
if err != nil {
|
||||
out.Error = "operation failed"
|
||||
if message := strings.TrimSpace(string(payload)); message != "" && len(message) <= 2000 {
|
||||
out.Error = message
|
||||
}
|
||||
return out
|
||||
}
|
||||
out.OK = true
|
||||
if json.Valid(payload) {
|
||||
out.Payload = json.RawMessage(payload)
|
||||
} else {
|
||||
out.Payload = json.RawMessage(`{}`)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// declaration pins every path and the writer group so a request cannot redirect
|
||||
// the operation to another stack, archive or journal.
|
||||
func (c Config) declaration() []string {
|
||||
return []string{
|
||||
"-source-app", c.SourceApp,
|
||||
"-source-pg", c.SourcePG,
|
||||
"-source-es", c.SourceES,
|
||||
"-governance-pg", c.GovernancePG,
|
||||
"-project", c.Project,
|
||||
"-writers", c.Writers,
|
||||
"-non-writers", c.NonWriters,
|
||||
"-archive", c.ArchiveRoot,
|
||||
"-journal", c.JournalRoot,
|
||||
}
|
||||
}
|
||||
|
||||
func (c Config) run(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||
if c.Run != nil {
|
||||
return c.Run(ctx, name, args...)
|
||||
}
|
||||
command := exec.CommandContext(ctx, name, args...)
|
||||
command.Env = append(os.Environ(), "LIBRARYCTL_AGENT=1")
|
||||
return command.CombinedOutput()
|
||||
}
|
||||
|
||||
// Describe returns a redacted view for logs and health checks.
|
||||
func (a *Agent) Describe() map[string]any {
|
||||
return map[string]any{
|
||||
"socket": a.config.Socket,
|
||||
"archive_root": a.config.ArchiveRoot,
|
||||
"journal_root": a.config.JournalRoot,
|
||||
"project": a.config.Project,
|
||||
"writers": a.config.Writers,
|
||||
"scope_choice": "request may select internal or external only",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package libraryagent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func testAgent(t *testing.T) (*Agent, string, func() []string) {
|
||||
t.Helper()
|
||||
root, err := os.MkdirTemp(os.TempDir(), "kgag-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(root) })
|
||||
if err = os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var mu sync.Mutex
|
||||
var calls []string
|
||||
config := Config{
|
||||
Socket: filepath.Join(root, "agent.sock"),
|
||||
Binary: "/bin/echo",
|
||||
ArchiveRoot: filepath.Join(root, "library"),
|
||||
JournalRoot: filepath.Join(root, "freeze"),
|
||||
SourceApp: "WKNFull-app",
|
||||
SourcePG: "WKNFull-postgres",
|
||||
SourceES: "WKNFull-elasticsearch",
|
||||
GovernancePG: "knowledge-governance-p1-postgres-1",
|
||||
Project: "weknora071full",
|
||||
Writers: "app",
|
||||
NonWriters: "frontend=UI only; no knowledge writes",
|
||||
MaxDuration: time.Minute,
|
||||
Run: func(_ context.Context, name string, args ...string) ([]byte, error) {
|
||||
mu.Lock()
|
||||
calls = append(calls, name+" "+strings.Join(args, " "))
|
||||
mu.Unlock()
|
||||
return []byte(`{"snapshot_id":"abc","state":"succeeded"}`), nil
|
||||
},
|
||||
}
|
||||
agent, err := New(config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return agent, config.Socket, func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]string(nil), calls...)
|
||||
}
|
||||
}
|
||||
|
||||
func roundTrip(t *testing.T, socket string, payload string) response {
|
||||
t.Helper()
|
||||
conn, err := net.Dial("unix", socket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
if _, err = conn.Write([]byte(payload + "\n")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out response
|
||||
if err = json.NewDecoder(conn).Decode(&out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// The socket is the whole security boundary: 0600 in a 0700 directory, and the
|
||||
// declaration (archive, journal, project, writers) comes from the agent's own
|
||||
// configuration, never from the request.
|
||||
func TestAgentSocketIsPrivateAndPinsTheDeclaration(t *testing.T) {
|
||||
agent, socket, calls := testAgent(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go func() { _ = agent.Serve(ctx) }()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
if _, err := os.Stat(socket); err == nil {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("agent socket never appeared")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
info, err := os.Stat(socket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0600 {
|
||||
t.Fatalf("socket mode %v", info.Mode().Perm())
|
||||
}
|
||||
dir, err := os.Stat(filepath.Dir(socket))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dir.Mode().Perm() != 0700 {
|
||||
t.Fatalf("socket directory mode %v", dir.Mode().Perm())
|
||||
}
|
||||
out := roundTrip(t, socket, `{"action":"capture","scope":"internal","job":"lib-internal-test"}`)
|
||||
if !out.OK || out.Job != "lib-internal-test" {
|
||||
t.Fatalf("capture rejected: %+v", out)
|
||||
}
|
||||
recorded := calls()
|
||||
if len(recorded) != 1 {
|
||||
t.Fatalf("expected one execution, got %v", recorded)
|
||||
}
|
||||
for _, want := range []string{"capture -scope internal -job lib-internal-test",
|
||||
"-archive " + filepath.Join(filepath.Dir(socket), "library"),
|
||||
"-journal " + filepath.Join(filepath.Dir(socket), "freeze"),
|
||||
"-project weknora071full", "-writers app"} {
|
||||
if !strings.Contains(recorded[0], want) {
|
||||
t.Fatalf("execution %q missing %q", recorded[0], want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(recorded[0], "..") {
|
||||
t.Fatal("unexpected path traversal in declaration")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentRejectsUnsupportedRequestsWithoutExecuting(t *testing.T) {
|
||||
agent, socket, calls := testAgent(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go func() { _ = agent.Serve(ctx) }()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
if _, err := os.Stat(socket); err == nil {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("agent socket never appeared")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
for _, payload := range []string{
|
||||
`{"action":"shell","command":"docker ps"}`,
|
||||
`{"action":"capture","scope":"production"}`,
|
||||
`{"action":"capture","scope":"internal","job":"bad job; rm -rf /"}`,
|
||||
`not json`,
|
||||
} {
|
||||
out := roundTrip(t, socket, payload)
|
||||
if out.OK || out.Error == "" {
|
||||
t.Fatalf("accepted %q: %+v", payload, out)
|
||||
}
|
||||
}
|
||||
if got := calls(); len(got) != 0 {
|
||||
t.Fatalf("rejected requests still executed: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRejectsIncompleteConfiguration(t *testing.T) {
|
||||
if _, err := New(Config{}); err == nil {
|
||||
t.Fatal("empty configuration accepted")
|
||||
}
|
||||
if _, err := New(Config{Socket: "relative.sock", ArchiveRoot: "/tmp/a", JournalRoot: "/tmp/j",
|
||||
Binary: "/bin/true", Project: "p", Writers: "app", NonWriters: "frontend=ui", MaxDuration: time.Minute}); err == nil {
|
||||
t.Fatal("relative socket path accepted")
|
||||
}
|
||||
if _, err := New(Config{Socket: "/tmp/a.sock", ArchiveRoot: "/tmp/a", JournalRoot: "/tmp/j",
|
||||
Binary: "/bin/true", Project: "p", Writers: "app", NonWriters: "frontend", MaxDuration: time.Minute}); err == nil {
|
||||
t.Fatal("non-writer declaration without a reason accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package libraryagent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ClientConfig is what a governance process needs: one socket path. It never
|
||||
// carries source credentials or Docker access — those stay with the agent.
|
||||
type ClientConfig struct {
|
||||
Socket string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Result is the agent's answer to one capture/status/recover request.
|
||||
type Result struct {
|
||||
OK bool
|
||||
Scope string
|
||||
Job string
|
||||
SnapshotID string
|
||||
Replay bool
|
||||
Error string
|
||||
Payload json.RawMessage
|
||||
}
|
||||
|
||||
// Capture asks the agent to seal one library scope. The job id makes the call
|
||||
// idempotent: repeating it returns the already sealed candidate.
|
||||
func Capture(ctx context.Context, config ClientConfig, scope, job string) (Result, error) {
|
||||
return call(ctx, config, map[string]string{"action": "capture", "scope": scope, "job": job})
|
||||
}
|
||||
|
||||
// Status probes the agent (source wiring, writer group, archive usage).
|
||||
func Status(ctx context.Context, config ClientConfig) (Result, error) {
|
||||
return call(ctx, config, map[string]string{"action": "status"})
|
||||
}
|
||||
|
||||
// Recover restores writers from an interrupted freeze journal.
|
||||
func Recover(ctx context.Context, config ClientConfig) (Result, error) {
|
||||
return call(ctx, config, map[string]string{"action": "recover"})
|
||||
}
|
||||
|
||||
func call(ctx context.Context, config ClientConfig, request map[string]string) (Result, error) {
|
||||
if config.Socket == "" {
|
||||
return Result{}, errors.New("library agent socket is not configured")
|
||||
}
|
||||
timeout := config.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 2 * time.Minute
|
||||
}
|
||||
bounded, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
var dialer net.Dialer
|
||||
conn, err := dialer.DialContext(bounded, "unix", config.Socket)
|
||||
if err != nil {
|
||||
return Result{}, errors.New("library agent is unreachable")
|
||||
}
|
||||
defer conn.Close()
|
||||
if deadline, ok := bounded.Deadline(); ok {
|
||||
_ = conn.SetDeadline(deadline)
|
||||
}
|
||||
if err = json.NewEncoder(conn).Encode(request); err != nil {
|
||||
return Result{}, errors.New("library agent request failed")
|
||||
}
|
||||
var response struct {
|
||||
OK bool `json:"ok"`
|
||||
Scope string `json:"scope"`
|
||||
Job string `json:"job"`
|
||||
Error string `json:"error"`
|
||||
Payload json.RawMessage `json:"payload"`
|
||||
}
|
||||
if err = json.NewDecoder(conn).Decode(&response); err != nil {
|
||||
return Result{}, errors.New("library agent returned an invalid response")
|
||||
}
|
||||
result := Result{OK: response.OK, Scope: response.Scope, Job: response.Job, Error: response.Error, Payload: response.Payload}
|
||||
var payload struct {
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Replay bool `json:"replay"`
|
||||
}
|
||||
if len(response.Payload) > 0 && json.Unmarshal(response.Payload, &payload) == nil {
|
||||
result.SnapshotID, result.Replay = payload.SnapshotID, payload.Replay
|
||||
}
|
||||
if !result.OK {
|
||||
if result.Error == "" {
|
||||
result.Error = "library agent refused the request"
|
||||
}
|
||||
return result, errors.New(result.Error)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package libraryagent
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// peerAllowed enforces that the connecting process runs as the same uid as the
|
||||
// agent. File mode 0600 already limits connect() to that uid; the credential
|
||||
// check makes the boundary explicit and fails closed if the socket is ever
|
||||
// reached another way (bind mount into a container with a different uid).
|
||||
func peerAllowed(conn net.Conn) error {
|
||||
unixConn, ok := conn.(*net.UnixConn)
|
||||
if !ok {
|
||||
return errors.New("unsupported transport")
|
||||
}
|
||||
raw, err := unixConn.SyscallConn()
|
||||
if err != nil {
|
||||
return errors.New("peer credentials unavailable")
|
||||
}
|
||||
var credential *syscall.Ucred
|
||||
var controlErr error
|
||||
if err = raw.Control(func(fd uintptr) {
|
||||
credential, controlErr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
|
||||
}); err != nil {
|
||||
return errors.New("peer credentials unavailable")
|
||||
}
|
||||
if controlErr != nil || credential == nil {
|
||||
return errors.New("peer credentials unavailable")
|
||||
}
|
||||
if credential.Uid != uint32(os.Geteuid()) {
|
||||
return errors.New("peer uid is not allowed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build !linux
|
||||
|
||||
package libraryagent
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
// The capture host is Linux (Docker + unix socket); other platforms refuse
|
||||
// rather than guess at peer credentials.
|
||||
func peerAllowed(net.Conn) error {
|
||||
return errors.New("library agent requires Linux peer credentials")
|
||||
}
|
||||
@@ -129,6 +129,25 @@ func (c *Coordinator) Recover(ctx context.Context) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Inspect reports the persisted result of a job, if this coordinator ever ran it.
|
||||
// A caller which re-uses a job ID needs the original request identity (time,
|
||||
// scope, knowledge base, contract) to replay idempotently instead of guessing a
|
||||
// fresh one, which would be rejected as a conflicting request.
|
||||
func (c *Coordinator) Inspect(job string) (Result, bool, error) {
|
||||
if !validID(job) {
|
||||
return Result{}, false, errors.New("invalid freeze job id")
|
||||
}
|
||||
j, err := c.load(job)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return Result{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return Result{}, false, err
|
||||
}
|
||||
return j.Result, true, nil
|
||||
}
|
||||
|
||||
func invokeCapture(ctx context.Context, capture func(context.Context) (string, error)) (id string, err error) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A deployed test stack owns its containers: it cannot be relabelled without
|
||||
// recreating it, which would be a change to that stack rather than to this
|
||||
// platform. ProjectController therefore pins the writer group by the identity
|
||||
// the stack already carries: the Compose project and the exact service names.
|
||||
//
|
||||
// Safety properties (the reason this is not a name filter):
|
||||
// - the whole Compose project is enumerated, not just the running subset;
|
||||
// - every service in the project must be declared, either as a writer or as
|
||||
// explicitly non-writing with a reason, so a new sibling container cannot
|
||||
// be silently omitted from the maintenance window;
|
||||
// - container IDs are pinned on first inventory, so a recreated container is
|
||||
// refused instead of being stopped by a stale identity;
|
||||
// - only SIGTERM is sent and start waits for health, exactly like the
|
||||
// label-scoped controller.
|
||||
type ProjectController struct {
|
||||
project string
|
||||
writers map[string]bool
|
||||
nonWriter map[string]string
|
||||
timeout time.Duration
|
||||
client *http.Client
|
||||
transport *http.Transport
|
||||
pinned map[string]string
|
||||
}
|
||||
|
||||
const composeProjectLabel = "com.docker.compose.project"
|
||||
const composeServiceLabel = "com.docker.compose.service"
|
||||
|
||||
// NewProjectController validates the declaration. nonWriter must explain every
|
||||
// service in the project which is not a writer; an empty reason is rejected.
|
||||
func NewProjectController(socket, project string, writers []string, nonWriter map[string]string, timeout time.Duration) (*ProjectController, error) {
|
||||
if !filepath.IsAbs(socket) || !validID(project) || timeout <= 0 || timeout > 5*time.Minute || len(writers) == 0 || len(writers) > 32 {
|
||||
return nil, errors.New("invalid project Docker controller configuration")
|
||||
}
|
||||
set := map[string]bool{}
|
||||
for _, name := range writers {
|
||||
if !validID(name) || set[name] {
|
||||
return nil, errors.New("invalid project writer declaration")
|
||||
}
|
||||
if _, both := nonWriter[name]; both {
|
||||
return nil, errors.New("project service declared as both writer and non-writer")
|
||||
}
|
||||
set[name] = true
|
||||
}
|
||||
for name, reason := range nonWriter {
|
||||
if !validID(name) || strings.TrimSpace(reason) == "" {
|
||||
return nil, errors.New("invalid non-writer declaration")
|
||||
}
|
||||
}
|
||||
info, err := os.Stat(socket)
|
||||
if err != nil || info.Mode()&os.ModeSocket == 0 {
|
||||
return nil, errors.New("local Docker socket unavailable")
|
||||
}
|
||||
transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
|
||||
}}
|
||||
client := &http.Client{Transport: transport, Timeout: timeout, CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return errors.New("Docker redirects prohibited")
|
||||
}}
|
||||
return &ProjectController{project: project, writers: set, nonWriter: nonWriter, timeout: timeout,
|
||||
client: client, transport: transport, pinned: map[string]string{}}, nil
|
||||
}
|
||||
|
||||
func (p *ProjectController) Close() { p.transport.CloseIdleConnections() }
|
||||
|
||||
func (p *ProjectController) request(ctx context.Context, method, path string, out any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, method, "http://docker"+path, nil)
|
||||
if err != nil {
|
||||
return errors.New("invalid Docker request")
|
||||
}
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return errors.New("project Docker request failed")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return errors.New("project Docker request rejected")
|
||||
}
|
||||
if out != nil {
|
||||
data, readErr := io.ReadAll(io.LimitReader(resp.Body, 1024*1024+1))
|
||||
if readErr != nil || len(data) > 1024*1024 || json.Unmarshal(data, out) != nil {
|
||||
return errors.New("invalid Docker response")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type projectInspection struct {
|
||||
ID string `json:"Id"`
|
||||
Config struct {
|
||||
Labels map[string]string `json:"Labels"`
|
||||
Image string `json:"Image"`
|
||||
} `json:"Config"`
|
||||
State struct {
|
||||
Running bool
|
||||
Paused bool
|
||||
Restarting bool
|
||||
Dead bool
|
||||
Status string
|
||||
Health *struct{ Status string }
|
||||
} `json:"State"`
|
||||
}
|
||||
|
||||
// service resolves one container to its declared service name, refusing any
|
||||
// container which does not belong to the declared project.
|
||||
func (p *ProjectController) service(data projectInspection) (string, error) {
|
||||
if data.Config.Labels[composeProjectLabel] != p.project {
|
||||
return "", errors.New("container is not part of the declared project")
|
||||
}
|
||||
name := data.Config.Labels[composeServiceLabel]
|
||||
if !p.writers[name] {
|
||||
return "", errors.New("container service is not a declared writer")
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
func (p *ProjectController) inspect(ctx context.Context, id string) (Service, error) {
|
||||
if !dockerID(id) {
|
||||
return Service{}, errors.New("immutable Docker ID required")
|
||||
}
|
||||
var data projectInspection
|
||||
if err := p.request(ctx, "GET", "/containers/"+id+"/json", &data); err != nil {
|
||||
return Service{}, err
|
||||
}
|
||||
if data.ID != id {
|
||||
return Service{}, errors.New("container identity mismatch")
|
||||
}
|
||||
name, err := p.service(data)
|
||||
if err != nil {
|
||||
return Service{}, err
|
||||
}
|
||||
if pinned, ok := p.pinned[name]; ok && pinned != id {
|
||||
return Service{}, errors.New("declared project writer identity changed")
|
||||
}
|
||||
if data.State.Paused || data.State.Restarting || data.State.Dead {
|
||||
return Service{}, errors.New("project writer has unstable runtime state")
|
||||
}
|
||||
if data.State.Status != "running" && data.State.Status != "exited" && data.State.Status != "created" {
|
||||
return Service{}, errors.New("unknown project writer runtime state")
|
||||
}
|
||||
if data.State.Running != (data.State.Status == "running") {
|
||||
return Service{}, errors.New("contradictory project writer state")
|
||||
}
|
||||
healthy := data.State.Running && data.State.Health != nil && data.State.Health.Status == "healthy"
|
||||
return Service{ID: id, Running: data.State.Running, Healthy: healthy}, nil
|
||||
}
|
||||
|
||||
// Inventory enumerates the complete project writer group and rejects an
|
||||
// incomplete or extended declaration.
|
||||
func (p *ProjectController) Inventory(ctx context.Context) ([]Service, error) {
|
||||
filters, _ := json.Marshal(map[string][]string{"label": {composeProjectLabel + "=" + p.project}})
|
||||
var containers []struct {
|
||||
ID string `json:"Id"`
|
||||
Labels map[string]string `json:"Labels"`
|
||||
}
|
||||
if err := p.request(ctx, "GET", "/containers/json?all=1&filters="+url.QueryEscape(string(filters)), &containers); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(containers) == 0 || len(containers) > 256 {
|
||||
return nil, errors.New("empty or oversized project container group")
|
||||
}
|
||||
byService := map[string]string{}
|
||||
for _, container := range containers {
|
||||
service := container.Labels[composeServiceLabel]
|
||||
if service == "" {
|
||||
return nil, errors.New("project container without a compose service label")
|
||||
}
|
||||
if _, duplicate := byService[service]; duplicate {
|
||||
return nil, errors.New("duplicate project service instance")
|
||||
}
|
||||
if !p.writers[service] {
|
||||
if _, declared := p.nonWriter[service]; declared {
|
||||
continue
|
||||
}
|
||||
return nil, errors.New("undeclared project service " + service)
|
||||
}
|
||||
byService[service] = container.ID
|
||||
}
|
||||
for name := range p.writers {
|
||||
if byService[name] == "" {
|
||||
return nil, errors.New("declared project writer is missing")
|
||||
}
|
||||
}
|
||||
items := make([]Service, 0, len(byService))
|
||||
for _, id := range byService {
|
||||
s, err := p.inspect(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, s)
|
||||
}
|
||||
// Pin after every successful inventory so a later recreation is visible even
|
||||
// when the coordinator journal is inspected outside a run.
|
||||
for name, id := range byService {
|
||||
p.pinned[name] = id
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool { return items[i].ID < items[j].ID })
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (p *ProjectController) wait(ctx context.Context, id string, running bool) error {
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
s, err := p.inspect(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.Running == running && (!running || s.Healthy) {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return errors.New("project writer state did not settle before deadline")
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stop sends SIGTERM only; there is no delayed SIGKILL which could fire after
|
||||
// recovery starts the container again.
|
||||
func (p *ProjectController) Stop(ctx context.Context, id string) error {
|
||||
bounded, cancel := context.WithTimeout(ctx, p.timeout)
|
||||
defer cancel()
|
||||
s, err := p.inspect(bounded, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !s.Running {
|
||||
return nil
|
||||
}
|
||||
if err = p.request(bounded, "POST", "/containers/"+id+"/kill?signal=SIGTERM", nil); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.wait(bounded, id, false)
|
||||
}
|
||||
|
||||
func (p *ProjectController) Start(ctx context.Context, id string) error {
|
||||
bounded, cancel := context.WithTimeout(ctx, p.timeout)
|
||||
defer cancel()
|
||||
s, err := p.inspect(bounded, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !s.Running {
|
||||
if err = p.request(bounded, "POST", "/containers/"+id+"/start", nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return p.wait(bounded, id, true)
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package libraryfreeze
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type projectFixture struct {
|
||||
appID string
|
||||
frontID string
|
||||
appRunning bool
|
||||
appHealthy bool
|
||||
signals []string
|
||||
services []string
|
||||
}
|
||||
|
||||
func newProjectFixture(t *testing.T) (*projectFixture, string) {
|
||||
t.Helper()
|
||||
f := &projectFixture{
|
||||
appID: strings.Repeat("a", 64),
|
||||
frontID: strings.Repeat("b", 64),
|
||||
appRunning: true,
|
||||
appHealthy: true,
|
||||
services: []string{"app", "frontend"},
|
||||
}
|
||||
// A short path: unix socket addresses are length-limited and t.TempDir()
|
||||
// embeds the (long) test name.
|
||||
root, err := os.MkdirTemp(os.TempDir(), "kgp-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(root) })
|
||||
socket := filepath.Join(root, "engine.sock")
|
||||
listener, err := net.Listen("unix", socket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
labels := func(service string) map[string]string {
|
||||
return map[string]string{composeProjectLabel: "weknora", composeServiceLabel: service}
|
||||
}
|
||||
server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/containers/json"):
|
||||
if !strings.Contains(r.URL.Query().Get("filters"), "weknora") {
|
||||
t.Error("missing project filter")
|
||||
}
|
||||
items := []map[string]any{}
|
||||
for _, service := range f.services {
|
||||
id := f.appID
|
||||
if service == "frontend" {
|
||||
id = f.frontID
|
||||
}
|
||||
items = append(items, map[string]any{"Id": id, "Labels": labels(service)})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(items)
|
||||
case r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/json"):
|
||||
id := strings.TrimPrefix(strings.TrimSuffix(r.URL.Path, "/json"), "/containers/")
|
||||
service := "app"
|
||||
if id == f.frontID {
|
||||
service = "frontend"
|
||||
}
|
||||
status := "exited"
|
||||
health := any(nil)
|
||||
if id == f.appID && f.appRunning {
|
||||
status = "running"
|
||||
if f.appHealthy {
|
||||
health = map[string]string{"Status": "healthy"}
|
||||
} else {
|
||||
health = map[string]string{"Status": "starting"}
|
||||
}
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"Id": id, "Config": map[string]any{"Labels": labels(service)},
|
||||
"State": map[string]any{"Running": id == f.appID && f.appRunning, "Status": status, "Health": health}})
|
||||
case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/kill"):
|
||||
if r.URL.Query().Get("signal") != "SIGTERM" {
|
||||
t.Error("unsafe stop signal")
|
||||
}
|
||||
if !strings.Contains(r.URL.Path, f.appID) {
|
||||
t.Error("stopped an undeclared container")
|
||||
}
|
||||
f.signals = append(f.signals, "stop")
|
||||
f.appRunning = false
|
||||
w.WriteHeader(204)
|
||||
case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/start"):
|
||||
f.signals = append(f.signals, "start")
|
||||
f.appRunning = true
|
||||
w.WriteHeader(204)
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
})}
|
||||
go server.Serve(listener)
|
||||
t.Cleanup(func() { server.Close() })
|
||||
return f, socket
|
||||
}
|
||||
|
||||
func TestProjectControllerStopsOnlyDeclaredWritersByPinnedIdentity(t *testing.T) {
|
||||
fixture, socket := newProjectFixture(t)
|
||||
control, err := NewProjectController(socket, "weknora", []string{"app"},
|
||||
map[string]string{"frontend": "serves the UI only; never writes knowledge"}, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer control.Close()
|
||||
items, err := control.Inventory(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 1 || items[0].ID != fixture.appID || !items[0].Running || !items[0].Healthy {
|
||||
t.Fatalf("unexpected writer inventory %+v", items)
|
||||
}
|
||||
if err = control.Stop(context.Background(), fixture.appID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fixture.appRunning {
|
||||
t.Fatal("writer still running after stop")
|
||||
}
|
||||
if err = control.Start(context.Background(), fixture.appID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fixture.signals) != 2 || fixture.signals[0] != "stop" || fixture.signals[1] != "start" {
|
||||
t.Fatalf("unexpected signal order %v", fixture.signals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectControllerRefusesUndeclaredSibling(t *testing.T) {
|
||||
fixture, socket := newProjectFixture(t)
|
||||
control, err := NewProjectController(socket, "weknora", []string{"app"}, map[string]string{}, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer control.Close()
|
||||
if _, err = control.Inventory(context.Background()); err == nil {
|
||||
t.Fatal("undeclared sibling service was accepted")
|
||||
}
|
||||
if len(fixture.signals) != 0 {
|
||||
t.Fatal("refused inventory still signalled a container")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectControllerRefusesReplacedContainerIdentity(t *testing.T) {
|
||||
fixture, socket := newProjectFixture(t)
|
||||
control, err := NewProjectController(socket, "weknora", []string{"app"},
|
||||
map[string]string{"frontend": "serves the UI only; never writes knowledge"}, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer control.Close()
|
||||
if _, err = control.Inventory(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A recreated container keeps the service name but is a different instance:
|
||||
// stopping it would hit a container the maintenance window never declared.
|
||||
fixture.appID = strings.Repeat("c", 64)
|
||||
if _, err = control.Inventory(context.Background()); err == nil {
|
||||
t.Fatal("recreated writer identity was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectControllerWaitsForHealthOnStart(t *testing.T) {
|
||||
fixture, socket := newProjectFixture(t)
|
||||
control, err := NewProjectController(socket, "weknora", []string{"app"},
|
||||
map[string]string{"frontend": "serves the UI only; never writes knowledge"}, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer control.Close()
|
||||
if _, err = control.Inventory(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fixture.appRunning = false
|
||||
fixture.appHealthy = false
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
if err = control.Start(ctx, fixture.appID); err == nil {
|
||||
t.Fatal("start succeeded without health")
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,9 @@ import (
|
||||
)
|
||||
|
||||
const Format = "weknora-library-snapshot/v1"
|
||||
|
||||
// ArtifactAcceptancePolicy requires separate snapshot-bound semantic acceptance.
|
||||
const ArtifactAcceptancePolicy = "artifact-acceptance-v1"
|
||||
const maxManifestBytes = 16 * 1024 * 1024
|
||||
|
||||
type Part struct {
|
||||
@@ -39,13 +42,14 @@ type Compatibility struct {
|
||||
}
|
||||
|
||||
type Manifest struct {
|
||||
Compatibility Compatibility `json:"compatibility"`
|
||||
Format string `json:"format"`
|
||||
Scope string `json:"scope"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Parts []Part `json:"parts"`
|
||||
ValidationPolicy string `json:"validation_policy,omitempty"`
|
||||
Compatibility Compatibility `json:"compatibility"`
|
||||
Format string `json:"format"`
|
||||
Scope string `json:"scope"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Parts []Part `json:"parts"`
|
||||
}
|
||||
type Archive struct {
|
||||
root, blobs, versions *os.Root
|
||||
@@ -361,6 +365,9 @@ func identifier(s string) bool {
|
||||
}
|
||||
|
||||
func encodeManifest(m Manifest) ([]byte, error) {
|
||||
if m.ValidationPolicy != "" && m.ValidationPolicy != ArtifactAcceptancePolicy {
|
||||
return nil, errors.New("unsupported snapshot validation policy")
|
||||
}
|
||||
c := m.Compatibility
|
||||
if c.WeKnoraVersion != releasebundle.WeKnoraVersionV071 || c.SchemaVersion != releasebundle.WeKnoraMigrationV071 || c.RetrieverEngine != "elasticsearch_v8" || !identifier(c.EmbeddingModel) || c.EmbeddingDimension != releasebundle.EmbeddingDimensionV071 || !validDigest(c.IndexMappingSHA256) {
|
||||
return nil, errors.New("unsupported snapshot compatibility contract")
|
||||
|
||||
@@ -6,9 +6,11 @@ import (
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
type Usage struct {
|
||||
@@ -97,6 +99,135 @@ func (a *Archive) Usage() ([]Usage, error) {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ContentUsage is the archive-wide accounting of *content* bytes.
|
||||
//
|
||||
// It exists because per-version Usage() deduplicates only within one version: a
|
||||
// blob shared by two versions is counted in both UniqueBytes, so summing those
|
||||
// numbers over-reports the archive. ContentBytes here is deduplicated across
|
||||
// every sealed version.
|
||||
//
|
||||
// It is still not filesystem occupancy: manifests, unreferenced blobs left by an
|
||||
// interrupted Put and filesystem allocation (block rounding, metadata) are
|
||||
// reported separately, and none of these numbers are reclaimable space. Cleanup
|
||||
// needs retention/protection and live-job references from the coordinator.
|
||||
type ContentUsage struct {
|
||||
Versions int `json:"versions"`
|
||||
ReferencedBlobs int `json:"referenced_blobs"`
|
||||
ContentBytes int64 `json:"content_bytes"`
|
||||
UnreferencedBlobs int `json:"unreferenced_blobs"`
|
||||
UnreferencedBytes int64 `json:"unreferenced_bytes"`
|
||||
BlobFileBytes int64 `json:"blob_file_bytes"`
|
||||
BlobAllocatedBytes int64 `json:"blob_allocated_bytes"`
|
||||
ManifestFileBytes int64 `json:"manifest_file_bytes"`
|
||||
ManifestAllocatedBytes int64 `json:"manifest_allocated_bytes"`
|
||||
}
|
||||
|
||||
// ContentUsage walks the sealed versions and the blob directory once, with the
|
||||
// same "inventory must not change under us" guard as Usage.
|
||||
func (a *Archive) ContentUsage() (ContentUsage, error) {
|
||||
var usage ContentUsage
|
||||
ids, err := a.versionIDs()
|
||||
if err != nil {
|
||||
return usage, err
|
||||
}
|
||||
referenced := map[string]int64{}
|
||||
for _, id := range ids {
|
||||
m, err := a.Load(id)
|
||||
if err != nil {
|
||||
return usage, err
|
||||
}
|
||||
for _, p := range m.Parts {
|
||||
referenced[p.SHA256] = p.Bytes
|
||||
}
|
||||
}
|
||||
after, err := a.versionIDs()
|
||||
if err != nil {
|
||||
return usage, err
|
||||
}
|
||||
if !slices.Equal(ids, after) {
|
||||
return usage, errors.New("snapshot inventory changed; retry usage read")
|
||||
}
|
||||
usage.Versions = len(ids)
|
||||
usage.ReferencedBlobs = len(referenced)
|
||||
for _, size := range referenced {
|
||||
if usage.ContentBytes > math.MaxInt64-size {
|
||||
return usage, errors.New("snapshot usage overflow")
|
||||
}
|
||||
usage.ContentBytes += size
|
||||
}
|
||||
blobs, err := directoryBytes(a.blobs, func(name string) error {
|
||||
if !validDigest(name) {
|
||||
return errors.New("unexpected archive blob entry")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return usage, err
|
||||
}
|
||||
usage.BlobFileBytes, usage.BlobAllocatedBytes = blobs.fileBytes, blobs.allocatedBytes
|
||||
usage.UnreferencedBlobs = blobs.files - len(referenced)
|
||||
usage.UnreferencedBytes = blobs.fileBytes
|
||||
for _, size := range referenced {
|
||||
usage.UnreferencedBytes -= size
|
||||
}
|
||||
if usage.UnreferencedBytes < 0 || usage.UnreferencedBlobs < 0 {
|
||||
return usage, errors.New("archive blob inventory is inconsistent")
|
||||
}
|
||||
manifests, err := directoryBytes(a.versions, func(name string) error {
|
||||
if strings.HasPrefix(name, ".pending-") {
|
||||
return nil
|
||||
}
|
||||
if !strings.HasSuffix(name, ".json") {
|
||||
return errors.New("unexpected archive version entry")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return usage, err
|
||||
}
|
||||
usage.ManifestFileBytes, usage.ManifestAllocatedBytes = manifests.fileBytes, manifests.allocatedBytes
|
||||
return usage, nil
|
||||
}
|
||||
|
||||
type directoryUsage struct {
|
||||
files int
|
||||
fileBytes int64
|
||||
allocatedBytes int64
|
||||
}
|
||||
|
||||
// directoryBytes reports apparent size and allocated size (st_blocks) so callers
|
||||
// can tell content size from what the filesystem actually reserved.
|
||||
func directoryBytes(root *os.Root, validate func(string) error) (directoryUsage, error) {
|
||||
var usage directoryUsage
|
||||
dir, err := root.Open(".")
|
||||
if err != nil {
|
||||
return usage, err
|
||||
}
|
||||
defer dir.Close()
|
||||
entries, err := dir.ReadDir(-1)
|
||||
if err != nil {
|
||||
return usage, err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if err := validate(entry.Name()); err != nil {
|
||||
return usage, err
|
||||
}
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
return usage, err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return usage, errors.New("archive entry is not a regular file")
|
||||
}
|
||||
usage.files++
|
||||
usage.fileBytes += info.Size()
|
||||
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
|
||||
usage.allocatedBytes += stat.Blocks * 512
|
||||
}
|
||||
}
|
||||
return usage, nil
|
||||
}
|
||||
|
||||
func (a *Archive) versionIDs() ([]string, error) {
|
||||
f, err := a.versions.Open(".")
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package librarysnapshot
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// sealFixtureVersion seals one complete manifest whose parts are all derived
|
||||
// from the same rows, so two versions of the same content share every blob.
|
||||
func sealFixtureVersion(t *testing.T, archive *Archive, scope string, createdAt time.Time, documents int) string {
|
||||
t.Helper()
|
||||
rows := func(count int) string {
|
||||
if count == 0 {
|
||||
return "[]"
|
||||
}
|
||||
items := make([]string, count)
|
||||
for i := range items {
|
||||
items[i] = fmt.Sprintf(`{"id":"00000000-0000-4000-8000-%012d"}`, i)
|
||||
}
|
||||
return "[" + strings.Join(items, ",") + "]"
|
||||
}
|
||||
parts := []struct {
|
||||
kind, name string
|
||||
count int64
|
||||
body string
|
||||
}{
|
||||
{"database", "knowledges", int64(documents), rows(documents)},
|
||||
{"database", "chunks", int64(documents), rows(documents)},
|
||||
{"database", "resources", 0, rows(0)},
|
||||
{"database", "resource_bindings", 0, rows(0)},
|
||||
{"database", "knowledge_tags", 0, rows(0)},
|
||||
{"database", "knowledge_tag_relations", 0, rows(0)},
|
||||
{"index", "chunks", int64(documents), rows(documents)},
|
||||
{"wiki", "wiki_pages", 0, rows(0)},
|
||||
{"wiki", "wiki_folders", 0, rows(0)},
|
||||
{"wiki", "wiki_page_issues", 0, rows(0)},
|
||||
{"wiki", "wiki_log_entries", 0, rows(0)},
|
||||
}
|
||||
manifest := Manifest{ValidationPolicy: ArtifactAcceptancePolicy, Format: Format, Scope: scope,
|
||||
TenantID: 10000, KnowledgeBaseID: "kb-safe", CreatedAt: createdAt,
|
||||
Compatibility: Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74,
|
||||
RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024,
|
||||
IndexMappingSHA256: strings.Repeat("a", 64)}}
|
||||
for _, part := range parts {
|
||||
stored, err := archive.Put(bytes.NewReader([]byte(part.body)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored.Kind, stored.Name, stored.Count = part.kind, part.name, part.count
|
||||
manifest.Parts = append(manifest.Parts, stored)
|
||||
}
|
||||
id, err := archive.Seal(manifest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func fixtureArchive(t *testing.T) (*Archive, string) {
|
||||
t.Helper()
|
||||
root, err := os.MkdirTemp(os.TempDir(), "kgsnap-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(root) })
|
||||
if err = os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive, err := Open(root, 1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { archive.Close() })
|
||||
return archive, root
|
||||
}
|
||||
|
||||
// Two sealed versions with identical content share every blob: summing the
|
||||
// per-version UniqueBytes double counts them, which is the reporting bug this
|
||||
// accounting fixes.
|
||||
func TestContentUsageDeduplicatesAcrossVersions(t *testing.T) {
|
||||
archive, _ := fixtureArchive(t)
|
||||
sealFixtureVersion(t, archive, "internal", time.Date(2026, 10, 28, 1, 0, 0, 0, time.UTC), 4)
|
||||
sealFixtureVersion(t, archive, "internal", time.Date(2026, 10, 28, 2, 0, 0, 0, time.UTC), 4)
|
||||
perVersion, err := archive.Usage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(perVersion) != 2 {
|
||||
t.Fatalf("expected two versions, got %d", len(perVersion))
|
||||
}
|
||||
sum := perVersion[0].UniqueBytes + perVersion[1].UniqueBytes
|
||||
total, err := archive.ContentUsage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if total.Versions != 2 {
|
||||
t.Fatalf("versions=%d", total.Versions)
|
||||
}
|
||||
if total.ContentBytes <= 0 {
|
||||
t.Fatal("no content bytes reported")
|
||||
}
|
||||
if total.ContentBytes*2 != sum {
|
||||
t.Fatalf("shared content not deduplicated: content=%d sum-of-versions=%d", total.ContentBytes, sum)
|
||||
}
|
||||
if total.UnreferencedBlobs != 0 || total.UnreferencedBytes != 0 {
|
||||
t.Fatalf("unexpected unreferenced blobs: %+v", total)
|
||||
}
|
||||
if total.BlobFileBytes != total.ContentBytes {
|
||||
t.Fatalf("blob files=%d content=%d", total.BlobFileBytes, total.ContentBytes)
|
||||
}
|
||||
if total.BlobAllocatedBytes < total.BlobFileBytes {
|
||||
t.Fatalf("allocated=%d smaller than apparent=%d", total.BlobAllocatedBytes, total.BlobFileBytes)
|
||||
}
|
||||
if total.ManifestFileBytes <= 0 || total.ManifestAllocatedBytes < total.ManifestFileBytes {
|
||||
t.Fatalf("manifest accounting wrong: %+v", total)
|
||||
}
|
||||
}
|
||||
|
||||
// A blob written by an interrupted capture is referenced by no manifest and must
|
||||
// be reported separately, never folded into content bytes.
|
||||
func TestContentUsageSeparatesUnreferencedBlobs(t *testing.T) {
|
||||
archive, _ := fixtureArchive(t)
|
||||
sealFixtureVersion(t, archive, "internal", time.Date(2026, 10, 28, 3, 0, 0, 0, time.UTC), 2)
|
||||
before, err := archive.ContentUsage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stray, err := archive.Put(bytes.NewReader([]byte("interrupted-write")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := archive.ContentUsage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.ContentBytes != before.ContentBytes {
|
||||
t.Fatal("unreferenced blob changed content bytes")
|
||||
}
|
||||
if after.UnreferencedBlobs != 1 || after.UnreferencedBytes != stray.Bytes {
|
||||
t.Fatalf("unreferenced accounting wrong: %+v (stray=%d)", after, stray.Bytes)
|
||||
}
|
||||
if after.BlobFileBytes != before.BlobFileBytes+stray.Bytes {
|
||||
t.Fatal("blob file bytes do not include the unreferenced blob")
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ func ArchiveLibraryCandidate(ctx context.Context, archive *librarysnapshot.Archi
|
||||
if es.MappingSHA256 != contract.IndexMappingSHA256 {
|
||||
return "", errors.New("library mapping contract mismatch")
|
||||
}
|
||||
manifest := librarysnapshot.Manifest{Format: librarysnapshot.Format, Scope: scope, TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, CreatedAt: createdAt, Compatibility: contract}
|
||||
manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy, Format: librarysnapshot.Format, Scope: scope, TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, CreatedAt: createdAt, Compatibility: contract}
|
||||
put := func(kind, name string, count int64, data []byte) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
@@ -105,18 +105,22 @@ func ArchiveLibraryCandidate(ctx context.Context, archive *librarysnapshot.Archi
|
||||
}
|
||||
|
||||
type libraryRow struct {
|
||||
ID string `json:"id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
ChunkID string `json:"chunk_id"`
|
||||
TagID string `json:"tag_id"`
|
||||
ResourceID string `json:"resource_id"`
|
||||
Handle string `json:"handle"`
|
||||
OwnerType string `json:"owner_type"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Content string `json:"content"`
|
||||
ChunkStatus int `json:"-"`
|
||||
ID string `json:"id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
KnowledgeID string `json:"knowledge_id"`
|
||||
ChunkID string `json:"chunk_id"`
|
||||
TagID string `json:"tag_id"`
|
||||
ResourceID string `json:"resource_id"`
|
||||
Handle string `json:"handle"`
|
||||
OwnerType string `json:"owner_type"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Content string `json:"content"`
|
||||
Title string `json:"title"`
|
||||
ChunkType string `json:"chunk_type"`
|
||||
ChunkStatus int `json:"-"`
|
||||
SourceID string `json:"source_id"`
|
||||
Questions map[string]string `json:"-"`
|
||||
}
|
||||
|
||||
func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es SearchSnapshot) error {
|
||||
@@ -156,12 +160,26 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
|
||||
// use strings. Decode chunk metadata only for its owning table.
|
||||
if table.Name == "chunks" {
|
||||
var metadata struct {
|
||||
Status int `json:"status"`
|
||||
Status int `json:"status"`
|
||||
Metadata struct {
|
||||
GeneratedQuestions []struct {
|
||||
ID string `json:"id"`
|
||||
Question string `json:"question"`
|
||||
} `json:"generated_questions"`
|
||||
} `json:"metadata"`
|
||||
}
|
||||
if json.Unmarshal(raw, &metadata) != nil {
|
||||
return errors.New("invalid library chunk status")
|
||||
}
|
||||
row.ChunkStatus = metadata.Status
|
||||
row.Questions = map[string]string{}
|
||||
for _, question := range metadata.Metadata.GeneratedQuestions {
|
||||
sourceID := row.ID + "-" + question.ID
|
||||
if row.ChunkType != "text" || !validSearchIdentifier(question.ID) || strings.TrimSpace(question.Question) == "" || row.Questions[sourceID] != "" {
|
||||
return errors.New("invalid library generated question metadata")
|
||||
}
|
||||
row.Questions[sourceID] = question.Question
|
||||
}
|
||||
}
|
||||
if table.Name == "knowledge_tag_relations" {
|
||||
if !validSearchIdentifier(row.KnowledgeID) || !validSearchIdentifier(row.TagID) {
|
||||
@@ -233,6 +251,7 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
indexedChunks := map[string]bool{}
|
||||
indexedQuestions := map[string]map[string]bool{}
|
||||
for _, document := range es.Documents {
|
||||
var row libraryRow
|
||||
if json.Unmarshal(document.Source, &row) != nil || !validSearchIdentifier(document.ID) || seen[document.ID] {
|
||||
@@ -240,18 +259,45 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
|
||||
}
|
||||
seen[document.ID] = true
|
||||
chunk, ok := tables["chunks"][row.ChunkID]
|
||||
if !ok || row.KnowledgeID != chunk.KnowledgeID || row.Content != chunk.Content {
|
||||
if !ok || row.KnowledgeID != chunk.KnowledgeID {
|
||||
return errors.New("library index does not match database chunks")
|
||||
}
|
||||
if !searchHitMatches(document.Source, SearchIdentity{TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, KnowledgeID: row.KnowledgeID}) {
|
||||
return errors.New("cross-scope library index")
|
||||
}
|
||||
indexedChunks[row.ChunkID] = true
|
||||
if row.SourceID != "" && row.SourceID != row.ChunkID {
|
||||
question, exists := chunk.Questions[row.SourceID]
|
||||
if !exists || question != row.Content {
|
||||
return errors.New("library question index does not match persisted metadata")
|
||||
}
|
||||
if indexedQuestions[row.ChunkID] == nil {
|
||||
indexedQuestions[row.ChunkID] = map[string]bool{}
|
||||
}
|
||||
indexedQuestions[row.ChunkID][row.SourceID] = true
|
||||
} else {
|
||||
// Preserve the captured artifact; transient generation context is not
|
||||
// reconstructible from PG. This is not semantic acceptance or release approval.
|
||||
if strings.TrimSpace(row.Content) == "" {
|
||||
return errors.New("empty library index content")
|
||||
}
|
||||
indexedChunks[row.ChunkID] = true
|
||||
}
|
||||
}
|
||||
// v0.7.1 ChunkStatusIndexed is 2. One chunk can have several search
|
||||
// records, so compare identities rather than counts. Stored-only parent
|
||||
// chunks intentionally have no index and must not be rejected as missing.
|
||||
// Text ingestion also leaves indexed chunks at the legacy default status
|
||||
// zero. Without an archived no-index policy, absence is unverified, not
|
||||
// proof that indexing was disabled. Parent chunks are context-only.
|
||||
for id, chunk := range tables["chunks"] {
|
||||
for sourceID := range chunk.Questions {
|
||||
if !indexedQuestions[id][sourceID] {
|
||||
return errors.New("missing library generated question index")
|
||||
}
|
||||
}
|
||||
if chunk.ChunkStatus == 0 && chunk.ChunkType != "parent_text" && !indexedChunks[id] {
|
||||
return errors.New("unverified legacy library chunk index coverage")
|
||||
}
|
||||
if chunk.ChunkStatus == 2 && !indexedChunks[id] {
|
||||
return errors.New("missing indexed library chunk")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
func TestLibraryCandidateArtifactPolicyPreservesContextIndex(t *testing.T) {
|
||||
pg, es, objects := libraryCandidateFixture()
|
||||
es.Documents[0].Source = json.RawMessage(`{"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","chunk_id":"chunk-safe","source_id":"chunk-safe","content":"Title\nTransient heading\n\nchunk","embedding":[0.1,0.2]}`)
|
||||
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
|
||||
expected, err := json.Marshal(es.Documents)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := t.TempDir()
|
||||
if err = os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive, err := librarysnapshot.Open(root, 1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer archive.Close()
|
||||
contract := librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024, IndexMappingSHA256: es.MappingSHA256}
|
||||
id, err := ArchiveLibraryCandidate(context.Background(), archive, "internal", PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, contract, pg, es, objects, time.Now().UTC())
|
||||
if err != nil {
|
||||
t.Fatalf("artifact candidate rejected because generation cannot be reconstructed: %v", err)
|
||||
}
|
||||
m, err := archive.Load(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encoded, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var fields map[string]any
|
||||
if err = json.Unmarshal(encoded, &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fields["validation_policy"] != "artifact-acceptance-v1" {
|
||||
t.Fatal("candidate lacks explicit artifact acceptance policy")
|
||||
}
|
||||
found := false
|
||||
for _, part := range m.Parts {
|
||||
if part.Kind != "index" {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
r, e := archive.OpenPart(part)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got, e := io.ReadAll(r)
|
||||
r.Close()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if !bytes.Equal(got, expected) {
|
||||
t.Fatal("archived index content or vector rewritten")
|
||||
}
|
||||
}
|
||||
m.ValidationPolicy = "unsupported-policy"
|
||||
if _, err := archive.Seal(m); err == nil {
|
||||
t.Fatal("unknown policy accepted")
|
||||
}
|
||||
m.ValidationPolicy = ""
|
||||
legacyID, err := archive.Seal(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if legacyID == id {
|
||||
t.Fatal("validation policy was not bound into snapshot identity")
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("index missing")
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,11 @@ type LibraryCaptureRequest struct {
|
||||
Compatibility librarysnapshot.Compatibility
|
||||
CreatedAt time.Time
|
||||
MaxDocuments int
|
||||
// VerifyContract, when set, runs inside the stopped window immediately before
|
||||
// the export. The caller re-reads the source contract and returns an error if
|
||||
// it differs from Compatibility, so a model/index change between the
|
||||
// preflight read and the maintenance window cannot be sealed silently.
|
||||
VerifyContract func(context.Context) error
|
||||
}
|
||||
|
||||
// CaptureLibrary connects maintenance to the actual PG/PIT/object archive path.
|
||||
@@ -28,6 +33,9 @@ func CaptureLibrary(ctx context.Context, freeze *libraryfreeze.Coordinator, arch
|
||||
return libraryfreeze.Result{}, errors.New("invalid library capture configuration")
|
||||
}
|
||||
result, err := freeze.RunPrepared(ctx, req.JobID, func(ctx context.Context) error {
|
||||
if err := checkLibrarySourceSettlement(ctx, db); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := sourceReady(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -36,9 +44,17 @@ func CaptureLibrary(ctx context.Context, freeze *libraryfreeze.Coordinator, arch
|
||||
_, err := ExportLibrary(ctx, db, req.Identity)
|
||||
return err
|
||||
}, func(ctx context.Context) (string, error) {
|
||||
if err := checkLibrarySourceSettlement(ctx, db); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := sourceReady(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if req.VerifyContract != nil {
|
||||
if err := req.VerifyContract(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
pg, err := ExportLibrary(ctx, db, req.Identity)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -58,6 +74,9 @@ func CaptureLibrary(ctx context.Context, freeze *libraryfreeze.Coordinator, arch
|
||||
if err != nil {
|
||||
return libraryfreeze.Result{}, errors.New("captured library archive no longer verifies")
|
||||
}
|
||||
if saved.ValidationPolicy != librarysnapshot.ArtifactAcceptancePolicy {
|
||||
return libraryfreeze.Result{}, errors.New("library capture validation policy conflicts with existing job")
|
||||
}
|
||||
if saved.Scope != req.Scope || saved.TenantID != req.Identity.TenantID || saved.KnowledgeBaseID != req.Identity.KnowledgeBaseID || saved.Compatibility != req.Compatibility || !saved.CreatedAt.Equal(req.CreatedAt) {
|
||||
return libraryfreeze.Result{}, errors.New("library capture request conflicts with existing job")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// The writer is a real disposable Docker process, not a deployed WeKnora.
|
||||
// This tests capture orchestration, not production readiness or Wiki semantics.
|
||||
func TestLibraryCaptureIsolatedStack(t *testing.T) {
|
||||
dsn, base := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL"), os.Getenv("KG_LIBRARY_TEST_ELASTIC_URL")
|
||||
if dsn == "" || base == "" || os.Getenv("KG_FREEZE_DOCKER_ISOLATED") != "1" {
|
||||
t.Skip("requires isolated PG, ES and disposable Docker opt-in")
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
|
||||
t.Fatal("isolated database required")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
t.Fatal("open isolated PG")
|
||||
}
|
||||
defer db.Close()
|
||||
if _, err = db.Exec(ctx, libraryTestSchema); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(ctx, `ALTER TABLE resources ADD COLUMN provider text DEFAULT 's3', ADD COLUMN size bigint DEFAULT 8;
|
||||
ALTER TABLE wiki_pages ADD COLUMN status text DEFAULT 'published';
|
||||
ALTER TABLE wiki_page_issues ADD COLUMN status text DEFAULT 'open';`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token := make([]byte, 8)
|
||||
if _, err = rand.Read(token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := "kg-freeze-test-" + hex.EncodeToString(token)
|
||||
index := "kg_library_test_" + hex.EncodeToString(token)
|
||||
client := &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
request := func(method, path, body string, want int) {
|
||||
t.Helper()
|
||||
r, e := http.NewRequestWithContext(ctx, method, base+path, strings.NewReader(body))
|
||||
if e != nil {
|
||||
t.Fatal("fixture request")
|
||||
}
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
resp, e := client.Do(r)
|
||||
if e != nil {
|
||||
t.Fatal("fixture HTTP failed")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != want {
|
||||
t.Fatalf("fixture HTTP %d, expected %d", resp.StatusCode, want)
|
||||
}
|
||||
}
|
||||
request("PUT", "/"+index, `{"mappings":{"properties":{"tenant_id":{"type":"long"},"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"}}}}`, 200)
|
||||
defer func() { request("DELETE", "/"+index, "", 200); request("HEAD", "/"+index, "", 404) }()
|
||||
body := `{"tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","chunk_id":"chunk-safe","source_id":"chunk-safe","content":"Temporary context\nchunk","embedding":[0.1,0.2]}`
|
||||
request("PUT", "/"+index+"/_doc/chunk-safe?refresh=true", body, 201)
|
||||
search, err := NewSearchExporter(SearchExporterConfig{BaseURL: base, Index: index, PageSize: 1, HTTPClient: client})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mapping, err := search.inspectMapping(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
docker := func(args ...string) string {
|
||||
t.Helper()
|
||||
c, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
out, e := exec.CommandContext(c, "docker", append([]string{"--host", "unix:///var/run/docker.sock"}, args...)...).CombinedOutput()
|
||||
if e != nil {
|
||||
t.Fatalf("fixture Docker failed: %v", e)
|
||||
}
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
image := docker("image", "inspect", "busybox:1.36", "--format", "{{.Id}}")
|
||||
id := docker("create", "--name", source, "--network", "none", "--read-only", "--tmpfs", "/tmp:rw,noexec,nosuid,size=1m", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--memory", "32m", "--cpus", "0.1", "--label", "io.knowledge-governance.freeze-source="+source, "--label", "io.knowledge-governance.environment=test", "--label", "io.knowledge-governance.freeze-role=writer", "--health-cmd", "test -f /tmp/ready", "--health-interval", "1s", "--health-timeout", "1s", "--health-retries", "3", image, "sh", "-c", "trap 'exit 0' TERM; touch /tmp/ready; while :; do sleep 1 & wait $!; done")
|
||||
defer func() {
|
||||
docker("rm", "-f", id)
|
||||
if docker("ps", "-aq", "--filter", "label=io.knowledge-governance.freeze-source="+source) != "" {
|
||||
t.Error("Docker fixture remains")
|
||||
}
|
||||
}()
|
||||
controller, err := libraryfreeze.NewDockerController("/var/run/docker.sock", source, 10*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer controller.Close()
|
||||
if err = controller.Start(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
privateDir := func() string {
|
||||
t.Helper()
|
||||
p := t.TempDir()
|
||||
if e := os.Chmod(p, 0700); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return p
|
||||
}
|
||||
freeze, err := libraryfreeze.Open(privateDir(), source, controller)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer freeze.Close()
|
||||
archive, err := librarysnapshot.Open(privateDir(), 1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer archive.Close()
|
||||
objectPath := filepath.Join(privateDir(), "source.txt")
|
||||
if err = os.WriteFile(objectPath, []byte("resource"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
objects := &captureFileReader{path: objectPath}
|
||||
checks := 0
|
||||
ready := func(ctx context.Context) error {
|
||||
items, e := controller.Inventory(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if len(items) != 1 {
|
||||
return fmt.Errorf("unexpected fixture group")
|
||||
}
|
||||
checks++
|
||||
if items[0].Running != (checks%2 == 1) {
|
||||
return fmt.Errorf("wrong writer state at readiness boundary")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
req := LibraryCaptureRequest{JobID: "stack-capture", Scope: "internal", Identity: PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024, IndexMappingSHA256: mapping.digest}, CreatedAt: time.Now().UTC(), MaxDocuments: 100}
|
||||
result, err := CaptureLibrary(ctx, freeze, archive, db, search, objects, ready, req)
|
||||
if err != nil || result.State != "succeeded" {
|
||||
t.Fatalf("capture failed: %v state=%s", err, result.State)
|
||||
}
|
||||
assertHealthy := func() {
|
||||
t.Helper()
|
||||
items, e := controller.Inventory(ctx)
|
||||
if e != nil || len(items) != 1 || !items[0].Running || !items[0].Healthy {
|
||||
t.Fatal("fixture writer not restored healthy")
|
||||
}
|
||||
}
|
||||
assertHealthy()
|
||||
saved, err := archive.Load(result.SnapshotID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, part := range saved.Parts {
|
||||
r, e := archive.OpenPart(part)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
data, e := io.ReadAll(r)
|
||||
r.Close()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if strings.Contains(string(data), "private-session-marker") || strings.Contains(string(data), "other-scope") {
|
||||
t.Fatal("unrelated data leaked")
|
||||
}
|
||||
switch {
|
||||
case part.Kind == "index":
|
||||
var docs []SearchDocument
|
||||
if e = json.Unmarshal(data, &docs); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if len(docs) != 1 || !strings.Contains(string(docs[0].Source), "Temporary context") {
|
||||
t.Fatal("captured index lost")
|
||||
}
|
||||
seen["index"] = true
|
||||
case part.Kind == "resource":
|
||||
if string(data) != "resource" {
|
||||
t.Fatal("resource mismatch")
|
||||
}
|
||||
seen["object"] = true
|
||||
case part.Name == "wiki_pages":
|
||||
if !strings.Contains(string(data), "old-content") || !strings.Contains(string(data), "published") {
|
||||
t.Fatal("Wiki content/status lost")
|
||||
}
|
||||
seen["wiki"] = true
|
||||
}
|
||||
}
|
||||
if len(seen) != 3 || saved.ValidationPolicy != librarysnapshot.ArtifactAcceptancePolicy {
|
||||
t.Fatalf("incomplete captured evidence: %v", seen)
|
||||
}
|
||||
request("DELETE", "/"+index+"/_doc/chunk-safe?refresh=true", "", 200)
|
||||
req.JobID = "stack-missing-index"
|
||||
failed, err := CaptureLibrary(ctx, freeze, archive, db, search, objects, ready, req)
|
||||
if err == nil || failed.State == "succeeded" {
|
||||
t.Fatal("missing real index accepted")
|
||||
}
|
||||
assertHealthy()
|
||||
if err = os.Remove(objectPath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(ctx, `UPDATE knowledges SET parse_status='processing'; UPDATE wiki_pages SET content='later-content'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.JobID = "stack-capture"
|
||||
beforeCalls, beforeChecks := objects.calls, checks
|
||||
replay, err := CaptureLibrary(ctx, freeze, archive, db, search, objects, ready, req)
|
||||
if err != nil || replay.SnapshotID != result.SnapshotID || objects.calls != beforeCalls || checks != beforeChecks {
|
||||
t.Fatal("sealed replay touched changed source")
|
||||
}
|
||||
assertHealthy()
|
||||
if _, err = archive.Load(replay.SnapshotID); err != nil {
|
||||
t.Fatal("archive depended on deleted source object")
|
||||
}
|
||||
t.Log("real PG + ES + Docker capture and failed-capture restoration passed; source object removed, PG changed, ES document deleted; immutable replay verified")
|
||||
}
|
||||
|
||||
type captureFileReader struct {
|
||||
path string
|
||||
calls int
|
||||
}
|
||||
|
||||
func (r *captureFileReader) Open(_ context.Context, provider, key string) (io.ReadCloser, error) {
|
||||
r.calls++
|
||||
if provider != "s3" || key != "source.txt" {
|
||||
return nil, fmt.Errorf("unexpected synthetic resource")
|
||||
}
|
||||
return os.Open(r.path)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -14,11 +15,14 @@ import (
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
var errTestContractChanged = errors.New("source contract changed inside the maintenance window")
|
||||
|
||||
type captureWriter struct {
|
||||
running atomic.Bool
|
||||
db *libraryFixture
|
||||
late bool
|
||||
stops int
|
||||
running atomic.Bool
|
||||
db *libraryFixture
|
||||
late bool
|
||||
lateSource bool
|
||||
stops int
|
||||
}
|
||||
|
||||
func (c *captureWriter) Inventory(context.Context) ([]libraryfreeze.Service, error) {
|
||||
@@ -31,14 +35,99 @@ func (c *captureWriter) Stop(context.Context, string) error {
|
||||
if c.late {
|
||||
c.db.tx.pending = 1
|
||||
}
|
||||
if c.lateSource {
|
||||
c.db.tx.sourcePending = 1
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (c *captureWriter) Start(context.Context, string) error { c.running.Store(true); return nil }
|
||||
|
||||
// The contract is read before the window and must be re-checked inside it: a
|
||||
// model or mapping change between those two moments must abort, restore writers
|
||||
// and seal nothing.
|
||||
func TestLibraryCaptureRechecksContractInsideFrozenWindow(t *testing.T) {
|
||||
writer := &captureWriter{db: newLibraryFixture()}
|
||||
writer.running.Store(true)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/chunks/_mapping":
|
||||
fmt.Fprint(w, `{"chunks":{"mappings":{"properties":{"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"tenant_id":{"type":"long"}}}}}`)
|
||||
case "/chunks/_pit":
|
||||
fmt.Fprint(w, `{"id":"fixed-pit"}`)
|
||||
case "/_search":
|
||||
fmt.Fprint(w, `{"timed_out":false,"_shards":{"total":1,"successful":1,"failed":0},"hits":{"total":{"value":0,"relation":"eq"},"hits":[]}}`)
|
||||
case "/_pit":
|
||||
fmt.Fprint(w, `{"succeeded":true}`)
|
||||
default:
|
||||
http.Error(w, "unexpected", 400)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
search, err := NewSearchExporter(SearchExporterConfig{BaseURL: server.URL, Index: "chunks", PageSize: 10})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mapping, err := search.inspectMapping(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := t.TempDir()
|
||||
_ = os.Chmod(root, 0700)
|
||||
freeze, err := libraryfreeze.Open(root, "test-source", writer)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer freeze.Close()
|
||||
archiveRoot := t.TempDir()
|
||||
_ = os.Chmod(archiveRoot, 0700)
|
||||
archive, err := librarysnapshot.Open(archiveRoot, 1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer archive.Close()
|
||||
req := LibraryCaptureRequest{JobID: "contract-job", Scope: "internal",
|
||||
Identity: PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"},
|
||||
Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74,
|
||||
RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024,
|
||||
IndexMappingSHA256: mapping.digest},
|
||||
CreatedAt: time.Date(2026, 10, 28, 0, 0, 0, 0, time.UTC), MaxDocuments: 100}
|
||||
called := 0
|
||||
req.VerifyContract = func(context.Context) error {
|
||||
called++
|
||||
if writer.running.Load() {
|
||||
t.Error("contract re-check ran before writers stopped")
|
||||
}
|
||||
return errTestContractChanged
|
||||
}
|
||||
ready := func(context.Context) error { return nil }
|
||||
result, err := CaptureLibrary(context.Background(), freeze, archive, dbFixture(t, writer), search, &libraryCandidateReader{}, ready, req)
|
||||
if err == nil || result.State == "succeeded" || result.SnapshotID != "" {
|
||||
t.Fatalf("contract change was sealed: %+v %v", result, err)
|
||||
}
|
||||
if called != 1 {
|
||||
t.Fatalf("contract re-check called %d times", called)
|
||||
}
|
||||
if !writer.running.Load() {
|
||||
t.Fatal("writer left stopped after a contract abort")
|
||||
}
|
||||
if usage, usageErr := archive.Usage(); usageErr != nil || len(usage) != 0 {
|
||||
t.Fatalf("aborted capture left an artifact: %v %v", usage, usageErr)
|
||||
}
|
||||
}
|
||||
|
||||
func dbFixture(t *testing.T, writer *captureWriter) *libraryFixture {
|
||||
t.Helper()
|
||||
return writer.db
|
||||
}
|
||||
|
||||
func TestLibraryCaptureMaintenanceOwnsArchiveAndRestoresOnFailure(t *testing.T) {
|
||||
for _, mode := range []string{"success", "initial-busy", "late-pending", "search-failure"} {
|
||||
for _, mode := range []string{"success", "initial-busy", "late-pending", "search-failure", "other-library-busy", "other-library-late-pending"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
db := newLibraryFixture()
|
||||
writer := &captureWriter{db: db, late: mode == "late-pending"}
|
||||
writer := &captureWriter{db: db, late: mode == "late-pending", lateSource: mode == "other-library-late-pending"}
|
||||
if mode == "other-library-busy" {
|
||||
db.tx.sourcePending = 1
|
||||
}
|
||||
writer.running.Store(true)
|
||||
if mode == "initial-busy" {
|
||||
db.tx.pending = 1
|
||||
@@ -98,7 +187,7 @@ func TestLibraryCaptureMaintenanceOwnsArchiveAndRestoresOnFailure(t *testing.T)
|
||||
if err == nil {
|
||||
t.Fatal("invalid candidate succeeded")
|
||||
}
|
||||
if mode == "initial-busy" && writer.stops != 0 {
|
||||
if (mode == "initial-busy" || mode == "other-library-busy") && writer.stops != 0 {
|
||||
t.Fatal("busy source stopped")
|
||||
}
|
||||
return
|
||||
@@ -126,6 +215,24 @@ func TestLibraryCaptureMaintenanceOwnsArchiveAndRestoresOnFailure(t *testing.T)
|
||||
if got, err := CaptureLibrary(context.Background(), freeze, archive, db, search, &libraryCandidateReader{}, ready, req); err == nil || got.State == "succeeded" {
|
||||
t.Fatal("missing archive returned a successful candidate")
|
||||
}
|
||||
// Simulate a durable successful job created before the policy marker.
|
||||
// Replaying it must not silently upgrade its validation contract.
|
||||
saved.ValidationPolicy = ""
|
||||
legacyID, err := archive.Seal(saved)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.JobID = "legacy-capture-job"
|
||||
if _, err := freeze.RunPrepared(context.Background(), req.JobID, func(context.Context) error { return nil }, func(context.Context) (string, error) { return legacyID, nil }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stops, previousChecks := writer.stops, checks
|
||||
if got, err := CaptureLibrary(context.Background(), freeze, archive, db, search, &libraryCandidateReader{}, ready, req); err == nil || got.State == "succeeded" || got.SnapshotID != "" {
|
||||
t.Fatal("legacy policy replay silently upgraded to artifact acceptance")
|
||||
}
|
||||
if writer.stops != stops || checks != previousChecks {
|
||||
t.Fatal("policy conflict touched current source")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,38 @@ func TestLibraryExportIsolatedPostgres(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Run("whole source settlement", func(t *testing.T) {
|
||||
if err := checkLibrarySourceSettlement(ctx, db); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct{ name, change, restore string }{
|
||||
{"other tenant document", `UPDATE knowledges SET parse_status='processing' WHERE id='other-scope'`, `UPDATE knowledges SET parse_status='completed' WHERE id='other-scope'`},
|
||||
{"other library pending", `INSERT INTO task_pending_ops VALUES(20000,'wiki:ingest','knowledge_base','other-library')`, `DELETE FROM task_pending_ops`},
|
||||
{"deleted scope pending", `INSERT INTO task_pending_ops VALUES(20000,'wiki:retract','knowledge','physically-deleted-doc')`, `DELETE FROM task_pending_ops`},
|
||||
{"unknown scope pending", `INSERT INTO task_pending_ops VALUES(20000,'unknown:task','unknown','unknown')`, `DELETE FROM task_pending_ops`},
|
||||
{"other tenant dead letter", `INSERT INTO task_dead_letters VALUES(20000,'document:process','knowledge_base','other-library')`, `DELETE FROM task_dead_letters`},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := db.Exec(ctx, tc.change); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if _, err := db.Exec(ctx, tc.restore); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
if _, err := ExportLibrary(ctx, db, scope); err != nil {
|
||||
t.Fatalf("selected library unexpectedly busy: %v", err)
|
||||
}
|
||||
if err := checkLibrarySourceSettlement(ctx, db); err == nil {
|
||||
t.Fatal("source maintenance allowed while another scope has unfinished work")
|
||||
}
|
||||
})
|
||||
}
|
||||
if err := checkLibrarySourceSettlement(ctx, db); err != nil {
|
||||
t.Fatalf("settled source did not recover: %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("MVCC concurrent update", func(t *testing.T) {
|
||||
wrapper := libraryHookDB{pool: db, hook: func() {
|
||||
if _, err := db.Exec(ctx, `UPDATE wiki_pages SET content='new-content' WHERE id='wiki-safe'`); err != nil {
|
||||
|
||||
@@ -80,6 +80,7 @@ type libraryFixtureTx struct {
|
||||
pgx.Tx
|
||||
queries []string
|
||||
committed bool
|
||||
sourcePending int64
|
||||
pending, failed, unsettled int64
|
||||
graph bool
|
||||
queryError bool
|
||||
@@ -111,6 +112,10 @@ type libraryFixtureRow struct {
|
||||
|
||||
func (r libraryFixtureRow) Scan(dest ...any) error {
|
||||
switch {
|
||||
case strings.Contains(r.sql, "library-source-settlement"):
|
||||
*dest[0].(*int64) = r.d.unsettled
|
||||
*dest[1].(*int64) = r.d.pending + r.d.sourcePending
|
||||
*dest[2].(*int64) = r.d.failed
|
||||
case strings.Contains(r.sql, "schema_migrations"):
|
||||
*dest[0].(*int) = 74
|
||||
*dest[1].(*bool) = false
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Scheme A archives artifact bytes; these cases do not certify semantic quality.
|
||||
func TestLibraryCandidatePreservesArtifactContentWithoutReconstruction(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, kind, body, index string
|
||||
valid bool
|
||||
}{
|
||||
{"current title prefix", "text", "\n chunk \t", "Document title\nchunk", true},
|
||||
{"legacy raw body", "text", "\n chunk \t", "\n chunk \t", true},
|
||||
{"trimmed body", "text", "\n chunk \t", "chunk", true},
|
||||
{"wrong title", "text", "chunk", "Other title\nchunk", true},
|
||||
{"missing body", "text", "chunk", "Document title\n", true},
|
||||
{"different body", "text", "chunk", "Document title\nchanged", true},
|
||||
{"unverifiable context header", "text", "chunk", "Document title\nTransient heading\n\nchunk", true},
|
||||
{"nontext transform not assumed", "faq", "chunk", "Document title\nchunk", true},
|
||||
{"empty artifact content", "text", "chunk", " \n", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
pg, es, _ := libraryCandidateFixture()
|
||||
k, _ := json.Marshal(map[string]any{"id": "doc-safe", "tenant_id": 10000, "knowledge_base_id": "kb-safe", "title": " Document title\n"})
|
||||
c, _ := json.Marshal(map[string]any{"id": "chunk-safe", "tenant_id": 10000, "knowledge_base_id": "kb-safe", "knowledge_id": "doc-safe", "content": tc.body, "chunk_type": tc.kind, "status": 2})
|
||||
x, _ := json.Marshal(map[string]any{"knowledge_base_id": "kb-safe", "knowledge_id": "doc-safe", "chunk_id": "chunk-safe", "content": tc.index})
|
||||
pg.Tables[0] = newTableSnapshot("knowledges", []json.RawMessage{k})
|
||||
pg.Tables[1] = newTableSnapshot("chunks", []json.RawMessage{c})
|
||||
es.Documents[0].Source = x
|
||||
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
|
||||
err := validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es)
|
||||
if tc.valid && err != nil {
|
||||
t.Fatalf("valid indexed text refused: %v", err)
|
||||
}
|
||||
if !tc.valid && err == nil {
|
||||
t.Fatal("empty index content accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLibraryCandidateLegacyChunkIndexCoverage(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, kind string
|
||||
status int
|
||||
indexed, valid bool
|
||||
}{
|
||||
{"legacy text missing", "text", 0, false, false},
|
||||
{"legacy text indexed", "text", 0, true, true},
|
||||
{"legacy unknown type missing", "", 0, false, false},
|
||||
{"context parent not indexed", "parent_text", 0, false, true},
|
||||
{"stored parent not indexed", "parent_text", 1, false, true},
|
||||
{"indexed parent missing", "parent_text", 2, false, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
pg, es, _ := libraryCandidateFixture()
|
||||
raw, err := json.Marshal(map[string]any{"id": "chunk-safe", "tenant_id": 10000, "knowledge_base_id": "kb-safe", "knowledge_id": "doc-safe", "content": "chunk", "status": tc.status, "chunk_type": tc.kind})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pg.Tables[1] = newTableSnapshot("chunks", []json.RawMessage{raw})
|
||||
if !tc.indexed {
|
||||
es.Documents = nil
|
||||
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
|
||||
}
|
||||
err = validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es)
|
||||
if tc.valid && err != nil {
|
||||
t.Fatalf("valid chunk rejected: %v", err)
|
||||
}
|
||||
if !tc.valid && err == nil {
|
||||
t.Fatal("missing legacy index escaped completeness validation")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// Operator preflight surface. These wrappers expose the *same* checks used by
|
||||
// the capture path so an operator command can inspect a real source without
|
||||
// sealing an artifact, stopping a writer, or writing anything. They add no new
|
||||
// acceptance rule: a preflight which passes here is still only a candidate.
|
||||
//
|
||||
// Nothing here authorizes publication: artifact-acceptance-v1 still requires
|
||||
// snapshot-bound content, question/answer and performance acceptance, and
|
||||
// production release remains a separate, double-gated decision.
|
||||
|
||||
// LibrarySourceSettled reports whether the whole source database has finished
|
||||
// recorded processing. It is the identical query CaptureLibrary enforces before
|
||||
// and inside the maintenance window.
|
||||
func LibrarySourceSettled(ctx context.Context, db *pgxpool.Pool) error {
|
||||
return checkLibrarySourceSettlement(ctx, db)
|
||||
}
|
||||
|
||||
// ValidateLibraryCandidateForPreflight runs the candidate validator used by
|
||||
// ArchiveLibraryCandidate (identity, bidirectional content coverage, generated
|
||||
// question coverage, resources and digests) without archiving anything.
|
||||
func ValidateLibraryCandidateForPreflight(identity PostgresIdentity, pg PostgresSnapshot, es SearchSnapshot) error {
|
||||
return validateLibraryCandidate(identity, pg, es)
|
||||
}
|
||||
|
||||
// LibraryContentTables is the stable list of PostgreSQL tables a library
|
||||
// snapshot must contain, so an operator view does not hard-code table names.
|
||||
func LibraryContentTables() []string {
|
||||
names := make([]string, 0, len(libraryContentQueries)+1)
|
||||
names = append(names, "resources")
|
||||
for _, entry := range libraryContentQueries {
|
||||
names = append(names, entry.name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// LibrarySnapshotCompatibility is the archive-level compatibility contract.
|
||||
type LibrarySnapshotCompatibility = librarysnapshot.Compatibility
|
||||
@@ -0,0 +1,43 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLibraryCandidateGeneratedQuestionIndex(t *testing.T) {
|
||||
for _, mode := range []string{"complete", "wrong-id", "wrong-content", "missing-question", "missing-body", "foreign-source", "question-as-body"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
pg, es, _ := libraryCandidateFixture()
|
||||
pg.Tables[1] = newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"chunk","chunk_type":"text","status":0,"metadata":{"generated_questions":[{"id":"q1","question":"How does it work?"}]}}`)})
|
||||
questionID, content := "chunk-safe-q1", "How does it work?"
|
||||
if mode == "wrong-id" {
|
||||
questionID = "chunk-safe-q2"
|
||||
}
|
||||
if mode == "wrong-content" {
|
||||
content = "Different question"
|
||||
}
|
||||
if mode == "foreign-source" {
|
||||
questionID = "foreign-q1"
|
||||
}
|
||||
if mode == "question-as-body" {
|
||||
content = "chunk"
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"chunk_id": "chunk-safe", "knowledge_id": "doc-safe", "knowledge_base_id": "kb-safe", "source_id": questionID, "content": content})
|
||||
q := SearchDocument{ID: "question-index", Source: raw}
|
||||
if mode == "missing-body" {
|
||||
es.Documents = []SearchDocument{q}
|
||||
} else if mode != "missing-question" {
|
||||
es.Documents = append(es.Documents, q)
|
||||
}
|
||||
es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents)
|
||||
err := validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es)
|
||||
if mode == "complete" && err != nil {
|
||||
t.Fatalf("valid persisted question rejected: %v", err)
|
||||
}
|
||||
if mode != "complete" && err == nil {
|
||||
t.Fatal("incomplete or inconsistent question index accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// Live read-only diagnostic, not a cross-system frozen version or release gate.
|
||||
// Credentials are injected into this process only; never logged or persisted.
|
||||
func TestLibrarySourceReadOnlyDiagnostic(t *testing.T) {
|
||||
if os.Getenv("KG_LIBRARY_SOURCE_READONLY") != "1" {
|
||||
t.Skip("requires explicit read-only test-source credentials")
|
||||
}
|
||||
var config struct {
|
||||
DatabaseURL string
|
||||
TenantID uint64
|
||||
Scopes map[string]string
|
||||
Search SearchExporterConfig
|
||||
Object S3ObjectStoreConfig
|
||||
}
|
||||
if json.Unmarshal([]byte(os.Getenv("KG_LIBRARY_SOURCE_CONFIG")), &config) != nil || config.TenantID == 0 || len(config.Scopes) != 2 || config.Scopes["internal"] == "" || config.Scopes["external"] == "" {
|
||||
t.Fatal("invalid read-only diagnostic configuration")
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(config.DatabaseURL)
|
||||
if err != nil {
|
||||
t.Fatal("invalid diagnostic PG configuration")
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
|
||||
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "30000"
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel()
|
||||
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
t.Fatal("open diagnostic PG")
|
||||
}
|
||||
defer db.Close()
|
||||
var readOnly string
|
||||
if err = db.QueryRow(ctx, "SHOW default_transaction_read_only").Scan(&readOnly); err != nil || readOnly != "on" {
|
||||
t.Fatal("read-only session not enforced")
|
||||
}
|
||||
if err = checkLibrarySourceSettlement(ctx, db); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
search, err := NewSearchExporter(config.Search)
|
||||
if err != nil {
|
||||
t.Fatal("invalid diagnostic search configuration")
|
||||
}
|
||||
objects, err := NewS3ObjectStore(config.Object)
|
||||
if err != nil {
|
||||
t.Fatal("invalid diagnostic object configuration")
|
||||
}
|
||||
for _, scope := range []string{"internal", "external"} {
|
||||
t.Run(scope, func(t *testing.T) {
|
||||
identity := PostgresIdentity{TenantID: config.TenantID, KnowledgeBaseID: config.Scopes[scope]}
|
||||
pg, err := ExportLibrary(ctx, db, identity)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
es, err := search.ExportLibrary(ctx, SearchIdentity{TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID}, 100000)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = validateLibraryCandidate(identity, pg, es); err != nil {
|
||||
missing, deleted, wrongParent := 0, 0, 0
|
||||
reasons := map[string]int{}
|
||||
chunks := map[string]libraryRow{}
|
||||
for _, raw := range pg.Table("chunks").Rows {
|
||||
var r libraryRow
|
||||
if json.Unmarshal(raw, &r) != nil {
|
||||
t.Fatal("invalid diagnostic chunk")
|
||||
}
|
||||
chunks[r.ID] = r
|
||||
}
|
||||
for _, doc := range es.Documents {
|
||||
var r libraryRow
|
||||
if json.Unmarshal(doc.Source, &r) != nil {
|
||||
t.Fatal("invalid diagnostic index")
|
||||
}
|
||||
if c, ok := chunks[r.ChunkID]; ok {
|
||||
if r.KnowledgeID != c.KnowledgeID {
|
||||
wrongParent++
|
||||
}
|
||||
continue
|
||||
}
|
||||
var exists bool
|
||||
if e := db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chunks WHERE id=$1 AND tenant_id=$2)`, r.ChunkID, identity.TenantID).Scan(&exists); e != nil {
|
||||
t.Fatal("diagnostic relation query failed")
|
||||
}
|
||||
if exists {
|
||||
deleted++
|
||||
var reason string
|
||||
if e := db.QueryRow(ctx, `SELECT CASE WHEN c.deleted_at IS NOT NULL THEN 'chunk_soft_deleted' WHEN k.id IS NULL THEN 'parent_missing' WHEN k.deleted_at IS NOT NULL THEN 'parent_soft_deleted' ELSE 'scope_mismatch' END FROM chunks c LEFT JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id WHERE c.id=$1 AND c.tenant_id=$2`, r.ChunkID, identity.TenantID).Scan(&reason); e != nil {
|
||||
t.Fatal("diagnostic exclusion query failed")
|
||||
}
|
||||
reasons[reason]++
|
||||
} else {
|
||||
missing++
|
||||
}
|
||||
}
|
||||
t.Errorf("candidate rejected: %v; index_records=%d absent_chunk_records=%d existing_but_excluded_chunk_records=%d wrong_parent_records=%d", err, len(es.Documents), missing, deleted, wrongParent)
|
||||
t.Logf("index exclusion reasons: %v", reasons)
|
||||
probe, e := NewObjectExporter(objects, ObjectExporterLimits{MaxObjectBytes: 64 * 1024 * 1024, MaxTotalBytes: 256 * 1024 * 1024})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
assets, e := probe.Export(ctx, pg)
|
||||
if e != nil {
|
||||
t.Errorf("independent read-only resource probe: %v", e)
|
||||
} else {
|
||||
t.Logf("independent resource probe objects=%d bytes=%d", len(assets.Objects), assets.TotalBytes)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Logf("READONLY_DIAGNOSTIC frozen=false scope=%s documents=%d chunks=%d resources=%d wiki_pages=%d index_records=%d", scope, pg.Table("knowledges").RowCount, pg.Table("chunks").RowCount, pg.Table("resources").RowCount, pg.Table("wiki_pages").RowCount, len(es.Documents))
|
||||
root := t.TempDir()
|
||||
if err = os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive, err := librarysnapshot.Open(root, 64*1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer archive.Close()
|
||||
// The model name is an explicit diagnostic placeholder, not deployment compatibility evidence.
|
||||
compatibility := librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "diagnostic-unverified-model", EmbeddingDimension: 1024, IndexMappingSHA256: es.MappingSHA256}
|
||||
id, err := ArchiveLibraryCandidate(ctx, archive, scope, identity, compatibility, pg, es, objects, time.Now().UTC())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest, err := archive.Load(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var count, bytes int64
|
||||
for _, part := range manifest.Parts {
|
||||
if part.Kind == "resource" {
|
||||
count++
|
||||
bytes += part.Bytes
|
||||
}
|
||||
}
|
||||
if count != int64(pg.Table("resources").RowCount) {
|
||||
t.Fatal("resource archive coverage mismatch")
|
||||
}
|
||||
t.Logf("READONLY_DIAGNOSTIC frozen=false scope=%s archived_resources=%d resource_bytes=%d archive_verified=true compatibility_verified=false", scope, count, bytes)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// A maintenance window stops a shared writer, not a single KB. Check its entire
|
||||
// source database, including other tenants, deleted scopes and unknown task
|
||||
// scopes. Restricting this query to the selected KB can interrupt another job.
|
||||
// This only establishes recorded processing settlement, never Wiki semantics or
|
||||
// the absence of unrecorded/remote work; CaptureLibrary still requires the
|
||||
// deployment's ingress and background-worker readiness callback.
|
||||
func checkLibrarySourceSettlement(ctx context.Context, db librarySnapshotDB) error {
|
||||
tx, err := db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if err != nil {
|
||||
return errors.New("begin library source settlement")
|
||||
}
|
||||
defer tx.Rollback(context.WithoutCancel(ctx))
|
||||
var unsettled, pending, failed int64
|
||||
if err := tx.QueryRow(ctx, librarySourceSettlementSQL).Scan(&unsettled, &pending, &failed); err != nil {
|
||||
return errors.New("read library source settlement")
|
||||
}
|
||||
if unsettled != 0 || pending != 0 || failed != 0 {
|
||||
return errors.New("library source has unfinished or failed processing")
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return errors.New("commit library source settlement")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const librarySourceSettlementSQL = `SELECT /* library-source-settlement */
|
||||
(SELECT count(*) FROM knowledges WHERE deleted_at IS NULL AND (parse_status IS DISTINCT FROM 'completed' OR pending_subtasks_count IS NULL OR pending_subtasks_count<>0)),
|
||||
(SELECT count(*) FROM task_pending_ops),
|
||||
(SELECT count(*) FROM task_dead_letters)`
|
||||
Executable
BIN
Binary file not shown.
Executable
+56
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install/refresh the host-side library capture agent.
|
||||
#
|
||||
# The agent is the only component with the Docker socket and the source
|
||||
# credentials. It runs as this user (no root), listens on one 0600 unix socket and
|
||||
# executes the fixed capture command with the declaration below. Containers get
|
||||
# the socket path only.
|
||||
set -euo pipefail
|
||||
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
||||
UNIT_DIR="$HOME/.config/systemd/user"
|
||||
SOCKET_DIR="$HOME/.local/share/knowledge-governance/agent"
|
||||
mkdir -p "$UNIT_DIR" "$SOCKET_DIR"
|
||||
chmod 700 "$SOCKET_DIR"
|
||||
|
||||
echo "=== build libraryctl + libraryagent ==="
|
||||
(cd "$ROOT" && go build -o libraryctl ./cmd/libraryctl && go build -o libraryagent ./cmd/libraryagent)
|
||||
|
||||
echo "=== systemd user unit ==="
|
||||
cat > "$UNIT_DIR/knowledge-governance-library-agent.service" <<UNIT
|
||||
[Unit]
|
||||
Description=Knowledge governance whole-library capture agent (host-side execution boundary)
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=$ROOT
|
||||
ExecStart=$ROOT/libraryagent \\
|
||||
-socket $SOCKET_DIR/agent.sock \\
|
||||
-binary $ROOT/libraryctl \\
|
||||
-archive $HOME/.local/share/knowledge-governance/library \\
|
||||
-journal $HOME/.local/share/knowledge-governance/freeze \\
|
||||
-project weknora071full \\
|
||||
-writers app
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
UNIT
|
||||
|
||||
echo "=== enable + restart ==="
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable knowledge-governance-library-agent.service >/dev/null
|
||||
systemctl --user restart knowledge-governance-library-agent.service
|
||||
# Keep the agent running when no login session is open (it owns no privilege
|
||||
# beyond this account, but a stopped agent means the page cannot capture).
|
||||
loginctl enable-linger "$(id -un)" >/dev/null 2>&1 || echo " WARN: enable-linger failed; agent stops with the last session"
|
||||
|
||||
echo "=== read back ==="
|
||||
for _ in $(seq 1 30); do
|
||||
if [ -S "$SOCKET_DIR/agent.sock" ]; then break; fi
|
||||
sleep 0.2
|
||||
done
|
||||
[ -S "$SOCKET_DIR/agent.sock" ] || { echo "AGENT_SOCKET_MISSING"; exit 1; }
|
||||
stat -c '%A %n' "$SOCKET_DIR" "$SOCKET_DIR/agent.sock"
|
||||
systemctl --user is-active knowledge-governance-library-agent.service
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
# Whole-library capture entry point for the local WKNFull test stack.
|
||||
#
|
||||
# Every service of the Compose project is declared below: exactly one writer
|
||||
# (app) and a reason for each sibling which must NOT be stopped. ProjectController
|
||||
# refuses to run if the project gains a service that is not declared here, so a
|
||||
# new container cannot be silently left outside the maintenance window.
|
||||
#
|
||||
# Credentials are read from the running containers at call time and are never
|
||||
# printed. Nothing here writes to the source stack except SIGTERM/SIGSTART of the
|
||||
# declared writer.
|
||||
set -euo pipefail
|
||||
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
||||
BIN="${LIBRARYCTL_BIN:-$ROOT/libraryctl}"
|
||||
if [ ! -x "$BIN" ]; then
|
||||
echo "LIBRARYCTL_MISSING: build it with 'go build -o libraryctl ./cmd/libraryctl'" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Reasons must not contain commas: the flag is comma-separated.
|
||||
NON_WRITERS="frontend=UI only; no knowledge writes"
|
||||
NON_WRITERS+=",mcp=read-only MCP server"
|
||||
NON_WRITERS+=",dobotai-target=alpine placeholder; no knowledge writes"
|
||||
NON_WRITERS+=",docreader=parse RPC service; app persists parse output and settlement requires zero pending ops"
|
||||
NON_WRITERS+=",elasticsearch=search store; not an initiator"
|
||||
NON_WRITERS+=",postgres=database store; not an initiator"
|
||||
NON_WRITERS+=",redis=queue/cache store; not an initiator"
|
||||
NON_WRITERS+=",neo4j=graph store; not an initiator"
|
||||
NON_WRITERS+=",langfuse-web=LLM observability UI"
|
||||
NON_WRITERS+=",langfuse-worker=LLM observability worker; own storage"
|
||||
NON_WRITERS+=",langfuse-clickhouse=observability store"
|
||||
NON_WRITERS+=",langfuse-minio=observability object store"
|
||||
NON_WRITERS+=",langfuse-db-init=one-shot init; exited"
|
||||
NON_WRITERS+=",searxng=read-only search proxy"
|
||||
NON_WRITERS+=",searxng-init=one-shot init; exited"
|
||||
exec "$BIN" "$@" \
|
||||
-source-app WKNFull-app \
|
||||
-source-pg WKNFull-postgres \
|
||||
-source-es WKNFull-elasticsearch \
|
||||
-governance-pg knowledge-governance-p1-postgres-1 \
|
||||
-project weknora071full \
|
||||
-writers app \
|
||||
-non-writers "$NON_WRITERS"
|
||||
@@ -9,6 +9,16 @@
|
||||
"⚠️ 文件缺失或解析不了 ⇒ 门禁红:范围声明不出来时,不许默认放行。"
|
||||
],
|
||||
"optional": [
|
||||
{
|
||||
"package": "knowledge-governance/internal/releaseadapter/v071",
|
||||
"test": "TestLibrarySourceReadOnlyDiagnostic",
|
||||
"reason": "仅明确只读测试源授权及进程内凭据下运行;真实 PG、ES、OSS 不冻结,属于诊断而非一致性或生产放行;默认 CI 不注入测试源凭据,实际失败必须另行保留而非算通过"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/releaseadapter/v071",
|
||||
"test": "TestLibraryCaptureIsolatedStack",
|
||||
"reason": "显式隔离 PG、随机 ES 索引和无网络 Docker 夹具的联合捕获验收;默认 CI 不连接这些服务,本地另行运行并做索引覆盖变异反向验证;不代表真实 WeKnora 写入隔离或 Wiki 语义验收"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/libraryfreeze",
|
||||
"test": "TestFreezeIsolatedDocker",
|
||||
|
||||
@@ -4,6 +4,7 @@ import { DocumentWorkbench } from './DocumentWorkbench'
|
||||
import { SourceCatalogBrowser } from './SourceCatalogBrowser'
|
||||
import { WeKnoraMonitor } from './WeKnoraMonitor'
|
||||
import { VersionHistory } from './VersionHistory'
|
||||
import { LibraryVersions } from './LibraryVersions'
|
||||
import { QAOperations } from './QAOperations'
|
||||
import { SourceLinkManager } from './SourceLinkManager'
|
||||
import { SystemSettings } from './SystemSettings'
|
||||
@@ -62,6 +63,7 @@ const modules: ReadonlyArray<{ id: ModuleId; label: string; icon: string }> = [
|
||||
{ id: 'tasks', label: '解析监控', icon: '↻' },
|
||||
{ id: 'qaops', label: '问答运营', icon: '▤' },
|
||||
{ id: 'releases', label: '发布管理', icon: '⇧' },
|
||||
{ id: 'library', label: '整库版本', icon: '▦' },
|
||||
{ id: 'settings', label: '系统设置', icon: '⚙' },
|
||||
{ id: 'versions', label: '版本记录', icon: '⌥' },
|
||||
]
|
||||
@@ -2970,6 +2972,8 @@ export default function App() {
|
||||
<SystemSettings />
|
||||
) : workspace.activeTab === 'knowledge' ? (
|
||||
<DocumentWorkbench mode="attention" connections={connectionPage.items} />
|
||||
) : workspace.activeTab === 'library' ? (
|
||||
<LibraryVersions />
|
||||
) : workspace.activeTab === 'versions' ? (
|
||||
<VersionHistory />
|
||||
) : workspace.activeTab === 'qaops' ? (
|
||||
|
||||
@@ -0,0 +1,387 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
enqueueLibraryCapture,
|
||||
fetchLibraryCaptures,
|
||||
fetchLibrarySnapshots,
|
||||
formatBytes,
|
||||
scopeLabel,
|
||||
type LibraryCaptureJob,
|
||||
type LibrarySnapshot,
|
||||
type LibrarySnapshotList,
|
||||
} from './librarySnapshots'
|
||||
import { useOptionalAuth } from './auth'
|
||||
import './libraryVersions.css'
|
||||
|
||||
// 「整库版本」页:只读展示已封存的整库候选产物(对内/对外各一份最新)。
|
||||
// 页面不提供封存按钮:封存要停真实写入者并读来源凭据,只能在目标主机用
|
||||
// scripts/library-capture.sh 执行。通过完整性检查 != 已发布,授权仍走发布管理。
|
||||
const stamp = (value: string) =>
|
||||
value && Number.isFinite(new Date(value).getTime())
|
||||
? new Date(value).toLocaleString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
})
|
||||
: '—'
|
||||
|
||||
const metric = (snapshot: LibrarySnapshot, key: string) => String(snapshot.totals[key] ?? 0)
|
||||
|
||||
const jobStateLabel: Record<string, string> = {
|
||||
pending: '待执行',
|
||||
running: '执行中',
|
||||
retry: '重试中',
|
||||
completed: '已完成',
|
||||
failed: '失败',
|
||||
}
|
||||
|
||||
export function LibraryVersions() {
|
||||
const auth = useOptionalAuth()
|
||||
const [page, setPage] = useState<LibrarySnapshotList | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [expanded, setExpanded] = useState<string | null>(null)
|
||||
const [scopeFilter, setScopeFilter] = useState<'all' | 'internal' | 'external'>('all')
|
||||
const [jobs, setJobs] = useState<LibraryCaptureJob[]>([])
|
||||
const [pendingScope, setPendingScope] = useState<string | null>(null)
|
||||
const [notice, setNotice] = useState<string | null>(null)
|
||||
|
||||
const load = useCallback(async (signal?: AbortSignal) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const result = await fetchLibrarySnapshots(signal)
|
||||
setPage(result)
|
||||
setError(null)
|
||||
} catch (loadError) {
|
||||
if ((loadError as Error).name === 'AbortError') return
|
||||
setError(loadError instanceof Error ? loadError.message : '加载整库版本失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
void load(controller.signal)
|
||||
return () => controller.abort()
|
||||
}, [load])
|
||||
|
||||
const refreshJobs = useCallback(async (signal?: AbortSignal) => {
|
||||
const items = await fetchLibraryCaptures(signal)
|
||||
setJobs(items)
|
||||
return items
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
void refreshJobs(controller.signal).catch(() => undefined)
|
||||
return () => controller.abort()
|
||||
}, [refreshJobs])
|
||||
|
||||
// A capture runs in a maintenance window (seconds), so a short poll is enough
|
||||
// to show the real queue state and to pick up the new sealed version.
|
||||
const active = jobs.some((job) => job.state === 'pending' || job.state === 'running' || job.state === 'retry')
|
||||
useEffect(() => {
|
||||
if (!active) return
|
||||
const timer = window.setInterval(() => {
|
||||
void refreshJobs()
|
||||
.then((items) => {
|
||||
if (!items.some((job) => job.state === 'pending' || job.state === 'running' || job.state === 'retry')) {
|
||||
void load()
|
||||
}
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}, 3000)
|
||||
return () => window.clearInterval(timer)
|
||||
}, [active, refreshJobs, load])
|
||||
|
||||
const canCapture = (auth?.identity?.role === 'engineer' || auth?.identity?.role === 'admin') && page?.capture_available === true
|
||||
|
||||
const startCapture = async (scope: string) => {
|
||||
setPendingScope(scope)
|
||||
setNotice(null)
|
||||
try {
|
||||
const accepted = await enqueueLibraryCapture(scope)
|
||||
setNotice(`已投递封存作业:${scopeLabel(scope)} · ${accepted.capture_job}(等待主机侧执行)`)
|
||||
await refreshJobs()
|
||||
} catch (captureError) {
|
||||
setNotice(captureError instanceof Error ? captureError.message : '发起封存失败')
|
||||
} finally {
|
||||
setPendingScope(null)
|
||||
}
|
||||
}
|
||||
|
||||
const snapshots = page?.snapshots ?? []
|
||||
const latestByScope = useMemo(() => {
|
||||
const map: Record<string, LibrarySnapshot | undefined> = {}
|
||||
for (const snapshot of snapshots) {
|
||||
if (!map[snapshot.scope]) map[snapshot.scope] = snapshot
|
||||
}
|
||||
return map
|
||||
}, [snapshots])
|
||||
const visible = snapshots.filter((snapshot) => scopeFilter === 'all' || snapshot.scope === scopeFilter)
|
||||
|
||||
return (
|
||||
<section className="library-versions" aria-label="整库版本">
|
||||
<header className="library-versions-header">
|
||||
<div>
|
||||
<h2>整库版本</h2>
|
||||
<p className="library-versions-sub">
|
||||
每个条目是一份<b>完整封存</b>的整库候选:数据库十表、原始索引正文与向量、对象资源与 Wiki 快照,
|
||||
带逐项摘要与兼容契约。封存期间真实写入者被停住,完成后已恢复。
|
||||
</p>
|
||||
</div>
|
||||
<div className="library-versions-actions">
|
||||
<span
|
||||
className="library-versions-usage"
|
||||
title="跨版本去重后被版本引用的内容字节;不是磁盘占用,也不是可回收空间"
|
||||
>
|
||||
共 {snapshots.length} 份 · 被引用的去重内容 {formatBytes(page?.content_bytes ?? 0)}
|
||||
</span>
|
||||
<button type="button" onClick={() => void load()} disabled={loading}>
|
||||
{loading ? '刷新中…' : '刷新'}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{page && !page.available ? (
|
||||
<div className="library-versions-blocked">
|
||||
<strong>未接线</strong>
|
||||
<p>{page.reason || '归档根未配置'}</p>
|
||||
</div>
|
||||
) : null}
|
||||
{error ? (
|
||||
<div className="library-versions-blocked">
|
||||
<strong>读取失败</strong>
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{page?.available ? (
|
||||
<>
|
||||
<div className="library-versions-scopes">
|
||||
{(['internal', 'external'] as const).map((scope) => {
|
||||
const latest = latestByScope[scope]
|
||||
return (
|
||||
<article key={scope} className={`library-scope-card ${latest ? '' : 'empty'}`}>
|
||||
<header>
|
||||
<h3>{scopeLabel(scope)}</h3>
|
||||
<span className="library-scope-state">{latest ? '已封存' : '尚无封存'}</span>
|
||||
</header>
|
||||
{latest ? (
|
||||
<>
|
||||
<p className="library-scope-time">封存于 {stamp(latest.created_at)}</p>
|
||||
<dl className="library-scope-metrics">
|
||||
<div>
|
||||
<dt>文档</dt>
|
||||
<dd>{metric(latest, 'documents')}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>分块</dt>
|
||||
<dd>{metric(latest, 'chunks')}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>索引</dt>
|
||||
<dd>{metric(latest, 'index_documents')}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>资源</dt>
|
||||
<dd>{metric(latest, 'resources')}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Wiki 页</dt>
|
||||
<dd>{metric(latest, 'wiki_pages')}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>体积</dt>
|
||||
<dd>{formatBytes(latest.logical_bytes)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p className="library-scope-id">
|
||||
快照 <code>{latest.snapshot_id.slice(0, 16)}</code>
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="library-scope-hint">该库还没有封存产物。</p>
|
||||
)}
|
||||
<div className="library-scope-actions">
|
||||
{page?.capture_available ? (
|
||||
canCapture ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void startCapture(scope)}
|
||||
disabled={
|
||||
pendingScope === scope ||
|
||||
jobs.some(
|
||||
(job) =>
|
||||
job.scope === scope &&
|
||||
(job.state === 'pending' || job.state === 'running' || job.state === 'retry')
|
||||
)
|
||||
}
|
||||
>
|
||||
{pendingScope === scope ? '投递中…' : `发起${scopeLabel(scope)}封存`}
|
||||
</button>
|
||||
) : (
|
||||
<span>发起封存需要知识工程师及以上权限</span>
|
||||
)
|
||||
) : (
|
||||
<span>{page?.capture_reason}</span>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="library-versions-toolbar">
|
||||
<div className="library-versions-filters" role="group" aria-label="按范围筛选">
|
||||
{(
|
||||
[
|
||||
{ id: 'all', label: '全部' },
|
||||
{ id: 'internal', label: '对内' },
|
||||
{ id: 'external', label: '对外' },
|
||||
] as const
|
||||
).map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
className={scopeFilter === item.id ? 'active' : ''}
|
||||
onClick={() => setScopeFilter(item.id)}
|
||||
>
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span className="library-versions-note">{page.capture_note}</span>
|
||||
</div>
|
||||
|
||||
<div className="library-versions-toolbar library-versions-accounting">
|
||||
<span>
|
||||
磁盘事实(不是可回收空间):清单 {formatBytes(page.manifest_file_bytes)} · blob 文件{' '}
|
||||
{formatBytes(page.blob_file_bytes)}(实际分配 {formatBytes(page.blob_allocated_bytes)})· 未被任何版本引用{' '}
|
||||
{page.unreferenced_blobs} 个 / {formatBytes(page.unreferenced_bytes)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{visible.length === 0 ? (
|
||||
<p className="library-versions-empty">还没有封存产物。</p>
|
||||
) : (
|
||||
<table className="library-versions-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>封存时间</th>
|
||||
<th>范围</th>
|
||||
<th>文档</th>
|
||||
<th>分块</th>
|
||||
<th>索引</th>
|
||||
<th>资源</th>
|
||||
<th>Wiki</th>
|
||||
<th>体积</th>
|
||||
<th>模型 / 维度</th>
|
||||
<th>快照</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{visible.map((snapshot) => (
|
||||
<tr key={snapshot.snapshot_id}>
|
||||
<td>{stamp(snapshot.created_at)}</td>
|
||||
<td>{scopeLabel(snapshot.scope)}</td>
|
||||
<td>{metric(snapshot, 'documents')}</td>
|
||||
<td>{metric(snapshot, 'chunks')}</td>
|
||||
<td>{metric(snapshot, 'index_documents')}</td>
|
||||
<td>{metric(snapshot, 'resources')}</td>
|
||||
<td>{metric(snapshot, 'wiki_pages')}</td>
|
||||
<td
|
||||
title={`本版逻辑 ${snapshot.logical_bytes} 字节 · 本版内去重 ${snapshot.unique_bytes} 字节(跨版本去重见上方合计)`}
|
||||
>
|
||||
{formatBytes(snapshot.logical_bytes)}
|
||||
</td>
|
||||
<td>
|
||||
{snapshot.compatibility.embedding_model || '—'} / {snapshot.compatibility.embedding_dimension}
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="library-snapshot-toggle"
|
||||
onClick={() =>
|
||||
setExpanded(expanded === snapshot.snapshot_id ? null : snapshot.snapshot_id)
|
||||
}
|
||||
aria-expanded={expanded === snapshot.snapshot_id}
|
||||
>
|
||||
<code>{snapshot.snapshot_id.slice(0, 12)}</code>
|
||||
{expanded === snapshot.snapshot_id ? ' 收起' : ' 分项'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
|
||||
{notice ? <p className="library-capture-notice">{notice}</p> : null}
|
||||
|
||||
{jobs.length > 0 ? (
|
||||
<div className="library-capture-jobs">
|
||||
<h3>封存作业</h3>
|
||||
<table className="library-versions-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>投递时间</th>
|
||||
<th>范围</th>
|
||||
<th>状态</th>
|
||||
<th>作业号</th>
|
||||
<th>发起人</th>
|
||||
<th>最后错误</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{jobs.map((job) => (
|
||||
<tr key={job.job_id}>
|
||||
<td>{stamp(job.created_at)}</td>
|
||||
<td>{scopeLabel(job.scope)}</td>
|
||||
<td>{jobStateLabel[job.state] ?? job.state}</td>
|
||||
<td>
|
||||
<code>{job.capture_job.slice(0, 24)}</code>
|
||||
</td>
|
||||
<td>{job.requested_by || '—'}</td>
|
||||
<td className="library-capture-error">{job.last_error || '—'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{visible
|
||||
.filter((snapshot) => snapshot.snapshot_id === expanded)
|
||||
.map((snapshot) => (
|
||||
<div key={snapshot.snapshot_id} className="library-snapshot-parts">
|
||||
<header>
|
||||
<strong>{scopeLabel(snapshot.scope)} · {snapshot.snapshot_id}</strong>
|
||||
<span>
|
||||
策略 {snapshot.validation_policy || '—'} · WeKnora {snapshot.compatibility.weknora_version} ·
|
||||
schema {snapshot.compatibility.schema_version} · 映射{' '}
|
||||
{snapshot.compatibility.index_mapping_sha256.slice(0, 12)}
|
||||
</span>
|
||||
</header>
|
||||
<ul>
|
||||
{snapshot.parts.map((part) => (
|
||||
<li key={`${part.kind}-${part.name}`}>
|
||||
<span className="library-part-kind">{part.kind}</span>
|
||||
<span className="library-part-name">{part.name}</span>
|
||||
<span>{part.count} 项</span>
|
||||
<span>{formatBytes(part.bytes)}</span>
|
||||
<code title={part.sha256}>{part.sha256.slice(0, 12)}</code>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// 「整库版本」页的只读客户端:列已经封存的整库候选产物。
|
||||
//
|
||||
// 这里没有任何写操作:封存需要维护窗口(停真实写入者)与来源凭据,只能由运维
|
||||
// 命令在目标主机执行。页面只负责如实展示已封存的内容,不提供"开始同步"这类
|
||||
// 没接线的假按钮。
|
||||
|
||||
export interface LibrarySnapshotPart {
|
||||
kind: string
|
||||
name: string
|
||||
sha256: string
|
||||
count: number
|
||||
bytes: number
|
||||
}
|
||||
|
||||
export interface LibraryCompatibility {
|
||||
weknora_version: string
|
||||
schema_version: number
|
||||
retriever_engine: string
|
||||
embedding_model: string
|
||||
embedding_dimension: number
|
||||
index_mapping_sha256: string
|
||||
}
|
||||
|
||||
export interface LibrarySnapshot {
|
||||
snapshot_id: string
|
||||
scope: string
|
||||
knowledge_base_id: string
|
||||
tenant_id: number
|
||||
created_at: string
|
||||
validation_policy: string
|
||||
format: string
|
||||
compatibility: LibraryCompatibility
|
||||
parts: LibrarySnapshotPart[]
|
||||
logical_bytes: number
|
||||
unique_bytes: number
|
||||
shared_bytes: number
|
||||
totals: Record<string, number>
|
||||
}
|
||||
|
||||
export interface LibraryCaptureJob {
|
||||
job_id: string
|
||||
capture_job: string
|
||||
scope: string
|
||||
state: string
|
||||
attempt: number
|
||||
last_error: string
|
||||
requested_by: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface LibraryCaptureAccepted {
|
||||
job_id: string
|
||||
capture_job: string
|
||||
scope: string
|
||||
state: string
|
||||
}
|
||||
|
||||
export interface LibrarySnapshotList {
|
||||
available: boolean
|
||||
reason: string
|
||||
archive_root: string
|
||||
snapshots: LibrarySnapshot[]
|
||||
// 归档级口径:content_bytes 是跨版本去重后、被版本引用的内容字节;
|
||||
// 其余字段是文件系统事实,都不是可回收空间。
|
||||
versions: number
|
||||
content_bytes: number
|
||||
blob_file_bytes: number
|
||||
blob_allocated_bytes: number
|
||||
unreferenced_blobs: number
|
||||
unreferenced_bytes: number
|
||||
manifest_file_bytes: number
|
||||
manifest_allocated_bytes: number
|
||||
capture_note: string
|
||||
capture_available: boolean
|
||||
capture_reason: string
|
||||
}
|
||||
|
||||
const record = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
const text = (value: unknown) => (typeof value === 'string' ? value : '')
|
||||
const num = (value: unknown) => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
|
||||
const bool = (value: unknown) => value === true
|
||||
|
||||
function parsePart(raw: unknown): LibrarySnapshotPart | null {
|
||||
if (!record(raw)) return null
|
||||
const kind = text(raw.kind)
|
||||
const name = text(raw.name)
|
||||
if (!kind || !name) return null
|
||||
return { kind, name, sha256: text(raw.sha256), count: num(raw.count), bytes: num(raw.bytes) }
|
||||
}
|
||||
|
||||
function parseSnapshot(raw: unknown): LibrarySnapshot | null {
|
||||
if (!record(raw)) return null
|
||||
const snapshotID = text(raw.snapshot_id)
|
||||
if (!snapshotID) return null
|
||||
const compatibility = record(raw.compatibility) ? raw.compatibility : {}
|
||||
const totals: Record<string, number> = {}
|
||||
if (record(raw.totals)) {
|
||||
for (const [key, value] of Object.entries(raw.totals)) totals[key] = num(value)
|
||||
}
|
||||
return {
|
||||
snapshot_id: snapshotID,
|
||||
scope: text(raw.scope),
|
||||
knowledge_base_id: text(raw.knowledge_base_id),
|
||||
tenant_id: num(raw.tenant_id),
|
||||
created_at: text(raw.created_at),
|
||||
validation_policy: text(raw.validation_policy),
|
||||
format: text(raw.format),
|
||||
compatibility: {
|
||||
weknora_version: text(compatibility.weknora_version),
|
||||
schema_version: num(compatibility.schema_version),
|
||||
retriever_engine: text(compatibility.retriever_engine),
|
||||
embedding_model: text(compatibility.embedding_model),
|
||||
embedding_dimension: num(compatibility.embedding_dimension),
|
||||
index_mapping_sha256: text(compatibility.index_mapping_sha256),
|
||||
},
|
||||
parts: Array.isArray(raw.parts)
|
||||
? raw.parts.map(parsePart).filter((item): item is LibrarySnapshotPart => item !== null)
|
||||
: [],
|
||||
logical_bytes: num(raw.logical_bytes),
|
||||
unique_bytes: num(raw.unique_bytes),
|
||||
shared_bytes: num(raw.shared_bytes),
|
||||
totals,
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchLibrarySnapshots(signal?: AbortSignal): Promise<LibrarySnapshotList> {
|
||||
const response = await fetch('/api/v1/library/snapshots', {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal,
|
||||
})
|
||||
const value = (await response.json().catch(() => null)) as unknown
|
||||
if (!response.ok && !record(value)) {
|
||||
throw new Error(`加载整库版本失败(HTTP ${response.status})`)
|
||||
}
|
||||
if (!record(value)) throw new Error('整库版本响应无效')
|
||||
const snapshots = Array.isArray(value.snapshots)
|
||||
? value.snapshots.map(parseSnapshot).filter((item): item is LibrarySnapshot => item !== null)
|
||||
: []
|
||||
return {
|
||||
available: bool(value.available),
|
||||
reason: text(value.reason),
|
||||
archive_root: text(value.archive_root),
|
||||
snapshots,
|
||||
versions: num(value.versions),
|
||||
content_bytes: num(value.content_bytes),
|
||||
blob_file_bytes: num(value.blob_file_bytes),
|
||||
blob_allocated_bytes: num(value.blob_allocated_bytes),
|
||||
unreferenced_blobs: num(value.unreferenced_blobs),
|
||||
unreferenced_bytes: num(value.unreferenced_bytes),
|
||||
manifest_file_bytes: num(value.manifest_file_bytes),
|
||||
manifest_allocated_bytes: num(value.manifest_allocated_bytes),
|
||||
capture_note: text(value.capture_note),
|
||||
capture_available: bool(value.capture_available),
|
||||
capture_reason: text(value.capture_reason),
|
||||
}
|
||||
}
|
||||
|
||||
// 页面发起的封存只投递作业;停写入者、导出与恢复都在主机侧 agent 执行。
|
||||
export async function enqueueLibraryCapture(scope: string): Promise<LibraryCaptureAccepted> {
|
||||
const response = await fetch('/api/v1/library/captures', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ scope }),
|
||||
})
|
||||
const value = (await response.json().catch(() => null)) as unknown
|
||||
if (!response.ok) {
|
||||
if (response.status === 403) throw new Error('只有知识工程师及以上可以发起封存。')
|
||||
if (response.status === 503 && record(value)) {
|
||||
throw new Error(text(value.reason) || '主机侧封存 agent 未接线')
|
||||
}
|
||||
throw new Error(`发起封存失败(HTTP ${response.status})`)
|
||||
}
|
||||
if (!record(value)) throw new Error('封存作业响应无效')
|
||||
return {
|
||||
job_id: text(value.job_id),
|
||||
capture_job: text(value.capture_job),
|
||||
scope: text(value.scope),
|
||||
state: text(value.state),
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchLibraryCaptures(signal?: AbortSignal): Promise<LibraryCaptureJob[]> {
|
||||
const response = await fetch('/api/v1/library/captures', {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal,
|
||||
})
|
||||
const value = (await response.json().catch(() => null)) as unknown
|
||||
if (!response.ok || !record(value) || !Array.isArray(value.jobs)) return []
|
||||
return value.jobs.filter(record).map((job) => ({
|
||||
job_id: text(job.job_id),
|
||||
capture_job: text(job.capture_job),
|
||||
scope: text(job.scope),
|
||||
state: text(job.state),
|
||||
attempt: num(job.attempt),
|
||||
last_error: text(job.last_error),
|
||||
requested_by: text(job.requested_by),
|
||||
created_at: text(job.created_at),
|
||||
updated_at: text(job.updated_at),
|
||||
}))
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
let index = 0
|
||||
let value = bytes
|
||||
while (value >= 1024 && index < units.length - 1) {
|
||||
value /= 1024
|
||||
index += 1
|
||||
}
|
||||
return `${value >= 10 || index === 0 ? value.toFixed(0) : value.toFixed(1)} ${units[index]}`
|
||||
}
|
||||
|
||||
export function scopeLabel(scope: string): string {
|
||||
if (scope === 'internal') return '对内'
|
||||
if (scope === 'external') return '对外'
|
||||
return scope || '未知范围'
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
/* Whole-library versions: scope cards first, then a compact sealed-artifact table. */
|
||||
.library-versions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
min-width: 0;
|
||||
padding: 24px;
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.library-versions-header,
|
||||
.library-versions-toolbar,
|
||||
.library-snapshot-parts,
|
||||
.library-scope-card {
|
||||
background: var(--bg-panel, #fff);
|
||||
border: 1px solid var(--border-base, #e2e8f0);
|
||||
border-radius: 10px;
|
||||
padding: 20px;
|
||||
min-width: 0;
|
||||
}
|
||||
.library-versions-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.library-versions h2 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 22px;
|
||||
}
|
||||
.library-versions-sub {
|
||||
margin: 0;
|
||||
max-width: 68ch;
|
||||
color: var(--ink-mute, #64748b);
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.library-versions-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.library-versions-usage {
|
||||
font-size: 13px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.library-versions-actions button,
|
||||
.library-versions-filters button {
|
||||
padding: 7px 14px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-base, #e2e8f0);
|
||||
background: var(--bg-panel, #fff);
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.library-versions-actions button:disabled {
|
||||
cursor: progress;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.library-versions-blocked {
|
||||
border: 1px solid #f3c2b8;
|
||||
background: #fff6f3;
|
||||
border-radius: 10px;
|
||||
padding: 16px 20px;
|
||||
}
|
||||
.library-versions-blocked strong {
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
color: #a03a1e;
|
||||
}
|
||||
.library-versions-blocked p {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
color: #7c2d12;
|
||||
}
|
||||
.library-versions-scopes {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
.library-scope-card header {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.library-scope-card h3 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
}
|
||||
.library-scope-state {
|
||||
font-size: 12px;
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
background: #ecfdf5;
|
||||
color: #047857;
|
||||
border: 1px solid #a7f3d0;
|
||||
}
|
||||
.library-scope-card.empty .library-scope-state {
|
||||
background: #f8fafc;
|
||||
color: #64748b;
|
||||
border-color: #e2e8f0;
|
||||
}
|
||||
.library-scope-time {
|
||||
margin: 8px 0 14px;
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
}
|
||||
.library-scope-metrics {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
.library-scope-metrics div {
|
||||
border: 1px solid var(--border-base, #e2e8f0);
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
}
|
||||
.library-scope-metrics dt {
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
}
|
||||
.library-scope-metrics dd {
|
||||
margin: 2px 0 0;
|
||||
font-size: 18px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.library-scope-id,
|
||||
.library-scope-hint {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.library-scope-hint code,
|
||||
.library-scope-id code {
|
||||
font-size: 12px;
|
||||
background: #f1f5f9;
|
||||
border-radius: 5px;
|
||||
padding: 1px 6px;
|
||||
}
|
||||
.library-versions-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 12px 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.library-versions-filters {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
.library-versions-filters button.active {
|
||||
border-color: #2563eb;
|
||||
color: #1d4ed8;
|
||||
background: #eff6ff;
|
||||
}
|
||||
.library-versions-note {
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
max-width: 70ch;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.library-scope-actions {
|
||||
margin-top: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
}
|
||||
.library-scope-actions button {
|
||||
padding: 7px 14px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #2563eb;
|
||||
background: #eff6ff;
|
||||
color: #1d4ed8;
|
||||
cursor: pointer;
|
||||
}
|
||||
.library-scope-actions button:disabled {
|
||||
cursor: progress;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.library-capture-notice {
|
||||
margin: 0;
|
||||
padding: 10px 14px;
|
||||
border-radius: 8px;
|
||||
background: #eff6ff;
|
||||
border: 1px solid #bfdbfe;
|
||||
color: #1d4ed8;
|
||||
font-size: 13px;
|
||||
}
|
||||
.library-capture-jobs {
|
||||
background: var(--bg-panel, #fff);
|
||||
border: 1px solid var(--border-base, #e2e8f0);
|
||||
border-radius: 10px;
|
||||
padding: 16px 20px;
|
||||
}
|
||||
.library-capture-jobs h3 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 15px;
|
||||
}
|
||||
.library-capture-error {
|
||||
max-width: 360px;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: normal;
|
||||
}
|
||||
.library-versions-accounting {
|
||||
justify-content: flex-start;
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
line-height: 1.6;
|
||||
}
|
||||
.library-versions-empty {
|
||||
margin: 0;
|
||||
padding: 24px;
|
||||
border: 1px dashed var(--border-base, #e2e8f0);
|
||||
border-radius: 10px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
font-size: 13px;
|
||||
}
|
||||
.library-versions-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
background: var(--bg-panel, #fff);
|
||||
border: 1px solid var(--border-base, #e2e8f0);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
font-size: 13px;
|
||||
}
|
||||
.library-versions-table th,
|
||||
.library-versions-table td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--border-base, #eef2f7);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.library-versions-table th {
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
background: #f8fafc;
|
||||
}
|
||||
.library-versions-table td {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.library-snapshot-toggle {
|
||||
border: 1px solid var(--border-base, #e2e8f0);
|
||||
border-radius: 7px;
|
||||
background: #fff;
|
||||
padding: 4px 8px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
color: inherit;
|
||||
}
|
||||
.library-snapshot-parts header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
margin-bottom: 12px;
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute, #64748b);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.library-snapshot-parts header strong {
|
||||
font-size: 14px;
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.library-snapshot-parts ul {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.library-snapshot-parts li {
|
||||
display: grid;
|
||||
grid-template-columns: 90px minmax(140px, 2fr) 80px 90px 110px;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
font-size: 12px;
|
||||
padding: 6px 8px;
|
||||
border-radius: 7px;
|
||||
background: #f8fafc;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.library-part-kind {
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--ink-mute, #64748b);
|
||||
}
|
||||
.library-part-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.library-versions {
|
||||
padding: 12px;
|
||||
}
|
||||
.library-versions-table {
|
||||
display: block;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.library-snapshot-parts li {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.library-scope-metrics {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
+11
-2
@@ -1,11 +1,20 @@
|
||||
export type ModuleId = 'dashboard' | 'sources' | 'knowledge' | 'tasks' | 'releases' | 'settings' | 'versions' | 'qaops'
|
||||
export type ModuleId =
|
||||
| 'dashboard'
|
||||
| 'sources'
|
||||
| 'knowledge'
|
||||
| 'tasks'
|
||||
| 'releases'
|
||||
| 'library'
|
||||
| 'settings'
|
||||
| 'versions'
|
||||
| 'qaops'
|
||||
|
||||
export interface WorkspaceState {
|
||||
openTabs: ModuleId[]
|
||||
activeTab: ModuleId
|
||||
}
|
||||
|
||||
const moduleIds = new Set<ModuleId>(['dashboard', 'tasks', 'releases', 'settings', 'qaops'])
|
||||
const moduleIds = new Set<ModuleId>(['dashboard', 'tasks', 'releases', 'library', 'settings', 'qaops'])
|
||||
|
||||
export const initialWorkspace: WorkspaceState = {
|
||||
openTabs: ['dashboard'],
|
||||
|
||||
Reference in New Issue
Block a user