分析卡里随数据变化的调用错误记成算不了的一项,不让卡失败(复核 R6):analysis.run 加参数 refuse_data_errors(缺省假),为真时 DATA_ERRORS 里的调用错误——上一层没做成 parent_refused、下钻的段这期没有 parent_key_missing、期次这期没有 period_not_found(变化拆解、波动基线的本期、差异检验按期比、可比性检查)、总数那一格越界或为空 row_out_of_range / headline_empty、要比的组这期没有 unknown_group / too_few_groups、要用的那一格这期为空 empty_cell(乘积拆解的乘积和因子;差异检验的计数为空原来报的是 not_count,改报 empty_cell)——记成 status refused 的结论:契约 REASONS 加 parent_refused、input_unavailable,CallError 加 reason(照实说是哪一项、哪个值,不带改法),判定语「{叫法}没有做成:原因」;params 照调用原样(label 照样消毒),取过还没记用法的快照都记进输入(Inputs.settle,角色照第一次取时的),上一层在核对它做没做成之前就记进输入,复算按它们走到同一处;阈值和判定标准同各算子自己算不了时那一份(各模块的 USED / refusal_basis,算子本身也改用它)。recompute 一律按真复现;结构性的调用错误照旧抛。分析卡运行器传真,agent 工具不传。顺手:段数不够的原因里维度叫法和汉字之间照 say 的规矩补空格

