diff --git a/backend/app/gateway/app.py b/backend/app/gateway/app.py index a663c3f4e1..811dbea6f8 100644 --- a/backend/app/gateway/app.py +++ b/backend/app/gateway/app.py @@ -957,7 +957,14 @@ async def _gateway_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: set_subagent_batch_submitter(batch_service) app.state.subagent_batches_available = True - yield + workers = getattr(app.state, "coordination_workers", None) + try: + if workers is not None: + workers.start_recovery() + yield + finally: + if workers is not None: + await workers.close() await _shutdown_startup_trash_sweep(app) try: diff --git a/backend/app/gateway/coordination_workers.py b/backend/app/gateway/coordination_workers.py index b203e0f2f9..07462d17aa 100644 --- a/backend/app/gateway/coordination_workers.py +++ b/backend/app/gateway/coordination_workers.py @@ -3,6 +3,7 @@ import asyncio import logging from hashlib import sha256 +from time import time from uuid import uuid4 from deerflow_extension_api.agent_runs import AgentRunError @@ -11,47 +12,174 @@ from fastapi import HTTPException from app.gateway.deps import get_agent_runs from deerflow.persistence.coordination.model import TaskStatus from deerflow.persistence.coordination.sql import TaskConflict, TaskNotFound -from deerflow.persistence.coordination.workers import THREAD_PREFIX +from deerflow.persistence.coordination.workers import THREAD_PREFIX, WORKER_CHECKPOINT_RUN, WORKER_SHUTDOWN +from deerflow.runtime.runs.manager import LEASE_ORPHAN_RECOVERY_ERROR, ORPHAN_RECOVERY_STOP_REASON, STARTUP_ORPHAN_RECOVERY_ERROR logger = logging.getLogger(__name__) CANCEL_RESPONSE_TIMEOUT = 5 +RECOVERY_INTERVAL = 10 +GRANT_LIFETIME = 24 * 60 * 60 +WORKER_RUN_PERMISSIONS = frozenset({"runs:create", "runs:read", "threads:read", "threads:write"}) +WORKER_CANCEL_PERMISSIONS = frozenset({"runs:read", "runs:cancel"}) +WORKER_PERMISSIONS = WORKER_RUN_PERMISSIONS | WORKER_CANCEL_PERMISSIONS class CoordinationWorkers: - def __init__(self, repository): + def __init__(self, repository, host, connections=None): self.repo = repository + self._host = host + self._connections = connections self._drivers = {} self._wakeups = set() self._cancellations = {} + self._recovery = None + + def start_recovery(self): + self._recovery = asyncio.create_task(self._recover()) async def close(self): jobs = [*self._drivers.values(), *self._cancellations.values()] + if self._recovery is not None: + jobs.append(self._recovery) for job in jobs: job.cancel() await asyncio.gather(*jobs, return_exceptions=True) - async def dispatch(self, runs, owner, task_id, assistant_id): - turn = await self.repo.prepare(owner, task_id, assistant_id) - if turn is not None: - await self._admit(runs, owner, task_id, turn) - self.watch(runs, owner, task_id) - return await self.repo.view(owner, task_id) + @staticmethod + def _new_grant(authority, *, channel=None): + if authority is None: + raise AgentRunError(403, "A task requires restorable run authorization") + return { + "id": uuid4().hex, + "authority": {**authority, "permissions": sorted(WORKER_PERMISSIONS.intersection(authority["permissions"]))}, + "channel": channel, + "expires_at": time() + GRANT_LIFETIME, + } - async def _admit(self, runs, owner, task_id, turn): + async def dispatch(self, runs, owner, task_id, assistant_id, *, channel=None): + grant = self._new_grant(runs.capture_authority(), channel=channel) + turn = await self.repo.prepare(owner, task_id, assistant_id, initial_grant=grant) + if turn is not None: + authorized, grant_id = await self.authority(owner, task_id) + await self._admit(authorized, owner, task_id, turn, grant_id) + self.watch(authorized, owner, task_id, grant_id) + return await self.view(owner, task_id) + + async def dispatch_bound_channel(self, message, *, request_id, objective, assistant_id="lead_agent"): + """Entry point for a Gateway-side adapter after provider authentication.""" + from app.gateway.auth_disabled import AUTH_SOURCE_SESSION + from app.gateway.authz import resolve_route_permissions + + if self._connections is None or self._host.load_user is None or not message.connection_id or not message.owner_user_id or not message.user_id: + raise AgentRunError(403, "A bound messaging identity is required") + connection = await self._connections.find_connection_by_external_identity( + provider=message.channel_name, + external_account_id=message.user_id, + workspace_id=message.workspace_id or None, + ) + owner = message.owner_user_id + if connection is None or connection["id"] != message.connection_id or connection["owner_user_id"] != owner: + raise AgentRunError(403, "The messaging identity is no longer bound") + user = await self._host.load_user(owner) + if user is None or user.disabled or user.needs_setup: + raise AgentRunError(403, "The task owner is unavailable") + permissions = WORKER_PERMISSIONS.intersection(await resolve_route_permissions(user, is_internal=False)) + if "runs:create" not in permissions: + raise AgentRunError(403, "Permission denied: runs:create") + snapshot = {"token_version": user.token_version, "source": AUTH_SOURCE_SESSION, "permissions": sorted(permissions)} + runs = await self._host.restore_delegated_authority(user_id=owner, grant=snapshot) + request_key = sha256(f"{connection['id']}:{request_id}".encode()).hexdigest() + task = await self.repo.create(owner, request_id=f"im:{request_key}", objective=objective) + return await self.dispatch(runs, owner, task["id"], assistant_id, channel={"id": connection["id"], "updated_at": connection["updated_at"]}) + + async def authority(self, owner, task_id, *, cancelling=False): + grant = await self.repo.grant(owner, task_id) + if grant is None: + raise AgentRunError(403, "Task requires authorization") + + async def validate(): + current = await self.repo.grant(owner, task_id) + if current is None or current["id"] != grant["id"]: + raise AgentRunError(403, "Task authorization was revoked") + + runs = await self._host.restore_delegated_authority( + user_id=owner, + grant=grant["authority"], + validator=validate, + plugin_namespace="native-coordination", + required_permissions=WORKER_CANCEL_PERMISSIONS if cancelling else WORKER_RUN_PERMISSIONS, + ) + return runs, grant["id"] + + async def authorize(self, runs, owner, task_id): + await self.repo.set_grant(owner, task_id, self._new_grant(runs.capture_authority())) + return await self.view(owner, task_id) + + async def submit_input(self, owner, task_id, *, request_id, content): + receipt = await self.repo.replay_input(owner, task_id, request_id=request_id, content=content) + if receipt is not None: + return receipt + runs, grant_id = await self.authority(owner, task_id) + receipt = await self.repo.append_input(owner, task_id, request_id=request_id, content=content) + self.watch(runs, owner, task_id, grant_id) + return receipt + + async def view(self, owner, task_id): + view = await self.repo.view(owner, task_id) + required = False + status = view["task"]["status"] + if status in (TaskStatus.QUEUED, TaskStatus.RUNNING, TaskStatus.CANCELLING): + try: + await self.authority(owner, task_id, cancelling=status == TaskStatus.CANCELLING) + except AgentRunError as exc: + if exc.status_code != 403: + raise + required = True + return {**view, "authorization_required": required} + + async def recover_once(self): + after = "" + while page := await self.repo.recovery_page(after): + for task_id, owner, status, epoch in page: + key = (owner, task_id) + jobs = self._cancellations if status == TaskStatus.CANCELLING else self._drivers + if (job := jobs.get(key)) is not None and not job.done(): + continue + try: + runs, grant_id = await self.authority(owner, task_id, cancelling=status == TaskStatus.CANCELLING) + except AgentRunError as exc: + if exc.status_code != 403: + raise + continue + if status == TaskStatus.CANCELLING: + self._cancel_job(runs, owner, task_id, epoch) + else: + self.watch(runs, owner, task_id, grant_id) + after = page[-1][0] + + async def _recover(self): + while True: + try: + await self.recover_once() + except Exception: + logger.exception("Coordination recovery scan failed") + await asyncio.sleep(RECOVERY_INTERVAL) + + async def _admit(self, runs, owner, task_id, turn, grant_id): worker, execution, project = turn thread = worker["thread_id"] if execution["run_id"] is None: try: await runs.create_thread(thread_id=thread, assistant_id=worker["assistant_id"], project_id=project) - admitted = await runs.start_coordination_worker(task_id=task_id, execution_id=execution["id"]) + admitted = await runs.start_coordination_worker(task_id=task_id, execution_id=execution["id"], grant_id=grant_id) return admitted.run_id except AgentRunError as exc: - if exc.status_code in (400, 403, 404, 422): + if exc.status_code in (400, 404, 422): await self.repo.settle(owner, task_id, execution["id"], None, "admission_failed", []) raise return execution["run_id"] - def watch(self, runs, owner, task_id): + def watch(self, runs, owner, task_id, grant_id): key = (owner, task_id) if (existing := self._drivers.get(key)) is not None and not existing.done(): self._wakeups.add(key) @@ -62,7 +190,7 @@ class CoordinationWorkers: while True: self._wakeups.discard(key) try: - await self._drive(runs, owner, task_id) + await self._drive(runs, owner, task_id, grant_id) except AgentRunError as exc: if exc.status_code < 500: raise @@ -85,13 +213,13 @@ class CoordinationWorkers: task.add_done_callback(finished) return task - async def _drive(self, runs, owner, task_id): + async def _drive(self, runs, owner, task_id, grant_id): while (turn := await self.repo.prepare(owner, task_id)) is not None: worker, execution, _project = turn if execution["status"] == "waiting_for_input": return if execution["run_id"] is None: - await self._admit(runs, owner, task_id, turn) + await self._admit(runs, owner, task_id, turn, grant_id) continue thread = worker["thread_id"] try: @@ -100,7 +228,15 @@ class CoordinationWorkers: continue artifacts = [] status = run.status - if status == "success" and not run.stop_reason: + if run.stop_reason == WORKER_SHUTDOWN or (run.stop_reason == ORPHAN_RECOVERY_STOP_REASON and run.error in (STARTUP_ORPHAN_RECOVERY_ERROR, LEASE_ORPHAN_RECOVERY_ERROR)): + state = await runs.coordination_recovery_checkpoint(thread_id=thread, run_id=run.run_id) + if state and state.get("checkpoint_id") and state.get("metadata", {}).get(WORKER_CHECKPOINT_RUN) == run.run_id and state.get("next"): + if any(task.get("interrupts") for task in state.get("tasks", [])): + status = "waiting_for_input" + else: + await self.repo.recover_checkpoint(owner, task_id, execution["id"], run.run_id, state["checkpoint_id"]) + continue + elif status == "success" and not run.stop_reason: try: artifacts = await runs.coordination_artifacts(thread_id=thread, run_id=run.run_id) except AgentRunError as exc: @@ -115,10 +251,16 @@ class CoordinationWorkers: task = await self.repo.request_cancel(owner, task_id, expected_revision=revision) if task["status"] == TaskStatus.CANCELLED: return task + job = self._cancel_job(runs, owner, task_id, task["execution_epoch"]) + # asyncio.wait leaves the tracked job running after the response deadline. + done, _ = await asyncio.wait({job}, timeout=CANCEL_RESPONSE_TIMEOUT) + return job.result() if done else task + + def _cancel_job(self, runs, owner, task_id, epoch): key = (owner, task_id) job = self._cancellations.get(key) if job is None or job.done(): - job = asyncio.create_task(self._finish_cancellation(runs, owner, task_id, task["execution_epoch"])) + job = asyncio.create_task(self._finish_cancellation(runs, owner, task_id, epoch)) self._cancellations[key] = job def finished(completed): @@ -128,9 +270,7 @@ class CoordinationWorkers: logger.warning("Coordination cancellation stopped for task %s (%s)", task_id, type(error).__name__) job.add_done_callback(finished) - # asyncio.wait leaves the tracked job running after the response deadline. - done, _ = await asyncio.wait({job}, timeout=CANCEL_RESPONSE_TIMEOUT) - return job.result() if done else task + return job async def _finish_cancellation(self, runs, owner, task_id, epoch): delay = 1 @@ -193,10 +333,11 @@ async def managed_task(request, thread_id): async def direct_worker_run(request, task_id, body, key): from app.gateway.deps import get_run_manager - service, owner, runs = worker_context(request) + service, owner, _runs = worker_context(request) if getattr(request.state, "run_origin", None) or body.checkpoint or body.checkpoint_id or body.conversation_references or body.multitask_strategy != "reject": raise HTTPException(409, "Use a task input to continue this managed worker") try: + runs, grant_id = await service.authority(owner, task_id) if body.command is not None: if set(body.command) != {"resume"} or body.command["resume"] is None or body.input: raise HTTPException(422, "An explicit interrupt response is required") @@ -207,8 +348,8 @@ async def direct_worker_run(request, task_id, body, key): if native.status == "waiting_for_input": await service.repo.settle(owner, task_id, current["id"], native.run_id, native.status, []) turn = await service.repo.resume(owner, task_id, key=key or uuid4().hex, value=body.command["resume"]) - run_id = await service._admit(runs, owner, task_id, turn) - service.watch(runs, owner, task_id) + run_id = await service._admit(runs, owner, task_id, turn, grant_id) + service.watch(runs, owner, task_id, grant_id) else: messages = (body.input or {}).get("messages") if not isinstance(messages, list) or len(messages) != 1 or not isinstance(messages[0], dict): @@ -223,7 +364,7 @@ async def direct_worker_run(request, task_id, body, key): if not isinstance(identifier, str): raise HTTPException(422, "Message ID must be a string") row = await service.repo.append_input(owner, task_id, request_id="chat:" + sha256(identifier.encode()).hexdigest(), content=content) - driver = service.watch(runs, owner, task_id) + driver = service.watch(runs, owner, task_id, grant_id) # Streaming and wait endpoints must observe the Run that consumed this input. while not (run_id := await service.repo.run_for_input(owner, task_id, row["sequence"])): if driver.done(): diff --git a/backend/app/gateway/deps.py b/backend/app/gateway/deps.py index f99cdf8c7a..547d3f9e2c 100644 --- a/backend/app/gateway/deps.py +++ b/backend/app/gateway/deps.py @@ -965,14 +965,10 @@ async def langgraph_runtime(app: FastAPI, startup_config: AppConfig) -> AsyncGen stack.callback(reset_login_throttle_store) if sf is not None: - from app.gateway.coordination_workers import CoordinationWorkers - from deerflow.persistence.coordination.workers import CoordinationWorkerRepository from deerflow.persistence.feedback import FeedbackRepository from deerflow.persistence.personal_access_tokens import PersonalAccessTokenRepository from deerflow.persistence.run import RunRepository - app.state.coordination_workers = CoordinationWorkers(CoordinationWorkerRepository(sf)) - stack.push_async_callback(app.state.coordination_workers.close) app.state.run_store = RunRepository(sf) app.state.feedback_repo = FeedbackRepository(sf) from app.gateway.auth.pat import PAT_LAST_USED_WRITE_INTERVAL_SECONDS @@ -1164,6 +1160,13 @@ async def langgraph_runtime(app: FastAPI, startup_config: AppConfig) -> AsyncGen app.state.agent_runs_host = GatewayAgentRunsHost(app, load_user=SQLiteUserRepository(sf).get_user_by_id if sf is not None else None) stack.callback(app.state.agent_runs_host.close) + if sf is not None: + from app.gateway.coordination_workers import CoordinationWorkers + from deerflow.persistence.channel_connections.sql import ChannelConnectionRepository + from deerflow.persistence.coordination.workers import CoordinationWorkerRepository + + app.state.coordination_workers = CoordinationWorkers(CoordinationWorkerRepository(sf), app.state.agent_runs_host, ChannelConnectionRepository(sf)) + stack.push_async_callback(app.state.coordination_workers.close) # Extension unattended recovery waits on this before restoring grants; # past it, the whole run-admission stack above is ready. agent_runs_host_installed.set() diff --git a/backend/app/gateway/extension_agent_runs.py b/backend/app/gateway/extension_agent_runs.py index 36ad5afe7d..4947d7dc26 100644 --- a/backend/app/gateway/extension_agent_runs.py +++ b/backend/app/gateway/extension_agent_runs.py @@ -60,6 +60,10 @@ class GatewayAgentRunsHost: self.active = False def bind(self, request: Request): + # A background task's synthetic authorization must not be re-minted + # as a general-purpose session handle for the agent it starts. + if getattr(request.state, "coordination_grant_id", None) is not None: + return None user = getattr(request.state, "user", None) auth = getattr(request.state, "auth", None) if user is None or auth is None or not auth.is_authenticated: @@ -96,6 +100,7 @@ class GatewayAgentRunsHost: grant: dict, validator: Callable[[], Awaitable[None]] | None = None, plugin_namespace: str | None = None, + required_permissions: frozenset[str] = frozenset(), ): """Restore a persisted delegated grant (e.g. workflow recovery) with its ceiling. @@ -105,6 +110,8 @@ class GatewayAgentRunsHost: this handle performs. Restoring re-loads the user row and fails closed on a changed token_version, needs_setup or a disabled account, exactly like ``restore_batch_authority``; it never creates fresh authority. + Callers can preflight required permissions against the grant and current + policy. Host operations still revalidate permissions at use. """ source, version, permissions = grant.get("source"), grant.get("token_version"), grant.get("permissions") if source not in (AUTH_SOURCE_SESSION, AUTH_SOURCE_AUTH_DISABLED) or type(version) is not int or not isinstance(permissions, list) or any(not isinstance(value, str) for value in permissions): @@ -112,12 +119,17 @@ class GatewayAgentRunsHost: user = get_auth_disabled_user() if source == AUTH_SOURCE_AUTH_DISABLED and is_auth_disabled() else await self.load_user(user_id) if source == AUTH_SOURCE_SESSION and self.load_user is not None else None if user is None or str(user.id) != user_id or user.token_version != version or user.needs_setup or getattr(user, "disabled", False): raise AgentRunError(403, "Delegated authorization revoked") + granted_permissions = frozenset(permissions) + if required_permissions: + current_permissions = await resolve_route_permissions(user, is_internal=False) + if not required_permissions.issubset(granted_permissions.intersection(current_permissions)): + raise AgentRunError(403, "Delegated authorization lacks required permissions") return _BoundAgentRuns( self, user_id, version, source, - frozenset(permissions), + granted_permissions, plugin_namespace=plugin_namespace, origin=make_origin("extension", namespace=plugin_namespace), delegation_validator=validator, @@ -350,7 +362,7 @@ class _BoundAgentRuns: async def start(self, *, thread_id, input, context=None, idempotency_key=None, execution_fence=None, artifact_imports=None) -> AgentRun: return await self._start(thread_id=thread_id, input=input, context=context, idempotency_key=idempotency_key, execution_fence=execution_fence, artifact_imports=artifact_imports) - async def start_coordination_worker(self, *, task_id, execution_id): + async def start_coordination_worker(self, *, task_id, execution_id, grant_id): from app.gateway.run_models import RunCreateRequest from app.gateway.services import start_run from deerflow.persistence.coordination.sql import TaskConflict, TaskNotFound @@ -371,28 +383,32 @@ class _BoundAgentRuns: raise AgentRunError(409, "Worker thread binding changed") body = RunCreateRequest( assistant_id=worker["assistant_id"], - input=None if "command" in frozen else frozen, + input=frozen if "messages" in frozen else None, command=frozen.get("command"), + checkpoint_id=frozen.get("checkpoint_id"), context={"subagent_enabled": True}, on_disconnect="continue", ) request.state.coordination_execution_id = execution_id + request.state.coordination_grant_id = grant_id record = await start_run(body, thread_id, request, require_existing_thread=True, idempotency_key=RUN_KEY_PREFIX + execution_id) return _view(record) async def wait_coordination_worker(self, *, thread_id, run_id, timeout=60): """Observe the committed terminal status, written after the delivery receipt.""" - from app.gateway.deps import get_run_store + from app.gateway.deps import get_run_event_store, get_run_store + from deerflow.extensions.run_evidence import StoreRunEvidenceReader async with asyncio.timeout(timeout): delay = 0.25 while True: async with self._request("runs:read", thread_id) as request: - row = await get_run_store(request).get(run_id, user_id=self._user_id) - if row is None or row["thread_id"] != thread_id: + evidence = StoreRunEvidenceReader(get_run_store(request), get_run_event_store(request), user_id=self._user_id) + row = await evidence.get_run_status(thread_id=thread_id, run_id=run_id) + if row is None: raise AgentRunError(404, "Worker run unavailable") - if row["status"] not in ("pending", "running"): - return AgentRun(thread_id, run_id, row["status"], row.get("assistant_id"), row.get("stop_reason")) + if row.status not in ("pending", "running"): + return row await asyncio.sleep(delay) delay = min(delay * 2, 4) @@ -402,6 +418,21 @@ class _BoundAgentRuns: async with self._request("runs:cancel", thread_id) as request: await get_subagent_batch_service(request).cancel_batch(batch_id=batch_id, user_id=self._user_id, continuation_authority=self) + async def coordination_recovery_checkpoint(self, *, thread_id, run_id): + from app.gateway.deps import get_run_store + + async with self._request("runs:read", thread_id) as request: + row = await get_run_store(request).get(run_id, user_id=self._user_id) + if row is None or row["thread_id"] != thread_id or row.get("cancel_requested_at"): + return None + try: + return await self.get_state(thread_id=thread_id) + except AgentRunError as exc: + if exc.status_code != 404: + raise + # A stopped Run can have no readable checkpoint after restart. + return None + async def coordination_artifacts(self, *, thread_id, run_id): from app.gateway.artifact_archive import MAX_FILE_BYTES, MAX_FILES, MAX_TOTAL_BYTES from app.gateway.deps import get_run_event_store diff --git a/backend/app/gateway/routers/coordination.py b/backend/app/gateway/routers/coordination.py index c81f7ae847..d42588cfb7 100644 --- a/backend/app/gateway/routers/coordination.py +++ b/backend/app/gateway/routers/coordination.py @@ -56,7 +56,7 @@ async def create_worker_task(body: CreateWorkerTask, request: Request): async def get_worker_task(task_id: str, request: Request): service, owner, _runs = worker_context(request) try: - return await service.repo.view(owner, task_id) + return await service.view(owner, task_id) except TaskNotFound as exc: raise HTTPException(404, "Task not found") from exc @@ -64,12 +64,10 @@ async def get_worker_task(task_id: str, request: Request): @router.post("/{task_id}/inputs") @require_permission("runs", "create") async def add_worker_input(task_id: str, body: WorkerInput, request: Request): - service, owner, runs = worker_context(request) + service, owner, _runs = worker_context(request) try: - item = await service.repo.append_input(owner, task_id, request_id="input:" + sha256(body.request_id.encode()).hexdigest(), content=body.content) - service.watch(runs, owner, task_id) - return item - except (TaskNotFound, TaskConflict) as exc: + return await service.submit_input(owner, task_id, request_id="input:" + sha256(body.request_id.encode()).hexdigest(), content=body.content) + except (TaskNotFound, TaskConflict, AgentRunError) as exc: raise worker_error(exc) from exc @@ -96,6 +94,27 @@ async def cancel_worker_task(task_id: str, body: CancelTask, request: Request, r return task +@router.put("/{task_id}/authorization") +@require_permission("runs", "create") +async def authorize_worker_task(task_id: str, request: Request): + service, owner, runs = worker_context(request) + try: + return await service.authorize(runs, owner, task_id) + except (TaskNotFound, TaskConflict, AgentRunError) as exc: + raise worker_error(exc) from exc + + +@router.delete("/{task_id}/authorization", status_code=204) +@require_permission("runs", "cancel") +async def revoke_worker_task(task_id: str, request: Request): + service, owner, _runs = worker_context(request) + try: + await service.repo.set_grant(owner, task_id, None) + except (TaskNotFound, TaskConflict) as exc: + raise worker_error(exc) from exc + return Response(status_code=204) + + @router.get("/{task_id}/artifacts") @require_permission("threads", "read") async def list_worker_artifacts(task_id: str, request: Request, limit: int = Query(100, ge=1, le=100), offset: int = Query(0, ge=0)): diff --git a/backend/app/gateway/run_inputs.py b/backend/app/gateway/run_inputs.py index e66daf7248..8e21563622 100644 --- a/backend/app/gateway/run_inputs.py +++ b/backend/app/gateway/run_inputs.py @@ -46,18 +46,19 @@ async def submit_run_input(thread_id: str, run_id: str, body: RunInputRequest, r raise HTTPException(404, "Run not found") if get_agent_runs(request) is None: raise HTTPException(503, "Run inputs require an authenticated session") + from deerflow_extension_api.agent_runs import AgentRunError + from app.gateway.coordination_workers import managed_task, worker_context, worker_error from deerflow.persistence.coordination.sql import TaskConflict, TaskNotFound if task_id := await managed_task(request, thread_id): - service, owner, runs = worker_context(request) + service, owner, _runs = worker_context(request) if body.mode != "queue": raise HTTPException(409, "Use queue mode to update a managed worker") try: - item = await service.repo.append_input(owner, task_id, request_id=f"run-input:{run_id}:{body.request_id}", content=body.text) - service.watch(runs, owner, task_id) + item = await service.submit_input(owner, task_id, request_id=f"run-input:{run_id}:{body.request_id}", content=body.text) return _worker_input_receipt(item, run_id, body.request_id) - except (TaskConflict, TaskNotFound) as exc: + except (TaskConflict, TaskNotFound, AgentRunError) as exc: raise worker_error(exc) from exc row = await _store(request).get(run_id, user_id=user_id) if row is None or row.get("run_inputs") is None: diff --git a/backend/app/gateway/services.py b/backend/app/gateway/services.py index 94149e01c0..27c5582f9d 100644 --- a/backend/app/gateway/services.py +++ b/backend/app/gateway/services.py @@ -2587,7 +2587,7 @@ async def start_run( raise HTTPException(status_code=404, detail=f"Thread {thread_id} not found") from app.gateway.coordination_workers import direct_worker_run, managed_task - from deerflow.persistence.coordination.workers import THREAD_PREFIX + from deerflow.persistence.coordination.workers import RUN_GRANT_METADATA, THREAD_PREFIX, WORKER_CHECKPOINT_RUN if thread_id.startswith(THREAD_PREFIX) and not getattr(request.state, "coordination_execution_id", None): if task_id := await managed_task(request, thread_id): @@ -2667,6 +2667,8 @@ async def start_run( # is what keeps a forged value out of the live run config. origin = resolve_request_origin(request, body.metadata) run_metadata = _admit_scheduler_metadata(body.metadata, trusted=scheduled_task_runtime is not None) + run_metadata.pop(RUN_GRANT_METADATA, None) + run_metadata.pop(WORKER_CHECKPOINT_RUN, None) run_metadata.pop(DEERFLOW_ORIGIN_KEY, None) if origin is not None: run_metadata[DEERFLOW_ORIGIN_KEY] = origin @@ -2679,6 +2681,8 @@ async def start_run( raise HTTPException(status_code=422, detail=str(exc)) from exc if isinstance(config.get("metadata"), dict): config["metadata"] = _admit_scheduler_metadata(config["metadata"], trusted=scheduled_task_runtime is not None) + config["metadata"].pop(RUN_GRANT_METADATA, None) + config["metadata"].pop(WORKER_CHECKPOINT_RUN, None) config["metadata"].pop(DEERFLOW_ORIGIN_KEY, None) if origin is not None: config["metadata"][DEERFLOW_ORIGIN_KEY] = origin @@ -3105,6 +3109,8 @@ async def start_run( # appear while this request prepares its admission. Recheck # under the thread lock so a fresh input cannot replace it. await reject_new_run_when_approval_pending(request, thread_id) + if (grant_id := getattr(request.state, "coordination_grant_id", None)) is not None: + run_metadata[RUN_GRANT_METADATA] = grant_id return await run_mgr.create_or_reject( thread_id, body.assistant_id, diff --git a/backend/docs/task-coordination-state.md b/backend/docs/task-coordination-state.md index 8a210f2f02..15815f48ad 100644 --- a/backend/docs/task-coordination-state.md +++ b/backend/docs/task-coordination-state.md @@ -44,12 +44,17 @@ Content-Type: application/json ``` The response includes the task, its assignment (agent and thread), and the -latest execution. Replaying the request reuses the worker. Read the same -view with `GET /api/coordination/tasks/{task_id}`. Add a follow-up with +latest execution. After the task has admitted a Run, replaying the same create +request returns the saved task view and its current `authorization_required` +value, even if the Worker grant has expired. Read the same view with +`GET /api/coordination/tasks/{task_id}`. Add a follow-up with `POST /api/coordination/tasks/{task_id}/inputs` and a JSON object containing -`request_id` and `content`. A text message sent to the worker thread uses -the same queue. Streaming and wait callers observe the run that consumes -their message. An interrupted graph requires an explicit resume command. +`request_id` and `content`. The owner can replay an accepted input with the same +ID and content to get its original receipt after task closure or grant expiry. +This applies to the task input and managed Run input endpoints. New inputs need +a valid Worker grant. A text message sent to the worker thread uses the same +queue. Streaming and wait callers observe the run that consumes their message. +An interrupted graph requires an explicit resume command. The task owner can poll `GET /api/coordination/tasks/{task_id}/inputs` to read the inbox in sequence order. Pass the last seen `sequence` as @@ -92,7 +97,31 @@ through them. Files presented under the same path in different turns have separate IDs and URLs. The task detail's `execution.artifacts` lists deliveries produced by that execution. -Worker observation uses the initiating session's process-local run handle. -The task, frozen inputs, native run IDs and artifact contents survive a Gateway -restart. Automatic reauthorization and restart reconciliation are tracked in -the next stage of [RFC #8345](https://github.com/bytedance/deer-flow/issues/8345). +## Authorization and restart recovery + +Dispatch saves a task-scoped grant alongside the first Worker assignment. The +grant expires after 24 hours. The Gateway revalidates the owner's account, +session version, permissions and current grant on each host operation. +Grant replacement and Run admission share the task tree lock. + +The Gateway can also mint a grant for an authenticated IM adapter after looking +up the sender's current channel connection. Disconnecting or replacing the +binding invalidates the grant. The adapter entry point runs inside the Gateway. +IM commands and delivery are covered by a later stage of +[RFC #8345](https://github.com/bytedance/deer-flow/issues/8345). + +On startup and periodically, the Gateway reconciles open tasks with grants. +It observes live Runs, records results from committed terminal Run evidence, +and retries frozen admissions with their original idempotency key. A Run +interrupted by Gateway shutdown can continue from a pending checkpoint written +by that Run. When the checkpoint is missing, the Gateway settles the execution +from the Run's durable outcome. Pending approvals still require an +explicit response. Recovery also continues work already fenced for cancellation. + +The task view reports `authorization_required` when an open task lacks a +valid grant or its current permissions no longer cover the work. Recovery +waits for permission to return and can then continue with the same grant if +it remains valid. Older tasks created before the migration need a grant. +An authorized owner can renew with `PUT /api/coordination/tasks/{task_id}/authorization` +or revoke with `DELETE /api/coordination/tasks/{task_id}/authorization`. +The Grant table stores only authority metadata and the binding generation. diff --git a/backend/packages/harness/deerflow/persistence/coordination/model.py b/backend/packages/harness/deerflow/persistence/coordination/model.py index 2af92c6c64..91c67163b3 100644 --- a/backend/packages/harness/deerflow/persistence/coordination/model.py +++ b/backend/packages/harness/deerflow/persistence/coordination/model.py @@ -3,7 +3,7 @@ from datetime import datetime from enum import StrEnum -from sqlalchemy import JSON, BigInteger, DateTime, ForeignKey, ForeignKeyConstraint, Index, LargeBinary, String, Text, UniqueConstraint +from sqlalchemy import JSON, BigInteger, DateTime, Double, ForeignKey, ForeignKeyConstraint, Index, LargeBinary, String, Text, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column from deerflow.persistence.base import Base @@ -64,6 +64,17 @@ class CoordinationAssignmentRow(Base): assistant_id: Mapped[str] = mapped_column(String(128)) +class CoordinationGrantRow(Base): + """One current delegation per task. Reauthorization rotates its ID.""" + + __tablename__ = "coord_task_grants" + task_id: Mapped[str] = mapped_column(ForeignKey("coord_tasks.id"), primary_key=True) + id: Mapped[str] = mapped_column(String(64)) + authority: Mapped[dict] = mapped_column(JSON) + channel: Mapped[dict | None] = mapped_column(JSON) + expires_at: Mapped[float] = mapped_column(Double) + + class CoordinationExecutionRow(Base): __tablename__ = "coord_executions" __table_args__ = ( diff --git a/backend/packages/harness/deerflow/persistence/coordination/sql.py b/backend/packages/harness/deerflow/persistence/coordination/sql.py index 59c079deef..6b4bc430fe 100644 --- a/backend/packages/harness/deerflow/persistence/coordination/sql.py +++ b/backend/packages/harness/deerflow/persistence/coordination/sql.py @@ -139,17 +139,29 @@ class CoordinationTaskRepository: raise TaskConflict("Request ID was already used with different task data") return _snapshot(existing) + @staticmethod + async def _matching_input(session: AsyncSession, task_id: str, request_id: str, content: str) -> dict | None: + existing = await session.scalar(select(CoordinationInputRow).filter_by(task_id=task_id, request_id=request_id)) + if existing is None: + return None + if existing.content != content: + raise TaskConflict("Request ID was already used with different input") + return _snapshot(existing) + + async def replay_input(self, owner_id: str, task_id: str, *, request_id: str, content: str) -> dict | None: + """Return the owner's accepted receipt, including for a closed task.""" + async with self._sessions() as session: + await self._lookup(session, owner_id, task_id) + return await self._matching_input(session, task_id, request_id, content) + async def append_input(self, owner_id: str, task_id: str, *, request_id: str, content: str) -> dict: _request_id(request_id) if not content.strip(): raise ValueError("Task input is required") async with self._write() as session: task = await self._lock_tree(session, owner_id, task_id) - existing = await session.scalar(select(CoordinationInputRow).filter_by(task_id=task_id, request_id=request_id)) - if existing is not None: - if existing.content != content: - raise TaskConflict("Request ID was already used with different input") - return _snapshot(existing) + if (receipt := await self._matching_input(session, task_id, request_id, content)) is not None: + return receipt if task.status not in _OPEN: raise TaskConflict("Task is closed to new input") task.latest_input_seq += 1 diff --git a/backend/packages/harness/deerflow/persistence/coordination/workers.py b/backend/packages/harness/deerflow/persistence/coordination/workers.py index 6806459d5b..94b19aa899 100644 --- a/backend/packages/harness/deerflow/persistence/coordination/workers.py +++ b/backend/packages/harness/deerflow/persistence/coordination/workers.py @@ -1,5 +1,6 @@ """Durable admission, cancellation and result ownership for managed workers.""" +from time import time from uuid import uuid4 from sqlalchemy import select @@ -7,15 +8,19 @@ from sqlalchemy import select from deerflow.persistence.coordination.model import CoordinationArtifactRow as Artifact from deerflow.persistence.coordination.model import CoordinationAssignmentRow as Assignment from deerflow.persistence.coordination.model import CoordinationExecutionRow as Execution +from deerflow.persistence.coordination.model import CoordinationGrantRow as Grant from deerflow.persistence.coordination.model import CoordinationInputRow, CoordinationTaskRow, TaskStatus from deerflow.persistence.coordination.sql import CoordinationTaskRepository, TaskConflict, TaskNotFound THREAD_PREFIX = "coord-worker-" RUN_KEY_PREFIX = "coord-execution:" +RUN_GRANT_METADATA = "_coordination_grant_id" +WORKER_CHECKPOINT_RUN = "_coordination_checkpoint_run" +WORKER_SHUTDOWN = "coordination_gateway_shutdown" INPUT_SOURCES = {"input": "task_api", "chat": "worker_chat", "run-input": "run_input"} -async def bind_admitted_worker(session, thread_id, owner_id, key, run_id): +async def bind_admitted_worker(session, thread_id, owner_id, key, run_id, *, grant_id=None): """Called inside native SQL run admission, under the same tree lock as cancellation.""" from deerflow.runtime.runs.manager import ConflictError @@ -37,11 +42,79 @@ async def bind_admitted_worker(session, thread_id, owner_id, key, run_id): or execution.status != "admitting" ): raise ConflictError("Managed worker admission no longer matches the task") + grant = await session.get(Grant, task_id) + # Old tasks and older Gateways have no grant. Once a grant is installed, + # only its current generation may admit the next Run under the tree lock. + if grant is not None: + if grant.id != grant_id or grant.expires_at <= time() or not await grant_owner_matches(session, owner_id, grant.authority) or not await channel_binding_matches(session, owner_id, grant.channel, lock=True): + raise ConflictError("Task run authorization is no longer current") execution.run_id = run_id execution.status = "running" +async def grant_owner_matches(session, owner, authority): + if authority.get("source") == "auth_disabled": + return True # The host checks the live deployment setting before admission. + if authority.get("source") != "session" or type(authority.get("token_version")) is not int: + return False + from deerflow.persistence.user.model import UserRow + + user = await session.scalar(select(UserRow).where(UserRow.id == owner).with_for_update()) + return user is not None and not user.disabled and not user.needs_setup and user.token_version == authority["token_version"] + + +async def channel_binding_matches(session, owner, channel, *, lock=False): + if channel is None: + return True + from deerflow.persistence.channel_connections.model import ChannelConnectionRow + from deerflow.utils.time import coerce_iso + + query = select(ChannelConnectionRow).filter_by(id=channel["id"], owner_user_id=owner, status="connected") + row = await session.scalar(query.with_for_update() if lock else query) + return row is not None and coerce_iso(row.updated_at) == channel["updated_at"] + + class CoordinationWorkerRepository(CoordinationTaskRepository): + async def grant(self, owner, task_id): + async with self._sessions() as session: + await self._lookup(session, owner, task_id) + row = await session.get(Grant, task_id) + if row is None or row.expires_at <= time() or not await channel_binding_matches(session, owner, row.channel): + return None + return row.to_dict() + + async def set_grant(self, owner, task_id, grant): + async with self._write() as session: + task = await self._lock_tree(session, owner, task_id) + if task.status not in (TaskStatus.QUEUED, TaskStatus.RUNNING, TaskStatus.CANCELLING): + raise TaskConflict("Task is closed") + current = await session.get(Grant, task_id) + if grant is None: + if current is not None: + current.expires_at = 0 + elif current is None: + session.add(Grant(task_id=task_id, **grant)) + else: + current.id = grant["id"] + current.authority = grant["authority"] + current.channel = grant["channel"] + current.expires_at = grant["expires_at"] + + async def recovery_page(self, after, *, limit=100): + async with self._sessions() as session: + query = ( + select(CoordinationTaskRow.id, CoordinationTaskRow.owner_id, CoordinationTaskRow.status, CoordinationTaskRow.execution_epoch) + .join(Grant, Grant.task_id == CoordinationTaskRow.id) + .where( + CoordinationTaskRow.id > after, + CoordinationTaskRow.status.in_((TaskStatus.RUNNING, TaskStatus.CANCELLING)), + Grant.expires_at > time(), + ) + .order_by(CoordinationTaskRow.id) + .limit(limit) + ) + return (await session.execute(query)).all() + async def task_for_thread(self, thread_id): async with self._sessions() as session: return await session.scalar(select(Assignment.task_id).filter_by(thread_id=thread_id)) @@ -50,6 +123,10 @@ class CoordinationWorkerRepository(CoordinationTaskRepository): def _latest(task_id): return select(Execution).filter_by(task_id=task_id).order_by(Execution.turn.desc()).limit(1) + @staticmethod + def _latest_assignment(task_id): + return select(Assignment).filter_by(task_id=task_id).order_by(Assignment.epoch.desc()).limit(1) + @staticmethod async def _artifact_refs(session, task_id, *, execution_id=None, limit=None, offset=0): query = ( @@ -77,7 +154,7 @@ class CoordinationWorkerRepository(CoordinationTaskRepository): async def view(self, owner, task_id): async with self._sessions() as session: task = await self._lookup(session, owner, task_id) - assignment = await session.scalar(select(Assignment).filter_by(task_id=task_id).order_by(Assignment.epoch.desc()).limit(1)) + assignment = await session.scalar(self._latest_assignment(task_id)) execution = await session.scalar(self._latest(task_id)) result = None if execution is not None: @@ -111,13 +188,17 @@ class CoordinationWorkerRepository(CoordinationTaskRepository): raise TaskNotFound(artifact_id) return artifact.path, artifact.content - async def prepare(self, owner, task_id, assistant_id=None): - """Freeze a bounded turn before admission. Duplicate drivers get the same turn.""" + async def prepare(self, owner, task_id, assistant_id=None, *, initial_grant=None): + """Freeze a turn for dispatch or observation. Only dispatch supplies an assistant ID.""" async with self._write() as session: task = await self._lock_tree(session, owner, task_id) worker = await session.get(Assignment, (task_id, task.execution_epoch)) - if worker is not None and assistant_id is not None and worker.assistant_id != assistant_id: - raise TaskConflict("Task already has a different worker") + if assistant_id is not None: + assigned = worker + if assigned is None and task.execution_epoch: + assigned = await session.scalar(self._latest_assignment(task_id)) + if assigned is not None and assigned.assistant_id != assistant_id: + raise TaskConflict("Task already has a different worker") if task.status == TaskStatus.QUEUED: await self._start_locked(session, task) if task.status != TaskStatus.RUNNING: @@ -127,7 +208,14 @@ class CoordinationWorkerRepository(CoordinationTaskRepository): raise TaskConflict("Task has no assigned worker") worker = Assignment(task_id=task_id, epoch=task.execution_epoch, assistant_id=assistant_id, thread_id=THREAD_PREFIX + uuid4().hex) session.add(worker) + if initial_grant is not None and await session.get(Grant, task_id) is None: + session.add(Grant(task_id=task_id, **initial_grant)) await session.flush() + elif assistant_id is not None: + # A create retry returns the saved task even if a later turn is awaiting admission. + admitted = select(Execution.run_id).where(Execution.task_id == task_id, Execution.run_id.is_not(None)).limit(1) + if await session.scalar(admitted) is not None: + return None execution = await session.scalar(self._latest(task_id)) if execution is None or (execution.status == "superseded" and execution.covered_seq < task.latest_input_seq): previous = execution.covered_seq if execution else 0 @@ -181,6 +269,26 @@ class CoordinationWorkerRepository(CoordinationTaskRepository): worker = await session.get(Assignment, (task_id, execution.epoch)) return worker.to_dict(), execution.to_dict(), task.project_id + async def recover_checkpoint(self, owner, task_id, execution_id, run_id, checkpoint_id): + """Freeze a single successor for a known stopped run and pinned checkpoint.""" + async with self._write() as session: + task = await self._lock_tree(session, owner, task_id) + previous = await session.scalar(self._latest(task_id)) + if task.status != TaskStatus.RUNNING or previous is None or previous.id != execution_id or previous.epoch != task.execution_epoch or previous.status != "running" or previous.run_id != run_id: + return + previous.status = "interrupted" + session.add( + Execution( + id=uuid4().hex, + task_id=task_id, + turn=previous.turn + 1, + epoch=previous.epoch, + covered_seq=previous.covered_seq, + frozen_input={"checkpoint_id": checkpoint_id}, + status="admitting", + ) + ) + async def settle(self, owner, task_id, execution_id, run_id, status, artifacts): async with self._write() as session: task = await self._lock_tree(session, owner, task_id) diff --git a/backend/packages/harness/deerflow/persistence/migrations/versions/0059_coordination_grants.py b/backend/packages/harness/deerflow/persistence/migrations/versions/0059_coordination_grants.py new file mode 100644 index 0000000000..62e270114f --- /dev/null +++ b/backend/packages/harness/deerflow/persistence/migrations/versions/0059_coordination_grants.py @@ -0,0 +1,26 @@ +"""Persist revocable Task-scoped runtime authority.""" + +import sqlalchemy as sa +from alembic import op + +revision = "0059_coordination_grants" +down_revision = "0058_mcp_browser_oauth" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + if not sa.inspect(op.get_bind()).has_table("coord_task_grants"): + op.create_table( + "coord_task_grants", + sa.Column("task_id", sa.String(64), sa.ForeignKey("coord_tasks.id"), primary_key=True), + sa.Column("id", sa.String(64), nullable=False), + sa.Column("authority", sa.JSON(), nullable=False), + sa.Column("channel", sa.JSON(), nullable=True), + sa.Column("expires_at", sa.Double(), nullable=False), + ) + + +def downgrade() -> None: + if sa.inspect(op.get_bind()).has_table("coord_task_grants"): + op.drop_table("coord_task_grants") diff --git a/backend/packages/harness/deerflow/persistence/models/__init__.py b/backend/packages/harness/deerflow/persistence/models/__init__.py index 2aa676edc0..f950e0520a 100644 --- a/backend/packages/harness/deerflow/persistence/models/__init__.py +++ b/backend/packages/harness/deerflow/persistence/models/__init__.py @@ -24,7 +24,7 @@ from deerflow.persistence.channel_connections.model import ( from deerflow.persistence.channel_leases.model import ChannelLeaseRow from deerflow.persistence.channel_runtime_configs.model import ChannelRuntimeConfigRow from deerflow.persistence.channel_thread_bindings.model import ChannelThreadBindingRow -from deerflow.persistence.coordination.model import CoordinationArtifactRow, CoordinationAssignmentRow, CoordinationExecutionRow, CoordinationInputRow, CoordinationTaskRow +from deerflow.persistence.coordination.model import CoordinationArtifactRow, CoordinationAssignmentRow, CoordinationExecutionRow, CoordinationGrantRow, CoordinationInputRow, CoordinationTaskRow from deerflow.persistence.extension_leases.model import ExtensionExecutionLeaseRow from deerflow.persistence.feedback.model import FeedbackRow from deerflow.persistence.login_throttle.model import LoginThrottleRow @@ -65,6 +65,7 @@ __all__ = [ "CoordinationArtifactRow", "CoordinationAssignmentRow", "CoordinationExecutionRow", + "CoordinationGrantRow", "CoordinationInputRow", "CoordinationTaskRow", "FeedbackRow", diff --git a/backend/packages/harness/deerflow/persistence/run/sql.py b/backend/packages/harness/deerflow/persistence/run/sql.py index 60211d012a..eae5f90acd 100644 --- a/backend/packages/harness/deerflow/persistence/run/sql.py +++ b/backend/packages/harness/deerflow/persistence/run/sql.py @@ -1206,10 +1206,10 @@ class RunRepository(RunStore): if existing is not None: raise RunIdempotencyConflict(self._row_to_dict(existing)) - from deerflow.persistence.coordination.workers import THREAD_PREFIX, bind_admitted_worker + from deerflow.persistence.coordination.workers import RUN_GRANT_METADATA, THREAD_PREFIX, bind_admitted_worker if thread_id.startswith(THREAD_PREFIX) and values["operation_kind"] == "run": - await bind_admitted_worker(session, thread_id, resolved_user_id, idempotency_key, run_id) + await bind_admitted_worker(session, thread_id, resolved_user_id, idempotency_key, run_id, grant_id=(metadata or {}).get(RUN_GRANT_METADATA)) if multitask_strategy in ("interrupt", "rollback"): stmt = ( diff --git a/backend/packages/harness/deerflow/runtime/runs/manager.py b/backend/packages/harness/deerflow/runtime/runs/manager.py index 98225fb097..3bfd45ac2b 100644 --- a/backend/packages/harness/deerflow/runtime/runs/manager.py +++ b/backend/packages/harness/deerflow/runtime/runs/manager.py @@ -293,6 +293,7 @@ class RunRecord: start_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False) abort_event: asyncio.Event = field(default_factory=asyncio.Event, repr=False) abort_action: str = "interrupt" + coordination_shutdown: bool = False error: str | None = None model_name: str | None = None store_only: bool = False @@ -3596,6 +3597,8 @@ class RunManager: ``app.gateway.app._SHUTDOWN_HOOK_TIMEOUT_SECONDS``. Runs still active after ``timeout`` are logged and may still race teardown. """ + from deerflow.persistence.coordination.workers import RUN_GRANT_METADATA, WORKER_SHUTDOWN + loop = asyncio.get_running_loop() deadline = loop.time() + timeout @@ -3608,6 +3611,8 @@ class RunManager: finalizing = [record for record in self._runs.values() if record.status not in (RunStatus.pending, RunStatus.running) and record.task is not None and not record.task.done()] finalizing_ids = {record.run_id for record in finalizing} for record in inflight: + if not record.abort_event.is_set() and (record.metadata or {}).get(RUN_GRANT_METADATA): + record.coordination_shutdown = True record.abort_action = "interrupt" record.abort_event.set() record.task.cancel() # type: ignore[union-attr] # filtered above @@ -3649,6 +3654,8 @@ class RunManager: continue if record.status in (RunStatus.pending, RunStatus.running): record.status = RunStatus.interrupted + if record.coordination_shutdown: + record.stop_reason = WORKER_SHUTDOWN record.terminal_status_persisted = self._store is None record.updated_at = _now_iso() to_persist.append(record) diff --git a/backend/packages/harness/deerflow/runtime/runs/worker.py b/backend/packages/harness/deerflow/runtime/runs/worker.py index 490ad933dc..9da2182cea 100644 --- a/backend/packages/harness/deerflow/runtime/runs/worker.py +++ b/backend/packages/harness/deerflow/runtime/runs/worker.py @@ -1224,10 +1224,13 @@ async def run_agent( exc_info=True, ) else: + from deerflow.persistence.coordination.workers import WORKER_SHUTDOWN + await run_manager.set_status( run_id, RunStatus.interrupted, error=cleanup_error, + stop_reason=WORKER_SHUTDOWN if record.coordination_shutdown else None, **terminal_status_kwargs, ) logger.info("Run %s was cancelled", run_id) @@ -1452,6 +1455,10 @@ async def run_agent( checkpoint_metadata = {} config["metadata"] = checkpoint_metadata checkpoint_metadata[CHECKPOINT_AGENT_NAME_METADATA_KEY] = DEFAULT_AGENT_NAME_METADATA_VALUE if checkpoint_agent_name is None else checkpoint_agent_name + from deerflow.persistence.coordination.workers import RUN_GRANT_METADATA, WORKER_CHECKPOINT_RUN + + if (record.metadata or {}).get(RUN_GRANT_METADATA): + checkpoint_metadata[WORKER_CHECKPOINT_RUN] = run_id _pin_admission_project_context(config, runtime_ctx) if knowledge_scope is not None: runtime_ctx[KNOWLEDGE_SCOPE_RUNTIME_KEY] = execution_scope(knowledge_scope) diff --git a/backend/tests/test_coordination_task_repository.py b/backend/tests/test_coordination_task_repository.py index fe43b39c61..32f1de1155 100644 --- a/backend/tests/test_coordination_task_repository.py +++ b/backend/tests/test_coordination_task_repository.py @@ -81,6 +81,9 @@ async def test_concurrent_replay_and_owner_isolation(repo): other = group.create_task(repo.append_input("alice", task_id, request_id="two", content="Check logs")) (sequence,) = {job.result()["sequence"] for job in repeats} assert {sequence, other.result()["sequence"]} == {1, 2} + assert await repo.replay_input("alice", task_id, request_id="one", content="Check storage") == repeats[0].result() + with pytest.raises(TaskNotFound): + await repo.replay_input("bob", task_id, request_id="one", content="Check storage") assert [item["sequence"] for item in await repo.list_inputs("alice", task_id, after=1)] == [2] assert await repo.list_inputs("bob", task_id) == [] with pytest.raises(TaskConflict, match="different input"): @@ -174,27 +177,37 @@ async def test_cancel_and_followup_in_separate_transactions(repo): async def test_coordination_migration_matches_model_and_downgrades(database): engine, _, schema = database config = bootstrap._get_alembic_config(engine, postgres_schema=schema) + previous = "0058_mcp_browser_oauth" + revision = "0059_coordination_grants" await asyncio.to_thread(command.upgrade, config, "0055_thread_shares") - await asyncio.to_thread(command.upgrade, config, "0057_coordination_workers") + await asyncio.to_thread(command.upgrade, config, previous) + repo = CoordinationTaskRepository(async_sessionmaker(engine)) + task = await repo.create("alice", request_id="root", objective="Test the upgraded schema") + await asyncio.to_thread(command.upgrade, config, revision) async with engine.connect() as conn: def diff(sync): context = MigrationContext.configure( sync, - opts={"compare_type": True, "include_object": lambda _, name, kind, *_args: kind != "table" or name in {"coord_tasks", "coord_inputs", "coord_assignments", "coord_executions", "coord_artifacts"}}, + opts={"compare_type": True, "include_object": lambda _, name, kind, *_args: kind != "table" or name in {"coord_tasks", "coord_inputs", "coord_assignments", "coord_executions", "coord_artifacts", "coord_task_grants"}}, ) return compare_metadata(context, Base.metadata) assert await conn.run_sync(diff) == [] - repo = CoordinationTaskRepository(async_sessionmaker(engine)) - task = await repo.create("alice", request_id="root", objective="Test the upgraded schema") + assert (await repo.get("alice", task["id"]))["status"] == TaskStatus.QUEUED await repo.append_input("alice", task["id"], request_id="update", content="Record an input") + await asyncio.to_thread(command.downgrade, config, previous) + async with engine.connect() as conn: + tables = await conn.run_sync(lambda sync: set(inspect(sync).get_table_names())) + assert "mcp_oauth_attempts" in tables + assert "coord_task_grants" not in tables + assert (await repo.get("alice", task["id"]))["latest_input_seq"] == 1 await asyncio.to_thread(command.downgrade, config, "0055_thread_shares") async with engine.connect() as conn: tables = await conn.run_sync(lambda sync: set(inspect(sync).get_table_names())) assert "threads_meta" in tables - assert not {"coord_tasks", "coord_inputs", "coord_assignments", "coord_executions", "coord_artifacts"} & tables - await asyncio.to_thread(command.upgrade, config, "0057_coordination_workers") + assert not {"coord_tasks", "coord_inputs", "coord_assignments", "coord_executions", "coord_artifacts", "coord_task_grants"} & tables + await asyncio.to_thread(command.upgrade, config, revision) assert (await repo.create("alice", request_id="root", objective="After re-upgrade"))["status"] == TaskStatus.QUEUED @@ -235,6 +248,8 @@ async def test_worker_admission_is_atomic_with_cancellation_and_replay(database) return_exceptions=True, ) assert cancelled["status"] == TaskStatus.CANCELLING + with pytest.raises(TaskConflict, match="different worker"): + await workers.prepare("alice", task["id"], "other_agent") stopped = await workers.cancellations("alice", task["id"]) (receipt,) = await workers.list_worker_inputs("alice", task["id"], after=0, limit=1) if isinstance(admitted, ConflictError): @@ -246,3 +261,39 @@ async def test_worker_admission_is_atomic_with_cancellation_and_replay(database) assert (receipt["status"], receipt["run_id"]) == ("admitted", "native") with pytest.raises(ConflictError): await runs.create_thread_operation_atomic("late", **kwargs, idempotency_key=RUN_KEY_PREFIX + uuid4().hex) + + +@pytest.mark.asyncio +async def test_worker_admission_rechecks_grant_generation_and_session_version(database): + from time import time + + from deerflow.persistence.coordination.workers import RUN_GRANT_METADATA, RUN_KEY_PREFIX, CoordinationWorkerRepository + from deerflow.persistence.run import RunRepository + from deerflow.persistence.user.model import UserRow + from deerflow.runtime.runs.manager import ConflictError + + engine, dialect, schema = database + await bootstrap.bootstrap_schema(engine, backend=dialect, postgres_schema=schema) + sessions = async_sessionmaker(engine) + workers, runs = CoordinationWorkerRepository(sessions), RunRepository(sessions) + async with sessions.begin() as session: + session.add(UserRow(id="alice", email="alice@example.com")) + task = await workers.create("alice", request_id="grant", objective="Review") + grant = {"id": "old", "authority": {"token_version": 0, "source": "session", "permissions": ["runs:create"]}, "channel": None, "expires_at": time() + 100} + worker, execution, _ = await workers.prepare("alice", task["id"], "lead_agent", initial_grant=grant) + kwargs = dict(thread_id=worker["thread_id"], user_id="alice", owner_worker_id="worker", lease_expires_at=None, idempotency_key=RUN_KEY_PREFIX + execution["id"]) + async with sessions.begin() as session: + (await session.get(UserRow, "alice")).token_version = 1 + with pytest.raises(ConflictError, match="authorization"): + await runs.create_thread_operation_atomic("stale-session", **kwargs, metadata={RUN_GRANT_METADATA: "old"}) + await workers.set_grant("alice", task["id"], {**grant, "id": "new", "authority": {**grant["authority"], "token_version": 1}}) + with pytest.raises(ConflictError, match="authorization"): + await runs.create_thread_operation_atomic("stale-grant", **kwargs, metadata={RUN_GRANT_METADATA: "old"}) + await runs.create_thread_operation_atomic("authorized", **kwargs, metadata={RUN_GRANT_METADATA: "new"}) + assert (await workers.view("alice", task["id"]))["execution"]["run_id"] == "authorized" + await workers.append_input("alice", task["id"], request_id="input:next", content="Check the report") + await workers.settle("alice", task["id"], execution["id"], "authorized", "success", []) + _, followup, _ = await workers.prepare("alice", task["id"]) + assert followup["turn"] == 2 and followup["run_id"] is None + assert await workers.prepare("alice", task["id"], "lead_agent") is None + assert (await workers.prepare("alice", task["id"]))[1] == followup diff --git a/backend/tests/test_extension_agent_runs.py b/backend/tests/test_extension_agent_runs.py index 69354f0b44..5667f7fb7f 100644 --- a/backend/tests/test_extension_agent_runs.py +++ b/backend/tests/test_extension_agent_runs.py @@ -2,7 +2,7 @@ import os from types import SimpleNamespace -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, Mock import pytest import pytest_asyncio @@ -790,8 +790,10 @@ async def worker_gateway(runtime, tmp_path): from app.gateway.coordination_workers import CoordinationWorkers from app.gateway.routers import coordination, thread_runs from deerflow.persistence.bootstrap import bootstrap_schema + from deerflow.persistence.channel_connections.sql import ChannelConnectionRepository from deerflow.persistence.coordination.workers import CoordinationWorkerRepository from deerflow.persistence.run import RunRepository + from deerflow.persistence.user.model import UserRow from deerflow.runtime import RunManager from deerflow.runtime.user_context import reset_current_user, set_current_user @@ -799,10 +801,12 @@ async def worker_gateway(runtime, tmp_path): engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'workers.db'}") await bootstrap_schema(engine, backend="sqlite") factory = async_sessionmaker(engine) + async with factory.begin() as session: + session.add(UserRow(id=str(request.state.user.id), email=request.state.user.email)) state.run_store = RunRepository(factory) await state.run_manager.shutdown() state.run_manager = RunManager(store=state.run_store) - workers = state.coordination_workers = CoordinationWorkers(CoordinationWorkerRepository(factory)) + state.coordination_workers = CoordinationWorkers(CoordinationWorkerRepository(factory), state.agent_runs_host, ChannelConnectionRepository(factory)) state.release_worker = asyncio.Event() request.app.include_router(coordination.router) request.app.include_router(thread_runs.router) @@ -818,7 +822,7 @@ async def worker_gateway(runtime, tmp_path): async with AsyncClient(transport=ASGITransport(app=authenticated), base_url="http://gateway") as client: yield client, runs, state, entered, str(request.state.user.id) finally: - await workers.close() + await state.coordination_workers.close() await state.run_manager.shutdown() await engine.dispose() @@ -915,6 +919,76 @@ async def test_managed_worker_routes_followups_and_retains_the_producing_runs_fi await state.coordination_workers.repo.read_artifact("another-user", task_id, artifacts[0]["id"]) +@pytest.mark.asyncio +async def test_managed_worker_create_retry_returns_task_after_grant_expires(worker_gateway, monkeypatch): + import asyncio + + client, _, state, entered, owner = worker_gateway + url = "/api/coordination/tasks" + body = {"request_id": "create-replay", "objective": "wait"} + first = (await client.post(url, json=body)).raise_for_status().json() + task_id = first["task"]["id"] + await asyncio.wait_for(entered.wait(), 10) + try: + grant = await state.coordination_workers.repo.grant(owner, task_id) + monkeypatch.setattr("deerflow.persistence.coordination.workers.time", lambda: grant["expires_at"] + 1) + detail = (await client.get(f"{url}/{task_id}")).raise_for_status().json() + replay = (await client.post(url, json=body)).raise_for_status().json() + assert replay == detail + assert replay["authorization_required"] is True + assert replay["execution"]["run_id"] == first["execution"]["run_id"] + assert (await client.post(url, json={**body, "objective": "changed"})).status_code == 409 + assert (await client.post(url, json={**body, "assistant_id": "different"})).status_code == 409 + finally: + state.release_worker.set() + + +@pytest.mark.asyncio +async def test_managed_worker_replays_accepted_inputs_after_grant_expires(worker_gateway, monkeypatch): + import asyncio + + client, _, state, entered, owner = worker_gateway + tasks = "/api/coordination/tasks" + first = (await client.post(tasks, json={"request_id": "receipt-replay", "objective": "wait"})).raise_for_status().json() + task_id, thread_id, run_id = first["task"]["id"], first["assignment"]["thread_id"], first["execution"]["run_id"] + inputs = [ + (f"{tasks}/{task_id}/inputs", "content", {"request_id": "follow-up", "content": "Task follow-up"}), + (f"/api/threads/{thread_id}/runs/{run_id}/inputs", "text", {"request_id": "follow-up", "mode": "queue", "text": "Run follow-up"}), + ] + await asyncio.wait_for(entered.wait(), 10) + try: + receipts = [(await client.post(path, json=payload)).raise_for_status().json() for path, _, payload in inputs] + finally: + state.release_worker.set() + finished = await _wait_for_worker(client, task_id, "task", "status", "succeeded") + workers = state.coordination_workers + grant = await workers.repo.grant(owner, task_id) + monkeypatch.setattr("deerflow.persistence.coordination.workers.time", lambda: grant["expires_at"] + 1) + wake = Mock(side_effect=AssertionError("receipt replay must not wake a Worker")) + monkeypatch.setattr(workers, "watch", wake) + + for (path, text_field, payload), receipt in zip(inputs, receipts, strict=True): + assert (await client.post(path, json=payload)).raise_for_status().json() == receipt + assert (await client.post(path, json={**payload, text_field: "changed"})).status_code == 409 + assert (await client.post(path, json={**payload, "request_id": "new"})).status_code == 403 + wake.assert_not_called() + assert (await client.get(f"{tasks}/{task_id}")).raise_for_status().json() == finished + + +@pytest.mark.asyncio +async def test_managed_worker_replays_legacy_task_input_without_grant(worker_gateway): + from hashlib import sha256 + + client, _, state, _, owner = worker_gateway + repo = state.coordination_workers.repo + task = await repo.create(owner, request_id="old-task", objective="Review") + payload = {"request_id": "old-input", "content": "Check the report"} + receipt = await repo.append_input(owner, task["id"], request_id="input:" + sha256(b"old-input").hexdigest(), content=payload["content"]) + url = f"/api/coordination/tasks/{task['id']}/inputs" + assert (await client.post(url, json=payload)).raise_for_status().json() == receipt + assert (await client.post(url, json={**payload, "request_id": "new"})).status_code == 403 + + @pytest.mark.asyncio async def test_managed_worker_requires_explicit_resume_and_fences_cancellation(worker_gateway): import asyncio @@ -983,3 +1057,142 @@ async def test_managed_worker_cancel_returns_cancelling_and_finishes_in_backgrou assert calls == [run_id, run_id] assert final["execution"]["status"] == "cancelled" assert (await runs.get(thread_id=first["assignment"]["thread_id"], run_id=run_id)).status == "interrupted" + + +async def _restart_coordination(state): + from app.gateway.coordination_workers import CoordinationWorkers + from deerflow.runtime import RunManager + + previous = state.coordination_workers + await previous.close() + await state.run_manager.shutdown() + state.agent_runs_host.close() + host = GatewayAgentRunsHost(state.agent_runs_host.app, load_user=state.agent_runs_host.load_user) + state.agent_runs_host = host + state.run_manager = RunManager(store=state.run_store) + state.coordination_workers = CoordinationWorkers(previous.repo, host, previous._connections) + await state.coordination_workers.recover_once() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("previous_outcome", ["completed", "shutdown", "cancel-takeover", "orphan-no-checkpoint"]) +async def test_managed_worker_restart_reconciles_the_persisted_task(worker_gateway, tmp_path, previous_outcome): + import asyncio + + from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver + + from deerflow.runtime import ORPHAN_RECOVERY_STOP_REASON + from deerflow.runtime.runs.manager import STARTUP_ORPHAN_RECOVERY_ERROR + + client, runs, state, entered, _ = worker_gateway + path = str(tmp_path / "checkpoints.sqlite") + async with AsyncSqliteSaver.from_conn_string(path) as saver: + if previous_outcome != "orphan-no-checkpoint": + state.checkpointer = saver + first = (await client.post("/api/coordination/tasks", json={"objective": "wait", "request_id": "restart"})).raise_for_status().json() + task_id, run_id, thread = first["task"]["id"], first["execution"]["run_id"], first["assignment"]["thread_id"] + await asyncio.wait_for(entered.wait(), 10) + await state.coordination_workers.close() + if previous_outcome == "completed": + state.release_worker.set() + assert (await runs.wait_coordination_worker(thread_id=thread, run_id=run_id)).status == "success" + await state.run_manager.shutdown() + if previous_outcome == "cancel-takeover": + await state.run_store.update_status(run_id, "error", error="Run reclaimed by worker during cancellation", stop_reason=ORPHAN_RECOVERY_STOP_REASON) + elif previous_outcome == "orphan-no-checkpoint": + await state.run_store.update_status(run_id, "error", error=STARTUP_ORPHAN_RECOVERY_ERROR, stop_reason=ORPHAN_RECOVERY_STOP_REASON) + async with AsyncSqliteSaver.from_conn_string(path) as saver: + state.checkpointer = saver + await _restart_coordination(state) + state.release_worker.set() + finished = await _wait_for_worker(client, task_id, "task", "status", "failed" if previous_outcome in ("cancel-takeover", "orphan-no-checkpoint") else "succeeded") + assert finished["assignment"]["thread_id"] == thread + assert finished["execution"]["turn"] == (2 if previous_outcome == "shutdown" else 1) + assert (finished["execution"]["run_id"] != run_id) is (previous_outcome == "shutdown") + if previous_outcome == "orphan-no-checkpoint": + assert finished["execution"]["status"] == "error" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("denial", ["runs:create", "threads:write", "revoked"]) +async def test_managed_worker_admission_waits_for_restored_authorization(worker_gateway, monkeypatch, denial): + client, runs, state, _, owner = worker_gateway + service = state.coordination_workers + task = await service.repo.create(owner, request_id="pending-admission", objective="continue") + task_id = task["id"] + grant = service._new_grant(runs.capture_authority()) + turn = await service.repo.prepare(owner, task_id, "lead_agent", initial_grant=grant) + authorized, grant_id = await service.authority(owner, task_id) + permissions = grant["authority"]["permissions"] + policy = AsyncMock(return_value=[permission for permission in permissions if permission != denial]) + monkeypatch.setattr("app.gateway.extension_agent_runs.resolve_route_permissions", policy) + if denial == "revoked": + await service.repo.set_grant(owner, task_id, None) + + driver = service.watch(authorized, owner, task_id, grant_id) + with pytest.raises(AgentRunError) as exc: + await driver + assert exc.value.status_code == 403 + url = f"/api/coordination/tasks/{task_id}" + view = (await client.get(url)).raise_for_status().json() + assert view["execution"]["id"] == turn[1]["id"] + assert view["execution"]["run_id"] is None + assert view["task"]["status"] == "running" + assert view["execution"]["status"] == "admitting" + assert view["authorization_required"] is True + retry = await client.post("/api/coordination/tasks", json={"request_id": "pending-admission", "objective": "continue"}) + assert retry.status_code == 403 + await service.recover_once() + assert (owner, task_id) not in service._drivers + + policy.return_value = permissions + if denial == "revoked": + assert (await client.put(f"{url}/authorization")).raise_for_status().json()["authorization_required"] is False + else: + assert (await service.repo.grant(owner, task_id))["id"] == grant_id + await service.recover_once() + finished = await _wait_for_worker(client, task_id, "task", "status", "succeeded") + assert finished["authorization_required"] is False + assert finished["execution"]["id"] == turn[1]["id"] + + +@pytest.mark.asyncio +async def test_managed_worker_restart_finishes_a_previously_fenced_cancellation(worker_gateway): + import asyncio + + client, _, state, entered, owner = worker_gateway + first = (await client.post("/api/coordination/tasks", json={"objective": "wait", "request_id": "restart-cancel"})).raise_for_status().json() + task_id = first["task"]["id"] + await asyncio.wait_for(entered.wait(), 10) + await state.coordination_workers.repo.request_cancel(owner, task_id, expected_revision=first["task"]["revision"]) + await _restart_coordination(state) + finished = await _wait_for_worker(client, task_id, "task", "status", "cancelled") + assert finished["execution"]["run_id"] == first["execution"]["run_id"] + assert finished["execution"]["status"] == "cancelled" + + +@pytest.mark.asyncio +async def test_bound_channel_grant_is_invalid_after_reconnect_and_owner_can_reauthorize(worker_gateway): + import asyncio + + from app.channels.message_bus import InboundMessage + + client, _, state, entered, owner = worker_gateway + service = state.coordination_workers + binding = {"owner_user_id": owner, "provider": "telegram", "external_account_id": "sender"} + connection = await service._connections.upsert_connection(**binding) + message = InboundMessage(channel_name="telegram", chat_id="chat", user_id="sender", text="wait", connection_id=connection["id"], owner_user_id=owner) + first = await service.dispatch_bound_channel(message, request_id="event", objective="wait") + task_id = first["task"]["id"] + assert (await service.dispatch_bound_channel(message, request_id="event", objective="wait"))["execution"]["run_id"] == first["execution"]["run_id"] + await asyncio.wait_for(entered.wait(), 10) + await service._connections.disconnect_connection(connection_id=connection["id"], owner_user_id=owner) + with pytest.raises(AgentRunError, match="no longer bound"): + await service.dispatch_bound_channel(message, request_id="another-event", objective="wait") + await service._connections.upsert_connection(**binding) + url = f"/api/coordination/tasks/{task_id}" + assert (await client.get(url)).json()["authorization_required"] is True + assert (await client.post(f"{url}/inputs", json={"request_id": "new", "content": "retry"})).status_code == 403 + assert (await client.put(f"{url}/authorization")).raise_for_status().json()["authorization_required"] is False + assert (await client.delete(f"{url}/authorization")).status_code == 204 + assert (await client.get(url)).json()["authorization_required"] is True diff --git a/backend/tests/test_migration_0047_mcp_oauth_tokens.py b/backend/tests/test_migration_0047_mcp_oauth_tokens.py index 5f914f833e..69a0f2ae45 100644 --- a/backend/tests/test_migration_0047_mcp_oauth_tokens.py +++ b/backend/tests/test_migration_0047_mcp_oauth_tokens.py @@ -21,7 +21,8 @@ from deerflow.persistence.mcp_oauth_tokens import McpOAuthTokenRow from deerflow.persistence.postgres_schema import build_asyncpg_connect_args REVISION = "0047_mcp_oauth_tokens" -HEAD = "0058_mcp_browser_oauth" +HEAD = "0059_coordination_grants" +BROWSER_OAUTH_REVISION = "0058_mcp_browser_oauth" PREVIOUS = "0046_skill_mutations" TABLE = "mcp_oauth_tokens" COLUMNS = { @@ -48,7 +49,8 @@ async def test_0047_remains_in_the_single_migration_chain(): assert bootstrap._get_head_revision() == HEAD script = ScriptDirectory(str(bootstrap._MIGRATIONS_DIR)) assert script.get_heads() == [HEAD] - assert script.get_revision(HEAD).down_revision == "0057_coordination_workers" + assert script.get_revision(HEAD).down_revision == BROWSER_OAUTH_REVISION + assert script.get_revision(BROWSER_OAUTH_REVISION).down_revision == "0057_coordination_workers" assert script.get_revision("0057_coordination_workers").down_revision == "0056_coordination_task_state" assert script.get_revision("0056_coordination_task_state").down_revision == "0055_thread_shares" assert script.get_revision("0055_thread_shares").down_revision == "0054_project_memory" @@ -210,7 +212,7 @@ async def test_browser_oauth_migration_preserves_legacy_tokens_and_drops_delegat async with engine.begin() as conn: table = await conn.run_sync(lambda sync: sa.Table(TABLE, sa.MetaData(), autoload_with=sync)) await conn.execute(sa.insert(table).values(**_row(refresh_token_enc="legacy ciphertext"))) - await asyncio.to_thread(command.upgrade, cfg, HEAD) + await asyncio.to_thread(command.upgrade, cfg, BROWSER_OAUTH_REVISION) assert await _orm_diff(engine) == [] async with engine.begin() as conn: assert (await conn.execute(sa.select(McpOAuthTokenRow.grant_epoch))).scalar_one() is None