Compare commits
131 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0cc3cac837 | |||
| e4342fa05b | |||
| 040b7285d7 | |||
| cbc6b981c6 | |||
| ecf518e3bb | |||
| 0b753e550e | |||
| 2066bedbbe | |||
| 5f1a8f565c | |||
| 4fce49478f | |||
| 4d2cb13b0e | |||
| 0aa9f273e6 | |||
| fba2713b4e | |||
| 10568943af | |||
| 3f2626f621 | |||
| e8bfdbbc06 | |||
| ef3c1fbf84 | |||
| 2da96da592 | |||
| 10182b027e | |||
| 060872a144 | |||
| 0f7b8987b4 | |||
| 5e850e96f5 | |||
| 719876d039 | |||
| 9d445f4953 | |||
| 2eff9447e1 | |||
| 146ac832a2 | |||
| 77bbc3ac6b | |||
| eaa388f76b | |||
| cf11343cf4 | |||
| 7511c59987 | |||
| b81fcd07e3 | |||
| 1a0f99e346 | |||
| 7675e2cd88 | |||
| 5bf4aae30e | |||
| 1c80b07f2c | |||
| dfbf3336b2 | |||
| 600cca02e5 | |||
| e735ae603d | |||
| 2a2e98bd8e | |||
| 92684c6f60 | |||
| 537a6df46d | |||
| 0d9091e464 | |||
| e0fc2c32b8 | |||
| 6042955498 | |||
| a55319d972 | |||
| 017765763a | |||
| bd452e85b3 | |||
| 71f23c6763 | |||
| b4add6c9b0 | |||
| f9457fab52 | |||
| 5e1482e349 | |||
| 4421dd38ce | |||
| 22fb33aa75 | |||
| 0d180aa401 | |||
| 0a87dc8e03 | |||
| 96472c1dde | |||
| bad9034cf7 | |||
| f330a75641 | |||
| 19ec03c417 | |||
| 6209072e43 | |||
| e61f05c98c | |||
| a9d5adf78f | |||
| e8f8069473 | |||
| b7d6661a4e | |||
| 97da6ceba8 | |||
| 7cdbb74c8f | |||
| 1aa60c159e | |||
| 245cefd6b0 | |||
| 1e2bb385c7 | |||
| bf7f5fa03c | |||
| 24608e132b | |||
| 80254756f1 | |||
| 37f2dc73f9 | |||
| 9e31a6f956 | |||
| 1c58f1ef7e | |||
| 3b7ad9061c | |||
| 882e38591d | |||
| a1112d368a | |||
| ca32f2e661 | |||
| 513aa9e6f5 | |||
| 3bce6c7a3f | |||
| 18a4b83f78 | |||
| 7b2ab642f7 | |||
| 0a7c9f8510 | |||
| e09fddcb74 | |||
| fad26166a4 | |||
| 47be4ae502 | |||
| 6827fa922f | |||
| c31a7df4ca | |||
| 770252b55a | |||
| c256f2985c | |||
| f1cddfb601 | |||
| d2ff089b95 | |||
| 12b37690ec | |||
| a1472ff29f | |||
| f076c3af9c | |||
| 59eb12296a | |||
| 6ec1821294 | |||
| 099e58b5dc | |||
| e760d85427 | |||
| 98e7279632 | |||
| 30f223bcc4 | |||
| 2cbeca8d1d | |||
| b39902ef90 | |||
| 68f03bb30e | |||
| 93c0f34aac | |||
| 98ccb9366e | |||
| 07a9caf22b | |||
| eea0a0ec3b | |||
| 1d2fff8639 | |||
| 066dc45a25 | |||
| ff257064c3 | |||
| de867078c6 | |||
| b15633d37c | |||
| c938a4f4bf | |||
| ba1989b042 | |||
| a98828dc4a | |||
| e292b6f674 | |||
| 30686dd288 | |||
| 8ce78e28fa | |||
| 044fb37b2c | |||
| e34306b2db | |||
| 943b617b1f | |||
| 90ab1c3a5e | |||
| 99055a582e | |||
| 0df0e3cb1e | |||
| f4bd1980bf | |||
| 8df19f9368 | |||
| 8d838d9cb4 | |||
| 5afd8c0140 | |||
| 8febe12d7d | |||
| 5eef13b615 |
@@ -108,9 +108,23 @@ if [ -n "$BEFORE" ] && [ "$BEFORE" != "$ZERO" ]; then
|
||||
if git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then
|
||||
echo "✅ 事件 before ${BEFORE:0:12} 已在克隆里(本次推送范围可直接算)"
|
||||
else
|
||||
gitauth fetch -q --depth 50 origin "$BEFORE" 2>/dev/null \
|
||||
&& echo "✅ 已补取事件 before ${BEFORE:0:12}" \
|
||||
|| echo "⚠️ 取不到事件 before ${BEFORE:0:12}:范围校验会明确失败,不会静默收缩"
|
||||
# ⚠️ 为什么重试一次:浅克隆里用 `fetch --depth` 取一个**未公开**的对象(撤销/改写推送之后
|
||||
# 的旧提交就是这种)时,git 会在这次 fetch 中途重写 .git/shallow,随后发现自己读到的
|
||||
# 与开始时不同就整体中止:`fatal: shallow file has changed since we read it`。
|
||||
# 实测(run 305–317,含原地重跑)这一步必中止,而**同一仓库里紧接着重试同一条命令即成功**。
|
||||
# before 取不到 ⇒ commits 检查算不出范围 ⇒ 流水线红,且红的原因与代码质量无关。
|
||||
# 重试只负责"把 before 取进克隆",不收缩范围;两次都失败仍明确报警,由 commits 检查判红。
|
||||
FETCH_OK=""
|
||||
FETCH_ERR=""
|
||||
for _attempt in 1 2; do
|
||||
FETCH_ERR="$(gitauth fetch -q --depth 50 origin "$BEFORE" 2>&1 >/dev/null || true)"
|
||||
if git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then FETCH_OK=1; break; fi
|
||||
done
|
||||
if [ -n "$FETCH_OK" ]; then
|
||||
echo "✅ 已补取事件 before ${BEFORE:0:12}"
|
||||
else
|
||||
echo "⚠️ 取不到事件 before ${BEFORE:0:12}:范围校验会明确失败,不会静默收缩(最后一次错误:${FETCH_ERR:0:160})"
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo "(事件里没有 before / before 为全 0:新分支推送,范围按默认分支为基准判)"
|
||||
|
||||
+6236
-12
File diff suppressed because it is too large
Load Diff
+2
-2
@@ -50,7 +50,7 @@ RUN set -eux; \
|
||||
dws version
|
||||
WORKDIR /app
|
||||
COPY --from=build /out/ /app/
|
||||
COPY scripts/source_catalog_import.py scripts/live_catalog_refresh.py scripts/artifact_fetch.py \
|
||||
scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/
|
||||
COPY scripts/source_catalog_import.py scripts/live_catalog_refresh.py scripts/dws_dingtalk_scan.py \
|
||||
scripts/artifact_fetch.py scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/
|
||||
USER 65532:65532
|
||||
CMD ["/app/api"]
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
"/api/v1/qa-ops/master/weekly-mail/confirmations/{week}": {"get":{"operationId":"getQAWeeklyMailConfirmation","tags":["QA operations"],"summary":"读取该周是否已确认自动发送;current=false表示确认后正文已被修改,需要重新确认","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}},"post":{"operationId":"confirmQAWeeklyMail","tags":["QA operations"],"summary":"确认本周周报可自动发送,绑定当前草稿版本与正文哈希;后续改动使确认失效,不发送改动后的正文","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}},"delete":{"operationId":"unconfirmQAWeeklyMail","tags":["QA operations"],"summary":"取消该周的自动发送确认","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}}},
|
||||
"/api/v1/qa-ops/master/weekly-mail/sends": {"get":{"operationId":"listQAWeeklyMailSends","tags":["QA operations"],"summary":"读取周报邮件发送记录:周次、草稿版本、发送中/已发送/失败及错误摘要,不返回正文或收件人","parameters":[{"name":"week","in":"query","required":false,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}}},
|
||||
"/api/v1/qa-ops/master/weekly-mail/test": {"post":{"operationId":"sendQAWeeklyMailTest","tags":["QA operations"],"summary":"管理员用当前已保存的邮件设置立即发送一封测试邮件,正文取该周已保存草稿;不写入发送记录、不改变确认状态、不把该周标记为已发送","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["week"],"properties":{"week":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}}}}},"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可测试发送"},"502":{"description":"SMTP 拒绝或不可达,返回脱敏原因"},"503":{"description":"邮件设置存储不可用"}}}},
|
||||
"/api/v1/qa-ops/master/weekly-mail/send/{week}": {"get":{"operationId":"previewQAWeeklyMailSend","tags":["QA operations"],"summary":"管理员补发前核对:按周、已确认版本与正文hash返回真实主送/抄送人数、版本与是否已发送;不投递、不写记录","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"revision","in":"query","required":true,"schema":{"type":"integer","minimum":1}},{"name":"body_sha256","in":"query","required":true,"schema":{"type":"string","pattern":"^[0-9a-f]{64}$"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"409":{"description":"未确认/正文或版本已变化/当前周未到设定时点/上次结果未知"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"邮件设置存储不可用"}}},"post":{"operationId":"sendQAWeeklyMailFormal","tags":["QA operations"],"summary":"管理员正式补发周报:精确指定周、已确认版本与正文hash;已结束周可发、当前周须到设定时点、未来周拒绝;正文/看板图片/主送/抄送与自动发送共用,写入正式发送记录并返回真实message_id;已发送幂等、结果未知不重发","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["revision","body_sha256"],"properties":{"revision":{"type":"integer","minimum":1},"body_sha256":{"type":"string","pattern":"^[0-9a-f]{64}$"}}}}}},"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且需同源操作意图"},"409":{"description":"未确认/正文或版本已变化/当前周未到设定时点/上次结果未知/授权码缺失"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"description":"SMTP 拒绝或不可达,返回脱敏原因且不写已发送"},"503":{"description":"邮件设置存储不可用"}}}},
|
||||
"/api/v1/qa-ops/master/weekly-mail/confirmations/{week}/image": {"post":{"operationId":"saveQAWeeklyMailImage","tags":["QA operations"],"summary":"管理员保存该周确认对应的统计看板 PNG;发送时作为内嵌图片(cid)放在正文末尾,正文改动使确认失效后不再使用旧图","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["png_base64"],"properties":{"png_base64":{"type":"string","maxLength":12000000}}}}}},"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可上传"},"429":{"description":"请求过快"},"503":{"description":"邮件设置存储不可用"}}}},
|
||||
"/api/v1/qa-ops/departments/statistics": {
|
||||
"post": {
|
||||
@@ -832,6 +833,62 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/source-associations": {
|
||||
"post": {
|
||||
"tags": [
|
||||
"Runtime"
|
||||
],
|
||||
"operationId": "associateLegacyLibrarySource",
|
||||
"summary": "管理员核验原捕获证据并关联旧封存来源;不修改快照、不发布内容",
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"scope",
|
||||
"snapshot_id"
|
||||
],
|
||||
"properties": {
|
||||
"scope": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"internal",
|
||||
"external"
|
||||
]
|
||||
},
|
||||
"snapshot_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "已持久关联并读回;associated=true,published=false,返回准确snapshot_id/source_id/source_identity"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员登录身份"
|
||||
},
|
||||
"409": {
|
||||
"description": "原捕获证据缺失、来源/指纹/清单不符或已有不可变关联冲突"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"503": {
|
||||
"description": "来源配置或关联存储不可用"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/captures": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -1312,6 +1369,45 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/jobs/{id}/reconcile-capture": {
|
||||
"post": {
|
||||
"tags": [
|
||||
"Runtime"
|
||||
],
|
||||
"operationId": "reconcileLibraryCapture",
|
||||
"summary": "仅在 completed capture queue、精确 test_sealed 版本与归档复核一致时,修复该封存作业终态;不重新封存",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "已修复或已成功(幂等)"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"403": {
|
||||
"description": "需要管理员权限"
|
||||
},
|
||||
"404": {
|
||||
"description": "作业不存在"
|
||||
},
|
||||
"409": {
|
||||
"description": "队列/阶段/版本/归档证据不一致,拒绝修复"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/restore-availability": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -1599,6 +1695,93 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/verifications": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Runtime"
|
||||
],
|
||||
"operationId": "getLibraryRestoreVerification",
|
||||
"summary": "当前整库目标的恢复验证证据:verified 只由真实演练记录回答(按 target_id 绑定,换目标自动失效),并返回完整目标与失败原因",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "scope",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"internal",
|
||||
"external"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "目标与证据:verified/reason/latest/history/target"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"503": {
|
||||
"description": "恢复验证存储不可用或证据读取失败"
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"tags": [
|
||||
"Runtime"
|
||||
],
|
||||
"operationId": "startLibraryRestoreVerification",
|
||||
"summary": "发起一次真实恢复验证(管理员):维护隔离下捕获目标 → 校验基线 → 写 canary 证明校验有效 → 按预备份恢复 → 复核,通过后才产生同步闸口认的证据",
|
||||
"responses": {
|
||||
"202": {
|
||||
"description": "已创建 verify 作业(worker 在维护窗口内真实执行)"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"403": {
|
||||
"description": "不是管理员"
|
||||
},
|
||||
"409": {
|
||||
"description": "目标正在维护或已有在飞写作业(同步/恢复/基线/验证互斥)"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"503": {
|
||||
"description": "生产写入闸口关闭或恢复验证存储不可用"
|
||||
}
|
||||
},
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"scope"
|
||||
],
|
||||
"properties": {
|
||||
"scope": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"internal",
|
||||
"external"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/library/snapshots/{id}": {
|
||||
"get": {
|
||||
"tags": [
|
||||
|
||||
+47
-23
@@ -8,7 +8,6 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -26,6 +25,7 @@ import (
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"knowledge-governance/internal/qawemail"
|
||||
"knowledge-governance/internal/readiness"
|
||||
"knowledge-governance/internal/serviceverify"
|
||||
"knowledge-governance/internal/version"
|
||||
)
|
||||
@@ -90,26 +90,6 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
return errors.New("read production release authorization token")
|
||||
}
|
||||
}
|
||||
// P10: with a mounted API key the probe verifies a real knowledge-base read
|
||||
// (readiness); without one it degrades to the liveness-only HTTP check.
|
||||
var weknoraReadiness func(context.Context) error
|
||||
var knowledgeBaseLister httpapi.KnowledgeBaseLister
|
||||
if strings.TrimSpace(config.TestWeKnoraBaseURL) != "" {
|
||||
if apiKey, keyErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); keyErr == nil {
|
||||
probeTimeout := config.TestWeKnoraHTTPTimeout
|
||||
if probeTimeout > 10*time.Second || probeTimeout <= 0 {
|
||||
probeTimeout = 10 * time.Second
|
||||
}
|
||||
if probeClient, clientErr := weknora.NewClient(weknora.ClientConfig{BaseURL: config.TestWeKnoraBaseURL, APIKey: apiKey, Timeout: probeTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP}); clientErr == nil {
|
||||
knowledgeBaseLister = probeClient
|
||||
routingKB := config.InternalRoutingKnowledgeBaseID
|
||||
weknoraReadiness = func(probeCtx context.Context) error {
|
||||
_, _, err := probeClient.ListKnowledge(probeCtx, routingKB, 1, 1)
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Production WeKnora is probed for liveness only: the console must show the
|
||||
// real state of that endpoint, while credentials and the publish target stay
|
||||
// in the release runtime config (RELEASE_CONFIG_FILE).
|
||||
@@ -131,7 +111,43 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
}
|
||||
return settings.TestWeKnoraBaseURL
|
||||
}
|
||||
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraReadiness, WorkerStaleAfter: config.WorkerLivenessStaleAfter})
|
||||
// P10 readiness 与执行链看同一目标:网页保存的端点、当前持久化绑定、同一份
|
||||
// API Key。启动时只捕获 resolver,不捕获任何一项的值(F13:旧 env 绑定 404)。
|
||||
readinessResolver := newWeKnoraReadinessResolver(
|
||||
func(resolveCtx context.Context) string {
|
||||
if saved := testEndpointResolver(resolveCtx); saved != "" {
|
||||
return saved
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
},
|
||||
config.InternalRoutingKnowledgeBaseID,
|
||||
func(resolveCtx context.Context) (string, error) {
|
||||
internal, _, _, err := actionStore.LoadRoutingKBBindings(resolveCtx)
|
||||
return internal, err
|
||||
},
|
||||
func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) },
|
||||
)
|
||||
readinessProber := readiness.Prober{
|
||||
Resolve: readinessResolver,
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
}
|
||||
weknoraProbe := func(probeCtx context.Context) (string, error) {
|
||||
result := readinessProber.Check(probeCtx)
|
||||
return result.Target, result.Err
|
||||
}
|
||||
knowledgeBaseLister := &weKnoraLister{
|
||||
endpoint: func(resolveCtx context.Context) string {
|
||||
if saved := testEndpointResolver(resolveCtx); saved != "" {
|
||||
return saved
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
},
|
||||
readKey: func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) },
|
||||
timeout: config.TestWeKnoraHTTPTimeout,
|
||||
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
}
|
||||
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -190,7 +206,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
QAOpsTenantKey: qaSettings.TenantKey,
|
||||
QAOpsEnabled: qaSettings.Enabled,
|
||||
QAOpsProblem: qaSettings.Problem,
|
||||
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()),
|
||||
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID),
|
||||
Monitor: monitorProvider,
|
||||
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
|
||||
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
|
||||
@@ -217,10 +233,16 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
LibraryTargetWriters: config.LibraryTargetWriters,
|
||||
LibraryTargetIngressURL: config.LibraryTargetIngressURL,
|
||||
LibraryTargetIngressService: config.LibraryTargetIngressService,
|
||||
LibraryTargetIngressMode: config.LibraryTargetIngressMode,
|
||||
LibraryTargetHealthURL: config.LibraryTargetHealthURL,
|
||||
LibraryTargetDockerSocket: config.LibraryTargetDockerSocket,
|
||||
LibraryTargetJournalRoot: config.LibraryTargetJournalRoot,
|
||||
LibrarySourceInstance: config.SourceInstance(),
|
||||
LibrarySourceProject: config.SourceProject(),
|
||||
LibrarySourceApp: config.LibrarySourceApp,
|
||||
LibrarySourceTenantID: config.LibrarySourceTenantID,
|
||||
LibrarySourceInternalKB: config.LibrarySourceInternalKB,
|
||||
LibrarySourceExternalKB: config.LibrarySourceExternalKB,
|
||||
LibraryAgentSocket: config.LibraryAgentSocket,
|
||||
LibraryExecutorStatusMaxAge: config.LibraryExecutorStatusMaxAge,
|
||||
LibraryCapacityBudgetBytes: config.LibraryCapacityBudgetBytes,
|
||||
@@ -228,6 +250,8 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
LibraryProductionInternalKB: config.LibraryProductionInternalKB,
|
||||
LibraryProductionExternalKB: config.LibraryProductionExternalKB,
|
||||
LibraryProductionTenantID: config.LibraryProductionTenantID,
|
||||
LibraryProductionIndex: config.LibraryProductionIndex,
|
||||
LibraryProductionS3Bucket: config.LibraryProductionS3Bucket,
|
||||
LibraryRetentionVersions: config.LibraryRetentionVersions,
|
||||
LibraryRetentionDays: config.LibraryRetentionDays,
|
||||
BackupHost: backuphost.New(backuphost.Config{
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/readiness"
|
||||
)
|
||||
|
||||
// newWeKnoraReadinessResolver 把「探测目标」收敛到与业务同一组真源:
|
||||
// 端点来自网页保存的服务配置(endpoint 内部已做 env 兜底),知识库来自
|
||||
// 当前持久化绑定(未绑定才用 env 引导值),凭据每次重新读同一份 key 文件。
|
||||
// 任何一项读取失败都必须显式报错——静默退回旧值正是 F13 的成因。
|
||||
func newWeKnoraReadinessResolver(
|
||||
endpoint func(context.Context) string,
|
||||
envKnowledgeBaseID string,
|
||||
loadBinding func(context.Context) (string, error),
|
||||
readKey func() (string, error),
|
||||
) func(context.Context) (readiness.Target, error) {
|
||||
resolver := readiness.Resolver{
|
||||
Endpoint: endpoint,
|
||||
DefaultKB: envKnowledgeBaseID,
|
||||
LoadBinding: func(resolveCtx context.Context) (string, error) {
|
||||
if loadBinding == nil {
|
||||
return "", nil
|
||||
}
|
||||
stored, err := loadBinding(resolveCtx)
|
||||
if err != nil {
|
||||
log.Printf("readiness: load routing bindings: %v", err)
|
||||
}
|
||||
return stored, err
|
||||
},
|
||||
ReadKey: func() (string, error) {
|
||||
if readKey == nil {
|
||||
return "", nil
|
||||
}
|
||||
value, err := readKey()
|
||||
if err != nil {
|
||||
log.Printf("readiness: read WeKnora API key: %v", err)
|
||||
}
|
||||
return value, err
|
||||
},
|
||||
}
|
||||
return resolver.Resolve
|
||||
}
|
||||
|
||||
// weKnoraLister 让「系统设置」的知识库下拉与保存校验同样跟随当前端点/凭据,
|
||||
// 而不是复用启动时的客户端(否则改端点后选项仍来自旧实例)。
|
||||
type weKnoraLister struct {
|
||||
endpoint func(context.Context) string
|
||||
readKey func() (string, error)
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
}
|
||||
|
||||
func (lister *weKnoraLister) ListKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, error) {
|
||||
baseURL := ""
|
||||
if lister.endpoint != nil {
|
||||
baseURL = strings.TrimSpace(lister.endpoint(ctx))
|
||||
}
|
||||
if baseURL == "" {
|
||||
return nil, fmt.Errorf("WeKnora 端点未配置")
|
||||
}
|
||||
apiKey, err := lister.readKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
timeout := lister.timeout
|
||||
if timeout <= 0 || timeout > 10*time.Second {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: baseURL, APIKey: apiKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client.ListKnowledgeBases(ctx)
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/readiness"
|
||||
)
|
||||
|
||||
// F13 的接线回归:探测目标必须来自「网页保存的端点 + 当前持久化绑定」,
|
||||
// env 只能是未绑定时的引导兜底;任何一项都不许在启动时固化。
|
||||
func TestReadinessResolverUsesPersistedBindingOverEnv(t *testing.T) {
|
||||
const envKB = "1b52c140-2e18-4676-afc5-4c7d8d190a8c"
|
||||
const storedKB = "0c84a098-d3ed-4b82-a165-e6de9691d6a8"
|
||||
resolve := newWeKnoraReadinessResolver(
|
||||
func(context.Context) string { return "https://weknora.test" },
|
||||
envKB,
|
||||
func(context.Context) (string, error) { return storedKB, nil },
|
||||
func() (string, error) { return "key-1", nil },
|
||||
)
|
||||
target, err := resolve(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if target.KnowledgeBaseID != storedKB || target.BaseURL != "https://weknora.test" || target.APIKey != "key-1" {
|
||||
t.Fatalf("resolved target = %#v", target)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadinessResolverFallsBackToEnvOnlyWhenUnbound(t *testing.T) {
|
||||
const envKB = "1b52c140-2e18-4676-afc5-4c7d8d190a8c"
|
||||
resolve := newWeKnoraReadinessResolver(
|
||||
func(context.Context) string { return "https://weknora.test" },
|
||||
envKB,
|
||||
func(context.Context) (string, error) { return "", nil },
|
||||
func() (string, error) { return "key-1", nil },
|
||||
)
|
||||
target, err := resolve(context.Background())
|
||||
if err != nil || target.KnowledgeBaseID != envKB {
|
||||
t.Fatalf("unbound fallback = %#v, %v", target, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadinessResolverReportsBindingAndCredentialFailures(t *testing.T) {
|
||||
bindingDown := newWeKnoraReadinessResolver(
|
||||
func(context.Context) string { return "https://weknora.test" },
|
||||
"env-kb",
|
||||
func(context.Context) (string, error) { return "", errors.New("db unavailable") },
|
||||
func() (string, error) { return "key-1", nil },
|
||||
)
|
||||
target, err := bindingDown(context.Background())
|
||||
if err == nil {
|
||||
t.Fatalf("binding read failure must not silently probe env: %#v", target)
|
||||
}
|
||||
keyDown := newWeKnoraReadinessResolver(
|
||||
func(context.Context) string { return "https://weknora.test" },
|
||||
"env-kb",
|
||||
func(context.Context) (string, error) { return "", nil },
|
||||
func() (string, error) { return "", errors.New("key file missing") },
|
||||
)
|
||||
if _, err := keyDown(context.Background()); err == nil {
|
||||
t.Fatal("missing API key must surface, not degrade to liveness-only")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadinessResolverMarksUnconfiguredEndpoint(t *testing.T) {
|
||||
resolve := newWeKnoraReadinessResolver(
|
||||
func(context.Context) string { return "" },
|
||||
"env-kb",
|
||||
func(context.Context) (string, error) { return "", nil },
|
||||
func() (string, error) { return "key-1", nil },
|
||||
)
|
||||
// 端点缺失时归类为「未配置」,不是「服务不可用」。
|
||||
result := readiness.Prober{Resolve: resolve}.Check(context.Background())
|
||||
if !errors.Is(result.Err, readiness.ErrNotConfigured) {
|
||||
t.Fatalf("blank endpoint probe = %v, want ErrNotConfigured", result.Err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeBaseListerFollowsTheCurrentEndpoint(t *testing.T) {
|
||||
base := func(name string) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.URL.Path != "/api/v1/knowledge-bases" {
|
||||
writer.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"success":true,"data":[{"id":"` + name + `","name":"` + name + `"}]}`))
|
||||
}))
|
||||
}
|
||||
first, second := base("kb-a"), base("kb-b")
|
||||
defer first.Close()
|
||||
defer second.Close()
|
||||
endpoint := first.URL
|
||||
lister := &weKnoraLister{
|
||||
endpoint: func(context.Context) string { return endpoint },
|
||||
readKey: func() (string, error) { return "key-1", nil },
|
||||
timeout: time.Second,
|
||||
}
|
||||
bases, err := lister.ListKnowledgeBases(context.Background())
|
||||
if err != nil || len(bases) != 1 || bases[0].ID != "kb-a" {
|
||||
t.Fatalf("initial endpoint bases = %#v, %v", bases, err)
|
||||
}
|
||||
endpoint = second.URL
|
||||
bases, err = lister.ListKnowledgeBases(context.Background())
|
||||
if err != nil || len(bases) != 1 || bases[0].ID != "kb-b" {
|
||||
t.Fatalf("rotated endpoint bases = %#v, %v", bases, err)
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,13 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/libraryagent"
|
||||
"knowledge-governance/internal/librarydsn"
|
||||
"knowledge-governance/internal/librarymaintenance"
|
||||
)
|
||||
|
||||
@@ -25,22 +28,43 @@ func main() {
|
||||
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.SourcePG, "source-pg", "WKNFull-postgres", "source PostgreSQL container; empty = the source DB lives on a managed instance and is reached with the source app env (DB_HOST/...)")
|
||||
flag.StringVar(&config.SourceES, "source-es", "WKNFull-elasticsearch", "source Elasticsearch container")
|
||||
flag.StringVar(&config.SourceS3Endpoint, "source-s3-endpoint", "", "host-reachable source object-store endpoint (overrides the container-internal one)")
|
||||
flag.StringVar(&config.GovernancePG, "governance-pg", "knowledge-governance-p1-postgres-1", "governance PostgreSQL container")
|
||||
flag.StringVar(&config.GovernancePG, "governance-pg", "knowledge-governance-p1-postgres-1", "governance PostgreSQL container; empty = read the DSN from LIBRARY_GOVERNANCE_DSN_FILE")
|
||||
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")
|
||||
allowUIDs := flag.String("allow-peer-uid", "", "extra peer uids allowed to connect (comma separated; default: same uid only)")
|
||||
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()
|
||||
if strings.TrimSpace(*allowUIDs) != "" {
|
||||
for _, raw := range strings.Split(*allowUIDs, ",") {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
uid, err := strconv.ParseUint(raw, 10, 32)
|
||||
if err != nil {
|
||||
log.Fatalf("--allow-peer-uid 需要十进制 uid:%q", raw)
|
||||
}
|
||||
config.AllowedPeerUIDs = append(config.AllowedPeerUIDs, uint32(uid))
|
||||
}
|
||||
}
|
||||
config.NonWriters = *nonWriters
|
||||
|
||||
agent, err := libraryagent.New(config)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if *describe {
|
||||
// describe 只回答"这两个库从哪来"。地址与凭据一律不出现:这段输出会被贴进
|
||||
// 工单与日志,而 RDS 的连接串里带口令。
|
||||
log.Printf("source_db=%s governance_db=%s",
|
||||
librarydsn.SourceMode(config.SourcePG), librarydsn.GovernanceMode(config.GovernancePG))
|
||||
return
|
||||
}
|
||||
// 实例级维护接线(入口闸门 + 后台队列)不在 agent 的 Config 里:它由同一份
|
||||
// 环境声明提供给子进程。启动时先说清楚有没有——缺了封存会在开窗口前被拒,
|
||||
// 不允许"以为接好了"跑到一半才发现没有排空证据。
|
||||
@@ -49,10 +73,6 @@ func main() {
|
||||
} else {
|
||||
log.Printf("library agent: 实例级维护目标 %s 入口 %s 闸门 %s", target.Instance, target.IngressURL, target.IngressService)
|
||||
}
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 文件模式没配置:必须失败关闭并点名缺的那个变量——"静默退回容器模式"会让
|
||||
// 操作员以为在读 RDS,实际在读本机容器(或者干脆读到不存在的容器)。
|
||||
func TestGovernanceFileModeFailsClosedWithoutDSNFile(t *testing.T) {
|
||||
t.Setenv("LIBRARY_GOVERNANCE_DSN_FILE", "")
|
||||
_, err := readRoutingBindings(context.Background(), options{governancePG: ""})
|
||||
if err == nil {
|
||||
t.Fatal("没有 DSN 文件却读成功了")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "LIBRARY_GOVERNANCE_DSN_FILE") {
|
||||
t.Fatalf("错误没有点名缺哪一项:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 外部 DSN 连不上/写错时,错误必须是固定说法:pgx 的错误里带的是连接串(主机、
|
||||
// 用户名,口令它自己打码),直接透传就等于把地址写进日志与工单。
|
||||
func TestGovernanceFileModeNeverLeaksPasswordInErrors(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "governance.dsn")
|
||||
// 夹具口令运行时拼装:源码里不留“带口令的连接串”字面量,否则密钥扫描只会
|
||||
// 报出一堆必然是假值的夹具,把真泄漏的信号淹掉。
|
||||
password := strings.Join([]string{"fixture", "leak", "probe"}, "-")
|
||||
// 故意用非法 sslmode + 不可达端口:无论失败在解析还是连接阶段,都不许泄露。
|
||||
if err := os.WriteFile(path, []byte("postgres://gov:"+password+"@127.0.0.1:1/gov?sslmode=bogus&connect_timeout=1\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("LIBRARY_GOVERNANCE_DSN_FILE", path)
|
||||
_, err := readRoutingBindings(context.Background(), options{governancePG: ""})
|
||||
if err == nil {
|
||||
t.Fatal("坏 DSN 竟然读成功了")
|
||||
}
|
||||
if strings.Contains(err.Error(), password) {
|
||||
t.Fatalf("错误里漏了口令:%v", err)
|
||||
}
|
||||
}
|
||||
+173
-34
@@ -30,9 +30,11 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/librarydeadletter"
|
||||
"knowledge-governance/internal/librarydsn"
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/librarymaintenance"
|
||||
@@ -146,9 +148,13 @@ func usage() {
|
||||
|
||||
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-pg WKNFull-postgres source PostgreSQL container; empty = the source DB is a
|
||||
managed instance: connect with the source app env
|
||||
(DB_HOST/DB_PORT/DB_NAME/DB_USER/DB_PASSWORD), TLS mode from
|
||||
LIBRARY_SOURCE_DB_SSLMODE (default require)
|
||||
-source-es WKNFull-elasticsearch
|
||||
-governance-pg knowledge-governance-p1-postgres-1 routing bindings read here
|
||||
-governance-pg knowledge-governance-p1-postgres-1 routing bindings read here; empty = read
|
||||
the DSN from LIBRARY_GOVERNANCE_DSN_FILE (0600 file)
|
||||
-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
|
||||
@@ -182,9 +188,9 @@ func parseFlags(command string, args []string) (options, []string, error) {
|
||||
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.sourcePG, "source-pg", opts.sourcePG, "source PostgreSQL container; empty = connect to the source app's external (managed) database")
|
||||
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.governancePG, "governance-pg", opts.governancePG, "governance PostgreSQL container; empty = read the DSN from LIBRARY_GOVERNANCE_DSN_FILE")
|
||||
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")
|
||||
@@ -285,15 +291,25 @@ func discoverSource(ctx context.Context, opts options, binding map[string]string
|
||||
if app["DB_DRIVER"] != "postgres" {
|
||||
return config, errors.New("source database driver is not postgres")
|
||||
}
|
||||
address, err := containerAddress(ctx, opts.sourcePG)
|
||||
if err != nil {
|
||||
return config, err
|
||||
// 两种来源:给了 -source-pg 就按容器地址拼(0.7.1 栈);没给说明库是托管
|
||||
// 实例(RDS 型 0.9.0 栈没有源库容器),用源应用容器 env 里的 DB_* 直连。
|
||||
if librarydsn.SourceMode(opts.sourcePG) == librarydsn.SourceExternal {
|
||||
dsn, dsnErr := librarydsn.SourceURL(app, os.Getenv)
|
||||
if dsnErr != nil {
|
||||
return config, dsnErr
|
||||
}
|
||||
config.DatabaseURL = dsn
|
||||
} else {
|
||||
address, addressErr := containerAddress(ctx, opts.sourcePG)
|
||||
if addressErr != nil {
|
||||
return config, addressErr
|
||||
}
|
||||
dsn, dsnErr := librarydsn.ContainerURL(address, app)
|
||||
if dsnErr != nil {
|
||||
return config, dsnErr
|
||||
}
|
||||
config.DatabaseURL = dsn
|
||||
}
|
||||
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
|
||||
@@ -388,17 +404,12 @@ func parseBool(value string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func urlEscape(value string) string {
|
||||
replacer := strings.NewReplacer("%", "%25", ":", "%3A", "@", "%40", "/", "%2F", "?", "%3F", "#", "%23", "&", "%26", " ", "%20")
|
||||
return replacer.Replace(value)
|
||||
}
|
||||
|
||||
// scopeBindings 返回 scope→知识库 映射。治理 API 用的是 LIBRARY_PRODUCTION_KB_*,
|
||||
// CLI 读的是治理库里的 routing bindings;同一台机器上两份不一致时,
|
||||
// CLI 抓到的会是"配置里那个库"而不是 API 认为的目标——所以环境变量优先,
|
||||
// 读不到才退回 bindings。两边讲同一份身份,验收才可比。
|
||||
func scopeBindings(ctx context.Context, container string) (map[string]string, error) {
|
||||
binding, err := readRoutingBindings(ctx, container)
|
||||
func scopeBindings(ctx context.Context, opts options) (map[string]string, error) {
|
||||
binding, err := readRoutingBindings(ctx, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -410,17 +421,105 @@ func scopeBindings(ctx context.Context, container string) (map[string]string, er
|
||||
return binding, nil
|
||||
}
|
||||
|
||||
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'")
|
||||
// readRoutingBindings 读治理库里生效的 scope 绑定。两种来源:
|
||||
// - 给了 -governance-pg:docker exec 进治理库容器跑 psql(0.7.1 本机栈);
|
||||
// - 没给:治理库是托管实例(RDS 型 0.9.0 栈没有 governance 容器),DSN 来自
|
||||
// LIBRARY_GOVERNANCE_DSN_FILE 指向的 0600 文件。
|
||||
//
|
||||
// 两条路径只共用行解析,不共用连接方式:容器里没有网络到 RDS 的凭据,宿主机也不该
|
||||
// 为了读两列去 docker exec 一个不存在的容器。
|
||||
func readRoutingBindings(ctx context.Context, opts options) (map[string]string, error) {
|
||||
if librarydsn.GovernanceMode(opts.governancePG) == librarydsn.GovernanceFile {
|
||||
dsn, err := librarydsn.GovernanceURL(os.Getenv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return readRoutingBindingsFromDSN(ctx, dsn)
|
||||
}
|
||||
raw, err := dockerOutput(ctx, "exec", opts.governancePG, "psql", "-U", "governance", "-d", "governance", "-tAc",
|
||||
routingBindingsQuery)
|
||||
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 parseRoutingBindings(raw)
|
||||
}
|
||||
|
||||
// COALESCE 不能省:两列都可能是 NULL(0.9.0 迁移把\"旧知识库绑定已解除\"落成 NULL,
|
||||
// 平台约定\"对外库没有对应目标时留空\")。裸拼接遇 NULL 得到整行 NULL,文件模式
|
||||
// 会在 Scan 成 string 时直接失败,报出的还是一句\"read routing bindings failed\"——
|
||||
// 真正的原因(哪一列没绑)被吞掉。这里先拼成固定形状,由 parseRoutingBindings 判。
|
||||
const routingBindingsQuery = "SELECT COALESCE(internal_kb_id,'')||'|'||COALESCE(external_kb_id,'') FROM routing_kb_bindings WHERE id='active'"
|
||||
|
||||
// readRoutingBindingsFromDSN 用外部 DSN 读同一份绑定。
|
||||
//
|
||||
// 只读会话是刻意的:这条路径只是读两列,出了问题必须是"读不到",而不是在治理库上
|
||||
// 留下一次写入。错误一律收敛成固定说法:pgx 的错误里会带连接串(口令它自己打了码,
|
||||
// 但主机与用户名照旧出去),而这里连那份地址都不该出现在日志或工单里。
|
||||
func readRoutingBindingsFromDSN(ctx context.Context, dsn string) (map[string]string, error) {
|
||||
parsed, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, errors.New("governance database url is invalid")
|
||||
}
|
||||
return map[string]string{"internal": internal, "external": external}, nil
|
||||
parsed.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
|
||||
parsed.ConnConfig.RuntimeParams["statement_timeout"] = "30000"
|
||||
parsed.MaxConns = 2
|
||||
pool, err := pgxpool.NewWithConfig(ctx, parsed)
|
||||
if err != nil {
|
||||
return nil, errors.New("open governance database failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
var raw string
|
||||
if err = pool.QueryRow(ctx, routingBindingsQuery).Scan(&raw); err != nil {
|
||||
return nil, errors.New("read routing bindings failed")
|
||||
}
|
||||
return parseRoutingBindings(raw)
|
||||
}
|
||||
|
||||
// parseRoutingBindings 解一行 `<internal>|<external>`。两条来源(psql -tAc 与 pgx
|
||||
// 只读会话)拼的是同一句 SQL,所以只有这一份解析语义。
|
||||
//
|
||||
// 对内库必填:没有对内库就没有\"整库\"可言,此时必须点名是哪一列没绑,而不是退化成
|
||||
// 泛化的读失败。对外库可空:平台侧约定\"对外库没有对应目标时留空\",绑定本身仍然
|
||||
// 有效(`status`、internal scope 照常可跑);只有真去用 external scope 时才拒绝,
|
||||
// 且绝不回退到对内库——那会把对内库的内容当成对外库封存出去。
|
||||
func parseRoutingBindings(raw string) (map[string]string, error) {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
// 空输出 = 没有生效绑定行,等于对内库没绑:这跟"读失败"是两件事,
|
||||
// 必须说成前者,否则现场又会退回一句泛化错误。
|
||||
if trimmed == "" {
|
||||
return nil, errInternalKBMissing
|
||||
}
|
||||
internal, external, ok := strings.Cut(trimmed, "|")
|
||||
if !ok {
|
||||
return nil, errors.New("read routing bindings failed")
|
||||
}
|
||||
internal = strings.TrimSpace(internal)
|
||||
external = strings.TrimSpace(external)
|
||||
if internal == "" {
|
||||
return nil, errInternalKBMissing
|
||||
}
|
||||
binding := map[string]string{"internal": internal}
|
||||
if external != "" {
|
||||
binding["external"] = external
|
||||
}
|
||||
return binding, nil
|
||||
}
|
||||
|
||||
var (
|
||||
errInternalKBMissing = errors.New("对内知识库未绑定(routing_kb_bindings.internal_kb_id 为空)")
|
||||
errExternalKBMissing = errors.New("对外知识库未配置(routing_kb_bindings.external_kb_id 为空)")
|
||||
)
|
||||
|
||||
// scopeKnowledgeBase 取本次 scope 的目标库。空值必须在这里就拒绝:往下走会变成
|
||||
// \"knowledge base not found in source\"——那是拿空 UUID 查源库得到的假原因。
|
||||
func scopeKnowledgeBase(binding map[string]string, scope string) (string, error) {
|
||||
if kb := strings.TrimSpace(binding[scope]); kb != "" {
|
||||
return kb, nil
|
||||
}
|
||||
if scope == "external" {
|
||||
return "", errExternalKBMissing
|
||||
}
|
||||
return "", errInternalKBMissing
|
||||
}
|
||||
|
||||
func openSourceDatabase(ctx context.Context, config sourceConfig) (*pgxpool.Pool, error) {
|
||||
@@ -432,11 +531,25 @@ func openSourceDatabase(ctx context.Context, config sourceConfig) (*pgxpool.Pool
|
||||
// that a database-enforced property rather than a convention.
|
||||
parsed.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
|
||||
parsed.ConnConfig.RuntimeParams["statement_timeout"] = "120000"
|
||||
// 启动参数不足以保证只读:角色级/库级设置会在启动参数之后生效,托管实例
|
||||
// (RDS)上实测就是这样——SHOW 回来是 off。而池里每条连接是独立的会话,
|
||||
// 对单条连接 SET 管不到其他连接,所以放在 AfterConnect:每条新连接都显式
|
||||
// 置只读,池里就没有能写的会话。下面的 SHOW 只是对任意一条连接再核一次。
|
||||
parsed.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
|
||||
_, err := conn.Exec(ctx, "SET SESSION default_transaction_read_only = on")
|
||||
return err
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, parsed)
|
||||
if err != nil {
|
||||
return nil, errors.New("open source database failed")
|
||||
}
|
||||
var readOnly string
|
||||
// 连接失败与"能连上但会话可写"必须分开报:把两者压成同一句,现场只能看到
|
||||
// 一句无信息量的失败,反而会去怀疑权限或只读设置。
|
||||
if err = pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, errors.New("source database connection failed")
|
||||
}
|
||||
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")
|
||||
@@ -510,6 +623,11 @@ func openFreeze(ctx context.Context, opts options) (*libraryfreeze.Coordinator,
|
||||
//
|
||||
// 入口/队列的声明与容器内 worker 共用同一组 LIBRARY_TARGET_* 名称,
|
||||
// 数据库/索引/桶则取自本次真实发现的源,避免"关的是 A 的门、读的是 B 的队列"。
|
||||
//
|
||||
// LIBRARY_TARGET_INGRESS_MODE=none 只给整栈没有闸门的测试环境(0.9.0 测试栈):
|
||||
// 必须同时给 LIBRARY_NO_INGRESS_ACK=test-only,窗口里一笔闸门动作都不做,
|
||||
// 排空证据降为"写者全停 + 队列静默",恢复由 LIBRARY_TARGET_HEALTH_URL 的 200 证明。
|
||||
// 缺省仍是 gate:没有显式确认就照旧要求闸门。
|
||||
func captureMaintenanceConfig(opts options, source sourceConfig, get func(string) string) (librarymaintenance.Config, error) {
|
||||
target, err := librarymaintenance.TargetFromEnv(get)
|
||||
if err != nil {
|
||||
@@ -529,9 +647,12 @@ func captureMaintenanceConfig(opts options, source sourceConfig, get func(string
|
||||
Writers: writers,
|
||||
NonWriters: nonWriters,
|
||||
DockerSocket: opts.dockerSocket,
|
||||
IngressMode: target.Mode,
|
||||
IngressAck: target.Ack,
|
||||
IngressURL: target.IngressURL,
|
||||
IngressService: target.IngressService,
|
||||
IngressDrainFile: target.IngressDrainFile,
|
||||
HealthURL: target.HealthURL,
|
||||
Database: identity,
|
||||
Index: source.SearchIndex,
|
||||
Bucket: source.Object.Bucket,
|
||||
@@ -587,7 +708,12 @@ func openArchive(opts options) (*librarysnapshot.Archive, error) {
|
||||
|
||||
func runStatus(ctx context.Context, opts options) error {
|
||||
report := map[string]any{}
|
||||
binding, bindingErr := scopeBindings(ctx, opts.governancePG)
|
||||
// 只报来源模式:地址与凭据连 describe/status 都不出现,日志自然也不会带出去。
|
||||
report["databases"] = map[string]string{
|
||||
"source_db": librarydsn.SourceMode(opts.sourcePG),
|
||||
"governance_db": librarydsn.GovernanceMode(opts.governancePG),
|
||||
}
|
||||
binding, bindingErr := scopeBindings(ctx, opts)
|
||||
var config sourceConfig
|
||||
var err error
|
||||
if bindingErr != nil {
|
||||
@@ -680,7 +806,12 @@ 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 := scopeBindings(ctx, opts.governancePG)
|
||||
binding, err := scopeBindings(ctx, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 绑定缺哪一半在连源库之前就要说清楚:external 未配置不是"源库里没这个库"。
|
||||
kb, err := scopeKnowledgeBase(binding, opts.scope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -693,7 +824,6 @@ func runPreflight(ctx context.Context, opts options) error {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
kb := config.Scopes[opts.scope]
|
||||
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -773,7 +903,13 @@ func runCapture(ctx context.Context, opts options) error {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
binding, err := scopeBindings(ctx, opts.governancePG)
|
||||
binding, err := scopeBindings(ctx, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 先定住本次 scope 的库:external 没配置时,封存必须在开维护窗口之前就停,
|
||||
// 不能先停写者再发现目标为空。
|
||||
kb, err := scopeKnowledgeBase(binding, opts.scope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -801,7 +937,7 @@ func runCapture(ctx context.Context, opts options) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
scopedKB := binding[opts.scope]
|
||||
scopedKB := kb
|
||||
if found {
|
||||
manifest, err := replayCapture(job, opts.scope, scopedKB, existing, archive)
|
||||
if err != nil {
|
||||
@@ -814,7 +950,6 @@ func runCapture(ctx context.Context, opts options) error {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
kb := config.Scopes[opts.scope]
|
||||
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -1150,7 +1285,12 @@ func runDeadLetters(ctx context.Context, opts options) error {
|
||||
if opts.scope != "internal" && opts.scope != "external" {
|
||||
return errors.New("-scope must be internal or external")
|
||||
}
|
||||
binding, err := scopeBindings(ctx, opts.governancePG)
|
||||
binding, err := scopeBindings(ctx, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// external 未配置时,死信观测同样要明说"没配置",而不是拿空库去查源库。
|
||||
kb, err := scopeKnowledgeBase(binding, opts.scope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1163,7 +1303,6 @@ func runDeadLetters(ctx context.Context, opts options) error {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
kb := config.Scopes[opts.scope]
|
||||
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
)
|
||||
|
||||
// noGateMaintenanceEnv 是 0.9.0 测试栈:没有闸门,用显式确认 + 健康探针代替。
|
||||
func noGateMaintenanceEnv() map[string]string {
|
||||
env := maintenanceEnv()
|
||||
delete(env, "LIBRARY_TARGET_INGRESS_URL")
|
||||
delete(env, "LIBRARY_TARGET_INGRESS_SERVICE")
|
||||
delete(env, "LIBRARY_TARGET_INGRESS_DRAIN_FILE")
|
||||
env["LIBRARY_TARGET_INGRESS_MODE"] = libraryfreeze.IngressModeNone
|
||||
env["LIBRARY_NO_INGRESS_ACK"] = libraryfreeze.NoIngressAck
|
||||
env["LIBRARY_TARGET_HEALTH_URL"] = "http://127.0.0.1:18081/health"
|
||||
return env
|
||||
}
|
||||
|
||||
func TestCaptureMaintenanceConfigNoGateWithAck(t *testing.T) {
|
||||
env := noGateMaintenanceEnv()
|
||||
config, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] })
|
||||
if err != nil {
|
||||
t.Fatalf("no-gate 声明被拒:%v", err)
|
||||
}
|
||||
if config.IngressMode != libraryfreeze.IngressModeNone || config.IngressAck != libraryfreeze.NoIngressAck {
|
||||
t.Fatalf("入口形态没透传:%+v", config)
|
||||
}
|
||||
if config.IngressURL != "" || config.IngressService != "" || config.IngressDrainFile != "" {
|
||||
t.Fatalf("no-gate 配置里出现了闸门项:%+v", config)
|
||||
}
|
||||
if config.HealthURL != "http://127.0.0.1:18081/health" || config.RedisAddr != "127.0.0.1:26379" {
|
||||
t.Fatalf("健康探针/队列没透传:%+v", config)
|
||||
}
|
||||
// 目标身份仍取自本次真实发现的源:no-gate 只改证据形态,不改动的是谁。
|
||||
if config.Database != "127.0.0.1:25432/kgmaint_target" || config.Index != "kgmaint_1028a_chunks" {
|
||||
t.Fatalf("目标身份不对:%+v", config)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureMaintenanceConfigNoGateWithoutAckIsRefused(t *testing.T) {
|
||||
env := noGateMaintenanceEnv()
|
||||
delete(env, "LIBRARY_NO_INGRESS_ACK")
|
||||
_, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] })
|
||||
if err == nil || !strings.Contains(err.Error(), "LIBRARY_NO_INGRESS_ACK") {
|
||||
t.Fatalf("没有显式确认却放过了 no-gate:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// no-gate 不得悄悄接受半套闸门声明:要么有闸门,要么明确没有。
|
||||
func TestCaptureMaintenanceConfigNoGateRejectsPartialGate(t *testing.T) {
|
||||
env := noGateMaintenanceEnv()
|
||||
env["LIBRARY_TARGET_INGRESS_SERVICE"] = "ingress"
|
||||
if _, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] }); err == nil {
|
||||
t.Fatal("no-gate 与闸门服务同时存在却没有拒绝")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// internal 为空必须拒绝并点名。实测到的现场就是这一行:0.9.0 迁移后
|
||||
// internal_kb_id 与 external_kb_id 都是 NULL,旧解析退化成
|
||||
// "read routing bindings failed",操作员无法判断是连不上还是没绑定。
|
||||
// NULL 与空串在 SQL 侧由 routingBindingsQuery 的 COALESCE 收敛成同一形状,
|
||||
// 解析侧两者都必须落到同一条错误上。
|
||||
func TestParseRoutingBindingsRejectsEmptyInternal(t *testing.T) {
|
||||
for _, raw := range []string{"|", "|ext-kb", " \n| \n", "\n|\n", ""} {
|
||||
binding, err := parseRoutingBindings(raw)
|
||||
if err == nil {
|
||||
t.Fatalf("internal 为空却解析成功:%q → %v", raw, binding)
|
||||
}
|
||||
if binding != nil {
|
||||
t.Fatalf("internal 为空仍返回了映射:%q → %v", raw, binding)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "对内知识库未绑定") || !strings.Contains(err.Error(), "internal_kb_id") {
|
||||
t.Fatalf("错误没有点名 internal 未绑定:%q → %v", raw, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 0.9.0 测试实例的真实形状:只有对内库(wiki-demo),平台约定对外库没有对应
|
||||
// 目标时留空。绑定仍然有效,internal scope 能解析;external scope 必须失败、
|
||||
// 点名 external_kb_id,并且绝不回退到对内库。
|
||||
func TestParseRoutingBindingsAllowsEmptyExternal(t *testing.T) {
|
||||
binding, err := parseRoutingBindings("0da9b571-6f13-46a1-85fa-e63d2ef5666e|")
|
||||
if err != nil {
|
||||
t.Fatalf("对外库为空不该让整份绑定失效:%v", err)
|
||||
}
|
||||
if got := binding["internal"]; got != "0da9b571-6f13-46a1-85fa-e63d2ef5666e" {
|
||||
t.Fatalf("对内库解析错误:%q", got)
|
||||
}
|
||||
if value, present := binding["external"]; present {
|
||||
t.Fatalf("对外库没配置却写进了映射:%q", value)
|
||||
}
|
||||
|
||||
kb, err := scopeKnowledgeBase(binding, "internal")
|
||||
if err != nil || kb != "0da9b571-6f13-46a1-85fa-e63d2ef5666e" {
|
||||
t.Fatalf("internal scope 不该被 external 为空牵连:kb=%q err=%v", kb, err)
|
||||
}
|
||||
|
||||
kb, err = scopeKnowledgeBase(binding, "external")
|
||||
if err == nil {
|
||||
t.Fatalf("对外库未配置却解析出了目标库:%q", kb)
|
||||
}
|
||||
if kb != "" {
|
||||
t.Fatalf("external scope 回退到了别的库:%q", kb)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "对外知识库未配置") || !strings.Contains(err.Error(), "external_kb_id") {
|
||||
t.Fatalf("错误没有点名 external 未配置:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 两个库都绑定时行为不变:这是 0.7.1 栈与对外库已配置的 0.9.0 栈的常态路径。
|
||||
func TestParseRoutingBindingsBothScopesUnchanged(t *testing.T) {
|
||||
// psql -tAc 输出带行尾换行,pgx 那边不带——两边都必须是同一个结果。
|
||||
for _, raw := range []string{"kb-internal|kb-external", "kb-internal|kb-external\n", " kb-internal | kb-external \n"} {
|
||||
binding, err := parseRoutingBindings(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("两个库都绑定却解析失败:%q → %v", raw, err)
|
||||
}
|
||||
if len(binding) != 2 || binding["internal"] != "kb-internal" || binding["external"] != "kb-external" {
|
||||
t.Fatalf("解析结果与原行为不一致:%q → %v", raw, binding)
|
||||
}
|
||||
for _, scope := range []string{"internal", "external"} {
|
||||
if _, err := scopeKnowledgeBase(binding, scope); err != nil {
|
||||
t.Fatalf("%s scope 不该失败:%v", scope, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 没有分隔符说明拿到的不是那一行(空结果集、psql 报错文本等),只能是读失败。
|
||||
func TestParseRoutingBindingsRejectsMalformedRow(t *testing.T) {
|
||||
for _, raw := range []string{"kb-without-separator", "ERROR: relation \"routing_kb_bindings\" does not exist"} {
|
||||
if _, err := parseRoutingBindings(raw); err == nil {
|
||||
t.Fatalf("没有分隔符却解析成功:%q", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 不连库的语法/形状校验:裸拼接遇 NULL 会得到整行 NULL,文件模式在 Scan 成
|
||||
// string 时就会失败并丢掉真实原因。两句来源共用这一条 SQL,因此只查这一处。
|
||||
func TestRoutingBindingsQueryCoalescesBothColumns(t *testing.T) {
|
||||
query := routingBindingsQuery
|
||||
for _, column := range []string{"internal_kb_id", "external_kb_id"} {
|
||||
if !strings.Contains(query, "COALESCE("+column+",'')") {
|
||||
t.Fatalf("查询没有把 %s 的 NULL 收敛成空串:%s", column, query)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(query, "||'|'||") {
|
||||
t.Fatalf("查询不再产出 '<internal>|<external>' 形状:%s", query)
|
||||
}
|
||||
if !strings.Contains(query, "WHERE id='active'") {
|
||||
t.Fatalf("查询没有锁定生效绑定行:%s", query)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// v090 采集脚本是本轮新增的唯一入口。为什么用 bash -n 而不是"跑一遍":跑一遍要
|
||||
// 停写入者、连 RDS——那是真实采集,不是单元测试。语法与声明在这里钉住,能让
|
||||
// "标志写错一个字母"在 CI 里就红,而不是等到开维护窗口时才发现。
|
||||
func TestV090CaptureScriptIsSyntacticallyValid(t *testing.T) {
|
||||
bash, err := exec.LookPath("bash")
|
||||
if err != nil {
|
||||
t.Fatalf("需要 bash 才能检查脚本语法(CI 与测试机都有):%v", err)
|
||||
}
|
||||
path := filepath.Join("..", "..", "scripts", "library-capture-v090.sh")
|
||||
out, err := exec.Command(bash, "-n", path).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("bash -n %s 失败:%v\n%s", path, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
// 脚本内容断言:外部库模式(两个 -pg 传空)、写者声明、容器名、归档根、
|
||||
// LIBRARYCTL_BIN 缺失即失败——这些一旦漂移,真跑时会封错栈或读错库。
|
||||
func TestV090CaptureScriptDeclaresExternalDatabases(t *testing.T) {
|
||||
body, err := os.ReadFile(filepath.Join("..", "..", "scripts", "library-capture-v090.sh"))
|
||||
if err != nil {
|
||||
t.Fatalf("读脚本:%v", err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"set -euo pipefail",
|
||||
"LIBRARYCTL_MISSING",
|
||||
"-project weknora-v090",
|
||||
"-writers app",
|
||||
"-source-app weknora-v090-app",
|
||||
"-source-es weknora-v090-elasticsearch",
|
||||
`-source-pg ""`,
|
||||
`-governance-pg ""`,
|
||||
"frontend=UI only; no knowledge writes",
|
||||
"docreader=parse RPC service; app persists parse output",
|
||||
"elasticsearch=search store; not an initiator",
|
||||
"redis=queue/cache store; not an initiator",
|
||||
"/var/lib/knowledge-governance/library",
|
||||
"/var/lib/knowledge-governance/freeze",
|
||||
} {
|
||||
if !strings.Contains(string(body), want) {
|
||||
t.Fatalf("脚本缺少 %q", want)
|
||||
}
|
||||
}
|
||||
// 0.7.1 的服务名绝不能出现在 v090 入口里:那会让封存停错栈。
|
||||
for _, forbidden := range []string{"WKNFull", "weknora071full"} {
|
||||
if strings.Contains(string(body), forbidden) {
|
||||
t.Fatalf("v090 脚本里出现了 0.7.1 的 %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
v071 "knowledge-governance/internal/releaseadapter/v071"
|
||||
)
|
||||
|
||||
func writeDrillCanary(ctx context.Context, root string, ledger *libraryrelease.WriteSet, id string, mark func(context.Context) error, write func(context.Context) error) error {
|
||||
ledger.Rows = append(ledger.Rows, libraryrelease.WriteSetRow{Table: "knowledge_tags", ID: id, Existing: false})
|
||||
if err := ledger.Seal(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := v071.PersistWriteSet(root, ledger); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := mark(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return write(ctx)
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCanaryPersistsRecoveryEvidenceBeforeWrite(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
ledger := libraryrelease.WriteSet{Version: 1, JobID: "drill", Target: "internal", TenantID: 10000, KnowledgeBaseID: "kb", BackupSnapshotID: "backup", TargetSnapshotID: "backup", CreatedAt: time.Now().UTC(), Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
marked := false
|
||||
written := false
|
||||
err := writeDrillCanary(context.Background(), root, &ledger, "canary-id", func(context.Context) error { marked = true; return nil }, func(context.Context) error {
|
||||
if !marked {
|
||||
t.Fatal("write preceded risk marker")
|
||||
}
|
||||
if len(ledger.CreatedIDs("knowledge_tags")) != 1 {
|
||||
t.Fatal("canary absent from write set")
|
||||
}
|
||||
matches, e := filepath.Glob(filepath.Join(root, "writesets", "*.json"))
|
||||
if e != nil || len(matches) != 1 {
|
||||
t.Fatalf("durable ledger missing: %v %v", matches, e)
|
||||
}
|
||||
if _, e := os.Stat(matches[0]); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
written = true
|
||||
return nil
|
||||
})
|
||||
if err != nil || !written {
|
||||
t.Fatalf("err=%v written=%v", err, written)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanaryNeverWritesWithoutDurableLedger(t *testing.T) {
|
||||
root := filepath.Join(t.TempDir(), "blocked")
|
||||
if err := os.WriteFile(root, []byte("not a directory"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ledger := libraryrelease.WriteSet{Version: 1, JobID: "drill", Target: "internal", TenantID: 10000, KnowledgeBaseID: "kb", BackupSnapshotID: "backup", TargetSnapshotID: "backup", CreatedAt: time.Now().UTC(), Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
marked, written := false, false
|
||||
err := writeDrillCanary(context.Background(), root, &ledger, "canary-id", func(context.Context) error { marked = true; return nil }, func(context.Context) error { written = true; return nil })
|
||||
if err == nil || marked || written {
|
||||
t.Fatalf("err=%v marked=%v written=%v", err, marked, written)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanaryNeverWritesWhenRiskMarkerFails(t *testing.T) {
|
||||
ledger := libraryrelease.WriteSet{Version: 1, JobID: "drill", Target: "internal", TenantID: 10000, KnowledgeBaseID: "kb", BackupSnapshotID: "backup", TargetSnapshotID: "backup", CreatedAt: time.Now().UTC(), Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
written := false
|
||||
err := writeDrillCanary(context.Background(), t.TempDir(), &ledger, "canary-id", func(context.Context) error { return errors.New("journal unavailable") }, func(context.Context) error { written = true; return nil })
|
||||
if err == nil || written {
|
||||
t.Fatalf("err=%v written=%v", err, written)
|
||||
}
|
||||
}
|
||||
+15
-203
@@ -1,4 +1,4 @@
|
||||
// command librarydrill 在目标实例上做一次**真实**的恢复演练:
|
||||
// command librarydrill 是恢复演练的**命令行入口**,实现在 internal/libraryverify:
|
||||
//
|
||||
// 维护隔离(关入口/停写入者/证明排空)
|
||||
// → 捕获目标整库(真预备份,落归档)
|
||||
@@ -8,16 +8,14 @@
|
||||
// → 逐表/索引/资源/Wiki 再校验一次,必须完全一致
|
||||
// → 关窗口(按原运行状态恢复服务、开入口、验证健康)
|
||||
//
|
||||
// 它只读/写**被测目标自己**,绝不触碰封存源;所有凭据来自进程环境
|
||||
// (与 worker 同一份 LIBRARY_* 配置),不进命令行、不打印。
|
||||
// 任一步失败都不伪装成功:窗口保持维护、报告写明失败阶段。
|
||||
// 为什么只剩薄封装:页面要能点一次"恢复验证",worker 必须在进程内跑同一份实现。
|
||||
// 两份实现意味着"CLI 通过、页面失败"或反过来,演练结论就不可信了。
|
||||
// 它只读/写**被测目标自己**,绝不触碰封存源;所有凭据来自进程环境。
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
@@ -26,35 +24,12 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/libraryfreeze"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarystack"
|
||||
"knowledge-governance/internal/libraryverify"
|
||||
)
|
||||
|
||||
type drillVerification struct {
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Verified bool `json:"verified"`
|
||||
Error string `json:"error,omitempty"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
type drillReport struct {
|
||||
Status string `json:"status"` // passed | failed | maintenance_held
|
||||
Scope string `json:"scope"`
|
||||
Target string `json:"target"`
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Project string `json:"project"`
|
||||
Counts map[string]int64 `json:"counts"`
|
||||
BaselineCheck *drillVerification `json:"baseline_check"`
|
||||
DriftCheck *drillVerification `json:"drift_check"` // 必须失败:证明确实能发现差异
|
||||
RestoreCheck *drillVerification `json:"restore_check"`
|
||||
Canary string `json:"canary"`
|
||||
Failure string `json:"failure,omitempty"`
|
||||
Stage string `json:"stage,omitempty"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FinishedAt time.Time `json:"finished_at"`
|
||||
Until map[string]string `json:"until,omitempty"`
|
||||
}
|
||||
// 报告类型直接复用共享实现:命令行与页面/worker 的证据字段完全一致。
|
||||
type drillVerification = libraryverify.Verification
|
||||
type drillReport = libraryverify.Report
|
||||
|
||||
func main() {
|
||||
scope := flag.String("scope", "internal", "internal|external")
|
||||
@@ -88,18 +63,7 @@ func recoverWindows() error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("load config: %w", err)
|
||||
}
|
||||
manager, err := librarystack.OpenMaintenance(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer manager.Close()
|
||||
coordinator, control, err := manager.Open(config.LibraryTargetJournalRoot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer control.Close()
|
||||
defer coordinator.Close()
|
||||
if err := coordinator.Recover(context.Background()); err != nil {
|
||||
if err := libraryverify.RecoverWindows(config); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("maintenance windows recovered; target should be back to its original service state")
|
||||
@@ -107,170 +71,18 @@ func recoverWindows() error {
|
||||
}
|
||||
|
||||
func run(scope, jobID string) (*drillReport, error) {
|
||||
if scope != "internal" && scope != "external" {
|
||||
return nil, errors.New("scope must be internal or external")
|
||||
}
|
||||
config, err := appconfig.Load(os.Getenv)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load config: %w", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
report := &drillReport{Status: "failed", Scope: scope, Project: config.LibraryTargetProject,
|
||||
Target: config.LibraryTargetInstance, StartedAt: time.Now().UTC()}
|
||||
fail := func(stage string, cause error, held bool) (*drillReport, error) {
|
||||
report.Stage = stage
|
||||
report.Failure = cause.Error()
|
||||
report.FinishedAt = time.Now().UTC()
|
||||
if held {
|
||||
report.Status = "maintenance_held"
|
||||
}
|
||||
return report, cause
|
||||
}
|
||||
|
||||
target, backups, err := librarystack.OpenBaselineStack(ctx, config, scope)
|
||||
if err != nil {
|
||||
return fail("open_target", err, false)
|
||||
}
|
||||
defer target.Close()
|
||||
manager, err := librarystack.OpenMaintenance(config)
|
||||
if err != nil {
|
||||
return fail("open_maintenance", err, false)
|
||||
}
|
||||
defer manager.Close()
|
||||
if err := manager.VerifyTopology(ctx); err != nil {
|
||||
return fail("topology", err, false)
|
||||
}
|
||||
coordinator, control, err := manager.Open(config.LibraryTargetJournalRoot)
|
||||
if err != nil {
|
||||
return fail("open_coordinator", err, false)
|
||||
}
|
||||
defer control.Close()
|
||||
defer coordinator.Close()
|
||||
|
||||
if jobID == "" {
|
||||
jobID = "drill-" + scope + "-" + time.Now().UTC().Format("20060102T150405")
|
||||
jobID = fmt.Sprintf("drill-%s-%d", scope, time.Now().UTC().UnixNano())
|
||||
}
|
||||
var (
|
||||
snapshotID string
|
||||
counts map[string]int64
|
||||
canary string
|
||||
contentTouched bool
|
||||
baseline drillVerification
|
||||
drift drillVerification
|
||||
restored drillVerification
|
||||
)
|
||||
work := func(ctx context.Context, window *libraryfreeze.Window) (string, error) {
|
||||
start := time.Now()
|
||||
current, err := target.Current(ctx)
|
||||
if err != nil {
|
||||
return "", errors.New("读取目标当前整库状态失败:" + err.Error())
|
||||
}
|
||||
counts = current.Counts
|
||||
report.Counts = counts
|
||||
// 1) 真预备份(落归档、内容寻址、导出后复核内容未变)。
|
||||
backup, err := backups.Prepare(ctx, "", current)
|
||||
if err != nil {
|
||||
return "", errors.New("捕获目标整库失败:" + err.Error())
|
||||
}
|
||||
snapshotID = backup.SnapshotID
|
||||
report.SnapshotID = snapshotID
|
||||
if err := window.SetBackupSnapshot(ctx, snapshotID); err != nil {
|
||||
return "", errors.New("记录预备份身份失败:" + err.Error())
|
||||
}
|
||||
log.Printf("drill: snapshot captured snapshot=%s bytes=%d in=%s", snapshotID, backup.Bytes, time.Since(start))
|
||||
|
||||
// 2) 基线校验:预备份必须与目标完全一致。
|
||||
baseline = drillVerification{SnapshotID: snapshotID, At: time.Now().UTC()}
|
||||
if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); err != nil {
|
||||
baseline.Error = err.Error()
|
||||
report.BaselineCheck = &baseline
|
||||
return "", errors.New("预备份与目标不一致(预备份本身不可信):" + err.Error())
|
||||
}
|
||||
baseline.Verified = true
|
||||
report.BaselineCheck = &baseline
|
||||
|
||||
// Canary is an isolated tag, including on an empty target. Never seed
|
||||
// a document or change an existing row merely to make a drill possible.
|
||||
var random [16]byte
|
||||
if _, err := rand.Read(random[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
canary = fmt.Sprintf("%x", random[:])
|
||||
identityValue := target.Identity()
|
||||
var exists bool
|
||||
if err := target.Pool().QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM knowledge_tags WHERE id=$1)", canary).Scan(&exists); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if exists {
|
||||
return "", errors.New("canary identity collision; no write attempted")
|
||||
}
|
||||
ledger := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, JobID: jobID, Target: scope,
|
||||
TenantID: identityValue.TenantID, KnowledgeBaseID: identityValue.KnowledgeBaseID,
|
||||
BackupSnapshotID: snapshotID, TargetSnapshotID: snapshotID,
|
||||
CreatedAt: time.Now().UTC(), Universe: backup.Universe}
|
||||
report.Canary = canary
|
||||
if err := writeDrillCanary(ctx, config.LibraryArchiveRoot, &ledger, canary,
|
||||
func(ctx context.Context) error {
|
||||
if err := window.MarkContentRisk(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
contentTouched = true
|
||||
return nil
|
||||
}, func(ctx context.Context) error {
|
||||
_, err := target.Pool().Exec(ctx, `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id,name) VALUES($1,$2,$3,$4)`, canary, identityValue.TenantID, identityValue.KnowledgeBaseID, "drill-canary-"+canary)
|
||||
return err
|
||||
}); err != nil {
|
||||
return "", fmt.Errorf("canary preparation/write failed: %w", err)
|
||||
}
|
||||
drift = drillVerification{SnapshotID: snapshotID, At: time.Now().UTC()}
|
||||
if verifyErr := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); verifyErr == nil {
|
||||
drift.Error = "写入 canary 后校验仍然通过:校验没有真正比对内容"
|
||||
report.DriftCheck = &drift
|
||||
return "", errors.New("写入 canary 后校验仍然通过:校验没有真正比对内容,拒绝把这次演练当成通过")
|
||||
} else {
|
||||
drift.Error = verifyErr.Error()
|
||||
}
|
||||
report.DriftCheck = &drift
|
||||
log.Printf("drill: drift detected as expected (%s)", drift.Error)
|
||||
|
||||
// 4) 按预备份恢复。
|
||||
// Restore removes only the exact new canary identity in the durable write set.
|
||||
if err := target.Restore(ctx, libraryrelease.BackupRef{ID: "backup-" + snapshotID, SnapshotID: snapshotID,
|
||||
WriteSet: &ledger}); err != nil {
|
||||
return "", errors.New("按预备份恢复失败:" + err.Error())
|
||||
}
|
||||
// 5) 恢复后逐类复核:必须与预备份完全一致。
|
||||
restored = drillVerification{SnapshotID: snapshotID, At: time.Now().UTC()}
|
||||
if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); err != nil {
|
||||
restored.Error = err.Error()
|
||||
report.RestoreCheck = &restored
|
||||
return "", errors.New("恢复后内容仍与预备份不一致:" + err.Error())
|
||||
}
|
||||
restored.Verified = true
|
||||
report.RestoreCheck = &restored
|
||||
log.Printf("drill: restored and verified snapshot=%s", snapshotID)
|
||||
return snapshotID, nil
|
||||
}
|
||||
|
||||
window, windowErr := coordinator.RunWindow(ctx, jobID,
|
||||
func(ctx context.Context) error { return manager.VerifyRunning(ctx) }, work,
|
||||
// 没写过目标内容 ⇒ 按原状态恢复永远安全;写过 canary ⇒ 只有恢复并校验通过才开放。
|
||||
func(error) bool { return !contentTouched || restored.Verified })
|
||||
|
||||
report.Until = map[string]string{"job": jobID, "window_state": window.State}
|
||||
if windowErr != nil || window.State != "succeeded" {
|
||||
cause := windowErr
|
||||
if cause == nil {
|
||||
cause = fmt.Errorf("维护窗口状态 %s(未成功)", window.State)
|
||||
}
|
||||
if window.State == "held" {
|
||||
return fail("window", cause, true)
|
||||
}
|
||||
return fail("window", cause, false)
|
||||
}
|
||||
report.Status = "passed"
|
||||
report.FinishedAt = time.Now().UTC()
|
||||
return report, nil
|
||||
// 主机侧 CLI 不持有治理库连接:维护记录由调用它的作业/运维流程负责。
|
||||
// 页面发起的验证走 worker,那里 Options 同时接治理生命周期与写集合登记。
|
||||
return libraryverify.Run(context.TODO(), config, scope, jobID, libraryverify.Options{
|
||||
Progress: func(stage, state, detail string) { log.Printf("stage=%s state=%s %s", stage, state, detail) },
|
||||
})
|
||||
}
|
||||
|
||||
func writeReport(path string, report *drillReport) error {
|
||||
|
||||
@@ -87,7 +87,7 @@ func run(ctx context.Context, config appconfig.Config, scope, snapshotID, backup
|
||||
if strings.TrimSpace(expectSource) != want {
|
||||
return nil, fmt.Errorf("来源范围与 -expect-source 不一致:归档为 %s,参数为 %s", want, expectSource)
|
||||
}
|
||||
target, _, err := librarystack.OpenProductionStack(ctx, config, scope, backupSnapshotID, "")
|
||||
target, _, err := librarystack.OpenProductionStack(ctx, config, scope, backupSnapshotID, "", nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("装配目标失败: %w", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/objectgateway"
|
||||
v071 "knowledge-governance/internal/releaseadapter/v071"
|
||||
)
|
||||
|
||||
// This command belongs to the separately authenticated controller. It must not
|
||||
// be installed with control credentials in an ordinary data worker container.
|
||||
func main() {
|
||||
if e := run(); e != nil {
|
||||
fmt.Fprintln(os.Stderr, e)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
func run() error {
|
||||
path := flag.String("plan", "", "exact frozen write-set JSON")
|
||||
directory := flag.String("grant-directory", "", "private durable grant output directory")
|
||||
expected := flag.Int64("expected-epoch", -1, "previous epoch from the frozen controller intent; never guessed")
|
||||
flag.Parse()
|
||||
if *path == "" || *directory == "" || *expected < 0 || flag.NArg() != 0 {
|
||||
return errors.New("exact plan, grant directory and expected epoch required")
|
||||
}
|
||||
f, e := os.Open(*path)
|
||||
if e != nil {
|
||||
return errors.New("frozen gateway plan unavailable")
|
||||
}
|
||||
defer f.Close()
|
||||
var set libraryrelease.WriteSet
|
||||
d := json.NewDecoder(io.LimitReader(f, 16<<20))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(&set) != nil || d.Decode(&struct{}{}) != io.EOF {
|
||||
return errors.New("frozen gateway plan invalid")
|
||||
}
|
||||
provider, endpoint, bucket := os.Getenv("OBJECT_GATEWAY_PROVIDER"), os.Getenv("OBJECT_GATEWAY_ENDPOINT"), os.Getenv("OBJECT_GATEWAY_BUCKET")
|
||||
if provider == "" || endpoint == "" || bucket == "" {
|
||||
return errors.New("exact gateway target configuration required")
|
||||
}
|
||||
scope := objectgateway.Digest([]byte(provider + "\x00" + endpoint + "\x00" + bucket))
|
||||
client, e := objectgateway.NewClient(os.Getenv("OBJECT_GATEWAY_URL"), os.Getenv("OBJECT_GATEWAY_CONTROL_TOKEN"), scope)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
if e = v071.PrepareObjectGatewayGrant(ctx, client, set, *expected, provider, bucket, *directory); e != nil {
|
||||
return e
|
||||
}
|
||||
fmt.Printf("gateway grant persisted: plan=%s epoch=%d\n", set.Digest, *expected+1)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/objectgateway"
|
||||
v071 "knowledge-governance/internal/releaseadapter/v071"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
log.Print(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
func run() error {
|
||||
ctx := context.Background()
|
||||
addr := os.Getenv("OBJECT_GATEWAY_LISTEN")
|
||||
host, _, e := net.SplitHostPort(addr)
|
||||
// A reviewed TLS terminator may expose this loopback-only listener. Never bind
|
||||
// authenticated plaintext to a LAN address by an accidental config default.
|
||||
if e != nil || (host != "127.0.0.1" && host != "::1") {
|
||||
return errors.New("gateway_requires_loopback_listener")
|
||||
}
|
||||
data, control := os.Getenv("OBJECT_GATEWAY_DATA_TOKEN"), os.Getenv("OBJECT_GATEWAY_CONTROL_TOKEN")
|
||||
if len(data) < 32 || len(control) < 32 || data == control {
|
||||
return errors.New("gateway_distinct_tokens_required")
|
||||
}
|
||||
provider, endpoint, bucket := os.Getenv("OBJECT_GATEWAY_PROVIDER"), os.Getenv("OBJECT_GATEWAY_ENDPOINT"), os.Getenv("OBJECT_GATEWAY_BUCKET")
|
||||
scope := objectgateway.Digest([]byte(provider + "\x00" + endpoint + "\x00" + bucket))
|
||||
pool, e := pgxpool.New(ctx, os.Getenv("OBJECT_GATEWAY_DATABASE_URL"))
|
||||
if e != nil {
|
||||
return objectgateway.ErrPersistence
|
||||
}
|
||||
defer pool.Close()
|
||||
backend, e := v071.NewGatewayBackend(v071.S3ObjectStoreConfig{Provider: provider, Endpoint: endpoint, Bucket: bucket, Region: os.Getenv("OBJECT_GATEWAY_REGION"), AccessKeyID: os.Getenv("OBJECT_GATEWAY_ACCESS_KEY"), SecretAccessKey: os.Getenv("OBJECT_GATEWAY_SECRET_KEY"), MaxObjectBytes: 256 * 1024 * 1024})
|
||||
if e != nil {
|
||||
return errors.New("gateway_backend_configuration_invalid")
|
||||
}
|
||||
// The target bucket is shared with other writers. Admission is the journal
|
||||
// plus backend capability; retired attestation env vars are deliberately
|
||||
// ignored so an old deployment file cannot gate this path.
|
||||
g := &objectgateway.Gateway{Pool: pool, Scope: scope, Backend: backend, MaxBytes: 256 * 1024 * 1024}
|
||||
if governanceURL := os.Getenv("OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL"); governanceURL != "" {
|
||||
cfg, e := pgxpool.ParseConfig(governanceURL)
|
||||
if e != nil {
|
||||
return errors.New("gateway_control_authority_unavailable")
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
|
||||
cfg.MaxConns = 4
|
||||
governancePool, e := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if e != nil {
|
||||
return errors.New("gateway_control_authority_unavailable")
|
||||
}
|
||||
defer governancePool.Close()
|
||||
authority := &v071.GatewayGovernanceAuthority{Pool: governancePool, ArchiveRoot: os.Getenv("OBJECT_GATEWAY_ARCHIVE_ROOT"), TargetID: os.Getenv("OBJECT_GATEWAY_TARGET_ID"), Provider: provider, Bucket: bucket}
|
||||
if e = authority.Ready(ctx); e != nil {
|
||||
return e
|
||||
}
|
||||
g.Authority = authority
|
||||
}
|
||||
probe, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
if e = g.Ready(probe); e != nil {
|
||||
return e
|
||||
}
|
||||
server := &http.Server{Addr: addr, Handler: objectgateway.HTTPServer{Gateway: g, DataToken: data, ControlToken: control}, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 3 * time.Minute, WriteTimeout: 3 * time.Minute, IdleTimeout: 30 * time.Second}
|
||||
if server.ListenAndServe() != nil {
|
||||
return errors.New("gateway_listener_stopped")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// startErrorMessage builds the addressed binary and runs it long enough to
|
||||
// observe why the real entry point refused to listen.
|
||||
func startErrorMessage(t *testing.T, extra ...string) (string, int) {
|
||||
t.Helper()
|
||||
bin := filepath.Join(t.TempDir(), "object-gateway")
|
||||
build := exec.Command("go", "build", "-o", bin, ".")
|
||||
if out, err := build.CombinedOutput(); err != nil {
|
||||
t.Fatalf("build gateway: %v\n%s", err, out)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, bin)
|
||||
cmd.Env = append([]string{
|
||||
"PATH=" + os.Getenv("PATH"),
|
||||
"HOME=" + os.Getenv("HOME"),
|
||||
"OBJECT_GATEWAY_LISTEN=127.0.0.1:0",
|
||||
"OBJECT_GATEWAY_DATABASE_URL=postgres://gateway@127.0.0.1:1/gateway?sslmode=disable&connect_timeout=2",
|
||||
"OBJECT_GATEWAY_PROVIDER=minio",
|
||||
"OBJECT_GATEWAY_ENDPOINT=http://127.0.0.1:19100",
|
||||
"OBJECT_GATEWAY_BUCKET=maintenance-fixture-bucket",
|
||||
"OBJECT_GATEWAY_REGION=us-east-1",
|
||||
"OBJECT_GATEWAY_ACCESS_KEY=fixture-access-key",
|
||||
"OBJECT_GATEWAY_SECRET_KEY=fixture-secret-key",
|
||||
"OBJECT_GATEWAY_DATA_TOKEN=" + strings.Repeat("d", 32),
|
||||
"OBJECT_GATEWAY_CONTROL_TOKEN=" + strings.Repeat("c", 32),
|
||||
}, extra...)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if ctx.Err() != nil {
|
||||
t.Fatalf("gateway did not terminate; output=%s", out)
|
||||
}
|
||||
code := 0
|
||||
if exit, ok := err.(*exec.ExitError); ok {
|
||||
code = exit.ExitCode()
|
||||
} else if err != nil {
|
||||
t.Fatalf("run gateway: %v", err)
|
||||
}
|
||||
return string(out), code
|
||||
}
|
||||
|
||||
// The default shared-bucket path must not require a whole-bucket exclusive
|
||||
// writer attestation. Only the journal/backend admission gate may refuse it,
|
||||
// and a stale attestation file left behind by an older deployment must not
|
||||
// gate the default path either.
|
||||
func TestGatewayEntrypointDoesNotRequireBucketAttestation(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
env []string
|
||||
}{
|
||||
{name: "no_audit_configured"},
|
||||
{name: "stale_audit_file_ignored", env: []string{
|
||||
"OBJECT_GATEWAY_ID=retired-gateway",
|
||||
"OBJECT_GATEWAY_AUDIT_FILE=/nonexistent/expired-attestation.json",
|
||||
"OBJECT_GATEWAY_AUDIT_PUBLIC_KEY=" + base64.StdEncoding.EncodeToString(make([]byte, 32)),
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
out, code := startErrorMessage(t, tc.env...)
|
||||
if code == 0 {
|
||||
t.Fatalf("gateway exited 0 instead of reporting its admission state: %s", out)
|
||||
}
|
||||
if strings.Contains(out, "gateway_auditor_key_required") || strings.Contains(out, "gateway_exclusive_writer_evidence_unverified") {
|
||||
t.Fatalf("shared-bucket admission still gated by whole-bucket attestation: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "gateway_persistence_unavailable") && !strings.Contains(out, "gateway_backend_not_ready") {
|
||||
t.Fatalf("gateway did not reach journal/backend admission: %s", out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,10 @@ func secret(path string) string {
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := v071.CheckLegacyObjectWrites(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
configPath := flag.String("config", "", "release config json")
|
||||
knowledgeID := flag.String("knowledge", "", "knowledge id to release")
|
||||
mode := flag.String("mode", "publish", "publish | withdraw | rollback")
|
||||
|
||||
@@ -69,6 +69,10 @@ func secret(path string) string {
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := v071.CheckLegacyObjectWrites(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
configPath := flag.String("config", "", "release config json")
|
||||
knowledgeID := flag.String("knowledge", "", "knowledge id to diagnose")
|
||||
flag.Parse()
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
v071 "knowledge-governance/internal/releaseadapter/v071"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLegacyReleaseRuntimeRefusesBeforeCredentials(t *testing.T) {
|
||||
// Empty credential paths would fail differently if route assembly were reached.
|
||||
runtime, e := buildReleaseRuntime(context.Background(), releaseRuntimeConfig{})
|
||||
if runtime != nil || e == nil || e.Error() != v071.CheckLegacyObjectWrites().Error() {
|
||||
t.Fatal("legacy runtime did not fail at the no-write gate", e)
|
||||
}
|
||||
route, pools, e := buildReleaseRoute(context.Background(), "", releaseTargetSnapshotConfig{}, releaseRouteConfig{})
|
||||
if route != nil || len(pools) != 0 || e == nil || e.Error() != v071.CheckLegacyObjectWrites().Error() {
|
||||
t.Fatal("direct route bypassed the no-write gate", e)
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,9 @@ func (runtime *releaseRuntime) Close() {
|
||||
}
|
||||
|
||||
func buildReleaseRuntime(ctx context.Context, config releaseRuntimeConfig) (*releaseRuntime, error) {
|
||||
if err := v071.CheckLegacyObjectWrites(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
runtime := &releaseRuntime{}
|
||||
publishers := make(map[string]releaseworkflow.Publisher, len(config.Routes))
|
||||
for _, route := range config.Routes {
|
||||
@@ -52,6 +55,9 @@ func buildReleaseRuntime(ctx context.Context, config releaseRuntimeConfig) (*rel
|
||||
}
|
||||
|
||||
func buildReleaseRoute(ctx context.Context, archiveRoot string, snapshot releaseTargetSnapshotConfig, route releaseRouteConfig) (releaseworkflow.Publisher, []*pgxpool.Pool, error) {
|
||||
if err := v071.CheckLegacyObjectWrites(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
sourceDatabaseURL, err := readRestrictedValue(route.Source.DatabaseURLFile)
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("read source database credential")
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
)
|
||||
|
||||
// r13CountingTarget 记录 Apply 次数:锚点写失败时它必须是 0。
|
||||
type r13CountingTarget struct {
|
||||
ledgerTestTarget
|
||||
applied int
|
||||
}
|
||||
|
||||
func (t *r13CountingTarget) Apply(ctx context.Context, stage libraryrelease.Stage, snapshot string) error {
|
||||
t.applied++
|
||||
return t.ledgerTestTarget.Apply(ctx, stage, snapshot)
|
||||
}
|
||||
|
||||
// B25:写集合/预备份锚点写不进治理库时,必须在任何业务写入之前失败,目标零写入,
|
||||
// 也不许留下"已有基线"的假象。故障来自真实 PG(版本表上的 CHECK 约束拒绝写入),
|
||||
// 不是包一层必失败的假 store。
|
||||
func TestR13AnchorWriteFailureBlocksTargetIsolated(t *testing.T) {
|
||||
store, pool := openLedgerStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
const (
|
||||
scope = "internal"
|
||||
jobID = "libsync-r13-anchor"
|
||||
snapshot = "backup-snap-r13-anchor"
|
||||
target = "target-snap-r13-anchor"
|
||||
params = "params-r13-anchor"
|
||||
)
|
||||
if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ID: jobID, Scope: scope,
|
||||
Kind: governance.LibraryJobSync, IdempotencyKey: "library.sync:internal:r13-anchor",
|
||||
RequestDigest: params, Actor: "admin", TargetSnapshotID: target}, governance.SyncStages(), now); err != nil {
|
||||
t.Fatalf("create job: %v", err)
|
||||
}
|
||||
var exists bool
|
||||
// 隔离夹具把表建在每次运行专属 schema 里(search_path 指向它),
|
||||
// 因此这里用非限定名,不能写死 public。
|
||||
if err := pool.QueryRow(ctx, `SELECT to_regclass('library_versions') IS NOT NULL`).Scan(&exists); err != nil {
|
||||
t.Fatalf("locate version table: %v", err)
|
||||
}
|
||||
if !exists {
|
||||
rows, err := pool.Query(ctx, `SELECT table_schema||'.'||table_name FROM information_schema.tables
|
||||
WHERE table_name LIKE 'library%' ORDER BY 1`)
|
||||
if err == nil {
|
||||
var names []string
|
||||
for rows.Next() {
|
||||
var n string
|
||||
rows.Scan(&n)
|
||||
names = append(names, n)
|
||||
}
|
||||
rows.Close()
|
||||
t.Logf("library tables visible: %v", names)
|
||||
}
|
||||
var ledger []string
|
||||
if r2, err := pool.Query(ctx, `SELECT version::text FROM schema_migrations ORDER BY 1 DESC LIMIT 5`); err == nil {
|
||||
for r2.Next() {
|
||||
var v string
|
||||
r2.Scan(&v)
|
||||
ledger = append(ledger, v)
|
||||
}
|
||||
r2.Close()
|
||||
}
|
||||
t.Fatalf("版本表不存在:夹具/迁移不完整,本用例的前提不成立(最近迁移=%v)", ledger)
|
||||
}
|
||||
// NOT VALID:不动已有行,只让新的版本写入被真实 PG 拒绝。
|
||||
if _, err := pool.Exec(ctx, `ALTER TABLE library_versions ADD CONSTRAINT r13_anchor_reject CHECK (false) NOT VALID`); err != nil {
|
||||
t.Fatalf("inject anchor constraint: %v", err)
|
||||
}
|
||||
dropConstraint := func() {
|
||||
pool.Exec(context.Background(), `ALTER TABLE library_versions DROP CONSTRAINT IF EXISTS r13_anchor_reject`)
|
||||
}
|
||||
t.Cleanup(dropConstraint)
|
||||
recorder := libraryStageRecorder{store: store, jobID: jobID, scope: scope}
|
||||
// 写集合必须落在一次性目录,不能把测试产物写进仓库。
|
||||
inner := &r13CountingTarget{ledgerTestTarget: ledgerTestTarget{root: t.TempDir()}}
|
||||
backups := ledgerTestBackups{ref: libraryrelease.BackupRef{ID: "backup-" + snapshot, SnapshotID: snapshot,
|
||||
Bytes: 4096, Universe: map[string]libraryrelease.TableFingerprint{"resources": {Count: 1, Digest: "universe"}}}}
|
||||
request := libraryrelease.Request{JobID: jobID, Target: scope, SnapshotID: target, ParamsDigest: params,
|
||||
Now: now, Grant: libraryrelease.Grant{Target: scope, SnapshotID: target, ParamsDigest: params,
|
||||
ExpiresAt: now.Add(time.Hour), AuthorizedBy: "tester"}}
|
||||
outcome := libraryrelease.Run(ctx, request, inner, backups, recorder)
|
||||
if outcome.State != "failed" {
|
||||
t.Fatalf("锚点写失败却继续执行:%+v", outcome)
|
||||
}
|
||||
if outcome.FailedAt != "" {
|
||||
t.Fatalf("锚点失败必须早于任何阶段写入,failed_at=%q", outcome.FailedAt)
|
||||
}
|
||||
if inner.applied != 0 {
|
||||
t.Fatalf("锚点失败后仍写了目标 %d 个阶段", inner.applied)
|
||||
}
|
||||
shown := false
|
||||
for _, sub := range []string{"写集合", "登记", "constraint", "check", "23514"} {
|
||||
if strings.Contains(outcome.Error, sub) {
|
||||
shown = true
|
||||
}
|
||||
}
|
||||
if !shown {
|
||||
t.Fatalf("失败原因没有指向锚点写入:%q", outcome.Error)
|
||||
}
|
||||
versions, err := store.LibraryVersionsBySnapshot(ctx, scope, snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("read versions: %v", err)
|
||||
}
|
||||
if len(versions) != 0 {
|
||||
t.Fatalf("锚点失败却留下版本证据:%+v", versions)
|
||||
}
|
||||
// 去掉故障后同一请求能完成登记:证明失败来自注入的锚点故障,不是环境坏掉。
|
||||
dropConstraint()
|
||||
retry := libraryrelease.Run(ctx, request, inner, backups, recorder)
|
||||
if retry.State != "succeeded" {
|
||||
t.Fatalf("去掉故障后应当能完成:%+v", retry)
|
||||
}
|
||||
if inner.applied != 4 {
|
||||
t.Fatalf("去掉故障后应写满四个阶段,实际 %d", inner.applied)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build !kg_isolated_drill
|
||||
|
||||
package main
|
||||
|
||||
import "time"
|
||||
|
||||
// Production timing is not controllable through test environment variables.
|
||||
const libraryAttemptLease = 10 * time.Minute
|
||||
@@ -0,0 +1,26 @@
|
||||
//go:build kg_isolated_drill
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Only an explicitly tagged executable can shorten the real lease clock. It
|
||||
// refuses non-disposable DBs; no production binary recognizes this injection.
|
||||
const libraryAttemptLease = 4 * time.Second
|
||||
|
||||
func init() {
|
||||
if os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
|
||||
panic("isolated drill build requires explicit opt-in")
|
||||
}
|
||||
for _, name := range []string{"DATABASE_URL", "LIBRARY_PRODUCTION_DATABASE_URL"} {
|
||||
u, e := url.Parse(os.Getenv(name))
|
||||
if e != nil || (u.Hostname() != "127.0.0.1" && u.Hostname() != "localhost") || !strings.HasPrefix(u.Path, "/kg_library_test_r8_") {
|
||||
panic("isolated drill build refuses non-disposable database")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//go:build !kg_isolated_drill
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestProductionAttemptTimingIgnoresDrillEnvironment(t *testing.T) {
|
||||
t.Setenv("KG_LIBRARY_TEST_ISOLATED", "1")
|
||||
t.Setenv("WORKER_LEASE_DURATION", "1ms")
|
||||
if libraryAttemptLease != 10*time.Minute {
|
||||
t.Fatal("production lease shortened by drill injection")
|
||||
}
|
||||
}
|
||||
@@ -111,10 +111,12 @@ func runLibraryBaseline(ctx context.Context, base *postgresstore.Store, config a
|
||||
if _, admitErr := admitLibraryJob(ctx, base, job, payload.LibraryJobID, payload.Scope, governance.LibraryJobBaseline, true); admitErr != nil {
|
||||
return admitErr
|
||||
}
|
||||
writer, attemptErr := beginLibraryWriter(ctx, base, payload.LibraryJobID, libraryQueueOwner(config.WorkerID, job, payload.LibraryJobID))
|
||||
if attemptErr != nil {
|
||||
return attemptErr
|
||||
}
|
||||
return runOwnedLibraryAttempt(ctx, base, config, job, payload.LibraryJobID, func(runCtx context.Context, writer *libraryAttemptWriter) error {
|
||||
return runLibraryBaselineAttempt(runCtx, writer, config, payload)
|
||||
})
|
||||
}
|
||||
|
||||
func runLibraryBaselineAttempt(ctx context.Context, writer *libraryAttemptWriter, config appconfig.Config, payload libraryBaselinePayload) error {
|
||||
store := writer
|
||||
now := time.Now().UTC()
|
||||
recorder := libraryStageRecorder{store: store, jobID: payload.LibraryJobID, scope: payload.Scope,
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
type capturePersistenceFake struct {
|
||||
failAdvance error
|
||||
failStage error
|
||||
advanced []governance.LibraryJobState
|
||||
stages []string
|
||||
}
|
||||
|
||||
func (f *capturePersistenceFake) AdvanceLibraryJob(_ context.Context, _ string, state governance.LibraryJobState,
|
||||
_, _, _, _, _ string, _ time.Time) error {
|
||||
f.advanced = append(f.advanced, state)
|
||||
return f.failAdvance
|
||||
}
|
||||
|
||||
func (f *capturePersistenceFake) UpdateLibraryStage(_ context.Context, _, stage, state string,
|
||||
_, _, _, _ *int64, _ string, _ time.Time) error {
|
||||
f.stages = append(f.stages, stage+"/"+state)
|
||||
return f.failStage
|
||||
}
|
||||
|
||||
// The handler must stop before touching the source when the starting state
|
||||
// cannot be persisted. This is the failure injection that the old log-and-ignore
|
||||
// path hid behind a completed queue row.
|
||||
func TestBeginLibraryCaptureStopsOnAdvanceFailure(t *testing.T) {
|
||||
store := &capturePersistenceFake{failAdvance: errors.New("injected advance failure")}
|
||||
err := beginLibraryCaptureJob(context.Background(), store, "libseal-test", time.Now())
|
||||
if err == nil || !strings.Contains(err.Error(), "cannot be advanced") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobRunning {
|
||||
t.Fatalf("advance calls=%v", store.advanced)
|
||||
}
|
||||
if len(store.stages) != 0 {
|
||||
t.Fatalf("stage was written before advance failure: %v", store.stages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeginLibraryCaptureStopsOnStageFailure(t *testing.T) {
|
||||
store := &capturePersistenceFake{failStage: errors.New("injected stage failure")}
|
||||
err := beginLibraryCaptureJob(context.Background(), store, "libseal-test", time.Now())
|
||||
if err == nil || !strings.Contains(err.Error(), "stage cannot be advanced") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(store.stages) != 1 || store.stages[0] != "export/running" {
|
||||
t.Fatalf("stage calls=%v", store.stages)
|
||||
}
|
||||
}
|
||||
|
||||
// Terminal persistence is two writes; either failure must be returned rather
|
||||
// than turning the queue row into completed while the business job is pending.
|
||||
func TestCompleteLibraryCaptureStopsOnStageFailure(t *testing.T) {
|
||||
store := &capturePersistenceFake{failStage: errors.New("injected success stage failure")}
|
||||
err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now())
|
||||
if err == nil || !strings.Contains(err.Error(), "success stage cannot be persisted") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(store.advanced) != 0 {
|
||||
t.Fatalf("advance must not run after stage failure: %v", store.advanced)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteLibraryCaptureStopsOnAdvanceFailure(t *testing.T) {
|
||||
store := &capturePersistenceFake{failAdvance: errors.New("injected success advance failure")}
|
||||
err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now())
|
||||
if err == nil || !strings.Contains(err.Error(), "success terminal cannot be persisted") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(store.stages) != 1 || store.stages[0] != "export/succeeded" {
|
||||
t.Fatalf("stage calls=%v", store.stages)
|
||||
}
|
||||
if len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobSucceeded {
|
||||
t.Fatalf("advance calls=%v", store.advanced)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteLibraryCapturePersistsBothFacts(t *testing.T) {
|
||||
store := &capturePersistenceFake{}
|
||||
if err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(store.stages) != 1 || store.stages[0] != "export/succeeded" ||
|
||||
len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobSucceeded {
|
||||
t.Fatalf("stages=%v advanced=%v", store.stages, store.advanced)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/jobs"
|
||||
)
|
||||
|
||||
// R3g: only retained deterministic capture failures become permanent after the
|
||||
// agent has recovered the writer. Cancelled body-index coverage markers are
|
||||
// deliberately absent.
|
||||
func TestRetainedLibraryCaptureFailuresArePermanent(t *testing.T) {
|
||||
for _, marker := range []string{
|
||||
"missing library generated question index",
|
||||
"empty library index content",
|
||||
} {
|
||||
t.Run(marker, func(t *testing.T) {
|
||||
original := errors.New("LIBRARYCTL_FAILED: " + marker + ";已执行 recover 并确认写入者恢复")
|
||||
got := terminalLibraryCaptureError(original)
|
||||
terminal, code := jobs.Terminal(got)
|
||||
if !terminal || code != jobs.ErrCodeValidationFailed {
|
||||
t.Fatalf("retained validation failure must park immediately: terminal=%v code=%q err=%v", terminal, code, got)
|
||||
}
|
||||
if got.Error() != original.Error() {
|
||||
t.Fatalf("original message changed: got %q want %q", got.Error(), original.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelledCoverageFailureStaysRetryable(t *testing.T) {
|
||||
for _, marker := range []string{
|
||||
"unverified legacy library chunk index coverage",
|
||||
"missing indexed library chunk",
|
||||
} {
|
||||
err := terminalLibraryCaptureError(errors.New(marker + ";已执行 recover 并确认写入者恢复"))
|
||||
if terminal, code := jobs.Terminal(err); terminal {
|
||||
t.Fatalf("cancelled marker %q must not be terminal; code=%q", marker, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransientLibraryCaptureFailureStaysRetryable(t *testing.T) {
|
||||
for _, message := range []string{
|
||||
"library agent is unreachable",
|
||||
"context deadline exceeded",
|
||||
`LIBRARYCTL_FAILED: job "lib-internal-x" already exists with state "failed";已执行 recover 并确认写入者恢复`,
|
||||
"missing library generated question index; writer restore not confirmed",
|
||||
} {
|
||||
got := terminalLibraryCaptureError(errors.New(message))
|
||||
if terminal, code := jobs.Terminal(got); terminal {
|
||||
t.Fatalf("%q must stay retryable, got terminal code=%q", message, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetainedFailureDoesNotChangeMessage(t *testing.T) {
|
||||
original := errors.New("LIBRARYCTL_FAILED: missing library generated question index;已执行 recover 并确认写入者恢复")
|
||||
got := terminalLibraryCaptureError(original)
|
||||
if !strings.Contains(got.Error(), "missing library generated question index") {
|
||||
t.Fatalf("lost original cause: %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
)
|
||||
|
||||
type contractAdoptingTarget struct {
|
||||
plainTarget
|
||||
adopted int
|
||||
planned int
|
||||
reject error
|
||||
}
|
||||
|
||||
func (t *contractAdoptingTarget) AdoptWriteSet(set libraryrelease.WriteSet) error {
|
||||
t.adopted++
|
||||
return t.reject
|
||||
}
|
||||
func (t *contractAdoptingTarget) PlanWriteSet(context.Context, libraryrelease.WriteSetPlan) (libraryrelease.WriteSet, error) {
|
||||
t.planned++
|
||||
return libraryrelease.WriteSet{}, errors.New("must not replan")
|
||||
}
|
||||
|
||||
func TestContractWorkerWrapperReplaysPersistedPlan(t *testing.T) {
|
||||
for _, reject := range []bool{false, true} {
|
||||
inner := &contractAdoptingTarget{}
|
||||
if reject {
|
||||
inner.reject = errors.New("binding mismatch")
|
||||
}
|
||||
wrapped := &contentTrackedTarget{inner: inner, jobID: "job-1", onApply: func() {}}
|
||||
set := sealedLedger(t, "")
|
||||
now := time.Now().UTC()
|
||||
request := libraryrelease.Request{JobID: "job-1", Target: "internal", SnapshotID: "target-snap", ParamsDigest: "digest", Now: now,
|
||||
Grant: libraryrelease.Grant{Target: "internal", SnapshotID: "target-snap", ParamsDigest: "digest", ExpiresAt: now.Add(time.Hour), AuthorizedBy: "test"}}
|
||||
backup := ledgerBackupStore{ref: libraryrelease.BackupRef{ID: "backup-1", SnapshotID: "backup-snap", Bytes: 4096}, write: &set}
|
||||
result := libraryrelease.Run(context.Background(), request, wrapped, backup, nil)
|
||||
if inner.adopted != 1 || inner.planned != 0 {
|
||||
t.Fatalf("real wrapper lost adoption: adopted=%d planned=%d result=%+v", inner.adopted, inner.planned, result)
|
||||
}
|
||||
if reject && (inner.applied != 0 || result.State == "succeeded") {
|
||||
t.Fatal("adoption failure must be zero-write")
|
||||
}
|
||||
if !reject && result.State != "succeeded" {
|
||||
t.Fatalf("replay: %+v", result)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// B28:内容已通过校验之后的两类收尾故障必须只补收尾、不重写目标,且绝不伪报成功。
|
||||
//
|
||||
// 这里用真实治理 PG(维护行、作业行、版本事件行都是真表),故障只注入在
|
||||
// “释放 scope 维护占用”这一个步骤上;其余调用照旧打到真库。
|
||||
type r11FinishFaultStore struct {
|
||||
*postgresstore.Store
|
||||
applies *int
|
||||
failOnRelease bool
|
||||
releaseFailure error
|
||||
}
|
||||
|
||||
func (s *r11FinishFaultStore) ReleaseLibraryMaintenance(ctx context.Context, scope, ownerJobID string, now time.Time) error {
|
||||
if s.failOnRelease {
|
||||
return s.releaseFailure
|
||||
}
|
||||
return s.Store.ReleaseLibraryMaintenance(ctx, scope, ownerJobID, now)
|
||||
}
|
||||
|
||||
type r11HealthyTarget struct{ err error }
|
||||
|
||||
func (h r11HealthyTarget) VerifyRunning(context.Context) error { return h.err }
|
||||
|
||||
func TestR11FinalizeFailureAfterTerminalHoldsThenRepairsWithoutRewrite(t *testing.T) {
|
||||
store, _ := openLedgerStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
const (
|
||||
scope = "internal"
|
||||
instance = "kgseal-r11-finalize"
|
||||
jobID = "libsync-r11-finalize"
|
||||
target = "target-snap-r11-finalize"
|
||||
backup = "backup-snap-r11-finalize"
|
||||
operation = "libop-r11-finalize"
|
||||
)
|
||||
if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ID: jobID, Scope: scope,
|
||||
Kind: governance.LibraryJobSync, IdempotencyKey: "library.sync:internal:r11-finalize",
|
||||
RequestDigest: "digest-r11-finalize", Actor: "admin", TargetSnapshotID: target},
|
||||
governance.SyncStages(), now); err != nil {
|
||||
t.Fatalf("create library job: %v", err)
|
||||
}
|
||||
// 生效事件必须引用真实 operation:登记前先落这条执行意图(真表,不是夹具)。
|
||||
if _, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ID: operation, Scope: scope,
|
||||
Kind: governance.LibraryJobSync, TargetSnapshotID: target, RequestDigest: "digest-r11-finalize",
|
||||
OperationKey: "r11-finalize", Actor: "admin", CreatedAt: now}); err != nil {
|
||||
t.Fatalf("ensure library operation: %v", err)
|
||||
}
|
||||
// 这次作业确实持有两把维护锁:收尾失败后必须仍然持有(页面显示维护中)。
|
||||
if _, err := store.AcquireLibraryMaintenance(ctx, postgresstore.LibraryMaintenance{Scope: scope,
|
||||
OwnerJobID: jobID, TargetIdentity: "scope=" + scope, Level: "library", State: "acquired",
|
||||
IngressState: "closed", Services: []string{"app"}}, now); err != nil {
|
||||
t.Fatalf("acquire library maintenance: %v", err)
|
||||
}
|
||||
if _, err := store.AcquireInstanceMaintenance(ctx, postgresstore.LibraryInstanceMaintenance{Instance: instance,
|
||||
OwnerJobID: jobID, OwnerScope: scope, TargetFingerprint: "fingerprint-r11",
|
||||
Level: "instance", Services: []string{"app"}, IngressState: "closed", State: "acquired"}, now); err != nil {
|
||||
t.Fatalf("acquire instance maintenance: %v", err)
|
||||
}
|
||||
// 完整锚点:真实字节数与写集合摘要。缺任何一项,收尾都该拒绝登记而不是补一份空台账。
|
||||
if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{
|
||||
ID: governance.LibraryVersionID(governance.LibraryVersionProductionPrebackup, scope, backup),
|
||||
Scope: scope, Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: backup,
|
||||
SourceJobID: jobID, CreatedBy: "tester",
|
||||
Evidence: map[string]any{"backup_snapshot": backup, "backup_bytes": float64(4096),
|
||||
"writeset_digest": "writeset-digest-r11", "writeset_rows": float64(7)},
|
||||
CreatedAt: now,
|
||||
}); err != nil {
|
||||
t.Fatalf("record prebackup version: %v", err)
|
||||
}
|
||||
|
||||
// 目标内容落盘且计数:任何“再来一次”的重写都会让计数增长。
|
||||
root := t.TempDir()
|
||||
published := filepath.Join(root, "target-content.txt")
|
||||
if err := os.WriteFile(published, []byte("published-v1"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
applies := 1 // 内容写入(含校验)已经发生过一次
|
||||
writer := &libraryAttemptWriter{Store: store, attempt: governance.LibraryAttempt{
|
||||
OperationID: operation, JobID: jobID, Owner: "queue-r11-finalize"}}
|
||||
recorder := libraryStageRecorder{store: store, jobID: jobID, scope: scope, operationID: operation}
|
||||
payload := libraryReleasePayload{LibraryJobID: jobID, Scope: scope, TargetSnapshotID: target, FinalizeOnly: true}
|
||||
previous := governance.LibraryJob{ID: jobID, Scope: scope, Kind: governance.LibraryJobSync,
|
||||
SnapshotID: backup, TargetSnapshotID: target}
|
||||
grant := governance.LibraryReleaseAuthorization{AuthorizedBy: "admin", Scope: scope, SnapshotID: target}
|
||||
|
||||
// 1) 事件登记失败(这里用真实数据缺口:锚点里没有写集合摘要)必须拒绝登记,
|
||||
// 不写生效版本、不进入终态、不重写目标。
|
||||
if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{
|
||||
ID: governance.LibraryVersionID(governance.LibraryVersionProductionPrebackup, scope, backup+"-noanchor"),
|
||||
Scope: scope, Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: backup + "-noanchor",
|
||||
SourceJobID: jobID + "-noanchor", CreatedBy: "tester",
|
||||
Evidence: map[string]any{"backup_snapshot": backup + "-noanchor"},
|
||||
CreatedAt: now,
|
||||
}); err != nil {
|
||||
t.Fatalf("record anchorless prebackup: %v", err)
|
||||
}
|
||||
badBoundary := payload
|
||||
badBoundary.TargetSnapshotID = target + "-noanchor"
|
||||
badPrevious := previous
|
||||
badPrevious.SnapshotID = backup + "-noanchor"
|
||||
if _, err := rebuildSuccessBoundary(ctx, writer, recorder, badBoundary, badPrevious,
|
||||
governance.LibraryJobSync, grant); err == nil {
|
||||
t.Fatal("anchorless prebackup was accepted as a success boundary")
|
||||
}
|
||||
if _, found, err := store.LibraryVersionByRef(ctx, scope, governance.LibraryVersionProductionEffective,
|
||||
jobID, target+"-noanchor"); err != nil || found {
|
||||
t.Fatalf("refused registration still wrote an effective version: found=%v err=%v", found, err)
|
||||
}
|
||||
if job, err := store.LibraryJob(ctx, jobID); err != nil || job.State == governance.LibraryJobSucceeded {
|
||||
t.Fatalf("refused registration reported success: state=%v err=%v", job.State, err)
|
||||
}
|
||||
|
||||
// 2) journal 终态之后、释放维护占用这一步失败:不许报成功,锁必须继续持有。
|
||||
failing := &r11FinishFaultStore{Store: store, applies: &applies, failOnRelease: true,
|
||||
releaseFailure: errors.New("injected: scope maintenance release failed after terminal journal")}
|
||||
boundary := successBoundary{Ready: true, Backup: backup, Target: target, FinishedAt: now}
|
||||
if err := finishLibrarySuccess(ctx, failing, r11HealthyTarget{}, instance, scope, jobID, boundary); err == nil {
|
||||
t.Fatal("finish reported success even though the maintenance release failed")
|
||||
}
|
||||
if job, err := store.LibraryJob(ctx, jobID); err != nil || job.State != governance.LibraryJobFailed {
|
||||
t.Fatalf("job must be failed after finalize failure: state=%v err=%v", job.State, err)
|
||||
}
|
||||
held, err := store.LibraryMaintenanceOf(ctx, scope)
|
||||
if err != nil || held == nil || held.OwnerJobID != jobID || held.ReleasedAt != nil {
|
||||
t.Fatalf("scope maintenance must stay held by this job: %+v err=%v", held, err)
|
||||
}
|
||||
if held.State != "needs_restore" {
|
||||
t.Fatalf("held maintenance state = %q, want needs_restore", held.State)
|
||||
}
|
||||
if applies != 1 {
|
||||
t.Fatalf("finalize failure rewrote target content: applies=%d", applies)
|
||||
}
|
||||
content, err := os.ReadFile(published)
|
||||
if err != nil || string(content) != "published-v1" {
|
||||
t.Fatalf("target bytes changed during finalize failure: %q err=%v", content, err)
|
||||
}
|
||||
|
||||
// 3) 修复只补收尾:同一个持久凭据再收尾一次即可成功,且仍然不重写。
|
||||
repaired := &r11FinishFaultStore{Store: store, applies: &applies}
|
||||
if err := finishLibrarySuccess(ctx, repaired, r11HealthyTarget{}, instance, scope, jobID, boundary); err != nil {
|
||||
t.Fatalf("finalize-only repair failed: %v", err)
|
||||
}
|
||||
if job, err := store.LibraryJob(ctx, jobID); err != nil || job.State != governance.LibraryJobSucceeded {
|
||||
t.Fatalf("job not succeeded after repair: state=%v err=%v", job.State, err)
|
||||
}
|
||||
released, err := store.LibraryMaintenanceOf(ctx, scope)
|
||||
if err != nil || released == nil || released.ReleasedAt == nil {
|
||||
t.Fatalf("scope maintenance not released after repair: %+v err=%v", released, err)
|
||||
}
|
||||
if applies != 1 {
|
||||
t.Fatalf("finalize-only repair rewrote target content: applies=%d", applies)
|
||||
}
|
||||
content, err = os.ReadFile(published)
|
||||
if err != nil || string(content) != "published-v1" {
|
||||
t.Fatalf("target bytes changed during repair: %q err=%v", content, err)
|
||||
}
|
||||
|
||||
// 4) current/event 与实际内容一致:补登记的生效版本恰好一条,重复收尾不再新增。
|
||||
if _, err := rebuildSuccessBoundary(ctx, writer, recorder, payload, previous,
|
||||
governance.LibraryJobSync, grant); err != nil {
|
||||
t.Fatalf("rebuild boundary after repair: %v", err)
|
||||
}
|
||||
if _, err := rebuildSuccessBoundary(ctx, writer, recorder, payload, previous,
|
||||
governance.LibraryJobSync, grant); err != nil {
|
||||
t.Fatalf("idempotent rebuild: %v", err)
|
||||
}
|
||||
current, found, err := store.LibraryCurrentVersion(ctx, scope)
|
||||
if err != nil || !found || current.SnapshotID != target || current.SourceJobID != jobID {
|
||||
t.Fatalf("current does not point at the repaired snapshot: %+v found=%v err=%v", current, found, err)
|
||||
}
|
||||
versions, err := store.LibraryVersionsBySnapshot(ctx, scope, target)
|
||||
if err != nil {
|
||||
t.Fatalf("read effective versions: %v", err)
|
||||
}
|
||||
same := 0
|
||||
for _, version := range versions {
|
||||
if version.Kind == governance.LibraryVersionProductionEffective {
|
||||
same++
|
||||
}
|
||||
}
|
||||
if same != 1 {
|
||||
t.Fatalf("effective version rows for %s = %d, want exactly 1", target, same)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
)
|
||||
|
||||
// r11RevokingBackups 在真实预备份完成之后撤销授权:这正是"排空之后、首次写之前"
|
||||
// 被撤销的那个窗口,不是凭空造一个失败。
|
||||
type r11RevokingBackups struct {
|
||||
inner libraryrelease.BackupStore
|
||||
after func()
|
||||
}
|
||||
|
||||
func (b r11RevokingBackups) Prepare(ctx context.Context, id string, current libraryrelease.CurrentState) (libraryrelease.BackupRef, error) {
|
||||
ref, err := b.inner.Prepare(ctx, id, current)
|
||||
if err == nil && b.after != nil {
|
||||
b.after()
|
||||
}
|
||||
return ref, err
|
||||
}
|
||||
|
||||
// B30:授权在预备份之后被撤销,必须一笔目标写都不发生;同一链路在没有撤销时
|
||||
// 正常完成(正例对照,证明这条门不是靠"永远失败"通过的)。
|
||||
func TestR11RevokedAuthorizationStopsBeforeFirstWrite(t *testing.T) {
|
||||
store, _ := openLedgerStore(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
const (
|
||||
scope = "internal"
|
||||
jobID = "libsync-r11-revoke"
|
||||
snapshot = "control-snap-r11-revoke"
|
||||
target = "target-snap-r11-revoke"
|
||||
params = "params-r11-revoke"
|
||||
operation = "libop-r11-revoke"
|
||||
backup = "backup-snap-r11-revoke"
|
||||
authID = "libauth-r11-revoke"
|
||||
)
|
||||
if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ID: jobID, Scope: scope,
|
||||
Kind: governance.LibraryJobSync, IdempotencyKey: "library.sync:internal:r11-revoke",
|
||||
RequestDigest: params, Actor: "admin", TargetSnapshotID: target}, governance.SyncStages(), now); err != nil {
|
||||
t.Fatalf("create library job: %v", err)
|
||||
}
|
||||
if _, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ID: operation, Scope: scope,
|
||||
Kind: governance.LibraryJobSync, TargetSnapshotID: target, RequestDigest: params,
|
||||
OperationKey: "r11-revoke", Actor: "admin", CreatedAt: now}); err != nil {
|
||||
t.Fatalf("ensure library operation: %v", err)
|
||||
}
|
||||
if err := store.CreateLibraryAuthorization(ctx, governance.LibraryReleaseAuthorization{ID: authID, Scope: scope,
|
||||
SnapshotID: target, ParamsDigest: params, AuthorizedBy: "admin", ExpiresAt: now.Add(time.Hour), CreatedAt: now}); err != nil {
|
||||
t.Fatalf("create authorization: %v", err)
|
||||
}
|
||||
grant := libraryrelease.Grant{Target: scope, SnapshotID: target, ParamsDigest: params,
|
||||
ExpiresAt: now.Add(time.Hour), AuthorizedBy: "admin"}
|
||||
request := libraryrelease.Request{JobID: jobID, Target: scope, SnapshotID: target,
|
||||
ParamsDigest: params, Now: now, Grant: grant}
|
||||
backups := ledgerTestBackups{ref: libraryrelease.BackupRef{ID: "backup-" + backup, SnapshotID: backup,
|
||||
Bytes: 4096, Universe: map[string]libraryrelease.TableFingerprint{"resources": {Count: 1, Digest: "universe"}}}}
|
||||
|
||||
// 正例对照:授权有效时同一条链路写完四个阶段。
|
||||
control := &planningTarget{}
|
||||
controlTarget := &contentTrackedTarget{inner: control, jobID: jobID, onApply: func() {},
|
||||
revalidateGrant: revalidateLibraryGrant(store)}
|
||||
if out := libraryrelease.Run(ctx, request, controlTarget, backups, nil); out.State != "succeeded" {
|
||||
t.Fatalf("control run did not succeed with a live authorization: %+v", out)
|
||||
}
|
||||
if control.applied != 4 {
|
||||
t.Fatalf("control run applied %d stages, want 4", control.applied)
|
||||
}
|
||||
|
||||
// 撤销后:预备份成功、授权随即失效,写集合都不该被算出来(那会分配序列)。
|
||||
guarded := &planningTarget{}
|
||||
guardedTarget := &contentTrackedTarget{inner: guarded, jobID: jobID, onApply: func() {},
|
||||
revalidateGrant: revalidateLibraryGrant(store)}
|
||||
revoking := r11RevokingBackups{inner: backups, after: func() {
|
||||
if err := store.RevokeLibraryAuthorization(ctx, authID, time.Now().UTC()); err != nil {
|
||||
t.Fatalf("revoke authorization: %v", err)
|
||||
}
|
||||
}}
|
||||
out := libraryrelease.Run(ctx, request, guardedTarget, revoking, nil)
|
||||
if out.State != "failed" {
|
||||
t.Fatalf("revoked authorization still produced state %q: %+v", out.State, out)
|
||||
}
|
||||
if !strings.Contains(out.Error, "持久授权") {
|
||||
t.Fatalf("refusal reason does not name the persisted authorization: %q", out.Error)
|
||||
}
|
||||
if guarded.applied != 0 || guarded.planned != 0 {
|
||||
t.Fatalf("revoked authorization wrote target: applied=%d planned=%d", guarded.applied, guarded.planned)
|
||||
}
|
||||
if out.Backup.SnapshotID != backup || !strings.Contains(out.Recovery, "预备份保留") {
|
||||
t.Fatalf("prebackup must be preserved for a retry: backup=%+v recovery=%q", out.Backup, out.Recovery)
|
||||
}
|
||||
// 撤销是持久的:再读一次仍然查不到有效授权。
|
||||
if _, ok, err := store.ActiveLibraryAuthorization(ctx, scope, target, params, time.Now().UTC()); err != nil || ok {
|
||||
t.Fatalf("revocation did not persist: ok=%v err=%v", ok, err)
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,40 @@ type contentTrackedTarget struct {
|
||||
inner libraryrelease.Target
|
||||
jobID string
|
||||
onApply func()
|
||||
// revalidateGrant 由 runLibraryRelease 无条件接线:每笔副作用前按治理库里的
|
||||
// 授权行重新判定(撤销/过期即停)。测试夹具可以显式传 nil 表示"这份夹具没有
|
||||
// 持久授权行",但真实发布路径不允许为空 —— 那里的空值等于回到只信内存快照。
|
||||
revalidateGrant func(context.Context, libraryrelease.Grant) error
|
||||
}
|
||||
|
||||
// revalidateLibraryGrant 是"授权没有被中途撤销/过期"的唯一判定实现:
|
||||
// 真实发布链路与测试都走它,避免测试自己写一份看起来相同的查询。
|
||||
func revalidateLibraryGrant(store *postgresstore.Store) func(context.Context, libraryrelease.Grant) error {
|
||||
return func(ctx context.Context, current libraryrelease.Grant) error {
|
||||
// 权威来源是治理库里的授权行:参数摘要一变就查不到,撤销/过期立即消失。
|
||||
found, ok, err := store.ActiveLibraryAuthorization(ctx, current.Target, current.SnapshotID,
|
||||
current.ParamsDigest, time.Now().UTC())
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取持久授权失败:%w", err)
|
||||
}
|
||||
if !ok {
|
||||
return errors.New("当前授权已撤销或已过期")
|
||||
}
|
||||
if found.AuthorizedBy != current.AuthorizedBy {
|
||||
return errors.New("持久授权与本次执行身份不一致")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (t *contentTrackedTarget) RevalidateGrant(ctx context.Context, grant libraryrelease.Grant) error {
|
||||
if t.revalidateGrant != nil {
|
||||
return t.revalidateGrant(ctx, grant)
|
||||
}
|
||||
if inner, ok := t.inner.(libraryrelease.GrantRevalidator); ok {
|
||||
return inner.RevalidateGrant(ctx, grant)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *contentTrackedTarget) Current(ctx context.Context) (libraryrelease.CurrentState, error) {
|
||||
@@ -91,6 +125,20 @@ func (t *contentTrackedTarget) PlanWriteSet(ctx context.Context, plan libraryrel
|
||||
return set, err
|
||||
}
|
||||
|
||||
func (t *contentTrackedTarget) AdoptWriteSet(set libraryrelease.WriteSet) error {
|
||||
adopter, ok := t.inner.(libraryrelease.WriteSetAdopter)
|
||||
if !ok {
|
||||
return errors.New("目标实现不支持接管已持久化写集合,拒绝重建计划")
|
||||
}
|
||||
if set.JobID != t.jobID {
|
||||
return errors.New("写集合与 worker 作业身份不符")
|
||||
}
|
||||
return adopter.AdoptWriteSet(set)
|
||||
}
|
||||
|
||||
var _ libraryrelease.WriteSetPlanner = (*contentTrackedTarget)(nil)
|
||||
var _ libraryrelease.WriteSetAdopter = (*contentTrackedTarget)(nil)
|
||||
|
||||
// libraryReleasePayload 是同步与恢复共用的队列载荷形状。
|
||||
type libraryReleasePayload struct {
|
||||
LibraryJobID string `json:"library_job_id"`
|
||||
@@ -117,19 +165,13 @@ func runLibraryRelease(ctx context.Context, base *postgresstore.Store, config ap
|
||||
if _, admitErr := admitLibraryJob(ctx, base, job, payload.LibraryJobID, payload.Scope, kind, true); admitErr != nil {
|
||||
return admitErr
|
||||
}
|
||||
// 执行代次:这一次投递是一个确定的执行者身份。所有治理写入都走 writer
|
||||
// (同名方法带 epoch 守卫),失租的旧执行从此写不进业务状态/维护锁(F13)。
|
||||
writer, attemptErr := beginLibraryWriter(ctx, base, payload.LibraryJobID, libraryQueueOwner(config.WorkerID, job, payload.LibraryJobID))
|
||||
if attemptErr != nil {
|
||||
return attemptErr
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
writer.finish(context.WithoutCancel(ctx), governance.LibraryAttemptFailed, err.Error())
|
||||
return
|
||||
}
|
||||
writer.finish(context.WithoutCancel(ctx), governance.LibraryAttemptCompleted, "")
|
||||
}()
|
||||
return runOwnedLibraryAttempt(ctx, base, config, job, payload.LibraryJobID, func(runCtx context.Context, writer *libraryAttemptWriter) error {
|
||||
return runLibraryReleaseAttempt(runCtx, writer, config, kind, payload)
|
||||
})
|
||||
}
|
||||
|
||||
func runLibraryReleaseAttempt(ctx context.Context, writer *libraryAttemptWriter, config appconfig.Config,
|
||||
kind governance.LibraryJobKind, payload libraryReleasePayload) (err error) {
|
||||
store := writer
|
||||
now := time.Now().UTC()
|
||||
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobRunning, "prebackup", "", "", "", "", now)
|
||||
@@ -191,8 +233,8 @@ func runLibraryRelease(ctx context.Context, base *postgresstore.Store, config ap
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
gateReasons = append(gateReasons, "生产写入闸口关闭")
|
||||
}
|
||||
if !config.ProductionBackupRestoreVerified {
|
||||
gateReasons = append(gateReasons, "没有已核验的生产恢复演练证据")
|
||||
if ok, reason := libraryRestoreEvidenceSatisfied(ctx, store, config, payload.Scope); !ok {
|
||||
gateReasons = append(gateReasons, reason)
|
||||
}
|
||||
if len(gateReasons) > 0 {
|
||||
message := "生产" + kindLabel(kind) + "被闸口拒绝:" + strings.Join(gateReasons, ";")
|
||||
@@ -230,7 +272,7 @@ func runLibraryRelease(ctx context.Context, base *postgresstore.Store, config ap
|
||||
// 生产索引映射基线:权威来源是当前生效版本(精确查),其次任何一次成功记录的映射。
|
||||
// 只认"生效版本"会在恢复把版本顶替掉之后误判"索引被改动"。
|
||||
knownMapping := knownIndexMapping(ctx, store, payload.Scope)
|
||||
target, backups, wireErr := buildLibraryProductionStack(ctx, config, payload.Scope, payload.TargetSnapshotID, knownMapping)
|
||||
target, backups, wireErr := buildLibraryProductionStack(ctx, config, restoreDispatchGate(config, store.Store), payload.Scope, payload.TargetSnapshotID, knownMapping)
|
||||
if wireErr == nil {
|
||||
if mapping, mapErr := target.Search().MappingSHA256(ctx); mapErr == nil {
|
||||
recorder.mappingDigest = mapping
|
||||
@@ -320,7 +362,8 @@ func runLibraryRelease(ctx context.Context, base *postgresstore.Store, config ap
|
||||
}
|
||||
pending := successBoundary{}
|
||||
tracked := &contentTrackedTarget{inner: target, jobID: payload.LibraryJobID,
|
||||
onApply: func() { contentState = contentHalfWritten }}
|
||||
onApply: func() { contentState = contentHalfWritten },
|
||||
revalidateGrant: revalidateLibraryGrant(store.Store)}
|
||||
allowRestore := func(error) bool {
|
||||
return contentState == contentUntouched || contentState == contentSucceeded || contentState == contentRolledBack
|
||||
}
|
||||
@@ -549,6 +592,11 @@ func runLibraryRelease(ctx context.Context, base *postgresstore.Store, config ap
|
||||
// 已经持久化预备份的重新排队(同一个业务作业 id,阶段与备份都接着用),
|
||||
// 连预备份都没完成的才判失败——那种情况没有可回滚的基线,不能盲写。
|
||||
func resumeInterruptedLibraryJobs(ctx context.Context, store libraryResumeStore, config appconfig.Config) (int, int, error) {
|
||||
if recoveries, ok := store.(interface{ ResumeExpiredLibraryRecoveryQueues(context.Context) error }); ok {
|
||||
if err := recoveries.ResumeExpiredLibraryRecoveryQueues(ctx); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
}
|
||||
interrupted, err := store.InterruptedLibraryJobs(ctx)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
@@ -580,6 +628,10 @@ func resumeInterruptedLibraryJobs(ctx context.Context, store libraryResumeStore,
|
||||
// 基线作业被杀时窗口可能还停着目标:用同一个作业 id 接管那个窗口,
|
||||
// 继续捕获/校验,而不是留下一个 held 目标等人工处理。
|
||||
queueType = libraryBaselineJobType
|
||||
case governance.LibraryJobVerify:
|
||||
// 恢复验证同样持有维护窗口:接管时必须用同一份作业 id 收掉那个窗口,
|
||||
// 否则目标会一直停在维护里而作业显示失败。
|
||||
queueType = libraryVerifyJobType
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]string{"library_job_id": job.ID, "scope": job.Scope,
|
||||
"target_snapshot_id": job.TargetSnapshotID})
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Run remains synchronous: cancellation is a request, not proof that the last
|
||||
// network write has stopped. The caller may release ownership only after run
|
||||
// and its cleanup have actually returned, and the renewal goroutine is joined.
|
||||
func runWithLibraryLease(parent context.Context, interval time.Duration, renew func(context.Context) error, run func(context.Context) error) error {
|
||||
ctx, cancel := context.WithCancelCause(parent)
|
||||
defer cancel(nil)
|
||||
stop := make(chan struct{})
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
done <- nil
|
||||
return
|
||||
case <-ctx.Done():
|
||||
done <- context.Cause(ctx)
|
||||
return
|
||||
case <-ticker.C:
|
||||
bounded, finish := context.WithTimeout(ctx, interval)
|
||||
err := renew(bounded)
|
||||
finish()
|
||||
if err != nil {
|
||||
cancel(err)
|
||||
done <- err
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
err := run(ctx)
|
||||
close(stop)
|
||||
leaseErr := <-done
|
||||
return errors.Join(err, leaseErr, context.Cause(ctx))
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestContractLeaseLossWaitsForActualWriteExit(t *testing.T) {
|
||||
lost := errors.New("lease lost")
|
||||
entered := make(chan struct{})
|
||||
cancelled := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
finished := make(chan error, 1)
|
||||
go func() {
|
||||
finished <- runWithLibraryLease(context.Background(), time.Millisecond, func(context.Context) error { <-entered; return lost }, func(ctx context.Context) error { close(entered); <-ctx.Done(); close(cancelled); <-release; return nil })
|
||||
}()
|
||||
select {
|
||||
case <-cancelled:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("loss did not cancel actual writer")
|
||||
}
|
||||
select {
|
||||
case <-finished:
|
||||
t.Fatal("returned while actual write still running")
|
||||
default:
|
||||
}
|
||||
close(release)
|
||||
select {
|
||||
case err := <-finished:
|
||||
if !errors.Is(err, lost) {
|
||||
t.Fatalf("loss hidden: %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("writer not joined")
|
||||
}
|
||||
}
|
||||
|
||||
func TestContractLeaseRenewsDuringLongWrite(t *testing.T) {
|
||||
renewed := make(chan struct{}, 1)
|
||||
err := runWithLibraryLease(context.Background(), time.Millisecond, func(context.Context) error {
|
||||
select {
|
||||
case renewed <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return nil
|
||||
}, func(ctx context.Context) error {
|
||||
select {
|
||||
case <-renewed:
|
||||
return nil
|
||||
case <-time.After(time.Second):
|
||||
return errors.New("no renewal")
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/objectgateway"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"time"
|
||||
)
|
||||
|
||||
// All target-changing handlers share one execution lock, not one lock per job or
|
||||
// scope. Lease loss cancels work but cannot release ownership before cleanup joins.
|
||||
func runOwnedLibraryAttempt(ctx context.Context, base *postgresstore.Store, config appconfig.Config, queue jobs.Job, jobID string, run func(context.Context, *libraryAttemptWriter) error) error {
|
||||
return base.WithLibraryExecution(ctx, config.LibraryTargetInstance, func(ctx context.Context, ping func(context.Context) error) (err error) {
|
||||
writer, err := beginLibraryWriter(ctx, base, jobID, libraryQueueOwner(config.WorkerID, queue, jobID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
finishCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
if err != nil {
|
||||
writer.finish(finishCtx, governance.LibraryAttemptFailed, err.Error())
|
||||
} else {
|
||||
writer.finish(finishCtx, governance.LibraryAttemptCompleted, "")
|
||||
}
|
||||
}()
|
||||
return runWithLibraryLease(ctx, libraryAttemptLease/10, func(probe context.Context) error {
|
||||
if err := ping(probe); err != nil {
|
||||
return err
|
||||
}
|
||||
return base.RenewLibraryAttempt(probe, writer.attempt, libraryAttemptLease, time.Now().UTC())
|
||||
}, func(runCtx context.Context) error {
|
||||
runCtx = objectgateway.WithClaim(runCtx, objectgateway.Claim{JobID: writer.attempt.JobID, OperationID: writer.attempt.OperationID, AttemptEpoch: int64(writer.attempt.Epoch), Owner: writer.attempt.Owner})
|
||||
return run(runCtx, writer)
|
||||
})
|
||||
})
|
||||
}
|
||||
+113
-91
@@ -10,10 +10,12 @@ import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"bytes"
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/objectgateway"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
v071 "knowledge-governance/internal/releaseadapter/v071"
|
||||
)
|
||||
@@ -21,8 +23,13 @@ import (
|
||||
// libraryRecoveryPayload 是"按预备份恢复并校验"的队列载荷。
|
||||
// 它只说明动哪个窗口;恢复目标快照由 journal 里持久化的那份决定,调用方改不了。
|
||||
type libraryRecoveryPayload struct {
|
||||
Scope string `json:"scope"`
|
||||
WindowJobID string `json:"window_job_id"`
|
||||
Scope string `json:"scope"`
|
||||
WindowJobID string `json:"window_job_id"`
|
||||
SourceSnapshot string `json:"source_snapshot_id,omitempty"`
|
||||
TargetID string `json:"target_id,omitempty"`
|
||||
OriginalOperation string `json:"original_operation_id,omitempty"`
|
||||
BackupSnapshot string `json:"backup_snapshot_id,omitempty"`
|
||||
PlanDigest string `json:"plan_digest,omitempty"`
|
||||
}
|
||||
|
||||
// runLibraryRecovery 是"内容风险未验证"窗口的唯一收尾入口:
|
||||
@@ -30,10 +37,15 @@ type libraryRecoveryPayload struct {
|
||||
// 只有校验通过才恢复服务、开入口、释放占用。失败则保持维护。
|
||||
func runLibraryRecovery(ctx context.Context, store *postgresstore.Store, config appconfig.Config, job jobs.Job) error {
|
||||
var payload libraryRecoveryPayload
|
||||
if err := json.Unmarshal(job.Payload, &payload); err != nil ||
|
||||
decoder := json.NewDecoder(bytes.NewReader(job.Payload))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&payload); err != nil ||
|
||||
(payload.Scope != "internal" && payload.Scope != "external") || payload.WindowJobID == "" {
|
||||
return errors.New("invalid library recovery payload")
|
||||
}
|
||||
if err := store.ValidateLibraryRecoveryQueue(ctx, job, payload.Scope, payload.WindowJobID); err != nil {
|
||||
return err
|
||||
}
|
||||
manager, err := openLibraryMaintenance(config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("目标维护未接线,不能做恢复:%w", err)
|
||||
@@ -62,93 +74,98 @@ func runLibraryRecovery(ctx context.Context, store *postgresstore.Store, config
|
||||
if admitErr != nil {
|
||||
return admitErr
|
||||
}
|
||||
// 恢复是一次**新执行代次**:它接管这个窗口,旧代次从此不能写业务状态/释放锁(F13)。
|
||||
writer, attemptErr := beginLibraryWriter(ctx, store, payload.WindowJobID, libraryQueueOwner(config.WorkerID, job, payload.WindowJobID))
|
||||
if attemptErr != nil {
|
||||
return fmt.Errorf("无法取得恢复窗口的执行权:%w", attemptErr)
|
||||
}
|
||||
guarded := writer
|
||||
prebackup := windowJob.SnapshotID
|
||||
if prebackup == "" {
|
||||
return errors.New("原作业没有持久化预备份,无法证明恢复到哪一份")
|
||||
}
|
||||
// 恢复是**新意图**(kind=recover):内容更旧、意图更新。把恢复事实挂在失败作业的旧
|
||||
// operation 上会被 current 的次序(按意图创建时间)判成迟到事实而拒绝——F06 就治不好。
|
||||
recoveryDigest, digestErr := governance.LibraryRequestDigest(payload.Scope, governance.LibraryJobRecover,
|
||||
map[string]any{"window_job": payload.WindowJobID, "backup_snapshot": prebackup})
|
||||
if digestErr != nil {
|
||||
return fmt.Errorf("无法计算恢复意图摘要:%w", digestErr)
|
||||
}
|
||||
recoveryKey := fmt.Sprintf("%s#%d", payload.WindowJobID, writer.attempt.Epoch)
|
||||
recoveryOp, _, opErr := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{
|
||||
ID: governance.LibraryOperationID(payload.Scope, governance.LibraryJobRecover, recoveryKey),
|
||||
Scope: payload.Scope, Kind: governance.LibraryJobRecover, TargetSnapshotID: prebackup,
|
||||
RequestDigest: recoveryDigest, OperationKey: recoveryKey, Actor: job.LeaseOwner,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
return runOwnedLibraryAttempt(ctx, store, config, job, payload.WindowJobID, func(ctx context.Context, writer *libraryAttemptWriter) error {
|
||||
guarded := writer
|
||||
prebackup := windowJob.SnapshotID
|
||||
if prebackup == "" {
|
||||
return errors.New("原作业没有持久化预备份,无法证明恢复到哪一份")
|
||||
}
|
||||
// 恢复必须带着"这次作业写了什么"的持久记录:没有它就只能按目标现状推断残渣,
|
||||
// 而那会误删历史孤儿/其它知识库暂未绑定的资源(快照里没有这些行,删了回不来)。
|
||||
ledger, ledgerErr := loadWriteSetForJob(ctx, store, config.LibraryArchiveRoot, payload.Scope,
|
||||
payload.WindowJobID, prebackup)
|
||||
if ledgerErr != nil {
|
||||
note := "恢复缺少持久化的写集合记录,目标保持维护:" + ledgerErr.Error()
|
||||
_ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, time.Now().UTC())
|
||||
_ = guarded.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.WindowJobID, "needs_restore", note, time.Now().UTC())
|
||||
return errors.New(note)
|
||||
}
|
||||
for _, pair := range [][2]string{{payload.SourceSnapshot, ledger.TargetSnapshotID}, {payload.TargetID, config.LibraryTargetIdentity()}, {payload.OriginalOperation, windowJob.OperationID}, {payload.BackupSnapshot, prebackup}, {payload.PlanDigest, ledger.Digest}} {
|
||||
if pair[0] != "" && pair[0] != pair[1] {
|
||||
return errors.New("recovery supplied identity differs from original immutable binding")
|
||||
}
|
||||
}
|
||||
recoveryDigest, digestErr := governance.LibraryRecoveryDigest(payload.Scope, job.ID, payload.WindowJobID, windowJob.OperationID, config.LibraryTargetIdentity(), ledger.TargetSnapshotID, prebackup, ledger.Digest)
|
||||
if digestErr != nil {
|
||||
return digestErr
|
||||
}
|
||||
recoveryOp, _, opErr := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{
|
||||
ID: governance.LibraryOperationID(payload.Scope, governance.LibraryJobRecover, job.ID),
|
||||
Scope: payload.Scope, Kind: governance.LibraryJobRecover, TargetSnapshotID: prebackup,
|
||||
RequestDigest: recoveryDigest, OperationKey: job.ID, Actor: job.LeaseOwner, CreatedAt: job.CreatedAt,
|
||||
})
|
||||
if opErr != nil {
|
||||
return opErr
|
||||
}
|
||||
claim := objectgateway.ClaimFromContext(ctx)
|
||||
if claim.JobID == "" {
|
||||
return errors.New("recovery attempt context missing")
|
||||
}
|
||||
claim.RecoveryJobID, claim.RecoveryOperationID = job.ID, recoveryOp.ID
|
||||
ctx = objectgateway.WithClaim(ctx, claim)
|
||||
knownMapping := knownIndexMapping(ctx, store, payload.Scope)
|
||||
target, _, wireErr := buildLibraryProductionStack(ctx, config, restoreDispatchGate(config, store), payload.Scope, prebackup, knownMapping)
|
||||
if wireErr != nil {
|
||||
return fmt.Errorf("恢复目标装配失败:%w", wireErr)
|
||||
}
|
||||
defer target.Close()
|
||||
|
||||
coordinator, control, openErr := manager.Open(config.LibraryTargetJournalRoot)
|
||||
if openErr != nil {
|
||||
return fmt.Errorf("维护协调器不可用:%w", openErr)
|
||||
}
|
||||
defer control.Close()
|
||||
defer coordinator.Close()
|
||||
|
||||
restorer := recoveryRestorer{target: target, expected: prebackup, writeSet: ledger,
|
||||
// 恢复验证写的是"隔离 canary",不是发布计划:同一 job 的收尾走受限的演练
|
||||
// 恢复入口(同样的身份合同 + 整段回放),不能拿发布计划合同去回放它。
|
||||
drill: windowJob.Kind == governance.LibraryJobVerify}
|
||||
verifier := recoveryVerifier{target: target, expected: prebackup}
|
||||
result, recoverErr := coordinator.RecoverWindow(ctx, payload.WindowJobID, restorer, verifier)
|
||||
now := time.Now().UTC()
|
||||
if recoverErr != nil {
|
||||
note := "恢复/校验未通过,目标保持维护:" + recoverErr.Error()
|
||||
_ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, now)
|
||||
_ = guarded.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.WindowJobID, "needs_restore", note, now)
|
||||
return recoverErr
|
||||
}
|
||||
if result.State != "recovered" {
|
||||
note := "恢复流程结束但状态不是 recovered:" + result.State
|
||||
_ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, now)
|
||||
return errors.New(note)
|
||||
}
|
||||
// 恢复事实必须落成**新事件并推进 current**(F06)。旧实现只释放锁:物理内容已经
|
||||
// 是预备份那份,页面/差异/后续作业却仍以为失败的新版本生效,下一步就会拿错基线决策。
|
||||
// 事件是追加的,不改写原来那条失败作业与失败版本。
|
||||
digest := result.Digest
|
||||
if digest == "" {
|
||||
return errors.New("恢复完成但没有校验摘要:拒绝登记恢复事实(无法证明恢复到了哪一份内容)")
|
||||
}
|
||||
if err := recordRecoveryEvent(ctx, writer, recoveryOp, payload.Scope, payload.WindowJobID, result.SnapshotID,
|
||||
digest, "按预备份恢复并逐类校验通过"); err != nil {
|
||||
return fmt.Errorf("恢复已完成但恢复事实登记失败:%w", err)
|
||||
}
|
||||
// 收尾顺序:先登记事实,再释放占用。反过来会出现"锁已放、current 还指向失败版本"
|
||||
// 的窗口——那正是页面把恢复成功显示成待恢复的状态。
|
||||
if err := releaseWindowLocks(ctx, guarded, identity.Instance, payload.Scope, payload.WindowJobID,
|
||||
"按预备份恢复并逐类校验通过,目标已按原运行状态恢复", now); err != nil {
|
||||
return fmt.Errorf("恢复已验证,但维护占用释放失败:%w", err)
|
||||
}
|
||||
log.Printf("library recovery succeeded window=%s scope=%s backup=%s digest=%s",
|
||||
payload.WindowJobID, payload.Scope, prebackup, digest)
|
||||
return nil
|
||||
})
|
||||
if opErr != nil {
|
||||
return fmt.Errorf("无法登记恢复意图:%w", opErr)
|
||||
}
|
||||
// 恢复必须带着"这次作业写了什么"的持久记录:没有它就只能按目标现状推断残渣,
|
||||
// 而那会误删历史孤儿/其它知识库暂未绑定的资源(快照里没有这些行,删了回不来)。
|
||||
ledger, ledgerErr := loadWriteSetForJob(ctx, store, config.LibraryArchiveRoot, payload.Scope,
|
||||
payload.WindowJobID, prebackup)
|
||||
if ledgerErr != nil {
|
||||
note := "恢复缺少持久化的写集合记录,目标保持维护:" + ledgerErr.Error()
|
||||
_ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, time.Now().UTC())
|
||||
_ = guarded.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.WindowJobID, "needs_restore", note, time.Now().UTC())
|
||||
return errors.New(note)
|
||||
}
|
||||
knownMapping := knownIndexMapping(ctx, store, payload.Scope)
|
||||
target, _, wireErr := buildLibraryProductionStack(ctx, config, payload.Scope, prebackup, knownMapping)
|
||||
if wireErr != nil {
|
||||
return fmt.Errorf("恢复目标装配失败:%w", wireErr)
|
||||
}
|
||||
defer target.Close()
|
||||
|
||||
coordinator, control, openErr := manager.Open(config.LibraryTargetJournalRoot)
|
||||
if openErr != nil {
|
||||
return fmt.Errorf("维护协调器不可用:%w", openErr)
|
||||
}
|
||||
defer control.Close()
|
||||
defer coordinator.Close()
|
||||
|
||||
restorer := recoveryRestorer{target: target, expected: prebackup, writeSet: ledger}
|
||||
verifier := recoveryVerifier{target: target, expected: prebackup}
|
||||
result, recoverErr := coordinator.RecoverWindow(ctx, payload.WindowJobID, restorer, verifier)
|
||||
now := time.Now().UTC()
|
||||
if recoverErr != nil {
|
||||
note := "恢复/校验未通过,目标保持维护:" + recoverErr.Error()
|
||||
_ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, now)
|
||||
_ = guarded.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.WindowJobID, "needs_restore", note, now)
|
||||
return recoverErr
|
||||
}
|
||||
if result.State != "recovered" {
|
||||
note := "恢复流程结束但状态不是 recovered:" + result.State
|
||||
_ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, now)
|
||||
return errors.New(note)
|
||||
}
|
||||
// 恢复事实必须落成**新事件并推进 current**(F06)。旧实现只释放锁:物理内容已经
|
||||
// 是预备份那份,页面/差异/后续作业却仍以为失败的新版本生效,下一步就会拿错基线决策。
|
||||
// 事件是追加的,不改写原来那条失败作业与失败版本。
|
||||
digest := result.Digest
|
||||
if digest == "" {
|
||||
return errors.New("恢复完成但没有校验摘要:拒绝登记恢复事实(无法证明恢复到了哪一份内容)")
|
||||
}
|
||||
if err := recordRecoveryEvent(ctx, writer, recoveryOp, payload.Scope, payload.WindowJobID, result.SnapshotID,
|
||||
digest, "按预备份恢复并逐类校验通过"); err != nil {
|
||||
return fmt.Errorf("恢复已完成但恢复事实登记失败:%w", err)
|
||||
}
|
||||
// 收尾顺序:先登记事实,再释放占用。反过来会出现"锁已放、current 还指向失败版本"
|
||||
// 的窗口——那正是页面把恢复成功显示成待恢复的状态。
|
||||
if err := releaseWindowLocks(ctx, guarded, identity.Instance, payload.Scope, payload.WindowJobID,
|
||||
"按预备份恢复并逐类校验通过,目标已按原运行状态恢复", now); err != nil {
|
||||
return fmt.Errorf("恢复已验证,但维护占用释放失败:%w", err)
|
||||
}
|
||||
writer.finish(context.WithoutCancel(ctx), governance.LibraryAttemptCompleted, "recovered")
|
||||
log.Printf("library recovery succeeded window=%s scope=%s backup=%s digest=%s",
|
||||
payload.WindowJobID, payload.Scope, prebackup, digest)
|
||||
return nil
|
||||
}
|
||||
|
||||
// recoveryRestorer 只按"作业记录里那份预备份"恢复:协调器传进来的 id 与它不一致
|
||||
@@ -157,6 +174,8 @@ type recoveryRestorer struct {
|
||||
target *v071.ProductionLibraryTarget
|
||||
expected string
|
||||
writeSet *libraryrelease.WriteSet
|
||||
// drill 表示窗口属于恢复演练:它的写集合是 canary,不是发布执行计划。
|
||||
drill bool
|
||||
}
|
||||
|
||||
func (r recoveryRestorer) Restore(ctx context.Context, backupID string) error {
|
||||
@@ -169,8 +188,11 @@ func (r recoveryRestorer) Restore(ctx context.Context, backupID string) error {
|
||||
if r.writeSet.BackupSnapshotID != backupID {
|
||||
return fmt.Errorf("写集合记录绑定预备份 %s,不是 %s", r.writeSet.BackupSnapshotID, backupID)
|
||||
}
|
||||
return r.target.Restore(ctx, libraryrelease.BackupRef{ID: "backup-" + backupID, SnapshotID: backupID,
|
||||
WriteSet: r.writeSet})
|
||||
ref := libraryrelease.BackupRef{ID: "backup-" + backupID, SnapshotID: backupID, WriteSet: r.writeSet}
|
||||
if r.drill {
|
||||
return r.target.RestoreDrill(ctx, ref)
|
||||
}
|
||||
return r.target.Restore(ctx, ref)
|
||||
}
|
||||
|
||||
// recoveryVerifier 做真实的内容校验,并把目标当前状态摘要作为"校验过什么"的凭证。
|
||||
|
||||
@@ -30,4 +30,9 @@ func registerLibraryReleaseHandlers(handlers map[string]jobs.Handler, store *pos
|
||||
handlers[libraryBaselineJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
|
||||
return runLibraryBaseline(ctx, store, config, job)
|
||||
})
|
||||
// 恢复验证:真实"备份→canary→恢复→复核",通过后写入与当前目标绑定的可恢复证据。
|
||||
// 它是同步闸口的证据来源,所以与上面三类共用同一把执行锁与准入。
|
||||
handlers[libraryVerifyJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error {
|
||||
return runLibraryVerify(ctx, store, config, job)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// A12:能力默认关闭;只有"配置开启 + 目标身份存在 + 真实治理台账"同时成立才装配。
|
||||
// 配置本身不是独占证明,baseline 装配永远不传该台账。
|
||||
func TestRestoreDispatchGateRequiresExplicitConfiguration(t *testing.T) {
|
||||
store := &postgresstore.Store{}
|
||||
identity := appconfig.Config{LibraryProductionDatabaseURL: "postgres://local@127.0.0.1:5432/target_db",
|
||||
LibraryTargetInstance: "inst", LibraryProductionTenantID: 1, LibraryProductionInternalKB: "kb"}
|
||||
if gate := restoreDispatchGate(identity, store); gate != nil {
|
||||
t.Fatal("gate wired without the explicit switch")
|
||||
}
|
||||
enabled := identity
|
||||
enabled.LibraryRestoreDispatchEnabled = true
|
||||
if gate := restoreDispatchGate(enabled, store); gate == nil {
|
||||
t.Fatal("gate not wired when explicitly enabled")
|
||||
}
|
||||
if gate := restoreDispatchGate(enabled, nil); gate != nil {
|
||||
t.Fatal("gate wired without a governance store")
|
||||
}
|
||||
// 空目标配置仍会得到一个 gate:真实闸门是治理库激活登记(见 store 用例),
|
||||
// 用"配置看起来完整"冒充独占证明才是要避免的。
|
||||
}
|
||||
@@ -15,7 +15,8 @@ import (
|
||||
func TestRegisterLibraryReleaseHandlersCoversOnlyReleaseJobs(t *testing.T) {
|
||||
handlers := map[string]jobs.Handler{}
|
||||
registerLibraryReleaseHandlers(handlers, nil, appconfig.Config{}, nil)
|
||||
want := []string{librarySyncJobType, libraryRestoreJobType, libraryRecoverJobType, libraryBaselineJobType}
|
||||
want := []string{librarySyncJobType, libraryRestoreJobType, libraryRecoverJobType,
|
||||
libraryBaselineJobType, libraryVerifyJobType}
|
||||
if len(handlers) != len(want) {
|
||||
t.Fatalf("registered %d handlers, want %d: %#v", len(handlers), len(want), handlers)
|
||||
}
|
||||
@@ -30,7 +31,8 @@ func TestRegisterLibraryReleaseHandlersCoversOnlyReleaseJobs(t *testing.T) {
|
||||
func TestRegisterLibraryReleaseHandlersFailsClosedWhenNotAdmitted(t *testing.T) {
|
||||
handlers := map[string]jobs.Handler{}
|
||||
registerLibraryReleaseHandlers(handlers, nil, appconfig.Config{}, errNotAdmitted{})
|
||||
for _, jobType := range []string{librarySyncJobType, libraryRestoreJobType, libraryRecoverJobType, libraryBaselineJobType} {
|
||||
for _, jobType := range []string{librarySyncJobType, libraryRestoreJobType, libraryRecoverJobType,
|
||||
libraryBaselineJobType, libraryVerifyJobType} {
|
||||
err := handlers[jobType](context.Background(), jobs.Job{})
|
||||
if err == nil || !strings.Contains(err.Error(), "准入未通过") {
|
||||
t.Fatalf("handler %q error = %v, want admission refusal", jobType, err)
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
// fakeStageStore 记录封存失败分支对业务作业行的两次落库调用。
|
||||
type fakeStageStore struct {
|
||||
stageCalls []string
|
||||
jobCalls []string
|
||||
}
|
||||
|
||||
func (f *fakeStageStore) UpdateLibraryStage(_ context.Context, jobID, stage, state string, _, _, _, _ *int64, detail string, _ time.Time) error {
|
||||
f.stageCalls = append(f.stageCalls, jobID+"|"+stage+"|"+state+"|"+detail)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStageStore) AdvanceLibraryJob(_ context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, _, _ string, _ time.Time) error {
|
||||
f.jobCalls = append(f.jobCalls, jobID+"|"+string(state)+"|"+stage+"|"+message+"|"+recovery)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStageStore) LibraryVersionByRef(context.Context, string, governance.LibraryVersionKind, string, string) (governance.LibraryVersion, bool, error) {
|
||||
return governance.LibraryVersion{}, false, nil
|
||||
}
|
||||
|
||||
func (f *fakeStageStore) RecordLibraryVersion(context.Context, governance.LibraryVersion) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 归档根必须是非符号链接的 0700 目录;t.TempDir 的权限受 umask 影响。
|
||||
func privateDir(t *testing.T) string {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
if err := os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
func sourceFor(scope, kb string) governance.LibrarySourceIdentity {
|
||||
return governance.LibrarySourceIdentity{Project: "kgmaint-weknora", App: "kgmaint-app", Scope: scope, TenantID: 1, KnowledgeBaseID: kb}
|
||||
}
|
||||
|
||||
// RED 用例:快照来源与配置不一致时,队列已 failed、页面却永远"导出中"(真实事故:
|
||||
// libseal-lib-internal-20261102T234053 running/export/error 空)。失败必须同时写进
|
||||
// stage 与 job,且原错原样出现在两处与返回值里 —— 不能被"已记录失败"遮住。
|
||||
func TestCapturedSourceMismatchPersistsFailedStageAndJob(t *testing.T) {
|
||||
root := privateDir(t)
|
||||
snapshotID := sealTinyBaseline(t, root, "internal", time.Date(2026, 11, 2, 23, 40, 53, 0, time.UTC))
|
||||
// 清单里是 kb-baseline;worker 配置漂移后拿的是另一个 KB(256 验收遗留正是这样)。
|
||||
source := sourceFor("internal", "0c84a098-d3ed-4b82-a165-e6de9691d6a8")
|
||||
store := &fakeStageStore{}
|
||||
|
||||
err := ensureCapturedSource(context.Background(), store, "libseal-lib-internal-20261102T234053",
|
||||
root, snapshotID, source, time.Now().UTC())
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), "captured manifest differs from configured source") {
|
||||
t.Fatalf("mismatch must keep the original error, got %v", err)
|
||||
}
|
||||
if len(store.stageCalls) != 1 {
|
||||
t.Fatalf("stage writes = %v, want exactly one failed stage", store.stageCalls)
|
||||
}
|
||||
if !strings.HasPrefix(store.stageCalls[0], "libseal-lib-internal-20261102T234053|export|failed|") ||
|
||||
!strings.Contains(store.stageCalls[0], "captured manifest differs from configured source") {
|
||||
t.Fatalf("stage write = %q, want failed+original error", store.stageCalls[0])
|
||||
}
|
||||
if len(store.jobCalls) != 1 {
|
||||
t.Fatalf("job writes = %v, want exactly one failed job", store.jobCalls)
|
||||
}
|
||||
if !strings.HasPrefix(store.jobCalls[0], "libseal-lib-internal-20261102T234053|failed|export|") ||
|
||||
!strings.Contains(store.jobCalls[0], "captured manifest differs from configured source") {
|
||||
t.Fatalf("job write = %q, want failed+original error", store.jobCalls[0])
|
||||
}
|
||||
// 恢复说明必须指向真实下一步,而不是暗示数据损坏。
|
||||
if !strings.Contains(store.jobCalls[0], "重新封存") {
|
||||
t.Fatalf("job recovery = %q, want a re-seal instruction", store.jobCalls[0])
|
||||
}
|
||||
}
|
||||
|
||||
// 正例对照:身份一致时不得写任何失败,也不得把成功路径变成失败。
|
||||
func TestCapturedSourceMatchStaysSuccessful(t *testing.T) {
|
||||
root := privateDir(t)
|
||||
snapshotID := sealTinyBaseline(t, root, "internal", time.Date(2026, 11, 2, 23, 40, 53, 0, time.UTC))
|
||||
store := &fakeStageStore{}
|
||||
|
||||
if err := ensureCapturedSource(context.Background(), store, "libseal-ok",
|
||||
root, snapshotID, sourceFor("internal", "kb-baseline"), time.Now().UTC()); err != nil {
|
||||
t.Fatalf("matching source rejected: %v", err)
|
||||
}
|
||||
if len(store.stageCalls) != 0 || len(store.jobCalls) != 0 {
|
||||
t.Fatalf("success path wrote failures: stage=%v job=%v", store.stageCalls, store.jobCalls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
"time"
|
||||
)
|
||||
|
||||
func configuredCaptureSource(config appconfig.Config, scope string) governance.LibrarySourceIdentity {
|
||||
kb := config.LibrarySourceInternalKB
|
||||
if scope == "external" {
|
||||
kb = config.LibrarySourceExternalKB
|
||||
}
|
||||
return governance.LibrarySourceIdentity{Project: config.SourceProject(), App: config.LibrarySourceApp, Scope: scope, TenantID: config.LibrarySourceTenantID, KnowledgeBaseID: kb}
|
||||
}
|
||||
func verifyCapturedSource(root, snapshotID string, source governance.LibrarySourceIdentity) error {
|
||||
if _, err := source.ID(); err != nil {
|
||||
return err
|
||||
}
|
||||
archive, err := librarysnapshot.Open(root, 256*1024*1024)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
manifest, err := archive.Load(snapshotID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if manifest.Scope != source.Scope || manifest.TenantID != source.TenantID || manifest.KnowledgeBaseID != source.KnowledgeBaseID {
|
||||
return errors.New("captured manifest differs from configured source")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureCapturedSource 校验快照来源。校验失败必须把失败写进业务行:
|
||||
// 队列侧此时已 failed,只 return err 会让页面永远停在"导出中"
|
||||
// (实际事故:libseal-lib-internal-20261102T234053 running/export/error 空)。
|
||||
func ensureCapturedSource(ctx context.Context, store libraryStageStore, jobID, root, snapshotID string, source governance.LibrarySourceIdentity, now time.Time) error {
|
||||
err := verifyCapturedSource(root, snapshotID, source)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
// 快照本身已产生且字节完好,错的只是 worker 读到的来源身份;因此恢复路径是
|
||||
// "修配置后重新登记/重新封存",不是"重采数据"。原错原样写进 stage、job 与
|
||||
// 返回值:改写成更友好的文案会让真正的配置漂移查不出来。
|
||||
libraryStageRecorder{store: store, jobID: jobID}.Stage(ctx, "export", "failed", err.Error())
|
||||
_ = store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobFailed, "export", err.Error(),
|
||||
"快照已产生但来源身份与配置不一致,未登记为测试封存;修正来源配置后重新封存", "", "", now)
|
||||
return err
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,262 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/librarymaintenance"
|
||||
"knowledge-governance/internal/libraryverify"
|
||||
"knowledge-governance/internal/pgdsn"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// libraryVerifyPayload 是"恢复验证"的队列载荷。
|
||||
//
|
||||
// 它只带作业号与 scope:目标(库/索引/桶/实例)来自本进程的部署配置,不接受请求方
|
||||
// 指定。否则一次页面点击就能把"验证"引到别的库上,证据也就证明不了当前目标。
|
||||
type libraryVerifyPayload struct {
|
||||
LibraryJobID string `json:"library_job_id"`
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
|
||||
// runLibraryVerify 在目标实例上真实跑一次恢复验证,并把结果登记成证据。
|
||||
//
|
||||
// 与 sync/restore/baseline 共用同一套准入与代次守卫:它会停写入者、在目标上写 canary
|
||||
// 再按预备份恢复,所以必须走 admitLibraryJob + runOwnedLibraryAttempt,不能绕开。
|
||||
// 执行体本身是 internal/libraryverify——与 cmd/librarydrill 同一份实现,不允许两份。
|
||||
func runLibraryVerify(ctx context.Context, base *postgresstore.Store, config appconfig.Config, job jobs.Job) error {
|
||||
var payload libraryVerifyPayload
|
||||
if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.LibraryJobID == "" ||
|
||||
(payload.Scope != "internal" && payload.Scope != "external") {
|
||||
return errors.New("invalid library verify payload")
|
||||
}
|
||||
if _, admitErr := admitLibraryJob(ctx, base, job, payload.LibraryJobID, payload.Scope,
|
||||
governance.LibraryJobVerify, true); admitErr != nil {
|
||||
return admitErr
|
||||
}
|
||||
return runOwnedLibraryAttempt(ctx, base, config, job, payload.LibraryJobID,
|
||||
func(runCtx context.Context, writer *libraryAttemptWriter) error {
|
||||
return runLibraryVerifyAttempt(runCtx, writer, config, payload)
|
||||
})
|
||||
}
|
||||
|
||||
func runLibraryVerifyAttempt(ctx context.Context, writer *libraryAttemptWriter, config appconfig.Config,
|
||||
payload libraryVerifyPayload) error {
|
||||
store := writer
|
||||
now := time.Now().UTC()
|
||||
recorder := libraryStageRecorder{store: store, jobID: payload.LibraryJobID, scope: payload.Scope,
|
||||
operationID: writer.attempt.OperationID}
|
||||
|
||||
existing, jobErr := store.LibraryJob(ctx, payload.LibraryJobID)
|
||||
if jobErr != nil {
|
||||
// 作业行读不到就没有可登记的终态:直接失败,不落任何证据。
|
||||
return fmt.Errorf("读不到业务作业 %s:%w", payload.LibraryJobID, jobErr)
|
||||
}
|
||||
if existing.State == governance.LibraryJobSucceeded {
|
||||
// 幂等重放:已经成功过的验证不重复停目标、不重复写 canary。
|
||||
recorder.Stage(ctx, "finalize", "skipped", "该恢复验证已成功完成,重复投递不重复执行")
|
||||
return nil
|
||||
}
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
return failLibraryJob(ctx, store, recorder, payload.LibraryJobID,
|
||||
"生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false):恢复验证要停写入者并在目标上写 canary,闸口关闭时不执行",
|
||||
"capture")
|
||||
}
|
||||
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobRunning, "capture",
|
||||
"", "", "", "", now)
|
||||
|
||||
report, runErr := libraryverify.Run(ctx, config, payload.Scope, payload.LibraryJobID,
|
||||
libraryverify.Options{
|
||||
Progress: func(stage, state, detail string) { recorder.Stage(ctx, stage, state, detail) },
|
||||
Governance: verifyGovernance{store: store, config: config},
|
||||
Ledger: recorder,
|
||||
})
|
||||
|
||||
// 证据只由真实执行产生:失败也照实登记 failure 与报告,绝不写成 passed。
|
||||
evidence := governance.LibraryRestoreVerification{
|
||||
ID: "libverify-" + payload.Scope + "-" + payload.LibraryJobID,
|
||||
Scope: payload.Scope,
|
||||
JobID: payload.LibraryJobID,
|
||||
Status: governance.LibraryVerificationFailed,
|
||||
StartedAt: now,
|
||||
}
|
||||
if report != nil {
|
||||
evidence.StartedAt = report.StartedAt
|
||||
evidence.SnapshotID = report.SnapshotID
|
||||
evidence.Report = verificationReportObject(report)
|
||||
}
|
||||
if runErr == nil && report != nil && report.Status == "passed" {
|
||||
evidence.Status = governance.LibraryVerificationPassed
|
||||
evidence.FinishedAt = report.FinishedAt
|
||||
} else {
|
||||
evidence.FinishedAt = time.Now().UTC()
|
||||
if report != nil && report.FinishedAt.After(evidence.StartedAt) {
|
||||
evidence.FinishedAt = report.FinishedAt
|
||||
}
|
||||
switch {
|
||||
case runErr != nil:
|
||||
evidence.Failure = runErr.Error()
|
||||
case report != nil && report.Status != "passed":
|
||||
evidence.Failure = "恢复验证未通过(状态 " + report.Status + ")"
|
||||
default:
|
||||
evidence.Failure = "恢复验证未产生报告"
|
||||
}
|
||||
}
|
||||
if saveErr := store.SaveLibraryRestoreVerification(ctx, evidence); saveErr != nil {
|
||||
// 证据落不了库就不能宣称验证通过:这会把闸口建立在一次没留痕的执行上。
|
||||
return failLibraryJob(ctx, store, recorder, payload.LibraryJobID,
|
||||
"恢复验证执行结束但证据登记失败:"+saveErr.Error(), "finalize")
|
||||
}
|
||||
|
||||
if runErr != nil || evidence.Status != governance.LibraryVerificationPassed {
|
||||
held := report != nil && report.Status == "maintenance_held"
|
||||
message := "恢复验证未通过:" + evidence.Failure
|
||||
if held {
|
||||
message += "(目标仍在维护窗口,入口关闭、写入者已停)"
|
||||
}
|
||||
// 失败出口只写真实结果:报告里的 restore_check 与窗口终态说明目标此刻是
|
||||
// 仍在维护,还是已经按原运行状态安全收尾。不能拿"有快照"冒充"已恢复并复核"。
|
||||
recovery := "未对目标执行任何写入,无需恢复"
|
||||
switch {
|
||||
case held:
|
||||
recovery = "目标仍在维护窗口:在同一作业上执行「按预备份恢复」(library.recover),恢复与逐类校验通过后才会开入口并释放占用"
|
||||
case report != nil && report.WindowState != "":
|
||||
recovery = "维护窗口已按原运行状态收尾(window=" + report.WindowState + "):目标内容未写入或已恢复并复核,无需再恢复"
|
||||
}
|
||||
snapshot := ""
|
||||
if report != nil {
|
||||
snapshot = report.SnapshotID
|
||||
}
|
||||
recorder.Stage(ctx, "finalize", "failed", message)
|
||||
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, "finalize",
|
||||
message, recovery, snapshot, snapshot, time.Now().UTC())
|
||||
return errors.New(message)
|
||||
}
|
||||
|
||||
finishedAt := evidence.FinishedAt
|
||||
if finishedAt.IsZero() {
|
||||
finishedAt = time.Now().UTC()
|
||||
}
|
||||
recorder.Stage(ctx, "finalize", "succeeded",
|
||||
"恢复验证通过:快照 "+evidence.SnapshotID+" 的预备份可真实恢复,证据已按当前目标登记")
|
||||
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobSucceeded, "finalize",
|
||||
"", "", evidence.SnapshotID, evidence.SnapshotID, finishedAt)
|
||||
log.Printf("library verify %s passed target snapshot=%s", payload.LibraryJobID, evidence.SnapshotID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyGovernance 把演练接进**既有**维护生命周期:实例行 + scope 行都由 worker 的
|
||||
// 真实 attempt 写入,入口状态与状态文字来自实际执行。页面读的维护接口只认这些行,
|
||||
// 所以只写磁盘 journal 的窗口在 UI 上等于不存在(审核 B2 的真实缺口)。
|
||||
type verifyGovernance struct {
|
||||
store *libraryAttemptWriter
|
||||
config appconfig.Config
|
||||
}
|
||||
|
||||
func (g verifyGovernance) targetIdentity(scope string) string {
|
||||
return fmt.Sprintf("scope=%s db=%s index=%s bucket=%s", scope,
|
||||
pgdsn.Endpoint(g.config.LibraryProductionDatabaseURL), g.config.LibraryProductionIndex, g.config.LibraryProductionS3Bucket)
|
||||
}
|
||||
|
||||
func (g verifyGovernance) Acquire(ctx context.Context, jobID, scope string, target libraryverify.TargetIdentity, originalServiceState string) error {
|
||||
now := time.Now().UTC()
|
||||
note := "实例级维护:关闭目标入口并停止全部写入者,恢复验证完成并复核后开放"
|
||||
if _, err := g.store.AcquireInstanceMaintenance(ctx, postgresstore.LibraryInstanceMaintenance{
|
||||
Instance: target.Instance, OwnerJobID: jobID, OwnerScope: scope,
|
||||
TargetFingerprint: target.Fingerprint, Level: librarymaintenance.LevelInstance,
|
||||
Services: target.Writers, IngressState: "unknown", State: "acquired",
|
||||
OriginalServiceState: originalServiceState, Note: note,
|
||||
}, now); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := g.store.AcquireLibraryMaintenance(ctx, postgresstore.LibraryMaintenance{
|
||||
Scope: scope, OwnerJobID: jobID, TargetIdentity: g.targetIdentity(scope),
|
||||
Level: librarymaintenance.LevelInstance, TargetFingerprint: target.Fingerprint,
|
||||
Services: target.Writers, IngressState: "unknown", State: "acquired",
|
||||
OriginalServiceState: originalServiceState, Note: note,
|
||||
}, now); err != nil {
|
||||
// scope 行没拿到时目标还没被停用:释放实例占用,避免留下一个空窗口。
|
||||
_ = g.store.ReleaseInstanceMaintenance(ctx, target.Instance, jobID, now)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g verifyGovernance) Ingress(ctx context.Context, jobID, scope, state, note string) error {
|
||||
now := time.Now().UTC()
|
||||
if err := g.store.SetLibraryMaintenanceIngress(ctx, scope, jobID, state, note, now); err != nil {
|
||||
return err
|
||||
}
|
||||
return g.store.SetInstanceMaintenanceIngress(ctx, g.config.LibraryTargetInstance, jobID, state, note, now)
|
||||
}
|
||||
|
||||
func (g verifyGovernance) State(ctx context.Context, jobID, scope, state, note string) error {
|
||||
now := time.Now().UTC()
|
||||
if err := g.store.UpdateLibraryMaintenanceState(ctx, scope, jobID, state, note, now); err != nil {
|
||||
return err
|
||||
}
|
||||
return g.store.UpdateInstanceMaintenanceState(ctx, g.config.LibraryTargetInstance, jobID, state, note, now)
|
||||
}
|
||||
|
||||
func (g verifyGovernance) Release(ctx context.Context, jobID, scope, note string) error {
|
||||
now := time.Now().UTC()
|
||||
if err := g.store.ReleaseLibraryMaintenance(ctx, scope, jobID, now); err != nil {
|
||||
return err
|
||||
}
|
||||
return g.store.ReleaseInstanceMaintenance(ctx, g.config.LibraryTargetInstance, jobID, now)
|
||||
}
|
||||
|
||||
// verificationReportObject 把报告转成可落库的 JSON 对象(保留 canary/漂移校验等证据字段)。
|
||||
func verificationReportObject(report *libraryverify.Report) map[string]any {
|
||||
if report == nil {
|
||||
return nil
|
||||
}
|
||||
raw, err := json.Marshal(report)
|
||||
if err != nil {
|
||||
return map[string]any{"encode_error": err.Error()}
|
||||
}
|
||||
var object map[string]any
|
||||
if err := json.Unmarshal(raw, &object); err != nil {
|
||||
return map[string]any{"encode_error": err.Error()}
|
||||
}
|
||||
return object
|
||||
}
|
||||
|
||||
// libraryRestoreEvidenceSatisfied 回答"当前目标 + scope 有没有可支撑写生产的恢复证据"。
|
||||
//
|
||||
// 证据是第一来源:library_restore_verifications 按当前 target_id 读取,换库/换索引/换桶
|
||||
// 之后旧证据自动失效,不需要谁记得关开关。历史部署里的 PRODUCTION_BACKUP_RESTORE_VERIFIED
|
||||
// 仍作为显式覆盖保留(不删除旧部署能力),但只允许在**明确没有证据行**时兜底;
|
||||
// 明确 failed/invalid 与读取错误一律拒绝(审核 B3:不能把"不知道"当"满足")。
|
||||
func libraryRestoreEvidenceSatisfied(ctx context.Context, store interface {
|
||||
LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error)
|
||||
}, config appconfig.Config, scope string) (bool, string) {
|
||||
// 存储没有证据能力(nil/迁移前形状)等同于"没有证据行":历史 env 覆盖可兜底;
|
||||
// 但只要读得出证据行,failed/invalid 与读取错误都优先拒绝。
|
||||
missing := true
|
||||
if store != nil {
|
||||
evidence, found, err := store.LatestLibraryRestoreVerification(ctx, scope)
|
||||
switch {
|
||||
case err != nil:
|
||||
return false, "读取恢复验证证据失败:" + err.Error()
|
||||
case found:
|
||||
missing = false
|
||||
if ok, reason := governance.LibraryVerificationSatisfied(evidence, scope); ok {
|
||||
return true, ""
|
||||
} else {
|
||||
return false, reason
|
||||
}
|
||||
}
|
||||
}
|
||||
if missing && config.ProductionBackupRestoreVerified {
|
||||
return true, ""
|
||||
}
|
||||
return false, "当前目标还没有恢复验证证据:先跑一次恢复验证(备份 → canary → 恢复 → 复核)"
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
// 同步闸口的"恢复可验证"判断必须以当前目标的证据为准:
|
||||
// 没有证据 ⇒ 拒绝并说清怎么补;有 passed 证据 ⇒ 放行;只有失败证据 ⇒ 拒绝并带失败原因。
|
||||
// 历史 env 覆盖只在证据缺失时兜底(页面不再写它)。
|
||||
type verifyEvidenceStore struct {
|
||||
evidence governance.LibraryRestoreVerification
|
||||
found bool
|
||||
}
|
||||
|
||||
func (s verifyEvidenceStore) LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error) {
|
||||
return s.evidence, s.found, nil
|
||||
}
|
||||
|
||||
// 审核 B3:读取失败不能被 env=true 洗成"满足"。
|
||||
type unreadableEvidenceStore struct{}
|
||||
|
||||
func (unreadableEvidenceStore) LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error) {
|
||||
return governance.LibraryRestoreVerification{}, false, errors.New("evidence lookup failed")
|
||||
}
|
||||
|
||||
func TestWorkerUnreadableEvidenceBeatsEnv(t *testing.T) {
|
||||
ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), unreadableEvidenceStore{},
|
||||
appconfig.Config{ProductionBackupRestoreVerified: true}, "internal")
|
||||
if ok {
|
||||
t.Fatalf("unreadable evidence must block even with env=true; reason=%q", reason)
|
||||
}
|
||||
if !strings.Contains(reason, "读取恢复验证证据失败") {
|
||||
t.Fatalf("reason=%q", reason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryRestoreEvidenceSatisfied(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
passed := verifyEvidenceStore{found: true, evidence: governance.LibraryRestoreVerification{
|
||||
Scope: "internal", Status: governance.LibraryVerificationPassed, SnapshotID: "snap-1", FinishedAt: now}}
|
||||
if ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), passed, appconfig.Config{}, "internal"); !ok {
|
||||
t.Fatalf("passed evidence must satisfy gate: %q", reason)
|
||||
}
|
||||
failed := verifyEvidenceStore{found: true, evidence: governance.LibraryRestoreVerification{
|
||||
Scope: "internal", Status: governance.LibraryVerificationFailed, SnapshotID: "snap-1",
|
||||
Failure: "恢复后内容仍与预备份不一致", FinishedAt: now}}
|
||||
if ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), failed, appconfig.Config{}, "internal"); ok ||
|
||||
!strings.Contains(reason, "恢复后内容仍与预备份不一致") {
|
||||
t.Fatalf("failed evidence must block with its own failure: ok=%v reason=%q", ok, reason)
|
||||
}
|
||||
missing := verifyEvidenceStore{}
|
||||
if ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), missing, appconfig.Config{}, "internal"); ok ||
|
||||
!strings.Contains(reason, "恢复验证") {
|
||||
t.Fatalf("missing evidence must block and point at the remedy: ok=%v reason=%q", ok, reason)
|
||||
}
|
||||
// 历史部署的 env 覆盖:证据缺失时才生效,证据存在时不再起作用。
|
||||
if ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), missing,
|
||||
appconfig.Config{ProductionBackupRestoreVerified: true}, "internal"); !ok {
|
||||
t.Fatalf("legacy env override must still allow when no evidence: %q", reason)
|
||||
}
|
||||
if ok, _ := libraryRestoreEvidenceSatisfied(context.Background(), failed,
|
||||
appconfig.Config{ProductionBackupRestoreVerified: true}, "internal"); ok {
|
||||
t.Fatal("evidence must win over the legacy env override")
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,9 @@ import (
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/librarymaintenance"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"knowledge-governance/internal/librarystack"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
v071 "knowledge-governance/internal/releaseadapter/v071"
|
||||
)
|
||||
|
||||
@@ -18,13 +20,27 @@ func openLibraryMaintenance(config appconfig.Config) (*librarymaintenance.Manage
|
||||
return librarystack.OpenMaintenance(config)
|
||||
}
|
||||
|
||||
// restoreDispatchGate 只在部署显式开启时才把治理台账交给目标。
|
||||
//
|
||||
// 为什么不能只信配置:配置为 true 只说明"允许装配",不证明旧 writer 已退出;
|
||||
// 真正的发放许可还要求治理库里对该目标存在未撤销的激活登记(见迁移 78)。
|
||||
func restoreDispatchGate(config appconfig.Config, store *postgresstore.Store) libraryrelease.RestoreMarkerGate {
|
||||
// 只判断"是否允许装配":目标身份与独占证明由治理台账的激活登记回答,
|
||||
// 这里再用一个空配置也能算出来的摘要去当门槛只会制造虚假的严格。
|
||||
if !config.LibraryRestoreDispatchEnabled || store == nil {
|
||||
return nil
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
||||
// buildLibraryProductionStack 用"要同步的这份快照"做契约装配目标与预备份存储。
|
||||
func buildLibraryProductionStack(ctx context.Context, config appconfig.Config, scope, snapshotID, knownMapping string) (
|
||||
*v071.ProductionLibraryTarget, *v071.ProductionBackupStore, error) {
|
||||
return librarystack.OpenProductionStack(ctx, config, scope, snapshotID, knownMapping)
|
||||
func buildLibraryProductionStack(ctx context.Context, config appconfig.Config, gate libraryrelease.RestoreMarkerGate,
|
||||
scope, snapshotID, knownMapping string) (*v071.ProductionLibraryTarget, *v071.ProductionBackupStore, error) {
|
||||
return librarystack.OpenProductionStack(ctx, config, scope, snapshotID, knownMapping, gate)
|
||||
}
|
||||
|
||||
// buildLibraryBaselineStack 装配"给目标自己建基线"所需的目标与捕获器(契约取目标当前映射)。
|
||||
// 基线不参与发布/恢复派发,永远不传派发台账:只读/建基线不得获得恢复写许可。
|
||||
func buildLibraryBaselineStack(ctx context.Context, config appconfig.Config, scope string) (
|
||||
*v071.ProductionLibraryTarget, *v071.ProductionBackupStore, error) {
|
||||
return librarystack.OpenBaselineStack(ctx, config, scope)
|
||||
|
||||
@@ -37,7 +37,7 @@ func beginLibraryWriter(ctx context.Context, store *postgresstore.Store, jobID,
|
||||
// 迁移前的历史作业没有 operation:仍然取租约(防止双执行),但没有代次可守卫。
|
||||
log.Printf("library job %s has no operation id (pre-identity row): guarded writes fall back to lease only", jobID)
|
||||
}
|
||||
attempt, err := store.BeginLibraryAttempt(ctx, jobID, owner, 10*time.Minute, time.Now().UTC())
|
||||
attempt, err := store.BeginLibraryAttempt(ctx, jobID, owner, libraryAttemptLease, time.Now().UTC())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -135,9 +135,7 @@ func libraryQueueOwner(workerID string, job jobs.Job, libraryJobID string) strin
|
||||
if queueID == "" {
|
||||
queueID = libraryJobID
|
||||
}
|
||||
worker := workerID
|
||||
if worker == "" {
|
||||
worker = "worker"
|
||||
}
|
||||
return fmt.Sprintf("%s#%s#%d", worker, queueID, job.Attempt)
|
||||
// 合成规则只有一份(governance.LibraryDeliveryOwner):派发台账要按同一格式核
|
||||
// "这次许可属于哪次真实投递"。
|
||||
return governance.LibraryDeliveryOwner(workerID, queueID, job.Attempt)
|
||||
}
|
||||
|
||||
+99
-24
@@ -9,6 +9,7 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -23,7 +24,9 @@ import (
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/readiness"
|
||||
"knowledge-governance/internal/versionhistory"
|
||||
"knowledge-governance/internal/weknoraaccess"
|
||||
artifactfetch "knowledge-governance/internal/workflows/artifactfetch"
|
||||
catalogrefresh "knowledge-governance/internal/workflows/catalogrefresh"
|
||||
"knowledge-governance/internal/workflows/sourcescan"
|
||||
@@ -98,6 +101,27 @@ func stageSizesFrom(manifest librarysnapshot.Manifest) map[string]stageSize {
|
||||
// libraryCaptureJobType is shared with the API which enqueues it.
|
||||
const libraryCaptureJobType = "library.capture"
|
||||
|
||||
// Retained deterministic source-content failures: the agent has already
|
||||
// restored the writer, so retrying the same journal only replaces the first
|
||||
// cause with "already exists". Body-index coverage markers are intentionally
|
||||
// absent; that inferred rule was removed in R3f.
|
||||
var terminalLibraryCaptureMarkers = []string{
|
||||
"missing library generated question index",
|
||||
"empty library index content",
|
||||
}
|
||||
|
||||
func terminalLibraryCaptureError(err error) error {
|
||||
if err == nil || !strings.Contains(err.Error(), "已执行 recover 并确认写入者恢复") {
|
||||
return err
|
||||
}
|
||||
for _, marker := range terminalLibraryCaptureMarkers {
|
||||
if strings.Contains(err.Error(), marker) {
|
||||
return jobs.Permanent(jobs.ErrCodeValidationFailed, err)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// librarySyncJobType 是生产同步作业的队列类型;与封存严格分开,状态不共用。
|
||||
const librarySyncJobType = "library.sync"
|
||||
|
||||
@@ -110,6 +134,10 @@ const libraryRestoreJobType = "library.restore"
|
||||
// libraryBaselineJobType 是"建立目标权威基线"的队列类型(与 API 侧常量同值)。
|
||||
const libraryBaselineJobType = "library.baseline"
|
||||
|
||||
// libraryVerifyJobType 是"恢复验证"的队列类型:真实备份→canary→恢复→复核,
|
||||
// 通过后才会产生同步闸口认的恢复证据。与 API 侧常量同值。
|
||||
const libraryVerifyJobType = "library.verify"
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
@@ -142,7 +170,8 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
} else if len(pending) > 0 {
|
||||
return fmt.Errorf("治理库 schema 落后(待应用迁移 %v):本角色不拥有 DDL,先由控制面进程完成迁移", pending)
|
||||
}
|
||||
store := postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity())
|
||||
store := postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID).
|
||||
WithRestoreDispatchEvidence(config.LibraryTargetJournalRoot)
|
||||
log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity())
|
||||
// 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败:
|
||||
// 顺序反了会把可接管的作业先标失败,丢掉已完成的备份。
|
||||
@@ -259,6 +288,41 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
return worker.Run(ctx, config.PollInterval)
|
||||
}
|
||||
|
||||
type libraryCapturePersistence interface {
|
||||
UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error
|
||||
AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error
|
||||
}
|
||||
|
||||
// beginLibraryCaptureJob persists the starting state before any source
|
||||
// operation. If either write fails the handler must return, so the queue cannot
|
||||
// be reported completed while the business job is still pending.
|
||||
func beginLibraryCaptureJob(ctx context.Context, store libraryCapturePersistence, jobID string, now time.Time) error {
|
||||
if err := store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobRunning, "export", "", "", "", "", now); err != nil {
|
||||
return fmt.Errorf("library seal job %s cannot be advanced: %w", jobID, err)
|
||||
}
|
||||
if err := store.UpdateLibraryStage(ctx, jobID, "export", "running", nil, nil, nil, nil,
|
||||
"主机侧正在暂停写入者、导出并恢复", now); err != nil {
|
||||
return fmt.Errorf("library seal job %s stage cannot be advanced: %w", jobID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// completeLibraryCaptureJob persists both terminal facts. A failed write must
|
||||
// be returned (queue failed), not logged and ignored; the capture journal keeps
|
||||
// replay idempotent, and the admin reconcile path can repair only after the
|
||||
// exact queue/version/archive evidence is present.
|
||||
func completeLibraryCaptureJob(ctx context.Context, store libraryCapturePersistence, jobID, snapshotID string, now time.Time) error {
|
||||
if err := store.UpdateLibraryStage(ctx, jobID, "export", "succeeded", nil, nil, nil, nil,
|
||||
"已封存快照 "+snapshotID, now); err != nil {
|
||||
return fmt.Errorf("library seal job %s success stage cannot be persisted: %w", jobID, err)
|
||||
}
|
||||
if err := store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobSucceeded, "export", "", "",
|
||||
snapshotID, "", now); err != nil {
|
||||
return fmt.Errorf("library seal job %s success terminal cannot be persisted: %w", jobID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[string]jobs.Handler, error) {
|
||||
handlers := map[string]jobs.Handler{
|
||||
"demo": func(_ context.Context, job jobs.Job) error {
|
||||
@@ -320,12 +384,8 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
// 持久作业:页面读的是这里写的阶段与结果,worker 重启后仍能如实展示。
|
||||
libraryJobID := "libseal-" + payload.CaptureJob
|
||||
startedAt := time.Now().UTC()
|
||||
if advanceErr := store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobRunning, "export", "", "", "", "", startedAt); advanceErr != nil {
|
||||
log.Printf("library seal job %s cannot be advanced: %v", libraryJobID, advanceErr)
|
||||
}
|
||||
if stageErr := store.UpdateLibraryStage(ctx, libraryJobID, "export", "running", nil, nil, nil, nil,
|
||||
"主机侧正在暂停写入者、导出并恢复", startedAt); stageErr != nil {
|
||||
log.Printf("library seal job %s stage update failed: %v", libraryJobID, stageErr)
|
||||
if beginErr := beginLibraryCaptureJob(ctx, store, libraryJobID, startedAt); beginErr != nil {
|
||||
return beginErr
|
||||
}
|
||||
// 平台审计过的精确死信解除指纹:读取失败必须阻断(fail closed),
|
||||
// 不能因为存储不可用就静默按"没有解除"或"全部解除"处理。
|
||||
@@ -344,6 +404,11 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
"未停任何写入者;补齐来源身份配置后重试", "", "", time.Now().UTC())
|
||||
return expectErr
|
||||
}
|
||||
source := configuredCaptureSource(config, payload.Scope)
|
||||
sourceID, sourceErr := source.ID()
|
||||
if sourceErr != nil {
|
||||
return sourceErr
|
||||
}
|
||||
result, err := libraryagent.CaptureReleased(ctx, agentConfig, payload.Scope, payload.CaptureJob, released, expectation)
|
||||
finishedAt := time.Now().UTC()
|
||||
if err != nil {
|
||||
@@ -352,7 +417,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
_ = store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobFailed, "export", err.Error(),
|
||||
"agent 已执行恢复检查;确认来源 healthy 后可重试同一作业号", "", "", finishedAt)
|
||||
log.Printf("library capture failed scope=%s capture_job=%s: %v", payload.Scope, payload.CaptureJob, err)
|
||||
return err
|
||||
return terminalLibraryCaptureError(err)
|
||||
}
|
||||
// 执行后复核:结果里 agent 自报的身份必须还是期望实例,否则这次封存
|
||||
// 可能来自别的栈,绝不能登记成"本实例的测试封存"。
|
||||
@@ -362,23 +427,25 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
"快照已产生但来源身份不符,未登记为测试封存;核对执行器后重新封存", "", "", finishedAt)
|
||||
return identityErr
|
||||
}
|
||||
if err := ensureCapturedSource(ctx, store, libraryJobID, config.LibraryArchiveRoot, result.SnapshotID, source, finishedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
// 封存产物成版本记录:只登记"测试封存",绝不写成生产生效版本。
|
||||
versionErr := store.RecordLibraryVersion(ctx, governance.LibraryVersion{
|
||||
ID: governance.LibraryVersionID(governance.LibraryVersionTestSealed, payload.Scope, result.SnapshotID),
|
||||
Scope: payload.Scope,
|
||||
Kind: governance.LibraryVersionTestSealed, SnapshotID: result.SnapshotID, SourceJobID: libraryJobID,
|
||||
Evidence: map[string]any{"capture_job": payload.CaptureJob, "replay": result.Replay,
|
||||
Evidence: map[string]any{"source_id": sourceID, "source_identity": source, "capture_job": payload.CaptureJob, "replay": result.Replay,
|
||||
"requested_by": payload.RequestedBy, "expectation_fingerprint": expectationFingerprint(expectation),
|
||||
"agent_result": json.RawMessage(result.Payload)},
|
||||
CreatedBy: payload.RequestedBy, CreatedAt: finishedAt,
|
||||
})
|
||||
if versionErr != nil {
|
||||
log.Printf("library seal job %s cannot record version: %v", libraryJobID, versionErr)
|
||||
return fmt.Errorf("library seal job %s cannot record version: %w", libraryJobID, versionErr)
|
||||
}
|
||||
if completeErr := completeLibraryCaptureJob(ctx, store, libraryJobID, result.SnapshotID, finishedAt); completeErr != nil {
|
||||
return completeErr
|
||||
}
|
||||
_ = store.UpdateLibraryStage(ctx, libraryJobID, "export", "succeeded", nil, nil, nil, nil,
|
||||
"已封存快照 "+result.SnapshotID, finishedAt)
|
||||
_ = store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobSucceeded, "export", "", "",
|
||||
result.SnapshotID, "", finishedAt)
|
||||
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
|
||||
@@ -458,19 +525,27 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
if !config.TestWeKnoraEnabled || !config.LibraryWorkerRole.ExecutesSourceWork() {
|
||||
return handlers, nil
|
||||
}
|
||||
apiKey, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile)
|
||||
if err != nil {
|
||||
// 启动只验证凭据“存在”(缺失像以前一样拒绝启动);具体值仍由 resolver 每次调用重读。
|
||||
if _, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); err != nil {
|
||||
return nil, fmt.Errorf("read test WeKnora API key: %w", err)
|
||||
}
|
||||
client, err := weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: config.TestWeKnoraBaseURL,
|
||||
APIKey: apiKey,
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create test WeKnora client: %w", err)
|
||||
// 与 API 探测共用同一有效目标:网页保存的端点优先、env 只作未配置兜底;
|
||||
// 当前持久化绑定优先、env 兜底;凭据每次调用重读同一 key 文件。
|
||||
remoteResolver := readiness.Resolver{
|
||||
Endpoint: func(resolveCtx context.Context) string {
|
||||
if settings, settingsErr := store.GetActiveUISettings(resolveCtx); settingsErr == nil && strings.TrimSpace(settings.TestWeKnoraBaseURL) != "" {
|
||||
return settings.TestWeKnoraBaseURL
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
},
|
||||
LoadBinding: func(resolveCtx context.Context) (string, error) {
|
||||
internal, _, _, bindingErr := store.LoadRoutingKBBindings(resolveCtx)
|
||||
return internal, bindingErr
|
||||
},
|
||||
ReadKey: func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) },
|
||||
DefaultKB: config.InternalRoutingKnowledgeBaseID,
|
||||
}
|
||||
client := &weknoraaccess.Client{Resolver: remoteResolver, Timeout: config.TestWeKnoraHTTPTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP}
|
||||
upload, err := testweknora.NewUploadHandler(testweknora.UploadHandlerConfig{
|
||||
Store: store,
|
||||
Client: client,
|
||||
|
||||
+6
-1
@@ -18,4 +18,9 @@
|
||||
|
||||
1. 跑 `make verify`(本地全绿不等于远端跑通,需要一次真实 run 的证据)。
|
||||
2. 把**使用者可见**的变化写成 `CHANGELOG.md` 的 `[Unreleased]` 条目(按四类,别写过程)。
|
||||
3. 从本文件划掉该项;过程记录归档到 `docs/archive/`。
|
||||
3. 从本文件划掉该项;过程记录归档到 `docs/archive/`。
|
||||
## 资源首次复用的归属审计(后续)
|
||||
|
||||
- 当前首次复用只依赖“目标行逐列一致 + 对象字节一致”,不再要求本目标历史成功同步/预备份来源。
|
||||
- 后续可补:资源首次写入者/首次绑定 KB、跨 KB 引用计数、孤儿资源与同 tenant 共享资源的可审计归属视图;
|
||||
不以此重新阻断正常的同内容首次复用。
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# DS01 激活证据的不变量(v2)
|
||||
|
||||
状态:源码与隔离测试已实现;**未在正式治理库执行激活**。
|
||||
相关实现:`internal/libraryrelease/restore_dispatch_activation.go`、
|
||||
`internal/platform/postgres/library_restore_dispatch_activation.go`、
|
||||
`internal/libraryfreeze/journal_evidence.go`。
|
||||
|
||||
## 1. 当前生产装配从哪里取得可核证据
|
||||
|
||||
```
|
||||
worker(LIBRARY_RESTORE_DISPATCH_V2=true)
|
||||
└─ librarymaintenance.Manager(LIBRARY_TARGET_*)
|
||||
└─ libraryfreeze.Coordinator
|
||||
├─ 关闭入口 → 读 gate drain.json(closed / drained / active_at_close)
|
||||
├─ 等后台静默 → QuiesceProof(depth/pending_ops/unsettled=0,稳定窗口)
|
||||
├─ 停写者 → Controller.Stop + Inventory 复核 + 退出码
|
||||
└─ 写 <LIBRARY_TARGET_JOURNAL_ROOT>/<job>.json(state=held)
|
||||
└─ library_instance_maintenance(治理库):instance / owner_job_id / target_fingerprint /
|
||||
level=instance / services / state / released_at
|
||||
```
|
||||
|
||||
激活是**部署动作**,不是业务请求:`Store.ActivateRestoreDispatch` 只在部署流程里调用。
|
||||
`Store.WithRestoreDispatchEvidence(LIBRARY_TARGET_JOURNAL_ROOT)` 是唯一允许读取 journal 的根;
|
||||
未配置该根 ⇒ `ErrRestoreDispatchActivationDisabled`(能力关闭),不退回"只看字符串"。
|
||||
|
||||
## 2. 证据文件只声明身份,不声明结论
|
||||
|
||||
v2 证据文档(`protocol_version=2`)字段。注意:台账行 `library_index_restore_dispatch_activation.protocol_version`
|
||||
仍是 1(迁移 78 的派发协议身份约束),证据文档版本与台账协议版本不是同一个数字:
|
||||
|
||||
| 字段 | 含义 |
|
||||
|---|---|
|
||||
| `target_identity` | 目标身份 |
|
||||
| `target_fingerprint` | 维护窗口/部署目标指纹(64 位 sha256 hex),必须等于 journal 与维护行 |
|
||||
| `restore_target_fingerprint` | 激活时对恢复目标(库/索引/桶)的实时观察指纹 |
|
||||
| `target_instance` | 治理库维护窗口的实例名,必须等于 journal 的 `source` |
|
||||
| `governance_database` | 当前治理库名,与 `current_database()` 比对 |
|
||||
| `protocol_build` | 必须是**运行中二进制**的 `version.DisplayVersion()` |
|
||||
| `maintenance_job` / `maintenance_journal` | 维护窗口作业;journal 名必须恰好是 `<job>.json` |
|
||||
| `maintenance_journal_sha256` | 磁盘 journal 字节的 sha256(不是文件内自报值) |
|
||||
| `writers[] {name, kind, instance_id}` | 旧 writer 集合:名字对治理库 `services`,实例 ID 对 journal `services[].id` |
|
||||
|
||||
**没有** `stopped` / `queue_drained` / `exited_at` / `drain_evidence` 这些调用方布尔字段。
|
||||
"已退出、已排空"只能从 journal 事实与治理库行推出来。
|
||||
|
||||
## 3. 激活门逐项不变量
|
||||
|
||||
- **A1 来源**:journal 由 `libraryfreeze` 写、位于配置的私有根(目录 0700、非符号链接);
|
||||
文件以 `O_NOFOLLOW` 打开、≤1MiB、严格 JSON(未知字段拒绝)。
|
||||
- **A2 摘要**:磁盘字节 sha256 == 证据声明值;写入台账的 `drain_evidence_digest` 是这个值。
|
||||
- **A3 窗口状态**:journal `state=held`、`level=instance`;已 `recovered`/`released` 的窗口
|
||||
不能证明"旧 writer 仍停着"。
|
||||
- **A4 实例绑定**:journal `source` == 证据 `target_instance`,且 == 治理库
|
||||
`library_instance_maintenance.instance`。
|
||||
- **A5 作业绑定**:journal `job` == 证据 `maintenance_job` == 维护行 `owner_job_id`。
|
||||
- **A6 目标绑定**:journal `target_fingerprint` == 证据 `target_fingerprint` == 维护行指纹;
|
||||
证据 `restore_target_fingerprint` == 调用方激活时对恢复目标的只读观察值。两者是
|
||||
不同层(实例/部署 vs 内容/索引/桶身份),不能用一个值互相顶替。
|
||||
- **A7 入口排空**:`ingress_closed=true`、`drain_verified=true`、gate `closed && drained &&
|
||||
active_at_close==0`。
|
||||
- **A8 后台静默**:`quiesce` 存在且 depth/pending_ops/unsettled 全 0、有合法 digest、
|
||||
停写后复核(`post_stop_at ≥ proven_at`、`post_stop_depth=0`、`post_stop_digest=digest`)。
|
||||
- **A9 writer 集合**:证据 writer 名字集合 == 维护行 `services`;实例 ID 集合 == journal
|
||||
`services[].id`;每个 writer `stop_requested=true` 且有 `exit_code`;数量必须一致。
|
||||
- **A10 有效性**:停写/排空观察(`quiesce.post_stop_at`)在 2 小时有效期内;
|
||||
证据 `attested_at` 不早于该观察、不晚于未来 5 分钟;窗口 `acquired_at` 早于观察。
|
||||
- **A11 现场身份**:`current_database()` 等于证据库名;运行构建必须已注入身份且等于
|
||||
`protocol_build`;调用方传入的目标指纹必须等于证据指纹。
|
||||
- **A12 失败关闭**:任一不满足 ⇒ 不写 activation 行;已撤销行的终局性仍由迁移 78 的
|
||||
trigger 保证(`revoked_at→NULL`、删行、状态倒退都拒绝)。
|
||||
|
||||
## 4. 它不证明什么
|
||||
|
||||
- 不独立观测"外部 writer 进程此刻不在运行";A7–A9 是维护链自己的受控观察
|
||||
(入口 drain、退出码、后台静默),不是通用进程扫描。
|
||||
- 不提供 ES 端 fence,也不保证已 `dispatching` 的旧 owner 不会迟到一次。
|
||||
- 不抵抗超级管理员禁用 trigger 或恢复旧 PG 快照。
|
||||
|
||||
## 5. 测试如何证明它不是"验字符串"
|
||||
|
||||
反例(真 PG,见 `library_restore_dispatch_linearization_test.go`):伪造 journal 摘要、
|
||||
摘要计算后替换真实文件、错 writer 名字/实例、无退出码、从未要求停、入口未排空
|
||||
(`drained=false` / `active_at_close=1` / `drain_verified=false`)、停写观察过期、
|
||||
证据过期、治理库身份不符、现场指纹不符、构建不符、维护窗口已释放、作业不属于窗口、
|
||||
journal 已 recovered、未配置受信根。全部要求零 activation 行;正例才产生 1 行,并把
|
||||
已核事实(journal 摘要、gate、quiesce、每个 writer 的退出码)写进 `evidence.verified`。
|
||||
@@ -0,0 +1,90 @@
|
||||
# DS01:删除型恢复的派发台账(实现说明)
|
||||
|
||||
状态:源码与隔离测试已实现;**未在 8088 / 正式治理库 / 业务 WeKnora 上执行 DDL 或激活**。
|
||||
设计正本:`astra-ds01-design.md`。有限验收表:握手目录 `ds01-acceptance-freeze.md`。
|
||||
|
||||
## 它证明什么、不证明什么
|
||||
|
||||
证明:对一个固定的删除型恢复 effect(`Before` 非空、`After` 空,恢复写入是独占 `_create`),
|
||||
台账里 `prepared` 意味着没有任何遵守本协议的派发者取得过发送许可;`dispatching` 之后永不回退,
|
||||
因此"曾经发送过"不可能再表现为 `prepared`。
|
||||
|
||||
不证明:ES 端 fencing;已 `dispatching` 的旧 owner 不会迟到一次;目标历史上没被外部写过;
|
||||
PG 快照回滚/手工删行之后的协议有效性(这类历史倒退必须 held 并人工处置)。
|
||||
|
||||
## 状态与唯一发送路径
|
||||
|
||||
```
|
||||
prepared --(CAS, 同一短事务内校验 activation/job/operation/attempt/lease/binding)--> dispatching
|
||||
dispatching --(真实 receipt + 当前 owner/lease)--> marker_confirmed
|
||||
```
|
||||
|
||||
- 发送许可只由 `AcquireRestoreMarker` 在 **COMMIT 明确返回后**给出,`RestoreSendPermit` 消费一次即作废。
|
||||
- CAS 事务按 `job → operation → activation → active attempt → effect` 取锁:
|
||||
- 激活撤销(`revoked_at`)与 CAS 在同一事务里线性化:撤销先完成则拒绝,CAS 先取锁则撤销排队;
|
||||
- lease 用 `clock_timestamp()` 在取锁之后判定,等锁跨过租约即拒绝;
|
||||
- attempt 必须属于原 window job;job 的 owner/epoch/lease、operation 的 scope/来源快照/
|
||||
已登记写集摘要、实例维护窗口(未释放且属于该作业)逐项核对;
|
||||
- 恢复路径另核 recovery queue job(运行中且有 lease)与 recovery operation(`kind=recover`、
|
||||
绑定同一 backup);
|
||||
- 同一 effect 换 plan 摘要会被台账拒绝(不能靠新 key 重开证明)。
|
||||
- 不可变绑定来自原持久锚点:`scope`、来源快照(发布基线)、写前镜像(backup)、目标实例/
|
||||
实际指纹/索引 UUID、变更/标记/请求摘要与 attempt 身份。来源与写前镜像不允许是同一份快照。
|
||||
目标指纹与索引 UUID 每次重建绑定都实时重读并与本次恢复冻结值比较:同名重建的目标/索引
|
||||
无法复用旧证明。
|
||||
- 恢复期 `_create` 只从 `sendRestoreMarkerOnce` 发出;preflight/故障钩子都在 CAS 之前。
|
||||
- 请求设置 `GetBody=nil`,Go 传输层不会在 keep-alive 重连时重放该 mutation。
|
||||
|
||||
## Restore 准入与收尾
|
||||
|
||||
`Restore` 在 `AdoptWriteSet` 之后、任何阶段写入之前调用纯读准入,并先对照原 window 的
|
||||
**权威台账全集**(跨 plan 摘要):出现另一份 plan、计划外 effect 或不可识别状态立即 held。
|
||||
|
||||
| 台账/证据 | 结果 |
|
||||
|---|---|
|
||||
| 无意图、无证据、无台账 | 首次恢复,可建立 `prepared` |
|
||||
| 旧意图、无台账 | held(旧协议未知历史,不补 prepared) |
|
||||
| `prepared` + 绑定冲突(`Held`) | held |
|
||||
| `prepared` + 已存在 claimed/finalize/目标精确 marker | held(协议证据矛盾) |
|
||||
| `prepared` + 无矛盾 | 可竞争一次许可 |
|
||||
| `prepared` + mark-intent 未落盘(文件失败/崩溃区段) | 核对绑定一致后补写**同内容**意图,再竞争 |
|
||||
| `dispatching` + 目标无精确 marker | held(零新发送) |
|
||||
| `dispatching` + 精确 marker/内容/世代 | 只走确认分支,不发 create |
|
||||
| `marker_confirmed` + 无 `restored` 证据 | held |
|
||||
| `restored` 证据与目标内容/世代一致 | 终态,允许重放 |
|
||||
|
||||
收尾前(整库指纹比对之后)以同一份权威全集再检查一次:任何 `prepared`/`dispatching` 记录、
|
||||
计划外记录、换 plan 摘要、或缺失 `restored` 文件证据的 effect 都拒绝返回成功,维护窗口不会
|
||||
被释放。
|
||||
|
||||
## 激活(部署动作,不属于本开发包)
|
||||
|
||||
新能力默认关闭。启用需要两步,缺一不可:
|
||||
|
||||
1. 部署配置 `LIBRARY_RESTORE_DISPATCH_V2=true`(只表示允许装配);
|
||||
2. 部署流程在**维护窗口 held 的当下**登记激活:`Store` 必须绑定
|
||||
`LIBRARY_TARGET_JOURNAL_ROOT`(`WithRestoreDispatchEvidence`),由
|
||||
`ActivateRestoreDispatch` 消费一份 v2 证据文件。
|
||||
|
||||
v2 证据只声明身份(目标/实例/治理库/构建、维护作业、journal 文件名与 sha256、
|
||||
旧 writer 集合);"已退出、已排空"由代码直接读维护 journal 与治理库
|
||||
`library_instance_maintenance` 行核出:窗口必须 `held`、入口 `closed/drained/
|
||||
active_at_close=0`、后台 quiesce 全零且有停写后复核、每个 writer 有
|
||||
`stop_requested` 与退出码、writer 集合与治理库一致、观察在 2 小时内。
|
||||
|
||||
没有配置受信 journal 根时返回 `ErrRestoreDispatchActivationDisabled`(能力关闭),
|
||||
不会退回"三个非空字符串就开门"。逐项不变量见
|
||||
`docs/architecture/ds01-activation-evidence.md`。
|
||||
|
||||
撤销是终局:`revoked_at` 一旦写入,SQL 不能改回 `NULL`、不能改时间,activation 行也不能删除;
|
||||
重新开放同一物理目标只能换新的目标身份。
|
||||
|
||||
边界:代码核验 journal 完整性、身份绑定与维护链自己的停写/排空观察;它不独立扫描
|
||||
外部进程,也不提供 ES 端 fence。
|
||||
|
||||
## 迁移与回滚
|
||||
|
||||
- `000078_library_restore_dispatch.up.sql` 只建治理库表与触发器,不碰 WeKnora Schema。
|
||||
- `000078_..._down.sql` 在 `library_index_restore_dispatch` 或 activation 表有**任意行**时拒绝执行:
|
||||
这些行是"是否发送过 / 是否曾被授权"的唯一证明,抹掉等于把 unknown 伪装成 prepared,或把
|
||||
已撤销的激活悄悄删掉。
|
||||
@@ -81,6 +81,7 @@ A06(内容、问答、引用图片效果、性能报告)已由用户取消
|
||||
|
||||
| ID | 缺口 | 现状与影响 |
|
||||
| --- | --- | --- |
|
||||
| R02-b | 删除型索引恢复的自动重试 | 应用期删掉了目标文档、恢复写入是独占 `_create`。持久意图已落盘而文档缺失时,服务端没有可持久、不可重用的"这份写入没落地"证据:缺失与"从未写过"同形;ES `_stats` 写计数是分片生命周期统计(官方文档:分片迁到另一节点时该分片统计会被清零),索引 uuid 不变不绑定统计生命周期,清零后重新累计到同一数值(ABA)不能排除。**现状 fail-closed**:既存 `restore-mark-intent` 一律 held(`rollback_failed`、零写入、零误归属),不自动重试,需人工按预备份核验后重新规划;本次尝试开始前不存在任何恢复意图时仍可正常重建。这是**开发缺口**(r37 反例:同 uuid 同计数 + 真实写删,恢复仍须 held),不是用户接受的能力收窄;是否引入可校验的持久 not-dispatched 状态与派发原子协议,由后续设计决定。保留的可证明路径:真实 marker 仍在且世代一致的 clean 收尾重试、文档仍是 applied 结果且世代一致的 `DELETE` 补偿重试 |
|
||||
| R03 | 存快/恢复快对比 | A06 性能报告已由用户取消,不作为门槛。**已记实测耗时**(小测试库,不是压测):封存 15.8s(含停写~5s)、同步 13.6s(预备份 13.4s 占主要)、恢复 13.8s;证据 `13-r03-durations.json`。没有做高负载压测,也不写没有测量的数字 |
|
||||
| 死信解除·真实重放演练 | 没有可解除的真实死信,也没有源侧系统管理员凭据 | 契约与执行侧已实现(见下节新增行):上游保留原行、治理侧审计+指纹绑定、未结清/变化/新死信仍阻断。**本轮没有真实死信**(`dead_letters=0`),无法演练"真实重放成功→解除→放行"整条链路;上游只有 `系统管理 runtime run_now`(需要源侧管理员权限)与整队列 purge(销毁证据,不采用)。治理平台故意不持有源侧管理员凭据(放大授权),因此这一步**阻塞在真实死信 + 重放执行方**,不伪造成功 |
|
||||
|
||||
|
||||
@@ -56,8 +56,16 @@ LIBRARY_TARGET_INGRESS_URL 入口地址(恢复后要能 200)
|
||||
LIBRARY_TARGET_INGRESS_SERVICE Compose 里的入口闸门服务名
|
||||
LIBRARY_TARGET_INGRESS_DRAIN_FILE 闸门写排空证据的宿主机文件
|
||||
LIBRARY_TARGET_REDIS_ADDR/_PASSWORD/_DB 后台队列(asynq)地址
|
||||
LIBRARY_TARGET_INGRESS_MODE gate(缺省)或 none;none 只给没有闸门的测试栈
|
||||
LIBRARY_NO_INGRESS_ACK mode=none 时必须逐字符等于 test-only
|
||||
LIBRARY_TARGET_HEALTH_URL mode=none 时的健康探针(恢复后必须 200)
|
||||
```
|
||||
|
||||
`none` 是显式降档,不是默认:整栈(如 0.9.0 测试栈)没有入口闸门时,`none` + 确认串
|
||||
才允许缺入口三项,窗口里不调用任何闸门动作,`gate` 证据位置写
|
||||
`{"mode":"none","reason":"stack has no ingress gate (test-only)"}`;恢复以
|
||||
`LIBRARY_TARGET_HEALTH_URL` 返回 200 为准。缺省 `gate` 的行为与文案不变。
|
||||
|
||||
另外 `-source-s3-endpoint <URL>` 用来覆盖"源对象存储的访问入口":容器里写的
|
||||
`MINIO_ENDPOINT` 往往是服务名(`langfuse-minio:9000`),封存跑在宿主机上时解析不到,
|
||||
资源导出会失败(`read library resource`)。覆盖只换入口,桶与对象键不变;`status`
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# v0.7.1 整库发布的数据契约与覆盖边界
|
||||
|
||||
这是候选代码的契约,不是部署许可。真实隔离执行证据在交付目录 `data-contract-r10.md`、`test-summary-r10.json` 及其 raw 索引。PG/ES/MinIO 均为本机隔离真实服务;发布/恢复测试直接调用适配器;B22 另走实际 `librarystack.OpenProductionStack` 和 HTTP 网关。网关按限定 key 工作,不要求整桶独占审核;B22 控制读取角色是真实 SELECT-only PG 角色。
|
||||
|
||||
## 1. 源 schema、历史身份与准入
|
||||
|
||||
- 新 `ExportLibraryWithReleases` 在读取内容的同一 REPEATABLE READ / READ ONLY 事务中读取 columns、constraints、indexes、triggers、relations、sequences;非普通表、RLS/继承/分区、自定义触发器或未知入边 FK 拒绝。
|
||||
- 新归档增加一个内容寻址的 `schema/migration-catalog` 部件。归档核 JSON 目录结构、计数、大小和 SHA256;来源清单摘要绑定该部件。PlanWriteSet 在分配序列或执行任何业务写前要求其摘要与当前目标目录一致。序列定义属于目录,last_value/is_called 不属于 DDL 指纹。
|
||||
- 旧快照没有该部件:不追加字段、不重新 seal、不改历史 hash;继续走原目标 catalog 和逐行字段/身份检查。它不能被称为“原捕获时已有 schema 证明”。旧V1台账的 canonical 规则不变。
|
||||
- 目录严格一致不是自动迁移方案。源/目标定义不同会拒绝,需要单独评审兼容性,不能在业务库上临时 DDL 绕过。
|
||||
- 实际 stack 准入读取目标模型、维度、schema 和 graph 状态。同维不同模型、模型行缺失、空模型名、graph 开启、schema dirty 均拒绝;不重算 embedding、不关闭 graph。正例和负例都比较 PG、ES正文/CAS、对象精确版本与网关 journal,证明准入无业务副作用。
|
||||
|
||||
## 2. 逐表身份、闭包和保真规则
|
||||
|
||||
|表|身份及本轮已执行的边界|保真/未闭合范围|
|
||||
|---|---|---|
|
||||
|knowledges|稳定字符串 ID;租户与KB按计划映射;正文/file_path/metadata 中规范资源引用进入闭包|其余原始列保留;模型/存储定位只按已冻结目标策略改写。不声称已穷尽全部业务 metadata 中非资源ID的语义|
|
||||
|chunks|稳定 ID;knowledge_id 必须存在且同租户同KB;源 scoped 孤儿不能被 JOIN 静默丢掉;seq_id 使用固定数值映射|chunk_index 排序、按tenant+seq_id查询实跑;规范pre_chunk_id/next_chunk_id/parent_chunk_id要求同knowledge;tag_id及relation_chunks/indirect_relation_chunks要求在范围内,父树拒绝环;不把任意metadata数字猜成seq引用|
|
||||
|knowledge_tags|稳定 ID;租户/KB必须匹配;seq_id按源数值大小分配并固定|sort_order ASC、created_at DESC、seq_id DESC 的并列排序实跑;原数值在恢复时回原,不回拨共享序列|
|
||||
|knowledge_tag_relations|精确(knowledge_id,tag_id)元组;任一父可证明范围;缺knowledge、缺tag、跨KB/租户在源、入站及目标规划处拒绝|不通过内连接删除异常关系、不把元组拼成单列。非空正常/既存元组由完整隔离套件执行|
|
||||
|resources|稳定 ID/22字符handle;引用资源必须存在,原对象字节、精确版本保真;目标正文引用也进入before-image和验证范围|共享资源仍按原不可变before-image/来源证明判断复用,不放宽成“字节相同即认领”。无本次归属的历史孤儿保持不动|
|
||||
|resource_bindings|稳定 ID;resource_id必须在来源闭包;owner仅knowledge/chunk,必须可解析且租户一致|未知owner_type、NULL owner_type、缺owner及跨租户拒绝。被本次引用资源上的所有绑定都核验,包括指向其它KB的共享绑定;合法共享允许、未知共享归属拒绝|
|
||||
|wiki_folders|稳定 ID、tenant/KB保真;整行JSON的规范资源字符串参与识别|parent_id必须在本次目录闭包且无环;目录ID碰撞写前拒绝;未知外部持久路径仍不声明支持|
|
||||
|wiki_pages|稳定 ID;正文和嵌套metadata资源在无binding时也捕获/备份/发布/恢复|页面内容原样保留;按真实字段source_refs(含knowledgeID|title旧形状)、chunk_refs、folder_id检查闭包;不按不存在的source_knowledge_ids字段推断支持|
|
||||
|wiki_page_issues|稳定 ID、tenant/KB保真;整行资源字符串参与识别|原v071按slug引用/展示的问题记录原样保留;未知扩展字段不自动映射数值ID,不能当作任意插件引用支持|
|
||||
|wiki_log_entries|BIGINT正整数,不经float64;按源数值大小映射(2在100之前),映射绑定原计划|id DESC和cursor id<实际SQL实跑;恢复原id。旧外部持久游标不能跨映射直接复用,原A04此项仍需决策/验收|
|
||||
|resource_access_grants(非迁移表)|唯一已审核的resources外部FK入边;不搬运、不删除授权|新建资源清理/Restore前若出现授权,持父键锁拒绝删除;恢复入口另核未知绑定/计划外绑定和外库正文metadata引用,有引用时在ES/对象/PG写前held,锁内再次核全部正文/绑定;当前完整隔离测试读回grant、PG、ES、原对象版本均未变。其它未知入边/触发器拒绝|
|
||||
|
||||
既有目标历史软删除行按原 destructive predicate 进入 before-image,不用来源活跃行过滤规则裁剪恢复数据。来源导出只包含活跃内容;可归属于本库的异常边在过滤前检查。完全没有任何父或范围锚的历史记录不能猜成属于本库:不全局扫出后删除、不自动迁移;这不是“所有历史孤儿已修复”。
|
||||
|
||||
## 3. 资源引用的实际格式
|
||||
|
||||
只读参考源码:`WeKnora-v0.7.1-dev/internal/types/resource.go` 中 `ResourceHandleLength=22` 与 `ParseResourcePath`;本轮没有修改WeKnora源码。
|
||||
|
||||
支持并真实执行:
|
||||
|
||||
- knowledge或Wiki正文里的 `resource://` 加22个URL-safe字符,包含Markdown图片语法;
|
||||
- 嵌套JSON对象/数组字符串值里的同一规范引用,例如metadata.image_info[].url;
|
||||
- 无binding的上述四种组合:源捕获、目标before-image、发布、恢复;完整PG及精确对象版本含历史孤儿比对。
|
||||
|
||||
实现先解码JSON再递归扫描字符串,不将JSON数字转为float64,也不重写正文。所有迁移行的字符串参与资源发现。目标 SQL 选择覆盖所有带tenant/KB的迁移表整行JSON,并与严格解析/完整引用存在性检查配合,不再只认chunk.content。
|
||||
|
||||
明确拒绝本轮实测的未知表示:短handle、过长handle、URI query/path/fragment后缀、再次转义的resource协议串;不截取22字符前缀冒充合法引用。未知owner独立拒绝。
|
||||
|
||||
覆盖边界:这不是任意富文本、任意编码或所有插件格式解析器。不承诺识别不含规范协议标识的opaque/base64内容、插件自定义裸UUID引用或全部非资源语义ID。新增格式需给出真实生产/读消费者契约、负例与保真证据后再支持;当前总体验收保持INCOMPLETE。
|
||||
|
||||
## 4. 数值序列与消费者
|
||||
|
||||
- chunks.seq_id、knowledge_tags.seq_id、wiki_log_entries.id:正常分配、落后于已占值、耗尽、源显式NULL分别真实执行。后3类在业务阶段前拒绝;所有序列的last_value/is_called、PG全文、ES正文/CAS、S3版本/删除标记不变。
|
||||
- 正常分配是明确副作用,会推进序列;必须先固化P0/预备份,不能称只读。新target接管同一WriteSet再Apply不再取号;恢复原行但不rewind序列,合法空洞不等于身份丢失。
|
||||
- v071消费者位置:repository/tag.go(sort_order/created_at/seq_id排序)、repository/chunk.go(seq_id读取及chunk_index排序)、repository/wiki_log_entry.go(id DESC、cursor id<)。本轮执行其SQL语义,不声称启动了完整WeKnora UI或所有外部消费者。
|
||||
|
||||
## 5. 后续门与安全边界
|
||||
|
||||
- 真实v071历史catalog镜像对照及UUID/自然键矩阵在r11执行,隔离结论与外部当前目录采样分开。A04已识别嵌套引用有有限支持,旧外部cursor仍不自动转换,不因内部结构正例而升级整项。
|
||||
- r8/r9进程恢复历史证据只在原发送协议、不可变计划/receipt及相应场景前提不变时复用。本轮对schema/引用准入有收紧,不能把历史执行日志称为当前源码正式进程全链重跑;完整当前隔离适配器回归单列。
|
||||
- clean-finalization unknown保持held是安全行为,但未满足全部自动收敛要求。若要求自动完成,需要能绑定原写入、完整内容和代次的充分服务端证据;相同干净正文、人工猜测归属或放宽共享规则均不可替代。
|
||||
- 最终提交/push、远端CI、父复核和本机部署为明确下一门;整体安全验收未齐不部署。网关真实 OSS 业务端到端与宿主重启/断电是另行授权的部署/破坏性验收,不能作为停止本机授权开发的借口。
|
||||
|
||||
## 6. 目录与唯一键的有限支持矩阵
|
||||
|
||||
`testdata/catalog-v071-r11.json` 来自既存只读取证 `source-schema-live-r3b.json`,不是当前线上目录新采样。隔离镜像按原列、约束、索引、关系和触发器定义重建并逐项比较;sequence定义和OWNED BY归属独立绑定,不将last_value伪装成只读DDL。未知外部入边、外部出边、迁移表内部数值FK扩展不能因为源/目标同样扩展就默认放行。
|
||||
|
||||
稳定主键:knowledges、chunks、knowledge_tags、resources、resource_bindings、wiki_folders、wiki_pages、wiki_page_issues按同租户异KB/异租户碰撞检查;knowledge_tag_relations使用父身份元组;三个本地数值身份按固定WriteSet映射而非稳定UUID处理。资源共享的合法同ID复用仍依赖原before-image和所有权证明。
|
||||
|
||||
自然键以实际catalog的unique/partial indexes为基准:资源handle、有效tenant/location_hash、资源绑定复合键、tag tenant/KB/name、目录KB/parent/name、wiki KB/slug,以及provider/physical_path的应用层排他。wiki_page_issues在该目录中只有主键,没有额外自然唯一键。partial predicate按有效/软删除判定,并验证不同parent的正常目录;不能无差别拒绝全部正常资料。具体逐键DDL、正负例对应表见交付 `data-contract-r11.md`。
|
||||
|
||||
Wiki日志pages_affected仅支持消费者已有的字符串slug数组和{slug,title}对象数组;已删除页面/knowledge的历史日志是展示事实,不以缺现存父强删/拒绝历史日志。数字数组、对象中新增log_id等未知结构拒绝。普通metadata数字原样保存,不推断为日志ID。
|
||||
|
||||
旧外部cursor是明确剩余风险:目标新游标可正确分页,但源数字cursor或发布前旧cursor不能直接带入目标新映射。原A04“改本地ID不破坏引用/语义”没有豁免条款,所以仍未整项通过;本模块不擅改上游WeKnora,也不把“刷新页面即可”当作已经实现的自动失效协议。
|
||||
|
||||
授权以执行时真实时钟为准;完成预备份及持久计划登记后均再验。目标实现 `GrantRevalidator` 时按治理库授权行回读:`ActiveLibraryAuthorization` 只返回未撤销、未过期且参数摘要一致的记录,撤销后连写集合都不计算(避免序列分配),预备份保留待重新授权。真实发布 wrapper 无条件接线;未接线不等于安全,只是本机历史证据的边界。
|
||||
|
||||
## 7. r12 追加的真实边界
|
||||
|
||||
- **软删除 before-image**:destructive predicate 能碰到的 7 张带 `deleted_at` 的表(knowledges/chunks/knowledge_tags/resources/wiki_folders/wiki_page_issues/wiki_pages)逐表核对备份行数与删除谓词命中数;晚阶段失败后的恢复把这些行连同 `deleted_at` 原值一起放回(r12 真实 PG)。
|
||||
- **索引独立 oracle**:发布成功后,正文、向量(同维不同值)、metadata(knowledge_id)任一被改都会让校验变红;改回后必须重新通过,说明合法本地列映射没有被这项收紧误杀。
|
||||
- **外部索引文档**:同 `_id` 属于其它知识库时整轮在写前拒绝,且那份文档的 `_source`、`_seq_no`、`_primary_term` 与对象版本逐字节不变。
|
||||
- **共享资源差异**:同 ID 共享资源在 handle / 定位 / 字节三类差异下都写前拒绝,共享对象版本不变;完全相同的共享资源按 no-op 复用,行 `xmin`/整行 JSON 与对象精确版本均不变。
|
||||
- **晚阶段失败与对象**:Wiki 阶段失败回滚后,本次新建对象不残留,**已有对象的精确版本**(versionId + SHA256 + 字节数)不变。
|
||||
- **clean 归属能力(实测)**:两个不同操作写入完全相同的字节后,索引侧只剩同一份 `_source`;`_seq_no`/`_version` 是分片提交计数,不绑定原 operation。因此"相同正文"或"seq_no+1"都不能证明是同一次 clean,缺服务端归属证据时继续 held(探针:`b19-capability-probe.json`)。
|
||||
- **旧外部游标**:游标是裸数字 id(`next_cursor` → `id < cursor`),发布按源数值升序重排本地 id。目标自己发出的游标在同代内正确;发布前或来自其它实例的游标没有代次信息,无法自动翻译,会静默错位而非报错。详见交付 `a04-cursor-semantics-r12.md` 的 A/B 决策。
|
||||
|
||||
## 8. 已接受的可用性边界(r13,用户明确接受)
|
||||
|
||||
- **旧分页游标跨发布失效**:`next_cursor` 是裸数字 id(`id < cursor`),发布按源数值升序重排本地 id,请求里没有代次信息。发布前/跨实例游标无法翻译,回传会静默错位而非报错。已接受做法:发布或恢复后刷新页面、重新从第一页分页;不改 WeKnora 源码/Schema。同代内游标与引用重映射仍然正确。
|
||||
- **clean-finalization 缺归属证据时保持 held**:真实 ES 探针显示两个不同操作写入相同字节后只剩同一份 `_source`,`_seq_no`/`_version` 是分片提交计数、不绑定 operation。此分支保持维护锁定并走人工核验/恢复,不承诺自动收敛;**不允许**凭相同正文或 seq_no+1 推断归属、补写 receipt、跳过校验、强制开门或删除未知内容。带原 marker/before-image/CAS/不可变 receipt 的 unknown 仍走既有自动补偿,不因本边界回退。
|
||||
|
||||
配套只读诊断:`GET /api/v1/library/jobs/{id}` 在作业失败且目标仍被本作业持有时返回 `maintenance`(held/owner/state/ingress/target_identity/note)与 `next_step` 文本,明确"按预备份与校验证据人工核验后再放行",且不提供任何强制成功入口;作业本身仍带 operation_id/attempt_epoch/backup/target 快照与错误、恢复说明。
|
||||
@@ -0,0 +1,43 @@
|
||||
# 发布身份与不可变计划:开发检查点
|
||||
|
||||
本批是统一修复的未完成检查点,不是发布就绪版本。不得依据本地门禁通过开启发布写门或部署云执行器。
|
||||
|
||||
## 已实现边界
|
||||
|
||||
- 显式逐表身份解析:字符串稳定身份、关系二元组、Wiki bigint;未知非空表、缺身份、错误整数类型和重复身份拒绝。
|
||||
- chunks.seq_id、knowledge_tags.seq_id、wiki_log_entries.id 使用目标 sequence 分配并落入不可变写集合。接管校验来源 manifest、映射覆盖及 Wiki 写身份;回滚保留原始编号,不回退共享 sequence。
|
||||
- 原始目标 before-image 与源候选导出分离,保留范围谓词内的软删除行和关联。resource_access_grants 外部级联入边已保护;尚未证明全部 FK/trigger 级联闭包。
|
||||
- worker 包装器转发 AdoptWriteSet。不可变证据先同步文件,再同步目录;并发写者不能替换已存在的不同字节。
|
||||
- ES 写前按全索引 ID 查归属,冻结逐 ID before/after/CAS 并持久化不可变 effect。维护窗口内使用既有 content 字段的暂态操作归属标记,不新增业务 mapping;确认归属后按 CAS 写入干净正文。标记写入成功但响应丢失时,新进程可从计划、完整内容、标记和 CAS 自动确认并补偿。无归属标记、内容或代次不符、清除标记后的未知结果、删除/补偿的未知结果仍拒绝,不能据此宣布完成恢复。
|
||||
- 同 ID 资源即使在 before-image 内也必须证明等价才能只读复用;差异拒绝。已有 catalog 驱动自然唯一键预检及物理键绑定;完整负例矩阵仍未齐。
|
||||
- 内容 canonicalization 保留大整数及失效期;孤儿查询错误向上传播。
|
||||
|
||||
## 兼容与回退
|
||||
|
||||
不修改旧 manifest/blob,也不改变其 hash。本批未增加或修改业务 schema、治理迁移。
|
||||
|
||||
新执行计划使用 V2,历史 V1 canonical 字节保持不变,并拒绝在 V1 中添加新执行字段;旧 V1 仅可读取诊断,不能把缺失副作用证据的旧计划当作安全执行计划。V2 当前仍不是完整跨存储协议:带归属标记的 ES unknown 已有真实跨进程补偿证据,所有无充分证据的分支仍保持维护,原生 OSS 条件创建协议仍未闭合。复用证据的 V2 before-image 等价证明与写集合版本独立。
|
||||
|
||||
一旦新计划被用于真实副作用,不得直接降级旧执行器消费新计划;须先证明没有在飞操作并完成原备份恢复和验证。当前没有部署,也未启动任何云作业。
|
||||
|
||||
## 阻止发布的剩余项
|
||||
|
||||
1. D0 完整源/目标 schema 指纹、FK 入出边、trigger、应用引用和序列消费者闭合。
|
||||
2. 对象精确计划/intent/归属回执及版本化 MinIO 清理已局部实现并运行;MinIO 忽略 Delete IfMatch 的反例已记录,改用精确 versionId。业务桶不自动启用版本控制,无版本桶/未经验证的 OSS 适配写前拒绝。对象计划绑定与完整 adapter 隔离回归已复验;原生 OSS 版本协议已在明确授权测试前缀完成两个真实版本的精确写/读/清理,并列举确认版本与删除标记均无残留;严格条件创建与业务集成仍未闭合,不能放行。
|
||||
3. ES 未记录的干净 finalization、删除与恢复网络结果不明时的进一步对账;不得将 fail-closed 状态算作完成。
|
||||
4. 自然唯一键、resource_access_grants 与未知引用闭包。
|
||||
5. 完整执行权续租、失权取消并等待写结束、跨执行域 fencing,以及队列提交补偿。
|
||||
6. source candidate 精确查询与 API/UI 提交接线已测;旧 seal 显式证据关联已接管理员API/UI:核验原捕获响应/期望指纹与原manifest后只追加治理证据,不改快照hash;四种模式及真实页面闭环仍缺。
|
||||
7. 两次连续真实 worker 中断,55 项完整验收、最终提交/远端 CI 与父独立复核。
|
||||
|
||||
已授权的云专用 KB 发布/恢复及测试 App 短停仍属于父独立审查后的后续阶段,无需重复索要开发授权;宿主重启与生产不在本批范围。
|
||||
|
||||
## 原生 OSS 的具体差异
|
||||
|
||||
原生版本协议实现提供 versioning 只读确认、带归属 metadata 的显式 append、精确 versionId 读取、完整回执比对后精确删除及再次读取验证。它不是 conditionalObjectStore 的替代,未接成生产 CreateObject。官方 PutObject 文档说明:桶启用/暂停版本控制时,x-oss-forbid-overwrite 无效。因此不能把版本 append 包装成原子仅新建,也不能用 S3 If-None-Match 的本机 MinIO 测试代替 OSS 证明。
|
||||
|
||||
真实测试只在 KG_OSS_VERSION_TEST_ALLOW=1、明确获准的 KG_OSS_VERSION_TEST_PREFIX、私有持久证据目录及测试凭据齐全时运行。默认不发云写;允许的测试桶固定为 dobot-weknora-test,端点固定深圳 OSS,只操作随机子键及精确版本,不改桶配置。未知 append 留下 intent,不盲扫桶猜测孤儿。限定前缀 kg-library-test-r4/ 已获明确授权并完成真实协议测试;生产条件创建的安全协议仍是实现缺口,不以版本 append 冒充严格仅新建,也不请求降低既有保护。
|
||||
|
||||
### 证据目录持久性边界
|
||||
|
||||
不可变 sidecar 的目录创建逐级检查真实目录,拒绝祖先软链接,逐级 fsync 父目录并传播错误;文件与最终目录仍同步。已验证祖先软链接写前拒绝、逐级同步调用覆盖和同步错误传播。这不是实际断电/文件系统崩溃测试,也不等于完整 F12:归档初始化现同步根目录及其父目录,任一fsync失败即拒绝返回可用归档,已做故障注入;PG锚点失败和跨节点介质策略仍需单独验收。
|
||||
@@ -0,0 +1,48 @@
|
||||
# 目标库隔离 ID 映射
|
||||
|
||||
同一 WeKnora 实例里可以有多个知识库。同步把源快照写进目标库时,如果沿用源库的 UUID 主键,
|
||||
第二个目标库会与实例里已有库的行撞主键(真实证据:2 knowledges / 2 chunks / 23 wiki_pages /
|
||||
17 wiki_folders 已存在于旧库),写入前的跨范围检查会拒绝整次同步。关闭检查等于让两个库共享身份,
|
||||
删除/恢复/校验会互相误伤,因此身份必须在目标侧派生。
|
||||
|
||||
## 映射规则
|
||||
|
||||
```
|
||||
digest = sha256("knowledge-governance/target-identity/v1" || tenant || kb || table || source_id)
|
||||
target_id = 前 16 字节按 8-4-4-4-12 十六进制格式化(置 RFC 4122 variant/version 位)
|
||||
```
|
||||
|
||||
这是**本产品自定义的稳定 ID 算法**(`target_id_mode=scoped-sha256-v1`),只保证确定性与目标隔离;
|
||||
它不是标准 RFC 4122 UUIDv5(UUIDv5 用 SHA-1 + 标准 namespace),不要按 UUIDv5 互操作。
|
||||
|
||||
- 只绑定**稳定目标身份**(目标 tenant、目标 KB)与源身份,表名参与命名空间;
|
||||
- 不绑定 job、时间、快照版本等瞬态值:同一目标重复同步/重试/跨版本得到同一 ID;
|
||||
- 不同目标 KB、不同表得到不同 ID;
|
||||
- 源归档字节不变,映射只存在于目标侧派生视图(写集合、写入行、索引文档、校验预期);
|
||||
- 计划把策略持久化为 `target_id_mode=scoped-sha256-v1`:新进程按该字段重建映射,旧计划/写前镜像
|
||||
没有该字段则按原 ID 回放,绝不二次映射。
|
||||
|
||||
## 参与映射的表与字段
|
||||
|
||||
| 表 | 身份 | 引用字段 |
|
||||
|---|---|---|
|
||||
| knowledges | id | — |
|
||||
| chunks | id | knowledge_id, tag_id, parent_chunk_id, pre_chunk_id, next_chunk_id, relation_chunks, indirect_relation_chunks, metadata(仅精确匹配) |
|
||||
| knowledge_tags | id | — |
|
||||
| knowledge_tag_relations | (knowledge_id, tag_id) | 两个分量分别映射 |
|
||||
| wiki_folders | id | parent_id |
|
||||
| wiki_pages | id | folder_id, chunk_refs, source_refs(保留 `id|title`), page_metadata(仅精确匹配) |
|
||||
| wiki_page_issues | id | page_id, knowledge_id, chunk_id |
|
||||
| resource_bindings | id | owner_id(按 owner_type) |
|
||||
| resources | **不映射** | resource_id 保持共享身份 |
|
||||
| 索引文档 | 文档物理 ID | chunk_id, knowledge_id, source_id, tag_id |
|
||||
|
||||
正文、标题、摘要、向量、slug、in_links/out_links、pages_affected 不改写;本地自增列
|
||||
(如 `wiki_log_entries.id`)仍由既有 LocalIDs 分配。引用指向未登记身份时拒绝(悬挂引用不静默放行)。
|
||||
|
||||
## 一致性边界
|
||||
|
||||
- 写集合登记的是目标身份;verify 的身份摘要与内容摘要都按同一 `rowTransform` 计算;
|
||||
- 索引计划的目标文档 ID 与 `_source` 引用同步映射,before-image(目标写前镜像)保持原样;
|
||||
- 恢复重放写前镜像时映射关闭,避免把目标原始 ID 再映射一次;
|
||||
- 资源对象路径/location_hash 仍由既有资源改写逻辑处理,不因 ID 映射而变化。
|
||||
@@ -0,0 +1,105 @@
|
||||
# 对象写入网关(开发候选,尚不可部署业务)
|
||||
|
||||
## 协议与持久化
|
||||
|
||||
`cmd/object-gateway` 提供 `kg-object-gateway-v1`,只监听 loopback;外部接入需要另行审核的 TLS 终结与网络隔离。治理 PG 保存不可变计划、grant、intent、逐版本 receipt 和 attempt→grant delivery。部署迁移身份显式应用 `internal/objectgateway/schema.sql`;启动不自动迁移。运行身份只授必要 SELECT/INSERT 和 scope 行 UPDATE,不授 DDL/TRUNCATE/证据修改或业务库写权限。
|
||||
|
||||
scope 是 provider、原 endpoint、bucket 的 NUL 分隔 SHA256。同一物理桶在本网关内只使用一个 scope 和一套共享 journal,不能用 endpoint 别名或另一日志库建立平行写域。这不要求整桶只有本网关一个写者:别的服务可以在同一桶的其它 key 上正常读写。
|
||||
|
||||
数据认证端点:`POST /v1/acquire`、`/v1/resolve`、`/v1/execute`、`/v1/reconcile`、`/v1/observe`,以及 `GET /v1/capabilities`。所有请求核验协议和 scope。`capabilities.automatic_grants` 必须为真,正式 stack 才接受自动授权能力;未接控制源、只读角色权限异常、协议不符或不可达均拒绝,无直写回退。
|
||||
|
||||
PG 行锁负责原子准入,不是远端存储 fence。intent 必须持久提交后才发送一次请求;连接死亡、租约过期不清除未知 intent。任何未终态 intent 均阻止 scope 换 epoch。重复 operation 只读回执或精确对账,不重发 PUT;暂时查不到版本仍 held。删除必须绑定已确认 create 的精确 VersionID,不删 latest、不生成删除标记。
|
||||
|
||||
同 key 竞争按 key 判定,不按桶判定:create 前已存在任何版本 → 回执 `rejected` 且不修改该对象;PUT 后除精确版本读回外还核对当前 latest,若并发写者已产生更新的当前版本,则只按精确 VersionID 撤回本次写入,保留对方版本并返回冲突;读不到当前版本时保持 held,不删除、不猜测。版本化存储的 PUT 不是原子 create-if-absent,因此“本 key 多数情况下归本计划”不是存储层保证。
|
||||
|
||||
不可变证据表拒绝 UPDATE/DELETE/TRUNCATE。Ready 核 fsync、synchronous_commit、full_page_writes、主库可写及必要表/触发器;管理员与迁移身份仍是可信边界,触发器不能抵御 DBA 的 DDL。
|
||||
|
||||
## 正式控制交付路径
|
||||
|
||||
生产代码路径已接入,并已在专属本机隔离栈运行正式 worker 的两次 SIGKILL 接管;这不是生产部署验收:
|
||||
|
||||
`cmd/worker.runOwnedLibraryAttempt → attempt context → librarystack → GatewayObjectStore(Automatic) → ProductionLibraryTarget.Apply → EnsureObjectGrant → /v1/acquire → GatewayGovernanceAuthority → 原持久 WriteSet → journal delivery → 数据 execute`。
|
||||
|
||||
冻结/采用计划时只保存自校验后的 WriteSet,不提前索取 grant;observer 先把摘要锚定到原预备份事件,首笔业务 PG Apply 前才请求授权。worker 只提交 job/operation/attempt epoch/owner/plan digest,不提交可替换的 key/body allowlist,也不能选择网关 epoch。
|
||||
|
||||
可信控制域使用独立 SELECT-only 治理连接,核对目标身份、job/operation、当前 attempt、owner、有效租约、running 状态和原预备份事件中的摘要、job、backup、目标快照;再从归档加载并验 hash、范围、provider/bucket。客户端自述不能替代这些持久事实。控制读角色不得是 superuser、CREATEDB、CREATEROLE,不能写/截断/建触发器到这些治理表。每次加载和能力查询重验角色。
|
||||
|
||||
网关在 scope 锁内再次核对授权事实,原子写入 grant、当前 epoch、不可变 delivery。同一 attempt 重试返回原 grant;owner/operation/plan 替换拒绝;同一 job 的后续 attempt 必须沿用原 operation 和 plan。旧发送未终态时,新 attempt 可先只读对账,但无充分证据仍 held,不能交接。
|
||||
|
||||
控制服务配置了治理 authority 后,旧 `/v1/plans`、`/v1/advance` 手动控制端点关闭,控制 token 也不能绕过原计划绑定。旧 `cmd/object-gateway-control` 仅保留离线/协议兼容路径,不是正式 worker 的交付方案。
|
||||
|
||||
## 独立恢复请求
|
||||
|
||||
`library.recover` 的队列ID由原窗口job确定;它具有独立恢复operation与request digest,绑定scope、queue、原window/operation、target、source、backup和原WriteSet。原计划的job、operation和摘要不改写。Claim中的`recovery_job_id`与`recovery_operation_id`仅为独立授权上下文,原`job_id`/`operation_id`仍是发送域。网关重新读取持久队列payload、running状态、当前owner/attempt/有效租约与恢复operation,不信任worker自行声明。可选显式来源/目标/backup/plan字段只能收紧原绑定,不能覆盖它。
|
||||
|
||||
SELECT-only治理角色需要读取`library_jobs`、`library_operations`、`library_attempts`、`library_versions`、`jobs`,均不能INSERT/UPDATE/DELETE/TRUNCATE/TRIGGER。已有原窗口恢复请求时不自动重启原发布;过期running恢复队列只在相同target、未释放维护窗口、原业务租约也过期时重新投递,业务attempt/epoch仍重新申请。
|
||||
|
||||
## 索引unknown恢复边界
|
||||
|
||||
原冻结before-image非空时,恢复先持久化`restore-mark-intent`,再以原CAS(或确认缺失的create)写入包含原计划/index/id归属标记的完整before-image。丢响应后仅匹配完整标记正文及有效CAS才能登记`restore-claimed`并CAS去标记;已知回执的代次不一致拒绝。恢复完成的`restored`回执仍须匹配正文和CAS,不能接受同正文的新代次。
|
||||
|
||||
去标记前持久化`restore-finalize-intent`。发布clean-finalization或恢复clean-finalization已提交但响应丢失时,当前干净正文并非充分归属证据;继续held,不盲删、不重发、不把相同外观当回执。旧unknown缺少写前标记intent亦不自动升级认领。本候选没有服务端可验证的clean提交关联凭证,因此这部分自动收敛仍是明确缺口,不是可部署完整恢复保证。
|
||||
|
||||
## 跨 epoch 的不可变发送身份
|
||||
|
||||
`Request.Grant` 继续代表首次发送的不可变身份,后端 claim、intent 和 receipt 都不改。新 `ExecuteRequest.authorization` 仅代表本次准入权限。`/v1/resolve` 根据相同 operation/key/action/hash/length/owner/plan 取回旧请求;只允许 epoch 差异,不能换内容。
|
||||
|
||||
新 attempt 获得新 grant 后,已发送 key 沿用旧 request/claim,未发送 key 使用新授权 epoch 建立首次 intent。当前授权必须匹配 journal 的当前 epoch;旧 epoch 的新写拒绝。新 epoch 补偿删除仍使用原 create 回执和精确版本,删除本身有独立不可变发送身份。
|
||||
|
||||
## 配置与凭据归属
|
||||
|
||||
网关进程环境:
|
||||
|
||||
- `OBJECT_GATEWAY_LISTEN`:仅 `127.0.0.1:<port>` 或 `[::1]:<port>`。
|
||||
- `OBJECT_GATEWAY_DATABASE_URL`:独立 journal 连接,迁移与运行角色分离。
|
||||
- `OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL`:仅可信网关持有的 SELECT-only 治理读连接;独立于 journal 运行身份和普通 worker 身份。
|
||||
- `OBJECT_GATEWAY_ARCHIVE_ROOT`:原持久计划所在归档绝对路径,部署只读挂载。
|
||||
- `OBJECT_GATEWAY_TARGET_ID`:与正式 worker `LibraryTargetIdentity()` 完全相同的逻辑目标身份;不能用另一个环境的值。
|
||||
- `OBJECT_GATEWAY_PROVIDER`、`OBJECT_GATEWAY_ENDPOINT`、`OBJECT_GATEWAY_BUCKET`、`OBJECT_GATEWAY_REGION`:精确存储身份。
|
||||
- `OBJECT_GATEWAY_ACCESS_KEY`、`OBJECT_GATEWAY_SECRET_KEY`:网关持有的对象凭据,需在目标桶 PUT/GET/按版本 DELETE/列举版本。沿用现有 AK 即可,不要求另建独立只读或独占写凭据。
|
||||
- `OBJECT_GATEWAY_DATA_TOKEN`、`OBJECT_GATEWAY_CONTROL_TOKEN`:不同且至少 32 字节;普通 worker 仅持有 data token。
|
||||
- `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`:**已退役**。旧部署残留的值被忽略,不参与启动、Ready、每次 Execute 或能力判断;不需要管理员签发整桶独占证明,也不会因过期文件拒绝发布。
|
||||
|
||||
秘密只经服务环境/私有文件注入,不进 argv、URL 或日志。所有调用端错误都使用固定原因码。
|
||||
|
||||
正式 worker 使用 `LIBRARY_OBJECT_GATEWAY_URL` 和 `LIBRARY_OBJECT_GATEWAY_TOKEN`;不再依赖预先生成的 grant 文件。`LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY` 保留旧离线兼容用途,不是自动模式的授权来源。发布 stack 对所有对象 provider 强制网关;S3 构造仍用于只读捕获/预备份,可继续使用现有凭据,不再要求独立只读 OSS AK。
|
||||
|
||||
## 已关闭的本仓旁路
|
||||
|
||||
- `ObjectImporter.Stage/Promote` 无条件拒绝,不留配置开关,不执行 PUT/COPY。
|
||||
- legacy `release-worker` runtime/route 在读凭据及连接目标前拒绝。
|
||||
- `release-diag`、`release-channel-e2e` 旧写型入口启动即非零退出,避免 probe PUT 或文档级旁路。
|
||||
- `librarystack` 不再为缺网关的 MinIO/S3 返回直写 writer。
|
||||
- `libraryctl` capture 的 S3 构造与读取保留;未把读取当作写入口禁用。
|
||||
|
||||
这不等于已经撤销运行环境旧进程的凭据;源码变更尚未部署。`librarydrill` 等无 owned-attempt 的旧写型工具不能靠静态 grant 绕过自动模式,需补正式执行身份后才可用于写入。低层 S3 adapter 仍用于网关后端、读取及显式隔离夹具;共享桶不要求撤除其它写者,跨写者的同 key 竞争按冲突/held 处理。
|
||||
|
||||
## 实测与未完成边界
|
||||
|
||||
已实跑:真实治理 PG(独立 SELECT-only 登录角色)、原 archive、数据 HTTP、业务 PG 与 MinIO 的自动授权/跨 epoch 链;未锚定计划在第一笔 PG 前拒绝,接管保持原发送身份且不增加 PUT。另有真实网关二进制的两次中断验证,以及共享桶下“无整桶证明启动 + 其它 key 并发写入 + 同 key 既有对象拒绝”的真实 PG/MinIO 用例。历史隔离审计 authority/故障注入是当时的测试设施,不是当前部署前置。
|
||||
|
||||
正式 worker 隔离进程证据:真实 Docker 入口闸门/队列、只读 worker 对象身份、独立治理读取角色、网关与业务 PG/ES/MinIO;首次 PG 后和对象提交后两次 SIGKILL,同一原 job/operation/plan 的三代 attempt 完成发布,原对象发送 epoch 与回执不变。隔离构建标签 `kg_isolated_drill` 仅把真实租约缩短至4秒,并拒绝非 loopback 一次性 r8 库;正常构建仍为10分钟。维护上游是无业务凭据的独立 HTTP 夹具,不是运行中的 WeKnora;签名证据绑定本次真实拒写/排空材料,不代表生产独占审核。
|
||||
|
||||
已补独立 `library.recover` 正式worker链、恢复中再次SIGKILL、完整before-image/CAS/精确版本读回,以及来源/目标/原job/计划/operation/任意队列身份拒绝。ES故障代理只转发真实ES并丢弃已提交响应,未伪造服务响应。
|
||||
|
||||
尚未完成:clean-finalization unknown的充分归属与自动收敛;网关真实 OSS 端到端与真实部署验收(父执行);原D0/F11/F12与55项其余缺口。测试/隔离验收与真实部署分列。
|
||||
|
||||
整桶独占审核、全部 writer 排空、独立只读对象凭据已不再是发布前置;维护窗口内停目标写入容器并读回确认即可更新。网关按 key 拒绝冲突、精确版本回滚,但不承诺无关写者同时修改同一 key 时仍能自动完成——那种情况会明确冲突或 held,需要人工按回执处理。未改生产权限或上游 WeKnora 源码/Schema。
|
||||
|
||||
## 维护式更新(已采用)
|
||||
|
||||
目标测试 KB 的更新走维护窗口,不再要求证明整桶只有一个写者:
|
||||
|
||||
1. 停目标测试 WeKnora 的写入应用容器(只停该服务,不停机器人、适配器、共享 PG/ES 或其它 KB 的服务),并由容器状态/健康读回确认已停止。这是本轮文档化的运维步骤;代码侧没有新增停容器实现。
|
||||
2. 用既有维护/预备份链记录本次目标 KB/对象范围:实例级维护窗口与写者停写证据由 `internal/libraryfreeze` + `internal/librarymaintenance` 采集,`libraryctl capture`(页面入口 `POST /api/v1/library/captures`)完成闸门排空→停写者→导出快照并保留 `post_stop_digest`;不把通用主机备份当作 KB 预备份的替代。
|
||||
3. 用原 plan、原 WriteSet 摘要和限定对象清单走既有 `ProductionLibraryTarget.Apply`(经正式 worker owned attempt 与网关 grant)更新资源;网关沿用现有 AK,不换凭据、不签独占证明。
|
||||
4. 启动原容器,健康检查与页面业务验收;失败走既有 `library.recover`/`RestoreDrill` 恢复链按原预备份回放并启动原服务,不无限留停机。
|
||||
5. 无关服务与无关 key 全程不需要停;同 key 若仍有外部写者,按上节的冲突/held 处理:双方版本都保留,由人按证据处置,不自动合并。
|
||||
|
||||
部署需变更的组件:`object-gateway`(本候选镜像)、`worker`(同提交镜像),以及两者 env 中移除/留空已退役的 `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`。`api`、`web` 无协议变更,可不同步。journal、治理 PG 只读 authority、archive 与 target identity 配置保持不变。
|
||||
|
||||
## 部署与回退(未执行)
|
||||
|
||||
测试主机 `120.76.217.51`、生产 `120.76.218.137` 各自独立批准;本候选未在任一主机执行停机、备份、更新或启动。r5 的已完成 OSS 测试授权不能重复使用。
|
||||
|
||||
按“停目标写入容器→读回确认→备份目标 KB 范围→更新资源→启动→健康/页面验收”执行;失败按原备份恢复并启动原服务。回退先关新写准入并保留 journal;所有已发送请求有终态才可撤网关,unknown 继续 held。不得因网关故障自动恢复旧直写凭据。当前整模块仍未完成真实 OSS 端到端与 clean-finalization 收敛,禁止把本候选当作完整生产就绪。
|
||||
@@ -0,0 +1,45 @@
|
||||
# 发布管理流程与页面精简
|
||||
|
||||
## 目标与边界
|
||||
|
||||
现有整库发布页面同时呈现日常发布、维护诊断、恢复演练与历史快照,且封存操作位于页面底部,版本入口重复。此次优化聚焦 `ReleaseTargets` 的信息层级和操作位置,沿用现有 API、权限、授权绑定、维护所有者与恢复确认。
|
||||
|
||||
基线采用云测试站当前前端对应的工作树 `cbc6b98`;该提交的 web 与部署版本 `0b753e5` 相同。并行主干及其他工作树不合并、不覆盖。
|
||||
|
||||
## 操作者主流程
|
||||
|
||||
| 顺序 | 页面操作 | 后台行为 | 完成边界 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 选择对内或对外知识库 | 读取该范围 overview、快照、作业及维护窗口 | 目标身份与版本来自所选范围;读取失败不当作空库 |
|
||||
| 2 | 封存测试版本 | POST `/api/v1/library/captures`,由队列及执行器捕获测试整库版本 | 投递不等于完成,以作业与登记快照为准;此步不发布生产 |
|
||||
| 3 | 查看变更及发布条件 | 展开变更、备份与恢复验证;若缺基线或恢复证据,沿用对应管理员入口 | 逐条呈现服务端阻塞原因,不删除发布门槛 |
|
||||
| 4 | 签发同步授权 | 管理员调用 `/api/v1/library/authorizations`,绑定目标与当前快照 | 有效期内仍需单独点击启动;不自动执行同步 |
|
||||
| 5 | 启动同步 | 沿用现有同步请求与执行链:固定版本、生产预备份、同步、校验及收尾 | 只在接口条件允许时可执行;运行中主按钮改为查看任务 |
|
||||
| 6 | 查看结果 | 自动刷新作业进度,终态按真实记录呈现 | 失败显示原始原因;维护占用不被其他作业成功覆盖 |
|
||||
| 异常 | 从版本与快照选择恢复点 | 继续执行独立恢复授权、影响确认和恢复条件校验 | 恢复整套目标知识状态,不回退测试知识库 |
|
||||
|
||||
封存、签发授权、启动同步三个动作保持独立,不将其合并为一键生产写入。
|
||||
|
||||
## 页面保留规则
|
||||
|
||||
- 顶栏:唯一的「版本与快照」入口和刷新。
|
||||
- 主工作区:实际目标身份、当前生产版本、候选测试版本、紧凑变更统计、当前主动作与一份阻塞原因。
|
||||
- 已有封存时提供次级「重新封存」;运行时不提供重复封存、授权或同步入口。
|
||||
- 「查看变更明细」「发布准备与恢复验证」「封存完整性」默认折叠;原有详情和验证回调继续存在。
|
||||
- 目标维护正常时折叠,持有维护窗口时自动展开;仍按窗口持有作业展示恢复信息。
|
||||
- 最近作业仅在有记录时展示,正常完成默认折叠,失败默认展开;运行中保留主进度,分项明细按需展开。
|
||||
- 版本抽屉保留历史筛选、分页、校验记录、恢复授权和影响确认,移除重复的封存按钮。
|
||||
- 发布管理页面移除旧文档级发布及历史来源关联区域,只展示整库发布流程。
|
||||
|
||||
## 验收清单
|
||||
|
||||
- [x] 前端生产构建通过。
|
||||
- [x] 原发布、恢复、维护所有者和刷新/切库回归通过。
|
||||
- [x] 同一挂载下依次切换封存、授权、同步,点击只调用对应动作。
|
||||
- [x] 折叠与展开、打开历史不触发业务写入。
|
||||
- [x] 运行时主操作只查看任务,不调用封存、授权或同步。
|
||||
- [x] 正常维护折叠、持有时展开、释放后折叠;切库重置明细展开状态。
|
||||
- [x] 无作业不画空进度;失败原因默认可见。
|
||||
- [x] 只读角色和读取失败时禁止主动作。
|
||||
|
||||
浏览器验收使用本地候选构建,GET/HEAD 通过已有 SSH 通道读取云测试 API;代理拒绝所有写请求。界面验收与真实封存、生产同步及恢复演练分开记录;本任务不执行这些业务写入。完整仓库门禁和云端部署结论以实际运行结果为准,不用上述前端检查替代。
|
||||
+123
-61
@@ -3,6 +3,7 @@ package appconfig
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -23,8 +24,11 @@ type Config struct {
|
||||
ReleaseConfigFile string
|
||||
ProductionReleaseRequestsEnabled bool
|
||||
ProductionBackupRestoreVerified bool
|
||||
ProductionReleaseAuthorizerRef string
|
||||
ProductionReleaseAuthTokenFile string
|
||||
// LibraryRestoreDispatchEnabled 允许 worker 装配 DS01 派发台账;默认 false。
|
||||
// 它不能单独证明独占:治理库里的目标激活登记同样必需。
|
||||
LibraryRestoreDispatchEnabled bool
|
||||
ProductionReleaseAuthorizerRef string
|
||||
ProductionReleaseAuthTokenFile string
|
||||
// Production WeKnora endpoint: the release target itself stays declared in
|
||||
// the release runtime config (RELEASE_CONFIG_FILE); these settings only let
|
||||
// the API probe that endpoint so the console can show its real state.
|
||||
@@ -81,12 +85,15 @@ type Config struct {
|
||||
LibraryProductionExternalKB string
|
||||
// LibraryProductionS3Provider 必须与生产库 resources.provider 的取值一致:
|
||||
// 对象路径按 provider 路由,写错会在上传时被拒绝(而不是写错桶)。
|
||||
LibraryProductionS3Provider string
|
||||
LibraryProductionS3Endpoint string
|
||||
LibraryProductionS3Region string
|
||||
LibraryProductionS3Bucket string
|
||||
LibraryProductionS3AccessKey string
|
||||
LibraryProductionS3SecretKey string
|
||||
LibraryProductionS3Provider string
|
||||
LibraryProductionS3Endpoint string
|
||||
LibraryProductionS3Region string
|
||||
LibraryProductionS3Bucket string
|
||||
LibraryProductionS3AccessKey string
|
||||
LibraryProductionS3SecretKey string
|
||||
LibraryObjectGatewayURL string
|
||||
LibraryObjectGatewayToken string
|
||||
LibraryObjectGatewayGrantDirectory string
|
||||
// LibraryEmbeddingModel 是整库发布使用的向量模型声明(快照契约缺失时的回落值)。
|
||||
LibraryEmbeddingModel string
|
||||
// LibraryWorkerRole 决定这个进程消费哪一段队列(见 LibraryWorkerRole 说明)。
|
||||
@@ -123,6 +130,11 @@ type Config struct {
|
||||
// 入口闸门:关入口与排空在它身上做(被代理服务自己不排空)。
|
||||
LibraryTargetIngressService string
|
||||
LibraryTargetIngressDrainFile string
|
||||
// 入口形态:gate(默认)或 none。none 只给整栈没有入口闸门的测试环境用,
|
||||
// 必须同时给 LibraryTargetNoIngressAck,且证据等级降一档并如实记录。
|
||||
LibraryTargetIngressMode string
|
||||
LibraryTargetNoIngressAck string
|
||||
LibraryTargetHealthURL string
|
||||
// 后台静默检查:目标队列 + 目标库(HTTP 排空不等于后台任务排空)。
|
||||
LibraryTargetRedisAddr string
|
||||
LibraryTargetRedisPassword string
|
||||
@@ -203,54 +215,61 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
TestAcceptancePolicyVersion: valueOrDefault(getenv("TEST_ACCEPTANCE_POLICY_VERSION"), "structural-v1"),
|
||||
TestAutoReviewPolicy: valueOrDefault(getenv("TEST_AUTO_REVIEW_POLICY"), string(governance.AutoReviewInternal)),
|
||||
// 整库逻辑备份的目标主机:三项同时给出才接线(脚本目录/备份根有默认值)。
|
||||
BackupHostSSHConfig: strings.TrimSpace(getenv("BACKUP_HOST_SSH_CONFIG")),
|
||||
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
|
||||
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
|
||||
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
|
||||
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
|
||||
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
|
||||
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
|
||||
LibraryArchiveRoot: strings.TrimSpace(getenv("LIBRARY_ARCHIVE_ROOT")),
|
||||
LibraryAgentSocket: strings.TrimSpace(getenv("LIBRARY_AGENT_SOCKET")),
|
||||
LibraryProductionDatabaseURL: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_DATABASE_URL")),
|
||||
LibraryProductionElasticURL: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_ELASTIC_URL")),
|
||||
LibraryProductionIndex: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_INDEX")), "weknora_full_chunks"),
|
||||
LibraryProductionTenantID: uint64(tenantID),
|
||||
LibraryProductionInternalKB: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_KB_INTERNAL")),
|
||||
LibraryProductionExternalKB: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_KB_EXTERNAL")),
|
||||
LibraryProductionS3Provider: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_PROVIDER")), "s3"),
|
||||
LibraryProductionS3Endpoint: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_ENDPOINT")),
|
||||
LibraryProductionS3Region: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_REGION")), "us-east-1"),
|
||||
LibraryProductionS3Bucket: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_BUCKET")),
|
||||
LibraryProductionS3AccessKey: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_ACCESS_KEY")),
|
||||
LibraryProductionS3SecretKey: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_SECRET_KEY")),
|
||||
LibraryTargetInstance: strings.TrimSpace(getenv("LIBRARY_TARGET_INSTANCE")),
|
||||
LibrarySourceInstance: strings.TrimSpace(getenv("LIBRARY_SOURCE_INSTANCE")),
|
||||
LibrarySourceProject: strings.TrimSpace(getenv("LIBRARY_SOURCE_PROJECT")),
|
||||
LibrarySourceApp: strings.TrimSpace(getenv("LIBRARY_SOURCE_APP")),
|
||||
LibrarySourceTenantID: uint64(sourceTenantID),
|
||||
LibrarySourceInternalKB: strings.TrimSpace(getenv("LIBRARY_SOURCE_KB_INTERNAL")),
|
||||
LibrarySourceExternalKB: strings.TrimSpace(getenv("LIBRARY_SOURCE_KB_EXTERNAL")),
|
||||
LibraryTargetProject: strings.TrimSpace(getenv("LIBRARY_TARGET_PROJECT")),
|
||||
LibraryTargetWriters: splitList(getenv("LIBRARY_TARGET_WRITERS")),
|
||||
LibraryTargetNonWriters: splitDeclarations(getenv("LIBRARY_TARGET_NON_WRITERS")),
|
||||
LibraryTargetDockerSocket: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_TARGET_DOCKER_SOCKET")), "/var/run/docker.sock"),
|
||||
LibraryTargetIngressURL: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_URL")),
|
||||
LibraryTargetIngressService: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_SERVICE")),
|
||||
LibraryTargetIngressDrainFile: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_DRAIN_FILE")),
|
||||
LibraryTargetRedisAddr: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_ADDR")),
|
||||
LibraryTargetRedisPassword: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_PASSWORD")),
|
||||
LibraryTargetRedisDB: valueOrDefaultInt(getenv("LIBRARY_TARGET_REDIS_DB"), 0),
|
||||
LibraryTargetJournalRoot: strings.TrimSpace(getenv("LIBRARY_TARGET_JOURNAL_ROOT")),
|
||||
LibraryEmbeddingModel: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_MODEL")), "text-embedding-v4"),
|
||||
LibraryEmbeddingDimension: embeddingDimension,
|
||||
LibraryCapacityBudgetBytes: capacityBudget,
|
||||
LibraryRetentionVersions: retentionVersions,
|
||||
LibraryRetentionDays: retentionDays,
|
||||
LibraryExecutorStatusMaxAge: 2 * time.Minute,
|
||||
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
|
||||
VersionHistoryHTTPTimeout: 15 * time.Second,
|
||||
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
|
||||
BackupHostSSHConfig: strings.TrimSpace(getenv("BACKUP_HOST_SSH_CONFIG")),
|
||||
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
|
||||
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
|
||||
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
|
||||
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
|
||||
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
|
||||
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
|
||||
LibraryArchiveRoot: strings.TrimSpace(getenv("LIBRARY_ARCHIVE_ROOT")),
|
||||
LibraryAgentSocket: strings.TrimSpace(getenv("LIBRARY_AGENT_SOCKET")),
|
||||
LibraryProductionDatabaseURL: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_DATABASE_URL")),
|
||||
LibraryProductionElasticURL: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_ELASTIC_URL")),
|
||||
LibraryProductionIndex: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_INDEX")), "weknora_full_chunks"),
|
||||
LibraryProductionTenantID: uint64(tenantID),
|
||||
LibraryProductionInternalKB: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_KB_INTERNAL")),
|
||||
LibraryProductionExternalKB: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_KB_EXTERNAL")),
|
||||
LibraryProductionS3Provider: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_PROVIDER")), "s3"),
|
||||
LibraryProductionS3Endpoint: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_ENDPOINT")),
|
||||
LibraryProductionS3Region: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_REGION")), "us-east-1"),
|
||||
LibraryProductionS3Bucket: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_BUCKET")),
|
||||
LibraryProductionS3AccessKey: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_ACCESS_KEY")),
|
||||
LibraryProductionS3SecretKey: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_SECRET_KEY")),
|
||||
LibraryObjectGatewayURL: strings.TrimSpace(getenv("LIBRARY_OBJECT_GATEWAY_URL")),
|
||||
LibraryObjectGatewayToken: strings.TrimSpace(getenv("LIBRARY_OBJECT_GATEWAY_TOKEN")),
|
||||
LibraryObjectGatewayGrantDirectory: strings.TrimSpace(getenv("LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY")),
|
||||
LibraryTargetInstance: strings.TrimSpace(getenv("LIBRARY_TARGET_INSTANCE")),
|
||||
LibrarySourceInstance: strings.TrimSpace(getenv("LIBRARY_SOURCE_INSTANCE")),
|
||||
LibrarySourceProject: strings.TrimSpace(getenv("LIBRARY_SOURCE_PROJECT")),
|
||||
LibrarySourceApp: strings.TrimSpace(getenv("LIBRARY_SOURCE_APP")),
|
||||
LibrarySourceTenantID: uint64(sourceTenantID),
|
||||
LibrarySourceInternalKB: strings.TrimSpace(getenv("LIBRARY_SOURCE_KB_INTERNAL")),
|
||||
LibrarySourceExternalKB: strings.TrimSpace(getenv("LIBRARY_SOURCE_KB_EXTERNAL")),
|
||||
LibraryTargetProject: strings.TrimSpace(getenv("LIBRARY_TARGET_PROJECT")),
|
||||
LibraryTargetWriters: splitList(getenv("LIBRARY_TARGET_WRITERS")),
|
||||
LibraryTargetNonWriters: splitDeclarations(getenv("LIBRARY_TARGET_NON_WRITERS")),
|
||||
LibraryTargetDockerSocket: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_TARGET_DOCKER_SOCKET")), "/var/run/docker.sock"),
|
||||
LibraryTargetIngressURL: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_URL")),
|
||||
LibraryTargetIngressService: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_SERVICE")),
|
||||
LibraryTargetIngressDrainFile: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_DRAIN_FILE")),
|
||||
LibraryTargetIngressMode: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_MODE")),
|
||||
// 确认串不 Trim:必须逐字符相等,多一个空格都算没确认。
|
||||
LibraryTargetNoIngressAck: getenv("LIBRARY_NO_INGRESS_ACK"),
|
||||
LibraryTargetHealthURL: strings.TrimSpace(getenv("LIBRARY_TARGET_HEALTH_URL")),
|
||||
LibraryTargetRedisAddr: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_ADDR")),
|
||||
LibraryTargetRedisPassword: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_PASSWORD")),
|
||||
LibraryTargetRedisDB: valueOrDefaultInt(getenv("LIBRARY_TARGET_REDIS_DB"), 0),
|
||||
LibraryTargetJournalRoot: strings.TrimSpace(getenv("LIBRARY_TARGET_JOURNAL_ROOT")),
|
||||
LibraryEmbeddingModel: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_MODEL")), "text-embedding-v4"),
|
||||
LibraryEmbeddingDimension: embeddingDimension,
|
||||
LibraryCapacityBudgetBytes: capacityBudget,
|
||||
LibraryRetentionVersions: retentionVersions,
|
||||
LibraryRetentionDays: retentionDays,
|
||||
LibraryExecutorStatusMaxAge: 2 * time.Minute,
|
||||
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
|
||||
VersionHistoryHTTPTimeout: 15 * time.Second,
|
||||
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
|
||||
}
|
||||
if config.DatabaseURL == "" {
|
||||
return Config{}, errors.New("DATABASE_URL is required")
|
||||
@@ -298,6 +317,14 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, fmt.Errorf("PRODUCTION_BACKUP_RESTORE_VERIFIED: %w", err)
|
||||
}
|
||||
}
|
||||
// DS01 恢复标记派发协议:默认关闭。开关只是"允许装配"的意思,不是独占证明——
|
||||
// 真正发放许可还要求治理库里对该目标存在未撤销的激活登记。
|
||||
if raw := getenv("LIBRARY_RESTORE_DISPATCH_V2"); raw != "" {
|
||||
config.LibraryRestoreDispatchEnabled, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("LIBRARY_RESTORE_DISPATCH_V2: %w", err)
|
||||
}
|
||||
}
|
||||
if raw := getenv("PRODUCTION_WEKNORA_ALLOW_DOCKER_HTTP"); raw != "" {
|
||||
config.ProductionWeKnoraAllowDockerHTTP, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
@@ -370,9 +397,35 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
if config.LibraryAgentSocket != "" && !filepath.IsAbs(config.LibraryAgentSocket) {
|
||||
return Config{}, errors.New("LIBRARY_AGENT_SOCKET 必须是绝对路径(unix socket 由主机侧 agent 持有)")
|
||||
}
|
||||
// 入口形态:缺省 gate,行为与之前完全一致。none 只给整栈没有入口闸门的
|
||||
// 测试环境用,必须显式确认;确认串逐字符相等,多一个空格都算没确认。
|
||||
if config.LibraryTargetIngressMode == "" {
|
||||
config.LibraryTargetIngressMode = "gate"
|
||||
}
|
||||
switch config.LibraryTargetIngressMode {
|
||||
case "gate", "none":
|
||||
default:
|
||||
return Config{}, fmt.Errorf("LIBRARY_TARGET_INGRESS_MODE 无效(%q):只能是 gate 或 none",
|
||||
config.LibraryTargetIngressMode)
|
||||
}
|
||||
noGate := config.LibraryTargetIngressMode == "none"
|
||||
if noGate && config.LibraryTargetNoIngressAck != "test-only" {
|
||||
return Config{}, errors.New("no-gate 维护必须显式确认:LIBRARY_NO_INGRESS_ACK 必须逐字符等于 test-only,拒绝启动")
|
||||
}
|
||||
if !noGate && config.LibraryTargetNoIngressAck != "" {
|
||||
return Config{}, errors.New("LIBRARY_NO_INGRESS_ACK 只在 LIBRARY_TARGET_INGRESS_MODE=none 下有效")
|
||||
}
|
||||
if config.LibraryTargetHealthURL != "" {
|
||||
parsed, err := url.Parse(config.LibraryTargetHealthURL)
|
||||
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") ||
|
||||
parsed.Host == "" || parsed.User != nil {
|
||||
return Config{}, errors.New("LIBRARY_TARGET_HEALTH_URL 必须是 http(s) 地址且不带凭据")
|
||||
}
|
||||
}
|
||||
// 目标维护要么完整配置,要么完全不配;半配置会让窗口"看起来存在"却挡不住目标。
|
||||
targetSet := config.LibraryTargetInstance != "" || config.LibraryTargetProject != "" ||
|
||||
len(config.LibraryTargetWriters) > 0 || config.LibraryTargetIngressURL != ""
|
||||
len(config.LibraryTargetWriters) > 0 || config.LibraryTargetIngressURL != "" ||
|
||||
noGate || config.LibraryTargetHealthURL != ""
|
||||
if targetSet {
|
||||
missing := make([]string, 0, 4)
|
||||
if config.LibraryTargetInstance == "" {
|
||||
@@ -384,16 +437,21 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
if len(config.LibraryTargetWriters) == 0 {
|
||||
missing = append(missing, "LIBRARY_TARGET_WRITERS")
|
||||
}
|
||||
if config.LibraryTargetIngressURL == "" {
|
||||
if noGate {
|
||||
// 没有闸门可声明:健康探针是唯一能证明"目标回来了"的必需项。
|
||||
if config.LibraryTargetHealthURL == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_HEALTH_URL")
|
||||
}
|
||||
} else if config.LibraryTargetIngressURL == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
|
||||
}
|
||||
if config.LibraryTargetJournalRoot == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_JOURNAL_ROOT")
|
||||
}
|
||||
if config.LibraryTargetIngressService == "" {
|
||||
if !noGate && config.LibraryTargetIngressService == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
|
||||
}
|
||||
if config.LibraryTargetIngressDrainFile == "" {
|
||||
if !noGate && config.LibraryTargetIngressDrainFile == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_DRAIN_FILE")
|
||||
}
|
||||
if config.LibraryTargetRedisAddr == "" {
|
||||
@@ -402,13 +460,17 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
if len(missing) > 0 {
|
||||
return Config{}, fmt.Errorf("目标维护配置不完整:缺少 %s", strings.Join(missing, "、"))
|
||||
}
|
||||
if noGate && (config.LibraryTargetIngressURL != "" || config.LibraryTargetIngressService != "" ||
|
||||
config.LibraryTargetIngressDrainFile != "") {
|
||||
return Config{}, errors.New("no-gate 维护不得同时配置入口地址/闸门服务/排空文件:要么有闸门,要么明确没有")
|
||||
}
|
||||
if !filepath.IsAbs(config.LibraryTargetJournalRoot) {
|
||||
return Config{}, errors.New("LIBRARY_TARGET_JOURNAL_ROOT 必须是绝对路径")
|
||||
}
|
||||
if !filepath.IsAbs(config.LibraryTargetDockerSocket) {
|
||||
return Config{}, errors.New("LIBRARY_TARGET_DOCKER_SOCKET 必须是绝对路径")
|
||||
}
|
||||
if !filepath.IsAbs(config.LibraryTargetIngressDrainFile) {
|
||||
if !noGate && !filepath.IsAbs(config.LibraryTargetIngressDrainFile) {
|
||||
return Config{}, errors.New("LIBRARY_TARGET_INGRESS_DRAIN_FILE 必须是绝对路径")
|
||||
}
|
||||
if len(config.LibraryTargetNonWriters) == 0 {
|
||||
|
||||
@@ -73,12 +73,13 @@ func (r LibraryWorkerRole) LibraryJobKinds() []string {
|
||||
switch r {
|
||||
case LibraryWorkerRoleReleaseExecutor:
|
||||
return []string{string(governance.LibraryJobSync), string(governance.LibraryJobRestore),
|
||||
string(governance.LibraryJobRecover), string(governance.LibraryJobBaseline)}
|
||||
string(governance.LibraryJobRecover), string(governance.LibraryJobBaseline),
|
||||
string(governance.LibraryJobVerify)}
|
||||
case LibraryWorkerRoleCapture:
|
||||
return []string{string(governance.LibraryJobSeal)}
|
||||
default:
|
||||
return []string{string(governance.LibraryJobSeal), string(governance.LibraryJobSync),
|
||||
string(governance.LibraryJobRestore), string(governance.LibraryJobRecover),
|
||||
string(governance.LibraryJobBaseline)}
|
||||
string(governance.LibraryJobBaseline), string(governance.LibraryJobVerify)}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,13 +63,14 @@ func TestLoadRejectsUnknownLibraryWorkerRole(t *testing.T) {
|
||||
// 每个角色收拾哪些 kind、谁拥有 DDL,都必须互斥且覆盖完整。
|
||||
func TestLibraryWorkerRoleOwnershipMaps(t *testing.T) {
|
||||
release := LibraryWorkerRoleReleaseExecutor
|
||||
if got := release.LibraryJobKinds(); len(got) != 4 || got[0] != "sync" || got[1] != "restore" || got[2] != "recover" || got[3] != "baseline" {
|
||||
if got := release.LibraryJobKinds(); len(got) != 5 || got[0] != "sync" || got[1] != "restore" ||
|
||||
got[2] != "recover" || got[3] != "baseline" || got[4] != "verify" {
|
||||
t.Fatalf("release-executor kinds = %v", got)
|
||||
}
|
||||
if got := LibraryWorkerRoleCapture.LibraryJobKinds(); len(got) != 1 || got[0] != "seal" {
|
||||
t.Fatalf("capture kinds = %v", got)
|
||||
}
|
||||
if got := LibraryWorkerRoleFull.LibraryJobKinds(); len(got) != 5 {
|
||||
if got := LibraryWorkerRoleFull.LibraryJobKinds(); len(got) != 6 {
|
||||
t.Fatalf("full kinds = %v", got)
|
||||
}
|
||||
for _, role := range []LibraryWorkerRole{LibraryWorkerRoleFull, LibraryWorkerRoleCapture} {
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strconv"
|
||||
@@ -127,12 +129,81 @@ func (r *Runner) runRemote(ctx context.Context, timeout time.Duration, remote st
|
||||
if ctx.Err() != nil {
|
||||
return text, fmt.Errorf("ssh %s 超时(%s)", r.config.Target, timeout)
|
||||
}
|
||||
// 主机侧脚本会用退出码表达"参数非法/有库失败",把输出带回去便于页面展示。
|
||||
return text, fmt.Errorf("ssh %s 执行失败: %s", r.config.Target, firstLines(text, 6))
|
||||
// 连接层失败与主机侧命令失败必须分开说:前者连脚本都没跑,
|
||||
// 任何"脚本缺失/计划未下发"都是把未观测当成事实。
|
||||
return text, hostFailure(r.config.Target, text)
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
|
||||
// hostFailure 把 ssh 的非零退出分成两类:连不上,和连上了但远端命令失败。
|
||||
func hostFailure(target, text string) error {
|
||||
if connectionFailurePattern.MatchString(text) {
|
||||
return fmt.Errorf("目标主机 %s 不可达(%s);未执行任何主机侧脚本,脚本与计划状态未知",
|
||||
target, firstLines(text, 3))
|
||||
}
|
||||
// 主机侧脚本会用退出码表达"参数非法/有库失败",把输出带回去便于页面展示。
|
||||
return fmt.Errorf("已连上 %s,但主机侧命令失败: %s", target, firstLines(text, 6))
|
||||
}
|
||||
|
||||
// connectionFailurePattern 是 OpenSSH 客户端在"根本没建立连接"时打的原文。
|
||||
// 只有命中它才允许说"不可达";其余非零退出属于远端命令自己的失败。
|
||||
var connectionFailurePattern = regexp.MustCompile(`(?i)ssh: connect to host|Operation timed out|Connection timed out|Connection refused|Connection reset by peer|No route to host|Network is unreachable|Could not resolve hostname|Host key verification failed|Permission denied|Connection closed by`)
|
||||
|
||||
// Endpoint 读回挂载的 ssh 配置里本别名真实拨号的 host:port。
|
||||
// 页面必须能说清"现在连的是哪个地址"——只显示别名时,改错文件也看不出来。
|
||||
func (r *Runner) Endpoint() string {
|
||||
if r == nil || r.config.SSHConfig == "" || r.config.Target == "" {
|
||||
return ""
|
||||
}
|
||||
raw, err := os.ReadFile(r.config.SSHConfig)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
host, port := sshConfigEndpoint(string(raw), r.config.Target)
|
||||
if host == "" {
|
||||
return ""
|
||||
}
|
||||
if port == "" {
|
||||
port = "22"
|
||||
}
|
||||
return net.JoinHostPort(host, port)
|
||||
}
|
||||
|
||||
// sshConfigEndpoint 解析 `Host <alias>` 段的 HostName/Port(首个匹配段生效)。
|
||||
// 只做"页面显示用"的最小解析,不替代 ssh 自己的配置语义。
|
||||
func sshConfigEndpoint(config, alias string) (string, string) {
|
||||
host, port := "", ""
|
||||
active := false
|
||||
for _, line := range strings.Split(config, "\n") {
|
||||
fields := strings.Fields(strings.TrimSpace(line))
|
||||
if len(fields) == 0 || strings.HasPrefix(fields[0], "#") {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(fields[0])
|
||||
if key == "host" {
|
||||
active = false
|
||||
for _, pattern := range fields[1:] {
|
||||
if pattern == alias {
|
||||
active = true
|
||||
break
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !active || len(fields) < 2 {
|
||||
continue
|
||||
}
|
||||
switch key {
|
||||
case "hostname":
|
||||
host = strings.Trim(fields[1], `"`)
|
||||
case "port":
|
||||
port = strings.Trim(fields[1], `"`)
|
||||
}
|
||||
}
|
||||
return host, port
|
||||
}
|
||||
|
||||
var scheduleAppliedPattern = regexp.MustCompile(
|
||||
`SCHEDULE_APPLIED enabled=(\d)(?: time=(\S+))?(?: days=(\d+))?(?: months=(\d+))?(?: next=(\S+))?(?: cron=(\S+))?`)
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ package backuphost
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -188,6 +190,41 @@ func TestRunnerSurfacesHostFailure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 现场原错:ssh: connect to host 120.76.217.51 port 22: Operation timed out。
|
||||
// 连不上时脚本根本没跑,只能说"不可达";断言配对的反面:不能说脚本缺失。
|
||||
func TestHostFailureSeparatesUnreachableFromRemoteCommand(t *testing.T) {
|
||||
unreachable := hostFailure("weknora-test", "ssh: connect to host 120.76.217.51 port 22: Operation timed out")
|
||||
if !strings.Contains(unreachable.Error(), "不可达") || !strings.Contains(unreachable.Error(), "Operation timed out") {
|
||||
t.Fatalf("连接超时应报不可达并带原错: %v", unreachable)
|
||||
}
|
||||
if strings.Contains(unreachable.Error(), "主机侧命令失败") || strings.Contains(unreachable.Error(), "脚本缺失") {
|
||||
t.Fatalf("连接失败不能报成远端命令/脚本问题: %v", unreachable)
|
||||
}
|
||||
remote := hostFailure("weknora-test", "bash: /opt/weknora-test/logical-backup.sh: No such file or directory")
|
||||
if !strings.Contains(remote.Error(), "已连上") || !strings.Contains(remote.Error(), "No such file") {
|
||||
t.Fatalf("已连接但脚本失败时应原样带回原因: %v", remote)
|
||||
}
|
||||
if strings.Contains(remote.Error(), "不可达") {
|
||||
t.Fatalf("已连上就不能说不可达: %v", remote)
|
||||
}
|
||||
}
|
||||
|
||||
// 页面要能说清"实际拨号的地址",否则改错 ssh_config 也看不出来。
|
||||
func TestRunnerEndpointReadsDialedHostPort(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "ssh_config")
|
||||
config := "Host other\n HostName 10.0.0.9\n Port 2222\n\nHost weknora-test\n HostName 100.85.111.121\n HostKeyAlias 120.76.217.51\n"
|
||||
if err := os.WriteFile(path, []byte(config), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := New(Config{SSHConfig: path, Target: "weknora-test", ScriptDir: "/opt/weknora-test"})
|
||||
if got := runner.Endpoint(); got != "100.85.111.121:22" {
|
||||
t.Fatalf("应报真实拨号地址(默认 22),得到 %q", got)
|
||||
}
|
||||
if got := New(Config{SSHConfig: filepath.Join(t.TempDir(), "missing"), Target: "weknora-test"}).Endpoint(); got != "" {
|
||||
t.Fatalf("配置文件不可读时应返回空,不猜地址,得到 %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerRunNowReadsBackLastRun(t *testing.T) {
|
||||
calls := 0
|
||||
runner := testRunner(func(_ context.Context, _ time.Duration, remote string) (string, error) {
|
||||
|
||||
@@ -16,9 +16,8 @@ func developmentNotes(changelog, version, sha string) string {
|
||||
return ""
|
||||
}
|
||||
lines := strings.Split(changelog, "\n")
|
||||
prefix := "## 开发快照 snapshot/v" + version + " - "
|
||||
for i, line := range lines {
|
||||
if strings.HasPrefix(line, prefix) {
|
||||
if developmentHeadingMatches(line, version) {
|
||||
end := len(lines)
|
||||
for j := i + 1; j < len(lines); j++ {
|
||||
if strings.HasPrefix(lines[j], "## ") {
|
||||
@@ -39,3 +38,33 @@ func developmentNotes(changelog, version, sha string) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// developmentHeadingMatches 接受两种真实标题:
|
||||
// - 旧格式:## 开发快照 snapshot/v0.1.1 - 2026-10-18
|
||||
// - 开发快照:## 开发快照 0.1.351(索引预检使用目标映射 ID)
|
||||
//
|
||||
// 版本号后必须是字符串结束或分隔符,避免 0.1.35 命中 0.1.351;
|
||||
// 只读取到下一个二级标题,不跨版本吞正文。
|
||||
func developmentHeadingMatches(line, version string) bool {
|
||||
prefixes := []string{
|
||||
"## 开发快照 snapshot/v" + version,
|
||||
"## 开发快照 " + version,
|
||||
}
|
||||
for _, prefix := range prefixes {
|
||||
if !strings.HasPrefix(line, prefix) {
|
||||
continue
|
||||
}
|
||||
rest := line[len(prefix):]
|
||||
if rest == "" {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(rest, "—") || strings.HasPrefix(rest, "(") {
|
||||
return true
|
||||
}
|
||||
switch rest[0] {
|
||||
case ' ', '\t', '-', '(':
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package governance
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
func LibraryQueueRequest(handoff bool, jobID, scope, snapshotID, releaseType string) (string, string, []byte, error) {
|
||||
payload := map[string]string{"library_job_id": jobID, "scope": scope, "target_snapshot_id": snapshotID}
|
||||
queueID := QueueJobIDFor(jobID)
|
||||
queueType := releaseType
|
||||
if handoff {
|
||||
payload["next_type"] = releaseType
|
||||
queueID = LibraryHandoffQueueJobID(jobID)
|
||||
queueType = "library.snapshot.handoff"
|
||||
}
|
||||
raw, err := json.Marshal(payload)
|
||||
return queueID, queueType, raw, err
|
||||
}
|
||||
@@ -44,6 +44,10 @@ const (
|
||||
// 读出来封存成快照并逐类校验,再登记成 production_effective。
|
||||
// 它不写目标内容、不清空目标、不猜版本——基线只能来自真实捕获与校验。
|
||||
LibraryJobBaseline LibraryJobKind = "baseline"
|
||||
// LibraryJobVerify 是"恢复验证":在维护窗口内捕获目标 → 校验基线一致 →
|
||||
// 写一个 canary 证明校验能发现差异 → 按预备份恢复 → 复核完全一致。
|
||||
// 它是唯一能产生"生产可恢复"证据的作业,页面不再接受手填开关。
|
||||
LibraryJobVerify LibraryJobKind = "verify"
|
||||
)
|
||||
|
||||
type LibraryJobState string
|
||||
@@ -173,6 +177,12 @@ func BaselineStages() []string {
|
||||
return []string{"capture", "verify", "finalize"}
|
||||
}
|
||||
|
||||
// VerifyStages 是恢复验证的阶段:捕获 → 基线校验 → 写 canary(证明校验有效)
|
||||
// → 按预备份恢复 → 恢复后复核。canary 与 restore 都是真实写入,失败必须可见。
|
||||
func VerifyStages() []string {
|
||||
return []string{"capture", "verify", "canary", "restore", "finalize"}
|
||||
}
|
||||
|
||||
// LibraryReleaseAuthorization 是生产发布授权:绑定目标、快照、参数摘要与有效期。
|
||||
type LibraryReleaseAuthorization struct {
|
||||
ID string `json:"id"`
|
||||
|
||||
@@ -147,7 +147,7 @@ func ValidateLibraryOperation(op LibraryOperation) error {
|
||||
return errors.New("library operation requires internal or external scope")
|
||||
}
|
||||
switch op.Kind {
|
||||
case LibraryJobSeal, LibraryJobSync, LibraryJobRestore, LibraryJobBaseline, LibraryJobRecover:
|
||||
case LibraryJobSeal, LibraryJobSync, LibraryJobRestore, LibraryJobBaseline, LibraryJobRecover, LibraryJobVerify:
|
||||
default:
|
||||
return fmt.Errorf("unsupported library operation kind %q", op.Kind)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// The recovery request has its own queue identity and stable operation. It
|
||||
// borrows the original window's fence, never its immutable sending identity.
|
||||
func LibraryRecoveryQueueID(windowJob string) string {
|
||||
sum := sha256.Sum256([]byte(windowJob))
|
||||
return "lrec-" + hex.EncodeToString(sum[:14])
|
||||
}
|
||||
|
||||
func LibraryRecoveryDigest(scope, queue, window, operation, target, source, backup, plan string) (string, error) {
|
||||
return LibraryRequestDigest(scope, LibraryJobRecover, map[string]any{
|
||||
"recovery_queue": queue, "window_job": window, "original_operation": operation,
|
||||
"target_id": target, "source_snapshot": source, "backup_snapshot": backup, "writeset_digest": plan,
|
||||
})
|
||||
}
|
||||
|
||||
// LibraryDeliveryOwner 是队列投递 + 业务 attempt 的合成 owner:
|
||||
//
|
||||
// <worker>#<queue job>#<queue attempt>
|
||||
//
|
||||
// 它就是 library_attempts.owner,也决定了"这次派发属于哪一次真实投递"。worker 与
|
||||
// 派发台账必须用同一份格式,否则"当前 owner"会变成两处各自解释的字符串。
|
||||
func LibraryDeliveryOwner(workerID, queueID string, attempt int) string {
|
||||
if queueID == "" {
|
||||
queueID = "-"
|
||||
}
|
||||
if workerID == "" {
|
||||
workerID = "worker"
|
||||
}
|
||||
return fmt.Sprintf("%s#%s#%d", workerID, queueID, attempt)
|
||||
}
|
||||
|
||||
// ParseLibraryDeliveryOwner 把 owner 拆回 (worker, ok);queue/attempt 必须逐位相同,
|
||||
// 不能靠后缀匹配把别的投递混进来。
|
||||
func ParseLibraryDeliveryOwner(owner, queueID string, attempt int) (string, bool) {
|
||||
suffix := fmt.Sprintf("#%s#%d", queueID, attempt)
|
||||
if queueID == "" || !strings.HasSuffix(owner, suffix) {
|
||||
return "", false
|
||||
}
|
||||
worker := strings.TrimSuffix(owner, suffix)
|
||||
if worker == "" || strings.Contains(worker, "#") {
|
||||
return "", false
|
||||
}
|
||||
return worker, true
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// SourceIdentity binds an immutable capture to its configured origin, not to a
|
||||
// target or a page of mixed version history. It does not modify snapshot hashes.
|
||||
type LibrarySourceIdentity struct {
|
||||
Project string `json:"project"`
|
||||
App string `json:"app"`
|
||||
Scope string `json:"scope"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
}
|
||||
|
||||
func (s LibrarySourceIdentity) ID() (string, error) {
|
||||
if s.Project == "" || s.App == "" || (s.Scope != "internal" && s.Scope != "external") || s.TenantID == 0 || s.KnowledgeBaseID == "" {
|
||||
return "", errors.New("source project/app/scope/tenant/knowledge base binding incomplete")
|
||||
}
|
||||
raw, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
return hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LibraryRestoreVerification 是一次**真实**恢复验证(备份 → canary → 恢复 → 复核)的登记。
|
||||
//
|
||||
// 为什么不能继续用环境变量 PRODUCTION_BACKUP_RESTORE_VERIFIED:那是一个可以手填的开关,
|
||||
// 它既证明不了"有人真跑过恢复",也证明不了"跑的是当前目标"。这里的每条记录由 worker
|
||||
// 在真实演练结束后写入,绑定 target_id(实例+库+索引+桶)与 scope,失败也照实留痕。
|
||||
type LibraryRestoreVerification struct {
|
||||
ID string `json:"id"`
|
||||
Scope string `json:"scope"`
|
||||
Status string `json:"status"` // passed | failed
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
JobID string `json:"job_id"`
|
||||
Failure string `json:"failure,omitempty"`
|
||||
Report map[string]any `json:"report,omitempty"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FinishedAt time.Time `json:"finished_at"`
|
||||
}
|
||||
|
||||
const (
|
||||
LibraryVerificationPassed = "passed"
|
||||
LibraryVerificationFailed = "failed"
|
||||
)
|
||||
|
||||
// LibraryVerificationSatisfied 只回答一件事:这条证据能不能支撑"当前目标的恢复验证已通过"。
|
||||
// 通过的条件必须是全部成立——状态 passed、scope 相同、快照非空、完成时间有效。
|
||||
// target_id 的匹配由查询层(按当前 target_id 过滤)保证,这里不重复比较。
|
||||
func LibraryVerificationSatisfied(verification LibraryRestoreVerification, scope string) (bool, string) {
|
||||
if verification.Status != LibraryVerificationPassed {
|
||||
reason := "最近一次恢复验证没有通过"
|
||||
if detail := strings.TrimSpace(verification.Failure); detail != "" {
|
||||
reason += ":" + detail
|
||||
}
|
||||
return false, reason
|
||||
}
|
||||
if verification.Scope != scope {
|
||||
return false, "恢复验证证据属于另一个 scope(" + verification.Scope + ")"
|
||||
}
|
||||
if strings.TrimSpace(verification.SnapshotID) == "" {
|
||||
return false, "恢复验证证据没有绑定快照,不能作为备份可恢复的证明"
|
||||
}
|
||||
if verification.FinishedAt.IsZero() {
|
||||
return false, "恢复验证证据没有完成时间"
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 证据能不能支撑"当前目标可恢复"只由这四个条件回答:
|
||||
// 状态 passed、scope 相同、绑定了快照、有完成时间。少任何一条都不算。
|
||||
func TestLibraryVerificationSatisfied(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
cases := []struct {
|
||||
name string
|
||||
verification LibraryRestoreVerification
|
||||
scope string
|
||||
want bool
|
||||
reason string
|
||||
}{
|
||||
{name: "passed with snapshot", scope: "internal", want: true,
|
||||
verification: LibraryRestoreVerification{Status: LibraryVerificationPassed, Scope: "internal",
|
||||
SnapshotID: "snap-1", FinishedAt: now}},
|
||||
{name: "failed carries failure", scope: "internal", want: false, reason: "canary 后校验仍通过",
|
||||
verification: LibraryRestoreVerification{Status: LibraryVerificationFailed, Scope: "internal",
|
||||
SnapshotID: "snap-1", Failure: "canary 后校验仍通过", FinishedAt: now}},
|
||||
{name: "wrong scope", scope: "internal", want: false, reason: "另一个 scope",
|
||||
verification: LibraryRestoreVerification{Status: LibraryVerificationPassed, Scope: "external",
|
||||
SnapshotID: "snap-1", FinishedAt: now}},
|
||||
{name: "no snapshot", scope: "internal", want: false, reason: "没有绑定快照",
|
||||
verification: LibraryRestoreVerification{Status: LibraryVerificationPassed, Scope: "internal",
|
||||
FinishedAt: now}},
|
||||
{name: "no finish time", scope: "internal", want: false, reason: "没有完成时间",
|
||||
verification: LibraryRestoreVerification{Status: LibraryVerificationPassed, Scope: "internal",
|
||||
SnapshotID: "snap-1"}},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
ok, reason := LibraryVerificationSatisfied(testCase.verification, testCase.scope)
|
||||
if ok != testCase.want {
|
||||
t.Fatalf("satisfied=%v want=%v reason=%q", ok, testCase.want, reason)
|
||||
}
|
||||
if !testCase.want && testCase.reason != "" && !containsText(reason, testCase.reason) {
|
||||
t.Fatalf("reason=%q want contains %q", reason, testCase.reason)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func containsText(haystack, needle string) bool {
|
||||
return len(haystack) >= len(needle) && (haystack == needle || indexOf(haystack, needle) >= 0)
|
||||
}
|
||||
|
||||
func indexOf(haystack, needle string) int {
|
||||
for i := 0; i+len(needle) <= len(haystack); i++ {
|
||||
if haystack[i:i+len(needle)] == needle {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
@@ -36,8 +36,11 @@ type ServiceHealth struct {
|
||||
ObservedAt time.Time `json:"observed_at"`
|
||||
LastSuccessAt *time.Time `json:"last_success_at"`
|
||||
ConsecutiveFailures int `json:"consecutive_failures"`
|
||||
Configured bool `json:"configured"`
|
||||
Applicable bool `json:"applicable"`
|
||||
// ProbeTarget names the object being probed (instance + short binding id),
|
||||
// never credentials or full UUIDs, so a red light can be attributed.
|
||||
ProbeTarget string `json:"probe_target"`
|
||||
Configured bool `json:"configured"`
|
||||
Applicable bool `json:"applicable"`
|
||||
}
|
||||
|
||||
type KnowledgeBaseProgress struct {
|
||||
|
||||
@@ -116,6 +116,7 @@ type CatalogRouteRequest struct {
|
||||
// fulfillment path needs to materialize and fetch it later.
|
||||
type CatalogRouteFile struct {
|
||||
NodeID string
|
||||
ParentNodeID string
|
||||
Name string
|
||||
RelativePath string
|
||||
SizeBytes *int64
|
||||
|
||||
@@ -99,7 +99,7 @@ func isAuthEndpoint(method, path string) bool {
|
||||
|
||||
// classify maps a request to the minimum role required.
|
||||
func classifyRole(method, path string) string {
|
||||
if path == "/api/v1/source-connections/audit" {
|
||||
if path == "/api/v1/source-connections/audit" || path == "/api/v1/library/source-associations" {
|
||||
return roleAdmin
|
||||
}
|
||||
// The member roster exposes account identities and roles: admin-only for
|
||||
@@ -148,6 +148,11 @@ func classifyRole(method, path string) string {
|
||||
if strings.HasPrefix(path, "/api/v1/backup-schedule") && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// 核对封存结果会把一个 pending 业务作业修成 succeeded;只允许管理员,
|
||||
// 且 handler 仍要求 completed queue、精确版本和归档复核。
|
||||
if strings.HasPrefix(path, "/api/v1/library/jobs/") && strings.HasSuffix(path, "/reconcile-capture") {
|
||||
return roleAdmin
|
||||
}
|
||||
// 版本记录的同步会拉起一次对远端仓库的抓取(消耗网络与数据库写入),
|
||||
// 与"谁能改生产绑定"同级:读任何角色可看,同步只能管理员。
|
||||
if strings.HasPrefix(path, "/api/v1/version-history") && method != http.MethodGet {
|
||||
|
||||
@@ -24,6 +24,9 @@ type BackupScheduleStore interface {
|
||||
type BackupHost interface {
|
||||
Available() bool
|
||||
Target() string
|
||||
// Endpoint 是挂载的 ssh 配置里该别名真实拨号的 host:port;页面据此证明
|
||||
// "连的是哪条通道",而不是只显示一个别名。
|
||||
Endpoint() string
|
||||
Show(context.Context) (backuphost.ShowResult, error)
|
||||
Apply(context.Context, bool, string, int, int) (backuphost.ApplyResult, error)
|
||||
RunNow(context.Context) (backuphost.RunResult, error)
|
||||
@@ -82,8 +85,11 @@ type backupScheduleView struct {
|
||||
// HostConfigured/HostReachable 区分"没接线"与"接线了但连不上"。
|
||||
HostConfigured bool `json:"host_configured"`
|
||||
HostTarget string `json:"host_target"`
|
||||
HostReachable bool `json:"host_reachable"`
|
||||
HostError string `json:"host_error"`
|
||||
// HostEndpoint 是这条别名真实拨号的 host:port(来自挂载的 ssh 配置)。
|
||||
// 连接失败时它就是"到底往哪连"的唯一证据,不能只给一个别名让人猜。
|
||||
HostEndpoint string `json:"host_endpoint"`
|
||||
HostReachable bool `json:"host_reachable"`
|
||||
HostError string `json:"host_error"`
|
||||
|
||||
HostScheduleEnabled bool `json:"host_schedule_enabled"`
|
||||
HostScheduleTime string `json:"host_schedule_time"`
|
||||
@@ -92,6 +98,8 @@ type backupScheduleView struct {
|
||||
HostCronLines []string `json:"host_cron_lines"`
|
||||
HostCronService string `json:"host_cron_service"`
|
||||
HostScriptPresent bool `json:"host_script_present"`
|
||||
// HostCheckedAt 是本次真实主机探测时间;没有探测(只读库)时为空。
|
||||
HostCheckedAt string `json:"host_checked_at,omitempty"`
|
||||
|
||||
LastRunStamp string `json:"last_run_stamp"`
|
||||
LastRunCreatedAt string `json:"last_run_created_at"`
|
||||
@@ -281,6 +289,7 @@ func (config Config) backupSchedulePayload(ctx context.Context, probeHost bool)
|
||||
}
|
||||
view.HostConfigured = config.BackupHost.Available()
|
||||
view.HostTarget = config.BackupHost.Target()
|
||||
view.HostEndpoint = config.BackupHost.Endpoint()
|
||||
if !view.HostConfigured {
|
||||
view.InSync = false
|
||||
view.HostError = "目标主机凭据未挂载(BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET)"
|
||||
@@ -289,10 +298,14 @@ func (config Config) backupSchedulePayload(ctx context.Context, probeHost bool)
|
||||
if !probeHost {
|
||||
return view, nil
|
||||
}
|
||||
view.HostCheckedAt = formatTime(config.Now().UTC())
|
||||
show, err := config.BackupHost.Show(ctx)
|
||||
if err != nil {
|
||||
view.HostReachable = false
|
||||
view.HostError = err.Error()
|
||||
if view.HostEndpoint != "" {
|
||||
view.HostError += "(拨号地址 " + view.HostEndpoint + ")"
|
||||
}
|
||||
view.InSync = false
|
||||
} else {
|
||||
view.HostReachable = true
|
||||
|
||||
@@ -46,6 +46,7 @@ func (store *fakeBackupScheduleStore) MarkBackupScheduleApplied(_ context.Contex
|
||||
type fakeBackupHost struct {
|
||||
available bool
|
||||
target string
|
||||
endpoint string
|
||||
show backuphost.ShowResult
|
||||
showErr error
|
||||
apply backuphost.ApplyResult
|
||||
@@ -59,6 +60,9 @@ type fakeBackupHost struct {
|
||||
|
||||
func (host *fakeBackupHost) Available() bool { return host.available }
|
||||
func (host *fakeBackupHost) Target() string { return host.target }
|
||||
func (host *fakeBackupHost) Endpoint() string {
|
||||
return host.endpoint
|
||||
}
|
||||
func (host *fakeBackupHost) Show(context.Context) (backuphost.ShowResult, error) {
|
||||
return host.show, host.showErr
|
||||
}
|
||||
@@ -166,6 +170,48 @@ func TestHandleBackupScheduleHostFlagsDrift(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBackupScheduleHostUnreachableSeparatesConnectionFromHostState(t *testing.T) {
|
||||
// 现场原错:ssh connect to host 120.76.217.51 port 22 Operation timed out。
|
||||
// 连接没建立 ⇒ 既不能报"脚本缺失",也不能报"计划未下发",只能报不可达 + 拨号地址。
|
||||
host := &fakeBackupHost{
|
||||
available: true, target: "weknora-test", endpoint: "100.85.111.121:22",
|
||||
showErr: errors.New("目标主机 weknora-test 不可达(ssh: connect to host 120.76.217.51 port 22: Operation timed out);未执行任何主机侧脚本,脚本与计划状态未知"),
|
||||
}
|
||||
config := backupConfig(&fakeBackupScheduleStore{schedule: goldenSchedule}, host)
|
||||
recorder := httptest.NewRecorder()
|
||||
config.handleBackupScheduleHost(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/host", nil))
|
||||
data := decodeData(t, recorder)
|
||||
if data["host_reachable"] != false || data["in_sync"] != false {
|
||||
t.Fatalf("连不上时不能报告可达或已同步: %+v", data)
|
||||
}
|
||||
message := data["host_error"].(string)
|
||||
if !strings.Contains(message, "不可达") || !strings.Contains(message, "100.85.111.121:22") {
|
||||
t.Fatalf("应报不可达并给出真实拨号地址: %q", message)
|
||||
}
|
||||
if strings.Contains(message, "脚本缺失") || strings.Contains(message, "未下发") {
|
||||
t.Fatalf("未观测到的脚本/计划状态不能当成结论: %q", message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBackupScheduleHostReportsMissingScriptOnlyAfterConnecting(t *testing.T) {
|
||||
// 真正的脚本缺失:ssh 已连上,主机回的是脚本不存在 ⇒ 这时才允许说脚本缺失。
|
||||
host := &fakeBackupHost{
|
||||
available: true, target: "weknora-test", endpoint: "100.85.111.121:22",
|
||||
showErr: errors.New("已连上 weknora-test,但主机侧命令失败: bash: /opt/weknora-test/install_backup_schedule.sh: No such file or directory"),
|
||||
}
|
||||
config := backupConfig(&fakeBackupScheduleStore{schedule: goldenSchedule}, host)
|
||||
recorder := httptest.NewRecorder()
|
||||
config.handleBackupScheduleHost(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/host", nil))
|
||||
data := decodeData(t, recorder)
|
||||
message := data["host_error"].(string)
|
||||
if !strings.Contains(message, "已连上") || !strings.Contains(message, "No such file") {
|
||||
t.Fatalf("已连接但脚本缺失时应原样带回主机原因: %q", message)
|
||||
}
|
||||
if strings.Contains(message, "不可达") {
|
||||
t.Fatalf("已连上就不能说不可达: %q", message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBackupScheduleHostUnconfiguredDegrades(t *testing.T) {
|
||||
config := backupConfig(&fakeBackupScheduleStore{schedule: goldenSchedule}, &fakeBackupHost{available: false})
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
@@ -107,12 +106,12 @@ func libraryBaselineEnqueue(w http.ResponseWriter, r *http.Request, config Confi
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
|
||||
job, reused, err := store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{
|
||||
ID: fmt.Sprintf("libbase-%s-%d", request.Scope, now.UnixNano()), Scope: request.Scope,
|
||||
Kind: governance.LibraryJobBaseline,
|
||||
IdempotencyKey: "library.baseline:" + request.Scope + ":" + now.Format("20060102T150405.000000000"),
|
||||
RequestDigest: digest, Actor: identity.Username,
|
||||
}, governance.BaselineStages(), now)
|
||||
}, governance.BaselineStages(), false, now)
|
||||
if errors.Is(err, governance.ErrLibraryJobActive) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_write_active",
|
||||
"error": "该目标已有在飞的写作业(同步/恢复/基线互斥),等它结束再发起"})
|
||||
@@ -131,26 +130,6 @@ func libraryBaselineEnqueue(w http.ResponseWriter, r *http.Request, config Confi
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true})
|
||||
return
|
||||
}
|
||||
payload, err := json.Marshal(map[string]string{"library_job_id": job.ID, "scope": request.Scope})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build baseline payload"})
|
||||
return
|
||||
}
|
||||
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
|
||||
ID: governance.QueueJobIDFor(job.ID), Type: libraryBaselineJobType, Payload: payload,
|
||||
AvailableAt: now, MaxAttempts: 1, IdempotencyKey: "library.baseline.queue:" + job.ID,
|
||||
}, now)
|
||||
if err != nil || queueJob == nil {
|
||||
// 作业先落库、队列投递失败就把作业取消:不留下"看起来在跑"的空作业,
|
||||
// 否则它会一直占着该 scope 的写互斥。
|
||||
_ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始建立基线", now)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue baseline job"})
|
||||
return
|
||||
}
|
||||
if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach baseline job"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false,
|
||||
"target_counts": counts})
|
||||
}
|
||||
|
||||
@@ -45,6 +45,21 @@ func (s *baselineMutexStore) CreateLibraryJob(ctx context.Context, job governanc
|
||||
return s.fakeLibraryStore.CreateLibraryJob(ctx, job, stages, now)
|
||||
}
|
||||
|
||||
func (s *baselineMutexStore) CreateLibraryDispatch(ctx context.Context, job governance.LibraryJob, stages []string, handoff bool, now time.Time) (governance.LibraryJob, bool, error) {
|
||||
if s.activeByScope == nil {
|
||||
s.activeByScope = map[string]string{}
|
||||
}
|
||||
if s.activeByScope[job.Scope] != "" {
|
||||
return governance.LibraryJob{}, false, governance.ErrLibraryJobActive
|
||||
}
|
||||
created, reused, err := s.fakeLibraryStore.CreateLibraryDispatch(ctx, job, stages, handoff, now)
|
||||
if err == nil {
|
||||
s.activeByScope[job.Scope] = created.ID
|
||||
s.enqueues++
|
||||
}
|
||||
return created, reused, err
|
||||
}
|
||||
|
||||
func (s *baselineMutexStore) Enqueue(ctx context.Context, request jobs.EnqueueRequest, now time.Time) (*jobs.Job, error) {
|
||||
s.enqueues++
|
||||
return s.fakeLibraryStore.fakeJobStore.Enqueue(ctx, request, now)
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
// libraryCaptureReconciler is deliberately narrow: it repairs one business
|
||||
// seal job only after the completed capture queue, the successful export stage,
|
||||
// the exact test-sealed version and the archived bytes all agree. It never
|
||||
// captures, freezes writers, creates snapshots, writes source/target content or
|
||||
// changes historical failure evidence.
|
||||
type libraryCaptureReconciler interface {
|
||||
LibraryJob(ctx context.Context, id string) (governance.LibraryJob, error)
|
||||
LibraryCaptureExportEvidence(ctx context.Context, jobID string) (string, string, error)
|
||||
LibraryTestSealedVersionForJob(ctx context.Context, scope, jobID string) (governance.LibraryVersion, bool, error)
|
||||
EnsureLibraryOperation(ctx context.Context, op governance.LibraryOperation) (governance.LibraryOperation, bool, error)
|
||||
ReconcileLibraryCaptureTerminal(ctx context.Context, jobID, scope, queueJobID, snapshotID string, now time.Time) (bool, error)
|
||||
ReconcileMisclassifiedLibraryCapture(ctx context.Context, jobID, scope, queueJobID, snapshotID, expectedStage, expectedError, expectedRecovery string, expectedFinished *time.Time, auditID, actor, reason string, evidence map[string]any, now time.Time) (bool, error)
|
||||
}
|
||||
|
||||
const (
|
||||
legacyOrphanError = "队列中已无对应作业,业务作业未收到结果"
|
||||
legacyOrphanRecovery = "封存作业由 agent 恢复来源;确认来源 healthy 后可重发"
|
||||
)
|
||||
|
||||
type libraryCaptureQueueReader interface {
|
||||
QueueJob(ctx context.Context, id string) (jobs.Job, bool, error)
|
||||
}
|
||||
|
||||
func libraryCaptureReconcile(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
|
||||
return
|
||||
}
|
||||
store, ok := config.Store.(libraryCaptureReconciler)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
|
||||
"reason": "封存作业核对存储不可用"})
|
||||
return
|
||||
}
|
||||
queueStore, ok := config.Store.(libraryCaptureQueueReader)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
|
||||
"reason": "队列精确读取不可用"})
|
||||
return
|
||||
}
|
||||
jobID := strings.TrimSpace(r.PathValue("id"))
|
||||
if jobID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "job id required"})
|
||||
return
|
||||
}
|
||||
job, err := store.LibraryJob(r.Context(), jobID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusNotFound, map[string]any{"available": false, "reason": "作业不存在"})
|
||||
return
|
||||
}
|
||||
if job.Kind != governance.LibraryJobSeal {
|
||||
conflict(w, "只有封存作业可以核对封存结果")
|
||||
return
|
||||
}
|
||||
systemMisclassified := job.State == governance.LibraryJobFailed && job.Stage == "" &&
|
||||
job.Error == legacyOrphanError && job.Recovery == legacyOrphanRecovery && job.SnapshotID == ""
|
||||
if job.State != governance.LibraryJobPending && job.State != governance.LibraryJobRunning &&
|
||||
job.State != governance.LibraryJobSucceeded && !systemMisclassified {
|
||||
conflict(w, "作业是真实失败/取消终态,不能改写成成功")
|
||||
return
|
||||
}
|
||||
if job.QueueJobID == "" {
|
||||
conflict(w, "作业没有关联队列号,不能证明封存完成")
|
||||
return
|
||||
}
|
||||
captureJob := strings.TrimPrefix(job.ID, "libseal-")
|
||||
if captureJob == "" || captureJob == job.ID {
|
||||
conflict(w, "作业号不是封存作业身份")
|
||||
return
|
||||
}
|
||||
queue, found, err := queueStore.QueueJob(r.Context(), job.QueueJobID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read capture queue"})
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
conflict(w, "队列作业不存在,不能证明封存完成")
|
||||
return
|
||||
}
|
||||
if queue.Type != libraryCaptureJobType || queue.State != jobs.StateCompleted {
|
||||
conflict(w, "队列作业不是 completed 的 library.capture")
|
||||
return
|
||||
}
|
||||
var payload struct {
|
||||
Scope string `json:"scope"`
|
||||
CaptureJob string `json:"capture_job"`
|
||||
}
|
||||
if err := json.Unmarshal(queue.Payload, &payload); err != nil ||
|
||||
payload.Scope != job.Scope || payload.CaptureJob != captureJob ||
|
||||
queue.IdempotencyKey != "library.capture:"+captureJob {
|
||||
conflict(w, "队列作业的 scope/capture_job/幂等键与业务作业不一致")
|
||||
return
|
||||
}
|
||||
stageState, _, err := store.LibraryCaptureExportEvidence(r.Context(), job.ID)
|
||||
if err != nil || stageState != "succeeded" {
|
||||
conflict(w, "导出阶段没有成功证据,不能修复终态")
|
||||
return
|
||||
}
|
||||
version, found, err := store.LibraryTestSealedVersionForJob(r.Context(), job.Scope, job.ID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read exact test-sealed version"})
|
||||
return
|
||||
}
|
||||
if !found || version.Kind != governance.LibraryVersionTestSealed ||
|
||||
version.Scope != job.Scope || version.SourceJobID != job.ID || version.SnapshotID == "" {
|
||||
conflict(w, "没有与作业/scope 精确绑定的测试封存版本")
|
||||
return
|
||||
}
|
||||
source := configuredLibrarySource(config, job.Scope)
|
||||
sourceID, err := source.ID()
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
|
||||
"reason": "来源身份配置不完整,无法核对封存来源"})
|
||||
return
|
||||
}
|
||||
evidenceSource, _ := version.Evidence["source_id"].(string)
|
||||
evidenceCapture, _ := version.Evidence["capture_job"].(string)
|
||||
if evidenceSource != sourceID || evidenceCapture != captureJob {
|
||||
conflict(w, "版本来源或 capture_job 与当前作业不一致")
|
||||
return
|
||||
}
|
||||
if config.LibraryArchiveRoot == "" {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
|
||||
"reason": "未接线归档根,无法复核归档完整性"})
|
||||
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(version.SnapshotID)
|
||||
if err != nil {
|
||||
conflict(w, "归档字节复核失败,不能修复作业")
|
||||
return
|
||||
}
|
||||
if manifest.Scope != source.Scope || manifest.TenantID != source.TenantID ||
|
||||
manifest.KnowledgeBaseID != source.KnowledgeBaseID {
|
||||
conflict(w, "归档清单来源身份与当前来源不一致")
|
||||
return
|
||||
}
|
||||
if job.SnapshotID != "" && job.SnapshotID != version.SnapshotID {
|
||||
conflict(w, "作业已有不同快照,不能覆盖")
|
||||
return
|
||||
}
|
||||
if job.State == governance.LibraryJobSucceeded {
|
||||
if job.SnapshotID != version.SnapshotID {
|
||||
conflict(w, "作业已成功但快照与精确版本不一致")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"repaired": false, "already_succeeded": true, "job_id": job.ID,
|
||||
"snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
|
||||
"version_id": version.ID,
|
||||
})
|
||||
return
|
||||
}
|
||||
actor := ""
|
||||
if identity, ok := sessionFrom(r.Context()); ok {
|
||||
actor = identity.Username
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
digest, err := governance.LibraryRequestDigest(job.Scope, governance.LibraryJobRecover, map[string]any{
|
||||
"kind": "capture_reconcile", "job_id": job.ID, "queue_job_id": queue.ID,
|
||||
"snapshot_id": version.SnapshotID, "capture_job": captureJob, "stage": "export",
|
||||
})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build reconcile audit digest"})
|
||||
return
|
||||
}
|
||||
if systemMisclassified {
|
||||
auditID := "librepair-" + digest[:16]
|
||||
updated, repairErr := store.ReconcileMisclassifiedLibraryCapture(r.Context(), job.ID, job.Scope,
|
||||
job.QueueJobID, version.SnapshotID, job.Stage, legacyOrphanError, legacyOrphanRecovery,
|
||||
job.FinishedAt, auditID, actor, "completed capture queue + export succeeded + exact version + archive verified; legacy orphan misclassification", map[string]any{
|
||||
"original_state": job.State, "original_error": job.Error, "original_recovery": job.Recovery,
|
||||
"original_finished_at": job.FinishedAt, "queue_job_id": queue.ID,
|
||||
"snapshot_id": version.SnapshotID, "version_id": version.ID, "archive_verified": true,
|
||||
}, now)
|
||||
if repairErr != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot persist misclassification repair"})
|
||||
return
|
||||
}
|
||||
if !updated {
|
||||
conflict(w, "原误判行状态/错误/完成时间已变化,拒绝覆盖")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"repaired": true, "already_succeeded": false, "misclassification_repaired": true,
|
||||
"job_id": job.ID, "snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
|
||||
"stage": "export", "version_id": version.ID, "audit_repair_id": auditID,
|
||||
})
|
||||
return
|
||||
}
|
||||
opID := "libop-capture-reconcile-" + digest[:16]
|
||||
op, _, err := store.EnsureLibraryOperation(r.Context(), governance.LibraryOperation{
|
||||
ID: opID, Scope: job.Scope, Kind: governance.LibraryJobRecover,
|
||||
TargetSnapshotID: version.SnapshotID, RequestDigest: digest,
|
||||
OperationKey: "capture-reconcile:" + job.ID, Actor: actor, CreatedAt: now,
|
||||
})
|
||||
if errors.Is(err, governance.ErrLibraryOperationConflict) {
|
||||
conflict(w, "同一核对键对应了不同证据,拒绝修复")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot record reconcile audit"})
|
||||
return
|
||||
}
|
||||
updated, err := store.ReconcileLibraryCaptureTerminal(r.Context(), job.ID, job.Scope, job.QueueJobID, version.SnapshotID, now)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]any{
|
||||
"error": "cannot persist reconciled job terminal", "audit_operation_id": op.ID,
|
||||
})
|
||||
return
|
||||
}
|
||||
if !updated {
|
||||
conflict(w, "作业状态/身份在核对期间变化,拒绝覆盖")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"repaired": true, "already_succeeded": false, "job_id": job.ID,
|
||||
"snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
|
||||
"stage": "export", "version_id": version.ID, "audit_operation_id": op.ID,
|
||||
})
|
||||
}
|
||||
|
||||
func conflict(w http.ResponseWriter, reason string) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"available": false, "repaired": false, "reason": reason})
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
func (f *fakeLibraryStore) QueueJob(_ context.Context, id string) (jobs.Job, bool, error) {
|
||||
if f.queue == nil || f.queue.ID != id {
|
||||
return jobs.Job{}, false, nil
|
||||
}
|
||||
return *f.queue, true, nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) LibraryCaptureExportEvidence(_ context.Context, _ string) (string, string, error) {
|
||||
return f.stageState, "", f.stageErr
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) LibraryJobStage(_ context.Context, _, stage string) (string, string, error) {
|
||||
if f.stageErr != nil {
|
||||
return "", "", f.stageErr
|
||||
}
|
||||
if stage != "export" {
|
||||
return "", "", errors.New("unexpected stage")
|
||||
}
|
||||
return f.stageState, "", nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) LibraryTestSealedVersionForJob(_ context.Context, scope, jobID string) (governance.LibraryVersion, bool, error) {
|
||||
if f.versionErr != nil {
|
||||
return governance.LibraryVersion{}, false, f.versionErr
|
||||
}
|
||||
if f.sealedVersion == nil || f.sealedVersion.Scope != scope || f.sealedVersion.SourceJobID != jobID {
|
||||
return governance.LibraryVersion{}, false, nil
|
||||
}
|
||||
return *f.sealedVersion, true, nil
|
||||
}
|
||||
|
||||
func reconcileFixture(t *testing.T) (*fakeLibraryStore, Config, governance.LibraryJob, []byte) {
|
||||
t.Helper()
|
||||
root := libraryFixtureRoot(t)
|
||||
snapshotID := sealSharedVersions(t, root, 1, 4)[0]
|
||||
archive, err := librarysnapshot.Open(root, 256*1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest, err := archive.Load(snapshotID)
|
||||
archive.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config := Config{LibraryArchiveRoot: root,
|
||||
LibrarySourceProject: "fixture-project", LibrarySourceApp: "fixture-app",
|
||||
LibrarySourceTenantID: manifest.TenantID, LibrarySourceInternalKB: manifest.KnowledgeBaseID}
|
||||
source := configuredLibrarySource(config, "internal")
|
||||
sourceID, err := source.ID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job := governance.LibraryJob{ID: "libseal-cap-1", Scope: "internal", Kind: governance.LibraryJobSeal,
|
||||
State: governance.LibraryJobPending, QueueJobID: "libcap-1"}
|
||||
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "cap-1"})
|
||||
store := &fakeLibraryStore{
|
||||
jobs: []governance.LibraryJob{job},
|
||||
stageState: "succeeded",
|
||||
queue: &jobs.Job{ID: "libcap-1", Type: libraryCaptureJobType, State: jobs.StateCompleted,
|
||||
Payload: payload, IdempotencyKey: "library.capture:cap-1"},
|
||||
sealedVersion: &governance.LibraryVersion{ID: "libver-1", Scope: "internal",
|
||||
Kind: governance.LibraryVersionTestSealed, SnapshotID: snapshotID, SourceJobID: job.ID,
|
||||
Evidence: map[string]any{"source_id": sourceID, "capture_job": "cap-1"}},
|
||||
}
|
||||
config.Store = store
|
||||
return store, config, job, payload
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) ReconcileLibraryCaptureTerminal(_ context.Context, jobID, scope, queueJobID, snapshotID string, _ time.Time) (bool, error) {
|
||||
if f.reconcileDenied {
|
||||
return false, nil
|
||||
}
|
||||
for index := range f.jobs {
|
||||
if f.jobs[index].ID != jobID || f.jobs[index].Scope != scope || f.jobs[index].Kind != governance.LibraryJobSeal ||
|
||||
f.jobs[index].QueueJobID != queueJobID || (f.jobs[index].State != governance.LibraryJobPending && f.jobs[index].State != governance.LibraryJobRunning) ||
|
||||
(f.jobs[index].SnapshotID != "" && f.jobs[index].SnapshotID != snapshotID) {
|
||||
return false, nil
|
||||
}
|
||||
f.jobs[index].State = governance.LibraryJobSucceeded
|
||||
f.jobs[index].SnapshotID = snapshotID
|
||||
f.lastState = governance.LibraryJobSucceeded
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) ReconcileMisclassifiedLibraryCapture(_ context.Context, jobID, scope, queueJobID, snapshotID, expectedStage, expectedError, expectedRecovery string, expectedFinished *time.Time, _ string, _ string, _ string, _ map[string]any, _ time.Time) (bool, error) {
|
||||
if f.reconcileDenied {
|
||||
return false, nil
|
||||
}
|
||||
for index := range f.jobs {
|
||||
j := &f.jobs[index]
|
||||
if j.ID != jobID || j.Scope != scope || j.Kind != governance.LibraryJobSeal || j.QueueJobID != queueJobID ||
|
||||
j.State != governance.LibraryJobFailed || j.Stage != expectedStage || j.Error != expectedError ||
|
||||
j.Recovery != expectedRecovery || j.SnapshotID != "" || (j.FinishedAt == nil) != (expectedFinished == nil) ||
|
||||
(j.FinishedAt != nil && expectedFinished != nil && !j.FinishedAt.Equal(*expectedFinished)) {
|
||||
return false, nil
|
||||
}
|
||||
j.State = governance.LibraryJobSucceeded
|
||||
j.SnapshotID = snapshotID
|
||||
j.Stage = "export"
|
||||
f.lastState = governance.LibraryJobSucceeded
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
var _ libraryCaptureReconciler = (*fakeLibraryStore)(nil)
|
||||
|
||||
func runReconcile(t *testing.T, config Config, jobID string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/"+jobID+"/reconcile-capture", nil)
|
||||
req.SetPathValue("id", jobID)
|
||||
rec := httptest.NewRecorder()
|
||||
libraryCaptureReconcile(rec, req, config)
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRepairsExactCompletedCapture(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["repaired"] != true || body["snapshot_id"] == "" || body["audit_operation_id"] == "" {
|
||||
t.Fatalf("body=%v", body)
|
||||
}
|
||||
if store.lastState != governance.LibraryJobSucceeded {
|
||||
t.Fatalf("advanced state=%s", store.lastState)
|
||||
}
|
||||
if len(store.operations) != 1 {
|
||||
t.Fatalf("audit operations=%v", store.operations)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileAlreadySucceededIsReadOnly(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
job.State = governance.LibraryJobSucceeded
|
||||
job.SnapshotID = store.sealedVersion.SnapshotID
|
||||
store.jobs[0] = job
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &body)
|
||||
if body["already_succeeded"] != true || body["repaired"] != false || store.lastState != "" {
|
||||
t.Fatalf("body=%v advanced=%q", body, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsQueueNotCompleted(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.queue.State = jobs.StateRunning
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsStageNotSucceeded(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.stageState = "failed"
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsWrongVersionSource(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.sealedVersion.Evidence["source_id"] = "other-source"
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsWrongCaptureJob(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.sealedVersion.Evidence["capture_job"] = "other-capture"
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsBadArchive(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.sealedVersion.SnapshotID = "missing-snapshot"
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsFailedJob(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
job.State = governance.LibraryJobFailed
|
||||
store.jobs[0] = job
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileIsIdempotent(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
first := runReconcile(t, config, job.ID)
|
||||
if first.Code != http.StatusOK {
|
||||
t.Fatalf("first code=%d body=%s", first.Code, first.Body.String())
|
||||
}
|
||||
second := runReconcile(t, config, job.ID)
|
||||
if second.Code != http.StatusOK {
|
||||
t.Fatalf("second code=%d body=%s", second.Code, second.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(second.Body.Bytes(), &body)
|
||||
if body["already_succeeded"] != true || len(store.operations) != 1 {
|
||||
t.Fatalf("body=%v ops=%v", body, store.operations)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsMissingQueue(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.queue = nil
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsQueueScope(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.queue.Payload, _ = json.Marshal(map[string]string{"scope": "external", "capture_job": "cap-1"})
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsMissingVersion(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.sealedVersion = nil
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsWrongScopeVersion(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.sealedVersion.Scope = "external"
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsDifferentExistingSnapshot(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
job.SnapshotID = "other-snapshot"
|
||||
store.jobs[0] = job
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileConditionalWriteRejectsConcurrentState(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
store.reconcileDenied = true
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRepairsExactLegacyMisclassification(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
finished := time.Now().UTC()
|
||||
job.State = governance.LibraryJobFailed
|
||||
job.Stage = ""
|
||||
job.Error = legacyOrphanError
|
||||
job.Recovery = legacyOrphanRecovery
|
||||
job.FinishedAt = &finished
|
||||
store.jobs[0] = job
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &body)
|
||||
if body["misclassification_repaired"] != true || store.lastState != governance.LibraryJobSucceeded {
|
||||
t.Fatalf("body=%v advanced=%q", body, store.lastState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsOtherFailedError(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
finished := time.Now().UTC()
|
||||
job.State = governance.LibraryJobFailed
|
||||
job.Stage = ""
|
||||
job.Error = "capture export failed"
|
||||
job.Recovery = legacyOrphanRecovery
|
||||
job.FinishedAt = &finished
|
||||
store.jobs[0] = job
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileRejectsRealFailureAndCancel(t *testing.T) {
|
||||
for _, state := range []governance.LibraryJobState{governance.LibraryJobFailed, governance.LibraryJobCancelled} {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
job.State = state
|
||||
job.Error = "real failure"
|
||||
store.jobs[0] = job
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("state=%s code=%d advanced=%q", state, rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCaptureReconcileMisclassificationCASRejectsChange(t *testing.T) {
|
||||
store, config, job, _ := reconcileFixture(t)
|
||||
finished := time.Now().UTC()
|
||||
job.State = governance.LibraryJobFailed
|
||||
job.Stage = ""
|
||||
job.Error = legacyOrphanError
|
||||
job.Recovery = legacyOrphanRecovery
|
||||
job.FinishedAt = &finished
|
||||
store.jobs[0] = job
|
||||
store.reconcileDenied = true
|
||||
rec := runReconcile(t, config, job.ID)
|
||||
if rec.Code != http.StatusConflict || store.lastState != "" {
|
||||
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// Vertical PostgreSQL path: the real worker startup reconciliation must leave
|
||||
// a pending seal with a completed capture queue intact, then the actual HTTP
|
||||
// handler must verify archive/version/stage and repair it. This is not a fake
|
||||
// store or a direct helper test.
|
||||
func verticalReconcileFixture(t *testing.T) (*postgresstore.Store, Config, string, *pgxpool.Pool) {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database")
|
||||
}
|
||||
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")
|
||||
}
|
||||
cfg.MaxConns = 1
|
||||
cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp"
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
if _, err := pool.Exec(ctx, `
|
||||
CREATE TEMP TABLE library_jobs(
|
||||
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL,
|
||||
state varchar(16) NOT NULL, stage varchar(32) NOT NULL DEFAULT '',
|
||||
idempotency_key varchar(255) NOT NULL DEFAULT '', request_digest varchar(64) NOT NULL DEFAULT '',
|
||||
queue_job_id varchar(64) NOT NULL DEFAULT '', snapshot_id varchar(64) NOT NULL DEFAULT '',
|
||||
target_snapshot_id varchar(64) NOT NULL DEFAULT '', actor varchar(128) NOT NULL DEFAULT '',
|
||||
error text NOT NULL DEFAULT '', recovery varchar(255) NOT NULL DEFAULT '',
|
||||
operation_id varchar(64) NOT NULL DEFAULT '', attempt_epoch integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL, finished_at timestamptz,
|
||||
target_id text NOT NULL DEFAULT '');
|
||||
CREATE TEMP TABLE library_job_stages(
|
||||
job_id varchar(64) NOT NULL, stage varchar(32) NOT NULL, state varchar(16) NOT NULL,
|
||||
total bigint, completed bigint, bytes_total bigint, bytes_done bigint,
|
||||
detail text NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, PRIMARY KEY(job_id,stage));
|
||||
CREATE TEMP TABLE library_versions(
|
||||
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(24) NOT NULL,
|
||||
snapshot_id varchar(64) NOT NULL DEFAULT '', version_label varchar(64) NOT NULL DEFAULT '',
|
||||
source_job_id varchar(64) NOT NULL DEFAULT '', operation_id varchar(64) NOT NULL DEFAULT '',
|
||||
attempt_epoch integer NOT NULL DEFAULT 0, evidence jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_by varchar(128) NOT NULL DEFAULT '', created_at timestamptz NOT NULL, superseded_at timestamptz);
|
||||
CREATE TEMP TABLE library_job_repairs(
|
||||
id varchar(64) PRIMARY KEY, job_id varchar(64) NOT NULL, scope varchar(16) NOT NULL,
|
||||
kind varchar(16) NOT NULL, queue_job_id varchar(64) NOT NULL, snapshot_id varchar(64) NOT NULL,
|
||||
original_state varchar(16) NOT NULL, original_stage varchar(32) NOT NULL DEFAULT '',
|
||||
original_error text NOT NULL DEFAULT '', original_recovery varchar(255) NOT NULL DEFAULT '',
|
||||
original_finished_at timestamptz, reason varchar(255) NOT NULL, actor varchar(128) NOT NULL DEFAULT '',
|
||||
evidence jsonb NOT NULL DEFAULT '{}'::jsonb, created_at timestamptz NOT NULL);
|
||||
CREATE TEMP TABLE library_operations(
|
||||
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL,
|
||||
target_snapshot_id varchar(64) NOT NULL DEFAULT '', request_digest varchar(64) NOT NULL,
|
||||
operation_key varchar(255) NOT NULL, actor varchar(128) NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL, target_id text NOT NULL DEFAULT '',
|
||||
first_backup_snapshot_id varchar(64), first_backup_bytes bigint, first_backup_at timestamptz,
|
||||
writeset_digest varchar(64), writeset_rows bigint, target_fingerprint varchar(128), anchors_at timestamptz);
|
||||
CREATE UNIQUE INDEX library_operations_key_test ON library_operations(scope,kind,operation_key);
|
||||
CREATE TEMP TABLE jobs(
|
||||
id varchar(64) PRIMARY KEY, type varchar(64) NOT NULL, payload jsonb NOT NULL,
|
||||
state varchar(16) NOT NULL, priority integer NOT NULL DEFAULT 0, available_at timestamptz NOT NULL,
|
||||
lease_owner varchar(128), lease_until timestamptz, attempt integer NOT NULL DEFAULT 0,
|
||||
max_attempts integer NOT NULL DEFAULT 1, last_error text, idempotency_key varchar(255) NOT NULL,
|
||||
created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL);`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := libraryFixtureRoot(t)
|
||||
snapshotID := sealSharedVersions(t, root, 1, 4)[0]
|
||||
archive, err := librarysnapshot.Open(root, 256*1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest, err := archive.Load(snapshotID)
|
||||
archive.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config := Config{LibraryArchiveRoot: root,
|
||||
LibrarySourceProject: "fixture-project", LibrarySourceApp: "fixture-app",
|
||||
LibrarySourceTenantID: manifest.TenantID, LibrarySourceInternalKB: manifest.KnowledgeBaseID}
|
||||
source := configuredLibrarySource(config, "internal")
|
||||
sourceID, err := source.ID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "vertical"})
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,available_at,idempotency_key,created_at,updated_at)
|
||||
VALUES('q-vertical','library.capture',$1,'completed',$2,'library.capture:vertical',$2,$2)`, payload, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,evidence,created_at)
|
||||
VALUES('ver-vertical','internal','test_sealed',$1,'libseal-vertical',$2,$3)`, snapshotID,
|
||||
map[string]any{"source_id": sourceID, "capture_job": "vertical"}, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO library_job_stages(job_id,stage,state,detail,updated_at)
|
||||
VALUES('libseal-vertical','export','succeeded','已封存快照', $1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := postgresstore.NewStore(pool)
|
||||
config.Store = store
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,idempotency_key,request_digest,queue_job_id,created_at,updated_at)
|
||||
VALUES('libseal-vertical','internal','seal','pending','k','d','q-vertical',$1,$1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return store, config, snapshotID, pool
|
||||
}
|
||||
|
||||
func TestStartupReconcileThenHandlerRepairsPendingCapture(t *testing.T) {
|
||||
store, config, _, _ := verticalReconcileFixture(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
if n, err := store.ReconcileLibraryJobs(ctx, now, []string{"seal"}); err != nil || n != 0 {
|
||||
t.Fatalf("startup reconcile n=%d err=%v", n, err)
|
||||
}
|
||||
job, err := store.LibraryJob(ctx, "libseal-vertical")
|
||||
if err != nil || job.State != governance.LibraryJobPending {
|
||||
t.Fatalf("startup changed job: %+v err=%v", job, err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/libseal-vertical/reconcile-capture", nil)
|
||||
req.SetPathValue("id", "libseal-vertical")
|
||||
rec := httptest.NewRecorder()
|
||||
libraryCaptureReconcile(rec, req, config)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("handler code=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
job, err = store.LibraryJob(ctx, "libseal-vertical")
|
||||
if err != nil || job.State != governance.LibraryJobSucceeded || job.SnapshotID == "" {
|
||||
t.Fatalf("handler did not repair: %+v err=%v", job, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartupReconcilePreservesFailedCapturesForExactReconcile(t *testing.T) {
|
||||
store, config, snapshotID, pool := verticalReconcileFixture(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
source := configuredLibrarySource(config, "internal")
|
||||
sourceID, err := source.ID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "vertical-failed"})
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,available_at,idempotency_key,created_at,updated_at)
|
||||
VALUES('q-failed','library.capture',$1,'completed',$2,'library.capture:vertical-failed',$2,$2)`, payload, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,evidence,created_at)
|
||||
VALUES('ver-failed','internal','test_sealed',$1,'libseal-vertical-failed',$2,$3)`,
|
||||
snapshotID, map[string]any{"source_id": sourceID, "capture_job": "vertical-failed"}, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO library_job_stages(job_id,stage,state,detail,updated_at)
|
||||
VALUES('libseal-vertical-failed','export','succeeded','已封存快照', $1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
finished := now.Truncate(time.Microsecond)
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,idempotency_key,request_digest,queue_job_id,error,recovery,created_at,updated_at,finished_at)
|
||||
VALUES('libseal-vertical-failed','internal','seal','failed','kf','df','q-failed',$1,$2,$3,$3,$3)`,
|
||||
"队列中已无对应作业,业务作业未收到结果", "封存作业由 agent 恢复来源;确认来源 healthy 后可重发", finished); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, err := store.ReconcileLibraryJobs(ctx, now, []string{"seal"}); err != nil || n != 0 {
|
||||
t.Fatalf("startup reconcile n=%d err=%v", n, err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/libseal-vertical-failed/reconcile-capture", nil)
|
||||
req.SetPathValue("id", "libseal-vertical-failed")
|
||||
rec := httptest.NewRecorder()
|
||||
libraryCaptureReconcile(rec, req, config)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("handler code=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
job, err := store.LibraryJob(ctx, "libseal-vertical-failed")
|
||||
if err != nil || job.State != governance.LibraryJobSucceeded || job.SnapshotID != snapshotID {
|
||||
t.Fatalf("failed misclassification not repaired: %+v err=%v", job, err)
|
||||
}
|
||||
var originalState, originalError string
|
||||
if err := pool.QueryRow(ctx, `SELECT original_state, original_error FROM library_job_repairs WHERE job_id='libseal-vertical-failed'`).
|
||||
Scan(&originalState, &originalError); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if originalState != "failed" || originalError == "" {
|
||||
t.Fatalf("audit missing original: state=%q error=%q", originalState, originalError)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"time"
|
||||
)
|
||||
|
||||
// In-memory API fixture mirrors dispatch shape; atomicity is tested against PG.
|
||||
func (s *fakeLibraryStore) CreateLibraryDispatch(ctx context.Context, job governance.LibraryJob, stages []string, handoff bool, now time.Time) (governance.LibraryJob, bool, error) {
|
||||
created, reused, err := s.CreateLibraryJob(ctx, job, stages, now)
|
||||
if err != nil {
|
||||
return created, reused, err
|
||||
}
|
||||
if reused && (created.State != governance.LibraryJobPending || created.QueueJobID != "") {
|
||||
return created, reused, nil
|
||||
}
|
||||
id, kind, payload, err := governance.LibraryQueueRequest(handoff, created.ID, created.Scope, created.TargetSnapshotID, "library."+string(created.Kind))
|
||||
if err != nil {
|
||||
return created, reused, err
|
||||
}
|
||||
queued, err := s.Enqueue(ctx, jobs.EnqueueRequest{ID: id, Type: kind, Payload: payload, AvailableAt: now, MaxAttempts: 1, IdempotencyKey: kind + ".queue:" + created.ID}, now)
|
||||
if err != nil {
|
||||
s.lastJob = governance.LibraryJob{}
|
||||
return governance.LibraryJob{}, false, err
|
||||
}
|
||||
if err = s.AttachLibraryQueueJob(ctx, created.ID, queued.ID, now); err != nil {
|
||||
return created, reused, err
|
||||
}
|
||||
created.QueueJobID = queued.ID
|
||||
return created, reused, nil
|
||||
}
|
||||
@@ -2,12 +2,9 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -345,7 +342,11 @@ type libraryOverview struct {
|
||||
CaptureAvailable bool `json:"capture_available"`
|
||||
CaptureReason string `json:"capture_reason,omitempty"`
|
||||
Executor libraryExecutorView `json:"executor"`
|
||||
Now time.Time `json:"now"`
|
||||
// 实际目标身份:页面不能只显示"weknora-test"或旧文档级绑定名称。
|
||||
TargetInstance string `json:"target_instance,omitempty"`
|
||||
TargetProject string `json:"target_project,omitempty"`
|
||||
TargetKnowledgeBaseID string `json:"target_knowledge_base_id,omitempty"`
|
||||
Now time.Time `json:"now"`
|
||||
}
|
||||
|
||||
// libraryVersionRef 只回答"这个快照被登记成哪一类版本、由哪个作业登记"。
|
||||
@@ -360,6 +361,7 @@ type libraryVersionRef struct {
|
||||
}
|
||||
|
||||
type libraryJobStore interface {
|
||||
CreateLibraryDispatch(context.Context, governance.LibraryJob, []string, bool, time.Time) (governance.LibraryJob, bool, error)
|
||||
CreateLibraryJob(ctx context.Context, job governance.LibraryJob, stages []string, now time.Time) (governance.LibraryJob, bool, error)
|
||||
// EnsureLibraryOperation 幂等登记"一次明确意图":同键+同摘要 ⇒ 同一次意图(客户端重放),
|
||||
// 换键 ⇒ 新意图。作业是意图的执行代次,不能反过来用"历史成功作业"回答新意图(F01)。
|
||||
@@ -470,8 +472,7 @@ func libraryMaintenanceRecoverHandler(w http.ResponseWriter, r *http.Request, co
|
||||
}
|
||||
// 队列作业 id 与幂等键都按窗口固定:重复点击只会得到同一个恢复作业。
|
||||
// 队列 id 有长度上限(36),窗口作业 id 比它还长,所以按窗口摘要取短 id。
|
||||
sum := sha256.Sum256([]byte(held.OwnerJobID))
|
||||
queueID := "lrec-" + hex.EncodeToString(sum[:14])
|
||||
queueID := governance.LibraryRecoveryQueueID(held.OwnerJobID)
|
||||
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
|
||||
ID: queueID, Type: libraryRecoverJobType, Payload: payload,
|
||||
AvailableAt: now, MaxAttempts: 1, IdempotencyKey: "library.recover:" + held.OwnerJobID,
|
||||
@@ -598,6 +599,11 @@ func testSealedOf(versions []governance.LibraryVersion, byID map[string]libraryS
|
||||
// 它刻意只说配置:能停写入者/关入口/证明排空的真实能力在 worker 侧(docker socket、
|
||||
// 闸门、排空文件),API 若声称"能力可用"就是拿配置字符串冒充执行证据。
|
||||
func libraryMaintenanceCapability(config Config) map[string]any {
|
||||
mode := strings.TrimSpace(config.LibraryTargetIngressMode)
|
||||
if mode == "" {
|
||||
mode = "gate"
|
||||
}
|
||||
noGate := mode == "none"
|
||||
missing := make([]string, 0, 6)
|
||||
if config.LibraryTargetInstance == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INSTANCE")
|
||||
@@ -608,11 +614,18 @@ func libraryMaintenanceCapability(config Config) map[string]any {
|
||||
if len(config.LibraryTargetWriters) == 0 {
|
||||
missing = append(missing, "LIBRARY_TARGET_WRITERS")
|
||||
}
|
||||
if config.LibraryTargetIngressURL == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
|
||||
}
|
||||
if config.LibraryTargetIngressService == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
|
||||
if noGate {
|
||||
// 没有闸门:页面必须如实说"无闸门(测试模式)",不能显示"打开"。
|
||||
if config.LibraryTargetHealthURL == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_HEALTH_URL")
|
||||
}
|
||||
} else {
|
||||
if config.LibraryTargetIngressURL == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
|
||||
}
|
||||
if config.LibraryTargetIngressService == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
|
||||
}
|
||||
}
|
||||
if config.LibraryTargetJournalRoot == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_JOURNAL_ROOT")
|
||||
@@ -620,12 +633,18 @@ func libraryMaintenanceCapability(config Config) map[string]any {
|
||||
if config.LibraryTargetDockerSocket == "" {
|
||||
missing = append(missing, "LIBRARY_TARGET_DOCKER_SOCKET")
|
||||
}
|
||||
ingressState := "闸门"
|
||||
if noGate {
|
||||
ingressState = "无闸门(测试模式)"
|
||||
}
|
||||
return map[string]any{
|
||||
"configured": len(missing) == 0,
|
||||
"missing": missing,
|
||||
"instance": config.LibraryTargetInstance,
|
||||
"project": config.LibraryTargetProject,
|
||||
"writers": config.LibraryTargetWriters,
|
||||
"ingress_mode": mode,
|
||||
"ingress_state": ingressState,
|
||||
"ingress_service": config.LibraryTargetIngressService,
|
||||
"note": "配置齐全只说明治理侧接线完整;停写入者、关入口与排空由 worker 在作业内校验并执行",
|
||||
}
|
||||
@@ -645,9 +664,7 @@ func librarySyncGateWithGrant(config Config, production libraryKnownView, prebac
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
gate.Reasons = append(gate.Reasons, "生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false)")
|
||||
}
|
||||
if !config.ProductionBackupRestoreVerified {
|
||||
gate.Reasons = append(gate.Reasons, "没有已核验的生产恢复演练证据(PRODUCTION_BACKUP_RESTORE_VERIFIED=false)")
|
||||
}
|
||||
gate.Reasons = append(gate.Reasons, restoreGateReasons(config)...)
|
||||
// 生产端点以"整库目标是否配置"为准:整库同步直接写 PG/ES/对象,
|
||||
// 不依赖 WeKnora 的 HTTP 端,所以不能拿它是否配置当门禁。
|
||||
if strings.TrimSpace(config.LibraryProductionDatabaseURL) == "" {
|
||||
@@ -691,10 +708,16 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
overview := libraryOverview{Scope: scope, Jobs: []governance.LibraryJob{}, Now: now,
|
||||
TargetInstance: config.LibraryTargetInstance, TargetProject: config.LibraryTargetProject,
|
||||
Gate: libraryGateView{Reasons: []string{}},
|
||||
Diff: libraryDiffView{State: "unknown", Reason: "生产与测试的文档级差异读取未接线", Added: []any{}, Updated: []any{}, Removed: []any{}}}
|
||||
// 可发起封存 = worker 真实探测到执行器可用且指向本实例;原因逐条给全。
|
||||
overview.CaptureAvailable, overview.CaptureReason, overview.Executor = libraryExecutorAvailability(r.Context(), config)
|
||||
if scope == "internal" {
|
||||
overview.TargetKnowledgeBaseID = config.LibraryProductionInternalKB
|
||||
} else {
|
||||
overview.TargetKnowledgeBaseID = config.LibraryProductionExternalKB
|
||||
}
|
||||
|
||||
// 测试封存来自归档 + 版本登记:归档里**不止**测试封存——生产预备份与目标基线
|
||||
// 快照同样带 scope,如果只按"这个 scope 最新一份"挑,页面就会把目标自己的内容
|
||||
@@ -727,7 +750,11 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
|
||||
return
|
||||
}
|
||||
if archiveReadable {
|
||||
overview.TestSealed, overview.TestSealedReason = testSealedOf(versions, byID)
|
||||
var candidateErr error
|
||||
overview.TestSealed, candidateErr = currentSourceCandidate(r.Context(), config, scope)
|
||||
if candidateErr != nil {
|
||||
overview.TestSealedReason = candidateErr.Error()
|
||||
}
|
||||
}
|
||||
overview.Production = libraryKnownView{State: "unknown", Reason: "还没有生产验证通过的生效版本记录"}
|
||||
overview.Prebackup = libraryKnownView{State: "unknown", Reason: "这个范围还没有任何生产预备份"}
|
||||
@@ -813,7 +840,8 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
|
||||
|
||||
grant, hasGrant := activeGrantFor(r.Context(), config, scope, target)
|
||||
overview.Authorization = authorizationViewOf(grant, hasGrant)
|
||||
overview.Gate = librarySyncGateWithGrant(config, overview.Production, overview.Prebackup, target, hasGrant)
|
||||
// 闸口按当前目标的真实恢复证据判断(没有证据时也接受历史 env 覆盖)。
|
||||
overview.Gate = librarySyncGateWithGrant(config.withRestoreEvidence(r.Context(), scope), overview.Production, overview.Prebackup, target, hasGrant)
|
||||
writeJSON(w, http.StatusOK, overview)
|
||||
}
|
||||
|
||||
@@ -852,7 +880,38 @@ func libraryJobDetailHandler(w http.ResponseWriter, r *http.Request, config Conf
|
||||
writeJSON(w, http.StatusNotFound, map[string]any{"available": false, "reason": "作业不存在"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"available": true, "job": job})
|
||||
detail := map[string]any{"available": true, "job": job}
|
||||
// 只读诊断:明确"目标现在被谁按着、入口是什么状态、下一步该怎么做"。
|
||||
// 这里刻意不提供任何"强制成功/强制开门"的入口:缺归属证据的作业必须停在
|
||||
// held,由人工按预备份与校验证据处置(已接受的可用性边界)。
|
||||
if maintenanceStore, ok := config.Store.(interface {
|
||||
LibraryMaintenanceOf(ctx context.Context, scope string) (*postgresstore.LibraryMaintenance, error)
|
||||
}); ok {
|
||||
maintenance, maintenanceErr := maintenanceStore.LibraryMaintenanceOf(r.Context(), job.Scope)
|
||||
if maintenanceErr != nil || maintenance == nil {
|
||||
writeJSON(w, http.StatusOK, detail)
|
||||
return
|
||||
}
|
||||
held := maintenance.ReleasedAt == nil
|
||||
detail["maintenance"] = map[string]any{
|
||||
"held": held,
|
||||
"owner_job_id": maintenance.OwnerJobID,
|
||||
"owner_is_job": maintenance.OwnerJobID == job.ID,
|
||||
"state": maintenance.State,
|
||||
"ingress": maintenance.IngressState,
|
||||
"target_identity": maintenance.TargetIdentity,
|
||||
"note": maintenance.Note,
|
||||
"acquired_at": maintenance.AcquiredAt,
|
||||
"released": !held,
|
||||
}
|
||||
if held && job.State == governance.LibraryJobFailed {
|
||||
detail["next_step"] = "内容可能已写入并通过校验,但收尾未完成:目标仍处于维护、入口未开。按本作业的预备份与校验证据人工核验后再放行;本接口不提供强制成功。"
|
||||
}
|
||||
}
|
||||
if _, ok := detail["next_step"]; !ok && job.State == governance.LibraryJobFailed && job.Recovery != "" {
|
||||
detail["next_step"] = job.Recovery
|
||||
}
|
||||
writeJSON(w, http.StatusOK, detail)
|
||||
}
|
||||
|
||||
// librarySyncEnqueue 是生产同步的唯一入口:闸口未齐时**不建作业**,直接说明缺项。
|
||||
@@ -873,6 +932,7 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
// OperationKey 是客户端重放键:同一次意图重发要命中同一个 operation。
|
||||
// 不传就是一次新意图(同一个快照再发布一次也必须真的执行)。
|
||||
OperationKey string `json:"operation_key"`
|
||||
SourceID string `json:"source_id"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&request); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
|
||||
@@ -930,7 +990,7 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
}
|
||||
gate := librarySyncGateWithGrant(config, overview.Production, overview.Prebackup, request.Target, hasGrant)
|
||||
gate := librarySyncGateWithGrant(config.withRestoreEvidence(r.Context(), request.Scope), overview.Production, overview.Prebackup, request.Target, hasGrant)
|
||||
if !gate.SyncAllowed {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
|
||||
"code": "library_sync_blocked", "reasons": gate.Reasons,
|
||||
@@ -939,6 +999,11 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
|
||||
candidate, candidateErr := currentSourceCandidate(r.Context(), config, request.Scope)
|
||||
if candidateErr != nil || request.SourceID == "" || candidate == nil || candidate.SourceID != request.SourceID || candidate.SnapshotID != request.Target {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_source_candidate_changed", "error": "来源候选已变化或身份未绑定,请刷新后重试", "detail": errString(candidateErr)})
|
||||
return
|
||||
}
|
||||
// 走到这里说明闸口与证据都齐了才真正建作业;互斥与幂等由数据库索引保证。
|
||||
digest, err := governance.LibraryRequestDigest(request.Scope, governance.LibraryJobSync,
|
||||
map[string]any{"target_snapshot_id": request.Target})
|
||||
@@ -965,11 +1030,11 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot register library intent"})
|
||||
return
|
||||
}
|
||||
job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
|
||||
job, reused, err := store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{
|
||||
ID: jobID, Scope: request.Scope, Kind: governance.LibraryJobSync,
|
||||
IdempotencyKey: intent.JobKey, RequestDigest: digest, OperationID: intent.Operation.ID,
|
||||
TargetSnapshotID: request.Target, Actor: actor,
|
||||
}, governance.SyncStages(), now)
|
||||
}, governance.SyncStages(), config.LibraryHandoffEnabled, now)
|
||||
if errors.Is(err, governance.ErrLibraryJobActive) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_active",
|
||||
"error": "该目标已有在飞的生产写作业(同步与恢复互斥)"})
|
||||
@@ -986,13 +1051,13 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
// 上一次同意图请求失败/被取消后,幂等键不能再把新请求塞回那个死作业里:
|
||||
// 在**同一个 operation** 下开一个新的执行作业(重试代次),旧作业保留为审计记录。
|
||||
if reused && (job.State == governance.LibraryJobFailed || job.State == governance.LibraryJobCancelled) {
|
||||
job, reused, err = store.CreateLibraryJob(r.Context(), governance.LibraryJob{
|
||||
job, reused, err = store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{
|
||||
ID: fmt.Sprintf("libsync-%s-%d", request.Scope, time.Now().UTC().UnixNano()), Scope: request.Scope,
|
||||
Kind: governance.LibraryJobSync,
|
||||
IdempotencyKey: intent.JobKey + ":retry:" + now.Format("20060102T150405.000000000"),
|
||||
RequestDigest: digest, OperationID: intent.Operation.ID,
|
||||
TargetSnapshotID: request.Target, Actor: actor,
|
||||
}, governance.SyncStages(), now)
|
||||
}, governance.SyncStages(), config.LibraryHandoffEnabled, now)
|
||||
if err != nil || reused {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_retry_conflict",
|
||||
"error": "无法为重试创建新作业", "detail": errString(err)})
|
||||
@@ -1003,27 +1068,6 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true})
|
||||
return
|
||||
}
|
||||
// 业务作业先落库,再投递队列:投递失败就把作业标失败,不留下"看起来在跑"的空作业。
|
||||
queueID, queueType, payload, err := libraryQueueRequest(config.LibraryHandoffEnabled, job.ID,
|
||||
request.Scope, request.Target, librarySyncJobType)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build sync payload"})
|
||||
return
|
||||
}
|
||||
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
|
||||
ID: queueID, Type: queueType, Payload: payload, AvailableAt: now,
|
||||
MaxAttempts: 1, IdempotencyKey: queueType + ".queue:" + job.ID,
|
||||
}, now)
|
||||
if err != nil || queueJob == nil {
|
||||
log.Printf("library sync enqueue failed job=%s: %v", job.ID, err)
|
||||
_ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始同步", now)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue sync job"})
|
||||
return
|
||||
}
|
||||
if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach sync job"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false})
|
||||
}
|
||||
|
||||
@@ -1033,17 +1077,5 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
// 由它在成功后再入 releaseType;搬运未接线时保持原样。两种情况下 releaseType
|
||||
// 作业的 ID 都是 QueueJobIDFor(jobID),所以接管/续作的既有路径不受影响。
|
||||
func libraryQueueRequest(handoff bool, jobID, scope, snapshotID, releaseType string) (string, string, []byte, error) {
|
||||
payload := map[string]string{"library_job_id": jobID, "scope": scope, "target_snapshot_id": snapshotID}
|
||||
queueID := governance.QueueJobIDFor(jobID)
|
||||
queueType := releaseType
|
||||
if handoff {
|
||||
payload["next_type"] = releaseType
|
||||
queueID = governance.LibraryHandoffQueueJobID(jobID)
|
||||
queueType = libraryHandoffJobType
|
||||
}
|
||||
raw, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", "", nil, err
|
||||
}
|
||||
return queueID, queueType, raw, nil
|
||||
return governance.LibraryQueueRequest(handoff, jobID, scope, snapshotID, releaseType)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
)
|
||||
|
||||
// 生产闸口与整库状态契约的针对性测试:不做数据库集成,只验证
|
||||
@@ -18,6 +19,7 @@ import (
|
||||
|
||||
// 复用既有 fakeJobStore 提供 Store 的其余方法,只覆盖整库作业这几个。
|
||||
type fakeLibraryStore struct {
|
||||
sourceCandidate *governance.LibraryVersion
|
||||
fakeJobStore
|
||||
grant *governance.LibraryReleaseAuthorization
|
||||
versions []governance.LibraryVersion
|
||||
@@ -32,6 +34,17 @@ type fakeLibraryStore struct {
|
||||
// operations/lastOperation 记录"意图身份":重放与换键的差别在这里表达(F01)。
|
||||
operations map[string]governance.LibraryOperation
|
||||
lastOperation governance.LibraryOperation
|
||||
// 续作:resumeOK/resumeErr 驱动存储层结果,resumeCalls 记录每次调用(断言不重复投递)。
|
||||
resumeOK bool
|
||||
resumeErr error
|
||||
resumeCalls []string
|
||||
// capture reconciliation fixtures
|
||||
queue *jobs.Job
|
||||
stageState string
|
||||
stageErr error
|
||||
sealedVersion *governance.LibraryVersion
|
||||
versionErr error
|
||||
reconcileDenied bool
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) CreateLibraryJob(_ context.Context, job governance.LibraryJob, _ []string, _ time.Time) (governance.LibraryJob, bool, error) {
|
||||
@@ -58,6 +71,11 @@ func (f *fakeLibraryStore) EnsureLibraryOperation(_ context.Context, op governan
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) LibraryJob(_ context.Context, id string) (governance.LibraryJob, error) {
|
||||
for _, job := range f.jobs {
|
||||
if job.ID == id {
|
||||
return job, nil
|
||||
}
|
||||
}
|
||||
return governance.LibraryJob{ID: id}, nil
|
||||
}
|
||||
|
||||
@@ -117,8 +135,16 @@ func (f *fakeLibraryStore) UpdateLibraryStage(_ context.Context, _, _, _ string,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, _ string, state governance.LibraryJobState, _, _, _, _, _ string, _ time.Time) error {
|
||||
func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, jobID string, state governance.LibraryJobState, _, _, _, snapshotID, _ string, _ time.Time) error {
|
||||
f.lastState = state
|
||||
for index := range f.jobs {
|
||||
if f.jobs[index].ID == jobID {
|
||||
f.jobs[index].State = state
|
||||
if snapshotID != "" {
|
||||
f.jobs[index].SnapshotID = snapshotID
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -177,6 +203,23 @@ func (f *fakeLibraryStore) ResetQueueJobForResume(_ context.Context, _ string, _
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResumeLibraryJob 模拟存储层事务语义:结果由 resumeResult 驱动,调用次数可断言"重复请求不重复投递"。
|
||||
func (f *fakeLibraryStore) ResumeLibraryJob(_ context.Context, jobID, queueType string, _ time.Time) (governance.LibraryJob, bool, error) {
|
||||
f.resumeCalls = append(f.resumeCalls, jobID+"/"+queueType)
|
||||
if f.resumeErr != nil {
|
||||
return governance.LibraryJob{}, false, f.resumeErr
|
||||
}
|
||||
if !f.resumeOK {
|
||||
return governance.LibraryJob{}, false, nil
|
||||
}
|
||||
for _, job := range f.jobs {
|
||||
if job.ID == jobID {
|
||||
return job, true, nil
|
||||
}
|
||||
}
|
||||
return governance.LibraryJob{}, false, nil
|
||||
}
|
||||
|
||||
func TestLibrarySyncGateRequiresEveryPieceOfEvidence(t *testing.T) {
|
||||
known := libraryKnownView{State: "known", Version: &libraryVersionView{ID: "v1"}}
|
||||
cases := []struct {
|
||||
@@ -345,8 +388,11 @@ func TestLibrarySyncEnqueueCreatesJobOnlyWithGrant(t *testing.T) {
|
||||
store.enqueueEchoRequestedID = true
|
||||
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
|
||||
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int", LibraryCapacityBudgetBytes: 1 << 40}
|
||||
sourceID := bindSourceFixture(t, &config, store, &target)
|
||||
digest, _ = librarySyncParamsDigest("internal", target)
|
||||
body := `{"scope":"internal","target_snapshot_id":"` + target + `"}`
|
||||
|
||||
body = sourceRequestBody(t, body, sourceID)
|
||||
// 先没有授权
|
||||
recorder := httptest.NewRecorder()
|
||||
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
|
||||
@@ -393,6 +439,7 @@ func TestLibraryOverviewShowsLatestPrebackupWhenTargetDiffers(t *testing.T) {
|
||||
SnapshotID: sealed, CreatedAt: now.Add(-2 * time.Hour)},
|
||||
}}
|
||||
config := Config{Store: store, LibraryArchiveRoot: root, LibraryCapacityBudgetBytes: 1 << 30}
|
||||
bindSourceFixture(t, &config, store, &sealed)
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/overview?scope=internal", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryOverviewHandler(recorder, request, config)
|
||||
@@ -510,7 +557,10 @@ func TestLibrarySyncEnqueueUsesExactCurrentVersionBeyondWindow(t *testing.T) {
|
||||
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
|
||||
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
|
||||
LibraryCapacityBudgetBytes: 1 << 40}
|
||||
sourceID := bindSourceFixture(t, &config, store, &target)
|
||||
digest, _ = librarySyncParamsDigest("internal", target)
|
||||
body := `{"scope":"internal","target_snapshot_id":"` + target + `"}`
|
||||
body = sourceRequestBody(t, body, sourceID)
|
||||
recorder := httptest.NewRecorder()
|
||||
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
|
||||
if recorder.Code != http.StatusAccepted {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
type r13HeldDetailStore struct {
|
||||
fakeLibraryStore
|
||||
maintenance *postgresstore.LibraryMaintenance
|
||||
job governance.LibraryJob
|
||||
}
|
||||
|
||||
func (s *r13HeldDetailStore) LibraryJob(_ context.Context, id string) (governance.LibraryJob, error) {
|
||||
job := s.job
|
||||
job.ID = id
|
||||
return job, nil
|
||||
}
|
||||
|
||||
func (s *r13HeldDetailStore) LibraryMaintenanceOf(context.Context, string) (*postgresstore.LibraryMaintenance, error) {
|
||||
return s.maintenance, nil
|
||||
}
|
||||
|
||||
// 已接受的边界:缺归属证据的作业停在 held,页面/接口必须给出可核对的 job/operation/目标
|
||||
// 与阻断原因,并且**不能**提供"强制成功/强制开门"的动作。
|
||||
func TestR13HeldJobDetailExplainsManualRecovery(t *testing.T) {
|
||||
store := &r13HeldDetailStore{maintenance: &postgresstore.LibraryMaintenance{
|
||||
Scope: "internal", OwnerJobID: "job-held", State: "needs_restore",
|
||||
IngressState: "open", TargetIdentity: "scope=internal", Note: "内容已验证,但收尾未完成",
|
||||
Services: []string{"app"},
|
||||
}}
|
||||
store.job = governance.LibraryJob{
|
||||
Scope: "internal", Kind: governance.LibraryJobSync, State: governance.LibraryJobFailed,
|
||||
Stage: "finalize", OperationID: "op-r13", AttemptEpoch: 2,
|
||||
SnapshotID: "backup-r13", TargetSnapshotID: "target-r13",
|
||||
Error: "内容已验证,但收尾未完成", Recovery: "预备份保留;按归档人工核验",
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/jobs/job-held", nil)
|
||||
request.SetPathValue("id", "job-held")
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryJobDetailHandler(recorder, request, Config{Store: store})
|
||||
if recorder.Code != http.StatusOK {
|
||||
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)
|
||||
}
|
||||
job, _ := body["job"].(map[string]any)
|
||||
if job["operation_id"] != "op-r13" || job["attempt_epoch"] != float64(2) ||
|
||||
job["snapshot_id"] != "backup-r13" || job["target_snapshot_id"] != "target-r13" {
|
||||
t.Fatalf("作业身份/证据不完整:%v", job)
|
||||
}
|
||||
maintenance, _ := body["maintenance"].(map[string]any)
|
||||
if maintenance["held"] != true || maintenance["owner_is_job"] != true || maintenance["state"] != "needs_restore" {
|
||||
t.Fatalf("维护状态没有暴露:%v", maintenance)
|
||||
}
|
||||
step, _ := body["next_step"].(string)
|
||||
if !strings.Contains(step, "维护") || !strings.Contains(step, "人工") {
|
||||
t.Fatalf("下一步没有指向人工核验:%q", step)
|
||||
}
|
||||
raw := strings.ToLower(recorder.Body.String())
|
||||
for _, banned := range []string{"force_success", "force-open", "force_open", "ignore_unknown", "skip_verify"} {
|
||||
if strings.Contains(raw, banned) {
|
||||
t.Fatalf("诊断接口出现了强制动作:%s", banned)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,8 @@ import (
|
||||
// 判据:换 operation_key ⇒ 新 operation(ID 不同、作业幂等键不同);
|
||||
// 同一个 operation_key ⇒ 同一 operation(重放)。
|
||||
func TestLibrarySyncNewIntentReExecutesInsteadOfReusingHistory(t *testing.T) {
|
||||
target := "snap-1"
|
||||
root := libraryFixtureRoot(t)
|
||||
target := sealSharedVersions(t, root, 1, 4)[0]
|
||||
digest, err := librarySyncParamsDigest("internal", target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -36,14 +37,19 @@ func TestLibrarySyncNewIntentReExecutesInsteadOfReusingHistory(t *testing.T) {
|
||||
return store
|
||||
}
|
||||
config := func(store *fakeLibraryStore) Config {
|
||||
return Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
|
||||
c := Config{Store: store, LibraryArchiveRoot: root, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
|
||||
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
|
||||
LibraryCapacityBudgetBytes: 1 << 40}
|
||||
bindSourceFixture(t, &c, store, &target)
|
||||
return c
|
||||
}
|
||||
post := func(store *fakeLibraryStore, body string) *httptest.ResponseRecorder {
|
||||
c := config(store)
|
||||
id, _ := configuredLibrarySource(c, "internal").ID()
|
||||
body = sourceRequestBody(t, body, id)
|
||||
recorder := httptest.NewRecorder()
|
||||
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs",
|
||||
strings.NewReader(body)), config(store))
|
||||
strings.NewReader(body)), c)
|
||||
return recorder
|
||||
}
|
||||
withKey := `{"scope":"internal","target_snapshot_id":"` + target + `","operation_key":"%s"}`
|
||||
@@ -85,7 +91,8 @@ func TestLibrarySyncNewIntentReExecutesInsteadOfReusingHistory(t *testing.T) {
|
||||
|
||||
// 同一个意图键配上不同快照 = 冲突,不能悄悄共享谱系。
|
||||
func TestLibrarySyncIntentKeyReusedWithAnotherSnapshotConflicts(t *testing.T) {
|
||||
target := "snap-1"
|
||||
root := libraryFixtureRoot(t)
|
||||
target := sealSharedVersions(t, root, 1, 4)[0]
|
||||
digest, _ := librarySyncParamsDigest("internal", target)
|
||||
now := time.Now().UTC()
|
||||
store := &fakeLibraryStore{current: &governance.LibraryVersion{ID: "ver-prod", Scope: "internal",
|
||||
@@ -101,7 +108,9 @@ func TestLibrarySyncIntentKeyReusedWithAnotherSnapshotConflicts(t *testing.T) {
|
||||
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
|
||||
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
|
||||
LibraryCapacityBudgetBytes: 1 << 40}
|
||||
body := `{"scope":"internal","target_snapshot_id":"` + target + `","operation_key":"intent-1"}`
|
||||
config.LibraryArchiveRoot = root
|
||||
sourceID := bindSourceFixture(t, &config, store, &target)
|
||||
body := sourceRequestBody(t, `{"scope":"internal","target_snapshot_id":"`+target+`","operation_key":"intent-1"}`, sourceID)
|
||||
recorder := httptest.NewRecorder()
|
||||
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
|
||||
if recorder.Code != http.StatusConflict {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"knowledge-governance/internal/governance"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type libraryLegacySourceBinder interface {
|
||||
BindLegacyLibrarySource(context.Context, string, string, governance.LibrarySourceIdentity, string, time.Time) error
|
||||
}
|
||||
|
||||
func libraryLegacySourceBind(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
identity, ok := sessionFrom(r.Context())
|
||||
if !ok || identity.Role != roleAdmin || identity.Username == "" {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "administrator session required"})
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
Scope string `json:"scope"`
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
}
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&input) != nil || decoder.Decode(new(any)) != io.EOF || (input.Scope != "internal" && input.Scope != "external") || input.SnapshotID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "exact snapshot and scope required"})
|
||||
return
|
||||
}
|
||||
source := configuredLibrarySource(config, input.Scope)
|
||||
sourceID, err := source.ID()
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
store, ok := config.Store.(libraryLegacySourceBinder)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "source association store unavailable"})
|
||||
return
|
||||
}
|
||||
if err = store.BindLegacyLibrarySource(r.Context(), input.SnapshotID, config.LibraryArchiveRoot, source, identity.Username, time.Now().UTC()); err != nil {
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"snapshot_id": input.SnapshotID, "source_id": sourceID, "source_identity": source, "associated": true, "published": false})
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/governance"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type legacySourceAPIStore struct {
|
||||
fakeLibraryStore
|
||||
calls int
|
||||
actor string
|
||||
source governance.LibrarySourceIdentity
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *legacySourceAPIStore) BindLegacyLibrarySource(_ context.Context, _ string, _ string, source governance.LibrarySourceIdentity, actor string, _ time.Time) error {
|
||||
s.calls++
|
||||
s.actor = actor
|
||||
s.source = source
|
||||
return s.err
|
||||
}
|
||||
func TestContractLegacySourceAssociationAPI(t *testing.T) {
|
||||
for _, role := range []string{roleViewer, roleEngineer, roleAdmin} {
|
||||
store := &legacySourceAPIStore{}
|
||||
config := Config{Store: store, LibrarySourceProject: "configured-project", LibrarySourceApp: "configured-app", LibrarySourceTenantID: 10000, LibrarySourceInternalKB: "configured-kb"}
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/source-associations", strings.NewReader(`{"scope":"internal","snapshot_id":"exact-snapshot"}`))
|
||||
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "real-session-actor", Role: role}))
|
||||
response := httptest.NewRecorder()
|
||||
libraryLegacySourceBind(response, request, config)
|
||||
if role == roleAdmin {
|
||||
if response.Code != 200 || store.calls != 1 || store.actor != "real-session-actor" || store.source.Project != "configured-project" || store.source.KnowledgeBaseID != "configured-kb" {
|
||||
t.Fatal("association contract", response.Code, response.Body.String())
|
||||
}
|
||||
} else if response.Code != 403 || store.calls != 0 {
|
||||
t.Fatal("non-admin associated source")
|
||||
}
|
||||
}
|
||||
if classifyRole("POST", "/api/v1/library/source-associations") != roleAdmin {
|
||||
t.Fatal("route is not administrator only")
|
||||
}
|
||||
}
|
||||
func TestContractLegacySourceAssociationAPIRejectsSpoofAndEvidenceFailure(t *testing.T) {
|
||||
for _, body := range []string{`{"scope":"internal","snapshot_id":"x","actor":"forged"}`, `{"scope":"internal","snapshot_id":"x","source_identity":{"project":"forged"}}`, `{"scope":"internal","snapshot_id":"x"} {}`} {
|
||||
store := &legacySourceAPIStore{}
|
||||
req := httptest.NewRequest("POST", "/", strings.NewReader(body))
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "admin", Role: roleAdmin}))
|
||||
out := httptest.NewRecorder()
|
||||
libraryLegacySourceBind(out, req, Config{Store: store})
|
||||
if out.Code != 400 || store.calls != 0 {
|
||||
t.Fatal("spoofed or trailing payload accepted")
|
||||
}
|
||||
}
|
||||
store := &legacySourceAPIStore{err: errors.New("original proof mismatch")}
|
||||
req := httptest.NewRequest("POST", "/", strings.NewReader(`{"scope":"internal","snapshot_id":"x"}`))
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "admin", Role: roleAdmin}))
|
||||
out := httptest.NewRecorder()
|
||||
libraryLegacySourceBind(out, req, Config{Store: store, LibrarySourceProject: "p", LibrarySourceApp: "app", LibrarySourceTenantID: 1, LibrarySourceInternalKB: "kb"})
|
||||
if out.Code != 409 {
|
||||
t.Fatal("unproven association reported success")
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ func TestEmptyTargetOverviewAndEnqueueAgree(t *testing.T) {
|
||||
}
|
||||
return true, nil, nil
|
||||
}}
|
||||
sourceID := bindSourceFixture(t, &config, store, &target)
|
||||
rec := httptest.NewRecorder()
|
||||
libraryOverviewHandler(rec, httptest.NewRequest(http.MethodGet, "/api/v1/library/overview?scope=internal", nil), config)
|
||||
var overview libraryOverview
|
||||
@@ -40,7 +41,7 @@ func TestEmptyTargetOverviewAndEnqueueAgree(t *testing.T) {
|
||||
t.Fatalf("failed=%v gate=%+v", failed, overview.Gate)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
librarySyncEnqueue(rec, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(`{"scope":"internal","target_snapshot_id":"`+target+`"}`)), config)
|
||||
librarySyncEnqueue(rec, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(sourceRequestBody(t, `{"scope":"internal","target_snapshot_id":"`+target+`"}`, sourceID))), config)
|
||||
if failed {
|
||||
if rec.Code != http.StatusServiceUnavailable || store.createN != 0 {
|
||||
t.Fatalf("unreachable target enqueued: %d %s", rec.Code, rec.Body.String())
|
||||
|
||||
@@ -266,3 +266,25 @@ func TestLibraryReadPathsRejectTamperedManifest(t *testing.T) {
|
||||
t.Fatalf("storage must fail closed: status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// F11: the HTTP projection must include binding and Wiki log counts; the
|
||||
// previous projection silently omitted them and the UI turned absence into 0.
|
||||
func TestLibrarySnapshotTotalsIncludeBindingsAndWikiLogs(t *testing.T) {
|
||||
view := librarySnapshotViewOfNoUsage("snap-totals", librarysnapshot.Manifest{
|
||||
Scope: "internal", KnowledgeBaseID: "kb", TenantID: 10000,
|
||||
Parts: []librarysnapshot.Part{
|
||||
{Kind: "database", Name: "knowledges", Count: 4},
|
||||
{Kind: "database", Name: "chunks", Count: 38},
|
||||
{Kind: "database", Name: "resources", Count: 21},
|
||||
{Kind: "database", Name: "resource_bindings", Count: 4},
|
||||
{Kind: "wiki", Name: "wiki_pages", Count: 31},
|
||||
{Kind: "wiki", Name: "wiki_folders", Count: 21},
|
||||
{Kind: "wiki", Name: "wiki_log_entries", Count: 11},
|
||||
},
|
||||
})
|
||||
for key, want := range map[string]int64{"documents": 4, "chunks": 38, "resources": 21, "bindings": 4, "wiki_pages": 31, "wiki_folders": 21, "wiki_log_entries": 11} {
|
||||
if view.Totals[key] != want {
|
||||
t.Fatalf("totals[%s]=%d want=%d (%v)", key, view.Totals[key], want, view.Totals)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,13 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"knowledge-governance/internal/platform/postgres"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
)
|
||||
|
||||
// 按指定整库版本恢复:与同步分开的作业类型,需要**单独的管理员授权**,
|
||||
@@ -71,9 +71,7 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
reasons = append(reasons, "生产写入闸口关闭")
|
||||
}
|
||||
if !config.ProductionBackupRestoreVerified {
|
||||
reasons = append(reasons, "没有已核验的生产恢复演练证据")
|
||||
}
|
||||
reasons = append(reasons, restoreGateReasons(config.withRestoreEvidence(r.Context(), request.Scope))...)
|
||||
authorizationOK := false
|
||||
if storeWithAuth, ok := config.Store.(interface {
|
||||
ActiveLibraryAuthorization(ctx context.Context, scope, snapshotID, digest string, now time.Time) (governance.LibraryReleaseAuthorization, bool, error)
|
||||
@@ -104,12 +102,12 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot register restore intent"})
|
||||
return
|
||||
}
|
||||
job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
|
||||
job, reused, err := store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{
|
||||
ID: jobID, Scope: request.Scope, Kind: governance.LibraryJobRestore,
|
||||
IdempotencyKey: intent.JobKey,
|
||||
RequestDigest: digest, OperationID: intent.Operation.ID, TargetSnapshotID: request.SnapshotID,
|
||||
Actor: identity.Username,
|
||||
}, governance.SyncStages(), now)
|
||||
}, governance.SyncStages(), config.LibraryHandoffEnabled, now)
|
||||
if errors.Is(err, governance.ErrLibraryJobActive) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_restore_active", "error": "该目标已有在飞作业"})
|
||||
return
|
||||
@@ -123,12 +121,12 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
|
||||
return
|
||||
}
|
||||
if reused && (job.State == governance.LibraryJobFailed || job.State == governance.LibraryJobCancelled) {
|
||||
job, reused, err = store.CreateLibraryJob(r.Context(), governance.LibraryJob{
|
||||
job, reused, err = store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{
|
||||
ID: jobID + "-retry", Scope: request.Scope, Kind: governance.LibraryJobRestore,
|
||||
IdempotencyKey: intent.JobKey + ":retry:" + strconv.FormatInt(now.UnixNano(), 10),
|
||||
RequestDigest: digest, OperationID: intent.Operation.ID, TargetSnapshotID: request.SnapshotID,
|
||||
Actor: identity.Username,
|
||||
}, governance.SyncStages(), now)
|
||||
}, governance.SyncStages(), config.LibraryHandoffEnabled, now)
|
||||
if err != nil || reused {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_restore_retry_conflict", "error": "无法为重试创建新作业"})
|
||||
return
|
||||
@@ -138,25 +136,6 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true})
|
||||
return
|
||||
}
|
||||
queueID, queueType, payload, err := libraryQueueRequest(config.LibraryHandoffEnabled, job.ID,
|
||||
request.Scope, request.SnapshotID, libraryRestoreJobType)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build restore payload"})
|
||||
return
|
||||
}
|
||||
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
|
||||
ID: queueID, Type: queueType, Payload: payload, AvailableAt: now,
|
||||
MaxAttempts: 1, IdempotencyKey: queueType + ".queue:" + job.ID,
|
||||
}, now)
|
||||
if err != nil || queueJob == nil {
|
||||
_ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始恢复", now)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue restore job"})
|
||||
return
|
||||
}
|
||||
if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach restore job"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false})
|
||||
}
|
||||
|
||||
@@ -188,9 +167,7 @@ func libraryRestoreAvailability(w http.ResponseWriter, r *http.Request, config C
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
view.Reasons = append(view.Reasons, "生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false)")
|
||||
}
|
||||
if !config.ProductionBackupRestoreVerified {
|
||||
view.Reasons = append(view.Reasons, "没有已核验的生产恢复演练证据(PRODUCTION_BACKUP_RESTORE_VERIFIED=false)")
|
||||
}
|
||||
view.Reasons = append(view.Reasons, restoreGateReasons(config.withRestoreEvidence(r.Context(), scope))...)
|
||||
digest, err := libraryRestoreParamsDigest(scope, snapshotID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot digest params"})
|
||||
@@ -247,9 +224,7 @@ func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
reasons = append(reasons, "生产写入闸口关闭")
|
||||
}
|
||||
if !config.ProductionBackupRestoreVerified {
|
||||
reasons = append(reasons, "没有已核验的生产恢复演练证据")
|
||||
}
|
||||
reasons = append(reasons, restoreGateReasons(config.withRestoreEvidence(r.Context(), source.Scope))...)
|
||||
var digest string
|
||||
switch source.Kind {
|
||||
case governance.LibraryJobSync:
|
||||
@@ -290,42 +265,47 @@ func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
// id 落盘。另建 `-resume` 作业只能继承 operation,其它所有者仍指向旧作业:
|
||||
// AcquireInstanceMaintenance 会拒绝它、journal 与预备份也查不到——那样"续作"只是
|
||||
// 一个漂亮的新行,接不上原窗口。原作业 + 新 attempt 才是批准协议的形状。
|
||||
prepared, resumed, err := store.PrepareLibraryJobResume(r.Context(), sourceID, now)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot prepare resumed job"})
|
||||
// 阶段/状态/执行权与载荷全部在存储层的事务里校验并构造:handler 手里的 source 只用于
|
||||
// 授权与闸口判断,不参与续作决策,避免用过期快照复活一个已经变化的作业。
|
||||
resumer, ok := config.Store.(interface {
|
||||
ResumeLibraryJob(ctx context.Context, jobID, queueType string, now time.Time) (governance.LibraryJob, bool, error)
|
||||
})
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"error": "作业存储不支持续作"})
|
||||
return
|
||||
}
|
||||
if !resumed {
|
||||
// 状态在检查之后被别的执行者推进(已接管/已完成):不许再塞一次。
|
||||
prepared, resumed, err := resumer.ResumeLibraryJob(r.Context(), sourceID, queueType, now)
|
||||
switch {
|
||||
case errors.Is(err, postgres.ErrLibraryResumeBusy):
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_resume_busy",
|
||||
"error": "该作业已有执行在跑(租约仍有效),等它结束再续作"})
|
||||
return
|
||||
case errors.Is(err, postgres.ErrLibraryResumeRequiresRecover):
|
||||
// 窗口是否仍被持有由维护记录决定:已释放的回滚作业说"窗口已释放",不能一律宣称仍持有。
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_resume_requires_recover",
|
||||
"error": "作业停在回滚阶段,请走维护恢复而不是续作",
|
||||
"maintenance_held": maintenanceHeldFor(r.Context(), config, source)})
|
||||
return
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot resume job"})
|
||||
return
|
||||
case !resumed:
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_resume_state_changed",
|
||||
"error": "作业已不在可续作状态(可能已被接管或完成)"})
|
||||
return
|
||||
}
|
||||
// 写入已完成、只差登记版本的情况:续作只做幂等收尾,不重写生产。
|
||||
body := map[string]any{"library_job_id": prepared.ID, "scope": source.Scope,
|
||||
"target_snapshot_id": source.TargetSnapshotID}
|
||||
if source.Stage == "finalize" && source.SnapshotID != "" {
|
||||
body["finalize_only"] = true
|
||||
}
|
||||
payload, _ := json.Marshal(body)
|
||||
queueID := governance.QueueJobIDFor(prepared.ID)
|
||||
if _, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
|
||||
ID: queueID, Type: queueType, Payload: payload, AvailableAt: now,
|
||||
MaxAttempts: 1, IdempotencyKey: "library.resume.queue:" + prepared.ID,
|
||||
}, now); err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue resumed job"})
|
||||
return
|
||||
}
|
||||
// 队列行可能还是上一次的终态:重置为 pending。仍有效的租约 ⇒ 有执行在跑,让路。
|
||||
if resetErr := store.ResetQueueJobForResume(r.Context(), queueID, now); resetErr != nil {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_resume_busy",
|
||||
"error": "该作业已有执行在跑(租约仍有效),等它结束再续作", "detail": errString(resetErr)})
|
||||
return
|
||||
}
|
||||
if attachErr := store.AttachLibraryQueueJob(r.Context(), prepared.ID, queueID, now); attachErr != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach resumed job"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": prepared, "resumed_from": sourceID,
|
||||
"resumed": true, "next_attempt_epoch": prepared.AttemptEpoch + 1})
|
||||
}
|
||||
|
||||
// maintenanceHeldFor 只回答"这个作业现在是否仍持有维护窗口",用于给回滚作业的拒绝文案定性。
|
||||
func maintenanceHeldFor(ctx context.Context, config Config, job governance.LibraryJob) bool {
|
||||
reader, ok := config.Store.(interface {
|
||||
LibraryMaintenanceOf(ctx context.Context, scope string) (*postgres.LibraryMaintenance, error)
|
||||
})
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
m, err := reader.LibraryMaintenanceOf(ctx, job.Scope)
|
||||
return err == nil && m != nil && m.OwnerJobID == job.ID && m.ReleasedAt == nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
func resumeRequest(id string) *http.Request {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/"+id+"/resume", nil)
|
||||
request.SetPathValue("id", id)
|
||||
return request.WithContext(context.WithValue(request.Context(), sessionKey{},
|
||||
sessionIdentity{Username: "admin", Role: roleAdmin}))
|
||||
}
|
||||
|
||||
func resumableStore(job governance.LibraryJob) *fakeLibraryStore {
|
||||
now := time.Now().UTC()
|
||||
digest, _ := librarySyncParamsDigest(job.Scope, job.TargetSnapshotID)
|
||||
if job.Kind == governance.LibraryJobRestore {
|
||||
digest, _ = libraryRestoreParamsDigest(job.Scope, job.TargetSnapshotID)
|
||||
}
|
||||
store := &fakeLibraryStore{
|
||||
jobs: []governance.LibraryJob{job},
|
||||
grant: &governance.LibraryReleaseAuthorization{ID: "a", Scope: job.Scope,
|
||||
SnapshotID: job.TargetSnapshotID, ParamsDigest: digest, ExpiresAt: now.Add(time.Hour), CreatedAt: now},
|
||||
}
|
||||
store.resumeOK = true
|
||||
return store
|
||||
}
|
||||
|
||||
func resumeConfig(store *fakeLibraryStore) Config {
|
||||
return Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true}
|
||||
}
|
||||
|
||||
// 合法续作:202,并且只投递一次。
|
||||
func TestR26ResumeAcceptedDeliversOnce(t *testing.T) {
|
||||
job := governance.LibraryJob{ID: "job-ok", Scope: "internal", Kind: governance.LibraryJobSync,
|
||||
State: governance.LibraryJobFailed, Stage: "resources", TargetSnapshotID: "snap-1"}
|
||||
store := resumableStore(job)
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryJobResume(recorder, resumeRequest("job-ok"), resumeConfig(store))
|
||||
if recorder.Code != http.StatusAccepted {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if len(store.resumeCalls) != 1 || store.resumeCalls[0] != "job-ok/library.sync" {
|
||||
t.Fatalf("resume calls=%v", store.resumeCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// 回滚阶段的作业:409,且文案不能一律宣称"仍持有维护窗口"(窗口可能已释放)。
|
||||
func TestR26ResumeRollbackStageRequiresRecover(t *testing.T) {
|
||||
job := governance.LibraryJob{ID: "job-rb", Scope: "internal", Kind: governance.LibraryJobRestore,
|
||||
State: governance.LibraryJobFailed, Stage: "rollback", TargetSnapshotID: "snap-1"}
|
||||
store := resumableStore(job)
|
||||
store.resumeErr = postgres.ErrLibraryResumeRequiresRecover
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryJobResume(recorder, resumeRequest("job-rb"), resumeConfig(store))
|
||||
if recorder.Code != http.StatusConflict || !strings.Contains(recorder.Body.String(), "library_resume_requires_recover") {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if strings.Contains(recorder.Body.String(), "保留维护窗口") {
|
||||
t.Fatalf("must not always claim the window is held: %s", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// 租约仍有效:409 busy,不是 500。
|
||||
func TestR26ResumeBusyIsConflict(t *testing.T) {
|
||||
job := governance.LibraryJob{ID: "job-busy", Scope: "internal", Kind: governance.LibraryJobSync,
|
||||
State: governance.LibraryJobFailed, Stage: "resources", TargetSnapshotID: "snap-1"}
|
||||
store := resumableStore(job)
|
||||
store.resumeErr = postgres.ErrLibraryResumeBusy
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryJobResume(recorder, resumeRequest("job-busy"), resumeConfig(store))
|
||||
if recorder.Code != http.StatusConflict || !strings.Contains(recorder.Body.String(), "library_resume_busy") {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// 入队失败(存储层事务回滚):500,且不得把作业当成已续作。
|
||||
func TestR26ResumeEnqueueFailureIsServerError(t *testing.T) {
|
||||
job := governance.LibraryJob{ID: "job-fail", Scope: "internal", Kind: governance.LibraryJobRestore,
|
||||
State: governance.LibraryJobFailed, Stage: "resources", TargetSnapshotID: "snap-1"}
|
||||
store := resumableStore(job)
|
||||
store.resumeErr = errors.New("enqueue resumed job: injected")
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryJobResume(recorder, resumeRequest("job-fail"), resumeConfig(store))
|
||||
if recorder.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if strings.Contains(recorder.Body.String(), "resumed") {
|
||||
t.Fatalf("failed enqueue must not claim success: %s", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// 重复请求:第二次被存储层拒绝(状态已推进),不会重复投递。
|
||||
func TestR26ResumeDuplicateRequestDoesNotRedeliver(t *testing.T) {
|
||||
job := governance.LibraryJob{ID: "job-dup", Scope: "internal", Kind: governance.LibraryJobSync,
|
||||
State: governance.LibraryJobFailed, Stage: "resources", TargetSnapshotID: "snap-1"}
|
||||
store := resumableStore(job)
|
||||
first := httptest.NewRecorder()
|
||||
libraryJobResume(first, resumeRequest("job-dup"), resumeConfig(store))
|
||||
store.resumeOK = false // 第二次:业务作业已不是 failed
|
||||
second := httptest.NewRecorder()
|
||||
libraryJobResume(second, resumeRequest("job-dup"), resumeConfig(store))
|
||||
if first.Code != http.StatusAccepted || second.Code != http.StatusConflict {
|
||||
t.Fatalf("first=%d second=%d body=%s", first.Code, second.Code, second.Body.String())
|
||||
}
|
||||
if len(store.resumeCalls) != 2 {
|
||||
t.Fatalf("expected 2 store calls, got %v", store.resumeCalls)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
@@ -28,19 +29,21 @@ type librarySnapshotPart struct {
|
||||
}
|
||||
|
||||
type librarySnapshotView struct {
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Scope string `json:"scope"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ValidationPolicy string `json:"validation_policy"`
|
||||
Format string `json:"format"`
|
||||
Compatibility librarysnapshot.Compatibility `json:"compatibility"`
|
||||
Parts []librarySnapshotPart `json:"parts"`
|
||||
LogicalBytes int64 `json:"logical_bytes"`
|
||||
UniqueBytes int64 `json:"unique_bytes"`
|
||||
SharedBytes int64 `json:"shared_bytes"`
|
||||
Totals map[string]int64 `json:"totals"`
|
||||
SourceID string `json:"source_id,omitempty"`
|
||||
SourceIdentity *governance.LibrarySourceIdentity `json:"source_identity,omitempty"`
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Scope string `json:"scope"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ValidationPolicy string `json:"validation_policy"`
|
||||
Format string `json:"format"`
|
||||
Compatibility librarysnapshot.Compatibility `json:"compatibility"`
|
||||
Parts []librarySnapshotPart `json:"parts"`
|
||||
LogicalBytes int64 `json:"logical_bytes"`
|
||||
UniqueBytes int64 `json:"unique_bytes"`
|
||||
SharedBytes int64 `json:"shared_bytes"`
|
||||
Totals map[string]int64 `json:"totals"`
|
||||
// Verified 只在这一份版本的每个部件都被重新哈希并核对通过时为 true。
|
||||
// 列表口径下它恒为 false:枚举只证明清单可读,不是"完整性已验证"。
|
||||
Verified bool `json:"verified"`
|
||||
@@ -258,10 +261,14 @@ func librarySnapshotViewOfNoUsage(id string, manifest librarysnapshot.Manifest)
|
||||
}
|
||||
case "resources":
|
||||
snapshot.Totals["resources"] = part.Count
|
||||
case "resource_bindings":
|
||||
snapshot.Totals["bindings"] = part.Count
|
||||
case "wiki_pages":
|
||||
snapshot.Totals["wiki_pages"] = part.Count
|
||||
case "wiki_folders":
|
||||
snapshot.Totals["wiki_folders"] = part.Count
|
||||
case "wiki_log_entries":
|
||||
snapshot.Totals["wiki_log_entries"] = part.Count
|
||||
}
|
||||
}
|
||||
sort.Slice(snapshot.Parts, func(i, j int) bool {
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
|
||||
type librarySourceCandidateStore interface {
|
||||
LibrarySourceCandidate(context.Context, string, string) (governance.LibraryVersion, bool, error)
|
||||
}
|
||||
|
||||
func configuredLibrarySource(config Config, scope string) governance.LibrarySourceIdentity {
|
||||
kb := config.LibrarySourceInternalKB
|
||||
if scope == "external" {
|
||||
kb = config.LibrarySourceExternalKB
|
||||
}
|
||||
return governance.LibrarySourceIdentity{Project: config.LibrarySourceProject, App: config.LibrarySourceApp, Scope: scope, TenantID: config.LibrarySourceTenantID, KnowledgeBaseID: kb}
|
||||
}
|
||||
|
||||
func currentSourceCandidate(ctx context.Context, config Config, scope string) (*librarySnapshotView, error) {
|
||||
source := configuredLibrarySource(config, scope)
|
||||
id, err := source.ID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
store, ok := config.Store.(librarySourceCandidateStore)
|
||||
if !ok {
|
||||
return nil, errors.New("source candidate exact query unavailable")
|
||||
}
|
||||
candidate, found, err := store.LibrarySourceCandidate(ctx, scope, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !found {
|
||||
return nil, errors.New("当前来源没有已绑定封存;旧快照须以原捕获证据核验关联,不能继承其他来源")
|
||||
}
|
||||
if candidate.Kind != governance.LibraryVersionTestSealed || candidate.Scope != scope || candidate.Evidence["source_id"] != id {
|
||||
return nil, errors.New("candidate source binding mismatch")
|
||||
}
|
||||
archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer archive.Close()
|
||||
manifest, err := archive.Load(candidate.SnapshotID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if manifest.Scope != scope || manifest.TenantID != source.TenantID || manifest.KnowledgeBaseID != source.KnowledgeBaseID {
|
||||
return nil, errors.New("candidate manifest differs from configured source")
|
||||
}
|
||||
view := librarySnapshotViewOfNoUsage(candidate.SnapshotID, manifest)
|
||||
view.SourceID = id
|
||||
view.SourceIdentity = &source
|
||||
return &view, nil
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/governance"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestContractSyncRejectsUnboundSourceBeforeCreatingJob(t *testing.T) {
|
||||
store := &fakeLibraryStore{current: &governance.LibraryVersion{SnapshotID: "current"}, grant: &governance.LibraryReleaseAuthorization{Scope: "internal", SnapshotID: "foreign", ExpiresAt: time.Now().Add(time.Hour)}}
|
||||
digest, _ := librarySyncParamsDigest("internal", "foreign")
|
||||
store.grant.ParamsDigest = digest
|
||||
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true, LibraryProductionDatabaseURL: "postgres://unreachable.invalid/db", LibraryCapacityBudgetBytes: 1 << 40}
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(`{"scope":"internal","target_snapshot_id":"foreign"}`))
|
||||
response := httptest.NewRecorder()
|
||||
librarySyncEnqueue(response, request, config)
|
||||
if store.createN != 0 {
|
||||
t.Fatalf("unbound foreign source created %d jobs; response=%s", store.createN, response.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func (f *fakeLibraryStore) LibrarySourceCandidate(_ context.Context, scope, sourceID string) (governance.LibraryVersion, bool, error) {
|
||||
if f.sourceCandidate != nil && f.sourceCandidate.Scope == scope && f.sourceCandidate.Evidence["source_id"] == sourceID {
|
||||
return *f.sourceCandidate, true, nil
|
||||
}
|
||||
return governance.LibraryVersion{}, false, nil
|
||||
}
|
||||
|
||||
// These fixtures now contain the same capture identity and real immutable
|
||||
// manifest required by the production admission path. No production bypass.
|
||||
func bindSourceFixture(t *testing.T, config *Config, store *fakeLibraryStore, target *string) string {
|
||||
t.Helper()
|
||||
if config.LibraryArchiveRoot == "" {
|
||||
config.LibraryArchiveRoot = libraryFixtureRoot(t)
|
||||
*target = sealSharedVersions(t, config.LibraryArchiveRoot, 1, 4)[0]
|
||||
}
|
||||
archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer archive.Close()
|
||||
manifest, err := archive.Load(*target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config.LibrarySourceProject = "fixture-project"
|
||||
config.LibrarySourceApp = "fixture-app"
|
||||
config.LibrarySourceTenantID = manifest.TenantID
|
||||
config.LibrarySourceInternalKB = manifest.KnowledgeBaseID
|
||||
source := configuredLibrarySource(*config, "internal")
|
||||
id, err := source.ID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store.sourceCandidate = &governance.LibraryVersion{Scope: "internal", Kind: governance.LibraryVersionTestSealed, SnapshotID: *target, Evidence: map[string]any{"source_id": id}}
|
||||
if store.grant != nil {
|
||||
store.grant.SnapshotID = *target
|
||||
store.grant.ParamsDigest, _ = librarySyncParamsDigest("internal", *target)
|
||||
}
|
||||
return id
|
||||
}
|
||||
func sourceRequestBody(t *testing.T, body, id string) string {
|
||||
t.Helper()
|
||||
var v map[string]any
|
||||
if err := json.Unmarshal([]byte(body), &v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v["source_id"] = id
|
||||
raw, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(raw)
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
// 恢复验证:页面点一次"跑恢复验证",后端建一个持久作业,worker 用与 CLI 同一份实现
|
||||
// (internal/libraryverify)真实执行:捕获目标 → 基线校验 → 写 canary 证明校验有效 →
|
||||
// 按预备份恢复 → 恢复后复核。通过与否只由这条证据表回答,页面不接受手填开关。
|
||||
const libraryVerifyJobType = "library.verify"
|
||||
|
||||
type libraryVerifyRequest struct {
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
|
||||
// libraryVerificationView 是页面需要的全部事实:当前目标是谁、最近一次验证结果、
|
||||
// 证据是否对当前目标成立、以及同步闸口能不能据此放行。
|
||||
type libraryVerificationView struct {
|
||||
Scope string `json:"scope"`
|
||||
Target libraryVerificationTarget `json:"target"`
|
||||
Verified bool `json:"verified"`
|
||||
Reason string `json:"reason"`
|
||||
Latest *governance.LibraryRestoreVerification `json:"latest,omitempty"`
|
||||
// SnapshotLatest 只在请求显式带 snapshot_id 时返回:快照报告不能拿 scope
|
||||
// 最近一条代替。
|
||||
SnapshotLatest *governance.LibraryRestoreVerification `json:"snapshot_latest,omitempty"`
|
||||
History []governance.LibraryRestoreVerification `json:"history"`
|
||||
Running bool `json:"running"`
|
||||
JobID string `json:"job_id,omitempty"`
|
||||
State string `json:"state,omitempty"`
|
||||
Stage string `json:"stage,omitempty"`
|
||||
}
|
||||
|
||||
type libraryVerificationTarget struct {
|
||||
Instance string `json:"instance"`
|
||||
Project string `json:"project"`
|
||||
InternalKB string `json:"internal_kb"`
|
||||
ExternalKB string `json:"external_kb"`
|
||||
Index string `json:"index"`
|
||||
S3Bucket string `json:"s3_bucket"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
DatabaseSet bool `json:"database_configured"`
|
||||
}
|
||||
|
||||
// libraryVerifyEnqueue 投递一次恢复验证作业(管理员)。
|
||||
//
|
||||
// 它不签发发布授权、不改版本:验证只回答"当前目标的预备份能不能恢复"。
|
||||
// 目标是部署配置,不接受请求体指定——否则一次点击就能验证别的库并把证据挂到当前目标上。
|
||||
func libraryVerifyEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
|
||||
return
|
||||
}
|
||||
identity, ok := sessionFrom(r.Context())
|
||||
if !ok || roleRank(identity.Role) < roleRank(roleAdmin) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]any{"error": "恢复验证仅管理员可发起"})
|
||||
return
|
||||
}
|
||||
var request libraryVerifyRequest
|
||||
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
|
||||
}
|
||||
store, ok := libraryStore(config)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"code": "library_verify_unavailable",
|
||||
"error": "恢复验证存储不可用"})
|
||||
return
|
||||
}
|
||||
// 验证要停写入者并在目标上写 canary:维护中或闸口关闭时直接拒绝,
|
||||
// 不让页面投一个 worker 必然失败的作业。
|
||||
if body, held := instanceMaintenanceGuard(r.Context(), config, request.Scope); held {
|
||||
writeJSON(w, http.StatusConflict, body)
|
||||
return
|
||||
}
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
|
||||
"code": "library_verify_blocked",
|
||||
"reasons": []string{
|
||||
"生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false):恢复验证要停写入者并在目标上写 canary",
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
digest, err := governance.LibraryRequestDigest(request.Scope, governance.LibraryJobVerify,
|
||||
map[string]any{"scope": request.Scope})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot digest request"})
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
// 验证作业必须有和同步/恢复同一套不可变 operation:worker 的 owned attempt 从
|
||||
// job.operation_id 取身份,恢复派发闸口和对象网关都按它核验。没有 operation 的
|
||||
// verify 作业在真实恢复时会被 fail closed(审核 B2-R1)。
|
||||
intent, intentErr := ensureLibraryIntent(r.Context(), store, request.Scope, governance.LibraryJobVerify,
|
||||
"", digest, identity.Username, "", now)
|
||||
if intentErr != nil {
|
||||
if isIntentConflict(intentErr) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_verify_conflict",
|
||||
"error": "同一幂等键对应了不同的请求"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library verify operation"})
|
||||
return
|
||||
}
|
||||
job, reused, err := store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{
|
||||
ID: fmt.Sprintf("libverify-%s-%d", request.Scope, now.UnixNano()), Scope: request.Scope,
|
||||
Kind: governance.LibraryJobVerify,
|
||||
IdempotencyKey: intent.JobKey,
|
||||
RequestDigest: digest, OperationID: intent.Operation.ID, Actor: identity.Username,
|
||||
}, governance.VerifyStages(), false, now)
|
||||
if errors.Is(err, governance.ErrLibraryJobActive) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_write_active",
|
||||
"error": "该目标已有在飞的写作业(同步/恢复/基线/验证互斥),等它结束再发起"})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, governance.ErrLibraryJobIdempotencyConflict) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_verify_conflict",
|
||||
"error": "同一幂等键对应了不同的请求"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library verify job"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": reused})
|
||||
}
|
||||
|
||||
// libraryVerifications 读当前目标的恢复验证证据(页面轮询用)。
|
||||
func libraryVerifications(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
scope, err := scopeFromQuery(r)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
view := libraryVerificationView{
|
||||
Scope: scope,
|
||||
History: []governance.LibraryRestoreVerification{},
|
||||
Target: libraryVerificationTarget{
|
||||
Instance: config.LibraryTargetInstance,
|
||||
Project: config.LibraryTargetProject,
|
||||
InternalKB: config.LibraryProductionInternalKB,
|
||||
ExternalKB: config.LibraryProductionExternalKB,
|
||||
Index: config.LibraryProductionIndex,
|
||||
S3Bucket: config.LibraryProductionS3Bucket,
|
||||
TenantID: config.LibraryProductionTenantID,
|
||||
DatabaseSet: config.LibraryProductionDatabaseURL != "",
|
||||
},
|
||||
}
|
||||
store, ok := config.Store.(interface {
|
||||
LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error)
|
||||
LibraryRestoreVerifications(context.Context, string, int) ([]governance.LibraryRestoreVerification, error)
|
||||
})
|
||||
if !ok {
|
||||
view.Reason = "当前部署没有恢复验证存储:无法读取证据"
|
||||
writeJSON(w, http.StatusServiceUnavailable, view)
|
||||
return
|
||||
}
|
||||
latest, found, err := store.LatestLibraryRestoreVerification(r.Context(), scope)
|
||||
if err != nil {
|
||||
view.Reason = "读取恢复验证证据失败:" + err.Error()
|
||||
writeJSON(w, http.StatusServiceUnavailable, view)
|
||||
return
|
||||
}
|
||||
if found {
|
||||
view.Latest = &latest
|
||||
view.JobID = latest.JobID
|
||||
}
|
||||
if history, err := store.LibraryRestoreVerifications(r.Context(), scope, 10); err == nil {
|
||||
view.History = history
|
||||
}
|
||||
if snapshotID := strings.TrimSpace(r.URL.Query().Get("snapshot_id")); snapshotID != "" {
|
||||
if exact, ok := config.Store.(interface {
|
||||
LibraryRestoreVerificationForSnapshot(context.Context, string, string) (governance.LibraryRestoreVerification, bool, error)
|
||||
}); ok {
|
||||
item, found, exactErr := exact.LibraryRestoreVerificationForSnapshot(r.Context(), scope, snapshotID)
|
||||
if exactErr != nil {
|
||||
view.Reason = "读取该快照的恢复验证记录失败"
|
||||
writeJSON(w, http.StatusServiceUnavailable, view)
|
||||
return
|
||||
}
|
||||
if found {
|
||||
view.SnapshotLatest = &item
|
||||
}
|
||||
}
|
||||
}
|
||||
view.Verified, view.Reason = governance.LibraryVerificationSatisfied(latest, scope)
|
||||
if !found {
|
||||
view.Verified = false
|
||||
view.Reason = "还没有对当前目标做过恢复验证:点「跑一次恢复验证」(真实备份 → canary → 恢复 → 复核)"
|
||||
}
|
||||
if snapshotID := strings.TrimSpace(r.URL.Query().Get("snapshot_id")); snapshotID != "" {
|
||||
// 显式按快照查询时,verified 只回答该快照;不能让 scope 最新通过记录
|
||||
// 把另一个未演练的快照染绿。
|
||||
view.Verified = false
|
||||
if view.SnapshotLatest == nil {
|
||||
view.Reason = "该快照没有真实恢复验证记录(未验证;不是读取失败)"
|
||||
} else if view.SnapshotLatest.Status == governance.LibraryVerificationPassed {
|
||||
view.Verified = true
|
||||
view.Reason = ""
|
||||
} else {
|
||||
view.Reason = "该快照最近一次恢复验证未通过"
|
||||
}
|
||||
}
|
||||
// 在飞作业必须从真实业务行读出来:旧实现只构造 running 字段却从不赋值,
|
||||
// 页面因此在验收里看不到"已接受/正在执行",按钮也不会进入执行态(审核 B4)。
|
||||
if jobs, ok := config.Store.(interface {
|
||||
ListLibraryJobs(context.Context, string, int) ([]governance.LibraryJob, error)
|
||||
}); ok {
|
||||
if items, err := jobs.ListLibraryJobs(r.Context(), scope, 20); err == nil {
|
||||
var active *governance.LibraryJob
|
||||
for index := range items {
|
||||
item := items[index]
|
||||
if item.Kind != governance.LibraryJobVerify || string(item.State) == "" {
|
||||
continue
|
||||
}
|
||||
if !libraryJobActiveState(item.State) {
|
||||
continue
|
||||
}
|
||||
if active == nil || item.CreatedAt.After(active.CreatedAt) {
|
||||
active = &item
|
||||
}
|
||||
}
|
||||
if active != nil {
|
||||
view.Running = true
|
||||
view.JobID = active.ID
|
||||
view.State = string(active.State)
|
||||
view.Stage = active.Stage
|
||||
view.Reason = "恢复验证作业 " + active.ID + " 正在执行(" + active.Stage + ");终态会在这里显示证据,页面会自动刷新"
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, view)
|
||||
}
|
||||
|
||||
// libraryJobActiveState 只认仍在执行的业务状态:终态不是"在飞"。
|
||||
func libraryJobActiveState(state governance.LibraryJobState) bool {
|
||||
switch state {
|
||||
case governance.LibraryJobPending, governance.LibraryJobRunning:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// withRestoreEvidence 把"当前目标是否有真实恢复证据"注入 Config 的副本,
|
||||
// 让同步/恢复闸口在同一个请求里按证据判断,而不是读一个可能被手填的 env。
|
||||
//
|
||||
// 证据优先级是不可交换的(审核 B3):明确 failed/invalid 或读取失败都必须拒绝,
|
||||
// 即使 env=true;历史 env 覆盖只在**明确没有证据行**(not-found)时兜底。
|
||||
// 把读取失败混进 not-found 等于把"不知道"说成"满足"。
|
||||
func (c Config) withRestoreEvidence(ctx context.Context, scope string) Config {
|
||||
satisfied, missing, err := c.restoreEvidence(ctx, scope)
|
||||
c.restoreEvidenceChecked = true
|
||||
switch {
|
||||
case err != nil:
|
||||
c.restoreVerified = false
|
||||
c.restoreEvidenceReason = err.Error()
|
||||
case satisfied:
|
||||
c.restoreVerified = true
|
||||
c.restoreEvidenceReason = ""
|
||||
case missing && c.ProductionBackupRestoreVerified:
|
||||
c.restoreVerified = true
|
||||
c.restoreEvidenceReason = ""
|
||||
default:
|
||||
c.restoreVerified = false
|
||||
if missing {
|
||||
c.restoreEvidenceReason = "当前目标还没有恢复演练证据:先在「生产保护与恢复」里跑一次恢复验证"
|
||||
} else {
|
||||
c.restoreEvidenceReason = "没有已核验的生产恢复演练证据"
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// restoreEvidence 读当前目标的最近一条证据并给出它能不能支撑"可恢复"。
|
||||
// missing 只在"查询成功且确实没有这一行"时为 true;读取错误单独返回。
|
||||
func (c Config) restoreEvidence(ctx context.Context, scope string) (satisfied bool, missing bool, err error) {
|
||||
store, ok := c.Store.(interface {
|
||||
LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error)
|
||||
})
|
||||
if !ok {
|
||||
// 存储没有证据能力(迁移前的部署形状)等同于"没有证据行":
|
||||
// 历史 env 覆盖仍可兜底,但一旦读得出证据行,失败/无效/读取错误都优先拒绝。
|
||||
return false, true, nil
|
||||
}
|
||||
latest, found, err := store.LatestLibraryRestoreVerification(ctx, scope)
|
||||
if err != nil {
|
||||
return false, false, fmt.Errorf("读取恢复验证证据失败:%w", err)
|
||||
}
|
||||
if !found {
|
||||
return false, true, nil
|
||||
}
|
||||
ok, reason := governance.LibraryVerificationSatisfied(latest, scope)
|
||||
if !ok {
|
||||
return false, false, errors.New(reason)
|
||||
}
|
||||
return true, false, nil
|
||||
}
|
||||
|
||||
// restoreGateReasons 是闸口对"恢复可验证"的统一判断:只看 withRestoreEvidence 的结论。
|
||||
// 这里不再 OR env:env 兜底只在证据缺失时、且已经在 withRestoreEvidence 里判定过。
|
||||
func restoreGateReasons(config Config) []string {
|
||||
if config.restoreVerified {
|
||||
return nil
|
||||
}
|
||||
// 没有走过证据读取的调用点(历史路径/单元夹具)保持原有 env 语义;
|
||||
// 一旦读过证据,上面的 withRestoreEvidence 已经把优先级判定完毕。
|
||||
if !config.restoreEvidenceChecked && config.ProductionBackupRestoreVerified {
|
||||
return nil
|
||||
}
|
||||
reason := config.restoreEvidenceReason
|
||||
if reason == "" {
|
||||
reason = "没有已核验的生产恢复演练证据"
|
||||
}
|
||||
return []string{reason}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
// 恢复验证的页面契约:
|
||||
// - 只有管理员能发起(它会停写入者并在目标上写 canary);
|
||||
// - 闸口关闭 / 维护中时直接拒绝,不投一个 worker 必然失败的作业;
|
||||
// - 证据只由真实执行写入:没有证据 ⇒ verified=false,过期/换目标 ⇒ 失效。
|
||||
//
|
||||
// 这里不模拟"真跑一次恢复"(那需要真实目标);执行体本身在 internal/libraryverify,
|
||||
// 由库内 CLI 与 worker 共用,属于隔离 fixture 之外的集成范围。
|
||||
|
||||
type verificationStore struct {
|
||||
fakeLibraryStore
|
||||
verifications []governance.LibraryRestoreVerification
|
||||
}
|
||||
|
||||
func (s *verificationStore) LatestLibraryRestoreVerification(_ context.Context, scope string) (governance.LibraryRestoreVerification, bool, error) {
|
||||
for _, item := range s.verifications {
|
||||
if item.Scope == scope {
|
||||
return item, true, nil
|
||||
}
|
||||
}
|
||||
return governance.LibraryRestoreVerification{}, false, nil
|
||||
}
|
||||
|
||||
func (s *verificationStore) LibraryRestoreVerificationForSnapshot(_ context.Context, scope, snapshotID string) (governance.LibraryRestoreVerification, bool, error) {
|
||||
for _, item := range s.verifications {
|
||||
if item.Scope == scope && item.SnapshotID == snapshotID {
|
||||
return item, true, nil
|
||||
}
|
||||
}
|
||||
return governance.LibraryRestoreVerification{}, false, nil
|
||||
}
|
||||
|
||||
func (s *verificationStore) LibraryRestoreVerifications(_ context.Context, scope string, limit int) ([]governance.LibraryRestoreVerification, error) {
|
||||
items := make([]governance.LibraryRestoreVerification, 0, len(s.verifications))
|
||||
for _, item := range s.verifications {
|
||||
if item.Scope == scope {
|
||||
items = append(items, item)
|
||||
}
|
||||
}
|
||||
if limit > 0 && len(items) > limit {
|
||||
items = items[:limit]
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func verifyRequest(body, role, username string) *http.Request {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/verifications", strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
ctx := context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: username, Role: role})
|
||||
return request.WithContext(ctx)
|
||||
}
|
||||
|
||||
func TestLibraryVerifyRequiresAdmin(t *testing.T) {
|
||||
store := &verificationStore{}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryVerifyEnqueue(recorder, verifyRequest(`{"scope":"internal"}`, roleEngineer, "eng"),
|
||||
Config{Store: store, ProductionReleaseRequestsEnabled: true})
|
||||
if recorder.Code != http.StatusForbidden {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if store.createN != 0 {
|
||||
t.Fatal("non-admin must not create a verify job")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryVerifyRefusesWhenWriteGateClosed(t *testing.T) {
|
||||
store := &verificationStore{}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryVerifyEnqueue(recorder, verifyRequest(`{"scope":"internal"}`, roleAdmin, "admin"),
|
||||
Config{Store: store, ProductionReleaseRequestsEnabled: false})
|
||||
if recorder.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
body := decodeBody(t, recorder)
|
||||
if body["code"] != "library_verify_blocked" {
|
||||
t.Fatalf("body=%v", body)
|
||||
}
|
||||
if store.createN != 0 {
|
||||
t.Fatal("closed gate must not create a verify job")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryVerifyEnqueuesVerifyJobWithCanaryStages(t *testing.T) {
|
||||
store := &verificationStore{}
|
||||
store.enqueueEchoRequestedID = true
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryVerifyEnqueue(recorder, verifyRequest(`{"scope":"internal"}`, roleAdmin, "admin"),
|
||||
Config{Store: store, ProductionReleaseRequestsEnabled: true})
|
||||
if recorder.Code != http.StatusAccepted {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if store.lastJob.Kind != governance.LibraryJobVerify || store.lastJob.Scope != "internal" {
|
||||
t.Fatalf("job=%#v", store.lastJob)
|
||||
}
|
||||
if !strings.HasPrefix(store.lastJob.ID, "libverify-internal-") {
|
||||
t.Fatalf("job id=%q", store.lastJob.ID)
|
||||
}
|
||||
// B2-R1:verify 作业必须带不可变 operation,worker 的 owned attempt / 恢复派发
|
||||
// 身份都从它取;没有 operation 的作业在真实恢复时会被 fail closed。
|
||||
if store.lastJob.OperationID == "" || store.lastJob.OperationID != store.lastOperation.ID {
|
||||
t.Fatalf("verify job must carry its operation: job=%#v op=%#v", store.lastJob, store.lastOperation)
|
||||
}
|
||||
if store.lastOperation.Kind != governance.LibraryJobVerify || store.lastOperation.Scope != "internal" {
|
||||
t.Fatalf("verify operation identity=%#v", store.lastOperation)
|
||||
}
|
||||
// 阶段必须包含 canary:没有"写 canary 证明校验有效"这一步,验证就只是自证。
|
||||
want := governance.VerifyStages()
|
||||
if len(want) != 5 || want[2] != "canary" || want[3] != "restore" || want[4] != "finalize" {
|
||||
t.Fatalf("verify stages=%v", want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryVerificationsWithoutEvidenceIsNotVerified(t *testing.T) {
|
||||
store := &verificationStore{}
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal", nil)
|
||||
libraryVerifications(recorder, request, Config{Store: store})
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
body := decodeBody(t, recorder)
|
||||
if body["verified"] != false {
|
||||
t.Fatalf("verified must be false without evidence: %v", body)
|
||||
}
|
||||
if reason, _ := body["reason"].(string); !strings.Contains(reason, "还没有对当前目标做过恢复验证") {
|
||||
t.Fatalf("reason=%q", reason)
|
||||
}
|
||||
}
|
||||
|
||||
// F03: the selected snapshot must resolve its own evidence, never the scope's
|
||||
// newest passed record.
|
||||
func TestLibraryVerificationsExactSnapshotDoesNotBorrowLatest(t *testing.T) {
|
||||
store := &verificationStore{verifications: []governance.LibraryRestoreVerification{
|
||||
{ID: "verify-new", Scope: "internal", Status: governance.LibraryVerificationPassed,
|
||||
SnapshotID: "snap-new", JobID: "job-new", FinishedAt: time.Now().UTC()},
|
||||
{ID: "verify-old", Scope: "internal", Status: governance.LibraryVerificationFailed,
|
||||
SnapshotID: "snap-old", JobID: "job-old", Failure: "old restore mismatch",
|
||||
FinishedAt: time.Now().UTC().Add(-time.Hour)},
|
||||
}}
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal&snapshot_id=snap-old", nil)
|
||||
libraryVerifications(recorder, request, Config{Store: store})
|
||||
body := decodeBody(t, recorder)
|
||||
exact, ok := body["snapshot_latest"].(map[string]any)
|
||||
if !ok || exact["snapshot_id"] != "snap-old" || exact["status"] != "failed" {
|
||||
t.Fatalf("snapshot_latest=%v body=%v", body["snapshot_latest"], body)
|
||||
}
|
||||
if body["verified"] != false {
|
||||
t.Fatalf("old failed snapshot must not inherit latest passed: %v", body["verified"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryVerificationsWithPassedEvidenceIsVerified(t *testing.T) {
|
||||
store := &verificationStore{verifications: []governance.LibraryRestoreVerification{{
|
||||
ID: "libverify-internal-job1", Scope: "internal", Status: governance.LibraryVerificationPassed,
|
||||
SnapshotID: "snap-1", JobID: "job1", StartedAt: time.Now().UTC().Add(-time.Minute),
|
||||
FinishedAt: time.Now().UTC(),
|
||||
}}}
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal", nil)
|
||||
libraryVerifications(recorder, request, Config{Store: store})
|
||||
body := decodeBody(t, recorder)
|
||||
if body["verified"] != true {
|
||||
t.Fatalf("verified must be true with passed evidence: %v", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryVerificationsFailedEvidenceIsNotVerified(t *testing.T) {
|
||||
store := &verificationStore{verifications: []governance.LibraryRestoreVerification{{
|
||||
ID: "libverify-internal-job2", Scope: "internal", Status: governance.LibraryVerificationFailed,
|
||||
SnapshotID: "snap-2", JobID: "job2", Failure: "恢复后内容仍与预备份不一致",
|
||||
StartedAt: time.Now().UTC().Add(-time.Minute), FinishedAt: time.Now().UTC(),
|
||||
}}}
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal", nil)
|
||||
libraryVerifications(recorder, request, Config{Store: store})
|
||||
body := decodeBody(t, recorder)
|
||||
if body["verified"] != false {
|
||||
t.Fatalf("failed evidence must not verify: %v", body)
|
||||
}
|
||||
if reason, _ := body["reason"].(string); !strings.Contains(reason, "恢复后内容仍与预备份不一致") {
|
||||
t.Fatalf("reason=%q", reason)
|
||||
}
|
||||
}
|
||||
|
||||
// 同步闸口必须消费同一 target 的证据:有 passed 证据即放行,
|
||||
// 只有失败证据时仍然拒绝并给出失败原因(不是笼统"没有证据")。
|
||||
// 审核 B3 反例(GPT-6 overlay)转成通过断言:env=true 不能覆盖明确失败或读取失败。
|
||||
type evidenceReadErrorStore struct{ verificationStore }
|
||||
|
||||
func (*evidenceReadErrorStore) LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error) {
|
||||
return governance.LibraryRestoreVerification{}, false, errors.New("evidence lookup failed")
|
||||
}
|
||||
|
||||
func TestRestoreGateFailedEvidenceBeatsEnv(t *testing.T) {
|
||||
store := &verificationStore{verifications: []governance.LibraryRestoreVerification{{
|
||||
Scope: "internal", Status: governance.LibraryVerificationFailed, Failure: "restore mismatch",
|
||||
FinishedAt: time.Now().UTC(),
|
||||
}}}
|
||||
config := Config{Store: store, ProductionBackupRestoreVerified: true}.withRestoreEvidence(context.Background(), "internal")
|
||||
reasons := restoreGateReasons(config)
|
||||
if len(reasons) == 0 || !strings.Contains(strings.Join(reasons, ";"), "restore mismatch") {
|
||||
t.Fatalf("failed evidence must beat env=true: %v", reasons)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreGateUnreadableEvidenceBeatsEnv(t *testing.T) {
|
||||
config := Config{Store: &evidenceReadErrorStore{}, ProductionBackupRestoreVerified: true}.
|
||||
withRestoreEvidence(context.Background(), "internal")
|
||||
reasons := restoreGateReasons(config)
|
||||
if len(reasons) == 0 || !strings.Contains(strings.Join(reasons, ";"), "读取恢复验证证据失败") {
|
||||
t.Fatalf("unreadable evidence must beat env=true: %v", reasons)
|
||||
}
|
||||
}
|
||||
|
||||
// env 兜底只允许在"明确没有证据行"时生效。
|
||||
func TestRestoreGateEnvFallbackOnlyWhenEvidenceMissing(t *testing.T) {
|
||||
config := Config{Store: &verificationStore{}, ProductionBackupRestoreVerified: true}.
|
||||
withRestoreEvidence(context.Background(), "internal")
|
||||
if reasons := restoreGateReasons(config); len(reasons) != 0 {
|
||||
t.Fatalf("explicit not-found with legacy env must still allow: %v", reasons)
|
||||
}
|
||||
}
|
||||
|
||||
// 审核 B4:GET 必须从真实业务行投影在飞验证作业,而不是永远 running=false。
|
||||
func TestLibraryVerificationsProjectsActiveVerifyJob(t *testing.T) {
|
||||
store := &verificationStore{}
|
||||
store.jobs = []governance.LibraryJob{{
|
||||
ID: "verify-running", Scope: "internal", Kind: governance.LibraryJobVerify,
|
||||
State: governance.LibraryJobRunning, Stage: "restore", CreatedAt: time.Now().UTC(),
|
||||
}}
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal", nil)
|
||||
libraryVerifications(recorder, request, Config{Store: store})
|
||||
body := decodeBody(t, recorder)
|
||||
if body["running"] != true {
|
||||
t.Fatalf("running verify job must be projected: %v", body)
|
||||
}
|
||||
if body["job_id"] != "verify-running" {
|
||||
t.Fatalf("job_id=%v", body["job_id"])
|
||||
}
|
||||
if body["stage"] != "restore" {
|
||||
t.Fatalf("stage=%v", body["stage"])
|
||||
}
|
||||
}
|
||||
|
||||
// 终态作业不是"在飞":页面不能一直显示执行中。
|
||||
func TestLibraryVerificationsIgnoresTerminalVerifyJob(t *testing.T) {
|
||||
store := &verificationStore{}
|
||||
store.jobs = []governance.LibraryJob{{
|
||||
ID: "verify-done", Scope: "internal", Kind: governance.LibraryJobVerify,
|
||||
State: governance.LibraryJobSucceeded, CreatedAt: time.Now().UTC(),
|
||||
}}
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal", nil)
|
||||
libraryVerifications(recorder, request, Config{Store: store})
|
||||
body := decodeBody(t, recorder)
|
||||
if body["running"] != false {
|
||||
t.Fatalf("terminal verify job must not be projected as running: %v", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibrarySyncGateConsumesRestoreEvidence(t *testing.T) {
|
||||
base := Config{ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: false,
|
||||
LibraryProductionDatabaseURL: "postgres://unused.invalid/db", LibraryCapacityBudgetBytes: 1 << 40}
|
||||
base.Store = &verificationStore{verifications: []governance.LibraryRestoreVerification{{
|
||||
Scope: "internal", Status: governance.LibraryVerificationPassed, SnapshotID: "snap-1",
|
||||
JobID: "job1", FinishedAt: time.Now().UTC(),
|
||||
}}}
|
||||
allowed := librarySyncGateWithGrant(base.withRestoreEvidence(context.Background(), "internal"),
|
||||
libraryKnownView{State: "known"}, libraryKnownView{State: "unknown"}, "snap-1", true)
|
||||
if !allowed.SyncAllowed {
|
||||
t.Fatalf("gate should allow with passed evidence: %v", allowed.Reasons)
|
||||
}
|
||||
noEvidence := Config{ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: false,
|
||||
LibraryProductionDatabaseURL: "postgres://unused.invalid/db", LibraryCapacityBudgetBytes: 1 << 40,
|
||||
Store: &verificationStore{}}.withRestoreEvidence(context.Background(), "internal")
|
||||
blocked := librarySyncGateWithGrant(noEvidence,
|
||||
libraryKnownView{State: "known"}, libraryKnownView{State: "unknown"}, "snap-1", true)
|
||||
if blocked.SyncAllowed {
|
||||
t.Fatalf("gate without env and without evidence must block: %v", blocked.Reasons)
|
||||
}
|
||||
if len(blocked.Reasons) == 0 || !strings.Contains(strings.Join(blocked.Reasons, ";"), "恢复验证") {
|
||||
t.Fatalf("blocked reasons=%v", blocked.Reasons)
|
||||
}
|
||||
failedConfig := Config{ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: false,
|
||||
LibraryProductionDatabaseURL: "postgres://unused.invalid/db", LibraryCapacityBudgetBytes: 1 << 40,
|
||||
Store: &verificationStore{verifications: []governance.LibraryRestoreVerification{{
|
||||
Scope: "internal", Status: governance.LibraryVerificationFailed, SnapshotID: "snap-2",
|
||||
JobID: "job2", Failure: "canary 后校验仍通过", FinishedAt: time.Now().UTC(),
|
||||
}}}}
|
||||
reason := strings.Join(restoreGateReasons(failedConfig.withRestoreEvidence(context.Background(), "internal")), ";")
|
||||
if !strings.Contains(reason, "canary 后校验仍通过") {
|
||||
t.Fatalf("失败证据的失败原因必须出现在闸口:%q", reason)
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user