双盲复算写业务日期:真写按写入时的版本重读上传表格导入时认作日期的列,几个列表块写同一张表时每一块都记为日期才算

record_choices 的表结构是写入时现读的,候选里的 upload_dates 却是发起审批时读的:审批停着时上传源换了版本、把日期列
改成文字,两份拼在一起会写出一条哪个版本单独看都不会给出的人工确认。现在候选里带 upload_dates 的,真写在读数据源的
同一个会话里按当前版本重读、覆盖候选里的那份,和表结构出自同一个版本,版本没变时预告和真写仍一字不差;候选里没有
这一项的是升级前发起的审批,卡上预告的是不写,照旧不认。

recipe_dates 以前只要有一个列表块把某列记为日期就算日期列:两个工作表的列表块写同一张表、同一列一个日期一个文字时,
表形状一样(都存成 TEXT),配方校验不拦,按文字导入的那一块存的是单元格原文。现在写这一列的块都记为日期才算。

补测试:审批停着时修改配方把支付日期改成文字,裁决后照实说按文字保存、不写;没有 upload_dates 的老候选不重读、照旧
不写,带着的按写入时的版本重读后照写;两块类型不一致的列不算日期。
This commit is contained in:
ThearchyHelios
2026-10-06 18:03:12 +08:00
parent fbcff1a585
commit 04606cfe94
3 changed files with 108 additions and 14 deletions
+23 -9
View File
@@ -47,7 +47,8 @@ is_test = 0、is_valid = 1、deleted_at IS NULL);只涉及一张表。拿不
哪一项、本来要写什么,卡上才认得出它和别的指标是不是落到同一项上。同一次裁决里几个指标落到同一项上时,写进去的是
合起来的说法(上一段),单个指标的预告说不准:preview_joint 把这几个指标各自选哪一边的每种组合都按真写的办法算一遍
(_merged 归拢、_screen 拿掉驳回的、_plan 对目录),卡上按各指标当前的选择取对应的那一种。和真写是同一套判断、同一句
原因,只有审批停下期间目录被人改了时才会和最后写的不一样。组合太多的(JOINT_LIMIT)那一项不预告,卡上有条件地说。
原因,只有审批停下期间目录被人改了、数据源换了版本时才会和最后写的不一样:真写按写入时的目录、表结构和导入时认作
日期的列判断。组合太多的(JOINT_LIMIT)那一项不预告,卡上有条件地说。
catalog.save_patch 不收备注,这里用它的同一套原料(read_entry、apply_patch、write_entry 的乐观锁)写,只多把备注放进项里。
"""
@@ -149,9 +150,10 @@ def derive(candidate: Mapping[str, Any], schema_cache: Mapping[str, Any] | None,
这个指标自己的范围:texts 是口径说明、所在分组的取值、本次运行的输入(指标名称总算在内),columns 是分组的列;有效
记录条件用它排除指标自己的筛选范围。uploaded 为真是上传表格建的数据源,upload_dates 是它导入时认作日期的列
({表名: [列名]},由 upload_dates 从配方读出):按文字保存的列在这里面的算日期列,不在的业务日期不记、原因照实说
是上传的表格按文字保存日期。两项都由节点发起审批时备好、放进候选:预告和审批之后的真写认的是同一份。schema_cache
是数据源的表结构:认表,业务日期还要看两边的列声明的类型。notes 是这个数据源的目录({表名: notes}),认码值的意思
用。只看差异说明,不重新比 SQL:审核人看到的就是这份说明。
是上传的表格按文字保存日期。两项都由节点发起审批时备好、放进候选,审批卡上的预告按它;真写时 record_choices 按
写入时的版本重读 upload_dates,和它现读的表结构出自同一个版本。schema_cache 是数据源的表结构:认表,业务日期还要
看两边的列声明的类型。notes 是这个数据源的目录({表名: notes}),认码值的意思用。只看差异说明,不重新比 SQL:
审核人看到的就是这份说明。
"""
name = str(candidate.get("metric") or "")
side = candidate.get("choice")
@@ -292,15 +294,21 @@ def recipe_dates(recipe: Any) -> dict[str, list[str]]:
就是导入确认时界面上标「日期」的那些(recipe_notes 给列写日期格式说明认的也是这两种):交叉表的日期轴(Axis.type 恒为
日期),列表块里类型记为 DATE 的列。执行器把它们一律存成 YYYY-MM-DD 的文字,表结构里只剩 TEXT。哪张表有哪几列按
recipe_types.derive_tables 推(建表用的同一份):日期轴写进它各分段的表,列表合计行另存的表只有合计项和数字列。
列表的类型按 _DATED_TYPE 认,配方以后添了日期时间也算;只有时刻的不算。"""
列表的类型按 _DATED_TYPE 认,配方以后添了日期时间也算;只有时刻的不算。几个列表块写同一张表的,这一列每一块都
记为日期才算:日期和文字都存成 TEXT,建出的表形状一样,配方校验不拦,可按文字导入的那一块存的是单元格原文。"""
from app.data.recipe_types import ListBlock, derive_tables
tables, _ = derive_tables(recipe)
listed = {(block.table, column.name) for sheet in recipe.sheets for block in sheet.blocks
if isinstance(block, ListBlock) for column in block.columns if _DATED_TYPE.fullmatch(column.type)}
listed: dict[tuple[str, str], bool] = {}
for sheet in recipe.sheets:
for block in sheet.blocks:
if isinstance(block, ListBlock):
for column in block.columns:
key = (block.table, column.name)
listed[key] = listed.get(key, True) and _DATED_TYPE.fullmatch(column.type) is not None
out: dict[str, list[str]] = {}
for table, columns in tables.items():
names = [c.name for c in columns if c.role == "axis" or (table, c.name) in listed]
names = [c.name for c in columns if c.role == "axis" or listed.get((table, c.name), False)]
if names:
out[table] = list(dict.fromkeys(names))
return out
@@ -806,7 +814,8 @@ async def record_choices(candidates: list[Mapping[str, Any]], *, run_id: str, no
进去,都落在 skipped 里照实说。
先把每个候选认成目录项,再按(数据源、表、项)归拢成一项(_merged:说法一样的、有效记录条件合起来写,说法
不同的整组不写),逐项写(_write:按读到的目录先拿掉各自带回驳回说法的指标,其余的照写)。"""
不同的整组不写),逐项写(_write:按读到的目录先拿掉各自带回驳回说法的指标,其余的照写)。认目录项用的表结构、
目录、上传表格导入时认作日期的列(upload_dates)都按写入时数据源的现状读。"""
skipped: list[dict[str, Any]] = []
facts: list[Fact] = []
for candidate in candidates:
@@ -818,6 +827,11 @@ async def record_choices(candidates: list[Mapping[str, Any]], *, run_id: str, no
skipped.append({"reason": f"数据源「{name}」已不存在,指标「{candidate.get('metric')}」的选择未写入数据目录"})
continue
notes = {table: entry.notes for table, entry in (await catalog.read_catalog(session, row.id)).items()}
if "upload_dates" in candidate:
# 表结构是这里现读的,导入时认作日期的列也按写入时的当前版本重读:审批停着时换了版本(日期列改成了
# 文字),拿发起审批时读的那份去配新的表结构,会写出一条哪个版本单独看都不会给出的人工确认。候选里
# 没有这一项的是升级前发起的审批,卡上预告的是不写,照旧不认
candidate = {**candidate, "upload_dates": await upload_dates(session, row)}
fact, why = derive(candidate, row.schema_cache, notes)
except Exception: # noqa: BLE001 - 目录读不出来不能毁掉审批的结果:缺口照样按选择记
logger.exception("双盲复算的选择核对数据目录失败(数据源 %s)", name)
+2 -1
View File
@@ -1168,7 +1168,8 @@ async def _source_info(sources: _Sources, name: str) -> dict[str, Any]:
"""比较两条 SQL、预告目录写入要用的:方言、表结构、列的中文名、整份数据目录,以及是不是上传表格建的数据源
(uploaded:导入时日期一律存成文字)和它导入时认作日期的列(upload_dates,按当前版本的配方读,见
dual_check_facts.upload_dates)——业务日期据此认上传表格的日期列,认不出的原因照实说(_dated_problem)。两项都进
候选:审批卡的预告和裁决后的真写认的是发起审批时读的这一份。数据源没了就都不给,照样比原文。"""
候选:审批卡的预告按发起审批时读的这一份;裁决后的真写按写入时的版本重读 upload_dates,和现读的表结构一起以写入时
为准(dual_check_facts.record_choices)。数据源没了就都不给,照样比原文。"""
from app.data import catalog
from app.data.sql_semantics import catalog_labels
+83 -4
View File
@@ -5,8 +5,10 @@
- 配方里是日期的两列(列表块里类型为 DATE 的列、交叉表的日期轴):审核人选了哪一边,业务日期就记哪一列;审批卡的预告
和真写一字不差
- 配方里是文字的列不写;配方读不出来(简单导入没有配方、配方记录坏了)的照旧不写,原因都照实说是上传的表格按文字保存
- 只认数据源当前版本的配方:表结构出自同一个版本
- 配方里是文字的列不写;配方读不出来(简单导入没有配方、配方记录坏了)的照旧不写,原因都照实说是上传的表格按文字保存;
几个列表块写同一张表的,这一列每一块都记为日期才算
- 只认数据源当前版本的配方:表结构出自同一个版本。审批停着时数据源换了版本,真写按写入时的版本重读(和表结构一样以
写入时为准);升级前发起的审批(候选里没有 upload_dates)不重读,照它审批卡上的预告不写
数据源一律经真实的导入接口建(暂存 → 改配方 → 试运行 → 提交,或者简单导入),工作簿是现造的:表名、地区、金额都是
虚构的。盲算模型是 MockChatModel 剧本(tests/fixtures/dual_check_shop.Blind)。
@@ -23,11 +25,12 @@ from httpx import ASGITransport, AsyncClient
from openpyxl import Workbook
from sqlalchemy import delete, select
from app.data.recipe_types import Recipe
from app.data.recipe_types import Recipe, derive_tables
from app.data.sql_semantics import explain_sql_diff
from app.db.base import SessionLocal
from app.db.models import DataSource, Setting, SourceSnapshot, TableRecipe
from app.engine import spend
from app.engine.dual_check_facts import recipe_dates, upload_dates
from app.engine.dual_check_facts import recipe_dates, record_choices, upload_dates
from app.engine.runner import run_manager
from app.main import app
from tests.fixtures.dual_check_shop import ROWS, Blind
@@ -174,6 +177,28 @@ def test_the_axis_of_a_crosstab_is_a_date_column_of_every_table_it_writes():
"日客流": ["日期"], "时段客流": ["日期"], "时段客流_表内合计": ["日期"]}
def test_a_column_two_lists_type_differently_is_not_a_date():
"""两个工作表的列表块写同一张表,支付日期一块记为「日期」、一块记为「文字」:两块建出的表形状一样(日期也存成文字),
配方校验不拦,可按文字导入的那一块存的是单元格原文(「待定」这类),这一列并不都是日期。写这一列的块都记为日期
才算,拿不准就不认;两块都记为日期的下单日期照常认。"""
recipe = list_recipe()
february = json.loads(json.dumps(recipe["sheets"][0]))
february["id"], february["match"] = "s2", {"name": "二月"}
february["blocks"][0]["id"] = "orders_feb"
for column in february["blocks"][0]["columns"]:
if column["name"] == "支付日期":
column["type"] = "TEXT"
recipe["sheets"].append(february)
parsed = Recipe.model_validate(recipe)
assert derive_tables(parsed)[1] == [], "背景:两块写成的表形状一样,不报冲突"
assert recipe_dates(parsed) == {TABLE: ["下单日期"]}
# 两块都记为日期:照常认两列
both = list_recipe()
both["sheets"].append({**json.loads(json.dumps(both["sheets"][0])), "id": "s2", "match": {"name": "二月"}})
both["sheets"][1]["blocks"][0]["id"] = "orders_feb"
assert recipe_dates(Recipe.model_validate(both)) == {TABLE: ["下单日期", "支付日期"]}
def test_a_list_total_kept_as_a_table_has_no_date_column():
"""列表的合计行另存成表时只有合计项和数字列:日期列不在里面。"""
recipe = list_recipe()
@@ -313,3 +338,57 @@ async def test_without_a_readable_recipe_nothing_is_written(monkeypatch, client,
[wrote] = logs(await events(run.id), "dual_check_catalog")
assert wrote["written"] == [] and [s["reason"] for s in wrote["skipped"]] == [said["a"]["reason"]]
assert await notes_of(source_id, TABLE) is None
# --------------------------------------------------------------------------
# 审批停着时数据源换了版本:真写按写入时的版本认
# --------------------------------------------------------------------------
async def test_a_new_version_while_waiting_is_what_the_write_reads(monkeypatch, client, dated):
"""审批停着时修改配方、把支付日期改成「文字」并提交成新版本:真写时表结构是现读的,导入时认作日期的列也按写入时的
当前版本重读,两者出自同一个版本。审批卡上预告会记「支付日期」,裁决后照实说按文字保存、不写——不拿发起审批时读的
配方去配新版本的表结构,写出一条哪个版本单独看都不会给出的人工确认。"""
name, source_id = dated
Blind(monkeypatch, name, {"销售额": (RIGHT, "gmv")})
run = await start(upload_graph(name, BY_ORDER_DATE))
assert run.status == "interrupted", run.error
[item] = (await pending(run.id)).payload["summary"]
assert item["catalog"]["b"]["write"] is True, "背景:发起审批时两列在配方里都是日期"
r = await client.post(f"{API}/{source_id}/redraft", json={})
assert r.status_code == 201, r.text
await commit_recipe(client, r.json()["id"], list_recipe(paid="TEXT"))
assert await dates_of(source_id) == {TABLE: ["下单日期"]}
done = await decide(client, run.id, {"gmv": "b"})
assert done.status == "succeeded", done.error
[wrote] = logs(await events(run.id), "dual_check_catalog")
assert wrote["written"] == []
assert [s["reason"] for s in wrote["skipped"]] == [
f"指标「销售额」被采纳的盲算按时间筛的列「{TABLE}.支付日期」{STORED_AS_TEXT},不写入数据目录"]
assert await notes_of(source_id, TABLE) is None
async def candidate_of(name: str, source_id: str, choice: str) -> dict:
"""真写收到的候选(节点从 checkpoint 里取出、加上审核人的选择):差异说明按数据源的表结构真算。"""
async with SessionLocal() as session:
schema = (await session.get(DataSource, source_id)).schema_cache
diff = explain_sql_diff(BY_ORDER_DATE, RIGHT, "sqlite", schema=schema, labels=("原流程", "盲算")).as_dict()
return {"metric_id": "gmv", "metric": "销售额", "source": name, "dialect": "sqlite", "uploaded": True,
"sql": {"a": BY_ORDER_DATE, "b": RIGHT}, "diff": diff, "choice": choice}
async def test_a_checkpoint_without_the_dates_is_written_as_its_card_said(client, dated):
"""升级前发起的审批,checkpoint 的候选里没有 upload_dates:它的审批卡预告的是按文字保存、不写,真写不重读配方,照旧
不写,和那张卡说的一致。候选里带着这一项的(升级后发起的)按写入时的版本重读:发起审批时读出来是空的,写入时配方里
两列都是日期,照写——和表结构、目录在审批期间变了一样,以写入时为准。"""
name, source_id = dated
old = await candidate_of(name, source_id, "b")
assert [i["aspect"] for i in old["diff"]["items"]] == ["time"], "背景:两边只差按哪一列筛时间"
result = await record_choices([old], run_id="run_old", node_title="复核", actor=None)
assert result["written"] == []
assert [s["reason"] for s in result["skipped"]] == [
f"指标「销售额」被采纳的盲算按时间筛的列「{TABLE}.支付日期」{STORED_AS_TEXT},不写入数据目录"]
result = await record_choices([{**old, "upload_dates": {}}], run_id="run_new", node_title="复核", actor=None)
assert result["skipped"] == []
assert result["written"] == [
{"source": name, "table": TABLE, "item": "business_date", "value": {"column": "支付日期"}}]