Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(explorer): dedupe SPARQL row-cap logic and cover CONSTRUCT/DESCRIBE truncation
KaifAhmad1d102584af6d1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 627edee7..26ece469 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Verified read-only allowlist enforcement against write and mutation queries (`INSERT DATA`, `DELETE DATA`, `DELETE WHERE`, `DROP ALL`, `CLEAR ALL`, `LOAD`, `CREATE GRAPH`, `MODIFY`, comments, and multi-statement injections like `SELECT ... ; DROP ALL`), confirming rejected queries short-circuit before any graph is built or queried- Verified resource-limiting behavior, confirming row capping (`_SPARQL_MAX_ROWS`) truncates results and sets `truncated: true`, query timeout (`_SPARQL_TIMEOUT_S`) returns a clean error message without crashing, and concurrency semaphore (`_SPARQL_MAX_CONCURRENT`) prevents thread starvation under load- Verified RDF projection fidelity for node properties and edge relationships, and error formatting for malformed SPARQL syntax with line and column extraction+ - Follow-up review fixes (#805): extracted the duplicated row-cap-and-truncate loop (previously copy-pasted between the `CONSTRUCT`/`DESCRIBE` and `SELECT` branches) into a shared `_cap_rows()` helper so the `_SPARQL_MAX_ROWS` cap is enforced identically by both; added `test_row_cap_truncates_construct_results`, since the truncation path for `CONSTRUCT`/`DESCRIBE` results had no direct test coverage even though `SELECT` truncation did- **Global default persistent storage for `ProvenanceManager`, plus a working `provenance` CLI** (#795, #802) by @Sameer6305 and @KaifAhmad1- Every ingestion/processing module (`kg_provenance.py`, `pipeline_provenance.py`, and 20+ other call sites) instantiated its own `ProvenanceManager()` with no `storage_path`, so all of them silently fell back to `InMemoryStorage` and the SQLite audit trail was never actually written. `ProvenanceManager.set_default_storage_path(path)` now sets a class-level default that every no-arg instantiation picks up, and `Semantica.__init__` wires `config.provenance.storage_path` into it automatically during orchestrator initdiff --git a/semantica/explorer/routes/sparql.py b/semantica/explorer/routes/sparql.pyindex fbaf49ce..0d7e2f77 100644--- a/semantica/explorer/routes/sparql.py+++ b/semantica/explorer/routes/sparql.py@@ -14,7 +14,7 @@ Security contractimport asyncioimport re-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Optional, Tupleimport rdflibfrom fastapi import APIRouter, Depends@@ -98,6 +98,22 @@ _SPARQL_MAX_CONCURRENT = 4 # semaphore: max simultaneous executions_sparql_semaphore = asyncio.Semaphore(_SPARQL_MAX_CONCURRENT)+def _cap_rows(items: Any, row_builder) -> Tuple[List[Dict[str, Any]], bool]:+ """Materialize up to ``_SPARQL_MAX_ROWS`` items via ``row_builder``, reporting truncation.++ Shared by the SELECT and CONSTRUCT/DESCRIBE branches below so the row cap+ is enforced identically regardless of query type.+ """+ rows: List[Dict[str, Any]] = []+ truncated = False+ for item in items:+ if len(rows) >= _SPARQL_MAX_ROWS:+ truncated = True+ break+ rows.append(row_builder(item))+ return rows, truncated++@router.post("", response_model=SparqlResponse)async def execute_sparql(req: SparqlRequest,@@ -146,33 +162,31 @@ async def execute_sparql(# SELECT → rows keyed by projected variable names# ---------------------------------------------------------------------------query_type: str = query_results.type # always set by rdflib- truncated = Falseif query_type == "ASK":columns = ["result"]rows = [{"result": "true" if query_results.askAnswer else "false"}]+ truncated = Falseelif query_type in ("CONSTRUCT", "DESCRIBE"):columns = ["subject", "predicate", "object"]- rows = []- for s, p, o in query_results: # rdflib always yields (s, p, o) 3-tuples- if len(rows) >= _SPARQL_MAX_ROWS:- truncated = True- break- rows.append({"subject": str(s), "predicate": str(p), "object": str(o)})+ rows, truncated = _cap_rows(+ query_results, # rdflib always yields (s, p, o) 3-tuples+ lambda triple: {+ "subject": str(triple[0]),+ "predicate": str(triple[1]),+ "object": str(triple[2]),+ },+ )else: # SELECTcolumns = [str(var) for var in (query_results.vars or [])]- rows = []- for row in query_results:- if len(rows) >= _SPARQL_MAX_ROWS:- truncated = True- break- rows.append(- {- column: (str(row[index]) if row[index] is not None else None)- for index, column in enumerate(columns)- }- )+ rows, truncated = _cap_rows(+ query_results,+ lambda row: {+ column: (str(row[index]) if row[index] is not None else None)+ for index, column in enumerate(columns)+ },+ )return SparqlResponse(columns=columns, rows=rows, total=len(rows), truncated=truncated)diff --git a/tests/explorer/test_sparql_route.py b/tests/explorer/test_sparql_route.pyindex 33ef946d..36dacce5 100644--- a/tests/explorer/test_sparql_route.py+++ b/tests/explorer/test_sparql_route.py@@ -260,6 +260,22 @@ def test_result_below_cap_is_not_marked_truncated(client):assert payload["truncated"] is False+def test_row_cap_truncates_construct_results(client):+ """CONSTRUCT/DESCRIBE share _cap_rows with SELECT; confirm the cap applies there too."""+ with patch.object(sparql_mod, "_SPARQL_MAX_ROWS", 1):+ resp = _post(+ client,+ "CONSTRUCT { ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label } "+ "WHERE { ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label }",+ )+ assert resp.status_code == 200+ payload = resp.json()+ assert payload["error"] is None+ assert len(payload["rows"]) == 1+ assert payload["total"] == 1+ assert payload["truncated"] is True++def test_query_timeout_returns_clean_error_not_a_crash(client):async def _raise_timeout(coro, timeout=None):coro.close() # avoid a 'coroutine was never awaited' warning from the mock