Compare commits

...

5 Commits

Author SHA1 Message Date
zheromiku 082f77fc18 fix(reconciliation): R6 改用 removal_candidates 视图,定时批每日只占一个名额
build / build (push) Successful in 2m28s
白盒补充复核提出的三项:
- P1 R6 与 /monitor/overview「需下架」计数口径不一致:R6 原先只在扫描结果里存在
  且上游 parse_status=completed 时才生成,上游仍在 processing/finalizing 或单条读取
  失败导致扫描缺行时,总览有数、对账无记录(陷阱 15)。改为直接由 removal_candidates
  视图行生成,台账细节按 publication 回填,计数与总览同一来源;补单测覆盖
  「上游 processing」「扫描未见」两种差异。
- P2 定时批失败后每个 tick 都重建:每日占位只排除 running/succeeded,failed 不占位,
  一次失败当天会每分钟刷批。占位条件加入 failed,重跑改为显式手动触发;补 PG 集成用例。
- P2 队列不可用时前端显示 0 等待 · 0 运行:改为按 available 判定并显示不可用文案;
  补组件用例。
2026-12-01 18:56:05 +08:00
zheromiku a655f4cca8 fix(reconciliation): 用 RECONCILIATION_ENABLED 独立接线对账服务
build / build (push) Successful in 2m56s
T6 的 9 个接口此前只在 TEST_WEKNORA_ENABLED=true 时才构造对账服务,
而该开关同时要求旧测试库端点/KB/Key 文件与 spool 根(appconfig 校验),
候选环境给不出这些旧材料,于是 9 个接口恒 503 reconciliation_not_configured,
QA 无法执行任一用例。

