mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-09-14 16:08:41 +00:00
* feat(extensions): add gateway services and routers * feat(extensions): add standalone reference extension * fix(extensions): harden contributed gateway routes * docs(extensions): document gateway contribution points * feat(extensions): add operator CLI for packaged extension management Add `deerflow extensions install/list/enable/disable/remove` plus the root `make extension-*` wrappers, backed by an `ExtensionManager` that owns one transaction over backend/pyproject.toml, backend/uv.lock, the managed source snapshot, the uv environment, and the `plugins:` block in config.yaml. Install accepts a package requirement, a public HTTPS Git URL, or a local directory. Local directories are copied to backend/extensions/sources/ as deployable snapshots rather than editable installs, and the root .dockerignore re-includes that tree so snapshots reach the backend builder. Remote sources are HTTPS-only; SSH Git, file:// and local wheels are rejected because the stock Docker builder cannot reproduce them. Because environment configuration can still resolve a plain package name to a local wheel (a UV_FIND_LINKS wheelhouse, say), every uv add/remove is followed by an audit of the new lock: any local reference the stock image build cannot reproduce rolls back the whole transaction. A config carrying duplicate top-level `plugins:` keys is rejected outright rather than managed against one block while the Gateway reads another. Dependency synchronization now has one lock authority. The `extensions` dependency group joins [tool.uv].default-groups, every startup path syncs the same lock with --locked and launches with --no-sync, and the Docker images move to uv 0.11.1 for the --no-workspace boundary the manager needs. Loader gains `enabled`, `name` and `package` fields so a disabled extension is skipped before resolution and import. Co-authored-by: Codex <codex@openai.com> * fix(extensions): stop the managed plugins rewrite from destroying config Two data-safety defects in the managed `plugins:` block writer. The "next top-level key" boundary was a regex matching only `[A-Za-z_][A-Za-z0-9_-]*` or a quoted key. `AppConfig` is `extra="allow"`, so a config may legally carry any top-level key, and a key the pattern cannot recognize did not fail loudly — it read as "no next section", and the rewrite replaced that neighbour and its entire subtree with the managed block. `my.key`, `2fa`, `$schema`, `my key` and non-ASCII keys were all silently deleted by a plain `extension-enable`/`disable`. Both boundaries now come from the YAML parser's node marks, so key shape is irrelevant. The file-final branch never consulted the trailing-comment scan the has-next-key branch used, so any comment below the block was dropped. Since the manager appends `plugins:` at end of file, that is the steady-state shape for most installs: an operator note below the block was destroyed on the next toggle. Separately, every managed install wrote `required: true` while the loader defaults to false. That turned any later load failure — broken wheel, missing native library, deleted snapshot — into a Gateway startup abort recoverable only with shell access. New records are now written `required: false`, with an explicit `install --required` opt-in; adopting an existing hand-written record still preserves the operator's own choice. * fix(extensions): harden the manager transaction and correct its docs Follow-up hardening on the extension package manager. Security posture, which the docs already claimed: - Scrub `UV_PYTHON`, `UV_INSECURE_HOST`, `UV_CONSTRAINT` and `UV_NO_BUILD_ISOLATION` from the controlled uv environment. `UV_PYTHON` swaps the interpreter that the entry-point probe then imports and calls, and every later `uv run --no-sync` startup uses; `UV_INSECURE_HOST` removes the TLS validation the HTTPS-only source rule depends on. Neither is an index, proxy, cache or credential-provider setting, so neither was covered by the carve-out. - Recognize run-together and all-caps secret query parameters (`accesstoken`, `ACCESSTOKEN`, `key`, `pw`, `sas`, `code`). The camel-case splitter only fires on case transitions, so only the separated spellings were caught. Short generic words stay boundary-anchored, so `?keyword=` remains installable. - Validate the config before running any uv command. `uv add`/`uv sync` execute the package's build backend, so a config the manager could never write to must fail before that code runs rather than afterwards through rollback. Transaction integrity: - Run the second dependency-file restore from a `finally`. The recovery sync runs without `--locked` when the checkout had no lock, so uv writes one while resolving; if that sync then failed, the restore was skipped and the operator kept a lock file they never had. A failing recovery sync now also reports the original failure instead of replacing it. - Skip the recovery sync on cancellation. Answering Ctrl-C with a full dependency resolve invites a second interrupt that escapes the handler and strands the checkout mid-transaction; the declarations are already restored and the next locked startup sync reconciles the environment. - Retry a non-blocking lock on Windows instead of using `msvcrt.LK_LOCK`, which gives up after ~10s — far shorter than a real `uv add` plus `uv sync`, so contention surfaced as `Permission denied` rather than serializing. - Locate the entry-point probe's JSON payload instead of parsing stdout's first line, so a `sitecustomize`/`.pth` banner cannot roll back a good install. - Warn when the lock records a loopback source. `127.0.0.1` inside the image builder is a different machine, but unlike an environment-driven wheelhouse resolution this is a source the operator typed deliberately, so it is reported rather than rolled back. Private-network indexes are untouched: a builder on that network can reach them. Docs: the blanket claim that failed operations restore the config file was wrong — the conflict branches deliberately preserve a concurrent external edit and leave `remove` deactivated. Document that, the `required: false` default, the config preflight, the interrupt behaviour, and where the plugins-block boundaries come from. * test(gateway): pin the request-path projection agreement `get_request_route_path()` imports the private `starlette._utils.get_route_path` so the auth and CSRF predicates classify the exact string Starlette's router matches on. Its requirement is not "strip root_path correctly" but "return what the dispatcher is matching", so delegating to the router's own implementation keeps the two in lockstep by construction. Keep the private import rather than vendoring a copy: an import that disappears fails loudly at startup, while a stale copy diverges silently at a security boundary. Cover the property directly instead of the mechanism, so the tests survive a future reimplementation: - projection edge cases, including the segment-boundary guard that keeps root_path="/api" from slicing "/apifoo/models" into a string the router would never match - agreement with the router under nested mounts - the two bypasses these predicates exist to prevent: a protected route mounted under the "/health" public prefix must still 401, and a POST mounted under "/api/webhooks" must still require a CSRF token Both are verified to fail when the projection is reverted to `request.url.path` (9/13 red) and when a plausible vendored copy omits the boundary guard (the 2 boundary cases red). Declare starlette as a bounded direct dependency so a bump — which is security-relevant here — shows up in review rather than arriving silently through FastAPI. * ci: pin uv to the version production ships ExtensionManager is not a consumer of uv the build tool -- it is a program whose whole job is driving `uv` as a subprocess, depending on its CLI behavior (`--no-workspace`, `--no-sync`, what `uv add` writes into `[dependency-groups] extensions`) and on the `uv.lock` serialization format. uv is closer to a runtime dependency with a contract than to incidental tooling. backend/Dockerfile pins that binary to 0.11.1, but all eight astral-sh/setup-uv steps installed whatever was latest at run time, so CI exercised the manager against a uv that is not the uv production runs. The sharpest failure that allows: a newer uv bumps uv.lock's `revision`, CI stays green because the same uv reads back what it wrote, and the pinned uv in the production image cannot read the committed lock. `uv lock --check` is version-sensitive for the same reason -- it verifies the lock is what *this* uv would produce, and two versions can emit equivalent but non-identical output. Pin every step to 0.11.1 and lift the one lingering setup-uv@v3 to v7 so the steps share input and caching behavior. Pinning alone drifts apart again on the next bump, so add a constraint test in the style of test_compose_default_bind_host.py: the Dockerfile's UV_IMAGE tag is the single source of truth, and both compose defaults plus every setup-uv step must match it. Verified to fail when a pin drifts, when a step omits `version`, and -- the real scenario -- when the Dockerfile is bumped alone, which lights up the workflows and both compose files at once. * fix(gateway): state the extension route auth limit and abort a failed dev sync Two scoped review follow-ups. README: contributed routers cannot enter the host's reserved public prefixes, which makes every extension endpoint session-authenticated -- there is no way to expose an unauthenticated route. The rejection rule was documented but its consequence was not, so inbound provider webhooks and public status endpoints read as merely undocumented rather than out of scope for this release. docker/dev-entrypoint.sh: the self-heal retry reuses `--locked`, so it repairs a corrupt .venv but never a lock that disagrees with pyproject.toml. `set -e` already stopped the script there -- uvicorn was not being started against a stale environment -- but it exited on a bare uv exit code with no indication of what to do. Abort explicitly with the cause and the fix. Tests slice the sync block out of the real script and run it against a stub uv, so they exercise the shipped code rather than a copy of it (/app/backend only exists inside the container). They cover the success path, the retry that recovers, the abort, and the guidance. Verified against the pre-fix script: only the guidance case goes red, confirming the abort itself was already correct. * fix(extensions): point Git SSH shorthand at the HTTPS correction Git's SCP-like shorthand carries no URL scheme, so `git+git@host:org/repo.git` reached the scheme rules looking like a bare path and was rejected with "local path references are not deployable; pass a local directory so DeerFlow can snapshot it". The operator asked for a remote source, so that guidance points at the wrong fix. Detect the shorthand ahead of the scheme rules and report the public-HTTPS correction instead. The bare `git@host:org/repo.git` spelling took a different wrong turn: packaging parses it as a direct reference named `git`, leaving `host:org/repo.git`, whose `host` reads as a URL scheme and produced the generic HTTPS message. Both spellings now share one message, as does the PEP 508 named form. * docs: keep the root extension summary within its new budget #4799 split the depth out of the module guides and added a size gate; the root file's job is now orientation, and this branch had pushed it 192 bytes past the soft limit. The manager transaction, source rules, and lock discipline are already stated in full in the extensions guide, so the root keeps the one-line orientation and points there instead of restating them. --------- Co-authored-by: Codex <codex@openai.com>
438 lines
16 KiB
Python
438 lines
16 KiB
Python
"""Regression tests for graceful run-task drain on Gateway shutdown.
|
|
|
|
Guards bytedance/deer-flow issue #3373:
|
|
|
|
psycopg_pool.PoolClosed: the pool 'pool-1' is already closed
|
|
|
|
Root cause: chat runs are fire-and-forget background ``asyncio`` tasks
|
|
(``app/gateway/services.py`` -> ``asyncio.create_task(run_agent(...))``) owned
|
|
by nobody. On shutdown, ``langgraph_runtime``'s ``AsyncExitStack`` tore down the
|
|
checkpointer's postgres pool while those tasks were still mid-graph. langgraph's
|
|
``AsyncPregelLoop._checkpointer_put_after_previous`` then ran its
|
|
``finally: await checkpointer.aput(...)`` against the already-closed pool.
|
|
|
|
Fix: ``RunManager.shutdown()`` cancels and *bounded*-awaits every in-flight run,
|
|
and ``langgraph_runtime`` calls it BEFORE the ``AsyncExitStack`` closes the
|
|
checkpointer — so the final checkpoint write lands while the pool is still open.
|
|
The drain must stay bounded (a stuck run must not hang the worker, the
|
|
precondition for the signal-reentrancy deadlock guarded by
|
|
``app.gateway.app._SHUTDOWN_HOOK_TIMEOUT_SECONDS``).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import operator
|
|
from contextlib import asynccontextmanager, suppress
|
|
from types import SimpleNamespace
|
|
from typing import Annotated, TypedDict
|
|
|
|
import pytest
|
|
from langgraph.checkpoint.memory import InMemorySaver
|
|
|
|
from deerflow.runtime import RunManager, RunStatus
|
|
|
|
|
|
# Module-level so langgraph's get_type_hints (which resolves annotations against
|
|
# module globals under `from __future__ import annotations`) can see Annotated.
|
|
class _CountState(TypedDict):
|
|
count: Annotated[int, operator.add]
|
|
|
|
|
|
class _CloseableSaver(InMemorySaver):
|
|
"""InMemorySaver that fails writes once closed, like a closed pool."""
|
|
|
|
def __init__(self) -> None:
|
|
super().__init__()
|
|
self._closed = False
|
|
self.writes_after_close: list[str] = []
|
|
|
|
def close(self) -> None:
|
|
self._closed = True
|
|
|
|
async def aput(self, *args, **kwargs):
|
|
if self._closed:
|
|
self.writes_after_close.append("aput")
|
|
raise RuntimeError("checkpointer is closed")
|
|
return await super().aput(*args, **kwargs)
|
|
|
|
async def aput_writes(self, *args, **kwargs):
|
|
if self._closed:
|
|
self.writes_after_close.append("aput_writes")
|
|
raise RuntimeError("checkpointer is closed")
|
|
return await super().aput_writes(*args, **kwargs)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_shutdown_cancels_and_awaits_inflight_run():
|
|
"""shutdown() cancels the in-flight task, waits for it, marks it interrupted."""
|
|
rm = RunManager()
|
|
record = await rm.create("t-drain")
|
|
await rm.set_status(record.run_id, RunStatus.running)
|
|
|
|
started = asyncio.Event()
|
|
cancelled = asyncio.Event()
|
|
|
|
async def worker() -> None:
|
|
try:
|
|
started.set()
|
|
await asyncio.Event().wait()
|
|
except asyncio.CancelledError:
|
|
cancelled.set()
|
|
raise
|
|
|
|
record.task = asyncio.create_task(worker())
|
|
try:
|
|
await asyncio.wait_for(started.wait(), timeout=1.0)
|
|
|
|
await rm.shutdown(timeout=5.0)
|
|
|
|
assert record.task.done()
|
|
assert cancelled.is_set()
|
|
assert record.status == RunStatus.interrupted
|
|
finally:
|
|
if not record.task.done():
|
|
record.task.cancel()
|
|
with suppress(asyncio.CancelledError):
|
|
await record.task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_shutdown_is_bounded_when_run_ignores_cancellation():
|
|
"""A run that swallows cancellation must not make shutdown() hang."""
|
|
rm = RunManager()
|
|
record = await rm.create("t-stubborn")
|
|
await rm.set_status(record.run_id, RunStatus.running)
|
|
|
|
started = asyncio.Event()
|
|
stop = asyncio.Event()
|
|
|
|
async def stubborn() -> None:
|
|
started.set()
|
|
while not stop.is_set():
|
|
try:
|
|
await asyncio.sleep(3600)
|
|
except asyncio.CancelledError:
|
|
if stop.is_set():
|
|
raise
|
|
# else: swallow — simulates a run stuck in slow cleanup
|
|
|
|
record.task = asyncio.create_task(stubborn())
|
|
try:
|
|
await asyncio.wait_for(started.wait(), timeout=1.0)
|
|
|
|
loop = asyncio.get_running_loop()
|
|
t0 = loop.time()
|
|
await rm.shutdown(timeout=0.3)
|
|
elapsed = loop.time() - t0
|
|
|
|
assert elapsed < 2.0, f"shutdown took {elapsed:.2f}s; drain is not bounded"
|
|
finally:
|
|
# cleanup the deliberately-stubborn task
|
|
stop.set()
|
|
record.task.cancel()
|
|
with suppress(asyncio.CancelledError):
|
|
await record.task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_shutdown_is_noop_without_inflight_runs():
|
|
"""shutdown() on an idle manager completes cleanly and is idempotent."""
|
|
rm = RunManager()
|
|
await rm.shutdown(timeout=1.0)
|
|
# already-finished runs must not be re-cancelled or error out
|
|
record = await rm.create("t-done")
|
|
await rm.set_status(record.run_id, RunStatus.success)
|
|
await rm.shutdown(timeout=1.0)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_langgraph_runtime_drains_runs_before_closing_checkpointer(monkeypatch):
|
|
"""Drain runs before services, then close runtime resources in stack order.
|
|
|
|
Patches every ``langgraph_runtime`` collaborator down to trivial stand-ins so
|
|
only the bootstrap/teardown ordering runs. The checkpointer probe records when
|
|
its context manager exits (pool close); a ``RunManager.shutdown`` spy records
|
|
when the drain happens. The drain MUST come first.
|
|
"""
|
|
from fastapi import FastAPI
|
|
|
|
from app.gateway.deps import langgraph_runtime
|
|
from deerflow.extensions.registry import ExtensionRegistry
|
|
|
|
events: list[str] = []
|
|
|
|
@asynccontextmanager
|
|
async def probe_checkpointer(_config):
|
|
try:
|
|
yield object()
|
|
finally:
|
|
events.append("checkpointer_closed")
|
|
|
|
@asynccontextmanager
|
|
async def fake_stream_bridge(_config):
|
|
try:
|
|
yield object()
|
|
finally:
|
|
events.append("stream_bridge_closed")
|
|
|
|
@asynccontextmanager
|
|
async def fake_store(_config):
|
|
try:
|
|
yield object()
|
|
finally:
|
|
events.append("store_closed")
|
|
|
|
async def fake_init_engine(_db):
|
|
events.append("engine_initialized")
|
|
|
|
def fake_session_factory():
|
|
events.append("session_factory_resolved")
|
|
return None
|
|
|
|
async def fake_close_engine():
|
|
events.append("engine_closed")
|
|
|
|
async def spy_shutdown(self, *, timeout): # noqa: ANN001
|
|
events.append("runs_drained")
|
|
|
|
def spy_set_extension_notify_loop(loop): # noqa: ANN001
|
|
assert loop is asyncio.get_running_loop()
|
|
events.append("extension_loop_set")
|
|
|
|
def spy_reset_extension_notify_loop():
|
|
events.append("extension_loop_reset")
|
|
|
|
monkeypatch.setattr("deerflow.runtime.checkpointer.async_provider.make_checkpointer", probe_checkpointer)
|
|
monkeypatch.setattr("deerflow.runtime.make_stream_bridge", fake_stream_bridge)
|
|
monkeypatch.setattr("deerflow.runtime.make_store", fake_store)
|
|
monkeypatch.setattr("deerflow.persistence.engine.init_engine_from_config", fake_init_engine)
|
|
monkeypatch.setattr("deerflow.persistence.engine.close_engine", fake_close_engine)
|
|
monkeypatch.setattr("deerflow.persistence.engine.get_session_factory", fake_session_factory)
|
|
monkeypatch.setattr("deerflow.runtime.events.store.make_run_event_store", lambda _cfg: object())
|
|
monkeypatch.setattr("deerflow.persistence.thread_meta.make_thread_store", lambda _sf, _store: object())
|
|
monkeypatch.setattr(RunManager, "shutdown", spy_shutdown, raising=False)
|
|
monkeypatch.setattr("deerflow.extensions.notify.set_extension_notify_loop", spy_set_extension_notify_loop)
|
|
monkeypatch.setattr("deerflow.extensions.notify.reset_extension_notify_loop", spy_reset_extension_notify_loop)
|
|
|
|
app = FastAPI()
|
|
registry = ExtensionRegistry()
|
|
|
|
class _Service:
|
|
async def start(self, _deps):
|
|
events.append("service_started")
|
|
|
|
async def stop(self):
|
|
events.append("service_stopped")
|
|
|
|
with registry.attributed_to("service:install"):
|
|
registry.service(_Service())
|
|
app.state.extensions = registry.build()
|
|
startup_config = SimpleNamespace(database=SimpleNamespace(backend="memory", checkpoint_channel_mode="full", checkpoint_delta=SimpleNamespace(snapshot_frequency=10)), run_events=None)
|
|
|
|
async with langgraph_runtime(app, startup_config):
|
|
pass
|
|
|
|
assert "runs_drained" in events, "langgraph_runtime never drained in-flight runs on shutdown"
|
|
assert "service_started" in events
|
|
assert "service_stopped" in events
|
|
assert "checkpointer_closed" in events
|
|
assert events.index("engine_initialized") < events.index("session_factory_resolved")
|
|
assert events.index("session_factory_resolved") < events.index("service_started")
|
|
assert events.index("runs_drained") < events.index("service_stopped")
|
|
assert events.index("service_stopped") < events.index("store_closed")
|
|
assert events.index("store_closed") < events.index("checkpointer_closed")
|
|
assert events.index("checkpointer_closed") < events.index("engine_closed")
|
|
assert events.index("engine_closed") < events.index("stream_bridge_closed")
|
|
assert events[0] == "extension_loop_set"
|
|
assert events.index("stream_bridge_closed") < events.index("extension_loop_reset"), f"extension loop reset must be the final runtime teardown; got order {events}"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("startup_error", [RuntimeError("startup failed"), asyncio.CancelledError()])
|
|
async def test_langgraph_runtime_resets_extension_loop_when_startup_exits_early(monkeypatch, startup_error):
|
|
"""A partial startup must not leave a stale process-wide loop binding."""
|
|
from fastapi import FastAPI
|
|
|
|
from app.gateway.deps import langgraph_runtime
|
|
|
|
events: list[str] = []
|
|
|
|
@asynccontextmanager
|
|
async def failing_stream_bridge(_config):
|
|
raise startup_error
|
|
yield # pragma: no cover - makes this an async context manager
|
|
|
|
def spy_set_extension_notify_loop(loop): # noqa: ANN001
|
|
assert loop is asyncio.get_running_loop()
|
|
events.append("extension_loop_set")
|
|
|
|
def spy_reset_extension_notify_loop():
|
|
events.append("extension_loop_reset")
|
|
|
|
monkeypatch.setattr("deerflow.runtime.make_stream_bridge", failing_stream_bridge)
|
|
monkeypatch.setattr("deerflow.extensions.notify.set_extension_notify_loop", spy_set_extension_notify_loop)
|
|
monkeypatch.setattr("deerflow.extensions.notify.reset_extension_notify_loop", spy_reset_extension_notify_loop)
|
|
|
|
app = FastAPI()
|
|
startup_config = SimpleNamespace(
|
|
database=SimpleNamespace(
|
|
backend="memory",
|
|
checkpoint_channel_mode="full",
|
|
checkpoint_delta=SimpleNamespace(snapshot_frequency=10),
|
|
),
|
|
)
|
|
|
|
with pytest.raises(type(startup_error)):
|
|
async with langgraph_runtime(app, startup_config):
|
|
pass
|
|
|
|
assert events == ["extension_loop_set", "extension_loop_reset"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_drain_flushes_real_graph_checkpoint_before_close():
|
|
"""End-to-end #3373 guard with a REAL langgraph graph + checkpointer.
|
|
|
|
A real run is driven through ``graph.astream`` in a background task, then
|
|
``RunManager.shutdown()`` drains it. The checkpointer raises once closed
|
|
(mirroring ``psycopg_pool.PoolClosed``). Closing only happens AFTER the
|
|
drain — as the gateway's AsyncExitStack does. The drain must let langgraph
|
|
flush its final checkpoint while the checkpointer is still open, so no write
|
|
lands against a closed checkpointer.
|
|
|
|
Unlike the unit/spy tests above, this exercises the real langgraph
|
|
checkpoint-put machinery, so a future langgraph change that cancels (rather
|
|
than awaits) its checkpoint-put task on executor exit would fail this test
|
|
instead of silently regressing #3373.
|
|
"""
|
|
from langgraph.graph import END, START, StateGraph
|
|
|
|
async def slow(_state: _CountState) -> dict:
|
|
await asyncio.sleep(0.1)
|
|
return {"count": 1}
|
|
|
|
saver = _CloseableSaver()
|
|
builder = StateGraph(_CountState)
|
|
for name in ("a", "b", "c"):
|
|
builder.add_node(name, slow)
|
|
builder.add_edge(START, "a")
|
|
builder.add_edge("a", "b")
|
|
builder.add_edge("b", "c")
|
|
builder.add_edge("c", END)
|
|
graph = builder.compile(checkpointer=saver)
|
|
|
|
rm = RunManager()
|
|
record = await rm.create("t-e2e")
|
|
await rm.set_status(record.run_id, RunStatus.running)
|
|
thread_cfg = {"configurable": {"thread_id": "t-e2e"}}
|
|
|
|
started = asyncio.Event()
|
|
|
|
async def run() -> None:
|
|
started.set()
|
|
async for _ in graph.astream({"count": 0}, config=thread_cfg):
|
|
pass
|
|
|
|
record.task = asyncio.create_task(run())
|
|
try:
|
|
await asyncio.wait_for(started.wait(), timeout=1.0)
|
|
|
|
# Deterministically wait until the run is genuinely in-flight — poll for
|
|
# the first persisted checkpoint instead of a fixed sleep (avoids CI
|
|
# flakiness on slow runners / under event-loop contention).
|
|
async def _await_first_checkpoint() -> None:
|
|
while (await saver.aget_tuple(thread_cfg)) is None:
|
|
await asyncio.sleep(0.01)
|
|
|
|
await asyncio.wait_for(_await_first_checkpoint(), timeout=5.0)
|
|
|
|
# The fix: drain while the checkpointer is still open ...
|
|
await rm.shutdown(timeout=5.0)
|
|
# ... and only then close it (mirrors langgraph_runtime's ExitStack).
|
|
saver.close()
|
|
|
|
assert saver.writes_after_close == [], f"a checkpoint write raced a closed checkpointer: {saver.writes_after_close}"
|
|
# The final checkpoint landed before close.
|
|
snapshot = await saver.aget_tuple(thread_cfg)
|
|
assert snapshot is not None
|
|
finally:
|
|
if not record.task.done():
|
|
record.task.cancel()
|
|
with suppress(asyncio.CancelledError):
|
|
await record.task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_shutdown_preserves_status_of_run_completed_during_drain():
|
|
"""A run that finishes (e.g. success) during the drain window must keep its
|
|
real terminal status — shutdown must not blanket-overwrite it to
|
|
``interrupted`` in memory or in the store (Copilot review on PR #3381)."""
|
|
from deerflow.runtime.runs.store.memory import MemoryRunStore
|
|
|
|
store = MemoryRunStore()
|
|
rm = RunManager(store=store)
|
|
record = await rm.create("t-complete")
|
|
await rm.set_status(record.run_id, RunStatus.running)
|
|
|
|
async def worker() -> None:
|
|
try:
|
|
await asyncio.Event().wait()
|
|
except asyncio.CancelledError:
|
|
# The run had effectively finished; swallow the cancellation and
|
|
# record success, like a run that completed in the same tick the
|
|
# shutdown cancelled it.
|
|
pass
|
|
await rm.set_status(record.run_id, RunStatus.success)
|
|
|
|
record.task = asyncio.create_task(worker())
|
|
try:
|
|
await asyncio.sleep(0) # let the task reach its await point
|
|
|
|
await rm.shutdown(timeout=5.0)
|
|
|
|
assert record.status == RunStatus.success, f"shutdown overwrote in-memory status: {record.status}"
|
|
persisted = await store.get(record.run_id)
|
|
assert persisted is not None and persisted["status"] == "success", f"shutdown overwrote persisted status: {persisted}"
|
|
finally:
|
|
if not record.task.done():
|
|
record.task.cancel()
|
|
with suppress(asyncio.CancelledError):
|
|
await record.task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_shutdown_surfaces_failed_interrupted_persist(caplog):
|
|
"""A failed interrupted-status persist during the drain must be surfaced (with
|
|
the run_id), not silently swallowed by the gather (maintainer review on
|
|
PR #3381)."""
|
|
import logging
|
|
|
|
from deerflow.runtime.runs.store.memory import MemoryRunStore
|
|
|
|
class _FailingStore(MemoryRunStore):
|
|
async def update_status(self, *args, **kwargs):
|
|
raise RuntimeError("store unavailable")
|
|
|
|
rm = RunManager(store=_FailingStore())
|
|
record = await rm.create("t-failpersist")
|
|
record.status = RunStatus.running # set in memory; the failing store is exercised by the drain
|
|
|
|
started = asyncio.Event()
|
|
|
|
async def worker() -> None:
|
|
started.set()
|
|
await asyncio.Event().wait() # blocks until cancelled by the drain
|
|
|
|
record.task = asyncio.create_task(worker())
|
|
try:
|
|
await asyncio.wait_for(started.wait(), timeout=1.0)
|
|
with caplog.at_level(logging.WARNING, logger="deerflow.runtime.runs.manager"):
|
|
await rm.shutdown(timeout=5.0)
|
|
assert "Could not persist interrupted status for run" in caplog.text, caplog.text
|
|
finally:
|
|
if not record.task.done():
|
|
record.task.cancel()
|
|
with suppress(asyncio.CancelledError):
|
|
await record.task
|