From 5c2ba3e06fa25290989eae846ca40355a2af0ce7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zhero=20=26=20=E5=8A=A9=E7=90=86?= Date: Thu, 3 Dec 2026 18:03:32 +0800 Subject: [PATCH] =?UTF-8?q?fix(weknora):=20=E4=B8=8A=E4=BC=A0=E5=B8=A6?= =?UTF-8?q?=E4=B8=8A=E5=B7=B2=E5=8F=91=E7=8E=B0=E7=9A=84=20X-Tenant-ID?= =?UTF-8?q?=EF=BC=8CTENANT=5FREQUIRED=20=E4=B8=8D=E5=86=8D=E8=AF=AF?= =?UTF-8?q?=E5=88=A4=E4=B8=BA=E5=8E=BB=E9=87=8D=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 平台级 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。 --- internal/platform/postgres/queue_sql.go | 15 ++++ internal/platform/weknora/client.go | 22 ++++- internal/platform/weknora/client_test.go | 100 +++++++++++++++++++++++ 3 files changed, 135 insertions(+), 2 deletions(-) diff --git a/internal/platform/postgres/queue_sql.go b/internal/platform/postgres/queue_sql.go index 909e3f5..e5e4ef4 100644 --- a/internal/platform/postgres/queue_sql.go +++ b/internal/platform/postgres/queue_sql.go @@ -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 ` diff --git a/internal/platform/weknora/client.go b/internal/platform/weknora/client.go index 590bb47..5488fa8 100644 --- a/internal/platform/weknora/client.go +++ b/internal/platform/weknora/client.go @@ -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 } diff --git a/internal/platform/weknora/client_test.go b/internal/platform/weknora/client_test.go index f082d2e..63ebdcc 100644 --- a/internal/platform/weknora/client_test.go +++ b/internal/platform/weknora/client_test.go @@ -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) {