feat(qa-ops): 完成复检留档与人工复核闭环
治理侧保存输入观测版本、自动复检及人工复核历史,输入变化失效、版本冲突和幂等重放不覆盖人工记录。批量质量数量使用完整筛选元数据,未采集原文不伪造快照,延迟旧扫描不回退新输入。 验证:全仓 make verify 退出码0,Go656及前端253通过;五包竞态、源/组织/质量隔离PG、真实只读源和隔离网页读回复核通过。默认91个可选集成跳过不计通过。未接AI模型,不写DobotAI源库,未推送、未合并、未部署。
This commit is contained in:
@@ -44,12 +44,16 @@ type UsageGroups struct {
|
||||
func decodeRecord(raw string) (Record, error) {
|
||||
var wire struct {
|
||||
Record
|
||||
Identity ActorIdentity `json:"_identity"`
|
||||
Identity ActorIdentity `json:"_identity"`
|
||||
QualityHash string `json:"_quality_hash"`
|
||||
QualityObservedAt time.Time `json:"_quality_observed_at"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &wire); err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
wire.Record.Identity = wire.Identity
|
||||
wire.Record.QualityInputHash = wire.QualityHash
|
||||
wire.Record.QualityObservedAt = wire.QualityObservedAt
|
||||
wire.Record.Coverage = CheckAnswerCoverage(wire.Record.Answer)
|
||||
return wire.Record, nil
|
||||
}
|
||||
|
||||
@@ -27,6 +27,9 @@ func TestQARecordInternalIdentityAndWholeFilterKeys(t *testing.T) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if len(page.ScopeQuality) != 4 || len(page.Items[0].QualityInputHash) != 64 {
|
||||
t.Fatal("whole-scope quality versions missing")
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("whole-filter keys missing; later-page department would be hidden")
|
||||
}
|
||||
@@ -34,6 +37,15 @@ func TestQARecordInternalIdentityAndWholeFilterKeys(t *testing.T) {
|
||||
if err != nil || item.Identity.StaffID != "ext-actor-1" || item.Identity.UnionID != "fixture-union" {
|
||||
t.Fatalf("stable identity not read from inbound actor/message: %v", err)
|
||||
}
|
||||
scope, se := client.ReadQualityScope(context.Background(), query)
|
||||
if se != nil || len(scope.Keys) != 4 || scope.AsOf.IsZero() {
|
||||
t.Fatal("quality metadata scope incomplete", se)
|
||||
}
|
||||
for _, key := range scope.Keys {
|
||||
if len(key.InputHash) != 64 || key.ObservedAt.IsZero() {
|
||||
t.Fatal("scope omitted input version")
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(page)
|
||||
detail, _ := json.Marshal(item)
|
||||
for _, s := range []string{string(raw), string(detail)} {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type QualityScope struct {
|
||||
Keys []QualityKey
|
||||
AsOf time.Time
|
||||
}
|
||||
|
||||
func (c *Client) ReadQualityScope(ctx context.Context, query RecordQuery) (QualityScope, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return QualityScope{}, err
|
||||
}
|
||||
if query.Cursor != "" {
|
||||
return QualityScope{}, ErrInvalidQuery
|
||||
}
|
||||
pattern, err := recordKeywordPattern(query.Keyword)
|
||||
if err != nil {
|
||||
return QualityScope{}, err
|
||||
}
|
||||
result := QualityScope{Keys: []QualityKey{}}
|
||||
err = c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&result.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, err := q.Query(ctx, recordsBaseSQL+` SELECT id,quality_hash,strpos(payload->>'answer',$5)>0,(payload->'source_coverage')::text FROM records WHERE `+recordFilterSQL+` ORDER BY id LIMIT 5001`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern, noPublishedMarker)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var key QualityKey
|
||||
var raw string
|
||||
if rows.Scan(&key.ID, &key.InputHash, &key.Marker, &raw) != nil || json.Unmarshal([]byte(raw), &key.Source) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if len(result.Keys) >= 5000 {
|
||||
return ErrInvalidQuery
|
||||
}
|
||||
key.ObservedAt = result.AsOf
|
||||
result.Keys = append(result.Keys, key)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
@@ -29,8 +29,11 @@ type CoverageCheck struct {
|
||||
|
||||
// Absence of this exact substring is not evidence that knowledge covers a question.
|
||||
func CheckAnswerCoverage(answer string) CoverageCheck {
|
||||
return CheckMarkerCoverage(strings.Contains(answer, noPublishedMarker))
|
||||
}
|
||||
func CheckMarkerCoverage(matched bool) CoverageCheck {
|
||||
result := CoverageCheck{State: "pending", RuleVersion: CoverageRuleVersion}
|
||||
if strings.Contains(answer, noPublishedMarker) {
|
||||
if matched {
|
||||
result.State = "checked"
|
||||
result.Verdict = "uncovered"
|
||||
result.MatchedText = noPublishedMarker
|
||||
@@ -51,23 +54,26 @@ type RecordFeedback struct {
|
||||
}
|
||||
|
||||
type Record struct {
|
||||
Identity ActorIdentity `json:"-"`
|
||||
Organization *RecordOrganization `json:"organization,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
AskedAt time.Time `json:"asked_at"`
|
||||
TimeSource string `json:"time_source"`
|
||||
Asker string `json:"asker"`
|
||||
TriggerPerson string `json:"trigger_person"`
|
||||
Department string `json:"department"`
|
||||
Region string `json:"region"`
|
||||
References json.RawMessage `json:"references"`
|
||||
Media json.RawMessage `json:"media"`
|
||||
SourceCoverage SourceCoverage `json:"source_coverage"`
|
||||
Feedback RecordFeedback `json:"feedback"`
|
||||
Coverage CoverageCheck `json:"coverage"`
|
||||
QualityObservedAt time.Time `json:"-"`
|
||||
QualityInputHash string `json:"-"`
|
||||
Quality json.RawMessage `json:"quality,omitempty"`
|
||||
Identity ActorIdentity `json:"-"`
|
||||
Organization *RecordOrganization `json:"organization,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
AskedAt time.Time `json:"asked_at"`
|
||||
TimeSource string `json:"time_source"`
|
||||
Asker string `json:"asker"`
|
||||
TriggerPerson string `json:"trigger_person"`
|
||||
Department string `json:"department"`
|
||||
Region string `json:"region"`
|
||||
References json.RawMessage `json:"references"`
|
||||
Media json.RawMessage `json:"media"`
|
||||
SourceCoverage SourceCoverage `json:"source_coverage"`
|
||||
Feedback RecordFeedback `json:"feedback"`
|
||||
Coverage CoverageCheck `json:"coverage"`
|
||||
}
|
||||
|
||||
type RecordQuery struct {
|
||||
@@ -77,7 +83,15 @@ type RecordQuery struct {
|
||||
Limit int
|
||||
}
|
||||
|
||||
type QualityKey struct {
|
||||
ObservedAt time.Time `json:"-"`
|
||||
Marker bool `json:"marker"`
|
||||
Source SourceCoverage `json:"source"`
|
||||
ID string `json:"id"`
|
||||
InputHash string `json:"input_hash"`
|
||||
}
|
||||
type RecordPage struct {
|
||||
ScopeQuality []QualityKey `json:"-"`
|
||||
ScopeActors []ActorIdentity `json:"-"`
|
||||
Organization *OrganizationVersion `json:"organization,omitempty"`
|
||||
Items []Record `json:"items"`
|
||||
@@ -97,11 +111,12 @@ type recordCursor struct {
|
||||
// A single inbound-message join controls names/time. Feedback is preaggregated;
|
||||
// joining each feedback row directly would multiply the business event count.
|
||||
const actorIdentitySQL = `jsonb_build_object('actor_id',COALESCE(a.id,''),'staff_id',COALESCE(a.external_actor_id,''),'union_id',COALESCE(m.actor_union_id_snapshot,''))`
|
||||
const qualityHashSQL = `encode(sha256(convert_to(jsonb_build_array('quality-input-v1',t.id,t.status,t.question,t.answer,t.references_json,COALESCE(m.media_json,'[]'::jsonb))::text,'UTF8')),'hex')`
|
||||
const recordsBaseSQL = `
|
||||
WITH records AS (
|
||||
SELECT t.id,COALESCE(m.created_at,t.created_at) AS asked_at,t.question,t.status,` + actorIdentitySQL + ` AS identity,
|
||||
SELECT t.id,COALESCE(m.created_at,t.created_at) AS asked_at,t.question,t.status,` + actorIdentitySQL + ` AS identity,` + qualityHashSQL + ` AS quality_hash,
|
||||
jsonb_build_object(
|
||||
'_identity',` + actorIdentitySQL + `,
|
||||
'_identity',` + actorIdentitySQL + `, '_quality_hash',` + qualityHashSQL + `,'_quality_observed_at',transaction_timestamp(),
|
||||
'id',t.id,'status',t.status,'question',t.question,'answer',t.answer,
|
||||
'asked_at',COALESCE(m.created_at,t.created_at),
|
||||
'time_source',CASE WHEN m.id IS NULL THEN 'turn.created_at' ELSE 'request_message.created_at' END,
|
||||
@@ -143,7 +158,7 @@ const recordColumnsSQL = `SELECT count(*),jsonb_build_object(
|
||||
'region',COALESCE(bool_or(payload->>'region'<>''),false),
|
||||
'feedback',COALESCE(bool_or(payload->'feedback'->>'asker_value'<>'' OR
|
||||
(payload->'feedback'->>'up')::bigint>0 OR (payload->'feedback'->>'down')::bigint>0),false)
|
||||
)::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text FROM records WHERE `
|
||||
)::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text,COALESCE(jsonb_agg(jsonb_build_object('id',id,'input_hash',quality_hash,'marker',strpos(payload->>'answer',$5)>0,'source',payload->'source_coverage')),'[]'::jsonb)::text FROM records WHERE `
|
||||
|
||||
var recordColumnOrder = []string{"question_chinese", "answer", "coverage", "is_correct", "product_category", "problem_type", "root_cause", "asked_at", "asker", "question", "language", "trigger_person", "department", "region", "feedback"}
|
||||
|
||||
@@ -186,10 +201,16 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
if err := q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&page.AsOf); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
var rawColumns, rawActors string
|
||||
if err := q.QueryRow(ctx, recordsBaseSQL+recordColumnsSQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns, &rawActors); err != nil {
|
||||
var rawColumns, rawActors, rawQuality string
|
||||
if err := q.QueryRow(ctx, recordsBaseSQL+recordColumnsSQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns, &rawActors, &rawQuality); err != nil {
|
||||
return fmt.Errorf("%w: record count failed", ErrUnavailable)
|
||||
}
|
||||
if json.Unmarshal([]byte(rawQuality), &page.ScopeQuality) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
for i := range page.ScopeQuality {
|
||||
page.ScopeQuality[i].ObservedAt = page.AsOf
|
||||
}
|
||||
var available map[string]bool
|
||||
if json.Unmarshal([]byte(rawActors), &page.ScopeActors) != nil {
|
||||
return ErrUnavailable
|
||||
|
||||
@@ -104,6 +104,10 @@ func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
enrichQAPage(&page, projection)
|
||||
if err := enrichQAQualityPage(r.Context(), config, &page); err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": page})
|
||||
}
|
||||
|
||||
@@ -130,6 +134,10 @@ func getQAOpsRecord(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
enrichQARecord(&item, projection)
|
||||
if err := enrichQAQualityRecord(r.Context(), config, &item); err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": item})
|
||||
}
|
||||
|
||||
|
||||
@@ -17,8 +17,11 @@ type QAOrgSyncStore interface {
|
||||
}
|
||||
|
||||
func authorizeQAOrganizationWrite(w http.ResponseWriter, r *http.Request) bool {
|
||||
if r.Header.Get("X-Governance-Action") != "qa-organization" || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
writeJSON(w, 403, map[string]string{"error": "区域配置需要同源操作意图"})
|
||||
return authorizeQAIntent(w, r, "qa-organization")
|
||||
}
|
||||
func authorizeQAIntent(w http.ResponseWriter, r *http.Request, intent string) bool {
|
||||
if r.Header.Get("X-Governance-Action") != intent || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
writeJSON(w, 403, map[string]string{"error": "此操作需要同源操作意图"})
|
||||
return false
|
||||
}
|
||||
// Fetch Metadata survives same-origin proxies that rewrite Host; untrusted
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type QAQualityStore interface {
|
||||
ObserveKeys(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error)
|
||||
Observe(context.Context, []dobotaiops.Record) (map[string]qaopsquality.View, error)
|
||||
Save(context.Context, dobotaiops.Record, qaopsquality.SaveRequest, string) (qaopsquality.Receipt, error)
|
||||
Columns(context.Context, []dobotaiops.QualityKey) ([]string, error)
|
||||
History(context.Context, string, int64, int64) (qaopsquality.History, error)
|
||||
Snapshot(context.Context, string, int64) (qaopsquality.Snapshot, error)
|
||||
}
|
||||
|
||||
type qaQualityReader interface {
|
||||
ReadQualityScope(context.Context, dobotaiops.RecordQuery) (dobotaiops.QualityScope, error)
|
||||
}
|
||||
|
||||
func writeQualityError(w http.ResponseWriter, err error) {
|
||||
status, code, message := 503, "quality_unavailable", "质量留档/复核存储不可用,未将失败伪装为空值或零统计"
|
||||
switch {
|
||||
case errors.Is(err, qaopsquality.ErrInvalid) || errors.Is(err, dobotaiops.ErrInvalidQuery):
|
||||
status, code, message = 400, "invalid_quality_request", "质量操作参数无效:请核对结论、理由、版本和筛选范围(最多5000条/32MiB)"
|
||||
case errors.Is(err, qaopsquality.ErrConflict):
|
||||
status, code, message = 409, "quality_conflict", "原始问答或人工复核版本已变化,请重新读取问答后核对;未覆盖现有结论"
|
||||
case errors.Is(err, qaopsquality.ErrSnapshotMissing):
|
||||
status, code, message = 409, "quality_input_metadata_only", "此版本仅留存指纹与复检元数据,未采集原文;未编造空问题或空答案"
|
||||
case errors.Is(err, qaopsquality.ErrNotFound):
|
||||
status, code, message = 404, "quality_input_not_found", "未找到当前授权范围的输入版本"
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": message, "code": code})
|
||||
}
|
||||
func enrichQAQualityRecord(ctx context.Context, c Config, item *dobotaiops.Record) error {
|
||||
if c.QAQuality == nil {
|
||||
return nil
|
||||
}
|
||||
views, err := c.QAQuality.Observe(ctx, []dobotaiops.Record{*item})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v, ok := views[item.ID]
|
||||
if !ok {
|
||||
return qaopsquality.ErrUnavailable
|
||||
}
|
||||
item.Quality, err = json.Marshal(v)
|
||||
return err
|
||||
}
|
||||
func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordPage) error {
|
||||
if c.QAQuality == nil {
|
||||
return nil
|
||||
}
|
||||
views, err := c.QAQuality.Observe(ctx, page.Items)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range page.Items {
|
||||
v, ok := views[page.Items[i].ID]
|
||||
if !ok {
|
||||
return qaopsquality.ErrUnavailable
|
||||
}
|
||||
page.Items[i].Quality, err = json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
columns, err := c.QAQuality.Columns(ctx, page.ScopeQuality)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dobotaiops.AddRecordColumns(page, columns...)
|
||||
return nil
|
||||
}
|
||||
func walkQualityJSON(d *json.Decoder) error {
|
||||
token, err := d.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if token == nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
if delimiter, ok := token.(json.Delim); ok {
|
||||
if delimiter != '{' && delimiter != '[' {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
keys := map[string]bool{}
|
||||
for d.More() {
|
||||
if delimiter == '{' {
|
||||
key, e := d.Token()
|
||||
name, ok := key.(string)
|
||||
if e != nil || !ok || keys[name] {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
keys[name] = true
|
||||
}
|
||||
if walkQualityJSON(d) != nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
}
|
||||
_, err = d.Token()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func decodeQualityJSON(w http.ResponseWriter, r *http.Request, target any, required ...string) error {
|
||||
if r.URL.RawQuery != "" {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64<<10))
|
||||
if err != nil || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
var top map[string]json.RawMessage
|
||||
if json.Unmarshal(raw, &top) != nil || top == nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
for _, key := range required {
|
||||
if _, ok := top[key]; !ok {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
}
|
||||
check := json.NewDecoder(bytes.NewReader(raw))
|
||||
if walkQualityJSON(check) != nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
var extra any
|
||||
if check.Decode(&extra) != io.EOF {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(raw))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(target) != nil || d.Decode(&extra) != io.EOF {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func qaQualityReview(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-quality") {
|
||||
return
|
||||
}
|
||||
var request qaopsquality.SaveRequest
|
||||
if decodeQualityJSON(w, r, &request, "input_hash", "input_epoch", "base_revision", "nonce", "fields", "reason") != nil || qaopsquality.Validate(request) != nil {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if c.QAQuality == nil || c.QAOps == nil || c.QAOpsTenantKey == "" {
|
||||
writeQualityError(w, qaopsquality.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
record, err := c.QAOps.GetRecord(r.Context(), c.QAOpsTenantKey, r.PathValue("id"))
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
receipt, err := c.QAQuality.Save(r.Context(), record, request, identity.Username)
|
||||
if err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": receipt})
|
||||
}
|
||||
func qaQualityQuery(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-quality") {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &request) != nil {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
window, err := dobotaiops.NewWindow(c.QAOpsTenantKey, request.Start, request.End, 90*24*time.Hour, c.Now())
|
||||
if err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
reader, ok := c.QAOps.(qaQualityReader)
|
||||
if !ok || c.QAQuality == nil {
|
||||
writeQualityError(w, qaopsquality.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
scope, err := reader.ReadQualityScope(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword})
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
views, err := c.QAQuality.ObserveKeys(r.Context(), scope.Keys)
|
||||
if err != nil || len(views) != len(scope.Keys) {
|
||||
if err == nil {
|
||||
err = qaopsquality.ErrUnavailable
|
||||
}
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": map[string]any{"summary": qaopsquality.Summarize(views), "start": window.Start, "end": window.End, "keyword": request.Keyword, "as_of": scope.AsOf, "ai_state": "not_configured", "scope": "whole_filter"}})
|
||||
}
|
||||
func qaQualityHistory(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if c.QAQuality == nil {
|
||||
writeQualityError(w, qaopsquality.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
values := r.URL.Query()
|
||||
for key, v := range values {
|
||||
if (key != "review_before" && key != "check_before") || len(v) != 1 {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
}
|
||||
cursors := map[string]int64{}
|
||||
for _, key := range []string{"review_before", "check_before"} {
|
||||
raw := values.Get(key)
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
n, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || n < 1 {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
cursors[key] = n
|
||||
}
|
||||
value, err := c.QAQuality.History(r.Context(), r.PathValue("id"), cursors["review_before"], cursors["check_before"])
|
||||
if err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": value})
|
||||
}
|
||||
func qaQualitySnapshot(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
epoch, err := strconv.ParseInt(r.PathValue("epoch"), 10, 64)
|
||||
if err != nil || epoch < 1 || r.URL.RawQuery != "" {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if c.QAQuality == nil {
|
||||
writeQualityError(w, qaopsquality.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
value, err := c.QAQuality.Snapshot(r.Context(), r.PathValue("id"), epoch)
|
||||
if err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": value})
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type qualityFake struct {
|
||||
actor string
|
||||
calls int
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (s *qualityFake) Observe(_ context.Context, records []dobotaiops.Record) (map[string]qaopsquality.View, error) {
|
||||
s.calls++
|
||||
if s.fail {
|
||||
return nil, qaopsquality.ErrUnavailable
|
||||
}
|
||||
out := map[string]qaopsquality.View{}
|
||||
for _, r := range records {
|
||||
e, _ := qaopsquality.EvidenceFor(r)
|
||||
out[r.ID] = qaopsquality.Project(e.Hash, 1, 0, qaopsquality.Check{InputEpoch: 1, InputHash: e.Hash, Result: dobotaiops.CheckAnswerCoverage(r.Answer)}, nil)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (s *qualityFake) ObserveKeys(_ context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
s.calls++
|
||||
out := map[string]qaopsquality.View{}
|
||||
for _, key := range keys {
|
||||
out[key.ID] = qaopsquality.Project(key.InputHash, 1, 0, qaopsquality.Check{Result: dobotaiops.CheckMarkerCoverage(key.Marker)}, nil)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (s *qualityFake) Save(_ context.Context, r dobotaiops.Record, q qaopsquality.SaveRequest, actor string) (qaopsquality.Receipt, error) {
|
||||
s.actor = actor
|
||||
v := qaopsquality.Project(q.InputHash, 1, 1, qaopsquality.Check{Result: dobotaiops.CheckAnswerCoverage(r.Answer)}, &qaopsquality.Review{InputEpoch: 1, InputHash: q.InputHash, Fields: q.Fields, Reason: q.Reason, Reviewer: actor})
|
||||
return qaopsquality.Receipt{View: v, SavedRevision: 1}, nil
|
||||
}
|
||||
func (s *qualityFake) Columns(_ context.Context, keys []dobotaiops.QualityKey) ([]string, error) {
|
||||
return []string{"is_correct", "product_category"}, nil
|
||||
}
|
||||
func (s *qualityFake) History(context.Context, string, int64, int64) (qaopsquality.History, error) {
|
||||
return qaopsquality.History{Reviews: []qaopsquality.Review{}, Checks: []qaopsquality.Check{}}, nil
|
||||
}
|
||||
func (s *qualityFake) Snapshot(context.Context, string, int64) (qaopsquality.Snapshot, error) {
|
||||
return qaopsquality.Snapshot{}, qaopsquality.ErrNotFound
|
||||
}
|
||||
|
||||
type qualitySource struct {
|
||||
attributedReader
|
||||
record dobotaiops.Record
|
||||
tenant string
|
||||
scopeCalls int
|
||||
}
|
||||
|
||||
func (s *qualitySource) GetRecord(_ context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
s.tenant = tenant
|
||||
return s.record, nil
|
||||
}
|
||||
func (s *qualitySource) ListRecords(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
return dobotaiops.RecordPage{Items: []dobotaiops.Record{s.record}, Columns: []string{"question"}, Total: 2, AsOf: time.Now()}, nil
|
||||
}
|
||||
func (s *qualitySource) ReadQualityScope(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
s.scopeCalls++
|
||||
s.tenant = q.Window.TenantKey
|
||||
second := s.record
|
||||
second.ID = "second-turn"
|
||||
keys := []dobotaiops.QualityKey{}
|
||||
for _, r := range []dobotaiops.Record{s.record, second} {
|
||||
e, _ := qaopsquality.EvidenceFor(r)
|
||||
keys = append(keys, dobotaiops.QualityKey{ID: r.ID, InputHash: e.Hash, Marker: e.Result.Verdict == "uncovered", Source: r.SourceCoverage})
|
||||
}
|
||||
return dobotaiops.QualityScope{Keys: keys, AsOf: time.Now()}, nil
|
||||
}
|
||||
func qualityTestHandler(t *testing.T) (http.Handler, *qualityFake, *qualitySource) {
|
||||
t.Helper()
|
||||
store := &qualityFake{}
|
||||
source := &qualitySource{record: dobotaiops.Record{ID: "fixture-turn", Status: "succeeded", Question: "示例", Answer: "暂无已发布"}}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["quality-admin"] = "usr-boss"
|
||||
auth.sessions["quality-viewer"] = "usr-eye"
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: source, QAOpsTenantKey: "fixed", QAQuality: store, Now: func() time.Time { return time.Date(2026, 10, 17, 0, 0, 0, 0, time.UTC) }})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return h, store, source
|
||||
}
|
||||
func qualityRequest(h http.Handler, method, path, token, body string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
r.Header.Set("X-Governance-Action", "qa-quality")
|
||||
if token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
func TestQAQualityDetailListAndWholeScopeCounts(t *testing.T) {
|
||||
h, store, source := qualityTestHandler(t)
|
||||
w := qualityRequest(h, "GET", "/api/v1/qa-ops/records/fixture-turn", "quality-admin", "")
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"quality"`) {
|
||||
t.Fatal("persisted quality absent in detail", w.Code)
|
||||
}
|
||||
w = qualityRequest(h, "GET", "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z", "quality-admin", "")
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"is_correct"`) {
|
||||
t.Fatal("whole-filter quality columns absent")
|
||||
}
|
||||
w = qualityRequest(h, "POST", "/api/v1/qa-ops/quality/query", "quality-admin", `{"start":"2026-10-14T00:00:00Z","end":"2026-10-15T00:00:00Z","keyword":""}`)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"unreviewed":2`) || source.scopeCalls != 1 || source.tenant != "fixed" || store.calls < 2 {
|
||||
t.Fatal("quality summary estimated from page instead of scope", w.Code, w.Body.String())
|
||||
}
|
||||
store.fail = true
|
||||
w = qualityRequest(h, "GET", "/api/v1/qa-ops/records/fixture-turn", "quality-admin", "")
|
||||
if w.Code != 503 || !strings.Contains(w.Body.String(), "quality_unavailable") {
|
||||
t.Fatal("quality storage failure presented as empty success")
|
||||
}
|
||||
}
|
||||
func TestQAQualityReviewUsesSessionActorAndStrictReadOnlySourceBoundary(t *testing.T) {
|
||||
h, store, source := qualityTestHandler(t)
|
||||
e, _ := qaopsquality.EvidenceFor(source.record)
|
||||
q := qaopsquality.SaveRequest{InputHash: e.Hash, InputEpoch: 1, Nonce: strings.Repeat("n", 32), Fields: qaopsquality.Fields{Coverage: "uncovered", Correctness: "pending"}, Reason: "人工核对"}
|
||||
raw, _ := json.Marshal(q)
|
||||
path := "/api/v1/qa-ops/records/fixture-turn/reviews"
|
||||
w := qualityRequest(h, "POST", path, "quality-admin", string(raw))
|
||||
if w.Code != 200 || store.actor != "boss" || source.tenant != "fixed" {
|
||||
t.Fatal("manual review failed or actor came from request", w.Code, store.actor)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
token, body string
|
||||
status int
|
||||
}{{"", string(raw), 401}, {"quality-viewer", string(raw), 403}, {"quality-admin", strings.TrimSuffix(string(raw), "}") + `,"reviewer":"forged"}`, 400}, {"quality-admin", `null`, 400}, {"quality-admin", string(raw) + `{}`, 400}, {"quality-admin", `{"nonce":"a","nonce":"b"}`, 400}} {
|
||||
w = qualityRequest(h, "POST", path, tc.token, tc.body)
|
||||
if w.Code != tc.status {
|
||||
t.Fatal("review boundary failed", w.Code, tc.status)
|
||||
}
|
||||
}
|
||||
r := httptest.NewRequest("POST", path, strings.NewReader(string(raw)))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "quality-admin"})
|
||||
r.Header.Set("X-Governance-Action", "qa-quality")
|
||||
r.Header.Set("Sec-Fetch-Site", "cross-site")
|
||||
w = httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 403 {
|
||||
t.Fatal("cross-site review accepted")
|
||||
}
|
||||
w = qualityRequest(h, "GET", path+"/invalid", "quality-admin", "")
|
||||
if w.Code != 404 {
|
||||
t.Fatal("unknown endpoint silently accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQAQualityReviewRejectsMissingRevisionAndNestedNull(t *testing.T) {
|
||||
h, _, source := qualityTestHandler(t)
|
||||
e, _ := qaopsquality.EvidenceFor(source.record)
|
||||
q := qaopsquality.SaveRequest{InputHash: e.Hash, InputEpoch: 1, Nonce: strings.Repeat("n", 32), Fields: qaopsquality.Fields{Coverage: "pending", Correctness: "pending"}, Reason: "示例复核"}
|
||||
raw, _ := json.Marshal(q)
|
||||
for _, body := range []string{strings.Replace(string(raw), `"base_revision":0,`, "", 1), strings.Replace(string(raw), `"base_revision":0`, `"base_revision":null`, 1), strings.Replace(string(raw), `"product_category":""`, `"product_category":null`, 1)} {
|
||||
w := qualityRequest(h, "POST", "/api/v1/qa-ops/records/fixture-turn/reviews", "quality-admin", body)
|
||||
if w.Code != 400 {
|
||||
t.Fatal("missing/null version or field silently became a default", w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,7 @@ type Store interface {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
QAQuality QAQualityStore
|
||||
QAOrgSync QAOrgSyncStore
|
||||
QAOrgSyncEnabled bool
|
||||
QAOrg QAOrgStore
|
||||
@@ -175,6 +176,11 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
config.NewID = newID
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/quality/query", func(w http.ResponseWriter, r *http.Request) { qaQualityQuery(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/records/{id}/reviews", func(w http.ResponseWriter, r *http.Request) { qaQualityReview(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/records/{id}/quality/history", func(w http.ResponseWriter, r *http.Request) { qaQualityHistory(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/records/{id}/quality/inputs/{epoch}", func(w http.ResponseWriter, r *http.Request) { qaQualitySnapshot(w, r, config) })
|
||||
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/usage/people", func(w http.ResponseWriter, r *http.Request) { qaMonthlyPeople(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/usage", func(w http.ResponseWriter, r *http.Request) { qaOpsUsage(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/organization/sync", func(w http.ResponseWriter, r *http.Request) { qaOrganizationSync(w, r, config) })
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
DROP TABLE qa_ops_quality_reviews;
|
||||
DROP TABLE qa_ops_quality_checks;
|
||||
DROP TABLE qa_ops_quality_inputs;
|
||||
DROP TABLE qa_ops_quality_records;
|
||||
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE qa_ops_quality_records (
|
||||
tenant_key TEXT NOT NULL,record_id TEXT NOT NULL,observed_at TIMESTAMPTZ,input_hash TEXT NOT NULL DEFAULT '',input_epoch BIGINT NOT NULL DEFAULT 0 CHECK(input_epoch>=0),review_revision BIGINT NOT NULL DEFAULT 0 CHECK(review_revision>=0),PRIMARY KEY(tenant_key,record_id)
|
||||
);
|
||||
CREATE TABLE qa_ops_quality_inputs (
|
||||
tenant_key TEXT NOT NULL,record_id TEXT NOT NULL,input_epoch BIGINT NOT NULL CHECK(input_epoch>0),input_hash TEXT NOT NULL CHECK(input_hash ~ '^[a-f0-9]{64}$'),payload JSONB CHECK(payload IS NULL OR jsonb_typeof(payload)='object'),created_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY(tenant_key,record_id,input_epoch),FOREIGN KEY(tenant_key,record_id) REFERENCES qa_ops_quality_records(tenant_key,record_id)
|
||||
);
|
||||
CREATE TABLE qa_ops_quality_checks (
|
||||
id BIGSERIAL PRIMARY KEY,tenant_key TEXT NOT NULL,record_id TEXT NOT NULL,input_epoch BIGINT NOT NULL,rule_version TEXT NOT NULL,result JSONB NOT NULL CHECK(jsonb_typeof(result)='object'),source JSONB NOT NULL CHECK(jsonb_typeof(source)='object'),created_at TIMESTAMPTZ NOT NULL DEFAULT now(),UNIQUE(tenant_key,record_id,input_epoch,rule_version),FOREIGN KEY(tenant_key,record_id,input_epoch) REFERENCES qa_ops_quality_inputs(tenant_key,record_id,input_epoch)
|
||||
);
|
||||
CREATE TABLE qa_ops_quality_reviews (
|
||||
tenant_key TEXT NOT NULL,record_id TEXT NOT NULL,revision BIGINT NOT NULL CHECK(revision>0),input_epoch BIGINT NOT NULL,input_hash TEXT NOT NULL CHECK(input_hash ~ '^[a-f0-9]{64}$'),fields JSONB NOT NULL CHECK(jsonb_typeof(fields)='object'),reason TEXT NOT NULL CHECK(length(btrim(reason))>0),reviewer TEXT NOT NULL CHECK(length(btrim(reviewer))>0),nonce TEXT NOT NULL,request_hash TEXT NOT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY(tenant_key,record_id,revision),UNIQUE(tenant_key,record_id,nonce),FOREIGN KEY(tenant_key,record_id,input_epoch) REFERENCES qa_ops_quality_inputs(tenant_key,record_id,input_epoch)
|
||||
);
|
||||
CREATE INDEX idx_qa_quality_checks_history ON qa_ops_quality_checks(tenant_key,record_id,id DESC);
|
||||
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 48 {
|
||||
t.Fatalf("migration count = %d, want 48", len(migrations))
|
||||
if len(migrations) != 49 {
|
||||
t.Fatalf("migration count = %d, want 49", len(migrations))
|
||||
}
|
||||
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
|
||||
t.Fatalf("migration 1 = %#v", migrations[0])
|
||||
|
||||
@@ -134,6 +134,19 @@ func TestOrganizationStoreRoundTripAndOptimisticConflict(t *testing.T) {
|
||||
if err = pool.QueryRow(ctx, "SELECT count(*) FROM qa_ops_region_revisions WHERE tenant_key=$1", "fixture-tenant").Scan(&revisions); err != nil || revisions != 2 {
|
||||
t.Fatal("revision history changed unexpectedly")
|
||||
}
|
||||
// This test exercises migration 48, not whichever unrelated migration is latest.
|
||||
for {
|
||||
var latest int64
|
||||
if pool.QueryRow(ctx, "SELECT max(version) FROM schema_migrations").Scan(&latest) != nil {
|
||||
t.Fatal("migration version unavailable")
|
||||
}
|
||||
if latest <= 48 {
|
||||
break
|
||||
}
|
||||
if postgresstore.RollbackLatestMigration(ctx, pool) != nil {
|
||||
t.Fatal("could not reach organization migration")
|
||||
}
|
||||
}
|
||||
if err = postgresstore.RollbackLatestMigration(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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} }
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user