mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-23 01:41:59 +00:00
合入 W1-c 数据事件触发:定时任务加「事件触发」(上传表格出新一期、上游工作流正式运行成功结束、数据源有要处理的变化),事件在发生处写进待派发事件、调度循环去抖派发;保存时与运行时防环;{{ event.* }} 模板变量;途经驳回、应用补算的缺省不认(可勾选);积压一拍处理完、过期的合成一条跳过;按期次分窗口;定时页可选「定时 / 事件触发」
This commit is contained in:
@@ -0,0 +1,494 @@
|
||||
"""数据事件触发(docs/design/orchestration-round/00-总方案.md §4;scheduler/triggers.py、scheduler/outbox.py)。
|
||||
|
||||
- 三种事件在发生处各记一条待派发事件,调度的一拍取走、派给合条件的事件触发任务、发起一次正式运行:
|
||||
上传表格按期累积的新一期启用(data/table_versions)、正式运行成功结束(engine/runner 收尾)、探查 / 剖析新记了要处理的变化
|
||||
(data/source_changes.notify_after_job,一个任务一条);探索运行、失败的运行不算;
|
||||
- 输入模板里的 {{ event.* }} 按事件渲染(上游的出口字段、这一期、变化的条数);触发记录 kind=event、inputs 带事件的说明;
|
||||
运行来源 origin_kind=schedule,origin.trigger 带事件种类、对象、事件 id、触发深度;
|
||||
- 去抖:同一个任务 debounce_s 内的几次事件合成一次,内容取最新的那一条,fire_at 是窗口结束的时刻;窗口外的另起一次;
|
||||
- 上一次还没结束照 overlap=skip 记 skipped_overlap;触发链超过 5 层不发起、照实记;派发得太晚(超出补发宽限)记 skipped_misfire;
|
||||
- 任务停用、改了触发条件时等着的不再派发;调度关着(没有这一拍)时事件留在表里;
|
||||
- 存量的 cron 任务一字不变(老测试照过,见 test_scheduler_loop.py 等)。
|
||||
|
||||
工作流、表格、数据源、字段都是虚构的。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import delete, select
|
||||
|
||||
from app.db.base import SessionLocal, utcnow
|
||||
from app.db.models import DataSource, Run, Schedule, ScheduleFire, Workflow, WorkflowVersion
|
||||
from app.db.models_sources import SourceChange
|
||||
from app.db.models_triggers import TriggerDelivery, TriggerEvent
|
||||
from app.engine.launch import launch_run
|
||||
from app.engine.runner import run_manager
|
||||
from app.scheduler import outbox, service, triggers
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def engine_up():
|
||||
await run_manager.setup()
|
||||
async with SessionLocal() as session:
|
||||
await session.execute(delete(TriggerDelivery))
|
||||
await session.execute(delete(TriggerEvent))
|
||||
await session.execute(delete(Schedule))
|
||||
await session.commit()
|
||||
yield
|
||||
await run_manager.shutdown()
|
||||
|
||||
|
||||
def node(nid, ntype, **config):
|
||||
return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": nid, "config": config}}
|
||||
|
||||
|
||||
def graph(fields: list[dict], value: str) -> dict:
|
||||
return {"nodes": [node("start", "input", fields=fields),
|
||||
node("out", "output", fields=[{"name": "r", "value": value}, {"name": "rows", "value": "12"}])],
|
||||
"edges": [{"source": "start", "target": "out"}]}
|
||||
|
||||
|
||||
async def workflow(name: str, *, fields: list[dict] | None = None, value: str = "完成") -> str:
|
||||
fields = fields if fields is not None else []
|
||||
async with SessionLocal() as session:
|
||||
wf = Workflow(name=f"{name}-{uuid.uuid4().hex[:6]}", graph=graph(fields, value), status="published",
|
||||
published_version=1)
|
||||
session.add(wf)
|
||||
await session.flush()
|
||||
session.add(WorkflowVersion(workflow_id=wf.id, version=1, graph=graph(fields, value)))
|
||||
await session.commit()
|
||||
return wf.id
|
||||
|
||||
|
||||
async def event_schedule(workflow_id: str, trigger: dict, *, template: dict | None = None, enabled: bool = True,
|
||||
grace: int = 3600, name: str = "下游汇总") -> str:
|
||||
async with SessionLocal() as session:
|
||||
row = Schedule(name=name, workflow_id=workflow_id, target_kind="workflow", target_id=workflow_id, cron="",
|
||||
timezone="Asia/Shanghai", run_class="formal", input_template=template or {}, enabled=enabled,
|
||||
misfire_grace_s=grace, next_run_at=None, trigger_kind="event",
|
||||
trigger=triggers.normalize(trigger))
|
||||
session.add(row)
|
||||
await session.commit()
|
||||
return row.id
|
||||
|
||||
|
||||
async def formal_run(workflow_id: str, inputs: dict | None = None, **origin) -> Run:
|
||||
async with SessionLocal() as session:
|
||||
run = await launch_run(session, workflow_id=workflow_id, run_class="formal", input_payload=inputs or {},
|
||||
actor="检查员", origin_kind=origin.pop("origin_kind", "launcher"), **origin)
|
||||
return await settle(run.id)
|
||||
|
||||
|
||||
async def settle(run_id: str) -> Run:
|
||||
for _ in range(400):
|
||||
async with SessionLocal() as session:
|
||||
row = await session.get(Run, run_id)
|
||||
if row.status in ("succeeded", "failed", "cancelled") and row.manifest_seq is not None:
|
||||
await run_manager.wait_idle(run_id)
|
||||
return row
|
||||
await asyncio.sleep(0.03)
|
||||
raise AssertionError(f"运行 {run_id} 停在 {row.status}")
|
||||
|
||||
|
||||
async def fires(schedule_id: str) -> list[ScheduleFire]:
|
||||
async with SessionLocal() as session:
|
||||
return list((await session.execute(select(ScheduleFire).where(ScheduleFire.schedule_id == schedule_id)
|
||||
.order_by(ScheduleFire.created_at))).scalars())
|
||||
|
||||
|
||||
async def events(kind: str | None = None, subject: str | None = None) -> list[TriggerEvent]:
|
||||
async with SessionLocal() as session:
|
||||
q = select(TriggerEvent).order_by(TriggerEvent.created_at)
|
||||
if kind:
|
||||
q = q.where(TriggerEvent.event == kind)
|
||||
if subject:
|
||||
q = q.where(TriggerEvent.subject_id == subject)
|
||||
return list((await session.execute(q)).scalars())
|
||||
|
||||
|
||||
async def deliveries(schedule_id: str) -> list[TriggerDelivery]:
|
||||
async with SessionLocal() as session:
|
||||
return list((await session.execute(select(TriggerDelivery).where(TriggerDelivery.schedule_id == schedule_id)
|
||||
.order_by(TriggerDelivery.occurred_at))).scalars())
|
||||
|
||||
|
||||
def later(seconds: float = 1) -> datetime:
|
||||
return utcnow() + timedelta(seconds=seconds)
|
||||
|
||||
|
||||
async def put_event(kind: str, subject: str, payload: dict, at: datetime, *, depth: int = 0,
|
||||
name: str = "门店日报") -> str:
|
||||
async with SessionLocal() as session:
|
||||
ev = TriggerEvent(event=kind, subject_id=subject, subject_name=name, payload=payload, occurred_at=at,
|
||||
depth=depth, created_at=at)
|
||||
session.add(ev)
|
||||
await session.commit()
|
||||
return ev.id
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 上游工作流运行成功结束
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_workflow_finished_triggers_downstream_with_outputs():
|
||||
upstream = await workflow("门店日报", value="日报完成")
|
||||
downstream = await workflow("区域汇总", fields=[{"name": "basis", "required": True}, {"name": "run"}])
|
||||
sid = await event_schedule(downstream, {"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 0},
|
||||
template={"basis": "{{ event.outputs.r }}({{ event.outputs.rows }} 行)",
|
||||
"run": "{{ event.run_id }}"})
|
||||
a = await formal_run(upstream)
|
||||
[ev] = await events("workflow.finished", upstream)
|
||||
assert ev.status == "pending" and ev.payload["run_id"] == a.id and ev.depth == 0 and ev.chain == [a.id]
|
||||
# 发生处只记事件、不发起:调度的一拍之前下游什么都没有
|
||||
assert await fires(sid) == []
|
||||
|
||||
[fire] = await outbox.dispatch_due(later())
|
||||
assert (fire.kind, fire.status) == ("event", "started")
|
||||
assert fire.fire_at == ev.occurred_at # debounce 0:窗口结束就是事件发生的那一刻
|
||||
assert fire.inputs["inputs"] == {"basis": "日报完成(12 行)", "run": a.id}
|
||||
brief = fire.inputs["event"]
|
||||
assert (brief["event"], brief["subject_id"], brief["merged"], brief["depth"]) == (
|
||||
"workflow.finished", upstream, 1, 1)
|
||||
assert brief["text"].startswith("工作流「门店日报-") and f"#{a.id[:6]}" in brief["text"]
|
||||
b = await settle(fire.run_id)
|
||||
assert b.status == "succeeded" and b.schedule_id == sid and b.input == {"basis": "日报完成(12 行)", "run": a.id}
|
||||
assert b.origin_kind == "schedule"
|
||||
trigger = b.origin["trigger"]
|
||||
assert (trigger["kind"], trigger["event"], trigger["subject_id"], trigger["event_id"], trigger["depth"]) == (
|
||||
"event", "workflow.finished", upstream, ev.id, 1)
|
||||
assert trigger["chain"] == [a.id] and trigger["text"] == brief["text"]
|
||||
[delivery] = await deliveries(sid)
|
||||
assert (delivery.status, delivery.fire_id) == ("fired", fire.id)
|
||||
# 再来一拍:已经派完,不再发起
|
||||
assert await outbox.dispatch_due(later(2)) == [] and len(await fires(sid)) == 1
|
||||
# 应用页的印章「来源」照实写由什么事件触发
|
||||
from app.apps import resolve
|
||||
|
||||
async with SessionLocal() as session:
|
||||
said = await resolve._from_text(session, resolve.Source(id="v", kind="latest_sealed", state="ok", run=b))
|
||||
assert said == f"由事件触发:{brief['text']},定时任务「下游汇总」第 1 次"
|
||||
|
||||
|
||||
async def test_webhook_says_the_event(monkeypatch):
|
||||
"""事件触发的那一次推的通知:写「事件触发」和事件的说法,不写「计划触发」"""
|
||||
import json
|
||||
|
||||
import httpx
|
||||
|
||||
from app.core.crypto import encrypt
|
||||
from app.scheduler import webhook
|
||||
|
||||
sent: list[dict] = []
|
||||
monkeypatch.setattr(webhook, "_transport", httpx.MockTransport(
|
||||
lambda request: sent.append(json.loads(request.content)) or httpx.Response(200, json={})))
|
||||
upstream = await workflow("门店日报")
|
||||
sid = await event_schedule(await workflow("区域汇总"),
|
||||
{"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 0})
|
||||
async with SessionLocal() as session:
|
||||
await session.execute(Schedule.__table__.update().where(Schedule.id == sid).values(
|
||||
webhook_format="generic", webhook_url=encrypt("https://hooks.example.com/agentlab/inbox-9a1b"),
|
||||
webhook_events=["finished"]))
|
||||
await session.commit()
|
||||
a = await formal_run(upstream)
|
||||
[fire] = await outbox.dispatch_due(later())
|
||||
await settle(fire.run_id)
|
||||
for _ in range(3):
|
||||
await webhook.notify_due(later(120))
|
||||
[body] = sent
|
||||
assert body["fire_kind"] == "event" and body["event"] == "finished"
|
||||
assert f"事件触发:工作流「门店日报-" in body["text"] and f"(#{a.id[:6]})" in body["text"]
|
||||
assert "计划触发" not in body["text"]
|
||||
|
||||
|
||||
async def test_only_successful_formal_runs_are_events():
|
||||
wf = await workflow("门店日报")
|
||||
async with SessionLocal() as session:
|
||||
run = await launch_run(session, workflow_id=wf, run_class="exploratory", input_payload={}, actor="检查员",
|
||||
origin_kind="canvas")
|
||||
await settle(run.id)
|
||||
failing = await workflow("坏掉的日报", fields=[{"name": "d", "required": True}])
|
||||
async with SessionLocal() as session:
|
||||
bad = await launch_run(session, workflow_id=failing, run_class="formal", input_payload={}, actor="检查员",
|
||||
origin_kind="launcher")
|
||||
assert (await settle(bad.id)).status == "failed"
|
||||
assert await events("workflow.finished", wf) == [] and await events("workflow.finished", failing) == []
|
||||
|
||||
|
||||
async def test_workflow_filters_by_app_and_origin():
|
||||
upstream = await workflow("门店日报")
|
||||
downstream = await workflow("区域汇总")
|
||||
only_hook = await event_schedule(downstream, {"event": "workflow.finished", "workflow_id": upstream,
|
||||
"origin_kind": "hook", "debounce_s": 0})
|
||||
await formal_run(upstream) # 手动正式运行:不是钩子来的
|
||||
assert await outbox.dispatch_due(later()) == [] and await fires(only_hook) == []
|
||||
[ev] = await events("workflow.finished", upstream)
|
||||
assert (ev.status, ev.matched) == ("routed", 0)
|
||||
|
||||
|
||||
async def test_chain_deeper_than_limit_is_refused():
|
||||
"""防环的兜底:上游自己已经是事件触发链上的第 5 层,下游会是第 6 层,不发起、照实记"""
|
||||
upstream = await workflow("门店日报")
|
||||
downstream = await workflow("区域汇总")
|
||||
sid = await event_schedule(downstream, {"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 0})
|
||||
await put_event("workflow.finished", upstream, {"workflow": "门店日报", "workflow_id": upstream, "run_id": "r5"},
|
||||
utcnow(), depth=triggers.MAX_DEPTH)
|
||||
[fire] = await outbox.dispatch_due(later())
|
||||
assert (fire.status, fire.run_id) == ("failed_to_start", None)
|
||||
assert "第 6 层(上限 5 层)" in fire.reason and "循环触发" in fire.reason
|
||||
assert fire.inputs["event"]["depth"] == 6
|
||||
|
||||
|
||||
async def test_chain_depth_follows_the_runs():
|
||||
"""A 跑完触发 B:B 的运行来源记第 1 层;B 跑完又是一个事件,深度跟着走、经过的运行接上"""
|
||||
a = await workflow("门店日报")
|
||||
b = await workflow("区域汇总")
|
||||
c = await workflow("全国汇总")
|
||||
await event_schedule(b, {"event": "workflow.finished", "workflow_id": a, "debounce_s": 0}, name="B")
|
||||
sc = await event_schedule(c, {"event": "workflow.finished", "workflow_id": b, "debounce_s": 0}, name="C")
|
||||
first = await formal_run(a)
|
||||
[fb] = await outbox.dispatch_due(later())
|
||||
run_b = await settle(fb.run_id)
|
||||
[ev_b] = await events("workflow.finished", b)
|
||||
assert ev_b.depth == 1 and ev_b.chain == [first.id, run_b.id]
|
||||
[fc] = [f for f in await outbox.dispatch_due(later(2)) if f.schedule_id == sc]
|
||||
run_c = await settle(fc.run_id)
|
||||
assert run_c.origin["trigger"]["depth"] == 2 and run_c.origin["trigger"]["chain"] == [first.id, run_b.id]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 去抖、重叠、停用、太晚
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_debounce_merges_events_in_the_window():
|
||||
upstream = await workflow("门店日报")
|
||||
downstream = await workflow("区域汇总", fields=[{"name": "run"}])
|
||||
sid = await event_schedule(downstream, {"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 60},
|
||||
template={"run": "{{ event.run_id }}"})
|
||||
t0 = utcnow().replace(microsecond=0)
|
||||
payload = lambda rid: {"workflow": "门店日报", "workflow_id": upstream, "run_id": rid} # noqa: E731
|
||||
e1 = await put_event("workflow.finished", upstream, payload("run-1"), t0)
|
||||
e2 = await put_event("workflow.finished", upstream, payload("run-2"), t0 + timedelta(seconds=30))
|
||||
# 窗口还没过:只派、不发
|
||||
assert await outbox.dispatch_due(t0 + timedelta(seconds=40)) == []
|
||||
assert [d.status for d in await deliveries(sid)] == ["pending", "pending"]
|
||||
async with SessionLocal() as session:
|
||||
state = await outbox.pending_for(session, await session.get(Schedule, sid))
|
||||
assert state == {"events": 0, "waiting": 2, "due_at": (t0 + timedelta(seconds=60)).isoformat()}
|
||||
e3 = await put_event("workflow.finished", upstream, payload("run-3"), t0 + timedelta(seconds=70))
|
||||
[fire] = await outbox.dispatch_due(t0 + timedelta(seconds=61))
|
||||
assert fire.fire_at == t0 + timedelta(seconds=60) and fire.kind == "event"
|
||||
assert fire.inputs["event"]["merged"] == 2 and fire.inputs["event"]["event_ids"] == [e1, e2]
|
||||
# 内容取窗口里最新的那一条
|
||||
assert fire.inputs["inputs"] == {"run": "run-2"}
|
||||
await settle(fire.run_id)
|
||||
states = {d.event_id: (d.status, d.fire_id) for d in await deliveries(sid)}
|
||||
assert states[e1] == states[e2] == ("fired", fire.id) and states[e3] == ("pending", None)
|
||||
# 窗口外的那一条另起一次:从它发生起再等 60 秒
|
||||
assert await outbox.dispatch_due(t0 + timedelta(seconds=100)) == []
|
||||
[second] = await outbox.dispatch_due(t0 + timedelta(seconds=131))
|
||||
assert second.fire_at == t0 + timedelta(seconds=130) and second.inputs["event"]["event_ids"] == [e3]
|
||||
await settle(second.run_id)
|
||||
|
||||
|
||||
async def test_previous_run_still_going_skips_and_consumes_the_events():
|
||||
upstream = await workflow("门店日报")
|
||||
downstream = await workflow("区域汇总")
|
||||
sid = await event_schedule(downstream, {"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 0})
|
||||
async with SessionLocal() as session:
|
||||
busy = Run(workflow_id=downstream, workflow_name="区域汇总", status="running", schedule_id=sid,
|
||||
run_class="formal")
|
||||
session.add(busy)
|
||||
await session.commit()
|
||||
await put_event("workflow.finished", upstream, {"workflow_id": upstream, "run_id": "r1"}, utcnow())
|
||||
[fire] = await outbox.dispatch_due(later())
|
||||
assert (fire.status, fire.run_id, fire.kind) == ("skipped_overlap", None, "event")
|
||||
assert f"上一次运行 #{busy.id[:6]} 仍在进行中" in fire.reason
|
||||
assert [d.status for d in await deliveries(sid)] == ["fired"]
|
||||
assert await outbox.dispatch_due(later(2)) == []
|
||||
|
||||
|
||||
async def test_disabled_or_changed_schedule_drops_waiting_events():
|
||||
upstream = await workflow("门店日报")
|
||||
other = await workflow("别的日报")
|
||||
downstream = await workflow("区域汇总")
|
||||
off = await event_schedule(downstream, {"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 60},
|
||||
name="停用的")
|
||||
moved = await event_schedule(downstream, {"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 60},
|
||||
name="改了对象的")
|
||||
t0 = utcnow()
|
||||
await put_event("workflow.finished", upstream, {"workflow_id": upstream, "run_id": "r1"}, t0)
|
||||
await outbox.route(t0 + timedelta(seconds=1))
|
||||
async with SessionLocal() as session:
|
||||
await session.execute(Schedule.__table__.update().where(Schedule.id == off).values(enabled=False))
|
||||
await session.execute(Schedule.__table__.update().where(Schedule.id == moved).values(
|
||||
trigger={"event": "workflow.finished", "workflow_id": other, "debounce_s": 60}))
|
||||
await session.commit()
|
||||
assert await outbox.dispatch_due(t0 + timedelta(seconds=61)) == []
|
||||
assert [d.status for d in await deliveries(off)] == ["dropped"]
|
||||
assert [d.status for d in await deliveries(moved)] == ["dropped"]
|
||||
assert await fires(off) == [] and await fires(moved) == []
|
||||
|
||||
|
||||
async def test_disabled_schedule_does_not_receive_events():
|
||||
upstream = await workflow("门店日报")
|
||||
sid = await event_schedule(await workflow("区域汇总"),
|
||||
{"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 0}, enabled=False)
|
||||
await put_event("workflow.finished", upstream, {"workflow_id": upstream, "run_id": "r1"}, utcnow())
|
||||
assert await outbox.dispatch_due(later()) == [] and await deliveries(sid) == []
|
||||
|
||||
|
||||
async def test_events_left_while_scheduler_was_off_are_skipped_past_grace():
|
||||
"""调度关着的那几天没人派:事件留在表里;开起来以后超出补发宽限的照实记一次错过、不补发"""
|
||||
upstream = await workflow("门店日报")
|
||||
sid = await event_schedule(await workflow("区域汇总"),
|
||||
{"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 60}, grace=600)
|
||||
old = utcnow() - timedelta(days=2)
|
||||
await put_event("workflow.finished", upstream, {"workflow_id": upstream, "run_id": "r-old"}, old)
|
||||
[ev] = await events("workflow.finished", upstream)
|
||||
assert ev.status == "pending" # 没有调度的一拍:一直等着
|
||||
async with SessionLocal() as session:
|
||||
state = await outbox.pending_for(session, await session.get(Schedule, sid))
|
||||
assert state["events"] == 1 and state["waiting"] == 0
|
||||
[fire] = await outbox.dispatch_due(later())
|
||||
assert (fire.status, fire.kind, fire.run_id) == ("skipped_misfire", "event", None)
|
||||
assert "服务当时没有派发" in fire.reason and "超出补发宽限(10 分钟)" in fire.reason
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 数据源有要处理的变化
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_source_changed_once_per_job_with_counts():
|
||||
async with SessionLocal() as session:
|
||||
source = DataSource(name=f"门店库-{uuid.uuid4().hex[:6]}", kind="sqlite", database=":memory:")
|
||||
session.add(source)
|
||||
await session.flush()
|
||||
for i, severity in enumerate(("action", "action", "warning")):
|
||||
session.add(SourceChange(source_id=source.id, source_name=source.name, table_name="orders",
|
||||
column_name=f"c{i}", kind="column_removed", severity=severity,
|
||||
detected_by={"job_kind": "introspect", "job_id": "job-7"},
|
||||
fingerprint=uuid.uuid4().hex, status="open"))
|
||||
await session.commit()
|
||||
source_id, source_name = source.id, source.name
|
||||
downstream = await workflow("变化处理", fields=[{"name": "n"}, {"name": "who"}])
|
||||
sid = await event_schedule(downstream, {"event": "source.changed", "source_id": source_id, "debounce_s": 0},
|
||||
template={"n": "{{ event.counts.new }}", "who": "{{ event.source }}"})
|
||||
from app.data import source_changes
|
||||
|
||||
assert await source_changes.notify_after_job(source_id, "job-7") == 2
|
||||
# 同一个任务没有新记要处理的变化(别的任务号):不记事件
|
||||
assert await source_changes.notify_after_job(source_id, "job-8") == 0
|
||||
[ev] = await events("source.changed", source_id)
|
||||
assert ev.payload["counts"]["new"] == 2 and ev.payload["counts"]["warning"] == 1 and ev.payload["job_id"] == "job-7"
|
||||
[fire] = await outbox.dispatch_due(later())
|
||||
assert fire.status == "started" and fire.inputs["inputs"] == {"n": "2", "who": source_name}
|
||||
assert fire.inputs["event"]["text"] == f"数据源「{source_name}」出现要处理的变化(新记 2 条)"
|
||||
await settle(fire.run_id)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 上传表格出了新的一期
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
from tests.test_table_versions_p3 import Chain, store # noqa: E402,F401 (store:每个测试一个独立的数据目录)
|
||||
|
||||
|
||||
async def test_table_version_on_each_new_period():
|
||||
chain = Chain()
|
||||
await chain.first()
|
||||
[aug] = await events("table.version", chain.sid)
|
||||
assert aug.payload["period"] == "2026-08" and aug.payload["replaced"] is False
|
||||
assert aug.payload["version"] == chain.s1 and aug.payload["table"] == chain.name
|
||||
downstream = await workflow("月报", fields=[{"name": "month", "required": True}, {"name": "table"}])
|
||||
sid = await event_schedule(downstream, {"event": "table.version", "source_id": chain.sid, "debounce_s": 0},
|
||||
template={"month": "{{ event.period }}", "table": "{{ event.table }}"})
|
||||
async with SessionLocal() as session:
|
||||
await session.execute(TriggerEvent.__table__.update().where(TriggerEvent.id == aug.id)
|
||||
.values(status="routed")) # 8 月是建任务之前的事:不算
|
||||
await session.commit()
|
||||
await chain.second()
|
||||
sep = [e for e in await events("table.version", chain.sid) if e.id != aug.id]
|
||||
assert [e.payload["period"] for e in sep] == ["2026-09"] and sep[0].payload["version"] == chain.s2
|
||||
[fire] = await outbox.dispatch_due(later())
|
||||
assert fire.status == "started" and fire.inputs["inputs"] == {"month": "2026-09", "table": chain.name}
|
||||
assert fire.inputs["event"]["text"] == f"上传表格「{chain.name}」出了新的一期(2026-09)"
|
||||
run = await settle(fire.run_id)
|
||||
assert run.origin["trigger"]["event"] == "table.version" and run.origin["trigger"]["subject_id"] == chain.sid
|
||||
|
||||
|
||||
async def test_table_version_marks_a_replaced_period():
|
||||
chain = Chain()
|
||||
await chain.first()
|
||||
await chain.second()
|
||||
async with SessionLocal() as session:
|
||||
await outbox.stage_table_version(session, source_id=chain.sid, source_name=chain.name, snapshot_id="s3",
|
||||
previous_snapshot_id=chain.s2, period_start=chain.sep_start,
|
||||
period_end=chain.sep_end, seq=3)
|
||||
await session.commit()
|
||||
replaced = [e for e in await events("table.version", chain.sid) if e.payload["version"] == "s3"]
|
||||
assert replaced[0].payload["replaced"] is True
|
||||
trigger = triggers.normalize({"event": "table.version", "source_id": chain.sid, "period": "new"})
|
||||
assert not triggers.matches(trigger, "table.version", chain.sid, replaced[0].payload)
|
||||
assert triggers.matches({**trigger, "period": "any"}, "table.version", chain.sid, replaced[0].payload)
|
||||
assert triggers.event_text("table.version", "门店销售", replaced[0].payload) == "上传表格「门店销售」替换了已有的一期(2026-09)"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 写法与模板
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_period_labels():
|
||||
cases = {("2026-09-01", "2026-09-30"): "2026-09", ("2026-07-01", "2026-09-30"): "2026-Q3",
|
||||
("2026-01-01", "2026-12-31"): "2026", ("2026-09-28", "2026-10-04"): "2026-W40",
|
||||
("2026-09-30", "2026-09-30"): "2026-09-30", ("2026-09-03", "2026-09-17"): "2026-09-03~2026-09-17",
|
||||
(None, None): ""}
|
||||
assert {k: triggers.period_label(*k) for k in cases} == cases
|
||||
|
||||
|
||||
def test_event_templates_check_and_render():
|
||||
tpl = {"month": "{{ event.period }}", "basis": "{{ event.outputs.r }}"}
|
||||
with pytest.raises(service.TemplateError, match="「event.outputs.r」不是可用的变量"):
|
||||
service.check_template(tpl, event="table.version")
|
||||
assert service.check_template({"basis": "{{ event.outputs.r | trim }}"}, event="workflow.finished")
|
||||
with pytest.raises(service.TemplateError, match="在事件触发的任务里不可用"):
|
||||
service.check_template({"d": "{{ schedule.last_fire_time }}"}, event="source.changed")
|
||||
with pytest.raises(service.TemplateError, match="event.counts.new"):
|
||||
service.check_template({"n": "{{ event.counts.total }}"}, event="source.changed")
|
||||
# 按 cron 触发的任务:event.* 不认,说法一字不变
|
||||
with pytest.raises(service.TemplateError, match="「event.period」不是可用的变量,可用的变量:schedule.today"):
|
||||
service.check_template({"m": "{{ event.period }}"})
|
||||
fire_at = datetime(2026, 10, 8, 1, 30, tzinfo=UTC)
|
||||
values = triggers.values("table.version", triggers.table_payload(
|
||||
"门店销售", snapshot_id="snap-9", period_start="2026-09-01", period_end="2026-09-30",
|
||||
activated_at=fire_at, replaced=False, seq=2), "Asia/Shanghai")
|
||||
out = service.render_inputs({"m": "{{ event.period }}", "at": "{{ event.activated_at }}",
|
||||
"d": "{{ schedule.yesterday }}"},
|
||||
service.template_values(fire_at, "Asia/Shanghai", ""), event=values)
|
||||
assert out == {"m": "2026-09", "at": "2026-10-08T09:30:00+08:00", "d": "2026-10-07"}
|
||||
|
||||
|
||||
def test_trigger_shape_is_checked():
|
||||
with pytest.raises(triggers.TriggerError, match="事件种类"):
|
||||
triggers.normalize({"event": "caliber.published", "source_id": "x"})
|
||||
with pytest.raises(triggers.TriggerError, match="请选择上传表格"):
|
||||
triggers.normalize({"event": "table.version"})
|
||||
with pytest.raises(triggers.TriggerError, match="不认识的项:perid"):
|
||||
triggers.normalize({"event": "table.version", "source_id": "x", "perid": "new"})
|
||||
with pytest.raises(triggers.TriggerError, match="按应用、来源过滤"):
|
||||
triggers.normalize({"event": "table.version", "source_id": "x", "app_id": "a"})
|
||||
with pytest.raises(triggers.TriggerError) as e:
|
||||
triggers.normalize({"event": "source.changed", "source_id": "x", "debounce_s": -1})
|
||||
assert e.value.field == "debounce_s"
|
||||
assert triggers.normalize({"event": "workflow.finished", "workflow_id": " wf ", "origin_kind": "hook"}) == {
|
||||
"event": "workflow.finished", "workflow_id": "wf", "origin_kind": "hook", "debounce_s": 60}
|
||||
@@ -0,0 +1,389 @@
|
||||
"""事件触发的定时任务接口(api/schedules.py,docs/design/orchestration-round/00-总方案.md §4)。
|
||||
|
||||
- 建任务收 trigger_kind(cron 缺省,字段和行为一字不变)/ trigger:事件触发时 cron 存空串、下一次触发为空,目标只能是工作流;
|
||||
核对对象(表格在、是按期累积的上传表格;上游工作流在、已发布;数据源在;只认的应用在),输入模板按事件种类核对 {{ event.* }};
|
||||
不对回 422 {detail(中文), field}
|
||||
- 防环:workflow.finished 串成环(A→B→A、自己触发自己)拒收,说清是哪几个工作流;改触发条件、改目标同样查
|
||||
- 返回带 trigger_kind、trigger、trigger_text(给人看的触发说明,也写进 description_text)、trigger_state(几条事件在等、
|
||||
去抖到什么时候、调度开没开);触发历史里事件触发的那几次带 event(事件的说明)
|
||||
- 预览按一个示例事件渲染(上游最近一次成功的正式运行的出口字段……);变量清单按事件种类给 {{ event.* }};
|
||||
立即运行按示例事件发起,还没发生过这种事件、模板又用到 {{ event.* }} 的照实记未能发起
|
||||
- 触发方式建好之后不能改;Webhook 照旧可配
|
||||
|
||||
工作流、表格、数据源、应用都是虚构的。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import delete
|
||||
|
||||
from app.db.base import SessionLocal
|
||||
from app.db.models import DataSource, Run, Schedule, TableRecipe, Workflow, WorkflowVersion
|
||||
from app.db.models_apps import App
|
||||
from app.db.models_triggers import TriggerDelivery, TriggerEvent
|
||||
from app.engine.launch import launch_run
|
||||
from app.engine.runner import run_manager
|
||||
from app.main import app
|
||||
|
||||
HOOK = "https://hooks.example.com/agentlab/inbox-7f2e"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def engine_up():
|
||||
await run_manager.setup()
|
||||
async with SessionLocal() as session:
|
||||
await session.execute(delete(TriggerDelivery))
|
||||
await session.execute(delete(TriggerEvent))
|
||||
await session.execute(delete(Schedule))
|
||||
await session.commit()
|
||||
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
|
||||
|
||||
|
||||
def node(nid, ntype, **config):
|
||||
return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": nid, "config": config}}
|
||||
|
||||
|
||||
def graph(fields=(), value="完成") -> dict:
|
||||
return {"nodes": [node("start", "input", fields=list(fields)),
|
||||
node("out", "output", fields=[{"name": "r", "value": value}])],
|
||||
"edges": [{"source": "start", "target": "out"}]}
|
||||
|
||||
|
||||
async def workflow(name: str, *, published: bool = True, fields=(), value: str = "完成") -> tuple[str, str]:
|
||||
name = f"{name}-{uuid.uuid4().hex[:6]}"
|
||||
async with SessionLocal() as session:
|
||||
wf = Workflow(name=name, graph=graph(fields, value), status="published" if published else "draft",
|
||||
published_version=1 if published else None)
|
||||
session.add(wf)
|
||||
await session.flush()
|
||||
session.add(WorkflowVersion(workflow_id=wf.id, version=1, graph=graph(fields, value)))
|
||||
await session.commit()
|
||||
return wf.id, name
|
||||
|
||||
|
||||
async def upload_table(name: str, *, mode: str = "accumulate") -> str:
|
||||
async with SessionLocal() as session:
|
||||
source = DataSource(name=f"{name}-{uuid.uuid4().hex[:6]}", kind="sqlite", origin="upload", readonly=True)
|
||||
session.add(source)
|
||||
await session.flush()
|
||||
recipe = TableRecipe(source_id=source.id, seq=1, recipe={"mode": mode}, status="active")
|
||||
session.add(recipe)
|
||||
await session.flush()
|
||||
source.current_recipe_id = recipe.id
|
||||
await session.commit()
|
||||
return source.id
|
||||
|
||||
|
||||
async def manual_source(name: str = "门店库") -> str:
|
||||
async with SessionLocal() as session:
|
||||
source = DataSource(name=f"{name}-{uuid.uuid4().hex[:6]}", kind="sqlite", database=":memory:")
|
||||
session.add(source)
|
||||
await session.commit()
|
||||
return source.id
|
||||
|
||||
|
||||
def body(workflow_id: str, trigger: dict, **extra) -> dict:
|
||||
return {"name": "下游汇总", "workflow_id": workflow_id, "trigger_kind": "event", "trigger": trigger,
|
||||
"timezone": "Asia/Shanghai", **extra}
|
||||
|
||||
|
||||
async def settle(run_id: str) -> Run:
|
||||
for _ in range(400):
|
||||
async with SessionLocal() as session:
|
||||
row = await session.get(Run, run_id)
|
||||
if row.status in ("succeeded", "failed", "cancelled") and row.manifest_seq is not None:
|
||||
await run_manager.wait_idle(run_id)
|
||||
return row
|
||||
await asyncio.sleep(0.03)
|
||||
raise AssertionError(f"运行 {run_id} 停在 {row.status}")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 建、读
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_create_table_version_schedule(client):
|
||||
table = await upload_table("门店销售")
|
||||
wf, _ = await workflow("月报", fields=[{"name": "month", "required": True}])
|
||||
r = await client.post("/api/schedules", json=body(wf, {"event": "table.version", "source_id": table,
|
||||
"period": "new"},
|
||||
input_template={"month": "{{ event.period }}"},
|
||||
webhook={"url": HOOK}))
|
||||
assert r.status_code == 201, r.text
|
||||
s = r.json()
|
||||
assert (s["trigger_kind"], s["cron"], s["next_run_at"], s["target_kind"]) == ("event", "", None, "workflow")
|
||||
assert {k: v for k, v in s["trigger"].items() if k != "subject_name"} == {
|
||||
"event": "table.version", "source_id": table, "period": "new", "debounce_s": 60}
|
||||
assert s["trigger"]["subject_name"].startswith("门店销售-") # 保存时记下的对象名
|
||||
assert s["trigger_text"].startswith("上传表格「门店销售-") and "(只认新增的一期;去抖 1 分钟)" in s["trigger_text"]
|
||||
assert s["description_text"] == s["trigger_text"]
|
||||
assert s["trigger_state"] == {"events": 0, "waiting": 0, "due_at": None, "scheduler_on": False}
|
||||
assert s["webhook"]["url_hint"].startswith("hooks.example.com")
|
||||
async with SessionLocal() as session:
|
||||
row = await session.get(Schedule, s["id"])
|
||||
assert (row.trigger_kind, row.cron, row.next_run_at) == ("event", "", None)
|
||||
# 列表里同一份
|
||||
listed = {x["id"]: x for x in (await client.get("/api/schedules")).json()["items"]}
|
||||
assert listed[s["id"]]["trigger_text"] == s["trigger_text"]
|
||||
|
||||
|
||||
async def test_cron_schedules_are_unchanged_and_say_so(client):
|
||||
wf, _ = await workflow("周报", fields=[{"name": "stat_date", "required": True}])
|
||||
r = await client.post("/api/schedules", json={"name": "周一早报", "workflow_id": wf, "cron": "0 9 * * 1",
|
||||
"timezone": "Asia/Shanghai",
|
||||
"input_template": {"stat_date": "{{ schedule.yesterday }}"}})
|
||||
assert r.status_code == 201, r.text
|
||||
s = r.json()
|
||||
assert (s["trigger_kind"], s["trigger"], s["trigger_text"], s["trigger_state"]) == ("cron", None, None, None)
|
||||
assert s["description_text"] == "每周一 09:00(Asia/Shanghai)" and s["next_run_at"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("make, trigger, says", [
|
||||
("replace", {"event": "table.version"}, "不是按期累积的上传表格"),
|
||||
("manual", {"event": "table.version"}, "不是上传表格"),
|
||||
("gone", {"event": "table.version"}, "上传表格不存在"),
|
||||
("draft", {"event": "workflow.finished"}, "还没有发布版本"),
|
||||
("gone", {"event": "source.changed"}, "数据源不存在"),
|
||||
])
|
||||
async def test_trigger_objects_are_checked(client, make, trigger, says):
|
||||
target, _ = await workflow("汇总")
|
||||
if make == "replace":
|
||||
subject = await upload_table("门店销售", mode="replace")
|
||||
elif make == "manual":
|
||||
subject = await manual_source()
|
||||
elif make == "draft":
|
||||
subject, _ = await workflow("草稿日报", published=False)
|
||||
else:
|
||||
subject = "nope"
|
||||
key = "workflow_id" if trigger["event"] == "workflow.finished" else "source_id"
|
||||
r = await client.post("/api/schedules", json=body(target, {**trigger, key: subject}))
|
||||
assert r.status_code == 422 and r.json()["field"] == "trigger" and says in r.json()["detail"], r.text
|
||||
|
||||
|
||||
async def test_event_schedule_rules(client):
|
||||
src = await manual_source()
|
||||
wf, _ = await workflow("汇总", fields=[{"name": "n"}])
|
||||
trigger = {"event": "source.changed", "source_id": src}
|
||||
cases = [
|
||||
({"cron": "0 9 * * 1"}, "cron", "不写 cron"),
|
||||
({"target_kind": "eval_suite", "target_id": "suite-1", "workflow_id": ""}, "target_kind", "只能指向工作流"),
|
||||
({"input_template": {"n": "{{ event.period }}"}}, "input_template", "event.counts.new"),
|
||||
({"trigger_kind": "hourly"}, "trigger_kind", "定时或事件触发"),
|
||||
({"trigger": {**trigger, "debounce_s": 999999}}, "debounce_s", "去抖"),
|
||||
]
|
||||
for extra, field, says in cases:
|
||||
r = await client.post("/api/schedules", json={**body(wf, trigger), **extra})
|
||||
assert r.status_code == 422, (extra, r.text)
|
||||
assert r.json()["field"] == field and says in r.json()["detail"], (extra, r.json())
|
||||
|
||||
|
||||
async def test_unknown_app_filter_is_refused(client):
|
||||
a, _ = await workflow("日报")
|
||||
b, _ = await workflow("汇总")
|
||||
r = await client.post("/api/schedules", json=body(b, {"event": "workflow.finished", "workflow_id": a,
|
||||
"app_id": "nope"}))
|
||||
assert r.status_code == 422 and "只认的应用不存在" in r.json()["detail"]
|
||||
async with SessionLocal() as session:
|
||||
shop = App(name="门店看板")
|
||||
session.add(shop)
|
||||
await session.commit()
|
||||
app_id = shop.id
|
||||
r = await client.post("/api/schedules", json=body(b, {"event": "workflow.finished", "workflow_id": a,
|
||||
"app_id": app_id}))
|
||||
assert r.status_code == 201 and "只认应用「门店看板」发起的" in r.json()["trigger_text"]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 防环
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_cycles_are_refused_when_saving(client):
|
||||
a, a_name = await workflow("日报")
|
||||
b, b_name = await workflow("汇总")
|
||||
c, c_name = await workflow("全国")
|
||||
first = await client.post("/api/schedules", json=body(b, {"event": "workflow.finished", "workflow_id": a}))
|
||||
assert first.status_code == 201
|
||||
second = await client.post("/api/schedules", json=body(c, {"event": "workflow.finished", "workflow_id": b}))
|
||||
assert second.status_code == 201
|
||||
loop = await client.post("/api/schedules", json=body(a, {"event": "workflow.finished", "workflow_id": c}))
|
||||
assert loop.status_code == 422 and loop.json()["field"] == "trigger"
|
||||
assert f"「{c_name}」→「{a_name}」→「{b_name}」→「{c_name}」" in loop.json()["detail"], loop.json()
|
||||
own = await client.post("/api/schedules", json=body(a, {"event": "workflow.finished", "workflow_id": a}))
|
||||
assert own.status_code == 422 and f"「{a_name}」→「{a_name}」" in own.json()["detail"]
|
||||
# 停用着的也算:启用不该绕过这道检查
|
||||
s2 = second.json()
|
||||
off = await client.patch(f"/api/schedules/{s2['id']}", json={"enabled": False, "version": s2["version"]})
|
||||
assert off.status_code == 200 and off.json()["next_run_at"] is None
|
||||
assert (await client.post("/api/schedules", json=body(a, {"event": "workflow.finished", "workflow_id": c}))
|
||||
).status_code == 422
|
||||
# 改目标、改触发条件造出环:同样拒
|
||||
s1 = first.json()
|
||||
moved = await client.patch(f"/api/schedules/{s1['id']}", json={
|
||||
"trigger": {"event": "workflow.finished", "workflow_id": c}, "version": s1["version"]})
|
||||
assert moved.status_code == 422 and "循环触发" in moved.json()["detail"]
|
||||
retarget = await client.patch(f"/api/schedules/{s2['id']}", json={"workflow_id": a, "version": off.json()["version"]})
|
||||
assert retarget.status_code == 422 and "循环触发" in retarget.json()["detail"]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 改
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_patch_event_schedule(client):
|
||||
src = await manual_source()
|
||||
wf, _ = await workflow("汇总", fields=[{"name": "n"}])
|
||||
s = (await client.post("/api/schedules", json=body(wf, {"event": "source.changed", "source_id": src}))).json()
|
||||
r = await client.patch(f"/api/schedules/{s['id']}", json={"trigger_kind": "cron", "version": s["version"]})
|
||||
assert r.status_code == 422 and r.json()["field"] == "trigger_kind"
|
||||
r = await client.patch(f"/api/schedules/{s['id']}", json={"cron": "0 9 * * *", "version": s["version"]})
|
||||
assert r.status_code == 422 and r.json()["field"] == "cron"
|
||||
r = await client.patch(f"/api/schedules/{s['id']}", json={
|
||||
"trigger": {"event": "source.changed", "source_id": src, "debounce_s": 300},
|
||||
"input_template": {"n": "{{ event.counts.new }}"}, "version": s["version"]})
|
||||
assert r.status_code == 200, r.text
|
||||
out = r.json()
|
||||
assert out["trigger"]["debounce_s"] == 300 and "去抖 5 分钟" in out["trigger_text"]
|
||||
assert out["version"] == s["version"] + 1 and out["next_run_at"] is None and out["cron"] == ""
|
||||
# 整份表单带回来(cron 空串、触发条件没变)照常保存
|
||||
same = await client.patch(f"/api/schedules/{s['id']}", json={
|
||||
"name": "变化处理", "cron": "", "trigger": out["trigger"], "trigger_kind": "event", "version": out["version"]})
|
||||
assert same.status_code == 200 and same.json()["name"] == "变化处理"
|
||||
# 模板里换成别的事件的变量:拒
|
||||
bad = await client.patch(f"/api/schedules/{s['id']}", json={
|
||||
"input_template": {"n": "{{ event.outputs.r }}"}, "version": same.json()["version"]})
|
||||
assert bad.status_code == 422 and bad.json()["field"] == "input_template"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 预览、变量、立即运行、触发历史
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_preview_and_run_now_with_a_sample_event(client):
|
||||
a, a_name = await workflow("日报", value="日报完成")
|
||||
b, _ = await workflow("汇总", fields=[{"name": "basis", "required": True}])
|
||||
trigger = {"event": "workflow.finished", "workflow_id": a}
|
||||
template = {"basis": "{{ event.outputs.r }} · {{ event.workflow }}"}
|
||||
# 上游还没成功过:示例值,照实说
|
||||
r = await client.post("/api/schedules/preview", json={"trigger_kind": "event", "trigger": trigger,
|
||||
"timezone": "Asia/Shanghai", "input_template": template,
|
||||
"workflow_id": b})
|
||||
assert r.status_code == 200, r.text
|
||||
p = r.json()
|
||||
assert p["next"] == [] and p["event"]["real"] is False and p["event"]["text"].startswith(f"工作流「{a_name}」")
|
||||
s = (await client.post("/api/schedules", json=body(b, trigger, input_template=template))).json()
|
||||
early = (await client.post(f"/api/schedules/{s['id']}/run")).json()
|
||||
assert early["run_id"] is None and early["fire"]["status"] == "failed_to_start"
|
||||
assert "还没有发生过这种事件" in early["fire"]["reason"] and early["fire"]["kind"] == "manual"
|
||||
# 上游成功过一次:预览、立即运行都按它
|
||||
async with SessionLocal() as session:
|
||||
up = await launch_run(session, workflow_id=a, run_class="formal", input_payload={}, actor="检查员",
|
||||
origin_kind="launcher")
|
||||
await settle(up.id)
|
||||
p = (await client.post("/api/schedules/preview", json={"trigger_kind": "event", "trigger": trigger,
|
||||
"timezone": "Asia/Shanghai", "input_template": template,
|
||||
"workflow_id": b})).json()
|
||||
assert p["inputs"] == {"basis": f"日报完成 · {a_name}"} and p["event"]["real"] is True
|
||||
assert p["description_text"].startswith(f"工作流「{a_name}」的正式运行成功结束时触发")
|
||||
await asyncio.sleep(1.05) # 立即运行按秒去重:上一次落在同一秒就交回那一条
|
||||
run = (await client.post(f"/api/schedules/{s['id']}/run")).json()
|
||||
assert run["run_id"] and run["fire"]["kind"] == "manual" and run["fire"]["event"]["sample"] is True
|
||||
done = await settle(run["run_id"])
|
||||
assert done.input == {"basis": f"日报完成 · {a_name}"}
|
||||
assert done.origin["trigger"]["sample"] is True and done.origin["trigger"]["event"] == "workflow.finished"
|
||||
assert done.origin["trigger"]["real"] is True and done.origin["trigger"]["chain"] == [up.id]
|
||||
# 应用页印章:立即运行按示例事件发起的不说「由事件触发」
|
||||
from app.apps import resolve
|
||||
|
||||
async with SessionLocal() as session:
|
||||
said = await resolve._from_text(session, resolve.Source(id="v", kind="latest_sealed", state="ok", run=done))
|
||||
assert said.startswith("定时任务「下游汇总」第 ")
|
||||
# 触发历史:事件的说明照写
|
||||
[newest, *_] = (await client.get(f"/api/schedules/{s['id']}/fires")).json()["items"]
|
||||
assert newest["event"]["text"].startswith(f"工作流「{a_name}」的正式运行成功结束(#{up.id[:6]})")
|
||||
|
||||
|
||||
async def test_variables_for_an_event(client):
|
||||
names = [v["name"] for v in (await client.get(
|
||||
"/api/schedules/variables", params={"trigger_kind": "event", "event": "workflow.finished"})).json()]
|
||||
assert "event.outputs.<字段名>" in names and "event.run_id" in names and "schedule.yesterday" in names
|
||||
assert "schedule.last_fire_time" not in names
|
||||
plain = [v["name"] for v in (await client.get("/api/schedules/variables")).json()]
|
||||
assert "schedule.last_fire_time" in plain and not any(n.startswith("event.") for n in plain)
|
||||
bad = await client.get("/api/schedules/variables", params={"trigger_kind": "event", "event": "nope"})
|
||||
assert bad.status_code == 422
|
||||
|
||||
|
||||
async def test_trigger_state_and_event_fires(client):
|
||||
"""调度关着:事件留在表里,接口照实说几条在等、调度没开;派发之后触发历史里是 kind=event、带事件的说明"""
|
||||
from app.scheduler import outbox
|
||||
from app.db.base import utcnow
|
||||
from datetime import timedelta
|
||||
|
||||
a, a_name = await workflow("日报")
|
||||
b, _ = await workflow("汇总")
|
||||
s = (await client.post("/api/schedules", json=body(b, {"event": "workflow.finished", "workflow_id": a,
|
||||
"debounce_s": 0}))).json()
|
||||
async with SessionLocal() as session:
|
||||
up = await launch_run(session, workflow_id=a, run_class="formal", input_payload={}, actor="检查员",
|
||||
origin_kind="launcher")
|
||||
await settle(up.id)
|
||||
state = (await client.get(f"/api/schedules/{s['id']}")).json()["trigger_state"]
|
||||
assert state == {"events": 1, "waiting": 0, "due_at": None, "scheduler_on": False}
|
||||
[fire] = await outbox.dispatch_due(utcnow() + timedelta(seconds=1))
|
||||
await settle(fire.run_id)
|
||||
got = (await client.get(f"/api/schedules/{s['id']}")).json()
|
||||
assert got["trigger_state"]["events"] == 0 and got["last_fire"]["kind"] == "event"
|
||||
assert got["last_fire"]["event"]["text"] == f"工作流「{a_name}」的正式运行成功结束(#{up.id[:6]})"
|
||||
assert got["last_fire"]["inputs"] is None # 工作流目标的输入不在触发历史里列
|
||||
|
||||
|
||||
async def test_trigger_options(client):
|
||||
table = await upload_table("门店销售")
|
||||
flat = await upload_table("门店名单", mode="replace")
|
||||
wf, wf_name = await workflow("日报")
|
||||
draft, _ = await workflow("草稿", published=False)
|
||||
r = await client.get("/api/schedules/trigger-options")
|
||||
assert r.status_code == 200
|
||||
out = r.json()
|
||||
events = {e["event"]: e for e in out["events"]}
|
||||
assert list(events) == ["table.version", "workflow.finished", "source.changed"]
|
||||
tables = {o["id"]: o for o in events["table.version"]["objects"]}
|
||||
assert tables[table]["ok"] is True and tables[flat]["ok"] is False and "按期累积" in tables[flat]["reason"]
|
||||
flows = {o["id"]: o for o in events["workflow.finished"]["objects"]}
|
||||
assert flows[wf] == {"id": wf, "name": wf_name, "ok": True, "reason": None}
|
||||
assert flows[draft]["ok"] is False and "发布" in flows[draft]["reason"]
|
||||
assert "hook" in [o["kind"] for o in out["origins"]] and out["max_depth"] == 5
|
||||
assert out["default_debounce_s"] == 60
|
||||
|
||||
|
||||
async def test_include_rejected_and_backfill_through_the_api(client):
|
||||
"""复核 M1、C5:上游工作流的触发缺省不认途经驳回的、应用补算的,说法照实写;勾了「也认」的存下来、说法跟着变;
|
||||
别的事件带这两项拒收"""
|
||||
a, a_name = await workflow("日报")
|
||||
b, _ = await workflow("汇总", fields=[{"name": "rej"}])
|
||||
plain = (await client.post("/api/schedules", json=body(b, {"event": "workflow.finished", "workflow_id": a},
|
||||
input_template={"rej": "{{ event.rejected }}"}))).json()
|
||||
assert "途经驳回、应用补算的不算" in plain["trigger_text"] and "include_rejected" not in plain["trigger"]
|
||||
r = await client.patch(f"/api/schedules/{plain['id']}", json={
|
||||
"trigger": {"event": "workflow.finished", "workflow_id": a, "include_rejected": True}, "version": plain["version"]})
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["trigger"]["include_rejected"] is True and "途经驳回的也算;应用补算的不算" in r.json()["trigger_text"]
|
||||
src = await upload_table("门店销售")
|
||||
bad = await client.post("/api/schedules", json=body(b, {"event": "table.version", "source_id": src,
|
||||
"include_backfill": True}))
|
||||
assert bad.status_code == 422 and bad.json()["field"] == "trigger"
|
||||
@@ -0,0 +1,277 @@
|
||||
"""数据事件触发复核意见的修正(docs/design/orchestration-round/00-总方案.md §4;scheduler/outbox.py、triggers.py)。
|
||||
|
||||
- M1 途经驳回:正式运行走驳回出口跑完(succeeded,run.finished 带 rejected_via)照发 workflow.finished,事件内容带 rejected_via、
|
||||
说法接「(途经驳回)」、模板有 {{ event.rejected }};触发条件缺省只认没途经驳回的,include_rejected 时也认;
|
||||
- C1 去抖积压:一拍处理到没有到点的窗口为止;已过宽限的几个窗口合成一条跳过(合并了几条、时间跨度),「调度未运行」只在
|
||||
派发确实晚到(派给任务的时刻离事件发生超过宽限)时说,否则照实说积压;积压清完之后新来的事件照常触发;
|
||||
- C3 source.changed 按任务补写:同一个任务只记一条(dedupe),任务结束后没记上的(进程死了、库被锁)在调度的一拍按 job_id 补写;
|
||||
- C4 不同期次的 table.version 不合进同一个窗口:各期有各自的触发;同一期的重传照旧合并;
|
||||
- C5 应用补算(app_backfill)发的 workflow.finished 缺省不认,include_backfill 或只认补算时才认;
|
||||
- C6 预览、立即运行的示例事件和真派发同一套出口字段过滤(「_」开头的不给模板)。
|
||||
|
||||
工作流、表格、数据源都是虚构的。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db.base import SessionLocal, utcnow
|
||||
from app.db.models import DataSource, Run, Schedule
|
||||
from app.db.models_sources import IntrospectJob, SourceChange
|
||||
from app.db.models_triggers import TriggerDelivery, TriggerEvent
|
||||
from app.scheduler import outbox, triggers
|
||||
from tests.test_schedule_events import ( # noqa: F401 (engine_up:每个测试清掉定时任务和事件)
|
||||
deliveries, engine_up, event_schedule, events, fires, formal_run, later, put_event, settle, workflow,
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# M1 途经驳回
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_rejected_via_is_carried_and_excluded_by_default():
|
||||
upstream = await workflow("门店日报")
|
||||
plain = await event_schedule(await workflow("区域汇总"),
|
||||
{"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 0}, name="不认驳回")
|
||||
also = await event_schedule(await workflow("驳回复核", fields=[{"name": "rej"}]),
|
||||
{"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 0,
|
||||
"include_rejected": True}, template={"rej": "{{ event.rejected }}"}, name="也认驳回")
|
||||
a = await formal_run(upstream)
|
||||
async with SessionLocal() as session:
|
||||
# runner 收尾时把这次运行途经的驳回交进来(W1-b 的 _rejected_via(state)):这里直接调,覆盖那一下
|
||||
await session.execute(TriggerEvent.__table__.delete().where(TriggerEvent.subject_id == upstream))
|
||||
outbox.stage_run_finished(session, await session.get(Run, a.id),
|
||||
rejected_via=[{"node_id": "gate", "label": "主管审核"}])
|
||||
await session.commit()
|
||||
[ev] = await events("workflow.finished", upstream)
|
||||
assert ev.payload["rejected"] is True and ev.payload["rejected_via"] == [{"node_id": "gate", "label": "主管审核"}]
|
||||
assert triggers.event_text(ev.event, ev.subject_name, ev.payload).endswith("(途经驳回)")
|
||||
[fire] = await outbox.dispatch_due(later())
|
||||
assert fire.schedule_id == also and fire.status == "started" and fire.inputs["inputs"] == {"rej": "true"}
|
||||
assert fire.inputs["event"]["text"].endswith("(途经驳回)")
|
||||
assert await fires(plain) == [] and await deliveries(plain) == []
|
||||
await settle(fire.run_id)
|
||||
|
||||
|
||||
async def test_plain_runs_say_not_rejected():
|
||||
upstream = await workflow("门店日报")
|
||||
sid = await event_schedule(await workflow("区域汇总", fields=[{"name": "rej"}]),
|
||||
{"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 0},
|
||||
template={"rej": "{{ event.rejected }}"})
|
||||
await formal_run(upstream) # runner 收尾没交 rejected_via:没途经驳回
|
||||
[ev] = await events("workflow.finished", upstream)
|
||||
assert ev.payload["rejected"] is False and ev.payload["rejected_via"] is None
|
||||
[fire] = await outbox.dispatch_due(later())
|
||||
assert fire.schedule_id == sid and fire.inputs["inputs"] == {"rej": "false"}
|
||||
assert "途经驳回" not in fire.inputs["event"]["text"]
|
||||
await settle(fire.run_id)
|
||||
|
||||
|
||||
def test_rejected_and_backfill_options_are_described():
|
||||
base = triggers.normalize({"event": "workflow.finished", "workflow_id": "wf"})
|
||||
assert "(途经驳回、应用补算的不算;去抖 1 分钟)" in triggers.describe(base, "门店日报")
|
||||
both = triggers.normalize({"event": "workflow.finished", "workflow_id": "wf", "include_rejected": True,
|
||||
"include_backfill": True})
|
||||
assert both["include_rejected"] is True and both["include_backfill"] is True
|
||||
assert "(途经驳回、应用补算的也算;去抖 1 分钟)" in triggers.describe(both, "门店日报")
|
||||
# 只认应用补算的:补算本来就要认,不再说「补算的不算」
|
||||
only = triggers.normalize({"event": "workflow.finished", "workflow_id": "wf", "origin_kind": "app_backfill"})
|
||||
text = triggers.describe(only, "门店日报")
|
||||
assert "只认来源为「应用补算」的" in text and "应用补算的不算" not in text and "途经驳回的不算" in text
|
||||
# 别的事件不收这两项
|
||||
for key in ("include_rejected", "include_backfill"):
|
||||
try:
|
||||
triggers.normalize({"event": "table.version", "source_id": "x", key: True})
|
||||
except triggers.TriggerError as e:
|
||||
assert "上游工作流运行成功结束" in str(e)
|
||||
else:
|
||||
raise AssertionError(key)
|
||||
assert "event.rejected" in triggers.names("workflow.finished")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# C5 应用补算
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_backfill_runs_are_excluded_unless_asked():
|
||||
payload = {"origin_kind": "app_backfill", "rejected": False}
|
||||
base = triggers.normalize({"event": "workflow.finished", "workflow_id": "wf"})
|
||||
assert not triggers.matches(base, "workflow.finished", "wf", payload)
|
||||
assert triggers.matches(base, "workflow.finished", "wf", {**payload, "origin_kind": "launcher"})
|
||||
assert triggers.matches({**base, "include_backfill": True}, "workflow.finished", "wf", payload)
|
||||
assert triggers.matches({**base, "origin_kind": "app_backfill"}, "workflow.finished", "wf", payload)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# C6 示例事件的出口字段
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_sample_outputs_use_the_same_filter_as_dispatch():
|
||||
upstream = await workflow("门店日报")
|
||||
run = await formal_run(upstream)
|
||||
async with SessionLocal() as session:
|
||||
await session.execute(Run.__table__.update().where(Run.id == run.id).values(
|
||||
output={"r": "日报完成", "_issuance": {"tier": "full"}}))
|
||||
await session.commit()
|
||||
got = await triggers.sample(session, {"event": "workflow.finished", "workflow_id": upstream})
|
||||
assert got.real and got.outputs == {"r": "日报完成"}
|
||||
assert triggers.outputs_of({"r": 1, "_x": 2}) == {"r": 1}
|
||||
|
||||
|
||||
async def test_sample_skips_rejected_and_backfill_runs_by_default():
|
||||
upstream = await workflow("门店日报")
|
||||
plain = await formal_run(upstream)
|
||||
backfill = await formal_run(upstream, origin_kind="app_backfill")
|
||||
async with SessionLocal() as session:
|
||||
got = await triggers.sample(session, {"event": "workflow.finished", "workflow_id": upstream})
|
||||
wide = await triggers.sample(session, {"event": "workflow.finished", "workflow_id": upstream,
|
||||
"include_backfill": True})
|
||||
assert got.payload["run_id"] == plain.id and wide.payload["run_id"] == backfill.id
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# C1 去抖积压
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _backlog(upstream: str, sid: str, *, n: int, gap_s: int, routed_late: bool) -> tuple:
|
||||
"""n 条相隔 gap_s 秒的事件,派给了任务、还没处理。routed_late:派给任务的时刻是现在(调度停过);否则发生后 1 秒就派了
|
||||
(调度在跑,只是没处理完)。"""
|
||||
t0 = utcnow().replace(microsecond=0) - timedelta(seconds=gap_s * (n - 1) + 61)
|
||||
ids = []
|
||||
async with SessionLocal() as session:
|
||||
for i in range(n):
|
||||
at = t0 + timedelta(seconds=gap_s * i)
|
||||
ev = TriggerEvent(event="workflow.finished", subject_id=upstream, subject_name="门店日报",
|
||||
payload={"workflow_id": upstream, "run_id": f"run-{i}", "rejected": False},
|
||||
occurred_at=at, created_at=at, status="routed", matched=1)
|
||||
session.add(ev)
|
||||
await session.flush()
|
||||
session.add(TriggerDelivery(schedule_id=sid, event_id=ev.id, occurred_at=at,
|
||||
created_at=utcnow() if routed_late else at + timedelta(seconds=1)))
|
||||
ids.append(ev.id)
|
||||
await session.commit()
|
||||
return t0, ids
|
||||
|
||||
|
||||
async def test_backlog_is_drained_in_one_tick_and_missed_windows_merge_into_one_skip():
|
||||
"""12 条相隔 5 分钟、去抖 60 秒、宽限 600 秒:一拍处理完。过了宽限的 10 个窗口合成一条跳过(合并 10 次、写时间跨度),
|
||||
宽限内的两个照常发起(第二个照重叠规则可能跳过);积压清完以后新来的事件照常触发"""
|
||||
upstream = await workflow("门店日报")
|
||||
sid = await event_schedule(await workflow("区域汇总", fields=[{"name": "run"}]),
|
||||
{"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 60}, grace=600,
|
||||
template={"run": "{{ event.run_id }}"})
|
||||
t0, ids = await _backlog(upstream, sid, n=12, gap_s=300, routed_late=True)
|
||||
done = await outbox.dispatch_due(utcnow())
|
||||
assert len(done) == 3, [(f.status, f.reason) for f in done]
|
||||
skip, *rest = done
|
||||
assert skip.status == "skipped_misfire" and skip.kind == "event"
|
||||
assert skip.inputs["event"]["merged"] == 10 and skip.inputs["event"]["windows"] == 10
|
||||
assert skip.inputs["event"]["event_ids"] == ids[:10]
|
||||
assert "服务当时没有派发(调度未运行或已停止)" in skip.reason and " 至 " in skip.reason and "10 次事件" in skip.reason
|
||||
assert [f.inputs["event"]["event_ids"] for f in rest] == [[ids[10]], [ids[11]]]
|
||||
assert rest[0].status == "started" and rest[1].status in ("started", "skipped_overlap")
|
||||
assert {d.status for d in await deliveries(sid)} == {"fired"}
|
||||
for f in rest:
|
||||
if f.run_id:
|
||||
await settle(f.run_id)
|
||||
# 积压清完:新来的一条照常触发
|
||||
new = await put_event("workflow.finished", upstream, {"workflow_id": upstream, "run_id": "run-new"}, utcnow())
|
||||
[fresh] = await outbox.dispatch_due(later(61))
|
||||
assert fresh.status == "started" and fresh.inputs["event"]["event_ids"] == [new]
|
||||
await settle(fresh.run_id)
|
||||
|
||||
|
||||
async def test_backlog_while_scheduler_ran_says_backlog_not_scheduler_off():
|
||||
upstream = await workflow("门店日报")
|
||||
sid = await event_schedule(await workflow("区域汇总"),
|
||||
{"event": "workflow.finished", "workflow_id": upstream, "debounce_s": 60}, grace=600)
|
||||
await _backlog(upstream, sid, n=4, gap_s=600, routed_late=False)
|
||||
skip, *rest = await outbox.dispatch_due(utcnow())
|
||||
assert skip.status == "skipped_misfire" and skip.inputs["event"]["merged"] == 3
|
||||
assert "调度未运行" not in skip.reason and "积压" in skip.reason, skip.reason
|
||||
for f in rest:
|
||||
if f.run_id:
|
||||
await settle(f.run_id)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# C4 不同期次各自一个窗口
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_different_periods_get_their_own_windows():
|
||||
table = uuid.uuid4().hex
|
||||
sid = await event_schedule(await workflow("月报", fields=[{"name": "month"}]),
|
||||
{"event": "table.version", "source_id": table, "debounce_s": 60},
|
||||
template={"month": "{{ event.period }}"})
|
||||
t0 = utcnow().replace(microsecond=0)
|
||||
payload = lambda p, s, e: {"table": "门店销售", "period": p, "period_start": s, "period_end": e, # noqa: E731
|
||||
"version": f"snap-{p}", "replaced": False}
|
||||
sep = await put_event("table.version", table, payload("2026-09", "2026-09-01", "2026-09-30"), t0, name="门店销售")
|
||||
oct_ = await put_event("table.version", table, payload("2026-10", "2026-10-01", "2026-10-31"),
|
||||
t0 + timedelta(seconds=30), name="门店销售")
|
||||
again = await put_event("table.version", table, {**payload("2026-09", "2026-09-01", "2026-09-30"), "replaced": True},
|
||||
t0 + timedelta(seconds=40), name="门店销售")
|
||||
[first] = await outbox.dispatch_due(t0 + timedelta(seconds=61))
|
||||
# 9 月一个窗口:9 月和 9 月的重传合在一起(内容取最新的那一条),10 月不合进来
|
||||
assert first.inputs["event"]["event_ids"] == [sep, again] and first.inputs["inputs"] == {"month": "2026-09"}
|
||||
await settle(first.run_id)
|
||||
[second] = await outbox.dispatch_due(t0 + timedelta(seconds=91))
|
||||
assert second.inputs["event"]["event_ids"] == [oct_] and second.inputs["inputs"] == {"month": "2026-10"}
|
||||
assert second.fire_at == t0 + timedelta(seconds=90) and second.status == "started"
|
||||
await settle(second.run_id)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# C3 source.changed 按任务补写
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _source_with_changes(job_status: str) -> tuple[str, str]:
|
||||
async with SessionLocal() as session:
|
||||
source = DataSource(name=f"门店库-{uuid.uuid4().hex[:6]}", kind="sqlite", database=":memory:")
|
||||
session.add(source)
|
||||
await session.flush()
|
||||
job = IntrospectJob(source_id=source.id, status=job_status,
|
||||
finished_at=utcnow() if job_status != "running" else None)
|
||||
session.add(job)
|
||||
await session.flush()
|
||||
for i in range(2):
|
||||
session.add(SourceChange(source_id=source.id, source_name=source.name, table_name="orders",
|
||||
column_name=f"c{i}", kind="column_removed", severity="action",
|
||||
detected_by={"job_kind": "introspect", "job_id": job.id},
|
||||
fingerprint=uuid.uuid4().hex, status="open"))
|
||||
await session.commit()
|
||||
return source.id, job.id
|
||||
|
||||
|
||||
async def test_source_changed_is_backfilled_once_per_job():
|
||||
"""任务结束了、变化记下了,那条事件却没记上(进程在中间死了):调度的一拍按 job_id 补写,只补一次;之后再走到
|
||||
notify_after_job 也不重复"""
|
||||
source_id, job_id = await _source_with_changes("succeeded")
|
||||
running_source, _ = await _source_with_changes("running")
|
||||
assert await events("source.changed", source_id) == []
|
||||
assert await outbox.backfill_source_changes(utcnow()) >= 1
|
||||
[ev] = await events("source.changed", source_id)
|
||||
assert ev.payload["job_id"] == job_id and ev.payload["counts"]["new"] == 2 and ev.dedupe_key == f"source.changed:{job_id}"
|
||||
# 还在进行的任务不补:它结束时自己会记
|
||||
assert await events("source.changed", running_source) == []
|
||||
await outbox.backfill_source_changes(utcnow())
|
||||
from app.data import source_changes
|
||||
|
||||
await source_changes.notify_after_job(source_id, job_id)
|
||||
assert len(await events("source.changed", source_id)) == 1
|
||||
|
||||
|
||||
async def test_dispatch_tick_runs_the_backfill():
|
||||
source_id, _ = await _source_with_changes("succeeded")
|
||||
outbox._backfilled_at = None # 刚起的服务:第一拍就补
|
||||
await outbox.dispatch_due(utcnow())
|
||||
assert len(await events("source.changed", source_id)) == 1
|
||||
@@ -41,10 +41,14 @@ SCHEDULE_KEYS = {"id", "name", "workflow_id", "workflow_name", "cron", "timezone
|
||||
"enabled", "overlap", "misfire_grace_s", "webhook", "next_run_at", "last_fire", "description_text",
|
||||
"created_by", "created_at", "updated_at", "version",
|
||||
# 定时的目标(next-round X4):种类、id、叫法、现在的名字、还在不在
|
||||
"target_kind", "target_id", "target_label", "target_name", "target_exists"}
|
||||
"target_kind", "target_id", "target_label", "target_name", "target_exists",
|
||||
# 触发方式(orchestration-round §4):cron 任务这几项是 cron / null(test_schedule_events_api.py)
|
||||
"trigger_kind", "trigger", "trigger_text", "trigger_state"}
|
||||
FIRE_KEYS = {"id", "fire_at", "kind", "status", "run_id", "run_status", "reason", "notified", "compare", "created_at",
|
||||
# 目标是评测题集时这一次触发建的那次评测;目标是数据源维护时这一次建了哪些任务、哪几步没执行(别的目标为 null)
|
||||
"eval_run_id", "inputs"}
|
||||
"eval_run_id", "inputs",
|
||||
# 事件触发的那几次:事件的说明(别的为 null,orchestration-round §4)
|
||||
"event"}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
|
||||
Reference in New Issue
Block a user