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
feat(perf): benchmark suite with regressive CLI
ZohaibHassan169b05622f8cc7
diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.ymlnew file mode 100644index 00000000..1f943b6e--- /dev/null+++ b/.github/workflows/benchmark.yml@@ -0,0 +1,51 @@+name: Semantica Performance Suite++on:+ push:+ branches: [main, master]+ pull_request:+ branches: [main, master]++jobs:+ performance-test:+ name: Benchmark Runner (Ubuntu/Python 3.12)+ runs-on: ubuntu-latest++ steps:+ - name: Checkout Code+ uses: actions/checkout@v4+ with:+ fetch-depth: 0++ - name: Set up Python 3.12+ uses: actions/setup-python@v5+ with:+ python-version: "3.12"+ cache: 'pip'++ - name: Install Dependencies+ env:++ BENCHMARK_REAL_LIBS: "1"+ run: |+ python -m pip install --upgrade pip+ pip install -e .+ pip install -r benchmarks/requirements.txt+ python -m spacy download en_core_web_sm+ pip install rdflib neo4j faiss-cpu torch # Add torch if any embedding tests need it++ - name: Execute Benchmarks (Real Mode)+ env:+ BENCHMARK_REAL_LIBS: "1"+ run: |+ python benchmarks/benchmarks_runner.py+ # Optional: Compare to baseline (requires previous run artifact)+ # pytest-benchmark --storage file://benchmarks/results --benchmark-compare++ - name: Upload Benchmark Results+ uses: actions/upload-artifact@v4+ if: always()+ with:+ name: benchmark-report-${{ github.run_id }}+ path: benchmarks/results+ retention-days: 30diff --git a/benchmarks/.gitignore b/benchmarks/.gitignorenew file mode 100644index 00000000..1407b07a--- /dev/null+++ b/benchmarks/.gitignore@@ -0,0 +1,75 @@+--- Python Standards ---++pycache/+*.py[cod]+*$py.class+*.so+.Python+env/+build/+develop-eggs/+dist/+downloads/+eggs/+.eggs/+lib/+lib64/+parts/+sdist/+var/+wheels/+*.egg-info/+.installed.cfg+*.egg++--- Virtual Environments ---++.env+.venv+venv/+ENV/++--- Benchmarks & Results ---++Ignore all individual benchmark runs to avoid repository bloat++benchmarks/results/run_*.json++Ignore the .pytest_cache which can get quite large++.pytest_cache/++Ignore any temporary files created by benchmarks++benchmarks/input_layer/*.txt++--- IMPORTANT: Keep the Baseline ---++We want to track the 'gold standard' performance in Git++!benchmarks/results/baseline.json++--- IDEs & Editors ---++.idea/+.vscode/+*.swp+*.swo+.project+.pydevproject+.settings/++--- Jupyter Notebooks ---++.ipynb_checkpoints++--- OS Specific ---++.DS_Store+Thumbs.db++--- Project Specific ---++logs/+*.log+semantica.logdiff --git a/benchmarks/__init__.py b/benchmarks/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/benchmarks/benchmarks.md b/benchmarks/benchmarks.mdnew file mode 100644index 00000000..fcba47f7--- /dev/null+++ b/benchmarks/benchmarks.md@@ -0,0 +1,72 @@+# Semantica Performance Benchmark Suite++This document outlines the architecture, directory structure, and usage of the performance benchmarking suite for the Semantica Agentic RAG framework.++## Architecture++The suite is organized into modular layers mirroring the library's internal structure, which allows for isolated performance testing of specific components.++### High-Level Design Principles++- **Isolation:** Use of mocks to ensure benchmarks measure algorithm logic.++- **Virtualization:** A custom `conftest.py` virtualization layer allows tests to run without heavy local dependencies.++- **Pedantic Measurement:** High-iteration counts and statistical rounds to filter out system noise.++## Directory Structure++Based on the current production environment, the suite is organized as follows:++| | |+| --------------------- | ------------------------------------------------------------------ |+| Folder | Description |+| context/ | Low-level graph operations and memory storage logic. |+| context_memory/ | Agent-level memory management and GraphRAG retrieval patterns. |+| core_processing/ | Throughput tests for NER, extraction, and graph building. |+| export/ | Serialization benchmarks for JSON, CSV, RDF, and GraphML. |+| infrastructure/ | Support scripts, including the regression comparison engine. |+| input_layer/ | Ingestion, parsing, and splitting performance. |+| normalize/ | Text cleaning, encoding handling, and date normalization. |+| ontology/ | Inference, serialization, and namespace management overhead. |+| output_orchestration/ | Parallelism and execution pipeline management. |+| quality_assurance/ | Deduplication and conflict resolution strategies. |+| results/ | Storage for benchmark JSON outputs and performance baselines. |+| storage/ | Latency tests for Vector stores (FAISS) and Triplet stores (Jena). |+| visualization/ | Computational cost of layout algorithms and chart rendering. |++## Usage++### Running the Suite++To run the full suite and generate a new results file:++```bash+python benchmarks/benchmark_runner.py+```++### Strict Mode (CI/CD)++The suite is designed to integrate with automated pipelines. Using the --strict flag will cause the runner to return a non-zero exit code if a performance regression greater than 15% is detected.++```bash+python benchmarks/benchmark_runner.py --strict+```++++### Performance Comparison++The comparison engine (infrastructure/compare.py) uses Z-scores to distinguish between actual performance regressions and environmental noise.++- Regression: Change > 15% AND Z-score > 2.0.++- Noise: Change > 15% but Z-score < 2.0.++### Updating Baseline++When a performance change is intentional (e.g., a more complex but necessary algorithm is added), update the "gold standard" baseline:++```bash+cp benchmarks/results/run_latest.json benchmarks/results/baseline.json+```diff --git a/benchmarks/benchmarks_runner.py b/benchmarks/benchmarks_runner.pynew file mode 100644index 00000000..84858a61--- /dev/null+++ b/benchmarks/benchmarks_runner.py@@ -0,0 +1,84 @@+import argparse+import os+import subprocess+import sys+from datetime import datetime+++def run_benchmarks():+ """+ Master Runner for Semantica Benchmarks.+ """+ parser = argparse.ArgumentParser(description="Run Semantica Benchmarks")+ parser.add_argument(+ "--strict", action="store_true", help="Fail script if performance regresses"+ )+ args = parser.parse_args()++ print("Starting Semantica Benchmark Suite...")++ timestamp = datetime.now().strftime("%Y%m%d_%H_%M_%S")+ os.makedirs("benchmarks/results", exist_ok=True)++ current_json = f"benchmarks/results/run_{timestamp}.json"+ baseline_json = "benchmarks/results/baseline.json"++ # Run Benchmarks+ cmd = [+ sys.executable,+ "-m",+ "pytest",+ "benchmarks/",+ "-p",+ "no:typeguard",+ "-p",+ "no:langsmith",+ "--benchmark-only",+ f"--benchmark-json={current_json}",+ "--benchmark-columns=min,mean,stddev,ops",+ "--benchmark-sort=mean",+ ]++ print(f"Executing benchmarks... (saving to {current_json})")+ result = subprocess.run(cmd)++ if result.returncode != 0:+ print("Benchmarks failed to execute (runtime errors).")+ sys.exit(result.returncode)++ print("Benchmarks completed execution.")++ # Compare against Baseline+ if os.path.exists(baseline_json):+ print(f"Comparing against Baseline ({baseline_json})...")++ if os.path.exists("benchmarks/infrastructure/compare.py"):+ compare_cmd = [+ sys.executable,+ "benchmarks/infrastructure/compare.py",+ baseline_json,+ current_json,+ ]++ compare_result = subprocess.run(compare_cmd)++ if compare_result.returncode != 0:+ print("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")+ print(" PERFORMANCE REGRESSION DETECTED")+ print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")+ if args.strict:+ sys.exit(1)+ else:+ print("Performance is within acceptable limits.")+ else:+ print(+ "Comparison script not found (benchmarks/infrastructure/compare.py). Skipping comparison."+ )+ else:+ print("No baseline found. This run effectively sets the new baseline.")++ print(f"\n[Action] To update baseline: cp {current_json} {baseline_json}")+++if __name__ == "__main__":+ run_benchmarks()diff --git a/benchmarks/conftest.py b/benchmarks/conftest.pynew file mode 100644index 00000000..c5ca2d9a--- /dev/null+++ b/benchmarks/conftest.py@@ -0,0 +1,265 @@+import importlib.abc+import importlib.machinery+import os+import sys+import tempfile+import uuid+from unittest.mock import patch++import numpy as np+import pytest++# Import interception++HEAVY_LIBS = {+ "pdfplumber",+ "docx",+ "pptx",+ "openpyxl",+ "pandas",+ "PIL",+ "lxml",+ "pytesseract",+ "networkx",+ "chardet",+ "langdetect",+ "neo4j",+ "weaviate",+ "qdrant_client",+ "sentence_transformers",+ "transformers",+ "fastembed",+ "spacy",+ "thinc",+ "torch",+ "matplotlib",+ "umap",+ "pynndescent",+}+++class MockMeta(type):+ """Metaclass that only claims RobustMocks as instances."""++ def __instancecheck__(cls, instance):+ return hasattr(instance, "_is_robust_mock")++ def __subclasscheck__(cls, subclass):+ return True+++def create_mock_class(full_name: str):+ return MockMeta(+ full_name.split(".")[-1],+ (object,),+ {+ "__module__": ".".join(full_name.split(".")[:-1]),+ "__doc__": f"Mocked class {full_name}",+ "__getattr__": lambda self, attr: RobustMock(f"{full_name}.{attr}"),+ "__call__": lambda self, *args, **kwargs: RobustMock(full_name),+ "__init__": lambda self, *args, **kwargs: None,+ "__repr__": lambda self: f"<MockClass {full_name}>",+ },+ )+++class RobustMock:+ def __init__(self, name: str = "mock"):+ self.__name__ = name+ self.__version__ = "9.9.9"+ self._is_robust_mock = True+ self.__path__ = []+ self.__file__ = "mock_file.py"+ self.__all__ = []++ def __getattr__(self, name):+ if name.startswith("__") and name.endswith("__"):+ raise AttributeError(name)+ full_name = f"{self.__name__}.{name}"+ # Capital names are classes++ if name and name[0].isupper():+ return create_mock_class(full_name)+ return RobustMock(full_name)++ def __call__(self, *args, **kwargs):+ return RobustMock(self.__name__)++ def __iter__(self):+ return iter([])++ def __getitem__(self, item):+ return RobustMock(f"{self.__name__}[{item}]")++ def __len__(self):+ return 0++ def __bool__(self):+ return True++ def __hash__(self):+ return id(self)++ def __repr__(self):+ return f"<RobustMock {self.__name__}>"+++class MockLoader(importlib.abc.Loader):+ def create_module(self, spec):+ mock_module = RobustMock(spec.name)+ mock_module.__spec__ = spec+ mock_module.__loader__ = self+ mock_module.__package__ = spec.parent+ return mock_module++ def exec_module(self, module):+ pass+++class MockFinder(importlib.abc.MetaPathFinder):+ def find_spec(self, fullname, path, target=None):+ top_level = fullname.split(".")[0]+ if top_level in HEAVY_LIBS:+ return importlib.machinery.ModuleSpec(fullname, MockLoader())+ return None+++if os.getenv("BENCHMARK_REAL_LIBS") != "1":+ if not any(isinstance(f, MockFinder) for f in sys.meta_path):+ sys.meta_path.insert(0, MockFinder())++# Infrastructure and Data Fixtures+++class NullTracker:+ def start_tracking(self, *args, **kwargs):+ return "dummy_id"++ def update_tracking(self, *args, **kwargs):+ pass++ def stop_tracking(self, *args, **kwargs):+ pass++ def register_pipeline_modules(self, *args, **kwargs):+ pass++ def clear_pipeline_context(self, *args, **kwargs):+ pass++ def update_progress(self, *args, **kwargs):+ pass++ def update_progress_batch(self, *args, **kwargs):+ pass++ @property+ def enabled(self):+ return False++ @enabled.setter+ def enabled(self, value):+ pass++[email protected](autouse=True)+def kill_io_overhead():+ tracker = NullTracker()+ with patch("semantica.utils.logging.get_logger"), patch(+ "semantica.utils.progress_tracker.get_progress_tracker", return_value=tracker+ ):+ patches = []+ for mod_name, module in list(sys.modules.items()):+ if mod_name.startswith("semantica.") and hasattr(+ module, "get_progress_tracker"+ ):+ p = patch.object(module, "get_progress_tracker", return_value=tracker)+ patches.append(p)+ for p in patches:+ p.start()+ yield+ for p in patches:+ p.stop()+++class MockVectorStore:+ def __init__(self, dim=384):+ self.dim = dim++ def embed(self, text: str):+ return np.random.rand(self.dim).astype(np.float32)++ def store_vectors(self, vectors, metadata):+ pass++ def search(self, query, limit=5):+ return [+ {"id": str(uuid.uuid4()), "score": 0.9, "content": "test", "metadata": {}}+ for _ in range(limit)+ ]+++def mock_vector_store():+ return MockVectorStore()+++def generate_graph_data():+ BASE_NS = "http://semantica.example.org/resource/"+ PRED_NS = "http://semantica.example.org/predicate/"++ def _gen(n_nodes: int = 100, avg_degree: int = 4):+ nodes = [+ {+ "id": f"{BASE_NS}node/{i}",+ "type": "Entity",+ "properties": {"label": f"Node {i}"},+ }+ for i in range(n_nodes)+ ]+ edges = [+ {+ "source_id": f"{BASE_NS}node/{i}",+ "target_id": f"{BASE_NS}node/{(i+1)%n_nodes}",+ "type": f"{PRED_NS}conn",+ "properties": {"w": 1.0},+ }+ for i in range(n_nodes)+ ]+ return nodes, edges++ return _gen+++def populated_context_graph(generate_graph_data):+ from semantica.context.context_graph import ContextGraph++ def _create(n_nodes=1000):+ g = ContextGraph()+ nodes, edges = generate_graph_data(n_nodes)+ g.add_nodes(nodes)+ g.add_edges(edges)+ return g++ return _create+++def sample_text_file():+ lines = ["Line " + str(i) for i in range(1000)]+ content = "\n".join(lines)+ with tempfile.NamedTemporaryFile(+ mode="w+", delete=False, suffix=".txt", encoding="utf-8"+ ) as tmp:+ tmp.write(content)+ tmp_path = tmp.name+ yield tmp_path+ if os.path.exists(tmp_path):+ os.remove(tmp_path)+++def long_text_string():+ return "benchmark " * 5000diff --git a/benchmarks/context/conftest.py b/benchmarks/context/conftest.pynew file mode 100644index 00000000..ccfc0e84--- /dev/null+++ b/benchmarks/context/conftest.py@@ -0,0 +1,23 @@+import pytest++from semantica.context.agent_memory import AgentMemory+from semantica.context.context_retriever import ContextRetriever+++def retriever_setup(mock_vector_store, populated_context_graph):+ """+ Sets up a fully configured retriever+ """+ kg = populated_context_graph(n_nodes=1000)++ memory = AgentMemory(vector_store=mock_vector_store, knowledge_graph=kg)++ retriever = ContextRetriever(+ memory_store=memory,+ knowledge_graph=kg,+ vector_store=mock_vector_store,+ hybrid_alpha=0.5,+ )++ return retrieverdiff --git a/benchmarks/context/test_graph_ops.py b/benchmarks/context/test_graph_ops.pynew file mode 100644index 00000000..f7c2106d--- /dev/null+++ b/benchmarks/context/test_graph_ops.py@@ -0,0 +1,47 @@+import pytest++from semantica.context.context_graph import ContextGraph++[email protected](group="graph_traversal")[email protected]("hops", [1, 2])+def test_bfs_traversal_depth(benchmark, populated_context_graph, hops):+ """Benchmarks the BFS neighbor retrieval at differnet depths."""+ graph = populated_context_graph(n_nodes=2000)+ start_node = list(graph.nodes.keys())[0]++ def run():+ return graph.get_neighbors(start_node, hops=hops)++ benchmark.pedantic(run, iterations=5, rounds=10)++[email protected](group="graph_construction")[email protected]("size", [1000])+def test_graph_ingestion_speed(benchmark, generate_graph_data, size):+ """+ Benchmarks the speed of adding nodes and edges to the+ in-memory structure.+ """++ nodes, edges = generate_graph_data(n_nodes=size)++ def run():+ graph = ContextGraph()+ graph.add_nodes(nodes)+ graph.add_edges(edges)++ benchmark.pedantic(run, iterations=1, rounds=5)++[email protected](group="graph_query")+def test_graph_keyword_search(benchmark, populated_context_graph):+ """+ Benchmarks the linear scan keyword search over graph nodes.+ """+ graph = populated_context_graph(n_nodes=2000)++ def run():+ return graph.query("Node content 500")++ benchmark.pedantic(run, iterations=5, rounds=10)diff --git a/benchmarks/context/test_linking.py b/benchmarks/context/test_linking.pynew file mode 100644index 00000000..414fe4f6--- /dev/null+++ b/benchmarks/context/test_linking.py@@ -0,0 +1,32 @@+import pytest++from semantica.context.context_graph import ContextGraph+from semantica.context.entity_linker import EntityLinker++[email protected](group="entity_linkiing")[email protected]("num_entities_in_graph", [100, 1000])+def test_entity_linking_complexity(benchmark, num_entities_in_graph):+ """+ Benchmarks finding links for extracted entities+ against the existing graph.+ """++ graph = ContextGraph()+ nodes = [+ {"id": f"e_{i}", "type": "Entity", "properties": {"content": f"Entity {i}"}}+ for i in range(num_entities_in_graph)+ ]+ graph.add_nodes(nodes)++ graph_dict = graph.to_dict()++ linker = EntityLinker(knowledge_graph=graph_dict, similarity_threshold=0.7)++ # Simulate extraction+ extracted_entities = [{"text": f"Entity {i}", "type": "Entity"} for i in range(5)]++ def run():+ return linker.link("dummy text", entities=extracted_entities)++ benchmark.pedantic(run, iterations=1, rounds=5)diff --git a/benchmarks/context/test_memory_storage.py b/benchmarks/context/test_memory_storage.pynew file mode 100644index 00000000..acd9d37b--- /dev/null+++ b/benchmarks/context/test_memory_storage.py@@ -0,0 +1,40 @@+import pytest++from semantica.context.agent_memory import AgentMemory++[email protected](group="memory_io")+def test_memory_storage_overhead(benchmark, mock_vector_store):+ """+ Benchmarks storing a memory item.+ """+ memory = AgentMemory(vector_store=mock_vector_store)+ content = "This is nothing burger for benchmarking this memory thingy."+ metadata = {"type": "conversation", "user": "u_1"}++ def run():+ return memory.store(content, metadata=metadata)++ benchmark.pedantic(run, iterations=10, rounds=10)++[email protected](group="memory_io")+def test_short_term_pruning(benchmark, mock_vector_store):+ """+ Benchmarks the pruning logic when short-term memory+ limit is hit.+ """++ def setup_overfilled_memory():+ memory = AgentMemory(vector_store=mock_vector_store, short_term_limit=50)+ # Pre-fill+ for i in range(55):+ memory.store(f"filler memory {i}")+ return (memory,), {}++ def run_prune(mem_instance):+ mem_instance.store("Trigger Pruning")++ benchmark.pedantic(+ target=run_prune, setup=setup_overfilled_memory, iterations=1, rounds=20+ )diff --git a/benchmarks/context/test_retrieval_logic.py b/benchmarks/context/test_retrieval_logic.pynew file mode 100644index 00000000..ef4d5d77--- /dev/null+++ b/benchmarks/context/test_retrieval_logic.py@@ -0,0 +1,42 @@+import pytest++from semantica.context.agent_memory import AgentMemory+from semantica.context.context_retriever import ContextRetriever, RetrievedContext++[email protected](group="rag_logic")+def test_hybrid_ranking_overhead(benchmark, retriever_setup):+ """+ Benchmarks the CPU cost of the 'rank_and_merge' logic.+ """++ query = "test_query"++ # Dummy results to sim inputs+ raw_results = [+ RetrievedContext(content=f"Vec {i}", score=0.9 - i * 0.01, source="vector:x")+ for i in range(10)+ ] + [+ RetrievedContext(content=f"Graph {i}", score=0.8 - i * 0.01, source="graph:y")+ for i in range(10)+ ]++ def run():+ return retriever_setup._rank_and_merge(raw_results, query)++ benchmark.pedantic(run, iterations=10, rounds=20)++[email protected](group="rag_logic")[email protected]("use_graph", [True, False])+def test_full_retrieval_pipeline(benchmark, retriever_setup, use_graph):+ """+ Benchmarks the orchestration of the retrieve() method.+ """++ def run():+ return retriever_setup.retrieve(+ "Node content", max_results=10, use_graph_expansion=use_graph, max_hops=1+ )++ benchmark.pedantic(run, iterations=1, rounds=5)diff --git a/benchmarks/context_memory/test_agentic.py b/benchmarks/context_memory/test_agentic.pynew file mode 100644index 00000000..4921fbc5--- /dev/null+++ b/benchmarks/context_memory/test_agentic.py@@ -0,0 +1,86 @@+from unittest.mock import MagicMock, patch++import pytest++from semantica.context.agent_context import AgentContext+from semantica.context.context_retriever import RetrievedContext++# Fixtures+++def mock_agent_context():+ """+ Creates an AgentContext with mocked internals.+ """+ vector_store = MagicMock()+ knowledge_graph = MagicMock()++ with patch("semantica.context.agent_context.AgentMemory") as MockMemory, patch(+ "semantica.context.agent_context.ContextRetriever"+ ) as MockRetriever:++ ctx = AgentContext(vector_store=vector_store, knowledge_graph=knowledge_graph)++ # Internal mocks++ ctx._memory = MockMemory.return_value+ ctx._retriever = MockRetriever.return_value++ return ctx+++# Benchmarks+++def test_router_overhead(benchmark, mock_agent_context):+ """+ Benchmarks the logic that decides between Vector vs Graph retrieval.+ """++ mock_agent_context._retriever.retrieve.return_value = []++ def op():+ return mock_agent_context.retrieve("test query", use_graph=None)++ benchmark.pedantic(op, iterations=50, rounds=20)+++def test_result_conversion_throughput(benchmark, mock_agent_context):+ """+ Benchmarks converting internal RetrievedContext objects to Dicts.+ """++ fake_results = [+ RetrievedContext(+ content=f"Result {i}",+ score=0.9,+ source="graph:node_1",+ metadata={"type": "fact"},+ related_entities=[{"id": "e1", "name": "Entity"}],+ related_relationships=[{"source": "e1", "target": "e2"}],+ )+ for i in range(100)+ ]+ mock_agent_context._retriever.retrieve.return_value = fake_results++ def op():+ return mock_agent_context.retrieve("test", use_graph=True)++ benchmark.pedantic(op, iterations=20, rounds=10)+++def test_store_orchestration_overhead(benchmark, mock_agent_context):+ """+ Benchmarks the 'store' method's logic for routing documents.+ """+ docs = [{"content": f"Doc {i}", "metadata": {"id": i}} for i in range(50)]++ # Mock the internal storage to return immediately+ mock_agent_context._memory.store.return_value = "mem_id"+ mock_agent_context._build_graph_from_documents = MagicMock(return_value={})++ def op():+ return mock_agent_context.store(docs, extract_entities=False)++ benchmark.pedantic(op, iterations=10, rounds=10)diff --git a/benchmarks/context_memory/test_graphrag.py b/benchmarks/context_memory/test_graphrag.pynew file mode 100644index 00000000..0ac7bc41--- /dev/null+++ b/benchmarks/context_memory/test_graphrag.py@@ -0,0 +1,244 @@+from dataclasses import dataclass, field+from typing import Any, Dict, List+from unittest.mock import patch++import numpy as np+import pytest++from semantica.context.agent_context import AgentContext+from semantica.context.agent_memory import AgentMemory+from semantica.context.context_graph import ContextGraph+from semantica.context.context_retriever import ContextRetriever, RetrievedContext+from semantica.context.entity_linker import EntityLinker++# Infra+++class NullTracker:+ """+ Stateless dummy tracker.+ """++ def start_tracking(self, *args, **kwargs):+ return "dummy_id"++ def update_tracking(self, *args, **kwargs):+ pass++ def stop_tracking(self, *args, **kwargs):+ pass++ def register_pipeline_modules(self, *args, **kwargs):+ pass++ def clear_pipeline_context(self, *args, **kwargs):+ pass++ def update_progress(self, *args, **kwargs):+ pass++ @property+ def enabled(self):+ return False++ @enabled.setter+ def enabled(self, value):+ pass+++# ~~ MOCK STORES ~~+++class MockVectorStore:+ """+ A feather VectorStore sim that does no math.+ We want to measure the MANAGER overhead.+ """++ def __init__(self):+ self.vectors = {}+ self.dim = 384++ def embed(self, text):+ return np.random.rand(self.dim).tolist()++ def add(self, items):+ for item in items:+ self.vectors[item.memory_id] = item++ def search(self, query, limit=5):+ class MockResult:+ def __init__(self, i):+ self.id = f"mem_{i}"+ self.content = f"Content for result {i} matching {query[:10]}"+ self.score = 0.9 - (i * 0.05)+ self.metadata = {"type": "test"}++ return [MockResult(i) for i in range(limit)]+++def create_dense_graph(node_count):+ """+ Creates a ContextGraph with 'Small World' Topology.+ Used to stress-test BFS traversal scaling.+ """+ graph = ContextGraph()++ graph.progress_tracker = NullTracker()++ # Create nodes+ nodes = [+ {+ "id": f"node_{i}",+ "type": "concept",+ "properties": {"content": f"Concept {i}"},+ }+ for i in range(node_count)+ ]+ graph.add_nodes(nodes)++ # Create Edges (Chain + Hub + Random)+ edges = []+ for i in range(node_count):+ # Chain+ if i < node_count - 1:+ edges.append(+ {"source_id": f"node_{i}", "target_id": f"node_{i+1}", "type": "next"}+ )+ # Hub+ if i > 0:+ edges.append(+ {"source_id": "node_0", "target_id": f"node_{i}", "type": "hub_link"}+ )+ # Rando+ if i % 5 == 0 and i + 5 < node_count:+ edges.append(+ {+ "source_id": f"node_{i}",+ "target_id": f"node_{i+5}",+ "type": "cross_link",+ }+ )++ graph.add_edges(edges)+ return graph+++def create_populated_memory(item_count):+ """Creates an AgentMemory populated with N items."""+ vs = MockVectorStore()+ memory = AgentMemory(vector_store=vs)+ memory.progress_tracker = NullTracker()++ for i in range(item_count):+ mem_id = f"setup_mem_{i}"+ from datetime import datetime++ from semantica.context.agent_memory import MemoryItem++ memory.memory_items[mem_id] = MemoryItem(+ content=f"History item {i}",+ timestamp=datetime.now(),+ memory_id=mem_id,+ metadata={"type": "chat"},+ )+ memory.memory_index.append(mem_id)++ return memory+++# ~~ BENCHMARKS ~~++[email protected]("graph_size", [100, 1000])[email protected]("hops", [1, 2])+def test_graph_traversal_scaling(benchmark, graph_size, hops):+ """+ Measures 'Hop Explosion' effect.+ Retrieving multi-hop neighbors on a dense graph.+ """+ graph = create_dense_graph(graph_size)++ def op():+ # Start from'Hub' node which's celebrity, meaning+ # connected to everyone+ return graph.get_neighbors("node_0", hops=hops)++ benchmark.pedantic(op, iterations=5, rounds=5)++[email protected]("memory_count", [100, 1000])+def test_retriever_ranking_throughput(benchmark, memory_count):+ """+ Measures CPU cost of merging and ranking results.+ """+ retriever = ContextRetriever(+ vector_store=MockVectorStore(),+ memory_store=create_populated_memory(10),+ knowledge_graph=None,+ hybrid_alpha=0.5,+ )+ retriever.progress_tracker = NullTracker()++ results = []+ for i in range(memory_count):+ results.append(+ RetrievedContext(+ content=f"Vector Item {i}",+ score=np.random.random(),+ source=f"vector:{i}",+ )+ )+ results.append(+ RetrievedContext(+ content=f"Graph Item {i}",+ score=np.random.random(),+ source=f"graph:{i}",+ metadata={"node_id": f"node_{i}"},+ )+ )++ def op():+ return retriever._rank_and_merge(results, "query context")++ benchmark.pedantic(op, iterations=5, rounds=10)++[email protected]("registry_size", [100, 1000])+def test_entity_linking_speed(benchmark, registry_size):+ """+ Measures O(N) linear scan speed in `find_similar_entities`.+ """+ linker = EntityLinker()+ linker.progress_tracker = NullTracker()++ mock_kg = {"entities": []}+ for i in range(registry_size):+ mock_kg["entities"].append(+ {"id": f"ent_{i}", "text": f"Entity Number {i}", "type": "TEST"}+ )+ linker.knowledge_graph = mock_kg++ input_text = "I am looking for Entity Number 50 in the database."++ def op():+ return linker.find_similar_entities(input_text, threshold=0.1)++ benchmark.pedantic(op, iterations=5, rounds=5)++[email protected]("batch_size", [1, 10, 50])+def test_agent_store_throughput(benchmark, batch_size):+ """+ 'store' pipeline test.+ """+ vs = MockVectorStore()+ context = AgentContext(vector_store=vs)+ context._memory.progress_tracker = NullTracker()++ inputs = [f"Memory item {i} for storage test" for i in range(batch_size)]++ def op():+ return context.batch_store(inputs)++ benchmark.pedantic(op, iterations=5, rounds=5)diff --git a/benchmarks/core_processing/conftest.py b/benchmarks/core_processing/conftest.pynew file mode 100644index 00000000..2267c52b--- /dev/null+++ b/benchmarks/core_processing/conftest.py@@ -0,0 +1,44 @@+import pytest+++# Data factories+def node_batch():+ """Generates 1000 nodes for graph"""+ return [+ {+ "id": f"node_{i}",+ "type": "Concept",+ "properties": {"name": f"Concept {i}", "weight": i / 1000},+ }+ for i in range(1000)+ ]+++def edge_batch():+ """Generates 1000 edges connection to the nodes."""+ return [+ {+ "source_id": f"node_{i}",+ "target_id": f"node_{i + 1}",+ "type": "related to",+ "weight": 0.5,+ }+ for i in range(999)+ ]+++def conversation_data():+ """Simulates a large conversation log"""+ entities = [{"text": f"Entity_{i}", "type": "topic"} for i in range(50)]++ return [+ {+ "id": "conv_1",+ "content": "This is a conversation about banking.",+ "entities": entities,+ "relationships": [],+ }+ ]diff --git a/benchmarks/core_processing/test_extraction.py b/benchmarks/core_processing/test_extraction.pynew file mode 100644index 00000000..77b175d0--- /dev/null+++ b/benchmarks/core_processing/test_extraction.py@@ -0,0 +1,153 @@+from unittest.mock import patch++import pytest++from semantica.semantic_extract.ner_extractor import Entity, NERExtractor+from semantica.semantic_extract.semantic_analyzer import SemanticAnalyzer+++# Fixtures+def document_batch():+ base = "The quick brown fox jumps over the lazy dog."+ docs = [+ f"{base} Variation {i}. Apple Inc released a product in 2024."+ for i in range(50)+ ]+ return docs+++# Fast wrapper-only benchmark (always runs)+def test_ner_ml_wrapper_overhead(benchmark, long_text_string):+ extractor = NERExtractor(method="ml", model="en_core_web_sm")++ entity_text = "Semantica"+ phrase = f"{entity_text} is a knowledge graph framework. "+ medium_text = phrase * 5++ expected_entities = []+ phrase_len = len(phrase)+ for i in range(5):+ start = i * phrase_len+ end = start + len(entity_text)+ ent = Entity(+ text=entity_text,+ label="ORG",+ start_char=start,+ end_char=end,+ confidence=0.98,+ metadata={"lemma": entity_text},+ )+ expected_entities.append(ent)++ def custom_ml_extraction(text: str, **method_options):+ min_confidence = method_options.get("min_confidence", 0.5)+ entity_types = method_options.get("entity_types")+ filtered = []+ for ent in expected_entities:+ if entity_types and ent.label not in entity_types:+ continue+ if ent.confidence >= min_confidence:+ filtered.append(ent)+ return filtered++ with patch(+ "semantica.semantic_extract.methods.get_entity_method"+ ) as mock_get_method:+ mock_get_method.side_effect = lambda name: (+ custom_ml_extraction if name == "ml" else (lambda t, **o: [])+ )++ def op():+ return extractor.extract_entities(text=medium_text)++ result = benchmark.pedantic(op, rounds=20, iterations=5)++ assert len(result) == 5+ assert all(e.text == "Semantica" for e in result)+ assert all(e.label == "ORG" for e in result)+ assert all(e.confidence == 0.98 for e in result)+ assert all(medium_text[e.start_char : e.end_char] == e.text for e in result)+++# Real spaCy benchmark[email protected](group="ner_real_ml")+def test_ner_ml_real_performance(benchmark, long_text_string):+ """+ Full spaCy inference + wrapper overhead.+ Only runs when real spaCy is loaded (BENCHMARK_REAL_LIBS=1).+ """+ extractor = NERExtractor(method="ml", model="en_core_web_sm")++ if (+ extractor.nlp is None+ or not hasattr(extractor.nlp, "pipe_names")+ or "ner" not in extractor.nlp.pipe_names+ ):+ pytest.skip(+ "Real spaCy NER pipeline not available — skipping production benchmark"+ )++ medium_text = long_text_string[:10000]++ medium_text += " Apple Inc. was founded by Steve Jobs and Steve Wozniak in Cupertino, California on April 1, 1976. Microsoft is a competitor."++ def op():+ return extractor.extract_entities(text=medium_text)++ result = benchmark.pedantic(op, rounds=6, iterations=2)++ assert len(result) >= 6+ assert any("Apple" in e.text and e.label == "ORG" for e in result)+ assert any(e.label == "PERSON" for e in result)+ assert any(e.label in {"GPE", "LOC"} for e in result)+ assert any(e.label == "DATE" for e in result)+ assert any("Microsoft" in e.text and e.label == "ORG" for e in result)+++def test_ner_pattern_speed(benchmark, long_text_string):+ extractor = NERExtractor(method="pattern")+ medium_text = long_text_string[:50000]+ text_with_entities = medium_text + " Apple Inc. was founded in 1976. "++ def op():+ return extractor.extract_entities(text=text_with_entities)++ result = benchmark.pedantic(op, rounds=20, iterations=5)+ assert len(result) > 0+ assert result[0].label in ["ORG", "DATE", "UNKNOWN"]+++def test_ner_batch_throughput(benchmark, document_batch):+ extractor = NERExtractor(method="pattern")++ def run_batch():+ return extractor.extract_entities_batch(document_batch, max_workers=2)++ result = benchmark.pedantic(run_batch, rounds=10, iterations=5)+ assert len(result) == len(document_batch)+ assert len(result[0]) > 0+++def test_similarity_calculation(benchmark):+ analyzer = SemanticAnalyzer()+ text1 = "The quick brown fox jumps over the lazy dog" * 10+ text2 = "The slow brown fox jumped over the sleeping dog" * 10++ def op():+ return analyzer.calculate_similarity(text1, text2, method="jaccard")++ result = benchmark.pedantic(op, rounds=100, iterations=100)+ assert 0.0 <= result <= 1.0+++def test_clustering_algorithm(benchmark, document_batch):+ analyzer = SemanticAnalyzer()+ options = {"similarity_threshold": 0.1}++ def op():+ return analyzer.cluster_semantically(texts=document_batch, **options)++ result = benchmark.pedantic(op, rounds=10, iterations=5)+ assert len(result) > 0+ assert result[0].textsdiff --git a/benchmarks/core_processing/test_graph_building.py b/benchmarks/core_processing/test_graph_building.pynew file mode 100644index 00000000..6c6560dc--- /dev/null+++ b/benchmarks/core_processing/test_graph_building.py@@ -0,0 +1,56 @@+from unittest.mock import MagicMock++import pytest++from semantica.context.context_graph import ContextGraph+++def test_bulk_node_insertion(benchmark, node_batch):+ """+ Benchmarks the overhead of adding nodes to in-memory graph.++ """++ def setup_graph():+ return (ContextGraph(),), {}++ def run(graph_instance):+ graph_instance.add_nodes(node_batch)++ benchmark.pedantic(target=run, setup=setup_graph, rounds=50, iterations=1)+++def test_bulk_edge_insertion(benchmark, node_batch, edge_batch):+ """+ Benchmarks adding edges.+ """++ def setup_graph_with_nodes():+ g = ContextGraph()+ g.add_nodes(node_batch)+ return (g,), {}++ def run(graph_instance):+ graph_instance.add_edges(edge_batch)++ benchmark.pedantic(+ target=run, setup=setup_graph_with_nodes, rounds=50, iterations=1+ )+++def test_conversation_to_graph_conversion(benchmark, conversation_data):+ """+ Benchmarks parsing conversation dicts into graph structures.+ """++ def setup_clean_builder():+ g = ContextGraph()+ g.entity_linker = MagicMock()+ return (g,), {}++ def run(graph_instance):+ return graph_instance.build_from_conversations(+ conversation_data, link_entities=False+ )++ benchmark.pedantic(target=run, setup=setup_clean_builder, rounds=20, iterations=1)diff --git a/benchmarks/export/conftest.py b/benchmarks/export/conftest.pynew file mode 100644index 00000000..367cd96c--- /dev/null+++ b/benchmarks/export/conftest.py@@ -0,0 +1,81 @@+import random+import uuid+from typing import Any, Dict, List++import numpy as np+import pytest++# Data Generators+++def generate_entities():+ def _gen(count: int) -> List[Dict[str, Any]]:+ entities = []+ for i in range(count):+ entities.append(+ {+ "id": f"e_{i}",+ "text": f"Entity Number {i}",+ "type": random.choice(+ ["person", "Organization", "Location", "Event"]+ ),+ "confidence": random.uniform(0.7, 1.0),+ "metadata": {"source": "doc_1.txt", "page": 1},+ }+ )++ return entities++ return _gen+++def generate_knowledge_graph(generate_entities):+ def _gen(entity_count: int, rel_density: float = 1.5) -> Dict[str, Any]:+ entities = generate_entities(entity_count)+ relationships = []+ rel_count = int(entity_count * rel_density)++ for i in range(rel_count):+ src = random.choice(entities)+ tgt = random.choice(entities)+ relationships.append(+ {+ "id": f"r_{i}",+ "source_id": src["id"],+ "target_id": tgt["id"],+ "type": " RELATED_TO",+ "confidence": 0.9,+ "metadata": {"extractor": "v1"},+ }+ )++ return {+ "entities": entities,+ "relationships": relationships,+ "metadata": {"generated_at": "2026-02-05"},+ }++ return _gen+++def generate_vectors():+ def _gen(count: int, dim: int = 384) -> List[Dict[str, Any]]:+ matrix = np.random.rand(count, dim).astype(np.float32)++ data = []++ for i in range(count):+ data.append(+ {+ "id": f"vec_{i}",+ "vector": matrix[i].tolist(),+ "text": f"Text {i}",+ "metadata": {"model": "bert"},+ }+ )+ return data++ return _gendiff --git a/benchmarks/export/test_core_formats.py b/benchmarks/export/test_core_formats.pynew file mode 100644index 00000000..808f3cae--- /dev/null+++ b/benchmarks/export/test_core_formats.py@@ -0,0 +1,42 @@+import pytest++from semantica.export.csv_exporter import CSVExporter+from semantica.export.json_exporter import JSONExporter+from semantica.export.yaml_exporter import SemanticNetworkYAMLExporter++[email protected](group="structured_export")[email protected]("size", [1000, 5000])+def test_json_parsing_throughput(benchmark, tmp_path, generate_knowledge_graph, size):+ kg = generate_knowledge_graph(size)+ exporter = JSONExporter(indent=None)+ output_file = tmp_path / "output.json"++ def run():+ exporter.export(kg, output_file)++ benchmark.pedantic(run, iterations=1, rounds=5)++[email protected](group="structured_export")+def test_csv_entity_export(benchmark, tmp_path, generate_entities):+ entities = generate_entities(5000)+ exporter = CSVExporter()+ output_file = tmp_path / "entities.csv"++ def run():+ exporter.export_entities(entities, output_file)++ benchmark.pedantic(run, iterations=1, rounds=5)++[email protected](group="structured_export")+def test_yaml_serialization_overhead(benchmark, tmp_path, generate_knowledge_graph):+ kg = generate_knowledge_graph(500)+ exporter = SemanticNetworkYAMLExporter()+ output_file = tmp_path / "output.yaml"++ def run():+ exporter.export(kg, output_file)++ benchmark.pedantic(run, iterations=1, rounds=5)diff --git a/benchmarks/export/test_graph_export.py b/benchmarks/export/test_graph_export.pynew file mode 100644index 00000000..5681d105--- /dev/null+++ b/benchmarks/export/test_graph_export.py@@ -0,0 +1,22 @@+import pytest++from semantica.export.graph_exporter import GraphExporter++[email protected](group="vis_export")[email protected]("format", ["graphml", "gexf"])+def test_graph_conversion_overhead(+ benchmark, tmp_path, generate_knowledge_graph, format+):+ """+ Measures the cost of converting internal KG structure to XML-based graph formats.+ Includes dictionary traversal and XML string building.+ """+ kg = generate_knowledge_graph(2000)+ exporter = GraphExporter(format=format)+ output_file = tmp_path / f"graph.{format}"++ def run():+ exporter.export_knowledge_graph(kg, output_file)++ benchmark(run)diff --git a/benchmarks/export/test_semantic_export.py b/benchmarks/export/test_semantic_export.pynew file mode 100644index 00000000..50da2068--- /dev/null+++ b/benchmarks/export/test_semantic_export.py@@ -0,0 +1,45 @@+import pytest++from semantica.export.lpg_exporter import LPGExporter+from semantica.export.owl_exporter import OWLExporter+from semantica.export.rdf_exporter import RDFExporter++[email protected](group="semantic_serialization")[email protected]("format", ["turtle", "rdfxml"])+def test_rdf_serialization_formats(benchmark, generate_knowledge_graph, format):+ kg = generate_knowledge_graph(1000)+ exporter = RDFExporter()+ rdf_data = exporter.serializer.convert_kg_to_rdf(kg)++ def run():+ return exporter.export_to_rdf(rdf_data, format=format)++ benchmark.pedantic(run, iterations=1, rounds=5)++[email protected](group="graph_db_export")+def test_lpg_cypher_generation(benchmark, generate_knowledge_graph):+ kg = generate_knowledge_graph(2000)+ exporter = LPGExporter(batch_size=1000, include_indexes=False)++ def run():+ return exporter._generate_cypher_queries(kg)++ benchmark.pedantic(run, iterations=1, rounds=5)++[email protected](group="semantic_serialization")+def test_owl_xml_generation(benchmark, tmp_path):+ ontology = {+ "name": "BenchmarkOntology",+ "classes": [{"name": f"Class{i}"} for i in range(500)],+ "object_properties": [{"name": f"Prop{i}"} for i in range(200)],+ }+ exporter = OWLExporter()+ output_file = tmp_path / "ontology.xml"++ def run():+ exporter.export(ontology, output_file, format="owl-xml")++ benchmark.pedantic(run, iterations=1, rounds=5)diff --git a/benchmarks/export/test_vector_export.py b/benchmarks/export/test_vector_export.pynew file mode 100644index 00000000..bd93d9ef--- /dev/null+++ b/benchmarks/export/test_vector_export.py@@ -0,0 +1,51 @@+import numpy as np+import pytest++from semantica.export.vector_exporter import VectorExporter++[email protected](group="vector_io")[email protected]("count", [1000, 10000])+def test_numpy_compression_speed(benchmark, tmp_path, generate_vectors, count):+ """+ Measures cost of np.savez_compressed.+ """+ vectors = generate_vectors(count)+ exporter = VectorExporter(format="numpy")+ output_file = tmp_path / "vectors.npz"++ def run():+ exporter.export(vectors, output_file)++ benchmark(run)++[email protected](group="vector_io")+def test_json_vector_overhead(benchmark, tmp_path, generate_vectors):+ """+ Benchmarks JSON export for vectors.+ """++ vectors = generate_vectors(2000)+ exporter = VectorExporter(format="json")+ output_file = tmp_path / "vectors.json"++ def run():+ exporter.export(vectors, output_file)++ benchmark(run)++[email protected](group="vector_io")+def test_binary_raw_throughput(benchmark, tmp_path, generate_vectors):+ """+ Measures raw binary dump speed (no compression, no metadata).+ """+ vectors = generate_vectors(10000)+ exporter = VectorExporter(format="binary")+ output_file = tmp_path / "vectors.bin"++ def run():+ exporter.export(vectors, output_file)++ benchmark(run)diff --git a/benchmarks/infrastructure/compare.py b/benchmarks/infrastructure/compare.pynew file mode 100644index 00000000..deee620f--- /dev/null+++ b/benchmarks/infrastructure/compare.py@@ -0,0 +1,102 @@+import argparse+import json+import sys+from pathlib import Path+from typing import Any, Dict, List+++def load_results(filepath: str) -> Dict[str, Any]:+ with open(filepath, "r") as f:+ return json.load(f)+++def calc_z_score(current_mean, base_mean, base_stddev):+ """+ Z-Score indicates how many standard deviations+ away current run is from baseline+ """++ if base_stddev == 0:+ return 0 if current_mean == base_mean else 100.0++ return (current_mean - base_mean) / base_stddev+++def compare_benchmarks(+ baseline: Dict[str, Any], current: Dict[str, Any], threshold_pct: float = 10.0+):+ """+ Uses Mean for % change and Z-score for noise detection.+ """++ # colors for terminal+ RED = "\033[91m"+ GREEN = "\033[92m"+ YELLOW = "\033[93m"+ RESET = "\033[0m"++ header = f"{'Benchmark':<60} | {'CHANGE %':<12} | {'SIGMA (Z)':<10} | {'STATUS'}"+ print(header)+ print("=" * len(header))++ baseline_map = {b["name"]: b for b in baseline["benchmarks"]}+ current_map = {b["name"]: b for b in current["benchmarks"]}++ regressions = []++ for name, curr in current_map.items():+ base = baseline_map.get(name)+ if not base:+ print(f"{name:<60} | {'NEW':<12} | {'N/A':<10} | NEW")+ continue++ m1 = base["stats"]["mean"]+ s1 = base["stats"]["stddev"]+ m2 = curr["stats"]["mean"]++ if m1 == 0:+ delta_pct = 0.0+ else:+ delta_pct = ((m2 - m1) / m1) * 100++ z_score = calc_z_score(m2, m1, s1)++ status = f"{GREEN} OK{RESET}"++ if delta_pct > threshold_pct:+ if abs(z_score) > 2.0:+ status = f"{RED} REGRESSION{RESET}"+ regressions.append(name)+ else:+ status = f"{YELLOW} NOISE{RESET}"+ elif delta_pct < -threshold_pct and abs(z_score) > 2.0:+ status = f"{GREEN} IMPROVED{RESET}"++ print(f"{name:<60} | {delta_pct:>+10.2f}% | {z_score:>9.2f} | {status}")++ if regressions:+ print(+ f"\n{RED}FAILURE: Performance regression detected in {len(regressions)} tests.{RESET}"+ )+ return True+ print(f"\n{GREEN}SUCCESS: No significant regressions.{RESET}")+ return False+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument("baseline", help="Gold standard JSON")+ parser.add_argument("current", help="NEW RUN JSON")+ parser.add_argument(+ "--threshold", type=float, default=10.0, help="FAIL if slower by %"+ )+ args = parser.parse_args()++ try:+ failed = compare_benchmarks(+ load_results(args.baseline), load_results(args.current), args.threshold+ )+ sys.exit(1 if failed else 0)+ except FileNotFoundError as e:+ print(f"Error loading files: {e}")+ sys.exit(0)diff --git a/benchmarks/input_layer/__init__.py b/benchmarks/input_layer/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/benchmarks/input_layer/test_ingestion.py b/benchmarks/input_layer/test_ingestion.pynew file mode 100644index 00000000..5e049769--- /dev/null+++ b/benchmarks/input_layer/test_ingestion.py@@ -0,0 +1,22 @@+import pytest++from semantica.ingest.file_ingestor import FileIngestor+++def test_ingest_file_performance(benchmark, sample_text_file):+ """+ Benchmarks the speed of the ingest_file method++ Metrics:+ - Time to open, read, validate and wrap a ~~10 KB text file.+ """++ ingestor = FileIngestor()+ result = benchmark(+ ingestor.ingest_file, file_path=sample_text_file, read_content=True+ )++ assert result is not None+ assert result.size > 0+ assert result.name.endswith(".txt")+ assert "Line 0" in result.textdiff --git a/benchmarks/input_layer/test_parsing.py b/benchmarks/input_layer/test_parsing.pynew file mode 100644index 00000000..b1f6b475--- /dev/null+++ b/benchmarks/input_layer/test_parsing.py@@ -0,0 +1,188 @@+import csv+import io+import json+import time+from typing import Any, Dict, List+from unittest.mock import MagicMock, patch++import pytest++from semantica.parse.code_parser import CodeParser+from semantica.parse.csv_parser import CSVParser+from semantica.parse.document_parser import DocumentParser+from semantica.parse.html_parser import HTMLParser+from semantica.parse.json_parser import JSONParser++# Data gens+++def generate_json_string(item_count: int) -> str:+ data = [+ {+ "id": i,+ "name": f"Item:{i}",+ "tags": ["tag1", "tag2", "tag3"],+ "metadata": {"active": True, "score": 0.95},+ }+ for i in range(item_count)+ ]+ return json.dumps(data)+++def generate_csv_string(row_count: int) -> str:+ output = io.StringIO()+ writer = csv.writer(output)+ writer.writerow(["id", "name", "description", "value", "date"])+ for i in range(row_count):+ writer.writerow([i, f"Item {i}", "Description text here", 100.50, "2024-01-01"])+ return output.getvalue()+++def generate_html_string(element_count: int) -> str:+ lis = "".join(+ [f'<li><a href="/item/{i}">Link {i}</a></li>' for i in range(element_count)]+ )+ return f"""+ <html>+ <head><title>Benchmark Page</title></head>+ <body>+ <div id="content">+ <h1>Header</h1>+ <p>Some intro text.</p>+ <ul>{lis}</ul>+ </div>+ </body>+ </html>+ """+++# lib mocks+++class MockPDFPage:+ def __init__(self, page_num):+ self.width = 600+ self.height = 800+ self.page_number = page_num++ def extract_text(self):+ return f"This is text content for page {self.page_number}. " * 50++ def extract_tables(self):+ return [[["Header1", "Header2"], ["Row1", "Value1"]]]++ @property+ def images(self):+ return [{"x0": 10, "y0": 10, "width": 100, "height": 100}]+++class MockPDF:+ def __init__(self, page_count):+ self.pages = [MockPDFPage(i) for i in range(page_count)]+ self.metadata = {"Title": "Benchmark PDF", "Author": "Noone"}++ def __enter__(self):+ return self++ def __exit__(self, *args):+ pass+++def mock_pdfplumber():+ with patch("pdfplumber.open") as mock_open:+ yield mock_open+++# Benchmarks++[email protected]("size", [1000, 10000])+def test_json_parsing_throughput(benchmark, size):+ parser = JSONParser()+ json_str = generate_json_string(size)++ with patch("pathlib.Path.exists", return_value=False):++ def op():+ return parser.parse(json_str)++ benchmark.pedantic(op, iterations=5, rounds=10)++[email protected]("rows", [1000, 10000])+def test_csv_parsing_throughput(benchmark, rows):+ """+ Measures CSV parsing throughput.+ """+ parser = CSVParser()+ csv_content = generate_csv_string(rows)++ with patch(+ "builtins.open", side_effect=lambda *args, **kwargs: io.StringIO(csv_content)+ ):+ with patch("pathlib.Path.exists", return_value=True):++ def op():+ return parser.parse("dummy.csv")++ benchmark.pedantic(op, iterations=5, rounds=5)++[email protected]("elements", [100, 1000])+def test_html_scraping_speed(benchmark, elements):+ parser = HTMLParser()+ html_content = generate_html_string(elements)++ with patch("pathlib.Path.exists", return_value=False):++ def op():+ return parser.parse(html_content, extract_links=True)++ benchmark.pedantic(op, iterations=5, rounds=5)++[email protected]("pages", [10, 50])+def test_pdf_extraction_overhead(benchmark, mock_pdfplumber, pages):+ parser = DocumentParser()++ mock_pdf = MockPDF(pages)+ mock_pdfplumber.return_value = mock_pdf++ with patch("pathlib.Path.exists", return_value=True), patch(+ "pathlib.Path.suffix", new_callable=MagicMock(return_value=".pdf")+ ):++ def op():+ return parser.parse_document("dummy.pdf", extract_images=True)++ benchmark.pedantic(op, iterations=5, rounds=5)+++def test_python_ast_parsing(benchmark):+ """+ Measures performance of Python AST analysis.+ """+ parser = CodeParser()++ code_lines = []+ for i in range(200):+ code_lines.append(f"import module_{i}")+ code_lines.append(f"def function_{i}(arg):")+ code_lines.append(f" '''Docstring for function {i}'''")+ code_lines.append(f" return arg + {i}")+ code_lines.append(f"class Class_{i}:")+ code_lines.append(f" pass")++ code_content = "\n".join(code_lines)++ with patch(+ "builtins.open", side_effect=lambda *args, **kwargs: io.StringIO(code_content)+ ), patch("pathlib.Path.exists", return_value=True), patch(+ "pathlib.Path.suffix", new_callable=MagicMock(return_value=".py")+ ):++ def op():+ return parser.parse_code("dummy.py")++ benchmark.pedantic(op, iterations=5, rounds=5)diff --git a/benchmarks/input_layer/test_splitting.py b/benchmarks/input_layer/test_splitting.pynew file mode 100644index 00000000..db3c31b0--- /dev/null+++ b/benchmarks/input_layer/test_splitting.py@@ -0,0 +1,27 @@+from unittest.mock import MagicMock, patch++import pytest++try:+ from semantica.split.sliding_window_chunker import SlidingWindowChunker+ from semantica.split.splitter import TextSplitter+except ImportError as e:+ pytest.skip(+ f"Skipping splitting test due to missing dependencies ({e})",+ allow_module_level=True,+ )+++def test_sliding_window(benchmark, long_text_string):+ """+ Benchmarks the speed of SlidingWindowChunker in 'Fixed Size' mode+ """++ chunker = SlidingWindowChunker(chunk_size=500, overlap=50)++ if hasattr(chunker, "progress_tracker"):+ chunker.progress_tracker = MagicMock()++ result = benchmark(chunker.chunk, text=long_text_string, preserve_boundaries=False)++ assert len(result) > 0diff --git a/benchmarks/normalize/conftest.py b/benchmarks/normalize/conftest.pynew file mode 100644index 00000000..dfd43af4--- /dev/null+++ b/benchmarks/normalize/conftest.py@@ -0,0 +1,62 @@+import random+import string+from typing import Any, Dict, List+from unittest.mock import MagicMock, patch++import pytest++# Data gen+++def generate_text_data():+ """Generates various types of text data."""++ def _gen(type="clean", length=100):+ if type == "clean":+ return "".join(random.choices(string.ascii_letters + " ", k=length))+ elif type == "html":+ tags = ["<div>", "<p>", "<span>", "<a>", "<b>", "<i>"]+ content = "".join(random.choices(string.ascii_letters + " ", k=length))+ return f"{random.choice(tags)}{content}{random.choice(tags).replace('<', '</')}"+ elif type == "unicode":+ chars = string.ascii_letters + "éàèùâêîôûçñ"+ return "".join(random.choices(chars, k=length))+ elif type == "dirty":+ chars = string.ascii_letters + " \t\n\r"+ return "".join(random.choices(chars, k=length))++ return _gen+++def generate_dataset():+ """Generates dataset for data cleaner."""++ def _gen(rows=100, duplicate_rate=0.0):+ base_rows = []+ unique_count = int(rows * (1 - duplicate_rate))++ for i in range(unique_count):+ base_rows.append(+ {+ "id": i,+ "name": f"Entity_{i}",+ "email": f"user{i}@yahoo.com",+ "value": random.random() * 100,+ "category": random.choice(["A", "B", "C"]),+ }+ )++ final_dataset = base_rows.copy()+ while len(final_dataset) < rows:+ source = random.choice(base_rows)+ dup = source.copy()+ if random.random() > 0.5:+ dup["value"] = source["value"] + 0.001+ final_dataset.append(dup)++ random.shuffle(final_dataset)+ return final_dataset++ return _gendiff --git a/benchmarks/normalize/test_data_cleaner.py b/benchmarks/normalize/test_data_cleaner.pynew file mode 100644index 00000000..83cf1506--- /dev/null+++ b/benchmarks/normalize/test_data_cleaner.py@@ -0,0 +1,38 @@+import pytest++from semantica.normalize.data_cleaner import DataCleaner++[email protected]("rows", [100, 500])+def test_duplication_detection_scaling(benchmark, generate_dataset, rows):+ """+ Benchmarks duplicate detection scaling.+ """++ cleaner = DataCleaner()+ dataset = generate_dataset(rows=rows, duplicate_rate=0.2)++ def run():+ return cleaner.detect_duplicates(dataset, key_fields=["name", "email"])++ benchmark.pedantic(run, iterations=1, rounds=5)+++def test_missing_value_imputation(benchmark, generate_dataset):+ """+ Benchmarks statistical imputation.+ """+ cleaner = DataCleaner()++ def setup_broken_dataset():+ dataset = generate_dataset(rows=5000)+ for row in dataset:+ if row["id"] % 5 == 0:+ row["value"] = None++ return (dataset,), {}++ def run(data):+ return cleaner.handle_missing_values(data, strategy="impute", method="mean")++ benchmark.pedantic(target=run, setup=setup_broken_dataset, iterations=1, rounds=10)diff --git a/benchmarks/normalize/test_heavy_libs.py b/benchmarks/normalize/test_heavy_libs.pynew file mode 100644index 00000000..f9815aa3--- /dev/null+++ b/benchmarks/normalize/test_heavy_libs.py@@ -0,0 +1,31 @@+from unittest.mock import MagicMock, patch++import pytest++from semantica.normalize.encoding_handler import EncodingHandler+from semantica.normalize.language_detector import LanguageDetector+++def test_language_detection_throughput(benchmark, generate_text_data):+ """Benchmarks langdetect intergration."""+ detector = LanguageDetector()+ texts = [generate_text_data("clean", 200) for _ in range(50)]++ def run():+ return detector.detect_batch(texts)++ benchmark.pedantic(run, iterations=1, rounds=5)+++def test_encoding_detection(benchmark):+ """Benchmarks chardet integration via EncodingHandler."""+ handler = EncodingHandler()+ data = (+ b"Wowzaaa a simple string for encoding decoding , oh encoding detection just."+ * 100+ )++ def run():+ return handler.detect(data)++ benchmark.pedantic(run, iterations=5, rounds=10)diff --git a/benchmarks/normalize/test_parsers.py b/benchmarks/normalize/test_parsers.pynew file mode 100644index 00000000..e3faa1d6--- /dev/null+++ b/benchmarks/normalize/test_parsers.py@@ -0,0 +1,25 @@+import pytest++from semantica.normalize.date_normalizer import DateNormalizer+from semantica.normalize.number_normalizer import NumberNormalizer++[email protected]("date_str", ["2026-02-03", "Ferbuary 2nd, 2026", "9 days ago"])+def test_data_parsing_variations(benchmark, date_str):+ """Compare speed of different date formats."""+ normalizer = DateNormalizer()+ benchmark.pedantic(+ lambda: normalizer.normalize_date(date_str), iterations=10, rounds=20+ )+++def test_number_normalization(benchmark):+ """Benchmarks number parsing with currency and unit stripping."""+ normalizer = NumberNormalizer()+ raw_inputs = ["$1,234.56", "1.5k", "50%", "1,000,000"] * 100++ def run():+ for n in raw_inputs:+ normalizer.normalize_number(n)++ benchmark.pedantic(run, iterations=5, rounds=20)diff --git a/benchmarks/normalize/test_text_processing.py b/benchmarks/normalize/test_text_processing.pynew file mode 100644index 00000000..54c91733--- /dev/null+++ b/benchmarks/normalize/test_text_processing.py@@ -0,0 +1,42 @@+import pytest++from semantica.normalize.text_cleaner import TextCleaner+from semantica.normalize.text_normalizer import TextNormalizer+++def test_html_removal_reg_vs_bs4(benchmark, generate_text_data):+ """+ Compare regex vs BeautifulSoup.+ """+ cleaner = TextCleaner()+ html_content = generate_text_data("html", 10_000)++ def run():+ return cleaner.remove_html(html_content, preserve_structure=False)++ benchmark.pedantic(run, rounds=50, iterations=10)+++def test_unicode_normalization_throughput(benchmark, generate_text_data):+ """+ Benchmarks unicode NFC normalization speed.+ """+ normalizer = TextNormalizer()+ text = generate_text_data("unicode", 50_000)++ def run():+ return normalizer.normalize_text(text, unicode_form="NFC")++ benchmark.pedantic(run, iterations=5, rounds=10)+++def test_whitespace_normalization(benchmark, generate_text_data):+ """Benchmarks whitespace regex replacement."""+ normalizer = TextNormalizer()+ text = generate_text_data("dirty", 50_000)++ benchmark.pedantic(+ lambda: normalizer.normalize_text(text, unicode_form="NFC"),+ iterations=5,+ rounds=10,+ )diff --git a/benchmarks/ontology/conftest.py b/benchmarks/ontology/conftest.pynew file mode 100644index 00000000..82a86c3e--- /dev/null+++ b/benchmarks/ontology/conftest.py@@ -0,0 +1,85 @@+import random+import string+from unittest.mock import MagicMock, patch++import pytest++# Data generators+++def _random_str(length=8):+ return "".join(random.choices(string.ascii_letters, k=length))+++def generate_ontology_data():+ """+ Generates a synthetic dataset of entities and relationships+ designed to triger class and property inference class.+ """++ def _generate(entity_count: int, relationship_density: float = 1.5):++ num_classes = max(5, entity_count // 50)+ class_names = [f"Class_{_random_str(4)}" for _ in range(num_classes)]++ entities = []++ for i in range(entity_count):+ cls = random.choice(class_names)++ props = {+ f"prop_{_random_str(3)}": random.choice([10, "text", 1.5, True])+ for _ in range(random.randint(1, 5))+ }++ entity = {+ "id": f"e_{i}",+ "type": cls,+ "name": f"Entity_{i}",+ "confidence": 0.95,+ **props,+ }++ entities.append(entity)++ relationships = []+ rel_count = int(entity_count * relationship_density)+ rel_types = ["relatedTo", "hasPart", "worksFor", "contains", "memberOf"]++ for _ in range(rel_count):+ src = random.choice(entities)+ tgt = random.choice(entities)+ rel = {+ "source": src["name"],+ "target": tgt["name"],+ "type": random.choice(rel_types),+ "source_type": src["type"],+ "target_type": tgt["type"],+ "confidence": 0.8,+ }+ relationships.append(rel)++ return {"entities": entities, "relationships": relationships}++ return _generate+++def large_ontology_definition(generate_ontology_data):+ """Pre-calculates a structured ontology+ definition dictionary.+ """+ from semantica.ontology.ontology_generator import OntologyGenerator++ data = generate_ontology_data(entity_count=1000)++ # Mocking validation in 6-step pipeline to speed up setup++ with patch(+ "semantica.ontology.ontology_validator.OntologyValidator.validate"+ ) as mock_val:+ mock_val.return_value.valid = True+ gen = OntologyGenerator()++ return gen.generate_ontology(data, validate=False)diff --git a/benchmarks/ontology/test_inference.py b/benchmarks/ontology/test_inference.pynew file mode 100644index 00000000..2dd71415--- /dev/null+++ b/benchmarks/ontology/test_inference.py@@ -0,0 +1,70 @@+import pytest++from semantica.ontology.class_inferrer import ClassInferrer+from semantica.ontology.property_generator import PropertyGenerator++[email protected](group="class_Inference")[email protected]("entity_count", [1000, 5000])+def test_class_inference_scaling(benchmark, generate_ontology_data, entity_count):+ """+ Benchmarks grouping and threshold logic in ClassInferrer.+ """++ data = generate_ontology_data(entity_count=entity_count)+ inferrer = ClassInferrer(min_occurrences=2)++ def run():+ return inferrer.infer_classes(data["entities"])++ benchmark.pedantic(run, iterations=1, rounds=5)++[email protected](group="property_inference")[email protected]("size", [(1000, 1500)])+def test_property_inference_scaling(benchmark, generate_ontology_data, size):+ """+ Benchmarks: PropertyGenerator+ """++ e_count, _ = size+ data = generate_ontology_data(entity_count=e_count)++ inferrer = ClassInferrer()+ classes = inferrer.infer_classes(data["entities"])++ prop_gen = PropertyGenerator()++ def run():+ return prop_gen.infer_properties(+ entities=data["entities"],+ relationships=data["relationships"],+ classes=classes,+ )++ benchmark.pedantic(run, iterations=1, rounds=5)+++def test_hierarchy_circular_detection(benchmark):+ """+ Benchmarks the DFS cycle detection in ClassInferrer.+ """++ inferrer = ClassInferrer()++ # Create a deep chain A -> B -> C ... -> Z++ chain_length = 200+ classes = []++ for i in range(chain_length):+ cls = {+ "name": f"Class_{i}",+ "subClassOf": f"Class_{i+1}" if i < chain_length - 1 else None,+ }+ classes.append(cls)++ def run():+ return inferrer.validate_classes(classes)++ benchmark.pedantic(run, iterations=1, rounds=10)diff --git a/benchmarks/ontology/test_ontology_pipeline.py b/benchmarks/ontology/test_ontology_pipeline.pynew file mode 100644index 00000000..7cd4ed38--- /dev/null+++ b/benchmarks/ontology/test_ontology_pipeline.py@@ -0,0 +1,46 @@+from unittest.mock import MagicMock, patch++import pytest++from semantica.ontology.ontology_generator import OntologyGenerator++[email protected](group="full_pipeline")[email protected]("entity_count", [1000])+def test_e2e_ontology_generation(benchmark, generate_ontology_data, entity_count):+ """+ Benchmarks complete 6-stage pipeline+ """++ data = generate_ontology_data(entity_count)+ generator = OntologyGenerator()++ with patch(+ "semantica.ontology.ontology_validator.OntologyValidator.validate"+ ) as mock_val:+ mock_val.return_value.valid = True++ def run():+ return generator.generate_ontology(data, validate=True)++ benchmark.pedantic(run, iterations=1, rounds=5)+++def test_associative_class_creation(benchmark):+ """+ Benchmarks the creation of complex N-ary relationships.+ """+ from semantica.ontology.associative_class import AssociativeClassBuilder++ builder = AssociativeClassBuilder()++ def run():+ for i in range(50):+ builder.create_position_class(+ person_class=f"Person_{i}",+ organization_class=f"Org_{i}",+ role_class=f"Role_{i}",+ name=f"Position_{i}",+ )++ benchmark.pedantic(run, iterations=1, rounds=10)diff --git a/benchmarks/ontology/test_reuse.py b/benchmarks/ontology/test_reuse.pynew file mode 100644index 00000000..2d925d9d--- /dev/null+++ b/benchmarks/ontology/test_reuse.py@@ -0,0 +1,43 @@+import pytest++from semantica.ontology.namespace_manager import NamespaceManager+from semantica.ontology.reuse_manager import ReuseManager+++def test_namespace_iri_generation(benchmark):+ """+ High-throughput test for IRI Generation.+ """+ manager = NamespaceManager(base_uri="https://semantica.dev/bench/")+ names = [f"EntityName_{i}" for i in range(1000)]++ def run():+ for name in names:+ manager.generate_class_iri(name)++ benchmark.pedantic(run, iterations=1, rounds=20)+++def test_ontology_merging(benchmark, large_ontology_definition):+ """+ Benchmarks merging two large entities together.+ """+ manager = ReuseManager()+ target = large_ontology_definition.copy()+ source = large_ontology_definition.copy()++ new_classes = []++ for c in source["classes"]:+ base_id = c.get("uri") or c.get("name") or "UnkownEntity"+ new_c = c.copy()+ new_c["uri"] = f"{base_id}_merged"+ new_classes.append(new_c)++ source["classes"] = new_classes++ def run():+ t_copy = target.copy()+ return manager.merge_ontology_data(t_copy, source, overwrite=False)++ benchmark.pedantic(run, iterations=1, rounds=10)diff --git a/benchmarks/ontology/test_serialization.py b/benchmarks/ontology/test_serialization.pynew file mode 100644index 00000000..6b7615cf--- /dev/null+++ b/benchmarks/ontology/test_serialization.py@@ -0,0 +1,33 @@+import pytest++from semantica.ontology.owl_generator import OWLGenerator++[email protected](group="serialization")[email protected]("format", ["turtle", "xml"])+def test_owl_serialization_formats(benchmark, large_ontology_definition, format):+ """Benchmarks the cost of serializing the ontology+ to different string formats.+ """+ generator = OWLGenerator()++ def run():+ return generator.generate_owl(large_ontology_definition, format=format)++ benchmark.pedantic(run, iterations=1, rounds=5)+++def test_rdflib_graph_construction(benchmark, large_ontology_definition):+ """+ Benchmarks the creation of rdflib.Graph object.+ """+ generator = OWLGenerator()++ def run():+ if hasattr(generator, "_generate_with_rdflib"):+ return generator._generate_with_rdflib(+ large_ontology_definition, format="turtle"+ )+ return generator.generate_owl(large_ontology_definition)++ benchmark.pedantic(run, iterations=1, rounds=5)diff --git a/benchmarks/output_orchestration/test_execution_pipeline.py b/benchmarks/output_orchestration/test_execution_pipeline.pynew file mode 100644index 00000000..86e3faf6--- /dev/null+++ b/benchmarks/output_orchestration/test_execution_pipeline.py@@ -0,0 +1,98 @@+from unittest.mock import MagicMock, patch++import pytest++from semantica.pipeline.execution_engine import ExecutionEngine+from semantica.pipeline.pipeline_builder import PipelineBuilder, StepStatus+from semantica.pipeline.resource_scheduler import ResourceScheduler+++# ~~ Fixtures[email protected](autouse=True)+def kill_hardware_checks():+ with patch.object(ResourceScheduler, "_initialize_resources", return_value=None):+ yield++[email protected](autouse=True)+def kill_logging():+ with patch("semantica.utils.logging.get_logger"):+ yield++[email protected](autouse=True)+def kill_tracker():+ mock_tracker = MagicMock()+ mock_tracker.enabled = False+ with patch(+ "semantica.pipeline.execution_engine.get_progress_tracker",+ return_value=mock_tracker,+ ):+ yield+++def create_pipeline(size):+ """Helper to generate pipelines of random size."""+ builder = PipelineBuilder()+ builder.progress_tracker = MagicMock()+ builder.progress_tracker.enabled = False+ handler = lambda x, **k: x++ builder.add_step("start", "dummy", handler=handler)+ for i in range(1, size):+ builder.add_step(f"step_{i}", "dummy", handler=handler)+ builder.connect_steps("start" if i == 1 else f"step_{i-1}", f"step_{i}")++ return builder.build(f"bench_pipe_{size}")+++# ~~ Benchmarks ~~++[email protected]("step_count", [10, 100, 500])+def test_pipeline_construction_scaling(benchmark, step_count):+ """+ Verifies if construction time scales linearly.+ """++ def op():+ builder = PipelineBuilder()+ builder.progress_tracker = MagicMock()+ for i in range(step_count):+ builder.add_step(f"s{i}", "t")+ return builder.build()++ benchmark.pedantic(op, iterations=5, rounds=5)++[email protected]("step_count", [10, 100])+def test_execution_overhead_scaling(benchmark, step_count):+ """+ Measures per-step overhead as it gets more complex+ """+ engine = ExecutionEngine()+ pipeline = create_pipeline(step_count)++ def setup_run():+ for step in pipeline.steps:+ step.status = StepStatus.PENDING+ step.result = None+ return (pipeline,), {"data": {"val": 1}}++ def op(pipeline, data):+ return engine.execute_pipeline(pipeline, data=data)++ benchmark.pedantic(op, setup=setup_run, iterations=1, rounds=10)++[email protected]("step_count", [10, 100, 1000])+def test_topological_sort_scaling(benchmark, step_count):+ """+ Stress test for dependency graph algorithm.+ """+ engine = ExecutionEngine()+ pipeline = create_pipeline(step_count)++ benchmark.pedantic(+ lambda: engine._topological_sort(pipeline.steps), iterations=20, rounds=10+ )diff --git a/benchmarks/output_orchestration/test_parallelism.py b/benchmarks/output_orchestration/test_parallelism.pynew file mode 100644index 00000000..335b6417--- /dev/null+++ b/benchmarks/output_orchestration/test_parallelism.py@@ -0,0 +1,91 @@+import time+from unittest.mock import MagicMock, patch++import pytest++from semantica.pipeline.parallelism_manager import ParallelismManager, Task+from semantica.pipeline.resource_scheduler import ResourceScheduler+++# ~~ Fixtures ~~[email protected](autouse=True)+def kill_hardware_checks():+ with patch.object(ResourceScheduler, "_initialize_resources", return_value=None):+ yield++[email protected](autouse=True)+def kill_logging():+ with patch("semantica.utils.logging.get_logger"):+ yield++[email protected](autouse=True)+def kill_tracker():+ mock_tracker = MagicMock()+ mock_tracker.enabled = False+ with patch(+ "semantica.pipeline.parallelism_manager.get_progress_tracker",+ return_value=mock_tracker,+ ):+ yield+++def blocking_task(duration):+ """Simulates a task that waits for I/O (like a DB query or API call)."""+ time.sleep(duration)+ return True+++def thread_manager():+ return ParallelismManager(max_workers=4, use_processes=False)+++def process_manager():+ return ParallelismManager(max_workers=4, use_processes=True)+++# ~~ BENCHMARKS ~~+++def test_parallel_vs_serial_io(benchmark, thread_manager):+ """+ Runs 4 tasks that sleep for 0.1s.+ """+ tasks = [+ Task(task_id=f"t{i}", handler=blocking_task, args=(0.1,)) for i in range(4)+ ]++ def op():+ return thread_manager.execute_parallel(tasks)++ benchmark.pedantic(op, iterations=1, rounds=5)+++def test_thread_pool_overhead(benchmark, thread_manager):+ """+ Measures the raw cost of spinning up threads for zero-work tasks.+ """+ # No-op handler+ noop = lambda: None+ tasks = [Task(task_id=f"t{i}", handler=noop) for i in range(100)]++ def op():+ return thread_manager.execute_parallel(tasks)++ benchmark.pedantic(op, iterations=5, rounds=10)+++def test_process_pool_overhead(benchmark, process_manager):+ """+ Measures overhead of ProcessPoolExecutor+ """+ noop = lambda: None+ tasks = [Task(task_id=f"t{i}", handler=noop) for i in range(10)]++ def op():+ return process_manager.execute_parallel(tasks)++ benchmark.pedantic(op, iterations=1, rounds=5)diff --git a/benchmarks/quality_assurance/test_conflicts.py b/benchmarks/quality_assurance/test_conflicts.pynew file mode 100644index 00000000..4e7ed231--- /dev/null+++ b/benchmarks/quality_assurance/test_conflicts.py@@ -0,0 +1,84 @@+from unittest.mock import MagicMock, patch++import pytest++from semantica.deduplication.merge_strategy import MergeStrategy, MergeStrategyManager++# Fixtures+++def conflict_manager():+ """Returns a MergeStrategyManager with default settings."""+ return MergeStrategyManager()+++def conflicting_entities_batch():+ """+ Generates a list of 100 entities that are all 'duplicates' of each other+ but have conflicting property values. This forces the resolution logic to run hard.+ """+ entities = []+ for i in range(100):+ entities.append(+ {+ "id": "e_1",+ "name": f"Entity Name {i}",+ "type": "Person",+ "confidence": 0.5 + (i * 0.005),+ "properties": {+ "age": 20 + i,+ "email": f"user{i}@example.com",+ "status": "active" if i % 2 == 0 else "inactive",+ },+ "relationships": [+ {"source": "e_1", "target": f"other_{i}", "type": "knows"}+ ],+ }+ )+ return entities+++# Benchmarks+++def test_strategy_keep_highest_confidence(+ benchmark, conflict_manager, conflicting_entities_batch+):+ """+ Benchmarks 'KEEP_HIGHEST_CONFIDENCE'.+ """++ def op():+ return conflict_manager.merge_entities(+ conflicting_entities_batch, strategy=MergeStrategy.KEEP_HIGHEST_CONFIDENCE+ )++ benchmark.pedantic(op, iterations=10, rounds=10)+++def test_strategy_merge_all(benchmark, conflict_manager, conflicting_entities_batch):+ """+ Benchmarks 'MERGE_ALL'.+ """++ def op():+ return conflict_manager.merge_entities(+ conflicting_entities_batch, strategy=MergeStrategy.MERGE_ALL+ )++ benchmark.pedantic(op, iterations=10, rounds=10)+++def test_property_resolution_overhead(benchmark, conflict_manager):+ """+ Micro-benchmark for the inner _resolve_property_conflict logic.+ """++ def op():+ return conflict_manager._resolve_property_conflict(+ "age", 25, 30, MergeStrategy.KEEP_MOST_COMPLETE+ )++ benchmark.pedantic(op, iterations=1000, rounds=20)diff --git a/benchmarks/quality_assurance/test_deduplication.py b/benchmarks/quality_assurance/test_deduplication.pynew file mode 100644index 00000000..7ba0042d--- /dev/null+++ b/benchmarks/quality_assurance/test_deduplication.py@@ -0,0 +1,255 @@+import random+import string+import time+from typing import Any, Dict, List+from unittest.mock import patch++import numpy as np+import pytest++from semantica.deduplication.cluster_builder import ClusterBuilder+from semantica.deduplication.duplicate_detector import DuplicateDetector+from semantica.deduplication.entity_merger import EntityMerger+from semantica.deduplication.similarity_calculator import SimilarityCalculator++# Infra+++class NullTracker:+ """+ Discards all data to prevent memory leaks+ """++ def start_tracking(self, *args, **kwargs):+ return "dummy_id"++ def update_tracking(self, *args, **kwargs):+ pass++ def stop_tracking(self, *args, **kwargs):+ pass++ def register_pipeline_modules(self, *args, **kwargs):+ pass++ def clear_pipeline_context(self, *args, **kwargs):+ pass++ def update_progress(self, *args, **kwargs):+ pass++ @property+ def enabled(self):+ return False++ @enabled.setter+ def enabled(self, value):+ pass++[email protected](autouse=True)+def kill_io_overhead():+ """+ Replaces ProgressTracker with NullTracker globally.+ """+ with patch("semantica.utils.logging.get_logger"), patch(+ "semantica.utils.progress_tracker.get_progress_tracker"+ ) as mock_getter:++ mock_getter.return_value = NullTracker()++ with patch(+ "semantica.deduplication.similarity_calculator.get_progress_tracker",+ return_value=NullTracker(),+ ), patch(+ "semantica.deduplication.duplicate_detector.get_progress_tracker",+ return_value=NullTracker(),+ ), patch(+ "semantica.deduplication.cluster_builder.get_progress_tracker",+ return_value=NullTracker(),+ ):+ yield+++# Sim data+++def generate_entity_cluster(base_name: str, size: int) -> List[Dict[str, Any]]:+ """+ Generates a cluster of similar entities based on a seed name.+ Example: "Apple" -> ["Apple Inc", "Apple Corp", etc.]+ """++ entities = []+ suffixes = ["Inc", "Corp", "Ltd", "Gmbh", "LLC", "Group", "Systems"]++ for i in range(size):+ if random.random() < 0.8:+ name = f"{base_name} {random.choice(suffixes)}"+ else:+ # Generating a typo for our calc to work on+ chars = list(base_name)+ if len(chars) > 2:+ idx = random.randint(0, len(chars) - 2)+ chars[idx], chars[idx + 1] = chars[idx + 1], chars[idx]+ name = "".join(chars)++ entities.append(+ {+ "id": f"{base_name.lower()}_{i}",+ "name": name,+ "type": "Organization",+ "properties": {+ "location": "USA" if i % 2 == 0 else "California",+ "sector": "Tech",+ "employee_count": 100 + i,+ },+ }+ )++ return entities+++def generate_dataset(+ num_clusters: int, items_per_cluster: int, worst_case_blocking: bool = False+):+ """+ Generates a full dataset++ Args:+ worst_case_blocking: If True, all names start with 'A' to defeat+ first-char blocking strategy in SimilarityCalculator.++ """+ dataset = []+ for i in range(num_clusters):+ if worst_case_blocking:+ # All starts with 'A'+ base_name = f"A_Company_{i}"+ else:+ start_char = random.choice(string.ascii_uppercase)+ base_name = f"{start_char}_company_{i}"++ cluster = generate_entity_cluster(base_name, items_per_cluster)+ dataset.extend(cluster)++ return dataset+++# ~~ Benchmarks ~~++[email protected]("method", ["levenshtein", "jaro_winkler"])+def test_string_metric_speed(benchmark, method):+ """+ Measures the speed of string comparison algos.+ """++ calc = SimilarityCalculator()+ s1 = "International Business Machines Corporation"+ s2 = "International Business Machine Corp."++ benchmark.pedantic(+ lambda: calc.calculate_string_similarity(s1, s2, method=method),+ iterations=1000,+ rounds=100,+ )+++def test_full_similarity_calculation(benchmark):+ """+ Measures weighted multi-factor calculation overhead.+ (String + Property + Relationship + Weights).+ """++ calc = SimilarityCalculator(+ string_weight=0.5, property_weight=0.3, relationship_weight=0.2+ )++ e1 = {+ "name": "Acme Corp",+ "properties": {"loc": "NY", "id": "123"},+ "relationships": [{"target": "t1"}, {"target": "t2"}],+ }++ e2 = {+ "name": "Acme Inc",+ "properties": {"loc": "NY", "id": "123"},+ "relationships": [{"target": "t1"}, {"target": "t2"}],+ }++ benchmark.pedantic(+ lambda: calc.calculate_similarity(e1, e2), iterations=1000, rounds=50+ )++[email protected]("dataset_size", [100, 500])+def test_duplicate_detection_scaling_opt(benchmark, dataset_size):+ """+ Tests duplication on a 'Distributed' dataset (Best Case)+ """++ data = generate_dataset(+ num_clusters=dataset_size // 10, items_per_cluster=10, worst_case_blocking=False+ )+ detector = DuplicateDetector(similarity_threshold=0.8)++ benchmark.pedantic(lambda: detector.detect_duplicates(data), iterations=1, rounds=5)++[email protected]("dataset_size", [100, 500])+def test_duplicate_detection_worst_Case(benchmark, dataset_size):+ """+ Tests detection on a 'Clustered' dataset (Worst Case).+ """++ data = generate_dataset(+ num_clusters=dataset_size // 10, items_per_cluster=10, worst_case_blocking=True+ )+ detector = DuplicateDetector(similarity_threshold=0.8)++ benchmark.pedantic(lambda: detector.detect_duplicates(data), iterations=1, rounds=5)+++def test_incremental_detection_speed(benchmark):+ """+ Measures performance of adding new data to existing index.+ """++ existing = generate_dataset(num_clusters=50, items_per_cluster=5)+ new_data = generate_dataset(num_clusters=5, items_per_cluster=2)++ detector = DuplicateDetector()++ benchmark.pedantic(+ lambda: detector.incremental_detect(new_data, existing), iterations=5, rounds=10+ )++[email protected]("algo", ["graph", "hierarchical"])+def test_clustering_strategy_performance(benchmark, algo):+ """+ Comapres Union-Fund (Graph) vs Hierarchical Clustering.+ """++ data = generate_dataset(num_clusters=20, items_per_cluster=10)++ use_hierarchical = algo == "hierarchical"+ builder = ClusterBuilder(use_hierarchical=use_hierarchical)++ benchmark.pedantic(lambda: builder.build_clusters(data), iterations=1, rounds=5)+++def test_merge_entity_benchmark(benchmark):+ """+ Measures the cost of fusing entities / res conflicts.+ """++ group = generate_entity_cluster("MegaCorp", 50)+ merger = EntityMerger()++ benchmark.pedantic(+ lambda: merger.merge_entity_group(group, strategy="keep_most_complete"),+ iterations=10,+ rounds=10,+ )diff --git a/benchmarks/requirements.txt b/benchmarks/requirements.txtnew file mode 100644index 00000000..5dbebddf--- /dev/null+++ b/benchmarks/requirements.txt@@ -0,0 +1,43 @@+# Benchmark Tools++pytest>=7.0.0+pytest-benchmark>=4.0.0++# Core Utils++pydantic+loguru+chardet+requests+greenlet+typing-extensions+tqdm+click+rich++numpy+pandas+networkx+scikit-learn++# Graph & Storage++sqlalchemy+rdflib+neo4j+redis++# AI proc++torch+transformers+sentence-transformers+spacy+beautifulsoup4+lxml+pypdf2+python-docx+openpyxl+pillow+feedparser+GitPythondiff --git a/benchmarks/storage/test_embeddings.py b/benchmarks/storage/test_embeddings.pynew file mode 100644index 00000000..92ef879d--- /dev/null+++ b/benchmarks/storage/test_embeddings.py@@ -0,0 +1,180 @@+from typing import Generator, List+from unittest.mock import MagicMock, patch++import numpy as np+import pytest++from semantica.embeddings.embedding_generator import EmbeddingGenerator+from semantica.embeddings.graph_embedding_manager import GraphEmbeddingManager+from semantica.embeddings.pooling_strategies import PoolingStrategyFactory+from semantica.embeddings.text_embedder import TextEmbedder+++# Infra Mocks[email protected](autouse=True)+def kill_io_overhead():+ """Silences logging and tracker globally."""+ with patch("semantica.utils.logging.get_logger"), patch(+ "semantica.utils.progress_tracker.get_progress_tracker"+ ) as mock_tracker:++ tracker = MagicMock()+ tracker.enabled = False+ tracker._start_tracking.return_value = "dummy_id"+ mock_tracker.return_value = tracker++ with patch(+ "semantica.embeddings.text_embedder.get_progress_tracker",+ return_value=tracker,+ ):+ yield+++# __ Model Mocks __+++class MockSentenceTransformer:+ """+ Simulates ST.encode without loading the fat model itself.+ """++ def __init__(self, dim=384):+ self.dim = dim++ def encode(+ self, sentences: List[str], normalize_embeddings=True, **kwargs+ ) -> np.ndarray:+ count = len(sentences)+ return np.random.rand(count, self.dim).astype(np.float32)++ def get_sentence_embedding_dimension(self):+ return self.dim+++class MockFastEmbed:+ """+ Simulates FastEmbed.embed generator behavior.+ """++ def __init__(self, dim=384):+ self.dim = dim++ def embed(self, documents: List[str]) -> Generator[np.ndarray, None, None]:+ for _ in documents:+ yield np.random.rand(self.dim).astype(np.float32)+++# ~~ Fixtures ~~+def text_embedder_st():+ """+ Text embedder configured with SentenceTransformer+ """+ embedder = TextEmbedder(method="sentence_transformers", model_name="mock-bert")+ embedder.model = MockSentenceTransformer()+ embedder.progress_tracker = MagicMock()+ embedder.progress_tracker.enabled = False++ return embedder+++def text_embedder_fast():+ """+ Text Embedder cofnigures with Mock FastEmbed.+ """++ embedder = TextEmbedder(method="fastembed", model_name="mock-bge")+ embedder.fastembed_model = MockFastEmbed()+ embedder.progress_tracker = MagicMock()+ embedder.progress_tracker.enabled = False+ return embedder+++# ~~ Benchmarks++[email protected]("strategy", ["mean", "max", "cls", "attention"])+def test_pooling_math_speed(benchmark, strategy):+ """+ Measures the raw NumPy speed of pooling strategies.+ Scenario: Pooling a batch of 128 token embeddings.+ """++ embeddings = np.random.rand(128, 768).astype(np.float32)+ pooler = PoolingStrategyFactory.create(strategy)++ benchmark.pedantic(lambda: pooler.pool(embeddings), iterations=1000, rounds=100)+++def test_hierarchical_pooling_overhead(benchmark):+ """+ Measures the overhead of two-step hierarchical pooling.+ """++ embeddings = np.random.rand(1000, 768).astype(np.float32)+ pooler = PoolingStrategyFactory.create("hierarchical", chunk_size=100)++ benchmark.pedantic(lambda: pooler.pool(embeddings), iterations=500, rounds=50)+++def test_st_wrapper_overhead(benchmark, text_embedder_st):+ """+ Measures overhead of TextEmbedder wrapper around SentenceTransformers.+ """++ text = "This is a whatever we are doing here since idk"++ benchmark.pedantic(+ lambda: text_embedder_st.embed_text(text), iterations=1000, rounds=20+ )+++def test_fastembed_generator_consumption(benchmark, text_embedder_fast):+ """+ Measures the cost of consuming the FastEmbed generator+ and converting to Array.+ """+ texts = [f"Sentence {i}" for i in range(20)]++ benchmark.pedantic(+ lambda: text_embedder_fast.embed_batch(texts), iterations=100, rounds=20+ )++[email protected]("batch_size", [10, 100, 1000])+def test_batch_processing_pipeline(benchmark, batch_size, text_embedder_st):+ """+ Measures the full EmbeddingGenerator pipeline:+ Input validation -> Type detection -> Batching -> Mock Model -> Error handling.+ """++ generator = EmbeddingGenerator()++ generator.text_embedder = text_embedder_st+ generator.progress_tracker = MagicMock()+ generator.progress_tracker.enabled = False++ data = [f"Item {i}" for i in range(batch_size)]++ benchmark.pedantic(lambda: generator.process_batch(data), iterations=5, rounds=10)++[email protected]("count", [100, 1000])+def test_graph_embedding_prep(benchmark, count, text_embedder_st):+ """+ Measures how fast we can reshape dict for GraphDBs+ """+ manager = GraphEmbeddingManager()+ manager.embedding_generator.text_embedder = text_embedder_st++ manager.embedding_generator.generate_embeddings = MagicMock(+ return_value=np.random.rand(count, 384).astype(np.float32)+ )++ entities = [{"id": f"e{i}", "text": f"Entity{i}"} for i in range(count)]++ def op():+ return manager.prepare_for_graph_db(entities, backend="neo4j")++ benchmark.pedantic(op, iterations=10, rounds=10)diff --git a/benchmarks/storage/test_graph_store.py b/benchmarks/storage/test_graph_store.pynew file mode 100644index 00000000..42b94936--- /dev/null+++ b/benchmarks/storage/test_graph_store.py@@ -0,0 +1,137 @@+from unittest.mock import MagicMock, patch++import pytest++from semantica.graph_store.graph_store import GraphStore+++def mock_neo4j_driver():+ """+ Creates a mock of of Neo4j Driver+ Simulates: Driver -> Session -> Transaction -> Result -> Record+ """++ mock_result = MagicMock()+ fake_props = {"name": "TestNode", "age": 30}++ def get_item(key):+ if key == "id":+ return 12345+ if key == "n":+ return fake_props+ if key == "count":+ return 42+ return None++ mock_record = MagicMock()+ mock_record.__getitem__.side_effect = get_item+ mock_record.keys.return_value = ["id", "n"]+ mock_record.values.return_value = [12345, fake_props]++ # dict conversion - essentially doing it because the db sometimes demands it+ mock_record.items.return_value = [("id", 12345), ("n", fake_props)]++ # ~~ Result Methods ~~+ mock_result = MagicMock()+ mock_result.single.return_value = mock_record+ mock_result.__iter__.side_effect = lambda: iter([mock_record])++ # ~~ Session ~~+ mock_session = MagicMock()+ mock_session.run.return_value = mock_result+ mock_session.__enter__.return_value = mock_session+ mock_session.__exit__.return_value = None++ # ~~ Driver ~~+ mock_driver = MagicMock()+ mock_driver.session.return_value = mock_session+ mock_driver.verify_connectivity.return_value = True++ return mock_driver+++def graph_store(mock_neo4j_driver):+ """+ Returns a GraphsStore connected to mnock driver.+ """++ # ~~ Patch GraphDatbase ~~+ with patch("semantica.graph_store.neo4j_store.GraphDatabase") as mockDB:+ mockDB.driver.return_value = mock_neo4j_driver+ store = GraphStore(+ backend="neo4j", uri="bolt://mock:7687", user="mock", password="mock"+ )+ store.connect()++ if hasattr(store, "progress_tracker"):+ store.progress_tracker = MagicMock()++ return store+++# ~~ Benchmarks ~~+++def test_node_creation_overhead(benchmark, graph_store):+ """+ Benchamrks the full stack overhead for creating a single node.+ Path: GraphStore -> NodeManager -> Neo4jStore, Driver+ """++ def op():+ return graph_store.create_node(+ labels=["Person"], properties={"name": "Alexander", "age": 17}+ )++ result = benchmark(op)+ assert result["id"] == 12345+++def test_batch_node_creation_overhead(benchmark, graph_store):+ """+ Benchmarks the loop overhead in create_nodes (Batch).+ Checks if it handles lists efficiently.+ """++ nodes = [{"labels": ["Person"], "properties": {"id": i}} for i in range(50)]++ def op():+ return graph_store.create_nodes(nodes)++ result = benchmark(op)+ assert len(result) == 50+++def test_query_construction_and_parsing(benchmark, graph_store):+ """+ Benchmarks every execution overhead.+ Measures how fast `QueryEngine` parses result into a Python dict.+ """++ query = "MATCH ( n:Person) RETURN n LIMIT 1"++ def op():+ return graph_store.execute_query(query)++ result = benchmark(op)+ assert result["success"] is True+ assert len(result["records"]) > 0+++def test_analytics_shortest_path_overhead(benchmark, graph_store):+ """+ Benchmarks the wrapper overhead for graph analytics.+ """++ def op():+ return graph_store.shortest_path(+ start_node_id=1, end_node_id=2, rel_type="KNOWS"+ )++ try:+ benchmark(op)+ except Exception:+ # v pass as we are only trying to benchmark the function overhead call mainly+ passdiff --git a/benchmarks/storage/test_triplet_storage.py b/benchmarks/storage/test_triplet_storage.pynew file mode 100644index 00000000..002142cb--- /dev/null+++ b/benchmarks/storage/test_triplet_storage.py@@ -0,0 +1,146 @@+import time+from dataclasses import dataclass+from unittest.mock import MagicMock, patch++import pytest++from semantica.triplet_store.bulk_loader import BulkLoader+from semantica.triplet_store.jena_store import JenaStore+from semantica.triplet_store.triplet_store import TripletStore++# ~~ Mocking ~~+# We basically define a facile Triplet class for creating ds devoid of fat AI models+++@dataclass+class SimpleTriplet:+ subject: str+ predicate: str+ object: str+ confidence: float = 1.0+++# ~~ Fixtures ~~+def triplet_batch():+ """Generates 1000 triplets."""+ return [+ SimpleTriplet(+ subject=f"http://gandhara.org/entity/{i}",+ predicate="http://gandhara.org/relation/knows",+ object=f"http://example.org/entity/{i+1}",+ )+ for i in range(1000)+ ]+++def large_knowledge_graph_dict():+ """+ Generates a large dict (1000 ent) to test parsing+ logic in `TripletStore.store()`+ """+ entities = [+ {+ "id": f"ent_{i}",+ "type": "Person",+ "properties": {"name": f"Person {i}", "age": 60},+ }+ for i in range(1000)+ ]+ relationships = [+ {"source": f"ent_{i}", "target": f"ent_{i+1}", "type": "KNOWS"}+ for i in range(999)+ ]++ return {"entities": entities, "relationships": relationships}+++def in_memory_store():+ """Returns a real JenaStore using RDFLib (In-Mmeory)."""++ store = JenaStore(endpoint=None)+ if store.graph is None:+ pytest.fail("JenaStore failed to initialize rdflib graph.")+ if hasattr(store, "progress_tracker"):+ store.progress_tracker = MagicMock()++ return store+++# ~~ Benchmarks ~~+++def test_rdflib_insert_throughput(benchmark, in_memory_store, triplet_batch):+ """+ Benchmarks raw Write Speed to in-memory RDF graph.+ Is our baseline+ """++ def op():+ in_memory_store.add_triplets(triplet_batch)++ benchmark(op)++ assert len(in_memory_store.graph) >= 1000+++def test_triplet_conversion_overhead(benchmark, large_knowledge_graph_dict):+ """+ Benchmarks the `store()` method in TripletStore.+ This tests Python logic that converts a Dict -> Triplet objects.+ """++ with patch("semantica.triplet_store.blazegraph_store.BlazegraphStore") as mockBE:+ mock_instance = mockBE.return_value+ mock_instance.add_triplets.return_value = {"success": True}++ manager = TripletStore(backend="blazegraph")+ if hasattr(manager, "progress_tracker"):+ manager.progress_tracker = MagicMock()++ def op():+ manager.store(+ knowledge_graph=large_knowledge_graph_dict,+ ontology={"classes": [], "properties": []},+ )++ benchmark(op)+++def test_bulk_loader_logic(benchmark, triplet_batch):+ """+ Benchmarks teh BulkLoader class.+ Measures the overhead of batching, retries and progress tracking.+ """++ loader = BulkLoader(batch_size=100)+ if hasattr(loader, "progress_tracker"):+ loader.progress_tracker = MagicMock()++ mock_store = MagicMock()+ mock_store.add_triplets.return_value = {"success": True}++ def op():+ return loader.load_triplets(triplet_batch, mock_store)++ result = benchmark(op)+ assert result.total_batches == 10+++def test_sparql_query_performance(benchmark, in_memory_store, triplet_batch):+ """+ Benchamrks SPARQL query execution speed on 1000 items.+ """++ in_memory_store.add_triplets(triplet_batch)++ query = "SELECT ?s ?o WHERE { ?s <http://gandhara.org/relation/knows> ?o } LIMIT 50"++ def op():+ return in_memory_store.execute_sparql(query)++ result = benchmark(op)+ assert result["success"] is True+ assert len(result["bindings"]) == 50diff --git a/benchmarks/storage/test_vector_storage.py b/benchmarks/storage/test_vector_storage.pynew file mode 100644index 00000000..896dc5d2--- /dev/null+++ b/benchmarks/storage/test_vector_storage.py@@ -0,0 +1,85 @@+from unittest.mock import MagicMock, patch++import numpy as np+import pytest++from semantica.vector_store.faiss_store import FAISSStore+from semantica.vector_store.vector_store import VectorStore++# Fixtures+++def vector_dim():+ return 768+++def random_vectors(vector_dim):+ """Generates a batch of 10,000 rando vectors."""+ count = 10000+ vectors = np.random.rand(count, vector_dim).astype(np.float32)+ return vectors+++def populated_store(random_vectors, vector_dim):+ """+ Returns a FAISS store bred with data.+ """++ store = FAISSStore(dimension=vector_dim)+ if hasattr(store, "progress_tracker"):+ store.progress_tracker = MagicMock()+ store.create_index(index_type="flat")+ store.add_vectors(random_vectors)+ return store+++# Benchmarks+++def test_faiss_insert_throughput(benchmark, random_vectors, vector_dim):+ """+ Benchmarks raw Write speed to FAISS+ """+ store = FAISSStore(dimension=vector_dim)+ if hasattr(store, "progress_tracker"):+ store.progress_tracker = MagicMock()+ store.create_index(index_type="flat")++ def insert_op():+ store.add_vectors(random_vectors)++ benchmark(insert_op)++ assert len(store.index.vector_ids) >= 10000+++def test_faiss_search_latency(benchmark, populated_store, vector_dim):+ """+ Benchmarks Read/Search speed+ """++ query = np.random.rand(1, vector_dim).astype(np.float32)+ results = benchmark(populated_store.search_similar, query_vector=query, k=10)+ assert len(results) == 10+++def test_vector_storage_manager_overhead(benchmark, random_vectors, vector_dim):+ """+ Benchmarks the overhead of the VectorStore class+ """+ with patch(+ "semantica.vector_store.vector_store.EmbeddingGenerator"+ ) as MockEmbedder:+ manager = VectorStore(backend="faiss", dimension=vector_dim)+ if hasattr(manager, "progress_tracker"):+ manager.progress_tracker = MagicMock()++ def store_op():+ manager.store_vectors(random_vectors)++ benchmark(store_op)++ assert len(manager.vectors) >= 10000diff --git a/benchmarks/visualization/conftest.py b/benchmarks/visualization/conftest.pynew file mode 100644index 00000000..86a72bf1--- /dev/null+++ b/benchmarks/visualization/conftest.py@@ -0,0 +1,80 @@+import random+from typing import Any, Dict, List+from unittest.mock import MagicMock, patch++import numpy as np+import pytest+++# Data Generators+def generate_embeddings():+ """Generates synthetic high-dim embeddings."""++ def _gen(n_samples: int, n_features: int = 768):+ return np.random.rand(n_samples, n_features).astype(np.float32)++ return _gen+++def generate_knowledge_graph():+ """Generates synthetic Knowledge Graph dictionary."""++ def _gen(n_nodes: int, density: float = 0.05):+ entities = [+ {+ "id": f"e_{i}",+ "label": f"Entity_{i}",+ "type": random.choice(["Person", "Organization", "Location", "Event"]),+ "metadata": {"score": random.random()},+ }+ for i in range(n_nodes)+ ]++ relationships = []+ n_edges = int(n_nodes * (n_nodes - 1) * density)+ # Capping edges for safety+ n_edges = min(n_edges, n_nodes * 5)++ for i in range(n_edges):+ src = random.randint(0, n_nodes - 1)+ tgt = random.randint(0, n_nodes - 1)++ if src != tgt:+ relationships.append(+ {+ "source": f"e_{src}",+ "target": f"e_{tgt}",+ "type": "related_to",+ "metadata": {"weight": random.random()},+ }+ )++ return {"entities": entities, "relationships": relationships}++ return _gen+++def generate_temporal_data(generate_knowledge_graph):+ """Generates synthetic temporal graph snapshots."""++ def _gen(n_snapshots: int, n_nodes: int):+ timestamps_map = {}+ base_kg = generate_knowledge_graph(n_nodes)+ entities = base_kg["entities"]++ all_years = list(range(2020, 2020 + n_snapshots))+ for ent in entities:+ start = random.randint(0, len(all_years) - 2)+ duration = random.randint(1, len(all_years) - start)+ timestamps_map[ent["id"]] = all_years[start : start + duration]++ return {+ "entities": entities,+ "relationships": base_kg["relationships"],+ "timestamps": timestamps_map,+ }++ return _gendiff --git a/benchmarks/visualization/test_analytics_viz.py b/benchmarks/visualization/test_analytics_viz.pynew file mode 100644index 00000000..1d596e7f--- /dev/null+++ b/benchmarks/visualization/test_analytics_viz.py@@ -0,0 +1,26 @@+import random++import pytest++from semantica.visualization.analytics_visualizer import AnalyticsVisualizer++[email protected](group="analytics_charts")+def test_centrality_ranking_sort_and_render(benchmark):+ """+ Benchmarks sorting a large centrality dictionary+ and rendering the Top N bar chart.+ """+ viz = AnalyticsVisualizer()++ # Generate 5000 node scores+ centrality_data = {+ "centrality": {f"node_{i}": random.random() for i in range(5000)}+ }++ def run():+ return viz.visualize_centrality_rankings(+ centrality_data, centrality_type="degree", top_n=50, output="interactive"+ )++ benchmark.pedantic(run, iterations=1, rounds=10)diff --git a/benchmarks/visualization/test_embedding_viz.py b/benchmarks/visualization/test_embedding_viz.pynew file mode 100644index 00000000..66242d7d--- /dev/null+++ b/benchmarks/visualization/test_embedding_viz.py@@ -0,0 +1,45 @@+import numpy as np+import pytest++from semantica.visualization.embedding_visualizer import EmbeddingVisualizer++[email protected](group="embedding_projection")[email protected]("method", ["pca", "tsne"])[email protected]("n_samples", [500])+def test_projection_calculation_overhead(+ benchmark, generate_embeddings, method, n_samples+):+ """+ Measures the combined cost of:+ 1. Dimensionality Reduction (Math)+ 2. Plotly Trace Construction (Object creation)+ """++ viz = EmbeddingVisualizer()+ embeddings = generate_embeddings(n_samples=n_samples, n_features=128)+ labels = [f"Label {i}" for i in range(n_samples)]++ def run():+ return viz.visualize_2d_projection(+ embeddings, labels=labels, method=method, output="interactive"+ )++ rounds = 5 if method == "tsne" else 10+ benchmark.pedantic(run, iterations=1, rounds=rounds)++[email protected](group="embedding_heatmap")+def test_similarity_heatmap_generation(benchmark, generate_embeddings):+ """+ Benchmarks O(N^2) similarity matrix calculation+ and heatmap renderin.+ """++ viz = EmbeddingVisualizer()+ embeddings = generate_embeddings(n_samples=500, n_features=64)++ def run():+ return viz.visualize_similarity_heatmap(embeddings, output="interactive")++ benchmark.pedantic(run, iterations=1, rounds=5)diff --git a/benchmarks/visualization/test_kg_viz.py b/benchmarks/visualization/test_kg_viz.pynew file mode 100644index 00000000..9b3671b9--- /dev/null+++ b/benchmarks/visualization/test_kg_viz.py@@ -0,0 +1,33 @@+import pytest++from semantica.visualization.kg_visualizer import KGVisualizer++[email protected](group="graph_layouyt")[email protected]("layout", ["circular", "force"])[email protected]("size", [100])+def test_network_layout_performance(benchmark, generate_knowledge_graph, layout, size):+ """+ Compares layout algorithm.+ """+ viz = KGVisualizer(layout=layout, force_layout_iterations=50)+ graph = generate_knowledge_graph(n_nodes=size)++ def run():+ return viz.visualize_network(graph, output="interactive")++ benchmark.pedantic(run, iterations=1, rounds=5)++[email protected](group="graph_structure")+def test_matrix_view_rendering(benchmark, generate_knowledge_graph):+ """+ Benchmarks the creation of an adjacent/relationship matrix.+ """+ viz = KGVisualizer()+ graph = generate_knowledge_graph(n_nodes=500)++ def run():+ return viz.visualize_relationship_matrix(graph, output="interactive")++ benchmark.pedantic(run, iterations=1, rounds=5)diff --git a/benchmarks/visualization/test_temporal_viz.py b/benchmarks/visualization/test_temporal_viz.pynew file mode 100644index 00000000..2cfed442--- /dev/null+++ b/benchmarks/visualization/test_temporal_viz.py@@ -0,0 +1,39 @@+import pytest++from semantica.visualization.temporal_visualizer import TemporalVisualizer++[email protected](group="temporal_animation")+def test_network_evolution_frames(benchmark, generate_temporal_data):+ """+ Measures the cost of generating animation frames for Plotly.+ """++ temporal_data = generate_temporal_data(n_snapshots=5, n_nodes=100)+ viz = TemporalVisualizer()++ def run():+ return viz.visualize_network_evolution(temporal_data, output="interactive")++ benchmark.pedantic(run, iterations=1, rounds=5)++[email protected](group="temporal_dashboard")+def test_temporal_dashboard_assembly(benchmark, generate_temporal_data):+ """+ Benchmarks the creation of a multi-subplot dashboard.+ """+ temporal_data = generate_temporal_data(n_snapshots=20, n_nodes=200)+ viz = TemporalVisualizer()++ metrics = {+ "Accuracy": [0.5 + i * 0.02 for i in range(20)],+ "Loss": [1.0 - i * 0.04 for i in range(20)],+ }++ def run():+ return viz.visualize_temporal_dashboard(+ temporal_data, metrics=metrics, output="interactive"+ )++ benchmark.pedantic(run, iterations=1, rounds=5)