fix(qaops): 点踩问题统一判为不正确

通过持久来源关联读取最新本地反馈,强制总表有效正确性为否,保留原问答和人工证据。统一列表、详情、指标和两阶段读取的反馈快照,拒绝冲突选择并保留其他字段编辑。已通过完整本地门禁、隔离PG竞态和真实恢复库52条点踩逐条读回、桌面及手机验收;未调用模型或连接源生产库。
This commit is contained in:
姚章浩
2026-10-20 08:18:03 +08:00
parent 87f97a2f9b
commit ace8578152
22 changed files with 403 additions and 35 deletions
+7
View File
@@ -76,6 +76,13 @@
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
## 开发快照 snapshot/v0.1.42 - 2026-10-20
### Fixed
- 问题存在当前点踩时,总表有效“是否正确”固定为“否”,列表、详情和动态质量统计使用同一规则;通过已保存来源关联读取本地镜像最新反馈,避免导入快照漏掉后续点踩。仅点赞或无反馈不推定正确,原问答、旧模型结论、人工复核与字段修改审计保持不变。
- 详情对已点踩问题锁定“是否正确”并简洁说明;后端拒绝改为“是”或“待确认”的冲突选择,其余字段仍可编辑。迁移59只补充派生读模型、反馈索引及总表快照失效通知,不回写 DobotAI 源数据,也不重算或覆盖旧周冻结与历史上报。
## 开发快照 snapshot/v0.1.41 - 2026-10-20
### Added
+3 -3
View File
@@ -45,7 +45,7 @@
],
"paths": {
"/api/v1/qa-ops/master/field-options": {"get":{"operationId":"getQAMasterFieldOptions","tags":["QA operations"],"summary":"只读主表五字段的正式可选范围,与模型共享同一分类字典;不返回业务问答","parameters":[],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}}},
"/api/v1/qa-ops/master/records/{id}/fields": {"post":{"operationId":"patchQAMasterFields","tags":["QA operations"],"summary":"只更新明确选择的字段并留幂等审计;不改原始正文、其他空白、旧复核或冻结证据","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-master-fields"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["input_hash","input_epoch","base_revision","base_review_revision","nonce","fields"],"properties":{"input_hash":{"type":"string","pattern":"^[a-f0-9]{64}$"},"input_epoch":{"type":"integer","minimum":1},"base_revision":{"type":"integer","minimum":0},"base_review_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"fields":{"type":"object","additionalProperties":false,"minProperties":1,"maxProperties":5,"properties":{"is_correct":{"type":"string","enum":["是","否","待确认"]},"product_category":{"type":"string","enum":["CR/CRA/H/AP","CRV","CR配件","Nova及系列","Nova配件","MG400","MG400配件","M1 Pro","VX500","新示教器","DobotStudio Pro","仿真软件","维护工具","教育所有产品","人形机器人","四六足机器人","X-Trainer","码垛解决方案","码垛插件","焊接解决方案","焊接插件","移动复合机器人","生态插件","生态合作","安全皮肤","未知"]},"problem_type":{"type":"string","enum":["参数","故障","使用配置","二次开发","资料获取","咨询","认证","案例","售后","培训与学习","其他"]},"root_cause":{"type":"string","enum":["知识缺失","检索不到","结果不清","答案生成错误","问题质量差","非知识范围","知识过期"]},"coverage":{"type":"string","enum":["是","否","否但不计入"]}}}}}}}}}},
"/api/v1/qa-ops/master/records/{id}/fields": {"post":{"operationId":"patchQAMasterFields","tags":["QA operations"],"summary":"只更新明确选择的字段并留幂等审计;不改原始正文、其他空白、旧复核或冻结证据。存在当前点踩时是否正确固定为否,改为是或待确认返回409且不写审计","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-master-fields"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["input_hash","input_epoch","base_revision","base_review_revision","nonce","fields"],"properties":{"input_hash":{"type":"string","pattern":"^[a-f0-9]{64}$"},"input_epoch":{"type":"integer","minimum":1},"base_revision":{"type":"integer","minimum":0},"base_review_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"fields":{"type":"object","additionalProperties":false,"minProperties":1,"maxProperties":5,"properties":{"is_correct":{"type":"string","enum":["是","否","待确认"]},"product_category":{"type":"string","enum":["CR/CRA/H/AP","CRV","CR配件","Nova及系列","Nova配件","MG400","MG400配件","M1 Pro","VX500","新示教器","DobotStudio Pro","仿真软件","维护工具","教育所有产品","人形机器人","四六足机器人","X-Trainer","码垛解决方案","码垛插件","焊接解决方案","焊接插件","移动复合机器人","生态插件","生态合作","安全皮肤","未知"]},"problem_type":{"type":"string","enum":["参数","故障","使用配置","二次开发","资料获取","咨询","认证","案例","售后","培训与学习","其他"]},"root_cause":{"type":"string","enum":["知识缺失","检索不到","结果不清","答案生成错误","问题质量差","非知识范围","知识过期"]},"coverage":{"type":"string","enum":["是","否","否但不计入"]}}}}}}}}}},
"/api/v1/qa-ops/master/weekly-drafts/{week}": {"get":{"operationId":"getQAWeeklyDraft","tags":["QA operations"],"summary":"读取租户指定北京时间ISO周的持久草稿;不存在时revision=0且不创建记录","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}},"post":{"operationId":"saveQAWeeklyDraft","tags":["QA operations"],"summary":"防抖编辑保存:版本锁、逐版历史及同nonce重放;正文不会触发外发/归档","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-draft"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["base_revision","nonce","markdown"],"properties":{"base_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"markdown":{"type":"string","maxLength":262144,"description":"UTF-8正文最多256KiB;允许空正文,保存草稿不等于发布"}}}}}}}},
"/api/v1/qa-ops/master/weekly-drafts/{week}/prefill": {"post":{"operationId":"prefillQAWeeklyDraft","tags":["QA operations"],"summary":"从同一正式总表截止和保存区域生成中英各六节草稿;优先匹配已上报/冻结历史指标,其余用当周实时指标;不编造FAQ调整或重点。须带当前草稿版本,防止覆盖旧编辑","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-draft"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["base_revision","nonce"],"properties":{"base_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"}}}}}}}},
"/api/v1/qa-ops/departments/statistics": {
@@ -290,7 +290,7 @@
"QA operations"
],
"operationId": "listQAOperationsRecordsMaster",
"summary": "正式主表:按半开提问时间范围、原问题关键词、稳定游标列出钉钉问答;租户由后端固定;答案包含暂无已发布则治理侧未覆盖",
"summary": "正式主表:按半开提问时间范围、原问题关键词、稳定游标列出问答;租户固定。通过持久来源关联读取本地镜像最新反馈,点踩强制有效是否正确为否,quality.feedback_rule=downvote-is-incorrect-v1;原人工证据保留,点赞不推定正确。答案包含暂无已发布则未覆盖",
"parameters": [
{
"name": "start",
@@ -366,7 +366,7 @@
"QA operations"
],
"operationId": "getQAOperationsRecordMaster",
"summary": "正式主表:读取授权租户内的完整问答与源端覆盖对照;治理覆盖规则独立,不写回源库",
"summary": "正式主表:读取授权租户内的完整问答与最新本地反馈;点踩强制有效是否正确为否,quality.feedback_rule=downvote-is-incorrect-v1;原人工证据不改写,治理规则不写回源库",
"parameters": [
{
"name": "id",
@@ -0,0 +1,53 @@
package httpapi
import (
"context"
"encoding/json"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsquality"
"testing"
)
type downvoteSnapshotReader struct {
QAOpsReader
view qaopsquality.View
}
func (s downvoteSnapshotReader) ReadStoredQuality(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
return map[string]qaopsquality.View{"fixture-feedback-race": s.view}, nil
}
func TestMasterQualityEnrichmentUsesOneFeedbackDecisionEvenWhenVoteChangesBetweenReads(t *testing.T) {
for _, test := range []struct {
name string
old, current dobotaiops.RecordFeedback
label, correctness, rule string
}{
{"new-downvote", dobotaiops.RecordFeedback{}, dobotaiops.RecordFeedback{Down: 1}, "否", "incorrect", "downvote-is-incorrect-v1"},
{"withdrawn-current-vote", dobotaiops.RecordFeedback{Down: 1}, dobotaiops.RecordFeedback{}, "是", "correct", ""},
} {
t.Run(test.name, func(t *testing.T) {
view := qaopsquality.View{EffectiveSource: "master-effective-fields-v1", FeedbackRule: test.rule, Effective: qaopsquality.Fields{Correctness: test.correctness}, MasterFeedback: &test.current}
c := Config{QAOps: downvoteSnapshotReader{view: view}, QAQuality: &qualityFake{}}
item := dobotaiops.Record{ID: "fixture-feedback-race", RecordOrigin: "dobotai_2_0", Feedback: test.old, MasterFields: map[string]string{"is_correct": "待确认"}}
if err := enrichQAQualityRecord(context.Background(), c, &item); err != nil {
t.Fatal(err)
}
if item.Feedback != test.current || item.MasterFields["is_correct"] != test.label {
t.Fatal("detail combines an old feedback snapshot with a newer quality decision")
}
page := dobotaiops.RecordPage{Items: []dobotaiops.Record{{ID: item.ID, RecordOrigin: item.RecordOrigin, Feedback: test.old, MasterFields: map[string]string{"is_correct": "待确认"}}}}
// The common projection must be shared by the list and detail enrichment paths.
if err := enrichQAQualityPage(context.Background(), c, &page); err != nil {
t.Fatal(err)
}
if page.Items[0].Feedback != test.current || page.Items[0].MasterFields["is_correct"] != test.label {
t.Fatal("list combines an old feedback snapshot with a newer quality decision")
}
var quality map[string]any
if json.Unmarshal(item.Quality, &quality) != nil {
t.Fatal("quality response missing")
}
})
}
}
+2
View File
@@ -43,6 +43,8 @@ func qaMasterFieldPatch(w http.ResponseWriter, r *http.Request, c Config) {
result, err := writer.PatchMasterFields(r.Context(), r.PathValue("id"), q, identity.Username)
if err != nil {
switch {
case errors.Is(err, qaopsquality.ErrDownvoted):
writeJSON(w, 409, map[string]string{"error": "问题已点踩,是否正确固定为否;未保存冲突选择,请重新读取"})
case errors.Is(err, qaopsquality.ErrConflict):
writeJSON(w, 409, map[string]string{"error": "字段或问答版本已变化,请重新读取后修改;未覆盖其他人的内容"})
case errors.Is(err, dobotaiops.ErrInvalidQuery):
+19 -2
View File
@@ -68,9 +68,26 @@ func enrichQAQualityRecord(ctx context.Context, c Config, item *dobotaiops.Recor
if !ok {
return qaopsquality.ErrUnavailable
}
item.Quality, err = json.Marshal(v)
return attachQAQualityView(item, v)
}
func attachQAQualityView(item *dobotaiops.Record, view qaopsquality.View) error {
// A vote may change between the payload and quality reads; return the vote
// that actually produced this decision, not a contradictory older snapshot.
if view.MasterFeedback != nil && item.RecordOrigin != "" {
item.Feedback = *view.MasterFeedback
fields := make(map[string]string, len(item.MasterFields)+1)
for key, value := range item.MasterFields {
fields[key] = value
}
fields["is_correct"] = map[string]string{"correct": "是", "incorrect": "否", "pending": "待确认"}[view.Effective.Correctness]
item.MasterFields = fields
}
raw, err := json.Marshal(view)
item.Quality = raw
return err
}
func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordPage) error {
if c.QAQuality == nil {
return nil
@@ -84,7 +101,7 @@ func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordP
if !ok {
return qaopsquality.ErrUnavailable
}
page.Items[i].Quality, err = json.Marshal(v)
err = attachQAQualityView(&page.Items[i], v)
if err != nil {
return err
}
@@ -0,0 +1,15 @@
DROP TRIGGER qa_mirror_feedback_master_revision ON qa_ops_mirror_records;
DROP FUNCTION qa_ops_master_feedback_revision();
DROP VIEW qa_ops_master_read_model;
CREATE OR REPLACE VIEW qa_ops_master_read_model AS
SELECT m.*,a.ai_fields,t.background_tasks,qa_ops_fill_empty_fields(m.local_fields||jsonb_build_object('question_chinese',m.chinese_question),a.ai_fields)||COALESCE(CASE WHEN e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0) THEN e.fields END,'{}'::jsonb) AS effective_fields,COALESCE(e.revision,0) AS field_edit_revision,COALESCE(CASE WHEN e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0) THEN e.fields END,'{}'::jsonb) AS inline_fields
FROM qa_ops_master_records m LEFT JOIN LATERAL (
SELECT COALESCE(jsonb_object_agg(f.key,f.value ORDER BY o.created_at,o.work_id),'{}'::jsonb) AS ai_fields
FROM qa_ops_ai_outputs o CROSS JOIN LATERAL jsonb_each(o.applied_fields) f
WHERE o.tenant_key=m.tenant_key AND o.record_id=m.id AND o.input_hash=CASE WHEN o.kind='evaluation' THEN m.quality_hash ELSE encode(sha256(convert_to(m.question,'UTF8')),'hex') END
) a ON true LEFT JOIN LATERAL (
SELECT COALESCE(jsonb_agg(jsonb_build_object('id',w.id,'record_id',w.record_id,'kind',w.kind,'state',w.state,'stage',w.stage,'attempt',w.attempt,'error_code',w.error_code,'skip_reason',w.skip_reason,'started_at',w.started_at,'updated_at',w.updated_at)),'[]'::jsonb) AS background_tasks
FROM (SELECT DISTINCT ON (kind) * FROM qa_ops_ai_work WHERE tenant_key=m.tenant_key AND record_id=m.id ORDER BY kind,created_at DESC,id DESC) w
) t ON true LEFT JOIN qa_ops_quality_records h ON h.tenant_key=m.tenant_key||'::master' AND h.record_id=m.id LEFT JOIN qa_ops_master_field_overrides e ON e.tenant_key=m.tenant_key AND e.record_id=m.id;
DROP INDEX idx_qa_master_source_feedback;
DROP FUNCTION qa_ops_feedback_is_down(jsonb);
@@ -0,0 +1,33 @@
-- Feedback is a derived business rule; imported payloads and human evidence stay immutable.
CREATE FUNCTION qa_ops_feedback_is_down(value jsonb) RETURNS boolean LANGUAGE sql IMMUTABLE AS $$
SELECT COALESCE(value->>'asker_value'='down',false) OR CASE WHEN jsonb_typeof(value->'down')='number' THEN (value->>'down')::numeric>0 ELSE false END
$$;
CREATE INDEX idx_qa_master_source_feedback ON qa_ops_master_source_links(tenant_key,master_id,source_kind,source_id);
CREATE FUNCTION qa_ops_master_feedback_revision() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP='UPDATE' AND OLD.payload->'feedback' IS NOT DISTINCT FROM NEW.payload->'feedback' THEN RETURN NEW; END IF;
IF EXISTS(SELECT 1 FROM qa_ops_master_source_links WHERE tenant_key=NEW.tenant_key AND source_kind='dobotai_2_0' AND source_id=NEW.id) THEN
UPDATE qa_ops_master_state SET revision=revision+1,updated_at=clock_timestamp() WHERE tenant_key=NEW.tenant_key;
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER qa_mirror_feedback_master_revision AFTER INSERT OR UPDATE OF payload ON qa_ops_mirror_records FOR EACH ROW EXECUTE FUNCTION qa_ops_master_feedback_revision();
-- The effective read contract changes once on activation, without rewriting any question row.
UPDATE qa_ops_master_state SET revision=revision+1,updated_at=clock_timestamp();
CREATE OR REPLACE VIEW qa_ops_master_read_model AS
SELECT m.*,a.ai_fields,t.background_tasks,qa_ops_fill_empty_fields(m.local_fields||jsonb_build_object('question_chinese',m.chinese_question),a.ai_fields)||COALESCE(CASE WHEN e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0) THEN e.fields END,'{}'::jsonb)||CASE WHEN qa_ops_feedback_is_down(f.current_feedback) THEN '{"is_correct":"否"}'::jsonb ELSE '{}'::jsonb END AS effective_fields,COALESCE(e.revision,0) AS field_edit_revision,COALESCE(CASE WHEN e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0) THEN e.fields END,'{}'::jsonb) AS inline_fields,f.current_feedback
FROM qa_ops_master_records m LEFT JOIN LATERAL (
SELECT COALESCE((
SELECT jsonb_build_object('asker_value',CASE WHEN bool_or(r.payload#>>'{feedback,asker_value}'='down') THEN 'down' WHEN bool_or(r.payload#>>'{feedback,asker_value}'='up') THEN 'up' ELSE '' END,
'up',sum(COALESCE((r.payload#>>'{feedback,up}')::bigint,0)),'down',sum(COALESCE((r.payload#>>'{feedback,down}')::bigint,0)))
FROM qa_ops_master_source_links l JOIN qa_ops_mirror_records r ON r.tenant_key=l.tenant_key AND r.id=l.source_id
WHERE l.tenant_key=m.tenant_key AND l.master_id=m.id AND l.source_kind='dobotai_2_0' HAVING count(*)>0
),jsonb_build_object('asker_value','','up',0,'down',0)||COALESCE(NULLIF(m.payload->'feedback','null'::jsonb),'{}'::jsonb)) AS current_feedback
) f ON true LEFT JOIN LATERAL (
SELECT COALESCE(jsonb_object_agg(f.key,f.value ORDER BY o.created_at,o.work_id),'{}'::jsonb) AS ai_fields
FROM qa_ops_ai_outputs o CROSS JOIN LATERAL jsonb_each(o.applied_fields) f
WHERE o.tenant_key=m.tenant_key AND o.record_id=m.id AND o.input_hash=CASE WHEN o.kind='evaluation' THEN m.quality_hash ELSE encode(sha256(convert_to(m.question,'UTF8')),'hex') END
) a ON true LEFT JOIN LATERAL (
SELECT COALESCE(jsonb_agg(jsonb_build_object('id',w.id,'record_id',w.record_id,'kind',w.kind,'state',w.state,'stage',w.stage,'attempt',w.attempt,'error_code',w.error_code,'skip_reason',w.skip_reason,'started_at',w.started_at,'updated_at',w.updated_at)),'[]'::jsonb) AS background_tasks
FROM (SELECT DISTINCT ON (kind) * FROM qa_ops_ai_work WHERE tenant_key=m.tenant_key AND record_id=m.id ORDER BY kind,created_at DESC,id DESC) w
) t ON true LEFT JOIN qa_ops_quality_records h ON h.tenant_key=m.tenant_key||'::master' AND h.record_id=m.id LEFT JOIN qa_ops_master_field_overrides e ON e.tenant_key=m.tenant_key AND e.record_id=m.id;
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 58 {
t.Fatalf("migration count = %d, want 58", len(migrations))
if len(migrations) != 59 {
t.Fatalf("migration count = %d, want 59", 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])
@@ -0,0 +1,30 @@
package postgres
import (
"strings"
"testing"
)
func TestMasterDownvoteMigrationPreservesOriginalAndSavedHumanData(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
m := migrations[58]
if m.Version != 59 {
t.Fatal("missing feedback-rule migration")
}
for _, marker := range []string{"CREATE FUNCTION qa_ops_feedback_is_down", "qa_ops_master_source_links", "l.master_id=m.id", "l.source_kind='dobotai_2_0'", "current_feedback", "'{\"is_correct\":\"否\"}'::jsonb", "e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0)", "qa_mirror_feedback_master_revision", "CREATE INDEX idx_qa_master_source_feedback"} {
if !strings.Contains(m.UpSQL, marker) {
t.Fatalf("downvote read contract missing: %s", marker)
}
}
for _, marker := range []string{"UPDATE qa_ops_master_records", "UPDATE qa_ops_quality_reviews", "UPDATE qa_ops_master_field_overrides", "DELETE FROM", "DROP TABLE"} {
if strings.Contains(m.UpSQL, marker) || strings.Contains(m.DownSQL, marker) {
t.Fatalf("derived feedback migration mutates saved business or human evidence: %s", marker)
}
}
if !strings.Contains(m.DownSQL, "AS inline_fields") || !strings.Contains(m.DownSQL, "DROP TRIGGER qa_mirror_feedback_master_revision") {
t.Fatal("rollback must retain sparse human fields and remove only the new derived feedback contract")
}
}
@@ -10,7 +10,7 @@ func TestInlineFieldsWeeklyDraftMigrationIsAdditiveTenantScopedAndRollbackProtec
if e != nil {
t.Fatal(e)
}
m := migrations[len(migrations)-1]
m := migrations[57]
if m.Version != 58 {
t.Fatal("missing migration 58")
}
+8 -4
View File
@@ -20,6 +20,7 @@ type dashboardRecord struct {
fields map[string]string
edits map[string]string
coverage dobotaiops.CoverageCheck
feedback dobotaiops.RecordFeedback
}
func dashboardRate(n, d int) qaopsquality.Rate {
@@ -119,7 +120,7 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
rowsSQL := `SELECT id,asked_at,identity,quality_hash FROM qa_ops_mirror_records WHERE tenant_key=$1 AND asked_at>=$2 AND asked_at<$3 AND ($4='' OR position(lower($4) IN lower(question))>0) ORDER BY id LIMIT 100001`
if master {
rowsSQL = strings.ReplaceAll(rowsSQL, "qa_ops_mirror_records", "qa_ops_master_read_model")
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 FROM")
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)
@@ -133,8 +134,8 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
var identity []byte
var scanErr error
if master {
var fields, coverage, edits []byte
scanErr = rows.Scan(&r.id, &r.at, &identity, &r.hash, &fields, &coverage, &edits)
var fields, coverage, edits, feedback []byte
scanErr = rows.Scan(&r.id, &r.at, &identity, &r.hash, &fields, &coverage, &edits, &feedback)
if scanErr == nil {
scanErr = json.Unmarshal(fields, &r.fields)
if scanErr == nil {
@@ -144,6 +145,9 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
if scanErr == nil {
scanErr = json.Unmarshal(coverage, &r.coverage)
}
if scanErr == nil {
scanErr = json.Unmarshal(feedback, &r.feedback)
}
} else {
scanErr = rows.Scan(&r.id, &r.at, &identity, &r.hash)
}
@@ -187,7 +191,7 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
if master {
for _, r := range records {
if v, ok := views[r.id]; ok {
views[r.id] = qaopsquality.ProjectMasterWithEdits(v, r.fields, r.coverage, r.edits)
views[r.id] = qaopsquality.ProjectMasterWithEdits(v, r.fields, r.coverage, r.edits, r.feedback)
}
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ func (s *Store) MasterQualityStore() *qaopsquality.Store {
return qaopsquality.NewStore(s.pool, s.tenant+"::master")
}
const masterBaseSQL = `WITH records AS (SELECT id,asked_at,question||E'\n'||chinese_question||E'\n'||COALESCE(ai_fields->>'question_chinese','') AS question,status,identity,quality_hash,jsonb_set(payload,'{master_fields}',effective_fields)||jsonb_build_object('record_origin',origin,'background_tasks',background_tasks,'field_edit_revision',field_edit_revision) AS payload FROM qa_ops_master_read_model WHERE tenant_key=$1)`
const masterBaseSQL = `WITH records AS (SELECT id,asked_at,question||E'\n'||chinese_question||E'\n'||COALESCE(ai_fields->>'question_chinese','') AS question,status,identity,quality_hash,jsonb_set(payload,'{master_fields}',effective_fields)||jsonb_build_object('record_origin',origin,'background_tasks',background_tasks,'field_edit_revision',field_edit_revision,'feedback',current_feedback) AS payload FROM qa_ops_master_read_model WHERE tenant_key=$1)`
var masterMetadataBase = strings.NewReplacer("qa_ops_mirror_records", "qa_ops_master_read_model", "h.tenant_key=m.tenant_key", "h.tenant_key=m.tenant_key||'::master'", "m.question", "(m.question||E'\\n'||m.chinese_question||E'\\n'||COALESCE(m.ai_fields->>'question_chinese','')) AS question").Replace(localMetadataBase)
@@ -0,0 +1,86 @@
package qaopsmirror
import (
"context"
"encoding/json"
"knowledge-governance/internal/dobotaiops"
pg "knowledge-governance/internal/platform/postgres"
"testing"
"time"
)
func TestMasterDownvoteOverridesStoredAndInlineCorrectnessAcrossReaders(t *testing.T) {
p := mirrorFixture(t)
ctx := context.Background()
s := NewStore(p, "fixture-feedback-rule")
queue := pg.NewStore(p)
entry := fixtureEntry("feedback-rule", "已有资料")
var wire map[string]any
if err := json.Unmarshal(entry.Payload, &wire); err != nil {
t.Fatal(err)
}
wire["asked_at"] = "2026-10-06T08:00:00+08:00"
entry.Payload, _ = json.Marshal(wire)
job := claimMirrorJob(t, s, queue, "feedback-rule-seed")
if err := s.HandleSync(ctx, *job, func(context.Context) (Source, error) {
return &fixtureSource{rows: []dobotaiops.MirrorRecord{entry}}, nil
}); err != nil {
t.Fatal(err)
}
if _, err := p.Exec(ctx, `UPDATE qa_ops_master_records SET local_fields=local_fields||'{"coverage":"是","is_correct":"是","product_category":"MG400","problem_type":"参数"}'::jsonb WHERE tenant_key=$1 AND id=$2`, s.tenant, "feedback-rule"); err != nil {
t.Fatal(err)
}
rec, err := s.GetMasterRecord(ctx, s.tenant, "feedback-rule")
if err != nil {
t.Fatal(err)
}
keys := []dobotaiops.QualityKey{{ID: rec.ID, InputHash: rec.QualityInputHash}}
views, err := s.ReadMasterQualityViews(ctx, keys)
if err != nil {
t.Fatal(err)
}
v := views[rec.ID]
receipt, err := s.PatchMasterFields(ctx, rec.ID, MasterFieldPatch{InputHash: v.InputHash, InputEpoch: v.InputEpoch, BaseReviewRevision: v.Revision, Nonce: "fixture_feedback_rule_001", Fields: map[string]string{"is_correct": "是"}}, "fixture-admin")
if err != nil || receipt.SavedRevision != 1 {
t.Fatal("fixture inline positive edit failed", err)
}
var before string
if err = p.QueryRow(ctx, `SELECT md5(payload::text||original_fields::text||local_fields::text) FROM qa_ops_master_records WHERE tenant_key=$1 AND id=$2`, s.tenant, rec.ID).Scan(&before); err != nil {
t.Fatal(err)
}
// Only the replaceable local source mirror receives the live feedback update.
var revisionBefore, revisionAfter int64
if err = p.QueryRow(ctx, `SELECT revision FROM qa_ops_master_state WHERE tenant_key=$1`, s.tenant).Scan(&revisionBefore); err != nil {
t.Fatal(err)
}
if _, err = p.Exec(ctx, `UPDATE qa_ops_mirror_records SET payload=jsonb_set(payload,'{feedback}','{"asker_value":"down","up":0,"down":1}') WHERE tenant_key=$1 AND id=$2`, s.tenant, rec.ID); err != nil {
t.Fatal(err)
}
if err = p.QueryRow(ctx, `SELECT revision FROM qa_ops_master_state WHERE tenant_key=$1`, s.tenant).Scan(&revisionAfter); err != nil || revisionAfter <= revisionBefore {
t.Fatal("current master feedback changed without invalidating its snapshot revision", err)
}
fresh, err := s.GetMasterRecord(ctx, s.tenant, rec.ID)
if err != nil || fresh.Feedback.Down != 1 || fresh.MasterFields["is_correct"] != "否" {
t.Fatalf("live downvote did not force detail/master fields to incorrect: fields=%v feedback=%+v error=%v", fresh.MasterFields, fresh.Feedback, err)
}
page, err := s.ListMasterRecords(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: rec.AskedAt.Add(-time.Hour), End: rec.AskedAt.Add(time.Hour)}, Limit: 10})
if err != nil || len(page.Items) != 1 || page.Items[0].MasterFields["is_correct"] != "否" {
t.Fatal("list differs from detail", err)
}
views, err = s.ReadMasterQualityViews(ctx, keys)
if err != nil || views[rec.ID].Effective.Correctness != "incorrect" {
t.Fatal("effective quality retained the old positive inline edit", err)
}
if _, err = s.PatchMasterFields(ctx, rec.ID, MasterFieldPatch{InputHash: fresh.QualityInputHash, InputEpoch: views[rec.ID].InputEpoch, BaseRevision: 1, BaseReviewRevision: views[rec.ID].Revision, Nonce: "fixture_feedback_rule_002", Fields: map[string]string{"is_correct": "是"}}, "fixture-admin"); err == nil {
t.Fatal("an active downvote accepted a positive correctness write")
}
start, _ := time.Parse(time.RFC3339, "2026-10-05T00:00:00+08:00")
dashboard, err := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: start.AddDate(0, 0, 7)}})
if err != nil || dashboard.Quality.Rates.Correctness.Numerator != 0 || dashboard.Quality.Rates.Correctness.Denominator != 1 {
t.Fatal("dashboard did not consume the same downvote rule", err)
}
var after, originalInline string
if err = p.QueryRow(ctx, `SELECT md5(m.payload::text||m.original_fields::text||m.local_fields::text),e.fields->>'is_correct' FROM qa_ops_master_records m JOIN qa_ops_master_field_overrides e ON e.tenant_key=m.tenant_key AND e.record_id=m.id WHERE m.tenant_key=$1 AND m.id=$2`, s.tenant, rec.ID).Scan(&after, &originalInline); err != nil || after != before || originalInline != "是" {
t.Fatal("feedback projection rewrote original questions, labels or human evidence", err)
}
}
+8 -4
View File
@@ -99,8 +99,8 @@ func (s *Store) PatchMasterFields(ctx context.Context, id string, q MasterFieldP
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
var masterHash string
var fieldsRaw, coverageRaw, editsRaw []byte
err = tx.QueryRow(ctx, `SELECT quality_hash,effective_fields,coverage_result,inline_fields FROM qa_ops_master_read_model WHERE tenant_key=$1 AND id=$2`, s.tenant, id).Scan(&masterHash, &fieldsRaw, &coverageRaw, &editsRaw)
var fieldsRaw, coverageRaw, editsRaw, feedbackRaw []byte
err = tx.QueryRow(ctx, `SELECT quality_hash,effective_fields,coverage_result,inline_fields,current_feedback FROM qa_ops_master_read_model WHERE tenant_key=$1 AND id=$2`, s.tenant, id).Scan(&masterHash, &fieldsRaw, &coverageRaw, &editsRaw, &feedbackRaw)
if err != nil {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
@@ -109,14 +109,18 @@ func (s *Store) PatchMasterFields(ctx context.Context, id string, q MasterFieldP
}
var fields, edits map[string]string
var coverage dobotaiops.CoverageCheck
if json.Unmarshal(fieldsRaw, &fields) != nil || json.Unmarshal(editsRaw, &edits) != nil || json.Unmarshal(coverageRaw, &coverage) != nil {
var feedback dobotaiops.RecordFeedback
if json.Unmarshal(fieldsRaw, &fields) != nil || json.Unmarshal(editsRaw, &edits) != nil || json.Unmarshal(coverageRaw, &coverage) != nil || json.Unmarshal(feedbackRaw, &feedback) != nil {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
if value, changed := q.Fields["is_correct"]; changed && value != "否" && qaopsquality.FeedbackForcesIncorrect(feedback) {
return MasterFieldReceipt{}, qaopsquality.ErrDownvoted
}
views, err := s.MasterQualityStore().ReadViewsInTx(ctx, tx, []dobotaiops.QualityKey{{ID: id, InputHash: masterHash}})
if err != nil {
return MasterFieldReceipt{}, err
}
current := qaopsquality.ProjectMasterWithEdits(views[id], fields, coverage, edits).Effective
current := qaopsquality.ProjectMasterWithEdits(views[id], fields, coverage, edits, feedback).Effective
beforeAll := map[string]string{"coverage": map[string]string{"covered": "是", "uncovered": "否", "partial": "部分覆盖", "pending": "待确认", "excluded": "否但不计入"}[current.Coverage], "is_correct": map[string]string{"correct": "是", "incorrect": "否", "pending": "待确认"}[current.Correctness], "product_category": current.ProductCategory, "problem_type": current.ProblemType, "root_cause": current.RootCause}
correctness := beforeAll["is_correct"]
if value, ok := q.Fields["is_correct"]; ok {
+5 -4
View File
@@ -27,17 +27,18 @@ func (s *Store) ReadMasterQualityViews(ctx context.Context, keys []dobotaiops.Qu
ids = append(ids, key.ID)
hashes[key.ID] = key.InputHash
}
rows, err := tx.Query(ctx, `SELECT id,quality_hash,effective_fields,coverage_result,inline_fields FROM qa_ops_master_read_model WHERE tenant_key=$1 AND id=ANY($2::text[])`, s.tenant, ids)
rows, err := tx.Query(ctx, `SELECT id,quality_hash,effective_fields,coverage_result,inline_fields,current_feedback FROM qa_ops_master_read_model WHERE tenant_key=$1 AND id=ANY($2::text[])`, s.tenant, ids)
if err != nil {
return nil, dobotaiops.ErrUnavailable
}
count := 0
for rows.Next() {
var id, hash string
var rawFields, rawCoverage, rawEdits []byte
var rawFields, rawCoverage, rawEdits, rawFeedback []byte
var feedback dobotaiops.RecordFeedback
var fields, edits map[string]string
var coverage dobotaiops.CoverageCheck
if rows.Scan(&id, &hash, &rawFields, &rawCoverage, &rawEdits) != nil || json.Unmarshal(rawFields, &fields) != nil || json.Unmarshal(rawCoverage, &coverage) != nil || json.Unmarshal(rawEdits, &edits) != nil {
if rows.Scan(&id, &hash, &rawFields, &rawCoverage, &rawEdits, &rawFeedback) != nil || json.Unmarshal(rawFields, &fields) != nil || json.Unmarshal(rawCoverage, &coverage) != nil || json.Unmarshal(rawEdits, &edits) != nil || json.Unmarshal(rawFeedback, &feedback) != nil {
rows.Close()
return nil, dobotaiops.ErrUnavailable
}
@@ -50,7 +51,7 @@ func (s *Store) ReadMasterQualityViews(ctx context.Context, keys []dobotaiops.Qu
rows.Close()
return nil, qaopsquality.ErrUnavailable
}
views[id] = qaopsquality.ProjectMasterWithEdits(view, fields, coverage, edits)
views[id] = qaopsquality.ProjectMasterWithEdits(view, fields, coverage, edits, feedback)
count++
}
err = rows.Err()
+15 -1
View File
@@ -2,8 +2,18 @@ package qaopsquality
import "knowledge-governance/internal/dobotaiops"
func ProjectMasterWithEdits(v View, stored map[string]string, derived dobotaiops.CoverageCheck, edits map[string]string) View {
func FeedbackForcesIncorrect(feedback dobotaiops.RecordFeedback) bool {
return feedback.Down > 0 || feedback.AskerValue == "down"
}
func ProjectMasterWithEdits(v View, stored map[string]string, derived dobotaiops.CoverageCheck, edits map[string]string, feedback ...dobotaiops.RecordFeedback) View {
v = ProjectMaster(v, stored, derived)
v.FeedbackRule = ""
v.MasterFeedback = nil
if len(feedback) > 0 {
current := feedback[0]
v.MasterFeedback = &current
}
if value, ok := edits["coverage"]; ok {
v.Effective.Coverage = map[string]string{"是": "covered", "否": "uncovered", "否但不计入": "excluded"}[value]
v.Effective.ExclusionReason = ""
@@ -23,6 +33,10 @@ func ProjectMasterWithEdits(v View, stored map[string]string, derived dobotaiops
if value, ok := edits["root_cause"]; ok {
v.Effective.RootCause = value
}
if len(feedback) > 0 && FeedbackForcesIncorrect(feedback[0]) {
v.Effective.Correctness = "incorrect"
v.FeedbackRule = "downvote-is-incorrect-v1"
}
if v.Effective.Correctness == "correct" {
v.Effective.RootCause = ""
}
@@ -0,0 +1,33 @@
package qaopsquality
import (
"knowledge-governance/internal/dobotaiops"
"testing"
)
func TestMasterDownvoteRuleOverridesOnlyCorrectnessWithoutChangingReviewEvidence(t *testing.T) {
for _, test := range []struct {
name string
feedback dobotaiops.RecordFeedback
correctness string
want string
}{
{"asker-down-without-counter", dobotaiops.RecordFeedback{AskerValue: "down"}, "correct", "incorrect"},
{"someone-else-down", dobotaiops.RecordFeedback{AskerValue: "up", Up: 10, Down: 1}, "pending", "incorrect"},
{"no-vote-keeps-pending", dobotaiops.RecordFeedback{}, "pending", "pending"},
{"up-is-not-proof-of-correctness", dobotaiops.RecordFeedback{AskerValue: "up", Up: 1}, "incorrect", "incorrect"},
} {
t.Run(test.name, func(t *testing.T) {
original := Fields{Coverage: "covered", Correctness: test.correctness, ProductCategory: "MG400", ProblemType: "参数"}
review := Review{Revision: 3, Fields: original}
v := View{State: "reviewed", Revision: 3, LatestReview: &review, Effective: original}
got := ProjectMasterWithEdits(v, map[string]string{}, dobotaiops.CoverageCheck{}, map[string]string{}, test.feedback)
if got.Effective.Correctness != test.want || review.Fields != original || got.LatestReview.Fields != original || got.State != "reviewed" || got.Revision != 3 || got.Effective.Coverage != "covered" || got.Effective.ProductCategory != "MG400" {
t.Fatalf("feedback rule changed unrelated quality or evidence: %+v", got)
}
if FeedbackForcesIncorrect(test.feedback) != (got.FeedbackRule == "downvote-is-incorrect-v1") {
t.Fatal("feedback provenance missing or invented")
}
})
}
}
+11 -8
View File
@@ -10,6 +10,7 @@ import (
var ErrInvalid = errors.New("invalid quality request")
var ErrConflict = errors.New("quality input or review revision changed")
var ErrDownvoted = errors.New("active downvote forces incorrect correctness")
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")
@@ -49,14 +50,16 @@ type Check struct {
CreatedAt time.Time `json:"created_at"`
}
type View struct {
EffectiveSource string `json:"effective_source,omitempty"`
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"`
FeedbackRule string `json:"feedback_rule,omitempty"`
MasterFeedback *dobotaiops.RecordFeedback `json:"-"`
EffectiveSource string `json:"effective_source,omitempty"`
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"`
+12 -2
View File
@@ -65,16 +65,23 @@ export function QAInlineFields({
{editableFieldKeys.map((field) => {
const value = pending?.field === field ? pending.value : editableFieldValue(record, field)
const rootNotNeeded = field === 'root_cause' && editableFieldValue(record, 'is_correct') === '是'
const downvoteLocked = field === 'is_correct' && record.quality?.feedback_rule === 'downvote-is-incorrect-v1'
return (
<div key={field} data-quality-field={field}>
<label>
<span>{qaColumns.find((c) => c.key === field)!.label}</span>
<select
aria-label={`修改${qaColumns.find((c) => c.key === field)!.label}`}
title="选择后自动保存"
title={downvoteLocked ? '已点踩,是否正确固定为否' : '选择后自动保存'}
value={rootNotNeeded ? '' : value}
disabled={
saving || !!pending || !options || !record.record_origin || !record.quality || rootNotNeeded
saving ||
!!pending ||
!options ||
!record.record_origin ||
!record.quality ||
rootNotNeeded ||
downvoteLocked
}
style={qaFieldColors(field, value || '—')}
onChange={(e) => {
@@ -107,6 +114,9 @@ export function QAInlineFields({
)
})}
</div>
{record.quality?.feedback_rule === 'downvote-is-incorrect-v1' ? (
<p className="qa-inline-save">已点踩,是否正确固定为否</p>
) : null}
{saving || notice ? (
<p className="qa-inline-save" role="status" aria-live="polite">
{saving ? '保存中…' : notice}
+43
View File
@@ -0,0 +1,43 @@
import { expect, it } from 'vitest'
import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { parseQARecord, qaCellValue } from './qaOps'
import { fixtureRecord } from './qaOps.test'
import { fields, qualityFixture } from './qaQuality.fixture'
import { QAInlineFields } from './QAInlineFields'
const downvoted = {
...fixtureRecord,
record_origin: 'dobotai_2_0',
master_fields: { is_correct: '否' },
quality: {
...qualityFixture,
effective_source: 'master-effective-fields-v1',
feedback_rule: 'downvote-is-incorrect-v1',
effective: { ...fields, correctness: 'incorrect' },
},
}
it('accepts the explicit downvote rule while retaining the original positive human evidence', () => {
const row = parseQARecord(downvoted)
expect(qaCellValue(row, 'is_correct')).toBe('否')
expect(row.quality?.latest_review?.fields.correctness).toBe('correct')
})
it('does not accept a fabricated downvote rule or use it to change unrelated human fields', () => {
expect(() => parseQARecord({ ...downvoted, feedback: { asker_value: '', up: 0, down: 0 } })).toThrow()
expect(() => parseQARecord({ ...downvoted, record_origin: undefined })).toThrow()
expect(() => parseQARecord({ ...downvoted, quality: { ...downvoted.quality, feedback_rule: 'unknown' } })).toThrow()
expect(() =>
parseQARecord({
...downvoted,
quality: { ...downvoted.quality, effective: { ...fields, correctness: 'incorrect', coverage: 'uncovered' } },
})
).toThrow()
})
it('explains the fixed negative correctness without restoring the removed review form', () => {
const row = parseQARecord(downvoted)
const html = renderToStaticMarkup(
createElement(QAInlineFields, { record: row, onSaved: () => {}, onReload: () => {} })
)
expect(html).toContain('已点踩,是否正确固定为否')
expect(html).not.toContain('人工复核反馈')
})
+5 -1
View File
@@ -185,7 +185,11 @@ export function parseQARecord(value: unknown): QARecord {
...(row.quality === undefined
? {}
: {
quality: parseQAQuality(row.quality, ['dobotai_2_0', 'historical_excel'].includes(String(row.record_origin))),
quality: parseQAQuality(
row.quality,
['dobotai_2_0', 'historical_excel'].includes(String(row.record_origin)),
askerValue === 'down' || count(feedback.down) > 0
),
}),
id: text(row.id),
status: text(row.status),
+11 -2
View File
@@ -26,6 +26,7 @@ export interface QualityReview {
}
export interface QAQuality {
effective_source?: 'master-effective-fields-v1'
feedback_rule?: 'downvote-is-incorrect-v1'
input_hash: string
input_epoch: number
revision: number
@@ -192,7 +193,7 @@ function review(value: unknown): QualityReview {
created_at: stamp(v.created_at),
}
}
export function parseQAQuality(value: unknown, allowMasterProjection = false): QAQuality {
export function parseQAQuality(value: unknown, allowMasterProjection = false, hasDownvote = false): QAQuality {
const v = obj(value),
state = text(v.state)
if (!['unreviewed', 'reviewed', 'stale'].includes(state)) return bad()
@@ -219,11 +220,18 @@ export function parseQAQuality(value: unknown, allowMasterProjection = false): Q
state === 'reviewed' ? latest_review!.fields : { ...emptyQualityFields, coverage: automatic.result.verdict || '' }
const master = v.effective_source === 'master-effective-fields-v1'
if (v.effective_source !== undefined && (!master || !allowMasterProjection)) return bad()
const downvoteRule = v.feedback_rule === 'downvote-is-incorrect-v1'
if (
v.feedback_rule !== undefined &&
(!downvoteRule || !master || !allowMasterProjection || !hasDownvote || effective.correctness !== 'incorrect')
)
return bad()
for (const key of Object.keys(expected) as (keyof QualityFields)[]) {
// The versioned master layer may fill missing fields, but never change an explicit human decision.
// Only the explicit feedback rule may override correctness; the human evidence stays intact.
if (master) {
if (
state === 'reviewed' &&
!(downvoteRule && key === 'correctness') &&
(expected[key] !== '' || (key === 'root_cause' && expected.correctness === 'correct')) &&
expected[key] !== effective[key]
)
@@ -239,6 +247,7 @@ export function parseQAQuality(value: unknown, allowMasterProjection = false): Q
latest_review,
effective,
...(master ? { effective_source: 'master-effective-fields-v1' as const } : {}),
...(downvoteRule ? { feedback_rule: 'downvote-is-incorrect-v1' as const } : {}),
}
}
function qualityRate(value: unknown): QualityRate {