mirror of
https://github.com/tiennm99/DocsGPT.git
synced 2026-10-05 10:13:39 +00:00
Source access control --------------------- `active_docs` is client-supplied and reached the retriever unchecked, and the retriever queries `WHERE source_id = <id>` with no owner predicate — so any caller could pass any source id to /stream or /api/answer and have another tenant's documents quoted back, while /api/sources/<id>/search correctly refused the same id. Gate it through `can_access`, the helper the guarded endpoints already use, and filter `self.source` down to the authorized set. Fails closed: no principal, or a check that errors, drops the source. Three sibling paths had the same gap: - workflow agent nodes: `AgentNodeConfig.sources` is written verbatim from client JSON at save time and nothing validated it, so a node could name any tenant's source. Gate against the workflow owner, so shared workflows keep reading their owner's sources like shared agents do. - /api/share: `_resolve_source_pg_id` resolved any id with no ownership predicate and baked it into the agent the share creates; /api/search then searched it. Authorize before attaching. - search_service: re-resolve the ids stored on an agent row instead of trusting them, so a row written by any future path with the same gap cannot be read back. Team grantees previously lost their source's retrieval config: the post-check read was still owner-scoped, so it missed and fell back to defaults (an `agentic_tool` source was bulk-prefetched for every grantee). Read unscoped after `can_access` passes. Retrieval --------- `PGVectorStore._ensure_table_exists` created an IVFFlat index on the empty table it had just created. IVFFlat computes centroids at build time, so those centroids were random, and combined with the `source_id` post-filter a source with hundreds of embedded chunks returned zero rows — retrieval reported no documents, the model answered from memory, and nothing was logged. Stop creating the index (exact search is correct and fast well past the sizes most deployments reach); raise `ivfflat.probes` to sqrt(lists) where an index still exists; and re-run a short indexed search exactly, since post-filtering means no index setting can guarantee a full result. `graphrag` had the same empty-table index with no fallback at all. Also: bound `chunks` to 0-500 on both the request and agent paths (0 still means "skip retrieval"), let a source's configured `retrieval.chunks` outrank the request body, and cap ClassicRAG's per-source floor at max(top_k, n_sources) so attaching sources cannot inflate the result set. Silent failures --------------- An empty retrieval was invisible to both the model and the client: the `source` event was suppressed when the list was empty, so "searched and found nothing" looked identical to "no source attached", and the prompt said nothing at all. Emit the event always, and tell the model when a search ran and returned nothing. A file that parses to nothing now fails ingest with a message naming the cause instead of storing an embedding of the empty string. `score_threshold` returns warnings when the active store or retriever cannot honour it. Prompt structure ---------------- Retrieved documents move from the system prompt into the user turn, with the injection guard restated next to them: they change every turn (defeating prefix caching), they are third-party text that should not carry system authority, and routing them through the query budget makes them truncatable rather than silently crowding it out. Documents are shed lowest-ranked-first before the question is touched. The six chat presets (3 tones x 2 retrieval modes) differed only in their Answering section; they are now composed from single-source fragments at load time, not through Jinja inheritance, which would have opened a file-read surface in the template sandbox and broken the tool-prefetch parser. Per-tool guidance moves out of the prompt into tool schemas, so it travels with the tool and cannot render when the tool is absent. A plain-text custom prompt is staged as a persona value inside the skeleton instead of replacing it wholesale — it used to silently lose the injection guard, platform block, memory and attachments, and its braces are now inert. Other fixes ----------- - agents/base: an oversized system prompt drove the query budget negative and dispatched a full-price request with an empty question; raise instead. - llm/anthropic: migrate off the retired Text Completions API. It flattened history to first+last message and ignored tools entirely. Adds the missing Anthropic handler, without which every tool call was silently dropped. - sources/upload: `sitemap` had no branch, so every sitemap ingest died on a TypeError; `validate_url` now rejects a falsy URL cleanly. - workflow nodes: retrieved documents never reached the node agent, so a classic node with a source and an ordinary prompt answered "I have no documents" while the run reported completed. - parser/bulk: copy the metadata dict, or every chunk reports the last chunk's token_count. - crawler_loader: carry the page title, or citations render the whole chunk body as the label.
209 lines
7.7 KiB
Python
209 lines
7.7 KiB
Python
"""IVFFlat probes must be raised, or a filtered search silently returns nothing.
|
|
|
|
An IVFFlat index splits vectors into ``lists`` clusters and the default
|
|
``probes = 1`` scans one of them. Our search filters by ``source_id`` *after*
|
|
the index picks candidates, so with one probe the candidates routinely all
|
|
belong to other sources and the query returns zero rows — retrieval reports no
|
|
documents and the model answers with no source material, with nothing logged.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from unittest.mock import MagicMock
|
|
|
|
import pytest
|
|
|
|
from application.vectorstore import pgvector as pgvector_module
|
|
from application.vectorstore.pgvector import PGVectorStore
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _clear_cache():
|
|
pgvector_module._IVFFLAT_LISTS_CACHE.clear()
|
|
yield
|
|
pgvector_module._IVFFLAT_LISTS_CACHE.clear()
|
|
|
|
|
|
def _store() -> PGVectorStore:
|
|
store = PGVectorStore.__new__(PGVectorStore)
|
|
store._table_name = "documents"
|
|
store._source_id = "s1"
|
|
store._text_column = "text"
|
|
store._metadata_column = "metadata"
|
|
store._vector_column = "embedding"
|
|
return store
|
|
|
|
|
|
def _conn(indexdef):
|
|
conn, cursor = MagicMock(), MagicMock()
|
|
conn.cursor.return_value.__enter__.return_value = cursor
|
|
cursor.fetchone.return_value = (indexdef,) if indexdef else None
|
|
return conn, cursor
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestIvfflatProbes:
|
|
def test_probes_derived_from_the_index_lists(self, monkeypatch):
|
|
monkeypatch.setattr(
|
|
pgvector_module.settings, "PGVECTOR_IVFFLAT_PROBES", None, raising=False
|
|
)
|
|
conn, cursor = _conn(
|
|
"CREATE INDEX i ON documents USING ivfflat (embedding vector_cosine_ops)"
|
|
" WITH (lists='100')"
|
|
)
|
|
_store()._apply_ivfflat_probes(conn)
|
|
|
|
# sqrt(100) = 10; 1 would scan a single cluster of a 100-way split.
|
|
assert any(
|
|
"ivfflat.probes = 10" in str(c) for c in cursor.execute.call_args_list
|
|
), cursor.execute.call_args_list
|
|
|
|
def test_explicit_setting_overrides_derivation(self, monkeypatch):
|
|
monkeypatch.setattr(
|
|
pgvector_module.settings, "PGVECTOR_IVFFLAT_PROBES", 42, raising=False
|
|
)
|
|
conn, cursor = _conn("... ivfflat ... WITH (lists='100')")
|
|
_store()._apply_ivfflat_probes(conn)
|
|
|
|
assert any(
|
|
"ivfflat.probes = 42" in str(c) for c in cursor.execute.call_args_list
|
|
)
|
|
|
|
def test_no_ivfflat_index_sets_nothing(self, monkeypatch):
|
|
monkeypatch.setattr(
|
|
pgvector_module.settings, "PGVECTOR_IVFFLAT_PROBES", None, raising=False
|
|
)
|
|
conn, cursor = _conn(None)
|
|
_store()._apply_ivfflat_probes(conn)
|
|
|
|
assert not any(
|
|
"ivfflat.probes" in str(c) for c in cursor.execute.call_args_list
|
|
)
|
|
|
|
def test_introspection_failure_never_breaks_search(self, monkeypatch):
|
|
monkeypatch.setattr(
|
|
pgvector_module.settings, "PGVECTOR_IVFFLAT_PROBES", None, raising=False
|
|
)
|
|
conn = MagicMock()
|
|
conn.cursor.side_effect = RuntimeError("no pg_indexes")
|
|
_store()._apply_ivfflat_probes(conn) # must not raise
|
|
|
|
def test_lists_lookup_is_cached_per_table(self, monkeypatch):
|
|
monkeypatch.setattr(
|
|
pgvector_module.settings, "PGVECTOR_IVFFLAT_PROBES", None, raising=False
|
|
)
|
|
conn, _ = _conn("... ivfflat ... WITH (lists='64')")
|
|
store = _store()
|
|
assert store._ivfflat_lists(conn) == 64
|
|
conn.cursor.side_effect = AssertionError("should not re-query")
|
|
assert store._ivfflat_lists(conn) == 64
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestNoVectorIndexOnEmptyTable:
|
|
"""The table must not get a vector index at creation time.
|
|
|
|
IVFFlat computes centroids at build time, so an index built on an empty
|
|
table gets random ones and never recovers — measured recall 0.06 once rows
|
|
arrive. With our ``source_id`` post-filter that returned zero rows for
|
|
sources with hundreds of chunks, silently.
|
|
"""
|
|
|
|
def test_ensure_table_exists_creates_no_vector_index(self):
|
|
import inspect
|
|
|
|
source = inspect.getsource(PGVectorStore._ensure_table_exists)
|
|
assert "USING ivfflat" not in source
|
|
assert "USING hnsw" not in source
|
|
# the non-vector indexes are still expected
|
|
assert "source_id_idx" in source and "text_fts_idx" in source
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestExactSearchFallback:
|
|
"""A short indexed result must be re-run exactly, never surfaced as-is."""
|
|
|
|
def _cursor(self, available, exact_rows):
|
|
cursor = MagicMock()
|
|
cursor.fetchone.return_value = (available,)
|
|
cursor.fetchall.return_value = exact_rows
|
|
return cursor
|
|
|
|
def test_short_result_is_replaced_by_exact(self):
|
|
ann = [("a", {}, 0.1)]
|
|
exact = [("a", {}, 0.1), ("b", {}, 0.2), ("c", {}, 0.3)]
|
|
store = _store()
|
|
out = store._exact_search(self._cursor(50, exact), [0.0], k=3, ann_results=ann)
|
|
assert out == exact
|
|
|
|
def test_full_result_is_left_alone(self):
|
|
ann = [("a", {}, 0.1), ("b", {}, 0.2)]
|
|
store = _store()
|
|
cursor = self._cursor(50, [("x", {}, 0.0)] * 9)
|
|
assert store._exact_search(cursor, [0.0], k=2, ann_results=ann) == ann
|
|
|
|
def test_source_smaller_than_k_is_not_a_short_result(self):
|
|
"""A 2-chunk source answering k=100 is complete, not under-returning."""
|
|
ann = [("a", {}, 0.1), ("b", {}, 0.2)]
|
|
store = _store()
|
|
cursor = self._cursor(2, [("x", {}, 0.0)] * 2)
|
|
assert store._exact_search(cursor, [0.0], k=100, ann_results=ann) == ann
|
|
|
|
def test_failure_returns_the_original_result(self):
|
|
ann = [("a", {}, 0.1)]
|
|
cursor = MagicMock()
|
|
cursor.execute.side_effect = RuntimeError("boom")
|
|
store = _store()
|
|
assert store._exact_search(cursor, [0.0], k=5, ann_results=ann) == ann
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestFallbackNeverPoisonsTheConnection:
|
|
"""A failure inside the safety net must not blind every later search.
|
|
|
|
The fallback runs extra statements on the shared connection. Without a
|
|
rollback, one error leaves the transaction INERROR and every subsequent
|
|
search on that store returns ``[]`` — reproducing the exact silent
|
|
zero-retrieval the fallback exists to prevent, and blinding
|
|
``keyword_search`` too since hybrid retrieval reuses the store.
|
|
"""
|
|
|
|
def test_failure_rolls_back(self):
|
|
cursor = MagicMock()
|
|
cursor.execute.side_effect = RuntimeError("aborted")
|
|
store = _store()
|
|
|
|
out = store._exact_search(cursor, [0.0], k=5, ann_results=[("a", {}, 0.1)])
|
|
|
|
assert out == [("a", {}, 0.1)]
|
|
cursor.connection.rollback.assert_called_once()
|
|
|
|
def test_planner_gucs_are_reset_not_forced_on(self):
|
|
"""RESET restores the deployment's setting; ``= on`` overrides it."""
|
|
cursor = MagicMock()
|
|
cursor.fetchone.return_value = (50,)
|
|
cursor.fetchall.return_value = [("a", {}, 0.1)] * 5
|
|
_store()._exact_search(cursor, [0.0], k=5, ann_results=[("a", {}, 0.1)])
|
|
|
|
executed = " ".join(str(c) for c in cursor.execute.call_args_list)
|
|
assert "RESET enable_indexscan" in executed
|
|
assert "enable_indexscan = on" not in executed
|
|
|
|
|
|
@pytest.mark.unit
|
|
class TestListsCacheAllowsLaterIndexCreation:
|
|
"""Caching a miss would keep probes unset for the process's lifetime.
|
|
|
|
The store now tells operators to add an index deliberately, later — so a
|
|
process that booted before that must notice it.
|
|
"""
|
|
|
|
def test_absent_index_is_not_cached(self):
|
|
store = _store()
|
|
conn, _ = _conn(None)
|
|
assert store._ivfflat_lists(conn) is None
|
|
assert "documents" not in pgvector_module._IVFFLAT_LISTS_CACHE
|
|
|
|
conn2, _ = _conn("... ivfflat ... WITH (lists='64')")
|
|
assert store._ivfflat_lists(conn2) == 64
|