: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(bk): show embedding status on knowledge sources (#63263)
Alex V8e88c59aa8dd
diff --git a/products/business_knowledge/backend/api/serializers.py b/products/business_knowledge/backend/api/serializers.pyindex 5b1c1f789253..09cb4197d485 100644--- a/products/business_knowledge/backend/api/serializers.py+++ b/products/business_knowledge/backend/api/serializers.py@@ -3,6 +3,7 @@from django.core.files.uploadedfile import UploadedFilefrom django.utils import timezone+from drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializersfrom posthog.security.url_validation import is_url_allowed@@ -16,7 +17,14 @@ from ..constants import (MAX_TEXT_SIZE_BYTES,MAX_URLS_PER_SOURCE,)-from ..models import REFRESH_INTERVAL_TIMEDELTAS, CrawlMode, KnowledgeSource, RefreshInterval, SourceType+from ..models import (+ REFRESH_INTERVAL_TIMEDELTAS,+ CrawlMode,+ EmbeddingStatus,+ KnowledgeSource,+ RefreshInterval,+ SourceType,+)class _GlobListField(serializers.ListField):@@ -69,6 +77,16 @@ class KnowledgeSourceSerializer(serializers.ModelSerializer):has_unsafe_documents = serializers.SerializerMethodField(help_text="True when at least one document in this source was flagged unsafe by the content classifier and is therefore excluded from agent search.",)+ embedding_status = serializers.SerializerMethodField(+ help_text=(+ "Semantic-index state of this source. A `ready` source serves keyword (full-text) search "+ "immediately, but semantic search needs a background job to classify and embed its documents, "+ "which can take up to an hour. `pending` — at least one document is still awaiting "+ "classification or embedding. `completed` — every eligible document has been submitted to the "+ "embedding pipeline. `disabled` — the organization has not approved AI data processing, so "+ "embeddings never run and search stays keyword-only. Only meaningful while `status` is `ready`."+ ),+ )class Meta:model = KnowledgeSource@@ -90,6 +108,7 @@ class KnowledgeSourceSerializer(serializers.ModelSerializer):"refresh_interval","next_refresh_at","has_unsafe_documents",+ "embedding_status","crawl_mode","crawl_config","original_filename",@@ -113,6 +132,28 @@ class KnowledgeSourceSerializer(serializers.ModelSerializer):# Annotated by the logic layer to avoid an N+1 in list responses.return bool(getattr(obj, "_has_unsafe_documents", False))+ @extend_schema_field(serializers.ChoiceField(choices=EmbeddingStatus.choices))+ def get_embedding_status(self, obj: KnowledgeSource) -> str:+ # Both inputs are annotated by the logic layer (list_for_team /+ # get_for_team) to avoid N+1s. When a source is serialized without+ # annotations (future code path), fall back to a live DB query for+ # both rather than silently returning the wrong value.+ if hasattr(obj, "_ai_processing_approved"):+ approved = bool(obj._ai_processing_approved)+ else:+ approved = bool(obj.team.organization.is_ai_data_processing_approved)+ if not approved:+ return EmbeddingStatus.DISABLED+ if hasattr(obj, "_has_pending_embeddings"):+ pending = bool(obj._has_pending_embeddings)+ else:+ from .. import logic++ pending = logic.has_pending_embeddings(obj.id)+ if pending:+ return EmbeddingStatus.PENDING+ return EmbeddingStatus.COMPLETED+class CreateTextSourceSerializer(_NameValidationMixin, serializers.Serializer):name = serializers.CharField(diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.pyindex 6aadc09b5f93..19877e54eb56 100644--- a/products/business_knowledge/backend/logic.py+++ b/products/business_knowledge/backend/logic.py@@ -295,6 +295,43 @@ def _unsafe_documents_subquery() -> Exists:)+def _pending_embedding_documents_subquery() -> Exists:+ """+ Live docs that are still on their way into the semantic index: either+ awaiting safety classification (with retries left — docs past the attempt+ cap stay excluded forever, so they're not "pending"), or already SAFE with+ chunks but not yet produced to the embedding pipeline. Mirrors the+ eligibility rules of `_embeddable_documents_qs` so the API never reports+ "pending" for a doc the coordinator will never pick up.+ """+ has_chunks = Exists(KnowledgeChunk.objects.filter(document_id=OuterRef("pk")))+ return Exists(+ KnowledgeDocument.objects.filter(source_id=OuterRef("pk"), tombstoned_at__isnull=True).filter(+ Q(safety_verdict=SafetyVerdict.UNKNOWN, classification_attempts__lt=CLASSIFY_MAX_ATTEMPTS)+ | (Q(safety_verdict=SafetyVerdict.SAFE, embeddings_emitted_at__isnull=True) & Q(has_chunks))+ )+ )+++def has_pending_embeddings(source_id: UUID) -> bool:+ """Standalone DB check — same logic as the annotation subquery."""+ return (+ KnowledgeDocument.objects.filter(+ source_id=source_id,+ tombstoned_at__isnull=True,+ )+ .filter(+ Q(safety_verdict=SafetyVerdict.UNKNOWN, classification_attempts__lt=CLASSIFY_MAX_ATTEMPTS)+ | Q(+ safety_verdict=SafetyVerdict.SAFE,+ embeddings_emitted_at__isnull=True,+ chunks__isnull=False,+ )+ )+ .exists()+ )++@with_team_scope(canonical=True)def list_for_team(team_id: int) -> list[KnowledgeSource]:# Annotate counts in one round-trip so the serializer doesn't N+1.@@ -304,6 +341,8 @@ def list_for_team(team_id: int) -> list[KnowledgeSource]:_document_count=Count("documents", distinct=True),_chunk_count=Count("chunks", distinct=True),_has_unsafe_documents=_unsafe_documents_subquery(),+ _has_pending_embeddings=_pending_embedding_documents_subquery(),+ _ai_processing_approved=F("team__organization__is_ai_data_processing_approved"),).order_by("-created_at"))@@ -316,6 +355,8 @@ def get_for_team(source_id: UUID, team_id: int) -> KnowledgeSource | None:_document_count=Count("documents", distinct=True),_chunk_count=Count("chunks", distinct=True),_has_unsafe_documents=_unsafe_documents_subquery(),+ _has_pending_embeddings=_pending_embedding_documents_subquery(),+ _ai_processing_approved=F("team__organization__is_ai_data_processing_approved"),).get(id=source_id, team_id=team_id)except KnowledgeSource.DoesNotExist:return Nonediff --git a/products/business_knowledge/backend/models/__init__.py b/products/business_knowledge/backend/models/__init__.pyindex ee8aee63e8a7..a8fd11a4fb8c 100644--- a/products/business_knowledge/backend/models/__init__.py+++ b/products/business_knowledge/backend/models/__init__.py@@ -1,6 +1,7 @@from .constants import (REFRESH_INTERVAL_TIMEDELTAS,CrawlMode,+ EmbeddingStatus,RefreshInterval,RefreshStatus,SafetyVerdict,@@ -14,6 +15,7 @@ from .knowledge_source import KnowledgeSource__all__ = ["REFRESH_INTERVAL_TIMEDELTAS","CrawlMode",+ "EmbeddingStatus","KnowledgeChunk","KnowledgeDocument","KnowledgeSource",diff --git a/products/business_knowledge/backend/models/constants.py b/products/business_knowledge/backend/models/constants.pyindex 976c0721d50f..81c267dd7248 100644--- a/products/business_knowledge/backend/models/constants.py+++ b/products/business_knowledge/backend/models/constants.py@@ -78,6 +78,20 @@ REFRESH_INTERVAL_TIMEDELTAS: dict[str, datetime.timedelta] = {}+class EmbeddingStatus(models.TextChoices):+ """+ API-only (not a DB column): semantic-index state of a source, derived+ from its documents. A `ready` source serves keyword (FTS) search right+ away, but semantic search needs the hourly coordinator to classify and+ embed its documents — `pending` covers that window. `disabled` means the+ org has not approved AI data processing, so embeddings never run.+ """++ PENDING = "pending", "Pending"+ COMPLETED = "completed", "Completed"+ DISABLED = "disabled", "Disabled"++class SafetyVerdict(models.TextChoices):"""Content-safety classification of a document, set by the backgrounddiff --git a/products/business_knowledge/backend/tests/test_api.py b/products/business_knowledge/backend/tests/test_api.pyindex 44542a85ad89..f0eebf83ce16 100644--- a/products/business_knowledge/backend/tests/test_api.py+++ b/products/business_knowledge/backend/tests/test_api.py@@ -1,11 +1,15 @@from posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.utils import timezone++from parameterized import parameterizedfrom rest_framework import statusfrom posthog.models.activity_logging.activity_log import ActivityLogfrom products.business_knowledge.backend import logic+from products.business_knowledge.backend.constants import CLASSIFY_MAX_ATTEMPTSfrom products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource, SafetyVerdict@@ -111,6 +115,55 @@ class TestKnowledgeSourceAPI(APIBaseTest):assert response.json()["source_type"] == "text"+@patch("posthoganalytics.feature_enabled", return_value=True)+class TestEmbeddingStatusAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.url = f"/api/projects/{self.team.id}/business_knowledge/sources/"++ def _create_source(self) -> str:+ response = self.client.post(self.url, {"name": "Docs", "text": "Some content."}, format="json")+ assert response.status_code == status.HTTP_201_CREATED, response.content+ return response.json()["id"]++ def test_fresh_source_is_pending(self, _ff) -> None:+ # The doc starts UNKNOWN — classification + embedding are still ahead,+ # and that must be visible from the create response already.+ response = self.client.post(self.url, {"name": "Docs", "text": "Some content."}, format="json")+ assert response.json()["embedding_status"] == "pending"++ @parameterized.expand(+ [+ ("awaiting_classification", SafetyVerdict.UNKNOWN, 0, False, "pending"),+ # Past the attempt cap the coordinator stops re-queuing — the doc+ # will never embed, so the source must not look pending forever.+ ("classification_gave_up", SafetyVerdict.UNKNOWN, CLASSIFY_MAX_ATTEMPTS, False, "completed"),+ ("awaiting_embedding_emit", SafetyVerdict.SAFE, 0, False, "pending"),+ ("embedded", SafetyVerdict.SAFE, 0, True, "completed"),+ ("unsafe_never_embeds", SafetyVerdict.UNSAFE, 0, False, "completed"),+ ]+ )+ def test_embedding_status_reflects_document_state(self, _ff, name, verdict, attempts, emitted, expected) -> None:+ source_id = self._create_source()+ KnowledgeDocument.objects.unscoped().filter(source_id=source_id).update(+ safety_verdict=verdict,+ classification_attempts=attempts,+ embeddings_emitted_at=timezone.now() if emitted else None,+ )+ retrieve = self.client.get(f"{self.url}{source_id}/").json()+ assert retrieve["embedding_status"] == expected, name+ listed = self.client.get(self.url).json()["results"]+ assert listed[0]["embedding_status"] == expected, name++ @parameterized.expand([("declined", False), ("undecided", None)])+ def test_disabled_when_org_has_not_approved_ai_processing(self, _ff, _name, approved) -> None:+ source_id = self._create_source()+ self.organization.is_ai_data_processing_approved = approved+ self.organization.save()+ response = self.client.get(f"{self.url}{source_id}/").json()+ assert response["embedding_status"] == "disabled"++@patch("posthoganalytics.feature_enabled", return_value=True)class TestKnowledgeDocumentWindowAPI(APIBaseTest):def setUp(self) -> None:diff --git a/products/business_knowledge/frontend/components/StatusTag.tsx b/products/business_knowledge/frontend/components/StatusTag.tsxindex bda63cbb7995..7d36fb010dfd 100644--- a/products/business_knowledge/frontend/components/StatusTag.tsx+++ b/products/business_knowledge/frontend/components/StatusTag.tsx@@ -1,9 +1,30 @@-import { LemonTag } from '@posthog/lemon-ui'+import { LemonTag, Tooltip } from '@posthog/lemon-ui'import { KnowledgeSource } from '../scenes/businessKnowledgeLogic'-export function StatusTag({ status }: { status: KnowledgeSource['status'] }): JSX.Element {- const variant =- status === 'ready' ? 'success' : status === 'error' ? 'danger' : status === 'processing' ? 'warning' : 'muted'- return <LemonTag type={variant}>{status}</LemonTag>+export function StatusTag({ source }: { source: KnowledgeSource }): JSX.Element {+ if (source.status === 'ready') {+ // Chunks + keyword (full-text) search are ready immediately, but semantic+ // embeddings are generated by a background job that can take up to an hour.+ if (source.embedding_status === 'pending') {+ return (+ <Tooltip title="Keyword search works already. Semantic search embeddings are generated in the background — this can take up to an hour.">+ <LemonTag type="completion">indexing</LemonTag>+ </Tooltip>+ )+ }+ return (+ <Tooltip+ title={+ source.embedding_status === 'disabled'+ ? 'Indexed for keyword search. Semantic search is off because AI data processing is not approved for your organization.'+ : 'Fully indexed for keyword and semantic search.'+ }+ >+ <LemonTag type="success">ready</LemonTag>+ </Tooltip>+ )+ }+ const variant = source.status === 'error' ? 'danger' : source.status === 'processing' ? 'warning' : 'muted'+ return <LemonTag type={variant}>{source.status}</LemonTag>}diff --git a/products/business_knowledge/frontend/generated/api.schemas.ts b/products/business_knowledge/frontend/generated/api.schemas.tsindex c7c7b0cb47fc..db173838d29b 100644--- a/products/business_knowledge/frontend/generated/api.schemas.ts+++ b/products/business_knowledge/frontend/generated/api.schemas.ts@@ -116,6 +116,14 @@ export const RefreshIntervalEnumApi = {'7d': '7d',} as const+export type EmbeddingStatusEnumApi = (typeof EmbeddingStatusEnumApi)[keyof typeof EmbeddingStatusEnumApi]++export const EmbeddingStatusEnumApi = {+ Pending: 'pending',+ Completed: 'completed',+ Disabled: 'disabled',+} as const+/*** * `single` - Single page* * `sitemap` - Sitemap@@ -158,6 +166,8 @@ export interface KnowledgeSourceApi {readonly next_refresh_at: string | null/** True when at least one document in this source was flagged unsafe by the content classifier and is therefore excluded from agent search. */readonly has_unsafe_documents: boolean+ /** Semantic-index state of this source. A `ready` source serves keyword (full-text) search immediately, but semantic search needs a background job to classify and embed its documents, which can take up to an hour. `pending` — at least one document is still awaiting classification or embedding. `completed` — every eligible document has been submitted to the embedding pipeline. `disabled` — the organization has not approved AI data processing, so embeddings never run and search stays keyword-only. Only meaningful while `status` is `ready`. */+ readonly embedding_status: EmbeddingStatusEnumApireadonly crawl_mode: CrawlModeEnumApireadonly crawl_config: unknownreadonly original_filename: stringdiff --git a/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsxindex 9e8abda18334..490a77ba9058 100644--- a/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx+++ b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx@@ -107,7 +107,7 @@ export function BusinessKnowledgeScene(): JSX.Element {{title: 'Status',key: 'status',- render: (_, row) => <StatusTag status={row.status} />,+ render: (_, row) => <StatusTag source={row} />,},{title: 'Pages / chunks',diff --git a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.tsindex 43b26af1720c..aca10495de98 100644--- a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts+++ b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts@@ -353,9 +353,13 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([loadSourcesSuccess: ({ sources }) => {// URL ingestion runs in the background — poll while anything is still// processing so the row flips to ready (or error) without a manual reload.- if (sources.some((s) => s.status === 'processing')) {+ // After that, embeddings are generated by an hourly background job, so+ // keep polling at a much slower cadence until everything is fully indexed.+ const isProcessing = sources.some((s) => s.status === 'processing')+ const isEmbedding = sources.some((s) => s.status === 'ready' && s.embedding_status === 'pending')+ if (isProcessing || isEmbedding) {cache.disposables.add(() => {- const id = setTimeout(() => actions.loadSources(), 3000)+ const id = setTimeout(() => actions.loadSources(), isProcessing ? 3000 : 60000)return () => clearTimeout(id)}, 'pollProcessing')} else {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 39c76df8b3f5..9007ee1eeb6a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14797,6 +14797,15 @@ export namespace Schemas {design?: EmailTemplateDesign;}+ export type EmbeddingStatusEnum = typeof EmbeddingStatusEnum[keyof typeof EmbeddingStatusEnum];+++ export const EmbeddingStatusEnum = {+ Pending: 'pending',+ Completed: 'completed',+ Disabled: 'disabled',+ } as const;+/*** One citation attached to a finding. Mirrors `SignalsScoutEvidenceEntry`.*/@@ -22240,6 +22249,8 @@ export namespace Schemas {readonly next_refresh_at: string | null;/** True when at least one document in this source was flagged unsafe by the content classifier and is therefore excluded from agent search. */readonly has_unsafe_documents: boolean;+ /** Semantic-index state of this source. A `ready` source serves keyword (full-text) search immediately, but semantic search needs a background job to classify and embed its documents, which can take up to an hour. `pending` — at least one document is still awaiting classification or embedding. `completed` — every eligible document has been submitted to the embedding pipeline. `disabled` — the organization has not approved AI data processing, so embeddings never run and search stays keyword-only. Only meaningful while `status` is `ready`. */+ readonly embedding_status: EmbeddingStatusEnum;readonly crawl_mode: CrawlModeEnum;readonly crawl_config: unknown;readonly original_filename: string;