~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(deploy): allow time for Compose shutdown cleanup (#6918)
LearningCircuit9163fbe9b4eb
diff --git a/.github/workflows/compose-integration-test.yml b/.github/workflows/compose-integration-test.ymlindex 34a2cca1b7..e90ac4dd31 100644--- a/.github/workflows/compose-integration-test.yml+++ b/.github/workflows/compose-integration-test.yml@@ -21,8 +21,8 @@ name: Compose Integration Test## Tests the bundled docker-compose.yml without service overrides, including# authenticated persistence across stop/restart. The restart probe's stop-# honours the service's stop_grace_period; only while the bundled file-# declares none (Docker's 10s default, #6918) does it pass an explicit+# honours the service's stop_grace_period, which the bundled file sets to+# 60s (#6918); only if that is removed does it pass an explicit# --timeout 60 and emit a warning (see that step). Model pulling remains# separate from startup: the opt-in `run-model-probe` input pulls a small model# and checks real inference. It defaults to false and release.yml's@@ -206,14 +206,15 @@ jobs:docker compose exec -T local-deep-research /install/.venv/bin/python /tmp/compose_ollama.py- name: Verify authenticated persistence across Compose restart- # The stop must exercise the grace period users actually get. When the- # bundled compose declares stop_grace_period, a plain `compose stop`- # applies it. While it declares none, users get Docker's 10s default,- # which equals uvicorn's own drain budget and can SIGKILL the lifespan- # cleanup (#6918; pinned by the strict-xfail- # test_stop_grace_period_covers_the_shutdown_budget). This probe then- # passes --timeout 60 so it checks that shutdown completes at all, and- # says loudly that it is not testing the shipped grace.+ # The stop must exercise the grace period users actually get. The+ # bundled compose declares stop_grace_period: 60s (#6918), so a plain+ # `compose stop` applies it. Were that removed, users would get+ # Docker's 10s default, which equals uvicorn's own drain budget and+ # can SIGKILL the lifespan cleanup;+ # test_stop_grace_period_covers_the_shutdown_budget fails in that+ # case. This probe would then pass --timeout 60 so it checks that+ # shutdown completes at all, and say loudly that it is not testing+ # the shipped grace.## Fail closed: `shell: bash` makes GitHub run this with# `bash --noprofile --norc -eo pipefail` instead of the defaultdiff --git a/changelog.d/+compose-shutdown-grace.bugfix.md b/changelog.d/+compose-shutdown-grace.bugfix.mdnew file mode 100644index 0000000000..ae29ffa655--- /dev/null+++ b/changelog.d/+compose-shutdown-grace.bugfix.md@@ -0,0 +1 @@+Allow 60 seconds for shutdown in the standard and generated Docker Compose stacks, so request draining leaves time for scheduler, queue, log and database cleanup.diff --git a/cookiecutter-docker/{{cookiecutter.config_name}}/docker-compose.{{cookiecutter.config_name}}.yml b/cookiecutter-docker/{{cookiecutter.config_name}}/docker-compose.{{cookiecutter.config_name}}.ymlindex 600faac119..967ffd7751 100644--- a/cookiecutter-docker/{{cookiecutter.config_name}}/docker-compose.{{cookiecutter.config_name}}.yml+++ b/cookiecutter-docker/{{cookiecutter.config_name}}/docker-compose.{{cookiecutter.config_name}}.yml@@ -1,5 +1,7 @@services:local-deep-research:+ # Allow request draining, then scheduler, queue, log and database cleanup.+ stop_grace_period: 60s{%- if cookiecutter.build %}build:context: .diff --git a/docker-compose.yml b/docker-compose.ymlindex dd28949fcf..b2dbfaf138 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -19,6 +19,8 @@services:local-deep-research:image: localdeepresearch/local-deep-research:latest+ # Allow request draining, then scheduler, queue, log and database cleanup.+ stop_grace_period: 60snetworks:- ldr-networkdiff --git a/docs/docker-compose-guide.md b/docs/docker-compose-guide.mdindex 3a16a4b647..5901bec23d 100644--- a/docs/docker-compose-guide.md+++ b/docs/docker-compose-guide.md@@ -173,6 +173,17 @@ docker compose pull && docker compose up -ddocker compose down -v```+The standard and generated Compose stacks allow 60 seconds for LDR to stop.+Uvicorn first gives active requests up to 10 seconds to drain, then the app+stops schedulers and the queue dispatcher, flushes logs and closes databases.+The GPU and Unraid overrides inherit this grace period from the base stack.++An in-flight scheduler job can take longer than this allowance. Increase+`services.local-deep-research.stop_grace_period` for deployments that need+more time; Docker sends SIGKILL when the allowance expires. This does not+guarantee that an in-progress research run completes during shutdown.+See Docker's [stop grace period reference](https://docs.docker.com/reference/compose-file/services/#stop_grace_period).+## Troubleshooting### Container won't startdiff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.pyindex 17f92782b3..8cb9772bb3 100644--- a/src/local_deep_research/web/fastapi_app.py+++ b/src/local_deep_research/web/fastapi_app.py@@ -521,30 +521,15 @@ async def lifespan(app: FastAPI):except Exception:logger.warning("Failed to start cleanup scheduler")- # Shutdown is the code after `yield` below. A parallel atexit handler- # would double-close the DB on normal exit (lifespan runs first, then- # atexit fires on interpreter teardown), which is why there isn't one.- #- # CORRECTION (pre-merge readiness audit): this comment previously said- # "the lifespan `finally` below owns shutdown". There is no `finally` —- # the body is flat, `yield` then shutdown statements. That matters- # because the sentence was doing real work: it justified having no- # atexit handler by appealing to a guarantee the code does not make.- #- # What actually holds. uvicorn's graceful path stops accepting, drains- # connections, then drives the ASGI lifespan shutdown, which resumes- # this generator through a normal `__aexit__` — so on SIGTERM the code- # below DOES run. What is NOT covered is cancellation: if- # `timeout_graceful_shutdown` (10s, see web/app.py) expires or the- # process is killed harder, CancelledError is thrown in at the `yield`- # and everything below is skipped. Wrapping this in try/finally would- # close that, and is deliberately NOT done in the migration PR: it- # reindents ~48 lines on the shutdown path, and running full DB cleanup- # while already past the force-kill deadline is a judgement call for- # whoever owns deployment, not a mechanical fix.- #- # Consequence to know when reasoning about the atexit decision above:- # on a forced kill neither runs.+ # Uvicorn drains requests before entering lifespan shutdown. Its+ # timeout_graceful_shutdown (10s) drain timeout cancels request tasks,+ # then still sends the lifespan shutdown event; it does not cancel+ # this generator at the yield.+ # Compose allows 60s for both phases. Scheduler shutdown can still wait+ # for an in-flight job, so this is an outer grace period, not a bound on+ # each cleanup step. SIGKILL or cancellation of the lifespan itself can+ # skip the code below. An atexit handler cannot recover from SIGKILL and+ # would double-close databases on normal exit.yield # --- App is running ---diff --git a/tests/deployment/test_deployment_surface_contracts.py b/tests/deployment/test_deployment_surface_contracts.pyindex af694756d6..9ae52f83a5 100644--- a/tests/deployment/test_deployment_surface_contracts.py+++ b/tests/deployment/test_deployment_surface_contracts.py@@ -1478,10 +1478,11 @@ class TestSignalsAndShutdown:lifespan = FASTAPI_APP_PY.read_text(encoding="utf-8")assert "reconcile_orphan_active_research" not in lifespan- def test_lifespan_shutdown_is_not_protected_by_try_finally(self):- """Pinned as documented behaviour: everything after ``yield`` is- skipped if the graceful deadline expires or the process is killed- harder, and there is no atexit backstop."""+ def test_lifespan_owns_shutdown_without_an_atexit_backstop(self):+ """The request-drain timeout still enters the lifespan shutdown.++ A forced kill cannot run either lifespan or atexit cleanup.+ """source = FASTAPI_APP_PY.read_text(encoding="utf-8")assert "import atexit" not in sourceassert "atexit.register" not in source@@ -1492,21 +1493,6 @@ class TestSignalsAndShutdown:assert "db_manager.close_all_databases()" in after_yieldassert "cleanup_scheduler.shutdown(wait=True)" in after_yield- @pytest.mark.xfail(- strict=True,- reason=(- "DEFECT: no compose file sets stop_grace_period, so Docker's "- "10s default applies -- exactly equal to uvicorn's own "- "timeout_graceful_shutdown=10. The lifespan shutdown that runs "- "AFTER the drain (queue_processor.stop() joins up to 10s more, "- "cleanup_scheduler.shutdown(wait=True) is unbounded, then the "- "log-queue flush and close_all_databases()) therefore starts at "- "or past the SIGKILL deadline. The code comments state plainly "- "that a forced kill skips all of it and there is no atexit "- "backstop, so encrypted DB handles are torn down uncleanly on "- "an ordinary 'docker compose down'."- ),- )def test_stop_grace_period_covers_the_shutdown_budget(self):graceful = int(re.search(@@ -1520,16 +1506,27 @@ class TestSignalsAndShutdown:PROCESSOR_PY.read_text(encoding="utf-8"),).group(1))- for path in (COMPOSE_BASE, COMPOSE_UNRAID, COMPOSE_GPU):- data = yaml.safe_load(path.read_text(encoding="utf-8"))- service = (data.get("services") or {}).get(LDR_SERVICE)- if not service:- continue+ base = yaml.safe_load(COMPOSE_BASE.read_text(encoding="utf-8"))[+ "services"+ ][LDR_SERVICE]+ services = {COMPOSE_BASE.name: base}+ # These files are overrides of the base stack. Compose inherits+ # scalar settings unless the override explicitly replaces them.+ for path in (COMPOSE_UNRAID, COMPOSE_GPU):+ override = yaml.safe_load(path.read_text(encoding="utf-8"))+ services[path.name] = {+ **base,+ **override.get("services", {}).get(LDR_SERVICE, {}),+ }+ for gpu, amd in ((False, False), (True, False), (True, True)):+ services[f"generated-{gpu}-{amd}"] = render_cookiecutter(+ enable_gpu=gpu, _amd_gpu=amd+ )["services"][LDR_SERVICE]+ for name, service in services.items():grace = service.get("stop_grace_period")- assert grace is not None, (- f"{path.name} relies on Docker's 10s default"- )- assert int(str(grace).rstrip("s")) >= graceful + join+ assert grace is not None, f"{name} relies on Docker's 10s default"+ # Leave time for log flushing and DB cleanup after both joins.+ assert int(str(grace).rstrip("s")) > graceful + join + 2# ---------------------------------------------------------------------------diff --git a/tests/web/test_lifespan_startup_shutdown.py b/tests/web/test_lifespan_startup_shutdown.pyindex e1f05aa76c..774a85a970 100644--- a/tests/web/test_lifespan_startup_shutdown.py+++ b/tests/web/test_lifespan_startup_shutdown.py@@ -39,9 +39,9 @@ What this file protects, and what breaks if it regresses:now raises, and because ``SECRET_KEY = _load_secret_key()`` runs at modulescope that failure aborts the import, i.e. the boot.* **``timeout_graceful_shutdown``** — hardcoded to 10 in ``web/app.py`` with- no env override, and the lifespan's own comment quotes that number when- explaining which shutdown paths are covered. Pinned here so a silent- change to either side is visible.+ no env override, and the lifespan's own comment quotes that number as the+ request-drain budget that the Compose ``stop_grace_period`` is sized+ against. Pinned here so a silent change to either side is visible.WHY A CHILD PROCESS. ``socketio_asgi.init_lock()`` only assigns when``_lock is None``, so a process may complete at most ONE real lifespan cycle@@ -968,8 +968,9 @@ def test_graceful_shutdown_timeout_is_pinned_at_ten_seconds():"""Without it uvicorn waits forever on research SSE streams.Hardcoded on purpose (no env override), so pin the literal: a silent- change to this number changes how much of the shutdown path below- ``yield`` actually gets to run before CancelledError is thrown in.+ change to this number changes how long uvicorn drains requests before it+ sends the lifespan shutdown event, and that time counts against the+ Compose ``stop_grace_period`` (see ``test_deployment_surface_contracts``)."""call = _uvicorn_run_call()kwargs = {kw.arg: kw.value for kw in call.keywords}@@ -1020,13 +1021,13 @@ def test_the_lifespan_comment_quotes_the_real_shutdown_timeout():quoted = re.findall(r"timeout_graceful_shutdown`?\s*\((\d+)s", source)assert quoted, ("premise broken: the lifespan no longer quotes "- "timeout_graceful_shutdown's value when explaining which shutdown "- f"paths are covered, so drift cannot be detected. {FASTAPI_APP_PATH}"+ "timeout_graceful_shutdown's value when explaining the request-drain "+ f"budget, so drift cannot be detected. {FASTAPI_APP_PATH}")mismatched = [n for n in quoted if int(n) != configured]assert not mismatched, (f"the lifespan comment says timeout_graceful_shutdown is "f"{mismatched}s but web/app.py passes {configured}s. That comment is "- "load-bearing: it is the stated reason there is no try/finally "- "around the shutdown path."+ "load-bearing: it is the request-drain budget that the Compose "+ "stop_grace_period is sized against.")