feat(coordination): persist worker run settings (#8540)

* feat(coordination): persist worker run settings

Refs #8533

* test(persistence): update coordination migration head

Keep the single-head migration regression aligned with revision 0060 and assert the new edge to the existing grant revision.

---------

Co-authored-by: ZcWang <200940025+hajicheng@users.noreply.github.com>
This commit is contained in:
hajicheng 2026-11-24 10:27:32 +08:00 committed by GitHub
parent 6763d2ace4
commit f81d1633a4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 139 additions and 18 deletions

View File

@ -371,7 +371,7 @@ class _BoundAgentRuns:
async with self._request("runs:create") as request:
try:
worker, frozen, project_id = await request.app.state.coordination_workers.repo.admission(self._user_id, task_id, execution_id)
worker, frozen, project_id, saved_settings = await request.app.state.coordination_workers.repo.admission(self._user_id, task_id, execution_id)
except TaskNotFound as exc:
raise AgentRunError(404, "Worker task unavailable") from exc
except TaskConflict as exc:
@ -381,12 +381,16 @@ class _BoundAgentRuns:
record = await request.app.state.thread_store.get(thread_id, user_id=self._user_id)
if record is None or record.get("assistant_id") != worker["assistant_id"] or (record.get("metadata") or {}).get(THREAD_PROJECT_METADATA_KEY) != project_id:
raise AgentRunError(409, "Worker thread binding changed")
settings = saved_settings or {}
context = {key: settings[key] for key in ("thinking_enabled", "is_plan_mode") if key in settings}
context["subagent_enabled"] = True
body = RunCreateRequest(
assistant_id=worker["assistant_id"],
input=frozen if "messages" in frozen else None,
command=frozen.get("command"),
checkpoint_id=frozen.get("checkpoint_id"),
context={"subagent_enabled": True},
config={"recursion_limit": settings["recursion_limit"]} if "recursion_limit" in settings else None,
context=context,
on_disconnect="continue",
)
request.state.coordination_execution_id = execution_id

View File

@ -7,7 +7,7 @@ from typing import Annotated
from deerflow_extension_api.agent_runs import AgentRunError
from fastapi import APIRouter, HTTPException, Query, Request
from fastapi.responses import Response
from pydantic import BaseModel, Field, StringConstraints
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StringConstraints
from app.gateway.authz import require_permission
from app.gateway.coordination_workers import worker_context, worker_error
@ -20,11 +20,20 @@ RequestId = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1
TaskText = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=16384)]
class WorkerRunSettings(BaseModel):
model_config = ConfigDict(extra="forbid")
recursion_limit: int | None = Field(default=None, strict=True, ge=1)
thinking_enabled: StrictBool | None = None
is_plan_mode: StrictBool | None = None
class CreateWorkerTask(BaseModel):
request_id: RequestId
objective: TaskText
assistant_id: str = Field(default="lead_agent", min_length=1, max_length=128)
project_id: str | None = Field(default=None, min_length=1, max_length=64)
run: WorkerRunSettings | None = None
class WorkerInput(BaseModel):
@ -42,7 +51,13 @@ async def create_worker_task(body: CreateWorkerTask, request: Request):
service, owner, runs = worker_context(request)
async def dispatch():
task = await service.repo.create(owner, request_id=body.request_id, objective=body.objective, project_id=body.project_id)
task = await service.repo.create(
owner,
request_id=body.request_id,
objective=body.objective,
project_id=body.project_id,
run_settings=body.run.model_dump(exclude_none=True) if body.run is not None else None,
)
return await service.dispatch(runs, owner, task["id"], body.assistant_id)
try:

View File

