Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat: bk hybrid retrieval (#62198)

Alex V2243ebe8ebcf
diff --git a/ee/hogai/tools/search.py b/ee/hogai/tools/search.py
index 839b02fe53de..761c312a56f6 100644
--- a/ee/hogai/tools/search.py
+++ b/ee/hogai/tools/search.py
@@ -1,4 +1,5 @@
import re
+import asyncio
from typing import Literal
from django.conf import settings
@@ -9,8 +10,10 @@ from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
+from posthog.api.embedding_worker import async_generate_embedding
from posthog.sync import database_sync_to_async
+from products.business_knowledge.backend.constants import BK_EMBEDDING_MODEL, BK_QUERY_EMBEDDING_TIMEOUT
from products.business_knowledge.backend.logic import has_ready_sources, search_knowledge
from ee.hogai.context.entity_search.context import EntityKind
@@ -185,8 +188,24 @@ class SearchTool(MaxTool):
return response, None
async def _search_business_knowledge(self, query: str) -> str:
- results = await database_sync_to_async(search_knowledge)(self._team.id, query)
- logger.info("bk_search_results", team_id=self._team.id, result_count=len(results))
+ query_embedding = await self._get_query_embedding(query)
+ use_semantic = query_embedding is not None
+
+ # thread_sensitive=False: the hybrid path issues a ClickHouse query that
+ # can take seconds; the default shared sync thread would serialize all
+ # such calls and block other DB work. Run it on the general pool.
+ results = await database_sync_to_async(search_knowledge, thread_sensitive=False)(
+ self._team.id,
+ query,
+ use_semantic=use_semantic,
+ query_embedding=query_embedding,
+ )
+ logger.info(
+ "bk_search_results",
+ team_id=self._team.id,
+ result_count=len(results),
+ use_semantic=use_semantic,
+ )
if not results:
return BK_SEARCH_NO_RESULTS_TEMPLATE
@@ -201,6 +220,22 @@ class SearchTool(MaxTool):
header = BK_SEARCH_RESULTS_HEADER.format(count=len(results))
return f"{header}\n\n{formatted}\n{BK_SEARCH_RESULTS_FOOTER}"
+ async def _get_query_embedding(self, query: str) -> list[float] | None:
+ """Embed the query with a tight timeout; returns None on failure (FTS fallback)."""
+ try:
+ response = await asyncio.wait_for(
+ async_generate_embedding(self._team, query, model=BK_EMBEDDING_MODEL),
+ timeout=BK_QUERY_EMBEDDING_TIMEOUT,
+ )
+ return response.embedding
+ except Exception:
+ logger.warning(
+ "bk_query_embedding_failed",
+ team_id=self._team.id,
+ exc_info=True,
+ )
+ return None
+
@property
def _fts_entities(self) -> list[str]:
entities = list(EntityKind)
diff --git a/products/business_knowledge/backend/constants.py b/products/business_knowledge/backend/constants.py
index f2baca5cc133..993e9bab041c 100644
--- a/products/business_knowledge/backend/constants.py
+++ b/products/business_knowledge/backend/constants.py
@@ -112,3 +112,29 @@ PENDING_EMBEDDING_SCAN_CAP = 50
# re-checking docs whose vectors are simply still in flight through Kafka.
RECONCILE_EMBEDDING_SCAN_CAP = 50
RECONCILE_EMBEDDING_GRACE = datetime.timedelta(hours=2)
+
+# --- Hybrid retrieval tunables (PR2 read path) ---
+# cosineDistance threshold: vectors above this are discarded BEFORE re-joining
+# Postgres. text-embedding-3-small typically returns 0.2–0.5 for related content
+# and 0.7+ for unrelated. Start strict; loosen with data.
+BK_SEMANTIC_DISTANCE_CUTOFF = 0.65
+# Over-fetch factor: the safety re-join can discard top-k hits that point at
+# now-UNSAFE/tombstoned/deleted chunks, so we pull k * OVERFETCH from CH and
+# trim after re-join. 3x is generous; a lower factor would be fine once the
+# pipeline stabilises.
+BK_SEMANTIC_OVERFETCH = 3
+# RRF fusion constant. Standard value from the original RRF paper (Cormack et
+# al. 2009). Higher k flattens rank differences; lower k emphasises top ranks.
+BK_RRF_K = 60
+# Minimum fused RRF score a SEMANTIC-ONLY candidate must reach to be included.
+# FTS anchors are exempt (a tsquery hit is a real lexical match against
+# SAFE/READY content, never garbage) — applying the floor to them would silently
+# drop legitimate FTS results past rank ~6 in the hybrid path while keeping them
+# in the keyword-only path. The floor exists to stop a borderline semantic-only
+# hit (one that just scraped under the distance cutoff) from surfacing on an
+# off-topic query. 1/(60+5) ≈ 0.0154, so a semantic-only candidate must land in
+# roughly the top-5 of the semantic list to survive.
+BK_RRF_SCORE_FLOOR = 0.015
+# Timeout (seconds) for the async embedding call on the query path. If the
+# embedding service is slow, FTS alone fires (graceful degradation).
+BK_QUERY_EMBEDDING_TIMEOUT = 5.0
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index bf5ccc6c3529..348686c6b139 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -30,6 +30,13 @@ from posthog.security.url_validation import is_url_allowed
from . import crawl, discover, file_parse, html_parse, url_fetch
from .constants import (
+ BK_EMBEDDING_DOCUMENT_TYPE,
+ BK_EMBEDDING_MODEL,
+ BK_EMBEDDING_PRODUCT,
+ BK_RRF_K,
+ BK_RRF_SCORE_FLOOR,
+ BK_SEMANTIC_DISTANCE_CUTOFF,
+ BK_SEMANTIC_OVERFETCH,
CHUNK_HARD_MAX_CHARS,
CHUNK_TARGET_CHARS,
CLASSIFY_MAX_ATTEMPTS,
@@ -1482,6 +1489,131 @@ def has_ready_sources(team_id: int) -> bool:
_SEARCH_LIMIT_CAP = 20
+# ---------------------------------------------------------------------------
+# Semantic search helpers (hybrid retrieval, gated on use_semantic)
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class _SemanticCandidate:
+ """A chunk_id + cosineDistance returned from ClickHouse vector search."""
+
+ chunk_id: UUID
+ distance: float
+
+
+def _semantic_chunk_candidates(
+ team_id: int,
+ query_embedding: list[float],
+ *,
+ limit: int,
+) -> list[_SemanticCandidate]:
+ """
+ Vector search over document_embeddings for BK chunks.
+
+ Returns up to ``limit * BK_SEMANTIC_OVERFETCH`` candidates under the
+ distance cutoff, ordered by cosineDistance ASC. The caller re-joins to
+ Postgres for safety filters and trims to ``limit``.
+ """
+ from posthog.hogql import ast # noqa: PLC0415 — keeps HogQL compiler off the import path
+ from posthog.hogql.query import execute_hogql_query # noqa: PLC0415
+
+ from posthog.clickhouse.query_tagging import Feature, Product, tag_queries # noqa: PLC0415
+ from posthog.models.team.team import Team # noqa: PLC0415
+
+ ch_limit = limit * BK_SEMANTIC_OVERFETCH
+
+ # Distance is computed in the inner SELECT and filtered in the outer WHERE
+ # so cosineDistance runs once per row (ClickHouse can't reuse a SELECT alias
+ # in the same level's WHERE — WHERE is evaluated first). Matters at 1536 dims.
+ hogql_query = """
+ SELECT document_id, distance
+ FROM (
+ SELECT
+ document_id,
+ cosineDistance(embedding, {embedding}) AS distance
+ FROM document_embeddings
+ WHERE model_name = {model_name}
+ AND product = {product}
+ AND document_type = {document_type}
+ AND team_id = {team_id}
+ )
+ WHERE distance < {cutoff}
+ ORDER BY distance ASC
+ LIMIT {limit}
+ """
+
+ placeholders: dict[str, ast.Expr] = {
+ "embedding": ast.Constant(value=query_embedding),
+ "model_name": ast.Constant(value=BK_EMBEDDING_MODEL),
+ "product": ast.Constant(value=BK_EMBEDDING_PRODUCT),
+ "document_type": ast.Constant(value=BK_EMBEDDING_DOCUMENT_TYPE),
+ "team_id": ast.Constant(value=team_id),
+ "cutoff": ast.Constant(value=BK_SEMANTIC_DISTANCE_CUTOFF),
+ "limit": ast.Constant(value=ch_limit),
+ }
+
+ team = Team.objects.get(pk=team_id)
+ tag_queries(product=Product.CONVERSATIONS, feature=Feature.SEMANTIC_SEARCH)
+ result = execute_hogql_query(
+ query=hogql_query,
+ team=team,
+ placeholders=placeholders,
+ )
+
+ candidates: list[_SemanticCandidate] = []
+ for row in result.results or []:
+ doc_id_str, distance = row
+ try:
+ candidates.append(_SemanticCandidate(chunk_id=UUID(doc_id_str), distance=float(distance)))
+ except (ValueError, TypeError):
+ continue
+ return candidates
+
+
+def _rrf_fuse(
+ fts_chunk_ids: list[UUID],
+ semantic_candidates: list[_SemanticCandidate],
+ *,
+ k: int = BK_RRF_K,
+ score_floor: float = BK_RRF_SCORE_FLOOR,
+) -> list[UUID]:
+ """
+ Reciprocal Rank Fusion of FTS anchors and semantic candidates.
+
+ Each list contributes 1/(k + rank) per candidate. FTS anchors are always
+ kept (they're real lexical matches against SAFE/READY content); only
+ semantic-ONLY candidates are subject to ``score_floor``, so a borderline
+ semantic hit on an off-topic query is dropped without trimming the
+ legitimate FTS tail.
+
+ Semantic candidates are deduped by chunk_id first: the shared
+ ``document_embeddings`` table is a ReplacingMergeTree that we do NOT read
+ with FINAL, so a re-emitted chunk can appear as several rows. Keeping the
+ first occurrence (the CH query is ordered by distance ASC, so that's the
+ closest) prevents a duplicated vector from double-counting its RRF score.
+ """
+ scores: dict[UUID, float] = defaultdict(float)
+ fts_ids = set(fts_chunk_ids)
+
+ for rank, chunk_id in enumerate(fts_chunk_ids, start=1):
+ scores[chunk_id] += 1.0 / (k + rank)
+
+ seen_semantic: set[UUID] = set()
+ semantic_rank = 0
+ for candidate in semantic_candidates:
+ if candidate.chunk_id in seen_semantic:
+ continue
+ seen_semantic.add(candidate.chunk_id)
+ semantic_rank += 1
+ scores[candidate.chunk_id] += 1.0 / (k + semantic_rank)
+
+ # FTS anchors bypass the floor; semantic-only candidates must clear it.
+ fused = [(cid, score) for cid, score in scores.items() if cid in fts_ids or score >= score_floor]
+ fused.sort(key=lambda x: x[1], reverse=True)
+ return [cid for cid, _score in fused]
+
+
@dataclass(frozen=True)
class KnowledgeSearchResult:
"""A single chunk returned by a knowledge search, with source context."""
@@ -1503,60 +1635,83 @@ def search_knowledge(
query: str,
*,
limit: int = 10,
+ use_semantic: bool = False,
+ query_embedding: list[float] | None = None,
) -> list[KnowledgeSearchResult]:
"""
- Full-text relevance search over chunks belonging to READY sources.
+ Hybrid (lexical + semantic) relevance search over BK chunks.
+
+ When ``use_semantic=False`` (default / flag off), this is pure FTS — the
+ existing keyword path byte-for-byte.
- Builds an `english`-config `tsquery` from the user query (stemming +
- stopword removal + prefix match on the last term, via `process_query`) with
- OR semantics, and matches it against the chunk `content_search_vector` using
- the GIN index. The top `limit` matches by `ts_rank` (so chunks hitting more
- query terms rank first) anchor the result; each anchor is expanded to its
- ordinal-adjacent neighbours (ordinal n-1, n, n+1 within the same document)
- so the agent gets continuous context instead of isolated fragments.
- `ordinal` is document-global and contiguous, so neighbours never cross into
- a different document.
+ When ``use_semantic=True``, the caller must also pass ``query_embedding``
+ (the pre-computed query vector). Both FTS and vector results are fused via
+ Reciprocal Rank Fusion (RRF), safety-re-joined against Postgres, trimmed
+ to ``limit``, and ordinal-neighbour-expanded.
"""
limit = max(1, min(limit, _SEARCH_LIMIT_CAP))
- # `process_query` strips tsquery metacharacters and joins terms with a
- # trailing prefix match; returns None only when the result is an empty
- # string (i.e. the query contained nothing but unsafe characters).
- # Stopword-only inputs are not caught here — they pass through as a
- # non-empty string and PostgreSQL discards the stopwords inside
- # to_tsquery, yielding no matches.
+ # --- FTS anchors (always computed) ---
processed = process_query(query)
- if processed is None:
- return []
- # OR rather than AND the terms: the agent sends natural-language questions,
- # and AND drops any chunk missing a single term (e.g. "can a customer get a
- # refund within 30 days" wouldn't match a focused refund chunk). `ts_rank`
- # still surfaces chunks matching more terms first. `process_query` only ever
- # inserts " & " as a separator, so the replace is unambiguous.
- processed = processed.replace(" & ", " | ")
- search_query = SearchQuery(processed, config="english", search_type="raw")
-
- anchors = list(
- KnowledgeChunk.objects.filter(
- team_id=team_id,
- source__status=SourceStatus.READY,
- document__tombstoned_at__isnull=True,
- document__safety_verdict=SafetyVerdict.SAFE,
- content_search_vector=search_query,
+ fts_anchors: list[KnowledgeChunk] = []
+ if processed is not None:
+ processed = processed.replace(" & ", " | ")
+ search_query = SearchQuery(processed, config="english", search_type="raw")
+ fts_anchors = list(
+ KnowledgeChunk.objects.filter(
+ team_id=team_id,
+ source__status=SourceStatus.READY,
+ document__tombstoned_at__isnull=True,
+ document__safety_verdict=SafetyVerdict.SAFE,
+ content_search_vector=search_query,
+ )
+ .annotate(rank=SearchRank(F("content_search_vector"), search_query))
+ .only("id", "document_id", "ordinal", "char_count")
+ .order_by("-rank", "char_count", "id")[:limit]
)
- .annotate(rank=SearchRank(F("content_search_vector"), search_query))
- .only("id", "document_id", "ordinal", "char_count")
- # `id` is the final tiebreaker so rank+length ties order deterministically.
- .order_by("-rank", "char_count", "id")[:limit]
- )
- if not anchors:
+ fts_anchor_ids = [a.id for a in fts_anchors]
+
+ # --- Semantic candidates (hybrid path only) ---
+ semantic_candidates: list[_SemanticCandidate] = []
+ if use_semantic and query_embedding:
+ semantic_candidates = _semantic_chunk_candidates(team_id, query_embedding, limit=limit)
+
+ # --- Fusion or FTS-only ---
+ # Fusion requires an actual embedding; when it's None (e.g. embedding-service
+ # timeout) semantic_candidates is empty, so fall through to the FTS-only
+ # branch which reuses the already-filtered, rank-ordered anchors.
+ if use_semantic and query_embedding and (fts_anchor_ids or semantic_candidates):
+ fused_ids = _rrf_fuse(fts_anchor_ids, semantic_candidates)
+ if not fused_ids:
+ return []
+ # Semantic candidates may reference now-unsafe/tombstoned chunks, so we
+ # re-join against Postgres with all safety filters and trim after.
+ fetch_limit = limit * BK_SEMANTIC_OVERFETCH
+ anchor_chunks = list(
+ KnowledgeChunk.objects.filter(
+ id__in=fused_ids[:fetch_limit],
+ team_id=team_id,
+ source__status=SourceStatus.READY,
+ document__tombstoned_at__isnull=True,
+ document__safety_verdict=SafetyVerdict.SAFE,
+ ).only("id", "document_id", "ordinal")
+ )
+ if not anchor_chunks:
+ return []
+ id_to_rank = {cid: rank for rank, cid in enumerate(fused_ids)}
+ anchor_chunks.sort(key=lambda c: id_to_rank.get(c.id, len(fused_ids)))
+ anchor_chunks = anchor_chunks[:limit]
+ elif fts_anchors:
+ # FTS anchors are already safety-filtered — use them directly (no
+ # extra query). Already ordered by rank from the FTS query.
+ anchor_chunks = fts_anchors
+ else:
return []
- # Preserve relevance ranking at the document level (first anchor wins) and
- # collect the ordinal window we want to fetch for each document.
+ # --- Ordinal neighbour expansion ---
doc_rank: dict[UUID, int] = {}
wanted_ordinals: dict[UUID, set[int]] = {}
- for rank, anchor in enumerate(anchors):
+ for rank, anchor in enumerate(anchor_chunks):
doc_rank.setdefault(anchor.document_id, rank)
wanted_ordinals.setdefault(anchor.document_id, set()).update(
(anchor.ordinal - 1, anchor.ordinal, anchor.ordinal + 1)
@@ -1589,8 +1744,7 @@ def search_knowledge(
)
)
- # Order by document relevance, then ordinal so neighbours stay contiguous.
- ordered = sorted(chunks, key=lambda c: (doc_rank.get(c.document_id, len(anchors)), c.ordinal))
+ ordered = sorted(chunks, key=lambda c: (doc_rank.get(c.document_id, len(anchor_chunks)), c.ordinal))
return [
KnowledgeSearchResult(
diff --git a/products/business_knowledge/backend/tests/test_hybrid_search.py b/products/business_knowledge/backend/tests/test_hybrid_search.py
new file mode 100644
index 000000000000..a95a01412a9c
--- /dev/null
+++ b/products/business_knowledge/backend/tests/test_hybrid_search.py
@@ -0,0 +1,227 @@
+import uuid
+from uuid import UUID
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.scoping import team_scope
+
+from products.business_knowledge.backend import logic
+from products.business_knowledge.backend.constants import BK_RRF_SCORE_FLOOR
+from products.business_knowledge.backend.logic import _rrf_fuse, _SemanticCandidate, search_knowledge
+from products.business_knowledge.backend.models import (
+ KnowledgeChunk,
+ KnowledgeDocument,
+ KnowledgeSource,
+ SafetyVerdict,
+ SourceStatus,
+)
+
+
+class TestRRFFusion(BaseTest):
+ def test_fts_only_produces_ranked_output(self) -> None:
+ ids = [uuid.uuid4() for _ in range(3)]
+ fused = _rrf_fuse(ids, [])
+ assert fused == ids
+
+ def test_semantic_only_produces_ranked_output(self) -> None:
+ candidates = [_SemanticCandidate(chunk_id=uuid.uuid4(), distance=0.1 * i) for i in range(1, 4)]
+ fused = _rrf_fuse([], candidates)
+ assert fused == [c.chunk_id for c in candidates]
+
+ def test_overlapping_ids_get_higher_score(self) -> None:
+ shared_id = uuid.uuid4()
+ fts_only = uuid.uuid4()
+ sem_only = uuid.uuid4()
+
+ fts_ids = [shared_id, fts_only]
+ sem_candidates = [
+ _SemanticCandidate(chunk_id=shared_id, distance=0.2),
+ _SemanticCandidate(chunk_id=sem_only, distance=0.3),
+ ]
+ fused = _rrf_fuse(fts_ids, sem_candidates)
+ # shared_id appears in both lists so it should rank first
+ assert fused[0] == shared_id
+
+ def test_score_floor_filters_low_ranked_semantic_only(self) -> None:
+ # A semantic-only candidate ranked very low (rank 1000) scores below the
+ # floor and is dropped.
+ far_away_id = uuid.uuid4()
+ candidates = [_SemanticCandidate(chunk_id=uuid.uuid4(), distance=0.001 * i) for i in range(999)]
+ candidates.append(_SemanticCandidate(chunk_id=far_away_id, distance=0.64))
+ fused = _rrf_fuse([], candidates, score_floor=BK_RRF_SCORE_FLOOR)
+ assert far_away_id not in fused
+
+ def test_fts_anchors_bypass_floor(self) -> None:
+ # FTS anchors are real lexical matches and must never be floored out,
+ # even deep in the list — otherwise hybrid mode silently returns fewer
+ # results than keyword-only mode.
+ deep_fts_id = uuid.uuid4()
+ fts_ids = [uuid.uuid4() for _ in range(50)] + [deep_fts_id]
+ fused = _rrf_fuse(fts_ids, [], score_floor=BK_RRF_SCORE_FLOOR)
+ assert deep_fts_id in fused
+ assert fused == fts_ids
+
+ def test_duplicate_semantic_candidates_do_not_double_count(self) -> None:
+ # A chunk_id repeated in the CH result (un-deduped ReplacingMergeTree)
+ # must not accumulate score and leapfrog a genuinely closer single hit.
+ dup_id = uuid.uuid4()
+ single_id = uuid.uuid4()
+ candidates = [
+ _SemanticCandidate(chunk_id=single_id, distance=0.1),
+ _SemanticCandidate(chunk_id=dup_id, distance=0.2),
+ _SemanticCandidate(chunk_id=dup_id, distance=0.25),
+ ]
+ fused = _rrf_fuse([], candidates)
+ # single_id (rank 1) stays ahead of the deduped dup_id (rank 2)
+ assert fused == [single_id, dup_id]
+
+ def test_empty_inputs_returns_empty(self) -> None:
+ assert _rrf_fuse([], []) == []
+
+
+class TestHybridSearch(BaseTest):
+ """Integration tests for the hybrid (semantic + FTS) search path."""
+
+ def _ready_source_with_chunks(self, texts: list[str], name: str = "src") -> KnowledgeSource:
+ source = logic.create_text_source(
+ team_id=self.team.id,
+ created_by_id=self.user.id,
+ name=name,
+ text="\n\n".join(texts),
+ )
+ with team_scope(self.team.id, canonical=True):
+ KnowledgeDocument.objects.filter(source_id=source.id).update(safety_verdict=SafetyVerdict.SAFE)
+ return source
+
+ def _get_chunk_ids(self, source: KnowledgeSource) -> list[UUID]:
+ with team_scope(self.team.id, canonical=True):
+ return list(
+ KnowledgeChunk.objects.filter(source_id=source.id).order_by("ordinal").values_list("id", flat=True)
+ )
+
+ def test_use_semantic_false_is_pure_fts(self) -> None:
+ self._ready_source_with_chunks(["The refund policy states thirty day returns."])
+ results_kw = search_knowledge(self.team.id, "refund policy", use_semantic=False)
+ assert len(results_kw) >= 1
+ assert any("refund" in r.content.lower() for r in results_kw)
+
+ @patch("products.business_knowledge.backend.logic._semantic_chunk_candidates")
+ def test_semantic_candidates_merged_with_fts(self, mock_semantic: MagicMock) -> None:
+ # Two separate sources so each yields its own chunk (short texts in one
+ # source would collapse into a single chunk under CHUNK_TARGET_CHARS).
+ src_refund = self._ready_source_with_chunks(["The refund policy states thirty day returns."], name="refund")
+ src_warranty = self._ready_source_with_chunks(["Warranty covers manufacturing defects only."], name="warranty")
+ refund_id = self._get_chunk_ids(src_refund)[0]
+ warranty_id = self._get_chunk_ids(src_warranty)[0]
+ # Semantic returns the warranty chunk, which FTS for "refund" wouldn't match
+ mock_semantic.return_value = [_SemanticCandidate(chunk_id=warranty_id, distance=0.3)]
+
+ results = search_knowledge(
+ self.team.id,
+ "refund policy",
+ use_semantic=True,
+ query_embedding=[0.1] * 10,
+ )
+ result_ids = {r.chunk_id for r in results}
+ # FTS hit (refund chunk) and semantic-only hit (warranty chunk) both surface
+ assert refund_id in result_ids
+ assert warranty_id in result_ids
+
+ @patch("products.business_knowledge.backend.logic._semantic_chunk_candidates")
+ def test_off_topic_returns_empty(self, mock_semantic: MagicMock) -> None:
+ self._ready_source_with_chunks(["The refund policy states thirty day returns."])
+ # Semantic returns nothing (all above cutoff)
+ mock_semantic.return_value = []
+
+ results = search_knowledge(
+ self.team.id,
+ "quantum physics experiments",
+ use_semantic=True,
+ query_embedding=[0.1] * 10,
+ )
+ # FTS also finds nothing for "quantum physics experiments" so result is empty
+ assert results == []
+
+ @parameterized.expand(
+ [
+ (
+ "unsafe_verdict",
+ lambda t, s: KnowledgeDocument.objects.filter(source_id=s.id).update(
+ safety_verdict=SafetyVerdict.UNSAFE
+ ),
+ ),
+ (
+ "tombstoned",
+ lambda t, s: KnowledgeDocument.objects.filter(source_id=s.id).update(tombstoned_at=timezone.now()),
+ ),
+ (
+ "source_not_ready",
+ lambda t, s: KnowledgeSource.objects.filter(id=s.id).update(status=SourceStatus.PROCESSING),
+ ),
+ ]
+ )
+ @patch("products.business_knowledge.backend.logic._semantic_chunk_candidates")
+ def test_rejoin_filters_ineligible_chunks(self, _name: str, mark_ineligible, mock_semantic: MagicMock) -> None: # noqa: ANN001
+ source = self._ready_source_with_chunks(["Some indexed content here."])
+ chunk_ids = self._get_chunk_ids(source)
+
+ with team_scope(self.team.id, canonical=True):
+ mark_ineligible(self.team, source)
+
+ mock_semantic.return_value = [_SemanticCandidate(chunk_id=chunk_ids[0], distance=0.2)]
+
+ results = search_knowledge(
+ self.team.id,
+ "indexed content",
+ use_semantic=True,
+ query_embedding=[0.1] * 10,
+ )
+ assert results == []
+
+ @patch("products.business_knowledge.backend.logic._semantic_chunk_candidates")
+ def test_overfetch_still_yields_results_after_filtering(self, mock_semantic: MagicMock) -> None:
+ # Create two sources: one SAFE, one will be tombstoned
+ src_safe = self._ready_source_with_chunks(["Safe searchable chunk about dogs."], name="safe_src")
+ src_dead = self._ready_source_with_chunks(["Dead chunk about dogs too."], name="dead_src")
+
+ safe_ids = self._get_chunk_ids(src_safe)
+ dead_ids = self._get_chunk_ids(src_dead)
+
+ with team_scope(self.team.id, canonical=True):
+ KnowledgeDocument.objects.filter(source_id=src_dead.id).update(tombstoned_at=timezone.now())
+
+ # Semantic returns the dead chunk first (closer vector), then the safe one
+ mock_semantic.return_value = [
+ _SemanticCandidate(chunk_id=dead_ids[0], distance=0.1),
+ _SemanticCandidate(chunk_id=safe_ids[0], distance=0.3),
+ ]
+
+ results = search_knowledge(
+ self.team.id,
+ "dogs",
+ use_semantic=True,
+ query_embedding=[0.1] * 10,
+ limit=2,
+ )
+ # Dead chunk filtered, safe chunk survives
+ assert len(results) >= 1
+ result_ids = {r.chunk_id for r in results}
+ assert safe_ids[0] in result_ids
+ assert dead_ids[0] not in result_ids
+
+ def test_no_embedding_falls_back_to_fts(self) -> None:
+ self._ready_source_with_chunks(["The refund policy states thirty day returns."])
+ # use_semantic=True but no embedding → falls back to FTS only
+ results = search_knowledge(
+ self.team.id,
+ "refund policy",
+ use_semantic=True,
+ query_embedding=None,
+ )
+ # Should still find results via FTS
+ assert len(results) >= 1