superlocalmemory 3.5.5 → 3.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,37 @@ All notable changes to SuperLocalMemory V3 will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [3.5.6] - 2026-06-03 — Isolate LightGBM training (macOS daemon SIGSEGV fix)
9
+
10
+ ### Fixed (CRITICAL — daemon hard-crash on macOS / Apple Silicon)
11
+ - **`POST /api/learning/retrain`** ("Train model now" in the dashboard Brain pane)
12
+ and **`POST /api/v3/learning/consolidate`** no longer crash the unified daemon.
13
+ The daemon serves the API in-process with PyTorch's OpenMP runtime already warm
14
+ (reranker + embedding warm-up); importing `lightgbm` in that same process loaded
15
+ a second `libomp.dylib`, corrupting shared `__kmp` state and segfaulting a worker
16
+ thread (`SIGSEGV`, no Python traceback — the process died on a native signal and
17
+ auto-restarted).
18
+ - **Fix:** all LightGBM training now runs in an isolated subprocess
19
+ (`learning/lightgbm_subprocess.py`) that imports `lightgbm` **before** the
20
+ `superlocalmemory` package, so torch's OMP pool stays dormant and only LightGBM's
21
+ runtime is active. The child emits a single JSON verdict; the parent never raises,
22
+ so a native child crash is reported as an error and the daemon stays up. Mirrors
23
+ the existing `embedding_worker` / `reranker_worker` isolation pattern.
24
+ - On success the daemon invalidates the model cache so the freshly trained model is
25
+ reloaded. The fix applies on all platforms (subprocess spawn cost only off macOS).
26
+ - Thanks to @barrygfox for the detailed report, repro, and fix (#27).
27
+
28
+ ### Added
29
+ - **`SLM_HOST` env var** — shorter alias for `SLM_DAEMON_HOST` to set the daemon
30
+ bind address (issue #23). Set `SLM_HOST=0.0.0.0` (or `SLM_DAEMON_HOST=0.0.0.0`)
31
+ to serve one shared instance across a trusted private network; pair with
32
+ `SLM_MESH_HOST=0.0.0.0` + `SLM_MESH_SHARED_SECRET` for the mesh broker.
33
+ `SLM_DAEMON_HOST` takes precedence when both are set.
34
+
35
+ ### Changed
36
+ - CI: publish workflows now fail fast if `package.json`, `pyproject.toml`, and the
37
+ pushed `v*` tag disagree — prevents shipping mismatched npm/PyPI versions.
38
+
8
39
  ## [3.5.5] - 2026-05-31 — Write-Through Remember (instant cross-session recall)
9
40
 
10
41
  ### Fixed (CRITICAL — closes the remember→recall window)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "superlocalmemory",
3
- "version": "3.5.5",
3
+ "version": "3.5.6",
4
4
  "description": "Information-geometric agent memory with mathematical guarantees. 4-channel retrieval, Fisher-Rao similarity, zero-LLM mode, EU AI Act compliant. Works with Claude, Cursor, Windsurf, and 17+ AI tools.",
5
5
  "keywords": [
6
6
  "ai-memory",
package/pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "superlocalmemory"
3
- version = "3.5.5"
3
+ version = "3.5.6"
4
4
  description = "Information-geometric agent memory with mathematical guarantees"
5
5
  readme = "README.md"
6
6
  license = {text = "AGPL-3.0-or-later"}
@@ -0,0 +1,236 @@
1
+ # Copyright (c) 2026 Varun Pratap Bhardwaj / Qualixar
2
+ # Licensed under AGPL-3.0-or-later - see LICENSE file
3
+ # Part of SuperLocalMemory V3 | https://qualixar.com | https://varunpratap.com
4
+
5
+ """Isolated LightGBM work (retrain + consolidation) — OpenMP-crash guard.
6
+
7
+ **Why this exists** — the unified daemon serves the HTTP API in-process and,
8
+ by then, has already loaded PyTorch's OpenMP runtime (``torch/lib/libomp.dylib``)
9
+ with *warm* worker threads (the cross-encoder reranker + embedding warm-up at
10
+ startup). Any code path that imports ``lightgbm`` in that same process loads a
11
+ *second* OpenMP runtime — the Homebrew ``libomp.dylib`` that
12
+ ``lib_lightgbm.dylib`` links against — which corrupts the shared ``__kmp``
13
+ global state and SIGSEGVs a pre-existing torch OMP worker thread. That
14
+ hard-crashes the whole daemon (observed on macOS / Apple Silicon;
15
+ ``DiagnosticReports/Python-*.ips`` shows ``libomp.dylib __kmp_launch_worker``).
16
+
17
+ Two in-daemon entry points reach LightGBM training:
18
+ * ``POST /api/learning/retrain`` → legacy ``_retrain_ranker_impl``;
19
+ * ``POST /api/v3/learning/consolidate`` → ``ConsolidationWorker.run`` whose
20
+ step 5 trains via the online ``_run_shadow_cycle`` (active model) or the
21
+ legacy cold-start path.
22
+
23
+ Both are funnelled through this module so LightGBM only ever trains in a
24
+ **fresh subprocess** that never runs a torch tensor op — torch's OMP pool stays
25
+ dormant there and lightgbm's runtime is the only active one. The mechanism
26
+ mirrors the existing ``embedding_worker`` / ``reranker_worker`` isolation.
27
+
28
+ Spawned via :func:`run_retrain_isolated` / :func:`run_consolidation_isolated`,
29
+ which use a ``python -c`` bootstrap that imports lightgbm BEFORE the
30
+ ``superlocalmemory`` package. That ordering is load-bearing: importing the
31
+ package transitively pulls in torch, and torch-OMP-first-then-lightgbm is
32
+ exactly the sequence that segfaults. A plain ``python -m
33
+ superlocalmemory.learning.lightgbm_subprocess`` would run the package
34
+ ``__init__`` (torch) first and crash — do not invoke it that way.
35
+
36
+ The child emits a single JSON line on stdout — ``{"error": str|null, ...}`` —
37
+ plus a task payload (``trained`` for retrain, ``stats`` for consolidate).
38
+ Exit 0 = ran to completion; non-zero = handled failure. Either way the parent
39
+ (the daemon) keeps running.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import argparse
45
+ import json
46
+ import logging
47
+ import subprocess
48
+ import sys
49
+ from pathlib import Path
50
+
51
+ logger = logging.getLogger(__name__)
52
+
53
+ # Wall-clock ceilings. A retrain is 50 boosting rounds on ≤2000 rows (seconds);
54
+ # a full consolidation cycle also decays/dedups/mines/graph-analyses, so it
55
+ # gets more headroom.
56
+ RETRAIN_TIMEOUT_SEC = 300
57
+ CONSOLIDATE_TIMEOUT_SEC = 600
58
+
59
+
60
+ # ---------------------------------------------------------------------------
61
+ # Child-side task implementations (run in the isolated subprocess).
62
+ # ---------------------------------------------------------------------------
63
+
64
+ def _retrain(learning_db: str, profile_id: str, *, include_synthetic: bool) -> bool:
65
+ """Legacy ranker retrain in this (lightgbm-first) process. Returns trained."""
66
+ import lightgbm # noqa: F401 (import-order side effect is intentional)
67
+
68
+ from superlocalmemory.learning.ranker_retrain_legacy import (
69
+ _retrain_ranker_impl,
70
+ )
71
+
72
+ return bool(
73
+ _retrain_ranker_impl(
74
+ learning_db, profile_id, include_synthetic=include_synthetic,
75
+ )
76
+ )
77
+
78
+
79
+ def _consolidate(
80
+ memory_db: str, learning_db: str, profile_id: str, *, dry_run: bool,
81
+ ) -> dict:
82
+ """Full consolidation cycle (incl. step-5 LightGBM training). Returns stats."""
83
+ import lightgbm # noqa: F401 (import-order side effect is intentional)
84
+
85
+ from superlocalmemory.learning.consolidation_worker import (
86
+ ConsolidationWorker,
87
+ )
88
+
89
+ worker = ConsolidationWorker(memory_db, learning_db)
90
+ return worker.run(profile_id, dry_run=dry_run)
91
+
92
+
93
+ def _emit(obj: dict) -> None:
94
+ """Write the verdict as a single JSON line (default=str for safety)."""
95
+ sys.stdout.write(json.dumps(obj, default=str) + "\n")
96
+ sys.stdout.flush()
97
+
98
+
99
+ def main(argv: list[str] | None = None) -> int:
100
+ parser = argparse.ArgumentParser(prog="slm-lightgbm-subprocess")
101
+ parser.add_argument("--task", choices=["retrain", "consolidate"], default="retrain")
102
+ parser.add_argument("--learning-db", required=True)
103
+ parser.add_argument("--memory-db")
104
+ parser.add_argument("--profile", default="default")
105
+ parser.add_argument("--include-synthetic", action="store_true")
106
+ parser.add_argument("--dry-run", action="store_true")
107
+ args = parser.parse_args(argv)
108
+
109
+ result: dict = {"error": None}
110
+ try:
111
+ if args.task == "retrain":
112
+ result["trained"] = _retrain(
113
+ args.learning_db, args.profile,
114
+ include_synthetic=args.include_synthetic,
115
+ )
116
+ else:
117
+ if not args.memory_db:
118
+ raise ValueError("--memory-db is required for the consolidate task")
119
+ result["stats"] = _consolidate(
120
+ args.memory_db, args.learning_db, args.profile,
121
+ dry_run=args.dry_run,
122
+ )
123
+ except Exception as exc: # noqa: BLE001
124
+ result["error"] = f"{type(exc).__name__}: {exc}"
125
+ _emit(result)
126
+ return 1
127
+
128
+ _emit(result)
129
+ return 0
130
+
131
+
132
+ # ---------------------------------------------------------------------------
133
+ # Caller-side helpers — spawn the child in an isolated process.
134
+ # ---------------------------------------------------------------------------
135
+
136
+ def _run_isolated(task_args: list[str], *, timeout_sec: int) -> dict:
137
+ """Spawn the child with lightgbm imported first; return its JSON verdict.
138
+
139
+ Never raises for the expected failure modes (non-zero exit, timeout,
140
+ native crash with no JSON) — encodes them in an ``error`` key so the
141
+ calling daemon stays up no matter what.
142
+ """
143
+ # The leading ``import lightgbm`` is load-bearing: it must run BEFORE the
144
+ # superlocalmemory package (which transitively imports torch). ``-c`` is
145
+ # the only way to guarantee that ordering — ``-m superlocalmemory.…`` runs
146
+ # the package __init__ (torch) first and would reintroduce the crash.
147
+ bootstrap = (
148
+ "import lightgbm; "
149
+ "from superlocalmemory.learning.lightgbm_subprocess import main; "
150
+ "raise SystemExit(main())"
151
+ )
152
+ cmd = [sys.executable, "-c", bootstrap, *task_args]
153
+
154
+ try:
155
+ proc = subprocess.run(
156
+ cmd,
157
+ capture_output=True,
158
+ text=True,
159
+ timeout=timeout_sec,
160
+ check=False,
161
+ )
162
+ except subprocess.TimeoutExpired:
163
+ return {"error": f"timed out after {timeout_sec}s"}
164
+ except Exception as exc: # noqa: BLE001
165
+ return {"error": f"spawn failed: {exc}"}
166
+
167
+ # The verdict is the last JSON line on stdout. Parse defensively — a native
168
+ # crash in the child would leave no JSON, which we surface plainly.
169
+ for line in reversed((proc.stdout or "").splitlines()):
170
+ line = line.strip()
171
+ if not line:
172
+ continue
173
+ try:
174
+ return json.loads(line)
175
+ except ValueError:
176
+ continue
177
+
178
+ tail = (proc.stderr or "").strip()[-500:]
179
+ return {
180
+ "error": (
181
+ f"subprocess produced no verdict (exit={proc.returncode}). "
182
+ f"stderr tail: {tail}"
183
+ ),
184
+ }
185
+
186
+
187
+ def run_retrain_isolated(
188
+ learning_db: str | Path,
189
+ profile_id: str,
190
+ *,
191
+ include_synthetic: bool = False,
192
+ timeout_sec: int = RETRAIN_TIMEOUT_SEC,
193
+ ) -> dict:
194
+ """Train the ranker in a subprocess. Returns ``{"trained": bool, "error": ...}``."""
195
+ args = [
196
+ "--task", "retrain",
197
+ "--learning-db", str(learning_db),
198
+ "--profile", profile_id,
199
+ ]
200
+ if include_synthetic:
201
+ args.append("--include-synthetic")
202
+ verdict = _run_isolated(args, timeout_sec=timeout_sec)
203
+ verdict.setdefault("trained", False)
204
+ verdict.setdefault("error", None)
205
+ return verdict
206
+
207
+
208
+ def run_consolidation_isolated(
209
+ memory_db: str | Path,
210
+ learning_db: str | Path,
211
+ profile_id: str,
212
+ *,
213
+ dry_run: bool = False,
214
+ timeout_sec: int = CONSOLIDATE_TIMEOUT_SEC,
215
+ ) -> dict:
216
+ """Run the full consolidation cycle in a subprocess (its step-5 training
217
+ would otherwise crash the torch-warm daemon).
218
+
219
+ Returns ``{"stats": dict|None, "error": str|None}``.
220
+ """
221
+ args = [
222
+ "--task", "consolidate",
223
+ "--memory-db", str(memory_db),
224
+ "--learning-db", str(learning_db),
225
+ "--profile", profile_id,
226
+ ]
227
+ if dry_run:
228
+ args.append("--dry-run")
229
+ verdict = _run_isolated(args, timeout_sec=timeout_sec)
230
+ verdict.setdefault("stats", None)
231
+ verdict.setdefault("error", None)
232
+ return verdict
233
+
234
+
235
+ if __name__ == "__main__":
236
+ raise SystemExit(main())
@@ -15,6 +15,7 @@ from datetime import datetime, timezone
15
15
  from pathlib import Path
16
16
 
17
17
  from fastapi import APIRouter
18
+ from fastapi.concurrency import run_in_threadpool
18
19
 
19
20
  from .helpers import get_active_profile, MEMORY_DIR
20
21
 
@@ -597,16 +598,31 @@ async def learning_retrain(data: dict | None = None):
597
598
  data and data.get("include_synthetic")
598
599
  ) if isinstance(data, dict) else False
599
600
  try:
600
- from superlocalmemory.learning.consolidation_worker import (
601
- _retrain_ranker_impl,
601
+ # Train OUT OF PROCESS. The daemon already has torch's OpenMP runtime
602
+ # loaded with warm worker threads; importing lightgbm in-process loads
603
+ # a second libomp and SIGSEGVs the whole daemon (see
604
+ # retrain_subprocess module docstring). Isolation is the fix.
605
+ from superlocalmemory.learning.lightgbm_subprocess import (
606
+ run_retrain_isolated,
602
607
  )
603
608
  profile_id = get_active_profile() or "default"
604
- trained = _retrain_ranker_impl(
609
+ result = await run_in_threadpool(
610
+ run_retrain_isolated,
605
611
  LEARNING_DB,
606
612
  profile_id,
607
613
  include_synthetic=include_synthetic,
608
614
  )
609
- if trained:
615
+ if result.get("error"):
616
+ logger.error("learning_retrain failed: %s", result["error"])
617
+ return {"success": False, "error": result["error"]}
618
+ if result.get("trained"):
619
+ # Drop the cached model so the next recall reloads the freshly
620
+ # trained one the subprocess just persisted to learning.db.
621
+ try:
622
+ from superlocalmemory.learning.model_cache import invalidate
623
+ invalidate(profile_id)
624
+ except Exception as exc: # pragma: no cover — defensive
625
+ logger.debug("model cache invalidate failed: %s", exc)
610
626
  return {
611
627
  "success": True,
612
628
  "trained": True,
@@ -806,15 +806,37 @@ async def run_consolidation(request: Request):
806
806
  try:
807
807
  body = await request.json()
808
808
  dry_run = body.get("dry_run", False)
809
- from superlocalmemory.learning.consolidation_worker import ConsolidationWorker
809
+ # Run the full cycle OUT OF PROCESS. Step 5 trains the LightGBM ranker
810
+ # (online _run_shadow_cycle or legacy cold-start); importing lightgbm
811
+ # in the torch-warm daemon loads a second libomp and SIGSEGVs it (see
812
+ # lightgbm_subprocess module docstring). Isolation is the fix.
813
+ from superlocalmemory.learning.lightgbm_subprocess import (
814
+ run_consolidation_isolated,
815
+ )
810
816
  from superlocalmemory.core.config import SLMConfig
811
817
  from superlocalmemory.server.routes.helpers import DB_PATH
812
- worker = ConsolidationWorker(
813
- memory_db=str(DB_PATH),
814
- learning_db=str(DB_PATH.parent / "learning.db"),
815
- )
818
+ from fastapi.concurrency import run_in_threadpool
819
+
816
820
  config = SLMConfig.load()
817
- stats = worker.run(config.active_profile, dry_run=dry_run)
821
+ learning_db = DB_PATH.parent / "learning.db"
822
+ result = await run_in_threadpool(
823
+ run_consolidation_isolated,
824
+ str(DB_PATH),
825
+ str(learning_db),
826
+ config.active_profile,
827
+ dry_run=dry_run,
828
+ )
829
+ if result.get("error"):
830
+ return {"success": False, "error": result["error"]}
831
+ # Step-5 training may have promoted a new model — drop the daemon's
832
+ # cached model so the next recall reloads it from learning.db.
833
+ if not dry_run:
834
+ try:
835
+ from superlocalmemory.learning.model_cache import invalidate
836
+ invalidate(config.active_profile)
837
+ except Exception:
838
+ pass
839
+ stats = result.get("stats") or {}
818
840
  return {"success": True, **stats}
819
841
  except Exception as exc:
820
842
  return {"success": False, "error": str(exc)}
@@ -1950,10 +1950,19 @@ def start_server(port: int = _DEFAULT_PORT) -> None:
1950
1950
  log_dir = Path.home() / ".superlocalmemory" / "logs"
1951
1951
  log_dir.mkdir(parents=True, exist_ok=True)
1952
1952
 
1953
+ # Bind address. `SLM_DAEMON_HOST` is the canonical name; `SLM_HOST` is
1954
+ # accepted as a shorter alias (issue #23). Set either to 0.0.0.0 to serve
1955
+ # a shared instance over a trusted private network (e.g. WireGuard mesh).
1956
+ bind_host = (
1957
+ os.environ.get("SLM_DAEMON_HOST")
1958
+ or os.environ.get("SLM_HOST")
1959
+ or "127.0.0.1"
1960
+ )
1961
+
1953
1962
  config = uvicorn.Config(
1954
1963
  app="superlocalmemory.server.unified_daemon:create_app",
1955
1964
  factory=True,
1956
- host=os.environ.get("SLM_DAEMON_HOST", "127.0.0.1"),
1965
+ host=bind_host,
1957
1966
  port=port,
1958
1967
  log_level="warning",
1959
1968
  timeout_graceful_shutdown=10,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: superlocalmemory
3
- Version: 3.5.5
3
+ Version: 3.5.6
4
4
  Summary: Information-geometric agent memory with mathematical guarantees
5
5
  Author-email: Varun Pratap Bhardwaj <admin@superlocalmemory.com>
6
6
  License: AGPL-3.0-or-later
@@ -221,6 +221,7 @@ src/superlocalmemory/learning/forgetting_scheduler.py
221
221
  src/superlocalmemory/learning/hnsw_dedup.py
222
222
  src/superlocalmemory/learning/labeler.py
223
223
  src/superlocalmemory/learning/legacy_migration.py
224
+ src/superlocalmemory/learning/lightgbm_subprocess.py
224
225
  src/superlocalmemory/learning/memory_merge.py
225
226
  src/superlocalmemory/learning/model_cache.py
226
227
  src/superlocalmemory/learning/model_rollback.py