Compare commits

..

8 Commits

Author SHA1 Message Date
zheromiku e5040d88d8 Merge pull request 'fix(reconciliation): 处置视图列名限定 + 非法 document_id 返回 400(CYWL-34)' (#50) from fix/t6-action-view-and-path into main
build / build (push) Has started running
Merge pull request 'fix(reconciliation): 处置视图列名限定 + 非法 document_id 返回 400(CYWL-34)' (#50) from fix/t6-action-view-and-path into main
2026-12-01 20:39:22 +08:00
zheromiku 839b4ca2cf fix(reconciliation): 处置视图列名限定,非法 document_id 返回 400
build / build (push) Successful in 1m57s
QA 在候选上实测出两条:
- P0 处置接口 500:LoadReconciliationActionView 的 SELECT 用了未限定的
  reconciliationFindingColumns,而语句 JOIN 了 reconciliation_runs 与
  test_publications(两者也有 id/title/path/source),PostgreSQL 直接报
  column reference "id" is ambiguous,writeback/requeue/remove 全部 500。
  改为按别名限定列(qualifiedFindingColumns),补真库集成用例。
- R-102 契约偏差:空的 document_id 被多段路由规范化成 307、含未编码斜杠的 id
  落到 404,契约要求 400。补子树兜底路由,并在鉴权之后加 guard 把 // 路径拦成 400
  (未登录仍是 401),补接口用例。
2026-12-01 20:36:57 +08:00
zheromiku b662520439 Merge pull request 'fix(reconciliation): worker 在对账接线时注册 reconciliation.run(CYWL-34)' (#49) from fix/t6-worker-handler-gate into main
build / build (push) Successful in 2m3s
Merge pull request 'fix(reconciliation): worker 在对账接线时注册 reconciliation.run(CYWL-34)' (#49) from fix/t6-worker-handler-gate into main
2026-12-01 20:15:25 +08:00
zheromiku 9258aa8273 fix(reconciliation): worker 在对账接线时也要注册 reconciliation.run
build / build (push) Successful in 3m5s
候选(9dddda84)实测:批次能建、入队也成功(jobs 里有 pending 行),但 worker
从不认领——worker_heartbeats.job_types 里根本没有 reconciliation.run。
原因:该 handler 注册在 workerHandlers 的测试库取件块里,而这一块在
!TEST_WEKNORA_ENABLED 时直接 return,于是只开 RECONCILIATION_ENABLED 的候选
只有 API 接线、worker 空转,批次停在 running 直到 6h 僵死回收。

把注册移到那个早退之前:只依赖 reconciliationService(租户 Key 走知识库绑定),
与旧取件/上传链路解耦。
2026-12-01 20:11:59 +08:00
zheromiku 9dddda8491 Merge pull request 'fix(reconciliation): 对账任务入队 id 超长导致每批 queue_unavailable(CYWL-34)' (#48) from fix/t6-enqueue-job-id into main
build / build (push) Successful in 2m17s
Merge pull request 'fix(reconciliation): 对账任务入队 id 超长导致每批 queue_unavailable(CYWL-34)' (#48) from fix/t6-enqueue-job-id into main
2026-12-01 19:49:51 +08:00
zheromiku 28fb449d17 Merge pull request 'fix(reconciliation): 定时批占位语句修 42P08(CYWL-34)' (#47) from fix/t6-schedule-claim-42p08 into main
build / build (push) Successful in 2m28s
Merge pull request 'fix(reconciliation): 定时批占位语句修 42P08(CYWL-34)' (#47) from fix/t6-schedule-claim-42p08 into main
2026-12-01 19:14:44 +08:00
zheromiku f45b6fc8c9 Merge pull request 'fix(reconciliation): R6 改用 removal_candidates 视图 + 定时批每日一位(CYWL-34)' (#46) from fix/t6-r6-count-and-scheduler into main
build / build (push) Successful in 1m58s
Merge pull request 'fix(reconciliation): R6 改用 removal_candidates 视图 + 定时批每日一位(CYWL-34)' (#46) from fix/t6-r6-count-and-scheduler into main
2026-12-01 18:58:58 +08:00
zheromiku dc28f0b65c Merge pull request 'fix(reconciliation): 用 RECONCILIATION_ENABLED 独立接线对账服务(CYWL-34)' (#45) from fix/t6-reconciliation-switch into main
build / build (push) Successful in 2m55s
Merge pull request 'fix(reconciliation): 用 RECONCILIATION_ENABLED 独立接线对账服务(CYWL-34)' (#45) from fix/t6-reconciliation-switch into main
2026-12-01 18:37:51 +08:00
5 changed files with 115 additions and 14 deletions
+15 -11
View File
@@ -619,6 +619,21 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindi
}
handlers["source.scan.pp"] = handler.Handle
}
// 导入对账的作业处理器只依赖对账服务本身(租户 Key 走知识库绑定),
// 与旧测试库取件/上传链路(TEST_WEKNORA_ENABLED)无关,必须在下面那个
// 早退之前注册;否则 RECONCILIATION_ENABLED=true 时候选只接线了 API,
// worker 从不认领 reconciliation.run,批次永远停在 running。
if reconciliationService != nil {
handlers["reconciliation.run"] = func(handlerCtx context.Context, job jobs.Job) error {
var payload struct {
RunID string `json:"run_id"`
}
if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.RunID == "" {
return jobs.Permanent(jobs.ErrCodeHandlerFallback, errors.New("invalid reconciliation run payload"))
}
return reconciliationService.ExecuteRun(handlerCtx, payload.RunID)
}
}
if !config.TestWeKnoraEnabled || !config.LibraryWorkerRole.ExecutesSourceWork() {
return handlers, nil
}
@@ -695,17 +710,6 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindi
handlers["test.poll"] = poll.Handle
handlers["test.validate"] = validate.Handle
handlers["test.remove"] = remove.Handle
if reconciliationService != nil {
handlers["reconciliation.run"] = func(handlerCtx context.Context, job jobs.Job) error {
var payload struct {
RunID string `json:"run_id"`
}
if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.RunID == "" {
return jobs.Permanent(jobs.ErrCodeHandlerFallback, errors.New("invalid reconciliation run payload"))
}
return reconciliationService.ExecuteRun(handlerCtx, payload.RunID)
}
}
return handlers, nil
}
+18
View File
@@ -126,3 +126,21 @@ func TestReconciliationFindingTypeValidation(t *testing.T) {
t.Fatalf("invalid type = %d", recorder.Code)
}
}
func TestReconciliationProgressRejectsMalformedDocumentIDWith400(t *testing.T) {
service := &reconciliationServiceStub{}
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: service})
if err != nil {
t.Fatal(err)
}
for _, path := range []string{
"/api/v1/reconciliation/documents//progress",
"/api/v1/reconciliation/documents/doc-1/extra/progress",
} {
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, reconciliationRequest(http.MethodGet, path, roleViewer, ""))
if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), "invalid document id") {
t.Fatalf("%s = %d %s, want 400 invalid document id", path, recorder.Code, recorder.Body.String())
}
}
}
+19 -2
View File
@@ -855,15 +855,32 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("POST /api/v1/job-failures/{id}/requeue", func(w http.ResponseWriter, r *http.Request) {
requeueJobFailure(w, r, config)
})
// 契约要求非法 document_id 返回 400:空段(documents//progress)会被 ServeMux
// 规范化成 307,含未编码斜杠的 id 会落到 404。这里在路由前判定形状,且不新增
// 端点(契约已冻结);放在鉴权之后,未登录仍是 401,保持 401 → 400 的顺序。
guard := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
const prefix = "/api/v1/reconciliation/documents/"
if strings.HasPrefix(r.URL.Path, prefix) {
rest := strings.TrimPrefix(r.URL.Path, prefix)
segments := strings.Split(rest, "/")
if strings.Contains(r.URL.Path, "//") || len(segments) != 2 || segments[0] == "" || segments[1] != "progress" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid document id"})
return
}
}
next.ServeHTTP(w, r)
})
}
if config.Auth != nil {
if config.Auth.Store == nil {
return nil, errors.New("auth configuration requires a store")
}
config.authRoutes(mux)
config.userRoutes(mux)
return masterNoStore(config.Auth.authenticate(mux)), nil
return masterNoStore(config.Auth.authenticate(guard(mux))), nil
}
return masterNoStore(mux), nil
return masterNoStore(guard(mux)), nil
}
type createJobRequest struct {
@@ -112,3 +112,51 @@ func TestScheduledReconciliationClaimsOncePerDayAfterFailure(t *testing.T) {
t.Fatalf("next-day claim claimed=%t err=%v", claimed, err)
}
}
// TestLoadReconciliationActionViewJoinsWithoutAmbiguity freezes the action-view
// SQL: it joins reconciliation_runs and test_publications, both of which also
// own id/title/path, so an unqualified column list fails with
// `column reference "id" is ambiguous` and every writeback/requeue/remove
// answered 500 instead of touching the finding.
func TestLoadReconciliationActionViewJoinsWithoutAmbiguity(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)
}
started := time.Date(2026, 12, 1, 2, 0, 0, 0, time.UTC)
exec := func(query string, args ...any) {
t.Helper()
if _, err := pool.Exec(ctx, query, args...); err != nil {
t.Fatal(err)
}
}
exec(`INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-action','dingtalk','处置视图用例',TRUE)`)
exec(`INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,policy_state)
VALUES('si-action','conn-action','action.md',repeat('d',64),'处置视图','file','blocked')`)
exec(`INSERT INTO source_item_versions(id,source_item_id,revision,content_state) VALUES('sv-action','si-action','r1','verified')`)
exec(`INSERT INTO test_publications(id,source_item_version_id,test_kb_id,knowledge_id,ingest_state,processing_state,retrieval_state)
VALUES('pub-action','sv-action','kb-action','doc-action','uploaded','completed','unpublished')`)
exec(`INSERT INTO reconciliation_runs(id,test_kb_id,state,trigger,started_at,counts,created_at)
VALUES('run-action','kb-action','succeeded','manual',$1,'{}'::jsonb,$1)`, started)
exec(`INSERT INTO reconciliation_findings(id,run_id,finding_type,publication_id,knowledge_id,title,ledger_state,suggested_action)
VALUES('finding-action','run-action','R6','pub-action','doc-action','处置视图','completed','enter_removal')`)
store := NewStore(pool)
view, err := store.LoadReconciliationActionView(ctx, "finding-action")
if err != nil {
t.Fatalf("action view error = %v (ambiguous columns surface here)", err)
}
if view.TestKBID != "kb-action" || !view.CurrentExists || view.CurrentProcessingState != "completed" ||
view.CurrentKnowledgeID != "doc-action" || view.Finding.ID != "finding-action" {
t.Fatalf("action view = %#v", view)
}
}
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5"
@@ -315,6 +316,19 @@ const reconciliationFindingColumns = `id,run_id,finding_type,publication_id,know
target_scope,ledger_state,weknora_parse_status,normalized_state,ledger_sha256,declared_sha256,
weknora_file_md5,evidence_level,confirmation_state,detail,suggested_action,action_state,weknora_url`
// qualifiedFindingColumns prefixes every column with the table alias. A bare
// column list breaks as soon as the finding is joined with reconciliation_runs
// or test_publications: those tables also have id/title/path/source, so
// PostgreSQL rejects the statement with "column reference \"id\" is ambiguous"
// and every writeback/requeue/remove answered 500.
func qualifiedFindingColumns(alias string) string {
columns := strings.Split(reconciliationFindingColumns, ",")
for index, column := range columns {
columns[index] = alias + "." + strings.TrimSpace(column)
}
return strings.Join(columns, ",")
}
func scanReconciliationFinding(row rowScanner) (governance.ReconciliationFinding, error) {
var finding governance.ReconciliationFinding
if err := row.Scan(&finding.ID, &finding.RunID, &finding.Type, &finding.PublicationID, &finding.DocumentID,
@@ -390,7 +404,7 @@ func lockOpenReconciliationFinding(ctx context.Context, tx pgx.Tx, id string) er
func (s *Store) LoadReconciliationActionView(ctx context.Context, findingID string) (governance.ReconciliationActionView, error) {
var view governance.ReconciliationActionView
var currentExists bool
row := s.db.QueryRow(ctx, `SELECT `+reconciliationFindingColumns+`,
row := s.db.QueryRow(ctx, `SELECT `+qualifiedFindingColumns("finding")+`,
run.test_kb_id,run.started_at,
publication.id IS NOT NULL,
COALESCE(publication.processing_state,''),COALESCE(publication.knowledge_id,''),