端到端验收修复与指标出具:

- 身份与工具:登录页建第一个管理员(认人接口的 401 说明能不能建);搭建者有只读的人和组名录,选人给候选并核对名字;授权三行带标题;端点请求头名校验(空名、非法名存不进、发不出时说清原因);写入能力在工具页试运行一律演练、不发送,HTTP 状态照实说成败;写记忆不算只读、查询能力只能选同一端点上的只读能力;审批与遮罩的说法和实际规则一致;开登录时不要署名、导入和发布记登录的人;使用者不显示推演等只给搭建者的操作,403 按是否开登录说话;登录页只认一次人
- 流程与实例:图里用到的岗位(派给谁、超时升级给谁、发送确认派给谁)全部派生、没绑人的发布时报错;写外部系统的参数按能力声明的类型收拢后再算哈希和发送,收不成就不发;发起人的实例页只看这一步的状态,处理人才给待办卡;会签进度带登录核实和时间,升级后照实写规则;实例状态写流程的结论(已退回、未确认、等待核实写入结果),核实生效后不再挂失败原因;流程应用首页不派生最近封存运行的结果块,看板没数据时是安静的空态;样例⑩的金额带类型和下限、待办标题带金额,表单上下限前后端一起生效
- 看板与证据:定时任务模板加 ISO 周、上一 ISO 周、本月、上月;出处链穿过原样解析查询结果的整形节点,追不到原始数据的照实说停在哪里,样例⑨改用 cell();应用首页和版本历史都能做成应用;指标块单位不重复;版本列表带退役说明;定时任务页头跟着刷新;删视图要确认、新视图能起名;编辑器属性用中文名、术语带解释
- 指标出具(用户 2026-10-15 拍板):契约只写「指标来自」、上游没有报告撰写节点、成果里没有模型写的话时按指标出具——必需指标齐、指标输入追到原始数据、成果字段里的数回指得上才完整出具;受管级要求每个指标静态地追到原始数据(governed.metric_untraced);出具横幅和应用印章写明按指标
- 受管工作流降为已发布只给管理员(Q8 顺延,服务端同样拦);工作流接口带当前发布版的级别,画布上改过之后也认得出受管工作流
This commit is contained in:
ThearchyHelios
2026-10-15 07:15:37 +08:00
parent 5d42ffb62b
commit 941723b17c
116 changed files with 4917 additions and 631 deletions
+1 -1
View File
@@ -74,7 +74,7 @@ def endpoint_request_for(erp: FakeErp, *, lookup_capability: str = "erp_lookup")
async def fake(session: Any, capability: Any, args: dict[str, Any], *, environment: str,
idem_key: str | None = None, on_behalf: str | None = None, run_id: str | None = None,
node_id: str | None = None) -> EndpointResult:
node_id: str | None = None, tool: Any = None) -> EndpointResult:
if environment == "simulated":
return EndpointResult(status=None, body={"simulated": True}, environment="simulated")
if capability.name == lookup_capability:
+44
View File
@@ -0,0 +1,44 @@
"""组件目录(app/apps/catalog.py)的 props 写给人看的中文名。
- 每个组件的每一项 props 都有 title,而且是中文:应用编辑的属性面板按它写属性名,不露 label、chart、sort 这些键名
- 枚举都有 x-enum-labels,和 enum 一一对应(同表单 agentlab.form/1 的写法),选项不露 line / bar
- title、description、x-enum-labels 只是注解:校验照旧,取值不对的照样报 app.props_invalid
"""
from __future__ import annotations
import re
from jsonschema import Draft202012Validator
from app.apps.catalog import BY_NAME, COMPONENTS, catalog_payload
_CJK = re.compile(r"[㐀-鿿]")
def test_every_prop_has_a_chinese_title():
missing = [(c["name"], key) for c in COMPONENTS for key, prop in c["props"]["properties"].items()
if not (isinstance(prop.get("title"), str) and _CJK.search(prop["title"]))]
assert missing == []
# 接口交出去的就是这一份
assert catalog_payload()["components"][0]["props"]["properties"]["title"]["title"] == "标题"
def test_enums_have_labels_in_the_same_order():
enums = [(c["name"], key, prop) for c in COMPONENTS for key, prop in c["props"]["properties"].items() if "enum" in prop]
assert enums, "目录里应当有枚举属性"
for name, key, prop in enums:
labels = prop.get("x-enum-labels")
assert isinstance(labels, list) and len(labels) == len(prop["enum"]), (name, key)
assert all(isinstance(t, str) and _CJK.search(t) for t in labels), (name, key)
assert BY_NAME["series"]["props"]["properties"]["chart"]["x-enum-labels"] == ["折线图", "柱状图"]
def test_annotations_do_not_change_validation():
schema = BY_NAME["notice"]["props"]
assert not list(Draft202012Validator(schema).iter_errors({"text": "说明", "tone": "warn"}))
errors = list(Draft202012Validator(schema).iter_errors({"tone": "提醒"}))
assert [list(e.absolute_path) for e in errors] == [["tone"]]
table = BY_NAME["table"]["props"]
assert not list(Draft202012Validator(table).iter_errors({"title": "门店", "sort": "-gmv", "limit": 20}))
assert list(Draft202012Validator(table).iter_errors({"limit": 0}))
assert list(Draft202012Validator(table).iter_errors({"unknown": 1}))
+34
View File
@@ -99,6 +99,40 @@ def test_input_fields_become_a_form():
assert validate_form_schema(form) == []
def test_number_bounds_carry_into_the_form_and_are_enforced():
"""数字字段的上下限带进表单(只带数字类型、写成数的);服务端校验照它拦,前端同一份子集(lib/schemaForm.ts)照它拦。"""
form = input_schema([
{"name": "amount", "type": "number", "minimum": 0.01, "maximum": 50000, "required": True},
{"name": "count", "type": "integer", "minimum": 1},
{"name": "note", "minimum": 3},
{"name": "bad", "type": "number", "minimum": "零"},
])
props = form["properties"]
assert (props["amount"]["minimum"], props["amount"]["maximum"]) == (0.01, 50000) and props["count"]["minimum"] == 1
assert "minimum" not in props["note"] and "minimum" not in props["bad"]
assert validate_form_schema(form) == []
assert [e["code"] for e in validate_form(form, {"amount": -5})] == ["minimum"]
assert [e["code"] for e in validate_form(form, {"amount": 0})] == ["minimum"]
assert validate_form(form, {"amount": 60000})[0]["message"] == "「amount」不能大于 50000"
assert validate_form(form, {"amount": 0.01, "count": 1}) == []
def test_the_seeded_expense_template_refuses_a_negative_amount():
"""样例⑩:金额是数、不能小于 0.01(表单子集没有 exclusiveMinimum,「大于 0」写成 0.01);待办标题带上金额。"""
from app.apps.tree import input_fields
from app.seed import TEMPLATES
template = next(t for t in TEMPLATES if t["name"] == "⑩ 报销审批(会签)")
form = input_schema(input_fields({"nodes": template["nodes"]}))
assert form["properties"]["amount"] == {"type": "number", "title": "amount", "description": "金额(元)",
"minimum": 0.01}
assert validate_form(form, {"applicant": "钱七", "amount": -5, "reason": "出差"})[0]["code"] == "minimum"
assert validate_form(form, {"applicant": "钱七", "amount": "很多", "reason": "出差"})[0]["code"] == "type"
assert validate_form(form, {"applicant": "钱七", "amount": 1280.5, "reason": "出差"}) == []
review = next(n for n in template["nodes"] if n["id"] == "review")["data"]["config"]
assert "{{ input.amount }}" in review["title"] and "{{ input.amount }}" in review["message"]
# --------------------------------------------------------------------------
# 表达式
# --------------------------------------------------------------------------
+239
View File
@@ -0,0 +1,239 @@
"""流程应用的实例页和待办怎么说(apps/resolve.py 的流程组件、process/tasks.py 的待办描述)。
端到端验收(报销审批:财务会签、超时升级给总监)发现的几处「说得不对」:
- 发起人打开实例页,待办表单去取一条不是派给他的待办,红框写「待办不存在」:服务端解析时就判定读者是不是处理人,
不是的只给这一步的状态(派给了谁、会签进度、时限),不让界面去取;
- 会签进度把登录核实过的审批人写成「自报署名」、没有处理时间:页面解析给的派给谁要带上这两项;
- 同意过的人再打开写「没有派给你」:待办上带这个人的回复,写「你已处理」;
- 走了「已退回」分支的实例写「已完成」:实例的状态说流程走到了哪个成果节点;
- 升级之后写「0/3 已同意」,其实总监一人同意就通过:会签人数不算升级加派的那一份,升级后的规则单列;
- 同一个人两笔报销,待办列表里标题一样分不开:待办带上实例标题和开出的时间。
"""
from __future__ import annotations
import asyncio
import uuid
from datetime import timedelta
import pytest
from sqlalchemy import select
from app.api.deps import Principal
from app.db.base import SessionLocal, utcnow
from app.db.models import App, AppVersion, Group, GroupMember, Run, Task, User
from app.engine.runner import run_manager
from app.process import tasks
@pytest.fixture(autouse=True)
async def engine_up():
await run_manager.setup()
yield
await run_manager.shutdown()
def node(nid, ntype, label=None, **config):
return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": label or nid, "config": config}}
def expense() -> dict:
nodes = [node("start", "input", "发起报销", fields=[{"name": "applicant"}, {"name": "amount", "type": "number"}]),
node("review", "human", "财务会签", mode="approve", title="报销审批:{{ input.applicant }}",
assignee={"kind": "slot", "slot": "finance"}, policy="all", due="PT1H",
on_timeout={"action": "escalate", "to_slot": "director"}),
node("ok", "output", "已通过", fields=[{"name": "结论", "value": "已通过"}]),
node("no", "output", "已退回", fields=[{"name": "结论", "value": "已退回"}])]
edges = [{"source": "start", "target": "review"},
{"source": "review", "target": "ok", "sourceHandle": "approved"},
{"source": "review", "target": "no", "sourceHandle": "rejected"}]
return {"nodes": nodes, "edges": edges}
SPEC = {"format": "agentlab.app/1", "name": "报销", "pages": [{"id": "instance", "title": "实例", "body": [
{"id": "hdr", "type": "instance_header"}, {"id": "tl", "type": "instance_timeline"},
{"id": "form", "type": "task_form", "bind": {"task": "review"}},
{"id": "signs", "type": "signoffs", "bind": {"task": "review"}},
{"id": "mine", "type": "task_list", "props": {"scope": "mine"}}]}]}
def user(name: str) -> Principal:
return Principal(username=name, role="user", mode="local", verified=True)
async def _wait(run_id: str, statuses: tuple[str, ...], timeout: float = 20.0) -> Run:
deadline = asyncio.get_event_loop().time() + timeout
while asyncio.get_event_loop().time() < deadline:
async with SessionLocal() as session:
row = await session.get(Run, run_id)
if row and row.status in statuses and not run_manager.is_active(run_id):
return row
await asyncio.sleep(0.05)
raise AssertionError(f"运行 {run_id} 没有进入 {statuses}")
async def _setup() -> tuple[str, str, str, str]:
"""一个应用:财务岗位绑一个组(两个人),总监岗位绑一个人。返回 (应用 id, 财务甲, 财务乙, 总监)。"""
u = uuid.uuid4().hex[:6]
a, b, boss, group = f"zhang{u}", f"wang{u}", f"zhao{u}", f"finance{u}"
async with SessionLocal() as session:
people = [User(username=n, role="user") for n in (a, b)]
session.add_all(people)
g = Group(name=group)
session.add(g)
await session.flush()
session.add_all([GroupMember(group_id=g.id, user_id=p.id) for p in people])
app = App(name=f"报销-{u}", published_version=1)
session.add(app)
await session.flush()
session.add(AppVersion(app_id=app.id, version=1, spec=SPEC, spec_hash="x" * 64, bindings={"slots": {
"finance": [{"kind": "group", "name": group}], "director": [{"kind": "user", "name": boss}]}}))
await session.commit()
return app.id, a, b, boss
async def _start(app_id: str, title: str, amount: float = 1280.5) -> str:
run = await run_manager.start(graph=expense(), input_payload={"applicant": "钱七", "amount": amount},
app_id=app_id, app_version=1, started_by="qianqi", run_class="formal",
origin_kind="app_entry", origin={"entry": "start", "title": title})
await _wait(run.id, ("interrupted",))
return run.id
async def _task(run_id: str) -> Task:
async with SessionLocal() as session:
return (await session.execute(select(Task).where(Task.run_id == run_id))).scalars().one()
async def _page(app_id: str, run_id: str, reader: Principal) -> dict:
from app.apps.resolve import resolve_page
async with SessionLocal() as session:
app = await session.get(App, app_id)
version = (await session.execute(select(AppVersion).where(AppVersion.app_id == app_id))).scalars().one()
run = await session.get(Run, run_id)
vm = await resolve_page(session, app, page_id="instance", principal=reader, role="use", instance=run,
version=version)
return {n["id"]: n.get("data") for n in vm["tree"]}
async def test_the_initiator_sees_the_step_not_a_missing_task():
app_id, a, b, _ = await _setup()
run_id = await _start(app_id, "报销审批·钱七")
task = await _task(run_id)
view = await _page(app_id, run_id, user("qianqi"))
form = view["form"]
# 发起人不是处理人:不让界面去取待办(取了是 404),给这一步的状态
assert form["handler"] is False
assert sorted((x["principal"], x["status"]) for x in form["assignments"]) == \
sorted([(a, "pending"), (b, "pending")])
assert form["progress"] == {"policy": "all", "voters": 2, "need": 2, "agreed": 0, "rejected": 0}
assert form["task"]["due_at"] and form["task"]["instance_title"] == "报销审批·钱七"
assert tasks.visible(await tasks.detail(task.id, user("qianqi")), user("qianqi")) is False
# 处理人:给待办卡(界面按 id 取完整的待办)
assert (await _page(app_id, run_id, user(a)))["form"]["handler"] is True
# 关登录时人人都算处理人(同待办服务)
assert (await _page(app_id, run_id, Principal(username=None, role="admin", mode="off")))["form"]["handler"] is True
hdr = view["hdr"]
assert (hdr["status_code"], hdr["status_text"]) == ("waiting", "等待审批")
assert next(s for s in view["tl"]["steps"] if s["node"] == "review")["text"] == "等待审批"
async def test_signoffs_say_who_verified_and_when_and_the_voter_sees_their_own_answer():
app_id, a, b, _ = await _setup()
run_id = await _start(app_id, "报销审批·钱七")
task = await _task(run_id)
assert (await tasks.respond(task.id, user(a), decision="approve"))["resolved"] is False
signs = (await _page(app_id, run_id, user("qianqi")))["signs"]
done = next(x for x in signs["assignments"] if x["principal"] == a)
# 登录核实过的写「已登录核实」,不是「自报署名」;带处理时间
assert done["status"] == "responded" and done["verified"] is True and done["responded_at"]
assert done["decision"] == "approve" and done["source"] == "slot:finance"
assert signs["progress"]["agreed"] == 1 and signs["progress"]["need"] == 2
# 同意过的人再打开:不能再回复,带上他的回复(写「你已处理:同意」,不写「没有派给你」)
mine = await tasks.detail(task.id, user(a))
assert mine["can_respond"] is False and mine["my_response"]["decision"] == "approve"
assert mine["my_response"]["at"] and mine["my_response"]["verified"] is True
assert (await tasks.detail(task.id, user(b)))["my_response"] is None
assert (await _page(app_id, run_id, user(a)))["form"]["my_response"]["decision"] == "approve"
async def test_the_instance_says_which_outcome_it_reached():
app_id, a, b, _ = await _setup()
passed = await _start(app_id, "报销审批·钱七")
task = await _task(passed)
await tasks.respond(task.id, user(a), decision="approve")
await tasks.respond(task.id, user(b), decision="approve")
await _wait(passed, ("succeeded",))
view = await _page(app_id, passed, user("qianqi"))
assert (view["hdr"]["status_code"], view["hdr"]["status_text"]) == ("succeeded", "已通过")
review = next(s for s in view["tl"]["steps"] if s["node"] == "review")
assert (review["state"], review["text"]) == ("done", "已同意")
back = await _start(app_id, "报销审批·钱七")
await tasks.respond((await _task(back)).id, user(b), decision="reject", note="票据不全")
await _wait(back, ("succeeded",))
view = await _page(app_id, back, user("qianqi"))
# 走了退回分支:运行是「已完成」,流程的结论是「已退回」
assert (view["hdr"]["status_code"], view["hdr"]["status_text"]) == ("succeeded", "已退回")
assert next(s for s in view["tl"]["steps"] if s["node"] == "review")["text"] == "已驳回"
# 判定之后没回复的都撤回了:会签人数按判定那一刻的算,不缩成 1
assert view["signs"]["progress"] == {"policy": "all", "voters": 2, "need": 2, "agreed": 0, "rejected": 1}
from app.apps.resolve import list_instances
async with SessionLocal() as session:
rows = {r["run_id"]: r for r in await list_instances(session, app_id, mine="qianqi")}
assert (rows[back]["status_text"], rows[passed]["status_text"]) == ("已退回", "已通过")
async def test_outputs_reached_in_parallel_are_not_one_outcome():
"""几个成果节点并行都走到了(「周报」「明细」一起出):那不是哪一种结局,写「已完成」,不写最后走到的那个节点的名字。"""
from app.apps.resolve import instance_rows
graph = {"nodes": [node("start", "input", "发起", fields=[{"name": "week"}]),
node("weekly", "output", "周报", fields=[{"name": "周", "value": "{{ input.week }}"}]),
node("detail", "output", "明细", fields=[{"name": "周", "value": "{{ input.week }}"}])],
"edges": [{"source": "start", "target": "weekly"}, {"source": "start", "target": "detail"}]}
run = await run_manager.start(graph=graph, input_payload={"week": "2026-W41"})
done = await _wait(run.id, ("succeeded", "failed"))
assert done.status == "succeeded", done.error
async with SessionLocal() as session:
[row] = await instance_rows(session, [await session.get(Run, run.id)])
assert (row["status_code"], row["status_text"]) == ("succeeded", "已完成")
async def test_after_escalation_the_rule_is_one_director_not_zero_of_three():
app_id, a, b, boss = await _setup()
run_id = await _start(app_id, "报销审批·钱七")
task = await _task(run_id)
await tasks.respond(task.id, user(a), decision="approve")
assert await tasks.tick(utcnow() + timedelta(hours=2)) >= 1
detail = await tasks.detail(task.id, user(boss))
p = detail["progress"]
# 升级加派的那一份不算进会签人数:还是 1/2,另写升级给了谁、他一人说了算
assert (p["voters"], p["need"], p["agreed"]) == (2, 2, 1)
assert p["escalation"] == {"slot": "director", "assignees": [{"kind": "user", "name": boss}], "decided": None,
"by": None}
assert detail["can_respond"] is True
assert (await tasks.respond(task.id, user(boss), decision="approve"))["resolved"] is True
await _wait(run_id, ("succeeded",))
p = (await tasks.detail(task.id, user(boss)))["progress"]
assert (p["voters"], p["agreed"]) == (2, 1) and (p["escalation"]["decided"], p["escalation"]["by"]) == \
("approve", boss)
signs = (await _page(app_id, run_id, user("qianqi")))["signs"]
assert signs["progress"]["escalation"]["by"] == boss
async def test_tasks_with_the_same_title_carry_the_instance_and_when():
app_id, a, _, _ = await _setup()
first = await _start(app_id, "报销审批·钱七·第一笔")
second = await _start(app_id, "报销审批·钱七·第二笔", amount=300)
listed = [t for t in await tasks.list_tasks(user(a), app_id=app_id)]
assert [t["title"] for t in listed] == ["报销审批:钱七", "报销审批:钱七"]
assert {t["run_id"]: t["instance_title"] for t in listed} == {first: "报销审批·钱七·第一笔",
second: "报销审批·钱七·第二笔"}
rows = (await _page(app_id, first, user(a)))["mine"]["items"]
assert {r["instance_title"] for r in rows} == {"报销审批·钱七·第一笔", "报销审批·钱七·第二笔"}
assert all(r["created_at"] for r in rows)
+8 -1
View File
@@ -259,6 +259,10 @@ async def test_dashboard_app_on_a_schedule(client, source):
res = await client.post(f"/api/workflows/{wf_id}/versions/1/retire", json={"note": "改按支付日"})
assert res.status_code == 200, res.text
assert [a["app_id"] for a in res.json()["affected_apps"]] == [old_app]
# 版本列表照样给退役的人、时间和说明:版本历史的列表里直接看得到,不用逐个点开
listed = {v["version"]: v for v in (await client.get(f"/api/workflows/{wf_id}/versions")).json()}
assert listed[1]["retired_at"] and listed[1]["retire_note"] == "改按支付日" and "retired_by" in listed[1]
assert listed[2]["retired_at"] is None and listed[2]["retire_note"] is None
apps = {a["id"]: a for a in (await client.get("/api/apps")).json()["items"]}
assert apps[old_app]["needs_upgrade"] is True and apps[app_id]["needs_upgrade"] is False
assert apps[app_id]["my_role"] == "manage"
@@ -301,7 +305,10 @@ async def test_a_draft_preview_reads_sealed_runs_without_launching(client, sourc
vm = (await client.get(f"/api/apps/{app_id}/pages/home", params={"draft": 1})).json()
assert vm["app"]["version"] == 0 and vm["sources"]["latest"]["state"] == "empty"
assert vm["sources"]["od"]["state"] == "empty"
assert {p["code"] for p in vm["problems"]} == {"view.source_empty"}
# 还没有数据是安静的空态,不进「无法显示」;印章上写明还没有、什么时候会有
assert vm["problems"] == []
assert vm["sources"]["latest"]["message"].startswith("还没有数据:") and "正式运行成功并封存后" in \
vm["sources"]["latest"]["message"]
async with SessionLocal() as session:
after = len((await session.execute(select(Run.id).where(Run.workflow_id == wf_id))).all())
assert after == before, "草稿预览不该发起运行"
+123 -1
View File
@@ -325,7 +325,10 @@ async def test_derive_a_process_leaves_slots_empty(monkeypatch):
spec = await derive_app(session, wf, 1, name="报销审批")
assert spec["name"] == "报销审批" and spec["pins"][0]["use"] == "process"
assert spec["slots"] == {"finance": {"label": "finance"}, "reconciler": {"label": "动作核实"}}
assert spec["views"]["latest"]["source"]["from"] == "formal" and spec["views"]["inst"]["source"]["kind"] == "instance"
# 流程的首页只放发起和我发起的:结果在实例页看,不派生「最近封存运行」(派生出来只会挂一块永远空着的印章)
assert "latest" not in spec["views"] and spec["views"]["inst"]["source"]["kind"] == "instance"
home = next(p for p in spec["pages"] if p["id"] == "home")
assert [c["type"] for c in home["body"]] == ["entry_button", "instance_list"]
inst = next(p for p in spec["pages"] if p["id"] == "instance")
assert {"task_form", "signoffs", "action_status", "instance_header"} <= {c["type"] for c in inst["body"]}
assert spec["task_ui"] == {"check": {"title": "财务审批"}}
@@ -335,6 +338,125 @@ async def test_derive_a_process_leaves_slots_empty(monkeypatch):
assert {"app.slot_unbound", "app.reconciler_unbound"} <= codes(issues, "error")
async def test_an_empty_dashboard_says_when_data_will_come():
"""看板还没有封存运行:不是解析出错,写明还没有数据、什么时候会有(定时任务下次运行的时间,或者要等一次正式运行)。"""
from datetime import datetime, timezone
from app.apps.pins import load_pins
from app.apps.resolve import _empty_text
wf, info = await make_workflow(weekly())
async with SessionLocal() as session:
on = Schedule(name="周一早上", workflow_id=wf, cron="0 9 * * 1", timezone="Asia/Shanghai", run_class="formal",
next_run_at=datetime(2026, 10, 19, 1, 0, tzinfo=timezone.utc))
paused = Schedule(name="停着的", workflow_id=wf, cron="0 9 * * 1", timezone="Asia/Shanghai",
run_class="formal", enabled=False)
session.add_all([on, paused])
await session.commit()
state = (await load_pins(session, base_spec(wf, info)))["main"]
assert "定时任务「周一早上」下一次在 2026-10-19" in await _empty_text(session, state, f"schedule:{on.id}")
assert "定时任务「停着的」已停用" in await _empty_text(session, state, f"schedule:{paused.id}")
assert "已删除" in await _empty_text(session, state, "schedule:gone")
assert (await _empty_text(session, state, "formal")).endswith(f"「{info['name']} v1」有一次正式运行成功并封存后这里就有数")
def test_slot_refs_cover_every_place_a_graph_names_a_slot():
"""派给谁、超时升级给谁、动作确认派给谁,加上节点上没写、取图级 defaults 的:派生和检查认的是同一份。调用工具节点只有
写入的(会开发送确认卡)才算用到岗位:只读的写了派给谁、或者从 defaults 继承来的,都不算。"""
from app.apps.tree import slot_refs
graph = chain(
node("a", "human", "财务会签", assignee={"kind": "slot", "slot": " finance "}, due="PT1H",
on_timeout={"action": "escalate", "to_slot": "director"}),
node("b", "human", "复核"),
node("pay", "tool", "付款", tool="erp_pay", assignee={"kind": "slot", "slot": "cashier"}),
node("fetch", "tool", "取数", tool="erp_orders", assignee={"kind": "slot", "slot": "clerk"}),
node("sync", "tool", "同步", tool="erp_sync"),
node("c", "human", "补材料", assignee={"kind": "initiator"}, due="PT1H",
on_timeout={"action": "remind", "to_slot": "不算"}),
)
graph["defaults"] = {"assignee": {"kind": "slot", "slot": "auditor"}}
assert [(r["slot"], r["node_id"], r["role"]) for r in slot_refs(graph, {"pay", "sync"})] == [
("finance", "a", "assignee"), ("director", "a", "escalation"), ("auditor", "b", "assignee"),
("cashier", "pay", "confirm"), ("auditor", "sync", "confirm")]
# 没有写入节点:调用工具节点一个都不算
assert [r["node_id"] for r in slot_refs(graph)] == ["a", "a", "b"]
async def test_read_only_tool_nodes_do_not_use_slots_and_writes_follow_the_runtime_rule(monkeypatch):
"""只读的调用工具节点从不开确认卡:它写的派给谁(或图级默认的)不派生岗位、检查也不说「发送确认派给它」。哪些是写入
和运行时同一个认法(writes_externally):绑定端点、视参数而定的也是写入,要动作状态、要人核实。"""
from types import SimpleNamespace
from app.capabilities import registry
caps = {"erp_pay": SimpleNamespace(effect="write", endpoint_id=None, lookup="erp_lookup"),
"erp_orders": SimpleNamespace(effect="read", endpoint_id="ep-1", lookup=None),
"erp_sync": SimpleNamespace(effect="dynamic", endpoint_id="ep-1", lookup=None)}
async def get_capability(session, name):
return caps.get(name)
monkeypatch.setattr(registry, "get_capability", get_capability)
graph = chain(
node("start", "input", "开始", fields=[{"name": "amount", "type": "number", "required": True}]),
node("fetch", "tool", "取数", tool="erp_orders", args={}, assignee={"kind": "slot", "slot": "clerk"}),
node("check", "human", "财务审批", mode="approve", assignee={"kind": "slot", "slot": "finance"}),
node("pay", "tool", "付款", tool="erp_pay", args={}),
node("sync", "tool", "同步", tool="erp_sync", args={}),
node("out", "output", "成果", fields=[{"name": "r", "value": "完成"}]),
)
graph["defaults"] = {"assignee": {"kind": "slot", "slot": "cashier"}}
wf, _ = await make_workflow(graph)
async with SessionLocal() as session:
spec = await derive_app(session, wf, 1)
assert set(spec["slots"]) == {"finance", "cashier", "reconciler"}
inst = next(p for p in spec["pages"] if p["id"] == "instance")
assert [c["bind"]["action"] for c in inst["body"] if c["type"] == "action_status"] == ["pay", "sync"]
issues = await lint_app(session, spec, {"slots": {"finance": [{"kind": "user", "name": "u"}]}})
unbound = [i for i in issues if i["code"] == "app.slot_unbound"]
cashier = next(i for i in unbound if i["path"] == "slots.cashier")
assert "调用工具节点「付款」的发送确认派给它" in cashier["message"] and "「同步」" in cashier["message"]
assert not any("取数" in i["message"] for i in issues), [i["message"] for i in issues]
[reconcile] = [i for i in issues if i["code"] == "app.reconciler_unbound"]
assert reconcile["node_id"] == "sync" and "「同步」会写外部系统" in reconcile["message"]
async def test_escalation_and_confirm_slots_are_derived_and_must_be_bound(monkeypatch):
"""超时升级的岗位、动作确认的岗位以前既不派生也不检查:发布后升级、确认悄悄派给了任何人。"""
from app.capabilities import registry
class Cap:
effect = "write"
lookup = "erp_lookup"
async def get_capability(session, name):
return Cap() if name == "erp_pay" else None
monkeypatch.setattr(registry, "get_capability", get_capability)
graph = approval()
graph["nodes"][1]["data"]["config"].update(due="PT1H", on_timeout={"action": "escalate", "to_slot": "director"})
graph["nodes"][2]["data"]["config"]["assignee"] = {"kind": "slot", "slot": "cashier"}
wf, info = await make_workflow(graph)
async with SessionLocal() as session:
spec = await derive_app(session, wf, 1)
assert set(spec["slots"]) == {"finance", "director", "cashier"}
everyone = {"slots": {s: [{"kind": "user", "name": "u"}] for s in ("finance", "director", "cashier")}}
assert not codes(await lint_app(session, spec, everyone)) & {"app.slot_unbound"}
# 绑了两个、升级给的总监没绑:报错,说清是哪一步要它
issues = await lint_app(session, spec, {"slots": {k: v for k, v in everyone["slots"].items() if k != "director"}})
[unbound] = [i for i in issues if i["code"] == "app.slot_unbound"]
assert unbound["level"] == "error" and unbound["path"] == "slots.director"
assert "人工节点「财务审批」超时升级给它" in unbound["message"]
# 应用里根本没声明:按引用它的那一步报,落到节点上
del spec["slots"]["cashier"]
issues = await lint_app(session, spec, everyone)
undeclared = next(i for i in issues if i["code"] == "app.slot_unbound" and i.get("node_id") == "pay")
assert "调用工具节点「付款」的发送确认派给岗位「cashier」" in undeclared["message"]
async def test_describe_a_version_has_no_secrets():
graph = copy.deepcopy(weekly())
graph["nodes"][1]["data"]["config"]["args"] = {"sql": "SELECT * FROM t WHERE phone = '19912345678'"}
+2 -1
View File
@@ -215,7 +215,8 @@ async def test_on_demand_views(client):
app_id = await published_app(client, kpi_spec(wf, hash_), name="按需看板")
params = {"params": '{"week": "W40"}'}
vm = (await client.get(f"/api/apps/{app_id}/pages/home", params=params)).json()
assert vm["sources"]["od"]["state"] == "empty" and vm["problems"][0]["code"] == "view.source_empty"
assert vm["sources"]["od"]["state"] == "empty" and vm["problems"] == []
assert "刷新" in vm["sources"]["od"]["message"]
assert find(vm, "gmv")["data"]["state"] == "empty"
bad = await client.post(f"/api/apps/{app_id}/views/od/refresh", json={"params": {}})
+17
View File
@@ -383,3 +383,20 @@ async def test_legacy_versions_with_formal_runs_are_backfilled_as_published():
WorkflowVersion.__table__.select().where(WorkflowVersion.workflow_id == wf.id))).all()}
assert levels == {1: "published", 2: None, 3: None}
assert await backfill_legacy_levels(session) == 0
async def test_only_an_admin_downgrades_a_governed_workflow(client, monkeypatch):
"""当前发布版是受管级的工作流,以「已发布」发布新版本就是降级——之后的正式运行不再过治理门禁,和以受管级别发布
同一级的决定(Q8):开登录时只给管理员。画布上改过之后 status 回到 draft,按当前发布版的级别认(published_level)。"""
from app.api import deps
wf = await workflow({1: "governed", 2: None}, current=1, status="draft")
assert (await client.get(f"/api/workflows/{wf}")).json()["published_level"] == "governed"
monkeypatch.setattr(deps, "current_principal",
lambda: deps.Principal(username="bob", role="builder", verified=True, mode="local"))
res = await client.post(f"/api/workflows/{wf}/publish", json={"level": "published", "version": 2})
assert res.status_code == 403 and res.json()["code"] == "admin_only" and "降为已发布" in res.json()["detail"]
# 已发布级的工作流照旧由搭建者发布
plain = await workflow({1: "published", 2: None}, current=1, status="draft")
ok = await client.post(f"/api/workflows/{plain}/publish", json={"level": "published", "version": 2})
assert ok.status_code == 200, ok.text
+30 -1
View File
@@ -18,7 +18,7 @@ import httpx
import pytest
from sqlalchemy import select, update
from app.api.deps import Principal, actor_of, reset_principal, set_principal
from app.api.deps import Principal, actor_of, reset_principal, set_principal, signer_of
from app.db.base import SessionLocal, utcnow
from app.db.models import AuditEvent, AuthSession, Group, User
from tests.fakes import auth_env
@@ -55,9 +55,12 @@ async def test_actor_of_ignores_header_once_logged_in():
token = set_principal(Principal(username="alice", role="user", verified=True, mode="local"))
try:
assert actor_of("mallory") == "alice"
assert signer_of("请求体署名", "mallory") == "alice", "开了登录:数据导入这类请求体里自带的署名也不看"
finally:
reset_principal(token)
assert actor_of("mallory") == "mallory"
assert signer_of(" 请求体署名 ", "mallory") == "请求体署名" and signer_of("", "mallory") == "mallory", \
"关登录:请求体里填的优先,其次 X-Actor"
# ---------------------------------------------------------------- local
@@ -90,6 +93,7 @@ async def test_roles_401_403_and_forged_actor():
assert r.status_code == 401
me = await anon.get("/api/auth/me")
assert me.status_code == 401 and me.json()["mode"] == "local", "登录页据此显示账号密码"
assert me.json()["can_bootstrap"] is False, "已经有管理员:登录页不给建管理员"
uma = await auth_env.login("uma")
assert (await uma.get("/api/workflows")).status_code == 403
@@ -105,6 +109,27 @@ async def test_roles_401_403_and_forged_actor():
assert (audit.actor, audit.verified) == ("root", True), "伪造的 X-Actor 被忽略,审计照实记"
async def test_directory_is_read_only_for_builders_and_leaves_out_the_rest():
admin = await auth_env.turn_on_local()
await auth_env.make_user("bob", "builder", email="bob@example.com")
await auth_env.make_user("uma", "user", disabled=True)
assert (await admin.post("/api/groups", json={"name": "fin", "label": "财务"})).status_code == 201
bob = await auth_env.login("bob")
r = await bob.get("/api/directory")
assert r.status_code == 200, "搭建者绑岗位、授权要选人:名录给搭建者"
body = r.json()
assert {u["username"]: u["disabled"] for u in body["users"]} == {"root": False, "bob": False, "uma": True}, \
"停用的人也列出来,标明停用"
assert set(body["users"][0]) == {"username", "display_name", "disabled"}, "不含邮箱、角色这些"
assert body["groups"] == [{"name": "fin", "label": "财务"}]
assert (await bob.post("/api/directory", json={})).status_code == 405, "只读"
async with SessionLocal() as s:
await s.execute(update(User).where(User.username == "uma").values(disabled=False))
await s.commit()
uma = await auth_env.login("uma")
assert (await uma.get("/api/directory")).status_code == 403, "使用者不给"
async def test_csrf_header_and_origin():
admin = await auth_env.turn_on_local()
r = await admin.post("/api/groups", json={"name": "a"}, headers={"X-AgentLab-Request": ""})
@@ -163,8 +188,12 @@ async def test_env_mode_wins_and_bootstrap(monkeypatch):
monkeypatch.setenv("AGENTLAB_AUTH_MODE", "local")
c = auth_env.client()
assert (await c.get("/api/workflows")).status_code == 401
me = await c.get("/api/auth/me")
assert me.status_code == 401 and me.json()["can_bootstrap"] is True, "新部署:登录页据此给「建第一个管理员」"
r = await c.post("/api/auth/bootstrap", json={"username": "first", "password": "password-123"})
assert r.status_code == 200 and r.json()["role"] == "admin"
me = await auth_env.client().get("/api/auth/me")
assert me.status_code == 401 and me.json()["can_bootstrap"] is False, "有了管理员就不再给"
assert (await c.post("/api/auth/bootstrap", json={"username": "second", "password": "password-123"})
).status_code == 409
r = await c.put("/api/auth/settings", json={"mode": "off"})
+39 -6
View File
@@ -2,7 +2,8 @@
- 同步:主键是图里的工具名;同步得出的效果只说系统知道的(可写数据源为视参数而定,绑定端点的非 GET 为写入);
source_hash 没变不动;来源没了记 missing、不删行;
- 治理:version 乐观锁、写审计;只读能力才能免审批;
- 治理:version 乐观锁、写审计;只读能力才能免审批;查询能力只能是同一端点上、绑定端点的只读能力;
- 写记忆这类改平台自身状态的内置工具不记成只读(不能免审批、不能当查询能力),照旧能给 Agent 用;
- is_platform_query:数据源查询,和绑定端点、声明了表格、治理后只读的 http 工具;Python 工具写了表格也不算;
- build_tools(allow_write=False) 拒绝写入能力,视参数而定的照旧放行;
- 正式运行:只读 + 免审批的能力直接放行(修 F7),其余照旧问人;总要确认的探索运行里也问;
@@ -68,11 +69,12 @@ async def _row(name: str) -> Capability:
async def test_sync_derives_effects_and_only_touches_what_changed(world):
effects = {n: (await _row(n)).effect_system for n in (
"calculator", "shell_exec", "db_query__sales_ro", "db_query__sales_rw", "db_schema__sales_rw",
"erp_orders", "erp_pay", "calc_py", "mcp:kb/search")}
assert effects == {"calculator": "read", "shell_exec": "dynamic", "db_query__sales_ro": "read",
"db_query__sales_rw": "dynamic", "db_schema__sales_rw": "read", "erp_orders": "read",
"erp_pay": "write", "calc_py": "dynamic", "mcp:kb/search": "dynamic"}
"calculator", "shell_exec", "memory_recall", "memory_write", "db_query__sales_ro", "db_query__sales_rw",
"db_schema__sales_rw", "erp_orders", "erp_pay", "calc_py", "mcp:kb/search")}
assert effects == {"calculator": "read", "shell_exec": "dynamic", "memory_recall": "read", "memory_write": "dynamic",
"db_query__sales_ro": "read", "db_query__sales_rw": "dynamic", "db_schema__sales_rw": "read",
"erp_orders": "read", "erp_pay": "write", "calc_py": "dynamic", "mcp:kb/search": "dynamic"}, \
"写记忆改的是平台自己的状态:不是只读"
pay = await _row("erp_pay")
assert (pay.system, pay.endpoint_id) == ("erp", world["erp"])
async with SessionLocal() as s:
@@ -107,6 +109,37 @@ async def test_governance_lock_audit_and_rules(world):
assert "nope" not in snap and versions == {"mcp:kb/search": 2, "erp_pay": 1}
async def test_lookup_is_a_read_on_the_same_endpoint(world):
c = auth_env.client()
for wrong in ("memory_write", "db_query__sales_ro", "mcp:kb/search", "erp_pay", "nope"):
r = await c.put("/api/capabilities/erp_pay/governance", json={"version": 1, "lookup": wrong})
assert r.status_code == 422 and "同一端点" in r.json()["detail"], wrong
r = await c.put("/api/capabilities/erp_pay/governance", json={"version": 1, "lookup": "erp_orders"})
assert r.status_code == 200 and r.json()["lookup"] == "erp_orders", r.text
r = await c.put("/api/capabilities/erp_pay/governance", json={"version": 2, "lookup": None})
assert r.status_code == 200 and r.json()["lookup"] is None, "清掉照旧可以"
async with SessionLocal() as s:
await s.execute(update(Capability).where(Capability.name == "memory_write").values(effect="read"))
await s.commit()
r = await c.put("/api/capabilities/erp_pay/governance", json={"version": 3, "lookup": "memory_write"})
assert r.status_code == 422, "治理成只读的内置工具也不是端点上的读取,查不了这一笔写入"
ctx = ToolContext(run_id="t", node_id="n", data_versions=Versions.CURRENT)
async with SessionLocal() as s:
await s.execute(update(Capability).where(Capability.name == "memory_write").values(effect=None))
await s.commit()
assert [t.name for t in await build_tools(["memory_write"], ctx, session=s)] == ["memory_write"], \
"写记忆不是对外写入,Agent 照旧能用"
async def test_tool_library_rehearses_anything_governed_as_a_write(world):
c = auth_env.client()
r = await c.put("/api/capabilities/mcp:kb/search/governance", json={"version": 1, "effect": "write"})
assert r.status_code == 200, r.text
out = await c.post("/api/tools/mcp:kb/search/run", json={"args": {"q": "x"}})
assert out.status_code == 200, "演练不发送,没有副作用,不先要确认"
assert out.json()["rehearsal"] is True and out.json()["result"]["args"] == {"q": "x"}
async def test_platform_query_is_by_identity_not_by_shape(world):
c = auth_env.client()
tabular = {"rows": "/items", "columns": {"单号": "/id"}}
+31 -2
View File
@@ -1232,12 +1232,19 @@ MIX = {"id": "mix", "name": "销售额加首组名称字数", "unit": "元", "de
"expression": "cell(nodes.fetch, 0, 'gmv') + len(vars.res.rows[0][0])"}
def with_regions(spec: dict, source: str) -> dict:
#: 数据整形解析第二份查询结果的两种写法。原样解析(模板整串就是 {{ nodes.regions }})的,vars.res.rows[0][0] 确定地对到
#: 那份快照的第 0 行第 0 列,卡上记成 cell() 一样的单元格取数(engine/lineage.py);模板带了过滤器的不算原样解析,按位置
#: 取的格卡上只记路径和值,遮罩顺着取值链认(_positional_masks)——下面几个测试守的是后一条路
PARSED = "{{ nodes.regions }}"
FILTERED = "{{ nodes.regions | trim }}"
def with_regions(spec: dict, source: str, template: str = FILTERED) -> dict:
"""取数之后另查一次按地区分组的结果(第二份快照),数据整形把它解析进 vars.res:口径卡按位置取它的格。"""
nodes = list(spec["nodes"])
at = next(i for i, n in enumerate(nodes) if n["id"] == "fetch") + 1
nodes[at:at] = [node("regions", "tool", tool=f"db_query__{source}", args={"sql": BY_REGION}),
node("parse", "transform", mode="json", template="{{ nodes.regions }}", assign_to="res")]
node("parse", "transform", mode="json", template=template, assign_to="res")]
return {"nodes": nodes, "edges": [{"source": a["id"], "target": b["id"]} for a, b in zip(nodes, nodes[1:])]}
@@ -1277,6 +1284,28 @@ async def test_an_unmasked_cell_read_by_position_from_another_snapshot_is_blind_
assert "len('华东')" in task
async def test_a_cell_read_through_a_plain_parse_is_judged_like_cell(monkeypatch, masked_shop, shop):
"""数据整形只是原样解析第二次查询的结果:vars.res.rows[0][0] 卡上记成单元格取数(落在第二份快照的第 0 行 region 列),
和 cell(nodes.regions, 0, 'region') 一个说法——遮罩列上的照实说是遮罩、不盲算、取值不进任何产出;没遮罩时它是查询来
的文本,和 cell() 取的文本格一样不能单独复算,照实说不是数值。"""
for (name, _), reason in ((masked_shop, "输入 vars.res.rows[0][0] 取自设置了遮罩的列,不能用于复算"),
(shop, "输入 vars.res.rows[0][0] 不是数值")):
blind = Blind(monkeypatch, name, {"销售额加首组名称字数": (RIGHT, "gmv")})
run = await start(with_regions(graph(name, RIGHT, metrics=[MIX], dual={"definitions": {}}), name, PARSED))
assert run.status == "succeeded", run.error
evs = await events(run.id)
[card] = [e.data for e in evs if e.type == "node.finished" and e.node_id == "card"]
item = next(i for i in artifact_store.load(card["artifact"])["metrics"][0]["inputs"]
if i["path"] == "vars.res.rows[0][0]")
assert (item["via"], item["through"], item["node_id"], item["locator"]) == (
"tool_cell", "parse", "regions", {"row": 0, "column": "region"}), item
out = dual_output(run, evs)
[row] = out["metrics"]
assert row["status"] == "unchecked" and row["reason"] == reason, row
assert blind.tasks == [] and blind.runs == 0, blind.tasks
assert "华东" not in json.dumps(out, ensure_ascii=False)
#: 按位置取的那一格:数据整形解析好的第二份查询结果(首组地区名),快照 id 是编的
POSITIONAL = {"path": "vars.res.rows[0][0]", "value": "华东", "node_id": "parse", "via": "transform", "status": "ok"}
LOST = "cd" * 32
+128 -1
View File
@@ -7,7 +7,9 @@
- 带幂等头;service_on_behalf 带 EdDSA 身份断言,公钥在 /api/auth/jwks;
- 超时 → 结果未知;连接没建立 → 确定的失败;
- 声明了表格的读取落成查询快照同一个形状的端点快照,台账照 query 处理;
- 运行里的写入不从自定义工具直接发;
- 运行里的写入不从自定义工具直接发;工具页试运行、工具库执行写入能力一律演练(不发送,交回将要发送的请求);
- 试运行、测试连接按 HTTP 状态照实说:2xx 才算成功,能连上但 404 / 401 和连不上分开说;
- 认证头名字为空、不合法的存不进去(422 说人话),存量的坏头发请求时照实说是哪一项,不是 LocalProtocolError;
- 自定义工具请求头、MCP env 和请求头:加密存、掩码回、启动时存量明文加密一遍(幂等);MCP http 地址过 SSRF 检查或绑定端点。
"""
from __future__ import annotations
@@ -39,11 +41,15 @@ class Recorder:
def __init__(self) -> None:
self.requests: list[httpx.Request] = []
self.raise_: Exception | None = None
#: 按路径改回的状态码(测 4xx、404 时用)
self.status: dict[str, int] = {}
def __call__(self, request: httpx.Request) -> httpx.Response:
self.requests.append(request)
if self.raise_ is not None:
raise self.raise_
if (code := self.status.get(request.url.path)) is not None:
return httpx.Response(code, json={"error": "nope"})
if request.url.path.startswith("/orders"):
return httpx.Response(200, json={"items": [{"id": "A1", "amount": 12.5, "phone": "13900000001"},
{"id": "A2", "amount": 7, "phone": "13900000002"}]})
@@ -277,3 +283,124 @@ async def test_evidence_panel_masks_an_endpoint_snapshot_by_column():
"rows": [["A1", "13800000000", 12]], "mask_columns": ["电话"]}
sets = await _mask_sets(snap, "erp", _Masks())
assert sets.hidden == {"电话"} and sets.sure == {"电话"} and not sets.gone
async def test_header_names_are_checked_when_saved_and_when_sent(erp):
c, endpoint = erp["client"], erp["endpoint"]
for headers, words in (({"": ""}, "名称不能为空"), ({"X Token": "1"}, "不合法"), ({"X-Token": "第一\n第二"}, "不能换行")):
r = await c.patch(f"/api/endpoints/{endpoint['id']}", json={"version": 1, "environments": {
"prod": {"base_url": BASE, "headers": headers, "allow_intranet": True}}})
assert r.status_code == 422 and "生产环境的认证头有误" in r.json()["detail"] and words in r.json()["detail"], r.text
r = await c.post("/api/endpoints", json={"name": "erp2", "idempotency_header": "Idem Key", "environments": {
"prod": {"base_url": BASE}}})
assert r.status_code == 422 and "幂等请求头" in r.json()["detail"]
# 加校验之前存进去的 {"": ""}:发请求、测连接都照实说是认证头的事,请求没有发出,也不当成结果未知
async with SessionLocal() as s:
row = await s.get(Endpoint, endpoint["id"])
row.environments = {"prod": {**row.environments["prod"], "headers": {"": ""}}}
await s.commit()
before = len(erp["recorder"].requests)
cap = await s.get(Capability, "erp_pay")
result = await ep.endpoint_request(s, cap, {"amount": 1}, environment="prod", idem_key="k:9")
assert not result.unknown and "认证头有误" in result.error and "名称不能为空" in result.error
probe = (await c.post(f"/api/endpoints/{endpoint['id']}/test?env=prod")).json()
assert probe["ok"] is False and probe["reachable"] is False and "认证头有误" in probe["message"]
assert len(erp["recorder"].requests) == before, "坏头的请求一个都没发"
async def test_probe_tells_reachable_apart_from_ok(erp):
c, endpoint, recorder = erp["client"], erp["endpoint"], erp["recorder"]
ok = (await c.post(f"/api/endpoints/{endpoint['id']}/test?env=prod")).json()
assert ok["ok"] is True and ok["status"] == 201 and "连接成功" in ok["message"]
recorder.status["/"] = 404
missing = (await c.post(f"/api/endpoints/{endpoint['id']}/test?env=prod")).json()
assert (missing["ok"], missing["reachable"], missing["status"]) == (False, True, 404)
assert "能连上" in missing["message"] and "404" in missing["message"] and "成功" not in missing["message"], \
"能连上但路径不存在,不能说成连接成功"
recorder.status["/"] = 401
denied = (await c.post(f"/api/endpoints/{endpoint['id']}/test?env=prod")).json()
assert denied["ok"] is False and "认证" in denied["message"]
recorder.raise_ = httpx.ConnectError("refused")
down = (await c.post(f"/api/endpoints/{endpoint['id']}/test?env=prod")).json()
assert (down["ok"], down["reachable"]) == (False, False) and "无法连接" in down["message"]
async def test_trying_a_write_capability_rehearses_instead_of_sending(erp):
c, endpoint, recorder = erp["client"], erp["endpoint"], erp["recorder"]
tool = next(t for t in (await c.get("/api/custom-tools")).json() if t["name"] == "erp_pay")
before = len(recorder.requests)
trial = (await c.post(f"/api/custom-tools/{tool['id']}/test", json={"args": {"amount": 3}})).json()
assert trial["ok"] is True and trial["rehearsal"] is True, trial
req = trial["result"]["request"]
assert (req["method"], req["url"], req["body"]) == ("POST", f"{BASE}/payments", {"amount": 3})
assert trial["result"]["environment"] == "prod", "端点没有测试环境:写正式运行要发往的生产环境"
assert req["headers"] == ["Authorization", "Idempotency-Key"], "只交回请求头的名字"
assert "prod-secret-token" not in json.dumps(trial, ensure_ascii=False)
draft = (await c.post("/api/custom-tools/test", json={**tool, "args": {"amount": 3}})).json()
assert draft["rehearsal"] is True, "没保存的草稿同样只演练"
# 工具库执行:同样演练,没有副作用也就不先要确认
run = await c.post("/api/tools/erp_pay/run", json={"args": {"amount": 3}})
assert run.status_code == 200 and run.json()["rehearsal"] is True and run.json()["result"]["request"]["method"] == "POST"
assert len(recorder.requests) == before, "写入能力在工具页一个请求都没发"
# 读取照旧真的发,对方回 4xx 时照实说失败和状态码
recorder.status["/orders"] = 400
read = (await c.post("/api/tools/erp_orders/run?confirm=true", json={"args": {"q": "x"}})).json()
assert read["ok"] is False and "HTTP 400" in read["error"] and "nope" in read["detail"]
orders = next(t for t in (await c.get("/api/custom-tools")).json() if t["name"] == "erp_orders")
tried = (await c.post(f"/api/custom-tools/{orders['id']}/test", json={"args": {"q": "x"}})).json()
assert tried["ok"] is False and "HTTP 400" in tried["error"] and not tried.get("rehearsal")
assert len(recorder.requests) == before + 2
async def test_a_draft_trial_sends_the_draft_not_the_saved_tool(erp):
"""工具页试运行的草稿按草稿的配置拼请求,读写按已保存的治理和草稿的方法里更严的一个认。以前按名字找已保存的那一版:
把已保存的 GET /orders 改成草稿 POST /payments 去试,真发出去的是 GET /orders,结果写「成功」。"""
c, recorder = erp["client"], erp["recorder"]
orders = next(t for t in (await c.get("/api/custom-tools")).json() if t["name"] == "erp_orders")
before = len(recorder.requests)
post = {**orders, "config": {**orders["config"], "method": "POST", "path": "/payments", "query": {}}}
trial = (await c.post("/api/custom-tools/test", json={**post, "args": {"q": "x"}})).json()
assert trial["ok"] is True and trial["rehearsal"] is True, trial
req = trial["result"]["request"]
assert (req["method"], req["url"]) == ("POST", f"{BASE}/payments"), req
assert len(recorder.requests) == before, "草稿改成了写入:已保存的那一版是只读也只演练,一个请求都不发"
# 草稿只改了路径和查询参数(还是读取):真的发,发的是草稿的
moved = {**orders, "config": {**orders["config"], "path": "/orders/open", "query": {"status": "{{ q }}"}}}
read = (await c.post("/api/custom-tools/test", json={**moved, "args": {"q": "x"}})).json()
assert read["ok"] is True and not read.get("rehearsal"), read
[sent] = recorder.requests[before:]
assert (sent.method, sent.url.path, dict(sent.url.params)) == ("GET", "/orders/open", {"status": "x"})
# 还没保存过的绑定端点的读取:同样按草稿发(以前按名字找不到已保存的工具,报没有绑定端点)
fresh = (await c.post("/api/custom-tools/test", json={**moved, "name": "erp_orders_new", "args": {"q": "y"}})).json()
assert fresh["ok"] is True, fresh
assert recorder.requests[-1].url.path == "/orders/open" and len(recorder.requests) == before + 2
# 保存过的那一行和登记对得上:照治理的走(管理员把 POST 的查询接口治理成只读,是他的决定)
async with SessionLocal() as s:
from app.tools.custom import _effect_of
pay_cap = await s.get(Capability, "erp_pay")
pay = (await s.execute(select(CustomTool).where(CustomTool.name == "erp_pay"))).scalar_one()
pay_cap.effect = "read"
assert _effect_of(pay, pay_cap) == "read"
draft = CustomTool(name="erp_pay", kind="http", config={**pay.config, "method": "GET"})
assert _effect_of(draft, pay_cap) == "read"
pay_cap.effect = None
assert _effect_of(draft, pay_cap) == "write", "草稿改成了 GET:已保存的那一版是写入,取更严的"
await s.rollback()
async def test_custom_tool_header_names_are_checked():
c = auth_env.client()
r = await c.post("/api/custom-tools", json={"name": "bad_headers", "kind": "http", "parameters": {},
"config": {"url": "https://crm.example.com", "headers": {"": "x"}}})
assert r.status_code == 422 and "名称不能为空" in r.json()["detail"]
r = await c.post("/api/custom-tools", json={"name": "bad_headers", "kind": "http", "parameters": {},
"config": {"url": "https://crm.example.com",
"headers": {"Authorization": "Bearer {{ 令牌 }}"}}})
assert r.status_code == 201, "值里的模板不查"
async with SessionLocal() as s:
await s.execute(delete(CustomTool).where(CustomTool.name == "bad_headers"))
await s.commit()
+251
View File
@@ -0,0 +1,251 @@
"""口径卡的输入追没追到原始数据(engine/lineage.py):一处认定,运行时、证据面板、应用检查三处用。
- 「有出处」说的是数由口径卡确定性算出、复算一致;「追到原始数据」说的是输入一路对到查询快照里的格(或运行输入)。
证据接口的指标步骤另给 untraced:追不到的输入停在哪个节点(名字、类型),面板据此照实说,不能只写「有出处」
- 数据整形只是原样解析调用工具节点的结果(模板整串就是 {{ nodes.fetch }})时,vars.q.rows[i][j] 穿过它接上快照;
表达式整形、模板带过滤器、包了一层的都不算
- 受管级应用里绑定的指标,输入追不到原始数据的,应用检查给提示(app.metric_untraced,警告);已发布级不提示
库和数字都是编的。
"""
from __future__ import annotations
import asyncio
import sqlite3
import uuid
from types import SimpleNamespace
import pytest
from httpx import ASGITransport, AsyncClient
from app.apps.lint import _Issues, _lint_components
from app.apps.tree import node_map
from app.data.engine import engines
from app.db.base import SessionLocal
from app.db.models import DataSource, Run
from app.engine.lineage import RowCell, Stop, parsed_tool, row_cell, static_stops, traced, untraced
from app.engine.runner import run_manager
from app.main import app
SQL = "SELECT SUM(amount) AS gmv, COUNT(*) AS orders FROM orders"
def node(nid, ntype, label=None, **config):
return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": label or nid, "config": config}}
def chain(*nodes):
return {"nodes": list(nodes), "edges": [{"source": a["id"], "target": b["id"]} for a, b in zip(nodes, nodes[1:])]}
# --------------------------------------------------------------------------
# 纯函数
# --------------------------------------------------------------------------
@pytest.mark.parametrize("path, want", [
("vars.q.rows[0][0]", RowCell("vars", "q", 0, 0)),
("nodes.parse.rows[2]['gmv']", RowCell("nodes", "parse", 2, "gmv")),
("vars.q.rows[-1][0]", None), # 负数下标:数的是取回的最后一行,对不到确定的行号
("vars.q.rows[vars.i][0]", None), # 下标是变量
("vars.q.rows[0]", None), # 整行
("vars.w.res.rows[0][0]", None), # 多包了一层
("cell(nodes.fetch, 0, 'gmv')", None),
("input.week", None),
])
def test_row_cell(path, want):
assert row_cell(path) == want
@pytest.mark.parametrize("config, want", [
({"mode": "json", "template": "{{ nodes.fetch }}"}, "fetch"),
({"mode": "json", "template": " {{nodes.fetch}}\n"}, "fetch"),
({"mode": "json", "template": "{{ nodes.fetch | trim }}"}, None), # 带过滤器:不算原样
({"mode": "json", "template": '{"res": {{ nodes.fetch }}}'}, None), # 包了一层
({"mode": "json", "template": "{{ nodes.note }}"}, None), # 不是调用工具节点
({"mode": "template", "template": "{{ nodes.fetch }}"}, None),
({"mode": "expression", "expression": "nodes.fetch"}, None),
])
def test_parsed_tool(config, want):
types = {"fetch": "tool", "note": "llm"}
assert parsed_tool("transform", config, types.get) == want
assert parsed_tool("code", config, types.get) is None
def test_traced_and_untraced():
cell = {"path": "cell(nodes.fetch, 0, 'gmv')", "value": 1, "via": "tool_cell", "artifact": "a", "status": "verified"}
mismatch = {**cell, "status": "mismatch"} # 对得到快照,只是值不一样:另有说法,出处是追到了的
lost = {**cell, "status": "unresolved", "artifact": None} # 找不到快照
field = {"path": "vars.kpi.gmv", "value": 2, "via": "agent_field", "artifact": "a", "status": "verified"}
run_input = {"path": "input.target", "value": 3, "via": "input", "status": "ok"}
shaped = {"path": "vars.t.x", "value": 4, "node_id": "mid", "via": "transform", "status": "ok"}
empty = {"path": "vars.t.y", "value": None, "node_id": "mid", "via": "transform", "status": "missing"}
assert [traced(i) for i in (cell, mismatch, lost, field, run_input, shaped)] == [True, True, False, True, True, False]
# 没有值的不算在追不到里:缺输入另有说法
assert untraced([cell, lost, field, run_input, shaped, empty, "坏数据"]) == [lost, shaped]
def graph_nodes():
return node_map(chain(
node("start", "input", "开始", fields=[{"name": "target"}]),
node("fetch", "tool", "取数", tool="db_query__shop", args={"sql": SQL}),
node("parse", "transform", "解析", mode="json", template="{{ nodes.fetch }}", assign_to="q"),
node("raw_n", "transform", "解析(过滤器)", mode="json", template="{{ nodes.fetch | trim }}", assign_to="raw"),
node("calc", "transform", "加工", mode="expression", expression="{'x': 1}", assign_to="t"),
node("bot", "agent", "取数助手", output_schema={"type": "object"}, cite_fields=True, assign_to="kpi"),
node("loose", "agent", "没核对的助手", output_schema={"type": "object"}, assign_to="guess"),
node("box", "code", "沙箱", evidence_role="source", assign_to="c"),
node("card", "metrics", "口径卡", metrics=[]),
))
@pytest.mark.parametrize("expression, stops", [
("cell(nodes.fetch, 0, 'gmv')", []),
("cell(vars.q, 0, 'gmv') + vars.q.rows[0][1]", []), # 原样解析的结果:按格、按位置都追到快照
("nodes.parse.rows[0]['gmv']", []),
("input.target + vars.target", []), # 运行输入
("vars.kpi.gmv + nodes.bot.data.gmv", []), # 开了按出处核对字段的 Agent
("vars.raw.rows[0][0]", [Stop("vars.raw.rows[0][0]", "raw_n")]),
("cell(vars.t, 0, 0)", [Stop("cell(vars.t, 0, 0)", "calc")]),
("vars.t.x * 2", [Stop("vars.t.x", "calc")]),
("vars.guess.gmv", [Stop("vars.guess.gmv", "loose")]),
("vars.c.gmv", [Stop("vars.c.gmv", "box")]), # 沙箱取数核对不到快照
("vars.nowhere + 1", [Stop("vars.nowhere", None)]),
("vars.t.x +", []), # 写错了的表达式由画布的校验报,这里不报
])
def test_static_stops(expression, stops):
assert static_stops(graph_nodes(), expression) == stops
# --------------------------------------------------------------------------
# 证据接口:指标步骤说追没追到原始数据
# --------------------------------------------------------------------------
@pytest.fixture(autouse=True)
async def engine_up():
await run_manager.setup()
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
async def shop(tmp_path):
path = tmp_path / "shop.db"
with sqlite3.connect(path) as db:
db.executescript("CREATE TABLE orders (id INTEGER PRIMARY KEY, amount REAL);")
db.executemany("INSERT INTO orders VALUES (?, ?)", [(1, 100.5), (2, 200.0), (3, 300.0)])
name = f"origin_{uuid.uuid4().hex[:6]}"
async with SessionLocal() as session:
row = DataSource(name=name, kind="sqlite", database=str(path), readonly=True, enabled=True)
session.add(row)
await session.commit()
source_id = row.id
yield name
await engines.invalidate(source_id)
async def finish(graph: dict) -> Run:
run = await run_manager.start(graph=graph, input_payload={"target": 5})
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.id} 没跑完:{row.status}")
async def test_the_metric_step_says_how_far_the_inputs_were_traced(client, shop):
graph = chain(
node("start", "input", "开始", fields=[{"name": "target"}]),
node("fetch", "tool", "取数", tool=f"db_query__{shop}", args={"sql": SQL}),
node("parse", "transform", "解析查询结果", mode="json", template="{{ nodes.fetch }}", assign_to="q"),
node("raw_n", "transform", "整理查询结果", mode="json", template="{{ nodes.fetch | trim }}", assign_to="raw"),
node("card", "metrics", "口径卡", caliber="口径", metrics=[
{"id": "gmv", "name": "销售额", "decimals": 2, "expression": "vars.q.rows[0][0]"},
{"id": "raw", "name": "销售额(过滤器)", "decimals": 2, "expression": "vars.raw.rows[0][0] + input.target"},
{"id": "one", "name": "常量", "expression": "1"},
]),
node("out", "output", "成果", fields=[{"name": "r", "value": "{{ nodes.card.text }}"}]),
)
row = await finish(graph)
assert row.status == "succeeded", row.error
gmv = (await client.get(f"/api/runs/{row.id}/evidence/metrics/card/gmv")).json()["chain"]
step = gmv[0]
assert step["step"] == "metric" and step["recompute_ok"] is True and step["untraced"] == []
[inp] = [s for s in gmv if s["step"] == "input"]
assert (inp["via"], inp["through"], inp["through_label"], inp["status"]) == ("tool_cell", "parse", "解析查询结果",
"verified")
# 穿过整形节点接上了查询快照:链的最后一步是那次查询,高亮那一格
assert gmv[-1]["step"] == "query" and gmv[-1]["highlight"]["cells"] == [[0, "gmv"]]
raw = (await client.get(f"/api/runs/{row.id}/evidence/metrics/card/raw")).json()["chain"]
# 复算照样一致(有出处),可输入停在了整形节点:运行输入那一项追到了,不列
assert raw[0]["recompute_ok"] is True
assert raw[0]["untraced"] == [{"path": "vars.raw.rows[0][0]", "node_id": "raw_n", "label": "整理查询结果",
"type": "transform"}]
assert not [s for s in raw if s["step"] == "query"]
# 没有输入的常量:没有可追的,不给这个键
one = (await client.get(f"/api/runs/{row.id}/evidence/metrics/card/one")).json()["chain"]
assert "untraced" not in one[0]
# --------------------------------------------------------------------------
# 应用检查:受管级应用里绑定的指标
# --------------------------------------------------------------------------
def app_spec() -> dict:
return {
"format": "agentlab.app/1", "name": "看板", "pins": [{"alias": "main", "workflow_id": "wf", "version": 1,
"graph_hash": "h", "level": "governed", "use": "view"}],
"views": {"latest": {"source": {"kind": "latest_sealed", "pin": "main", "from": "formal"}}},
"pages": [{"id": "home", "title": "首页", "body": [
{"id": "m_gmv", "type": "metric", "props": {"label": "销售额"}, "bind": {"view": "latest", "metric": "card.gmv"}},
{"id": "m_raw", "type": "metric", "props": {"label": "整理过的"}, "bind": {"view": "latest", "metric": "card.raw"}},
{"id": "s_raw", "type": "series", "props": {"label": "趋势"}, "bind": {"view": "latest", "series": "card.raw"}},
]}],
}
def pinned_graph() -> dict:
return chain(
node("fetch", "tool", "取数", tool="db_query__shop", args={"sql": SQL}),
node("parse", "transform", "解析查询结果", mode="json", template="{{ nodes.fetch }}", assign_to="q"),
node("calc", "transform", "加工", mode="expression", expression="{'gmv': 1}", assign_to="t"),
node("card", "metrics", "口径卡", metrics=[
{"id": "gmv", "name": "销售额", "expression": "vars.q.rows[0][0] + cell(nodes.fetch, 0, 'orders')"},
{"id": "raw", "name": "加工后的销售额", "expression": "vars.t.gmv * 2"},
]),
)
def lint(level: str) -> list[dict]:
spec = app_spec()
pins = {"main": SimpleNamespace(row=object(), graph=pinned_graph(), level=level, label="周报 v1")}
out = _Issues()
_lint_components(spec, pins, spec["views"], level, out)
return [i for i in out.items if i["code"] == "app.metric_untraced"]
def test_governed_apps_flag_metrics_whose_inputs_stop_halfway():
found = lint("governed")
assert [(i["path"], i["level"], i["node_id"]) for i in found] == [
("pages[0].body[1].bind", "warning", "card"), ("pages[0].body[2].bind", "warning", "card")]
message = found[0]["message"]
assert "「加工后的销售额」" in message and "vars.t.gmv 停在「加工」(数据整形)" in message and "cell()" in message
# 原样解析的按位置取格、cell() 取的格都追到了快照:销售额不提示
assert not [i for i in found if i["path"].startswith("pages[0].body[0]")]
def test_published_apps_are_not_flagged():
assert lint("published") == []
+170
View File
@@ -0,0 +1,170 @@
"""指标出具(engine/issuance.metrics_only,用户 2026-10-15 拍板):纯指标看板——契约只写「指标来自」,没有「报告来自」
也没有「叙述」——出具的就是指标本身。三档的语义不变,核对的对象从叙述换成指标:
- 必需指标齐、每个指标的输入追到原始数据(查询快照的格、运行输入)、成果字段里给人看的数都回指得上:完整出具
- 指标的输入停在别的节点(表达式整形、带过滤器的解析……):降档,缺口写明哪个指标停在哪个节点
- 成果字段里有回指不上的数:降档(strict 下不予出具);必需指标缺了:不予出具
- 受管门禁:只写「指标来自」不再报「既没有报告来自、也没有叙述」;每个指标都要静态地追到原始数据,追不到的挡住发布
库和数字都是编的。
"""
from __future__ import annotations
import asyncio
import sqlite3
import uuid
import pytest
from app.data.engine import engines
from app.db.base import SessionLocal
from app.db.models import DataSource, Run
from app.engine.governance import lint_for_publish
from app.engine.issuance import metrics_only
from app.engine.runner import run_manager
from app.engine.schema import GraphSpec
SQL = "SELECT SUM(amount) AS gmv, COUNT(*) AS orders FROM orders"
def node(nid, ntype, label=None, **config):
return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": label or nid, "config": config}}
def chain(*nodes):
return {"nodes": list(nodes), "edges": [{"source": a["id"], "target": b["id"]} for a, b in zip(nodes, nodes[1:])]}
def board(source: str, *, gmv: str = "vars.q.rows[0][0]", fields=None, required=("gmv", "orders"), strict=False):
return chain(
node("start", "input", "开始", fields=[{"name": "week", "default": "2026-W40"}]),
node("fetch", "tool", "取数", tool=f"db_query__{source}", args={"sql": SQL}),
node("parse", "transform", "解析查询结果", mode="json", template="{{ nodes.fetch }}", assign_to="q"),
node("raw_n", "transform", "整理查询结果", mode="json", template="{{ nodes.fetch | trim }}", assign_to="raw"),
node("card", "metrics", "周报口径卡", caliber="周报口径", caliber_version="v1", metrics=[
{"id": "gmv", "name": "销售额", "unit": "元", "decimals": 2, "expression": gmv},
{"id": "orders", "name": "订单数", "expression": "cell(nodes.fetch, 0, 'orders')"},
]),
node("out", "output", "成果", fields=fields if fields is not None else [
{"name": "本期", "value": "{{ input.week }}"}, {"name": "指标", "value": "{{ nodes.card.text }}"}],
contract={"metrics_from": ["card"], "required": list(required), "strict": strict}),
)
@pytest.mark.parametrize("contract, want", [
({"metrics_from": ["card"], "required": ["gmv"]}, True),
({"metrics_from": "card"}, True),
({"metrics_from": ["card"], "narrative": "销售额 {{ nodes.card.text }}"}, False),
({"metrics_from": ["card"], "report_from": "write"}, False),
({"required": ["gmv"]}, False),
("card", False),
])
def test_metrics_only(contract, want):
assert metrics_only(contract) is want
# --------------------------------------------------------------------------
# 运行时
# --------------------------------------------------------------------------
@pytest.fixture(autouse=True)
async def engine_up():
await run_manager.setup()
yield
await run_manager.shutdown()
@pytest.fixture
async def shop(tmp_path):
path = tmp_path / "shop.db"
with sqlite3.connect(path) as db:
db.executescript("CREATE TABLE orders (id INTEGER PRIMARY KEY, amount REAL);")
db.executemany("INSERT INTO orders VALUES (?, ?)", [(1, 100.5), (2, 200.0), (3, 300.0)])
name = f"mx_{uuid.uuid4().hex[:6]}"
async with SessionLocal() as session:
row = DataSource(name=name, kind="sqlite", database=str(path), readonly=True, enabled=True)
session.add(row)
await session.commit()
source_id = row.id
yield name
await engines.invalidate(source_id)
async def issuance_of(graph: dict) -> dict:
run = await run_manager.start(graph=graph, input_payload={"week": "2026-W40"})
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:
assert row.status == "succeeded", row.error
return (row.output or {})["_issuance"]
raise AssertionError(f"运行 {run.id} 没跑完:{row.status}")
async def test_a_board_whose_metrics_reach_the_data_is_formal(shop):
issuance = await issuance_of(board(shop))
assert (issuance["tier"], issuance["mode"]) == ("formal", "metrics")
# 不再记「出具契约未设置『叙述』」:没有叙述不是缺口,核的是指标本身
assert issuance["gaps"] == [] and issuance["unmatched_numbers"] == []
# 成果字段里的数(口径卡的文字)都回指到了指标
assert issuance["matched_numbers"] >= 2
async def test_an_input_that_stops_short_of_the_data_degrades(shop):
issuance = await issuance_of(board(shop, gmv="vars.raw.rows[0][0]"))
assert issuance["tier"] == "degraded"
[gap] = issuance["gaps"]
assert "销售额" in gap and "没追到原始数据" in gap and "整理查询结果" in gap
async def test_numbers_in_the_fields_must_trace_and_required_metrics_must_be_there(shop):
loose = await issuance_of(board(shop, fields=[{"name": "备注", "value": "本周目标 12345 元"}]))
assert loose["tier"] == "degraded" and [u["token"] for u in loose["unmatched_numbers"]] == ["12345"]
strict = await issuance_of(board(shop, fields=[{"name": "备注", "value": "本周目标 12345 元"}], strict=True))
assert strict["tier"] == "withheld"
missing = await issuance_of(board(shop, required=("gmv", "orders", "refund_rate")))
assert (missing["tier"], missing["missing_required"]) == ("withheld", ["refund_rate"])
# --------------------------------------------------------------------------
# 受管门禁
# --------------------------------------------------------------------------
def gate(graph: dict, level: str = "governed") -> dict[str, str]:
return {i.code: i.level for i in lint_for_publish(GraphSpec.model_validate(graph), level=level).issues if i.code}
def test_a_metrics_only_contract_is_not_missing_its_checks():
codes = gate(board("shop"))
assert "contract.report_from_missing" not in codes and "governed.report_from_required" not in codes
assert "governed.metric_untraced" not in codes
def test_governed_metrics_must_reach_the_data_statically():
codes = gate(board("shop", gmv="vars.raw.rows[0][0]"))
assert codes.get("governed.metric_untraced") == "error"
# 已发布级不按这一条挡:运行时照样降档、照实写缺口
assert "governed.metric_untraced" not in gate(board("shop", gmv="vars.raw.rows[0][0]"), level="published")
def test_a_contract_that_checks_nothing_is_still_refused():
graph = board("shop")
graph["nodes"][-1]["data"]["config"]["contract"] = {"required": ["gmv"]}
assert gate(graph).get("contract.report_from_missing") == "error"
def test_a_board_with_a_report_or_model_text_is_not_metrics_only():
"""上游有报告撰写节点、或成果字段里有模型写的话:那是叙述,不能因为契约少写了「报告来自」就改成只核指标。"""
with_report = board("shop")
with_report["nodes"].insert(-1, node("write", "report", "写周报", metrics_from=["card"]))
with_report["edges"] = [*with_report["edges"][:-1], {"source": "card", "target": "write"},
{"source": "write", "target": "out"}]
assert gate(with_report).get("contract.report_from_missing") == "error"
with_model = board("shop", fields=[{"name": "点评", "value": "{{ nodes.say.text }}"}])
with_model["nodes"].insert(-1, node("say", "llm", "点评", prompt="点评一下"))
with_model["edges"] = [*with_model["edges"][:-1], {"source": "card", "target": "say"},
{"source": "say", "target": "out"}]
assert gate(with_model, level="published").get("contract.report_from_missing") == "warning"
@@ -2,7 +2,9 @@
recompute 的还原(_positional),用 recompute 的地方都跟着变,这里把变化钉住。
- 双盲复算的预检(dual_check._plan_metric 什么都不改先重算一遍):以前这种指标照常盲算,遮着的那一格还会作为字面量
写进给盲算模型的计算式;现在预检判它用到了遮罩列,按无法复算记,原因不说「推演」(这里不是推演)
写进给盲算模型的计算式;现在预检判它用到了遮罩列,按无法复算记,原因不说「推演」(这里不是推演)。数据整形只是原样
解析查询结果时(模板整串就是 {{ nodes.fetch }}),这一格卡上直接记成单元格取数(engine/lineage.py),和 cell() 取的
遮罩格同一个说法;模板带了过滤器的不算原样解析,走顺着取值链认遮罩的那条路——两种写法都守
- 运行对比(engine/compare.py):这种输入两边的值都不给,标 masked,和 cell() 取的遮罩格一样
库和数字都是编的:号码写成带横线的文本,区域名是「东区」这类。
@@ -11,6 +13,8 @@ from __future__ import annotations
import json
import pytest
from app.engine import compare
from app.engine.runner import run_manager
from tests.fixtures.compare_runs import BASE_ROWS, NEXT_ROWS, metric, scalar_in, week
@@ -26,12 +30,17 @@ from tests.test_evidence_metric_masks import ( # noqa: F401 - 夹具按名字
)
def dual_graph():
#: 数据整形的两种写法:原样解析、模板带过滤器(不算原样解析)
PARSED = "{{ nodes.fetch }}"
FILTERED = "{{ nodes.fetch | trim }}"
def dual_graph(template: str = PARSED):
"""取数 → 数据整形(vars.res)→ 口径卡 → 双盲复算(只复算 mix)→ 成果。"""
nodes = [
node("start", "input"),
node("fetch", "tool", tool="db_query__shop", args={"sql": SQL}),
node("parse", "transform", mode="json", template="{{ nodes.fetch }}", assign_to="res"),
node("parse", "transform", mode="json", template=template, assign_to="res"),
node("card", "metrics", caliber="遮罩口径", caliber_version="v1", metrics=METRICS),
node("dual", "dual_check", metrics=["mix"]),
node("out", "output", fields=[{"name": "结果", "value": "{{ nodes.card.text }}"}]),
@@ -52,9 +61,11 @@ async def dual_output(run_id: str) -> dict:
return artifact_store.load(finished.data["artifact"])
async def test_the_dual_check_does_not_blind_compute_a_metric_reading_a_masked_cell_by_position(shop):
@pytest.mark.parametrize("template", [PARSED, FILTERED])
async def test_the_dual_check_does_not_blind_compute_a_metric_reading_a_masked_cell_by_position(shop, template):
"""mix = round(cell(nodes.fetch, 1, 'amount') + len(vars.res.rows[1][2]), 1):cell() 那一格不在遮罩列上,按位置取的
号码在。认出它取自遮罩列,按无法复算记缺口,原因点名是哪个输入、不说「推演」;没遮罩时预检照常通过、指标进入盲算。"""
号码在。认出它取自遮罩列,按无法复算记缺口,原因点名是哪个输入、不说「推演」。没遮罩时:原样解析的那一格是查询来的
文本,和 cell() 取的文本格一样不能单独复算,照实说不是数值;模板带了过滤器的,预检照常通过、指标进入盲算。"""
import asyncio
from app.db.base import SessionLocal
@@ -62,7 +73,7 @@ async def test_the_dual_check_does_not_blind_compute_a_metric_reading_a_masked_c
async def run(options):
await set_source(shop, options)
run_id = (await run_manager.start(graph=dual_graph(), input_payload={})).id
run_id = (await run_manager.start(graph=dual_graph(template), input_payload={})).id
for _ in range(400):
await asyncio.sleep(0.05)
async with SessionLocal() as session:
@@ -81,10 +92,15 @@ async def test_the_dual_check_does_not_blind_compute_a_metric_reading_a_masked_c
assert not [p for p in PHONES if p in json.dumps(masked, ensure_ascii=False)]
assert any("遮罩" in gap for gap in masked["issuance_gaps"])
# 没遮罩:预检通过,原因不再是遮罩(盲算模型没配,按盲算没交回数记,但已经走到了盲算这一步)
plain = await run({})
[mix] = plain["metrics"]
assert "遮罩" not in (mix.get("reason") or "") and "无法按原表达式重算" not in (mix.get("reason") or "")
if template == PARSED:
# 原样解析:号码那一格是查询快照里的文本,和 cell() 取的文本格同一个说法
assert mix["status"] == "unchecked" and mix["reason"] == "输入 vars.res.rows[1][2] 不是数值", mix
else:
# 没遮罩:预检通过,原因不再是遮罩(盲算模型没配,按盲算没交回数记,但已经走到了盲算这一步)
assert "遮罩" not in (mix.get("reason") or "") and "无法按原表达式重算" not in (mix.get("reason") or "")
assert "不是数值" not in (mix.get("reason") or ""), mix
def region_len(fetch, bot, rows, bot_rows):
+175
View File
@@ -316,3 +316,178 @@ def test_masking_by_json_pointer():
out = actions.masked(doc, ["/a/b", "/a/c/1", "/d~0e", "/f~1g", "/missing/x"])
assert out == {"a": {"b": "••••", "c": [1, "••••"]}, "d~e": "••••", "f/g": "••••"}
assert doc["a"]["b"] == "secret"
# --------------------------------------------------------------------------
# 参数按能力的参数定义收好类型(typed_args):哈希、预览、发出去的都是收好的那一份
# --------------------------------------------------------------------------
PARAMS = {"type": "object", "required": ["amount"], "properties": {
"amount": {"type": "number"}, "count": {"type": "integer"}, "urgent": {"type": "boolean"},
"card": {"type": "string"}, "memo": {"type": "number"},
"payee": {"type": "object", "properties": {"id": {"type": "integer"}, "vip": {"type": "boolean"}}},
"splits": {"type": "array", "items": {"type": "number"}}}}
def _cap(schema=PARAMS):
from types import SimpleNamespace
return SimpleNamespace(name=PAY, title="付款", params_schema=schema)
def test_typed_args_follow_the_declared_types():
out = actions.typed_args(_cap(), {
"amount": "1280.5", "count": "3", "urgent": "true", "card": "6222", "extra": "原样",
"payee": '{"id": "42", "vip": "false", "name": "钱七"}', "splits": ["1", 2.5], "memo": ""})
assert out == {"amount": 1280.5, "count": 3, "urgent": True, "card": "6222", "extra": "原样",
"payee": {"id": 42, "vip": False, "name": "钱七"}, "splits": [1, 2.5]}
assert actions.typed_args(_cap(), {"amount": "120"})["amount"] == 120 and \
isinstance(actions.typed_args(_cap(), {"amount": "120"})["amount"], int)
assert actions.typed_args(_cap(), {"amount": 7, "count": "4.0"}) == {"amount": 7, "count": 4}
# 没登记参数定义的能力:原样不动,发出去的和以前一字不差
assert actions.typed_args(_cap({}), {"amount": "1280.5"}) == {"amount": "1280.5"}
@pytest.mark.parametrize("args, where, want", [
({"amount": "abc"}, "amount", "应为数"),
({"amount": "nan"}, "amount", "应为数"),
({"amount": "1", "count": "2.5"}, "count", "应为整数"),
({"amount": "1", "urgent": "yes"}, "urgent", "应为是或否"),
({"amount": "1", "payee": {"id": "x"}}, "payee.id", "应为整数"),
({"amount": "1", "splits": ["1", "两元"]}, "splits[1]", "应为数"),
({"amount": "1", "payee": "{坏的"}, "payee", "应为对象(JSON)"),
({"amount": " "}, "amount", "必填参数"),
])
def test_typed_args_refuse_what_cannot_be_the_declared_type(args, where, want):
with pytest.raises(actions.ActionFailed) as refused:
actions.typed_args(_cap(), args)
assert f" {where} " in str(refused.value) and want in str(refused.value) and "没有发送" in str(refused.value)
async def test_a_template_amount_is_sent_as_a_number_and_the_hash_covers_what_is_sent(erp, capabilities):
caps = capabilities(await _endpoint(test=True), lookup=False)
caps[PAY].params_schema = {"type": "object", "properties": {"amount": {"type": "number"},
"card": {"type": "string"}}}
run_id = await _formal(pay_graph(), amount=1280.5)
task = await _task(run_id, "action_confirm")
card = (await tasks.detail(task.id, ANN))["payload"]
assert card["preview"] == {"amount": 1280.5, "card": "••••"}
sent = {"amount": 1280.5, "card": "6222020200112233"}
assert card["payload_hash"] == actions.payload_hash(PAY, sent)
assert card["payload_hash"] != actions.payload_hash(PAY, {**sent, "amount": "1280.5"})
await _confirm(run_id)
final = await _wait(run_id, ("succeeded", "failed"))
assert final.status == "succeeded", final.error
[request] = erp.writes("prod")
assert request["body"] == sent and isinstance(request["body"]["amount"], float)
[rec] = await _records(run_id)
assert rec.payload_hash == card["payload_hash"] and rec.preview["amount"] == 1280.5
async def test_an_untyped_value_fails_the_node_without_sending(erp, capabilities):
caps = capabilities(await _endpoint(test=True), lookup=False)
caps[PAY].params_schema = {"type": "object", "properties": {"amount": {"type": "number"}}}
run_id = await _formal(pay_graph(), amount="abc")
final = await _wait(run_id, ("succeeded", "failed", "interrupted"))
assert final.status == "failed" and "参数 amount 应为数" in final.error and "「abc」" in final.error
assert erp.requests == [] and await _records(run_id) == []
async with SessionLocal() as session: # 收不成的在确认之前就停下:不开确认卡,看过的不会是发不出去的
assert (await session.execute(select(Task).where(Task.run_id == run_id))).scalars().all() == []
async def test_a_changed_params_schema_does_not_fail_a_write_that_already_went_out(erp, capabilities):
"""发出之后能力的参数定义改了(升级时停在结果未知的运行):先查记录再收类型。结果未知的照旧挂起等核实,核实为已生效
之后节点重新执行交回存下的回执——手上的「1,280」收不成新声明的数,也不把已经生效的写入判成失败。"""
caps = capabilities(await _endpoint(test=True), lookup=True)
erp.mode = "timeout_after_write"
run_id = await _formal(pay_graph(), amount="1,280")
await _confirm(run_id)
assert (await _wait(run_id, ("interrupted", "failed", "succeeded"))).status == "interrupted"
[rec] = await _records(run_id)
assert rec.state == "unknown" and rec.preview["amount"] == "1,280"
caps[PAY].params_schema = {"type": "object", "properties": {"amount": {"type": "number"}}}
args = {"amount": "1,280", "card": "6222020200112233"}
with pytest.raises(actions.ActionPending):
await actions.prepare(run_id=run_id, node_id="pay", exec_no=1, capability=caps[PAY], args=args)
assert await actions.tick(utcnow() + timedelta(minutes=2)) == 1
final = await _wait(run_id, ("succeeded", "failed"))
assert final.status == "succeeded", final.error
assert len(erp.writes()) == 1
[rec] = await _records(run_id)
assert rec.state == "confirmed"
# 再执行一次(接着跑、重放):交回生效那一次的回执,指纹、预览照记录,不按这一次的参数重算
prep = await actions.prepare(run_id=run_id, node_id="pay", exec_no=1, capability=caps[PAY], args=args)
assert prep.receipt is not None and prep.receipt["receipt"]["id"] == final.output["单号"]
assert (prep.payload_hash, prep.preview["amount"], prep.attempt) == (rec.payload_hash, "1,280", 1)
# 真要发的(新的一次执行)照旧按参数定义收类型:收不成的不发
with pytest.raises(actions.ActionFailed, match="参数 amount 应为数"):
await actions.prepare(run_id=run_id, node_id="pay", exec_no=2, capability=caps[PAY], args=args)
assert len(erp.writes()) == 1
# --------------------------------------------------------------------------
# 实例页怎么说:驳回动作确认、结果未知、核实之后
# --------------------------------------------------------------------------
async def _instance_view(run_id: str) -> dict:
"""按一页实例页(概况、进度、付款的动作状态)解析这次运行:{组件 id: data}。"""
from app.apps.resolve import resolve_page
from app.db.models import App, AppVersion
spec = {"format": "agentlab.app/1", "name": "付款", "pages": [{"id": "instance", "title": "实例", "body": [
{"id": "hdr", "type": "instance_header"}, {"id": "tl", "type": "instance_timeline"},
{"id": "act", "type": "action_status", "props": {"label": "付款"}, "bind": {"action": "pay"}}]}]}
async with SessionLocal() as session:
app = App(name="付款", published_version=1)
session.add(app)
await session.flush()
version = AppVersion(app_id=app.id, version=1, spec=spec, spec_hash="x" * 64)
session.add(version)
await session.commit()
run = await session.get(Run, run_id)
vm = await resolve_page(session, app, page_id="instance", principal=ANN, role="manage", instance=run,
version=version)
return {n["id"]: n.get("data") for n in vm["tree"]}
async def test_a_rejected_confirmation_reads_as_a_decision_not_a_fault(erp, capabilities):
capabilities(await _endpoint(test=True), lookup=False)
run_id = await _formal(pay_graph())
task = await _task(run_id, "action_confirm")
await tasks.respond(task.id, ANN, decision="reject", note="金额不对")
final = await _wait(run_id, ("succeeded", "failed"))
# 引擎里驳回就是节点失败、运行结束(没有可走的出口);说法写成未确认(被驳回),实例页按人的决定说
assert final.status == "failed" and final.error.startswith("「pay」未确认(被驳回),没有发送:金额不对")
view = await _instance_view(run_id)
assert (view["hdr"]["status_code"], view["hdr"]["status_text"]) == ("cancelled", "「pay」未确认(被驳回)")
step = next(s for s in view["tl"]["steps"] if s["node"] == "pay")
assert (step["state"], step["text"]) == ("rejected", "未确认(被驳回)")
assert erp.requests == []
async def test_unknown_then_reconciled_reads_as_waiting_then_a_footnote(erp, capabilities):
capabilities(await _endpoint(test=True), lookup=True)
erp.mode = "timeout_after_write"
run_id = await _formal(pay_graph())
await _confirm(run_id)
await _wait(run_id, ("interrupted",))
view = await _instance_view(run_id)
# 结果未知:在等核实,不是「等待审批」;付款这一步不是「完成」
assert (view["hdr"]["status_code"], view["hdr"]["status_text"]) == ("waiting", "等待核实写入结果")
step = next(s for s in view["tl"]["steps"] if s["node"] == "pay")
assert (step["state"], step["text"]) == ("unknown", "结果未知,等待核实")
[row] = view["act"]["records"]
assert row["state"] == "unknown" and "error" not in row and "ReadTimeout" in row["note"]
assert await actions.tick(utcnow() + timedelta(minutes=2)) == 1
final = await _wait(run_id, ("succeeded", "failed"))
assert final.status == "succeeded", final.error
view = await _instance_view(run_id)
assert view["hdr"]["status_text"] == "已完成"
assert next(s for s in view["tl"]["steps"] if s["node"] == "pay")["state"] == "done"
[row] = view["act"]["records"]
# 核实为已生效之后:第一次发送超时只作历史记一笔,不再当失败原因
assert row["state"] == "confirmed" and "error" not in row
assert "ReadTimeout" in row["note"] and "按幂等键查询核实为已生效" in row["note"]
+59 -3
View File
@@ -2,6 +2,7 @@
- 变量都按 fire_at(计划触发时间)在任务时区算,不按「现在」:补跑晚了一小时,昨天还是计划那天的昨天
- 跨月、跨年、跨时区(同一时刻在上海已经是周一,在纽约还是周日);周从周一算起
- ISO 周(2026-W42)的年份跟着周走:2026-12-31、2027-01-01 都是 2026-W53,2025-12-29 是 2026-W01;月份写 YYYY-MM
- schedule.last_fire_time 是上一次计划触发的时间(按 cron 往前找),和本次一样写成带偏移的 ISO 时间
- 模板写错(未知变量、未知过滤器、{{ }} 不成对、空的 {{ }}、值不是文本)抛 TemplateError,中文说明哪个输入
- 声明了入口字段的工作流:模板里多出来的字段名、缺的必填输入(没有默认值)都拦下
@@ -34,9 +35,15 @@ def test_monday_morning_in_shanghai():
assert v == {
"today": "2026-10-05",
"yesterday": "2026-10-04",
"this_week": "2026-W41",
"last_week": "2026-W40",
"week_before_last": "2026-W39",
"this_week_start": "2026-10-05",
"last_week_start": "2026-09-28",
"last_week_end": "2026-10-04",
"this_month": "2026-10",
"last_month": "2026-09",
"month_before_last": "2026-08",
"this_month_start": "2026-10-01",
"last_month_start": "2026-09-01",
"last_month_end": "2026-09-30",
@@ -62,6 +69,45 @@ def test_across_a_year_boundary():
assert v["last_fire_time"] == "2026-12-01T08:00:00+08:00"
@pytest.mark.parametrize("day, this_week, last_week, before_last", [
# 2026 年 1 月 1 日是周四,这一年有 53 周:年底那几天、2027 年开头的周五到周日都还在 2026-W53
((2026, 12, 31), "2026-W53", "2026-W52", "2026-W51"),
((2027, 1, 1), "2026-W53", "2026-W52", "2026-W51"),
((2027, 1, 3), "2026-W53", "2026-W52", "2026-W51"),
# 周一换周:上周是上一年的最后一周
((2027, 1, 4), "2027-W01", "2026-W53", "2026-W52"),
# 反过来,2025 年最后几天已经算 2026 年的第 1 周
((2025, 12, 29), "2026-W01", "2025-W52", "2025-W51"),
((2026, 1, 5), "2026-W02", "2026-W01", "2025-W52"),
])
def test_iso_weeks_across_the_year(day, this_week, last_week, before_last):
"""ISO 周的年份是周所在的年,不是日历年;周号补足两位"""
y, m, d = day
v = values(datetime(y, m, d, 1, 0, tzinfo=UTC)) # 上海当天 09:00
assert (v["this_week"], v["last_week"], v["week_before_last"]) == (this_week, last_week, before_last)
def test_iso_week_and_month_follow_the_schedule_timezone():
"""UTC 2026-12-31 16:30:上海已经是 2027-01-01 00:30(周五,仍在 2026-W53),伦敦还是 2026-12-31"""
moment = datetime(2026, 12, 31, 16, 30, tzinfo=UTC)
shanghai = values(moment, "Asia/Shanghai", "30 0 * * *")
london = values(moment, "Europe/London", "30 16 * * *")
assert (shanghai["this_week"], shanghai["this_month"], shanghai["last_month"], shanghai["month_before_last"]) == (
"2026-W53", "2027-01", "2026-12", "2026-11")
assert (london["this_week"], london["this_month"], london["last_month"]) == ("2026-W53", "2026-12", "2026-11")
# 跨到周一那一刻:上海已经是 2027-W01,纽约还在 2026-W53
monday = datetime(2027, 1, 3, 20, 0, tzinfo=UTC)
assert values(monday, "Asia/Shanghai", "0 4 * * *")["this_week"] == "2027-W01"
assert values(monday, "America/New_York", "0 15 * * *")["this_week"] == "2026-W53"
def test_months_across_a_year_boundary():
v = values(datetime(2027, 2, 1, 1, 0, tzinfo=UTC), cron="0 9 1 * *")
assert (v["this_month"], v["last_month"], v["month_before_last"]) == ("2027-02", "2027-01", "2026-12")
v = values(datetime(2027, 1, 1, 1, 0, tzinfo=UTC), cron="0 9 1 * *")
assert (v["this_month"], v["last_month"], v["month_before_last"]) == ("2027-01", "2026-12", "2026-11")
def test_leap_february_ends_on_the_29th():
v = values(datetime(2028, 3, 1, 1, 0, tzinfo=UTC), cron="0 9 1 * *")
assert (v["last_month_start"], v["last_month_end"]) == ("2028-02-01", "2028-02-29")
@@ -98,6 +144,11 @@ def test_render_inputs():
"tag": "{{ schedule.today | upper }}",
}, v)
assert out == {"stat_date": "2026-10-04", "week": "2026-09-28~2026-10-04", "region": "华东", "tag": "2026-10-05"}
# 按周统计的周报:周一早上出上周的报告,和上上周比
weekly = service.render_inputs({"week": "{{ schedule.last_week }}", "prev_week": "{{ schedule.week_before_last }}",
"month": "{{ schedule.last_month }}"}, v)
assert weekly == {"week": "2026-W40", "prev_week": "2026-W39", "month": "2026-09"}
assert service.check_template({"week": "{{ schedule.this_week }}", "month": "{{ schedule.this_month }}"})
def test_valid_templates_pass():
@@ -135,12 +186,17 @@ def test_variable_catalog():
items = service.variables(datetime(2026, 10, 5, 1, 0, tzinfo=UTC), "Asia/Shanghai")
names = [i["name"] for i in items]
assert names == [f"schedule.{key}" for key in (
"today", "yesterday", "this_week_start", "last_week_start", "last_week_end",
"this_month_start", "last_month_start", "last_month_end", "fire_time", "last_fire_time")]
"today", "yesterday", "this_week", "last_week", "week_before_last", "this_week_start", "last_week_start",
"last_week_end", "this_month", "last_month", "month_before_last", "this_month_start", "last_month_start",
"last_month_end", "fire_time", "last_fire_time")]
by_name = {i["name"]: i for i in items}
assert by_name["schedule.yesterday"] == {"name": "schedule.yesterday", "label": "昨天(YYYY-MM-DD)",
"example": "2026-10-04"}
"example": "2026-10-04", "note": ""}
assert by_name["schedule.last_week"]["example"] == "2026-W40" and "2026-W53" in by_name["schedule.last_week"]["note"]
assert by_name["schedule.this_month"]["example"] == "2026-10"
assert all(i["label"] and i["example"] for i in items)
# 补充说明只写在 ISO 周上
assert [i["name"] for i in items if i["note"]] == ["schedule.this_week", "schedule.last_week", "schedule.week_before_last"]
# --------------------------------------------------------------------------
+1 -1
View File
@@ -522,7 +522,7 @@ async def test_variables(client):
res = await client.get("/api/schedules/variables")
assert res.status_code == 200
items = res.json()
assert len(items) == 10 and all(set(i) == {"name", "label", "example"} for i in items)
assert len(items) == 16 and all(set(i) == {"name", "label", "example", "note"} for i in items)
assert {"name": "schedule.yesterday", "label": "昨天(YYYY-MM-DD)"}.items() <= next(
i for i in items if i["name"] == "schedule.yesterday").items()
assert (await client.get("/api/schedules/variables", params={"timezone": "Nowhere/City"})).status_code == 422
+48 -2
View File
@@ -1,8 +1,9 @@
"""内置模板「⑨ 可追溯周报」:tool 查库 → 解析 → 口径卡 → 报告撰写 → 出具(引用模式)。
"""内置模板「⑨ 可追溯周报」:tool 查库 → 口径卡 → 报告撰写 → 出具(引用模式)。
模板既是示范也是活文档:它要能通过 validate_graph,接上一个真实的库(这里用
SQLite 建一个示例 shop 库)要能从头跑到尾、完整出具,报告里每个数都点得开。
模板里只许出现通用示例名。
口径卡用 cell() 按列名取查询结果的格,每个指标的输入都一路追到查询快照(engine/lineage.py):
模板教的就是这种写法。模板里只许出现通用示例名。
"""
from __future__ import annotations
@@ -44,12 +45,57 @@ def test_template_passes_validation():
assert {"name": "周报", "value": f"{{{{ nodes.{report_id}.text }}}}"} in out["data"]["config"]["fields"]
def test_every_metric_of_the_template_reaches_the_query_snapshot():
"""口径卡的每个指标都用 cell() 取数:静态地认(和应用检查同一套),没有一个输入停在半路。"""
from app.apps.tree import node_map
from app.engine.lineage import static_stops
nodes = node_map(graph())
[card] = [n for n in nodes.values() if n["type"] == "metrics"]
metrics = card["config"]["metrics"]
assert metrics and all("cell(nodes.fetch" in m["expression"] for m in metrics)
assert {m["id"]: static_stops(nodes, m["expression"]) for m in metrics} == {m["id"]: [] for m in metrics}
async def test_every_metric_of_a_run_is_traced_to_the_snapshot(engine_up, shop, monkeypatch, client):
"""跑一遍:每个指标的输入都是单元格取数、与快照一致;证据接口的指标步骤说输入都追到了原始数据。"""
from app.providers import mock_model
monkeypatch.setattr(mock_model.MockChatModel, "_decide",
lambda self, messages: AIMessage(content="销售额 [[m:gmv]]。[[see:m:gmv]]"))
run = await run_manager.start(graph=graph(), input_payload={})
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:
break
assert row.status == "succeeded", row.error
for metric in ("gmv", "orders", "wow", "aov", "refund_rate"):
chain = (await client.get(f"/api/runs/{run.id}/evidence/metrics/caliber/{metric}")).json()["chain"]
step = chain[0]
assert step["step"] == "metric" and step["untraced"] == [], (metric, step.get("untraced"))
inputs = [s for s in chain if s["step"] == "input"]
assert inputs and all(i["via"] == "tool_cell" and i["status"] == "verified" for i in inputs), metric
assert chain[-1]["step"] == "query"
def test_template_is_listed_once_and_keeps_template_eight():
names = [t["name"] for t in TEMPLATES]
assert names.count(NAME) == 1
assert any(n.startswith("⑧ 周报") for n in names) # 老模板不改,免得覆盖用户复制过的那一份
@pytest.fixture
async def client():
from httpx import ASGITransport, AsyncClient
from app.main import app
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
yield c
@pytest.fixture
async def engine_up():
await run_manager.setup()
+34
View File
@@ -349,6 +349,40 @@ async def test_cell_lineage_points_at_the_exact_cell(engine_up, shop):
assert prev["eid"] == make_eid("cell", query["artifact"], {"row": 0, "column": "gmv_prev"})
async def test_a_positional_cell_through_a_plain_parse_reaches_the_snapshot(engine_up, shop):
"""数据整形只是把调用工具节点的结果原样按 JSON 解析(模板整串就是 {{ nodes.fetch }}):vars.q.rows[0][0] 确定地对到
查询快照的第 0 行第 0 列,和 cell() 一样核对快照、带 locator / artifact / eid,through 记下穿过的整形节点。
nodes.parse.rows[0]['gmv'] 按列名取也一样。模板带了过滤器、或者多包了一层的,不算原样解析:照旧记成数据整形的产出。"""
card = node("card", "metrics", caliber="周报口径", metrics=[
{"id": "gmv", "name": "销售额", "unit": "元", "decimals": 2, "format": "thousands",
"expression": "vars.q.rows[0][0]"},
{"id": "prev", "name": "上期", "decimals": 1, "format": "plain", "expression": "nodes.parse.rows[0]['gmv_prev']"},
{"id": "raw", "name": "过滤器", "decimals": 1, "format": "plain", "expression": "vars.raw.rows[0][0]"},
{"id": "wrap", "name": "包一层", "decimals": 1, "format": "plain", "expression": "vars.w.res.rows[0][0]"},
])
parse = node("parse", "transform", mode="json", template="{{ nodes.fetch }}", assign_to="q")
raw = node("parse_raw", "transform", mode="json", template="{{ nodes.fetch | trim }}", assign_to="raw")
wrap = node("wrap_n", "transform", mode="json", template='{"res": {{ nodes.fetch }}}', assign_to="w")
row = await finish(fetch_graph(parse, raw, wrap, card))
assert row.status == "succeeded", row.error
query = next(e for e in await ledger(row.id) if e["kind"] == "query")
finished = (await events(row.id, "node.finished", "card"))[0]
metrics = {m["id"]: m for m in artifact_store.load(finished.data["artifact"])["metrics"]}
gmv = metrics["gmv"]
assert gmv["value"] == 600.5 and gmv["recompute_ok"] is True
[cell] = gmv["inputs"]
assert cell == {"path": "vars.q.rows[0][0]", "value": 600.5, "node_id": "fetch", "via": "tool_cell",
"through": "parse", "status": "verified", "locator": {"row": 0, "column": "gmv"},
"artifact": query["artifact"], "eid": make_eid("cell", query["artifact"], {"row": 0, "column": "gmv"})}
[by_name] = metrics["prev"]["inputs"]
assert (by_name["via"], by_name["through"], by_name["locator"], by_name["status"]) == (
"tool_cell", "parse", {"row": 0, "column": "gmv_prev"}, "verified")
for metric_id, writer in (("raw", "parse_raw"), ("wrap", "wrap_n")):
[item] = metrics[metric_id]["inputs"]
assert (item["via"], item["node_id"]) == ("transform", writer) and "through" not in item, item
async def test_card_computes_on_integer_decimal_text(engine_up, shop):
"""sqlite 没有 DECIMAL:CAST(… AS TEXT) 落进快照的,和 MySQL 整数列 SUM() 的 str(Decimal) 一模一样。"""
sql = ("SELECT CAST(SUM(refunded) AS TEXT) AS refunds, CAST(COUNT(*) AS TEXT) AS orders "
+13 -5
View File
@@ -597,32 +597,40 @@ async def test_excluding_rows_of_an_old_run_never_says_unchanged(client, monkeyp
async def test_only_inputs_computed_after_the_snapshot_came_back_are_doubted(client, monkeypatch):
"""写在查询之前的容器(early)排除行影响不到它;查询之后才算出来、又对不上任何快照的(late)说不准。
按位置取自整份结果的一格(vars.res.rows[0][2])同样说不准:排除第 0 行后它取到的是另一行。"""
按位置取自整份结果的一格分两种:数据整形只是原样解析查询结果的(vars.res,模板整串就是 {{ nodes.fetch }}),那一格
卡上记成快照的第 0 行,和 cell() 一样——排除第 0 行,这个指标就照实说那一行已排除、算不出;模板带了过滤器的
(vars.raw)不算原样解析,认不出是快照的哪一行,说不准:排除第 0 行后它取到的是另一行。"""
metrics = [
{"id": "m_early", "name": "加早", "decimals": 1, "expression": f"round({AMOUNT5} + sum(vars.early.items), 1)"},
{"id": "m_late", "name": "加晚", "decimals": 1, "expression": f"round({AMOUNT5} + sum(vars.late.items), 1)"},
{"id": "first", "name": "首单占比", "decimals": 2,
"expression": "round(vars.res.rows[0][2] / len(vars.res.rows), 2)"},
{"id": "first_raw", "name": "首单占比(过滤器)", "decimals": 2,
"expression": "round(vars.raw.rows[0][2] / len(vars.raw.rows), 2)"},
]
row = await run_graph(monkeypatch, chain(
node("start", "input"),
node("early_n", "transform", mode="expression", expression="{'items': [1.5, 2.5]}", assign_to="early"),
node("fetch", "tool", tool="db_query__shop", args={"sql": SQL}),
node("parse", "transform", mode="json", template="{{ nodes.fetch }}", assign_to="res"),
node("parse_raw", "transform", mode="json", template="{{ nodes.fetch | trim }}", assign_to="raw"),
node("late_n", "transform", mode="expression", expression="{'items': [1.5, 2.5]}", assign_to="late"),
node("card", "metrics", caliber="推演口径", metrics=metrics),
node("write", "report", instructions="写周报", on_violation="flag"),
node("out", "output", fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}])),
text="加早 [[m:m_early]],加晚 [[m:m_late]],首单占比 [[m:first]]。")
text="加早 [[m:m_early]],加晚 [[m:m_late]],首单占比 [[m:first]],[[m:first_raw]]。")
snapshot = await snapshot_of(row.id)
assert [(m, s, new == old) for _, m, s, new, old in await faithful(row.id)] == [
("m_early", "ok", True), ("m_late", "ok", True), ("first", "ok", True)]
("m_early", "ok", True), ("m_late", "ok", True), ("first", "ok", True), ("first_raw", "ok", True)]
metrics = by_id(await whatif(client, row.id, {"card": "card", "overrides": {"exclude_rows": {snapshot: [0]}}}))
assert metrics["m_early"]["status"] == "unchanged" and metrics["m_early"]["changed"] is False
assert metrics["m_late"]["status"] == "unsupported" and "vars.late.items" in metrics["m_late"]["reason"]
assert "对不上任何查询快照" in metrics["m_late"]["reason"]
assert metrics["first"]["status"] == "unsupported" and metrics["first"]["new"] is None
assert "vars.res.rows[0][2]" in metrics["first"]["reason"]
assert metrics["first"]["status"] == "excluded" and metrics["first"]["new"] is None
assert "vars.res.rows[0][2] 所在的第 1 行已排除" in metrics["first"]["reason"], metrics["first"]["reason"]
assert metrics["first_raw"]["status"] == "unsupported" and metrics["first_raw"]["new"] is None
assert "vars.raw.rows[0][2]" in metrics["first_raw"]["reason"]
# --------------------------------------------------------------------------