多进程协调(W2-b)第一步:新增 app/cluster——工作进程在库里登记、心跳续租约(属主随进程,进程没了它认领的行一起到期),调度当班的租约,发给属主进程的停止 / 记事件请求,PostgreSQL 的 LISTEN/NOTIFY 叫醒,跨进程的互斥锁(咨询锁),SQLite 单进程守卫(第二个进程拒绝启动);运行、问数据一轮、起草 / 剖析 / 探查 / 评测 / 影子起草、文档、发布单记 owner,启动整理改成只接手属主不在了的行,当班进程隔一会儿再接手一次;运行的并发名额改成库里按交互 / 应用 / 定时 / 系统四类发(各有全站上限和优先级,设置里可调),替掉进程内的信号量;同源队记在库里;运行停止、记事件跨进程交给属主;运行事件、问数据事件跨进程转发(库里按 seq 追,不落库的流式增量和保活心跳只转给在看的进程);每日花费账先占住那一行再读写;访问密钥限流、登录失败计数在 PostgreSQL 时记在库里;登录设置、对外地址、向量模型、能力快照、数据源连接池、应用页面缓存跨进程失效;上传版本库、记录表、按需探查、出具、召回、补算、按需视图、个人刷新、定时发起的锁换成跨进程的锁

This commit is contained in:
ThearchyHelios
2026-10-19 11:40:33 +08:00
parent 9a0d87aa6e
commit 87f0d62f9b
74 changed files with 3521 additions and 447 deletions
+3
View File
@@ -131,6 +131,9 @@ async def put_settings(payload: SettingsIn, session: AsyncSession = Depends(get_
data={"before": bool(before.get(PERSONAL_KEYS)), "after": payload.personal_keys})
await session.commit()
remember_settings(value)
from app.cluster import caches
await caches.broadcast("auth_settings")
return await get_settings()
+6
View File
@@ -552,6 +552,9 @@ async def publish_draft(session: AsyncSession, app: App, *, note: str, dispositi
await session.rollback()
raise CodedHTTPException(409, "有人刚刚发布了这个应用,请刷新后再试", PUBLISH_CONFLICT) from e
clear_cache()
from app.cluster import caches
await caches.broadcast("app_pages")
return {"ok": True, "version": number, "level": level, "spec_hash": row.spec_hash, "issues": issues}
@@ -1045,4 +1048,7 @@ async def backfill(app_id: str, view_id: str, session: AsyncSession = Depends(ge
except LaunchRefused as e:
raise _view_refused(e) from e
clear_cache()
from app.cluster import caches
await caches.broadcast("app_pages")
return out
+7 -3
View File
@@ -94,13 +94,13 @@ async def login(payload: LoginIn, request: Request, response: Response,
if mode == "off":
raise HTTPException(409, "未开启登录,无需登录")
keys = (f"u:{payload.username.strip().lower()}", f"ip:{_client_ip(request)}")
if wait := sessions.wait_seconds(*keys):
if wait := await sessions.wait_for(*keys):
raise HTTPException(429, f"登录失败次数过多,请 {wait} 秒后再试")
user = (await session.execute(select(User).where(User.username == payload.username.strip()))).scalar_one_or_none()
if user is None or user.disabled or not verify_password(payload.password, user.password_hash):
sessions.failed(*keys)
await sessions.note_failed(*keys)
raise HTTPException(401, "用户名或密码不正确")
sessions.succeeded(*keys)
await sessions.note_succeeded(*keys)
token = await sessions.create_session(session, user, ip=_client_ip(request),
user_agent=request.headers.get("user-agent"))
await session.commit()
@@ -317,6 +317,10 @@ async def put_settings(payload: SettingsIn, request: Request, response: Response
user_agent=request.headers.get("user-agent"))
await session.commit()
remember_settings(value)
# 多进程:别的进程的登录设置缓存也要换(开没开登录!),见 app/cluster/caches.py
from app.cluster import caches
await caches.broadcast("auth_settings")
out = _settings_out(value)
if token is not None and created is not None:
_login_response(request, response, token)
+8 -4
View File
@@ -4190,7 +4190,7 @@ async def _append_judged(sealed: _Sealed, report: _Report, units: list[str],
核对和写入是同一个事务里的条件更新,和接着跑占住运行(runner._claim)抢的是同一行:谁先提交算谁的。
"""
from app.core.bus import bus
from app.engine.runner import _stage, run_manager
from app.engine.runner import _seq_floor, _stage, run_manager
same_seal = (Run.manifest_seq.is_(None) if sealed.run_manifest_seq is None
else Run.manifest_seq == sealed.run_manifest_seq,
@@ -4200,8 +4200,9 @@ async def _append_judged(sealed: _Sealed, report: _Report, units: list[str],
run = await session.get(Run, sealed.run_id)
if run is None:
return None
# 进程重启过的话内存里的序号从 0 起:接在库里最后一条后面,不和已有的撞号
bus.set_seq(sealed.run_id, run.last_seq or 0)
# 接在库里最后一条后面(进程重启过、或者别的进程追加过的话,内存里的序号对不上)
last = run.last_seq
bus.set_seq(sealed.run_id, await _seq_floor(session, sealed.run_id, last))
event = run_manager._event(
sealed.run_id, EventType.EVIDENCE_JUDGED, node_id=report.node_id, data={
"report": report.node_id, "doc_artifact": report.doc_artifact, "units": units,
@@ -4212,8 +4213,11 @@ async def _append_judged(sealed: _Sealed, report: _Report, units: list[str],
"calls": outcome["calls"], "duration_ms": outcome["duration_ms"], "budget": outcome["budget"],
"limits_hit": outcome["limits_hit"], "unjudged": outcome["unjudged"], "gaps": outcome["gaps"],
"notes": outcome["notes"], "skipped": outcome["skipped"], "post_seal": True})
# last_seq 也要还是读到的那个:多进程时别的进程可能同时往这次运行里追加(另一次裁判、批注),各拿着同一个号就撞了;
# 同 engine/run_append.append_events,谁先提交算谁的,后到的这一次不记(判定照样交回给点的人)
claimed = await session.execute(
update(Run).where(Run.id == sealed.run_id, Run.status.in_(_TERMINAL), *same_seal)
update(Run).where(Run.id == sealed.run_id, Run.status.in_(_TERMINAL), *same_seal,
Run.last_seq.is_(None) if last is None else Run.last_seq == last)
.values(last_seq=event.seq))
if claimed.rowcount != 1:
# 运行已经不是那份封存下的终态了。烧掉一个序号不要紧:不落库的事件(令牌流)本来就占序号,
+4
View File
@@ -404,6 +404,10 @@ async def set_embedding(
else:
session.add(Setting(key=emb.EMBEDDING_SETTING_KEY, value=value))
await session.commit()
# 多进程:别的进程照新的设置换向量模型(不换的话它们按旧模型检索、写旧模型的向量)
from app.cluster import caches
await caches.broadcast("embeddings")
return {
"embedder": emb.embedder_id(),
"dim": emb.embedder_dim(),
+16 -12
View File
@@ -637,18 +637,22 @@ async def stream_run(websocket: WebSocket, run_id: str) -> None:
await _end(websocket, run.status if run else None)
return
# 占位期间攒下的那几条历史里也有,按 seq 滤掉,否则前端同一步收两遍
pump = asyncio.create_task(_pump(websocket, subscription.stream(after=last_seq), run_id))
try:
# 客户端断开时读操作会抛异常,用它来结束这条连接
while True:
await websocket.receive_text()
except WebSocketDisconnect:
pass
finally:
pump.cancel()
with contextlib.suppress(asyncio.CancelledError):
await pump
# 占位期间攒下的那几条历史里也有,按 seq 滤掉,否则前端同一步收两遍。多进程时这次运行可能在别的进程里执行:
# 跟随它(app/cluster/relay.py),本进程从库里按 seq 追、在本进程的总线上发布,这里收到的和在执行的进程上一样
from app.cluster.relay import relay
with relay.follow_run(run_id, last_seq):
pump = asyncio.create_task(_pump(websocket, subscription.stream(after=last_seq), run_id))
try:
# 客户端断开时读操作会抛异常,用它来结束这条连接
while True:
await websocket.receive_text()
except WebSocketDisconnect:
pass
finally:
pump.cancel()
with contextlib.suppress(asyncio.CancelledError):
await pump
except WebSocketDisconnect:
return
except Exception: # noqa: BLE001
+1 -1
View File
@@ -472,7 +472,7 @@ async def _fire_outs(session: AsyncSession, fires: list[ScheduleFire]) -> list[d
for d in rows:
notified.setdefault(d.fire_id, []).append({"event": d.event, "status": d.status, "at": _iso(d.created_at)})
# 正在发起的触发:库里是占位的「未能发起」(为了进程被强杀时照实说),进程还在、只是还没发起完,按已发起给
launching = {f.id for f in fires if service.launching(f.id)}
launching = {f.id for f in fires if service.launching(f.id, f)}
return [{
"id": f.id,
"fire_at": _iso(f.fire_at),
+39
View File
@@ -900,6 +900,16 @@ def _mail_public(stored: Any) -> dict[str, Any]:
return mail.public_value(stored)
#: 运行并发一组(app/cluster/slots.py)
CONCURRENCY_GROUP = "concurrency"
def concurrency_values(stored: Any) -> dict[str, Any]:
from app.cluster import slots
return slots.values(stored)
def _internal(key: str) -> bool:
"""通知自己记的账(每天汇总的认领行、自动建过邮件渠道的人,notify/digest.STATE_PREFIX):不是用户设置,不列、不收。"""
from app.notify.digest import STATE_PREFIX
@@ -945,6 +955,8 @@ DEFAULT_SETTINGS: dict[str, Any] = {
EVAL_GROUP: eval_values(None),
# 邮件服务(SMTP):通知渠道的邮件格式用它发信。缺省关
MAIL_GROUP: _mail_public(None),
# 运行并发(app/cluster/slots.py):全站同时运行的上限,交互、应用、定时、系统四类各自的上限和优先级。多进程时几个进程合起来算
CONCURRENCY_GROUP: concurrency_values(None),
}
@@ -1011,6 +1023,7 @@ async def get_settings(session: AsyncSession = Depends(get_session)) -> dict[str
merged[APPS_GROUP] = apps_values(stored.get(APPS_GROUP))
merged[LEDGER_GROUP] = ledger_values(stored.get(LEDGER_GROUP))
merged[EVAL_GROUP] = eval_values(stored.get(EVAL_GROUP))
merged[CONCURRENCY_GROUP] = concurrency_values(stored.get(CONCURRENCY_GROUP))
# 口令不回(password 恒为 null),只说配没配(password_set)
merged[MAIL_GROUP] = _mail_public(stored.get(MAIL_GROUP))
for key, value in stored.items():
@@ -1122,6 +1135,14 @@ async def put_settings(
if problem := eval_problem(payload.values[EVAL_GROUP]):
raise HTTPException(422, problem)
payload.values[EVAL_GROUP] = eval_values(payload.values[EVAL_GROUP])
if CONCURRENCY_GROUP in payload.values:
from app.cluster import slots
if problem := slots.problem(payload.values[CONCURRENCY_GROUP]):
raise HTTPException(422, problem)
saved_row = await session.get(Setting, CONCURRENCY_GROUP)
payload.values[CONCURRENCY_GROUP] = slots.merged(saved_row.value if saved_row is not None else None,
payload.values[CONCURRENCY_GROUP])
if MAIL_GROUP in payload.values:
from app.notify import mail
@@ -1144,9 +1165,17 @@ async def put_settings(
else:
session.add(Setting(key=key, value=value))
await session.commit()
if CONCURRENCY_GROUP in payload.values:
# 本进程马上按新的发名额(别的进程最迟几秒,slots.POLICY_TTL_S)
from app.cluster import slots
slots.forget_policy()
if NOTIFY_GROUP in payload.values:
# 中间件、单点登录的回调按进程缓存取对外访问地址:写完库就刷新,不用重启
public_url.remember(payload.values[NOTIFY_GROUP][public_url.SETTING_KEY])
from app.cluster import caches
await caches.broadcast("public_url")
return await get_settings(session)
@@ -1226,4 +1255,14 @@ async def system_info() -> dict[str, Any]:
"max_run_seconds": app_settings.max_run_seconds,
"model_timeout_seconds": app_settings.model_timeout_seconds,
},
# 多进程协调(app/cluster):登记着的工作进程、谁在调度当班、各类运行在跑 / 在等几个
"cluster": await _cluster_info(),
}
async def _cluster_info() -> dict[str, Any]:
from app.cluster import identity, leader, slots, workers
return {"me": identity.owner(), "database": app_settings.db_dialect, "workers": await workers.listing(),
"leader": await leader.current(), "runs": await slots.snapshot(),
"lease_s": workers.lease_s(), "heartbeat_s": workers.heartbeat_s()}
+1 -1
View File
@@ -310,7 +310,7 @@ async def background_jobs(source_id: str, session: AsyncSession = Depends(get_se
brief = await module.job_brief(session, job) if job is not None else None
if job is None or brief is None:
continue
ahead = runtime.lanes.ahead(row.id, job.id)
ahead = await runtime.lanes.ahead(row.id, job.id)
position = len(ahead) if ahead is not None else None
found.append((position, job.created_at, {
"kind": kind, "id": job.id, "status": brief["status"], "total": brief.get("total", 0),