feat(qa-ops): 完成复检留档与人工复核闭环

治理侧保存输入观测版本、自动复检及人工复核历史,输入变化失效、版本冲突和幂等重放不覆盖人工记录。批量质量数量使用完整筛选元数据,未采集原文不伪造快照,延迟旧扫描不回退新输入。

验证:全仓 make verify 退出码0,Go656及前端253通过;五包竞态、源/组织/质量隔离PG、真实只读源和隔离网页读回复核通过。默认91个可选集成跳过不计通过。未接AI模型,不写DobotAI源库,未推送、未合并、未部署。
This commit is contained in:
姚章浩
2026-10-17 22:37:26 +08:00
parent 9556db1ef0
commit 4b3aaff321
30 changed files with 2483 additions and 30 deletions
+125
View File
@@ -0,0 +1,125 @@
package qaopsquality
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"knowledge-governance/internal/dobotaiops"
"regexp"
"strings"
"unicode/utf8"
)
var hashPattern = regexp.MustCompile(`^[a-f0-9]{64}$`)
var noncePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`)
func validText(s string, max int) bool {
return utf8.ValidString(s) && utf8.RuneCountInString(s) <= max && !strings.ContainsRune(s, 0)
}
func validID(s string) bool { return strings.TrimSpace(s) != "" && validText(s, 256) }
func canonical(raw json.RawMessage) (json.RawMessage, error) {
if len(raw) == 0 {
return json.RawMessage("null"), nil
}
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber()
var v any
if decoder.Decode(&v) != nil {
return nil, ErrInvalid
}
var extra any
if decoder.Decode(&extra) != io.EOF {
return nil, ErrInvalid
}
out, err := json.Marshal(v)
return out, err
}
func EvidenceFor(record dobotaiops.Record) (Evidence, error) {
if !validID(record.ID) {
return Evidence{}, ErrInvalid
}
refs, err := canonical(record.References)
if err != nil {
return Evidence{}, ErrInvalid
}
media, err := canonical(record.Media)
if err != nil {
return Evidence{}, ErrInvalid
}
// Keep only assessment inputs, never personnel or mutable feedback/organisation.
payload, err := json.Marshal(struct {
Version string `json:"version"`
ID string `json:"id"`
Status string `json:"status"`
Question string `json:"question"`
Answer string `json:"answer"`
References json.RawMessage `json:"references"`
Media json.RawMessage `json:"media"`
}{"dobotai-2.0-dingtalk-quality-v1", record.ID, record.Status, record.Question, record.Answer, refs, media})
if err != nil || len(payload) > 8<<20 {
return Evidence{}, ErrInvalid
}
sum := sha256.Sum256(payload)
hash := hex.EncodeToString(sum[:])
if record.QualityInputHash != "" {
if !hashPattern.MatchString(record.QualityInputHash) {
return Evidence{}, ErrInvalid
}
hash = record.QualityInputHash
}
return Evidence{Hash: hash, Payload: payload, Record: record, Result: dobotaiops.CheckAnswerCoverage(record.Answer)}, nil
}
func Validate(r SaveRequest) error {
if !hashPattern.MatchString(r.InputHash) || r.InputEpoch < 1 || r.BaseRevision < 0 || !noncePattern.MatchString(r.Nonce) || strings.TrimSpace(r.Reason) == "" || !validText(r.Reason, 4000) {
return ErrInvalid
}
f := r.Fields
validCoverage := false
for _, s := range []string{"covered", "uncovered", "partial", "pending", "excluded"} {
validCoverage = validCoverage || f.Coverage == s
}
if !validCoverage || (f.Correctness != "correct" && f.Correctness != "incorrect" && f.Correctness != "pending") {
return ErrInvalid
}
if !validText(f.ProductCategory, 128) || !validText(f.ProblemType, 128) || !validText(f.RootCause, 2000) || !validText(f.ExclusionReason, 2000) {
return ErrInvalid
}
if f.Correctness == "correct" && f.RootCause != "" || f.Coverage == "excluded" && strings.TrimSpace(f.ExclusionReason) == "" || f.Coverage != "excluded" && f.ExclusionReason != "" {
return ErrInvalid
}
return nil
}
func Project(hash string, epoch, revision int64, automatic Check, review *Review) View {
view := View{InputHash: hash, InputEpoch: epoch, Revision: revision, State: "unreviewed", Automatic: automatic, LatestReview: review, Effective: Fields{Coverage: automatic.Result.Verdict}}
if review == nil {
return view
}
view.State = "stale"
if review.InputEpoch == epoch && review.InputHash == hash {
view.State = "reviewed"
view.Effective = review.Fields
}
return view
}
func Summarize(views map[string]View) Summary {
result := Summary{Total: len(views)}
for _, v := range views {
switch v.State {
case "reviewed":
result.Reviewed++
if v.Effective.Coverage == "pending" || v.Effective.Correctness == "pending" {
result.PendingConfirmation++
}
case "stale":
result.Stale++
default:
result.Unreviewed++
}
if v.Automatic.Result.Verdict == "uncovered" {
result.RuleUncovered++
}
}
return result
}
+98
View File
@@ -0,0 +1,98 @@
package qaopsquality
import (
"encoding/json"
"errors"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/dobotaiops"
"time"
)
var ErrInvalid = errors.New("invalid quality request")
var ErrConflict = errors.New("quality input or review revision changed")
var ErrUnavailable = errors.New("quality store unavailable")
var ErrNotFound = errors.New("quality input snapshot not found")
var ErrSnapshotMissing = errors.New("only quality metadata was observed for this input")
type Fields struct {
Coverage string `json:"coverage"`
Correctness string `json:"correctness"`
ProductCategory string `json:"product_category"`
ProblemType string `json:"problem_type"`
RootCause string `json:"root_cause"`
ExclusionReason string `json:"exclusion_reason"`
}
type SaveRequest struct {
InputHash string `json:"input_hash"`
InputEpoch int64 `json:"input_epoch"`
BaseRevision int64 `json:"base_revision"`
Nonce string `json:"nonce"`
Fields Fields `json:"fields"`
Reason string `json:"reason"`
}
type Review struct {
Revision int64 `json:"revision"`
InputEpoch int64 `json:"input_epoch"`
InputHash string `json:"input_hash"`
Fields Fields `json:"fields"`
Reason string `json:"reason"`
Reviewer string `json:"reviewer"`
CreatedAt time.Time `json:"created_at"`
}
type Check struct {
InputAvailable bool `json:"input_available"`
ID int64 `json:"id"`
InputEpoch int64 `json:"input_epoch"`
InputHash string `json:"input_hash"`
Result dobotaiops.CoverageCheck `json:"result"`
Source dobotaiops.SourceCoverage `json:"source"`
CreatedAt time.Time `json:"created_at"`
}
type View struct {
InputHash string `json:"input_hash"`
InputEpoch int64 `json:"input_epoch"`
Revision int64 `json:"revision"`
State string `json:"state"`
Automatic Check `json:"automatic"`
LatestReview *Review `json:"latest_review"`
Effective Fields `json:"effective"`
}
type History struct {
Reviews []Review `json:"reviews"`
Checks []Check `json:"checks"`
NextReview int64 `json:"next_review"`
NextCheck int64 `json:"next_check"`
}
type Summary struct {
Total int `json:"total"`
Reviewed int `json:"reviewed"`
Unreviewed int `json:"unreviewed"`
Stale int `json:"stale"`
PendingConfirmation int `json:"pending_confirmation"`
RuleUncovered int `json:"rule_uncovered"`
}
type Receipt struct {
View View `json:"view"`
SavedRevision int64 `json:"saved_revision"`
Replayed bool `json:"replayed"`
}
type Evidence struct {
Result dobotaiops.CoverageCheck
Hash string
Payload json.RawMessage
Record dobotaiops.Record
}
type Snapshot struct {
InputEpoch int64 `json:"input_epoch"`
InputHash string `json:"input_hash"`
Payload json.RawMessage `json:"payload"`
CreatedAt time.Time `json:"created_at"`
}
type Store struct {
pool *pgxpool.Pool
tenant string
}
func NewStore(pool *pgxpool.Pool, tenant string) *Store { return &Store{pool: pool, tenant: tenant} }
+73
View File
@@ -0,0 +1,73 @@
package qaopsquality
import (
"encoding/json"
"knowledge-governance/internal/dobotaiops"
"strings"
"testing"
)
func TestEvidenceBindsQualityInputsNotPeopleFeedbackOrJSONKeyOrder(t *testing.T) {
record := dobotaiops.Record{ID: "fixture-turn", Status: "succeeded", Question: "示例问题", Answer: "有暂无已发布但存在引用", References: json.RawMessage(`[{"b":2,"a":1}]`), Media: json.RawMessage(`[]`)}
a, err := EvidenceFor(record)
if err != nil || len(a.Hash) != 64 || !strings.Contains(string(a.Payload), record.Answer) {
t.Fatal("quality inputs not snapshotted")
}
record.Asker = "another-person"
record.Department = "changed"
record.Feedback.Up = 10
record.References = json.RawMessage(`[{"a":1,"b":2}]`)
b, _ := EvidenceFor(record)
if b.Hash != a.Hash {
t.Fatal("irrelevant identity/feedback or JSON object ordering invalidated review")
}
record.Answer = "原答案变更"
b, _ = EvidenceFor(record)
if b.Hash == a.Hash {
t.Fatal("answer change undetected")
}
}
func TestHumanProjectionKeepsRuleAndStalesObservedInputChanges(t *testing.T) {
automatic := Check{Result: dobotaiops.CheckAnswerCoverage("暂无已发布"), InputEpoch: 2, InputHash: strings.Repeat("a", 64)}
review := &Review{InputEpoch: 1, InputHash: automatic.InputHash, Fields: Fields{Coverage: "covered", Correctness: "correct", ProductCategory: "MG400"}}
view := Project(automatic.InputHash, 2, 1, automatic, review)
if view.State != "stale" || view.Effective.Coverage != "uncovered" || view.Effective.Correctness != "" {
t.Fatal("old conclusion remained effective after input epoch changed")
}
review.InputEpoch = 2
view = Project(automatic.InputHash, 2, 1, automatic, review)
if view.State != "reviewed" || view.Effective.Coverage != "covered" || view.Automatic.Result.Verdict != "uncovered" {
t.Fatal("human and immutable rule not separated")
}
summary := Summarize(map[string]View{"a": view, "b": Project(automatic.InputHash, 3, 1, automatic, review), "c": Project(automatic.InputHash, 1, 0, automatic, nil)})
if summary.Total != 3 || summary.Reviewed != 1 || summary.Stale != 1 || summary.Unreviewed != 1 || summary.PendingConfirmation != 0 {
t.Fatal("quality counts invent rates or unknown judgments")
}
}
func TestReviewRequiresExplicitOutcomesAndEvidence(t *testing.T) {
valid := SaveRequest{InputHash: strings.Repeat("a", 64), InputEpoch: 1, Nonce: strings.Repeat("n", 32), Fields: Fields{Coverage: "uncovered", Correctness: "pending"}, Reason: "人工核对引用与答案,证据不足"}
if Validate(valid) != nil {
t.Fatal("valid review rejected")
}
for _, field := range []string{"reason", "hash", "coverage", "correctness", "root", "exclusion"} {
bad := valid
switch field {
case "reason":
bad.Reason = " "
case "hash":
bad.InputHash = "malformed"
case "coverage":
bad.Fields.Coverage = ""
case "correctness":
bad.Fields.Correctness = ""
case "root":
bad.Fields.Correctness = "correct"
bad.Fields.RootCause = "知识缺失"
case "exclusion":
bad.Fields.Coverage = "excluded"
}
if Validate(bad) == nil {
t.Fatal("invalid review accepted", field)
}
}
}
+322
View File
@@ -0,0 +1,322 @@
package qaopsquality
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/dobotaiops"
"sort"
"time"
)
func (s *Store) Columns(ctx context.Context, keys []dobotaiops.QualityKey) ([]string, error) {
if !s.available() {
return nil, ErrUnavailable
}
if len(keys) > 100000 {
return nil, ErrInvalid
}
for _, key := range keys {
if !validID(key.ID) || !hashPattern.MatchString(key.InputHash) {
return nil, ErrInvalid
}
}
raw, err := json.Marshal(keys)
if err != nil {
return nil, ErrInvalid
}
if len(keys) == 0 {
return []string{}, nil
}
var coverage, correctness, product, problem, root bool
err = s.pool.QueryRow(ctx, `SELECT COALESCE(bool_or(r.fields->>'coverage'<>''),false),COALESCE(bool_or(r.fields->>'correctness'<>''),false),COALESCE(bool_or(r.fields->>'product_category'<>''),false),COALESCE(bool_or(r.fields->>'problem_type'<>''),false),COALESCE(bool_or(r.fields->>'root_cause'<>''),false) FROM jsonb_to_recordset($2::jsonb) k(id text,input_hash text) JOIN qa_ops_quality_records h ON h.tenant_key=$1 AND h.record_id=k.id AND h.input_hash=k.input_hash JOIN qa_ops_quality_reviews r ON r.tenant_key=h.tenant_key AND r.record_id=h.record_id AND r.revision=h.review_revision AND r.input_epoch=h.input_epoch`, s.tenant, raw).Scan(&coverage, &correctness, &product, &problem, &root)
if err != nil {
return nil, ErrUnavailable
}
out := []string{}
for _, c := range []struct {
key string
yes bool
}{{"coverage", coverage}, {"is_correct", correctness}, {"product_category", product}, {"problem_type", problem}, {"root_cause", root}} {
if c.yes {
out = append(out, c.key)
}
}
return out, nil
}
func (s *Store) Snapshot(ctx context.Context, id string, epoch int64) (Snapshot, error) {
if !s.available() {
return Snapshot{}, ErrUnavailable
}
if !validID(id) || epoch < 1 {
return Snapshot{}, ErrInvalid
}
var value Snapshot
value.InputEpoch = epoch
err := s.pool.QueryRow(ctx, `SELECT input_hash,payload,created_at FROM qa_ops_quality_inputs WHERE tenant_key=$1 AND record_id=$2 AND input_epoch=$3`, s.tenant, id, epoch).Scan(&value.InputHash, &value.Payload, &value.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return Snapshot{}, ErrNotFound
}
if err != nil {
return Snapshot{}, ErrUnavailable
}
if len(value.Payload) == 0 {
return Snapshot{}, ErrSnapshotMissing
}
return value, nil
}
func (s *Store) available() bool { return s != nil && s.pool != nil && validID(s.tenant) }
func (s *Store) observeLocked(ctx context.Context, tx pgx.Tx, e Evidence) error {
id := e.Record.ID
if _, err := tx.Exec(ctx, `INSERT INTO qa_ops_quality_records(tenant_key,record_id) VALUES($1,$2) ON CONFLICT DO NOTHING`, s.tenant, id); err != nil {
return ErrUnavailable
}
var previous string
var epoch int64
var observedAt *time.Time
if tx.QueryRow(ctx, `SELECT input_hash,input_epoch,observed_at FROM qa_ops_quality_records WHERE tenant_key=$1 AND record_id=$2 FOR UPDATE`, s.tenant, id).Scan(&previous, &epoch, &observedAt) != nil {
return ErrUnavailable
}
// Source transaction time orders concurrent page/detail/scope observations.
// A late different input is rejected, never projected against a newer answer.
if observedAt != nil && !e.Record.QualityObservedAt.IsZero() && e.Record.QualityObservedAt.Before(*observedAt) && previous != e.Hash {
return ErrConflict
}
if !e.Record.QualityObservedAt.IsZero() {
if _, err := tx.Exec(ctx, `UPDATE qa_ops_quality_records SET observed_at=$3 WHERE tenant_key=$1 AND record_id=$2 AND(observed_at IS NULL OR observed_at<$3)`, s.tenant, id, e.Record.QualityObservedAt); err != nil {
return ErrUnavailable
}
}
var payload any
if len(e.Payload) > 0 {
payload = e.Payload
}
if previous != e.Hash {
epoch++
if _, err := tx.Exec(ctx, `INSERT INTO qa_ops_quality_inputs(tenant_key,record_id,input_epoch,input_hash,payload) VALUES($1,$2,$3,$4,$5)`, s.tenant, id, epoch, e.Hash, payload); err != nil {
return ErrUnavailable
}
tag, err := tx.Exec(ctx, `UPDATE qa_ops_quality_records SET input_hash=$3,input_epoch=$4 WHERE tenant_key=$1 AND record_id=$2`, s.tenant, id, e.Hash, epoch)
if err != nil || tag.RowsAffected() != 1 {
return ErrUnavailable
}
}
if payload != nil {
if _, err := tx.Exec(ctx, `UPDATE qa_ops_quality_inputs SET payload=$4 WHERE tenant_key=$1 AND record_id=$2 AND input_epoch=$3 AND payload IS NULL`, s.tenant, id, epoch, payload); err != nil {
return ErrUnavailable
}
}
automatic, _ := json.Marshal(e.Result)
source, _ := json.Marshal(e.Record.SourceCoverage)
if _, err := tx.Exec(ctx, `INSERT INTO qa_ops_quality_checks(tenant_key,record_id,input_epoch,rule_version,result,source) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(tenant_key,record_id,input_epoch,rule_version) DO NOTHING`, s.tenant, id, epoch, dobotaiops.CoverageRuleVersion, automatic, source); err != nil {
return ErrUnavailable
}
return nil
}
const checkObject = `jsonb_build_object('id',c.id,'input_epoch',c.input_epoch,'input_hash',i.input_hash,'result',c.result,'source',c.source,'created_at',c.created_at,'input_available',i.payload IS NOT NULL)`
const reviewObject = `jsonb_build_object('revision',r.revision,'input_epoch',r.input_epoch,'input_hash',r.input_hash,'fields',r.fields,'reason',r.reason,'reviewer',r.reviewer,'created_at',r.created_at)`
func (s *Store) view(ctx context.Context, tx pgx.Tx, id string) (View, error) {
var hash, checkRaw, reviewRaw string
var epoch, revision int64
err := tx.QueryRow(ctx, `SELECT h.input_hash,h.input_epoch,h.review_revision,`+checkObject+`::text,COALESCE((SELECT `+reviewObject+` FROM qa_ops_quality_reviews r WHERE r.tenant_key=h.tenant_key AND r.record_id=h.record_id AND r.revision=h.review_revision),'null'::jsonb)::text FROM qa_ops_quality_records h JOIN qa_ops_quality_inputs i ON i.tenant_key=h.tenant_key AND i.record_id=h.record_id AND i.input_epoch=h.input_epoch JOIN qa_ops_quality_checks c ON c.tenant_key=h.tenant_key AND c.record_id=h.record_id AND c.input_epoch=h.input_epoch AND c.rule_version=$3 WHERE h.tenant_key=$1 AND h.record_id=$2`, s.tenant, id, dobotaiops.CoverageRuleVersion).Scan(&hash, &epoch, &revision, &checkRaw, &reviewRaw)
var automatic Check
var review *Review
if err != nil || json.Unmarshal([]byte(checkRaw), &automatic) != nil || json.Unmarshal([]byte(reviewRaw), &review) != nil {
return View{}, ErrUnavailable
}
return Project(hash, epoch, revision, automatic, review), nil
}
func (s *Store) Observe(ctx context.Context, records []dobotaiops.Record) (map[string]View, error) {
if len(records) > 5000 {
return nil, ErrInvalid
}
items := make([]Evidence, 0, len(records))
for _, record := range records {
e, err := EvidenceFor(record)
if err != nil {
return nil, err
}
items = append(items, e)
}
return s.observeEvidence(ctx, items)
}
func (s *Store) ObserveKeys(ctx context.Context, keys []dobotaiops.QualityKey) (map[string]View, error) {
if len(keys) > 5000 {
return nil, ErrInvalid
}
items := make([]Evidence, 0, len(keys))
for _, key := range keys {
if !validID(key.ID) || !hashPattern.MatchString(key.InputHash) {
return nil, ErrInvalid
}
items = append(items, Evidence{Hash: key.InputHash, Record: dobotaiops.Record{ID: key.ID, SourceCoverage: key.Source, QualityObservedAt: key.ObservedAt}, Result: dobotaiops.CheckMarkerCoverage(key.Marker)})
}
return s.observeEvidence(ctx, items)
}
func (s *Store) observeEvidence(ctx context.Context, items []Evidence) (map[string]View, error) {
if !s.available() {
return nil, ErrUnavailable
}
evidence := map[string]Evidence{}
ids := []string{}
bytes := 0
for _, e := range items {
id := e.Record.ID
if old, ok := evidence[id]; ok {
if old.Hash != e.Hash || old.Result != e.Result {
return nil, ErrInvalid
}
continue
}
evidence[id] = e
ids = append(ids, id)
bytes += len(e.Payload)
if bytes > 32<<20 {
return nil, ErrInvalid
}
}
sort.Strings(ids)
result := map[string]View{}
if len(ids) == 0 {
return result, nil
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return nil, ErrUnavailable
}
defer tx.Rollback(context.Background())
for _, id := range ids {
if err = s.observeLocked(ctx, tx, evidence[id]); err != nil {
return nil, err
}
v, err := s.view(ctx, tx, id)
if err != nil {
return nil, err
}
result[id] = v
}
if tx.Commit(ctx) != nil {
return nil, ErrUnavailable
}
return result, nil
}
func (s *Store) Save(ctx context.Context, record dobotaiops.Record, request SaveRequest, actor string) (Receipt, error) {
if !s.available() {
return Receipt{}, ErrUnavailable
}
if Validate(request) != nil || !validID(actor) {
return Receipt{}, ErrInvalid
}
e, err := EvidenceFor(record)
if err != nil {
return Receipt{}, err
}
payload, _ := json.Marshal(request)
sum := sha256.Sum256(payload)
requestHash := hex.EncodeToString(sum[:])
tx, err := s.pool.Begin(ctx)
if err != nil {
return Receipt{}, ErrUnavailable
}
defer tx.Rollback(context.Background())
if err = s.observeLocked(ctx, tx, e); err != nil {
return Receipt{}, err
}
var existingHash, existingActor string
var savedRevision int64
err = tx.QueryRow(ctx, `SELECT request_hash,reviewer,revision FROM qa_ops_quality_reviews WHERE tenant_key=$1 AND record_id=$2 AND nonce=$3`, s.tenant, record.ID, request.Nonce).Scan(&existingHash, &existingActor, &savedRevision)
replay := err == nil
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return Receipt{}, ErrUnavailable
}
current, err := s.view(ctx, tx, record.ID)
if err != nil {
return Receipt{}, err
}
if replay {
if existingHash != requestHash || existingActor != actor {
return Receipt{}, ErrConflict
}
} else {
if current.InputHash != request.InputHash || current.InputEpoch != request.InputEpoch || current.Revision != request.BaseRevision {
if tx.Commit(ctx) != nil {
return Receipt{}, ErrUnavailable
}
return Receipt{}, ErrConflict
}
savedRevision = current.Revision + 1
fields, _ := json.Marshal(request.Fields)
if _, err = tx.Exec(ctx, `INSERT INTO qa_ops_quality_reviews(tenant_key,record_id,revision,input_epoch,input_hash,fields,reason,reviewer,nonce,request_hash) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, s.tenant, record.ID, savedRevision, current.InputEpoch, current.InputHash, fields, request.Reason, actor, request.Nonce, requestHash); err != nil {
return Receipt{}, ErrUnavailable
}
tag, err := tx.Exec(ctx, `UPDATE qa_ops_quality_records SET review_revision=$3 WHERE tenant_key=$1 AND record_id=$2`, s.tenant, record.ID, savedRevision)
if err != nil || tag.RowsAffected() != 1 {
return Receipt{}, ErrUnavailable
}
current, err = s.view(ctx, tx, record.ID)
if err != nil {
return Receipt{}, err
}
}
if tx.Commit(ctx) != nil {
return Receipt{}, ErrUnavailable
}
return Receipt{View: current, SavedRevision: savedRevision, Replayed: replay}, nil
}
func (s *Store) History(ctx context.Context, id string, reviewBefore, checkBefore int64) (History, error) {
result := History{Reviews: []Review{}, Checks: []Check{}}
if !s.available() {
return result, ErrUnavailable
}
if !validID(id) || reviewBefore < 0 || checkBefore < 0 {
return result, ErrInvalid
}
rows, err := s.pool.Query(ctx, `SELECT `+reviewObject+`::text FROM qa_ops_quality_reviews r WHERE tenant_key=$1 AND record_id=$2 AND ($3::bigint=0 OR revision<$3) ORDER BY revision DESC LIMIT 21`, s.tenant, id, reviewBefore)
if err != nil {
return result, ErrUnavailable
}
for rows.Next() {
var raw string
var value Review
if rows.Scan(&raw) != nil || json.Unmarshal([]byte(raw), &value) != nil {
rows.Close()
return result, ErrUnavailable
}
result.Reviews = append(result.Reviews, value)
}
err = rows.Err()
rows.Close()
if err != nil {
return result, ErrUnavailable
}
if len(result.Reviews) > 20 {
result.Reviews = result.Reviews[:20]
result.NextReview = result.Reviews[19].Revision
}
rows, err = s.pool.Query(ctx, `SELECT `+checkObject+`::text FROM qa_ops_quality_checks c JOIN qa_ops_quality_inputs i USING(tenant_key,record_id,input_epoch) WHERE c.tenant_key=$1 AND c.record_id=$2 AND ($3::bigint=0 OR c.id<$3) ORDER BY c.id DESC LIMIT 21`, s.tenant, id, checkBefore)
if err != nil {
return result, ErrUnavailable
}
defer rows.Close()
for rows.Next() {
var raw string
var value Check
if rows.Scan(&raw) != nil || json.Unmarshal([]byte(raw), &value) != nil {
return result, ErrUnavailable
}
result.Checks = append(result.Checks, value)
}
if rows.Err() != nil {
return result, ErrUnavailable
}
if len(result.Checks) > 20 {
result.Checks = result.Checks[:20]
result.NextCheck = result.Checks[19].ID
}
return result, nil
}
@@ -0,0 +1,219 @@
package qaopsquality_test
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/dobotaiops"
pg "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/qaopsquality"
"net/url"
"os"
"strings"
"testing"
"time"
)
func TestQualityStoreImmutableHistoryReplayConcurrencyAndStaleness(t *testing.T) {
dsn := os.Getenv("KG_QAOPS_QUALITY_TEST_DSN")
if dsn == "" {
t.Skip("explicit disposable quality DB required")
}
u, e := url.Parse(dsn)
if e != nil || u.Hostname() != "127.0.0.1" || !strings.HasPrefix(u.Path, "/kg_qaops_quality_test_") || os.Getenv("KG_QAOPS_QUALITY_TEST_ISOLATED") != "1" {
t.Fatal("refusing shared quality database")
}
ctx := context.Background()
pool, e := pgxpool.New(ctx, dsn)
if e != nil {
t.Fatal("fixture connection failed")
}
defer pool.Close()
if e = pg.ApplyMigrations(ctx, pool); e != nil {
t.Fatal(e)
}
store := qaopsquality.NewStore(pool, "fixture-tenant")
record := dobotaiops.Record{ID: "fixture-turn", Status: "succeeded", Question: "示例", Answer: "暂无已发布", AskedAt: time.Now()}
views, e := store.Observe(ctx, []dobotaiops.Record{record})
if e != nil {
t.Fatal("source observation not persisted", e)
}
first := views[record.ID]
again, e := store.Observe(ctx, []dobotaiops.Record{record})
if e != nil || again[record.ID].Automatic.ID != first.Automatic.ID {
t.Fatal("repeated GET duplicated immutable checks")
}
metaKey := dobotaiops.QualityKey{ID: "metadata-only-turn", InputHash: strings.Repeat("f", 64), Marker: true}
meta, me := store.ObserveKeys(ctx, []dobotaiops.QualityKey{metaKey})
if me != nil || meta[metaKey.ID].Automatic.InputAvailable {
t.Fatal("compact scope observation not stored honestly", me)
}
if _, me = store.Snapshot(ctx, metaKey.ID, 1); !errors.Is(me, qaopsquality.ErrSnapshotMissing) {
t.Fatal("metadata-only input fabricated an empty original")
}
full, me := store.Observe(ctx, []dobotaiops.Record{{ID: metaKey.ID, QualityInputHash: metaKey.InputHash, Question: "示例", Answer: "暂无已发布"}})
if me != nil || !full[metaKey.ID].Automatic.InputAvailable || full[metaKey.ID].Automatic.ID != meta[metaKey.ID].Automatic.ID {
t.Fatal("reading full content duplicated/replaced the same check")
}
req := qaopsquality.SaveRequest{InputHash: first.InputHash, InputEpoch: first.InputEpoch, BaseRevision: first.Revision, Nonce: strings.Repeat("n", 32), Fields: qaopsquality.Fields{Coverage: "covered", Correctness: "correct", ProductCategory: "MG400", ProblemType: "咨询"}, Reason: "人工核对有效引用"}
saved, e := store.Save(ctx, record, req, "fixture-admin")
if e != nil || saved.View.State != "reviewed" || saved.View.Effective.Coverage != "covered" || saved.View.Automatic.Result.Verdict != "uncovered" || saved.View.LatestReview.Reviewer != "fixture-admin" {
t.Fatal("manual override lost audit/rule separation", e)
}
cols, ce := store.Columns(ctx, []dobotaiops.QualityKey{{ID: record.ID, InputHash: first.InputHash}})
if ce != nil || len(cols) != 4 {
t.Fatal("review fields absent from whole-scope projection", ce)
}
replay, e := store.Save(ctx, record, req, "fixture-admin")
if e != nil || !replay.Replayed || replay.SavedRevision != saved.SavedRevision {
t.Fatal("retry duplicated review")
}
bad := req
bad.Reason = "changed body"
if _, e = store.Save(ctx, record, bad, "fixture-admin"); !errors.Is(e, qaopsquality.ErrConflict) {
t.Fatal("nonce reused with different request")
}
if _, e = store.Save(ctx, record, req, "other-admin"); !errors.Is(e, qaopsquality.ErrConflict) {
t.Fatal("nonce replay changed operator")
}
record.Answer = "新答案"
changed, e := store.Observe(ctx, []dobotaiops.Record{record})
if e != nil || changed[record.ID].State != "stale" || changed[record.ID].Effective.Correctness != "" {
t.Fatal("old manual result silently survived change")
}
if _, e = store.Save(ctx, record, req, "fixture-admin"); e != nil {
t.Fatal("old completed request should replay without a new review")
}
record.Answer = "暂无已发布"
reverted, e := store.Observe(ctx, []dobotaiops.Record{record})
v := reverted[record.ID]
if e != nil || v.InputHash != first.InputHash || v.InputEpoch <= first.InputEpoch || v.State != "stale" {
t.Fatal("answer revert reactivated old judgment")
}
req.InputHash = v.InputHash
req.InputEpoch = v.InputEpoch
req.BaseRevision = v.Revision
start := make(chan struct{})
results := make(chan error, 2)
for _, nonce := range []string{strings.Repeat("a", 32), strings.Repeat("b", 32)} {
go func(nonce string) {
q := req
q.Nonce = nonce
<-start
_, err := store.Save(ctx, record, q, "fixture-admin")
results <- err
}(nonce)
}
close(start)
success, conflict := 0, 0
for range 2 {
e = <-results
if e == nil {
success++
} else if errors.Is(e, qaopsquality.ErrConflict) {
conflict++
} else {
t.Fatal(e)
}
}
if success != 1 || conflict != 1 {
t.Fatal("concurrent reviewers overwrote each other")
}
h, e := store.History(ctx, record.ID, 0, 0)
if e != nil || len(h.Reviews) != 2 || len(h.Checks) != 3 || h.Checks[0].InputEpoch != 3 {
t.Fatal("history missing/replaced", e)
}
oldInput, oe := store.Snapshot(ctx, record.ID, 1)
if oe != nil || oldInput.InputHash != first.InputHash || !strings.Contains(string(oldInput.Payload), "暂无已发布") {
t.Fatal("old assessment evidence not readable")
}
// A slow older source scan must not roll back a newer observed input.
ordered := dobotaiops.Record{ID: "ordered-source-turn", Answer: "旧输入", QualityObservedAt: time.Now().Add(-time.Minute)}
oldEvidence, _ := qaopsquality.EvidenceFor(ordered)
if _, e = store.Observe(ctx, []dobotaiops.Record{ordered}); e != nil {
t.Fatal(e)
}
ordered.Answer = "新输入"
ordered.QualityObservedAt = ordered.QualityObservedAt.Add(time.Second)
newViews, ne := store.Observe(ctx, []dobotaiops.Record{ordered})
if ne != nil {
t.Fatal(ne)
}
newView := newViews[ordered.ID]
if _, e = store.ObserveKeys(ctx, []dobotaiops.QualityKey{{ID: ordered.ID, InputHash: oldEvidence.Hash, ObservedAt: ordered.QualityObservedAt.Add(-time.Second)}}); !errors.Is(e, qaopsquality.ErrConflict) {
t.Fatal("late old source scan rolled back the current input")
}
current, ce := store.Observe(ctx, []dobotaiops.Record{ordered})
if ce != nil || current[ordered.ID].InputEpoch != newView.InputEpoch {
t.Fatal("stale scan created extra input epochs")
}
// Independent cursors must enumerate more than one page without loss.
paging := dobotaiops.Record{ID: "history-paging-turn", Answer: "示例"}
pageSeen := map[int64]bool{}
checkSeen := map[int64]bool{}
for i := 0; i < 23; i++ {
paging.Answer = fmt.Sprintf("示例输入%d", i)
vv, ee := store.Observe(ctx, []dobotaiops.Record{paging})
if ee != nil {
t.Fatal(ee)
}
value := vv[paging.ID]
_, ee = store.Save(ctx, paging, qaopsquality.SaveRequest{InputHash: value.InputHash, InputEpoch: value.InputEpoch, BaseRevision: value.Revision, Nonce: fmt.Sprintf("history_%020d", i), Fields: qaopsquality.Fields{Coverage: "pending", Correctness: "pending"}, Reason: "隔离分页验证"}, "fixture-admin")
if ee != nil {
t.Fatal(ee)
}
}
rc, cc := int64(0), int64(0)
for {
page, ee := store.History(ctx, paging.ID, rc, cc)
if ee != nil {
t.Fatal(ee)
}
for _, r := range page.Reviews {
if pageSeen[r.Revision] {
t.Fatal("duplicate history review")
}
pageSeen[r.Revision] = true
}
for _, c := range page.Checks {
if checkSeen[c.ID] {
t.Fatal("duplicate history check")
}
checkSeen[c.ID] = true
}
rc, cc = page.NextReview, page.NextCheck
if rc == 0 && cc == 0 {
break
}
if rc == 0 || cc == 0 {
t.Fatal("unexpected fixture cursor shape")
}
}
if len(pageSeen) != 23 || len(checkSeen) != 23 {
t.Fatal("history cursor omitted immutable rows")
}
freshPool, fe := pgxpool.New(ctx, dsn)
if fe != nil {
t.Fatal(fe)
}
persisted, fe := qaopsquality.NewStore(freshPool, "fixture-tenant").History(ctx, record.ID, 0, 0)
freshPool.Close()
if fe != nil || len(persisted.Reviews) != 2 || len(persisted.Checks) != 3 {
t.Fatal("history did not survive a new connection pool")
}
// History survives a fresh store/connection, not merely an in-memory cache.
if h, e = qaopsquality.NewStore(pool, "other-tenant").History(ctx, record.ID, 0, 0); e != nil || len(h.Reviews) != 0 || len(h.Checks) != 0 {
t.Fatal("quality history crossed tenants")
}
if e = pg.RollbackLatestMigration(ctx, pool); e != nil {
t.Fatal(e)
}
var gone bool
if pool.QueryRow(ctx, `SELECT to_regclass('qa_ops_quality_records') IS NULL AND to_regclass('qa_ops_quality_inputs') IS NULL AND to_regclass('qa_ops_quality_checks') IS NULL AND to_regclass('qa_ops_quality_reviews') IS NULL`).Scan(&gone) != nil || !gone {
t.Fatal("quality down migration left data tables")
}
if e = pg.ApplyMigrations(ctx, pool); e != nil {
t.Fatal(e)
}
}