@ -40,9 +40,23 @@ an optional `project_id` to create its thread in an existing project.
POST /api/coordination/tasks
Content-Type: application/json
{"request_id":"review-27","objective":"Review the report","assistant_id":"lead_agent"}
{
"request_id": "review-27",
"objective": "Review the report",
"assistant_id": "lead_agent",
"run": {"recursion_limit": 400, "thinking_enabled": true, "is_plan_mode": false}
}
```
The optional `run` object accepts a positive integer `recursion_limit` and
boolean `thinking_enabled` and `is_plan_mode` flags. Omit any field to use the
normal run default. Each admission caps the requested recursion limit at the
Gateway's current `max_recursion_limit`. The task view shows the requested
settings in `task.run_settings`, or `null` when the task uses defaults.
Settings are saved at creation and apply to every turn, including follow-ups,
approval responses, and restart recovery. Reusing a create request ID with
changed settings returns HTTP 409.
The response includes the task, its assignment (agent and thread), and the
latest execution. After the task has admitted a Run, replaying the same create
request returns the saved task view and its current `authorization_required`

View File

@ -34,6 +34,7 @@ class CoordinationTaskRow(Base):
parent_id: Mapped[str | None] = mapped_column(ForeignKey("coord_tasks.id"))
depends_on: Mapped[list[str]] = mapped_column(JSON)
objective: Mapped[str] = mapped_column(Text)
run_settings: Mapped[dict[str, int | bool] | None] = mapped_column(JSON(none_as_null=True))
status: Mapped[str] = mapped_column(String(16))
revision: Mapped[int] = mapped_column(BigInteger)
execution_epoch: Mapped[int] = mapped_column(BigInteger)

View File

@ -90,19 +90,21 @@ class CoordinationTaskRepository:
project_id: str | None = None,
parent_id: str | None = None,
depends_on: Sequence[str] = (),
run_settings: dict[str, int | bool] | None = None,
) -> dict:
"""Create a task once. Dependencies refer to previously created siblings."""
_request_id(request_id)
if not objective.strip():
raise ValueError("Task objective is required")
dependencies = sorted(set(depends_on))
saved_run_settings = dict(run_settings) if run_settings else None
async with self._write() as session:
parent = await self._lock_tree(session, owner_id, parent_id) if parent_id is not None else None
if parent is not None:
if project_id is not None and project_id != parent.project_id:
raise TaskConflict("A child task must use its parent's project")
project_id = parent.project_id
create_fields = dict(objective=objective, project_id=project_id, parent_id=parent_id, depends_on=dependencies)
create_fields = dict(objective=objective, project_id=project_id, parent_id=parent_id, depends_on=dependencies, run_settings=saved_run_settings)
existing = await session.scalar(select(CoordinationTaskRow).filter_by(owner_id=owner_id, request_id=request_id))
if existing is None:
if parent is not None and parent.status not in _OPEN:

View File

@ -173,7 +173,7 @@ class CoordinationWorkerRepository(CoordinationTaskRepository):
if execution is None or execution.task_id != task_id or execution.epoch != task.execution_epoch or task.status != TaskStatus.RUNNING:
raise TaskConflict("Task no longer accepts this execution")
worker = await session.get(Assignment, (task_id, execution.epoch))
return worker.to_dict(), execution.frozen_input, task.project_id
return worker.to_dict(), execution.frozen_input, task.project_id, task.run_settings
async def list_artifacts(self, owner, task_id, *, limit, offset):
async with self._sessions() as session:

View File

@ -0,0 +1,20 @@
"""Persist optional run settings for managed coordination tasks."""
import sqlalchemy as sa
revision = "0060_coordination_run_settings"
down_revision = "0059_coordination_grants"
branch_labels = None
depends_on = None
def upgrade() -> None:
from deerflow.persistence.migrations._helpers import safe_add_column
safe_add_column("coord_tasks", sa.Column("run_settings", sa.JSON(none_as_null=True), nullable=True))
def downgrade() -> None:
from deerflow.persistence.migrations._helpers import safe_drop_column
safe_drop_column("coord_tasks", "run_settings")

View File

@ -177,12 +177,18 @@ 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"
previous = "0059_coordination_grants"
revision = "0060_coordination_run_settings"
await asyncio.to_thread(command.upgrade, config, "0055_thread_shares")
await asyncio.to_thread(command.upgrade, config, previous)
async with engine.begin() as conn:
await conn.execute(
text(
"INSERT INTO coord_tasks (id, owner_id, request_id, root_id, depends_on, objective, status, revision, execution_epoch, latest_input_seq, created_at, updated_at) "
"VALUES ('legacy', 'alice', 'root', 'legacy', '[]', 'Test the upgraded schema', 'queued', 0, 0, 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
)
)
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:
@ -194,14 +200,25 @@ async def test_coordination_migration_matches_model_and_downgrades(database):
return compare_metadata(context, Base.metadata)
assert await conn.run_sync(diff) == []
assert (await repo.get("alice", task["id"]))["status"] == TaskStatus.QUEUED
task = await repo.get("alice", "legacy")
assert task["status"] == TaskStatus.QUEUED
assert task["run_settings"] is None
assert await repo.create("alice", request_id="root", objective=task["objective"], run_settings={}) == task
await repo.append_input("alice", task["id"], request_id="update", content="Record an input")
settings = {"recursion_limit": 400, "thinking_enabled": False}
configured = await repo.create("alice", request_id="configured", objective="Review", run_settings=settings)
assert (await repo.get("alice", configured["id"]))["run_settings"] == settings
await asyncio.to_thread(command.downgrade, config, previous)
async with engine.connect() as conn:
columns = await conn.run_sync(lambda sync: {item["name"] for item in inspect(sync).get_columns("coord_tasks")})
assert "run_settings" not in columns
assert await conn.scalar(text("SELECT latest_input_seq FROM coord_tasks WHERE id = 'legacy'")) == 1
await asyncio.to_thread(command.downgrade, config, "0058_mcp_browser_oauth")
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()))

View File

@ -169,6 +169,9 @@ async def runtime(host, monkeypatch, tmp_path):
return {"messages": [AIMessage(content=f"answer:{prompt}")]}
def factory(*, config):
if (settings := getattr(state, "observed_worker_settings", None)) is not None and "run_id" in config["context"]:
context = config["context"]
settings.append((config["recursion_limit"], context.get("thinking_enabled"), context.get("is_plan_mode")))
builder = StateGraph(MessagesState)
builder.add_node("answer", answer)
builder.set_entry_point("answer")
@ -808,6 +811,7 @@ async def worker_gateway(runtime, tmp_path):
state.run_manager = RunManager(store=state.run_store)
state.coordination_workers = CoordinationWorkers(CoordinationWorkerRepository(factory), state.agent_runs_host, ChannelConnectionRepository(factory))
state.release_worker = asyncio.Event()
state.observed_worker_settings = []
request.app.include_router(coordination.router)
request.app.include_router(thread_runs.router)
@ -919,6 +923,39 @@ 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_reuses_saved_run_settings_for_followups(worker_gateway):
import asyncio
client, _, state, entered, _ = worker_gateway
url = "/api/coordination/tasks"
settings = {"recursion_limit": 400, "thinking_enabled": True, "is_plan_mode": False}
body = {"request_id": "dispatch", "objective": "wait", "run": settings}
first = (await client.post(url, json=body)).raise_for_status().json()
task_id = first["task"]["id"]
try:
await asyncio.wait_for(entered.wait(), 10)
assert first["task"]["run_settings"] == settings
assert (await client.post(url, json=body)).raise_for_status().json() == first
assert (await client.post(url, json={**body, "run": {**settings, "is_plan_mode": True}})).status_code == 409
(await client.post(f"{url}/{task_id}/inputs", json={"request_id": "follow-up", "content": "Review the results"})).raise_for_status()
finally:
state.release_worker.set()
finished = await _wait_for_worker(client, task_id, "task", "status", "succeeded")
assert finished["execution"]["turn"] == 2
assert state.observed_worker_settings == [(400, True, False)] * 2
@pytest.mark.asyncio
@pytest.mark.parametrize("settings", [{"recursion_limit": 0}, {"recursion_limit": True}, {"thinking_enabled": "false"}, {"user_id": "another-user"}, {"subagent_enabled": False}])
async def test_managed_worker_rejects_invalid_run_settings(worker_gateway, settings):
client, _, _, _, _ = worker_gateway
response = await client.post("/api/coordination/tasks", json={"request_id": "invalid", "objective": "Review", "run": settings})
assert response.status_code == 422
assert response.json()["detail"][0]["loc"][:2] == ["body", "run"]
@pytest.mark.asyncio
async def test_managed_worker_create_retry_returns_task_after_grant_expires(worker_gateway, monkeypatch):
import asyncio
@ -927,6 +964,8 @@ async def test_managed_worker_create_retry_returns_task_after_grant_expires(work
url = "/api/coordination/tasks"
body = {"request_id": "create-replay", "objective": "wait"}
first = (await client.post(url, json=body)).raise_for_status().json()
assert first["task"]["run_settings"] is None
assert (await client.post(url, json={**body, "run": {}})).raise_for_status().json() == first
task_id = first["task"]["id"]
await asyncio.wait_for(entered.wait(), 10)
try:
@ -993,17 +1032,19 @@ async def test_managed_worker_replays_legacy_task_input_without_grant(worker_gat
async def test_managed_worker_requires_explicit_resume_and_fences_cancellation(worker_gateway):
import asyncio
client, runs, _, entered, _ = worker_gateway
client, runs, state, entered, _ = worker_gateway
url = "/api/coordination/tasks"
paused = (await client.post(url, json={"request_id": "pause", "objective": "approve"})).raise_for_status().json()
settings = {"recursion_limit": 240, "thinking_enabled": False, "is_plan_mode": True}
paused = (await client.post(url, json={"request_id": "pause", "objective": "approve", "run": settings})).raise_for_status().json()
task_id = paused["task"]["id"]
await _wait_for_worker(client, task_id, "execution", "status", "waiting_for_input")
target = f"/api/threads/{paused['assignment']['thread_id']}/runs"
reply = {"json": {"command": {"resume": "confirmed"}}, "headers": {"Idempotency-Key": "reply"}}
reply = {"json": {"command": {"resume": "confirmed"}, "config": {"recursion_limit": 25}, "context": {"is_plan_mode": False}}, "headers": {"Idempotency-Key": "reply"}}
answered = (await client.post(target, **reply)).raise_for_status().json()
result = await _wait_for_worker(client, task_id, "task", "status", "succeeded")
assert result["task"]["result_ref"].endswith(f"/{answered['run_id']}/messages")
assert (await client.post(target, **reply)).raise_for_status().json()["run_id"] == answered["run_id"]
assert state.observed_worker_settings == [(240, False, True)] * 2
other = (await client.post(url, json={"request_id": "cancel", "objective": "wait"})).raise_for_status().json()
await asyncio.wait_for(entered.wait(), 10)
@ -1081,15 +1122,18 @@ async def test_managed_worker_restart_reconciles_the_persisted_task(worker_gatew
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
from deerflow.config.app_config import get_app_config
from deerflow.runtime import ORPHAN_RECOVERY_STOP_REASON
from deerflow.runtime.runs.manager import STARTUP_ORPHAN_RECOVERY_ERROR
client, runs, state, entered, _ = worker_gateway
limit = get_app_config().max_recursion_limit
settings = {"recursion_limit": limit + 100, "thinking_enabled": False, "is_plan_mode": True}
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()
first = (await client.post("/api/coordination/tasks", json={"objective": "wait", "request_id": "restart", "run": settings})).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()
@ -1108,6 +1152,8 @@ async def test_managed_worker_restart_reconciles_the_persisted_task(worker_gatew
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 state.observed_worker_settings == [(limit, False, True)] * finished["execution"]["turn"]
assert finished["task"]["run_settings"] == settings
assert (finished["execution"]["run_id"] != run_id) is (previous_outcome == "shutdown")
if previous_outcome == "orphan-no-checkpoint":
assert finished["execution"]["status"] == "error"

View File

@ -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 = "0059_coordination_grants"
HEAD = "0060_coordination_run_settings"
COORDINATION_GRANTS_REVISION = "0059_coordination_grants"
BROWSER_OAUTH_REVISION = "0058_mcp_browser_oauth"
PREVIOUS = "0046_skill_mutations"
TABLE = "mcp_oauth_tokens"
@ -49,7 +50,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 == BROWSER_OAUTH_REVISION
assert script.get_revision(HEAD).down_revision == COORDINATION_GRANTS_REVISION
assert script.get_revision(COORDINATION_GRANTS_REVISION).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"