mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-24 01:21:58 +00:00
复核 R-b1(卡住但没死的进程被当成没了):续租约挪到单独的任务、专用连接(不走连接池,不被同一拍别的活拖住);进程间请求另起任务办,不在心跳里等收尾;新增 cluster/fence 自我隔离——离上次续上租约超过一个租约时长,或者这段执行属于上一次隔离之前,执行在写事件、写断点、开审批、发外部写入、后台任务写库之前就停手(Fenced 是 BaseException,节点里的 except Exception 拦不住),续租时发现续晚了就隔离:停掉手上的运行和后台任务、不写终态,换一个身份重新登记;运行收尾先占住那一行、属主不是自己就不写;别的进程按租约过期再多等一个租约时长才算不在了(两边中间留一段);run_events 的 (run_id, seq) 改成唯一索引(存量库先数重复,有就照实记日志、这一次不建,不让启动失败)。补测试:卡住期间被接手之后不盖终态、不写事件、序号不重;被接手的那次在别处接着跑完只结束一次、后面那一步只跑一次;收尾按属主写;撞号被库拒绝;多进程端到端加 6b、6c(真 SIGSTOP / SIGCONT)
This commit is contained in:
@@ -0,0 +1,149 @@
|
||||
"""自我隔离(cluster/fence.py,复核 R-b1):本进程卡住了、续不上租约,别的进程已经把它在跑的运行接手了——它缓过来之后不再写:
|
||||
不写事件(不和接手的一边撞号)、不写断点、不写终态(不把接手的结果盖掉)。在一个进程里装出来:把「上次续上租约」拨到一个租约
|
||||
时长以前,再把运行改成接手之后的样子。两种库都跑。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.cluster import fence
|
||||
from app.cluster.workers import lease_s
|
||||
from app.db.base import SessionLocal, new_id
|
||||
from app.db.models import Run, RunEvent
|
||||
from app.engine import compiler
|
||||
from app.engine.runner import run_manager
|
||||
from app.engine.schema import NodeType
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def engine_up():
|
||||
await run_manager.setup()
|
||||
fence.activate()
|
||||
yield
|
||||
fence.deactivate()
|
||||
await run_manager.shutdown()
|
||||
|
||||
|
||||
def node(nid, ntype, **config):
|
||||
return {"id": nid, "type": ntype, "position": {"x": 0, "y": 0}, "data": {"label": nid, "config": config}}
|
||||
|
||||
|
||||
GRAPH = {"nodes": [node("start", "input", fields=[{"name": "question"}]),
|
||||
node("slow", "transform", mode="template", template="慢的这步"),
|
||||
node("next", "transform", mode="template", template="后面这步"),
|
||||
node("out", "output", fields=[{"name": "r", "value": "{{ nodes.next }}"}])],
|
||||
"edges": [{"source": "start", "target": "slow"}, {"source": "slow", "target": "next"},
|
||||
{"source": "next", "target": "out"}]}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def slow(monkeypatch):
|
||||
"""slow 那一步:第一次跑时卡住,等测试放行(好在它卡着的时候装出「续不上租约、被接手」);之后立刻返回。"""
|
||||
calls = {"n": 0}
|
||||
gate = asyncio.Event()
|
||||
entered = asyncio.Event()
|
||||
original = compiler.RUNNERS[NodeType.TRANSFORM]
|
||||
|
||||
async def runner(state, ctx):
|
||||
if ctx.node.id == "slow":
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 1:
|
||||
entered.set()
|
||||
await gate.wait()
|
||||
return await original(state, ctx)
|
||||
|
||||
monkeypatch.setitem(compiler.RUNNERS, NodeType.TRANSFORM, runner)
|
||||
return {"calls": calls, "gate": gate, "entered": entered}
|
||||
|
||||
|
||||
async def _taken_over(run_id: str) -> None:
|
||||
"""别的进程看它的租约过期了、接手:标中断、属主清空(同 run_manager.reap 做的)。"""
|
||||
from sqlalchemy import update
|
||||
|
||||
async with SessionLocal() as session:
|
||||
await session.execute(update(Run).where(Run.id == run_id).values(
|
||||
status="interrupted", owner=None, error="服务重启,运行已挂起,可从断点继续运行"))
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def _events(run_id: str) -> list[RunEvent]:
|
||||
async with SessionLocal() as session:
|
||||
return list((await session.execute(select(RunEvent).where(RunEvent.run_id == run_id)
|
||||
.order_by(RunEvent.seq))).scalars())
|
||||
|
||||
|
||||
async def _no_repeated_seq(run_id: str) -> None:
|
||||
async with SessionLocal() as session:
|
||||
rows = (await session.execute(select(RunEvent.seq, func.count()).where(RunEvent.run_id == run_id)
|
||||
.group_by(RunEvent.seq).having(func.count() > 1))).all()
|
||||
assert rows == [], f"撞号:{rows}"
|
||||
|
||||
|
||||
async def _stall_and_take_over(slow) -> str:
|
||||
run = await run_manager.start(graph=GRAPH, input_payload={"question": "q"})
|
||||
await asyncio.wait_for(slow["entered"].wait(), timeout=15)
|
||||
before = fence.generation()
|
||||
fence.renewed(time.monotonic() - lease_s() - 1) # 卡了一个多租约时长
|
||||
await _taken_over(run.id)
|
||||
slow["gate"].set() # 缓过来,手上的执行接着往下走
|
||||
for _ in range(200):
|
||||
if not run_manager.is_active(run.id):
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
assert not run_manager.is_active(run.id), "执行停了"
|
||||
assert fence.generation() == before + 1, "发现续晚了:隔离了一次"
|
||||
return run.id
|
||||
|
||||
|
||||
async def test_a_stalled_executor_does_not_overwrite_the_takeover(slow):
|
||||
run_id = await _stall_and_take_over(slow)
|
||||
async with SessionLocal() as session:
|
||||
row = await session.get(Run, run_id)
|
||||
assert row.status == "interrupted" and row.owner is None, "接手之后的样子没被盖掉"
|
||||
events = await _events(run_id)
|
||||
assert not [e for e in events if e.type in ("run.finished", "run.failed", "run.cancelled")]
|
||||
assert not [e for e in events if e.node_id == "next"], "缓过来之后一条都没写"
|
||||
await _no_repeated_seq(run_id)
|
||||
|
||||
|
||||
async def test_a_run_continued_elsewhere_finishes_once_and_the_stalled_side_stays_quiet(slow):
|
||||
run_id = await _stall_and_take_over(slow)
|
||||
fence.renewed() # 换了身份重新登记之后,这一世代照常
|
||||
await run_manager.continue_failed(run_id) # 接手的那一边接着跑
|
||||
for _ in range(300):
|
||||
async with SessionLocal() as session:
|
||||
row = await session.get(Run, run_id)
|
||||
if row.status in ("succeeded", "failed") and row.manifest_hash:
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
assert row.status == "succeeded", row.error
|
||||
events = await _events(run_id)
|
||||
assert len([e for e in events if e.type == "run.finished"]) == 1
|
||||
assert len([e for e in events if e.type == "node.started" and e.node_id == "next"]) == 1, "后面那一步只跑了一次"
|
||||
await _no_repeated_seq(run_id)
|
||||
|
||||
|
||||
async def test_the_final_write_checks_the_owner():
|
||||
async with SessionLocal() as session:
|
||||
run = Run(status="running", owner="peer-host:1:abcd", graph={}, input={})
|
||||
session.add(run)
|
||||
await session.commit()
|
||||
await run_manager._finalize(run.id, "succeeded", None, {}, 10, owner="mine:1:ffff")
|
||||
async with SessionLocal() as session:
|
||||
row = await session.get(Run, run.id)
|
||||
assert row.status == "running" and row.finished_at is None, "属主已经不是自己:不写终态"
|
||||
|
||||
|
||||
async def test_a_repeated_seq_is_refused_by_the_database():
|
||||
async with SessionLocal() as session:
|
||||
run = Run(status="running", graph={}, input={})
|
||||
session.add(run)
|
||||
await session.flush()
|
||||
session.add_all([RunEvent(id=new_id(), run_id=run.id, seq=1, type="log", ts=0, data={}),
|
||||
RunEvent(id=new_id(), run_id=run.id, seq=1, type="log", ts=0, data={})])
|
||||
with pytest.raises(IntegrityError):
|
||||
await session.commit()
|
||||
@@ -11,7 +11,9 @@
|
||||
全站 2 个、给交互留底 1 个:评测借满了别的名额、还有题排着,问数据一来马上拿到留底,不等评测跑完;
|
||||
6. 每日花费上限跨进程不越过:两个进程同时往同一本账上记,记下的合计不超过上限;
|
||||
7. 强杀 B:租约过期后,B 上在跑的运行被照实标中断(可从断点继续),停在审批上的运行照常能在 A 上批、接着跑完;B 当着调度班的
|
||||
话 A 接班。
|
||||
话 A 接班;
|
||||
8. 卡住但没死(复核 R-b1):A 在跑一次运行时被 SIGSTOP,B 等它的租约过期两倍时长后接手、标中断;A 缓过来(SIGCONT)之后发现续晚了,
|
||||
停手、不写终态、不写事件,换一个身份重新登记——不管 B 有没有在这期间把那次运行接着跑完,都不双写、不盖掉终态、序号不重。
|
||||
|
||||
缺省不跑:要 AGENTLAB_MULTIPROCESS_E2E=1 和 PostgreSQL 测试库(scripts/test-multiprocess.sh 起临时容器、设好这两样)。
|
||||
"""
|
||||
@@ -88,8 +90,16 @@ class Worker:
|
||||
self.proc.send_signal(signal.SIGKILL)
|
||||
self.proc.wait(timeout=10)
|
||||
|
||||
def pause(self) -> None:
|
||||
self.proc.send_signal(signal.SIGSTOP)
|
||||
|
||||
def resume(self) -> None:
|
||||
if self.proc.poll() is None:
|
||||
self.proc.send_signal(signal.SIGCONT)
|
||||
|
||||
def stop(self) -> None:
|
||||
if self.proc.poll() is None:
|
||||
self.proc.send_signal(signal.SIGCONT)
|
||||
self.proc.send_signal(signal.SIGTERM)
|
||||
try:
|
||||
self.proc.wait(timeout=15)
|
||||
@@ -98,7 +108,7 @@ class Worker:
|
||||
|
||||
def tail(self) -> str:
|
||||
try:
|
||||
return self.log.read_text(encoding="utf-8", errors="replace")[-4000:]
|
||||
return self.log.read_text(encoding="utf-8", errors="replace")[-12000:]
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
@@ -420,7 +430,8 @@ async def test_5b_the_interactive_reserve_is_there_when_evaluations_fill_the_res
|
||||
put = await client.put(f"{a.base}/api/settings", json={"values": {"concurrency": {
|
||||
"max_total": 2, "interactive_reserve": 1, "classes": {}}}})
|
||||
assert put.status_code == 200, put.text
|
||||
assert put.json()["concurrency"]["classes"]["system"]["limit"] == 1, "别的类缺省借满到 全站 − 留底"
|
||||
got = put.json()["concurrency"]
|
||||
assert got["max_total"] - got["interactive_reserve"] == 1, "别的类最多借得到 全站 − 留底 = 1 个"
|
||||
slots.forget_policy()
|
||||
monkeypatch.setattr(settings, "sandbox_backend", "local")
|
||||
await cluster.start()
|
||||
@@ -480,6 +491,88 @@ async def _spent() -> float:
|
||||
return float((await Ledger("e2e_spend").daily())["usd"])
|
||||
|
||||
|
||||
async def _stall_a_during_a_run(client, a: Worker, b: Worker, seconds: float) -> str:
|
||||
"""A 上发起一次运行,跑起来之后 SIGSTOP A,等 B 接手(标中断)。交回运行 id(A 还停着,调用方负责 SIGCONT)。"""
|
||||
run_id = (await client.post(f"{a.base}/api/runs", json={"graph": slow_graph(seconds), "input": {"question": "q"},
|
||||
"origin": "canvas"})).json()["id"]
|
||||
await _until(lambda: _owner_while_active(run_id), what="A 认领了运行")
|
||||
await asyncio.sleep(0.5)
|
||||
a.pause()
|
||||
|
||||
async def taken_over() -> Any:
|
||||
row = await _run(client, b, run_id)
|
||||
return row if row["status"] == "interrupted" else None
|
||||
|
||||
await _until(taken_over, timeout=LEASE_S * 6 + 10, what="B 接手了卡住的 A 上的运行")
|
||||
return run_id
|
||||
|
||||
|
||||
async def _a_reidentified(client, a: Worker) -> None:
|
||||
"""A 缓过来之后换了身份重新登记:fixture 里记的 owner 跟着换。"""
|
||||
old = a.owner
|
||||
|
||||
async def fresh() -> Any:
|
||||
try:
|
||||
me = (await client.get(f"{a.base}/api/system")).json()["cluster"]["me"]
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
return me if me != old else None
|
||||
|
||||
a.owner = await _until(fresh, timeout=15, what="A 换身份重新登记")
|
||||
|
||||
|
||||
async def _settled_events(client, worker: Worker, run_id: str) -> list[dict[str, Any]]:
|
||||
return (await client.get(f"{worker.base}/api/runs/{run_id}/events")).json()
|
||||
|
||||
|
||||
def _seqs_unique(events: list[dict[str, Any]]) -> None:
|
||||
seqs = [e["seq"] for e in events]
|
||||
assert len(seqs) == len(set(seqs)), f"撞号:{sorted(seqs)}"
|
||||
|
||||
|
||||
async def test_6b_a_stalled_worker_does_not_write_after_it_was_taken_over(workers):
|
||||
a, b = workers["A"], workers["B"]
|
||||
async with await _client() as client:
|
||||
try:
|
||||
run_id = await _stall_a_during_a_run(client, a, b, 6)
|
||||
finally:
|
||||
a.resume()
|
||||
await _a_reidentified(client, a)
|
||||
await asyncio.sleep(max(4.0, 3 * HEARTBEAT_S)) # A 手上那一步本来再过几秒就跑完:给它机会(它不该写)
|
||||
row = await _run(client, b, run_id)
|
||||
assert row["status"] == "interrupted", f"接手之后的状态被盖掉了:{row['status']}"
|
||||
events = await _settled_events(client, b, run_id)
|
||||
assert not [e for e in events if e["type"] in ("run.finished", "run.failed", "run.cancelled")]
|
||||
assert any(e["type"] == "log" and e["data"].get("code") == "server_shutdown" for e in events)
|
||||
_seqs_unique(events)
|
||||
|
||||
|
||||
async def test_6c_a_run_continued_by_the_other_worker_is_not_written_twice(workers):
|
||||
a, b = workers["A"], workers["B"]
|
||||
async with await _client() as client:
|
||||
try:
|
||||
run_id = await _stall_a_during_a_run(client, a, b, 3)
|
||||
cont = await client.post(f"{b.base}/api/runs/{run_id}/continue", json={})
|
||||
assert cont.status_code == 200, cont.text
|
||||
finally:
|
||||
a.resume()
|
||||
await _a_reidentified(client, a)
|
||||
|
||||
async def done() -> Any:
|
||||
row = await _run(client, b, run_id)
|
||||
return row if row["status"] in ("succeeded", "failed") and row.get("manifest_hash") else None
|
||||
|
||||
row = await _until(done, timeout=60, what="B 接着跑完")
|
||||
await asyncio.sleep(2.0)
|
||||
assert row["status"] == "succeeded", row
|
||||
assert (await _run(client, b, run_id))["status"] == "succeeded", "A 缓过来之后没有把终态改掉"
|
||||
events = await _settled_events(client, b, run_id)
|
||||
assert len([e for e in events if e["type"] == "run.finished"]) == 1
|
||||
_seqs_unique(events)
|
||||
verified = (await client.get(f"{b.base}/api/runs/{run_id}/verify")).json()
|
||||
assert verified["ok"] is True, verified
|
||||
|
||||
|
||||
async def test_7_kill_a_worker(workers):
|
||||
a, b = workers["A"], workers["B"]
|
||||
async with await _client() as client:
|
||||
|
||||
Reference in New Issue
Block a user