列表正文改为按需读取;保留完整导出、版本隔离和有效标签筛选。 验证:前端全量、Go全量及隔离PG全mirror竞态通过;覆盖首批回调、续载失败与筛选分页。
This commit is contained in:
@@ -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"`
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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} }
|
||||
|
||||
Reference in New Issue
Block a user