对账本身只需要知识库绑定里的租户 Key(需求书 §5/§6),与旧取件/上传链路无关,
因此新增 RECONCILIATION_ENABLED(默认 false)单独接线 api 与 worker 的对账服务:
- appconfig 解析该开关,不再借用 TEST_WEKNORA_ENABLED
- compose/.env.example 透传,默认关闭,生产按授权再开
- 验收候选(candidate_runtime.py 连 QA 库分支)显式置 true
- 文档补开关口径,加配置解析用例
2026-12-01 18:33:04 +08:00
zheromiku 5c34ef1429 Merge pull request 'fix(candidate): 容器未运行时带出退出码与日志尾' (#43) from fix/candidate-failure-diagnosis into main
build / build (push) Successful in 2m51s
2026-12-01 17:27:40 +08:00
zheromiku a55c8844a8 Merge pull request 'fix(appconfig): 内嵌 tzdata,修 worker 在 alpine 镜像启动即退出' (#42) from fix/reconciliation-tzdata into main
build / build (push) Has been cancelled
2026-12-01 17:27:23 +08:00
Zhero & 助理 6e0382c3ba fix(candidate): 容器未运行时带出退出码与日志尾
build / build (push) Successful in 2m11s
inspect() 原本把「容器没在跑」和「镜像不符」合成一句 expected container is
not running,真正的死因(缺时区、DSN 被拒、端口绑定失败)只在 dockerd 和容器
日志里,容器被 down 掉后无从查证。改为分别报未知状态/镜像不符,并附 5 行日志尾。
2026-12-01 17:22:08 +08:00
15 changed files with 254 additions and 20 deletions
+3
View File
@@ -29,6 +29,9 @@ QA_AI_MASTER_KEY_FILE=
WEKNORA_BINDING_MASTER_KEY_FILE= WEKNORA_BINDING_MASTER_KEY_FILE=
# 测试实例平台级只读 Key:绝对路径、0400;留空 = runtime/* 与队列降级。 # 测试实例平台级只读 Key:绝对路径、0400;留空 = runtime/* 与队列降级。
WEKNORA_RUNTIME_KEY_FILE= WEKNORA_RUNTIME_KEY_FILE=
# 导入对账(T6)总开关:只接线对账服务、只用知识库绑定里的租户 Key。
# 与 TEST_WEKNORA_ENABLED(旧取件/上传链路)解耦;默认关闭,生产按授权再开。
RECONCILIATION_ENABLED=false
RECONCILIATION_SCHEDULE_ENABLED=true RECONCILIATION_SCHEDULE_ENABLED=true
RECONCILIATION_DAILY_AT=02:00 RECONCILIATION_DAILY_AT=02:00
RECONCILIATION_TIMEZONE=Asia/Shanghai RECONCILIATION_TIMEZONE=Asia/Shanghai
+1 -1
View File
@@ -247,7 +247,7 @@ func run(ctx context.Context, getenv func(string) string) error {
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
} }
var reconciliationService httpapi.ReconciliationService var reconciliationService httpapi.ReconciliationService
if config.TestWeKnoraEnabled { if config.ReconciliationEnabled {
service, serviceErr := reconciliation.New(reconciliation.Config{ service, serviceErr := reconciliation.New(reconciliation.Config{
Store: actionStore, Store: actionStore,
Remote: reconciliationRemote, Remote: reconciliationRemote,
+1 -1
View File
@@ -262,7 +262,7 @@ func run(ctx context.Context, getenv func(string) string) error {
log.Printf("library job reconcile: %d orphan job(s) marked failed", repaired) log.Printf("library job reconcile: %d orphan job(s) marked failed", repaired)
} }
var reconciliationService *reconciliation.Service var reconciliationService *reconciliation.Service
if config.TestWeKnoraEnabled && config.LibraryWorkerRole.ExecutesSourceWork() { if config.ReconciliationEnabled && config.LibraryWorkerRole.ExecutesSourceWork() {
reconciliationRemote := &weknoraaccess.Client{ reconciliationRemote := &weknoraaccess.Client{
Resolver: readiness.Resolver{ Resolver: readiness.Resolver{
LoadBinding: func(resolveCtx context.Context) (string, error) { LoadBinding: func(resolveCtx context.Context) (string, error) {
+2
View File
@@ -71,6 +71,7 @@ services:
# 测试实例平台级只读 Key(0400,绝对路径)。空值 = runtime/* 与队列降级; # 测试实例平台级只读 Key(0400,绝对路径)。空值 = runtime/* 与队列降级;
# Key 本身只挂载 secret 文件,绝不写进 compose。 # Key 本身只挂载 secret 文件,绝不写进 compose。
WEKNORA_RUNTIME_KEY_FILE: "${WEKNORA_RUNTIME_KEY_FILE:-}" WEKNORA_RUNTIME_KEY_FILE: "${WEKNORA_RUNTIME_KEY_FILE:-}"
RECONCILIATION_ENABLED: "${RECONCILIATION_ENABLED:-false}"
RECONCILIATION_SCHEDULE_ENABLED: "${RECONCILIATION_SCHEDULE_ENABLED:-true}" RECONCILIATION_SCHEDULE_ENABLED: "${RECONCILIATION_SCHEDULE_ENABLED:-true}"
RECONCILIATION_DAILY_AT: "${RECONCILIATION_DAILY_AT:-02:00}" RECONCILIATION_DAILY_AT: "${RECONCILIATION_DAILY_AT:-02:00}"
RECONCILIATION_TIMEZONE: "${RECONCILIATION_TIMEZONE:-Asia/Shanghai}" RECONCILIATION_TIMEZONE: "${RECONCILIATION_TIMEZONE:-Asia/Shanghai}"
@@ -147,6 +148,7 @@ services:
TEST_WEKNORA_ALLOW_DOCKER_HTTP: "${TEST_WEKNORA_ALLOW_DOCKER_HTTP:-false}" TEST_WEKNORA_ALLOW_DOCKER_HTTP: "${TEST_WEKNORA_ALLOW_DOCKER_HTTP:-false}"
TEST_WEKNORA_KB_ID: "${TEST_WEKNORA_KB_ID:-}" TEST_WEKNORA_KB_ID: "${TEST_WEKNORA_KB_ID:-}"
TEST_WEKNORA_API_KEY_FILE: /run/secrets/test_weknora_api_key TEST_WEKNORA_API_KEY_FILE: /run/secrets/test_weknora_api_key
RECONCILIATION_ENABLED: "${RECONCILIATION_ENABLED:-false}"
RECONCILIATION_SCHEDULE_ENABLED: "${RECONCILIATION_SCHEDULE_ENABLED:-true}" RECONCILIATION_SCHEDULE_ENABLED: "${RECONCILIATION_SCHEDULE_ENABLED:-true}"
RECONCILIATION_DAILY_AT: "${RECONCILIATION_DAILY_AT:-02:00}" RECONCILIATION_DAILY_AT: "${RECONCILIATION_DAILY_AT:-02:00}"
RECONCILIATION_TIMEZONE: "${RECONCILIATION_TIMEZONE:-Asia/Shanghai}" RECONCILIATION_TIMEZONE: "${RECONCILIATION_TIMEZONE:-Asia/Shanghai}"
@@ -127,6 +127,7 @@ WeKnora v0.9.1 新增了系统管理员「任务队列」(CHANGELOG #4732、#5
## 6. 运行方式 ## 6. 运行方式
- **开关**:`RECONCILIATION_ENABLED`(默认 `false`)只决定对账服务是否接线——关着时 9 个接口统一 503 `reconciliation_not_configured`;它与 `TEST_WEKNORA_ENABLED`(旧的取件/上传链路)解耦,因为对账只用知识库绑定里的租户 Key。候选/测试环境显式开启,生产按授权再开。
- **对账批次**:每次对账生成一个批次(run),记录开始/结束时间、两侧计数、各类差异计数和明细。结果持久化,可以和上一成功批次比较。触发方式:定时(默认每天 02:00,可配)+ 页面手动触发。 - **对账批次**:每次对账生成一个批次(run),记录开始/结束时间、两侧计数、各类差异计数和明细。结果持久化,可以和上一成功批次比较。触发方式:定时(默认每天 02:00,可配)+ 页面手动触发。
- **唯一观测时刻**:批次以 `run.started_at` 作为唯一的“现在”。R5 宽限期、R7 阈值和所有相对时间判断都用它,不用 `time.Now()`。同一批次因此可重放、可解释,验收里的“连续两次一致”才有定义。 - **唯一观测时刻**:批次以 `run.started_at` 作为唯一的“现在”。R5 宽限期、R7 阈值和所有相对时间判断都用它,不用 `time.Now()`。同一批次因此可重放、可解释,验收里的“连续两次一致”才有定义。
- **全量扫描必须完整**:整页翻完才算完成,中途失败整批标为 `failed`,不产出部分结论。不能用“最近 N 条”代替全量(陷阱 17)。扫描使用 `page_size=1000`(§5)。这里的“完整”指本批把所有页翻完,不承诺对并发写入做快照:扫描期间有增删时可能漏掉个别条目,漏掉的在下一批补上,批次记 `window_overlapped` 供解释;不为此引入游标或重扫(Q10)。 - **全量扫描必须完整**:整页翻完才算完成,中途失败整批标为 `failed`,不产出部分结论。不能用“最近 N 条”代替全量(陷阱 17)。扫描使用 `page_size=1000`(§5)。这里的“完整”指本批把所有页翻完,不承诺对并发写入做快照:扫描期间有增删时可能漏掉个别条目,漏掉的在下一批补上,批次记 `window_overlapped` 供解释;不为此引入游标或重扫(Q10)。
+9
View File
@@ -63,6 +63,9 @@ type Config struct {
// runtime/* 与 overview 队列降级为不可用;对账本身只用租户 Key。 // runtime/* 与 overview 队列降级为不可用;对账本身只用租户 Key。
WeKnoraRuntimeKeyFile string WeKnoraRuntimeKeyFile string
// ReconciliationSettings:批次执行参数。全部可配,但都有安全默认值。 // ReconciliationSettings:批次执行参数。全部可配,但都有安全默认值。
// ReconciliationEnabled 是「导入对账」自身的开关:只决定对账服务是否接线,
// 与 TEST_WEKNORA_ENABLED(旧测试库取件/上传链路)解耦——对账只用租户 Key。
ReconciliationEnabled bool
ReconciliationScheduleEnabled bool ReconciliationScheduleEnabled bool
ReconciliationDailyAt string ReconciliationDailyAt string
ReconciliationTimezone string ReconciliationTimezone string
@@ -406,6 +409,12 @@ func Load(getenv func(string) string) (Config, error) {
if config.WeKnoraRuntimeKeyFile != "" && !filepath.IsAbs(config.WeKnoraRuntimeKeyFile) { if config.WeKnoraRuntimeKeyFile != "" && !filepath.IsAbs(config.WeKnoraRuntimeKeyFile) {
return Config{}, errors.New("WEKNORA_RUNTIME_KEY_FILE must be an absolute path") return Config{}, errors.New("WEKNORA_RUNTIME_KEY_FILE must be an absolute path")
} }
if raw := getenv("RECONCILIATION_ENABLED"); raw != "" {
config.ReconciliationEnabled, err = strconv.ParseBool(raw)
if err != nil {
return Config{}, fmt.Errorf("RECONCILIATION_ENABLED: %w", err)
}
}
if raw := getenv("RECONCILIATION_SCHEDULE_ENABLED"); raw != "" { if raw := getenv("RECONCILIATION_SCHEDULE_ENABLED"); raw != "" {
config.ReconciliationScheduleEnabled, err = strconv.ParseBool(raw) config.ReconciliationScheduleEnabled, err = strconv.ParseBool(raw)
if err != nil { if err != nil {
+22
View File
@@ -6,6 +6,28 @@ import (
"time" "time"
) )
func TestLoadParsesReconciliationEnabledWithoutLegacyTestWeKnora(t *testing.T) {
values := map[string]string{"DATA" + "BASE_URL": "postgres://example"}
config, err := Load(func(key string) string { return values[key] })
if err != nil {
t.Fatalf("Load() error = %v", err)
}
if config.ReconciliationEnabled {
t.Fatal("reconciliation must stay un-wired unless RECONCILIATION_ENABLED is set")
}
values["RECONCILIATION_ENABLED"] = "true"
config, err = Load(func(key string) string { return values[key] })
if err != nil {
t.Fatalf("Load() with RECONCILIATION_ENABLED error = %v", err)
}
if !config.ReconciliationEnabled {
t.Fatal("RECONCILIATION_ENABLED=true must wire reconciliation")
}
if config.TestWeKnoraEnabled {
t.Fatal("reconciliation must not require or imply the legacy test WeKnora pipeline")
}
}
func TestLoadUsesSafeDefaults(t *testing.T) { func TestLoadUsesSafeDefaults(t *testing.T) {
values := map[string]string{"DATABASE_URL": "postgres://example"} values := map[string]string{"DATABASE_URL": "postgres://example"}
config, err := Load(func(key string) string { return values[key] }) config, err := Load(func(key string) string { return values[key] })
@@ -72,3 +72,43 @@ func TestReconciliationRunUniquenessStaleAndRetentionIntegration(t *testing.T) {
t.Fatalf("new findings=%d err=%v", count, err) t.Fatalf("new findings=%d err=%v", count, err)
} }
} }
// TestScheduledReconciliationClaimsOncePerDayAfterFailure freezes the operator
// expectation "每天最多一批": a failed scheduled batch keeps the day's slot so a
// transient upstream error cannot spawn a new batch on every scheduler tick.
// A retry after a failure is an explicit manual trigger.
func TestScheduledReconciliationClaimsOncePerDayAfterFailure(t *testing.T) {
url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
if url == "" {
t.Skip("TEST_DATABASE_URL is not set")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, url)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err := ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
store := NewStore(pool)
dayStart := time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC)
run := func(id string, started time.Time) governance.ReconciliationRun {
return governance.ReconciliationRun{ID: id, KBID: "kb-sched", State: "running", Trigger: "schedule",
StartedAt: started, Counts: governance.ReconciliationCounts{}}
}
first, claimed, err := store.ClaimScheduledReconciliationRun(ctx, run("sched-1", dayStart.Add(2*time.Hour)), dayStart, dayStart.Add(2*time.Hour))
if err != nil || !claimed {
t.Fatalf("first claim claimed=%t err=%v", claimed, err)
}
if err := store.FailReconciliationRun(ctx, first.ID, "remote_scan_failed", dayStart.Add(2*time.Minute)); err != nil {
t.Fatal(err)
}
if _, claimed, err := store.ClaimScheduledReconciliationRun(ctx, run("sched-2", dayStart.Add(3*time.Minute)), dayStart, dayStart.Add(3*time.Minute)); err != nil || claimed {
t.Fatalf("same-day reclaim after failure claimed=%t err=%v", claimed, err)
}
nextDay := dayStart.Add(24 * time.Hour)
if _, claimed, err := store.ClaimScheduledReconciliationRun(ctx, run("sched-3", nextDay.Add(2*time.Hour)), nextDay, nextDay.Add(2*time.Hour)); err != nil || !claimed {
t.Fatalf("next-day claim claimed=%t err=%v", claimed, err)
}
}
@@ -77,7 +77,7 @@ func (s *Store) ClaimScheduledReconciliationRun(ctx context.Context, run governa
SELECT $1,$2,'running','schedule',$3,$4::jsonb,$5 SELECT $1,$2,'running','schedule',$3,$4::jsonb,$5
WHERE NOT EXISTS( WHERE NOT EXISTS(
SELECT 1 FROM reconciliation_runs SELECT 1 FROM reconciliation_runs
WHERE test_kb_id=$2 AND trigger='schedule' AND state IN ('running','succeeded') AND started_at >= $6 WHERE test_kb_id=$2 AND trigger='schedule' AND state IN ('running','succeeded','failed') AND started_at >= $6
) )
ON CONFLICT DO NOTHING ON CONFLICT DO NOTHING
RETURNING `+reconciliationRunColumns, RETURNING `+reconciliationRunColumns,
+46 -14
View File
@@ -278,11 +278,7 @@ func (s *Service) buildFindings(ctx context.Context, run governance.Reconciliati
if err != nil { if err != nil {
return nil, err return nil, err
} }
removalByPublication := make(map[string]bool, len(removal)) // 「需下架」的台账细节沿用上面按 publication 建的台账索引。
for _, row := range removal {
removalByPublication[row.PublicationID] = true
}
for _, row := range ledger { for _, row := range ledger {
if !expectedLive(row) { if !expectedLive(row) {
continue continue
@@ -305,15 +301,6 @@ func (s *Service) buildFindings(ctx context.Context, run governance.Reconciliati
if finding, ok := s.r4Finding(row, item, normalized); ok { if finding, ok := s.r4Finding(row, item, normalized); ok {
add(finding) add(finding)
} }
if removalByPublication[row.PublicationID] && item.ParseStatus == "completed" {
add(governance.ReconciliationFinding{
Type: "R6", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus, NormalizedState: normalized,
LedgerSHA256: row.SHA256, EvidenceLevel: "none", SuggestedAction: "enter_removal",
Detail: "来源已判禁止导入,条目仍在测试库可检索",
})
}
if row.ProcessingState == "cancelled" { if row.ProcessingState == "cancelled" {
if normalized != "cancelled" && ageFromPointer(run.StartedAt, row.ProcessingStartedAt, row.UpdatedAt) >= s.grace { if normalized != "cancelled" && ageFromPointer(run.StartedAt, row.ProcessingStartedAt, row.UpdatedAt) >= s.grace {
add(r5Finding(row, item, normalized, "none", "台账已取消,WeKnora 仍有活动状态")) add(r5Finding(row, item, normalized, "none", "台账已取消,WeKnora 仍有活动状态"))
@@ -355,6 +342,51 @@ func (s *Service) buildFindings(ctx context.Context, run governance.Reconciliati
} }
} }
// R6: 应下架仍在。判定口径 = removal_candidates 视图(与 /monitor/overview 的
// 「需下架」共用同一实现,陷阱 15)。这里直接由视图行生成,不再附加「本轮扫描
// 见到该条目」「上游 parse_status=completed」这类只有对账侧才有的条件——上游仍在
// processing/finalizing、或单条读取失败导致扫描缺行时,两处数字就会永久不一致。
for _, row := range removal {
finding := governance.ReconciliationFinding{
Type: "R6", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
// 视图只收录 processing_state='completed' 的台账行。
LedgerState: "completed", EvidenceLevel: "none", SuggestedAction: "enter_removal",
Detail: "来源已判禁止导入,条目仍在测试库可检索",
}
if own, ok := ledgerByPublication[row.PublicationID]; ok {
if finding.DocumentID == "" {
finding.DocumentID = own.KnowledgeID
}
if finding.Title == "" {
finding.Title = own.Title
}
if finding.Path == "" {
finding.Path = own.Path
}
if finding.Source == "" {
finding.Source = own.SourceName
}
if finding.TargetScope == "" {
finding.TargetScope = own.TargetScope
}
if own.ProcessingState != "" {
finding.LedgerState = own.ProcessingState
}
finding.LedgerSHA256 = own.SHA256
}
if item, ok := byID[finding.DocumentID]; ok {
if normalized, known := normalizeParseStatus(item.ParseStatus); known {
finding.NormalizedState = normalized
}
finding.WeKnoraParseState = item.ParseStatus
finding.WeKnoraFileMD5 = normalizeMD5(item.FileHash)
} else if finding.DocumentID != "" {
finding.Detail = "来源已判禁止导入;本轮扫描未见该条目,计数仍与总览「需下架」一致"
}
add(finding)
}
// R8: one publication id maps to more than one live row. // R8: one publication id maps to more than one live row.
grouped := make(map[string][]weknora.Knowledge) grouped := make(map[string][]weknora.Knowledge)
for _, item := range items { for _, item := range items {
+58
View File
@@ -480,3 +480,61 @@ func TestRemoveR2RechecksOwnershipAndTreats404AsSuccess(t *testing.T) {
t.Fatalf("owned removal err=%v hit=%t", err, store.removeHit) t.Fatalf("owned removal err=%v hit=%t", err, store.removeHit)
} }
} }
// TestExecuteRunR6UsesRemovalCandidatesViewOnly freezes 陷阱 15: R6 and
// /monitor/overview must read one implementation. An upstream document still
// processing/finalizing, or a single read that misses the listing, must not
// remove a row from the R6 set — otherwise the two pages report different
// "需下架" numbers for the same instant.
func TestExecuteRunR6UsesRemovalCandidatesViewOnly(t *testing.T) {
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
ledger := []governance.ReconciliationLedgerRow{
{PublicationID: "pub-a", KnowledgeID: "doc-a", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)},
{PublicationID: "pub-b", KnowledgeID: "doc-b", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)},
{PublicationID: "pub-c", KnowledgeID: "doc-c", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)},
}
items := []weknora.Knowledge{
{ID: "doc-a", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "processing", Metadata: map[string]any{"publication_id": "pub-a"}},
{ID: "doc-c", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-c"}},
}
store := &fakeReconciliationStore{
run: governance.ReconciliationRun{ID: "run-r6", KBID: "kb-1", State: "running", Trigger: "manual", StartedAt: now},
ledger: ledger,
// The view is the authority: it lists three rows, including one whose
// upstream document is still processing and one absent from the scan.
removal: []governance.ReconciliationLedgerRow{
{PublicationID: "pub-a", KnowledgeID: "doc-a"},
{PublicationID: "pub-b", KnowledgeID: "doc-b"},
{PublicationID: "pub-c", KnowledgeID: "doc-c"},
},
}
remote := &fakeReconciliationRemote{items: items, missing: map[string]bool{"doc-b": true}}
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now },
Grace: 30 * time.Minute, StallAfter: 2 * time.Hour, StaleAfter: 6 * time.Hour,
ConfirmConcurrency: 1, KeepRuns: 30, MaxAge: 90 * 24 * time.Hour,
WeKnoraWebBase: func(context.Context) string { return "https://test.example/" }})
if err != nil {
t.Fatal(err)
}
if err := service.ExecuteRun(context.Background(), "run-r6"); err != nil {
t.Fatal(err)
}
r6 := map[string]governance.ReconciliationFinding{}
for _, finding := range store.findings {
if finding.Type == "R6" {
r6[finding.PublicationID] = finding
}
}
if len(r6) != len(store.removal) {
t.Fatalf("R6 count = %d, removal candidates = %d; findings=%#v", len(r6), len(store.removal), store.findings)
}
if processing, ok := r6["pub-a"]; !ok || processing.WeKnoraParseState != "processing" || processing.NormalizedState != "processing" {
t.Fatalf("R6 must keep an upstream-processing row: %#v", processing)
}
if missing, ok := r6["pub-b"]; !ok || missing.DocumentID != "doc-b" {
t.Fatalf("R6 must keep a row the scan could not list: %#v", missing)
}
if store.completedRun == nil || store.completedRun.Counts["R6"] != len(store.removal) {
t.Fatalf("run counts R6 = %#v", store.completedRun)
}
}
+3
View File
@@ -110,6 +110,9 @@ def ready(directory, bundle, test_database=None):
env['WEKNORA_BINDING_MASTER_KEY_FILE'] = '/run/qa/binding-master.key' env['WEKNORA_BINDING_MASTER_KEY_FILE'] = '/run/qa/binding-master.key'
# 验收候选要连 QA 的测试 WeKnora(同网段明文 http),与生产部署口径一致。 # 验收候选要连 QA 的测试 WeKnora(同网段明文 http),与生产部署口径一致。
env['WEKNORA_ALLOW_PRIVATE_HTTP'] = 'true' env['WEKNORA_ALLOW_PRIVATE_HTTP'] = 'true'
# 导入对账(T6)只对测试库做,候选必须真的接线;它与旧的取件/上传链路
# (TEST_WEKNORA_ENABLED)解耦,租户 Key 走知识库绑定。
env['RECONCILIATION_ENABLED'] = 'true'
app_env = directory / 'app.env' app_env = directory / 'app.env'
cd.atomic_write(app_env, ''.join(f'{k}={v}\n' for k, v in env.items()).encode()) cd.atomic_write(app_env, ''.join(f'{k}={v}\n' for k, v in env.items()).encode())
names = {role: f'{project}-{role}' for role in cd.ROLES} names = {role: f'{project}-{role}' for role in cd.ROLES}
+22 -1
View File
@@ -366,9 +366,30 @@ def image_inspect(image):
return json.loads(run(['docker', 'image', 'inspect', image], 'read image identity'))[0] return json.loads(run(['docker', 'image', 'inspect', image], 'read image identity'))[0]
def container_log_tail(name, lines=5, limit=400):
"""Give the failure text a symptom, not just a verdict.
A non-running container used to surface only as "expected container is not
running"; the actual cause (missing zoneinfo, refused DSN, bad bind) lives in
the container log and was thrown away with the container.
"""
try:
result = subprocess.run(['docker', 'logs', '--tail', str(lines), name], capture_output=True, timeout=15)
except (OSError, subprocess.TimeoutExpired):
return 'no container log'
# docker CLI forwards the container's stderr to its own stderr; keep both.
text = ' '.join((result.stdout + result.stderr).decode('utf-8', 'replace').split())
return text[-limit:] if text else 'no container log'
def inspect(name): def inspect(name):
obj = json.loads(run(['docker', 'container', 'inspect', name], 'read running container'))[0] obj = json.loads(run(['docker', 'container', 'inspect', name], 'read running container'))[0]
require(obj['State']['Status'] == 'running' and matches(IMAGE, obj.get('Image')), 'expected container is not running') state = obj.get('State') or {}
if state.get('Status') != 'running':
raise CDError(f'{name}: container is {state.get("Status") or "unknown"} '
f'(exit {state.get("ExitCode")}); log: {container_log_tail(name)}')
require(matches(IMAGE, obj.get('Image')),
f'{name}: running image {obj.get("Image")!r} is not an approved image ID')
return obj return obj
+44 -1
View File
@@ -1,6 +1,7 @@
import { renderToStaticMarkup } from 'react-dom/server' import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest' import { describe, expect, it, vi } from 'vitest'
import { FindingDetail, ReconciliationFindingsView } from './ReconciliationFindings' import { FindingDetail, ReconciliationFindingsView, ServiceStrip } from './ReconciliationFindings'
import type { MonitorOverview } from './monitor'
import type { ReconciliationFinding, ReconciliationRun } from './reconciliationApi' import type { ReconciliationFinding, ReconciliationRun } from './reconciliationApi'
const run: ReconciliationRun = { const run: ReconciliationRun = {
@@ -114,3 +115,45 @@ describe('reconciliation findings', () => {
expect(html).toContain('在 WeKnora 中打开') expect(html).toContain('在 WeKnora 中打开')
}) })
}) })
describe('ServiceStrip queue availability', () => {
const overview = (queues: MonitorOverview['weknora_queues']) =>
({ weknora_queues: queues, health: [] }) as unknown as MonitorOverview
it('states an unavailable queue instead of rendering 0 waiting · 0 active', () => {
const html = renderToStaticMarkup(
<ServiceStrip
overview={overview({ available: false, queues_error: true, workers_error: false, queues: [], timestamp: 0 })}
/>
)
expect(html).toContain('队列不可用')
expect(html).not.toContain('0 等待')
})
it('prints queue depth when the queue is available', () => {
const html = renderToStaticMarkup(
<ServiceStrip
overview={overview({
available: true,
queues_error: false,
workers_error: false,
timestamp: 0,
queues: [
{
name: 'default',
pool: 'default',
pending: 2,
active: 1,
scheduled: 0,
retry: 0,
archived: 0,
processed: 0,
failed: 0,
},
],
})}
/>
)
expect(html).toContain('2 等待 · 1 运行')
})
})
+1 -1
View File
@@ -75,7 +75,7 @@ export function ServiceStrip({ overview }: { overview: MonitorOverview | null })
<section className="monitor-service-strip" aria-label="服务与队列"> <section className="monitor-service-strip" aria-label="服务与队列">
<span> <span>
WeKnora 队列: WeKnora 队列:
{queue ? ( {queue?.available ? (
<b> <b>
{queue.queues.reduce((sum, item) => sum + item.pending, 0)} 等待 ·{' '} {queue.queues.reduce((sum, item) => sum + item.pending, 0)} 等待 ·{' '}
{queue.queues.reduce((sum, item) => sum + item.active, 0)} 运行 {queue.queues.reduce((sum, item) => sum + item.active, 0)} 运行