Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

test: stop the semantic_extract config from leaking between tests (#1931)

Raashish Aggarwala703a704570f
diff --git a/.github/full-suite-known-failures.txt b/.github/full-suite-known-failures.txt
index ba0fb8c1..30caa14d 100644
--- a/.github/full-suite-known-failures.txt
+++ b/.github/full-suite-known-failures.txt
@@ -71,47 +71,11 @@ tests/ingest/test_web_ingestor.py::test_sitemap_index_recursion
tests/semantic_extract/test_cache_backends.py::test_sqlite_rejects_symlinked_db # windows-only
# --- A MagicMock reaches code that compares or parses it ----------------------
-# `TypeError: '>' not supported between instances of 'MagicMock' and 'int'`, or
# `TypeError: expected string or bytes-like object, got 'MagicMock'`. The
# doubles these tests install no longer satisfy the signatures the production
# code now uses, so the call raising is the production code behaving correctly.
tests/ingest/test_ingestors.py::TestUnifiedIngest::test_ingest_web_dispatch
tests/ingest/test_ingestors.py::TestWebIngestor::test_ingest_url
-tests/semantic_extract/test_extractors.py::TestExtractors::test_event_detector_batch_via_detect_events
-tests/semantic_extract/test_extractors.py::TestExtractors::test_ner_extraction_batch_via_extract_entities
-tests/semantic_extract/test_extractors.py::TestExtractors::test_relation_extraction_batch_via_extract_relations
-tests/semantic_extract/test_extractors.py::TestExtractors::test_semantic_analyzer_batch_parallel
-tests/semantic_extract/test_extractors.py::TestExtractors::test_semantic_network_batch_via_extract_network
-tests/semantic_extract/test_extractors.py::TestExtractors::test_triplet_extraction_batch_via_extract_triplets
-tests/semantic_extract/test_performance.py::TestSemanticExtractImprovements::test_ner_parallel_processing
-tests/semantic_extract/test_performance.py::TestSemanticExtractImprovements::test_relation_parallel_processing
-tests/semantic_extract/test_performance.py::TestSemanticExtractImprovements::test_triplet_parallel_processing
-tests/semantic_extract/test_regression_performance_edge_cases.py::test_pattern_batch_defaults_to_single_worker_low_latency
-tests/semantic_extract/test_retry_logic.py::TestRetryLogic::test_chunked_extraction_propagation
-tests/semantic_extract/test_retry_logic.py::TestRetryLogic::test_relations_chunked_propagation
-tests/semantic_extract/test_retry_logic.py::TestRetryLogic::test_triplets_chunked_propagation
-tests/semantic_extract/test_robustness_fallback.py::TestRobustnessFallback::test_batch_metadata_propagation
-tests/test_semantic_extract_batch_provenance.py::TestSemanticExtractBatch::test_event_detector_batch
-tests/test_semantic_extract_batch_provenance.py::TestSemanticExtractBatch::test_semantic_analyzer_batch
-tests/test_semantic_extract_batch_provenance.py::TestSemanticExtractBatch::test_semantic_network_batch
-
-# --- Provider pool: the assertions describe an older key-resolution contract ---
-# e.g. `unexpectedly identical: <MagicMock name='OpenAIProvider-0'>` — the test
-# wants a fresh provider per API key, the pool returns a shared one.
-tests/semantic_extract/test_provider_pool_isolation.py::TestCredentialIsolation::test_env_key_rotation_creates_fresh_provider
-tests/semantic_extract/test_provider_pool_isolation.py::TestCredentialIsolation::test_env_key_rotation_via_create_provider
-tests/semantic_extract/test_provider_pool_isolation.py::TestCredentialIsolation::test_explicit_key_matches_env_key_reuses_provider
-tests/semantic_extract/test_provider_pool_isolation.py::TestProviderPoolInternals::test_resolve_api_key_env_var_fallback
-
-# --- Provider fallback path: the doubles no longer drive the branch -----------
-# All six assert on generate_typed falling back to generate; the fallback never
-# fires under these doubles (`AssertionError: Exception not raised`, `0 != 2`).
-tests/test_issue_554_fixes.py::TestBug3GenerateTypedFallbackToPlainGenerate::test_error_raised_when_both_paths_fail
-tests/test_issue_554_fixes.py::TestBug3GenerateTypedFallbackToPlainGenerate::test_fallback_preserves_error_on_bad_json
-tests/test_issue_554_fixes.py::TestBug3GenerateTypedFallbackToPlainGenerate::test_fallback_to_plain_generate_when_structured_fails
-tests/test_issue_554_fixes.py::TestBug3GenerateTypedFallbackToPlainGenerate::test_generate_structured_fallback_warning_has_exc_info
-tests/test_issue_554_fixes.py::TestBug3GenerateTypedFallbackToPlainGenerate::test_generate_structured_is_attempted_first
-tests/test_issue_554_fixes.py::TestBug3GenerateTypedFallbackToPlainGenerate::test_schema_validation_wraps_plain_list
# --- Local embedding backend unavailable offline ------------------------------
# `128 != 384` and `'fallback' != 'sentence_transformers'`: the real model could
@@ -156,46 +120,11 @@ tests/test_semantic_extract_deepdive_part2.py::TestSemanticExtractDeepDivePart2:
# -----------------------------------------------------------------------------
# Added 2026-10-02 from CI run 36860808592 (job `build`, ubuntu-latest /
# CPython 3.11), when the suite first ran there. The Windows measurement above
-# could not see these: the process-wide config keeps a double that only leaks
-# in the single-process run this step uses, and the rest are environment and
-# expectation drift. No file any of them lives in is touched by the change that
-# added this step, so nothing here is caused by wiring the suite into CI.
+# could not see these: they are environment and expectation drift. No file any
+# of them lives in is touched by the change that added this step, so nothing
+# here is caused by wiring the suite into CI.
# -----------------------------------------------------------------------------
-# --- Provider key resolution: a double supplies the key in a full run ---------
-# `config.get_api_key` hands the client a key whose repr is a `<MagicMock ...>`:
-# a double left by another test is still in the process-wide config when these
-# run. `is_available()` then reports True with no key set, and generation
-# reaches the live client instead of raising `ProcessingError` — 401s from
-# openai/deepseek/groq, a 404 from novita, `EphemeralTokenAPIKeyError` from
-# gemini, and a `TypeError` from anthropic where the `MagicMock` is joined into
-# a string. They pass in the two-invocation Windows measurement above, so they
-# are absent from the groups it produced.
-tests/test_llm_anthropic.py::test_is_available_false_with_no_key
-tests/test_llm_anthropic.py::test_generate_raises_clear_error_when_unavailable
-tests/test_llm_anthropic.py::test_generate_structured_raises_clear_error_when_unavailable
-tests/test_llm_anthropic.py::test_generate_typed_raises_clear_error_when_unavailable
-tests/test_llm_deepseek.py::test_is_available_false_with_no_key
-tests/test_llm_deepseek.py::test_generate_raises_clear_error_when_unavailable
-tests/test_llm_deepseek.py::test_generate_structured_raises_clear_error_when_unavailable
-tests/test_llm_deepseek.py::test_generate_typed_raises_clear_error_when_unavailable
-tests/test_llm_gemini.py::test_is_available_false_with_no_key
-tests/test_llm_gemini.py::test_generate_raises_clear_error_when_unavailable
-tests/test_llm_gemini.py::test_generate_structured_raises_clear_error_when_unavailable
-tests/test_llm_gemini.py::test_generate_typed_raises_clear_error_when_unavailable
-tests/test_llm_groq.py::test_is_available_false_with_no_key
-tests/test_llm_groq.py::test_generate_raises_clear_error_when_unavailable
-tests/test_llm_groq.py::test_generate_structured_raises_clear_error_when_unavailable
-tests/test_llm_groq.py::test_generate_typed_raises_clear_error_when_unavailable
-tests/test_llm_novita.py::test_is_available_false_with_no_key
-tests/test_llm_novita.py::test_generate_raises_clear_error_when_unavailable
-tests/test_llm_novita.py::test_generate_structured_raises_clear_error_when_unavailable
-tests/test_llm_novita.py::test_generate_typed_raises_clear_error_when_unavailable
-tests/test_llm_openai.py::test_is_available_false_with_no_key
-tests/test_llm_openai.py::test_generate_raises_clear_error_when_unavailable
-tests/test_llm_openai.py::test_generate_structured_raises_clear_error_when_unavailable
-tests/test_llm_openai.py::test_generate_typed_raises_clear_error_when_unavailable
-
# --- The CLI wraps the paths it reports mid-token -----------------------------
# `test_reports_the_files_it_wrote` looks for the written filename in the
# command's output, but the reporter hard-wraps that output every ~44 columns,
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 00000000..2d432015
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,28 @@
+"""Shared pytest configuration for the whole test suite."""
+
+import copy
+import importlib
+import sys
+
+import pytest
+
+# Imported once, before any test module is collected, so the fixture below always
+# has the real module to put back.
+_CONFIG_MODULE_NAME = "semantica.semantic_extract.config"
+_config_module = importlib.import_module(_CONFIG_MODULE_NAME)
+
+
[email protected](autouse=True)
+def _isolate_semantic_extract_config():
+ """Undo what a test leaves in the process-wide semantic_extract config.
+
+ Providers read their API key from this config before the environment, so a
+ double left there by one test (or a stand-in module left in sys.modules)
+ makes every later provider test see a key that is not set.
+ """
+ configs = _config_module.config._configs
+ saved = copy.deepcopy(configs)
+ yield
+ configs.clear()
+ configs.update(saved)
+ sys.modules[_CONFIG_MODULE_NAME] = _config_module
diff --git a/tests/semantic_extract/test_config_isolation.py b/tests/semantic_extract/test_config_isolation.py
new file mode 100644
index 00000000..1174bc6d
--- /dev/null
+++ b/tests/semantic_extract/test_config_isolation.py
@@ -0,0 +1,47 @@
+"""The process-wide semantic_extract config does not carry state between tests.
+
+The tests in this file run in order: each odd one leaves something behind the
+way a careless test would, and the next one checks it is gone (see #1913).
+"""
+
+import sys
+from unittest.mock import MagicMock
+
+import pytest
+
+from semantica.semantic_extract.config import config
+
+
+def test_leaves_a_double_in_the_config():
+ config.set_provider("openai", api_key=MagicMock())
+ assert isinstance(config.get_api_key("openai"), MagicMock)
+
+
+def test_does_not_see_the_double_left_by_the_previous_test():
+ assert not isinstance(config.get_api_key("openai"), MagicMock)
+
+
[email protected](scope="module")
+def nested_setting():
+ config.set_provider("isolation_test", options={"model": "original"})
+ yield
+ config._configs.pop("isolation_test", None)
+
+
+def test_changes_a_nested_setting(nested_setting):
+ config.get_provider_config("isolation_test")["options"]["model"] = "changed"
+
+
+def test_does_not_see_the_nested_setting_changed_by_the_previous_test(
+ nested_setting,
+):
+ options = config.get_provider_config("isolation_test")["options"]
+ assert options["model"] == "original"
+
+
+def test_leaves_a_stand_in_config_module_in_sys_modules():
+ sys.modules["semantica.semantic_extract.config"] = MagicMock()
+
+
+def test_does_not_see_the_stand_in_config_module():
+ assert not isinstance(sys.modules["semantica.semantic_extract.config"], MagicMock)
diff --git a/tests/test_huggingface_impl.py b/tests/test_huggingface_impl.py
index 160e7309..025089b4 100644
--- a/tests/test_huggingface_impl.py
+++ b/tests/test_huggingface_impl.py
@@ -1,57 +1,32 @@
-
import sys
-import os
import traceback
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from semantica.semantic_extract.methods import (
+ extract_entities_huggingface,
+ extract_relations_huggingface,
+ extract_triplets_huggingface,
+)
+from semantica.semantic_extract.ner_extractor import Entity
-print("Starting test script...", flush=True)
+# transformers and torch are imported lazily by the HuggingFace model loader, so
+# they are swapped in only while the test runs. Replacing them in sys.modules at
+# import time would leak into every test collected after this module.
+mock_transformers = MagicMock()
+mock_pipeline = MagicMock()
+mock_transformers.pipeline = mock_pipeline
+mock_torch = MagicMock()
+mock_torch.cuda.is_available.return_value = False
+MOCKED_MODULES = {"transformers": mock_transformers, "torch": mock_torch}
-# Mock transformers and torch BEFORE any project imports
-try:
- mock_transformers = MagicMock()
- mock_pipeline = MagicMock()
- mock_transformers.pipeline = mock_pipeline
- sys.modules["transformers"] = mock_transformers
- sys.modules["torch"] = MagicMock()
- sys.modules["torch"].cuda.is_available.return_value = False
-
- # Mock spacy
- mock_spacy = MagicMock()
- sys.modules["spacy"] = mock_spacy
-
- # Mock instructor
- sys.modules["instructor"] = MagicMock()
-
- # Also mock semantica.semantic_extract.config to avoid initialization issues
- mock_config_module = MagicMock()
- mock_config_instance = MagicMock()
- # Setup default return values for config
- mock_config_instance.get.return_value = {}
- mock_config_instance.get_optimization_config.return_value = {"enable_cache": False}
-
- mock_config_module.config = mock_config_instance
- mock_config_module.Config = MagicMock(return_value=mock_config_instance)
- sys.modules["semantica.semantic_extract.config"] = mock_config_module
-
- print("Mocks setup complete.", flush=True)
-except Exception as e:
- print(f"Error setting up mocks: {e}", flush=True)
- sys.exit(1)
-# Add project root
-sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
-print(f"Added to path: {sys.path[0]}", flush=True)
[email protected](autouse=True)
+def mocked_hf_modules():
+ with patch.dict(sys.modules, MOCKED_MODULES):
+ yield
-try:
- print("Importing methods...", flush=True)
- from semantica.semantic_extract.methods import extract_entities_huggingface, extract_relations_huggingface, extract_triplets_huggingface
- print("Importing Entity class...", flush=True)
- from semantica.semantic_extract.ner_extractor import Entity
- print("Imports successful.", flush=True)
-except Exception as e:
- print(f"Import failed: {e}", flush=True)
- traceback.print_exc()
- sys.exit(1)
def test_enhanced_impl():
print("Testing enhanced implementation...", flush=True)
@@ -171,7 +146,8 @@ def test_enhanced_impl():
if __name__ == "__main__":
try:
- test_enhanced_impl()
+ with patch.dict(sys.modules, MOCKED_MODULES):
+ test_enhanced_impl()
print("\nAll tests passed!", flush=True)
except Exception as e:
print(f"\nTest failed: {e}", flush=True)