Compare commits

...

6 Commits

Author SHA1 Message Date
Zhero & 助理 9eeb4c7206 fix(test-ingest): 上传记录 SQL 参数错位导致 test.upload 永远 state_conflict
build / build (push) Successful in 2m6s
recordUploadAndSchedulePollSQL 在加入 retry_count 幂等键后仍按旧顺序取参数:
payload 取到 $4(时间戳)→ 报 cannot cast timestamptz to jsonb,调用方把任何
error 都折成 test_upload_state_conflict,于是文件其实已经传上 0.9、对账面却
永远记不下来,publication 卡在 uploading。

- 参数按 $1..$8 对齐(payload $5 / priority $6 / available_at $7 / max $8);
- 记录失败时把底层原因带进 job.last_error,不再吞掉;
- 用隔离 PG 的集成用例验证:修复前 42846,修复后通过。
2026-12-03 18:10:31 +08:00
Zhero & 助理 5c2ba3e06f fix(weknora): 上传带上已发现的 X-Tenant-ID,TENANT_REQUIRED 不再误判为去重冲突
平台级 Key 访问 0.9 的租户资源需要 X-Tenant-ID。GET 调用会在 409 后发现并重放,
但 multipart 上传既没有带上这个头、也无法重放请求体,于是每次上传都拿到
409 TENANT_REQUIRED,再被 handler 当成「已存在的同一份文件」去认领,最终
test.upload 连续失败、publication 停在 pending/uploading。

- UploadFile 复用 BeginTask 已发现的 workspace 头;
- 上传的 409 若携带 TENANT_REQUIRED,按普通 409 失败处理,不再返回 ErrConflict;
- test.upload 重试耗尽时把 publication 标为 failed,重试入口不再永远 409。
2026-12-03 18:03:32 +08:00
Zhero & 助理 efa26813dd fix(fetch): 钉钉取件按命令族传翻页开关与完成标记
build / build (push) Successful in 1m53s
dws 的 wiki 与 drive 两族参数不同:wiki +node-list 用 --page-limit 且给
data.autoPageComplete;drive +list 用 --max-pages,完成证据在
meta.pagination.endpoint_exhausted。取件脚本曾把 --page-limit 同时传给
drive +list,得到 unknown flag: --page-limit(classified unknown,终态
artifact_invalid,重试/重新入队都是同一个错误),修好后又因缺少 drive 的
完成标记被误判 source_lookup_incomplete 而永远可重试。

钉盘(space 为纯数字)来源的取件因此 100% 失败;改为按命令族分参数、并按
两族各自的完成标记判定目录已读完。
2026-12-03 14:29:06 +08:00
Zhero & 助理 371d8a60a0 fix(monitoring): 整库被顶替的库不再出现在对账下拉
build / build (push) Successful in 1m59s
概览按 test_kb_id 分组时只对计数加了 superseded 过滤,分组行本身还在,
于是一个已经删掉、8 条发布全被顶替的测试库仍以「0 条」的身份出现,
并继续作为导入对账的候选库。分组前先把历史行排除。
2026-12-03 11:40:10 +08:00
Zhero & 助理 bceb7ba682 fix(reconciliation): 区分知识库已删除与连接失败
台账里会残留已被删除的测试库(test_publications.test_kb_id 聚合出下拉候选),
页面默认又取排序最靠前的一项,于是「立即对账」打在死库上,远端回 404 被统一
映射成 remote_unavailable,页面提示「检查地址与 Key」——把工程师引去改一个根本
没坏的配置。

- 后端:BeginTask 的 404 单独落 remote_kb_missing,其余仍为 remote_unavailable
- 前端:新增文案「所选测试知识库已不存在」;默认选中当前绑定的测试库并在下拉里
  标注(当前绑定),用户自己选过(含「全部测试库」)后不再改写
