From 096210709f6cad09d37c0a877c04580ea73da284 Mon Sep 17 00:00:00 2001 From: MasterZRC <163502670+MasterZRC@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:36:39 +0800 Subject: [PATCH] feat(agent-teams): add optional PostgreSQL persistence (#8325) * feat(agent-teams): add optional PostgreSQL persistence * fix(agent-teams): propagate shutdown waiter cancellation * fix(tui): skip periodic refresh during shutdown --- .github/workflows/bundled-extension-tests.yml | 37 +- README.md | 1 + .../agent_teams_gateway.py | 7 +- .../packages/harness/deerflow/tui/AGENTS.md | 2 + backend/packages/harness/deerflow/tui/app.py | 4 +- .../test_agent_teams_storage_offloop.py | 52 ++ .../tests/test_agent_teams_postgres_flow.py | 328 +++++++++++ .../tests/test_agent_teams_postgres_store.py | 281 ++++++++++ .../tests/test_agent_teams_storage_config.py | 66 +++ .../test_agent_teams_storage_lifecycle.py | 510 ++++++++++++++++++ backend/tests/test_tui_app.py | 34 ++ .../deerflow-extension-agent-teams/AGENTS.md | 17 +- .../deerflow-extension-agent-teams/README.md | 66 ++- .../__init__.py | 15 +- .../artifacts.py | 1 + .../postgres_store.py | 224 ++++++++ .../deerflow_extension_agent_teams/service.py | 103 +++- .../deerflow_extension_agent_teams/store.py | 17 + .../pyproject.toml | 3 + 19 files changed, 1735 insertions(+), 33 deletions(-) create mode 100644 backend/tests/blocking_io/test_agent_teams_storage_offloop.py create mode 100644 backend/tests/test_agent_teams_postgres_flow.py create mode 100644 backend/tests/test_agent_teams_postgres_store.py create mode 100644 backend/tests/test_agent_teams_storage_config.py create mode 100644 backend/tests/test_agent_teams_storage_lifecycle.py create mode 100644 examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/postgres_store.py diff --git a/.github/workflows/bundled-extension-tests.yml b/.github/workflows/bundled-extension-tests.yml index 75f3e5c7a3..1c4c52b817 100644 --- a/.github/workflows/bundled-extension-tests.yml +++ b/.github/workflows/bundled-extension-tests.yml @@ -20,8 +20,14 @@ on: - 'backend/packages/**' - 'backend/app/gateway/**' - 'backend/tests/conftest.py' + - 'backend/extension_test_fixtures/agent_teams_gateway.py' - 'backend/tests/support/**' - 'backend/tests/test_agent_teams_plugin.py' + - 'backend/tests/test_agent_teams_postgres_store.py' + - 'backend/tests/test_agent_teams_postgres_flow.py' + - 'backend/tests/test_agent_teams_storage_config.py' + - 'backend/tests/test_agent_teams_storage_lifecycle.py' + - 'backend/tests/blocking_io/test_agent_teams_storage_offloop.py' - 'backend/tests/test_bookmark_plugin.py' - 'backend/tests/test_bundled_extension_ci.py' - 'backend/tests/test_jev_classify_extension.py' @@ -49,8 +55,14 @@ on: - 'backend/packages/**' - 'backend/app/gateway/**' - 'backend/tests/conftest.py' + - 'backend/extension_test_fixtures/agent_teams_gateway.py' - 'backend/tests/support/**' - 'backend/tests/test_agent_teams_plugin.py' + - 'backend/tests/test_agent_teams_postgres_store.py' + - 'backend/tests/test_agent_teams_postgres_flow.py' + - 'backend/tests/test_agent_teams_storage_config.py' + - 'backend/tests/test_agent_teams_storage_lifecycle.py' + - 'backend/tests/blocking_io/test_agent_teams_storage_offloop.py' - 'backend/tests/test_bookmark_plugin.py' - 'backend/tests/test_bundled_extension_ci.py' - 'backend/tests/test_jev_classify_extension.py' @@ -84,6 +96,20 @@ jobs: if: github.event.pull_request.draft == false runs-on: ubuntu-latest timeout-minutes: 10 + services: + postgres: + image: postgres:16-alpine + env: + POSTGRES_USER: deerflow + POSTGRES_PASSWORD: test-only-password + POSTGRES_DB: deerflow_test + ports: + - '127.0.0.1:5432:5432' + options: >- + --health-cmd "pg_isready -U deerflow -d deerflow_test" + --health-interval 5s + --health-timeout 5s + --health-retries 10 steps: - uses: actions/checkout@v6 @@ -99,8 +125,17 @@ jobs: - name: Install backend dependencies working-directory: backend - run: uv sync --group dev + run: uv sync --group dev --extra postgres - name: Run bundled extension behavior tests working-directory: backend + env: + TEST_POSTGRES_URI: postgresql://deerflow:test-only-password@127.0.0.1:5432/deerflow_test + UV_NO_SYNC: '1' run: make test-bundled-extensions + + - name: Check team storage event-loop isolation + working-directory: backend + env: + UV_NO_SYNC: '1' + run: uv run pytest tests/blocking_io/test_agent_teams_storage_offloop.py -q diff --git a/README.md b/README.md index 742dcbdc8c..7b045c9232 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,7 @@ Each guide is the full reference for its topic. Open the one you need. | Skills, built-in tools, script workflows, Claude Code integration | [Skills & Tools](docs/guide/skills-and-tools.md) | | MCP servers | [MCP Server](docs/guide/mcp.md) | | Sub-agents, task delegation and optional SQLite checkpoint history | [Sub-Agents](docs/guide/subagents.md), [Tool restrictions](docs/guide/subagents.md#tool-restrictions) | +| Agent teams, SQLite/PostgreSQL persistence and shutdown behavior | [Agent teams extension](examples/deerflow-extension-agent-teams/README.md) | | Long-term memory | [Long-Term Memory](docs/guide/memory.md) | | Session goals, context compaction, task notes, evidence-based decisions | [Context, Goals and Agent Decisions](docs/guide/context.md) | | Private knowledge retrieval (RAGFlow) | [Private Knowledge Retrieval](docs/guide/knowledge-retrieval.md) | diff --git a/backend/extension_test_fixtures/agent_teams_gateway.py b/backend/extension_test_fixtures/agent_teams_gateway.py index 09575ed0cf..5ef733b213 100644 --- a/backend/extension_test_fixtures/agent_teams_gateway.py +++ b/backend/extension_test_fixtures/agent_teams_gateway.py @@ -1,4 +1,4 @@ -"""Loopback-only team UI preview: real plugin routes, SQLite and graph checkpoints. +"""Loopback-only team UI preview with real routes, storage and graph checkpoints. Identity and AgentRuns admission are synthetic. This is a browser fixture, not production authentication or a substitute for Gateway run-control tests. @@ -130,10 +130,11 @@ class PreviewRuns: return Bound() -def create_app(directory): +def create_app(directory, *, storage_url=None, storage_schema="agent_teams"): os.environ["DEER_FLOW_HOME"] = str(directory) sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "examples/deerflow-extension-agent-teams")) - extensions, diagnostics = load_extensions([ExtensionSpec(use="deerflow_extension_agent_teams:install", config={"enabled": True, "storage_path": str(Path(directory) / "teams.sqlite")}, required=True)]) + storage = {"storage_url": storage_url, "storage_schema": storage_schema} if storage_url else {"storage_path": str(Path(directory) / "teams.sqlite")} + extensions, diagnostics = load_extensions([ExtensionSpec(use="deerflow_extension_agent_teams:install", config={"enabled": True, **storage}, required=True)]) assert not diagnostics ((_, plugin),) = extensions.plugins service = plugin.backend[0].handler.__self__ diff --git a/backend/packages/harness/deerflow/tui/AGENTS.md b/backend/packages/harness/deerflow/tui/AGENTS.md index ebcb8babee..7a8757aaf4 100644 --- a/backend/packages/harness/deerflow/tui/AGENTS.md +++ b/backend/packages/harness/deerflow/tui/AGENTS.md @@ -27,6 +27,8 @@ plain pytest. The app is tested through Textual's pilot with a fake session. headless modes exit with status 1 on it. - **The command registry excludes the slash names that the agent runtime reserves**, in the picker and in the resolver. +- **Periodic spinner and transcript refreshes check `App.is_running`.** Textual + can remove their widgets before it stops the app's timers during shutdown. ## Runs and threads diff --git a/backend/packages/harness/deerflow/tui/app.py b/backend/packages/harness/deerflow/tui/app.py index d1289e644b..1b3f439a2d 100644 --- a/backend/packages/harness/deerflow/tui/app.py +++ b/backend/packages/harness/deerflow/tui/app.py @@ -799,7 +799,7 @@ class DeerFlowTUI(App): self._refresh_status() def _flush_transcript(self) -> None: - if self._transcript_dirty: + if self.is_running and self._transcript_dirty: self._transcript_dirty = False self._refresh_transcript() @@ -872,7 +872,7 @@ class DeerFlowTUI(App): self._refresh_status() def _tick_spinner(self) -> None: - if self._streaming: + if self.is_running and self._streaming: self._spinner_idx = (self._spinner_idx + 1) % len(SYMBOLS["spinner"]) self._refresh_status() diff --git a/backend/tests/blocking_io/test_agent_teams_storage_offloop.py b/backend/tests/blocking_io/test_agent_teams_storage_offloop.py new file mode 100644 index 0000000000..377bf78737 --- /dev/null +++ b/backend/tests/blocking_io/test_agent_teams_storage_offloop.py @@ -0,0 +1,52 @@ +"""Team store ownership and reads run outside the Gateway event loop.""" + +import asyncio +import threading +from pathlib import Path + +import pytest + + +@pytest.mark.asyncio +async def test_team_storage_lifecycle_and_queries_stay_offloop(monkeypatch, tmp_path): + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[3] / "examples/deerflow-extension-agent-teams")) + from deerflow_extension_agent_teams.service import Teams + from deerflow_extension_agent_teams.store import Store + + store = await asyncio.to_thread(Store, tmp_path / "teams.sqlite") + loop_thread = threading.get_ident() + threads = [] + acquire, check, snapshot = store.acquire_service_lock, store.check_service_lock, store.scheduling_snapshots + + class Lock: + def __init__(self, connection): + self.connection = connection + + def close(self): + threads.append(threading.get_ident()) + self.connection.close() + + def record_acquire(): + threads.append(threading.get_ident()) + return Lock(acquire()) + + def record_check(): + threads.append(threading.get_ident()) + return check() + + def record_snapshot(): + threads.append(threading.get_ident()) + return snapshot() + + monkeypatch.setattr(store, "acquire_service_lock", record_acquire) + monkeypatch.setattr(store, "check_service_lock", record_check) + monkeypatch.setattr(store, "scheduling_snapshots", record_snapshot) + service = Teams(store=store) + await service.start(None) + try: + await service.ensure_available() + assert await service.db("scheduling_snapshots") == {} + finally: + await service.stop() + assert len(threads) >= 5 + assert all(thread != loop_thread for thread in threads) diff --git a/backend/tests/test_agent_teams_postgres_flow.py b/backend/tests/test_agent_teams_postgres_flow.py new file mode 100644 index 0000000000..61c1bcac11 --- /dev/null +++ b/backend/tests/test_agent_teams_postgres_flow.py @@ -0,0 +1,328 @@ +"""PostgreSQL team flows through installed actions, real graphs and file handoffs.""" + +import asyncio +import base64 +import json +import os +import socket +import subprocess +import sys +import uuid +from contextlib import asynccontextmanager +from pathlib import Path + +import httpx +import pytest +from deerflow_extension_api import ExtensionPrincipal +from deerflow_extension_api.plugins import ActionContext, ToolContext + +from deerflow.config.paths import get_paths +from deerflow.extensions.loader import ExtensionSpec, load_extensions +from extension_test_fixtures.agent_teams_gateway import PreviewRuns + +pytestmark = pytest.mark.bundled_extension + + +@pytest.fixture +def postgres_config(tmp_path, monkeypatch): + uri = os.environ.get("TEST_POSTGRES_URI") + if not uri: + pytest.skip("requires TEST_POSTGRES_URI") + psycopg = pytest.importorskip("psycopg") + from psycopg import sql + + package = Path(__file__).resolve().parents[2] / "examples/deerflow-extension-agent-teams" + monkeypatch.syspath_prepend(str(package)) + monkeypatch.setenv("DEER_FLOW_HOME", str(tmp_path)) + schema = "teams_flow_" + uuid.uuid4().hex + yield {"enabled": True, "storage_url": uri, "storage_schema": schema} + with psycopg.connect(uri, autocommit=True) as db: + db.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema))) + + +def installed(config): + loaded, diagnostics = load_extensions([ExtensionSpec(use="deerflow_extension_agent_teams:install", config=config, required=True)]) + assert not diagnostics + ((_, declaration),) = loaded.plugins + actions = {action.name: action.handler for action in declaration.backend} + tools = {tool.name: tool.handler for tool in declaration.tools} + return actions, tools, actions["list"].__self__ + + +def action_context(host, owner="alice"): + return ActionContext(ExtensionPrincipal(owner), {"enabled": True}, agent_runs=host.bound(owner)) + + +async def create_team(actions, host): + return await actions["create"]( + {"request_id": "team", "name": "Release", "goal": "Review the release report", "members": [{"name": "Writer", "agent": "writer"}, {"name": "Reviewer", "agent": "reviewer"}]}, + action_context(host), + ) + + +async def finish_graphs(host): + await asyncio.gather(*host.tasks) + + +@asynccontextmanager +async def preview_process(config, home): + """Pass a bound loopback socket to the isolated fixture process.""" + script = """ +import os, sys +from contextlib import asynccontextmanager +import uvicorn +from extension_test_fixtures.agent_teams_gateway import create_app +app = create_app(sys.argv[1], storage_url=os.environ["TEST_POSTGRES_URI"], storage_schema=sys.argv[2]) +original = app.router.lifespan_context +@asynccontextmanager +async def lifespan(app): + async with original(app): + print("TEAM_PREVIEW_READY", flush=True) + yield +app.router.lifespan_context = lifespan +uvicorn.run(app, fd=int(sys.argv[3]), log_level="warning") +""" + backend = Path(__file__).resolve().parents[1] + log = home / "server.log" + isolated_config = home / "config.yaml" + isolated_config.write_text("models: []\nsandbox:\n use: deerflow.sandbox.local:LocalSandboxProvider\nauthorization:\n enabled: false\n", encoding="utf-8") + env = {**os.environ, "PYTHONPATH": str(backend), "DEER_FLOW_HOME": str(home), "DEER_FLOW_CONFIG_PATH": str(isolated_config)} + with socket.socket() as listener, log.open("ab") as output: + listener.bind(("127.0.0.1", 0)) + listener.listen() + address = f"http://127.0.0.1:{listener.getsockname()[1]}" + process = await asyncio.create_subprocess_exec( + sys.executable, + "-c", + script, + str(home), + config["storage_schema"], + str(listener.fileno()), + env=env, + cwd=home, + pass_fds=(listener.fileno(),), + stdout=asyncio.subprocess.PIPE, + stderr=output, + ) + try: + ready = await asyncio.wait_for(process.stdout.readline(), 30) + assert ready == b"TEAM_PREVIEW_READY\n", log.read_text(encoding="utf-8") + async with httpx.AsyncClient(base_url=address, headers={"x-test-user": "alice", "X-Deerflow-Plugin-Viewer": "alice"}, timeout=10) as client: + yield client + finally: + if process.returncode is None: + process.terminate() + try: + await asyncio.wait_for(process.wait(), 10) + except TimeoutError: + process.kill() + await asyncio.wait_for(process.wait(), 10) + + +async def http_action(client, name, payload): + response = await client.post(f"/api/plugins/community.agent-teams/actions/{name}", json=payload) + assert response.status_code == 200, response.text + return response.json() + + +@pytest.mark.skipif(os.name == "nt", reason="the subprocess fixture passes a POSIX listener file descriptor") +@pytest.mark.asyncio +async def test_postgres_http_actions_survive_a_server_process_restart(postgres_config, tmp_path): + content = b"%PDF-1.7\n\x00\xff process restart evidence" + async with preview_process(postgres_config, tmp_path) as client: + discovery = await client.get("/api/plugins") + assert discovery.status_code == 200 + assert discovery.json()[0]["viewer_id"] == "alice" + team = await http_action(client, "create", {"request_id": "http-team", "name": "Release", "goal": "Check release evidence", "members": [{"name": "Writer", "agent": "writer"}, {"name": "Review", "agent": "reviewer"}]}) + response = await client.post("/preview/artifact", json={"team_id": team["id"], "request_id": "report", "name": "Report", "content_base64": base64.b64encode(content).decode()}) + assert response.status_code == 200, response.text + entry = response.json()["artifact"] + reference = {"team_id": team["id"], "artifact_id": entry["artifact_id"], "version": entry["version"]} + # Read the real endpoint until the asynchronous graph and artifact + # capture publish their terminal result. The timeout only bounds hangs. + async with asyncio.timeout(30): + while True: + completed = await http_action(client, "get", {"team_id": team["id"], "details": True}) + if completed["jobs"][0]["status"] == "completed": + break + assert completed["artifacts"][0]["status"] == "ready" + downloaded = await http_action(client, "get_artifact", reference) + assert base64.b64decode(downloaded["content_base64"]) == content + + async with preview_process(postgres_config, tmp_path) as client: + reopened = await http_action(client, "get", {"team_id": team["id"], "details": True}) + assert not reopened["connected"] + assert reopened["jobs"] == completed["jobs"] + assert reopened["artifacts"] == completed["artifacts"] + downloaded = await http_action(client, "get_artifact", reference) + assert base64.b64decode(downloaded["content_base64"]) == content + denied = await client.post("/api/plugins/community.agent-teams/actions/get_artifact", json=reference, headers={"x-test-user": "bob", "X-Deerflow-Plugin-Viewer": "bob"}) + assert denied.status_code == 422 + assert base64.b64encode(content).decode() not in denied.text + assert await http_action(client, "connect", {"team_id": team["id"]}) == {"connected": True} + connected = await http_action(client, "get", {"team_id": team["id"], "details": True}) + assert connected["connected"] + assert connected["jobs"] == completed["jobs"] + + +@pytest.mark.asyncio +async def test_postgres_team_result_and_exact_file_survive_restart(postgres_config): + actions, tools, service = installed(postgres_config) + host = PreviewRuns() + replacement = None + await service.start(None) + try: + team = await create_team(actions, host) + writer, reviewer = team["members"] + job = await actions["send"]({"team_id": team["id"], "member_id": writer["id"], "text": "Artifact fixture: produce a report", "request_id": "produce"}, action_context(host)) + await service.tick() + content = b"%PDF-1.7\n\x00\xff immutable release evidence" + source = get_paths().sandbox_outputs_dir(writer["thread_id"], user_id="alice") / "report.bin" + source.parent.mkdir(parents=True, exist_ok=True) + source.write_bytes(content) + member_context = ToolContext(ExtensionPrincipal("alice"), {"enabled": True}, writer["thread_id"], agent_runs=host.bound("alice"), run_id=job["id"]) + registration = await tools["register_team_artifact"]({"team_id": team["id"], "request_id": "report", "name": "Report", "path": "/mnt/user-data/outputs/report.bin"}, member_context) + entry = registration["artifact"] + ref = {"artifact_id": entry["artifact_id"], "version": entry["version"]} + host.artifact_gate.set() + await finish_graphs(host) + await service.tick() + completed = await actions["get"]({"team_id": team["id"], "details": True}, action_context(host)) + assert completed["jobs"][0]["status"] == "completed" + assert "Release evidence verified" in completed["jobs"][0]["result"] + assert completed["artifacts"][0]["status"] == "ready" + await service.stop() + source.unlink() + + # A fresh interpreter reads the persisted result and bytes through the + # production store, independently of this process's extension objects. + script = """ +import base64, json, os +from deerflow_extension_agent_teams.postgres_store import PostgresStore +args = json.loads(os.environ["TEAM_FLOW_READ"]) +store = PostgresStore(os.environ["TEST_POSTGRES_URI"], args["schema"]) +try: + store.acquire_service_lock() + team = store.get("alice", args["team_id"]) + entry, content = store.artifact("alice", args["team_id"], args["artifact_id"], args["version"]) + print(json.dumps({"status": team["jobs"][0]["status"], "result": team["jobs"][0]["result"], "content": base64.b64encode(content).decode()})) +finally: + store.close() +""" + package = Path(__file__).resolve().parents[2] / "examples/deerflow-extension-agent-teams" + env = {**os.environ, "PYTHONPATH": str(package), "TEAM_FLOW_READ": json.dumps({"schema": postgres_config["storage_schema"], "team_id": team["id"], **ref})} + process = await asyncio.to_thread(subprocess.run, [sys.executable, "-c", script], env=env, text=True, capture_output=True, check=True, timeout=30) + persisted = json.loads(process.stdout) + assert persisted["status"] == "completed" + assert persisted["result"] == completed["jobs"][0]["result"] + assert base64.b64decode(persisted["content"]) == content + + actions, tools, replacement = installed(postgres_config) + await replacement.start(None) + reopened = await actions["get"]({"team_id": team["id"], "details": True}, action_context(host)) + assert not reopened["connected"] + assert reopened["jobs"] == completed["jobs"] + assert (await actions["list"]({}, action_context(host, "bob")))["teams"] == [] + with pytest.raises(ValueError): + await actions["get_artifact"]({"team_id": team["id"], **ref}, action_context(host, "bob")) + await actions["connect"]({"team_id": team["id"]}, action_context(host)) + downloaded = await actions["get_artifact"]({"team_id": team["id"], **ref}, action_context(host)) + assert base64.b64decode(downloaded["content_base64"]) == content + await actions["send"]({"team_id": team["id"], "member_id": reviewer["id"], "text": "Review the retained report", "request_id": "review", "artifacts": [ref]}, action_context(host)) + await replacement.tick() + await finish_graphs(host) + await replacement.tick() + uploads = get_paths().sandbox_uploads_dir(reviewer["thread_id"], user_id="alice") + assert [path.read_bytes() for path in uploads.iterdir() if path.is_file()] == [content] + final = await actions["get"]({"team_id": team["id"], "details": True}, action_context(host)) + assert [job["status"] for job in final["jobs"]] == ["completed", "completed"] + finally: + host.artifact_gate.set() + await service.stop() + if replacement is not None: + await replacement.stop() + await finish_graphs(host) + + +@pytest.mark.asyncio +async def test_postgres_lock_loss_drains_worker_and_reconciles_frozen_admission(postgres_config, monkeypatch): + import psycopg + from deerflow_extension_agent_teams.store import StoreUnavailable + + actions, _, service = installed(postgres_config) + host = PreviewRuns() + entered, drained, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + real_bound = host.bound + + def gated_bound(owner): + bound = real_bound(owner) + start = bound.start + + async def admit(**kwargs): + result = await start(**kwargs) + entered.set() + try: + await release.wait() + finally: + drained.set() + return result + + bound.start = admit + return bound + + monkeypatch.setattr(host, "bound", gated_bound) + replacement = None + await service.start(None) + try: + team = await create_team(actions, host) + member = team["members"][0] + job = await actions["send"]({"team_id": team["id"], "member_id": member["id"], "text": "Check release readiness", "request_id": "uncertain"}, action_context(host)) + await service.tick(wait=False) + await asyncio.wait_for(entered.wait(), 10) + frozen = (await service.db("get", "alice", team["id"]))["jobs"][0] + assert frozen["input"] is not None and frozen["run_id"] is None + assert set(host.runs) == {job["id"]} + actions2, _, replacement = installed(postgres_config) + with pytest.raises(StoreUnavailable): + await replacement.start(None) + assert not replacement.available + + pid = service.store._connection.info.backend_pid + + def terminate_owner(): + with psycopg.connect(postgres_config["storage_url"], autocommit=True) as db: + assert db.execute("SELECT pg_terminate_backend(%s)", (pid,)).fetchone()[0] + + await asyncio.to_thread(terminate_owner) + with pytest.raises(StoreUnavailable): + await service.ensure_available() + await asyncio.wait_for(drained.wait(), 10) + assert not service.available + with pytest.raises(StoreUnavailable): + await service.db("change", "alice", team["id"], lambda team: team.update(name="stale writer")) + with pytest.raises((StoreUnavailable, ValueError)): + await actions["send"]({"team_id": team["id"], "member_id": member["id"], "text": "Stale work", "request_id": "stale"}, action_context(host)) + release.set() + await service.stop() + + monkeypatch.setattr(host, "bound", real_bound) + await replacement.start(None) + saved = (await replacement.db("get", "alice", team["id"]))["jobs"][0] + assert saved["input"] == frozen["input"] + assert saved["status"] not in {"completed", "failed", "cancelled"} + assert not replacement.handles + await actions2["connect"]({"team_id": team["id"]}, action_context(host)) + await replacement.tick() + await finish_graphs(host) + await replacement.tick() + assert set(host.runs) == {job["id"]} + final = await actions2["get"]({"team_id": team["id"], "details": True}, action_context(host)) + assert final["jobs"][0]["id"] == job["id"] + assert final["jobs"][0]["status"] == "completed" + finally: + release.set() + host.artifact_gate.set() + await service.stop() + if replacement is not None: + await replacement.stop() + await finish_graphs(host) diff --git a/backend/tests/test_agent_teams_postgres_store.py b/backend/tests/test_agent_teams_postgres_store.py new file mode 100644 index 0000000000..5867fb2c95 --- /dev/null +++ b/backend/tests/test_agent_teams_postgres_store.py @@ -0,0 +1,281 @@ +"""Plugin-owned PostgreSQL storage and ownership lifecycle.""" + +import hashlib +import os +import uuid +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from threading import Barrier + +import pytest + +pytestmark = pytest.mark.bundled_extension + + +@pytest.fixture(autouse=True) +def extension_path(monkeypatch): + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2] / "examples/deerflow-extension-agent-teams")) + + +@pytest.mark.parametrize( + "url", + [None, "", "sqlite:///private", "host=private password=secret", "http://private"], +) +def test_postgres_store_rejects_invalid_urls_without_echoing_credentials(url): + from deerflow_extension_agent_teams.postgres_store import PostgresStore + + with pytest.raises(ValueError, match="storage_url") as error: + PostgresStore(url) + assert "private" not in str(error.value) + assert "secret" not in str(error.value) + + +@pytest.mark.parametrize( + "schema", + [ + None, + "", + "public", + "pg_catalog", + "information_schema", + "other.schema", + "a" * 64, + 'x"; DROP SCHEMA public; --', + ], +) +def test_postgres_store_rejects_invalid_schema(schema): + from deerflow_extension_agent_teams.postgres_store import PostgresStore + + with pytest.raises(ValueError, match="storage_schema"): + PostgresStore("postgresql://localhost/test", schema) + + +def test_postgres_constructor_is_lazy_and_closed_store_requires_acquisition(): + from deerflow_extension_agent_teams.postgres_store import PostgresStore + from deerflow_extension_agent_teams.store import StoreUnavailable + + store = PostgresStore("postgresql://localhost/test") + with pytest.raises(StoreUnavailable): + store.list("alice") + store.close() + + +@pytest.fixture +def postgres_store(): + url = os.environ.get("TEST_POSTGRES_URI") + if not url: + pytest.skip("requires TEST_POSTGRES_URI") + psycopg = pytest.importorskip("psycopg") + from deerflow_extension_agent_teams.postgres_store import PostgresStore + from psycopg import sql + + schema = "teams_test_" + uuid.uuid4().hex + store = PostgresStore(url, schema) + store.acquire_service_lock() + try: + yield store, url, schema + finally: + store.close() + with psycopg.connect(url, autocommit=True) as db: + db.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema))) + + +def team(team_id, *, pending=False): + return { + "id": team_id, + "jobs": [{"status": "queued"}] if pending else [], + "artifacts": [ + { + "id": "version", + "artifact_id": "report", + "version": 1, + "status": "pending", + "source": {}, + } + ], + } + + +def test_postgres_owner_scope_ordering_projection_and_rollback(postgres_store): + store, _, _ = postgres_store + store.create("alice", team("first")) + store.create("alice", team("second", pending=True)) + store.create("bob", team("private")) + assert [item["id"] for item in store.list("alice")] == ["second", "first"] + assert list(store.scheduling_snapshots()) == [("alice", "second")] + assert store.create("alice", team("first", pending=True))["jobs"] == [] + with pytest.raises(ValueError, match="unavailable"): + store.get("bob", "first") + store.delete("bob", "first") + assert store.get("alice", "first")["id"] == "first" + + def fail(current): + current["jobs"].append({"status": "queued"}) + raise ValueError("rollback") + + with pytest.raises(ValueError, match="rollback"): + store.change("alice", "first", fail) + assert not store.get("alice", "first")["jobs"] + store.change("alice", "second", lambda current: current["jobs"][0].update(status="completed")) + assert not store.scheduling_snapshots() + + +def test_postgres_concurrent_team_count_is_bounded(postgres_store): + store, _, _ = postgres_store + + barrier = Barrier(8) + + def create(index): + barrier.wait(timeout=10) + try: + store.create("alice", team(str(index))) + return True + except ValueError as error: + assert "Team limit" in str(error) + return False + + with ThreadPoolExecutor(max_workers=8) as executor: + assert sum(executor.map(create, range(24))) == 20 + assert len(store.list("alice")) == 20 + store.create("bob", team("other-owner")) + + +def test_postgres_artifact_quota_atomicity_restart_and_immutable_bytes(postgres_store, monkeypatch): + import deerflow_extension_agent_teams.artifacts as artifacts + import psycopg + from deerflow_extension_agent_teams.postgres_store import PostgresStore + from psycopg import sql + + store, url, schema = postgres_store + monkeypatch.setattr(artifacts, "OWNER_BYTES", 5) + for name in ("one", "two"): + store.create("alice", team(name)) + + barrier = Barrier(2) + + def capture(name): + barrier.wait(timeout=10) + try: + store.capture_artifact("alice", name, "version", b"\x00\xffab", "run") + return name + except ValueError as error: + assert "storage limit" in str(error) + return None + + with ThreadPoolExecutor(max_workers=2) as executor: + captured = [name for name in executor.map(capture, ("one", "two")) if name] + assert len(captured) == 1 + winner = captured[0] + loser = "two" if winner == "one" else "one" + assert store.get("alice", loser)["artifacts"][0]["status"] == "pending" + store.capture_artifact("alice", winner, "version", b"ignored", "other-run") + entry, content = store.artifact("alice", winner, "report", 1) + assert content == b"\x00\xffab" + assert entry["sha256"] == hashlib.sha256(content).hexdigest() + assert entry["source"]["run_id"] == "run" + with psycopg.connect(url, autocommit=True) as db: + with pytest.raises(psycopg.errors.RaiseException, match="cannot be overwritten"): + db.execute( + sql.SQL("UPDATE {}.team_artifact_versions SET content = %s").format(sql.Identifier(schema)), + (b"changed",), + ) + store.close() + replacement = PostgresStore(url, schema) + replacement.acquire_service_lock() + try: + assert replacement.artifact("alice", winner, "report", 1) == (entry, content) + replacement.delete("alice", winner) + replacement.capture_artifact("alice", loser, "version", content, "new-run") + finally: + replacement.close() + + +def test_postgres_lock_loss_blocks_old_store_and_allows_new_owner(postgres_store): + import psycopg + from deerflow_extension_agent_teams.postgres_store import PostgresStore + from deerflow_extension_agent_teams.store import StoreUnavailable + + store, url, schema = postgres_store + store.create("alice", team("retained")) + contender = PostgresStore(url, schema) + with pytest.raises(StoreUnavailable, match="active"): + contender.acquire_service_lock() + with psycopg.connect(url, autocommit=True) as db: + pid = db.execute( + "SELECT pid FROM pg_locks WHERE locktype='advisory' AND classid=%s AND objid=%s AND objsubid=1 AND granted", + (store.lock_key >> 32, store.lock_key & 0xFFFFFFFF), + ).fetchone()[0] + db.execute("SELECT pg_terminate_backend(%s)", (pid,)) + with pytest.raises(StoreUnavailable): + store.check_service_lock() + with pytest.raises(StoreUnavailable): + store.create("alice", team("stale-write")) + contender.acquire_service_lock() + try: + assert [item["id"] for item in contender.list("alice")] == ["retained"] + finally: + contender.close() + + +def test_postgres_missing_optional_dependency_has_an_actionable_error(monkeypatch): + import builtins + + from deerflow_extension_agent_teams.postgres_store import PostgresStore + from deerflow_extension_agent_teams.store import StoreUnavailable + + original_import = builtins.__import__ + + def import_without_psycopg(name, *args, **kwargs): + if name == "psycopg": + raise ImportError("optional dependency absent") + return original_import(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", import_without_psycopg) + store = PostgresStore("postgresql://private:secret@localhost/test") + with pytest.raises(StoreUnavailable, match=r"agent-teams\[postgres\]") as error: + store.acquire_service_lock() + assert "secret" not in str(error.value) + with pytest.raises(StoreUnavailable): + store.list("alice") + + +def test_postgres_explicit_unlock_fences_store_writes(postgres_store): + from deerflow_extension_agent_teams.store import StoreUnavailable + + store, _, _ = postgres_store + assert store._connection.execute("SELECT pg_advisory_unlock(%s)", (store.lock_key,)).fetchone() == (True,) + with pytest.raises(StoreUnavailable): + store.create("alice", team("after-unlock")) + assert store._connection is None + + +def test_postgres_sql_failure_redacts_values_and_closes_connection(postgres_store): + from deerflow_extension_agent_teams.store import StoreUnavailable + + store, _, _ = postgres_store + store.create("alice", team("private-team-name")) + with pytest.raises(StoreUnavailable) as error: + store.create("bob", team("private-team-name")) + assert "private-team-name" not in str(error.value) + assert error.value.__suppress_context__ + assert store._connection is None + + +def test_postgres_schemas_have_independent_service_ownership(postgres_store): + import psycopg + from deerflow_extension_agent_teams.postgres_store import PostgresStore + from psycopg import sql + + store, url, schema = postgres_store + other_schema = schema + "_other" + other = PostgresStore(url, other_schema) + try: + other.acquire_service_lock() + store.create("alice", team("private")) + assert not other.list("alice") + other.create("alice", team("separate")) + assert [item["id"] for item in store.list("alice")] == ["private"] + finally: + other.close() + with psycopg.connect(url, autocommit=True) as db: + db.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(other_schema))) diff --git a/backend/tests/test_agent_teams_storage_config.py b/backend/tests/test_agent_teams_storage_config.py new file mode 100644 index 0000000000..0361226811 --- /dev/null +++ b/backend/tests/test_agent_teams_storage_config.py @@ -0,0 +1,66 @@ +"""Select the plugin-owned storage backend through extension installation.""" + +from pathlib import Path + +import pytest + +from deerflow.extensions.loader import ExtensionSpec, load_extensions + +pytestmark = pytest.mark.bundled_extension + + +@pytest.fixture(autouse=True) +def extension_path(monkeypatch): + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2] / "examples/deerflow-extension-agent-teams")) + + +def install(config): + return load_extensions([ExtensionSpec(use="deerflow_extension_agent_teams:install", config={"enabled": True, **config})]) + + +def test_postgres_configuration_loads_without_opening_a_connection(): + loaded, diagnostics = install({"storage_url": "postgresql://unused:5432/teams", "storage_schema": "team_data"}) + assert not diagnostics + ((_, plugin),) = loaded.plugins + service = next(action.handler.__self__ for action in plugin.backend if action.name == "list") + assert type(service.store).__name__ == "PostgresStore" + assert service.process_lock is None + + +def test_sqlite_configuration_selects_the_existing_store(tmp_path): + path = tmp_path / "teams.sqlite" + loaded, diagnostics = install({"storage_path": str(path)}) + assert not diagnostics + ((_, plugin),) = loaded.plugins + service = next(action.handler.__self__ for action in plugin.backend if action.name == "list") + assert service.store.path == path + + +@pytest.mark.parametrize( + "config", + [ + {}, + {"storage_url": "postgresql://unused/teams", "storage_path": "/tmp/teams.sqlite"}, + {"storage_url": None}, + {"storage_url": ""}, + {"storage_path": "relative.sqlite"}, + {"storage_path": "/tmp/teams.sqlite", "storage_schema": "teams"}, + {"storage_url": "sqlite:///tmp/teams.sqlite"}, + {"storage_url": "postgresql://unused/teams", "storage_schema": "public; DROP SCHEMA public"}, + {"storage_url": "postgresql://unused/teams", "enabled": "yes"}, + ], +) +def test_invalid_storage_configuration_fails_during_install(config, tmp_path): + if config.get("storage_path") == "/tmp/teams.sqlite": + config = {**config, "storage_path": str(tmp_path / "teams.sqlite")} + loaded, diagnostics = install(config) + assert not loaded.plugins + assert len(diagnostics) == 1 + + +def test_configuration_errors_do_not_disclose_database_credentials(): + secret_url = "postgresql://operator:private-credential@unused/teams" + loaded, diagnostics = install({"storage_url": secret_url, "storage_schema": "invalid-schema"}) + assert not loaded.plugins + assert diagnostics + assert "private-credential" not in str(diagnostics) diff --git a/backend/tests/test_agent_teams_storage_lifecycle.py b/backend/tests/test_agent_teams_storage_lifecycle.py new file mode 100644 index 0000000000..2a1640296f --- /dev/null +++ b/backend/tests/test_agent_teams_storage_lifecycle.py @@ -0,0 +1,510 @@ +"""Team service ownership covers startup, admission and worker shutdown.""" + +import asyncio +import sqlite3 +import threading +from pathlib import Path +from types import SimpleNamespace + +import pytest + +pytestmark = pytest.mark.bundled_extension + + +@pytest.fixture +def team_modules(monkeypatch): + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2] / "examples/deerflow-extension-agent-teams")) + from deerflow_extension_agent_teams import service, store + + return service, store + + +@pytest.mark.asyncio +async def test_injected_store_lifecycle_runs_offloop_and_drains_before_close(team_modules): + service_module, _ = team_modules + events = [] + threads = [] + loop_thread = threading.get_ident() + entered = asyncio.Event() + + class Store: + def acquire_service_lock(self): + threads.append(threading.get_ident()) + events.append("acquire") + return self + + def check_service_lock(self): + threads.append(threading.get_ident()) + + def scheduling_snapshots(self): + threads.append(threading.get_ident()) + return {} + + def close(self): + threads.append(threading.get_ident()) + events.append("close") + + service = service_module.Teams(store=Store()) + + async def worker(): + entered.set() + try: + await asyncio.Future() + finally: + events.append("worker drained") + + await service.start(None) + service.workers["worker"] = asyncio.create_task(worker()) + try: + await entered.wait() + finally: + await service.stop() + assert events == ["acquire", "worker drained", "close"] + assert threads and all(thread != loop_thread for thread in threads) + assert not service.available and service.process_lock is None + + +@pytest.mark.asyncio +async def test_cancelled_start_closes_a_lock_acquired_after_cancellation(team_modules): + service_module, _ = team_modules + entered = asyncio.Event() + release = threading.Event() + closed = threading.Event() + loop = asyncio.get_running_loop() + + class Store: + def acquire_service_lock(self): + loop.call_soon_threadsafe(entered.set) + assert release.wait(5) + return SimpleNamespace(close=closed.set) + + service = service_module.Teams(store=Store()) + task = asyncio.create_task(service.start(None)) + try: + await asyncio.wait_for(entered.wait(), 3) + task.cancel() + await asyncio.sleep(0) + finally: + release.set() + with pytest.raises(asyncio.CancelledError): + await task + assert closed.is_set() + assert service.process_lock is None and service.task is None and not service.available + + +@pytest.mark.asyncio +async def test_failed_second_start_preserves_the_active_service_lock(team_modules, tmp_path): + service_module, _ = team_modules + service = service_module.Teams(tmp_path / "teams.sqlite") + await service.start(None) + original_lock = service.process_lock + try: + with pytest.raises(sqlite3.OperationalError): + await service.start(None) + assert service.process_lock is original_lock and service.available + finally: + await service.stop() + await asyncio.to_thread(original_lock.close) + replacement = service_module.Teams(tmp_path / "teams.sqlite") + await replacement.start(None) + await replacement.stop() + + +@pytest.mark.asyncio +async def test_idle_service_detects_ownership_loss_and_drains_workers(team_modules): + service_module, store_module = team_modules + events = [] + entered = asyncio.Event() + + class Store: + def acquire_service_lock(self): + return self + + def scheduling_snapshots(self): + return {} + + def check_service_lock(self): + events.append("ownership lost") + raise store_module.StoreUnavailable("lost") + + def close(self): + events.append("close") + + service = service_module.Teams(store=Store()) + + async def worker(): + entered.set() + try: + await asyncio.Future() + finally: + events.append("worker drained") + + service.workers["worker"] = asyncio.create_task(worker()) + await entered.wait() + await service.start(None) + try: + await asyncio.wait_for(service.task, 3) + assert not service.available and not service.handles and not service.workers + assert events == ["ownership lost", "worker drained"] + finally: + await service.stop() + assert events[-1] == "close" + + +@pytest.mark.asyncio +async def test_storage_failure_in_worker_stops_other_workers_without_deadlock(team_modules): + service_module, store_module = team_modules + entered, release, drained = (asyncio.Event() for _ in range(3)) + failed = [] + + class Store: + def acquire_service_lock(self): + return self + + def check_service_lock(self): + pass + + def scheduling_snapshots(self): + return {} + + def get(self): + failed.append(True) + raise store_module.StoreUnavailable("lost") + + def close(self): + pass + + service = service_module.Teams(store=Store()) + await service.start(None) + + async def failing_worker(): + await release.wait() + with pytest.raises(store_module.StoreUnavailable): + await service.db("get") + + async def other_worker(): + entered.set() + try: + await asyncio.Future() + finally: + drained.set() + + service.workers["failing"] = asyncio.create_task(failing_worker()) + service.workers["other"] = asyncio.create_task(other_worker()) + service.handles["team"] = object() + try: + await entered.wait() + release.set() + await asyncio.wait_for(drained.wait(), 3) + assert failed and not service.available and not service.handles + finally: + await service.stop() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("resume", [False, True]) +async def test_lost_ownership_prevents_run_admission_with_frozen_input(team_modules, resume): + service_module, store_module = team_modules + checks, starts = [], [] + + class Store: + def check_service_lock(self): + checks.append(True) + raise store_module.StoreUnavailable("lost") + + def change(self, *_): + pass + + class Runs: + async def start(self, **kwargs): + starts.append(kwargs) + + async def resume(self, **kwargs): + starts.append(kwargs) + + service = service_module.Teams(store=Store()) + service.available = True + job = {"id": "job", "thread_id": "thread", "status": "resuming" if resume else "queued", "input": {"messages": []}, "run_id": "run" if resume else None, "resume": {"response": "answer", "key": "answer-key"}} + with pytest.raises(store_module.StoreUnavailable): + await service.advance("owner", {"id": "team"}, job, Runs()) + assert checks and not starts and not service.available + + +@pytest.mark.asyncio +async def test_reconnect_checks_service_ownership_before_creating_threads(team_modules): + service_module, store_module = team_modules + checks, creations = [], [] + + class Store: + def get(self, *_): + return {"id": "team", "members": [{"agent": "agent", "thread_id": "thread"}]} + + def check_service_lock(self): + checks.append(True) + raise store_module.StoreUnavailable("lost") + + class Runs: + async def create_thread(self, **kwargs): + creations.append(kwargs) + + service = service_module.Teams(store=Store()) + service.available = True + context = SimpleNamespace(principal=SimpleNamespace(user_id="owner"), agent_runs=Runs()) + with pytest.raises(store_module.StoreUnavailable): + await service.connect({"team_id": "team"}, context) + assert checks and not creations and not service.available + + +@pytest.mark.asyncio +async def test_shutdown_waits_for_in_progress_storage_work_before_unlocking(team_modules): + service_module, _ = team_modules + loop = asyncio.get_running_loop() + entered, cancelled = asyncio.Event(), asyncio.Event() + release = threading.Event() + events = [] + + class Store: + def acquire_service_lock(self): + return self + + def check_service_lock(self): + pass + + def scheduling_snapshots(self): + return {} + + def change(self): + loop.call_soon_threadsafe(entered.set) + assert release.wait(5) + events.append("committed") + + def close(self): + events.append("unlocked") + + service = service_module.Teams(store=Store()) + await service.start(None) + + async def worker(): + try: + await service.db("change") + finally: + cancelled.set() + + worker_task = asyncio.create_task(worker()) + service.workers["worker"] = worker_task + await entered.wait() + stopping = asyncio.create_task(service.stop()) + try: + # Once stop has requested worker cancellation, the synchronous call + # must still hold up worker draining and release of the service lock. + while not worker_task.cancelling(): + await asyncio.sleep(0) + await asyncio.sleep(0) + assert not cancelled.is_set() and not events + finally: + release.set() + await asyncio.wait_for(stopping, 3) + assert events == ["committed", "unlocked"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("loop_already_stopping", [False, True]) +async def test_cancelled_stop_waiters_leave_one_worker_drain_and_lock_release(team_modules, loop_already_stopping): + service_module, _ = team_modules + loop = asyncio.get_running_loop() + entered, draining, release_worker, closing = (asyncio.Event() for _ in range(4)) + release_close = threading.Event() + events = [] + + class Store: + def acquire_service_lock(self): + return self + + def check_service_lock(self): + pass + + def scheduling_snapshots(self): + return {} + + def close(self): + loop.call_soon_threadsafe(closing.set) + assert release_close.wait(5) + events.append("closed") + + service = service_module.Teams(store=Store()) + await service.start(None) + + async def worker(): + entered.set() + try: + await asyncio.Future() + finally: + draining.set() + await release_worker.wait() + events.append("drained") + + service.workers["worker"] = asyncio.create_task(worker()) + await entered.wait() + if loop_already_stopping: + service.task.cancel() + await asyncio.wait_for(draining.wait(), 3) + first_stop = asyncio.create_task(service.stop()) + second_stop = None + try: + await asyncio.wait_for(draining.wait(), 3) + while service.shutdown_task is None: + await asyncio.sleep(0) + first_stop.cancel() + second_stop = asyncio.create_task(service.stop()) + shutdown = service.shutdown_task + done, _ = await asyncio.wait([first_stop], timeout=3) + assert first_stop in done and first_stop.cancelled() + assert not second_stop.done() and not shutdown.done() + assert not events + release_worker.set() + await asyncio.wait_for(closing.wait(), 3) + second_stop.cancel() + done, _ = await asyncio.wait([second_stop], timeout=3) + assert second_stop in done and second_stop.cancelled() + assert service.shutdown_task is shutdown and not shutdown.done() + assert service.process_lock is not None + assert events == ["drained"] + finally: + release_worker.set() + release_close.set() + results = await asyncio.wait_for(asyncio.gather(first_stop, *([second_stop] if second_stop else []), return_exceptions=True), 3) + await asyncio.wait_for(service.stop(), 3) + assert all(isinstance(result, asyncio.CancelledError) for result in results) + assert events == ["drained", "closed"] + assert service.process_lock is None and not service.workers and not service.available + + +@pytest.mark.asyncio +@pytest.mark.parametrize("stall_at", ["database", "worker", "close"]) +async def test_gateway_stop_timeout_continues_while_team_cleanup_keeps_ownership(team_modules, stall_at): + from deerflow.extensions.gateway import stop_services + from deerflow.extensions.registry import ExtensionRegistry + + service_module, _ = team_modules + loop = asyncio.get_running_loop() + entered, draining, closing = (asyncio.Event() for _ in range(3)) + release_worker = asyncio.Event() + release_storage = threading.Event() + events = [] + + class Store: + def acquire_service_lock(self): + return self + + def check_service_lock(self): + pass + + def scheduling_snapshots(self): + return {} + + def change(self): + loop.call_soon_threadsafe(entered.set) + assert release_storage.wait(10) + events.append("committed") + + def close(self): + loop.call_soon_threadsafe(closing.set) + if stall_at == "close": + assert release_storage.wait(10) + events.append("closed") + + class OtherService: + async def start(self, deps): + pass + + async def stop(self): + events.append("other stopped") + + service = service_module.Teams(store=Store()) + await service.start(None) + + async def worker(): + try: + if stall_at == "database": + await service.db("change") + else: + entered.set() + await asyncio.Future() + finally: + draining.set() + if stall_at == "worker": + await release_worker.wait() + events.append("drained") + + service.workers["worker"] = asyncio.create_task(worker()) + registry = ExtensionRegistry() + with registry.attributed_to("other:install"): + registry.service(OtherService()) + with registry.attributed_to("teams:install"): + registry.service(service) + stopping = None + try: + await asyncio.wait_for(entered.wait(), 3) + # Use the real host timeout path with a short budget, while an explicit + # barrier keeps cleanup stalled until all timeout assertions finish. + stopping = asyncio.create_task(stop_services(registry.build(), timeout_seconds=0.01)) + if stall_at == "worker": + await asyncio.wait_for(draining.wait(), 3) + elif stall_at == "close": + await asyncio.wait_for(closing.wait(), 3) + done, _ = await asyncio.wait([stopping], timeout=3) + assert stopping in done, "Team cleanup swallowed the Gateway stop timeout" + diagnostics = stopping.result() + assert len(diagnostics) == 1 + assert diagnostics[0].source == "teams:install" + assert "timed out" in diagnostics[0].message + assert "other stopped" in events and "closed" not in events + assert not service.available and service.process_lock is not None + assert not service.shutdown_task.done() and not service.shutdown_task.cancelling() + finally: + release_worker.set() + release_storage.set() + if stopping is not None: + await asyncio.wait_for(stopping, 3) + await asyncio.wait_for(service.stop(), 3) + assert events[-1] == "closed" and events.count("closed") == 1 + assert events.index("drained") < events.index("closed") + if stall_at == "database": + assert events.index("committed") < events.index("drained") + assert service.process_lock is None and not service.workers + + +@pytest.mark.asyncio +async def test_detached_shutdown_failure_is_reported_without_storage_details(team_modules, caplog): + service_module, _ = team_modules + loop = asyncio.get_running_loop() + closing = asyncio.Event() + release = threading.Event() + + class Store: + def close(self): + loop.call_soon_threadsafe(closing.set) + assert release.wait(10) + raise RuntimeError("private storage connection details") + + service = service_module.Teams(store=Store()) + service.process_lock = service.store + stopping = asyncio.create_task(service.stop()) + try: + await asyncio.wait_for(closing.wait(), 3) + stopping.cancel() + done, _ = await asyncio.wait([stopping], timeout=3) + assert stopping in done and stopping.cancelled() + shutdown_done = asyncio.Event() + service.shutdown_task.add_done_callback(lambda _: shutdown_done.set()) + release.set() + await asyncio.wait_for(shutdown_done.wait(), 3) + assert "Agent teams shutdown failed" in caplog.text + assert "private storage connection details" not in caplog.text + # Reporting detached failures must not consume the error for a later + # stop caller or replace the shared shutdown with a second attempt. + with pytest.raises(RuntimeError, match="private storage connection details"): + await service.stop() + finally: + release.set() + await asyncio.gather(stopping, service.shutdown_task, return_exceptions=True) diff --git a/backend/tests/test_tui_app.py b/backend/tests/test_tui_app.py index e86e4ed2c2..ec4fbae4c7 100644 --- a/backend/tests/test_tui_app.py +++ b/backend/tests/test_tui_app.py @@ -11,6 +11,7 @@ import time import pytest from textual import events from textual.containers import VerticalScroll +from textual.css.query import NoMatches from deerflow.client import StreamEvent from deerflow.tui.app import DeerFlowTUI @@ -84,6 +85,39 @@ async def test_app_runs_a_turn_and_renders_streamed_assistant(): assert app.state.usage == {"total_tokens": 3} +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("callback_name", "pending_flag", "widget"), + [ + pytest.param("_tick_spinner", "_streaming", "#status", id="spinner"), + pytest.param("_flush_transcript", "_transcript_dirty", "#scroll", id="transcript"), + ], +) +async def test_periodic_refresh_skips_shutdown(monkeypatch, callback_name, pending_flag, widget): + app = DeerFlowTUI(_FakeSession(), LaunchPlan(mode="tui")) + original_close_all = app._close_all + errors: list[str] = [] + + async def close_all_with_late_tick(): + # Force the callback after its widget is gone, while the app's message + # pump is still open. Let Textual finish teardown even on regression. + await app.query_one(widget).remove() + setattr(app, pending_flag, True) + try: + getattr(app, callback_name)() + except NoMatches as exc: + errors.append(str(exc)) + finally: + setattr(app, pending_flag, False) + await original_close_all() + + monkeypatch.setattr(app, "_close_all", close_all_with_late_tick) + async with app.run_test(): + assert app.is_running + + assert not errors, errors + + @pytest.mark.asyncio @pytest.mark.parametrize("prefix", ["", "/tdd\n", "/tdd\t"]) async def test_multiline_paste_reaches_agent_without_dropping_lines(prefix): diff --git a/examples/deerflow-extension-agent-teams/AGENTS.md b/examples/deerflow-extension-agent-teams/AGENTS.md index 202e57959e..0e818934e8 100644 --- a/examples/deerflow-extension-agent-teams/AGENTS.md +++ b/examples/deerflow-extension-agent-teams/AGENTS.md @@ -46,7 +46,7 @@ authentication and stays on loopback; it is never a deployed Gateway. - **A terminal run alone is not success**, and an interruption is never approved automatically. After a restart, only an authenticated action or a native mention rebinds a job. -- **A terminal result and its follow-up receipt commit in one SQLite +- **A terminal result and its follow-up receipt commit in one storage transaction**, and so do team data and the pending-jobs projection. - **Hold the scheduling lock for bookkeeping only**, never across a host call. Execution and control mutations take the team-scoped lock. @@ -70,3 +70,18 @@ authentication and stays on loopback; it is never a deployed Gateway. - **A file transfer pauses the worker deadline.** Restore the remaining budget afterwards, and drain cancellation before you release a host reservation or a sandbox lease. + +## PostgreSQL ownership + +Use a dedicated plugin schema and one service-lock session for all storage +operations. Serialize each complete transaction on that connection so owner-wide +team and artifact quotas are atomic across teams. Connection loss invalidates +the store and stops service admission. Restart and authenticated Reconnect +recover retained work. Drain offloaded database operations and team workers +before releasing ownership. Keep connection URLs out of diagnostics. +Stop callers share one shielded shutdown task, but cancellation of a caller must +propagate immediately so the Gateway can enforce its per-service stop budget. +The background task retains ownership until draining completes; observe and +report failures without exposing storage exception details. Test blocked +database work, worker cleanup and connection close through the host stop path. +Run PostgreSQL regressions with `TEST_POSTGRES_URI` against a disposable database. diff --git a/examples/deerflow-extension-agent-teams/README.md b/examples/deerflow-extension-agent-teams/README.md index 914b4074f9..8d38df8475 100644 --- a/examples/deerflow-extension-agent-teams/README.md +++ b/examples/deerflow-extension-agent-teams/README.md @@ -35,6 +35,56 @@ the path require a Gateway restart. This SQLite example supports **one Gateway process per database**. A second service instance refuses to start against the same database; it cannot dispatch through its actions or middleware. +### PostgreSQL storage + +For PostgreSQL, configure `storage_url` and an optional `storage_schema` (default +`agent_teams`). Choose exactly one of `storage_path` and `storage_url`. + +```yaml +plugins: + - use: deerflow_extension_agent_teams:install + enabled: true + config: + enabled: true + storage_url: $AGENT_TEAMS_DATABASE_URL + storage_schema: agent_teams +``` + +Set `AGENT_TEAMS_DATABASE_URL` to a PostgreSQL connection URL in the Gateway +environment. The database role needs permission to create and own the configured +schema, tables, indexes and trigger function. Choose a dedicated schema, using +1โ€“63 ASCII letters, digits or underscores, starting with a letter or underscore. +The plugin stores team state and immutable file bytes in that schema. + +The PostgreSQL driver is provided by the backend's `postgres` extra. For a host +using SQLite with this plugin on PostgreSQL, install the driver into the managed +extension dependency group from `backend/` before restarting Gateway. + +```sh +uv add --group extensions 'psycopg[binary]>=3.3.3,<4' +``` + +Independent package installations can select the plugin's `postgres` extra. +Use a direct PostgreSQL connection or a session-pooling endpoint. The service +holds a session advisory lock for one active Gateway per database/schema and +serializes storage transactions on that same connection. This also makes owner +team-count and file-byte quota checks atomic across concurrent team requests. +Connections request five-second connect, SQL statement and lock timeouts. + +If storage ownership or connectivity is lost, the service becomes unavailable, +drains its workers and requires a Gateway restart. After restoring connectivity, +restart Gateway and use **Manage โ†’ Reconnect** to reconcile retained jobs through +their persisted input and idempotency keys. An already admitted host run can +finish while the team service is disconnected, so its result is reconciled on +Reconnect. A second service can acquire ownership once PostgreSQL releases the +previous session's lock. + +Include the plugin schema in database backups and restores. When the host and +plugin share a database, one database snapshot covers both sets of records. +Host runs and team state still commit in separate transactions, and Reconnect +handles their intermediate states. SQLite and PostgreSQL each hold an independent +team dataset. + ## Use 1. Create at least two Custom Agents in **Agents**. Members can delegate work to @@ -276,8 +326,12 @@ own teams. Sharing a host conversation does **not** share its team's private dat within the same team remain serialized, with a ten-second budget for ordinary job advancement. Each artifact import or capture pauses that budget and has its own 25-minute maximum for the bounded remote snapshot protocol (up to - 43 chunks with 30-second command timeouts). Shutdown cancels and drains all workers before releasing the - database service lock. + 43 chunks with 30-second command timeouts). Shutdown cancels and drains all + workers before releasing the database service lock. If the Gateway's + 30-second service stop budget expires, it continues stopping other services. + Team cleanup continues in the background while the process remains alive, + retaining ownership until database work and workers drain. This budget does + not forcibly terminate a blocked synchronous database call. - Each conversation is serialized, including result receipts targeting a source shared across teams. The first unfinished job retains the conversation until it finishes or is cancelled. A busy host conversation stays queued without @@ -341,6 +395,14 @@ uv run ruff check ../examples/deerflow-extension-agent-teams uv run ruff format --check ../examples/deerflow-extension-agent-teams ``` +PostgreSQL regressions use isolated schemas in an explicitly supplied disposable +database. The role must be able to terminate its own backend sessions for the +ownership-loss tests. Run from `backend/` with `TEST_POSTGRES_URI` set. + +```sh +uv run --extra postgres pytest tests/test_agent_teams_postgres_store.py tests/test_agent_teams_postgres_flow.py tests/test_agent_teams_storage_config.py tests/test_agent_teams_storage_lifecycle.py -q +``` + The tests load the real extension and exercise owner isolation, directed requests, real ToolNode dispatch, mention middleware in the Lead middleware pipeline, host-compatible mention labels at the UTF-16 boundary with stable routing IDs, diff --git a/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/__init__.py b/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/__init__.py index 5d4828520c..279c126a8d 100644 --- a/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/__init__.py +++ b/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/__init__.py @@ -42,9 +42,18 @@ class Contributor: @extension(api="0.2.11", name="agent-teams") def install(registry, config): enabled = config.get("enabled", False) - if type(enabled) is not bool or not isinstance(config.get("storage_path"), str): - raise ValueError("Configure boolean enabled and absolute storage_path") - teams = Teams(config["storage_path"]) + if type(enabled) is not bool: + raise ValueError("Configure boolean enabled") + if ("storage_path" in config) == ("storage_url" in config): + raise ValueError("Configure exactly one of storage_path or storage_url") + if "storage_url" in config: + from .postgres_store import PostgresStore + + teams = Teams(store=PostgresStore(config["storage_url"], config.get("storage_schema", "agent_teams"))) + else: + if not isinstance(config["storage_path"], str) or "storage_schema" in config: + raise ValueError("Configure an absolute storage_path; storage_schema requires storage_url") + teams = Teams(config["storage_path"]) send_schema = { "type": "object", "properties": {key: {"type": "string", "maxLength": limit} for key, limit in (("team_id", 64), ("member_id", 64), ("text", 4000), ("request_id", 128))}, diff --git a/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/artifacts.py b/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/artifacts.py index 3480854e3f..d1111cda04 100644 --- a/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/artifacts.py +++ b/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/artifacts.py @@ -207,6 +207,7 @@ class Artifacts: imports = [] for ref in job.get("artifacts", []): entry, content = await self.db("artifact", owner, team["id"], ref["artifact_id"], ref["version"]) + await self.ensure_available() result = await transfer(runs.import_artifact, thread_id=job["thread_id"], filename=job["id"][:12] + "-" + entry["filename"], content=content) if result.get("sha256") != hashlib.sha256(content).hexdigest() or result.get("size") != len(content) or not result.get("path", "").startswith("/mnt/user-data/uploads/"): raise ValueError("Host did not confirm the imported artifact") diff --git a/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/postgres_store.py b/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/postgres_store.py new file mode 100644 index 0000000000..de360c7ebb --- /dev/null +++ b/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/postgres_store.py @@ -0,0 +1,224 @@ +"""Plugin-owned PostgreSQL storage bound to its single service owner session.""" + +import hashlib +import json +import re +from contextlib import contextmanager +from threading import RLock +from urllib.parse import urlsplit + +from .store import StoreUnavailable, has_pending_jobs + + +class PostgresStore: + def __init__(self, url, schema="agent_teams"): + try: + valid_url = isinstance(url, str) and urlsplit(url).scheme in { + "postgresql", + "postgres", + } + except ValueError: + valid_url = False + if not valid_url: + raise ValueError("storage_url must be a PostgreSQL connection URL") + if not isinstance(schema, str) or not re.fullmatch(r"[a-zA-Z_][a-zA-Z_0-9]{0,62}", schema) or schema.lower() in {"public", "information_schema"} or schema.lower().startswith("pg_"): + raise ValueError("storage_schema must name a dedicated PostgreSQL schema (1โ€“63 identifier characters)") + self._url = url + self.schema = schema + # PostgreSQL advisory keys are database-local. Mask the sign bit so the + # same positive bigint can also be inspected through pg_locks. + self.lock_key = int.from_bytes( + hashlib.sha256(("deerflow.agent-teams.service\0" + schema).encode()).digest()[:8], + "big", + ) & ((1 << 63) - 1) + self._mutex = RLock() + self._connection = None + + def acquire_service_lock(self): + try: + import psycopg + from psycopg import sql + except ImportError: + raise StoreUnavailable("Install deerflow-extension-agent-teams[postgres] to use PostgreSQL storage") from None + with self._mutex: + if self._connection is not None: + raise StoreUnavailable("This team store already has an active service") + db = None + try: + db = psycopg.connect( + self._url, + autocommit=True, + connect_timeout=5, + keepalives=1, + keepalives_idle=5, + keepalives_interval=1, + keepalives_count=3, + ) + db.execute("SET statement_timeout = '5s'") + db.execute("SET lock_timeout = '5s'") + if not db.execute("SELECT pg_try_advisory_lock(%s)", (self.lock_key,)).fetchone()[0]: + raise StoreUnavailable("Another team service is active for this PostgreSQL store") + with db.transaction(): + db.execute(sql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(sql.Identifier(self.schema))) + db.execute(sql.SQL("SET search_path TO {}, pg_catalog").format(sql.Identifier(self.schema))) + db.execute("CREATE TABLE IF NOT EXISTS teams (id TEXT PRIMARY KEY, owner TEXT NOT NULL, data TEXT NOT NULL, has_pending_jobs INTEGER NOT NULL DEFAULT 0, position BIGINT GENERATED ALWAYS AS IDENTITY)") + db.execute("CREATE INDEX IF NOT EXISTS teams_pending_jobs ON teams(has_pending_jobs) WHERE has_pending_jobs=1") + db.execute("CREATE TABLE IF NOT EXISTS team_artifact_versions (owner TEXT NOT NULL, team_id TEXT NOT NULL, version_id TEXT NOT NULL, content BYTEA NOT NULL, PRIMARY KEY(team_id, version_id))") + db.execute("CREATE INDEX IF NOT EXISTS team_artifact_owner ON team_artifact_versions(owner)") + db.execute("CREATE OR REPLACE FUNCTION reject_artifact_update() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Artifact snapshots cannot be overwritten'; END $$") + db.execute("DROP TRIGGER IF EXISTS team_artifacts_immutable ON team_artifact_versions") + db.execute("CREATE TRIGGER team_artifacts_immutable BEFORE UPDATE ON team_artifact_versions FOR EACH ROW EXECUTE FUNCTION reject_artifact_update()") + self._connection = db + except BaseException as error: + if db is not None: + db.close() + if isinstance(error, psycopg.Error): + raise StoreUnavailable("PostgreSQL team store startup failed; check connectivity and schema permissions") from None + raise + return self + + def close(self): + with self._mutex: + if self._connection is not None: + self._connection.close() + self._connection = None + + @contextmanager + def _transaction(self): + # Every operation uses the ownership connection. Serializing complete + # transactions also keeps owner-wide count/byte checks atomic across teams. + with self._mutex: + db = self._connection + if db is None or db.closed: + raise StoreUnavailable("PostgreSQL team store unavailable; restart the Gateway") + import psycopg + + try: + with db.transaction(): + owned = db.execute( + "SELECT EXISTS (SELECT 1 FROM pg_locks WHERE locktype='advisory' AND pid=pg_backend_pid() AND classid=%s AND objid=%s AND objsubid=1 AND granted)", + (self.lock_key >> 32, self.lock_key & 0xFFFFFFFF), + ).fetchone()[0] + if not owned: + raise StoreUnavailable("PostgreSQL team store ownership lost; restart the Gateway") + yield db + except (psycopg.Error, StoreUnavailable): + self.close() + raise StoreUnavailable("PostgreSQL team store unavailable; restart the Gateway") from None + + def check_service_lock(self): + with self._transaction(): + pass + + def scheduling_snapshots(self): + with self._transaction() as db: + return {(owner, team_id): json.loads(data) for owner, team_id, data in db.execute("SELECT owner, id, data FROM teams WHERE has_pending_jobs=1 ORDER BY position")} + + def list(self, owner): + with self._transaction() as db: + return [ + json.loads(row[0]) + for row in db.execute( + "SELECT data FROM teams WHERE owner=%s ORDER BY position DESC", + (owner,), + ) + ] + + def get(self, owner, team_id): + with self._transaction() as db: + row = db.execute("SELECT data FROM teams WHERE owner=%s AND id=%s", (owner, team_id)).fetchone() + if row is None: + raise ValueError("Team unavailable") + return json.loads(row[0]) + + def create(self, owner, team): + with self._transaction() as db: + row = db.execute("SELECT data FROM teams WHERE owner=%s AND id=%s", (owner, team["id"])).fetchone() + if row: + return json.loads(row[0]) + if db.execute("SELECT count(*) FROM teams WHERE owner=%s", (owner,)).fetchone()[0] >= 20: + raise ValueError("Team limit reached (20)") + db.execute( + "INSERT INTO teams (id, owner, data, has_pending_jobs) VALUES (%s,%s,%s,%s)", + (team["id"], owner, json.dumps(team), has_pending_jobs(team)), + ) + return team + + def change(self, owner, team_id, update): + with self._transaction() as db: + row = db.execute( + "SELECT data FROM teams WHERE owner=%s AND id=%s FOR UPDATE", + (owner, team_id), + ).fetchone() + if row is None: + raise ValueError("Team unavailable") + team = json.loads(row[0]) + result = update(team) + db.execute( + "UPDATE teams SET data=%s, has_pending_jobs=%s WHERE owner=%s AND id=%s", + (json.dumps(team), has_pending_jobs(team), owner, team_id), + ) + return result + + def delete(self, owner, team_id): + with self._transaction() as db: + db.execute( + "DELETE FROM team_artifact_versions WHERE owner=%s AND team_id=%s", + (owner, team_id), + ) + db.execute("DELETE FROM teams WHERE owner=%s AND id=%s", (owner, team_id)) + + def capture_artifact(self, owner, team_id, version_id, content, run_id): + from .artifacts import MAX_BYTES, OWNER_BYTES + + if not isinstance(content, bytes) or len(content) > MAX_BYTES: + raise ValueError("Artifact must contain at most 2 MiB") + with self._transaction() as db: + row = db.execute( + "SELECT data FROM teams WHERE owner=%s AND id=%s FOR UPDATE", + (owner, team_id), + ).fetchone() + if row is None: + raise ValueError("Team unavailable") + team = json.loads(row[0]) + entry = next(entry for entry in team["artifacts"] if entry["id"] == version_id) + if entry["status"] != "pending": + return + retained = db.execute( + "SELECT coalesce(sum(octet_length(content)),0) FROM team_artifact_versions WHERE owner=%s", + (owner,), + ).fetchone()[0] + if retained + len(content) > OWNER_BYTES: + raise ValueError("Owner artifact storage limit reached (64 MiB)") + db.execute( + "INSERT INTO team_artifact_versions VALUES (%s,%s,%s,%s)", + (owner, team_id, version_id, content), + ) + entry.update( + status="ready", + sha256=hashlib.sha256(content).hexdigest(), + size=len(content), + ) + entry["source"]["run_id"] = run_id + db.execute( + "UPDATE teams SET data=%s WHERE owner=%s AND id=%s", + (json.dumps(team), owner, team_id), + ) + + def artifact(self, owner, team_id, artifact_id, version): + from .artifacts import lookup + + with self._transaction() as db: + row = db.execute("SELECT data FROM teams WHERE owner=%s AND id=%s", (owner, team_id)).fetchone() + if row is None: + raise ValueError("Team unavailable") + entry = lookup(json.loads(row[0]), {"artifact_id": artifact_id, "version": version}) + if entry["status"] != "ready": + raise ValueError("Artifact version is not ready") + row = db.execute( + "SELECT content FROM team_artifact_versions WHERE owner=%s AND team_id=%s AND version_id=%s", + (owner, team_id, entry["id"]), + ).fetchone() + if row is None or hashlib.sha256(row[0]).hexdigest() != entry["sha256"]: + raise ValueError("Artifact snapshot unavailable") + return entry, row[0] diff --git a/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/service.py b/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/service.py index d52b795e45..fd4b64aae0 100644 --- a/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/service.py +++ b/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/service.py @@ -3,7 +3,7 @@ import asyncio import hashlib import json -import sqlite3 +import logging import uuid from collections import deque from collections.abc import Mapping @@ -16,10 +16,26 @@ from deerflow_extension_api.agent_runs import AGENT_RUNS_CONTEXT_KEY from . import artifacts, history, shared_state from .artifacts import Artifacts -from .store import TERMINAL, Store +from .store import TERMINAL, Store, StoreUnavailable NAMESPACE = "community.agent-teams" LIMIT = 100 +logger = logging.getLogger(__name__) + + +def report_shutdown_failure(task): + if not task.cancelled() and task.exception() is not None: + # Stop waiters may have timed out already. Observe the failure without + # logging exception details that could contain connection credentials. + logger.error("Agent teams shutdown failed; storage ownership may not have been released") + + +async def drain_task(task): + """Finish pending work even if shutdown repeatedly cancels its waiter.""" + while not task.done(): + with suppress(asyncio.CancelledError, Exception): + await asyncio.shield(task) + return task.result() def text(payload, key, limit=4000): @@ -79,8 +95,8 @@ def pending_clarification(messages): class Teams(Artifacts): - def __init__(self, path): - self.store = Store(path) + def __init__(self, path=None, *, store=None): + self.store = store if store is not None else Store(path) self.handles = {} self.locks = WeakValueDictionary() self.scheduling_lock = asyncio.Lock() @@ -88,36 +104,71 @@ class Teams(Artifacts): self.in_flight = set() self.owner_rotation = deque() self.task = None + self.shutdown_task = None self.process_lock = None self.available = False async def db(self, method, *args): - return await asyncio.to_thread(getattr(self.store, method), *args) + operation = asyncio.create_task(asyncio.to_thread(getattr(self.store, method), *args)) + try: + return await asyncio.shield(operation) + except asyncio.CancelledError: + # A worker retains its team lock until the synchronous transaction + # finishes. Shutdown must drain it before releasing store ownership. + with suppress(Exception): + await drain_task(operation) + raise + except StoreUnavailable: + self.available = False + self.handles.clear() + # The loop owns worker draining. A failing worker must not wait for + # a shutdown operation that is itself waiting for that worker. + if self.task and self.task is not asyncio.current_task(): + self.task.cancel() + raise + + async def ensure_available(self): + if not self.available: + raise StoreUnavailable("Team service unavailable; restart Gateway and reconnect") + await self.db("check_service_lock") + if not self.available: + raise StoreUnavailable("Team service unavailable; restart Gateway and reconnect") async def start(self, deps): - # One service per database. A separate SQLite connection holds a process - # lock for the service lifetime, released by the OS after a crash. - def acquire(): - db = sqlite3.connect(str(self.store.path) + ".service-lock", timeout=0, check_same_thread=False) - try: - db.execute("BEGIN EXCLUSIVE") - except BaseException: - db.close() - raise - return db - - self.process_lock = await asyncio.to_thread(acquire) + acquisition = asyncio.create_task(asyncio.to_thread(self.store.acquire_service_lock)) try: + self.process_lock = await asyncio.shield(acquisition) await self.db("scheduling_snapshots") except BaseException: - await asyncio.to_thread(self.process_lock.close) - self.process_lock = None + # Cancelling to_thread cannot stop lock acquisition. Wait for its + # result and release it, including when shutdown cancels us again. + async def cleanup(): + lock = await acquisition + try: + await asyncio.to_thread(lock.close) + finally: + if self.process_lock is lock: + self.process_lock = None + + cleanup_task = asyncio.create_task(cleanup()) + with suppress(Exception): + await drain_task(cleanup_task) raise self.available = True + self.shutdown_task = None self.task = asyncio.create_task(self.loop()) async def stop(self): self.available = False + if self.shutdown_task is None: + self.shutdown_task = asyncio.create_task(self.shutdown()) + self.shutdown_task.add_done_callback(report_shutdown_failure) + # All callers share one drain, but a cancelled waiter must return so + # the Gateway's shutdown timeout can advance to the next service. + # Shield keeps worker draining and lock release owned by this task. + await asyncio.shield(self.shutdown_task) + + async def shutdown(self): if self.task: self.task.cancel() with suppress(asyncio.CancelledError, Exception): @@ -131,11 +182,14 @@ class Teams(Artifacts): async def loop(self): try: while True: + await self.ensure_available() await self.tick(wait=False) await asyncio.sleep(1) + except StoreUnavailable: + pass # Ownership loss is terminal for this service instance. finally: self.available = False - await self.cancel_workers() + await drain_task(asyncio.create_task(self.cancel_workers())) self.handles.clear() def team_lock(self, owner, team_id): @@ -180,6 +234,7 @@ class Teams(Artifacts): self.handles.pop((owner, team_id), None) raise for member in team["members"]: + await self.ensure_available() await context.agent_runs.create_thread(assistant_id=member["agent"], thread_id=member["thread_id"], metadata={"title": f"{team['name']} ยท {member['name']}"}) await self.db("change", owner, team_id, lambda t: t.update(ready=True)) return await self.get({"team_id": team_id}, context) @@ -247,6 +302,7 @@ class Teams(Artifacts): if context.agent_runs is None: raise ValueError("Agent control unavailable") for member in team["members"]: + await self.ensure_available() await context.agent_runs.create_thread(assistant_id=member["agent"], thread_id=member["thread_id"], metadata={}) self.bind(context, team["id"]) await self.db("change", context.principal.user_id, team["id"], lambda t: t.update(ready=True)) @@ -365,6 +421,7 @@ class Teams(Artifacts): # Structured references and labels are untrusted. The host capability # must authorize BOTH conversations before the plugin uses the owner. await runs.get_state(thread_id=source) + await self.ensure_available() await runs.create_thread(assistant_id=member["agent"], thread_id=member["thread_id"], metadata={}) content = text({"text": message.content}, "text") self.handles[(owner, team_id)] = runs @@ -457,7 +514,7 @@ class Teams(Artifacts): return job["input"] is not None async def plan(self, attempted, eligible): - # Only SQLite snapshots and slot bookkeeping live under this lock. + # Only storage snapshots and slot bookkeeping live under this lock. # Host calls run in independent workers, serialized by team. async with self.scheduling_lock: teams = await self.db("scheduling_snapshots") @@ -616,6 +673,7 @@ class Teams(Artifacts): return options = {"artifact_imports": job["artifact_imports"]} if job.get("artifact_imports") else {} try: + await self.ensure_available() run = await runs.start(thread_id=thread, input=job["input"], idempotency_key=job["id"], **options) except AgentRunError as exc: if exc.status_code != 422 or not options: @@ -643,15 +701,18 @@ class Teams(Artifacts): if not admitted and (not pending or pending["request_id"] != job["clarification"]["request_id"] or state.get("next") or state.get("interrupts")): await self.finish(owner, team, job, "failed", "Conversation advanced before the clarification response; inspect it before continuing") return + await self.ensure_available() run = await runs.start(thread_id=thread, input=continuation, idempotency_key=job["resume"]["key"]) job.update(result_message_id=message_id, result_run_id=run.run_id) else: + await self.ensure_available() run = await runs.resume(thread_id=thread, resume=job["resume"]["response"], idempotency_key=job["resume"]["key"]) job.update(run_id=run.run_id, execution_key=job["resume"]["key"], status="cancelling" if job["status"] == "cancelling" else "running", resume=None, clarification=None) await self.save_job(owner, team["id"], job) run = await runs.get(thread_id=thread, run_id=job["run_id"]) if job["status"] == "cancelling": if run.status in ("pending", "running"): + await self.ensure_available() await runs.cancel(thread_id=thread, run_id=job["run_id"]) else: await self.finish(owner, team, job, "cancelled", "Request cancelled; checkpoint retained") diff --git a/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/store.py b/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/store.py index 760a2acebe..3a5957d0ed 100644 --- a/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/store.py +++ b/examples/deerflow-extension-agent-teams/deerflow_extension_agent_teams/store.py @@ -13,6 +13,10 @@ def has_pending_jobs(team): return int(any(job["status"] not in TERMINAL for job in team["jobs"])) +class StoreUnavailable(RuntimeError): + """The store has lost its service ownership or cannot be reached.""" + + class Store: def __init__(self, path): self.path = Path(path) @@ -36,6 +40,19 @@ class Store: def connection(self): return sqlite3.connect(self.path, timeout=5) + def acquire_service_lock(self): + db = sqlite3.connect(str(self.path) + ".service-lock", timeout=0, check_same_thread=False) + try: + db.execute("BEGIN EXCLUSIVE") + except BaseException: + db.close() + raise + return db + + def check_service_lock(self): + # The SQLite lock is held on a local connection until service shutdown. + pass + def scheduling_snapshots(self): # Service-only, indexed projection. Completed history is never decoded; # all unfinished work is retained, regardless of capability availability. diff --git a/examples/deerflow-extension-agent-teams/pyproject.toml b/examples/deerflow-extension-agent-teams/pyproject.toml index 175e6b4e94..ac36365fa6 100644 --- a/examples/deerflow-extension-agent-teams/pyproject.toml +++ b/examples/deerflow-extension-agent-teams/pyproject.toml @@ -6,6 +6,9 @@ requires-python = ">=3.12" license = "MIT" dependencies = ["deerflow-extension-api>=0.2.11,<0.3", "langchain>=1.2,<2"] +[project.optional-dependencies] +postgres = ["psycopg[binary]>=3.3.3,<4"] + [project.entry-points."deerflow.extensions"] agent-teams = "deerflow_extension_agent_teams:install"