feat(qaops): 补充独立历史覆盖率与正确率趋势
build / build (push) Successful in 1m10s

用户提供的历史百分比独立持久化,按ISO自然周和截止范围读取,不伪造分子分母、记录数或冻结时间。现有两张趋势图与PNG共用来源分色/分段及两位小数;缺失周留空,关键词筛选不借用无明细历史,当前指标与原冻结证据不变。

验证:完整make verify退出0;镜像全量隔离PG race退出0,新增来源/精度/关键词/租户/截止/不可变和安全down回归先失败后通过。前端输入/来源及缺失周回归先红后绿。治理库上线前原生备份与真实恢复已完成,71表行数和28张QA表内容哈希一致,独立主密钥同时受限备份。

当前仅完成开发验证,真实数据候选浏览器验收、正式25周导入与应用上线需继续完成。不修改源生产数据库、原问答、已有模型自动开关或隧道;用户原始报表和图像只保存于私有证据目录,不入Git。
This commit is contained in:
姚章浩
2026-10-19 17:55:15 +08:00
parent 533db535f1
commit a9870beade
15 changed files with 453 additions and 34 deletions
@@ -0,0 +1,7 @@
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM qa_ops_reported_weekly_rates) THEN
RAISE EXCEPTION 'cannot discard imported historical rates during rollback' USING ERRCODE='55000';
END IF;
END $$;
DROP TABLE qa_ops_reported_weekly_rates;
DROP FUNCTION qa_ops_reported_history_immutable();
@@ -0,0 +1,21 @@
-- Percent-only historical reports stay separate from computed/frozen evidence.
CREATE TABLE qa_ops_reported_weekly_rates (
tenant_key TEXT NOT NULL CHECK (tenant_key<>'' AND length(tenant_key)<=128),
week_key TEXT NOT NULL CHECK (week_key ~ '^[0-9]{4}WK[0-9]{2}$'),
week_start TIMESTAMPTZ NOT NULL,
week_end TIMESTAMPTZ NOT NULL,
coverage_bp INTEGER NOT NULL CHECK (coverage_bp BETWEEN 0 AND 10000),
correctness_bp INTEGER NOT NULL CHECK (correctness_bp BETWEEN 0 AND 10000),
source_sha256 TEXT NOT NULL CHECK (source_sha256 ~ '^[a-f0-9]{64}$'),
imported_by TEXT NOT NULL CHECK (btrim(imported_by)<>''),
imported_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (tenant_key,week_key),
UNIQUE (tenant_key,week_start),
CHECK (week_end=week_start+interval '168 hours'),
CHECK (extract(isodow FROM week_start AT TIME ZONE 'Asia/Shanghai')=1),
CHECK ((week_start AT TIME ZONE 'Asia/Shanghai')::time=time '00:00:00'),
CHECK (week_key=to_char(week_start AT TIME ZONE 'Asia/Shanghai','IYYY"WK"IW'))
);
CREATE FUNCTION qa_ops_reported_history_immutable() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'reported historical rates are immutable; keep the original source' USING ERRCODE='55000'; END $$;
CREATE TRIGGER qa_reported_history_immutable BEFORE UPDATE OR DELETE ON qa_ops_reported_weekly_rates FOR EACH ROW EXECUTE FUNCTION qa_ops_reported_history_immutable();
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 56 {
t.Fatalf("migration count = %d, want 56", len(migrations))
if len(migrations) != 57 {
t.Fatalf("migration count = %d, want 57", 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])
+10
View File
@@ -14,6 +14,15 @@ type DashboardDaily struct {
Date string `json:"date"`
Count int `json:"count"`
}
type DashboardReported struct {
Week string `json:"week"`
WeekStart time.Time `json:"week_start"`
WeekEnd time.Time `json:"week_end"`
CoveragePercent float64 `json:"coverage_percent"`
CorrectnessPercent float64 `json:"correctness_percent"`
Source string `json:"source"`
}
type DashboardFrozen struct {
WeekStart time.Time `json:"week_start"`
WeekEnd time.Time `json:"week_end"`
@@ -49,6 +58,7 @@ type Dashboard struct {
Daily []DashboardDaily `json:"daily"`
Regions []DashboardRegion `json:"regions"`
FrozenWeeks []DashboardFrozen `json:"frozen_weeks"`
ReportedWeeks []DashboardReported `json:"reported_weeks"`
}
var dashboardLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
@@ -0,0 +1,36 @@
package qaopsmirror
import (
"context"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/dobotaiops"
"time"
)
// Supplied aggregates have neither row-level evidence nor a keyword denominator.
func (s *Store) readReportedDashboard(ctx context.Context, tx pgx.Tx, keyword string, end time.Time) ([]DashboardReported, error) {
out := []DashboardReported{}
if keyword != "" {
return out, nil
}
rows, err := tx.Query(ctx, `SELECT week_key,week_start,week_end,coverage_bp,correctness_bp FROM qa_ops_reported_weekly_rates WHERE tenant_key=$1 AND week_end<=$2 ORDER BY week_start`, s.tenant, end)
if err != nil {
return nil, dobotaiops.ErrUnavailable
}
defer rows.Close()
for rows.Next() {
var p DashboardReported
var coverage, correctness int
if rows.Scan(&p.Week, &p.WeekStart, &p.WeekEnd, &coverage, &correctness) != nil {
return nil, dobotaiops.ErrUnavailable
}
p.CoveragePercent = float64(coverage) / 100
p.CorrectnessPercent = float64(correctness) / 100
p.Source = "user_provided_history"
out = append(out, p)
}
if rows.Err() != nil {
return nil, dobotaiops.ErrUnavailable
}
return out, nil
}
@@ -0,0 +1,77 @@
package qaopsmirror
import (
"context"
"encoding/json"
"errors"
"github.com/jackc/pgx/v5/pgconn"
"knowledge-governance/internal/dobotaiops"
pg "knowledge-governance/internal/platform/postgres"
"strings"
"testing"
"time"
)
func TestReportedHistoryIsIndependentExactScopedAndImmutable(t *testing.T) {
p := mirrorFixture(t)
ctx := context.Background()
s := NewStore(p, "fixture-reported-history")
insert := `INSERT INTO qa_ops_reported_weekly_rates(tenant_key,week_key,week_start,week_end,coverage_bp,correctness_bp,source_sha256,imported_by) VALUES($1,'2026WK40','2026-09-28T00:00:00+08:00','2026-10-05T00:00:00+08:00',5723,9234,$2,'fixture-admin')`
if _, err := p.Exec(ctx, insert, s.tenant, strings.Repeat("a", 64)); err != nil {
t.Fatal(err)
}
start, _ := time.Parse(time.RFC3339, "2026-10-05T00:00:00+08:00")
end := start.AddDate(0, 0, 7)
read := func(tenant, keyword string, until time.Time) map[string]any {
t.Helper()
data, err := NewStore(p, tenant).ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: tenant, Start: until.AddDate(0, 0, -7), End: until}, Keyword: keyword})
if err != nil {
t.Fatal(err)
}
raw, _ := json.Marshal(data)
var wire map[string]any
if json.Unmarshal(raw, &wire) != nil {
t.Fatal("bad dashboard JSON")
}
return wire
}
data := read(s.tenant, "", end)
history, ok := data["reported_weeks"].([]any)
if !ok || len(history) != 1 {
t.Fatalf("reported percent-only history was not exposed independently: present=%v", ok)
}
row := history[0].(map[string]any)
if row["coverage_percent"] != 57.23 || row["correctness_percent"] != 92.34 || row["source"] != "user_provided_history" || row["week"] != "2026WK40" {
t.Fatal("reported precision or provenance lost")
}
for _, forbidden := range []string{"numerator", "denominator", "records", "frozen_at"} {
if _, exists := row[forbidden]; exists {
t.Fatal("invented historical evidence", forbidden)
}
}
if len(data["frozen_weeks"].([]any)) != 0 {
t.Fatal("historical input manufactured frozen evidence")
}
for _, wire := range []map[string]any{read(s.tenant, "needle", end), read("fixture-other-tenant", "", end), read(s.tenant, "", start.Add(-time.Hour))} {
if value, ok := wire["reported_weeks"].([]any); !ok || len(value) != 0 {
t.Fatal("history leaked across keyword, tenant or closing cutoff")
}
}
for _, query := range []string{`UPDATE qa_ops_reported_weekly_rates SET coverage_bp=123 WHERE tenant_key=$1`, `DELETE FROM qa_ops_reported_weekly_rates WHERE tenant_key=$1`} {
tx, e := p.Begin(ctx)
if e != nil {
t.Fatal(e)
}
_, e = tx.Exec(ctx, query, s.tenant)
_ = tx.Rollback(ctx)
var db *pgconn.PgError
if !errors.As(e, &db) || db.Code != "55000" {
t.Fatal("reported history could be overwritten or deleted")
}
}
e := pg.RollbackLatestMigration(ctx, p)
var failure *pgconn.PgError
if !errors.As(e, &failure) || failure.Code != "55000" {
t.Fatal("down did not explicitly protect historical data", e)
}
}
+4
View File
@@ -256,6 +256,10 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
return out, dobotaiops.ErrInvalidQuery
}
}
out.ReportedWeeks, e = s.readReportedDashboard(ctx, tx, q.Keyword, q.Window.End)
if e != nil {
return out, e
}
if tx.Commit(ctx) != nil {
return out, dobotaiops.ErrUnavailable
}