将可维护总表与可替换2.0镜像分离,稳定来源关联和原始事件键保留; 源端更新/删除不覆盖主表或人工复核。首次收录保留原评估审计, 主表输入/复核独立持久化;历史原标注不冒充新AI或冻结证据。 历史导入绑定源哈希、逐行批准清单与真实恢复备份;三字段精确去重, 批次及原字段留档,重复执行不覆盖后续修改。仅操作本地治理库。 验证:完整make verify退出0;镜像与区域两组隔离PG race退出0; 真实恢复数据隔离导入12522、跳过792、暂缓1,总表15050; 重放保留模拟修改,结构down拒绝丢历史;真实浏览器第41周551条完整, 历史原标注和独立主表复核读回通过,移动布局及JS异常0。
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (s *Store) MasterQualityStore() *qaopsquality.Store {
|
||||
return qaopsquality.NewStore(s.pool, s.tenant+"::master")
|
||||
}
|
||||
|
||||
const masterBaseSQL = `WITH records AS (SELECT id,asked_at,question,status,identity,quality_hash,payload||jsonb_build_object('record_origin',origin) AS payload FROM qa_ops_master_records WHERE tenant_key=$1)`
|
||||
|
||||
var masterMetadataBase = strings.NewReplacer("qa_ops_mirror_records", "qa_ops_master_records", "h.tenant_key=m.tenant_key", "h.tenant_key=m.tenant_key||'::master'").Replace(localMetadataBase)
|
||||
var masterSummarySQL = masterMetadataBase + ` SELECT count(*),'{}'::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text,COALESCE(jsonb_agg(jsonb_build_object('id',id,'input_hash',quality_hash,'marker',marker,'source',source_coverage)),'[]'::jsonb)::text FROM records WHERE $5::text IS NOT NULL AND `
|
||||
var masterQualityScopeSQL = masterMetadataBase + ` SELECT id,quality_hash,marker,source_coverage::text FROM records WHERE $5::text IS NOT NULL AND `
|
||||
|
||||
func (s *Store) ListMasterRecords(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
var revision int64
|
||||
p, e := s.repositoryFor(&revision, true).ListRecords(ctx, q)
|
||||
p.LocalRevision = revision
|
||||
p.Columns = []string{"question_chinese", "answer", "coverage", "is_correct", "product_category", "problem_type", "root_cause", "asked_at", "asker", "question", "language", "trigger_person", "department", "region", "feedback"}
|
||||
return p, e
|
||||
}
|
||||
func (s *Store) ReadMasterQualityScope(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
return s.repositoryFor(nil, true).ReadQualityScope(ctx, q)
|
||||
}
|
||||
func (s *Store) GetMasterRecord(ctx context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
return s.repositoryFor(nil, true).GetRecord(ctx, tenant, id)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMasterAdmissionPreservesPreExistingSourceReviewHistory(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(p, "fixture-pre-master-review")
|
||||
queue := pg.NewStore(p)
|
||||
entry := fixtureEntry("preexisting-review", "retained original answer")
|
||||
record, e := dobotaiops.DecodeMirrorPayload(string(entry.Payload))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
original := qaopsquality.NewStore(p, s.tenant)
|
||||
views, e := original.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
v := views[record.ID]
|
||||
receipt, e := original.Save(ctx, record, qaopsquality.SaveRequest{InputHash: v.InputHash, InputEpoch: v.InputEpoch, BaseRevision: v.Revision, Nonce: "fixture_pre_master_review_01", Reason: "existing fixture review", Fields: qaopsquality.Fields{Coverage: "covered", Correctness: "correct"}}, "fixture-original-reviewer")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
job := claimMirrorJob(t, s, queue, "admit-reviewed")
|
||||
source := &fixtureSource{rows: []dobotaiops.MirrorRecord{entry}}
|
||||
if e = s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
copy, e := s.MasterQualityStore().ReadViews(ctx, []dobotaiops.QualityKey{{ID: record.ID, InputHash: record.QualityInputHash}})
|
||||
if e != nil || copy[record.ID].State != "reviewed" || copy[record.ID].Revision != receipt.SavedRevision || copy[record.ID].LatestReview.Reviewer != "fixture-original-reviewer" {
|
||||
t.Fatal("existing source review/audit provenance was lost when admitted to master", e)
|
||||
}
|
||||
if _, e = original.History(ctx, record.ID, 0, 0); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMasterTableKeepsLocalEditsAcrossSourceRefreshAndDeletion(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(p, "fixture-master")
|
||||
queue := pg.NewStore(p)
|
||||
entry := fixtureEntry("master-source", "source original answer")
|
||||
var wire map[string]any
|
||||
if e := json.Unmarshal(entry.Payload, &wire); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
wire["asked_at"] = "2026-10-06T08:00:00+08:00"
|
||||
wire["asker"] = "fixture asker"
|
||||
entry.Payload, _ = json.Marshal(wire)
|
||||
keeper := fixtureEntry("other-outside-window", "unrelated retained row")
|
||||
source := &fixtureSource{rows: []dobotaiops.MirrorRecord{entry, keeper}}
|
||||
job := claimMirrorJob(t, s, queue, "master-first")
|
||||
if e := s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
start, _ := time.Parse(time.RFC3339, "2026-10-05T00:00:00+08:00")
|
||||
q := dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: start.AddDate(0, 0, 7)}, Limit: 100}
|
||||
if err := queue.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, e := s.ListMasterRecords(ctx, q)
|
||||
if e != nil || page.Total != 1 || len(page.Items) != 1 {
|
||||
t.Fatal("new source record was not admitted into the durable master", e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, `UPDATE qa_ops_master_records SET payload=jsonb_set(payload,'{answer}','"local edited answer"') WHERE tenant_key=$1 AND id='master-source'`, s.tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
wire["answer"] = "changed at source"
|
||||
entry.Payload, _ = json.Marshal(wire)
|
||||
entry.Key.Fingerprint = stringsForMasterFixture("b")
|
||||
source.rows = []dobotaiops.MirrorRecord{entry, keeper}
|
||||
job = claimMirrorJob(t, s, queue, "master-source-update")
|
||||
if e = s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if err := queue.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, e = s.ListMasterRecords(ctx, q)
|
||||
if e != nil || page.Items[0].Answer != "local edited answer" {
|
||||
t.Fatal("source refresh overwrote master edits", e)
|
||||
}
|
||||
source.rows = []dobotaiops.MirrorRecord{keeper}
|
||||
job = claimMirrorJob(t, s, queue, "master-source-delete")
|
||||
if e = s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if err := queue.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, e = s.ListMasterRecords(ctx, q)
|
||||
if e != nil || page.Total != 1 || page.Items[0].Answer != "local edited answer" {
|
||||
t.Fatal("source deletion removed local master content", e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, `UPDATE qa_ops_mirror_state SET ready=false,blocked=true WHERE tenant_key=$1`, s.tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
page, e = s.ListMasterRecords(ctx, q)
|
||||
if e != nil || page.Total != 1 {
|
||||
t.Fatal("source availability blocked independent master data", e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, `UPDATE qa_ops_master_records SET payload=jsonb_set(payload,'{id}','"relabelled-id"') WHERE tenant_key=$1 AND id='master-source'`, s.tenant); e == nil {
|
||||
t.Fatal("master payload ID was allowed to diverge from the stable master ID")
|
||||
}
|
||||
}
|
||||
func stringsForMasterFixture(s string) string {
|
||||
out := ""
|
||||
for i := 0; i < 64; i++ {
|
||||
out += s
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMasterHumanReviewIsIndependentOfSourceInputUpdates(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(p, "fixture-master-quality")
|
||||
queue := pg.NewStore(p)
|
||||
source := &fixtureSource{rows: []dobotaiops.MirrorRecord{fixtureEntry("master-review", "first")}}
|
||||
job := claimMirrorJob(t, s, queue, "review-first")
|
||||
if e := s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := queue.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
rec, e := s.GetMasterRecord(ctx, s.tenant, "master-review")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
quality := s.MasterQualityStore()
|
||||
key := []dobotaiops.QualityKey{{ID: rec.ID, InputHash: rec.QualityInputHash}}
|
||||
views, e := quality.ReadViews(ctx, key)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
v := views[rec.ID]
|
||||
request := qaopsquality.SaveRequest{InputHash: v.InputHash, InputEpoch: v.InputEpoch, BaseRevision: v.Revision, Nonce: "fixture_master_review_001", Reason: "fixture only", Fields: qaopsquality.Fields{Coverage: "covered", Correctness: "correct", ProductCategory: "fixture-local"}}
|
||||
if _, e = quality.Save(ctx, rec, request, "fixture-admin"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
source.rows = []dobotaiops.MirrorRecord{fixtureEntry("master-review", "changed at source")}
|
||||
job = claimMirrorJob(t, s, queue, "review-source-change")
|
||||
if e = s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
views, e = quality.ReadViews(ctx, key)
|
||||
if e != nil || views[rec.ID].State != "reviewed" || views[rec.ID].Effective.ProductCategory != "fixture-local" {
|
||||
t.Fatal("source sync invalidated a locally-owned master review", e)
|
||||
}
|
||||
current, e := qaopsquality.NewStore(p, s.tenant).ReadViews(ctx, []dobotaiops.QualityKey{{ID: rec.ID, InputHash: sourceRecordHash(t, source.rows[0])}})
|
||||
if e != nil || current[rec.ID].Revision != 0 {
|
||||
t.Fatal("master review modified original source evaluation", e)
|
||||
}
|
||||
}
|
||||
func sourceRecordHash(t *testing.T, r dobotaiops.MirrorRecord) string {
|
||||
t.Helper()
|
||||
v, e := dobotaiops.DecodeMirrorPayload(string(r.Payload))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return v.QualityInputHash
|
||||
}
|
||||
@@ -98,8 +98,15 @@ func (s *Store) Available(ctx context.Context) error {
|
||||
}
|
||||
func (s *Store) Safety() dobotaiops.SourceSafety { s.mu.RLock(); defer s.mu.RUnlock(); return s.safety }
|
||||
func (s *Store) repository(revision *int64) *dobotaiops.RecordsRepository {
|
||||
return s.repositoryFor(revision, false)
|
||||
}
|
||||
func (s *Store) repositoryFor(revision *int64, master bool) *dobotaiops.RecordsRepository {
|
||||
base, summary, scope := localBaseSQL, localSummarySQL, localQualityScopeSQL
|
||||
if master {
|
||||
base, summary, scope = masterBaseSQL, masterSummarySQL, masterQualityScopeSQL
|
||||
}
|
||||
return dobotaiops.NewRecordsRepository(dobotaiops.RecordsRepositoryOptions{
|
||||
BaseSQL: localBaseSQL, SummarySQL: localSummarySQL, QualityScopeSQL: localQualityScopeSQL, TenantKey: s.tenant,
|
||||
BaseSQL: base, SummarySQL: summary, QualityScopeSQL: scope, TenantKey: s.tenant,
|
||||
ValidateWindow: func(w dobotaiops.Window) error {
|
||||
if w.TenantKey != s.tenant {
|
||||
return dobotaiops.ErrInvalidQuery
|
||||
@@ -108,6 +115,9 @@ func (s *Store) repository(revision *int64) *dobotaiops.RecordsRepository {
|
||||
return e
|
||||
},
|
||||
ReadAsOf: func(ctx context.Context, q dobotaiops.RecordQuerier, t *time.Time) error {
|
||||
if master {
|
||||
return q.QueryRow(ctx, `SELECT updated_at FROM qa_ops_master_state WHERE tenant_key=$1`, s.tenant).Scan(t)
|
||||
}
|
||||
return q.QueryRow(ctx, `SELECT source_observed_at FROM qa_ops_mirror_state WHERE tenant_key=$1`, s.tenant).Scan(t)
|
||||
},
|
||||
Transaction: func(ctx context.Context, fn func(context.Context, dobotaiops.RecordQuerier) error) error {
|
||||
@@ -122,18 +132,26 @@ func (s *Store) repository(revision *int64) *dobotaiops.RecordsRepository {
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
q := txQuery{tx}
|
||||
state, e := s.readState(ctx, q)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if state.Blocked {
|
||||
return dobotaiops.ErrNotReadOnly
|
||||
}
|
||||
if !state.Ready {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
if revision != nil {
|
||||
*revision = state.Revision
|
||||
if master {
|
||||
if revision != nil {
|
||||
if e = q.QueryRow(ctx, `SELECT COALESCE((SELECT revision FROM qa_ops_master_state WHERE tenant_key=$1),0)`, s.tenant).Scan(revision); e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
}
|
||||
} else {
|
||||
state, err := s.readState(ctx, q)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if state.Blocked {
|
||||
return dobotaiops.ErrNotReadOnly
|
||||
}
|
||||
if !state.Ready {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
if revision != nil {
|
||||
*revision = state.Revision
|
||||
}
|
||||
}
|
||||
if e = fn(ctx, q); e != nil {
|
||||
return e
|
||||
|
||||
@@ -26,7 +26,7 @@ func TestLocalMirrorMetadataDoesNotReadLargeAnswerPayload(t *testing.T) {
|
||||
if _, e = p.Exec(ctx, `INSERT INTO qa_ops_mirror_state(tenant_key,ready,revision,record_count,source_observed_at,synced_at) VALUES($1,true,1,1,now(),now());`, tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, `INSERT INTO qa_ops_mirror_records(tenant_key,id,fingerprint,asked_at,question,status,identity,quality_hash,payload) VALUES($1,$2,$3,now()-interval '1 hour','fixture','succeeded','{}',$3,'{}')`, tenant, record.ID, hash); e != nil {
|
||||
if _, e = p.Exec(ctx, `INSERT INTO qa_ops_mirror_records(tenant_key,id,fingerprint,asked_at,question,status,identity,quality_hash,payload) VALUES($1,$2,$3,now()-interval '1 hour','fixture','succeeded','{}',$3,jsonb_build_object('id',$2::text))`, tenant, record.ID, hash); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
role := fmt.Sprintf("kg_mirror_metadata_%d", time.Now().UnixNano())
|
||||
@@ -34,7 +34,7 @@ func TestLocalMirrorMetadataDoesNotReadLargeAnswerPayload(t *testing.T) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer func() { p.Exec(ctx, "DROP OWNED BY "+role); p.Exec(ctx, "DROP ROLE "+role) }()
|
||||
if _, e = p.Exec(ctx, "GRANT SELECT(tenant_key,id,fingerprint,asked_at,question,status,identity,quality_hash) ON qa_ops_mirror_records TO "+role+";GRANT SELECT ON qa_ops_mirror_state,qa_ops_quality_records,qa_ops_quality_inputs,qa_ops_quality_checks TO "+role); e != nil {
|
||||
if _, e = p.Exec(ctx, "GRANT SELECT(tenant_key,id,fingerprint,asked_at,question,status,identity,quality_hash) ON qa_ops_mirror_records TO "+role+";GRANT SELECT(tenant_key,id,asked_at,question,status,identity,quality_hash) ON qa_ops_master_records TO "+role+";GRANT SELECT ON qa_ops_master_state,qa_ops_mirror_state,qa_ops_quality_records,qa_ops_quality_inputs,qa_ops_quality_checks TO "+role); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
config := p.Config().Copy()
|
||||
@@ -48,6 +48,10 @@ func TestLocalMirrorMetadataDoesNotReadLargeAnswerPayload(t *testing.T) {
|
||||
if e != nil || len(scope.Keys) != 1 || !scope.Keys[0].Marker {
|
||||
t.Fatal("local metadata still requires SELECT on large payload instead of committed quality evidence", e)
|
||||
}
|
||||
scope, e = NewStore(limited, tenant).ReadMasterQualityScope(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: tenant, Start: time.Now().Add(-2 * time.Hour), End: time.Now()}, Limit: 100})
|
||||
if e != nil || len(scope.Keys) != 1 || !scope.Keys[0].Marker {
|
||||
t.Fatal("master metadata requires forbidden payload access or lost copied coverage evidence", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalMirrorStoredQualityUsesReadOnlyBatchedProjection(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user