Files
AgentLab/backend/tests/test_upgrade_assist.py
T
ThearchyHelios 050bea4b72 可点击证据第五期:老工作流一键升级为可追溯结构;受管问数据图的 cells 一键选;pytest 并行
一、一键升级(只给预览,不自动保存)

- engine/upgrade.py:确定性改写,纯函数、重复执行结果不变
  - R1 契约的叙述指向模型调用节点 → 换成报告撰写节点(system 和 prompt 合成写作要求,模型配置照搬),契约改成 report_from
  - R2 没有契约、但模型写的文字进了出口,而且上游有取数 → 同样换成报告撰写
  - R3 input → 智能体 → 出口(问数据的典型图)→ 中间插入报告撰写节点,出口字段接报告的正文;
    只改直接相连的出口,经过别的节点读它的出口原样保留并写明原因
  - R4 配了 output_schema 的智能体 → 打开 cite_fields
  - R5 代码节点的产出被口径卡读 → 不改,只建议标成取数,等人确认
  - 一个叙述里混了几个写作者的,不猜,整步不做并写明原因
- POST /api/copilot/upgrade-evidence:返回改动、说明和改完的检查结果;assist 时再交给 Copilot 把纯算术的代码节点
  改写成口径卡表达式,不是纯算术的保留并给警告
- 升级和发布前修复走同一道「不许降低要求」的检查,只多两个由升级点名的例外:模型调用换成报告撰写、R3 改接的那条连线;
  改完不能更糟
- 校验对符合 R1–R4 的旧结构给一条建议「可以升级为可追溯结构」,不算提示、不挡发布
- Copilot 自查:报告撰写节点上游没有任何能引用数字的来源时打回

二、界面

- 问题面板的快速修复「升级为可追溯结构(预览改动)」:逐项写「节点 · 字段:原值 → 新值」,节点类型的变化写成
  「模型调用 → 报告撰写」,新插的节点和改接的连线另外写明;「应用」后走现有的保存,全图默认不丢
- 画布改过、存失败、画布被锁都有明确状态;保存失败后手动存成功会清掉「没存上」的提示,
  画布和预览对不上时「重试保存」不再盲存;校验接口失败时升级块照样在
- 记录页里没有逐段证据的运行给横幅「这次的报告没有逐段证据 → 升级这张图」,跳到编排页并打开升级预览
- 修掉一处旧缺陷:应用修复时只换配置、不换节点类型,模型调用换成报告撰写后存下去的还是模型调用

三、受管门禁:cells 一键选

- 图里没有口径卡、契约又没写 cells: true 的受管图,以前能过门禁、正式运行却每次失败;现在门禁拦下,
  发布弹窗给两个选项:写 cells: true,或交给 Copilot 改成口径卡指标(人亲手选的不算替人打开,Copilot 自己打开照样拦)
- 「修完要更好」的复核不再把改完才冒出来、只能由人拍板的这一处算作改坏:Copilot 补上契约、把 cells 留给人问,
  这一步会被采用,不再被判「冒出新的问题」作废

四、测试

- 开发依赖加上 pytest-xdist(锁文件只多了 pytest-xdist 和 execnet):全量后端测试 -n auto 约 16 秒,原来串行约 2 分钟
- 修掉并行下暴露的一处测试竞态:运行先落终态、再另一个事务封存,测试改成等封存完成再核对
2026-09-29 13:27:27 +08:00

