fix(ui): 接通取件后自动解析与一次性定位
build / build (push) Successful in 1m42s

F17:MarkArtifactFetched 与已验证内容复用都在同一事务内经过策略、来源启用、
过滤、superseded 和当前绑定的复核后,自动把 planned 转 pending 并入队唯一
test.upload;确认与作业幂等,失败整笔回滚。356 已卡记录可对同一文件再次保存
当前策略,经同一路径恢复,不做全库补扫或手工补队列。来源页提示改为自动接续。

F14:来源→监控定位清空未结束/动作/阶段/时间筛选;来源目录定位改为一次性请求
并由父消费,revision/sources 重载不再重放旧请求,手工换目录保持。

F13:抽出 readiness.Resolver 作为端点/绑定/凭据唯一来源;worker 上传/轮询/
校验/移除改用动态客户端,每次调用重读有效配置,不再固化启动 env 客户端。

验证:隔离 PG 的 F17 正负例与恢复用例、前端挂载定位回归、全量 Go/前端测试
及 make verify 17 项通过。未部署、未做 8088 UI 验收。
This commit is contained in:
姚章浩
2026-11-05 11:46:42 +08:00
parent 1c80b07f2c
commit 5bf4aae30e
17 changed files with 873 additions and 46 deletions
@@ -0,0 +1,236 @@
package postgres
import (
"context"
"os"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
)
// F17:取件 verified 后必须沿同一策略/当前绑定自动接续唯一 test.upload。
// 这里用真实隔离 PG 跑 RouteCatalogFiles + MarkArtifactFetched 的真实 SQL 路径。
type autoIngestFixture struct {
t *testing.T
ctx context.Context
pool *pgxpool.Pool
store *Store
now time.Time
connID string
kbID string
}
func newAutoIngestFixture(t *testing.T) *autoIngestFixture {
t.Helper()
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)
}
t.Cleanup(pool.Close)
if err = ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
now := time.Date(2026, 11, 5, 4, 0, 0, 0, time.UTC)
exec := func(q string, args ...any) {
t.Helper()
if _, err := pool.Exec(ctx, q, args...); err != nil {
t.Fatalf("%v: %s", err, q)
}
}
exec(`INSERT INTO source_connections (id,source_type,name,enabled) VALUES ('conn-auto','dingtalk','ATOM自动衔接',TRUE)`)
exec(`INSERT INTO source_catalog_snapshots (id,source_connection_id,snapshot_sha256,source_label,node_count,folder_count,file_count,observed_at)
VALUES ('snap-auto','conn-auto',repeat('a',64),'fixture',2,1,1,$1)`, now)
exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash)
VALUES ('snap-auto','node-dir',NULL,'folder','常见问题汇总','常见问题汇总',repeat('b',64))`)
exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash)
VALUES ('snap-auto','node-file','node-dir','file','人形常见问题.adoc','常见问题汇总/人形常见问题.adoc',repeat('c',64))`)
exec(`INSERT INTO source_catalog_heads (source_connection_id,snapshot_id,activated_at) VALUES ('conn-auto','snap-auto',$1)`, now)
exec(`INSERT INTO routing_kb_bindings (id,internal_kb_id,external_kb_id,updated_by) VALUES ('active','kb-current','kb-ext', 'fixture')
ON CONFLICT (id) DO UPDATE SET internal_kb_id='kb-current',external_kb_id='kb-ext'`)
return &autoIngestFixture{t: t, ctx: ctx, pool: pool, store: NewStore(pool).WithRoutingDefaults("kb-env", "kb-ext"), now: now, connID: "conn-auto", kbID: "kb-current"}
}
func (f *autoIngestFixture) route() (versionID, publicationID string) {
f.t.Helper()
result, err := f.store.RouteCatalogFiles(f.ctx, governance.CatalogRouteRequest{
ConnectionID: f.connID,
NodeIDs: []string{"node-file"},
Visibility: governance.VisibilityInternal,
TargetKnowledgeBaseID: f.kbID,
OperatorRef: "fixture",
Reason: "fixture",
Now: f.now,
})
if err != nil {
f.t.Fatal(err)
}
if result.SelectedFiles != 1 || result.PlannedPublications != 1 {
f.t.Fatalf("route result = %#v", result)
}
if err := f.pool.QueryRow(f.ctx, `SELECT publication.source_item_version_id,publication.id
FROM test_publications publication
JOIN catalog_import_intents intent ON intent.source_item_id=(SELECT source_item_id FROM source_item_versions WHERE id=publication.source_item_version_id)
WHERE intent.node_id='node-file' AND publication.test_kb_id=$1`, f.kbID).Scan(&versionID, &publicationID); err != nil {
f.t.Fatal(err)
}
return versionID, publicationID
}
func (f *autoIngestFixture) markFetched(versionID string) {
f.t.Helper()
if err := f.store.MarkArtifactFetched(f.ctx, versionID, "32222102cafd6e5cdaeee415aad51e7df52629136d5ef2c3eae6e0e30ff7153d", 6991, "spool/auto.docx", "docx", true, f.now.Add(time.Minute)); err != nil {
f.t.Fatal(err)
}
}
func (f *autoIngestFixture) uploadJobs(publicationID string) int {
f.t.Helper()
var count int
if err := f.pool.QueryRow(f.ctx, `SELECT COUNT(*) FROM jobs WHERE type='test.upload' AND payload->>'publication_id'=$1`, publicationID).Scan(&count); err != nil {
f.t.Fatal(err)
}
return count
}
func (f *autoIngestFixture) publicationState(publicationID string) string {
f.t.Helper()
var state string
if err := f.pool.QueryRow(f.ctx, `SELECT processing_state FROM test_publications WHERE id=$1`, publicationID).Scan(&state); err != nil {
f.t.Fatal(err)
}
return state
}
func TestFetchedVerifiedArtifactAutoStartsExactlyOneUpload(t *testing.T) {
f := newAutoIngestFixture(t)
versionID, publicationID := f.route()
if jobs := f.uploadJobs(publicationID); jobs != 0 {
t.Fatalf("upload job before verification = %d", jobs)
}
f.markFetched(versionID)
if jobs := f.uploadJobs(publicationID); jobs != 1 {
t.Fatalf("upload jobs after verified fetch = %d, want 1", jobs)
}
if state := f.publicationState(publicationID); state != "pending" {
t.Fatalf("publication state = %q, want pending", state)
}
// 幂等:重复完成不能造第二个上传任务。
f.markFetched(versionID)
if jobs := f.uploadJobs(publicationID); jobs != 1 {
t.Fatalf("duplicate verified fetch created %d upload jobs", jobs)
}
}
func TestRouteReusingVerifiedContentAlsoAutoStarts(t *testing.T) {
f := newAutoIngestFixture(t)
versionID, publicationID := f.route()
// 模拟"本地已有先比对":内容已 verified,删除尚未消费的取件作业后再路由。
if _, err := f.pool.Exec(f.ctx, `UPDATE source_item_versions SET content_object_id=$2,content_state='verified'
WHERE id=$1`, versionID, f.insertVerifiedContent()); err != nil {
t.Fatal(err)
}
if _, err := f.pool.Exec(f.ctx, `DELETE FROM jobs WHERE type='artifact.fetch' AND payload->>'version_id'=$1`, versionID); err != nil {
t.Fatal(err)
}
if _, err := f.store.RouteCatalogFiles(f.ctx, governance.CatalogRouteRequest{
ConnectionID: f.connID, NodeIDs: []string{"node-file"}, Visibility: governance.VisibilityInternal,
TargetKnowledgeBaseID: f.kbID, OperatorRef: "fixture", Reason: "reuse", Now: f.now.Add(time.Minute),
}); err != nil {
t.Fatal(err)
}
if jobs := f.uploadJobs(publicationID); jobs != 1 {
t.Fatalf("reused verified content upload jobs = %d, want 1", jobs)
}
}
func (f *autoIngestFixture) insertVerifiedContent() string {
f.t.Helper()
if _, err := f.pool.Exec(f.ctx, `INSERT INTO content_objects(id,sha256,size_bytes,mime,validated_format,local_spool_ref,content_state)
VALUES('co-auto',repeat('d',64),6991,'','docx','spool/auto.docx','verified')
ON CONFLICT(sha256) DO UPDATE SET local_spool_ref=EXCLUDED.local_spool_ref,content_state='verified'`); err != nil {
f.t.Fatal(err)
}
var id string
if err := f.pool.QueryRow(f.ctx, `SELECT id FROM content_objects WHERE sha256=repeat('d',64)`).Scan(&id); err != nil {
f.t.Fatal(err)
}
return id
}
func TestStuckPlannedVerifiedPublicationRecoversViaReRoute(t *testing.T) {
f := newAutoIngestFixture(t)
versionID, publicationID := f.route()
f.markFetched(versionID) // 新代码本会入队;先清掉,复现 356 已卡记录
if _, err := f.pool.Exec(f.ctx, `DELETE FROM jobs WHERE type='test.upload' AND payload->>'publication_id'=$1`, publicationID); err != nil {
t.Fatal(err)
}
if _, err := f.pool.Exec(f.ctx, `UPDATE test_publications SET processing_state='planned' WHERE id=$1`, publicationID); err != nil {
t.Fatal(err)
}
// 父在 UI 对同一文件再次保存当前策略:只这一条、只当前绑定,幂等接续。
if _, err := f.store.RouteCatalogFiles(f.ctx, governance.CatalogRouteRequest{
ConnectionID: f.connID, NodeIDs: []string{"node-file"}, Visibility: governance.VisibilityInternal,
TargetKnowledgeBaseID: f.kbID, OperatorRef: "fixture", Reason: "resume", Now: f.now.Add(2 * time.Minute),
}); err != nil {
t.Fatal(err)
}
if jobs := f.uploadJobs(publicationID); jobs != 1 {
t.Fatalf("stuck record recovered upload jobs = %d, want 1", jobs)
}
if state := f.publicationState(publicationID); state != "pending" {
t.Fatalf("stuck record state = %q", state)
}
}
func TestAutoStartRefusesStaleOrIneligiblePolicies(t *testing.T) {
cases := []struct {
name string
mutate func(f *autoIngestFixture, publicationID string)
}{
{"disabled source", func(f *autoIngestFixture, _ string) {
if _, err := f.pool.Exec(f.ctx, `UPDATE source_connections SET enabled=FALSE WHERE id='conn-auto'`); err != nil {
f.t.Fatal(err)
}
}},
{"blocked policy", func(f *autoIngestFixture, _ string) {
if _, err := f.pool.Exec(f.ctx, `UPDATE source_items SET policy_state='blocked' WHERE source_connection_id='conn-auto'`); err != nil {
f.t.Fatal(err)
}
}},
{"filtered filename", func(f *autoIngestFixture, _ string) {
if _, err := f.pool.Exec(f.ctx, `INSERT INTO filename_filter_rules(source_connection_id,directory_path,excluded_extensions,updated_by,mode)
VALUES('conn-auto','',ARRAY['adoc'],'fixture','exclude')`); err != nil {
f.t.Fatal(err)
}
}},
{"superseded publication", func(f *autoIngestFixture, publicationID string) {
if _, err := f.pool.Exec(f.ctx, `UPDATE test_publications SET superseded_at=$2 WHERE id=$1`, publicationID, f.now); err != nil {
f.t.Fatal(err)
}
}},
{"binding changed", func(f *autoIngestFixture, _ string) {
if _, err := f.pool.Exec(f.ctx, `UPDATE routing_kb_bindings SET internal_kb_id='kb-other' WHERE id='active'`); err != nil {
f.t.Fatal(err)
}
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := newAutoIngestFixture(t)
versionID, publicationID := f.route()
tc.mutate(f, publicationID)
f.markFetched(versionID)
if jobs := f.uploadJobs(publicationID); jobs != 0 {
t.Fatalf("%s auto-started %d upload jobs, want 0", tc.name, jobs)
}
})
}
}
@@ -27,7 +27,7 @@ func (s *Store) RouteCatalogFiles(ctx context.Context, request governance.Catalo
return governance.CatalogRouteResult{}, fmt.Errorf("begin catalog route: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
result, err := routeCatalogFilesTx(ctx, tx, request)
result, err := routeCatalogFilesTx(ctx, tx, s, request)
if err != nil {
return governance.CatalogRouteResult{}, err
}
@@ -57,7 +57,7 @@ func validateCatalogRouteRequest(request governance.CatalogRouteRequest) error {
return nil
}
func routeCatalogFilesTx(ctx context.Context, tx pgx.Tx, request governance.CatalogRouteRequest) (governance.CatalogRouteResult, error) {
func routeCatalogFilesTx(ctx context.Context, tx pgx.Tx, store *Store, request governance.CatalogRouteRequest) (governance.CatalogRouteResult, error) {
targetKnowledgeBaseIDs := request.TargetKnowledgeBaseIDs
if len(targetKnowledgeBaseIDs) == 0 && request.TargetKnowledgeBaseID != "" {
targetKnowledgeBaseIDs = []string{request.TargetKnowledgeBaseID}
@@ -142,7 +142,7 @@ ORDER BY node.node_id`, request.ConnectionID, nodeIDs)
return governance.CatalogRouteResult{}, fmt.Errorf("iterate catalog route files: %w", err)
}
rows.Close()
return fulfillCatalogIntentsTx(ctx, tx, request, files, request.Now)
return fulfillCatalogIntentsTx(ctx, tx, store, request, files, request.Now)
}
func setCatalogDirectoryPolicy(ctx context.Context, tx pgx.Tx, request governance.CatalogRouteRequest, directoryPath string) error {
@@ -35,7 +35,7 @@ func (s *Store) RouteCatalogFilesWithOperation(ctx context.Context, request gove
return governance.CatalogRouteResult{}, false, err
}
resultJSON, replayed, err := s.executeOperation(ctx, "catalog.route", operationID, fingerprint, request.Now, func(tx pgx.Tx) (json.RawMessage, error) {
result, err := routeCatalogFilesTx(ctx, tx, request)
result, err := routeCatalogFilesTx(ctx, tx, s, request)
if err != nil {
return nil, err
}
+102 -3
View File
@@ -23,14 +23,14 @@ import (
// 开始处理 promotes them within the configured concurrency budget. Blocked
// intents retire any planned publication and flip the item policy so the
// knowledge-base diff demands removal of anything still live.
func fulfillCatalogIntentsTx(ctx context.Context, tx pgx.Tx, request governance.CatalogRouteRequest, files []governance.CatalogRouteFile, now time.Time) (governance.CatalogRouteResult, error) {
func fulfillCatalogIntentsTx(ctx context.Context, tx pgx.Tx, store *Store, request governance.CatalogRouteRequest, files []governance.CatalogRouteFile, now time.Time) (governance.CatalogRouteResult, error) {
targetKnowledgeBaseIDs := request.TargetKnowledgeBaseIDs
if len(targetKnowledgeBaseIDs) == 0 && request.TargetKnowledgeBaseID != "" {
targetKnowledgeBaseIDs = []string{request.TargetKnowledgeBaseID}
}
result := governance.CatalogRouteResult{SelectedFiles: len(files)}
for _, file := range files {
recorded, fetchQueued, planned, blocked, err := fulfillCatalogIntent(ctx, tx, request, file, targetKnowledgeBaseIDs, now)
recorded, fetchQueued, planned, blocked, err := fulfillCatalogIntent(ctx, tx, store, request, file, targetKnowledgeBaseIDs, now)
if err != nil {
return governance.CatalogRouteResult{}, err
}
@@ -54,7 +54,7 @@ func fulfillCatalogIntentsTx(ctx context.Context, tx pgx.Tx, request governance.
// fulfillCatalogIntent applies one file decision. It returns recorded=false
// only when the node vanished mid-transaction; fetchQueued reports a newly
// enqueued artifact.fetch job and planned the number of publications created.
func fulfillCatalogIntent(ctx context.Context, tx pgx.Tx, request governance.CatalogRouteRequest, file governance.CatalogRouteFile, targetKnowledgeBaseIDs []string, now time.Time) (bool, bool, int, bool, error) {
func fulfillCatalogIntent(ctx context.Context, tx pgx.Tx, store *Store, request governance.CatalogRouteRequest, file governance.CatalogRouteFile, targetKnowledgeBaseIDs []string, now time.Time) (bool, bool, int, bool, error) {
policy := string(request.Visibility)
if _, err := tx.Exec(ctx, `INSERT INTO catalog_import_intents(
source_connection_id,node_id,visibility,decided_by,reason,relative_path,name,size_bytes,modified_at,content_sha256,
@@ -240,6 +240,11 @@ ON CONFLICT (source_item_version_id,test_kb_id) DO NOTHING`,
}
planned += int(tag.RowsAffected())
}
if contentState == string(governance.ContentVerified) {
if err := store.autoStartVerifiedPublicationsTx(ctx, tx, versionID, now); err != nil {
return false, false, 0, false, err
}
}
fetchQueued := false
if contentState != string(governance.ContentVerified) {
@@ -295,6 +300,97 @@ func sha256Hex(value string) string {
return hex.EncodeToString(sum[:])
}
// autoStartVerifiedPublicationsTx continues the normal ingestion chain in the
// SAME transaction that made the bytes verified. It deliberately re-checks the
// saved policy, the current binding and the live source state: a file routed
// before a policy/binding change must not be uploaded to a stale target.
func (s *Store) autoStartVerifiedPublicationsTx(ctx context.Context, tx pgx.Tx, versionID string, now time.Time) error {
if versionID == "" {
return errors.New("auto-start requires a version")
}
rows, err := tx.Query(ctx, `
WITH binding AS (
SELECT COALESCE(NULLIF(internal_kb_id,''), $3::text) AS internal_kb_id,
COALESCE(NULLIF(external_kb_id,''), $4::text) AS external_kb_id
FROM routing_kb_bindings WHERE id='active'
), eligible AS (
SELECT publication.id
FROM test_publications publication
JOIN source_item_versions version ON version.id=publication.source_item_version_id
JOIN content_objects content ON content.id=version.content_object_id
JOIN source_items item ON item.id=version.source_item_id
JOIN source_connections connection ON connection.id=item.source_connection_id
LEFT JOIN LATERAL (
SELECT intent.visibility FROM catalog_import_intents intent
WHERE intent.source_item_id=item.id AND intent.source_connection_id=item.source_connection_id
ORDER BY intent.updated_at DESC,intent.node_id LIMIT 1
) intent ON TRUE
CROSS JOIN binding
WHERE version.id=$1
AND publication.superseded_at IS NULL
AND publication.processing_state='planned'
AND publication.ingest_state='pending'
AND publication.knowledge_id=''
AND publication.retrieval_state='unpublished'
AND version.content_state='verified'
AND content.content_state='verified'
AND content.local_spool_ref<>''
AND content.size_bytes>0
AND connection.enabled
AND item.policy_state IN (publication.target_scope,'both')
AND intent.visibility IN (publication.target_scope,'both')
AND NOT filename_is_filtered(item.source_connection_id,item.normalized_path,item.title)
AND NOT EXISTS (SELECT 1 FROM jobs job WHERE job.type='test.upload' AND job.payload->>'publication_id'=publication.id)
AND ((publication.target_scope='internal' AND binding.internal_kb_id<>'' AND publication.test_kb_id=binding.internal_kb_id)
OR (publication.target_scope='external' AND binding.external_kb_id<>'' AND publication.test_kb_id=binding.external_kb_id))
)
UPDATE test_publications publication SET processing_state='pending',updated_at=$2
FROM eligible WHERE publication.id=eligible.id
RETURNING publication.id`, versionID, now, s.defaultInternalKBID, s.defaultExternalKBID)
if err != nil {
return fmt.Errorf("auto-start verified publications: %w", err)
}
ids := make([]string, 0, 2)
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
rows.Close()
return fmt.Errorf("scan auto-started publication: %w", err)
}
ids = append(ids, id)
}
if err := rows.Err(); err != nil {
rows.Close()
return fmt.Errorf("iterate auto-started publications: %w", err)
}
rows.Close()
for _, publicationID := range ids {
confirmationID, err := newOpaqueID("pc-")
if err != nil {
return err
}
jobID, err := newOpaqueID("job-")
if err != nil {
return err
}
payload, err := json.Marshal(map[string]string{"publication_id": publicationID})
if err != nil {
return errors.New("encode auto upload job")
}
if _, err := tx.Exec(ctx, `INSERT INTO processing_confirmations(id,publication_id,operator_ref,reason,confirmed_at,created_at)
VALUES($1,$2,'system:auto','取件 verified 自动接续',$3,$3)
ON CONFLICT (publication_id) DO NOTHING`, confirmationID, publicationID, now); err != nil {
return fmt.Errorf("record auto processing confirmation: %w", err)
}
if _, err := tx.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,priority,available_at,max_attempts,idempotency_key,created_at,updated_at)
VALUES($1,'test.upload',$2::jsonb,'pending',10,$3,5,$4,$3,$3)
ON CONFLICT (idempotency_key) DO NOTHING`, jobID, payload, now, "auto-test-upload:"+publicationID); err != nil {
return fmt.Errorf("enqueue auto upload: %w", err)
}
}
return nil
}
// MarkArtifactFetched finalizes one artifact.fetch success: it (re)uses the
// content_objects row for the verified hash (content-level dedupe), attaches it
// to the pending version and flips the intent to ready. matchedLocal records
@@ -358,6 +454,9 @@ WHERE id=$1`,
WHERE source_connection_id=$1 AND node_id=$2`, connectionID, nodeID); err != nil {
return fmt.Errorf("mark intent fetched: %w", err)
}
if err := s.autoStartVerifiedPublicationsTx(ctx, tx, versionID, now); err != nil {
return fmt.Errorf("continue fetched artifact into upload: %w", err)
}
if ownsTransaction {
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit artifact fetch: %w", err)
+15 -2
View File
@@ -23,8 +23,10 @@ type database interface {
}
type Store struct {
db database
libraryTargetID string
db database
libraryTargetID string
defaultInternalKBID string
defaultExternalKBID string
// restoreDispatchEvidenceRoot 是激活门唯一允许读取维护 journal 的根目录。
// 空值表示没有配置受信证据源:激活必须失败关闭,而不是退回"只看字符串"。
restoreDispatchEvidenceRoot string
@@ -43,6 +45,17 @@ func NewStore(db database) *Store {
return &Store{db: db}
}
// WithRoutingDefaults supplies the deployment's bootstrap bindings. The UI
// binding row still wins; defaults are only the unbound fallback, exactly like
// the route/readiness resolvers. Auto-continuation uses them only to prove the
// publication still targets the CURRENT effective knowledge base.
func (s *Store) WithRoutingDefaults(internal, external string) *Store {
copy := *s
copy.defaultInternalKBID = strings.TrimSpace(internal)
copy.defaultExternalKBID = strings.TrimSpace(external)
return &copy
}
// WithRestoreDispatchEvidence 绑定维护 journal 的受信根目录(部署配置
// LIBRARY_TARGET_JOURNAL_ROOT)。没有它时激活门一律失败关闭。
func (s *Store) WithRestoreDispatchEvidence(root string) *Store {