2026-12-03 11:35:35 +08:00
zheromiku c1bdbe181e Merge pull request 'fix(reconciliation): 平台 Key 自动带工作空间访问租户资源 (CYWL-37)' (#53) from hifox-agent/assistant/CYWL-37-workspace into main
build / build (push) Successful in 1m45s
Merge pull request #53 from hifox-agent/assistant/CYWL-37-workspace
2026-12-02 16:26:54 +08:00
12 changed files with 218 additions and 13 deletions
+3
View File
@@ -161,6 +161,9 @@ FROM test_publications p
JOIN source_item_versions version ON version.id=p.source_item_version_id
JOIN source_items item ON item.id=version.source_item_id
LEFT JOIN removal_candidates removal_candidate ON removal_candidate.publication_id=p.id
-- 整库都被顶替过的 KB 只剩历史行:不排除就仍会占一行「0 条」,
-- 还会出现在导入对账的库下拉里,点下去直接打在已删除的库上。
WHERE p.superseded_at IS NULL
GROUP BY p.test_kb_id
ORDER BY p.test_kb_id`)
if err != nil {
+15
View File
@@ -128,6 +128,21 @@ SET publication_id = EXCLUDED.publication_id,
resolution_reason = '',
created_at = EXCLUDED.created_at
RETURNING job_id
), parked_publication AS (
-- 上传重试耗尽时把对账面同步成失败:否则 publication 停在
-- pending/uploading,重试入口(要求 failed/stalled)永远 409,
-- 页面上的「重试」看起来点了没反应。
UPDATE test_publications p
SET ingest_state = CASE WHEN p.ingest_state = 'uploading' THEN 'failed' ELSE p.ingest_state END,
processing_state = 'failed',
last_error = $3,
updated_at = $4
FROM updated
WHERE updated.state = 'failed'
AND updated.type = 'test.upload'
AND updated.payload->>'publication_id' = p.id
AND p.knowledge_id = ''
RETURNING p.id
)
SELECT id FROM updated
`
@@ -273,8 +273,8 @@ WITH updated AS (
max_attempts, idempotency_key, created_at, updated_at
)
SELECT 'job-' || substring(md5($1 || '#test.poll#' || updated.retry_count || '#1') from 1 for 32),
'test.poll', $4::jsonb, 'pending', $5, $6, $7,
'test-poll:' || $1 || ':' || updated.retry_count || ':1', $3, $3
'test.poll', $5::jsonb, 'pending', $6, $7, $8,
'test-poll:' || $1 || ':' || updated.retry_count || ':1', $4, $4
FROM updated
ON CONFLICT (idempotency_key) DO NOTHING
)
+20 -2
View File
@@ -232,6 +232,13 @@ func (c *Client) UploadFile(ctx context.Context, request UploadRequest) (Knowled
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("X-API-Key", c.apiKey)
// A platform-scoped key is refused with 409 TENANT_REQUIRED until it names a
// workspace, and a multipart body cannot be replayed: the workspace has to be
// attached here, from the one BeginTask already discovered. Leaving it off
// turned every upload into a "conflict" that the handler read as a duplicate.
if tenant := c.currentTenant(); tenant != "" {
req.Header.Set("X-Tenant-ID", tenant)
}
resp, err := c.httpClient.Do(req)
if err != nil {
_ = pipeReader.CloseWithError(err)
@@ -245,8 +252,19 @@ func (c *Client) UploadFile(ctx context.Context, request UploadRequest) (Knowled
var response knowledgeResponse
if resp.StatusCode == http.StatusConflict {
if err := c.decodeBody(resp, &response); err != nil {
return Knowledge{}, err
payload, readErr := io.ReadAll(io.LimitReader(resp.Body, c.maxResponseBytes+1))
resp.Body.Close()
if readErr != nil {
return Knowledge{}, errors.New("read WeKnora response")
}
// TENANT_REQUIRED shares the 409 status with a real duplicate. Reading it
// as ErrConflict made the caller adopt a "duplicate" that never existed,
// so it is reported as a bare 409 and dead-letters with a clear reason.
if bytes.Contains(payload, []byte(`"TENANT_REQUIRED"`)) {
return Knowledge{}, &HTTPError{StatusCode: http.StatusConflict}
}
if err := json.Unmarshal(payload, &response); err != nil {
return Knowledge{}, errors.New("decode WeKnora response")
}
return response.Data, ErrConflict
}
+100
View File
@@ -555,6 +555,106 @@ func TestClientTenantKeyNeverSendsWorkspaceHeader(t *testing.T) {
}
}
// A multipart upload cannot be replayed, so the workspace that BeginTask
// discovered has to ride on the upload request itself. Without it a 0.9
// platform key gets 409 TENANT_REQUIRED and the caller reads that as a
// duplicate document.
func TestUploadFileSendsDiscoveredWorkspace(t *testing.T) {
const apiKey = "platform" + "-key"
var uploadTenant atomic.Value
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/tenants/all":
_, _ = w.Write([]byte(`{"success":true,"data":{"items":[{"id":10000}]}}`))
case "/api/v1/knowledge-bases/kb-1":
if r.Header.Get("X-Tenant-ID") != "10000" {
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED","error":"Workspace required"}`))
return
}
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-1","tenant_id":10000}}`))
case "/api/v1/knowledge-bases/kb-1/knowledge/file":
uploadTenant.Store(r.Header.Get("X-Tenant-ID"))
if r.Header.Get("X-Tenant-ID") != "10000" {
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED","error":"Workspace required"}`))
return
}
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"knowledge-1","knowledge_base_id":"kb-1","parse_status":"processing"}}`))
default:
t.Fatalf("unexpected path %s", r.URL.Path)
}
}))
defer server.Close()
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: apiKey, Timeout: time.Second})
if err != nil {
t.Fatal(err)
}
if _, err := client.GetKnowledgeBase(context.Background(), "kb-1"); err != nil {
t.Fatalf("GetKnowledgeBase() error = %v", err)
}
knowledge, err := client.UploadFile(context.Background(), UploadRequest{
KnowledgeBaseID: "kb-1",
FileName: "doc.pdf",
Content: strings.NewReader("%PDF-1.4"),
})
if err != nil || knowledge.ID != "knowledge-1" {
t.Fatalf("UploadFile() = %#v, %v", knowledge, err)
}
if got, _ := uploadTenant.Load().(string); got != "10000" {
t.Fatalf("upload X-Tenant-ID = %q, want 10000", got)
}
}
// A workspace refusal on the upload is not a duplicate: it must surface as a
// plain 409 so the handler dead-letters it with a readable reason.
func TestUploadFileTenantRequiredIsNotDuplicate(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED","error":"Workspace required"}`))
}))
defer server.Close()
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: "platform-key", Timeout: time.Second})
if err != nil {
t.Fatal(err)
}
_, err = client.UploadFile(context.Background(), UploadRequest{
KnowledgeBaseID: "kb-1",
FileName: "doc.pdf",
Content: strings.NewReader("%PDF-1.4"),
})
if errors.Is(err, ErrConflict) {
t.Fatalf("TENANT_REQUIRED was reported as a duplicate conflict: %v", err)
}
var httpErr *HTTPError
if !errors.As(err, &httpErr) || httpErr.StatusCode != http.StatusConflict {
t.Fatalf("UploadFile() error = %v, want HTTPError 409", err)
}
}
// A real duplicate still reports ErrConflict so the handler can adopt the
// existing knowledge instead of dead-lettering.
func TestUploadFileKeepsDuplicateConflict(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{"success":false,"data":{"id":"knowledge-9","knowledge_base_id":"kb-1","file_hash":"abc"}}`))
}))
defer server.Close()
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: "tenant-key", Timeout: time.Second})
if err != nil {
t.Fatal(err)
}
knowledge, err := client.UploadFile(context.Background(), UploadRequest{
KnowledgeBaseID: "kb-1",
FileName: "doc.pdf",
Content: strings.NewReader("%PDF-1.4"),
})
if !errors.Is(err, ErrConflict) || knowledge.ID != "knowledge-9" {
t.Fatalf("UploadFile() = %#v, %v want duplicate conflict", knowledge, err)
}
}
// An upload conflict keeps its own meaning: 409 without TENANT_REQUIRED is not
// treated as a workspace refusal.
func TestTenantRequiredIgnoresPlainConflict(t *testing.T) {
+12
View File
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"time"
"knowledge-governance/internal/governance"
@@ -42,6 +43,14 @@ func RuntimeErrorCode(err error) string {
}
}
// knowledgeBaseMissing 只认 WeKnora 明确回答的 404 —— 库被删掉、或 ID 属于
// 别的环境/租户。它与网络不通、Key 无权限要分开:这三种情况的处置完全不同,
// 页面把 404 说成「检查地址与 Key」会让工程师去改一个根本没坏的配置。
func knowledgeBaseMissing(err error) bool {
var httpErr *weknora.HTTPError
return errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusNotFound
}
type Store interface {
ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error)
ClaimReconciliationRun(context.Context, governance.ReconciliationRun, time.Time) (governance.ReconciliationRun, error)
@@ -268,6 +277,9 @@ func (s *Service) ExecuteRun(ctx context.Context, runID string) error {
}
pinned, _, err := s.remote.BeginTask(ctx, run.KBID)
if err != nil {
if knowledgeBaseMissing(err) {
return finished("remote_kb_missing")
}
return finished("remote_unavailable")
}
ledger, err := s.store.LoadReconciliationLedger(pinned, run.KBID)
+22
View File
@@ -145,6 +145,7 @@ type fakeReconciliationRemote struct {
missing map[string]bool
gets map[string]weknora.Knowledge
listErr error
beginErr error
pageSizes []int
deleteCalls int
listInFlight int
@@ -152,6 +153,9 @@ type fakeReconciliationRemote struct {
}
func (f *fakeReconciliationRemote) BeginTask(ctx context.Context, _ string) (context.Context, weknora.InstanceIdentity, error) {
if f.beginErr != nil {
return ctx, weknora.InstanceIdentity{}, f.beginErr
}
return ctx, weknora.InstanceIdentity{BaseURL: "https://test.example", TenantID: 7}, nil
}
func (f *fakeReconciliationRemote) ListKnowledge(_ context.Context, _ string, _ int, pageSize int) ([]weknora.Knowledge, int64, error) {
@@ -395,6 +399,24 @@ func (r *concurrencyRemote) GetKnowledge(context.Context, string) (weknora.Knowl
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
}
// 库被删掉时,远端回的是 404,不是网络故障。批次必须落成 remote_kb_missing,
// 页面才能提示「去选当前绑定的库」,而不是让人去改没坏的地址与 Key。
func TestExecuteRunReportsMissingKnowledgeBase(t *testing.T) {
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
store := &fakeReconciliationStore{run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-gone", State: "running", StartedAt: now}}
remote := &fakeReconciliationRemote{beginErr: &weknora.HTTPError{StatusCode: 404}}
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
if err := service.ExecuteRun(context.Background(), "run-1"); err != nil {
t.Fatal(err)
}
if store.failCode != "remote_kb_missing" {
t.Fatalf("fail code = %q", store.failCode)
}
}
func TestExecuteRunFailsWholeBatchWithoutFindings(t *testing.T) {
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
store := &fakeReconciliationStore{run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", State: "running", StartedAt: now}}
+3 -2
View File
@@ -7,6 +7,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"path/filepath"
"strings"
@@ -123,7 +124,7 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
uploadMD5, _ := handler.hashSpool(candidate)
now := handler.now()
if _, err := handler.store.RecordUploadAndSchedulePoll(ctx, candidate.ID, knowledge.ID, uploadMD5, now, now.Add(handler.firstPollDelay)); err != nil {
return ErrUploadStateConflict
return fmt.Errorf("%w: %v", ErrUploadStateConflict, err)
}
return nil
}
@@ -194,7 +195,7 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
}
now := handler.now()
if _, err := handler.store.RecordUploadAndSchedulePoll(ctx, candidate.ID, knowledge.ID, uploadMD5, now, now.Add(handler.firstPollDelay)); err != nil {
return ErrUploadStateConflict
return fmt.Errorf("%w: %v", ErrUploadStateConflict, err)
}
return nil
}
+13 -2
View File
@@ -404,7 +404,12 @@ def dingtalk_live_raw_key(manifest):
for index in range(len(parts)):
drive = space_id.isdigit()
args = ['drive', '+list', '--space-id', space_id] if drive else ['wiki', '+node-list', '--workspace', space_id]
args += ['--page-all', '--limit', '50', '--max-items', '10000', '--page-limit', '200']
# 翻页上限开关按命令族不同:wiki 叫 --page-limit,drive +list 叫 --max-pages。
# 混用会得到 `unknown flag: --page-limit`,被分类成 unknown 而成为终态失败。
if drive:
args += ['--page-all', '--limit', '50', '--max-items', '10000', '--max-pages', '200']
else:
args += ['--page-all', '--limit', '50', '--max-items', '10000', '--page-limit', '200']
if folder:
args += ['--folder', folder]
payload, verdict = dws_run(args, timeout=180)
@@ -412,7 +417,13 @@ def dingtalk_live_raw_key(manifest):
raise _dws_error(verdict)
data = payload.get('data', {}) if isinstance(payload, dict) else {}
entries = data.get('files' if drive else 'nodes')
if not isinstance(entries, list) or data.get('hasMore') is not False or data.get('autoPageComplete') is not True:
# 两族命令的“翻完了”证据不同:wiki 给 data.autoPageComplete,drive +list 只在
# meta.pagination.endpoint_exhausted 里给。缺这一条会被当成目录读不全而永远可重试。
meta = payload.get('meta') if isinstance(payload, dict) else None
pagination = meta.get('pagination') if isinstance(meta, dict) else None
exhausted = (data.get('autoPageComplete') is True
or (isinstance(pagination, dict) and pagination.get('endpoint_exhausted') is True))
if not isinstance(entries, list) or data.get('hasMore') is not False or not exhausted:
raise FetchError('DingTalk directory response is incomplete', retryable=True, code='source_lookup_incomplete')
matches = []
for entry in entries:
+20 -5
View File
@@ -606,6 +606,12 @@ export function WeKnoraMonitor({
const [findingFilters, setFindingFilters] = useState<FindingFilters>({ type: '', q: '' })
const [findingOffset, setFindingOffset] = useState(0)
const [selectedKB, setSelectedKB] = useState('')
// 下拉里的候选来自台账(test_publications.test_kb_id),可能包含早已被删掉的
// 测试库。默认值必须落在「当前绑定的测试库」上,否则一进页面点立即对账就会
// 打在死库上,远端只回 404。
const [boundKB, setBoundKB] = useState('')
const [bindingReady, setBindingReady] = useState(false)
const kbPickedRef = useRef(false)
const [findingDetail, setFindingDetail] = useState<ReconciliationFinding | null>(null)
const [reconLoading, setReconLoading] = useState(true)
const [reconBusy, setReconBusy] = useState(false)
@@ -727,9 +733,10 @@ export function WeKnoraMonitor({
return () => c.abort()
}, [resRev])
useEffect(() => {
if (selectedKB || !overview?.knowledge_bases.length) return
setSelectedKB(overview.knowledge_bases[0].id)
}, [overview, selectedKB])
if (kbPickedRef.current || !bindingReady || !overview?.knowledge_bases.length) return
const ids = overview.knowledge_bases.map((item) => item.id)
setSelectedKB(boundKB && ids.includes(boundKB) ? boundKB : ids[0])
}, [overview, bindingReady, boundKB])
// 绑定快照与批次列表分开取:批次列表成功会清空 reconError,不能把
// 「测试环境未配置」也塞进同一个 state,否则一刷新就消失。
useEffect(() => {
@@ -738,12 +745,17 @@ export function WeKnoraMonitor({
void fetchKBBindings(c.signal)
.then((snapshot) => {
if (!c.signal.aborted) {
setBoundKB(snapshot.test.internal_kb_id)
setBindingReady(true)
setBindingError(isTestBindingMissing(snapshot) ? reconciliationMessages.bindingMissing : '')
}
})
.catch(() => {
// 预检失败不阻塞页面:真正触发时仍由批次错误兜底。
if (!c.signal.aborted) setBindingError('')
if (!c.signal.aborted) {
setBindingReady(true)
setBindingError('')
}
})
return () => c.abort()
}, [tab, reconRev])
@@ -954,7 +966,10 @@ export function WeKnoraMonitor({
filters={findingFilters}
selectedRunID={selectedRunID}
selectedKB={selectedKB}
kbOptions={(overview?.knowledge_bases || []).map((item) => ({ id: item.id, name: item.name }))}
kbOptions={(overview?.knowledge_bases || []).map((item) => ({
id: item.id,
name: item.id === boundKB ? `${item.name}(当前绑定)` : item.name,
}))}
loading={reconLoading}
busy={reconBusy}
canOperate={canOperate}
+6
View File
@@ -41,6 +41,12 @@ describe('reconciliation error copy', () => {
}
})
it('distinguishes a deleted knowledge base from a broken binding', () => {
expect(reconciliationFailureText('remote_kb_missing')).toBe(reconciliationMessages.remoteKBMissing)
expect(reconciliationFailureText('remote_unavailable')).toBe(reconciliationMessages.remoteFailed)
expect(reconciliationMessages.remoteKBMissing).not.toBe(reconciliationMessages.remoteFailed)
})
it('falls back to Chinese for an unknown code instead of echoing it', () => {
expect(reconciliationFailureText('some_new_code')).toBe(reconciliationMessages.generic)
expect(reconciliationFailureText('some_new_code')).not.toContain('some_new_code')
+2
View File
@@ -13,6 +13,7 @@ export const reconciliationMessages = {
runInProgress: '该测试知识库已有对账批次在运行,请等本轮结束后再试',
stateChanged: '记录状态已变化,请刷新后重试',
remoteFailed: '测试知识库连接失败:请检查系统设置 → 知识库绑定中的测试环境地址与 Key',
remoteKBMissing: '所选测试知识库在 WeKnora 中已不存在(可能已被删除),请改选当前绑定的测试库',
queueUnavailable: '对账任务队列不可用,请联系管理员',
ledgerUnavailable: '台账读取失败,请稍后重试或联系管理员',
overlapCheckFailed: '无法确认整库作业状态,请稍后重试',
@@ -27,6 +28,7 @@ const failureMessages: Record<string, string> = {
reconciliation_not_configured: reconciliationMessages.notEnabled,
reconciliation_failed: reconciliationMessages.generic,
reconciliation_remote_failed: reconciliationMessages.remoteFailed,
remote_kb_missing: reconciliationMessages.remoteKBMissing,
remote_unavailable: reconciliationMessages.remoteFailed,
remote_scan_failed: reconciliationMessages.remoteFailed,
remote_confirm_failed: reconciliationMessages.remoteFailed,