diff --git a/backend/app/engine/nodes/metrics.py b/backend/app/engine/nodes/metrics.py index 096aeed8..67d9effc 100644 --- a/backend/app/engine/nodes/metrics.py +++ b/backend/app/engine/nodes/metrics.py @@ -128,8 +128,7 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]: errors.append(f"指标「{metric_id}」:小数位(decimals)需要填写整数,当前为「{definition.get('decimals')}」") continue decimals = display["decimals"] - if isinstance(value, float) and decimals is not None: - value = round(value, decimals) + value = round_metric(value, decimals) substituted = substitute(tree, values) incomplete: dict[str, Any] = {} if use.sources: @@ -334,6 +333,17 @@ def _integer(raw: Any) -> int | None: return None +def round_metric(value: Any, decimals: Any) -> Any: + """口径卡的取整:只取整浮点,按小数位 round(Python 的 round,负数取整到十位、百位);整数、文本、空值原样, + 小数位没写或不是整数(老卡上记着的 true、2.0 这类怪值)时也原样。 + + 推演重算(engine/recompute.py)、双盲复算的盲值都按卡重算,取整规则只能有这一处:两边各写一行,口径卡哪天换了 + 取整方式,推演就会对着同一张卡算出另一个数。""" + if isinstance(value, float) and isinstance(decimals, int) and not isinstance(decimals, bool): + return round(value, decimals) + return value + + def _rendered(value: Any, definition: dict[str, Any], display: dict[str, Any]) -> str: try: return render_number(value, unit=str(definition.get("unit") or ""), @@ -726,8 +736,7 @@ def _recompute(substituted: str, tctx: dict[str, Any], value: Any, decimals: int again = eval_expression(substituted, tctx) except Exception: # noqa: BLE001 - 代入式算不出来本身就是「对不上」 return False - if isinstance(again, float) and decimals is not None: - again = round(again, decimals) + again = round_metric(again, decimals) if is_number(again) and is_number(value): return math.isclose(again, value, rel_tol=1e-12, abs_tol=0.0) or again == value return again == value diff --git a/backend/app/engine/recompute.py b/backend/app/engine/recompute.py index 0f3a0f76..0a6d3da0 100644 --- a/backend/app/engine/recompute.py +++ b/backend/app/engine/recompute.py @@ -3,9 +3,9 @@ 推演永远不是出具。这里只算数:不读库、不写工件、不追加事件。接口(api/whatif.py)把这次运行封存范围内取得到的 工件交进来(Sources),结果原样交回给点开证据面板的人,运行记录和报告一个字都不动。 -口径卡怎么算的,这里就怎么算:同一条原式、同一个求值器(expressions.eval_expression),浮点结果按卡上记的小数位 -round(和 metrics.run_metrics 一样只 round 浮点),渲染走 evidence.render_metric。重算前先把每个输入当时的值还原 -出来,卡上记着的就用卡上的: +口径卡怎么算的,这里就怎么算:同一条原式、同一个求值器(expressions.eval_expression),取整用口径卡的同一个函数 +(metrics.round_metric,只取整浮点),渲染走 evidence.render_metric。重算前先把每个输入当时的值还原出来,卡上记着的 +就用卡上的: - 标量输入(数、文本、布尔、空值):卡上记的 value 就是当时代进去的值。cell() 取的格、agent 的单格字段和数组里的 一个元素也是标量,它们落在查询快照的哪一行记在 locator 里:排除了那一行,这个输入就当缺失,指标标「排除后无法计算」 @@ -52,7 +52,7 @@ from app.engine.expressions import ( parse_expression, substitute, ) -from app.engine.nodes.metrics import _REF_HEAD, _brief +from app.engine.nodes.metrics import _REF_HEAD, _brief, round_metric NO_LINEAGE = "这个指标生成于系统升级前,口径卡没有记录输入,不能推演" NO_FULL_VALUE = "当时没有保存这个输入的完整值" @@ -647,7 +647,7 @@ class _Bind(ast.NodeTransformer): def _evaluate(plan: _Plan, values: dict[str, Any]) -> tuple[Any, str | None]: - """按原式求值,报错的说法和口径卡一致。浮点结果按卡上的小数位 round(metrics.run_metrics 同样只 round 浮点)。""" + """按原式求值,报错的说法和口径卡一致。取整和口径卡共用 metrics.round_metric(只取整浮点)。""" names = {path: _PLACEHOLDER.format(i) for i, path in enumerate(plan.tops)} bound = ast.fix_missing_locations(_Bind(names).visit(copy.deepcopy(plan.tree))) ctx = {names[p]: values.get(p) for p in plan.tops} @@ -663,10 +663,8 @@ def _evaluate(plan: _Plan, values: dict[str, Any]) -> tuple[Any, str | None]: if isinstance(e, TypeError): return None, "输入的类型不正确,无法计算" return None, f"无法计算({describe_exception(e)})" - decimals = plan.metric.get("decimals") - if isinstance(value, float) and isinstance(decimals, int) and not isinstance(decimals, bool): - value = round(value, decimals) - return value, None + # 取整和口径卡是同一个函数:卡上怎么取整的,推演就怎么取整 + return round_metric(value, plan.metric.get("decimals")), None # -------------------------------------------------------------------------- @@ -723,11 +721,10 @@ def _delta(metric: dict[str, Any], old: Any, new: Any) -> tuple[Any, str | None] """变化量和它的写法。比率、百分数的变化写「个百分点」:8.7% 到 19.0% 是多了 10.3 个百分点,不是 10.3%。""" if not (_number(old) and _number(new)): return None, None - delta = new - old decimals = metric.get("decimals") places = decimals if isinstance(decimals, int) and not isinstance(decimals, bool) else None - if isinstance(delta, float) and places is not None: - delta = round(delta, places) + # 变化量按卡上的小数位取整,规则同指标本身(round_metric):不然 8.7 到 19.0 会写成 +10.299999999999999 + delta = round_metric(new - old, places) if delta == 0: return delta, None fmt = metric.get("format") or DEFAULT_FORMAT diff --git a/backend/tests/test_recompute_followups.py b/backend/tests/test_recompute_followups.py new file mode 100644 index 00000000..a3b8a802 --- /dev/null +++ b/backend/tests/test_recompute_followups.py @@ -0,0 +1,101 @@ +"""数字推演的几处补测(期 4 打磨): + +- 取整只有一个函数:推演重算(engine/recompute.py)用的就是口径卡(engine/nodes/metrics.py)那一个,口径卡的取整 + 规则哪天改了,推演跟着变,不会一边改了、另一边还按旧的算 +- _doubt 里 moot 的那一支:一个输入既嵌在下标里、又直接参与计算,包着它的引用给了新值之后,它直接参与的那一处照常 + 拿它的值——排除行后它变没变说不准,指标仍得说不准,不能借着「嵌在里面的那一处已无关紧要」放过去 +- 决定取哪一格的单格照给行段:它自己那一行勾得了,勾掉它确定是排除后无法计算 + +夹具沿用 test_recompute 的虚构快照和卡。只导入夹具,不导入它的测试函数:导进来的 test_* 会在这里再收集一遍。 +""" +from __future__ import annotations + +import pytest + +from app.engine import recompute +from app.engine.nodes import metrics as metrics_node +from app.engine.recompute import Changes, whatif +from tests.test_recompute import AMOUNTS, FEE, REGION, S1, cell, lone, scalar, sources + +# -------------------------------------------------------------------------- +# 取整:和口径卡共用一个函数 +# -------------------------------------------------------------------------- + + +def test_the_whatif_rounds_with_the_cards_own_function(): + assert recompute.round_metric is metrics_node.round_metric + + +@pytest.mark.parametrize("value, decimals, rounded", [ + # 二进制里落在半中间的数照 Python 的 round:口径卡当时就是这么算的 + (2.675, 2, 2.67), + (0.125, 2, 0.12), + # 负的小数位:取整到十位、百位 + (1234.5, -1, 1230.0), + (-1250.0, -2, -1200.0), + # 只取整浮点:整数、文本、空值原样 + (7, 2, 7), + ("3.14159", 2, "3.14159"), + (None, 2, None), + # 没写小数位、小数位不是整数(老卡上的怪值):不取整 + (1.25, None, 1.25), + (1.25, True, 1.25), + (1.25, 1.0, 1.25), +]) +def test_round_metric_rounds_only_floats_by_an_integer_number_of_places(value, decimals, rounded): + got = metrics_node.round_metric(value, decimals) + assert got == rounded and type(got) is type(rounded) + + +# -------------------------------------------------------------------------- +# _doubt 里 moot 的那一支 +# -------------------------------------------------------------------------- + +#: 按区域取费率,区域名本身还拿来数字数。区域名是查询交回之后才算出来的(label 节点,对不上快照) +RATE = "vars.kpi.rates[vars.kpi.region]" +TWICE = lone("fee_twice", f"round({RATE} * sum(vars.kpi.amounts), 1) + len(vars.kpi.region)", + "round(0.05 * sum(vars.kpi.amounts), 1) + len('华南')", 19.0, + [scalar(RATE, 0.05), scalar("vars.kpi.region", "华南", node="label"), AMOUNTS], decimals=1) +TIMED = {"returned": {S1: 10}, "finished": {"fetch": 5, "label": 12}} + + +def test_an_input_used_directly_and_as_an_index_stays_doubted_after_the_item_has_a_new_value(): + timed = sources(**TIMED) + assert recompute.recompute(TWICE["metrics"][0], Changes(), timed)["new"] == 19.0 + # 费率给了新值:区域名嵌在下标里的那一处已无关紧要。可它还直接参与计算(len),排除行后它变没变说不准 + [fee] = whatif(TWICE, Changes(inputs={RATE: 0.1}, exclude={S1: frozenset({1})}), timed)["metrics"] + assert (fee["status"], fee["new"], fee["changed"]) == ("unsupported", None, None), fee + assert "排除行对 vars.kpi.region 的影响无法确定" in fee["reason"] + # 对照:不排除行,费率的新值照常算进去 + [fee] = whatif(TWICE, Changes(inputs={RATE: 0.1}), timed)["metrics"] + assert (fee["status"], fee["new"]) == ("ok", round(0.1 * 340.0, 1) + 2), fee + + +def test_an_index_used_only_inside_the_item_is_still_moot(): + """对照:同一个区域名只嵌在下标里(不直接参与计算)时,费率给了新值就无关紧要,按剩下的行照常算。""" + card = lone("fee_once", f"round({RATE} * sum(vars.kpi.amounts), 1)", "round(0.05 * sum(vars.kpi.amounts), 1)", 17.0, + [scalar(RATE, 0.05), scalar("vars.kpi.region", "华南", node="label"), AMOUNTS], decimals=1) + [fee] = whatif(card, Changes(inputs={RATE: 0.1}, exclude={S1: frozenset({1})}), sources(**TIMED))["metrics"] + assert (fee["status"], fee["new"]) == ("ok", round(0.1 * (340.0 - 80.0), 1)), fee + + +# -------------------------------------------------------------------------- +# 决定取哪一格的单格照给行段 +# -------------------------------------------------------------------------- + + +def test_a_cell_that_picks_the_item_still_offers_its_own_row(): + """区域那一格决定取哪一项费率:它不能改(改它要重新取数),可它自己那一行勾得了——勾掉它,取哪一项不知道, + 确定是排除后无法计算,不是说不准。""" + card = lone("fee_pick", f"{FEE} * 100", "0.05 * 100", 5.0, [scalar(FEE, 0.05), cell("pull", 1, "region", "华南")], + decimals=1) + timed = sources(returned={S1: 10}, finished={"fetch": 5}) + baseline = whatif(card, Changes(), timed) + inputs = {i["path"]: i for i in baseline["metrics"][0]["inputs"]} + assert inputs[REGION]["row_span"] == [1, 1] and inputs[REGION]["editable"] is False + assert inputs[FEE]["editable"] is True and "row_span" not in inputs[FEE] + assert [(u["input"], u["reason"]) for u in baseline["unsupported"]] == [(REGION, recompute.SELECTOR)] + [fee] = whatif(card, Changes(exclude={S1: frozenset({1})}), timed)["metrics"] + assert (fee["status"], fee["changed"]) == ("excluded", True) and "第 2 行" in fee["reason"], fee + [row] = [i for i in fee["inputs"] if i["path"] == REGION] + assert row["excluded_rows"] == [1]