This commit is contained in:
ThearchyHelios
2026-10-21 15:47:30 +08:00
parent 0acf9fb3a8
commit 6e38df4fbf
13 changed files with 353 additions and 54 deletions
+5 -3
View File
@@ -52,8 +52,10 @@ CATALOGS = {"shop": {"orders": ORDERS}}
async def analyze(op: str, mode: str | None = None, *, snaps: Sequence[Mapping[str, Any]], today: date = TODAY,
catalogs: Mapping[str, Any] | None = None, probe: Any = None, facts: Any = None,
parents: Mapping[str, Mapping[str, Any]] | None = None, settings: Mapping[str, Any] | None = None,
hypothesis: str | None = None, check: bool = True, **params: Any) -> dict[str, Any]:
"""跑一次 analysis.run;check 时再复算一遍,核对和封存的逐字段相同(hypothesis 除外)。"""
hypothesis: str | None = None, check: bool = True, refuse_data_errors: bool = False,
**params: Any) -> dict[str, Any]:
"""跑一次 analysis.run;check 时再复算一遍,核对和封存的逐字段相同(hypothesis 除外)。refuse_data_errors 同 run(分析卡
传真);复算一律按真。"""
by_ref = {s["ref"]: s for s in snaps}
request: dict[str, Any] = {"op": op, "mode": mode, "params": params}
if hypothesis is not None:
@@ -64,7 +66,7 @@ async def analyze(op: str, mode: str | None = None, *, snaps: Sequence[Mapping[s
if facts is not None:
context["facts"] = facts
result = await analysis.run(request, by_ref.get, settings=effective_settings(settings), context=context,
parents=(parents or {}).get)
parents=(parents or {}).get, refuse_data_errors=refuse_data_errors)
if check:
again = recomputed(result, snaps, parents)
assert same(result, again), _diff(result, again)
+2 -2
View File
@@ -30,7 +30,7 @@ class FakeOps:
monkeypatch.setattr(analysis_ops, "run", self.run)
async def run(self, request: dict[str, Any], resolve: Any, *, settings: Any, context: Any,
parents: Any = None) -> dict[str, Any]:
parents: Any = None, refuse_data_errors: bool = False) -> dict[str, Any]:
params = request.get("params") or {}
names = [params[k] for k in ("query", "base_query", "target_query") if params.get(k)]
snapshots = {name: resolve(name) for name in names}
@@ -38,7 +38,7 @@ class FakeOps:
if isinstance(params.get("parent"), dict) and parents is not None:
parent = parents(params["parent"]["of"])
self.calls.append({"request": request, "snapshots": snapshots, "settings": dict(settings), "context": context,
"parent": parent, "parents": parents,
"parent": parent, "parents": parents, "refuse_data_errors": refuse_data_errors,
"visible": {n: parents is not None and parents(n) is not None for n in self.peek}})
error = self.errors.pop(0) if self.errors else None
if error is not None:
+70
View File
@@ -0,0 +1,70 @@
"""分析卡里随数据变化的调用错误(复核 R6):模板定死了调用,这期的数据里没有要用的那一项(上一层没做成、下钻的段这期没有……)
记成算不了的一项,不让卡失败;结构性的调用错误照旧让卡失败并说清哪一项。接真算子跑(tests/test_analysis_e2e 的虚构零售库
shop),每份结论按封存的工件复算、逐字段相同。"""
from __future__ import annotations
from app.core import artifact_store
from app.engine.runner import run_manager
from tests.test_analysis_e2e import ( # noqa: F401 - engine_up、shop 是自动用的夹具
BY_REGION, EAST, TOOL, TWO_WEEKS, WEEK, chain, engine_up, events, node, recomputes, shop, wait,
)
ONLY_EAST = (f"SELECT region, {WEEK} AS week, SUM(amount) AS gmv FROM orders "
"WHERE region = '华东' AND day >= '2026-05-11' GROUP BY region, week ORDER BY region, week")
WHERE = {"id": "where", "op": "decompose", "mode": "additive", "from": "by_region",
"params": {"by": ["region"], **TWO_WEEKS}}
DRILL = {"id": "east", "op": "decompose", "mode": "additive", "from": "east_q",
"params": {"by": ["channel"], **TWO_WEEKS, "parent": {"of": "where", "key": ["华东"]}}}
def card_graph(region_sql, items):
return chain(node("start", "input"), node("by_region", "tool", tool=TOOL, args={"sql": region_sql}),
node("east_q", "tool", tool=TOOL, args={"sql": EAST}),
node("card", "analysis", items=items),
node("out", "output", fields=[{"name": "r", "value": "{{ nodes.card.results.east.phrase }}"}]))
async def _card(region_sql, items):
run = await run_manager.start(graph=card_graph(region_sql, items), input_payload={})
row = await wait(run.id)
return row
async def test_a_drill_under_a_refused_parent_is_refused_and_the_card_goes_on():
row = await _card(ONLY_EAST, [WHERE, DRILL])
assert row.status == "succeeded", row.error
[finished] = await events(row.id, "node.finished", "card")
results = artifact_store.load(finished["artifact"])["results"]
assert results["where"]["status"] == "refused" and results["east"]["status"] == "refused"
east = artifact_store.load(results["east"]["artifact"])
assert east["reason_code"] == "parent_refused"
assert east["reason"] == "上一层「where」没有做成(按 region 只有 1 段,至少要 2 段才拆得开),不能在它下面下钻"
assert row.output["r"] == "变化拆解没有做成:" + east["reason"]
ends = {e["item"]: e for e in await events(row.id, "analysis.end", "card")}
assert ends["east"]["reason_code"] == "parent_refused" and ends["east"]["status"] == "refused"
warned = [e for e in await events(row.id, "log", "card") if e.get("code") == "analysis_refused"]
assert [e["item"] for e in warned] == ["where", "east"]
assert [(e["item"], e["status"]) for e in finished["evidence"]] == [("where", "refused"), ("east", "refused")]
recomputes(artifact_store.load(results["where"]["artifact"]))
recomputes(east)
async def test_a_segment_missing_this_time_is_refused_and_the_card_goes_on():
drill = {**DRILL, "params": {**DRILL["params"], "parent": {"of": "where", "key": ["东北"]}}}
row = await _card(BY_REGION, [WHERE, drill])
assert row.status == "succeeded", row.error
[finished] = await events(row.id, "node.finished", "card")
results = artifact_store.load(finished["artifact"])["results"]
assert results["where"]["status"] == "ok" and results["east"]["status"] == "refused"
east = artifact_store.load(results["east"]["artifact"])
assert east["reason_code"] == "input_unavailable" and east["reason"] == "上一层「where」里没有「东北」这一段"
assert [i["role"] for i in east["inputs"]] == ["parent", "data"]
recomputes(east)
async def test_a_structural_call_error_still_fails_the_card_and_names_the_item():
wrong = {**WHERE, "params": {**WHERE["params"], "by": ["channel"]}}
row = await _card(BY_REGION, [wrong])
assert row.status == "failed"
assert "分析项「where」(变化拆解)" in row.error and "没有「channel」这一列" in row.error
assert "请在分析卡中改正这一项" in row.error
+94
View File
@@ -153,3 +153,97 @@ async def test_ledger_entries_name_the_real_input_snapshots():
def test_the_call_limit_error_is_spoken_with_the_limit():
error = analysis.exhausted({"max_calls": 5})
assert error.code == "max_calls" and error.message == "这个 Agent 这次执行最多做 5 次分析,已经用完:用已有的分析结论写,不再新做分析"
# --------------------------------------------------------------------------
# 随数据变化的调用错误(分析卡传 refuse_data_errors):记成算不了的结论,复算也成立
# --------------------------------------------------------------------------
ONE_REGION = snap("Q6", WEEKLY_SQL, ["region", "week", "gmv"], [["华东", "2026-W41", 820], ["华东", "2026-W42", 700]])
TOTALS = snap("Q7", "SELECT week, SUM(amount) AS gmv FROM orders GROUP BY week", ["week", "gmv"],
[["2026-W42", 1926], ["2026-W41", None]])
FACTORS = snap("Q8", "SELECT week, SUM(amount) AS gmv, COUNT(*) AS orders, AVG(amount) AS aov FROM orders "
"GROUP BY week",
["week", "gmv", "orders", "aov"], [["2026-W41", 2120, 20, 106], ["2026-W42", None, 0, None]])
ONE_GROUP = snap("Q9", "SELECT region, SUM(refund_flag) AS refunds, COUNT(*) AS orders FROM orders GROUP BY region",
["region", "refunds", "orders"], [["西南", 80, 1000]])
WEEK_RATES = snap("Q10", "SELECT week, SUM(refund_flag) AS refunds, COUNT(*) AS orders FROM orders GROUP BY week",
["week", "refunds", "orders"], [["2026-W41", 30, 1000], ["2026-W42", None, 1000]])
REFUSALS = [WEEKLY, SERIES, RATES, ONE_REGION, TOTALS, FACTORS, ONE_GROUP, WEEK_RATES]
BY_REGION = {"query": "Q2", "by": ["region"], "period": "week", "base": "2026-W41", "target": "2026-W42",
"measure": "gmv"}
async def _refused(op, mode=None, *, parents=None, **params):
"""refuse_data_errors 为真跑两次:逐字节相同、形状照契约、复算逐字段相同(analyze 里按真复算);不传时照旧是调用错误。"""
one = await analyze(op, mode, snaps=REFUSALS, parents=parents, refuse_data_errors=True, **params)
two = await analyze(op, mode, snaps=REFUSALS, parents=parents, refuse_data_errors=True, **params)
assert json.dumps(one, sort_keys=True, ensure_ascii=False) == json.dumps(two, sort_keys=True, ensure_ascii=False)
_assert_shape(one)
assert one["status"] == "refused" and one["phrase"] == f"{c.OP_LABELS[op]}没有做成:{one['reason']}"
error = await call_error(op, mode, snaps=REFUSALS, parents=parents, **params)
assert error.code in analysis.DATA_ERRORS and error.reason == one["reason"]
return one
def test_the_data_errors_are_exported():
assert analysis.DATA_ERRORS == {"parent_refused", "parent_key_missing", "period_not_found", "row_out_of_range",
"headline_empty", "unknown_group", "too_few_groups", "empty_cell"}
assert {"parent_refused", "input_unavailable"} <= set(c.REASONS)
async def test_a_drill_under_a_refused_parent_is_itself_refused():
parent = await analyze("decompose", "additive", snaps=REFUSALS, **{**BY_REGION, "query": "Q6"})
assert parent["reason_code"] == "too_few_segments"
result = await _refused("decompose", "additive", parents={"where": parent},
**{**BY_REGION, "by": ["region"], "parent": {"of": "where", "key": ["华东"]}})
assert result["reason_code"] == "parent_refused"
assert result["reason"] == "上一层「where」没有做成(按地区只有 1 段,至少要 2 段才拆得开),不能在它下面下钻"
# 上一层、取过的快照都记进输入(复算按它们走到同一处);参数照调用原样,阈值同这个模式自己算不了时
assert [i["role"] for i in result["inputs"]] == ["parent", "data"]
assert result["inputs"][1] == {"ref": "Q2", "artifact": WEEKLY["artifact"], "role": "data",
"columns": ["region", "gmv", "week"], "rows": "all"}
assert result["params"]["parent"] == {"of": "where", "key": ["华东"]}
assert result["settings"] == {**{k: c.DEFAULTS[k] for k in ("main_share", "concentration", "offset_ratio",
"flat_pct", "table_top_k")}, "max_drill_depth": 3}
assert result["table"] is None and result["verdict"] is None
async def test_segments_periods_cells_and_groups_missing_this_time():
parent = await analyze("decompose", "additive", snaps=REFUSALS, **BY_REGION)
key = await _refused("decompose", "additive", parents={"A1": parent},
**{**BY_REGION, "parent": {"of": "A1", "key": ["东北"]}})
assert key["reason_code"] == "input_unavailable" and key["reason"] == "上一层「A1」里没有「东北」这一段"
period = await _refused("decompose", "additive", **{**BY_REGION, "target": "2026-W43", "label": "销售额,主要来自华东"})
assert period["reason"] == "期次列「week」里没有本期「2026-W43」" and period["params"]["label"] == "销售额"
row = await _refused("decompose", "additive", **BY_REGION, headline={"base": "Q7.r5.gmv", "target": "Q7.r0.gmv"})
assert row["reason"] == "基期总数那一格(Q7.r5.gmv)不在:Q7 这次只有 2 行"
assert [i["role"] for i in row["inputs"]] == ["data", "headline_base"]
empty = await _refused("decompose", "additive", **BY_REGION, headline={"base": "Q7.r1.gmv", "target": "Q7.r0.gmv"})
assert empty["reason"] == "基期总数那一格(Q7.r1.gmv)是空的"
factor = await _refused("decompose", "factor", query="Q8", period="week", base="2026-W41", target="2026-W42",
product="gmv", factors=["orders", "aov"])
assert factor["reason"] == "本期的「gmv」那一格是空的(Q8 第 1 行)"
target = await _refused("baseline", query="Q1", period="week", measure="gmv", target="2020-01-06")
assert target["reason"] == "期次列「week」里没有本期「2020-01-06」(或那一期为空)"
assert target["settings"] == {k: c.DEFAULTS[k] for k in ("k_warn", "k_alert", "min_history", "max_history")}
side = await _refused("comparable", query="Q2", period="week", base="2026-W40", target="2026-W42")
assert side["reason"] == "期次列「week」里没有基期「2026-W40」" and side["settings"] == {}
rates = {"by": ["region"], "numerator": "refunds", "denominator": "orders"}
group = await _refused("differ", "rate", query="Q3", **rates, pairs=[["华东", "东北"]])
assert group["reason"] == "分组列「region」里没有「东北」这一组"
assert group["settings"] == {"differ_alpha": 0.05, "min_expected": 5}
few = await _refused("differ", "rate", query="Q9", **rates)
assert few["reason"] == "分组列「region」里只有 1 组,至少要两组才比得了"
weeks = {"query": "Q10", "period": "week", "numerator": "refunds", "denominator": "orders"}
gone = await _refused("differ", "rate", **weeks, base="2026-W40", target="2026-W41")
assert gone["reason"] == "期次列「week」里没有基期「2026-W40」"
null = await _refused("differ", "rate", **weeks, base="2026-W41", target="2026-W42")
assert null["reason"] == "「refunds」那一格是空的(Q10 第 1 行)"
async def test_structural_call_errors_still_fail_even_when_data_errors_are_refused():
for params in ({**BY_REGION, "by": ["channel"]}, {**BY_REGION, "by": ["region", "week"]}):
with pytest.raises(CallError) as e:
await analyze("decompose", "additive", snaps=REFUSALS, refuse_data_errors=True, check=False, **params)
assert e.value.code not in analysis.DATA_ERRORS and e.value.reason is None