feat(qaops): 增加第40至43周实时累计趋势及受控回填依据
build / build (push) Successful in 1m8s

按北京时间各自然周截止对整张统计总表累计计数,字段取当前有效结论。
覆盖和正确各按周报是除以是加否,保留历史上报与冻结并优先展示动态累计。
新增30秒顺序刷新、本地规则和历史复用非模型依据,保护当前原问答与人工字段。

验证:完整make verify通过;隔离PostgreSQL全量mirror race通过;
恢复库与真实周报calc_metrics四点对拍、源点踩自然刷新、桌面/390px及PNG通过。
新增源同步成员变化、人工版本保护及跨策略标签间距回归已通过。
模型全量语义风险审核及正式业务回填尚未完成,未部署本版本。
This commit is contained in:
姚章浩
2026-10-20 11:09:47 +08:00
parent 2c0bb32183
commit 1580ebd826
16 changed files with 726 additions and 57 deletions
+26 -3
View File
@@ -430,6 +430,25 @@ export function QAAIEvidenceView({ evidence }: { evidence: AIEvidence[] }) {
</article>
))
: null}
{work.result.local_derivations
? Object.entries(work.result.local_derivations).map(([field, proof]) => (
<article key={field} className="qa-ai-field-evidence">
<strong>
{field === 'language'
? '语言'
: field === 'question_chinese'
? '中文问题'
: (fieldLabels[field] ?? field)}
:{proof.value}
</strong>
<p>{proof.reason}</p>
<small>
本地规则/历史复用(非模型);
{Object.hasOwn(work.applied_fields, field) ? '已回填' : '未回填,保留当前值'}
</small>
</article>
))
: null}
{work.result.question_chinese ? (
<article>
<strong>中文问题</strong>
@@ -442,10 +461,14 @@ export function QAAIEvidenceView({ evidence }: { evidence: AIEvidence[] }) {
<details>
<summary>模型、规则版本与输入指纹</summary>
<dl>
<dt>实际返回模型</dt>
<dd>{work.actual_model || '尚未返回'}</dd>
<dt>{work.actual_model === 'local-rule-history-v1' ? '结论来源(非模型)' : '实际返回模型'}</dt>
<dd>
{work.actual_model === 'local-rule-history-v1'
? '本地规则/历史复用(非模型)'
: work.actual_model || '尚未返回'}
</dd>
<dt>配置修订</dt>
<dd>{work.config_revision}</dd>
<dd>{work.config_revision === 0 ? '外部受控回填,未使用服务模型配置' : work.config_revision}</dd>
<dt>提示词版本</dt>
<dd>{work.prompt_version}</dd>
<dt>正式字典版本</dt>
+22 -11
View File
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from 'react'
import type { QAQuery } from './qaOps'
import { fetchQADashboard } from './qaDashboardData'
import { fetchQADashboard, liveDashboardQuery } from './qaDashboardData'
import type { QADashboardData } from './qaDashboardData'
import { QADashboardDrawing } from './QADashboardDrawing'
import { createDashboardPNG } from './qaDashboardExport'
@@ -100,18 +100,29 @@ export function QADashboard({
return
}
const abort = new AbortController()
let timer: ReturnType<typeof setTimeout> | undefined
setLoading(true)
void fetchQADashboard(query, abort.signal)
.then((v) => {
if (!abort.signal.aborted) setData(v)
})
.catch((e) => {
const refresh = async () => {
try {
const next = await fetchQADashboard(liveDashboardQuery(query, new Date()), abort.signal)
if (!abort.signal.aborted) {
setData(next)
setFailure('')
}
} catch (e) {
if (!abort.signal.aborted) setFailure(e instanceof Error ? e.message : '统计看板读取失败')
})
.finally(() => {
if (!abort.signal.aborted) setLoading(false)
})
return () => abort.abort()
} finally {
if (!abort.signal.aborted) {
setLoading(false)
timer = setTimeout(() => void refresh(), 30000)
}
}
}
void refresh()
return () => {
abort.abort()
if (timer !== undefined) clearTimeout(timer)
}
}, [query, revision])
return (
<div className="qa-dashboard-scroll">
+61
View File
@@ -49,6 +49,67 @@ it('renders reported history in both existing trend panels with exact values and
expect((html.match(/data-panel=/g) || []).length).toBe(11)
expect(html).toContain('data-frozen="available"')
})
it('renders dynamic cumulative points as a distinct green policy series in both charts', () => {
const data = parseQADashboard({
...dashboardFixture,
cumulative_weeks: [
{
week: '2026WK40',
week_start: '2026-09-28T00:00:00+08:00',
week_end: '2026-10-05T00:00:00+08:00',
cutoff_at: '2026-10-05T00:00:00+08:00',
calculated_at: '2026-10-18T10:00:00Z',
records: 2,
coverage: { numerator: 1, denominator: 2, percent: 50 },
correctness: { numerator: 1, denominator: 2, percent: 50 },
source: 'master_live_cumulative_v1',
policy_version: 'weekly-strict-yes-over-yes-no-v1',
},
],
})
const html = renderToStaticMarkup(<QADashboardDrawing data={data} width={350} />)
expect(html).toContain('绿:总表累计')
expect(html).toContain('stroke="#249c86"')
expect((html.match(/data-source="master_live_cumulative_v1"/g) || []).length).toBe(2)
expect(html).toContain('非历史冻结')
})
it('keeps adjacent policy-boundary week and percentage labels from overlapping in long history', () => {
const data = parseQADashboard(dashboardFixture),
first = Date.parse('2026-04-06T00:00:00+08:00'),
week = 7 * 86400000
data.end = '2026-10-20T01:00:00Z'
data.reported_weeks = Array.from({ length: 25 }, (_, i) => ({
week: `2026WK${String(15 + i).padStart(2, '0')}`,
week_start: new Date(first + i * week).toISOString(),
week_end: new Date(first + (i + 1) * week).toISOString(),
coverage_percent: 70,
correctness_percent: 97,
source: 'user_provided_history',
}))
data.cumulative_weeks = Array.from({ length: 4 }, (_, i) => ({
week: `2026WK${40 + i}`,
week_start: new Date(first + (25 + i) * week).toISOString(),
week_end: new Date(first + (26 + i) * week).toISOString(),
cutoff_at: new Date(Math.min(first + (26 + i) * week, Date.parse(data.end))).toISOString(),
calculated_at: data.end,
records: 1,
coverage: { numerator: 1, denominator: 1, percent: 100 },
correctness: { numerator: 1, denominator: 1, percent: 100 },
source: 'master_live_cumulative_v1',
policy_version: 'weekly-strict-yes-over-yes-no-v1',
}))
const html = renderToStaticMarkup(<QADashboardDrawing data={data} width={1166} />),
groups = [...html.matchAll(/<g data-source="[^"]+" data-week="[^"]+"[\s\S]*?<\/g>/g)]
const labels = groups
.slice(0, 29)
.map((g) => g[0].match(/<text x="([0-9.]+)"[^>]*>2026W[0-9]+<\/text>/))
.filter((v): v is RegExpMatchArray => v !== null)
.map((m) => Number(m[1]))
.sort((a, b) => a - b)
expect(groups).toHaveLength(58)
for (let i = 1; i < labels.length; i++) expect(labels[i] - labels[i - 1]).toBeGreaterThanOrEqual(51.99)
expect(groups.find((g) => g[0].includes('data-week="2026WK40"'))?.[0]).toContain('2026W40</text>')
})
it('reflows the same complete eleven panels at mobile width rather than clipping the canvas', () => {
const html = renderToStaticMarkup(<QADashboardDrawing data={parseQADashboard(dashboardFixture)} width={350} />)
expect((html.match(/data-panel=/g) || []).length).toBe(11)
+21 -22
View File
@@ -3,6 +3,7 @@ import type { QADashboardData, DashboardCount, DashboardRegion } from './qaDashb
import type { QualityRate } from './qaQuality'
import { currentQAWeek } from './qaWeeks'
import { historicalTrend } from './qaHistoricalTrend'
import type { HistoricalPlotPoint } from './qaHistoricalTrend'
interface Box {
x: number
y: number
@@ -267,14 +268,7 @@ function Products({ box, points }: { box: Box; points: DashboardCount[] }) {
</Panel>
)
}
interface PlotPoint {
label: string
value: number | null
hint: string
frozen?: boolean
source?: 'user_provided_history' | 'system_frozen'
week?: string
}
type PlotPoint = HistoricalPlotPoint
function Plot({
box,
title,
@@ -298,7 +292,8 @@ function Plot({
x = (i: number) =>
points.length === 1 ? (left + right) / 2 : left + (i * (right - left)) / Math.max(1, points.length - 1),
y = (n: number) => bottom - (n / max) * (bottom - top)
const color = (source: PlotPoint['source']) => (source === 'system_frozen' ? '#8b68c7' : blue)
const color = (source: PlotPoint['source']) =>
source === 'master_live_cumulative_v1' ? '#249c86' : source === 'system_frozen' ? '#8b68c7' : blue
const paths = [...new Set(points.map((p) => p.source))].map((source) => {
let path = '',
open = false
@@ -315,19 +310,21 @@ function Plot({
})
const every = Math.max(1, Math.ceil(points.length / (box.w < 420 ? 5 : 8)))
const labelled = new Set<number>()
points.forEach((point, i) => {
if (
point.value !== null &&
(i === 0 ||
points[i - 1]?.source !== point.source ||
i === points.length - 1 ||
points[i + 1]?.source !== point.source)
)
const label = (i: number) => {
if (points[i]?.value !== null && points[i] && [...labelled].every((k) => Math.abs(x(k) - x(i)) >= 52))
labelled.add(i)
}
label(0)
label(points.length - 1)
// Keep the first point of a new policy readable instead of forcing two adjacent labels at a boundary.
points.forEach((point, i) => {
if (i && points[i - 1]?.source !== point.source) label(i)
})
points.forEach((point, i) => {
if (points[i + 1]?.source !== point.source) label(i)
})
points.forEach((_, i) => {
if ((i % every === 0 || i === points.length - 1) && [...labelled].every((k) => Math.abs(x(k) - x(i)) >= 52))
labelled.add(i)
if (i % every === 0) label(i)
})
return (
<Panel box={box} title={title} en={en} id={id}>
@@ -387,9 +384,11 @@ function Plot({
))}
{percent ? (
<text x={16} y={box.h - 7} fontSize={9} fill={muted}>
{points.some((p) => p.source === 'user_provided_history')
? '蓝:用户提供(未提供分子/分母);紫:系统冻结'
: '缺失周留空;系统冻结与当前实时结果分开'}
{points.some((p) => p.source === 'master_live_cumulative_v1')
? '蓝:历史上报;紫:系统冻结;绿:总表累计'
: points.some((p) => p.source === 'user_provided_history')
? '蓝:用户提供(未提供分子/分母);紫:系统冻结'
: '缺失周留空;系统冻结与当前实时结果分开'}
</text>
) : null}
{!points.some((p) => p.value !== null) ? (
+48
View File
@@ -0,0 +1,48 @@
import { expect, it } from 'vitest'
import { renderToStaticMarkup } from 'react-dom/server'
import { parseAIEvidence } from './qaAITypes'
import { QAAIEvidenceView } from './QAAI'
const wire = {
id: 'fixture-local-proof',
record_id: 'fixture-record',
kind: 'evaluation',
state: 'succeeded',
stage: 'local_imported',
attempt: 1,
error_code: '',
skip_reason: '',
started_at: null,
updated_at: '2026-10-20T00:00:00Z',
input_hash: 'a'.repeat(64),
config_revision: 0,
prompt_version: 'qa-local-derivation-v1',
dictionary_version: 'qa-approved-labels-v1',
actual_model: 'local-rule-history-v1',
result: {
local_derivations: {
language: { value: '中文', kind: 'local_rule', reason: '原问题本地语言规则,不调用模型' },
question_chinese: { value: 'MG400如何连接?', kind: 'original_chinese_copy', reason: '原始中文逐字保留' },
product_category: { value: 'MG400', kind: 'unique_history_question_label', reason: '历史同问题标签唯一一致' },
},
},
applied_fields: { language: '中文', question_chinese: 'MG400如何连接?', product_category: 'MG400' },
skipped_fields: {},
}
it('renders field-level local and history provenance without pretending it is model output', () => {
const result = parseAIEvidence(wire)
expect(result.result).toHaveProperty('local_derivations')
const html = renderToStaticMarkup(<QAAIEvidenceView evidence={[result]} />)
for (const text of [
'本地规则/历史复用(非模型)',
'原问题本地语言规则,不调用模型',
'原始中文逐字保留',
'历史同问题标签唯一一致',
'中文',
'MG400',
])
expect(html).toContain(text)
expect(html).not.toContain('实际返回模型')
})
it('rejects local provenance falsely attached to a GPT response', () => {
expect(() => parseAIEvidence({ ...wire, actual_model: 'gpt-6.1-sol' })).toThrow()
})
+39 -1
View File
@@ -137,13 +137,22 @@ export interface AIFieldEvidence {
reason: string
quotes: AIQuote[]
}
export interface AILocalDerivation {
value: string
kind: 'local_rule' | 'original_chinese_copy' | 'unique_history_question_label'
reason: string
}
export interface AIEvidence extends AIWorkState {
input_hash: string
config_revision: number
prompt_version: string
dictionary_version: string
actual_model: string
result: { fields?: Record<string, AIFieldEvidence>; question_chinese?: string }
result: {
fields?: Record<string, AIFieldEvidence>
question_chinese?: string
local_derivations?: Record<string, AILocalDerivation>
}
applied_fields: Record<string, string>
skipped_fields: Record<string, string>
}
@@ -231,6 +240,35 @@ export function parseAIEvidence(value: unknown): AIEvidence {
})
)
}
if (r.local_derivations !== undefined) {
if (v.actual_model !== 'local-rule-history-v1') return bad()
const entries = Object.entries(aiObject(r.local_derivations))
if (!entries.length || entries.length > 4) return bad()
result.local_derivations = Object.fromEntries(
entries.map(([field, raw]) => {
const proof = aiObject(raw),
value = text(proof.value),
reason = text(proof.reason)
const expected =
field === 'language'
? 'local_rule'
: field === 'question_chinese'
? 'original_chinese_copy'
: ['product_category', 'problem_type'].includes(field)
? 'unique_history_question_label'
: null
if (
!expected ||
proof.kind !== expected ||
!value.trim() ||
!reason.trim() ||
Object.keys(proof).some((k) => !['value', 'kind', 'reason'].includes(k))
)
return bad()
return [field, { value, kind: expected, reason } as AILocalDerivation]
})
)
}
if (r.question_chinese !== undefined) result.question_chinese = text(r.question_chinese)
const input_hash = text(v.input_hash)
if (!/^[a-f0-9]{64}$/.test(input_hash)) return bad()
+69
View File
@@ -0,0 +1,69 @@
import { it, expect } from 'vitest'
import { parseQADashboard } from './qaDashboardData'
import { dashboardFixture } from './qaDashboard.fixture'
import { historicalTrend } from './qaHistoricalTrend'
it('rejects a closed-week cumulative point silently cut short before its required cutoff', () => {
const broken = structuredClone(live)
broken[1].cutoff_at = '2026-10-11T23:59:59+08:00'
expect(() => parseQADashboard({ ...dashboardFixture, cumulative_weeks: broken })).toThrow()
})
const rates = (n: number, d: number) => ({ numerator: n, denominator: d, percent: d ? (100 * n) / d : null })
const live = [
{
week: '2026WK40',
week_start: '2026-09-28T00:00:00+08:00',
week_end: '2026-10-05T00:00:00+08:00',
cutoff_at: '2026-10-05T00:00:00+08:00',
calculated_at: '2026-10-18T10:00:00Z',
records: 2,
coverage: rates(1, 2),
correctness: rates(1, 2),
source: 'master_live_cumulative_v1',
policy_version: 'weekly-strict-yes-over-yes-no-v1',
},
{
week: '2026WK41',
week_start: '2026-10-05T00:00:00+08:00',
week_end: '2026-10-12T00:00:00+08:00',
cutoff_at: '2026-10-12T00:00:00+08:00',
calculated_at: '2026-10-18T10:00:00Z',
records: 3,
coverage: rates(1, 3),
correctness: rates(2, 3),
source: 'master_live_cumulative_v1',
policy_version: 'weekly-strict-yes-over-yes-no-v1',
},
]
it('prioritizes live cumulative weeks over an overlapping report without mutating historical evidence', () => {
const wire = {
...dashboardFixture,
cumulative_weeks: live,
reported_weeks: [
{
week: '2026WK40',
week_start: live[0].week_start,
week_end: live[0].week_end,
coverage_percent: 99,
correctness_percent: 99,
source: 'user_provided_history',
},
],
}
const before = JSON.stringify(wire),
parsed = parseQADashboard(wire)
expect(historicalTrend(parsed, false)[0].source).toBe('master_live_cumulative_v1')
expect(historicalTrend(parsed, false)[0].value).toBe(50)
expect(parsed.reported_weeks[0].coverage_percent).toBe(99)
expect(JSON.stringify(wire)).toBe(before)
})
it('shows current cumulative counts instead of substituting old frozen-week values', () => {
const wire = { ...dashboardFixture, cumulative_weeks: live }
const before = JSON.stringify(wire)
const parsed = parseQADashboard(wire)
expect((parsed as unknown as { cumulative_weeks: unknown[] }).cumulative_weeks).toHaveLength(2)
expect(historicalTrend(parsed, false).map((p) => p.value)).toEqual([50, 100 / 3])
expect(historicalTrend(parsed, true).map((p) => p.value)).toEqual([50, 200 / 3])
expect(historicalTrend(parsed, true)[1].source).toBe('master_live_cumulative_v1')
expect(historicalTrend(parsed, true)[1].hint).toContain('2/3')
expect(JSON.stringify(wire)).toBe(before)
})
+85
View File
@@ -24,6 +24,18 @@ export interface DashboardFrozen {
coverage: QualityRate
correctness: QualityRate
}
export interface DashboardCumulative {
week: string
week_start: string
week_end: string
cutoff_at: string
calculated_at: string
records: number
coverage: QualityRate
correctness: QualityRate
source: 'master_live_cumulative_v1'
policy_version: 'weekly-strict-yes-over-yes-no-v1'
}
export interface DashboardRegion {
id: string
name: string
@@ -51,6 +63,7 @@ export interface QADashboardData {
regions: DashboardRegion[]
frozen_weeks: DashboardFrozen[]
reported_weeks: DashboardReported[]
cumulative_weeks?: DashboardCumulative[]
}
const bad = (): never => {
throw new Error('统计看板响应无效,未展示可能失真的指标')
@@ -233,6 +246,65 @@ export function parseQADashboard(value: unknown): QADashboardData {
}
})
if (reported_weeks.length > 5200) return bad()
const cumulative_weeks = list(v.cumulative_weeks === undefined ? [] : v.cumulative_weeks).map(
(raw, i): DashboardCumulative => {
const p = obj(raw),
begin = stamp(p.week_start),
finish = stamp(p.week_end),
cutoff = stamp(p.cutoff_at),
calculated = stamp(p.calculated_at),
records = count(p.records),
coverage = parseQualityRate(p.coverage),
correctness = parseQualityRate(p.correctness),
iso = currentQAWeek(new Date(begin))
const previous = i ? obj(list(v.cumulative_weeks)[i - 1]) : null
if (
i >= 4 ||
Date.parse(begin) !== Date.parse('2026-09-28T00:00:00+08:00') + i * 7 * dayMS ||
text(p.week) !== `${iso.year}WK${String(iso.week).padStart(2, '0')}` ||
Date.parse(finish) - Date.parse(begin) !== 7 * dayMS ||
Date.parse(cutoff) <= Date.parse(begin) ||
Date.parse(cutoff) !== Math.min(Date.parse(finish), Date.parse(end), Date.parse(calculated)) ||
p.source !== 'master_live_cumulative_v1' ||
p.policy_version !== 'weekly-strict-yes-over-yes-no-v1' ||
records > total_issues ||
coverage.denominator > records ||
correctness.denominator > records ||
Object.keys(p).some(
(k) =>
![
'week',
'week_start',
'week_end',
'cutoff_at',
'calculated_at',
'records',
'coverage',
'correctness',
'source',
'policy_version',
].includes(k)
) ||
(previous &&
(Date.parse(text(previous.cutoff_at)) !== Date.parse(text(previous.week_end)) ||
records < count(previous.records) ||
Date.parse(calculated) !== Date.parse(text(previous.calculated_at))))
)
return bad()
return {
week: text(p.week),
week_start: begin,
week_end: finish,
cutoff_at: cutoff,
calculated_at: calculated,
records,
coverage,
correctness,
source: 'master_live_cumulative_v1',
policy_version: 'weekly-strict-yes-over-yes-no-v1',
}
}
)
return {
start,
end,
@@ -241,6 +313,7 @@ export function parseQADashboard(value: unknown): QADashboardData {
week_start,
month_start,
reported_weeks,
cumulative_weeks,
local_revision: count(v.local_revision),
organization,
total_issues,
@@ -253,6 +326,18 @@ export function parseQADashboard(value: unknown): QADashboardData {
frozen_weeks,
}
}
export function liveDashboardQuery(query: QAQuery, now: Date): QAQuery {
const last = currentQAWeek(new Date(Date.parse(query.end) - 1)),
current = currentQAWeek(now)
if (
last.year !== current.year ||
last.week !== current.week ||
Date.parse(query.end) >= now.getTime() ||
now.getTime() - Date.parse(query.start) > 90 * dayMS
)
return query
return { ...query, end: now.toISOString() }
}
export async function fetchQADashboard(query: QAQuery, signal?: AbortSignal): Promise<QADashboardData> {
const response = await fetch('/api/v1/qa-ops/dashboard', {
method: 'POST',
+20
View File
@@ -0,0 +1,20 @@
import { it, expect } from 'vitest'
import { liveDashboardQuery } from './qaDashboardData'
const query = {
start: '2026-10-19T00:00:00+08:00',
end: '2026-10-20T08:00:00+08:00',
keyword: 'needle',
cursor: '',
limit: 20,
}
it('advances current-week dashboard end on each refresh without mutating the executed filter', () => {
const next = liveDashboardQuery(query, new Date('2026-10-20T09:00:00+08:00'))
expect(next.end).toBe('2026-10-20T01:00:00.000Z')
expect(next.start).toBe(query.start)
expect(next.keyword).toBe(query.keyword)
expect(query.end).toBe('2026-10-20T08:00:00+08:00')
})
it('never rolls an already closed selected week into a different week', () => {
const closed = { ...query, start: '2026-10-12T00:00:00+08:00', end: '2026-10-19T00:00:00+08:00' }
expect(liveDashboardQuery(closed, new Date('2026-10-20T09:00:00+08:00'))).toEqual(closed)
})
+15 -2
View File
@@ -5,14 +5,15 @@ export interface HistoricalPlotPoint {
value: number | null
hint: string
frozen?: boolean
source?: 'user_provided_history' | 'system_frozen'
source?: 'user_provided_history' | 'system_frozen' | 'master_live_cumulative_v1'
week?: string
}
// Never manufacture row counts or connect a line across missing weeks/policy changes.
export function historicalTrend(data: QADashboardData, correctness: boolean): HistoricalPlotPoint[] {
const frozen = new Map(data.frozen_weeks.map((p) => [Date.parse(p.week_start), p]))
const reported = new Map(data.reported_weeks.map((p) => [Date.parse(p.week_start), p]))
const starts = [...frozen.keys(), ...reported.keys()]
const cumulative = new Map((data.cumulative_weeks ?? []).map((p) => [Date.parse(p.week_start), p]))
const starts = [...frozen.keys(), ...reported.keys(), ...cumulative.keys()]
if (!starts.length) return []
const out: HistoricalPlotPoint[] = []
for (let at = Math.min(...starts); at < Date.parse(data.end) && out.length < 5200; at += 7 * 86400000) {
@@ -20,6 +21,18 @@ export function historicalTrend(data: QADashboardData, correctness: boolean): Hi
label = `${w.year}W${String(w.week).padStart(2, '0')}`,
supplied = reported.get(at),
point = frozen.get(at)
const live = cumulative.get(at)
if (live) {
const rate = correctness ? live.correctness : live.coverage
out.push({
label,
week: live.week,
value: rate.percent,
source: 'master_live_cumulative_v1',
hint: `${live.week}:${rate.percent?.toFixed(2) ?? '—'}%;${rate.numerator}/${rate.denominator};总表累计 ${live.records} 条,截至 ${live.cutoff_at};当前有效字段动态重算,是÷(是+否),非历史冻结`,
})
continue
}
if (supplied) {
const value = correctness ? supplied.correctness_percent : supplied.coverage_percent
out.push({