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 drill-down via read_data + MCP endpoint (A) (#62431)

Alex Vaa17180a9c6e
diff --git a/products/business_knowledge/backend/constants.py b/products/business_knowledge/backend/constants.py
index 993e9bab041c..aef2c22b0371 100644
--- a/products/business_knowledge/backend/constants.py
+++ b/products/business_knowledge/backend/constants.py
@@ -138,3 +138,11 @@ 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
+
+# --- Drill-down (agentic read) tunables ---
+# Default chunk radius for get_document_window: returns center +/- radius
+# chunks (up to 2*radius+1 = 11 chunks ~= 13k chars at typical size).
+BK_DRILLDOWN_DEFAULT_RADIUS = 5
+# Hard cap on drill-down radius. radius=15 => up to 31 chunks ~= 50k chars;
+# bounds how much one read_data call can pull.
+BK_DRILLDOWN_MAX_RADIUS = 15
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index 348686c6b139..2007a1bf1685 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -30,6 +30,8 @@ from posthog.security.url_validation import is_url_allowed
from . import crawl, discover, file_parse, html_parse, url_fetch
from .constants import (
+ BK_DRILLDOWN_DEFAULT_RADIUS,
+ BK_DRILLDOWN_MAX_RADIUS,
BK_EMBEDDING_DOCUMENT_TYPE,
BK_EMBEDDING_MODEL,
BK_EMBEDDING_PRODUCT,
@@ -1614,6 +1616,16 @@ def _rrf_fuse(
return [cid for cid, _score in fused]
+def _safe_chunks_qs(team_id: int) -> QuerySet[KnowledgeChunk]:
+ """Base queryset for searchable/readable chunks: team-scoped + all safety gates."""
+ return KnowledgeChunk.objects.filter(
+ team_id=team_id,
+ source__status=SourceStatus.READY,
+ document__tombstoned_at__isnull=True,
+ document__safety_verdict=SafetyVerdict.SAFE,
+ )
+
+
@dataclass(frozen=True)
class KnowledgeSearchResult:
"""A single chunk returned by a knowledge search, with source context."""
@@ -1658,13 +1670,8 @@ def search_knowledge(
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,
- )
+ _safe_chunks_qs(team_id)
+ .filter(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]
@@ -1688,13 +1695,7 @@ def search_knowledge(
# 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")
+ _safe_chunks_qs(team_id).filter(id__in=fused_ids[:fetch_limit]).only("id", "document_id", "ordinal")
)
if not anchor_chunks:
return []
@@ -1723,13 +1724,8 @@ def search_knowledge(
)
chunks = (
- KnowledgeChunk.objects.filter(
- window_filter,
- team_id=team_id,
- source__status=SourceStatus.READY,
- document__tombstoned_at__isnull=True,
- document__safety_verdict=SafetyVerdict.SAFE,
- )
+ _safe_chunks_qs(team_id)
+ .filter(window_filter)
.select_related("source", "document")
.only(
"id",
@@ -1762,6 +1758,64 @@ def search_knowledge(
]
+# ---------------------------------------------------------------------------
+# Drill-down: wider context window for a single document
+# ---------------------------------------------------------------------------
+
+
+@with_team_scope(canonical=True)
+def get_document_window(
+ team_id: int,
+ document_id: UUID,
+ center_ordinal: int,
+ *,
+ radius: int = BK_DRILLDOWN_DEFAULT_RADIUS,
+) -> list[KnowledgeSearchResult]:
+ """
+ Return a contiguous span of chunks from one document, centered on
+ ``center_ordinal``. Reuses the exact same safety filters as
+ ``search_knowledge`` so drill-down can never surface content that search
+ wouldn't return.
+ """
+ radius = max(0, min(radius, BK_DRILLDOWN_MAX_RADIUS))
+ center_ordinal = max(0, center_ordinal)
+ low = max(0, center_ordinal - radius)
+ high = center_ordinal + radius
+
+ chunks = (
+ _safe_chunks_qs(team_id)
+ .filter(document_id=document_id, ordinal__gte=low, ordinal__lte=high)
+ .select_related("source", "document")
+ .only(
+ "id",
+ "source_id",
+ "document_id",
+ "heading_path",
+ "ordinal",
+ "content",
+ "source__name",
+ "source__source_type",
+ "document__title",
+ )
+ .order_by("ordinal")
+ )
+
+ return [
+ KnowledgeSearchResult(
+ chunk_id=c.id,
+ source_id=c.source_id,
+ source_name=c.source.name,
+ source_type=c.source.source_type,
+ document_id=c.document_id,
+ document_title=c.document.title,
+ heading_path=c.heading_path,
+ ordinal=c.ordinal,
+ content=c.content,
+ )
+ for c in chunks
+ ]
+
+
# ---------------------------------------------------------------------------
# Background-refresh coordinator helpers (cross-team)
#
diff --git a/products/business_knowledge/backend/tests/test_hybrid_search.py b/products/business_knowledge/backend/tests/test_hybrid_search.py
index a95a01412a9c..f2314e957c6d 100644
--- a/products/business_knowledge/backend/tests/test_hybrid_search.py
+++ b/products/business_knowledge/backend/tests/test_hybrid_search.py
@@ -11,8 +11,13 @@ 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.constants import BK_DRILLDOWN_MAX_RADIUS, BK_RRF_SCORE_FLOOR
+from products.business_knowledge.backend.logic import (
+ _rrf_fuse,
+ _SemanticCandidate,
+ get_document_window,
+ search_knowledge,
+)
from products.business_knowledge.backend.models import (
KnowledgeChunk,
KnowledgeDocument,
@@ -225,3 +230,119 @@ class TestHybridSearch(BaseTest):
)
# Should still find results via FTS
assert len(results) >= 1
+
+
+class TestDocumentWindow(BaseTest):
+ """Tests for get_document_window drill-down logic."""
+
+ def _create_source_with_chunks(
+ self, num_chunks: int, *, safe: bool = True, name: str = "src"
+ ) -> tuple[KnowledgeSource, KnowledgeDocument]:
+ """Create a source with exactly num_chunks chunks (bypasses chunker)."""
+ with team_scope(self.team.id, canonical=True):
+ source = KnowledgeSource.objects.create(
+ team_id=self.team.id,
+ name=name,
+ source_type="text",
+ status=SourceStatus.READY,
+ )
+ doc = KnowledgeDocument.objects.create(
+ team_id=self.team.id,
+ source=source,
+ title=f"Doc for {name}",
+ safety_verdict=SafetyVerdict.SAFE if safe else SafetyVerdict.UNKNOWN,
+ )
+ chunks = []
+ for i in range(num_chunks):
+ content = f"Content of chunk {i} in document."
+ chunks.append(
+ KnowledgeChunk(
+ id=uuid.uuid4(),
+ team_id=self.team.id,
+ source=source,
+ document=doc,
+ ordinal=i,
+ content=content,
+ heading_path=f"Section {i}",
+ char_count=len(content),
+ )
+ )
+ KnowledgeChunk.objects.bulk_create(chunks)
+ return source, doc
+
+ @parameterized.expand(
+ [
+ ("contiguous_span", 10, 5, 2, [3, 4, 5, 6, 7]),
+ ("radius_zero", 5, 2, 0, [2]),
+ ("edge_no_wrap", 5, 0, 3, [0, 1, 2, 3]),
+ ("negative_center_clamped_to_zero", 5, -3, 2, [0, 1, 2]),
+ ]
+ )
+ def test_ordinal_window(self, _name: str, num_chunks: int, center: int, radius: int, expected: list[int]) -> None:
+ _source, doc = self._create_source_with_chunks(num_chunks)
+
+ results = get_document_window(self.team.id, doc.id, center_ordinal=center, radius=radius)
+
+ assert [r.ordinal for r in results] == expected
+
+ def test_radius_clamped_to_max(self) -> None:
+ _source, doc = self._create_source_with_chunks(40)
+
+ results = get_document_window(self.team.id, doc.id, center_ordinal=20, radius=100)
+
+ ordinals = [r.ordinal for r in results]
+ low = 20 - BK_DRILLDOWN_MAX_RADIUS
+ high = 20 + BK_DRILLDOWN_MAX_RADIUS
+ assert all(low <= o <= high for o in ordinals)
+ assert len(ordinals) <= 2 * BK_DRILLDOWN_MAX_RADIUS + 1
+
+ @parameterized.expand(
+ [
+ (
+ "unsafe_verdict",
+ lambda doc: KnowledgeDocument.objects.filter(id=doc.id).update(safety_verdict=SafetyVerdict.UNSAFE),
+ ),
+ (
+ "tombstoned",
+ lambda doc: KnowledgeDocument.objects.filter(id=doc.id).update(tombstoned_at=timezone.now()),
+ ),
+ (
+ "source_not_ready",
+ lambda doc: KnowledgeSource.objects.filter(id=doc.source_id).update(status=SourceStatus.PROCESSING),
+ ),
+ ]
+ )
+ def test_safety_filters_return_empty(self, _name: str, mark_ineligible) -> None: # noqa: ANN001
+ _source, doc = self._create_source_with_chunks(3)
+
+ with team_scope(self.team.id, canonical=True):
+ mark_ineligible(doc)
+
+ results = get_document_window(self.team.id, doc.id, center_ordinal=0, radius=5)
+ assert results == []
+
+ def test_cross_team_returns_empty(self) -> None:
+ from posthog.models.team import Team
+
+ _source, doc = self._create_source_with_chunks(3)
+
+ other_team = Team.objects.create_with_data(
+ organization=self.organization, initiating_user=self.user, name="Other"
+ )
+ results = get_document_window(other_team.id, doc.id, center_ordinal=0, radius=5)
+ assert results == []
+
+ def test_unknown_document_returns_empty(self) -> None:
+ results = get_document_window(self.team.id, uuid.uuid4(), center_ordinal=0, radius=5)
+ assert results == []
+
+ def test_result_fields_populated(self) -> None:
+ _source, doc = self._create_source_with_chunks(3, name="my_source")
+
+ results = get_document_window(self.team.id, doc.id, center_ordinal=0, radius=0)
+
+ assert len(results) == 1
+ r = results[0]
+ assert r.document_id == doc.id
+ assert r.source_name == "my_source"
+ assert "Content of chunk 0" in r.content