217 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""一键升级的语义层(assist: true):请 Copilot 把喂口径卡的纯算术沙箱代码改写成口径卡表达式。
模型一律用剧本,不调真接口。守这几件事:
- 纯算术的改写被采纳:口径卡的表达式改成直接读上游,代码节点留在图上,只是预览、不改库
- 删节点、放宽要求的改写整个作废,确定性改写的结果照样交出去
- 不是纯算术的保留原样并给警告;模型要人拿主意的原样放进 questions
- 改出新 error 的按自查循环交回去改,改不好就作废
- 没有要改写的代码节点时不调模型
"""
from __future__ import annotations
import json
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import select
from app.db.base import SessionLocal
from app.db.models import Workflow, WorkflowVersion
from app.main import app
@pytest.fixture
async def client():
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
yield c
def node(nid, ntype, label=None, x=0, **config):
return {"id": nid, "type": ntype, "position": {"x": x, "y": 80}, "data": {"label": label or nid, "config": config}}
def graph(*, summary_llm: bool = False) -> dict:
"""查库 → 沙箱代码算比率 → 口径卡读代码的产出 → 报告撰写(或者模型调用写总结)→ 出口。"""
writer = (node("write", "llm", "写总结", x=1120, prompt="写一句总结") if summary_llm
else node("write", "report", "报告撰写", x=1120, instructions="写一句话"))
return {
"nodes": [
node("start", "input", "输入", x=0),
node("fetch", "tool", "查库", x=280, tool="db_query__shop",
args={"sql": "SELECT SUM(amount) AS a, COUNT(*) AS b FROM orders"}),
node("calc", "code", "算比率", x=560, language="python", assign_to="calc",
code="import json\nprint(json.dumps({'ratio': 3 / 4}))"),
node("card", "metrics", "口径卡", x=840, metrics=[
{"id": "ratio", "name": "客单价", "expression": "vars.calc.ratio"}]),
writer,
node("out", "output", "成果", x=1400, fields=[{"name": "周报", "value": "{{ nodes.write.text }}"}]),
],
"edges": [{"id": f"e{i}", "source": a, "target": b} for i, (a, b) in enumerate(
[("start", "fetch"), ("fetch", "calc"), ("calc", "card"), ("card", "write"), ("write", "out")])],
}
class Scripted:
"""第一轮吐 first;收到自查请求(human 里有「上线前自查」)时吐 fix。记下每次的 human。"""
def __init__(self, first: list[dict], fix: list[dict] | None = None) -> None:
self.first = [json.dumps(o, ensure_ascii=False) for o in first]
self.fix = [json.dumps(o, ensure_ascii=False) for o in fix or []]
self.calls: list[str] = []
async def astream(self, messages):
from langchain_core.messages import AIMessageChunk
human = next(text for role, text in messages if role == "human")
self.calls.append(human)
for line in (self.fix if "上线前自查" in human else self.first):
yield AIMessageChunk(content=line + "\n")
def script(monkeypatch, first: list[dict], fix: list[dict] | None = None) -> Scripted:
import app.api.copilot as copilot
model = Scripted(first, fix)
async def _model(*_a, **_k):
return model, "mock-fast"
monkeypatch.setattr(copilot, "get_chat_model", _model)
return model
def wrap(*ops) -> list[dict]:
return [{"op": "plan", "summary": "把纯算术的代码挪进口径卡"}, *ops,
{"op": "done", "explanation": "客单价改由口径卡直接算"}]
REWRITE = {"op": "update_node", "id": "card", "config": {"metrics": [
{"id": "ratio", "name": "客单价", "expression": "cell(nodes.fetch, 0, 'a') / cell(nodes.fetch, 0, 'b')"}]}}
def by_id(g: dict) -> dict:
return {n["id"]: n for n in g["nodes"]}
async def upgrade(client, g: dict, **extra) -> dict:
r = await client.post("/api/copilot/upgrade-evidence", json={"graph": g, "assist": True, **extra})
assert r.status_code == 200, r.text
return r.json()
async def rows() -> list:
async with SessionLocal() as session:
return [sorted(repr({c.name: getattr(r, c.name) for c in m.__table__.columns})
for r in (await session.execute(select(m))).scalars())
for m in (Workflow, WorkflowVersion)]
async def test_a_pure_arithmetic_rewrite_is_adopted_as_a_preview(client, monkeypatch):
model = script(monkeypatch, wrap(REWRITE))
await client.post("/api/workflows", json={"name": "升级-兜底", "graph": graph()})
before = await rows()
body = await upgrade(client, graph())
assert body["assist"]["ok"] is True and body["assist"]["summary"] == "客单价改由口径卡直接算"
assert body["assist"]["warnings"] == [] and "assist" in body["applied"]
g = body["graph"]
assert by_id(g)["card"]["data"]["config"]["metrics"][0]["expression"] == REWRITE["config"]["metrics"][0]["expression"]
assert by_id(g)["calc"]["data"]["config"] == graph()["nodes"][2]["data"]["config"] # 代码节点留着、不替人标 source
assert [c for c in body["changes"] if c["rule"] == "assist"] == [
{"fix_id": "assist", "rule": "assist", "node_id": "card", "node_title": "口径卡", "field": "metrics",
"before": graph()["nodes"][3]["data"]["config"]["metrics"], "after": REWRITE["config"]["metrics"],
"label": "Copilot 的修改"}]
assert body["ops"][-1] == REWRITE
assert not [n for n in body["notes"] if n["rule"] == "R5"] # 口径卡不再读它,建议随之作废
assert await rows() == before # 只是预览
human = model.calls[0]
assert "纯算术" in human and "「算比率」(calc)" in human and "vars.calc.ratio" in human
assert "不许降低要求" in human and "不替人选" in human and "只改上面这些口径卡指标的 expression" in human
assert "只修下面列出的问题" not in human
async def test_the_prompt_names_the_metrics_that_read_the_code_through_a_reshaper(client, monkeypatch):
# 代码 → 整形 → 口径卡:口径卡的指标读的是整形节点,追到头才是这段代码,要改写的表达式照样得列给模型
g = graph()
g["nodes"].insert(3, node("shape", "transform", "整形", x=700, template="{{ vars.calc }}", assign_to="shaped"))
g["nodes"][4]["data"]["config"]["metrics"] = [
{"id": "ratio", "name": "客单价", "expression": "vars.shaped.ratio"},
{"id": "orders", "name": "订单数", "expression": "cell(nodes.fetch, 0, 'b')"}]
g["edges"] = [{"id": f"e{i}", "source": a, "target": b} for i, (a, b) in enumerate(
[("start", "fetch"), ("fetch", "calc"), ("calc", "shape"), ("shape", "card"), ("card", "write"),
("write", "out")])]
model = script(monkeypatch, wrap({"op": "question", "node_id": "calc", "text": "拿不准"}))
await upgrade(client, g)
[line] = [ln for ln in model.calls[0].splitlines() if ln.startswith("- 「算比率」(calc)")]
assert "ratio" in line and "vars.shaped.ratio" in line
assert "orders" not in line # 不读这段代码的指标不列
async def test_deleting_the_code_node_is_refused_and_the_deterministic_result_stays(client, monkeypatch):
script(monkeypatch, wrap(REWRITE, {"op": "remove_node", "id": "calc"}))
body = await upgrade(client, graph(summary_llm=True))
assert body["assist"]["ok"] is False and "assist" not in body["applied"]
[rejected] = [r for r in body["rejected"] if r["fix_id"] == "assist"]
assert "降低" in rejected["reason"] and "算比率" in rejected["reason"]
g = body["graph"]
assert "calc" in by_id(g) and by_id(g)["write"]["type"] == "report" # R2 照样生效
assert by_id(g)["card"]["data"]["config"]["metrics"][0]["expression"] == "vars.calc.ratio"
assert body["applied"] == ["R2:write"]
assert any("算比率" in w for w in body["assist"]["warnings"])
async def test_non_arithmetic_code_is_kept_with_a_warning(client, monkeypatch):
script(monkeypatch, wrap({"op": "question", "node_id": "calc", "text": "它读了一个文件,像是在取数,请确认"}))
body = await upgrade(client, graph())
assert body["assist"]["ok"] is True and body["applied"] == []
assert body["assist"]["questions"] == ["「算比率」:它读了一个文件,像是在取数,请确认"]
[warning] = body["assist"]["warnings"]
assert "算比率" in warning and "evidence_role" in warning and "口径卡" in warning
assert body["graph"] == graph()
assert [n["node_id"] for n in body["notes"] if n["rule"] == "R5"] == ["calc"]
async def test_nothing_to_rewrite_means_no_model_call(client, monkeypatch):
g = graph()
g["nodes"][2]["data"]["config"]["evidence_role"] = "source"
model = script(monkeypatch, wrap(REWRITE))
body = await upgrade(client, g)
assert model.calls == [] and body["assist"]["ok"] is True and body["assist"]["warnings"] == []
assert "没有要交给 Copilot 改写的" in body["assist"]["summary"]
async def test_a_new_error_is_sent_back_once_and_fixed(client, monkeypatch):
broken = {"op": "update_node", "id": "card", "config": {"metrics": [
{"id": "ratio", "name": "客单价", "expression": "cell(nodes.fetch, 0, 'a') /"}]}}
model = script(monkeypatch, wrap(broken), [REWRITE, {"op": "done"}])
body = await upgrade(client, graph())
assert len(model.calls) == 2 and "上线前自查" in model.calls[1] and "表达式" in model.calls[1]
assert body["assist"]["ok"] is True and "assist" in body["applied"]
assert body["assist"]["summary"] == "客单价改由口径卡直接算" # 修补轮的 done 不盖掉说明
expr = by_id(body["graph"])["card"]["data"]["config"]["metrics"][0]["expression"]
assert expr == REWRITE["config"]["metrics"][0]["expression"]
async def test_a_rewrite_that_stays_broken_is_refused(client, monkeypatch):
broken = {"op": "update_node", "id": "card", "config": {"metrics": [
{"id": "ratio", "name": "客单价", "expression": "cell(nodes.fetch, 0, 'a') /"}]}}
model = script(monkeypatch, wrap(broken), [broken, {"op": "done"}])
body = await upgrade(client, graph())
assert len(model.calls) == 3 # 最多交回去改两轮
assert body["assist"]["ok"] is False and "assist" not in body["applied"]
[rejected] = [r for r in body["rejected"] if r["fix_id"] == "assist"]
assert "变糟" in rejected["reason"]
assert by_id(body["graph"])["card"]["data"]["config"]["metrics"][0]["expression"] == "vars.calc.ratio"
async def test_marking_the_code_as_a_source_is_not_the_copilots_call(client, monkeypatch):
script(monkeypatch, wrap({"op": "update_node", "id": "calc", "config": {"evidence_role": "source"}}))
body = await upgrade(client, graph())
[rejected] = [r for r in body["rejected"] if r["fix_id"] == "assist"]
assert "source" in rejected["reason"] and body["graph"] == graph()
async def test_without_assist_there_is_no_model_call(client, monkeypatch):
model = script(monkeypatch, wrap(REWRITE))
r = await client.post("/api/copilot/upgrade-evidence", json={"graph": graph()})
assert r.json()["assist"] is None and model.calls == []