Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix: replace bare except with except Exception in 3 sites (#1069)
yzxcj7971914dd508ccc
diff --git a/semantica/parse/docling_parser.py b/semantica/parse/docling_parser.pyindex 7ebb896a..64f1a10c 100644--- a/semantica/parse/docling_parser.py+++ b/semantica/parse/docling_parser.py@@ -491,8 +491,8 @@ class DoclingParser:elif hasattr(item, 'export_to_markdown'):try:page_text_parts.append(item.export_to_markdown(doc=doc))- except:- pass+ except Exception:+ pass # export failure degrades to skipping this text item# Extract tables on this pagefrom docling_core.types.doc import TableItem@@ -549,7 +549,7 @@ class DoclingParser:"tables": [],"images": [],})- except:+ except Exception:pages.append({"page_number": 1,"text": "",@@ -572,7 +572,7 @@ class DoclingParser:"tables": [],"images": [],})- except:+ except Exception:pages.append({"page_number": 1,"text": "",diff --git a/semantica/semantic_extract/methods.py b/semantica/semantic_extract/methods.pyindex 10fe3e76..b9b1d4c3 100644--- a/semantica/semantic_extract/methods.py+++ b/semantica/semantic_extract/methods.py@@ -109,7 +109,9 @@ License: MITimport reimport difflibimport threading+from collections import OrderedDictfrom concurrent.futures import ThreadPoolExecutor, as_completed+from contextlib import contextmanagerfrom typing import Any, Dict, List, Optional, Tuple, Unionfrom ..utils.exceptions import ProcessingError@@ -199,32 +201,122 @@ _embedder_cache = None# spacy.load() on every call. Entries record the spacy module they were loaded# from: tests patch `methods.spacy` with a mock, and an entry produced by a# different module object must not be handed back to a later caller.-_spacy_model_cache: Dict[str, Tuple[Any, Any]] = {}+# Bounded: each spaCy Language costs hundreds of MB, and a long-running+# service that varies the `model` option would otherwise pin every model it+# ever touched for the life of the process. 4 covers lg/md/sm + one custom.+MAX_SPACY_MODELS_CACHED = 4+_spacy_model_cache: "OrderedDict[str, Tuple[Any, Any, threading.Lock]]" = OrderedDict()_spacy_model_cache_lock = threading.Lock()-def load_spacy_model(name: str):- """Load a spaCy model once per process, keyed by model name.+def _load_spacy_entry(name: str) -> Tuple[Any, Any, threading.Lock]:+ """Return the cache entry for ``name``: ``(spacy_module, nlp, call_lock)``.- Raises whatever ``spacy.load`` raises (``OSError`` for a missing model), so- callers keep their existing fallback behavior.+ The entire lookup-plus-update is performed under ``_spacy_model_cache_lock``+ so that the LRU ``move_to_end`` and eviction are always consistent.+ ``spacy.load`` is called inside the lock; that is acceptable here because+ model loads are rare (at most ``MAX_SPACY_MODELS_CACHED`` per process) and+ the simpler design eliminates the TOCTOU window that a lockless fast-path+ would introduce.++ Raises whatever ``spacy.load`` raises (``OSError`` for a missing model)."""if spacy is None:raise ImportError("spaCy is not installed. Install with: pip install 'semantica[nlp-spacy]'")-- cached = _spacy_model_cache.get(name)- if cached is not None and cached[0] is spacy:- return cached[1]-with _spacy_model_cache_lock:cached = _spacy_model_cache.get(name)if cached is not None and cached[0] is spacy:- return cached[1]+ _spacy_model_cache.move_to_end(name)+ return cachednlp = spacy.load(name)- _spacy_model_cache[name] = (spacy, nlp)- return nlp+ entry: Tuple[Any, Any, threading.Lock] = (spacy, nlp, threading.Lock())+ _spacy_model_cache[name] = entry+ while len(_spacy_model_cache) > MAX_SPACY_MODELS_CACHED:+ _spacy_model_cache.popitem(last=False)+ return entry+++def load_spacy_model(name: str):+ """Load a spaCy model once per process, keyed by model name.++ Raises whatever ``spacy.load`` raises (``OSError`` for a missing model), so+ callers keep their existing fallback behavior.++ .. warning::+ The returned ``Language`` object is shared process-wide. Calling it+ from multiple threads concurrently is not safe. Use+ ``spacy_pipeline_guard`` (or ``run_spacy_text``) to serialize calls.+ """+ _spacy_module, nlp, _call_lock = _load_spacy_entry(name)+ return nlp+++@contextmanager+def spacy_pipeline_guard(name: str):+ """Yield the cached ``Language`` for ``name`` under its per-model call lock.++ Concurrent calls on the *same* model serialize; calls on *different* models+ run in parallel. Raises whatever ``spacy.load`` raises (``OSError`` for a+ missing model).+ """+ _spacy_module, nlp, call_lock = _load_spacy_entry(name)+ with call_lock:+ yield nlp+++def run_spacy_text(+ name: str,+ text: str,+ *,+ fallback: Optional[str] = None,+ log_label: str = "spaCy",+):+ """Call ``nlp(text)`` under the per-model guard; try ``fallback`` on ``OSError``.++ Returns the ``Doc``, or ``None`` when no usable model is available — the+ caller's cue to take its own pattern fallback. All ``nlp(text)`` calls go+ through ``spacy_pipeline_guard``, serializing concurrent thread access for+ the same model while letting different models run in parallel.++ Fallback is only attempted when the *primary* model is missing (``OSError``).+ A pipeline error (non-OSError) returns ``None`` immediately without trying+ the fallback, because the fallback would likely hit the same error.+ """+ try:+ with spacy_pipeline_guard(name) as nlp:+ return nlp(text)+ except OSError:+ if not fallback:+ logger.warning("%s model '%s' not found", log_label, name)+ return None+ logger.warning(+ "%s model '%s' not found, trying fallback '%s'",+ log_label, name, fallback,+ )+ except Exception:+ logger.warning(+ "%s model '%s' raised an unexpected error; skipping.",+ log_label, name, exc_info=True,+ )+ return None++ # Reached only when primary raised OSError and fallback is set.+ try:+ with spacy_pipeline_guard(fallback) as nlp:+ return nlp(text)+ except OSError:+ logger.warning(+ "%s fallback model '%s' not found either",+ log_label, fallback,+ )+ except Exception:+ logger.warning(+ "%s fallback model '%s' raised an unexpected error; skipping.",+ log_label, fallback, exc_info=True,+ )+ return Nonedef clear_spacy_model_cache() -> None:@@ -282,8 +374,8 @@ def get_nlp_model():try:_nlp_cache = spacy.load("en_core_web_sm", disable=["parser", "ner", "lemmatizer"])return _nlp_cache- except:- pass+ except Exception:+ pass # spacy.load raises OSError for a missing modelexcept Exception as e:logger.warning(f"Failed to load spaCy model for similarity: {e}")@@ -765,32 +857,11 @@ def extract_entities_ml(logger.warning("spaCy not available, falling back to pattern extraction")return extract_entities_pattern(text, **kwargs)- try:- nlp = load_spacy_model(model)- except OSError:- logger.warning(f"spaCy model {model} not found, using en_core_web_sm")- try:- nlp = load_spacy_model("en_core_web_sm")- except OSError:- logger.warning(- "spaCy model not available, falling back to pattern extraction"- )- return extract_entities_pattern(text, **kwargs)- except Exception as exc:- logger.warning(- "spaCy fallback triggered because the default model failed to initialize. Falling back to pattern extraction.",- exc_info=True,- )- return extract_entities_pattern(text, **kwargs)- except Exception as exc:- logger.warning(- "spaCy model %s failed to initialize, falling back to pattern extraction.",- model,- exc_info=True,- )+ doc = run_spacy_text(+ model, text, fallback="en_core_web_sm", log_label="spaCy NER"+ )+ if doc is None:return extract_entities_pattern(text, **kwargs)-- doc = nlp(text)entities = []for ent in doc.ents:@@ -1444,34 +1515,30 @@ def extract_relations_similarity(return extract_relations_cooccurrence(text, entities, **kwargs)relations = []-- # Try to load spaCy model with vectors- nlp = None++ # Resolve which model to use for vectors (prefer larger models), then+ # invoke it only under its guard: spaCy Languages are shared process-wide+ # and not safe to call from concurrent threads.+ chosen_model = Noneif SPACY_AVAILABLE:- try:- # Prefer larger models for vectors- for model_name in ["en_core_web_lg", "en_core_web_md", "en_core_web_sm"]:- if spacy.util.is_package(model_name):- nlp = load_spacy_model(model_name)- break- if not nlp:- # Try loading what we have- try:- nlp = load_spacy_model("en_core_web_sm")- except:- pass- except Exception:- pass+ for model_name in ["en_core_web_lg", "en_core_web_md", "en_core_web_sm"]:+ if spacy.util.is_package(model_name):+ chosen_model = model_name+ break# Pre-compute relation type vectors if possiblerelation_vectors = {}has_vectors = False- if nlp:- # Check if model has vectors- if nlp.vocab.vectors.shape[0] > 0:- has_vectors = True- for rt in relation_types:- relation_vectors[rt] = nlp(rt)+ if chosen_model:+ try:+ with spacy_pipeline_guard(chosen_model) as guarded_nlp:+ # Check if model has vectors+ if guarded_nlp.vocab.vectors.shape[0] > 0:+ has_vectors = True+ for rt in relation_types:+ relation_vectors[rt] = guarded_nlp(rt)+ except Exception:+ passfor entity1 in entities:for entity2 in entities:@@ -1501,10 +1568,12 @@ def extract_relations_similarity(best_type = Nonebest_score = 0.0- if has_vectors and relation_vectors:- # Vector similarity- doc = nlp(between_text)- if doc.vector_norm:+ if has_vectors and relation_vectors and chosen_model:+ # Vector similarity — each call re-enters the model's guard+ doc = run_spacy_text(+ chosen_model, between_text, log_label="spaCy similarity"+ )+ if doc is not None and doc.vector_norm:for rt, vec in relation_vectors.items():if vec.vector_norm:sim = doc.similarity(vec)@@ -1556,13 +1625,9 @@ def extract_relations_dependency(logger.warning("spaCy not available, falling back to pattern extraction")return extract_relations_pattern(text, entities, **kwargs)- try:- nlp = load_spacy_model(model)- except OSError:- logger.warning(f"spaCy model {model} not found")+ doc = run_spacy_text(model, text, log_label="spaCy dependency")+ if doc is None:return extract_relations_pattern(text, entities, **kwargs)-- doc = nlp(text)relations = []# Map tokens to entitiesdiff --git a/tests/test_spacy_cache_bounds_and_locks.py b/tests/test_spacy_cache_bounds_and_locks.pynew file mode 100644index 00000000..8f74cb34--- /dev/null+++ b/tests/test_spacy_cache_bounds_and_locks.py@@ -0,0 +1,197 @@+"""Bounded, call-serialized spaCy model cache — regression tests.++Background+----------+The cache used to retain every model it ever loaded for the life of the+process (each spaCy Language is hundreds of MB), and it handed the SAME+Language object to every caller while batch extraction fans out over a+ThreadPoolExecutor — spaCy pipelines are not safe to invoke from concurrent+threads.++This file tests:+ - LRU eviction at MAX_SPACY_MODELS_CACHED+ - Per-model call serialization+ - Parallelism across different models+ - The single-lock design's correctness under concurrent load+ - The spacy-not-installed guard+"""++import sys+import os+import threading+import unittest+from unittest.mock import MagicMock, patch++sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))++from semantica.semantic_extract import methods+from semantica.semantic_extract.methods import (+ MAX_SPACY_MODELS_CACHED,+ clear_spacy_model_cache,+ run_spacy_text,+ spacy_pipeline_guard,+ _spacy_model_cache,+)+++def make_spacy_mock():+ """Return a minimal spaCy mock whose .load() returns a distinct nlp per name."""+ mock = MagicMock()+ mock.load = MagicMock(side_effect=lambda name: MagicMock(name=f"nlp-{name}"))+ return mock+++class TestBoundedCache(unittest.TestCase):+ def setUp(self):+ clear_spacy_model_cache()++ def tearDown(self):+ clear_spacy_model_cache()++ def test_cache_evicts_beyond_the_bound(self):+ spacy = make_spacy_mock()+ with patch.object(methods, "spacy", spacy):+ for i in range(MAX_SPACY_MODELS_CACHED + 2):+ with spacy_pipeline_guard(f"model_{i}"):+ pass+ self.assertLessEqual(+ len(_spacy_model_cache), MAX_SPACY_MODELS_CACHED,+ f"cache must stay bounded at {MAX_SPACY_MODELS_CACHED} entries",+ )+ self.assertNotIn("model_0", _spacy_model_cache, "oldest entry must be evicted first")++ def test_recently_used_entries_survive(self):+ """LRU: touching model_0 before overflow keeps it alive; model_1 is evicted."""+ spacy = make_spacy_mock()+ with patch.object(methods, "spacy", spacy):+ for i in range(MAX_SPACY_MODELS_CACHED):+ with spacy_pipeline_guard(f"model_{i}"):+ pass+ # Re-touch the oldest; overflow should evict model_1 (now the true LRU).+ with spacy_pipeline_guard("model_0"):+ pass+ with spacy_pipeline_guard("model_new"):+ pass+ self.assertIn("model_0", _spacy_model_cache)+ self.assertNotIn("model_1", _spacy_model_cache)++ def test_bound_never_exceeded_under_concurrent_load(self):+ """The single-lock design must not allow concurrent inserts to temporarily+ break the cache bound — something the old lockless fast-path could do.++ The patch is applied in the outer (test) thread so that all worker threads+ share one stable mock for the entire test. Patching per-thread would race:+ a thread exiting its patch context could restore the real spacy module while+ another thread is mid-load, causing sporadic OSError from the real spacy.+ """+ spacy = make_spacy_mock()+ errors = []++ def load_model(i):+ try:+ with spacy_pipeline_guard(f"concurrent_model_{i}"):+ # While holding the call lock, snapshot cache size.+ size = len(_spacy_model_cache)+ if size > MAX_SPACY_MODELS_CACHED:+ errors.append(+ f"cache size {size} exceeded bound at model_{i}"+ )+ except Exception as exc:+ errors.append(str(exc))++ n_threads = MAX_SPACY_MODELS_CACHED * 3+ with patch.object(methods, "spacy", spacy):+ threads = [+ threading.Thread(target=load_model, args=(i,))+ for i in range(n_threads)+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ self.assertEqual(errors, [], f"cache bound violated under concurrent load: {errors}")+ self.assertLessEqual(len(_spacy_model_cache), MAX_SPACY_MODELS_CACHED)++ def test_spacy_not_installed_raises_import_error(self):+ """_load_spacy_entry must raise ImportError if spacy is None, not AttributeError."""+ with patch.object(methods, "spacy", None):+ with self.assertRaises(ImportError):+ with spacy_pipeline_guard("any_model"):+ pass+++class TestPerModelSerialization(unittest.TestCase):+ def setUp(self):+ clear_spacy_model_cache()++ def tearDown(self):+ clear_spacy_model_cache()++ def test_concurrent_calls_on_one_model_never_overlap(self):+ """The per-model call lock must prevent concurrent nlp(text) on the same Language."""+ overlaps = []+ active = []+ state_lock = threading.Lock()++ def slow_nlp(text):+ with state_lock:+ active.append(text)+ if len(active) > 1:+ overlaps.append(list(active))+ import time+ time.sleep(0.05)+ with state_lock:+ active.pop()+ return MagicMock(name=f"doc-{text}")++ spacy = MagicMock()+ spacy.load = MagicMock(return_value=MagicMock(side_effect=slow_nlp))+ with patch.object(methods, "spacy", spacy):+ threads = [+ threading.Thread(target=lambda i=i: run_spacy_text("m", f"t{i}"))+ for i in range(4)+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ self.assertEqual(+ overlaps, [],+ "concurrent calls on the same model must be serialized by the per-model lock",+ )++ def test_different_models_run_in_parallel(self):+ """Two different models must be callable simultaneously (per-model, not global lock)."""+ entered = threading.Barrier(2, timeout=5)++ def blocking_nlp(text):+ # Both threads must reach this point simultaneously to clear the barrier.+ # If a single global lock were used, the second thread would be blocked+ # waiting for the first to finish, and the barrier would time out.+ entered.wait()+ return MagicMock()++ spacy = MagicMock()+ spacy.load = MagicMock(return_value=MagicMock(side_effect=blocking_nlp))+ with patch.object(methods, "spacy", spacy):+ threads = [+ threading.Thread(target=lambda n=n: run_spacy_text(n, "t"))+ for n in ("model_a", "model_b")+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=10)+ if t.is_alive():+ for alive in threads:+ alive.join(timeout=1)+ self.fail(+ "Barrier timed out — different models must run concurrently, "+ "not serialize on a single global lock"+ )+++if __name__ == "__main__":+ unittest.main()