Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ recorded after the fact rather than backdated to look contemporaneous.

## Unreleased

**`sgm-doctor`: four edge-case fixes from review.** Thanks @Kaap10 (#110): imports `brain_ask` lazily so a missing or broken NumPy prints a plain-words `[FAIL]` instead of an unhandled traceback; marks missing transitive dependencies of `sentence-transformers` as `[FAIL]` rather than a missing extra warning; isolates custom `HF_HUB_CACHE` / `HF_HOME` directories without mixing in default caches and respects `XDG_CACHE_HOME`; and validates index `.npy` array shape against metadata chunks so truncated or 0-byte index files report `[FAIL]` (closes #107).

**Credits that predate the credit gate.** `scripts/credit_gate.py` checks merges since 2026-10-19, so two earlier outside contributions were never named here: @HeaTTap wrote the first tests for `looks_like_entity()` and `_links_in()` (#6, shipped in bench-v0.1), and @Deva4287 corrected the README test status (#7, same release). Recorded now so the changelog names every outside author.

## v0.3.8 - 2026-11-10
Expand Down
74 changes: 61 additions & 13 deletions src/sqlite_graph_memory/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@
import sys
from pathlib import Path

from sqlite_graph_memory import brain_ask

OK, WARN, FAIL = 'ok', 'warn', 'fail'
MARK = {OK: '[ok] ', WARN: '[warn]', FAIL: '[FAIL]'}
FEEDBACK = brain_ask.FEEDBACK_URL
FEEDBACK = 'https://github.com/tonydzi/sqlite-graph-memory/discussions/categories/ideas'


def check_python(version=None):
Expand All @@ -40,7 +38,12 @@ def _intel_mac(system=None, machine=None):

def check_embeddings(system=None, machine=None):
"""The heavy half. Without it the graph and the SQLite parts work, indexing and recall do not."""
if brain_ask.backend() == 'onnx':
try:
from sqlite_graph_memory import brain_ask
is_onnx = (brain_ask.backend() == 'onnx')
except Exception:
is_onnx = (os.getenv('SGM_BACKEND', '').strip().lower() == 'onnx')
if is_onnx:
try:
import onnxruntime
import tokenizers # noqa: F401
Expand All @@ -59,9 +62,13 @@ def check_embeddings(system=None, machine=None):
import torch
import sentence_transformers
except ModuleNotFoundError as exc:
return (WARN, 'The embeddings extra is not installed (%s missing).' % exc.name,
'Only needed to index and recall. Install it with: pip install "sqlite-graph-memory[lite]"'
' (or [embeddings] for torch and a GPU)')
if exc.name in ('torch', 'sentence_transformers'):
return (WARN, 'The embeddings extra is not installed (%s missing).' % exc.name,
'Only needed to index and recall. Install it with: pip install "sqlite-graph-memory[lite]"'
' (or [embeddings] for torch and a GPU)')
why = '%s: %s' % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else '')
return FAIL, 'torch or sentence-transformers fails to import (%s).' % why, \
'Reinstall in a fresh virtualenv: pip install --force-reinstall "sqlite-graph-memory[embeddings]"'
except Exception as exc: # torch dies at import on a numpy it was not built for
why = '%s: %s' % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else '')
if _intel_mac(system, machine) and np_major >= 2:
Expand All @@ -77,16 +84,31 @@ def check_embeddings(system=None, machine=None):


def _hf_cache_dirs():
roots = [os.getenv('HF_HUB_CACHE'), os.getenv('SENTENCE_TRANSFORMERS_HOME')]
hf_home = os.getenv('HF_HOME') or str(Path.home() / '.cache' / 'huggingface')
roots.append(str(Path(hf_home) / 'hub'))
return [Path(r) for r in roots if r]
roots = []
if os.getenv('HF_HUB_CACHE'):
roots.append(Path(os.environ['HF_HUB_CACHE']))
elif os.getenv('HF_HOME'):
roots.append(Path(os.environ['HF_HOME']) / 'hub')
else:
xdg = os.getenv('XDG_CACHE_HOME')
base = Path(xdg) if xdg else Path.home() / '.cache'
roots.append(base / 'huggingface' / 'hub')

