diff --git a/internal/releaseadapter/v071/formal_maintenance_recovery_r38_early_test.go b/internal/releaseadapter/v071/formal_maintenance_recovery_r38_early_test.go new file mode 100644 index 0000000..744896f --- /dev/null +++ b/internal/releaseadapter/v071/formal_maintenance_recovery_r38_early_test.go @@ -0,0 +1,331 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" +) + +// 本轮唯一新增的夹具输入:来源文档二改为"已解析完成、无未结算子任务"。 +// +// 旧矩阵的 ds02SourceRows 一行不改:原 pending=1 输入仍然由正式来源契约拒绝(见负控)。 +// 这里只复制一份本轮 R38 early 场景专用声明,证明早段数据库故障不是靠不合法的来源夹具制造。 +func r38LegalSourceRows(t *testing.T) map[string][]map[string]any { + t.Helper() + rows := ds02SourceRows() + shared := ds02SourceRows() + index := -1 + for i, row := range rows["knowledges"] { + if row["id"] == "doc-src2" { + index = i + } + } + if index < 0 { + t.Fatal("source declaration lost doc-src2") + } + if shared["knowledges"][index]["pending_subtasks_count"] != 1 { + t.Fatalf("shared ds02 source declaration must stay pending=1, got %v", + shared["knowledges"][index]["pending_subtasks_count"]) + } + rows["knowledges"][index]["pending_subtasks_count"] = 0 + rows["knowledges"][index]["parse_status"] = "completed" + return rows +} + +func r38LegalSourceSpec(t *testing.T, fx *writeSetFixture) ds02Spec { + t.Helper() + rows := r38LegalSourceRows(t) + for table, list := range rows { + for i, row := range list { + rows[table][i] = ds02Canon(t, fx, table, row) + } + } + return ds02Spec{rows: rows, vectors: ds02Vectors, objects: ds02Objects} +} + +// r38SearchPathDB 让正式的结算检查跑在一张只装本轮声明的真实 PostgreSQL 表上。 +// 为什么不是直接插进业务表:来源行与发布写入共用主键 id,插进同一命名空间会让发布 +// 自己撞主键,故障就不再是"恢复阶段 database"。隔离 schema 只改变解析目标,不改产品代码。 +type r38SearchPathDB struct { + pool *pgxpool.Pool + schema string +} + +func (d r38SearchPathDB) BeginTx(ctx context.Context, opts pgx.TxOptions) (pgx.Tx, error) { + tx, err := d.pool.BeginTx(ctx, opts) + if err != nil { + return nil, err + } + if _, err := tx.Exec(ctx, `SET LOCAL search_path TO "`+d.schema+`", public`); err != nil { + _ = tx.Rollback(context.WithoutCancel(ctx)) + return nil, err + } + return tx, nil +} + +// r38ProveLegalSourceContract 用产品自己的 checkLibrarySourceSettlement 对 +// "本轮专用来源声明"做真实 PostgreSQL 结算,并保留 pending=1 被拒绝的负控。 +// 返回原始证据;调用方负责落盘。 +func r38ProveLegalSourceContract(t *testing.T, fx *writeSetFixture, spec ds02Spec) map[string]any { + t.Helper() + const schema = "r38_legal_source" + ctx := fx.ctx + if _, err := fx.pool.Exec(ctx, `DROP SCHEMA IF EXISTS `+schema+` CASCADE; +CREATE SCHEMA `+schema+`; +CREATE TABLE `+schema+`.knowledges (LIKE public.knowledges INCLUDING ALL)`); err != nil { + t.Fatalf("create the isolated settlement schema: %v", err) + } + drop := func() int { + if _, err := fx.pool.Exec(ctx, `DROP SCHEMA IF EXISTS `+schema+` CASCADE`); err != nil { + t.Fatalf("drop the isolated settlement schema: %v", err) + } + var left int + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.schemata WHERE schema_name=$1`, schema).Scan(&left); err != nil { + t.Fatalf("read back the isolated settlement schema: %v", err) + } + return left + } + t.Cleanup(func() { _ = drop }) + insert := `INSERT INTO ` + schema + `.knowledges SELECT * FROM jsonb_populate_record(NULL::` + schema + `.knowledges,$1::jsonb)` + for _, row := range spec.rows["knowledges"] { + raw, err := json.Marshal(row) + if err != nil { + t.Fatal(err) + } + if _, err := fx.pool.Exec(ctx, insert, raw); err != nil { + t.Fatalf("insert the declared source row %v: %v", row["id"], err) + } + } + var declared int + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM `+schema+`.knowledges`).Scan(&declared); err != nil { + t.Fatal(err) + } + // 负控:同一条正式结算必须拒绝 pending=1。控制行是本夹具自己插入的,解除只按 id+租户+库删除。 + controlID := "doc-src-pending-control" + controlKB := "kb-source-pending-control" + control := map[string]any{"id": controlID, "tenant_id": wsSourceTenant, "knowledge_base_id": controlKB, + "type": "document", "title": "待处理来源(负控)", "source": "upload", + "parse_status": "completed", "pending_subtasks_count": 1} + rawControl, err := json.Marshal(control) + if err != nil { + t.Fatal(err) + } + if _, err := fx.pool.Exec(ctx, insert, rawControl); err != nil { + t.Fatalf("insert the pending=1 negative control: %v", err) + } + db := r38SearchPathDB{pool: fx.pool, schema: schema} + pendingErr := checkLibrarySourceSettlement(ctx, db) + if pendingErr == nil { + t.Fatal("the formal settlement accepted a pending=1 source row: the negative control was lost") + } + controlDelete := `DELETE FROM ` + schema + `.knowledges WHERE id=$1 AND tenant_id=$2 AND knowledge_base_id=$3` + tag, err := fx.pool.Exec(ctx, controlDelete, controlID, wsSourceTenant, controlKB) + if err != nil { + t.Fatalf("remove the pending=1 negative control: %v", err) + } + if tag.RowsAffected() != 1 { + t.Fatalf("pending control removal affected %d rows", tag.RowsAffected()) + } + var controlLeft int + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM `+schema+`.knowledges WHERE id=$1`, controlID).Scan(&controlLeft); err != nil { + t.Fatal(err) + } + if controlLeft != 0 { + t.Fatalf("pending control row left %d rows", controlLeft) + } + settlementErr := checkLibrarySourceSettlement(ctx, db) + if settlementErr != nil { + t.Fatalf("the declared legal source rows were rejected by the formal settlement: %v", settlementErr) + } + // 校准作用域:同一条 SQL 在隔离 schema 里看到的就是本轮声明,而不是业务表里的旧行。 + tx, err := db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly}) + if err != nil { + t.Fatal(err) + } + var searchPath string + var visible int + if err := tx.QueryRow(ctx, `SHOW search_path`).Scan(&searchPath); err != nil { + t.Fatal(err) + } + if err := tx.QueryRow(ctx, `SELECT count(*) FROM knowledges`).Scan(&visible); err != nil { + t.Fatal(err) + } + _ = tx.Rollback(context.WithoutCancel(ctx)) + var businessCopies int + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM public.knowledges WHERE tenant_id=$1`, wsSourceTenant).Scan(&businessCopies); err != nil { + t.Fatal(err) + } + if businessCopies != 0 { + t.Fatalf("source rows leaked into the business knowledges table: %d", businessCopies) + } + if visible != declared { + t.Fatalf("settlement scope saw %d rows, want the %d declared rows", visible, declared) + } + left := drop() + return map[string]any{ + "shared_declaration_kept_pending": 1, + "declared_source_rows": declared, + "declared_knowledge_pending": []int{0, 0}, + "declared_knowledge_parse_status": []string{"completed", "completed"}, + "settlement_sql": librarySourceSettlementSQL, + "pending_control": map[string]any{"id": controlID, "pending_subtasks_count": 1, + "rejected": true, "error": pendingErr.Error(), + "delete_statement": controlDelete, "deleted": tag.RowsAffected(), "rows_left": controlLeft}, + "legal_settlement": "passed", "legal_error": nil, + "search_path": searchPath, "settlement_visible_rows": visible, + "business_table_source_rows": businessCopies, + "schema": schema, "schema_dropped": left == 0, + "scope_note": "same formal settlement SQL, executed on a real PostgreSQL table holding exactly the declared rows; the business tables were never given these ids because publish writes the same ids", + } +} + +const r38PGEarlyFaultInsert = `INSERT INTO knowledges SELECT * FROM jsonb_populate_record(NULL::knowledges, $1::jsonb)` + +// r38ArmPGEarlyFault 是早段唯一新增的故障:发布已经把目标范围的 before-image 文档删掉, +// 恢复的 database 阶段会按原 id 把该文档插回;先用一行"外部范围、同主键"的 knowledges +// 占住这个 id,那条真实 INSERT 就得到 SQLSTATE 23505。不改 schema/ACL,也不停共享 PG。 +func r38ArmPGEarlyFault(t *testing.T, fx *writeSetFixture, knowledgeID string) map[string]any { + t.Helper() + if knowledgeID == "" { + t.Fatal("pg early fault armed without a knowledges identity") + } + var inTarget int + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM knowledges WHERE id=$1 AND tenant_id=$2 AND knowledge_base_id=$3`, + knowledgeID, wsTargetTenant, wsTargetKB).Scan(&inTarget); err != nil { + t.Fatal(err) + } + if inTarget != 0 { + t.Fatalf("before-image knowledges id %s is still in the target scope: publish did not free the primary key", knowledgeID) + } + var raw []byte + if err := fx.pool.QueryRow(fx.ctx, `SELECT to_jsonb(x) FROM knowledges x ORDER BY id LIMIT 1`).Scan(&raw); err != nil { + t.Fatalf("pg early fault needs one existing knowledges row as a shape template: %v", err) + } + var row map[string]any + if err := json.Unmarshal(raw, &row); err != nil { + t.Fatal(err) + } + row["id"] = knowledgeID + row["tenant_id"] = 20000 + row["knowledge_base_id"] = "kb-r38-foreign" + row["title"] = "外部范围占位文档" + encoded, err := json.Marshal(row) + if err != nil { + t.Fatal(err) + } + if _, err := fx.pool.Exec(fx.ctx, r38PGEarlyFaultInsert, encoded); err != nil { + t.Fatalf("arm pg early fault (foreign row holding knowledge %s): %v", knowledgeID, err) + } + var tenant int64 + var kb string + if err := fx.pool.QueryRow(fx.ctx, `SELECT tenant_id,knowledge_base_id FROM knowledges WHERE id=$1`, knowledgeID).Scan(&tenant, &kb); err != nil { + t.Fatal(err) + } + if tenant != 20000 || kb != "kb-r38-foreign" { + t.Fatalf("pg early fault row readback = %d/%s, want 20000/kb-r38-foreign", tenant, kb) + } + return map[string]any{"stage": "database", "table": "knowledges", "conflict_id": knowledgeID, + "conflict_tenant": tenant, "conflict_kb": kb, "insert_statement": r38PGEarlyFaultInsert, + "expected_sqlstate": r38PGSQLState, + "mechanism": "foreign-scope row holds the primary key the recovery database stage restores", + "target_row_absent_at_arm": true, "schema_changed": false, + "scope": "one disposable business database; shared PG, ACL and sessions untouched"} +} + +// r38PGEarlyFaultHeld 证明:故障行仍在;同一 INSERT 仍被服务器以 23505 拒绝且没有多出行; +// database 阶段整段回滚,所以十张表都还是发布写入后的内容(不是 before-image)。 +func r38PGEarlyFaultHeld(t *testing.T, fx *writeSetFixture, before, applied map[string][]map[string]any, + failureText, knowledgeID string) map[string]any { + t.Helper() + if len(before) == 0 || len(applied) == 0 { + t.Fatal("held early-pg evidence needs both the before-image and the applied readback") + } + var rows int + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM knowledges WHERE id=$1 AND tenant_id=20000 AND knowledge_base_id='kb-r38-foreign'`, + knowledgeID).Scan(&rows); err != nil { + t.Fatal(err) + } + if rows != 1 { + t.Fatalf("pg early fault row was not preserved at held: %d rows for knowledge %s", rows, knowledgeID) + } + var raw []byte + if err := fx.pool.QueryRow(fx.ctx, `SELECT to_jsonb(x) FROM knowledges x WHERE id=$1`, knowledgeID).Scan(&raw); err != nil { + t.Fatal(err) + } + _, probeErr := fx.pool.Exec(fx.ctx, r38PGEarlyFaultInsert, raw) + var pgErr *pgconn.PgError + if probeErr == nil || !errors.As(probeErr, &pgErr) { + t.Fatalf("fault probe did not raise a PG error: %v", probeErr) + } + if pgErr.Code != r38PGSQLState { + t.Fatalf("fault probe SQLSTATE = %q, want %s", pgErr.Code, r38PGSQLState) + } + var probeRows int + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM knowledges WHERE id=$1`, knowledgeID).Scan(&probeRows); err != nil { + t.Fatal(err) + } + if probeRows != 1 { + t.Fatalf("failed probe left %d rows for knowledge %s: the statement did not roll back", probeRows, knowledgeID) + } + held := r38TargetRows(t, fx) + stillApplied := []string{} + for _, table := range ds02TargetTables { + if diff := r38CompareRows("held "+table, applied[table], held[table]); diff != "" { + t.Fatalf("held %s does not match the applied publish (the database stage must roll back as a whole): %s", table, diff) + } + stillApplied = append(stillApplied, table) + } + rolledBack := 0 + for _, table := range ds02TargetTables { + if r38CompareRows("held-vs-before "+table, before[table], held[table]) != "" { + rolledBack++ + } + } + if rolledBack == 0 { + t.Fatal("held state equals the before-image: the early database stage cannot have failed") + } + encoded, err := json.Marshal(held) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(encoded) + counts := map[string]int{} + for table, values := range held { + counts[table] = len(values) + } + return map[string]any{"conflict_id": knowledgeID, "conflict_rows": rows, + "probe_statement": r38PGEarlyFaultInsert, "sqlstate": pgErr.Code, "probe_error": pgErr.Error(), + "probe_rows_after_error": probeRows, + "transaction": "database stage INSERT failed; that stage transaction rolled back; no later stage ran", + "still_applied_tables": stillApplied, "tables_differing_from_before": rolledBack, + "held_row_counts": counts, "held_pg_sha256": hex.EncodeToString(sum[:]), + "matches_applied_publish": true, + "failure_text_has_sqlstate": strings.Contains(failureText, "SQLSTATE "+r38PGSQLState), + "failure_text_has_stage": strings.Contains(failureText, "恢复阶段 database 失败")} +} + +func r38DisarmPGEarlyFault(t *testing.T, fx *writeSetFixture, knowledgeID string) map[string]any { + t.Helper() + statement := `DELETE FROM knowledges WHERE id=$1 AND tenant_id=20000 AND knowledge_base_id='kb-r38-foreign'` + tag, err := fx.pool.Exec(fx.ctx, statement, knowledgeID) + if err != nil { + t.Fatal(err) + } + var left int + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM knowledges WHERE tenant_id=20000 AND knowledge_base_id='kb-r38-foreign'`).Scan(&left); err != nil { + t.Fatal(err) + } + if tag.RowsAffected() != 1 || left != 0 { + t.Fatalf("pg early fault not removed: deleted=%d left=%d", tag.RowsAffected(), left) + } + return map[string]any{"statement": statement, "deleted": tag.RowsAffected(), "foreign_rows_left": left, + "readback_absent": true} +} diff --git a/internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go b/internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go index f62726b..3075b9d 100644 --- a/internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go +++ b/internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go @@ -368,7 +368,7 @@ func TestFormalMaintenanceRecoveryObjectRestoreHeldThenRecovered(t *testing.T) { // TestFormalMaintenanceRecoveryPGRestoreHeldThenRecovered 是 PG 恢复失败分支的显式入口: // 隔离部署里必须由 runner 传入 KG_R38_SCENARIO=pg-restore。发布失败入口复用已证明的 -// after:wiki 定点;唯一新增故障来自这次专用恢复事务里的真实 PG 错误(触发器 + SQLSTATE), +// after:wiki 定点;唯一新增故障来自这次专用恢复事务里的真实主键冲突(SQLSTATE 23505), // 不靠停共享 PG、扩大 ACL 或改产品返回值制造。 func TestFormalMaintenanceRecoveryPGRestoreHeldThenRecovered(t *testing.T) { if os.Getenv("KG_R38_RUN") == "" { @@ -380,6 +380,21 @@ func TestFormalMaintenanceRecoveryPGRestoreHeldThenRecovered(t *testing.T) { TestFormalMaintenanceRecoveryHeldThenRecovered(t) } +// TestFormalMaintenanceRecoveryPGEarlyRestoreHeldThenRecovered 是早段 database 恢复失败的显式入口: +// 发布失败入口仍是已证明的 after:wiki 定点;唯一新增故障是恢复第一段(database)里的真实 +// 主键冲突。来源输入改用本轮专用副本:未删除文档 parse_status=completed 且 +// pending_subtasks_count=0,并在封版前用产品自己的正式结算检查证明它可被接受; +// 旧的 pending=1 输入仍保留为"被正式契约拒绝"的负控,不放宽 quiesce。 +func TestFormalMaintenanceRecoveryPGEarlyRestoreHeldThenRecovered(t *testing.T) { + if os.Getenv("KG_R38_RUN") == "" { + t.Skip("requires the dedicated r38 isolated deployment (KG_R38_RUN)") + } + if os.Getenv("KG_R38_SCENARIO") != "pg-early" { + t.Fatalf("pg early recovery branch requires KG_R38_SCENARIO=pg-early, got %q", os.Getenv("KG_R38_SCENARIO")) + } + TestFormalMaintenanceRecoveryHeldThenRecovered(t) +} + func TestFormalMaintenanceRecoveryHeldThenRecovered(t *testing.T) { root := os.Getenv("KG_R38_RUN") if root == "" { @@ -388,9 +403,10 @@ func TestFormalMaintenanceRecoveryHeldThenRecovered(t *testing.T) { scenario := os.Getenv("KG_R38_SCENARIO") objectBranch := scenario == "object-restore" pgBranch := scenario == "pg-restore" - // 三条分支共用同一套 fullshape/真实入库装配;对象分支与 PG 分支都让 ES 恢复成功, - // 只有 ES 分支把 clean 派发拒掉。 - fullShape := objectBranch || pgBranch + earlyBranch := scenario == "pg-early" + // 三条分支共用同一套 fullshape/真实入库装配;对象分支与两种 PG 分支都让 ES 恢复不成为 + // 第一个失败点:ES 分支拒绝 clean 派发,PG 分支在恢复自己的事务里拿到真实 SQLSTATE。 + fullShape := objectBranch || pgBranch || earlyBranch ctx := context.Background() save := func(name string, value any) { t.Helper() @@ -423,6 +439,13 @@ func TestFormalMaintenanceRecoveryHeldThenRecovered(t *testing.T) { } else { seedTargetData(t, fx) } + // 早段分支的来源输入是专用副本(pending=0/completed)。封版前先用产品自己的正式结算 + // 检查证明这份输入可被接受,并保留原 pending=1 被拒绝的负控。共享声明一行不改。 + var earlySourceSpec ds02Spec + if earlyBranch { + earlySourceSpec = r38LegalSourceSpec(t, fx) + save("01c-legal-source-proof.json", r38ProveLegalSourceContract(t, fx, earlySourceSpec)) + } _, e := fx.pool.Exec(ctx, `ALTER TABLE knowledge_bases ADD COLUMN embedding_model_id text, ADD COLUMN vector_store_id text; CREATE TABLE models(id text PRIMARY KEY,name text,parameters jsonb,deleted_at timestamptz); CREATE TABLE vector_stores(id text PRIMARY KEY,engine_type text,index_config jsonb,deleted_at timestamptz); @@ -436,6 +459,7 @@ UPDATE knowledge_bases SET embedding_model_id='r38-model',vector_store_id='r38-v // 日志行按原 id 插回目标范围,所以一个同主键、不同范围的"外来行"会让那条真实 // INSERT 报 23505;发布/恢复都不改 schema,也不动共享 PG。 var conflictLog int64 + var conflictKnowledge string var beforeTarget map[string][]map[string]any if pgBranch { must(fx.pool.QueryRow(ctx, `SELECT id FROM wiki_log_entries WHERE tenant_id=$1 AND knowledge_base_id=$2 ORDER BY id DESC LIMIT 1`, @@ -445,6 +469,16 @@ UPDATE knowledge_bases SET embedding_model_id='r38-model',vector_store_id='r38-v } beforeTarget = r38TargetRows(t, fx) } + if earlyBranch { + // 早段的冲突锚点:before-image 目标文档。发布整库替换时它会被删掉,恢复的 database + // 阶段必须按原 id 插回;外部范围同主键行会让那条真实 INSERT 报 23505。 + must(fx.pool.QueryRow(ctx, `SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2 ORDER BY id LIMIT 1`, + wsTargetTenant, wsTargetKB).Scan(&conflictKnowledge)) + if conflictKnowledge == "" { + t.Fatal("pg early branch needs a before-image knowledge identity to collide with") + } + beforeTarget = r38TargetRows(t, fx) + } if fullShape { for _, table := range ds02TargetTables { if len(beforePG[table]) == 0 { @@ -483,7 +517,12 @@ UPDATE knowledge_bases SET embedding_model_id='r38-model',vector_store_id='r38-v var source string var sourceParts map[string]int64 if fullShape { - spec = ds02SourceSpec(t, fx) + if earlyBranch { + // 早段专用来源副本:doc-src2 pending=0/completed,已通过上面的正式结算检查。 + spec = earlySourceSpec + } else { + spec = ds02SourceSpec(t, fx) + } expectation = ds02Expected(t, fx, spec) source = r38SealFullShape(t, fx, spec, mapping) save("04-snapshot.json", map[string]any{"snapshot": source, "index_mapping_sha256": mapping, "full_shape": true}) @@ -811,10 +850,15 @@ UPDATE knowledge_bases SET embedding_model_id='r38-model',vector_store_id='r38-v pgFault = r38ArmPGFault(t, fx, conflictLog) save("08e-pg-fault-armed.json", pgFault) } + if earlyBranch { + pgFault = r38ArmPGEarlyFault(t, fx, conflictKnowledge) + save("08e-pg-early-fault-armed.json", pgFault) + } must(os.WriteFile(filepath.Join(root, "barriers", "after-wiki.go"), []byte("release"), 0600)) save("08a-barrier.json", map[string]any{"point": "after:wiki", "hit": true, "released": true, "verify_corruption_armed": true, "refuse_clean_dispatch": !fullShape, - "refuse_object_restore_dispatch": objectBranch, "refuse_pg_restore": pgBranch, "scenario": scenario}) + "refuse_object_restore_dispatch": objectBranch, "refuse_pg_restore": pgBranch, + "refuse_pg_early_restore": earlyBranch, "scenario": scenario}) released = true break } @@ -861,6 +905,24 @@ UPDATE knowledge_bases SET embedding_model_id='r38-model',vector_store_id='r38-v save("09a-pg-failure.json", map[string]any{"job": job.ID, "error": libraryAfterPublish.Error, "recovery": libraryAfterPublish.Recovery, "failed_stage": libraryAfterPublish.Stage, "expected_sqlstate": r38PGSQLState, "fault_armed": pgFault, "matched_sqlstate": true}) + case earlyBranch: + // 失败必须来自恢复的第一段 database,且是同一条真实主键冲突;不能拿后段 wiki 的 + // 成功/失败冒充早段结论。 + if !strings.Contains(failureText, "恢复失败") || !strings.Contains(failureText, "恢复阶段 database 失败") { + t.Fatalf("publish failure does not name the failed early PG database stage: %q", failureText) + } + if strings.Contains(failureText, "恢复阶段 wiki 失败") { + t.Fatalf("early branch was mislabelled as a wiki-stage failure: %q", failureText) + } + if !strings.Contains(failureText, "SQLSTATE "+r38PGSQLState) { + t.Fatalf("publish failure carries no SQLSTATE %s: %q", r38PGSQLState, failureText) + } + if strings.Contains(failureText, "index effect outcome unknown") || strings.Contains(failureText, "conditional object cleanup not confirmed") { + t.Fatalf("early branch was mislabelled as an ES or object failure: %q", failureText) + } + save("09a-pg-early-failure.json", map[string]any{"job": job.ID, "error": libraryAfterPublish.Error, + "recovery": libraryAfterPublish.Recovery, "failed_stage": libraryAfterPublish.Stage, + "expected_sqlstate": r38PGSQLState, "fault_armed": pgFault, "matched_sqlstate": true}) default: if !strings.Contains(failureText, "恢复失败") || !strings.Contains(failureText, "index effect outcome unknown") { t.Fatalf("publish failure does not name the refused rollback write: %q", failureText) @@ -907,15 +969,30 @@ UPDATE knowledge_bases SET embedding_model_id='r38-model',vector_store_id='r38-v // 失败现场必须保留:故障未自行解除,失败事务没有提交,目标仍是发布写入后的内容。 save("11a-pg-failed-restore.json", r38PGFaultHeld(t, fx, beforeTarget, appliedRows, failureText, conflictLog)) } + if earlyBranch { + // 早段失败:database 阶段整个事务回滚,十张表都还是发布写入后的内容。 + save("11a-pg-early-failed-restore.json", r38PGEarlyFaultHeld(t, fx, beforeTarget, appliedRows, failureText, conflictKnowledge)) + } // 精确边界:restore-finalize-intent 已落盘、marker 原样停在自己世代上、clean 未派发。 effects := r38IndexEffects(t, archiveRoot, "chunk-target") save("12-index-effects-held.json", effects) switch { - case fullShape: - // 对象分支的 ES clean 写入已成功:索引恢复回执必须存在,这不是被拒的边界。 + case objectBranch, pgBranch: + // 对象分支的 ES clean 写入已成功;PG wiki 分支的 index 阶段先于 wiki 提交。 + // 两者都必须有恢复回执,这不是被拒的边界。 if _, ok := effects["restored"]; !ok { - t.Fatalf("object branch expected a completed index restore receipt (have %v)", effectPhases(effects)) + t.Fatalf("branch expected a completed index restore receipt (have %v)", effectPhases(effects)) + } + case earlyBranch: + // 早段在 database 就失败:index 阶段根本没跑,索引仍是发布写入后的那一代。 + for _, phase := range []string{"apply-intent", "applied"} { + if _, ok := effects[phase]; !ok { + t.Fatalf("early held boundary missing publish %s evidence (have %v)", phase, effectPhases(effects)) + } + } + if _, ok := effects["restored"]; ok { + t.Fatalf("early held boundary must not carry a restored receipt (have %v)", effectPhases(effects)) } default: for _, phase := range []string{"apply-intent", "applied", "restore-intent", "restore-claimed", "restore-finalize-intent"} { @@ -935,7 +1012,16 @@ UPDATE knowledge_bases SET embedding_model_id='r38-model',vector_store_id='r38-v } heldSource := heldDoc["_source"].(map[string]any) heldContent, _ := heldSource["content"].(string) - if fullShape { + if earlyBranch { + // database 阶段失败时索引还没被恢复:既不能有恢复 marker,也不能回到 before-image。 + if strings.HasPrefix(heldContent, indexRestoreClaimPrefix) { + t.Fatalf("early held index must not carry a restore marker: %q", heldContent) + } + appliedSource := appliedIndex["chunk-target"]["_source"] + if !reflect.DeepEqual(appliedSource, heldSource) { + t.Fatal("early held index must still be the applied publish content") + } + } else if fullShape { // 对象分支里索引已恢复,marker 不能还在:否则说明失败的其实是 ES 分支。 if strings.HasPrefix(heldContent, indexRestoreClaimPrefix) { t.Fatalf("object branch left the ES restore marker in place: %q", heldContent) @@ -1087,10 +1173,14 @@ UPDATE knowledge_bases SET embedding_model_id='r38-model',vector_store_id='r38-v // 只解除本轮注入的 PG 故障(drop trigger/function/switch table),不动共享 PG 本身。 save("17b-pg-fault-disarmed.json", r38DisarmPGFault(t, fx, conflictLog)) } + if earlyBranch { + // 精确解除:只删那一行外部范围的 knowledges 占位行;不换成删除 held 记录或重拍备份。 + save("17b-pg-early-fault-disarmed.json", r38DisarmPGEarlyFault(t, fx, conflictKnowledge)) + } save("17a-recover-request.json", map[string]any{"window_job_id": job.ID, "scope": "internal", "backup_snapshot_id": backupID, "original_job": job.ID, "object_fault_removed": objectBranch, - "pg_fault_removed": pgBranch, - "publish_entry": "store.CreateLibraryDispatch (publish API entry not proven)"}) + "pg_fault_removed": pgBranch, "pg_early_fault_removed": earlyBranch, + "publish_entry": "store.CreateLibraryDispatch (publish API entry not proven)"}) code, accepted := api.do(t, http.MethodPost, "/api/v1/library/maintenance/recover", map[string]any{"scope": "internal", "window_job_id": job.ID}) if code != http.StatusAccepted { @@ -1512,8 +1602,8 @@ UPDATE knowledge_bases SET embedding_model_id='r38-model',vector_store_id='r38-v _ = worker.Wait() objectEventsAfter, objectRefused, objectForwarded := objectProxy.snapshot() save("28-result.json", map[string]any{"scenario": scenario, "object_restore_branch": objectBranch, - "pg_restore_branch": pgBranch, - "window_job": job.ID, "publish_queue": queueID, + "pg_restore_branch": pgBranch, "pg_early_restore_branch": earlyBranch, + "window_job": job.ID, "publish_queue": queueID, "recovery_queue": recoveryQueueID, "backup": backupID, "scope": "internal", "instance": cfg.LibraryTargetInstance, "held": map[string]any{"journal": "held/restore_blocked", "maintenance": "needs_restore", "entry_http": 409}, "recovered": map[string]any{"journal": "recovered", "maintenance_released": true, "entry_http": 200,