mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-26 14:04:46 +00:00
结论句裁判改造:「不支持」拆成「证据相矛盾」和「证据不足」,补全交给裁判的证据,旧判定可按新规则重判
- 判定取值改为:支持 / 部分支持 / 证据相矛盾 / 证据不足 / 不是结论。只有证据和句子冲突才判相矛盾; 证据里没有相关信息判证据不足,并写明缺什么(比如 SQL、字段清单) - 出具判档不变松:证据相矛盾按 on_unsupported 降档或不予出具;证据不足记一条缺口,最多降档、不能判完整出具; 改造前的「证据不支持」照旧当相矛盾处理 - 补全证据摘录:表名附字段清单和类型(最多 60 个,快照不全时注明,遮罩列不列);口径卡指标附上每个输入 取自哪次查询、哪一格,以及那次查询的 SQL;一律只读封存范围内的工件 - 理由上限从 60 字放宽到 120 字,在句子边界截断,不再截在半句中间 - 裁判模型:按需裁判也判断是否和写作模型相同、是否在价格表里,证据面板里醒目提示; 设置页没配裁判模型时写明「未单独配置,将使用助手的模型」 - 新判定带规则版本:改造前的判定在界面上标「按旧规则判定」,可以请模型按当前规则重新判断 - 界面:证据相矛盾用红色;证据不足用中性色和 ○,写明缺什么;讲方法、讲结构的句子在证据面板里直接列出 对应的 SQL 和字段清单;出具横幅、审计表、报告节点印章的计数都分开这两档 - 顺带写稳 check-publish 里一条等按钮状态的断言(并行时偶发)
This commit is contained in:
@@ -152,24 +152,25 @@ async def test_every_claim_supported_is_a_full_issuance(monkeypatch):
|
||||
assert issuance["tier"] == "formal" and issuance["gaps"] == [], issuance
|
||||
claims = issuance["claims"]
|
||||
assert claims["policy"] == "judge" and claims["mode"] == "inline" and claims["complete"] is True
|
||||
assert claims["counts"] == {"supported": 2, "partial": 0, "unsupported": 0, "not_a_claim": 0, "unjudged": 0}
|
||||
assert claims["counts"] == {"supported": 2, "partial": 0, "contradicted": 0, "insufficient": 0, "not_a_claim": 0,
|
||||
"unjudged": 0, "unsupported": 0}
|
||||
assert claims["on_unsupported"] == "degrade" and claims["uncited_claims"] == 0
|
||||
assert claims["unsupported"] == [] and claims["model"] == JUDGE_MODEL
|
||||
assert claims["contradicted"] == [] and claims["insufficient"] == [] and claims["model"] == JUDGE_MODEL
|
||||
|
||||
|
||||
async def test_an_unsupported_claim_degrades_by_default(monkeypatch):
|
||||
Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
async def test_a_contradicted_claim_degrades_by_default(monkeypatch):
|
||||
Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
issuance = await issued(weekly())
|
||||
assert issuance["tier"] == "degraded", "不支持按缺口降档,不是不予出具(契约是 strict 的)"
|
||||
assert issuance["gaps"] == [], "判了就不是「没核」:档位来自判定,不来自缺口"
|
||||
[flagged] = issuance["claims"]["unsupported"]
|
||||
[flagged] = issuance["claims"]["contradicted"]
|
||||
assert flagged["text"] == "增长主要来自新客首单。" and flagged["rationale"] == "证据里没有新客维度"
|
||||
assert flagged["unit"] and len(flagged["span"]) == 2
|
||||
assert issuance["claims"]["counts"]["unsupported"] == 1
|
||||
assert issuance["claims"]["counts"]["contradicted"] == 1
|
||||
|
||||
|
||||
async def test_withhold_withholds(monkeypatch):
|
||||
Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
issuance = await issued(weekly(report={"judge": {"max_cost_usd": 0.05, "on_unsupported": "withhold"}}))
|
||||
assert issuance["tier"] == "withheld" and issuance["claims"]["on_unsupported"] == "withhold"
|
||||
|
||||
@@ -209,23 +210,24 @@ async def test_an_uncited_claim_still_counts_under_judge(monkeypatch):
|
||||
|
||||
|
||||
async def test_the_issuance_event_carries_the_counts(monkeypatch):
|
||||
Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
run = await run_manager.start(graph=weekly(), input_payload={}, run_class="formal")
|
||||
row = await wait(run.id)
|
||||
event = await issuance_event(row.id)
|
||||
assert event["tier"] == "degraded"
|
||||
assert event["claims"] == {"policy": "judge", "uncited_claims": 0, "on_unsupported": "degrade",
|
||||
"mode": "inline", "counts": {"supported": 1, "partial": 0, "unsupported": 1,
|
||||
"mode": "inline", "counts": {"supported": 1, "partial": 0, "contradicted": 1,
|
||||
"insufficient": 0, "unsupported": 0,
|
||||
"not_a_claim": 0, "unjudged": 0}}
|
||||
|
||||
|
||||
async def test_a_governed_formal_run_grades_by_the_verdicts(client, monkeypatch):
|
||||
Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
graph = weekly(report={"numbers": "strict", "on_violation": "fail",
|
||||
"judge": {"max_cost_usd": None, "on_unsupported": "withhold"}})
|
||||
row = await governed(client, graph)
|
||||
issuance = row.output["_issuance"]
|
||||
assert issuance["tier"] == "withheld" and issuance["claims"]["unsupported"][0]["text"] == "增长主要来自新客首单。"
|
||||
assert issuance["tier"] == "withheld" and issuance["claims"]["contradicted"][0]["text"] == "增长主要来自新客首单。"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
@@ -234,7 +236,7 @@ async def test_a_governed_formal_run_grades_by_the_verdicts(client, monkeypatch)
|
||||
|
||||
|
||||
async def test_explore_runs_only_annotate(monkeypatch):
|
||||
models = Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
models = Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
issuance = await issued(weekly(report={"judge": {"max_cost_usd": 0.05, "on_unsupported": "withhold"}}),
|
||||
run_class="exploratory")
|
||||
assert models.judges == [], "探索运行节点里不花这笔钱"
|
||||
@@ -242,7 +244,7 @@ async def test_explore_runs_only_annotate(monkeypatch):
|
||||
claims = issuance["claims"]
|
||||
assert claims["mode"] == "on_demand" and claims["complete"] is False
|
||||
assert claims["counts"]["unjudged"] == 2 and claims["unjudged"] == {"on_demand": 2}
|
||||
assert claims["unsupported"] == []
|
||||
assert claims["contradicted"] == [] and claims["insufficient"] == []
|
||||
|
||||
|
||||
async def test_explore_runs_still_count_uncited_claims(monkeypatch):
|
||||
@@ -257,14 +259,14 @@ async def test_explore_runs_still_count_uncited_claims(monkeypatch):
|
||||
|
||||
|
||||
async def test_the_contract_can_tighten_on_unsupported(monkeypatch):
|
||||
Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
issuance = await issued(weekly(contract={"claims": {"policy": "judge", "on_unsupported": "withhold"}}))
|
||||
assert issuance["tier"] == "withheld" and issuance["claims"]["on_unsupported"] == "withhold"
|
||||
assert not any("不支持" in g and "这一版" in g for g in issuance["gaps"])
|
||||
|
||||
|
||||
async def test_the_contract_cannot_loosen_on_unsupported(monkeypatch):
|
||||
Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
issuance = await issued(weekly(report={"judge": {"max_cost_usd": 0.05, "on_unsupported": "withhold"}},
|
||||
contract={"claims": {"policy": "judge", "on_unsupported": "degrade"}}))
|
||||
assert issuance["tier"] == "withheld"
|
||||
@@ -295,7 +297,7 @@ async def test_runs_from_before_the_upgrade_ignore_judge(monkeypatch):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(runner_mod, "_agent_limits", no_snapshot)
|
||||
models = Models(monkeypatch, text=UNCITED, verdicts={"新客": "unsupported"})
|
||||
models = Models(monkeypatch, text=UNCITED, verdicts={"新客": "contradicted"})
|
||||
issuance = await issued(weekly())
|
||||
assert models.judges == [] and issuance["tier"] == "formal" and "claims" not in issuance
|
||||
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
数字、实体是确定性的,系统自己能核对;「增长主要来自华东」这种话说得对不对,只能交给另一个模型按
|
||||
证据判断。这是概率性的判断,所以每一步都要留余地、说实话:
|
||||
|
||||
- 一份报告合并成一次调用(超过每批的句数就分批),每句给 supported / partial / unsupported / not_a_claim
|
||||
- 一份报告合并成一次调用(超过每批的句数就分批),每句给 supported / partial / contradicted / insufficient /
|
||||
not_a_claim
|
||||
- 模型不支持结构化输出、或者给的不是合法结构时退回 JSON 解析,再失败就记「未裁判」,不编判定
|
||||
- 裁判模型关掉 thinking,max_tokens 4096
|
||||
- 预算(每份报告的句数、金额、时长,全局每日金额)每一项都能写 null 表示不限;触顶就停、已判的保留、
|
||||
@@ -183,7 +184,7 @@ def status_of(outcome, doc, text):
|
||||
|
||||
|
||||
async def test_one_call_for_the_whole_report_and_the_verdict_shape(monkeypatch, stored):
|
||||
judge = Judge(monkeypatch, {"u3": "unsupported"})
|
||||
judge = Judge(monkeypatch, {"u3": "contradicted"})
|
||||
catalog = make_catalog(stored)
|
||||
doc = compose_doc(RAW, catalog)
|
||||
outcome = await judge_doc(doc, catalog, spec=SPEC, budget=UNLIMITED)
|
||||
@@ -192,7 +193,8 @@ async def test_one_call_for_the_whole_report_and_the_verdict_shape(monkeypatch,
|
||||
v = status_of(outcome, doc, CITED)
|
||||
assert v["status"] == "supported" and v["judge"] == PRICED and v["post_seal"] is False
|
||||
assert v["rationale"] and v["used"] == ["m:gmv"]
|
||||
assert outcome["counts"] == {"supported": 3, "partial": 0, "unsupported": 1, "not_a_claim": 0, "unjudged": 0}
|
||||
assert outcome["counts"] == {"supported": 3, "partial": 0, "contradicted": 1, "insufficient": 0, "not_a_claim": 0,
|
||||
"unjudged": 0, "unsupported": 0}
|
||||
assert outcome["model"] == PRICED and outcome["calls"] == 1 and outcome["gaps"] == []
|
||||
assert units_of(doc)["下面看细节。"] not in outcome["verdicts"], "连接性的话不送裁判"
|
||||
|
||||
@@ -226,7 +228,7 @@ async def test_structured_output_failure_falls_back_to_json(monkeypatch, stored)
|
||||
async def test_an_array_written_as_json_text_is_still_read(monkeypatch, stored):
|
||||
"""有的模型走工具调用时把嵌套的数组写成一段 JSON 文本({"items": "[…]"}):照样认,不为它再花一次调用。"""
|
||||
def stringified(units):
|
||||
items = [{"unit": u, "verdict": "unsupported", "rationale": "对不上", "used": []} for u in units]
|
||||
items = [{"unit": u, "verdict": "contradicted", "rationale": "对不上", "used": []} for u in units]
|
||||
return json.dumps({"items": json.dumps(items, ensure_ascii=False)}, ensure_ascii=False)
|
||||
|
||||
judge = Judge(monkeypatch, structured=stringified)
|
||||
@@ -234,7 +236,7 @@ async def test_an_array_written_as_json_text_is_still_read(monkeypatch, stored):
|
||||
doc = compose_doc(RAW, catalog)
|
||||
outcome = await judge_doc(doc, catalog, spec=SPEC, budget=UNLIMITED)
|
||||
assert [c["kind"] for c in judge.calls] == ["structured"]
|
||||
assert {v["status"] for v in outcome["verdicts"].values()} == {"unsupported"}
|
||||
assert {v["status"] for v in outcome["verdicts"].values()} == {"contradicted"}
|
||||
|
||||
|
||||
async def test_a_broken_provider_is_not_called_batch_after_batch(monkeypatch, stored):
|
||||
@@ -266,18 +268,18 @@ async def test_bad_items_are_not_trusted(monkeypatch, stored):
|
||||
|
||||
def messy(units):
|
||||
return json.dumps({"items": [
|
||||
{"unit": ids[CITED], "verdict": "supported", "rationale": "长" * 100, "used": ["m:gmv", "m:nope", "Q9"]},
|
||||
{"unit": ids[CITED], "verdict": "supported", "rationale": "长" * 200, "used": ["m:gmv", "m:nope", "Q9"]},
|
||||
{"unit": ids[CITED2], "verdict": "maybe", "rationale": "不认识的判定", "used": []},
|
||||
{"unit": ids[CAUSAL], "verdict": "unsupported", "rationale": "没有新客维度", "used": []},
|
||||
{"unit": ids[CAUSAL], "verdict": "contradicted", "rationale": "没有新客维度", "used": []},
|
||||
{"unit": "u999", "verdict": "supported", "rationale": "不存在的句子", "used": []},
|
||||
]}, ensure_ascii=False)
|
||||
|
||||
Judge(monkeypatch, structured=messy)
|
||||
outcome = await judge_doc(doc, catalog, spec=SPEC, budget=UNLIMITED)
|
||||
v = outcome["verdicts"]
|
||||
assert v[ids[CITED]]["rationale"] == "长" * RATIONALE_MAX and v[ids[CITED]]["used"] == ["m:gmv"]
|
||||
assert v[ids[CITED]]["rationale"] == "长" * (RATIONALE_MAX - 1) + "…" and v[ids[CITED]]["used"] == ["m:gmv"]
|
||||
assert (v[ids[CITED2]]["status"], v[ids[CITED2]]["reason"]) == ("unjudged", "format")
|
||||
assert v[ids[CAUSAL]]["status"] == "unsupported"
|
||||
assert v[ids[CAUSAL]]["status"] == "contradicted"
|
||||
assert (v[ids[NUMBER]]["status"], v[ids[NUMBER]]["reason"]) == ("unjudged", "missing")
|
||||
assert "u999" not in v
|
||||
|
||||
@@ -532,7 +534,7 @@ async def test_a_model_without_a_price_ignores_money_limits(monkeypatch, stored)
|
||||
|
||||
|
||||
async def test_known_sentences_are_not_judged_again(monkeypatch, stored):
|
||||
judge = Judge(monkeypatch, {"u2": "unsupported"})
|
||||
judge = Judge(monkeypatch, {"u2": "contradicted"})
|
||||
catalog = make_catalog(stored)
|
||||
doc = compose_doc(RAW, catalog)
|
||||
first = await judge_doc(doc, catalog, spec=SPEC, budget=UNLIMITED)
|
||||
|
||||
@@ -175,7 +175,7 @@ async def save_setting(key: str, value) -> None:
|
||||
|
||||
|
||||
async def test_an_on_demand_verdict_lands_after_the_seal_and_the_seal_still_holds(client, monkeypatch):
|
||||
models = Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
models = Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
row = await finish(weekly(claims="judge"))
|
||||
assert row.status == "succeeded" and models.judges == [], "探索运行节点里不判"
|
||||
doc = doc_of(row)
|
||||
@@ -185,7 +185,7 @@ async def test_an_on_demand_verdict_lands_after_the_seal_and_the_seal_still_hold
|
||||
assert res.status_code == 200, res.text
|
||||
body = res.json()
|
||||
verdict = body["verdicts"][ids[CAUSAL]]
|
||||
assert verdict["status"] == "unsupported" and verdict["post_seal"] is True and verdict["judge"] == PRICED
|
||||
assert verdict["status"] == "contradicted" and verdict["post_seal"] is True and verdict["judge"] == PRICED
|
||||
assert verdict["rationale"] and body["judged"] == [ids[CAUSAL]] and body["reused"] == []
|
||||
assert body["report"] == {"node_id": "write", "doc_artifact": row.output["_evidence"]["doc_artifact"]}
|
||||
assert body["post_seal"] is True and body["limited"] is False and body["calls"] == 1
|
||||
@@ -276,9 +276,9 @@ async def test_a_failed_attempt_can_be_retried(client, monkeypatch):
|
||||
failed = (await judge(client, row.id, [uid])).json()
|
||||
assert failed["verdicts"][uid]["status"] == "unjudged" and failed["verdicts"][uid]["reason"] == "error"
|
||||
assert "网关 502" in failed["message"] and failed["limited"] is False
|
||||
models = Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
models = Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
retried = (await judge(client, row.id, [uid])).json()
|
||||
assert retried["verdicts"][uid]["status"] == "unsupported" and retried["reused"] == [] and len(models.judges) == 1
|
||||
assert retried["verdicts"][uid]["status"] == "contradicted" and retried["reused"] == [] and len(models.judges) == 1
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
@@ -414,7 +414,7 @@ async def test_a_broken_seal_is_not_judged(client, monkeypatch):
|
||||
async def test_a_run_continued_during_the_judge_call_records_no_event(client, monkeypatch, meanwhile):
|
||||
"""判定只接在点击开始时的那份封存后面。运行在裁判期间被接着跑了,再追加就落进一次活着的运行中间,
|
||||
还会被封进下一份清单:不记进运行记录,判定照样交回给点的人,并说明为什么没记。"""
|
||||
models = Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
models = Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
row = await finish(weekly(claims="judge"))
|
||||
uid = unit_ids(doc_of(row))[CAUSAL]
|
||||
ask_model = judge_mod.get_chat_model
|
||||
@@ -430,7 +430,7 @@ async def test_a_run_continued_during_the_judge_call_records_no_event(client, mo
|
||||
assert res.status_code == 200, res.text
|
||||
body = res.json()
|
||||
assert len(models.judges) == 1 and body["calls"] == 1, "模型问过了"
|
||||
assert body["verdicts"][uid]["status"] == "unsupported" and body["judged"] == [uid], "判定照样交回"
|
||||
assert body["verdicts"][uid]["status"] == "contradicted" and body["judged"] == [uid], "判定照样交回"
|
||||
assert body["event"] is None and "运行已继续执行" in body["message"] and "未写入运行记录" in body["message"]
|
||||
assert await judged_events(row.id) == []
|
||||
async with SessionLocal() as session:
|
||||
@@ -444,7 +444,7 @@ async def test_a_continue_that_wins_the_row_between_check_and_write_gets_no_even
|
||||
from app.core.bus import bus
|
||||
from app.core.config import settings
|
||||
|
||||
Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
row = await finish(weekly(claims="judge"))
|
||||
uid = unit_ids(doc_of(row))[CAUSAL]
|
||||
set_seq = bus.set_seq
|
||||
@@ -462,7 +462,7 @@ async def test_a_continue_that_wins_the_row_between_check_and_write_gets_no_even
|
||||
|
||||
monkeypatch.setattr(bus, "set_seq", claimed_in_between)
|
||||
body = (await judge(client, row.id, [uid])).json()
|
||||
assert body["verdicts"][uid]["status"] == "unsupported" and body["event"] is None
|
||||
assert body["verdicts"][uid]["status"] == "contradicted" and body["event"] is None
|
||||
assert "未写入运行记录" in body["message"] and await judged_events(row.id) == []
|
||||
async with SessionLocal() as session:
|
||||
after = await session.get(Run, row.id)
|
||||
@@ -503,7 +503,7 @@ async def test_sentences_that_are_not_claims_are_skipped(client, monkeypatch):
|
||||
|
||||
|
||||
async def test_the_segment_shows_the_verdict_and_whether_it_can_still_be_asked(client, monkeypatch):
|
||||
Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
row = await finish(weekly(claims="judge"))
|
||||
doc = doc_of(row)
|
||||
ids = unit_ids(doc)
|
||||
@@ -513,7 +513,7 @@ async def test_the_segment_shows_the_verdict_and_whether_it_can_still_be_asked(c
|
||||
|
||||
await judge(client, row.id, [ids[CAUSAL]])
|
||||
after = (await client.get(f"/api/runs/{row.id}/evidence/segments/{seg_in(doc, ids[CAUSAL])}")).json()
|
||||
assert after["unit"]["verdict"]["status"] == "unsupported" and after["unit"]["verdict"]["post_seal"] is True
|
||||
assert after["unit"]["verdict"]["status"] == "contradicted" and after["unit"]["verdict"]["post_seal"] is True
|
||||
assert after["unit"]["on_demand"]["available"] is False and after["unit"]["on_demand"]["reason"] == "judged"
|
||||
assert "模型" in after["note"] and "后续版本" not in after["note"]
|
||||
other = (await client.get(f"/api/runs/{row.id}/evidence/segments/{seg_in(doc, ids[CITED])}")).json()
|
||||
@@ -531,11 +531,11 @@ async def test_the_segment_shows_the_verdict_and_whether_it_can_still_be_asked(c
|
||||
|
||||
|
||||
async def test_sealed_verdicts_of_a_formal_run_are_shown_as_sealed(client, monkeypatch):
|
||||
Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
row = await finish(weekly(claims="judge", judge={"max_cost_usd": 0.05}), run_class="formal")
|
||||
doc = doc_of(row)
|
||||
body = (await client.get(f"/api/runs/{row.id}/evidence/segments/{seg_in(doc, unit_ids(doc)[CAUSAL])}")).json()
|
||||
assert body["unit"]["verdict"]["status"] == "unsupported" and body["unit"]["verdict"]["post_seal"] is False
|
||||
assert body["unit"]["verdict"]["status"] == "contradicted" and body["unit"]["verdict"]["post_seal"] is False
|
||||
assert body["unit"]["on_demand"]["reason"] == "formal"
|
||||
graph = (await client.get(f"/api/runs/{row.id}/evidence")).json()
|
||||
assert graph["reports"][0]["post_seal_verdicts"] == {} and graph["reports"][0]["judge"]["mode"] == "inline"
|
||||
@@ -543,7 +543,7 @@ async def test_sealed_verdicts_of_a_formal_run_are_shown_as_sealed(client, monke
|
||||
|
||||
async def test_a_forged_event_cannot_overwrite_a_sealed_verdict(client, monkeypatch):
|
||||
"""封存后追加的判定只填补没判过的句子:封存内判过的,后面追加什么都盖不掉。"""
|
||||
Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
row = await finish(weekly(claims="judge", judge={"max_cost_usd": 0.05}), run_class="formal")
|
||||
doc = doc_of(row)
|
||||
uid = unit_ids(doc)[CAUSAL]
|
||||
@@ -552,7 +552,7 @@ async def test_a_forged_event_cannot_overwrite_a_sealed_verdict(client, monkeypa
|
||||
doc_artifact=doc_artifact, post_seal=True,
|
||||
verdicts={uid: {"status": "supported", "rationale": "改好了", "judge": "x", "post_seal": True}})
|
||||
body = (await client.get(f"/api/runs/{row.id}/evidence/segments/{seg_in(doc, uid)}")).json()
|
||||
assert body["unit"]["verdict"]["status"] == "unsupported"
|
||||
assert body["unit"]["verdict"]["status"] == "contradicted"
|
||||
|
||||
|
||||
async def test_appended_verdicts_always_read_as_post_seal(client, monkeypatch):
|
||||
|
||||
@@ -249,7 +249,7 @@ WITHHOLD = {**JUDGED, "judge": {"max_cost_usd": 0.05, "on_unsupported": "withhol
|
||||
])
|
||||
def test_relaxing_on_unsupported_on_the_node_is_loosening(judge, dropped):
|
||||
[reason] = _changed(WITHHOLD, {**WITHHOLD, "judge": judge})
|
||||
assert "「报告撰写」" in reason and "「结论句裁判 · 证据不支持时」" in reason
|
||||
assert "「报告撰写」" in reason and "「结论句裁判 · 证据相矛盾时」" in reason
|
||||
assert "「不予出具」" in reason and "「出具降档」" in reason
|
||||
assert ("删除了已设置的值" in reason) is dropped, reason
|
||||
|
||||
@@ -258,7 +258,7 @@ def test_replacing_the_whole_judge_block_to_add_a_budget_is_loosening():
|
||||
"""补预算把 judge 整个换成 {max_cost_usd}:连同裁判模型、withhold 一起丢了。"""
|
||||
before = {**STRICT, "claims": "judge", "judge": {"model": "judge-model", "on_unsupported": "withhold"}}
|
||||
[reason] = _changed(before, {**before, "judge": {"max_cost_usd": 0.05}})
|
||||
assert "「结论句裁判 · 证据不支持时」" in reason and "「不予出具」" in reason
|
||||
assert "「结论句裁判 · 证据相矛盾时」" in reason and "「不予出具」" in reason
|
||||
assert _changed(before, {**before, "judge": {**before["judge"], "max_cost_usd": 0.05}}) == [], \
|
||||
"带着原来的键补预算不算放宽"
|
||||
|
||||
@@ -268,7 +268,7 @@ def test_a_withhold_from_the_graph_defaults_lost_by_a_node_judge_is_loosening():
|
||||
defaults = {"judge": {"on_unsupported": "withhold", "max_cost_usd": 0.05}}
|
||||
report = {**STRICT, "claims": "judge"}
|
||||
[reason] = _changed(report, {**report, "judge": {"max_cost_usd": 0.05}}, defaults=defaults)
|
||||
assert "「结论句裁判 · 证据不支持时」" in reason and "从「不予出具」(跟随工作流默认设置)" in reason, reason
|
||||
assert "「结论句裁判 · 证据相矛盾时」" in reason and "从「不予出具」(跟随工作流默认设置)" in reason, reason
|
||||
assert "不再跟随工作流默认设置" in reason, "说清楚为什么全图默认里的 withhold 不生效了"
|
||||
assert _changed(report, {**report, "judge": {"max_cost_usd": 0.05, "on_unsupported": "withhold"}},
|
||||
defaults=defaults) == []
|
||||
@@ -280,7 +280,7 @@ def test_relaxing_on_unsupported_in_the_graph_defaults_is_loosening():
|
||||
new = copy.deepcopy(old)
|
||||
new["defaults"]["judge"]["on_unsupported"] = "degrade"
|
||||
[reason] = forbidden_changes(old, new)
|
||||
assert "「报告撰写」" in reason and "「结论句裁判 · 证据不支持时」" in reason
|
||||
assert "「报告撰写」" in reason and "「结论句裁判 · 证据相矛盾时」" in reason
|
||||
|
||||
|
||||
@pytest.mark.parametrize("before, after", [
|
||||
@@ -297,7 +297,7 @@ def test_tightening_or_keeping_on_unsupported_is_fine(before, after):
|
||||
def test_dropping_withhold_along_with_judge_is_one_reason():
|
||||
"""从 judge 退回 require_citation:claims 那一条已经说了,不再为 on_unsupported 另记一条。"""
|
||||
[reason] = _changed(WITHHOLD, {**STRICT, "judge": {"max_cost_usd": 0.05}})
|
||||
assert "「未附依据的结论句」" in reason and "证据不支持时" not in reason
|
||||
assert "「未附依据的结论句」" in reason and "证据相矛盾时" not in reason
|
||||
|
||||
|
||||
@pytest.mark.parametrize("before", ["require_citation", "judge"])
|
||||
|
||||
@@ -0,0 +1,486 @@
|
||||
"""结论句裁判改造(JR)的接口:片段接口的字段清单、按需裁判的模型标记、证据图的 judge_meta、审计行。
|
||||
|
||||
- 片段接口里表名实体那一步带上字段清单 fields: [{name, type}](封存范围内的表结构快照,最多 60 个,
|
||||
多出来的记 fields_more),遮罩的列不列
|
||||
- 按需裁判也判断裁判模型和写作模型是否相同(写作模型取这份报告撰写节点实际用的模型),并带上
|
||||
priced、writer_model;evidence.judged 事件同样记下
|
||||
- GET /evidence 每份报告带 judge_meta:最近一次按需裁判的 {model, same_model, priced, writer_model}
|
||||
- 交给裁判的新摘录(字段清单、指标输入的 SQL)只经封存范围内的 loader 读
|
||||
- 审计行的 issue 新增 contradicted_claim、insufficient_claim
|
||||
- 旧的 unsupported 判定照旧算「判过」:封存之后追加的判定盖不掉它
|
||||
|
||||
所有裁判都用 mock 模型给剧本,不调真接口。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from langchain_core.messages import AIMessage
|
||||
from sqlalchemy import delete, select
|
||||
|
||||
from app.core import artifact_store
|
||||
from app.core.events import EventType
|
||||
from app.data.engine import engines
|
||||
from app.db.base import SessionLocal
|
||||
from app.db.models import DataSource, Run, RunEvent, Setting
|
||||
from app.engine import judge as judge_mod
|
||||
from app.engine.evidence import iter_segments, iter_units
|
||||
from app.engine.judge import JUDGE_ROLE, SPEND_KEY
|
||||
from app.engine.runner import run_manager
|
||||
from app.main import app
|
||||
from app.providers.mock_model import MockChatModel
|
||||
|
||||
PRICED = "claude-sonnet-5"
|
||||
WRITER = "mock-fast"
|
||||
SOURCE = "jr_shop"
|
||||
TOOL = f"db_query__{SOURCE}"
|
||||
SQL = "SELECT region, SUM(amount) AS gmv FROM orders GROUP BY region ORDER BY gmv DESC"
|
||||
WIDE_COLS = [f"f{i:02d}" for i in range(65)]
|
||||
METRIC = "东区销售额最高,达 [[m:gmv]]。[[see:m:gmv]]"
|
||||
METHOD = "这个数由 [[t:orders]] 按 [[c:orders.region]] 分组求和得出。"
|
||||
WIDE = "明细在 [[t:wide_orders]] 里。"
|
||||
TEXT = METRIC + METHOD + WIDE
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def engine_up():
|
||||
await run_manager.setup()
|
||||
async with SessionLocal() as session:
|
||||
await session.execute(delete(Setting).where(Setting.key.in_([SPEND_KEY, "judge", "copilot"])))
|
||||
await session.commit()
|
||||
yield
|
||||
await run_manager.shutdown()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def client():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
|
||||
yield c
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def shop(tmp_path):
|
||||
"""探查过结构的示例库:orders(带手机号列,数据源设了遮罩)和一张 65 列的宽表。"""
|
||||
from app.data.introspect import introspect
|
||||
|
||||
path = tmp_path / "jr_shop.db"
|
||||
db = sqlite3.connect(path)
|
||||
db.executescript(
|
||||
"CREATE TABLE orders (id INTEGER PRIMARY KEY, region TEXT, amount REAL, phone TEXT);"
|
||||
f"CREATE TABLE wide_orders ({', '.join(f'{c} TEXT' for c in WIDE_COLS)});")
|
||||
db.executemany("INSERT INTO orders VALUES (?, ?, ?, ?)",
|
||||
[(1, "east", 300.5, "p1"), (2, "west", 200.0, "p2"), (3, "east", 100.0, "p3")])
|
||||
db.commit()
|
||||
db.close()
|
||||
probe = SimpleNamespace(id=f"probe-{path.name}", name=SOURCE, kind="sqlite", database=str(path), host=None,
|
||||
port=None, username=None, password=None, options={}, readonly=True, schema_cache={})
|
||||
cache = await introspect(probe)
|
||||
await engines.invalidate(probe.id)
|
||||
async with SessionLocal() as session:
|
||||
row = (await session.execute(select(DataSource).where(DataSource.name == SOURCE))).scalar_one_or_none()
|
||||
if row is None:
|
||||
row = DataSource(name=SOURCE, kind="sqlite", database=str(path), readonly=True, enabled=True)
|
||||
session.add(row)
|
||||
row.database, row.kind, row.enabled, row.readonly, row.schema_cache = str(path), "sqlite", True, True, cache
|
||||
row.options = {"mask_columns": "phone"}
|
||||
await session.commit()
|
||||
source_id = row.id
|
||||
await engines.invalidate(source_id)
|
||||
yield source_id
|
||||
await engines.invalidate(source_id)
|
||||
|
||||
|
||||
def node(nid, ntype, **config):
|
||||
return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": nid, "config": config}}
|
||||
|
||||
|
||||
def weekly(**report) -> dict:
|
||||
nodes = [
|
||||
node("start", "input"),
|
||||
node("fetch", "tool", tool=TOOL, args={"sql": SQL}),
|
||||
node("card", "metrics", caliber="周报口径", caliber_version="v2", metrics=[
|
||||
{"id": "gmv", "name": "销售额", "unit": "元", "decimals": 1, "expression": "cell(nodes.fetch, 0, 'gmv')"}]),
|
||||
node("write", "report", instructions="写周报", on_violation="flag", claims="judge", **report),
|
||||
node("out", "output", fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}]),
|
||||
]
|
||||
ids = [n["id"] for n in nodes]
|
||||
return {"nodes": nodes, "edges": [{"source": a, "target": b} for a, b in zip(ids, ids[1:])]}
|
||||
|
||||
|
||||
class Models:
|
||||
"""写作者回 text;裁判按句子里的字给判定:verdicts = {句中片段: (判定, missing)}。judges 记下请求原文。"""
|
||||
|
||||
def __init__(self, monkeypatch, verdicts=None, *, model=PRICED, text=TEXT):
|
||||
self.judges: list[str] = []
|
||||
verdicts = verdicts or {}
|
||||
|
||||
def decide(chat, messages):
|
||||
if JUDGE_ROLE in str(messages[0].content):
|
||||
request = str(messages[-1].content)
|
||||
self.judges.append(request)
|
||||
items = []
|
||||
for uid, line in re.findall(r"^\[(u\d+)\]([^\n]*)$", request, re.M):
|
||||
status, missing = next((v for frag, v in verdicts.items() if frag in line), ("supported", ""))
|
||||
items.append({"unit": uid, "verdict": status, "rationale": f"判的是:{line.strip()[:12]}",
|
||||
"missing": missing, "used": []})
|
||||
return AIMessage(content=json.dumps({"items": items}, ensure_ascii=False))
|
||||
return AIMessage(content=text)
|
||||
|
||||
monkeypatch.setattr(MockChatModel, "_decide", decide)
|
||||
self.model = model
|
||||
|
||||
async def judge_model_of(session, spec):
|
||||
return MockChatModel(model_name=self.model), self.model
|
||||
|
||||
monkeypatch.setattr(judge_mod, "get_chat_model", judge_model_of)
|
||||
|
||||
|
||||
async def wait(run_id: str) -> Run:
|
||||
for _ in range(400):
|
||||
await asyncio.sleep(0.05)
|
||||
async with SessionLocal() as session:
|
||||
row = await session.get(Run, run_id)
|
||||
if row.status in ("succeeded", "failed") and row.manifest_seq is not None:
|
||||
return row
|
||||
raise AssertionError(f"run {run_id} 没跑完:{row.status}")
|
||||
|
||||
|
||||
async def explore_run(graph=None) -> tuple[Run, dict]:
|
||||
started = await run_manager.start(graph=graph or weekly(), input_payload={}, run_class="exploratory")
|
||||
row = await wait(started.id)
|
||||
assert row.status == "succeeded", row.error
|
||||
return row, artifact_store.load(row.output["_evidence"]["doc_artifact"])
|
||||
|
||||
|
||||
def unit_of(doc: dict, prefix: str) -> str:
|
||||
md = doc["markdown"]
|
||||
return next(u["id"] for _, u in iter_units(doc) if md[u["span"][0]:u["span"][1]].strip().startswith(prefix))
|
||||
|
||||
|
||||
async def judged_events(run_id: str) -> list[RunEvent]:
|
||||
async with SessionLocal() as session:
|
||||
return list((await session.execute(select(RunEvent).where(
|
||||
RunEvent.run_id == run_id, RunEvent.type == EventType.EVIDENCE_JUDGED).order_by(RunEvent.seq))).scalars())
|
||||
|
||||
|
||||
async def ask(client, run_id: str, units: list[str]) -> dict:
|
||||
res = await client.post(f"/api/runs/{run_id}/evidence/judge", json={"units": units})
|
||||
assert res.status_code == 200, res.text
|
||||
return res.json()
|
||||
|
||||
|
||||
async def reseal(run_id: str) -> None:
|
||||
async with SessionLocal() as session:
|
||||
run = await session.get(Run, run_id)
|
||||
rows = [tuple(r) for r in await session.execute(
|
||||
select(RunEvent.seq, RunEvent.type, RunEvent.node_id, RunEvent.data)
|
||||
.where(RunEvent.run_id == run_id, RunEvent.seq <= run.manifest_seq).order_by(RunEvent.seq))]
|
||||
run.manifest_hash = artifact_store.manifest_hash(rows)
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def rewrite(run_id: str, etype: str, node_id: str, change) -> None:
|
||||
async with SessionLocal() as session:
|
||||
for row in (await session.execute(select(RunEvent).where(
|
||||
RunEvent.run_id == run_id, RunEvent.type == etype, RunEvent.node_id == node_id))).scalars():
|
||||
row.data = change(dict(row.data))
|
||||
await session.commit()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 片段接口:表名实体步骤的字段清单
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def open_entity(client, run_id: str, doc: dict, ref: str) -> dict:
|
||||
seg = next(s for s in iter_segments(doc) if s.get("kind") == "entity" and s.get("ref") == ref)
|
||||
res = await client.get(f"/api/runs/{run_id}/evidence/segments/{seg['id']}")
|
||||
assert res.status_code == 200, res.text
|
||||
[step] = res.json()["chain"]
|
||||
return step
|
||||
|
||||
|
||||
async def test_a_table_step_lists_its_fields_without_masked_columns(client, monkeypatch):
|
||||
Models(monkeypatch)
|
||||
row, doc = await explore_run()
|
||||
step = await open_entity(client, row.id, doc, "t:orders")
|
||||
assert step["step"] == "entity" and step["kind"] == "table"
|
||||
assert step["fields"] == [{"name": "id", "type": "INTEGER"}, {"name": "region", "type": "TEXT"},
|
||||
{"name": "amount", "type": "REAL"}], "遮罩的 phone 不列"
|
||||
assert "fields_more" not in step and step["columns"] == 4
|
||||
|
||||
|
||||
async def test_a_wide_table_step_stops_at_sixty_fields(client, monkeypatch):
|
||||
Models(monkeypatch)
|
||||
row, doc = await explore_run()
|
||||
step = await open_entity(client, row.id, doc, "t:wide_orders")
|
||||
assert [f["name"] for f in step["fields"]] == WIDE_COLS[:60]
|
||||
assert step["fields_more"] == 5
|
||||
|
||||
|
||||
async def test_a_table_step_outside_the_seal_has_no_fields(client, monkeypatch):
|
||||
Models(monkeypatch)
|
||||
row, doc = await explore_run()
|
||||
await rewrite(row.id, "tool.end", "fetch", lambda d: {k: v for k, v in d.items() if k != "schema_artifact"})
|
||||
await rewrite(row.id, "node.finished", "fetch",
|
||||
lambda d: {**d, "evidence": [e for e in d.get("evidence") or [] if e.get("kind") != "schema"]})
|
||||
await reseal(row.id)
|
||||
step = await open_entity(client, row.id, doc, "t:orders")
|
||||
assert "fields" not in step and "fields_more" not in step
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 按需裁判:新的判定、摘录、模型标记
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_on_demand_judging_sees_fields_and_metric_sql_and_reports_the_models(client, monkeypatch):
|
||||
models = Models(monkeypatch, verdicts={"分组求和": ("insufficient", "字段清单"), "东区销售额": ("contradicted", "")})
|
||||
row, doc = await explore_run()
|
||||
method, metric = unit_of(doc, "这个数由"), unit_of(doc, "东区销售额")
|
||||
|
||||
graph = (await client.get(f"/api/runs/{row.id}/evidence")).json()
|
||||
assert graph["reports"][0]["judge_meta"] is None, "还没按需裁判过"
|
||||
|
||||
body = await ask(client, row.id, [method, metric])
|
||||
request = models.judges[0]
|
||||
assert "region TEXT" in request and "id INTEGER" in request, "表附上字段清单和类型"
|
||||
assert "phone" not in request.lower(), "遮罩的列不出现"
|
||||
assert "查询 Q1 的 SQL" in request and "SUM(amount)" in request and "r0" in request, "指标附上输入的查询和格子"
|
||||
|
||||
assert body["verdicts"][method]["status"] == "insufficient" and body["verdicts"][method]["missing"] == "字段清单"
|
||||
assert body["verdicts"][metric]["status"] == "contradicted"
|
||||
assert body["same_model"] is False and body["priced"] is True and body["writer_model"] == WRITER
|
||||
|
||||
[event] = await judged_events(row.id)
|
||||
assert event.data["same_model"] is False and event.data["priced"] is True
|
||||
assert event.data["writer_model"] == WRITER
|
||||
|
||||
graph = (await client.get(f"/api/runs/{row.id}/evidence")).json()
|
||||
assert graph["reports"][0]["judge_meta"] == {"model": PRICED, "same_model": False, "priced": True,
|
||||
"writer_model": WRITER}
|
||||
|
||||
|
||||
async def test_judging_with_the_writer_model_is_flagged(client, monkeypatch):
|
||||
models = Models(monkeypatch, model=WRITER)
|
||||
row, doc = await explore_run()
|
||||
body = await ask(client, row.id, [unit_of(doc, "这个数由")])
|
||||
assert models.judges and body["model"] == WRITER
|
||||
assert body["same_model"] is True and body["writer_model"] == WRITER, "判定照常出,另带标记"
|
||||
assert body["verdicts"][unit_of(doc, "这个数由")]["status"] == "supported"
|
||||
[event] = await judged_events(row.id)
|
||||
assert event.data["same_model"] is True and event.data["writer_model"] == WRITER
|
||||
|
||||
# judge_meta 取最近一次:换一个价格目录里没有的模型再判一句,就按新的这次
|
||||
models.model = "house-judge-model"
|
||||
body = await ask(client, row.id, [unit_of(doc, "东区销售额")])
|
||||
assert body["same_model"] is False and body["priced"] is False, "目录里没有价格的模型:金额上限对它不生效"
|
||||
meta = (await client.get(f"/api/runs/{row.id}/evidence")).json()["reports"][0]["judge_meta"]
|
||||
assert meta == {"model": "house-judge-model", "same_model": False, "priced": False, "writer_model": WRITER}
|
||||
|
||||
|
||||
async def test_the_new_excerpts_only_read_sealed_artifacts(client, monkeypatch):
|
||||
"""表结构快照、查询快照被挪出封存范围(事件里追不到了):字段清单、指标输入的 SQL 都不进裁判的摘录。"""
|
||||
models = Models(monkeypatch)
|
||||
row, doc = await explore_run()
|
||||
await rewrite(row.id, "tool.end", "fetch",
|
||||
lambda d: {k: v for k, v in d.items() if k not in ("schema_artifact", "query_artifact")})
|
||||
await rewrite(row.id, "node.finished", "fetch",
|
||||
lambda d: {**d, "evidence": [e for e in d.get("evidence") or []
|
||||
if e.get("kind") not in ("schema", "query")]})
|
||||
await reseal(row.id)
|
||||
await ask(client, row.id, [unit_of(doc, "这个数由"), unit_of(doc, "东区销售额")])
|
||||
request = models.judges[0]
|
||||
assert "INTEGER" not in request and "region TEXT" not in request
|
||||
assert "SELECT" not in request
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 审计行
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_audit_rows_list_contradicted_and_insufficient_claims(client, monkeypatch):
|
||||
Models(monkeypatch, verdicts={"分组求和": ("insufficient", "字段清单"), "东区销售额": ("contradicted", "")})
|
||||
row, doc = await explore_run()
|
||||
method, metric = unit_of(doc, "这个数由"), unit_of(doc, "东区销售额")
|
||||
await ask(client, row.id, [method, metric])
|
||||
|
||||
body = (await client.get(f"/api/runs/{row.id}/evidence/audit")).json()
|
||||
rows = [r for g in body["groups"] for r in g["rows"] if r["kind"] == "claim"]
|
||||
by_issue = {r["issue"]: r for r in rows}
|
||||
assert by_issue["contradicted_claim"]["unit"] == metric and by_issue["contradicted_claim"]["group"] == "none"
|
||||
assert by_issue["insufficient_claim"]["unit"] == method
|
||||
assert "字段清单" in by_issue["insufficient_claim"]["note"]
|
||||
assert by_issue["insufficient_claim"]["verdict"]["missing"] == "字段清单"
|
||||
assert by_issue["contradicted_claim"]["verdict"]["post_seal"] is True
|
||||
|
||||
text = (await client.get(f"/api/runs/{row.id}/evidence/audit?format=csv")).text
|
||||
issues = {line[8] for line in csv.reader(io.StringIO(text.lstrip("")))}
|
||||
assert {"证据相矛盾", "证据不足"} <= issues
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 旧的 unsupported:照旧算判过
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_an_old_unsupported_verdict_still_counts_as_judged():
|
||||
from app.api.evidence import _effective_verdicts, _on_demand, _Report, _Sealed
|
||||
from app.engine.evidence import compose_doc
|
||||
|
||||
doc = compose_doc("增长主要来自新客首单。", {}, node_id="write", run_id="r1")
|
||||
[unit] = [u for _, u in iter_units(doc)]
|
||||
unit["verdict"] = {"status": "unsupported", "rationale": "证据不支持", "judge": PRICED, "post_seal": False,
|
||||
"used": []}
|
||||
report = _Report(node_id="write", doc_artifact="d" * 64, ok=True, repairs=0, stats={}, doc=doc, hash_ok=True,
|
||||
fields=[], claims="judge")
|
||||
later = {"report": "write", "doc_artifact": "d" * 64,
|
||||
"verdicts": {unit["id"]: {"status": "supported", "rationale": "有依据", "judge": PRICED}}}
|
||||
sealed = _Sealed(run_id="r1", graph={}, seal={"sealed": True, "ok": True, "manifest_seq": 5, "legacy": False},
|
||||
events=[], judged=[(9, "write", later)], run_class="exploratory", status="succeeded",
|
||||
ledger_on=True)
|
||||
effective, appended = _effective_verdicts(report, sealed)
|
||||
assert effective[unit["id"]]["status"] == "unsupported" and appended == {}, "追加的判定盖不掉封存的判定"
|
||||
assert _on_demand(sealed, doc, unit["id"], effective[unit["id"]])["reason"] == "judged"
|
||||
|
||||
|
||||
def test_the_writer_model_of_an_old_report_comes_from_the_sealed_node_output():
|
||||
"""改造前的文档裁判摘要里没有 writer_model、改造前的事件里没有 same_model:按报告撰写节点封存的产出里
|
||||
实际用的模型补上。"""
|
||||
from app.api.evidence import _judge_meta, _Report, _Sealed, _writer_model
|
||||
from app.engine.evidence import compose_doc
|
||||
|
||||
text = artifact_store.canonical_json({"text": "增长主要来自新客首单。", "model": "writer-old"})
|
||||
output = artifact_store.content_hash(text)
|
||||
path = artifact_store._path_of(output)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
|
||||
doc = compose_doc("增长主要来自新客首单。", {}, node_id="write", run_id="r2")
|
||||
doc["judge"] = {"mode": "on_demand", "model": None, "counts": {}}
|
||||
report = _Report(node_id="write", doc_artifact="e" * 64, ok=True, repairs=0, stats={}, doc=doc, hash_ok=True,
|
||||
fields=[], claims="judge")
|
||||
old_event = {"report": "write", "doc_artifact": "e" * 64, "model": "writer-old", "priced": False,
|
||||
"verdicts": {}}
|
||||
sealed = _Sealed(run_id="r2", graph={}, seal={"sealed": True, "ok": True, "manifest_seq": 5, "legacy": False},
|
||||
events=[(3, "node.finished", "write", {"artifact": output})], outputs={"write": output},
|
||||
judged=[(9, "write", old_event)], run_class="exploratory", status="succeeded", ledger_on=True)
|
||||
assert _writer_model(sealed, report) == "writer-old"
|
||||
assert _judge_meta(report, sealed) == {"model": "writer-old", "same_model": True, "priced": False,
|
||||
"writer_model": "writer-old"}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 按需裁判:早于当前规则的判定可以重判,当前规则下判过的照旧复用
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def on_demand_of(verdict: dict) -> dict:
|
||||
from app.api.evidence import _on_demand, _Sealed
|
||||
from app.engine.evidence import compose_doc
|
||||
|
||||
doc = compose_doc("增长主要来自新客首单。", {}, node_id="write", run_id="r3")
|
||||
[unit] = [u for _, u in iter_units(doc)]
|
||||
sealed = _Sealed(run_id="r3", graph={}, seal={"sealed": True, "ok": True, "manifest_seq": 5, "legacy": False},
|
||||
events=[], run_class="exploratory", status="succeeded", ledger_on=True)
|
||||
return _on_demand(sealed, doc, unit["id"], verdict)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("verdict", [
|
||||
{"status": "supported", "rationale": "有依据", "post_seal": True},
|
||||
{"status": "unsupported", "rationale": "证据不支持", "post_seal": True},
|
||||
{"status": "insufficient", "rationale": "缺 SQL", "post_seal": True, "rule_version": 1},
|
||||
])
|
||||
def test_an_outdated_appended_verdict_can_be_asked_again(verdict):
|
||||
got = on_demand_of(verdict)
|
||||
assert got["available"] is True and got["reason"] == "outdated" and got["message"]
|
||||
|
||||
|
||||
def test_a_current_verdict_is_not_asked_again():
|
||||
got = on_demand_of({"status": "contradicted", "rationale": "对不上", "post_seal": True,
|
||||
"rule_version": judge_mod.RULES_VERSION})
|
||||
assert got["available"] is False and got["reason"] == "judged"
|
||||
|
||||
|
||||
def test_a_sealed_verdict_is_never_reopened_by_version():
|
||||
"""封存的判定(文档里的,post_seal 为 False)盖不掉:版本再旧也不开放重判。"""
|
||||
got = on_demand_of({"status": "unsupported", "rationale": "证据不支持", "post_seal": False})
|
||||
assert got["available"] is False and got["reason"] == "judged"
|
||||
|
||||
|
||||
async def age(run_id: str, uid: str, **changes) -> None:
|
||||
"""把封存之后追加的那条判定改成改造前的样子(封存之后的事件不在封存核对范围里)。"""
|
||||
async with SessionLocal() as session:
|
||||
for row in (await session.execute(select(RunEvent).where(
|
||||
RunEvent.run_id == run_id, RunEvent.type == EventType.EVIDENCE_JUDGED))).scalars():
|
||||
data = json.loads(json.dumps(row.data))
|
||||
if uid in data.get("verdicts", {}):
|
||||
verdict = {k: v for k, v in data["verdicts"][uid].items() if k != "rule_version"}
|
||||
data["verdicts"][uid] = {**verdict, **changes}
|
||||
row.data = data
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def segment_of(client, run_id: str, doc: dict, uid: str) -> dict:
|
||||
seg = next(s["id"] for _, u in iter_units(doc) if u["id"] == uid for s in u["segments"])
|
||||
res = await client.get(f"/api/runs/{run_id}/evidence/segments/{seg}")
|
||||
assert res.status_code == 200, res.text
|
||||
return res.json()["unit"]
|
||||
|
||||
|
||||
async def test_an_outdated_verdict_is_really_judged_again(client, monkeypatch):
|
||||
models = Models(monkeypatch, verdicts={"东区销售额": ("contradicted", "")})
|
||||
row, doc = await explore_run()
|
||||
uid = unit_of(doc, "东区销售额")
|
||||
first = await ask(client, row.id, [uid])
|
||||
assert first["judged"] == [uid] and len(models.judges) == 1
|
||||
assert first["verdicts"][uid]["rule_version"] == judge_mod.RULES_VERSION
|
||||
|
||||
# 当前规则下判过的:照旧复用,不再调用
|
||||
again = await ask(client, row.id, [uid])
|
||||
assert again["reused"] == [uid] and again["judged"] == [] and len(models.judges) == 1
|
||||
assert (await segment_of(client, row.id, doc, uid))["on_demand"]["reason"] == "judged"
|
||||
|
||||
# 改造前判的(旧取值、没有规则版本):按钮照常出现,POST 真的重判一次,新判定追加在封存之后
|
||||
await age(row.id, uid, status="unsupported")
|
||||
unit = await segment_of(client, row.id, doc, uid)
|
||||
assert unit["verdict"]["status"] == "unsupported"
|
||||
assert unit["on_demand"]["available"] is True and unit["on_demand"]["reason"] == "outdated"
|
||||
redo = await ask(client, row.id, [uid])
|
||||
assert len(models.judges) == 2 and redo["judged"] == [uid] and redo["reused"] == []
|
||||
assert redo["verdicts"][uid]["status"] == "contradicted" and redo["event"] is not None
|
||||
assert len(await judged_events(row.id)) == 2
|
||||
graph = (await client.get(f"/api/runs/{row.id}/evidence")).json()
|
||||
latest = graph["reports"][0]["post_seal_verdicts"][uid]
|
||||
assert latest["status"] == "contradicted" and latest["rule_version"] == judge_mod.RULES_VERSION
|
||||
assert (await segment_of(client, row.id, doc, uid))["on_demand"]["reason"] == "judged"
|
||||
|
||||
|
||||
async def test_a_failed_rejudge_keeps_the_older_verdict_in_force(client, monkeypatch):
|
||||
"""重判没判成(模型不可用):旧判定照旧生效,答复和证据图说的一样;按钮还在,可以再点。"""
|
||||
models = Models(monkeypatch)
|
||||
row, doc = await explore_run()
|
||||
uid = unit_of(doc, "东区销售额")
|
||||
await ask(client, row.id, [uid])
|
||||
await age(row.id, uid)
|
||||
|
||||
async def broken(session, spec):
|
||||
raise RuntimeError("网关 502")
|
||||
|
||||
monkeypatch.setattr(judge_mod, "get_chat_model", broken)
|
||||
body = await ask(client, row.id, [uid])
|
||||
assert body["judged"] == [] and "网关 502" in body["message"]
|
||||
assert body["verdicts"][uid]["status"] == "supported" and "rule_version" not in body["verdicts"][uid]
|
||||
graph = (await client.get(f"/api/runs/{row.id}/evidence")).json()
|
||||
assert graph["reports"][0]["post_seal_verdicts"][uid] == body["verdicts"][uid]
|
||||
assert (await segment_of(client, row.id, doc, uid))["on_demand"]["reason"] == "outdated"
|
||||
assert len(models.judges) == 1
|
||||
@@ -0,0 +1,455 @@
|
||||
"""结论句裁判改造(JR)的内核:判定拆档、补全证据摘录、理由不硬截断。
|
||||
|
||||
- 判定拆成 contradicted(证据相矛盾)和 insufficient(证据不足):只有证据和句子冲突才判 contradicted,
|
||||
证据里没有相关信息判 insufficient,并写明缺的是什么(missing)。新判的不再产出 unsupported:
|
||||
模型照旧写 unsupported 的,按更严的 contradicted 收下
|
||||
- 讲方法、讲结构的句子只挂了表名、字段名,裁判以前只拿到名字:表附上字段清单和类型(最多 60 个,
|
||||
快照不完整要注明),字段附上类型和所属的表,口径卡指标附上输入取自哪次查询、哪一格和那次查询的 SQL。
|
||||
一律只经封存范围内的 loader 读工件,遮罩的列不出现
|
||||
- 理由上限 120 个字,超长时在句子边界截断加「…」;裁判规则要求 80 个字以内
|
||||
|
||||
所有模型调用都是 mock 剧本,不碰真接口。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from langchain_core.messages import AIMessage
|
||||
from sqlalchemy import delete
|
||||
|
||||
from app.db.base import SessionLocal
|
||||
from app.db.models import DataSource, Setting
|
||||
from app.engine import judge as judge_mod
|
||||
from app.engine.evidence import build_catalog, compose_doc, iter_units
|
||||
from app.engine.judge import (
|
||||
JUDGE_ROLE,
|
||||
JUDGE_SCHEMA,
|
||||
JUDGED,
|
||||
SPEND_KEY,
|
||||
SQL_CHARS,
|
||||
Budget,
|
||||
judge_doc,
|
||||
prepare,
|
||||
source_masks,
|
||||
summarize,
|
||||
)
|
||||
from app.providers.factory import ModelSpec
|
||||
from app.providers.mock_model import MockChatModel
|
||||
|
||||
PRICED = "claude-sonnet-5"
|
||||
UNLIMITED = Budget(max_claims=None, max_cost_usd=None, timeout_s=None, daily_max_usd=None)
|
||||
SPEC = ModelSpec(model=PRICED)
|
||||
|
||||
SOURCE = "warehouse"
|
||||
SCHEMA_ART, Q1_ART, Q2_ART, CARD_ART = "5" * 64, "a" * 64, "b" * 64, "c" * 64
|
||||
SQL1 = "SELECT COUNT(DISTINCT member_no) AS active_users FROM orders WHERE created_at >= '2026-09-01'"
|
||||
SQL2 = "SELECT region, SUM(amount) AS gmv FROM orders GROUP BY region"
|
||||
ORDER_COLS = [("id", "INTEGER"), ("member_no", "TEXT"), ("region", "TEXT"), ("amount", "REAL"),
|
||||
("phone", "TEXT"), ("created_at", "TEXT")]
|
||||
|
||||
|
||||
def schema_snapshot(columns=ORDER_COLS, *, truncated=False) -> dict:
|
||||
return {"source": SOURCE, "synced_at": "2026-09-01T00:00:00+00:00", "schema": None,
|
||||
"tables": {"orders": {"columns": [{"name": n, "type": t, "nullable": True} for n, t in columns],
|
||||
"primary_key": ["id"], "comment": None, "is_view": False},
|
||||
"refunds": {"columns": [{"name": "id", "type": "INTEGER"}, {"name": "amount", "type": "REAL"}],
|
||||
"primary_key": ["id"], "is_view": False}},
|
||||
**({"truncated": True, "total": 500} if truncated else {})}
|
||||
|
||||
|
||||
def query_entry(art: str, columns: list[str], tables: list[str]) -> dict:
|
||||
return {"kind": "query", "node_id": "fetch", "exec": 1, "artifact": art, "tool": f"db_query__{SOURCE}",
|
||||
"source": SOURCE, "columns": columns, "rows": 1, "truncated": False, "schema_artifact": SCHEMA_ART,
|
||||
"tables": tables}
|
||||
|
||||
|
||||
def schema_entry(snapshot: dict) -> dict:
|
||||
tables = {name: [c["name"] for c in meta["columns"]] for name, meta in snapshot["tables"].items()}
|
||||
return {"kind": "schema", "node_id": "fetch", "exec": 1, "artifact": SCHEMA_ART, "source": SOURCE,
|
||||
"tables": tables, **({"truncated": True, "total": 500} if snapshot.get("truncated") else {})}
|
||||
|
||||
|
||||
def snaps(snapshot=None, **extra) -> dict:
|
||||
out = {SCHEMA_ART: snapshot or schema_snapshot(),
|
||||
Q1_ART: {"columns": ["active_users"], "rows": [[321]], "sql": SQL1, "source": SOURCE},
|
||||
Q2_ART: {"columns": ["region", "gmv"], "rows": [["华东", 100.0]], "sql": SQL2, "source": SOURCE}}
|
||||
out.update(extra)
|
||||
return out
|
||||
|
||||
|
||||
def entity_catalog(snapshot=None) -> dict:
|
||||
snapshot = snapshot or schema_snapshot()
|
||||
return build_catalog(nodes={}, ledger=[query_entry(Q1_ART, ["active_users"], ["orders"]),
|
||||
query_entry(Q2_ART, ["region", "gmv"], ["orders"]), schema_entry(snapshot)])
|
||||
|
||||
|
||||
def excerpts(text: str, *, snapshot=None, loader=None, masked=None) -> dict[str, str]:
|
||||
cat = entity_catalog(snapshot)
|
||||
doc = compose_doc(text, cat)
|
||||
store = snaps(snapshot)
|
||||
return prepare(doc, cat, loader=loader or store.get, masked=masked).excerpts
|
||||
|
||||
|
||||
def field_line(excerpt: str) -> str:
|
||||
[line] = [x for x in excerpt.splitlines() if x.startswith("字段清单")]
|
||||
return line
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 判定拆档:取值、规则、schema
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_schema_offers_contradicted_and_insufficient_instead_of_unsupported():
|
||||
item = JUDGE_SCHEMA["properties"]["items"]["items"]
|
||||
assert item["properties"]["verdict"]["enum"] == list(JUDGED) == [
|
||||
"supported", "partial", "contradicted", "insufficient", "not_a_claim"]
|
||||
assert "unsupported" not in JUDGED
|
||||
assert "missing" in item["properties"] and "missing" in item["required"]
|
||||
assert "80" in item["properties"]["rationale"]["description"]
|
||||
|
||||
|
||||
def test_the_rules_separate_conflict_from_missing_information():
|
||||
rules = judge_mod.JUDGE_RULES
|
||||
assert "unsupported" not in rules, "新判的一律用新取值"
|
||||
assert "contradicted" in rules and "insufficient" in rules and "missing" in rules
|
||||
# 只有冲突才判 contradicted;没有相关信息判 insufficient,并写明缺什么
|
||||
[conflict] = [line for line in rules.splitlines() if line.startswith("- contradicted")]
|
||||
assert "冲突" in conflict
|
||||
[lacking] = [line for line in rules.splitlines() if line.startswith("- insufficient")]
|
||||
assert "没有" in lacking
|
||||
assert "80 个字" in rules and "60 个字" not in rules
|
||||
assert "表结构快照不完整" in rules, "快照不完整时「某字段不存在」只能判 insufficient"
|
||||
assert "数字已经由系统核对过,不要复算" in rules, "旧规则保留"
|
||||
|
||||
|
||||
def test_count_keys_keep_unsupported_for_old_data():
|
||||
assert set(judge_mod.COUNT_KEYS) == {"supported", "partial", "contradicted", "insufficient", "unsupported", "not_a_claim",
|
||||
"unjudged"}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 判定拆档:调用与收下
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
RAW = ("活跃用户数由 [[t:orders]] 按 [[c:orders.member_no]] 去重计数得出。"
|
||||
"各区销售额按 [[c:orders.region]] 汇总。[[see:Q2]]"
|
||||
"华东的销售额是全国最高的,领先第二名一倍。[[see:Q2]]"
|
||||
"订单表里没有退款字段。[[see:t:orders]]")
|
||||
|
||||
|
||||
class Judge:
|
||||
"""裁判剧本:items(units, request) 给出每句的条目;calls 记下每次交给裁判的请求原文。"""
|
||||
|
||||
def __init__(self, monkeypatch, items, *, model_id=PRICED):
|
||||
self.calls: list[str] = []
|
||||
|
||||
def decide(model, messages):
|
||||
assert JUDGE_ROLE in str(messages[0].content)
|
||||
request = str(messages[-1].content)
|
||||
self.calls.append("\n".join(str(m.content) for m in messages))
|
||||
units = re.findall(r"^\[(u\d+)\]", request, re.M)
|
||||
return AIMessage(content=json.dumps({"items": items(units)}, ensure_ascii=False))
|
||||
|
||||
monkeypatch.setattr(MockChatModel, "_decide", decide)
|
||||
|
||||
async def fake_model(session, spec):
|
||||
return MockChatModel(model_name=model_id), model_id
|
||||
|
||||
monkeypatch.setattr(judge_mod, "get_chat_model", fake_model)
|
||||
|
||||
|
||||
def ids_of(doc) -> dict[str, str]:
|
||||
md = doc["markdown"]
|
||||
return {md[u["span"][0]:u["span"][1]].strip(): u["id"] for _, u in iter_units(doc)}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def clean_settings():
|
||||
async with SessionLocal() as session:
|
||||
await session.execute(delete(Setting).where(Setting.key.in_([SPEND_KEY, "judge", "copilot"])))
|
||||
await session.commit()
|
||||
yield
|
||||
|
||||
|
||||
async def test_contradicted_and_insufficient_come_back_with_missing(monkeypatch):
|
||||
cat = entity_catalog()
|
||||
doc = compose_doc(RAW, cat)
|
||||
ids = ids_of(doc)
|
||||
method, grouped, ranked, absent = (ids[t] for t in list(ids)[:4])
|
||||
script = {
|
||||
method: {"verdict": "supported", "rationale": "Q1 的 SQL 写的是 COUNT(DISTINCT member_no)", "missing": ""},
|
||||
grouped: {"verdict": "insufficient", "rationale": "摘录里没有这次汇总的 SQL", "missing": "SQL"},
|
||||
ranked: {"verdict": "contradicted", "rationale": "Q2 里华东不是最高", "missing": "应当被丢掉"},
|
||||
absent: {"verdict": "insufficient", "rationale": "", "missing": ""},
|
||||
}
|
||||
Judge(monkeypatch, lambda units: [{"unit": u, "used": [], **script[u]} for u in units])
|
||||
outcome = await judge_doc(doc, cat, spec=SPEC, budget=UNLIMITED, loader=snaps().get)
|
||||
v = outcome["verdicts"]
|
||||
assert v[grouped]["status"] == "insufficient" and v[grouped]["missing"] == "SQL"
|
||||
assert v[ranked]["status"] == "contradicted" and "missing" not in v[ranked], "只有 insufficient 带 missing"
|
||||
assert v[absent]["status"] == "insufficient" and "missing" not in v[absent], "没写缺什么就不编"
|
||||
assert v[method]["status"] == "supported" and "missing" not in v[method]
|
||||
assert set(v[grouped]) == {"status", "rationale", "judge", "post_seal", "used", "missing", "rule_version"}
|
||||
assert outcome["counts"] == {"supported": 1, "partial": 0, "contradicted": 1, "insufficient": 2,
|
||||
"not_a_claim": 0, "unjudged": 0, "unsupported": 0}
|
||||
|
||||
|
||||
async def test_a_model_still_saying_unsupported_is_taken_as_contradicted(monkeypatch):
|
||||
"""新判的不再产出 unsupported:模型照旧写 unsupported 的按更严的 contradicted 收下,不当格式错误放过。"""
|
||||
cat = entity_catalog()
|
||||
doc = compose_doc(RAW, cat)
|
||||
Judge(monkeypatch, lambda units: [{"unit": u, "verdict": "unsupported", "rationale": "对不上", "used": []}
|
||||
for u in units])
|
||||
outcome = await judge_doc(doc, cat, spec=SPEC, budget=UNLIMITED, loader=snaps().get)
|
||||
assert {x["status"] for x in outcome["verdicts"].values()} == {"contradicted"}
|
||||
assert outcome["counts"]["unsupported"] == 0 and outcome["counts"]["contradicted"] == 4
|
||||
|
||||
|
||||
def test_summary_counts_always_carry_every_key():
|
||||
"""缓存里的旧判定只有旧的五个键:摘要照样补齐 contradicted、insufficient。"""
|
||||
outcome = {"counts": {"supported": 1, "partial": 0, "unsupported": 1, "not_a_claim": 0, "unjudged": 0},
|
||||
"candidates": 2, "screened": [], "unjudged": {}, "limits_hit": [], "gaps": []}
|
||||
summary = summarize(outcome, mode="inline", writer_model="writer-x")
|
||||
assert summary["counts"] == {"supported": 1, "partial": 0, "contradicted": 0, "insufficient": 0,
|
||||
"not_a_claim": 0, "unjudged": 0, "unsupported": 1}
|
||||
assert summary["writer_model"] == "writer-x"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 理由不硬截断
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_rationale_under_the_cap_is_kept_whole():
|
||||
text = "摘录里" + "有对应的指标和查询" * 10 + "。" # 94 个字:旧规则会截在 60 字的半句中间
|
||||
assert 60 < len(text) <= judge_mod.RATIONALE_MAX == 120
|
||||
assert judge_mod.clip_text(text) == text
|
||||
|
||||
|
||||
def test_a_long_rationale_is_cut_at_a_sentence_boundary():
|
||||
first = "Q2 的 SQL 按 region 汇总,华东 100 元排第一"
|
||||
text = first + ";" + "第二名的数字摘录里没有给出," * 12
|
||||
got = judge_mod.clip_text(text)
|
||||
assert len(got) <= judge_mod.RATIONALE_MAX and got.endswith("…")
|
||||
body = got[:-1]
|
||||
assert text.startswith(body) and text[len(body)] in "。;,", f"截在句子边界:{got}"
|
||||
|
||||
|
||||
def test_a_long_run_without_punctuation_is_not_cut_inside_a_word():
|
||||
text = " ".join(["evidence"] * 30)
|
||||
got = judge_mod.clip_text(text)
|
||||
assert len(got) <= judge_mod.RATIONALE_MAX and got.endswith("…")
|
||||
assert got[:-1].rstrip().split(" ")[-1] == "evidence", got
|
||||
|
||||
|
||||
async def test_the_judge_keeps_a_long_rationale_up_to_the_cap(monkeypatch):
|
||||
cat = entity_catalog()
|
||||
doc = compose_doc("各区销售额按 [[c:orders.region]] 汇总。[[see:Q2]]", cat)
|
||||
long = "Q2 的 SQL 是按 region 分组求和," * 3 + "句子说的汇总方式和 SQL 一致," * 8
|
||||
Judge(monkeypatch, lambda units: [{"unit": u, "verdict": "supported", "rationale": long, "used": []}
|
||||
for u in units])
|
||||
outcome = await judge_doc(doc, cat, spec=SPEC, budget=UNLIMITED, loader=snaps().get)
|
||||
[v] = outcome["verdicts"].values()
|
||||
assert 60 < len(v["rationale"]) <= judge_mod.RATIONALE_MAX and v["rationale"].endswith("…")
|
||||
assert long.startswith(v["rationale"][:-1])
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 补全证据摘录:表
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_table_excerpt_lists_its_fields_and_types():
|
||||
ex = excerpts("活跃用户数由 [[t:orders]] 去重计数得出。")
|
||||
table = ex["t:orders"]
|
||||
line = field_line(table)
|
||||
for name, kind in ORDER_COLS:
|
||||
assert f"{name} {kind}" in line, line
|
||||
assert "COUNT(DISTINCT member_no)" in table, "出现过的查询 SQL 保留"
|
||||
assert "表结构快照不完整" not in table
|
||||
|
||||
|
||||
def test_the_field_list_stops_at_sixty():
|
||||
columns = [(f"col_{i:02d}", "TEXT") for i in range(75)]
|
||||
ex = excerpts("活跃用户数由 [[t:orders]] 去重计数得出。", snapshot=schema_snapshot(columns))
|
||||
line = field_line(ex["t:orders"])
|
||||
listed = re.findall(r"col_\d\d", line)
|
||||
assert judge_mod.FIELDS_MAX == 60 and listed == [f"col_{i:02d}" for i in range(60)]
|
||||
assert "另有 15 个" in line
|
||||
|
||||
|
||||
def test_masked_fields_are_never_listed():
|
||||
ex = excerpts("活跃用户数由 [[t:orders]] 去重计数得出。", masked={SOURCE: ["Phone"]})
|
||||
table = ex["t:orders"]
|
||||
assert "phone" not in field_line(table).lower() and "member_no TEXT" in field_line(table)
|
||||
assert "遮罩" in table, "说明有字段按遮罩没列出:裁判不能据此说表里没有这个字段"
|
||||
|
||||
|
||||
def test_masks_recorded_in_a_query_snapshot_also_hide_fields():
|
||||
"""数据源改名、删掉了,现在查不到遮罩:查询当时记下的遮罩照样生效(证据面板同一个口径)。"""
|
||||
cat = entity_catalog()
|
||||
doc = compose_doc("活跃用户数由 [[t:orders]] 去重计数得出。", cat)
|
||||
store = snaps(**{Q1_ART: {"columns": ["active_users"], "rows": [[321]], "sql": SQL1, "source": SOURCE,
|
||||
"mask_columns": ["phone"]}})
|
||||
table = prepare(doc, cat, loader=store.get).excerpts["t:orders"]
|
||||
assert "phone" not in field_line(table).lower()
|
||||
|
||||
|
||||
def test_a_truncated_snapshot_is_called_out():
|
||||
ex = excerpts("活跃用户数由 [[t:orders]] 去重计数得出。", snapshot=schema_snapshot(truncated=True))
|
||||
table = ex["t:orders"]
|
||||
assert "表结构快照不完整" in table and "id INTEGER" in field_line(table)
|
||||
|
||||
|
||||
def test_only_the_sealed_loader_feeds_the_field_list():
|
||||
"""schema 快照不在封存范围里(loader 取不到):一个字段都不给,照实说没有字段清单。"""
|
||||
store = snaps()
|
||||
ex = excerpts("活跃用户数由 [[t:orders]] 去重计数得出。", loader=lambda a: None if a == SCHEMA_ART else store.get(a))
|
||||
table = ex["t:orders"]
|
||||
assert "INTEGER" not in table and "member_no TEXT" not in table
|
||||
assert "没有" in field_line(table)
|
||||
|
||||
|
||||
def test_new_excerpt_content_counts_toward_the_estimate():
|
||||
cat = entity_catalog()
|
||||
doc = compose_doc("活跃用户数由 [[t:orders]] 去重计数得出。", cat)
|
||||
store = snaps()
|
||||
full = prepare(doc, cat, loader=store.get)
|
||||
bare = prepare(doc, cat, loader=lambda a: None if a == SCHEMA_ART else store.get(a))
|
||||
assert full.cost(PRICED, full.cands) > bare.cost(PRICED, bare.cands)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 补全证据摘录:字段
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_column_excerpt_carries_its_type_and_table():
|
||||
column = excerpts("活跃用户数按 [[c:orders.member_no]] 去重计数得出。")["c:orders.member_no"]
|
||||
assert "类型:TEXT" in column and "所属的表:orders" in column
|
||||
assert "COUNT(DISTINCT member_no)" in column, "出现过的查询 SQL 保留"
|
||||
|
||||
|
||||
def test_a_result_column_takes_its_type_from_the_query_snapshot():
|
||||
"""聚合的别名(gmv)不在表结构里:类型取查询快照记下的列类型。"""
|
||||
cat = entity_catalog()
|
||||
doc = compose_doc("汇总在 [[c:gmv]] 这一列。[[see:Q2]]", cat)
|
||||
store = snaps(**{Q2_ART: {"columns": ["region", "gmv"], "rows": [["华东", 100.0]], "sql": SQL2, "source": SOURCE,
|
||||
"column_types": {"region": "text", "gmv": "number"}}})
|
||||
column = prepare(doc, cat, loader=store.get).excerpts["c:gmv"]
|
||||
assert "类型:number" in column
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 补全证据摘录:口径卡指标
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
LONG_SQL = "SELECT COUNT(DISTINCT member_no) AS active_users FROM orders WHERE " + " AND ".join(
|
||||
f"flag_{i} = 1" for i in range(80))
|
||||
CARD = {"kind": "metric_set", "caliber": "周报口径", "caliber_version": "v2", "metrics": [
|
||||
{"id": "active", "name": "活跃用户数", "unit": "人", "value": 321, "decimals": 0, "format": "plain", "status": "ok",
|
||||
"expression": "cell(nodes.fetch, 0, 'active_users')", "rendered": "321人",
|
||||
"inputs": [{"path": "cell(nodes.fetch, 0, 'active_users')", "value": 321, "node_id": None, "via": "tool_cell",
|
||||
"artifact": Q1_ART, "locator": {"row": 0, "column": "active_users"}, "status": "ok"},
|
||||
{"path": "vars.target", "value": 300, "node_id": "plan", "via": "transform", "status": "ok"}]}]}
|
||||
|
||||
|
||||
def metric_catalog():
|
||||
ledger = [{"kind": "metric_set", "node_id": "caliber", "exec": 1, "artifact": CARD_ART, "caliber": "周报口径",
|
||||
"version": "v2", "metrics": ["active"]}, query_entry(Q1_ART, ["active_users"], ["orders"])]
|
||||
return build_catalog(nodes={"caliber": {**CARD, "artifact": CARD_ART}}, ledger=ledger)
|
||||
|
||||
|
||||
def test_a_metric_excerpt_names_the_query_and_cell_of_its_input_and_that_sql():
|
||||
cat = metric_catalog()
|
||||
doc = compose_doc("活跃用户数 [[m:active]],按会员号去重计数。[[see:m:active]]", cat)
|
||||
store = {**snaps(), CARD_ART: CARD}
|
||||
metric = prepare(doc, cat, loader=store.get).excerpts["m:active"]
|
||||
assert "原式:cell(nodes.fetch, 0, 'active_users')" in metric
|
||||
[where] = [line for line in metric.splitlines() if "active_users" in line and "Q1" in line and "SQL" not in line]
|
||||
assert "r0" in where, where
|
||||
[sql] = [line for line in metric.splitlines() if line.startswith("查询 Q1 的 SQL")]
|
||||
assert "COUNT(DISTINCT member_no)" in sql
|
||||
assert any("vars.target" in line and "未追溯到查询" in line for line in metric.splitlines())
|
||||
|
||||
|
||||
def test_metric_input_sql_is_capped_and_needs_the_sealed_loader():
|
||||
cat = metric_catalog()
|
||||
doc = compose_doc("活跃用户数 [[m:active]],按会员号去重计数。[[see:m:active]]", cat)
|
||||
long = {**snaps(**{Q1_ART: {"columns": ["active_users"], "rows": [[321]], "sql": LONG_SQL, "source": SOURCE}}),
|
||||
CARD_ART: CARD}
|
||||
metric = prepare(doc, cat, loader=long.get).excerpts["m:active"]
|
||||
[sql] = [line for line in metric.splitlines() if line.startswith("查询 Q1 的 SQL")]
|
||||
assert LONG_SQL[:SQL_CHARS] in sql and LONG_SQL[:SQL_CHARS + 10] not in sql and sql.endswith("…")
|
||||
|
||||
sealed_only = {CARD_ART: CARD} # 查询快照不在封存范围里
|
||||
metric = prepare(doc, cat, loader=sealed_only.get).excerpts["m:active"]
|
||||
assert "SELECT" not in metric and "Q1" in metric, "位置照给,SQL 不给"
|
||||
|
||||
|
||||
def test_a_masked_input_column_is_not_named():
|
||||
cat = metric_catalog()
|
||||
doc = compose_doc("活跃用户数 [[m:active]],按会员号去重计数。[[see:m:active]]", cat)
|
||||
store = {**snaps(), CARD_ART: CARD}
|
||||
metric = prepare(doc, cat, loader=store.get, masked={SOURCE: ["active_users"]}).excerpts["m:active"]
|
||||
[where] = [line for line in metric.splitlines() if line.startswith("输入 cell(")]
|
||||
assert "r0" in where and "active_users" not in where.split(":", 1)[1]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 遮罩:表、字段的数据源也要查
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_source_masks_cover_the_sources_of_tables():
|
||||
name = "jr_mask_src"
|
||||
cat = build_catalog(nodes={}, ledger=[{**schema_entry(schema_snapshot()), "source": name}])
|
||||
assert cat and all(e["kind"] in ("table", "column") for e in cat.values())
|
||||
async with SessionLocal() as session:
|
||||
session.add(DataSource(name=name, kind="sqlite", database="unused.db", options={"mask_columns": "phone"}))
|
||||
await session.commit()
|
||||
try:
|
||||
assert await source_masks(cat) == {name: ["phone"]}
|
||||
finally:
|
||||
async with SessionLocal() as session:
|
||||
await session.execute(delete(DataSource).where(DataSource.name == name))
|
||||
await session.commit()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 断点里的旧判定:规则换了就不复用
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_request_key_carries_the_rules_version(monkeypatch):
|
||||
"""报告节点按 request_key 认断点里缓存的判定:规则、取值换了(旧的 unsupported),旧判定不能原样复用。"""
|
||||
cat = entity_catalog()
|
||||
doc = compose_doc(RAW, cat)
|
||||
request = prepare(doc, cat, loader=snaps().get)
|
||||
before = judge_mod.request_key(request, SPEC, UNLIMITED)
|
||||
assert before == judge_mod.request_key(request, SPEC, UNLIMITED), "同一份输入同一个指纹"
|
||||
monkeypatch.setattr(judge_mod, "RULES_VERSION", judge_mod.RULES_VERSION + 1)
|
||||
assert judge_mod.request_key(request, SPEC, UNLIMITED) != before
|
||||
|
||||
|
||||
async def test_a_new_verdict_carries_the_rules_version(monkeypatch):
|
||||
"""新判的判定带上规则版本(和 request_key 里的同一个常量):按需裁判据此认出早于当前规则的旧判定。"""
|
||||
cat = entity_catalog()
|
||||
doc = compose_doc("各区销售额按 [[c:orders.region]] 汇总。[[see:Q2]]", cat)
|
||||
Judge(monkeypatch, lambda units: [{"unit": u, "verdict": "supported", "rationale": "有依据", "used": []}
|
||||
for u in units])
|
||||
outcome = await judge_doc(doc, cat, spec=SPEC, budget=UNLIMITED, loader=snaps().get)
|
||||
[v] = outcome["verdicts"].values()
|
||||
assert v["rule_version"] == judge_mod.RULES_VERSION
|
||||
|
||||
|
||||
def test_which_verdicts_are_older_than_the_current_rules():
|
||||
current = judge_mod.RULES_VERSION
|
||||
assert judge_mod.outdated({"status": "supported"}), "没有规则版本:改造前判的"
|
||||
assert judge_mod.outdated({"status": "unsupported", "rule_version": current}), "旧取值一律算旧"
|
||||
assert judge_mod.outdated({"status": "partial", "rule_version": current - 1})
|
||||
assert not judge_mod.outdated({"status": "contradicted", "rule_version": current})
|
||||
assert not judge_mod.outdated({"status": "unjudged", "reason": "error"}), "没判成的谈不上新旧"
|
||||
@@ -0,0 +1,298 @@
|
||||
"""结论句裁判改造(JR)的判档:contradicted 沿用原来 unsupported 的处置,insufficient 按缺口处理。
|
||||
|
||||
- contradicted(证据相矛盾):按 on_unsupported 降档(degrade)或不予出具(withhold),和原来的 unsupported 一样
|
||||
- insufficient(证据不足):按缺口处理,最多降档——不会不予出具,也不会判完整出具
|
||||
- 不许比现在更松:受管正式运行里,原来会因「证据不支持」降档的句子,改判成 contradicted 或 insufficient
|
||||
都不能完整出具
|
||||
- 旧文档里的 unsupported 判档照旧当 contradicted 处理
|
||||
- 统计键(stats、counts、出具横幅的结论句计数)都有 contradicted、insufficient,unsupported 保留
|
||||
- 报告节点:改写一次把证据相矛盾、证据不足的句子都交回写作者;文档的裁判摘要记下写作模型
|
||||
|
||||
所有模型调用都是 mock 剧本,不碰真接口。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from langchain_core.messages import AIMessage
|
||||
from sqlalchemy import delete, select
|
||||
|
||||
from app.core import artifact_store
|
||||
from app.db.base import SessionLocal
|
||||
from app.db.models import Run, RunEvent, Setting, Workflow, WorkflowVersion
|
||||
from app.engine import judge as judge_mod
|
||||
from app.engine.evidence import compose_doc, iter_units
|
||||
from app.engine.issuance import decide_tier
|
||||
from app.engine.judge import JUDGE_ROLE, SPEND_KEY
|
||||
from app.engine.nodes.io import _claims
|
||||
from app.engine.runner import run_manager
|
||||
from app.main import app
|
||||
from app.providers.mock_model import MockChatModel
|
||||
|
||||
JUDGE_MODEL = "claude-sonnet-5"
|
||||
WRITER = "mock-fast"
|
||||
METRICS = [{"id": "gmv", "name": "销售额", "unit": "元", "decimals": 1, "expression": "vars.kpi.gmv"}]
|
||||
CITED = "本周销售额 [[m:gmv]]。[[see:m:gmv]]增长主要来自新客首单。[[see:m:gmv]]下面看细节。"
|
||||
SUPPORTED, CAUSAL = "本周销售额 45,678.5元。", "增长主要来自新客首单。"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 出口判档(io._claims):直接喂文档
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def judged_doc(statuses: dict[str, dict], *, on_unsupported="degrade") -> dict:
|
||||
"""两句结论:SUPPORTED_TEXT、CAUSAL_TEXT;statuses 按句子给判定。counts 照判定数。"""
|
||||
doc = compose_doc("本周销售额稳定增长。增长主要来自新客首单。", {})
|
||||
md = doc["markdown"]
|
||||
counts = {k: 0 for k in ("supported", "partial", "unsupported", "not_a_claim", "unjudged")}
|
||||
for _, unit in iter_units(doc):
|
||||
text = md[unit["span"][0]:unit["span"][1]].strip()
|
||||
verdict = {"status": "supported", "rationale": "有依据", "judge": JUDGE_MODEL, "post_seal": False, "used": [],
|
||||
**statuses.get(text, {})}
|
||||
unit["verdict"] = verdict
|
||||
counts[verdict["status"]] = counts.get(verdict["status"], 0) + 1
|
||||
doc["judge"] = {"mode": "inline", "model": JUDGE_MODEL, "on_unsupported": on_unsupported, "counts": counts,
|
||||
"unjudged": {}, "limits_hit": [], "complete": True, "gaps": []}
|
||||
return doc
|
||||
|
||||
|
||||
def grade(doc: dict, *, governed=False, contract=None) -> tuple[str, dict]:
|
||||
out = {"gaps": [], "claims_policy": None, "uncited": None, "claims": None, "unsupported": None}
|
||||
_claims(out, contract or {}, {"claims": "judge", "text": doc["markdown"]}, evidence_on=True, governed=governed,
|
||||
uncited=[], doc=doc, title="write")
|
||||
tier = decide_tier(missing_required=[], missing_expected=[], unmatched=[], strict=True, gaps=out["gaps"],
|
||||
unsupported=out["unsupported"], uncited_claims=out["uncited"],
|
||||
claims_policy=out["claims_policy"])
|
||||
return tier, out
|
||||
|
||||
|
||||
TEXT2 = "增长主要来自新客首单。"
|
||||
|
||||
|
||||
def test_all_supported_is_still_a_full_issuance():
|
||||
tier, out = grade(judged_doc({}))
|
||||
assert tier == "formal" and out["gaps"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("on_unsupported", "tier"), [("degrade", "degraded"), ("withhold", "withheld")])
|
||||
def test_contradicted_follows_on_unsupported(on_unsupported, tier):
|
||||
doc = judged_doc({TEXT2: {"status": "contradicted", "rationale": "证据里新客占比下降"}},
|
||||
on_unsupported=on_unsupported)
|
||||
got, out = grade(doc)
|
||||
assert got == tier
|
||||
claims = out["claims"]
|
||||
[item] = claims["contradicted"]
|
||||
assert item["text"] == TEXT2 and item["rationale"] == "证据里新客占比下降"
|
||||
assert claims["counts"]["contradicted"] == 1 and claims["counts"]["insufficient"] == 0
|
||||
assert out["gaps"] == [], "判档来自判定,不来自缺口"
|
||||
|
||||
|
||||
def test_insufficient_is_a_gap_and_never_withholds():
|
||||
doc = judged_doc({TEXT2: {"status": "insufficient", "rationale": "摘录里没有新客维度", "missing": "新客维度的查询"}},
|
||||
on_unsupported="withhold")
|
||||
tier, out = grade(doc, governed=True, contract={"claims": {"policy": "judge", "on_unsupported": "withhold"}})
|
||||
assert tier == "degraded", "证据不足最多降档:不能不予出具,也不能完整出具"
|
||||
[gap] = [g for g in out["gaps"] if "证据不足" in g]
|
||||
assert gap.startswith("报告「write」") and "1 句" in gap and "新客维度的查询" in gap
|
||||
[item] = out["claims"]["insufficient"]
|
||||
assert item["text"] == TEXT2 and item["missing"] == "新客维度的查询"
|
||||
assert out["claims"]["counts"]["insufficient"] == 1 and out["unsupported"] == []
|
||||
|
||||
|
||||
def test_an_old_unsupported_verdict_is_graded_as_contradicted():
|
||||
doc = judged_doc({TEXT2: {"status": "unsupported", "rationale": "证据不支持"}}, on_unsupported="withhold")
|
||||
tier, out = grade(doc)
|
||||
assert tier == "withheld"
|
||||
assert out["claims"]["counts"]["unsupported"] == 1
|
||||
assert [i["text"] for i in out["claims"]["unsupported"]] == [TEXT2]
|
||||
assert [i["text"] for i in out["unsupported"]] == [TEXT2]
|
||||
|
||||
|
||||
def test_the_issuance_counts_carry_every_key():
|
||||
_, out = grade(judged_doc({}))
|
||||
assert set(out["claims"]["counts"]) == set(judge_mod.COUNT_KEYS)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 端到端:正式运行、受管正式运行
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def engine_up():
|
||||
await run_manager.setup()
|
||||
async with SessionLocal() as session:
|
||||
await session.execute(delete(Setting).where(Setting.key.in_([SPEND_KEY, "judge", "copilot"])))
|
||||
await session.commit()
|
||||
yield
|
||||
await run_manager.shutdown()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def client(engine_up):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
|
||||
yield c
|
||||
|
||||
|
||||
def node(nid, ntype, **config):
|
||||
return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": nid, "config": config}}
|
||||
|
||||
|
||||
def weekly(*, report=None, contract=None) -> dict:
|
||||
nodes = [
|
||||
node("start", "input", fields=[{"name": "week", "default": "2026-W37"}]),
|
||||
node("fetch", "transform", mode="expression", expression="{'gmv': 45678.5}", assign_to="kpi"),
|
||||
node("caliber", "metrics", caliber="周报口径", caliber_version="v2", metrics=METRICS),
|
||||
node("write", "report", instructions="写周报", **{"claims": "judge", "judge": {"max_cost_usd": 0.05},
|
||||
**(report or {})}),
|
||||
node("out", "output", fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}],
|
||||
contract={"report_from": "write", "metrics_from": ["caliber"], "required": ["gmv"], "strict": True,
|
||||
**(contract or {})}),
|
||||
]
|
||||
ids = [n["id"] for n in nodes]
|
||||
return {"nodes": nodes, "edges": [{"source": a, "target": b} for a, b in zip(ids, ids[1:])]}
|
||||
|
||||
|
||||
class Models:
|
||||
"""写作者依次回 writer 里的几段;裁判按句子里的字给判定:verdicts = {句中片段: (判定, missing)}。"""
|
||||
|
||||
def __init__(self, monkeypatch, writer=(CITED,), verdicts=None):
|
||||
self.writes: list[list] = []
|
||||
self.judges: list[str] = []
|
||||
verdicts = verdicts or {}
|
||||
|
||||
def decide(model, messages):
|
||||
if JUDGE_ROLE in str(messages[0].content):
|
||||
request = str(messages[-1].content)
|
||||
self.judges.append(request)
|
||||
items = []
|
||||
for uid, line in re.findall(r"^\[(u\d+)\]([^\n]*)$", request, re.M):
|
||||
status, missing = next((v for frag, v in verdicts.items() if frag in line), ("supported", ""))
|
||||
items.append({"unit": uid, "verdict": status, "rationale": f"判的是:{line.strip()[:12]}",
|
||||
"missing": missing, "used": []})
|
||||
return AIMessage(content=json.dumps({"items": items}, ensure_ascii=False))
|
||||
self.writes.append(list(messages))
|
||||
return AIMessage(content=writer[min(len(self.writes), len(writer)) - 1])
|
||||
|
||||
monkeypatch.setattr(MockChatModel, "_decide", decide)
|
||||
|
||||
async def judge_model_of(session, spec):
|
||||
return MockChatModel(model_name=JUDGE_MODEL), JUDGE_MODEL
|
||||
|
||||
monkeypatch.setattr(judge_mod, "get_chat_model", judge_model_of)
|
||||
|
||||
|
||||
async def wait(run_id: str) -> Run:
|
||||
for _ in range(400):
|
||||
await asyncio.sleep(0.05)
|
||||
async with SessionLocal() as session:
|
||||
row = await session.get(Run, run_id)
|
||||
if row.status in ("succeeded", "failed") and row.manifest_seq is not None:
|
||||
return row
|
||||
raise AssertionError(f"run {run_id} 没跑完:{row.status}")
|
||||
|
||||
|
||||
async def run(graph, *, run_class="formal") -> Run:
|
||||
started = await run_manager.start(graph=graph, input_payload={}, run_class=run_class)
|
||||
row = await wait(started.id)
|
||||
assert row.status == "succeeded", row.error
|
||||
return row
|
||||
|
||||
|
||||
async def checked_of(run_id: str) -> tuple[dict, dict]:
|
||||
async with SessionLocal() as session:
|
||||
[event] = (await session.execute(select(RunEvent).where(
|
||||
RunEvent.run_id == run_id, RunEvent.type == "report.checked"))).scalars()
|
||||
return event.data, artifact_store.load(event.data["doc_artifact"])
|
||||
|
||||
|
||||
async def issuance_event(run_id: str) -> dict:
|
||||
async with SessionLocal() as session:
|
||||
[event] = (await session.execute(select(RunEvent).where(
|
||||
RunEvent.run_id == run_id, RunEvent.type == "issuance"))).scalars()
|
||||
return event.data
|
||||
|
||||
|
||||
async def test_a_formal_run_withholds_a_contradicted_claim(engine_up, monkeypatch):
|
||||
Models(monkeypatch, verdicts={"新客": ("contradicted", "")})
|
||||
row = await run(weekly(report={"judge": {"max_cost_usd": 0.05, "on_unsupported": "withhold"}}))
|
||||
issuance = row.output["_issuance"]
|
||||
assert issuance["tier"] == "withheld"
|
||||
assert [i["text"] for i in issuance["claims"]["contradicted"]] == [CAUSAL]
|
||||
event = await issuance_event(row.id)
|
||||
assert event["claims"]["counts"] == {"supported": 1, "partial": 0, "contradicted": 1, "insufficient": 0,
|
||||
"not_a_claim": 0, "unjudged": 0, "unsupported": 0}
|
||||
|
||||
|
||||
async def test_a_formal_run_only_degrades_an_insufficient_claim(engine_up, monkeypatch):
|
||||
Models(monkeypatch, verdicts={"新客": ("insufficient", "新客维度的数据")})
|
||||
row = await run(weekly(report={"judge": {"max_cost_usd": 0.05, "on_unsupported": "withhold"}}))
|
||||
issuance = row.output["_issuance"]
|
||||
assert issuance["tier"] == "degraded", "证据不足:最多降档,不因 withhold 不予出具"
|
||||
assert any("证据不足" in g and "新客维度的数据" in g for g in issuance["gaps"]), issuance["gaps"]
|
||||
[item] = issuance["claims"]["insufficient"]
|
||||
assert item["text"] == CAUSAL and item["missing"] == "新客维度的数据"
|
||||
assert issuance["claims"]["counts"]["insufficient"] == 1
|
||||
|
||||
checked, doc = await checked_of(row.id)
|
||||
assert doc["stats"]["insufficient"] == 1 and doc["stats"]["contradicted"] == 0 and doc["stats"]["unsupported"] == 0
|
||||
assert checked["stats"]["insufficient"] == 1
|
||||
assert doc["judge"]["writer_model"] == WRITER and checked["judge"]["writer_model"] == WRITER
|
||||
[unit] = [u for _, u in iter_units(doc) if u.get("verdict", {}).get("status") == "insufficient"]
|
||||
assert unit["verdict"]["missing"] == "新客维度的数据"
|
||||
|
||||
|
||||
async def governed(client, graph) -> Run:
|
||||
async with SessionLocal() as session:
|
||||
wf = Workflow(name=f"jr-{uuid.uuid4().hex[:6]}", graph=graph, status="governed", published_version=1)
|
||||
session.add(wf)
|
||||
await session.flush()
|
||||
session.add(WorkflowVersion(workflow_id=wf.id, version=1, graph=graph))
|
||||
await session.commit()
|
||||
wf_id = wf.id
|
||||
res = await client.post("/api/runs", json={"workflow_id": wf_id, "run_class": "formal"})
|
||||
assert res.status_code == 201, res.text
|
||||
row = await wait(res.json()["id"])
|
||||
assert row.status == "succeeded", row.error
|
||||
return row
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", ["contradicted", "insufficient"])
|
||||
async def test_a_governed_formal_run_is_never_fully_issued_on_a_split_verdict(client, monkeypatch, status):
|
||||
"""不许比现在更松:原来判「证据不支持」要降档的句子,改判成哪一档都不能完整出具。"""
|
||||
Models(monkeypatch, verdicts={"新客": (status, "新客维度的数据" if status == "insufficient" else "")})
|
||||
graph = weekly(report={"numbers": "strict", "on_violation": "fail", "judge": {"max_cost_usd": None}})
|
||||
row = await governed(client, graph)
|
||||
assert row.output["_issuance"]["tier"] == "degraded"
|
||||
|
||||
|
||||
async def test_rewrite_once_hands_back_contradicted_and_insufficient_sentences(engine_up, monkeypatch):
|
||||
draft = ("本周销售额 [[m:gmv]]。[[see:m:gmv]]增长主要来自新客首单。[[see:m:gmv]]"
|
||||
"华东贡献了大部分增长。[[see:m:gmv]]下面看细节。")
|
||||
rewritten = "本周销售额 [[m:gmv]]。[[see:m:gmv]]新客、华东的贡献要等分维度的数据再看。下面看细节。"
|
||||
models = Models(monkeypatch, writer=(draft, rewritten),
|
||||
verdicts={"新客首单": ("contradicted", ""), "华东贡献": ("insufficient", "分区域的查询"),
|
||||
"要等分维度": ("not_a_claim", "")})
|
||||
row = await run(weekly(report={"judge": {"max_cost_usd": 0.05, "rewrite_once": True}}))
|
||||
assert len(models.writes) == 2
|
||||
request = str(models.writes[1][-1].content)
|
||||
assert "增长主要来自新客首单。" in request and "华东贡献了大部分增长。" in request
|
||||
assert "分区域的查询" in request, "证据不足的句子连同缺的是什么一起交回"
|
||||
assert SUPPORTED not in request
|
||||
checked, _ = await checked_of(row.id)
|
||||
assert checked["judge"]["rewrite"]["applied"] is True and len(checked["judge"]["rewrite"]["sentences"]) == 2
|
||||
|
||||
|
||||
async def test_an_explore_report_records_the_writer_model_too(engine_up, monkeypatch):
|
||||
models = Models(monkeypatch)
|
||||
row = await run(weekly(), run_class="exploratory")
|
||||
assert models.judges == []
|
||||
checked, doc = await checked_of(row.id)
|
||||
assert doc["judge"]["mode"] == "on_demand" and doc["judge"]["writer_model"] == WRITER
|
||||
assert set(judge_mod.COUNT_KEYS) <= set(doc["stats"])
|
||||
@@ -26,7 +26,7 @@ from app.engine import judge as judge_mod
|
||||
from app.engine import replay
|
||||
from app.engine import runner as runner_mod
|
||||
from app.engine.evidence import CLAIMS_RULE, iter_units
|
||||
from app.engine.judge import JUDGE_ROLE, JUDGE_RULE, SPEND_KEY, SUMMARY_KEYS, daily_spend
|
||||
from app.engine.judge import COUNT_KEYS, JUDGE_ROLE, JUDGE_RULE, SPEND_KEY, SUMMARY_KEYS, daily_spend
|
||||
from app.engine.nodes import report as report_mod
|
||||
from app.engine.runner import run_manager, verify_manifest
|
||||
from app.providers.mock_model import MockChatModel
|
||||
@@ -167,7 +167,7 @@ async def judge_ends(run_id: str) -> list[dict]:
|
||||
|
||||
|
||||
async def test_a_formal_run_judges_inside_the_node_and_seals_the_verdicts(monkeypatch):
|
||||
models = Models(monkeypatch, verdicts={"新客": "unsupported"})
|
||||
models = Models(monkeypatch, verdicts={"新客": "contradicted"})
|
||||
row = await finish(weekly(claims="judge", judge={"on_unsupported": "withhold"}))
|
||||
assert row.status == "succeeded", row.error
|
||||
assert len(models.writes) == 1 and len(models.judges) == 1
|
||||
@@ -176,18 +176,19 @@ async def test_a_formal_run_judges_inside_the_node_and_seals_the_verdicts(monkey
|
||||
got = verdicts(doc)
|
||||
assert got[CITED]["status"] == "supported" and got[CITED]["judge"] == PRICED
|
||||
assert got[CITED]["post_seal"] is False and got[CITED]["rationale"]
|
||||
assert got[CAUSAL]["status"] == "unsupported"
|
||||
assert got[CAUSAL]["status"] == "contradicted"
|
||||
assert got[LINK] is None, "连接性的话不送裁判"
|
||||
assert CITED in models.judges[0] and CAUSAL in models.judges[0] and LINK not in models.judges[0]
|
||||
|
||||
summary = checked["judge"]
|
||||
assert tuple(summary) == SUMMARY_KEYS, "B 段照着这份键读:不能悄悄少一个、多一个"
|
||||
assert summary["mode"] == "inline" and summary["model"] == PRICED and summary["on_unsupported"] == "withhold"
|
||||
assert summary["counts"] == {"supported": 1, "partial": 0, "unsupported": 1, "not_a_claim": 0, "unjudged": 0}
|
||||
assert summary["counts"] == {"supported": 1, "partial": 0, "contradicted": 1, "insufficient": 0, "not_a_claim": 0,
|
||||
"unjudged": 0, "unsupported": 0}
|
||||
assert summary["complete"] is True and summary["gaps"] == []
|
||||
assert checked["claims"] == output["claims"] == "judge" and output["judge"] == summary
|
||||
assert doc["judge"]["mode"] == "inline" and doc["judge"]["counts"] == summary["counts"]
|
||||
assert {k: doc["stats"][k] for k in ("supported", "partial", "unsupported", "not_a_claim", "unjudged")} \
|
||||
assert {k: doc["stats"][k] for k in COUNT_KEYS} \
|
||||
== summary["counts"]
|
||||
|
||||
[end] = await judge_ends(row.id)
|
||||
@@ -277,7 +278,7 @@ REWRITTEN = "本周销售额 [[m:gmv]]。[[see:m:gmv]]新客首单的贡献要
|
||||
|
||||
async def test_rewrite_once_hands_back_only_the_unsupported_sentences(monkeypatch):
|
||||
models = Models(monkeypatch, writer=(TEXT, REWRITTEN),
|
||||
verdicts={"主要来自新客": "unsupported", "要等新客维度": "not_a_claim"})
|
||||
verdicts={"主要来自新客": "contradicted", "要等新客维度": "not_a_claim"})
|
||||
row = await finish(weekly(claims="judge", judge={"rewrite_once": True}))
|
||||
assert row.status == "succeeded", row.error
|
||||
assert len(models.writes) == 2 and len(models.judges) == 2
|
||||
@@ -305,23 +306,23 @@ async def test_rewrite_once_hands_back_only_the_unsupported_sentences(monkeypatc
|
||||
|
||||
|
||||
async def test_rewrite_once_is_off_by_default(monkeypatch):
|
||||
models = Models(monkeypatch, writer=(TEXT, REWRITTEN), verdicts={"主要来自新客": "unsupported"})
|
||||
models = Models(monkeypatch, writer=(TEXT, REWRITTEN), verdicts={"主要来自新客": "contradicted"})
|
||||
row = await finish(weekly(claims="judge"))
|
||||
assert row.status == "succeeded", row.error
|
||||
assert len(models.writes) == 1 and len(models.judges) == 1
|
||||
checked, doc, _ = await report_of(row.id)
|
||||
assert verdicts(doc)[CAUSAL]["status"] == "unsupported" and checked["judge"].get("rewrite") is None
|
||||
assert verdicts(doc)[CAUSAL]["status"] == "contradicted" and checked["judge"].get("rewrite") is None
|
||||
|
||||
|
||||
async def test_a_rewrite_that_breaks_the_numbers_is_not_used(monkeypatch):
|
||||
models = Models(monkeypatch, writer=(TEXT, "本周销售额 [[m:gmv]]。[[see:m:gmv]]新客贡献了 45678 元。下面看细节。"),
|
||||
verdicts={"主要来自新客": "unsupported"})
|
||||
verdicts={"主要来自新客": "contradicted"})
|
||||
row = await finish(weekly(claims="judge", judge={"rewrite_once": True}))
|
||||
assert row.status == "succeeded", row.error
|
||||
assert len(models.writes) == 2 and len(models.judges) == 1, "改坏了的那一稿不再花钱判"
|
||||
checked, doc, output = await report_of(row.id)
|
||||
assert CAUSAL in doc["markdown"] and "45678" not in doc["markdown"]
|
||||
assert verdicts(doc)[CAUSAL]["status"] == "unsupported"
|
||||
assert verdicts(doc)[CAUSAL]["status"] == "contradicted"
|
||||
rewrite = checked["judge"]["rewrite"]
|
||||
assert rewrite["applied"] is False and "45678" in rewrite["reason"]
|
||||
# 封存的是原稿:units 就是原稿(也就是封存文档)里的编号
|
||||
@@ -346,7 +347,7 @@ async def test_a_rewrite_that_makes_up_a_name_is_not_used(monkeypatch):
|
||||
with_schema(monkeypatch)
|
||||
models = Models(monkeypatch, writer=(TEXT, "本周销售额 [[m:gmv]]。[[see:m:gmv]]新客首单的贡献要看 `refund_detail` 表。"
|
||||
"下面看细节。"),
|
||||
verdicts={"主要来自新客": "unsupported"})
|
||||
verdicts={"主要来自新客": "contradicted"})
|
||||
row = await finish(weekly(claims="judge", judge={"rewrite_once": True}))
|
||||
assert row.status == "succeeded", row.error
|
||||
assert len(models.writes) == 2 and len(models.judges) == 1
|
||||
@@ -362,7 +363,7 @@ async def test_a_rewrite_that_trades_one_violation_for_another_is_not_used(monke
|
||||
"""去掉一处违规、又冒出另一处:总数没变,可冒出来的是原稿没有的,一样不采用。"""
|
||||
draft = "本周销售额 [[m:gmv]]。[[see:m:gmv]]增长主要来自新客首单,共 1200 单。下面看细节。"
|
||||
swapped = "本周销售额 [[m:gmv]]。[[see:m:gmv]]新客首单约占 3500 单。下面看细节。"
|
||||
models = Models(monkeypatch, writer=(draft, draft, swapped), verdicts={"主要来自新客": "unsupported"})
|
||||
models = Models(monkeypatch, writer=(draft, draft, swapped), verdicts={"主要来自新客": "contradicted"})
|
||||
row = await finish(weekly(claims="judge", on_violation="flag", max_repairs=1, judge={"rewrite_once": True}))
|
||||
assert row.status == "succeeded", row.error
|
||||
assert len(models.writes) == 3 and len(models.judges) == 1
|
||||
@@ -385,7 +386,7 @@ def test_new_violations_are_counted_one_by_one():
|
||||
|
||||
async def test_a_second_round_that_hits_a_limit_names_the_configured_limit(monkeypatch):
|
||||
"""第二轮用的是第一轮剩下的钱,可说给人看的上限是节点上配的那个数,不是剩下的零头。"""
|
||||
Models(monkeypatch, writer=(TEXT, REWRITTEN), verdicts={"主要来自新客": "unsupported"})
|
||||
Models(monkeypatch, writer=(TEXT, REWRITTEN), verdicts={"主要来自新客": "contradicted"})
|
||||
# 每句估 1 分钱、回复不带用量(实际就按估算记):第一轮两句花掉 2 分,第二轮只剩半分,一句也装不下
|
||||
monkeypatch.setattr(judge_mod.JudgeRequest, "cost", lambda self, model_id, units: 0.01 * len(units))
|
||||
monkeypatch.setattr(judge_mod, "_usage_of", lambda message, model_id: {"input_tokens": 0, "output_tokens": 0})
|
||||
|
||||
Reference in New Issue
Block a user