Skip to content

~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.

fix(server): apply process dump policy at startup (#7807)

LearningCircuitcc2124c5269e
diff --git a/README.md b/README.md
index 2bb5fcb997..c7eb708b55 100644
--- a/README.md
+++ b/README.md
@@ -163,7 +163,7 @@ Your data stays yours. Each user gets their own isolated SQLCipher database encr
The [Docker setup](docker-compose.yml) ships with `cap_drop: ALL`, `no-new-privileges`, and a non-root runtime, with the bundled Ollama and SearXNG images pinned by digest. With a model running in the bundled Ollama, inference runs on your own hardware. LDR judges locality mainly by provider and endpoint address, not by where the model runs, so a local endpoint that relays to a hosted model (an Ollama cloud model, or a local LiteLLM or other OpenAI-compatible proxy in front of a hosted API) can still send your prompts off the machine without being detected. A self-hosted SearXNG still forwards your search queries to its upstream engines on the internet. To keep a run on private sources, search only local sources (collections, your library) under the *Private only* egress scope described below. That scope is a best-effort guard rail, not an air gap: see the Egress control section below and [SECURITY.md](SECURITY.md#egress-policy-module).
-**In-memory credentials**: Like any application that uses secrets at runtime, credentials are held in process memory during active sessions — mitigated with session-scoped credential lifetimes and core dump exclusion. See the [Security Policy](SECURITY.md#in-memory-credentials) for the full threat model.
+**In-memory credentials**: Credentials are held in process memory during active sessions. LDR limits their lifetime and applies process dump controls at web and MCP startup on POSIX, with additional dumpability controls on Linux. Other platforms and applications embedding LDR require operating-system configuration. See the [Security Policy](SECURITY.md#in-memory-credentials) for scope and platform details.
**Supply Chain Security**: Docker images are signed with [Cosign](https://github.com/sigstore/cosign) using GitHub's keyless OIDC flow, include SLSA provenance attestations, and ship with attested SPDX SBOMs. See [Verifying images and SBOMs](SECURITY.md#verifying-images-and-sboms) for the step-by-step verification commands.
diff --git a/SECURITY.md b/SECURITY.md
index 00a4d7c956..08ec310c24 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -76,7 +76,24 @@ Like all applications that use secrets at runtime — including [password manage
**What we do to mitigate:**
- Session-scoped credential lifetimes with automatic expiration
-- Core dump exclusion via container security settings
+- At web and MCP server startup, POSIX processes set and verify both
+ `RLIMIT_CORE` limits as zero. Linux also sets and verifies
+ `PR_SET_DUMPABLE=0`, including when the host uses a piped core handler.
+ A supported-platform enforcement failure stops startup. Other platforms
+ emit a warning and require operating-system crash-dump configuration.
+
+These controls apply to `ldr-web`, the normal ASGI lifespan, and `ldr-mcp`
+(including `python -m local_deep_research.mcp`). Importing LDR as a library
+does not change the host process's policy; embedding applications and ASGI
+launches with lifespan disabled must configure their own policy. Linux
+resets dumpability on `exec`, so this does not promise the same controls
+for external converters or other executed programs. Privileged host
+administrators can still inspect process memory. On Linux, ordinary
+debugger attachment is also restricted while this server policy is active.
+
+See the Linux man-pages for [core limits and piped handlers](https://man7.org/linux/man-pages/man5/core.5.html),
+[process dumpability](https://man7.org/linux/man-pages/man2/pr_set_dumpable.2const.html),
+and [exec behavior](https://man7.org/linux/man-pages/man2/execve.2.html).
Ideas for further improvements are always welcome via [GitHub Issues](https://github.com/LearningCircuit/local-deep-research/issues).
diff --git a/changelog.d/+server-process-dump-policy.security.md b/changelog.d/+server-process-dump-policy.security.md
new file mode 100644
index 0000000000..bf4c18427f
--- /dev/null
+++ b/changelog.d/+server-process-dump-policy.security.md
@@ -0,0 +1 @@
+Web and MCP servers now apply and verify process dump controls at startup on POSIX and Linux, stop startup if supported controls fail, and report when operating-system configuration is required. On Linux the server is now non-dumpable: it writes no core dumps, same-user debuggers such as py-spy or gdb cannot attach, and same-user `lsof`, `fuser`, `ss -p` and `/proc/<pid>/fd` no longer see it (run them as root). There is no opt-out; startup stops if a seccomp profile or container denies `prctl`. See the troubleshooting guide.
diff --git a/docs/developing/resource-cleanup.md b/docs/developing/resource-cleanup.md
index 42e4c67cab..336a0be11c 100644
--- a/docs/developing/resource-cleanup.md
+++ b/docs/developing/resource-cleanup.md
@@ -605,20 +605,23 @@ sudo bash -c "
" | tee /tmp/ldr-fd-snapshot.txt
```
-Why host-side: reading the container's PID 1 FDs from inside the
-container requires the same UID that started PID 1. The Dockerfile
-entrypoint runs as root then `setpriv`s to `ldruser`, so the
-`docker exec` shell (ldruser) cannot `readlink` PID 1's FDs even though
-it can count them. Host root via `sudo` sidesteps the UID check.
+Why host-side, and why root: the server makes itself non-dumpable at
+startup (`prctl(PR_SET_DUMPABLE, 0)`), and Linux then lets only root read
+its `/proc/PID/fd`, `fdinfo`, `maps` and `environ` entries. A shell running
+as the same UID as the server (the `docker exec` shell as `ldruser`, or
+your own user on bare metal) can neither list nor `readlink` the server's
+FDs, and `lsof -p`, `fuser` and `ss -p` report nothing for it. Host root
+via `sudo` sidesteps the check.
#### Inside-container alternative (if the host is locked down)
```bash
-docker exec --user 0 <container-name> sh -c '...same body...'
+docker exec --privileged --user 0 <container-name> sh -c '...same body...'
```
-`--user 0` runs the exec'd shell as root inside the container,
-sidestepping the same UID restriction.
+`--user 0` runs the exec'd shell as root inside the container. Root there
+still lacks `CAP_SYS_PTRACE` by default, which Linux requires to resolve a
+non-dumpable process's FDs, so `--privileged` is needed as well.
### 2. The lookup table — FD type → likely source
@@ -652,7 +655,8 @@ httpx even when called inside a running loop."
Pidfds expose their target PID via fdinfo:
```bash
-# Run inside the container (or via docker exec --user 0):
+# Run as root with CAP_SYS_PTRACE: host root, docker exec --privileged
+# --user 0, or sudo on bare metal (the server is non-dumpable; see above).
for fd in $(ls /proc/1/fd 2>/dev/null); do
link=$(readlink /proc/1/fd/$fd 2>/dev/null)
case "$link" in
diff --git a/docs/security/rekey-recovery.md b/docs/security/rekey-recovery.md
index e821214a09..31f30d9c9b 100644
--- a/docs/security/rekey-recovery.md
+++ b/docs/security/rekey-recovery.md
@@ -168,8 +168,15 @@ permissions, a stuck process) has been fixed, or when the epoch files are
malformed.
1. **Stop the server**, every worker and process that uses the data
- directory. Check that nothing still holds the lock, for example with
- `fuser ldr_user_{user_hash}.db.rekey.lock` or `lsof`.
+ directory, then confirm that no LDR server process is left, for example
+ with `pgrep -af 'ldr-web|local_deep_research'` (bare-metal) or
+ `docker ps` (Docker). The server makes itself non-dumpable at startup,
+ so Linux makes its open-file entries under `/proc` readable only by
+ root: `fuser` or `lsof` run as the same user as the server report
+ nothing even while the server holds the lock. If you also check the
+ lock file, run them as root, for example
+ `sudo fuser -v ldr_user_{user_hash}.db.rekey.lock` or
+ `sudo lsof ldr_user_{user_hash}.db.rekey.lock`.
2. **Back up every file of that user first**: copy all
`ldr_user_{user_hash}.db*` files (database, `-wal`, `-shm`, `.salt` and
the `.rekey.*` files) together, outside the data directory.
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 1452a0ef16..c20f628a57 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -14,6 +14,7 @@ This guide covers common issues and their solutions.
- [Embedding Issues](#embedding-issues)
- [Performance Issues](#performance-issues)
- [Resource Exhaustion](#resource-exhaustion)
+- [Core Dumps and Debuggers](#core-dumps-and-debuggers)
---
@@ -364,6 +365,12 @@ sudo lsof -i :5000 # May need sudo for system services
# If "ControlCe" or "AirPlayXPC" appears → AirPlay is the cause
```
+On Linux, a running LDR server does not show up in `lsof -i :5000` run as
+your own user, because the server makes itself non-dumpable at startup and
+its sockets are then visible only to root. Use `sudo lsof -i :5000` (or
+`sudo ss -ltnp 'sport = :5000'`) to see it; `ss -ltn 'sport = :5000'`
+without `-p` still shows whether the port is taken.
+
**Solutions:**
1. **Disable AirPlay Receiver** (macOS 12 Monterey and later):
@@ -401,8 +408,9 @@ sudo lsof -i :5000 # May need sudo for system services
2. **Port conflicts:**
```bash
- # Check what's using port 5000
- lsof -i :5000
+ # Check what's using port 5000 (sudo: on Linux a running LDR server
+ # is non-dumpable, so a same-user lsof does not see its sockets)
+ sudo lsof -i :5000
# Use different port
docker run -p 8080:5000 ...
@@ -610,17 +618,30 @@ Each SQLCipher WAL-mode connection uses 2 file descriptors (main db + WAL), plus
**Diagnosis:**
```bash
-# Inside Docker (PID 1 is the app due to exec in entrypoint)
-ls /proc/1/fd | wc -l
-cat /proc/1/limits | grep "open files"
+# Docker (PID 1 is the app due to exec in entrypoint), from the host
+# <container> is the container name, e.g. local-deep-research, or
+# <project>-local-deep-research-1 under docker compose (see `docker ps`)
+sudo ls /proc/$(docker inspect -f '{{.State.Pid}}' <container>)/fd | wc -l
+sudo cat /proc/$(docker inspect -f '{{.State.Pid}}' <container>)/limits | grep "open files"
-# Bare-metal Linux
-ls /proc/$(pgrep -fo ldr-web)/fd | wc -l
+# Bare-metal Linux (sudo: see the note below)
+pgrep -af 'ldr-web|local_deep_research' # note the server's PID
+sudo ls /proc/<PID>/fd | wc -l
# Detailed view — show database-related FDs
-lsof -p <PID> | grep -E '\.db|\.wal|\.shm'
+sudo lsof -p <PID> | grep -E '\.db|\.wal|\.shm'
```
+These commands need root even when you run them as the user the server runs
+as: the server makes itself non-dumpable at startup, and Linux then lets only
+root read its `/proc/<PID>/fd`, `fdinfo`, `maps` and `environ` entries. Without
+`sudo`, `ls` fails with "Permission denied" and `lsof -p` lists nothing
+useful. For Docker, run the commands as root on the host against the
+container's PID, as above: root inside the container lacks `CAP_SYS_PTRACE`
+by default, so `docker exec --user 0` can count the FDs but may not resolve
+them (`docker exec --privileged --user 0` can).
+`pgrep` and `pkill` still work, because the command line stays readable.
+
**Solutions:**
1. The app includes automatic credential cleanup (~5 minutes) and periodic pool disposal (every 30 minutes) — this normally handles cleanup transparently
@@ -635,6 +656,33 @@ For the technical details of the cleanup architecture, see [Architecture - Threa
---
+## Core Dumps and Debuggers
+
+### No core dump, and py-spy or gdb cannot attach
+
+**Symptoms:**
+- A crashed server leaves no core file, and nothing appears in `coredumpctl`
+- `py-spy dump --pid <PID>`, `gdb -p <PID>` or `strace -p <PID>`, run as the user the server runs as, fail with "Operation not permitted" or "Permission denied"
+- `ls /proc/<PID>/fd`, `lsof -p <PID>`, `fuser` and `ss -p` show nothing for the running server
+
+**Why it happens:**
+
+This is by design. At startup the web and MCP servers set the core-file limit (`RLIMIT_CORE`) to zero and, on Linux, mark the process non-dumpable (`prctl(PR_SET_DUMPABLE, 0)`). The process memory holds session passwords and decrypted data, so the server keeps it out of core files and away from other programs running as the same user. A non-dumpable process cannot be attached to by same-user debuggers, and Linux makes its `/proc/<PID>` file-descriptor, memory-map and environment entries readable only by root. There is no setting to turn this off.
+
+The document-parser worker that the server starts to read uploaded files is a separate process. It also sets its core-file limit to zero, so it writes no core dumps, but it is not marked non-dumpable: a debugger running as the same user can still attach to it, and its `/proc/<PID>` entries stay readable. It holds the text of the document being parsed, not session passwords or database keys.
+
+**Diagnosis:**
+
+- Run the debugger or inspection tool as root, for example `sudo py-spy dump --pid <PID>` or `sudo lsof -p <PID>`. For Docker, run the tool as root on the host against the container's PID (`docker inspect -f '{{.State.Pid}}' <container>`); root inside the container lacks `CAP_SYS_PTRACE` by default.
+- Use the logs first: see [Debug Logging](#debug-logging).
+- Find the process with `pgrep -af 'ldr-web|local_deep_research'`; the command line stays readable.
+
+### Server refuses to start: "Cannot start server: ..."
+
+If the server cannot apply this policy, it stops at startup instead of serving without it. Messages such as `Cannot start server: Linux dumpability could not be disabled.` or `Cannot start server: core-file limits could not be disabled.` mean the operating system refused the call. This happens under some seccomp profiles, or in LXC and similar containers that block `prctl` or `setrlimit`. Allow `prctl(PR_SET_DUMPABLE)` and lowering `RLIMIT_CORE` for the server in that sandbox's configuration. The server has no option to skip this check.
+
+---
+
## Debug Logging
> **Security note:** Log files are unencrypted and may contain sensitive information such as research queries. Ensure appropriate file permissions.
diff --git a/scripts/dev/restart_server.sh b/scripts/dev/restart_server.sh
index 71d4f42f51..fd1e33d58f 100755
--- a/scripts/dev/restart_server.sh
+++ b/scripts/dev/restart_server.sh
@@ -22,6 +22,15 @@
# instances on different ports (e.g. several agents each on their own port)
# coexist — restarting one does not kill the others.
#
+# The server makes itself non-dumpable at startup, so on Linux a same-user
+# `fuser PORT/tcp`, `lsof -i` or `ss -p` cannot see which process owns the
+# port (its /proc fd entries become root-only). This script therefore
+# starts the server in its own process group, records that group in
+# ${XDG_RUNTIME_DIR:-/tmp}/ldr_server_PORT.pid, and on the next restart stops
+# the group only after checking it is an LDR server launched for this PORT.
+# It exits non-zero if the port is still taken or the new server fails to
+# start listening.
+#
# Referenced in:
# - tests/api_tests_with_login/README.md
# - examples/api_usage/http/README.md
@@ -29,6 +38,11 @@
# Do not delete without updating those references.
set -u
+# No job control, even when invoked from `bash -i`, with `set -m`, or with
+# monitor in an exported SHELLOPTS. With job control every background job
+# leads its own process group, and util-linux setsid then forks instead of
+# exec'ing, so $! would no longer be the server's process group.
+set +m
usage() {
cat <<'EOF'
@@ -64,27 +78,165 @@ for arg in "$@"; do
esac
done
-echo "Stopping existing LDR server on port ${PORT} (if any)..."
-# Port-scoped stop: kill only the process LISTENing on PORT, leaving
-# instances on other ports running. The port isn't in the process argv
-# (it comes from LDR_WEB_PORT), so a broad pkill can't distinguish them.
-if command -v fuser >/dev/null 2>&1; then
- fuser -k "${PORT}/tcp" 2>/dev/null || echo "No existing server on port ${PORT}"
-elif command -v lsof >/dev/null 2>&1; then
- pids=$(lsof -ti "tcp:${PORT}" -sTCP:LISTEN 2>/dev/null)
- if [ -n "${pids}" ]; then
- # $pids may be several PIDs; word-splitting is intended here.
- # shellcheck disable=SC2086
- kill ${pids} 2>/dev/null
+SERVER_PATTERN="local_deep_research.web.app"
+PID_DIR="${XDG_RUNTIME_DIR:-/tmp}"
+[ -d "${PID_DIR}" ] || PID_DIR=/tmp
+PID_FILE="${PID_DIR}/ldr_server_${PORT}.pid"
+LOG_FILE="/tmp/ldr_server_${PORT}.log"
+# Seconds to wait for the old server to exit and for the new one to listen.
+STOP_TIMEOUT=15
+START_TIMEOUT="${LDR_RESTART_START_TIMEOUT:-90}"
+case "${START_TIMEOUT}" in
+ ''|*[!0-9]*|0)
+ echo "Error: LDR_RESTART_START_TIMEOUT must be a positive whole number of seconds, got '${START_TIMEOUT}'." >&2
+ exit 2
+ ;;
+esac
+
+# Probe host: LDR_WEB_HOST as the server will see it, without IPv6 brackets.
+# A wildcard bind accepts connections on loopback. The host can also come
+# from the web.host setting or a legacy server_config.json in the data dir;
+# this script does not read those, so export LDR_WEB_HOST if you set the
+# host there to something other than a wildcard or loopback address.
+PROBE_HOST="${LDR_WEB_HOST:-127.0.0.1}"
+PROBE_HOST="${PROBE_HOST#[}"
+PROBE_HOST="${PROBE_HOST%]}"
+case "${PROBE_HOST}" in
+ 0.0.0.0|'') PROBE_HOST=127.0.0.1 ;;
+ ::) PROBE_HOST=::1 ;;
+esac
+
+# True when something accepts TCP connections on PORT. Uses bash's
+# /dev/tcp, which needs no access to the listening process's /proc entries.
+# Bounded by `timeout` where available, since a filtered address can make
+# the connect hang.
+port_in_use() {
+ # $1/$2 expand in the child bash, which gets host and port as arguments.
+ # shellcheck disable=SC2016
+ local probe='exec 3<>"/dev/tcp/$1/$2"'
+ if command -v timeout >/dev/null 2>&1; then
+ timeout 2 bash -c "${probe}" _ "${PROBE_HOST}" "${PORT}" 2>/dev/null
else
- echo "No existing server on port ${PORT}"
+ bash -c "${probe}" _ "${PROBE_HOST}" "${PORT}" 2>/dev/null
fi
-else
- echo "Warning: neither fuser nor lsof found; cannot port-scope the stop." >&2
- echo "Skipping stop to avoid killing instances on other ports." >&2
+}
+
+# True while any process in process group $1 is alive.
+group_alive() {
+ kill -0 -- "-$1" 2>/dev/null
+}
+
+# True when the pidfile may be trusted: a regular file, not a symlink, and
+# owned by the current user (a shared /tmp lets others pre-create it).
+pid_file_trusted() {
+ [ -f "${PID_FILE}" ] && [ ! -L "${PID_FILE}" ] && [ -O "${PID_FILE}" ]
+}
+
+# True when some process in group $1 was launched for this PORT. The
+# server itself is non-dumpable, so its environ is root-only, but the
+# `pdm run` / `env` processes above it in the group stay readable.
+group_serves_port() {
+ local pid
+ for pid in $(pgrep -g "$1" 2>/dev/null); do
+ if tr '\0' '\n' 2>/dev/null < "/proc/${pid}/environ" \
+ | grep -qxF "LDR_WEB_PORT=${PORT}"; then
+ return 0
+ fi
+ done
+ return 1
+}
+
+# Stop the server this script launched for PORT, by the process group
+# recorded in PID_FILE. Nothing is signalled unless the group runs
+# SERVER_PATTERN and was launched with LDR_WEB_PORT=PORT, so a stale or
+# planted pidfile cannot stop another port's server or an unrelated group.
+stop_recorded_server() {
+ local pgid
+ [ -e "${PID_FILE}" ] || [ -L "${PID_FILE}" ] || return 0
+ if ! pid_file_trusted; then
+ echo "Warning: ignoring ${PID_FILE}: not a regular file owned by $(id -un)." >&2
+ return 0
+ fi
+ pgid=$(cat "${PID_FILE}" 2>/dev/null)
+ case "${pgid}" in
+ ''|*[!0-9]*) rm -f "${PID_FILE}"; return 0 ;;
+ esac
+ if [ "${pgid}" -le 1 ]; then
+ rm -f "${PID_FILE}"
+ return 0
+ fi
+ if ! pgrep -g "${pgid}" -f "${SERVER_PATTERN}" >/dev/null 2>&1; then
+ rm -f "${PID_FILE}"
+ return 0
+ fi
+ if ! group_serves_port "${pgid}"; then
+ echo "Warning: process group ${pgid} in ${PID_FILE} is not an LDR server for port ${PORT}; not stopping it." >&2
+ rm -f "${PID_FILE}"
+ return 0
+ fi
+ echo "Stopping LDR server process group ${pgid} on port ${PORT}..."
+ kill -TERM -- "-${pgid}" 2>/dev/null
+ local i
+ for ((i = 0; i < STOP_TIMEOUT; i++)); do
+ group_alive "${pgid}" || break
+ sleep 1
+ done
+ if group_alive "${pgid}"; then
+ echo "Server did not exit after ${STOP_TIMEOUT}s; sending SIGKILL." >&2
+ kill -KILL -- "-${pgid}" 2>/dev/null
+ sleep 1
+ fi
+ rm -f "${PID_FILE}"
+}
+
+# Record process group $1 in PID_FILE without following a planted symlink
+# or overwriting a file another user owns.
+write_pid_file() {
+ if [ -L "${PID_FILE}" ] || { [ -e "${PID_FILE}" ] && ! pid_file_trusted; }; then
+ echo "Warning: not recording PID in ${PID_FILE}: not a regular file owned by $(id -un)." >&2
+ return 1
+ fi
+ rm -f "${PID_FILE}"
+ (set -C; echo "$1" > "${PID_FILE}") 2>/dev/null || {
+ echo "Warning: could not write ${PID_FILE}." >&2
+ return 1
+ }
+}
+
+echo "Stopping existing LDR server on port ${PORT} (if any)..."
+stop_recorded_server
+
+# A server this script did not start (or one started before it recorded
+# PIDs) is not in PID_FILE. Try a port-scoped stop; on Linux this only
+# finds a non-dumpable LDR server when run as root.
+if port_in_use; then
+ if command -v fuser >/dev/null 2>&1; then
+ fuser -k "${PORT}/tcp" >/dev/null 2>&1
+ elif command -v lsof >/dev/null 2>&1; then
+ pids=$(lsof -ti "tcp:${PORT}" -sTCP:LISTEN 2>/dev/null)
+ if [ -n "${pids}" ]; then
+ # $pids may be several PIDs; word-splitting is intended here.
+ # shellcheck disable=SC2086
+ kill ${pids} 2>/dev/null
+ fi
+ fi
+ for ((i = 0; i < STOP_TIMEOUT; i++)); do
+ port_in_use || break
+ sleep 1
+ done
fi
-sleep 1
+if port_in_use; then
+ echo "Error: port ${PORT} is still in use; not starting a new server." >&2
+ echo "It is held by a process this script did not start, and on Linux a" >&2
+ echo "running LDR server is non-dumpable, so same-user fuser/lsof cannot" >&2
+ echo "see it. Find and stop it with one of:" >&2
+ echo " pgrep -af '${SERVER_PATTERN}|ldr-web' # then: kill <PID>" >&2
+ echo " sudo fuser -k ${PORT}/tcp" >&2
+ echo "or pass a different PORT." >&2
+ exit 1
+fi
+echo "Port ${PORT} is free."
# Change to the project root.
cd "$(dirname "$0")/../.." || exit 1
@@ -103,8 +255,6 @@ if [ "$debug" -eq 1 ]; then
env_args+=(LDR_APP_DEBUG=true LDR_LOG_SETTINGS=summary)
fi
-LOG_FILE="/tmp/ldr_server_${PORT}.log"
-
if [ "$debug" -eq 1 ]; then
echo "Starting LDR server on port ${PORT} (DEBUG)..."
else
@@ -112,13 +262,59 @@ else
fi
# Start server in background and detach from terminal. Backgrounding nohup
# directly (rather than wrapping in an extra `( ... & ) &` subshell) means
-# $! captures the real server PID, not a transient subshell that has already
-# exited. nohup ignores SIGHUP, so the server survives the launcher exiting
-# and is reparented to init.
-nohup env "${env_args[@]}" pdm run python -m local_deep_research.web.app > "${LOG_FILE}" 2>&1 &
+# $! captures the real launcher PID, not a transient subshell that has
+# already exited. nohup ignores SIGHUP, so the server survives the launcher
+# exiting and is reparented to init. setsid (where available) puts the
+# server and its `pdm run` parent in a new process group. Because job
+# control is off (`set +m` above), the background job does not lead a
+# group, so setsid exec's in place and the new group's ID is $!; this is
+# checked once the server is up, before the next restart relies on it.
+launcher=(nohup)
+if command -v setsid >/dev/null 2>&1; then
+ launcher+=(setsid)
+fi
+"${launcher[@]}" env "${env_args[@]}" pdm run python -m local_deep_research.web.app > "${LOG_FILE}" 2>&1 &
SERVER_PID=$!
+if [ "${#launcher[@]}" -gt 1 ]; then
+ write_pid_file "${SERVER_PID}"
+fi
+
+# Wait until the new server accepts connections; fail loudly if it exits
+# first (e.g. the port was taken, or startup refused) or never listens.
+started=0
+for ((i = 0; i < START_TIMEOUT; i++)); do
+ if ! kill -0 "${SERVER_PID}" 2>/dev/null; then
+ break
+ fi
+ if port_in_use; then
+ started=1
+ break
+ fi
+ sleep 1
+done
-sleep 2
+if [ "${started}" -ne 1 ]; then
+ if kill -0 "${SERVER_PID}" 2>/dev/null; then
+ echo "Error: server (PID ${SERVER_PID}) is not listening on port ${PORT} after ${START_TIMEOUT}s." >&2
+ echo "It is still running; set LDR_RESTART_START_TIMEOUT to wait longer." >&2
+ else
+ echo "Error: server failed to start on port ${PORT}." >&2
+ rm -f "${PID_FILE}"
+ fi
+ echo "--- last 40 lines of ${LOG_FILE} ---" >&2
+ tail -40 "${LOG_FILE}" >&2 2>/dev/null
+ exit 1
+fi
+
+# Confirm the recorded group really is $!; if setsid forked anyway, the
+# pidfile would name a dead group, so drop it and say how to stop instead.
+if pid_file_trusted; then
+ pgid=$(ps -o pgid= -p "${SERVER_PID}" 2>/dev/null | tr -d ' ')
+ if [ "${pgid}" != "${SERVER_PID}" ]; then
+ echo "Warning: server is not in process group ${SERVER_PID}; next restart cannot stop it automatically." >&2
+ rm -f "${PID_FILE}"
+ fi
+fi
echo "Server started. PID: ${SERVER_PID}"
echo "Logs: ${LOG_FILE}"
@@ -129,6 +325,10 @@ if [ "$debug" -eq 1 ]; then
fi
echo ""
echo "To view logs: tail -f ${LOG_FILE}"
-echo "To stop server: fuser -k ${PORT}/tcp"
+if pid_file_trusted; then
+ echo "To stop server: kill -TERM -- -${SERVER_PID} (or rerun this script)"
+else
+ echo "To stop server: pkill -f '${SERVER_PATTERN}' (stops every instance)"
+fi
exit 0
diff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.py
index e4af75c2d1..1b6c89dc04 100644
--- a/src/local_deep_research/mcp/server.py
+++ b/src/local_deep_research/mcp/server.py
@@ -1095,6 +1095,9 @@ def run_server():
# `migrate_legacy_docstores()` would otherwise escape with the startup
# lines still queued and reproduce the very inversion this fixes.
try:
+ from ..security.process_dump_policy import enforce_process_dump_policy
+
+ enforce_process_dump_policy()
logger.info("Starting Local Deep Research MCP server...")
# Phase-1 of the RAG plaintext-at-rest migration must run here too,
diff --git a/src/local_deep_research/security/process_dump_policy.py b/src/local_deep_research/security/process_dump_policy.py
new file mode 100644
index 0000000000..fbd156805a
--- /dev/null
+++ b/src/local_deep_research/security/process_dump_policy.py
@@ -0,0 +1,95 @@
+"""Process dump policy applied explicitly when an LDR server starts.
+
+Importing this module does not change process limits or dumpability.
+"""
+
+from os import name as _os_name
+from sys import platform as _platform
+import warnings
+
+try:
+ import resource as _resource
+except ImportError: # Windows
+ _resource = None
+
+
+_PR_GET_DUMPABLE = 3
+_PR_SET_DUMPABLE = 4
+
+
+class ProcessDumpPolicyError(RuntimeError):
+ """A supported server process could not apply its dump policy."""
+
+
+def enforce_process_dump_policy() -> bool:
+ """Disable process dumps before starting server work.
+
+ POSIX servers require both core-file size limits to be zero. Linux
+ additionally requires a non-dumpable process because its piped core
+ handlers do not honor ``RLIMIT_CORE``. Each setting is read back;
+ failure raises ``ProcessDumpPolicyError`` and must stop startup.
+
+ Returns False, with a warning, on non-POSIX platforms where these
+ controls are unavailable. They require operating-system configuration.
+ This policy is not restored at shutdown. A child started with exec
+ inherits ``RLIMIT_CORE`` of zero, but Linux resets its dumpability, so
+ the child is dumpable again unless it disables that itself. The
+ document-parser worker (``security/isolated_worker.py``) does not: it
+ sets ``RLIMIT_CORE`` to zero itself and holds document text, not the
+ server's credentials.
+ """
+ if _os_name != "posix":
+ warnings.warn(
+ "Process dump controls are unavailable on this platform; "
+ "configure crash-dump policy in the operating system.",
+ RuntimeWarning,
+ stacklevel=2,
+ )
+ return False
+
+ if _resource is None:
+ raise ProcessDumpPolicyError(
+ "Cannot start server: POSIX core-file controls are unavailable."
+ )
+ try:
+ _resource.setrlimit(_resource.RLIMIT_CORE, (0, 0))
+ limits = _resource.getrlimit(_resource.RLIMIT_CORE)
+ except (AttributeError, OSError, ValueError):
+ raise ProcessDumpPolicyError(
+ "Cannot start server: core-file limits could not be disabled."
+ ) from None
+ if limits != (0, 0):
+ raise ProcessDumpPolicyError(
+ "Cannot start server: core-file limits remain enabled."
+ )
+
+ if _platform.startswith("linux"):
+ try:
+ # Imported here, not at module level: ctypes is only needed on
+ # Linux, and an interpreter built without _ctypes must still
+ # fail with ProcessDumpPolicyError rather than ImportError.
+ import ctypes
+
+ prctl = ctypes.CDLL(None, use_errno=True).prctl
+ # prctl is variadic: the trailing arguments must have the width
+ # of unsigned long, including the unused zero arguments.
+ prctl.argtypes = [ctypes.c_int] + [ctypes.c_ulong] * 4
+ prctl.restype = ctypes.c_int
+ configured = prctl(_PR_SET_DUMPABLE, 0, 0, 0, 0)
+ dumpable = prctl(_PR_GET_DUMPABLE, 0, 0, 0, 0)
+ except (
+ AttributeError,
+ ImportError,
+ OSError,
+ TypeError,
+ ValueError,
+ ):
+ raise ProcessDumpPolicyError(
+ "Cannot start server: Linux dumpability controls are unavailable."
+ ) from None
+ if configured != 0 or dumpable != 0:
+ raise ProcessDumpPolicyError(
+ "Cannot start server: Linux dumpability could not be disabled."
+ )
+
+ return True
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index fc3f82b2ab..e87bbf5778 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -71,6 +71,9 @@ def main():
config = load_server_config()
config_logger("ldr_web", debug=config["debug"])
+ from ..security.process_dump_policy import enforce_process_dump_policy
+
+ enforce_process_dump_policy()
logger.info(f"Starting Local Deep Research v{__version__}")
# One-time removal of plaintext legacy RAG docstores (phase 1 of the
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index e162c271cd..a0f13c0066 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -326,6 +326,10 @@ def warn_if_threadpool_exceeds_db_pool(worker_threads: int) -> bool:
async def lifespan(app: FastAPI):
"""Manage application lifecycle — start/stop background services."""
# --- Startup ---
+ from ..security.process_dump_policy import enforce_process_dump_policy
+
+ # Direct ASGI launches also need the policy before workers or requests.
+ enforce_process_dump_policy()
logger.info(f"Starting Local Deep Research v{__version__}")
# Capture uvicorn's running event loop so background threads can
diff --git a/tests/conftest.py b/tests/conftest.py
index 43065dac84..8e0614c0a4 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -196,6 +196,38 @@ def reset_all_singletons():
_reset()
+# NOTE: this fixture must NOT take a ``monkeypatch`` dependency. pytest
+# registers autouse fixtures in alphabetical order (conftest attributes are
+# scanned via ``dir()``), and a fixture's dependencies are set up alongside
+# it while finalization is LIFO over setup order. A ``monkeypatch``
+# dependency here would set up ``monkeypatch`` before
+# ``reset_all_singletons`` (this fixture's name sorts first) and defer
+# ``monkeypatch.undo()`` to AFTER the singleton-reset teardown, which then
+# calls ``discover_providers(force_refresh=True)`` through whatever doubles
+# the test left installed — "ERROR at teardown" for every such test. The
+# manual save/restore below leaves ``monkeypatch`` to test-level doubles
+# only, so their undo runs before the reset teardown as it did before this
+# fixture existed. ``tests/test_conftest_fixture_ordering.py`` pins both
+# properties.
[email protected](autouse=True)
+def isolate_server_process_dump_policy():
+ """Server startup tests must not change the pytest process's OS policy.
+
+ Helper tests receive the real function and restore it only after
+ replacing its resource/ctypes boundaries. Startup wiring tests replace
+ this stub with their own recorder or failure. Fresh interpreter probes
+ can apply the real policy without affecting the pytest process.
+ """
+ from local_deep_research.security import process_dump_policy
+
+ real_enforcer = process_dump_policy.enforce_process_dump_policy
+ process_dump_policy.enforce_process_dump_policy = lambda: True
+ try:
+ yield real_enforcer
+ finally:
+ process_dump_policy.enforce_process_dump_policy = real_enforcer
+
+
@pytest.fixture(autouse=True)
def database_operation_timeout():
"""Set shorter timeouts for database operations in tests.
diff --git a/tests/security/test_process_dump_policy.py b/tests/security/test_process_dump_policy.py
new file mode 100644
index 0000000000..7138c9c5f2
--- /dev/null
+++ b/tests/security/test_process_dump_policy.py
@@ -0,0 +1,174 @@
+"""Process-policy checks with all resource and ctypes calls mocked."""
+
+import ctypes
+import importlib.util
+import sys
+from pathlib import Path
+from unittest.mock import Mock, call
+
+import pytest
+
+from local_deep_research.security import process_dump_policy as policy
+from local_deep_research.security.process_dump_policy import (
+ ProcessDumpPolicyError,
+)
+
+
[email protected](autouse=True)
+def mocked_system(monkeypatch, isolate_server_process_dump_policy):
+ resource = Mock(RLIMIT_CORE=4)
+ resource.getrlimit.return_value = (0, 0)
+ prctl = Mock(return_value=0)
+ library = Mock(prctl=prctl)
+ loader = Mock(return_value=library)
+ monkeypatch.setattr(policy, "_resource", resource)
+ monkeypatch.setattr(policy, "_os_name", "posix")
+ monkeypatch.setattr(policy, "_platform", "linux")
+ # The helper imports ctypes lazily, so patch the module it will get.
+ monkeypatch.setattr(ctypes, "CDLL", loader)
+ # Restore the real helper only after every OS boundary is a fake.
+ monkeypatch.setattr(
+ policy,
+ "enforce_process_dump_policy",
+ isolate_server_process_dump_policy,
+ )
+ return resource, prctl, loader
+
+
+def test_linux_policy_sets_and_reads_back_both_controls(mocked_system):
+ resource, prctl, loader = mocked_system
+
+ assert policy.enforce_process_dump_policy() is True
+
+ resource.setrlimit.assert_called_once_with(resource.RLIMIT_CORE, (0, 0))
+ resource.getrlimit.assert_called_once_with(resource.RLIMIT_CORE)
+ loader.assert_called_once_with(None, use_errno=True)
+ assert prctl.call_args_list == [
+ call(policy._PR_SET_DUMPABLE, 0, 0, 0, 0),
+ call(policy._PR_GET_DUMPABLE, 0, 0, 0, 0),
+ ]
+ assert prctl.argtypes == [ctypes.c_int] + [ctypes.c_ulong] * 4
+ assert prctl.restype is ctypes.c_int
+
+
+def test_each_startup_reapplies_policy_instead_of_caching(mocked_system):
+ resource, prctl, _loader = mocked_system
+
+ policy.enforce_process_dump_policy()
+ policy.enforce_process_dump_policy()
+
+ assert resource.setrlimit.call_count == 2
+ assert prctl.call_count == 4
+
+
+def test_other_posix_platform_uses_core_limits(monkeypatch, mocked_system):
+ resource, _prctl, loader = mocked_system
+ monkeypatch.setattr(policy, "_platform", "darwin")
+
+ assert policy.enforce_process_dump_policy() is True
+
+ resource.getrlimit.assert_called_once_with(resource.RLIMIT_CORE)
+ loader.assert_not_called()
+
+
+def test_unsupported_platform_reports_scope(monkeypatch, mocked_system):
+ resource, _prctl, loader = mocked_system
+ monkeypatch.setattr(policy, "_os_name", "nt")
+
+ with pytest.warns(RuntimeWarning, match="operating system"):
+ assert policy.enforce_process_dump_policy() is False
+
+ resource.setrlimit.assert_not_called()
+ loader.assert_not_called()
+
+
+def test_posix_missing_resource_module_stops_startup(monkeypatch):
+ monkeypatch.setattr(policy, "_resource", None)
+
+ with pytest.raises(ProcessDumpPolicyError, match="unavailable"):
+ policy.enforce_process_dump_policy()
+
+
[email protected]("operation", ["setrlimit", "getrlimit"])
+def test_resource_failure_stops_before_linux_control(operation, mocked_system):
+ resource, _prctl, loader = mocked_system
+ getattr(resource, operation).side_effect = OSError("synthetic refusal")
+
+ with pytest.raises(ProcessDumpPolicyError, match="core-file limits"):
+ policy.enforce_process_dump_policy()
+
+ loader.assert_not_called()
+
+
[email protected]("limits", [(1, 1), (0, 1), (1, 0)])
+def test_resource_readback_must_confirm_both_zero(limits, mocked_system):
+ resource, _prctl, loader = mocked_system
+ resource.getrlimit.return_value = limits
+
+ with pytest.raises(ProcessDumpPolicyError, match="remain enabled"):
+ policy.enforce_process_dump_policy()
+
+ loader.assert_not_called()
+
+
+def test_unavailable_linux_control_stops_startup(mocked_system):
+ _resource, _prctl, loader = mocked_system
+ loader.side_effect = OSError("synthetic unavailable library")
+
+ with pytest.raises(ProcessDumpPolicyError, match="unavailable"):
+ policy.enforce_process_dump_policy()
+
+
+def test_missing_ctypes_module_stops_startup(monkeypatch, mocked_system):
+ _resource, _prctl, loader = mocked_system
+ # A None entry makes ``import ctypes`` raise ImportError, as on an
+ # interpreter built without _ctypes.
+ monkeypatch.setitem(sys.modules, "ctypes", None)
+
+ with pytest.raises(ProcessDumpPolicyError, match="unavailable"):
+ policy.enforce_process_dump_policy()
+
+ loader.assert_not_called()
+
+
+def test_non_linux_posix_does_not_need_ctypes(monkeypatch, mocked_system):
+ resource, _prctl, _loader = mocked_system
+ monkeypatch.setattr(policy, "_platform", "darwin")
+ monkeypatch.setitem(sys.modules, "ctypes", None)
+
+ assert policy.enforce_process_dump_policy() is True
+
+ resource.setrlimit.assert_called_once_with(resource.RLIMIT_CORE, (0, 0))
+
+
+def test_missing_prctl_symbol_stops_startup(mocked_system):
+ _resource, _prctl, loader = mocked_system
+ loader.return_value = Mock(spec=[])
+
+ with pytest.raises(ProcessDumpPolicyError, match="unavailable"):
+ policy.enforce_process_dump_policy()
+
+
[email protected]("results", [(-1, 0), (0, -1), (0, 1)])
+def test_linux_set_and_readback_must_succeed(results, mocked_system):
+ _resource, prctl, _loader = mocked_system
+ prctl.side_effect = results
+
+ with pytest.raises(ProcessDumpPolicyError, match="could not be disabled"):
+ policy.enforce_process_dump_policy()
+
+
+def test_import_does_not_change_process_policy(monkeypatch, mocked_system):
+ resource, _prctl, loader = mocked_system
+ monkeypatch.setitem(sys.modules, "resource", resource)
+ spec = importlib.util.spec_from_file_location(
+ "import_only_process_policy", Path(policy.__file__)
+ )
+ module = importlib.util.module_from_spec(spec)
+
+ spec.loader.exec_module(module)
+
+ assert callable(module.enforce_process_dump_policy)
+ resource.setrlimit.assert_not_called()
+ resource.getrlimit.assert_not_called()
+ loader.assert_not_called()
diff --git a/tests/test_cli_and_mcp_entrypoints.py b/tests/test_cli_and_mcp_entrypoints.py
index e5304f275d..08681e2a8f 100644
--- a/tests/test_cli_and_mcp_entrypoints.py
+++ b/tests/test_cli_and_mcp_entrypoints.py
@@ -487,6 +487,73 @@ class TestMcpModuleSurface:
)
+class TestMcpProcessDumpPolicy:
+ def test_policy_runs_before_migration_and_stdio(
+ self, mcp_server, monkeypatch
+ ):
+ from local_deep_research.security import process_dump_policy
+ from local_deep_research.vector_stores import legacy_cleanup
+
+ order = []
+ monkeypatch.setattr(mcp_server, "configure_mcp_logging", lambda: None)
+ monkeypatch.setattr(
+ mcp_server,
+ "logger",
+ types.SimpleNamespace(
+ info=lambda *_args: None, complete=lambda: None
+ ),
+ )
+ monkeypatch.setattr(
+ process_dump_policy,
+ "enforce_process_dump_policy",
+ lambda: order.append("policy"),
+ )
+ monkeypatch.setattr(
+ legacy_cleanup,
+ "migrate_legacy_docstores",
+ lambda: order.append("migration"),
+ )
+ monkeypatch.setattr(
+ mcp_server.mcp, "run", lambda **_kwargs: order.append("stdio")
+ )
+
+ mcp_server.run_server()
+
+ assert order == ["policy", "migration", "stdio"]
+
+ def test_policy_failure_stops_stdio_and_drains_logger(
+ self, mcp_server, monkeypatch
+ ):
+ from unittest.mock import Mock
+
+ from local_deep_research.security import process_dump_policy
+ from local_deep_research.vector_stores import legacy_cleanup
+
+ log = Mock()
+ migrate = Mock()
+ serve = Mock()
+ monkeypatch.setattr(mcp_server, "configure_mcp_logging", lambda: None)
+ monkeypatch.setattr(mcp_server, "logger", log)
+ monkeypatch.setattr(legacy_cleanup, "migrate_legacy_docstores", migrate)
+ monkeypatch.setattr(mcp_server.mcp, "run", serve)
+ monkeypatch.setattr(
+ process_dump_policy,
+ "enforce_process_dump_policy",
+ Mock(
+ side_effect=process_dump_policy.ProcessDumpPolicyError(
+ "synthetic refusal"
+ )
+ ),
+ )
+
+ with pytest.raises(process_dump_policy.ProcessDumpPolicyError):
+ mcp_server.run_server()
+
+ migrate.assert_not_called()
+ serve.assert_not_called()
+ log.complete.assert_called_once_with()
+
+
class TestWebEntryPoint:
def test_main_launches_uvicorn_with_the_resolved_config(self):
"""``ldr-web`` still reaches uvicorn after the port (no socket)."""
diff --git a/tests/test_conftest_fixture_ordering.py b/tests/test_conftest_fixture_ordering.py
new file mode 100644
index 0000000000..f7acdb0ca9
--- /dev/null
+++ b/tests/test_conftest_fixture_ordering.py
@@ -0,0 +1,78 @@
+"""Contracts for tests/conftest.py fixture finalization order.
+
+``reset_all_singletons`` calls ``discover_providers(force_refresh=True)``
+(among other module globals) in its teardown. Any ``monkeypatch`` double
+installed over those globals must therefore be undone BEFORE that teardown
+runs. pytest finalizes fixtures in LIFO order over setup order, autouse
+fixtures join each test's fixture closure in alphabetical order, and a
+fixture's ``monkeypatch`` dependency is set up when the first fixture
+requesting it is set up — so ``monkeypatch`` must be set up AFTER
+``reset_all_singletons``.
+
+When ``isolate_server_process_dump_policy`` took a ``monkeypatch``
+dependency it inverted this order (its name sorts before
+``reset_all_singletons``), and every test in
+tests/web/routers/test_model_refresh_concurrency.py ended with "ERROR at
+teardown: TypeError: <lambda>() got an unexpected keyword argument
+'force_refresh'" (102 in CI). The tests here pin the order and the
+behaviour so that regression cannot return silently.
+"""
+
+from local_deep_research.llm import providers
+from local_deep_research.security import process_dump_policy
+
+
+def test_monkeypatch_is_set_up_after_singleton_reset(request, monkeypatch):
+ """``monkeypatch`` must come after ``reset_all_singletons`` in the closure.
+
+ Autouse fixtures join the closure in alphabetical order (conftest
+ attributes are scanned via ``dir()``) with a fixture's dependencies
+ right after it, so any ``monkeypatch``-dependent autouse fixture whose
+ name sorts before ``reset_all_singletons`` pulls ``monkeypatch`` first —
+ the revert this test catches.
+ """
+ names = list(request.node.fixturenames)
+ monkeypatch_position = names.index("monkeypatch")
+ reset_position = names.index("reset_all_singletons")
+ assert monkeypatch_position > reset_position, (
+ "monkeypatch must be set up after reset_all_singletons so that "
+ "monkeypatch.undo() runs before the singleton-reset teardown; "
+ f"fixture closure order is {names!r}"
+ )
+
+
+def test_strict_discover_providers_double_is_undone_before_reset_teardown(
+ monkeypatch,
+):
+ """A strict discover_providers double must not survive into _reset().
+
+ The singleton-reset teardown calls ``discover_providers(force_refresh=True)``.
+ With the fixture order reverted, this test errors at teardown with
+ ``TypeError: <lambda>() got an unexpected keyword argument
+ 'force_refresh'`` — the exact CI failure this contract prevents.
+ """
+ monkeypatch.setattr(
+ "local_deep_research.llm.providers.discover_providers",
+ lambda: {},
+ )
+ assert providers.discover_providers() == {}
+
+
+def test_process_dump_policy_stub_is_active_during_tests(
+ isolate_server_process_dump_policy,
+):
+ """The autouse isolation stub shields test bodies from the OS policy.
+
+ The fixture returns the real enforcer while its stub is installed, so a
+ helper test can exercise the real function after replacing its OS
+ boundaries without any test changing the pytest process's policy.
+ """
+ assert process_dump_policy.enforce_process_dump_policy() is True
+ assert (
+ isolate_server_process_dump_policy
+ is not process_dump_policy.enforce_process_dump_policy
+ )
+ assert (
+ isolate_server_process_dump_policy.__name__
+ == "enforce_process_dump_policy"
+ )
diff --git a/tests/ui_tests/run_legacy_pkl_migration.sh b/tests/ui_tests/run_legacy_pkl_migration.sh
index a8c4a55ec4..ad83b89725 100755
--- a/tests/ui_tests/run_legacy_pkl_migration.sh
+++ b/tests/ui_tests/run_legacy_pkl_migration.sh
@@ -7,10 +7,11 @@
#
# 1. export a disposable LDR_DATA_DIR (default /tmp/ldr-migtest) and WIPE it,
# 2. run the Python seed (auth user + encrypted DB rows + legacy .faiss/.pkl),
-# 3. boot a THROWAWAY server on a spare port (default 5099) via
-# scripts/dev/restart_server.sh <PORT> --tmp — its startup runs phase-1,
+# 3. boot a THROWAWAY server on a spare port (default 5099) — its startup
+# runs phase-1,
# 4. run the Puppeteer test (login drives phase-2; then searches),
-# 5. tear the server down.
+# 5. tear the server down by the PID this script launched. (The server is
+# non-dumpable, so a same-user `fuser -k PORT/tcp` cannot find it.)
#
# NEVER touches the user's real dev server on 5001 or their real data dir.
#
@@ -22,6 +23,10 @@
# PORT (arg 1) throwaway server port (default 5099)
set -u
+# No job control (see scripts/dev/restart_server.sh): with it, the
+# background server would lead its own group, setsid would fork, and $!
+# would not be the group cleanup() signals.
+set +m
PORT="${1:-5099}"
export LDR_DATA_DIR="${LDR_DATA_DIR:-/tmp/ldr-migtest}"
@@ -37,11 +42,33 @@ if [ "${PORT}" = "5001" ]; then
exit 2
fi
+LOG_FILE="/tmp/ldr_server_${PORT}.log"
+SERVER_PID=""
+# Set when the server runs in its own process group (setsid available).
+SERVER_GROUP=0
+
# shellcheck disable=SC2329 # invoked indirectly via `trap cleanup EXIT` below
cleanup() {
+ [ -n "${SERVER_PID}" ] || return 0
echo ""
- echo "Tearing down throwaway server on port ${PORT}..."
- fuser -k "${PORT}/tcp" 2>/dev/null || true
+ echo "Tearing down throwaway server on port ${PORT} (PID ${SERVER_PID})..."
+ if [ "${SERVER_GROUP}" -eq 1 ]; then
+ kill -TERM -- "-${SERVER_PID}" 2>/dev/null
+ else
+ pkill -TERM -P "${SERVER_PID}" 2>/dev/null
+ kill -TERM "${SERVER_PID}" 2>/dev/null
+ fi
+ for _ in $(seq 1 15); do
+ kill -0 "${SERVER_PID}" 2>/dev/null || return 0
+ sleep 1
+ done
+ if [ "${SERVER_GROUP}" -eq 1 ]; then
+ kill -KILL -- "-${SERVER_PID}" 2>/dev/null
+ else
+ pkill -KILL -P "${SERVER_PID}" 2>/dev/null
+ kill -KILL "${SERVER_PID}" 2>/dev/null
+ fi
+ return 0
}
trap cleanup EXIT
@@ -60,7 +87,21 @@ if ! pdm run python tests/ui_tests/seed_legacy_pkl_migration.py; then
fi
echo "=== 3/4 Boot throwaway server on port ${PORT} (runs phase-1 at startup) ==="
-bash scripts/dev/restart_server.sh "${PORT}" --tmp >/dev/null 2>&1
+if (exec 3<>"/dev/tcp/127.0.0.1/${PORT}") 2>/dev/null; then
+ echo "Port ${PORT} is already in use; refusing to start a second server." >&2
+ exit 1
+fi
+launcher=(nohup)
+if command -v setsid >/dev/null 2>&1; then
+ # Own process group, so cleanup stops `pdm run` and the Python server
+ # it starts together. With job control off (`set +m` above) setsid
+ # exec's in place, so the group's ID is $!.
+ launcher+=(setsid)
+ SERVER_GROUP=1
+fi
+LDR_WEB_PORT="${PORT}" "${launcher[@]}" \
+ pdm run python -m local_deep_research.web.app >"${LOG_FILE}" 2>&1 &
+SERVER_PID=$!
# Wait for readiness.
ready=0
@@ -76,7 +117,7 @@ done
if [ "${ready}" -ne 1 ]; then
echo "Server failed to become ready on port ${PORT}" >&2
echo "--- last 40 log lines ---"
- tail -40 "/tmp/ldr_server_${PORT}.log" 2>/dev/null || true
+ tail -40 "${LOG_FILE}" 2>/dev/null || true
exit 1
fi
diff --git a/tests/web/test_process_dump_policy_startup.py b/tests/web/test_process_dump_policy_startup.py
new file mode 100644
index 0000000000..aed6541ce2
--- /dev/null
+++ b/tests/web/test_process_dump_policy_startup.py
@@ -0,0 +1,109 @@
+"""Server startup applies process policy before dispatching work."""
+
+import asyncio
+from unittest.mock import Mock
+
+import pytest
+
+from local_deep_research.security import process_dump_policy as policy
+from local_deep_research.web import app as web_app
+from local_deep_research.web import fastapi_app
+from local_deep_research.web.services import socketio_asgi
+
+
+def web_startup(monkeypatch):
+ monkeypatch.setattr(web_app, "_install_thread_excepthook", Mock())
+ monkeypatch.setattr(web_app, "config_logger", Mock())
+ monkeypatch.setattr(
+ web_app,
+ "load_server_config",
+ Mock(
+ return_value={
+ "host": "127.0.0.1",
+ "port": 5000,
+ "debug": False,
+ "use_https": False,
+ }
+ ),
+ )
+ from local_deep_research.vector_stores import legacy_cleanup
+
+ migrate = Mock()
+ serve = Mock()
+ monkeypatch.setattr(legacy_cleanup, "migrate_legacy_docstores", migrate)
+ monkeypatch.setattr(web_app, "_run_with_uvicorn", serve)
+ return migrate, serve
+
+
+def test_web_command_enforces_policy_before_uvicorn(monkeypatch, web_startup):
+ migrate, serve = web_startup
+ order = []
+ monkeypatch.setattr(
+ policy, "enforce_process_dump_policy", lambda: order.append("policy")
+ )
+ migrate.side_effect = lambda: order.append("migration")
+ serve.side_effect = lambda *_args: order.append("serve")
+
+ web_app.main()
+
+ assert order == ["policy", "migration", "serve"]
+
+
+def test_web_command_stops_when_policy_fails(monkeypatch, web_startup):
+ migrate, serve = web_startup
+ monkeypatch.setattr(
+ policy,
+ "enforce_process_dump_policy",
+ Mock(side_effect=policy.ProcessDumpPolicyError("synthetic refusal")),
+ )
+
+ with pytest.raises(policy.ProcessDumpPolicyError):
+ web_app.main()
+
+ migrate.assert_not_called()
+ serve.assert_not_called()
+
+
+def test_asgi_lifespan_enforces_policy_before_background_setup(monkeypatch):
+ order = []
+
+ class StopStartup(RuntimeError):
+ pass
+
+ def stop_before_setup(_loop):
+ order.append("background")
+ raise StopStartup
+
+ monkeypatch.setattr(
+ policy, "enforce_process_dump_policy", lambda: order.append("policy")
+ )
+ monkeypatch.setattr(socketio_asgi, "set_main_loop", stop_before_setup)
+
+ async def start():
+ async with fastapi_app.lifespan(fastapi_app.app):
+ pytest.fail("Startup should stop before acquiring resources")
+
+ with pytest.raises(StopStartup):
+ asyncio.run(start())
+
+ assert order == ["policy", "background"]
+
+
+def test_asgi_policy_failure_stops_before_background_setup(monkeypatch):
+ background = Mock()
+ monkeypatch.setattr(socketio_asgi, "set_main_loop", background)
+ monkeypatch.setattr(
+ policy,
+ "enforce_process_dump_policy",
+ Mock(side_effect=policy.ProcessDumpPolicyError("synthetic refusal")),
+ )
+
+ async def start():
+ async with fastapi_app.lifespan(fastapi_app.app):
+ pytest.fail("Startup should be refused")
+
+ with pytest.raises(policy.ProcessDumpPolicyError):
+ asyncio.run(start())
+
+ background.assert_not_called()
diff --git a/tests/web/test_startup_ordering_contracts.py b/tests/web/test_startup_ordering_contracts.py
index 15e142ed22..309532db3f 100644
--- a/tests/web/test_startup_ordering_contracts.py
+++ b/tests/web/test_startup_ordering_contracts.py
@@ -628,6 +628,7 @@ _GUARDED_STARTUP_STEPS = {
#: Steps deliberately left unguarded: if they raise, the lifespan raises,
#: uvicorn gets `lifespan.startup.failed` and refuses to serve.
_UNGUARDED_STARTUP_STEPS = (
+ "enforce_process_dump_policy",
"set_main_loop",
"init_lock",
"queue_processor.start",
@@ -675,8 +676,12 @@ def test_the_degraded_startup_census_is_pinned():
def test_the_load_bearing_startup_steps_still_abort_the_boot():
- """The three steps whose failure must stop the server from serving.
+ """The required steps whose failure must stop the server from serving.
+ ``enforce_process_dump_policy`` makes the process non-dumpable and
+ zeroes its core-file limit; serving after it failed would leave
+ session passwords and decrypted data exposed to core dumps and
+ same-user debuggers, so a failure refuses the boot instead.
``set_main_loop`` and ``init_lock`` decide whether background threads
can reach the browser at all; ``queue_processor.start`` is the only
drain path for queued research. Wrapping any of them would turn a hard