fix(qa): 首批即显并统一五字段后端筛选
build / build (push) Successful in 1m19s

列表正文改为按需读取;保留完整导出、版本隔离和有效标签筛选。
验证:前端全量、Go全量及隔离PG全mirror竞态通过;覆盖首批回调、续载失败与筛选分页。
This commit is contained in:
姚章浩
2026-10-25 12:45:31 +08:00
parent 65653e5c01
commit 00c4c13283
26 changed files with 836 additions and 39 deletions
+35
View File
@@ -0,0 +1,35 @@
package dobotaiops
import (
"strings"
"unicode/utf8"
)
var QualityFilterKeys = []string{"coverage", "is_correct", "product_category", "problem_type", "root_cause"}
func ValidQualityFilters(filters map[string]string) bool {
if len(filters) > 5 {
return false
}
for key, value := range filters {
found := false
for _, allowed := range QualityFilterKeys {
if key == allowed {
found = true
}
}
if !found || value == "" || !utf8.ValidString(value) || utf8.RuneCountInString(value) > 200 || strings.ContainsRune(value, 0) {
return false
}
if value == "__empty__" {
continue
}
if key == "coverage" && value != "是" && value != "否" && value != "否但不计入" && value != "部分覆盖" && value != "待确认" {
return false
}
if key == "is_correct" && value != "是" && value != "否" && value != "待确认" {
return false
}
}
return true
}
+5
View File
@@ -38,6 +38,11 @@ func NewRecordsRepository(o RecordsRepositoryOptions) *RecordsRepository {
}
return &RecordsRepository{summarySQL: o.SummarySQL, qualityScopeSQL: o.QualityScopeSQL, baseSQL: o.BaseSQL, transact: o.Transaction, validateQueryWindow: o.ValidateWindow, readAsOf: asOf, tenant: o.TenantKey}
}
func (c *RecordsRepository) WithSummarySQL(sql string) *RecordsRepository {
out := *c
out.summarySQL = sql
return &out
}
func (c *Client) recordRepository() *RecordsRepository {
return NewRecordsRepository(RecordsRepositoryOptions{BaseSQL: recordsBaseSQL, Transaction: c.withReadOnlyTx, ValidateWindow: c.validateQueryWindow})
}
+34 -7
View File
@@ -69,6 +69,7 @@ type RecordFeedback struct {
}
type Record struct {
ContentProjection string `json:"content_projection,omitempty"`
FieldEditRevision int64 `json:"field_edit_revision,omitempty"`
BackgroundTasks json.RawMessage `json:"background_tasks,omitempty"`
RecordOrigin string `json:"record_origin,omitempty"`
@@ -96,10 +97,14 @@ type Record struct {
}
type RecordQuery struct {
Window Window
Keyword string
Cursor string
Limit int
Summary bool
Filters map[string]string
MatchIDs []string
MatchVersion string
Window Window
Keyword string
Cursor string
Limit int
}
type QualityKey struct {
@@ -200,6 +205,16 @@ func (c *RecordsRepository) ListRecords(ctx context.Context, query RecordQuery)
return RecordPage{}, fmt.Errorf("%w: invalid record filters", ErrInvalidQuery)
}
scopeBytes, _ := json.Marshal([]string{query.Window.TenantKey, query.Window.Start.UTC().Format(time.RFC3339Nano), query.Window.End.UTC().Format(time.RFC3339Nano), query.Keyword})
if len(query.Filters) > 0 {
if query.MatchIDs == nil {
return RecordPage{}, ErrInvalidQuery
}
extra, _ := json.Marshal(struct {
Filters map[string]string
Version string
}{query.Filters, query.MatchVersion})
scopeBytes = append(scopeBytes, extra...)
}
scopeSum := sha256.Sum256(scopeBytes)
scope := hex.EncodeToString(scopeSum[:])
var cursor recordCursor
@@ -226,7 +241,13 @@ func (c *RecordsRepository) ListRecords(ctx context.Context, query RecordQuery)
if c.summarySQL != "" {
summarySQL = c.summarySQL
}
if err := q.QueryRow(ctx, summarySQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns, &rawActors, &rawQuality); err != nil {
summaryFilter := recordFilterSQL
summaryArgs := append(append([]any{}, args...), noPublishedMarker)
if query.MatchIDs != nil {
summaryFilter += " AND id=ANY($6::text[])"
summaryArgs = append(summaryArgs, query.MatchIDs)
}
if err := q.QueryRow(ctx, summarySQL+summaryFilter, summaryArgs...).Scan(&page.Total, &rawColumns, &rawActors, &rawQuality); err != nil {
return fmt.Errorf("%w: record count failed", ErrUnavailable)
}
if json.Unmarshal([]byte(rawQuality), &page.ScopeQuality) != nil {
@@ -247,8 +268,14 @@ func (c *RecordsRepository) ListRecords(ctx context.Context, query RecordQuery)
page.Columns = append(page.Columns, column)
}
}
rows, err := q.Query(ctx, c.baseSQL+` SELECT payload::text FROM records WHERE `+recordFilterSQL+`
AND ($5::timestamptz IS NULL OR (asked_at,id)<($5,$6)) ORDER BY asked_at DESC,id DESC LIMIT $7`, append(args, before, cursor.ID, query.Limit+1)...)
listFilter := recordFilterSQL
listArgs := append(append([]any{}, args...), before, cursor.ID, query.Limit+1)
if query.MatchIDs != nil {
listFilter += " AND id=ANY($8::text[])"
listArgs = append(listArgs, query.MatchIDs)
}
rows, err := q.Query(ctx, c.baseSQL+` SELECT payload::text FROM records WHERE `+listFilter+`
AND ($5::timestamptz IS NULL OR (asked_at,id)<($5,$6)) ORDER BY asked_at DESC,id DESC LIMIT $7`, listArgs...)
if err != nil {
return fmt.Errorf("%w: record list failed", ErrUnavailable)
}
+5 -4
View File
@@ -19,9 +19,10 @@ func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) {
return
}
var request struct {
Start string `json:"start"`
End string `json:"end"`
Keyword string `json:"keyword"`
Start string `json:"start"`
End string `json:"end"`
Keyword string `json:"keyword"`
Filters map[string]string `json:"filters,omitempty"`
}
if decodeQualityJSON(w, r, &request, "start", "end") != nil {
qaOpsError(w, dobotaiops.ErrInvalidQuery)
@@ -37,7 +38,7 @@ func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) {
qaOpsError(w, e)
return
}
dashboard, e := reader.ReadMasterDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword})
dashboard, e := reader.ReadMasterDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword, Filters: request.Filters})
if e != nil {
if errors.Is(e, qaopsquality.ErrConflict) {
writeQualityError(w, e)
+25 -2
View File
@@ -82,7 +82,10 @@ func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
return
}
values := r.URL.Query()
allowed := map[string]bool{"start": true, "end": true, "keyword": true, "cursor": true, "limit": true}
allowed := map[string]bool{"start": true, "end": true, "keyword": true, "cursor": true, "limit": true, "projection": true}
for _, key := range dobotaiops.QualityFilterKeys {
allowed[key] = true
}
for key, items := range values {
if !allowed[key] || len(items) != 1 {
qaOpsError(w, dobotaiops.ErrInvalidQuery)
@@ -102,12 +105,27 @@ func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
return
}
}
filters := map[string]string{}
for _, key := range dobotaiops.QualityFilterKeys {
if value := values.Get(key); value != "" {
filters[key] = value
}
}
if !dobotaiops.ValidQualityFilters(filters) {
qaOpsError(w, dobotaiops.ErrInvalidQuery)
return
}
mode := values.Get("projection")
if mode != "" && mode != "summary" && mode != "full" {
qaOpsError(w, dobotaiops.ErrInvalidQuery)
return
}
projection, err := recordAttribution(r.Context(), config)
if err != nil {
qaOpsError(w, err)
return
}
page, err := config.QAOps.ListRecords(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: values.Get("keyword"), Cursor: values.Get("cursor"), Limit: limit})
page, err := config.QAOps.ListRecords(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: values.Get("keyword"), Cursor: values.Get("cursor"), Limit: limit, Summary: mode == "summary", Filters: filters})
if err != nil {
qaOpsError(w, err)
return
@@ -117,6 +135,11 @@ func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
writeQualityError(w, err)
return
}
if mode == "summary" {
for i := range page.Items {
page.Items[i] = qaRecordPreview(page.Items[i])
}
}
writeJSON(w, http.StatusOK, map[string]any{"data": page})
}
+29
View File
@@ -0,0 +1,29 @@
package httpapi
import "knowledge-governance/internal/dobotaiops"
func qaPreviewText(s string) string {
r := []rune(s)
if len(r) > 400 {
return string(r[:400]) + "…"
}
return s
}
// Summaries never replace immutable business content or a full export response.
func qaRecordPreview(item dobotaiops.Record) dobotaiops.Record {
item.ContentProjection = "summary"
item.Question = qaPreviewText(item.Question)
item.Answer = qaPreviewText(item.Answer)
fields := make(map[string]string, len(item.MasterFields))
for key, value := range item.MasterFields {
if key == "question" || key == "answer" || key == "question_chinese" {
value = qaPreviewText(value)
}
fields[key] = value
}
item.MasterFields = fields
item.References = nil
item.Media = nil
return item
}
+93
View File
@@ -0,0 +1,93 @@
package httpapi
import (
"context"
"encoding/json"
"knowledge-governance/internal/dobotaiops"
"net/http"
"net/http/httptest"
"strings"
"testing"
"unicode/utf8"
)
type qaPreviewSpy struct {
qaOpsSpy
record dobotaiops.Record
}
func (s *qaPreviewSpy) ListRecords(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
s.query = q
return dobotaiops.RecordPage{Items: []dobotaiops.Record{s.record}, Total: 1}, nil
}
func TestQALightweightListPreservesFullRecordAndRejectsUnknownProjection(t *testing.T) {
full := strings.Repeat("长😀", 900)
spy := &qaPreviewSpy{record: dobotaiops.Record{ID: "preview-fixture", Question: full, Answer: full, MasterFields: map[string]string{"question_chinese": full, "product_category": "MG400"}, References: json.RawMessage(`[{"content":"private-reference-body"}]`), Media: json.RawMessage(`[{"url":"private-media"}]`)}}
auth := newFakeAuthStore()
auth.sessions["admin-qa-fixture"] = "usr-boss"
h, err := NewHandler(Config{Store: &fakeJobStore{}, QAOps: spy, QAOpsTenantKey: "approved-tenant", Auth: &AuthConfig{Store: auth}})
if err != nil {
t.Fatal(err)
}
base := "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z"
for _, mode := range []string{"summary", "full", "invalid"} {
req := httptest.NewRequest("GET", base+"&projection="+mode, nil)
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "admin-qa-fixture"})
out := httptest.NewRecorder()
h.ServeHTTP(out, req)
if mode == "invalid" {
if out.Code != 400 {
t.Fatal("unknown projection accepted")
}
continue
}
if out.Code != 200 {
t.Fatalf("projection %s status %d", mode, out.Code)
}
var data struct{ Data dobotaiops.RecordPage }
if json.Unmarshal(out.Body.Bytes(), &data) != nil || len(data.Data.Items) != 1 {
t.Fatal("invalid page")
}
row := data.Data.Items[0]
if mode == "summary" {
if utf8.RuneCountInString(row.Answer) > 401 || row.Answer == full || strings.Contains(out.Body.String(), "private-reference-body") || strings.Contains(out.Body.String(), "private-media") {
t.Fatal("summary leaked full content")
}
} else if row.Answer != full || !strings.Contains(out.Body.String(), "private-reference-body") {
t.Fatal("full export content changed")
}
}
if spy.record.Answer != full || spy.record.MasterFields["question_chinese"] != full {
t.Fatal("preview mutated original")
}
_ = http.StatusOK
}
func TestQARecordsAcceptFiveExactFiltersAndRejectUnsupportedValues(t *testing.T) {
spy := &qaOpsSpy{}
auth := newFakeAuthStore()
auth.sessions["admin-qa-fixture"] = "usr-boss"
h, err := NewHandler(Config{Store: &fakeJobStore{}, QAOps: spy, QAOpsTenantKey: "approved-tenant", Auth: &AuthConfig{Store: auth}})
if err != nil {
t.Fatal(err)
}
base := "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z"
for _, suffix := range []string{"&coverage=是&is_correct=否&product_category=MG400&problem_type=参数&root_cause=知识缺失", "&root_cause=__empty__"} {
req := httptest.NewRequest("GET", base+suffix, nil)
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "admin-qa-fixture"})
out := httptest.NewRecorder()
h.ServeHTTP(out, req)
if out.Code != 200 || len(spy.query.Filters) == 0 {
t.Fatalf("filter not forwarded: %d", out.Code)
}
}
for _, suffix := range []string{"&coverage=invalid", "&is_correct=是&is_correct=否", "&product_category=" + strings.Repeat("x", 501)} {
req := httptest.NewRequest("GET", base+suffix, nil)
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "admin-qa-fixture"})
out := httptest.NewRecorder()
h.ServeHTTP(out, req)
if out.Code != 400 {
t.Fatal("invalid filters accepted")
}
}
}
+1
View File
@@ -45,6 +45,7 @@ type Dashboard struct {
Start time.Time `json:"start"`
End time.Time `json:"end"`
Keyword string `json:"keyword"`
Filters map[string]string `json:"filters,omitempty"`
AsOf time.Time `json:"as_of"`
LocalRevision int64 `json:"local_revision"`
Organization dobotaiops.OrganizationVersion `json:"organization"`
+2 -1
View File
@@ -24,6 +24,7 @@ type DashboardCumulative struct {
}
type dashboardTimedQuality struct {
id string
at time.Time
view qaopsquality.View
}
@@ -84,7 +85,7 @@ func (s *Store) readMasterQualityTimeline(ctx context.Context, tx pgx.Tx, keywor
if !ok {
return nil, now, qaopsquality.ErrUnavailable
}
out = append(out, dashboardTimedQuality{at: r.at, view: qaopsquality.ProjectMasterWithEdits(v, r.fields, r.coverage, r.edits, r.feedback)})
out = append(out, dashboardTimedQuality{id: r.id, at: r.at, view: qaopsquality.ProjectMasterWithEdits(v, r.fields, r.coverage, r.edits, r.feedback)})
}
return out, now, nil
}
+44 -4
View File
@@ -69,6 +69,20 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
}
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
if !dobotaiops.ValidQualityFilters(q.Filters) {
return out, dobotaiops.ErrInvalidQuery
}
if len(q.Filters) > 0 {
if !master {
return out, dobotaiops.ErrInvalidQuery
}
var err error
q, err = s.resolveMasterFilters(ctx, q)
if err != nil {
return out, err
}
out.Filters = q.Filters
}
tx, e := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
if e != nil {
return out, dobotaiops.ErrUnavailable
@@ -107,7 +121,12 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
totalSQL = strings.ReplaceAll(totalSQL, "qa_ops_mirror_records", "qa_ops_master_read_model")
totalSQL = strings.ReplaceAll(totalSQL, "lower(question)", "lower(question||E'\\n'||chinese_question||E'\\n'||COALESCE(ai_fields->>'question_chinese',''))")
}
if e = tx.QueryRow(ctx, totalSQL, s.tenant, q.Window.End, q.Keyword).Scan(&out.TotalIssues, &first); e != nil {
totalArgs := []any{s.tenant, q.Window.End, q.Keyword}
if q.MatchIDs != nil {
totalSQL += " AND id=ANY($4::text[])"
totalArgs = append(totalArgs, q.MatchIDs)
}
if e = tx.QueryRow(ctx, totalSQL, totalArgs...).Scan(&out.TotalIssues, &first); e != nil {
return out, dobotaiops.ErrUnavailable
}
lower := q.Window.Start
@@ -123,7 +142,12 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
rowsSQL = strings.ReplaceAll(rowsSQL, "SELECT id,asked_at,identity,quality_hash FROM", "SELECT id,asked_at,identity,quality_hash,effective_fields,coverage_result,inline_fields,current_feedback FROM")
rowsSQL = strings.ReplaceAll(rowsSQL, "lower(question)", "lower(question||E'\\n'||chinese_question||E'\\n'||COALESCE(ai_fields->>'question_chinese',''))")
}
rows, e := tx.Query(ctx, rowsSQL, s.tenant, lower, q.Window.End, q.Keyword)
rowsArgs := []any{s.tenant, lower, q.Window.End, q.Keyword}
if q.MatchIDs != nil {
rowsSQL = strings.Replace(rowsSQL, " ORDER BY id LIMIT", " AND id=ANY($5::text[]) ORDER BY id LIMIT", 1)
rowsArgs = append(rowsArgs, q.MatchIDs)
}
rows, e := tx.Query(ctx, rowsSQL, rowsArgs...)
if e != nil {
return out, dobotaiops.ErrUnavailable
}
@@ -254,7 +278,7 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
}
}
}
if first != nil {
if first != nil && len(q.Filters) == 0 {
snapshots, err := s.readFrozenDashboard(ctx, tx, q.Keyword, q.Window.End)
if err != nil {
return out, err
@@ -269,6 +293,15 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
if err != nil {
return out, err
}
if len(q.Filters) > 0 {
filtered := make([]dashboardTimedQuality, 0)
for _, row := range timeline {
if matchesMasterFilters(row.view, q.Filters) {
filtered = append(filtered, row)
}
}
timeline = filtered
}
out.CumulativeWeeks = dashboardCumulativeFromTimeline(timeline, q.Window.End, calculated)
month, cutoff := dashboardQualityMonth(out.WeekStart, q.Window.End, calculated)
out.QualityPeriod = &DashboardQualityPeriod{Month: month.Format("2006-01"), Start: month, CutoffAt: cutoff, CalculatedAt: calculated, Source: dashboardMonthlySource, PolicyVersion: dashboardMonthlyPolicy}
@@ -279,10 +312,17 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
out.CumulativeWeeks = []DashboardCumulative{}
out.CalendarMonths = []DashboardMonth{}
}
out.ReportedWeeks, e = s.readReportedDashboard(ctx, tx, q.Keyword, q.Window.End)
if len(q.Filters) == 0 {
out.ReportedWeeks, e = s.readReportedDashboard(ctx, tx, q.Keyword, q.Window.End)
} else {
out.ReportedWeeks = []DashboardReported{}
}
if e != nil {
return out, e
}
if e = s.masterFiltersStillCurrent(ctx, q); e != nil {
return out, e
}
if tx.Commit(ctx) != nil {
return out, dobotaiops.ErrUnavailable
}
+12 -1
View File
@@ -24,8 +24,19 @@ var masterSummarySQL = masterMetadataBase + ` SELECT count(*),'{}'::text,COALESC
var masterQualityScopeSQL = masterMetadataBase + ` SELECT id,quality_hash,marker,source_coverage::text FROM records WHERE $5::text IS NOT NULL AND `
func (s *Store) ListMasterRecords(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
q, err := s.resolveMasterFilters(ctx, q)
if err != nil {
return dobotaiops.RecordPage{}, err
}
var revision int64
p, e := s.repositoryFor(&revision, true).ListRecords(ctx, q)
repo := s.repositoryFor(&revision, true)
if q.Summary {
repo = repo.WithSummarySQL(masterMetadataBase + ` SELECT count(*),'{}'::text,'[]'::text,'[]'::text FROM records WHERE $5::text IS NOT NULL AND `)
}
p, e := repo.ListRecords(ctx, q)
if e == nil {
e = s.masterFiltersStillCurrent(ctx, q)
}
p.LocalRevision = revision
if e == nil {
for i := range p.Items {
+119
View File
@@ -0,0 +1,119 @@
package qaopsmirror
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsquality"
"sync"
"time"
)
type masterFilterCache struct {
mu sync.Mutex
key string
version string
ids []string
expires time.Time
}
func matchesMasterFilters(v qaopsquality.View, filters map[string]string) bool {
values := map[string]string{"coverage": map[string]string{"covered": "是", "uncovered": "否", "excluded": "否但不计入", "partial": "部分覆盖", "pending": "待确认"}[v.Effective.Coverage], "is_correct": map[string]string{"correct": "是", "incorrect": "否", "pending": "待确认"}[v.Effective.Correctness], "product_category": v.Effective.ProductCategory, "problem_type": v.Effective.ProblemType, "root_cause": v.Effective.RootCause}
for key, wanted := range filters {
value := values[key]
if wanted == "__empty__" {
if value != "" {
return false
}
} else if value != wanted {
return false
}
}
return true
}
func (s *Store) masterFilterVersion(ctx context.Context) (string, error) {
var version string
err := s.pool.QueryRow(ctx, `SELECT COALESCE((SELECT revision FROM qa_ops_master_state WHERE tenant_key=$1),0)::text||':'||COALESCE((SELECT sum(input_epoch+review_revision) FROM qa_ops_quality_records WHERE tenant_key=$1||'::master'),0)::text||':'||COALESCE((SELECT count(*) FROM qa_ops_quality_records WHERE tenant_key=$1||'::master'),0)::text`, s.tenant).Scan(&version)
return version, err
}
// Cache contains only IDs, never answers; every request checks data/review versions.
func (s *Store) resolveMasterFilters(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordQuery, error) {
if !dobotaiops.ValidQualityFilters(q.Filters) {
return q, dobotaiops.ErrInvalidQuery
}
if len(q.Filters) == 0 {
return q, nil
}
if !s.valid() {
return q, dobotaiops.ErrUnavailable
}
version, err := s.masterFilterVersion(ctx)
if err != nil {
return q, err
}
raw, _ := json.Marshal(struct {
Keyword string
End time.Time
Filters map[string]string
Version string
}{q.Keyword, q.Window.End, q.Filters, version})
sum := sha256.Sum256(raw)
key := hex.EncodeToString(sum[:])
cache := &s.masterFilters
cache.mu.Lock()
defer cache.mu.Unlock()
if cache.key == key && time.Now().Before(cache.expires) {
q.MatchIDs = append([]string{}, cache.ids...)
q.MatchVersion = version
return q, nil
}
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
if err != nil {
return q, err
}
defer tx.Rollback(context.Background())
timeline, _, err := s.readMasterQualityTimeline(ctx, tx, q.Keyword, q.Window.End)
if err != nil {
return q, err
}
ids := []string{}
for _, row := range timeline {
if matchesMasterFilters(row.view, q.Filters) {
ids = append(ids, row.id)
}
}
if err = tx.Commit(ctx); err != nil {
return q, err
}
latest, err := s.masterFilterVersion(ctx)
if err != nil {
return q, err
}
if latest != version {
return q, qaopsquality.ErrConflict
}
cache.key = key
cache.version = version
cache.ids = ids
cache.expires = time.Now().Add(30 * time.Second)
q.MatchIDs = append([]string{}, ids...)
q.MatchVersion = version
return q, nil
}
func (s *Store) masterFiltersStillCurrent(ctx context.Context, q dobotaiops.RecordQuery) error {
if q.MatchVersion == "" {
return nil
}
now, err := s.masterFilterVersion(ctx)
if err != nil {
return err
}
if now != q.MatchVersion {
return qaopsquality.ErrConflict
}
return nil
}
@@ -0,0 +1,83 @@
package qaopsmirror
import (
"context"
"encoding/json"
"knowledge-governance/internal/dobotaiops"
pg "knowledge-governance/internal/platform/postgres"
"testing"
"time"
)
func TestMasterFiveFiltersUseEffectiveValuesAcrossAllPagesAndDashboard(t *testing.T) {
p := mirrorFixture(t)
ctx := context.Background()
s := NewStore(p, "fixture-five-filters")
queue := pg.NewStore(p)
entry := fixtureEntry("filter-one", "有效答案")
job := claimMirrorJob(t, s, queue, "filter-seed")
if err := s.HandleSync(ctx, *job, func(context.Context) (Source, error) {
return &fixtureSource{rows: []dobotaiops.MirrorRecord{entry}}, nil
}); err != nil {
t.Fatal(err)
}
_, err := p.Exec(ctx, `UPDATE qa_ops_master_records SET local_fields='{"coverage":"是","is_correct":"否","product_category":"MG400","problem_type":"参数","root_cause":"知识缺失"}',row_revision=row_revision+1 WHERE tenant_key=$1`, s.tenant)
if err != nil {
t.Fatal(err)
}
_, err = p.Exec(ctx, `INSERT INTO qa_ops_master_records(tenant_key,id,event_key,origin,asked_at,question,status,identity,quality_hash,payload,local_fields) SELECT tenant_key,'filter-two',repeat('c',64),origin,asked_at,question,status,identity,repeat('d',64),payload||jsonb_build_object('id','filter-two','_quality_hash',repeat('d',64)),'{"coverage":"是","is_correct":"是","product_category":"CR","problem_type":"参数","root_cause":"知识缺失"}' FROM qa_ops_master_records WHERE tenant_key=$1`, s.tenant)
if err != nil {
t.Fatal(err)
}
// The real INSERT trigger initializes local_fields from the payload; use a coherent post-insert edit.
_, err = p.Exec(ctx, `UPDATE qa_ops_master_records SET local_fields='{"coverage":"是","is_correct":"是","product_category":"CR","problem_type":"参数","root_cause":"知识缺失"}',row_revision=row_revision+1 WHERE tenant_key=$1 AND id='filter-two'`, s.tenant)
if err != nil {
t.Fatal(err)
}
start := time.Now().UTC().Add(-48 * time.Hour)
q := dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: time.Now().UTC()}, Limit: 1, Filters: map[string]string{"is_correct": "否", "product_category": "MG400"}}
page, err := s.ListMasterRecords(ctx, q)
if err != nil || page.Total != 1 || len(page.Items) != 1 || page.Items[0].ID != "filter-one" {
t.Fatalf("effective filters ignored: total=%d err=%v", page.Total, err)
}
q.Filters = map[string]string{"root_cause": "__empty__"}
page, err = s.ListMasterRecords(ctx, q)
if err != nil || page.Total != 1 || page.Items[0].ID != "filter-two" {
t.Fatal("correct answers must have effective empty root cause", err, page.Total)
}
q.Filters = map[string]string{"product_category": "MG400", "root_cause": "知识缺失", "problem_type": "参数", "coverage": "是", "is_correct": "否"}
got, err := s.ReadMasterDashboard(ctx, q)
if err != nil || got.Quality.Total != 1 || got.TotalIssues != 1 {
t.Fatal("dashboard/list filters differ", err, got.Quality.Total, got.TotalIssues)
}
q.Filters = map[string]string{"problem_type": "参数"}
q.Cursor = ""
first, err := s.ListMasterRecords(ctx, q)
if err != nil || !first.HasMore || first.Total != 2 {
t.Fatalf("filter pagination first page err=%v total=%d hasMore=%v items=%d", err, first.Total, first.HasMore, len(first.Items))
}
q.Cursor = first.NextCursor
last, err := s.ListMasterRecords(ctx, q)
if err != nil || last.HasMore || len(last.Items) != 1 || last.Items[0].ID == first.Items[0].ID {
t.Fatal("filter pagination duplicate/missing", err)
}
q.Filters = map[string]string{"product_category": "MG400"}
if _, err = s.ListMasterRecords(ctx, q); err == nil {
t.Fatal("cursor reused under another filter")
}
q.Cursor = ""
q.Filters = map[string]string{"product_category": "MG400", "root_cause": "知识缺失", "problem_type": "参数", "coverage": "是", "is_correct": "否"}
// A label update must invalidate a cached scope without restarting the service.
_, err = p.Exec(ctx, `UPDATE qa_ops_master_records SET local_fields=local_fields||'{"product_category":"CR"}',row_revision=row_revision+1 WHERE tenant_key=$1 AND id='filter-one'`, s.tenant)
if err != nil {
t.Fatal(err)
}
page, err = s.ListMasterRecords(ctx, q)
if err != nil || page.Total != 0 {
t.Fatal("cached filter scope survived changed labels", err)
}
raw, _ := json.Marshal(page)
_ = raw
}
+1
View File
@@ -22,6 +22,7 @@ type Store struct {
mu sync.RWMutex
safety dobotaiops.SourceSafety
departmentStats departmentStatisticsCache
masterFilters masterFilterCache
}
func NewStore(pool *pgxpool.Pool, tenant string) *Store { return &Store{pool: pool, tenant: tenant} }