if os.getenv('SENTENCE_TRANSFORMERS_HOME'):
roots.append(Path(os.environ['SENTENCE_TRANSFORMERS_HOME']))

return [r for r in roots if r]


def check_models():
"""Look for the two model folders in the local cache. Never downloads anything."""
try:
from sqlite_graph_memory import brain_ask
models = (brain_ask.E5_MODEL, brain_ask.RERANK_MODEL)
except Exception:
models = ('intfloat/multilingual-e5-base', 'cross-encoder/mmarco-mMiniLMv2-L12-H384-v1')
missing = []
for name in (brain_ask.E5_MODEL, brain_ask.RERANK_MODEL):
for name in models:
folder = 'models--' + name.replace('/', '--')
if not any((d / folder).exists() for d in _hf_cache_dirs()):
missing.append(name)
Expand All @@ -97,14 +119,40 @@ def check_models():


def check_index(index_dir=None):
d = Path(index_dir) if index_dir else brain_ask.INDEX_DIR
if index_dir:
d = Path(index_dir)
else:
try:
from sqlite_graph_memory import brain_ask
d = brain_ask.INDEX_DIR
except Exception:
d = Path(os.getenv('BRAIN_INDEX_DIR', 'index'))
emb, meta = d / '_brain_e5.npy', d / '_brain_e5_meta.pkl'
if not emb.exists() and not meta.exists():
return (WARN, 'No index in %s.' % d.resolve(),
'Run: sgm-index /path/to/your/notes (set BRAIN_INDEX_DIR to keep the index elsewhere)')
if emb.exists() != meta.exists():
left = meta.name if emb.exists() else emb.name
return FAIL, 'The index is half there: %s is missing.' % left, 'Rebuild it: sgm-index /path/to/your/notes'
try:
import pickle
import numpy as np
raw_meta = meta.read_bytes()
if not raw_meta:
return FAIL, 'The index is empty: %s is 0 bytes.' % meta.name, 'Rebuild it: sgm-index /path/to/your/notes'
m = pickle.loads(raw_meta)
if not isinstance(m, list):
return FAIL, 'The index is corrupt: %s is not a list.' % meta.name, 'Rebuild it: sgm-index /path/to/your/notes'
if emb.stat().st_size == 0:
return FAIL, 'The index is empty: %s is 0 bytes.' % emb.name, 'Rebuild it: sgm-index /path/to/your/notes'
e = np.load(emb)
if len(e.shape) != 2 or e.shape[0] != len(m):
rows = e.shape[0] if len(e.shape) > 0 else 0
return FAIL, 'The index is corrupt: %s rows (%d) != %s chunks (%d).' % (
emb.name, rows, meta.name, len(m)), 'Rebuild it: sgm-index /path/to/your/notes'
except Exception as exc:
why = str(exc).splitlines()[0] if str(exc) else type(exc).__name__
return FAIL, 'The index is unreadable or truncated (%s).' % why, 'Rebuild it: sgm-index /path/to/your/notes'
return OK, 'Index found in %s (%.1f MB).' % (d.resolve(), emb.stat().st_size / 1e6), ''


Expand Down
99 changes: 97 additions & 2 deletions tests/test_doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,106 @@ def test_half_index_fails(tmp_path):


def test_full_index_ok(tmp_path):
(tmp_path / "_brain_e5.npy").write_bytes(b"x")
(tmp_path / "_brain_e5_meta.pkl").write_bytes(b"x")
import pickle
import numpy as np
np.save(tmp_path / "_brain_e5.npy", np.zeros((1, 4), dtype="float32"))
(tmp_path / "_brain_e5_meta.pkl").write_bytes(pickle.dumps([{"path": "note.md"}]))
assert doctor.check_index(tmp_path)[0] == doctor.OK


