Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(docker): remap PUID/PGID for Unraid bind mounts (#1458)

Gao-Chenkai388399c3a1d1
diff --git a/CONTAINERIZATION.md b/CONTAINERIZATION.md
index b397e10df..113d08441 100644
--- a/CONTAINERIZATION.md
+++ b/CONTAINERIZATION.md
@@ -71,6 +71,28 @@ Open <http://127.0.0.1:3782>. The container creates
from the Web Settings page. Config, API keys, logs, workspace files,
memory, and knowledge bases persist in the `deeptutor-data` named volume.
+### Unraid / NAS bind mounts (PUID / PGID)
+
+Unraid and many NAS templates own appdata as a host user that is **not**
+UID 1000 (often `nobody:users` = 99:100, or a named share user). Those
+hosts also revert in-container `chown` on restart. The image still drops
+backend/frontend to the non-root `deeptutor` user; the entrypoint remaps
+that user's UID/GID to match the volume:
+
+```bash
+docker run --rm --name deeptutor \
+ -e PUID=99 -e PGID=100 \
+ -p 127.0.0.1:3782:3782 \
+ -v /mnt/user/appdata/deeptutor:/app/data \
+ ghcr.io/hkuds/deeptutor:latest
+```
+
+If the runtime user still cannot write `/app/data`, the entrypoint
+**exits** with an owner/mode message instead of starting and later
+reporting `Knowledge base not initialized (llamaindex)`. Rootless Podman
+skips the remap (`CAP_SETUID` is absent) and keeps the current user.
+`PUID=0` / `PGID=0` are rejected so the app never runs as root.
+
### Select a host Content Workspace
The application data mount contains private settings, credentials, databases,
@@ -467,6 +489,12 @@ need).
is the userns-mapped root problem; switch to a bind mount on a host
directory you own, or use `:U` on the volume mount.
+**`Data directory is not writable` / `Knowledge base not initialized
+(llamaindex)` on Unraid.** The app runs as the non-root `deeptutor` user.
+Set `PUID`/`PGID` to the host owner of the bind mount (see [Unraid / NAS
+bind mounts](#unraid--nas-bind-mounts-puid--pgid)). Do not run the
+container as root to work around this.
+
**`sed -i` errors on a fresh image.** There shouldn't be any — the
runtime no longer mutates the bundle. The URL is forwarded at request
time. If you see one, you are probably on an older image; pull
@@ -482,9 +510,11 @@ renormalized on save.
## Security notes
-- The image drops privileges to a non-root `deeptutor` user (UID 1000)
- before starting `supervisord`. Anything that runs as root is the
- entrypoint, the chown, and the env-var export.
+- The image drops privileges to a non-root `deeptutor` user (UID 1000
+ by default, or `PUID`/`PGID` under rootful Docker) before starting
+ `supervisord`. Anything that runs as root is the entrypoint, an
+ attempted chown of `/app/data`, and the env-var export. The app
+ processes themselves never stay root.
- `read_only: true` plus `tmpfs:` for the expected writable system
directories means the container's root filesystem is immutable at
runtime. A process that tries to write outside the listed tmpfs
diff --git a/Dockerfile b/Dockerfile
index 01d1d8b85..b150544ac 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -188,13 +188,15 @@ RUN mkdir -p \
data/user/logs \
data/knowledge_bases
-# Bake a non-root user (UID 1000) for the supervisord programs. supervisord
-# itself runs as PID 1's UID — root under rootful Docker/Podman, or UID 1000
-# under rootless podman + `userns_mode: keep-id` (where PID 1 is the host
-# user). Each child (backend/frontend) is dropped to this `deeptutor` user via
-# the per-program `user=deeptutor` directive, so the app processes stay
-# non-root in either runtime. UID 1000 also matches the host user under
-# keep-id with a bind mount on ./data.
+# Bake a non-root user (UID 1000 by default) for the supervisord programs.
+# supervisord itself runs as PID 1's UID — root under rootful Docker/Podman,
+# or the host UID under rootless podman + `userns_mode: keep-id`. Each child
+# (backend/frontend) is dropped to this `deeptutor` user via the per-program
+# `user=deeptutor` directive, so the app processes stay non-root. The
+# entrypoint remaps this user's UID/GID to PUID/PGID when PID 1 is root, so
+# Unraid/NAS bind mounts owned by a host user other than 1000 stay writable
+# without running the app as root. Under rootless keep-id the remap is
+# skipped (no CAP_SETUID) and UID 1000 matches the typical host user.
RUN groupadd --system --gid 1000 deeptutor \
&& useradd --system --uid 1000 --gid 1000 --no-create-home --shell /usr/sbin/nologin deeptutor \
&& chown -R deeptutor:deeptutor /app/data /app/web/.next
@@ -356,6 +358,40 @@ for key in \
unset "$key"
done
+# Runtime user for supervisord children (`user=deeptutor`). Default 1000:1000
+# matches ordinary Docker and rootless keep-id. Unraid/NAS bind mounts are
+# often owned by another host user that *reverts* in-container chown; set
+# PUID/PGID to that owner instead of running the app as root.
+PUID="${PUID:-${DEEPTUTOR_PUID:-1000}}"
+PGID="${PGID:-${DEEPTUTOR_PGID:-1000}}"
+export PUID PGID
+
+if [ "$(id -u)" -eq 0 ]; then
+ case "$PUID$PGID" in
+ ''|*[!0-9]*)
+ echo "❌ PUID and PGID must be non-root integers (got PUID=${PUID} PGID=${PGID})"
+ exit 1
+ ;;
+ esac
+ if [ "$PUID" -eq 0 ] || [ "$PGID" -eq 0 ]; then
+ echo "❌ PUID/PGID must be non-root so the app does not run as root (got PUID=${PUID} PGID=${PGID})"
+ exit 1
+ fi
+ echo "👤 Runtime user deeptutor → uid=${PUID} gid=${PGID}"
+ if [ "$(id -g deeptutor)" != "$PGID" ]; then
+ if getent group "$PGID" >/dev/null 2>&1; then
+ usermod -g "$PGID" deeptutor
+ else
+ groupmod -o -g "$PGID" deeptutor
+ fi
+ fi
+ if [ "$(id -u deeptutor)" != "$PUID" ]; then
+ usermod -o -u "$PUID" deeptutor
+ fi
+else
+ echo "👤 Rootless runtime uid=$(id -u) gid=$(id -g); skipping PUID remap"
+fi
+
# Initialize user data directories if empty
echo "📁 Checking data directories..."
echo " Ensuring runtime settings and workspace layout..."
@@ -363,11 +399,27 @@ python -c "
from pathlib import Path
from deeptutor.services.setup import init_user_directories
init_user_directories(Path('/app'))
-" 2>/dev/null || echo " ⚠️ Directory initialization skipped (will be created on first use)"
+" || echo " ⚠️ Directory initialization failed (volume writability check follows)"
+
+# Re-chown /app/data to the (possibly remapped) deeptutor user. Named Docker
+# volumes are typically root-owned and need this. Bind mounts on Unraid/NFS
+# often reject chown and keep the host owner — do NOT swallow that with
+# `|| true`; warn and let the writability probe fail-fast if the runtime
+# user still cannot write.
+if [ "$(id -u)" -eq 0 ]; then
+ if chown -R deeptutor:deeptutor /app/data; then
+ echo " ✅ /app/data owned by deeptutor (uid=${PUID} gid=${PGID})"
+ else
+ echo " ⚠️ chown /app/data failed (common on Unraid/NFS bind mounts that reject ownership changes)."
+ echo " The app will run as uid=${PUID} gid=${PGID}; the volume must already be writable by that user."
+ echo " Set PUID/PGID to the host owner of the bind mount rather than running as root."
+ fi
+else
+ echo " Skipping chown under rootless runtime"
+fi
-# Idempotent: re-chown /app/data so the unprivileged `deeptutor` user (UID 1000)
-# owns it. Cheap on no-op; the only first-start cost is one stat per file.
-chown -R deeptutor:deeptutor /app/data 2>/dev/null || true
+echo "📁 Verifying /app/data is writable by the runtime user..."
+python -c "from deeptutor.services.setup.data_volume import check_container_data_volume; check_container_data_volume()"
# Optional dependencies (#762). A container is disposable, so anything
# `docker exec … pip install`ed into a running one is gone at the next
@@ -402,7 +454,11 @@ fi
if [ -n "${DEEPTUTOR_EXTRAS:-}" ]; then
echo "🔧 Ensuring Python extras: ${DEEPTUTOR_EXTRAS}"
python /app/scripts/install_extras.py "${DEEPTUTOR_EXTRAS}" || true
- chown -R deeptutor:deeptutor "$PIP_CACHE_DIR" 2>/dev/null || true
+ if [ "$(id -u)" -eq 0 ]; then
+ if ! chown -R deeptutor:deeptutor "$PIP_CACHE_DIR"; then
+ echo " ⚠️ chown pip cache failed; continuing if the runtime user can still write it"
+ fi
+ fi
fi
echo "⚙️ Loading runtime JSON settings..."
diff --git a/deeptutor/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.py
index 8212af3b9..a0c9cf9c4 100644
--- a/deeptutor/knowledge/add_documents.py
+++ b/deeptutor/knowledge/add_documents.py
@@ -11,6 +11,7 @@ import hashlib
import itertools
import json
import logging
+import os
from pathlib import Path
import shutil
from typing import TYPE_CHECKING, List, Optional
@@ -24,9 +25,15 @@ from deeptutor.services.rag.factory import (
normalize_provider_name,
)
from deeptutor.services.rag.file_routing import FileTypeRouter
+from deeptutor.services.rag.index_probe import provider_failure_summary
from deeptutor.services.rag.index_versioning import list_kb_versions
from deeptutor.services.rag.provider_binding import resolve_bound_provider
from deeptutor.services.rag.service import RAGService
+from deeptutor.services.setup.data_volume import (
+ DataVolumePermissionError,
+ ensure_data_volume_writable,
+ format_data_volume_permission_error,
+)
logger = logging.getLogger(__name__)
@@ -171,6 +178,10 @@ class DocumentAdder:
self.legacy_rag_storage_dir = self.kb_dir / "rag_storage"
self.metadata_file = self.kb_dir / "metadata.json"
+ # Fail on UID-mismatched / unwritable volumes before the "not initialized"
+ # check, which otherwise hides Unraid bind-mount permission errors.
+ ensure_data_volume_writable(self.kb_dir)
+
# Incremental adds must use the engine DeepTutor has bound to this KB. An
# explicit rag_provider (from the API, already matched against the KB)
# wins; otherwise use the shared binding resolver.
@@ -190,10 +201,21 @@ class DocumentAdder:
f"Knowledge base '{kb_name}' uses legacy index format and requires reindex before incremental add"
)
- allows_lightrag_bootstrap = self.rag_provider == LIGHTRAG_PROVIDER and not list_kb_versions(
- self.kb_dir
- )
- if not has_provider_index and not allows_lightrag_bootstrap:
+ has_any_version = bool(list_kb_versions(self.kb_dir))
+ # Empty LlamaIndex/LightRAG KBs (created with no documents) have no
+ # index yet; add_documents() creates one. Do not report that as
+ # "not initialized".
+ allows_empty_bootstrap = self.rag_provider in {
+ DEFAULT_PROVIDER,
+ LIGHTRAG_PROVIDER,
+ } and not has_any_version
+ if not has_provider_index and not allows_empty_bootstrap:
+ summary = provider_failure_summary(self.kb_dir, self.rag_provider)
+ if summary:
+ raise ValueError(
+ f"Knowledge base '{kb_name}' has no ready {self.rag_provider} "
+ f"index: {summary}"
+ )
raise ValueError(f"Knowledge base not initialized ({self.rag_provider}): {kb_name}")
self.api_key = api_key
@@ -357,6 +379,13 @@ class DocumentAdder:
error = "Provider returned failure without details."
failures.append(DocumentIndexFailure(doc_file, error))
logger.error(f"Failed to index: {doc_file.name}")
+ except PermissionError as e:
+ logger.exception("Permission denied while indexing %s: %s", doc_file.name, e)
+ raise DataVolumePermissionError(
+ format_data_volume_permission_error(
+ self.kb_dir, uid=os.geteuid(), gid=os.getegid(), cause=e
+ )
+ ) from e
except Exception as e:
logger.exception(f"Failed {doc_file.name}: {e}")
failures.append(DocumentIndexFailure(doc_file, str(e)))
diff --git a/deeptutor/knowledge/initializer.py b/deeptutor/knowledge/initializer.py
index 33eb935b2..7da28613d 100644
--- a/deeptutor/knowledge/initializer.py
+++ b/deeptutor/knowledge/initializer.py
@@ -8,6 +8,7 @@ import asyncio
from datetime import datetime
import json
import logging
+import os
from pathlib import Path
import shutil
from typing import TYPE_CHECKING, Optional
@@ -23,6 +24,11 @@ from deeptutor.services.file_io import atomic_write_json
from deeptutor.services.rag.factory import normalize_provider_name
from deeptutor.services.rag.file_routing import FileTypeRouter
from deeptutor.services.rag.service import RAGService
+from deeptutor.services.setup.data_volume import (
+ DataVolumePermissionError,
+ ensure_data_volume_writable,
+ format_data_volume_permission_error,
+)
logger = logging.getLogger(__name__)
@@ -118,6 +124,7 @@ class KnowledgeBaseInitializer:
def create_directory_structure(self) -> None:
"""Create KB directory structure."""
logger.info(f"Creating directory structure for knowledge base: {self.kb_name}")
+ ensure_data_volume_writable(self.base_dir)
for dir_path in [
self.raw_dir,
@@ -241,6 +248,17 @@ class KnowledgeBaseInitializer:
self.kb_name,
exc_info=True,
)
+ except PermissionError as e:
+ error_msg = format_data_volume_permission_error(
+ self.kb_dir, uid=os.geteuid(), gid=os.getegid(), cause=e
+ )
+ logger.error("Error processing documents: %s", error_msg)
+ self.progress_tracker.update(
+ ProgressStage.ERROR,
+ message_key="Failed to process documents",
+ error=error_msg,
+ )
+ raise DataVolumePermissionError(error_msg) from e
except Exception as e:
error_msg = str(e)
logger.error(f"Error processing documents: {error_msg}")
diff --git a/deeptutor/services/setup/data_volume.py b/deeptutor/services/setup/data_volume.py
new file mode 100644
index 000000000..49b718f5e
--- /dev/null
+++ b/deeptutor/services/setup/data_volume.py
@@ -0,0 +1,168 @@
+"""Probe whether the runtime data volume is writable by the app user.
+
+The container image bakes a ``deeptutor`` user at UID/GID 1000 and drops
+supervisord children to that user. Bind mounts on Unraid / NAS hosts are often
+owned by a different host UID (``PUID``/``PGID``). A silent ``chown || true``
+then leaves the volume unwritable, and later KB indexing is reported as
+"Knowledge base not initialized" instead of a permission error.
+
+This helper is the fail-fast seam used by the container entrypoint,
+:class:`~deeptutor.knowledge.initializer.KnowledgeBaseInitializer`, and
+:class:`~deeptutor.knowledge.add_documents.DocumentAdder`.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+import stat
+from typing import Final
+
+DEFAULT_RUNTIME_UID: Final[int] = 1000
+DEFAULT_RUNTIME_GID: Final[int] = 1000
+_PROBE_PREFIX: Final[str] = ".deeptutor-write-probe"
+
+
+class DataVolumePermissionError(PermissionError):
+ """The data volume cannot be written by the process that will run the app."""
+
+
+def parse_id(value: str | None, *, default: int, name: str) -> int:
+ """Parse a PUID/PGID-style identifier, rejecting root and non-integers."""
+ raw = (value or "").strip() or str(default)
+ try:
+ parsed = int(raw)
+ except ValueError as exc:
+ raise ValueError(f"{name} must be a non-root integer, got {value!r}") from exc
+ if parsed <= 0:
+ raise ValueError(f"{name} must be a non-root integer, got {parsed}")
+ return parsed
+
+
+def resolve_runtime_ids(
+ *,
+ puid: str | None = None,
+ pgid: str | None = None,
+ euid: int | None = None,
+ egid: int | None = None,
+) -> tuple[int, int]:
+ """Return the UID/GID the app processes should run as.
+
+ Rootless (non-zero euid) keeps the current process identity so we do not
+ try to ``setuid`` without ``CAP_SETUID``. Rootful Docker remaps to
+ ``PUID``/``PGID`` (default 1000/1000).
+ """
+ current_uid = os.geteuid() if euid is None else euid
+ current_gid = os.getegid() if egid is None else egid
+ if current_uid != 0:
+ return current_uid, current_gid
+ return (
+ parse_id(puid, default=DEFAULT_RUNTIME_UID, name="PUID"),
+ parse_id(pgid, default=DEFAULT_RUNTIME_GID, name="PGID"),
+ )
+
+
+def describe_path_ownership(path: Path) -> str:
+ """Human-readable owner/mode for *path*, or ``unreadable``."""
+ try:
+ info = path.stat()
+ except OSError:
+ return "unreadable"
+ mode = stat.S_IMODE(info.st_mode)
+ return f"uid={info.st_uid} gid={info.st_gid} mode={mode:04o}"
+
+
+def format_data_volume_permission_error(
+ path: Path,
+ *,
+ uid: int,
+ gid: int,
+ cause: BaseException | None = None,
+) -> str:
+ """Explain a UID mismatch in terms operators can act on (PUID/PGID)."""
+ owner = describe_path_ownership(path)
+ cause_txt = f" ({cause})" if cause else ""
+ return (
+ f"Data directory is not writable by the running process "
+ f"(euid={uid}, egid={gid}): {path} is {owner}.{cause_txt} "
+ "On Unraid/NAS bind mounts, set PUID and PGID to the host owner of the "
+ "volume instead of chowning the mount. The app stays a non-root user; "
+ "the container remaps `deeptutor` to those ids."
+ )
+
+
+def ensure_data_volume_writable(
+ path: Path | str,
+ *,
+ uid: int | None = None,
+ gid: int | None = None,
+) -> None:
+ """Create *path* if needed and fail if the runtime user cannot write it.
+
+ When this process is root and *uid*/*gid* differ from the current euid,
+ the probe forks and drops to that identity so a root-only write does not
+ mask an Unraid bind-mount that UID 1000 cannot use. Non-root callers
+ (the FastAPI backend) probe as themselves.
+ """
+ target = Path(path)
+ probe_uid = os.geteuid() if uid is None else uid
+ probe_gid = os.getegid() if gid is None else gid
+ try:
+ target.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ raise DataVolumePermissionError(
+ format_data_volume_permission_error(target, uid=probe_uid, gid=probe_gid, cause=exc)
+ ) from exc
+
+ drop_privs = (
+ os.geteuid() == 0
+ and probe_uid != 0
+ and (probe_uid != os.geteuid() or probe_gid != os.getegid())
+ and hasattr(os, "fork")
+ and hasattr(os, "setuid")
+ )
+ if drop_privs:
+ _ensure_writable_as(target, probe_uid, probe_gid)
+ return
+ _try_write_or_raise(target, probe_uid, probe_gid)
+
+
+def check_container_data_volume(data_root: Path | str | None = None) -> None:
+ """Entrypoint fail-fast: ``/app/data`` and ``knowledge_bases`` must be writable."""
+ root = Path(data_root or "/app/data")
+ uid, gid = resolve_runtime_ids(
+ puid=os.environ.get("PUID") or os.environ.get("DEEPTUTOR_PUID"),
+ pgid=os.environ.get("PGID") or os.environ.get("DEEPTUTOR_PGID"),
+ )
+ for target in (root, root / "knowledge_bases"):
+ ensure_data_volume_writable(target, uid=uid, gid=gid)
+
+
+def _try_write_or_raise(path: Path, uid: int, gid: int) -> None:
+ probe = path / f"{_PROBE_PREFIX}-{os.getpid()}"
+ try:
+ probe.write_text("ok", encoding="utf-8")
+ probe.unlink(missing_ok=True)
+ except OSError as exc:
+ probe.unlink(missing_ok=True)
+ raise DataVolumePermissionError(
+ format_data_volume_permission_error(path, uid=uid, gid=gid, cause=exc)
+ ) from exc
+
+
+def _ensure_writable_as(path: Path, uid: int, gid: int) -> None:
+ """Fork, drop to *uid*/*gid*, and probe. Parent raises on child failure."""
+ pid = os.fork()
+ if pid == 0: # pragma: no cover - child process
+ try:
+ os.setgid(gid)
+ os.setuid(uid)
+ _try_write_or_raise(path, uid, gid)
+ os._exit(0)
+ except OSError:
+ os._exit(1)
+ _, status = os.waitpid(pid, 0)
+ if not os.WIFEXITED(status) or os.WEXITSTATUS(status) != 0:
+ raise DataVolumePermissionError(
+ format_data_volume_permission_error(path, uid=uid, gid=gid)
+ )
diff --git a/docker-compose.ghcr.yml b/docker-compose.ghcr.yml
index e266fd7c2..f8caa66ad 100644
--- a/docker-compose.ghcr.yml
+++ b/docker-compose.ghcr.yml
@@ -94,6 +94,10 @@ services:
# Optional entries can be added to the environment list above.
# - DEEPTUTOR_EXTRAS=math-animator,partners
# - DEEPTUTOR_APT_PACKAGES=ffmpeg
+ # Unraid / NAS bind mounts: PUID/PGID remap the unprivileged deeptutor
+ # user to the host owner of ./data. Do not run the app as root.
+ # - PUID=99
+ # - PGID=100
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:${DEEPTUTOR_DOCKER_BACKEND_PORT:-8001}/health/ready"]
diff --git a/docker-compose.yml b/docker-compose.yml
index 6fe325072..076a6917d 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -117,6 +117,12 @@ services:
# - DEEPTUTOR_EXTRAS=math-animator,partners
# - DEEPTUTOR_APT_PACKAGES=ffmpeg
+ # Unraid / NAS bind mounts: set these to the host owner of ./data
+ # instead of chowning the volume or running the app as root.
+ # The entrypoint remaps the unprivileged `deeptutor` user to these ids.
+ # - PUID=99
+ # - PGID=100
+
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:${DEEPTUTOR_DOCKER_BACKEND_PORT:-8001}/health/ready"]
interval: 30s
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index 97f3462df..ba9a7f235 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -990,6 +990,59 @@ def test_upload_task_marks_provider_failures_as_error(monkeypatch, tmp_path: Pat
assert entry["progress"]["indexed_count"] == 0
+def test_upload_task_bootstraps_empty_llamaindex_kb(monkeypatch, tmp_path: Path) -> None:
+ """Create-KB-then-upload (issue #1458) must index instead of raising
+ ``Knowledge base not initialized (llamaindex)``.
+ """
+ base_dir = tmp_path / "knowledge_bases"
+ kb_dir = base_dir / "Medicine"
+ raw_dir = kb_dir / "raw"
+ raw_dir.mkdir(parents=True)
+ (base_dir / "kb_config.json").write_text(
+ json.dumps(
+ {
+ "knowledge_bases": {
+ "Medicine": {
+ "path": "Medicine",
+ "rag_provider": "llamaindex",
+ "status": "ready",
+ }
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ source = tmp_path / "note.txt"
+ source.write_text("hello", encoding="utf-8")
+
+ class _SucceedingRagService:
+ def __init__(self, *_args, **_kwargs) -> None:
+ pass
+
+ async def add_documents(self, *_args, **_kwargs) -> bool:
+ return True
+
+ monkeypatch.setattr(
+ "deeptutor.knowledge.add_documents.RAGService",
+ _SucceedingRagService,
+ )
+
+ asyncio.run(
+ knowledge_router_module.run_upload_processing_task(
+ kb_name="Medicine",
+ base_dir=str(base_dir),
+ uploaded_file_paths=[str(source)],
+ task_id="empty-llamaindex-upload",
+ rag_provider="llamaindex",
+ )
+ )
+
+ persisted = json.loads((base_dir / "kb_config.json").read_text(encoding="utf-8"))
+ entry = persisted["knowledge_bases"]["Medicine"]
+ assert entry["status"] != "error"
+ assert "not initialized" not in str(entry.get("last_error") or "")
+
+
def test_upload_task_with_folder_root_preserves_subfolder_structure(
monkeypatch, tmp_path: Path
) -> None:
diff --git a/tests/knowledge/test_document_adder_provider.py b/tests/knowledge/test_document_adder_provider.py
index 680ba25ca..ab49499a6 100644
--- a/tests/knowledge/test_document_adder_provider.py
+++ b/tests/knowledge/test_document_adder_provider.py
@@ -4,6 +4,8 @@ import asyncio
import json
from pathlib import Path
+import pytest
+
from deeptutor.knowledge.add_documents import (
DocumentAdder,
RawDocumentRemoval,
@@ -91,6 +93,59 @@ def test_document_adder_allows_empty_lightrag_kb_to_bootstrap(tmp_path: Path) ->
assert adder.raw_dir.is_dir()
+def test_document_adder_allows_empty_llamaindex_kb_to_bootstrap(tmp_path: Path) -> None:
+ """Create-then-upload (no files at create time) must not look uninitialized."""
+ (tmp_path / "Medicine").mkdir()
+
+ adder = DocumentAdder(
+ kb_name="Medicine",
+ base_dir=str(tmp_path),
+ rag_provider="llamaindex",
+ )
+
+ assert adder.rag_provider == "llamaindex"
+ assert adder.raw_dir.is_dir()
+
+
+def test_document_adder_unready_index_reports_probe_summary(tmp_path: Path) -> None:
+ kb_dir = tmp_path / "kb"
+ (kb_dir / "raw").mkdir(parents=True)
+ version = kb_dir / "version-1"
+ version.mkdir()
+ (version / "meta.json").write_text(
+ '{"provider": "llamaindex", "signature": "sig", "version": "version-1"}',
+ encoding="utf-8",
+ )
+
+ with pytest.raises(ValueError, match="no ready llamaindex index") as caught:
+ DocumentAdder(kb_name="kb", base_dir=str(tmp_path), rag_provider="llamaindex")
+
+ assert "not initialized" not in str(caught.value)
+ assert "docstore.json" in str(caught.value)
+
+
+def test_document_adder_unwritable_kb_is_not_reported_as_uninitialized(
+ tmp_path: Path, monkeypatch
+) -> None:
+ kb_dir = tmp_path / "Medicine"
+ kb_dir.mkdir()
+ monkeypatch.setattr(
+ "deeptutor.knowledge.add_documents.ensure_data_volume_writable",
+ lambda _path: (_ for _ in ()).throw(
+ PermissionError(
+ "Data directory is not writable by the running process "
+ "(euid=1000, egid=1000): /app/data/knowledge_bases/Medicine "
+ "is uid=99 gid=100 mode=0755."
+ )
+ ),
+ )
+
+ with pytest.raises(PermissionError, match="not writable") as caught:
+ DocumentAdder(kb_name="Medicine", base_dir=str(tmp_path), rag_provider="llamaindex")
+
+ assert "not initialized" not in str(caught.value)
+
+
def test_process_new_documents_returns_failures_without_marking_processed(
monkeypatch, tmp_path: Path
) -> None:
diff --git a/tests/knowledge/test_kb_directory_layout.py b/tests/knowledge/test_kb_directory_layout.py
index ee58c30ea..68a894356 100644
--- a/tests/knowledge/test_kb_directory_layout.py
+++ b/tests/knowledge/test_kb_directory_layout.py
@@ -2,6 +2,8 @@ from __future__ import annotations
from pathlib import Path
+import pytest
+
from deeptutor.knowledge.add_documents import DocumentAdder
from deeptutor.knowledge.initializer import KnowledgeBaseInitializer
@@ -38,3 +40,17 @@ def test_document_adder_does_not_create_compatibility_dirs(tmp_path: Path) -> No
assert not (kb_dir / "index_versions").exists()
assert not (kb_dir / "images").exists()
assert not (kb_dir / "content_list").exists()
+
+
+def test_initializer_unwritable_base_dir_fail_fasts(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr(
+ "deeptutor.knowledge.initializer.ensure_data_volume_writable",
+ lambda _path: (_ for _ in ()).throw(
+ PermissionError(
+ "Data directory is not writable by the running process (euid=1000, egid=1000)"
+ )
+ ),
+ )
+ initializer = KnowledgeBaseInitializer(kb_name="demo", base_dir=str(tmp_path))
+ with pytest.raises(PermissionError, match="not writable"):
+ initializer.create_directory_structure()
diff --git a/tests/scripts/test_docker_compose.py b/tests/scripts/test_docker_compose.py
index befa0e072..b1f2896bd 100644
--- a/tests/scripts/test_docker_compose.py
+++ b/tests/scripts/test_docker_compose.py
@@ -213,6 +213,23 @@ def test_supervisord_runs_as_root_with_unprivileged_children() -> None:
)
+def test_entrypoint_fail_fasts_on_unwritable_data_volume_without_root_app() -> None:
+ """Unraid bind mounts owned by a non-1000 host user must not start the app
+ as root, and chown failure must not be swallowed into a later misleading
+ 'Knowledge base not initialized' error (#1458).
+ """
+ root = Path(__file__).resolve().parents[2]
+ content = (root / "Dockerfile").read_text(encoding="utf-8")
+
+ assert "chown -R deeptutor:deeptutor /app/data 2>/dev/null || true" not in content
+ assert "check_container_data_volume" in content
+ assert 'PUID="${PUID:-${DEEPTUTOR_PUID:-1000}}"' in content
+ assert "skipping PUID remap" in content
+ assert "PUID/PGID must be non-root" in content
+ assert "gosu deeptutor /usr/bin/supervisord" not in content
+ assert "user=deeptutor" in content
+
+
def test_frontend_api_is_url_agnostic_passthrough() -> None:
"""web/lib/api.ts no longer carries a build-time API base or a placeholder
token; apiUrl/wsUrl are pass-throughs and the Next.js middleware
diff --git a/tests/services/setup/test_data_volume.py b/tests/services/setup/test_data_volume.py
new file mode 100644
index 000000000..b0a40974f
--- /dev/null
+++ b/tests/services/setup/test_data_volume.py
@@ -0,0 +1,101 @@
+"""Data-volume writability probe for Unraid / UID-mismatched bind mounts."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+
+from deeptutor.services.setup.data_volume import (
+ DataVolumePermissionError,
+ check_container_data_volume,
+ ensure_data_volume_writable,
+ format_data_volume_permission_error,
+ parse_id,
+ resolve_runtime_ids,
+)
+
+
+def test_parse_id_rejects_root_and_non_integers() -> None:
+ assert parse_id(None, default=1000, name="PUID") == 1000
+ assert parse_id("99", default=1000, name="PUID") == 99
+ with pytest.raises(ValueError, match="non-root"):
+ parse_id("0", default=1000, name="PUID")
+ with pytest.raises(ValueError, match="non-root"):
+ parse_id("alan", default=1000, name="PUID")
+
+
+def test_resolve_runtime_ids_keeps_rootless_identity() -> None:
+ uid, gid = resolve_runtime_ids(puid="99", pgid="100", euid=501, egid=20)
+ assert (uid, gid) == (501, 20)
+
+
+def test_resolve_runtime_ids_uses_puid_when_root() -> None:
+ uid, gid = resolve_runtime_ids(puid="99", pgid="100", euid=0, egid=0)
+ assert (uid, gid) == (99, 100)
+
+
+def test_permission_error_names_uid_mismatch_and_puid_hint(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr(
+ "deeptutor.services.setup.data_volume.describe_path_ownership",
+ lambda _path: "uid=99 gid=100 mode=0755",
+ )
+ message = format_data_volume_permission_error(tmp_path / "knowledge_bases", uid=1000, gid=1000)
+
+ assert "euid=1000" in message
+ assert "uid=99 gid=100 mode=0755" in message
+ assert "PUID" in message
+ assert "PGID" in message
+ assert "not writable" in message
+
+
+def test_ensure_writable_succeeds_on_owned_directory(tmp_path: Path) -> None:
+ target = tmp_path / "data" / "knowledge_bases"
+ ensure_data_volume_writable(target)
+ assert target.is_dir()
+ assert not any(target.glob(".deeptutor-write-probe-*"))
+
+
+def test_ensure_unwritable_directory_fail_fasts(tmp_path: Path) -> None:
+ if hasattr(os, "geteuid") and os.geteuid() == 0:
+ pytest.skip("root bypasses directory mode bits")
+ target = tmp_path / "locked"
+ target.mkdir()
+ target.chmod(0o555)
+ try:
+ with pytest.raises(DataVolumePermissionError, match="not writable"):
+ ensure_data_volume_writable(target)
+ finally:
+ target.chmod(0o755)
+
+
+def test_check_container_data_volume_probes_knowledge_bases(
+ tmp_path: Path, monkeypatch
+) -> None:
+ data_root = tmp_path / "app-data"
+ monkeypatch.setenv("PUID", "1000")
+ monkeypatch.setenv("PGID", "1000")
+ check_container_data_volume(data_root)
+ assert (data_root / "knowledge_bases").is_dir()
+
+
+def test_check_container_data_volume_fail_fasts_when_unwritable(
+ tmp_path: Path, monkeypatch
+) -> None:
+ data_root = tmp_path / "app-data"
+ data_root.mkdir()
+ kb_root = data_root / "knowledge_bases"
+ kb_root.mkdir()
+
+ def _boom(path, **_kwargs):
+ raise DataVolumePermissionError(
+ format_data_volume_permission_error(Path(path), uid=1000, gid=1000)
+ )
+
+ monkeypatch.setattr(
+ "deeptutor.services.setup.data_volume.ensure_data_volume_writable",
+ _boom,
+ )
+ with pytest.raises(DataVolumePermissionError, match="not writable"):
+ check_container_data_volume(data_root)