fix(fetch): 修复钉钉来源身份与取件失败监控
build / build (push) Successful in 1m17s

This commit is contained in:
姚章浩
2026-10-27 14:36:24 +08:00
parent 1b09f7d35b
commit 74aef1e373
8 changed files with 211 additions and 9 deletions
@@ -0,0 +1,53 @@
package postgres
import (
"context"
"os"
"os/exec"
"path/filepath"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/workflows/artifactfetch"
)
func TestArtifactManifestCurrentSourceIntegration(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)
}
if _, err = pool.Exec(ctx, `INSERT INTO source_connections(id,source_type,name,base_url) VALUES('conn-live','dingtalk','Renamed KB','spaces/workspace1?space=workspace1');
INSERT INTO catalog_import_intents(source_connection_id,node_id,visibility,decided_by,relative_path,name,locator_hash,fetch_state) VALUES('conn-live','sn-live','internal','tester','Folder/Manual.adoc','Manual.adoc',repeat('a',64),'pending')`); err != nil {
t.Fatal(err)
}
manifest, err := NewStore(pool).LoadArtifactFetchManifest(ctx, "conn-live", "sn-live")
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
script := filepath.Join(dir, "manifest_probe.py")
if err = os.WriteFile(script, []byte("import json,sys\nm=json.loads(sys.argv[1])\nprint(json.dumps({'ok':m.get('source_root')=='spaces/workspace1?space=workspace1' and m.get('connection_id')=='conn-live','node_id':m['node_id']}))\n"), 0600); err != nil {
t.Fatal(err)
}
python, err := exec.LookPath("python3")
if err != nil {
t.Fatal(err)
}
runner, err := artifactfetch.NewCommandRunner(python, script, dir, "", 4096)
if err != nil {
t.Fatal(err)
}
result, err := runner.Run(ctx, manifest)
if err != nil || !result.OK {
t.Fatalf("current source coordinates lost across DB/Go/Python: %#v %v", result, err)
}
}
@@ -22,12 +22,13 @@ func loadArtifactFetchManifest(ctx context.Context, db interface {
var manifest artifactfetch.Manifest
var fetchState string
err := db.QueryRow(ctx, `SELECT connection.source_type,connection.name,intent.relative_path,intent.name,
intent.size_bytes,intent.modified_at,intent.locator_hash,intent.fetch_state
intent.size_bytes,intent.modified_at,intent.locator_hash,intent.fetch_state,
CASE WHEN connection.source_type='dingtalk' THEN connection.base_url ELSE '' END
FROM catalog_import_intents intent
JOIN source_connections connection ON connection.id=intent.source_connection_id
WHERE intent.source_connection_id=$1 AND intent.node_id=$2`, connectionID, nodeID).
Scan(&manifest.SourceType, &manifest.SourceName, &manifest.RelativePath, &manifest.Name,
&manifest.SizeBytes, &manifest.ModifiedAt, &manifest.LocatorHash, &fetchState)
&manifest.SizeBytes, &manifest.ModifiedAt, &manifest.LocatorHash, &fetchState, &manifest.SourceRoot)
if errors.Is(err, pgx.ErrNoRows) {
return artifactfetch.Manifest{}, artifactfetch.ErrManifestGone
}
+5 -5
View File
@@ -54,7 +54,7 @@ const monitorTasksCTE = `WITH history_publications AS (
WHERE $7<>'' AND (hv.source_item_id,hp.test_kb_id)=(SELECT v.source_item_id,p.test_kb_id FROM test_publications p JOIN source_item_versions v ON v.id=p.source_item_version_id WHERE p.id=$7)
), history_events AS (
SELECT updated_at AS at,'版本状态' AS kind,source_item_version_id || ' · ' || processing_state || ' / ' || retrieval_state AS detail FROM history_publications
UNION ALL SELECT f.created_at,'失败记录',f.job_type || ' · ' || f.error_code || ' · 尝试 ' || f.attempt FROM job_failures f WHERE f.publication_id IN(SELECT id FROM history_publications) OR (f.job_type='artifact.fetch' AND f.business_version_id IN(SELECT source_item_version_id FROM history_publications))
UNION ALL SELECT f.created_at,'失败记录',f.job_type || ' · ' || f.error_code || ' · 尝试 ' || f.attempt FROM job_failures f LEFT JOIN jobs fj ON fj.id=f.job_id WHERE f.publication_id IN(SELECT id FROM history_publications) OR (f.job_type='artifact.fetch' AND COALESCE(NULLIF(f.business_version_id,''),fj.payload->>'version_id') IN(SELECT source_item_version_id FROM history_publications))
UNION ALL SELECT r.created_at,'重试记录',r.reason || ' · ' || r.outcome FROM job_retry_operations r WHERE r.publication_id IN(SELECT id FROM history_publications)
), latest AS (
SELECT DISTINCT ON(v.source_item_id,p.test_kb_id) p.*,v.source_item_id,v.content_object_id
@@ -70,14 +70,14 @@ const monitorTasksCTE = `WITH history_publications AS (
CASE WHEN p.retrieval_state IN ('disabling','disabled') OR (p.knowledge_id<>'' AND si.policy_state='blocked') OR j.type='test.remove' THEN 'remove'
WHEN EXISTS(SELECT 1 FROM test_publications prev JOIN source_item_versions pv ON pv.id=prev.source_item_version_id WHERE pv.source_item_id=si.id AND prev.test_kb_id=p.test_kb_id AND prev.id<>p.id AND prev.created_at<p.created_at) THEN 'update' ELSE 'add' END AS action,
COALESCE(j.type,'') AS job_type,COALESCE(j.state,'') AS job_state,COALESCE(j.attempt,0) AS job_attempt,j.available_at,
COALESCE(f.id,'') AS failure_id,COALESCE(f.job_type,'') AS failure_type,COALESCE(f.error_code,'') AS failure_error
COALESCE(f.id,'') AS failure_id,COALESCE(f.job_type,'') AS failure_type,COALESCE(NULLIF(f.last_error,''),f.error_code,'') AS failure_error
FROM latest p JOIN source_items si ON si.id=p.source_item_id JOIN source_connections c ON c.id=si.source_connection_id
LEFT JOIN content_objects co ON co.id=p.content_object_id
LEFT JOIN LATERAL(SELECT j.type,j.state,j.attempt,j.available_at,j.updated_at FROM jobs j WHERE
(j.payload->>'publication_id'=p.id OR (j.type='artifact.fetch' AND j.payload->>'source_item_version_id'=p.source_item_version_id))
(j.payload->>'publication_id'=p.id OR (j.type='artifact.fetch' AND j.payload->>'version_id'=p.source_item_version_id))
AND j.type IN ('artifact.fetch','test.upload','test.poll','test.remove')
ORDER BY CASE WHEN j.state IN ('pending','running','retry') THEN 0 ELSE 1 END,j.updated_at DESC,j.id DESC LIMIT 1) j ON TRUE
LEFT JOIN LATERAL(SELECT f.id,f.job_type,f.error_code,f.created_at FROM job_failures f WHERE f.state='open' AND (f.publication_id=p.id OR (f.job_type='artifact.fetch' AND f.business_version_id=p.source_item_version_id)) ORDER BY f.created_at DESC,f.id DESC LIMIT 1) f ON TRUE
LEFT JOIN LATERAL(SELECT f.id,f.job_type,f.error_code,f.last_error,f.created_at FROM job_failures f LEFT JOIN jobs fj ON fj.id=f.job_id WHERE f.state='open' AND (f.publication_id=p.id OR (f.job_type='artifact.fetch' AND COALESCE(NULLIF(f.business_version_id,''),fj.payload->>'version_id')=p.source_item_version_id)) ORDER BY f.created_at DESC,f.id DESC LIMIT 1) f ON TRUE
), classified AS (
SELECT *,
CASE WHEN action='remove' AND retrieval_state='disabled' THEN 'completed'
@@ -85,7 +85,7 @@ const monitorTasksCTE = `WITH history_publications AS (
WHEN job_state IN ('pending','retry') AND job_attempt>0 THEN 'retrying'
WHEN job_state='running' THEN 'running'
WHEN job_state IN ('pending','retry') THEN 'waiting'
WHEN failure_id<>'' OR processing_state IN ('failed','stalled') OR ingest_state='failed' OR retrieval_state='failed' THEN 'attention'
WHEN job_state='failed' OR failure_id<>'' OR processing_state IN ('failed','stalled') OR ingest_state='failed' OR retrieval_state='failed' THEN 'attention'
WHEN processing_state='cancelled' THEN 'cancelled'
WHEN action='remove' THEN 'waiting'
WHEN processing_state IN ('processing','finalizing') THEN 'running'
@@ -102,4 +102,30 @@ func TestMonitorTasksUnifiedPaginationIntegration(t *testing.T) {
if err = store.RetryMonitorRemoval(ctx, "mt-remove", "tester", now); err != ErrPublicationStateConflict {
t.Fatalf("changed policy accepted: %v", err)
}
t.Run("fetch payload identity without business metadata", func(t *testing.T) {
insertReviewFixture(t, ctx, pool, 7, "mt-fetch", now)
exec(`UPDATE test_publications SET processing_state='planned',ingest_state='pending',knowledge_id='' WHERE id='mt-fetch'`)
exec(`INSERT INTO jobs(id,type,idempotency_key,payload,state,attempt,last_error) VALUES('mt-fetch-job','artifact.fetch','mt-fetch-key','{"version_id":"sv-review-7","source_connection_id":"conn-manual","node_id":"sn-fetch"}','failed',1,'DingTalk node not found in current inventory')`)
exec(`INSERT INTO job_failures(id,job_id,job_type,error_code,attempt,max_attempts_at_failure,last_error) VALUES('mt-fetch-failure','mt-fetch-job','artifact.fetch','artifact_invalid',1,8,'DingTalk node not found in current inventory')`)
check := func(status string, retryable int) {
t.Helper()
page, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{ID: "mt-fetch", Status: status, Stage: "fetch", Limit: 1})
if err != nil || page.Total != 1 || len(page.Items) != 1 || page.Retryable != retryable {
t.Fatalf("fetch status %s: %#v %v", status, page, err)
}
if status == "attention" {
row := page.Items[0]
if row.FailureID != "mt-fetch-failure" || row.RetryKind != "fetch" || row.Detail != "DingTalk node not found in current inventory" || len(row.History) < 2 {
t.Fatalf("failure details/history: %#v", row)
}
}
}
check("attention", 1)
exec(`UPDATE jobs SET state='pending',attempt=0 WHERE id='mt-fetch-job'`)
check("waiting", 0)
exec(`UPDATE jobs SET state='running',attempt=1 WHERE id='mt-fetch-job'`)
check("running", 0)
exec(`UPDATE jobs SET state='retry' WHERE id='mt-fetch-job'`)
check("retrying", 0)
})
}