feat(maf): add secure roundtable workflow runtime

This commit is contained in:
董宏凯 committed 2026-08-01 17:51:53 +08:00
1 parent e690475e6e
commit bd4131b4e2
52 files changed
+10315 -96

No files matched your search

@@ -198,12 +198,31 @@ async def delete_session(request: Request, session_id: str) -> dict[str, Any]:
async def create_run(request: Request, session_id: str, body: CreateRunRequest) -> RunResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
# Check MAF SDK availability BEFORE creating the run — so the user gets a
# clean 503 rather than a run that will immediately fail.
from app.maf_roundtable.dispatcher import MafSdkNotAvailableError, get_dispatcher
dispatcher = get_dispatcher(request.app)
try:
dispatcher.check_sdk_available()
except MafSdkNotAvailableError as exc:
raise HTTPException(status_code=503, detail=str(exc)) from exc
try:
run = await svc.create_run(
session_id=session_id, user_id=user_id, workflow_version=body.workflow_version, is_admin=is_admin
)
except (MafDisabledError, MafForbiddenError, MafNotFoundError, MafConflictError) as exc:
raise _map_service_error(exc) from exc
# Launch the workflow in the background. The run is already persisted as
# "pending"; the dispatcher transitions it to "running" then completes/fails it.
# Auto-dispatch can be disabled (e.g. in tests) via app.state.maf_auto_dispatch=False.
if getattr(request.app.state, "maf_auto_dispatch", True):
session = await svc.get_session(session_id=session_id, user_id=user_id, is_admin=is_admin)
await dispatcher.dispatch(session, run, user_id=user_id or "default")
return RunResponse(**run)
@@ -233,11 +252,43 @@ async def get_run(request: Request, run_id: str) -> RunResponse:
async def cancel_run(request: Request, run_id: str) -> RunResponse:
svc = _require_service(request)
user_id, is_admin = _user_ctx(request)
# Phase 1: atomically set run+session to cancelling (not yet cancelled).
try:
run = await svc.cancel_run(run_id=run_id, user_id=user_id, is_admin=is_admin)
await svc.start_cancel(run_id=run_id, user_id=user_id, is_admin=is_admin)
except (MafDisabledError, MafForbiddenError, MafNotFoundError) as exc:
raise _map_service_error(exc) from exc
return RunResponse(**run)
# Phase 2: cascade cancel to the background task + DeerFlow sub-runs.
from app.maf_roundtable.dispatcher import get_dispatcher
dispatcher = get_dispatcher(request.app)
result = await dispatcher.cancel(run_id)
# Phase 3: finalize based on the structured cancel result.
# - all_cancelled → finalize to ``cancelled`` (terminal).
# - some sub-runs failed/still active → mark ``cancel_failed`` (non-terminal)
# so the failure is visible and retryable. A failed cancel must NEVER
# masquerade as cancelled.
try:
if result.get("all_cancelled"):
final_run = await svc.finalize_cancel(run_id=run_id, user_id=user_id, is_admin=is_admin)
else:
failed = result.get("failed_run_ids") or []
still_active = result.get("still_active_run_ids") or []
detail = []
if failed:
detail.append(f"{len(failed)} sub-run(s) failed to cancel")
if still_active:
detail.append(f"{len(still_active)} sub-run(s) had no DeerFlow run id")
reason = "; ".join(detail) or "cancel cascade incomplete"
final_run = await svc.mark_cancel_failed(
run_id=run_id, user_id=user_id, is_admin=is_admin, reason=reason
)
except (MafDisabledError, MafForbiddenError, MafNotFoundError) as exc:
raise _map_service_error(exc) from exc
return RunResponse(**final_run)
# ── events ─────────────────────────────────────────────────────────────────
@@ -310,4 +361,25 @@ async def decide_approval(request: Request, approval_id: str, body: ApprovalDeci
)
except (MafDisabledError, MafForbiddenError, MafNotFoundError, MafConflictError) as exc:
raise _map_service_error(exc) from exc
# P1: after a successful approval decision, resume the workflow from its
# checkpoint. Only the owner can resume (decide_approval already enforced
# owner-only write). The resume loads the checkpoint, restores
# RoundtableState.from_dict(), and executes the approved action (at-most-once).
run_id = approval.get("run_id")
if run_id and body.decision in ("approved", "rejected"):
from app.maf_roundtable.dispatcher import get_dispatcher
dispatcher = get_dispatcher(request.app)
try:
await dispatcher.resume(run_id, user_id=user_id or "default")
except Exception:
# Resume failure should not fail the approval response itself —
# the approval is already persisted. Log for observability.
import logging
logging.getLogger(__name__).exception(
"MAF resume failed for run %s after approval %s", run_id, approval_id
)
return ApprovalResponse(**approval)