def test_empty_or_truncated_index_fails(tmp_path):
(tmp_path / "_brain_e5.npy").touch()
(tmp_path / "_brain_e5_meta.pkl").touch()
status, what, fix = doctor.check_index(tmp_path)
assert status == doctor.FAIL
assert "empty" in what or "corrupt" in what or "truncated" in what


def test_mismatched_index_shape_fails(tmp_path):
import pickle
import numpy as np
np.save(tmp_path / "_brain_e5.npy", np.zeros((2, 4), dtype="float32"))
(tmp_path / "_brain_e5_meta.pkl").write_bytes(pickle.dumps([{"path": "one.md"}]))
status, what, fix = doctor.check_index(tmp_path)
assert status == doctor.FAIL
assert "rows (2) != _brain_e5_meta.pkl chunks (1)" in what


def test_doctor_importable_when_numpy_is_none():
import os
import subprocess
import sys
src = str(Path(__file__).resolve().parent.parent / "src")
code = (
"import sys; "
f"sys.path.insert(0, {src!r}); "
"sys.modules['numpy'] = None; "
"from sqlite_graph_memory import doctor; "
"assert doctor.check_numpy()[0] == doctor.FAIL"
)
env = {**os.environ, "PYTHONPATH": src}
res = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env)
assert res.returncode == 0, res.stderr


def test_transitive_dependency_missing_fails_not_warns(monkeypatch):
monkeypatch.setenv("SGM_BACKEND", "torch")
import builtins
import types
real_import = builtins.__import__

def fake_import(name, *args, **kwargs):
if name == "torch":
m = types.ModuleType("torch")
m.__version__ = "2.0.0"
return m
if name == "sentence_transformers":
raise ModuleNotFoundError("No module named 'safetensors'", name="safetensors")
return real_import(name, *args, **kwargs)

monkeypatch.setattr(builtins, "__import__", fake_import)
status, what, fix = doctor.check_embeddings()
assert status == doctor.FAIL
assert "safetensors" in what or "fails to import" in what
assert "Reinstall" in fix


def test_hf_custom_cache_does_not_mix_default(tmp_path, monkeypatch):
custom_cache = tmp_path / "custom"
custom_cache.mkdir()
fake_default = tmp_path / "default_hf" / "hub"
fake_default.mkdir(parents=True)
(fake_default / "models--intfloat--multilingual-e5-base").mkdir()
(fake_default / "models--cross-encoder--mmarco-mMiniLMv2-L12-H384-v1").mkdir()

monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
monkeypatch.setenv("HF_HUB_CACHE", str(custom_cache))
monkeypatch.delenv("SENTENCE_TRANSFORMERS_HOME", raising=False)
monkeypatch.delenv("HF_HOME", raising=False)
monkeypatch.delenv("XDG_CACHE_HOME", raising=False)

status, what, _ = doctor.check_models()
assert status == doctor.WARN
assert "Not downloaded yet" in what


def test_xdg_cache_home_respected(tmp_path, monkeypatch):
xdg_dir = tmp_path / "xdg"
hub = xdg_dir / "huggingface" / "hub"
hub.mkdir(parents=True)
(hub / "models--intfloat--multilingual-e5-base").mkdir()
(hub / "models--cross-encoder--mmarco-mMiniLMv2-L12-H384-v1").mkdir()

monkeypatch.setenv("XDG_CACHE_HOME", str(xdg_dir))
monkeypatch.delenv("HF_HUB_CACHE", raising=False)
monkeypatch.delenv("HF_HOME", raising=False)
monkeypatch.delenv("SENTENCE_TRANSFORMERS_HOME", raising=False)

status, what, _ = doctor.check_models()
assert status == doctor.OK


def test_models_missing_when_cache_is_empty(tmp_path, monkeypatch):
monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path))
monkeypatch.delenv("SENTENCE_TRANSFORMERS_HOME", raising=False)
Expand Down
Loading