: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(business-knowledge): emit chunk embeddings for SAFE documents (#62083)
Alex V16843736285e
diff --git a/products/business_knowledge/backend/constants.py b/products/business_knowledge/backend/constants.pyindex 4a332fb8479a..f2baca5cc133 100644--- a/products/business_knowledge/backend/constants.py+++ b/products/business_knowledge/backend/constants.py@@ -2,6 +2,8 @@Constants and tunables for business_knowledge."""+import datetime+# Per-team caps. Enforced in the create endpoint, not at the DB layer — easier# to relax for a single paying customer without a migration.MAX_SOURCES_PER_TEAM = 500@@ -86,3 +88,27 @@ CLASSIFY_MAX_TOTAL_CHARS = 1_000_000# the hourly cadence this is ~5 hours of retries — enough to ride out a# transient Gemini outage, bounded enough to not loop forever on poison content.CLASSIFY_MAX_ATTEMPTS = 5++# --- Embedding pipeline tunables (hybrid retrieval) ---+# Embedding model used for both producing chunk vectors and (later) embedding+# search queries. MUST match a model_name in error_tracking's EMBEDDING_TABLES,+# and emit-model MUST equal query-model or cosineDistance compares across spaces.+BK_EMBEDDING_MODEL = "text-embedding-3-small-1536"+# `product` / `document_type` buckets in the shared `document_embeddings` table.+# One embedding row per chunk (document_id = chunk_id) so citations stay stable+# and the read path can re-join to Postgres chunks. Shared with the read path.+BK_EMBEDDING_PRODUCT = "business_knowledge"+BK_EMBEDDING_DOCUMENT_TYPE = "chunk"+BK_EMBEDDING_RENDERING = "plain"+# Per coordinator pass: how many SAFE documents we pull to emit embeddings for.+# Each pending doc loads its chunk content into memory to produce to Kafka, so+# this is the same memory knob as PENDING_CLASSIFICATION_SCAN_CAP. Kept small so+# the first post-deploy pass (which backfills every existing SAFE doc across all+# teams) drains over many hourly passes instead of blowing up one run.+PENDING_EMBEDDING_SCAN_CAP = 50+# Reconciliation: how many already-emitted SAFE docs to re-verify against+# ClickHouse per pass (oldest-emitted first), and the grace period a doc must+# have been emitted for before it's eligible. The grace window keeps us from+# re-checking docs whose vectors are simply still in flight through Kafka.+RECONCILE_EMBEDDING_SCAN_CAP = 50+RECONCILE_EMBEDDING_GRACE = datetime.timedelta(hours=2)diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.pyindex b8eaa4f2e10d..bf5ccc6c3529 100644--- a/products/business_knowledge/backend/logic.py+++ b/products/business_knowledge/backend/logic.py@@ -6,6 +6,7 @@ All ORM access, chunking, quota enforcement, and search queries.import uuidimport datetime+from collections import defaultdictfrom dataclasses import dataclassfrom functools import reducefrom operator import or_@@ -17,7 +18,7 @@ from django.db import (connection as db_connection,transaction,)-from django.db.models import Count, Exists, F, OuterRef, Q+from django.db.models import Count, Exists, F, OuterRef, Q, QuerySetfrom django.db.models.functions import Substrfrom django.utils import timezone@@ -40,6 +41,9 @@ from .constants import (MAX_SOURCES_PER_TEAM,MAX_TEXT_SIZE_BYTES,MAX_URLS_PER_SOURCE,+ PENDING_EMBEDDING_SCAN_CAP,+ RECONCILE_EMBEDDING_GRACE,+ RECONCILE_EMBEDDING_SCAN_CAP,)from .models import (REFRESH_INTERVAL_TIMEDELTAS,@@ -1134,10 +1138,13 @@ def _insert_document_and_chunks(document.tombstoned_at = None# Content changed (caller only reaches this branch on a hash diff), so# the prior safety verdict no longer applies — re-queue for- # classification with a fresh attempt budget.+ # classification with a fresh attempt budget. The old chunk vectors are+ # stale too (and the chunk ids may shift), so clear the embedding stamp+ # to re-embed once the new content is re-classified SAFE.document.safety_verdict = SafetyVerdict.UNKNOWNdocument.safety_reason = ""document.classification_attempts = 0+ document.embeddings_emitted_at = Nonedocument.save(update_fields=["title",@@ -1150,6 +1157,7 @@ def _insert_document_and_chunks("safety_verdict","safety_reason","classification_attempts",+ "embeddings_emitted_at","updated_at",])@@ -1762,3 +1770,183 @@ def sweep_tombstoned_documents(*, older_than: datetime.timedelta = datetime.timeKnowledgeDocument.objects.unscoped().filter(tombstoned_at__isnull=False, tombstoned_at__lt=cutoff).delete())return deleted+++# ---------------------------------------------------------------------------+# Embedding-pipeline coordinator helpers (cross-team)+#+# Like the classification helpers above, these run inside Temporal activities+# and scan across teams via `.unscoped()`. They only read/write Postgres; the+# actual produce-to-Kafka and ClickHouse presence check live in the coordinator+# activity so this module stays free of Kafka / ClickHouse dependencies.+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class ChunkToEmbed:+ chunk_id: UUID+ content: str+++@dataclass(frozen=True)+class DocumentToEmbed:+ """A SAFE document whose chunks need producing to the embedding pipeline."""++ team_id: int+ document_id: UUID+ # The document's stable `created_at`, passed as the embedding row `timestamp`+ # so a re-emit of the same chunk_id collapses onto one ClickHouse sort key /+ # partition instead of duplicating under a later `toDate(timestamp)`.+ timestamp: datetime.datetime+ chunks: list[ChunkToEmbed]+++@dataclass(frozen=True)+class EmittedDocument:+ """An already-emitted SAFE document, for ClickHouse-presence reconciliation."""++ team_id: int+ document_id: UUID+ chunk_ids: list[UUID]+++def _embeddable_documents_qs() -> QuerySet[KnowledgeDocument]:+ """Base queryset of docs eligible to be embedded: SAFE, live, READY source,+ and an org that approved AI data processing (we must not send content to the+ embedding service otherwise — same gate as classification). Cross-team.++ Zero-chunk docs are excluded: there's nothing to embed, and letting one+ through would loop forever — emit stamps it with no produce, then+ reconciliation finds no vectors in ClickHouse and clears the stamp, putting+ it right back in the pending queue. A SAFE doc with no chunks is unlikely but+ reachable (e.g. whitespace-only content), so we filter it out at the source.+ """+ return (+ KnowledgeDocument.objects.unscoped()+ .filter(+ safety_verdict=SafetyVerdict.SAFE,+ tombstoned_at__isnull=True,+ source__status=SourceStatus.READY,+ team__organization__is_ai_data_processing_approved=True,+ )+ .filter(Exists(KnowledgeChunk.objects.unscoped().filter(document_id=OuterRef("pk"))))+ )+++def _chunks_to_embed_by_document(document_ids: list[UUID]) -> dict[UUID, list[ChunkToEmbed]]:+ """Load chunk content for many docs in ONE query, grouped by document_id and+ ordered by ordinal within each doc. Avoids an N+1 (one query per pending+ doc). Cross-team."""+ by_doc: dict[UUID, list[ChunkToEmbed]] = defaultdict(list)+ for document_id, chunk_id, content in (+ KnowledgeChunk.objects.unscoped()+ .filter(document_id__in=document_ids)+ .order_by("document_id", "ordinal")+ .values_list("document_id", "id", "content")+ ):+ by_doc[document_id].append(ChunkToEmbed(chunk_id=chunk_id, content=content))+ return by_doc+++def _chunk_ids_by_document(document_ids: list[UUID]) -> dict[UUID, list[UUID]]:+ """Load chunk ids for many docs in ONE query, grouped by document_id. Avoids+ an N+1 in reconciliation. Cross-team."""+ by_doc: dict[UUID, list[UUID]] = defaultdict(list)+ for document_id, chunk_id in (+ KnowledgeChunk.objects.unscoped().filter(document_id__in=document_ids).values_list("document_id", "id")+ ):+ by_doc[document_id].append(chunk_id)+ return by_doc+++def list_documents_pending_embedding(*, limit: int = PENDING_EMBEDDING_SCAN_CAP) -> list[DocumentToEmbed]:+ """+ Return SAFE documents that have not yet had their chunks produced to the+ embedding pipeline (``embeddings_emitted_at IS NULL``).++ Bounded by ``limit`` (loads chunk content per doc into memory, same rationale+ as ``list_documents_pending_classification``). The first post-deploy pass+ backfills every existing SAFE doc across all teams, so the cap is what lets+ the hourly coordinator drain that over many passes. Cross-team — coordinator+ only.+ """+ rows = list(+ _embeddable_documents_qs()+ .filter(embeddings_emitted_at__isnull=True)+ .values_list("team_id", "id", "created_at")[:limit]+ )+ chunks_by_doc = _chunks_to_embed_by_document([document_id for _team_id, document_id, _created_at in rows])+ return [+ DocumentToEmbed(+ team_id=team_id,+ document_id=document_id,+ timestamp=created_at,+ chunks=chunks_by_doc.get(document_id, []),+ )+ for team_id, document_id, created_at in rows+ ]+++def list_documents_for_embedding_reconciliation(+ *,+ now: datetime.datetime | None = None,+ grace: datetime.timedelta = RECONCILE_EMBEDDING_GRACE,+ limit: int = RECONCILE_EMBEDDING_SCAN_CAP,+) -> list[EmittedDocument]:+ """+ Return already-emitted SAFE docs (oldest first) whose vectors should by now+ be in ClickHouse, so the coordinator can re-verify they actually landed.++ ``embeddings_emitted_at`` only means "produced to Kafka", not "present in+ ClickHouse": a transient produce failure that did NOT raise, or a worker+ that dropped the message, leaves a SAFE doc permanently serving FTS-only.+ The grace window skips docs whose vectors are merely still in flight.+ Cross-team — coordinator only.+ """+ now = now or timezone.now()+ cutoff = now - grace+ rows = list(+ _embeddable_documents_qs()+ .filter(embeddings_emitted_at__isnull=False, embeddings_emitted_at__lt=cutoff)+ .order_by("embeddings_emitted_at")+ .values_list("team_id", "id")[:limit]+ )+ chunk_ids_by_doc = _chunk_ids_by_document([document_id for _team_id, document_id in rows])+ return [+ EmittedDocument(+ team_id=team_id,+ document_id=document_id,+ chunk_ids=chunk_ids_by_doc.get(document_id, []),+ )+ for team_id, document_id in rows+ ]+++@with_team_scope(canonical=True)+def mark_document_embeddings_emitted(*, team_id: int, document_id: UUID) -> None:+ """+ Stamp ``embeddings_emitted_at`` after a successful produce.++ Gated on the doc still being SAFE and unstamped: a concurrent content change+ resets the verdict to ``unknown`` and the stamp to NULL, and we must never+ mark that new (unembedded) content as emitted. The guard makes this a no-op+ in that race, so the new content is re-embedded on a later pass.+ """+ KnowledgeDocument.objects.filter(+ team_id=team_id,+ id=document_id,+ safety_verdict=SafetyVerdict.SAFE,+ embeddings_emitted_at__isnull=True,+ ).update(embeddings_emitted_at=timezone.now(), updated_at=timezone.now())+++@with_team_scope(canonical=True)+def clear_document_embeddings_emitted(*, team_id: int, document_id: UUID) -> None:+ """+ Reset the emission stamp to NULL so the next pending pass re-emits.++ Used by reconciliation when a doc's vectors never landed in ClickHouse.+ """+ KnowledgeDocument.objects.filter(team_id=team_id, id=document_id).update(+ embeddings_emitted_at=None, updated_at=timezone.now()+ )diff --git a/products/business_knowledge/backend/migrations/0010_knowledgedocument_embeddings_emitted_at.py b/products/business_knowledge/backend/migrations/0010_knowledgedocument_embeddings_emitted_at.pynew file mode 100644index 000000000000..435f82a251e6--- /dev/null+++ b/products/business_knowledge/backend/migrations/0010_knowledgedocument_embeddings_emitted_at.py@@ -0,0 +1,19 @@+# Adds a nullable timestamp marking when a document's chunks were last produced+# to the embedding pipeline. Additive + nullable — a brief metadata lock, safe+# online. The backing partial index is built CONCURRENTLY in 0011.++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("business_knowledge", "0009_bk_chunk_content_tsv_index"),+ ]++ operations = [+ migrations.AddField(+ model_name="knowledgedocument",+ name="embeddings_emitted_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/business_knowledge/backend/migrations/0011_bk_doc_embed_state_index.py b/products/business_knowledge/backend/migrations/0011_bk_doc_embed_state_index.pynew file mode 100644index 000000000000..891271b1bb1e--- /dev/null+++ b/products/business_knowledge/backend/migrations/0011_bk_doc_embed_state_index.py@@ -0,0 +1,40 @@+# Partial index backing the cross-team embedding passes. Partial on `safe` (the+# only verdict ever embedded) so it tracks just the embeddable working set, and+# serves both the pending scan (`embeddings_emitted_at IS NULL`) and the+# reconciliation scan (`embeddings_emitted_at < cutoff`). Concurrent build+# avoids locking the documents table.++from django.db import migrations, models++from posthog.migration_helpers import CreateIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("business_knowledge", "0010_knowledgedocument_embeddings_emitted_at"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AddIndex(+ model_name="knowledgedocument",+ index=models.Index(+ fields=["embeddings_emitted_at"],+ name="bk_doc_embed_state",+ condition=models.Q(safety_verdict="safe"),+ ),+ ),+ ],+ database_operations=[+ CreateIndexConcurrently(+ index_name="bk_doc_embed_state",+ table_name="posthog_business_knowledge_knowledgedocument",+ columns="(embeddings_emitted_at)",+ where="WHERE safety_verdict = 'safe'",+ ),+ ],+ ),+ ]diff --git a/products/business_knowledge/backend/migrations/max_migration.txt b/products/business_knowledge/backend/migrations/max_migration.txtindex b544d222fa88..e2ae8f15757b 100644--- a/products/business_knowledge/backend/migrations/max_migration.txt+++ b/products/business_knowledge/backend/migrations/max_migration.txt@@ -1 +1 @@-0009_bk_chunk_content_tsv_index+0011_bk_doc_embed_state_indexdiff --git a/products/business_knowledge/backend/models/knowledge_document.py b/products/business_knowledge/backend/models/knowledge_document.pyindex 311615b3400f..fe5504ab4c4e 100644--- a/products/business_knowledge/backend/models/knowledge_document.py+++ b/products/business_knowledge/backend/models/knowledge_document.py@@ -59,6 +59,15 @@ class KnowledgeDocument(UUIDModel):# re-queuing (the doc stays excluded). Reset to 0 whenever content changes.classification_attempts = models.PositiveSmallIntegerField(default=0, db_default=0)+ # When this doc's chunks were last produced to the embedding pipeline+ # (Kafka -> worker -> ClickHouse `document_embeddings`). NULL means "not yet+ # embedded" — the coordinator's embedding pass picks those up. Only ever+ # stamped for a SAFE doc whose produce succeeded; reset to NULL whenever+ # content changes (so the new content re-embeds) or when reconciliation+ # finds the vectors never landed in ClickHouse. "Emitted" means produced to+ # Kafka, not confirmed-present in ClickHouse — see logic.emit_pending_embeddings.+ embeddings_emitted_at = models.DateTimeField(null=True, blank=True)+objects = TeamScopedManager()class Meta:@@ -76,6 +85,16 @@ class KnowledgeDocument(UUIDModel):),# Cross-team scan for the tombstone hard-delete sweep.models.Index(fields=["tombstoned_at"], name="bk_doc_tombstoned"),+ # Backs the cross-team embedding passes. Partial on `safe` (the only+ # verdict that's ever embedded) so it tracks just the embeddable+ # working set. Serves BOTH the pending scan (`embeddings_emitted_at+ # IS NULL`, NULLs clustered in the btree) and the reconciliation+ # scan (`embeddings_emitted_at < cutoff ORDER BY ASC`).+ models.Index(+ fields=["embeddings_emitted_at"],+ name="bk_doc_embed_state",+ condition=models.Q(safety_verdict=SafetyVerdict.SAFE),+ ),]constraints = [models.UniqueConstraint(fields=["source", "stable_id"], name="bk_doc_unique_per_source"),diff --git a/products/business_knowledge/backend/temporal/__init__.py b/products/business_knowledge/backend/temporal/__init__.pyindex 1eeb4694b75c..2ffadf887d8e 100644--- a/products/business_knowledge/backend/temporal/__init__.py+++ b/products/business_knowledge/backend/temporal/__init__.py@@ -3,9 +3,11 @@ from .coordinator import (BusinessKnowledgeRefreshCoordinatorWorkflow,BusinessKnowledgeRefreshSourceWorkflow,classify_pending_documents_activity,+ emit_pending_embeddings_activity,execute_refresh_knowledge_source_activity,ingest_knowledge_source_activity,list_due_refresh_sources_activity,+ reconcile_embeddings_activity,refresh_knowledge_source_activity,sweep_tombstoned_documents_activity,)@@ -19,6 +21,8 @@ WORKFLOWS = [ACTIVITIES = [sweep_tombstoned_documents_activity,classify_pending_documents_activity,+ reconcile_embeddings_activity,+ emit_pending_embeddings_activity,list_due_refresh_sources_activity,refresh_knowledge_source_activity,execute_refresh_knowledge_source_activity,@@ -32,9 +36,11 @@ __all__ = ["BusinessKnowledgeRefreshCoordinatorWorkflow","BusinessKnowledgeRefreshSourceWorkflow","classify_pending_documents_activity",+ "emit_pending_embeddings_activity","execute_refresh_knowledge_source_activity","ingest_knowledge_source_activity","list_due_refresh_sources_activity",+ "reconcile_embeddings_activity","refresh_knowledge_source_activity","sweep_tombstoned_documents_activity",]diff --git a/products/business_knowledge/backend/temporal/coordinator.py b/products/business_knowledge/backend/temporal/coordinator.pyindex db6395ff7da0..085b474a16cb 100644--- a/products/business_knowledge/backend/temporal/coordinator.py+++ b/products/business_knowledge/backend/temporal/coordinator.py@@ -21,6 +21,7 @@ no bespoke concurrency cap here.import jsonimport asyncioimport dataclasses+from collections import defaultdictfrom datetime import timedeltafrom typing import Anyfrom uuid import UUID@@ -29,11 +30,17 @@ import structlogfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy+from posthog.hogql import ast+from posthog.hogql.query import execute_hogql_query++from posthog.api.embedding_worker import emit_embedding_request+from posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeaterfrom .. import logic, safety+from ..constants import BK_EMBEDDING_DOCUMENT_TYPE, BK_EMBEDDING_MODEL, BK_EMBEDDING_PRODUCT, BK_EMBEDDING_RENDERINGfrom ..models import SafetyVerdictlogger = structlog.get_logger(__name__)@@ -81,6 +88,130 @@ async def classify_pending_documents_activity() -> dict[str, Any]:return {"classified": len(results), "unsafe": unsafe}+def _emit_one_document(doc: logic.DocumentToEmbed) -> int:+ """+ Produce every chunk of one SAFE doc to the embedding pipeline, then stamp+ the doc as emitted. Runs in a worker thread (sync Kafka produce + DB write).++ If any chunk produce raises, the exception propagates BEFORE the stamp, so+ the doc stays unstamped and the next pass retries the whole doc. Re-emitting+ chunks that already landed is harmless — the shared table dedupes on+ (chunk_id, stable timestamp) via ReplacingMergeTree.+ """+ for chunk in doc.chunks:+ emit_embedding_request(+ content=chunk.content,+ team_id=doc.team_id,+ product=BK_EMBEDDING_PRODUCT,+ document_type=BK_EMBEDDING_DOCUMENT_TYPE,+ rendering=BK_EMBEDDING_RENDERING,+ document_id=str(chunk.chunk_id),+ models=[BK_EMBEDDING_MODEL],+ # Stable timestamp so re-emits collapse onto one ClickHouse sort key.+ timestamp=doc.timestamp,+ # `document_id` lets the read path group a doc's chunk vectors and+ # re-join to Postgres; the chunk's own id is the embedding row's id.+ metadata={"document_id": str(doc.document_id)},+ )+ logic.mark_document_embeddings_emitted(team_id=doc.team_id, document_id=doc.document_id)+ return len(doc.chunks)+++async def emit_pending_embeddings_activity() -> dict[str, Any]:+ """+ Produce embeddings for SAFE documents that haven't been embedded yet.++ Bounded by ``PENDING_EMBEDDING_SCAN_CAP``; the hourly coordinator drains the+ backlog (and the initial cross-team backfill) over many passes. Per-doc+ failures are logged and skipped without stamping, so they retry next pass.+ """+ docs = await database_sync_to_async(logic.list_documents_pending_embedding, thread_sensitive=False)()+ documents_embedded = 0+ chunks_emitted = 0+ for doc in docs:+ try:+ written = await database_sync_to_async(_emit_one_document, thread_sensitive=False)(doc)+ except Exception:+ logger.exception(+ "business_knowledge.embedding.emit_failed",+ team_id=doc.team_id,+ document_id=str(doc.document_id),+ )+ continue+ documents_embedded += 1+ chunks_emitted += written+ return {"documents_embedded": documents_embedded, "chunks_emitted": chunks_emitted}+++def _present_chunk_ids_in_clickhouse(team_id: int, chunk_ids: list[UUID]) -> set[str]:+ """Return the subset of ``chunk_ids`` that already have a vector row in the+ shared ClickHouse embeddings table for this team + model. HogQL auto-scopes+ to the team, so no manual team_id filter is needed."""+ if not chunk_ids:+ return set()+ team = Team.objects.get(pk=team_id)+ query = """+ SELECT DISTINCT document_id+ FROM document_embeddings+ WHERE product = {product}+ AND document_type = {document_type}+ AND model_name = {model_name}+ AND document_id IN {chunk_ids}+ """+ result = execute_hogql_query(+ query=query,+ team=team,+ placeholders={+ "product": ast.Constant(value=BK_EMBEDDING_PRODUCT),+ "document_type": ast.Constant(value=BK_EMBEDDING_DOCUMENT_TYPE),+ "model_name": ast.Constant(value=BK_EMBEDDING_MODEL),+ "chunk_ids": ast.Constant(value=[str(c) for c in chunk_ids]),+ },+ )+ return {row[0] for row in (result.results or [])}+++async def reconcile_embeddings_activity() -> dict[str, Any]:+ """+ Re-verify that already-emitted SAFE docs actually landed in ClickHouse.++ ``embeddings_emitted_at`` only means "produced to Kafka". If a produce was+ lost or the worker dropped it, the doc would silently serve FTS-only forever.+ This bounded pass re-checks the oldest-emitted docs and, when NONE of a doc's+ chunk vectors are present, clears the stamp so the pending pass re-emits.++ Conservative on purpose: we only re-null when zero vectors are present (a+ clear "never landed" signal). Partial loss is left for a follow-up so a+ chunk the worker legitimately skips can't drive an endless re-emit loop.+ """+ docs = await database_sync_to_async(logic.list_documents_for_embedding_reconciliation, thread_sensitive=False)()++ # One ClickHouse query per team, not per doc: HogQL auto-scopes to a single+ # team so we can't batch across teams, but within a team we union every doc's+ # chunk_ids into one IN-list and compare the returned present-set in Python.+ docs_by_team: dict[int, list[logic.EmittedDocument]] = defaultdict(list)+ for doc in docs:+ docs_by_team[doc.team_id].append(doc)++ re_nulled = 0+ for team_id, team_docs in docs_by_team.items():+ chunk_ids = [chunk_id for doc in team_docs for chunk_id in doc.chunk_ids]+ present = await database_sync_to_async(_present_chunk_ids_in_clickhouse, thread_sensitive=False)(+ team_id, chunk_ids+ )+ for doc in team_docs:+ # Conservative: only re-null when NONE of the doc's chunks landed.+ if any(str(chunk_id) in present for chunk_id in doc.chunk_ids):+ continue+ await database_sync_to_async(logic.clear_document_embeddings_emitted, thread_sensitive=False)(+ team_id=team_id, document_id=doc.document_id+ )+ re_nulled += 1+ return {"reconciled": len(docs), "re_nulled": re_nulled}++@activity.defnasync def list_due_refresh_sources_activity() -> list[tuple[int, str, str]]:"""Return (team_id, source_id, host) for URL sources whose refresh is due."""@@ -259,6 +390,21 @@ class BusinessKnowledgeRefreshCoordinatorWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=2),)+ # Reconcile first so any "emitted but never landed in ClickHouse" docs are+ # un-stamped, then the emit pass re-produces them alongside the newly-SAFE+ # docs classified just above — all in this one pass.+ reconciled = await workflow.execute_activity(+ reconcile_embeddings_activity,+ start_to_close_timeout=timedelta(minutes=10),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )++ embedded = await workflow.execute_activity(+ emit_pending_embeddings_activity,+ start_to_close_timeout=timedelta(minutes=10),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+return {"tombstoned_deleted": swept,"sources_due": len(due),@@ -267,6 +413,10 @@ class BusinessKnowledgeRefreshCoordinatorWorkflow(PostHogWorkflow):"sources_failed": failed,"documents_classified": classified.get("classified", 0),"documents_unsafe": classified.get("unsafe", 0),+ "embeddings_reconciled": reconciled.get("reconciled", 0),+ "embeddings_re_nulled": reconciled.get("re_nulled", 0),+ "documents_embedded": embedded.get("documents_embedded", 0),+ "chunks_emitted": embedded.get("chunks_emitted", 0),}@staticmethoddiff --git a/products/business_knowledge/backend/tests/test_embeddings.py b/products/business_knowledge/backend/tests/test_embeddings.pynew file mode 100644index 000000000000..654bf4653397--- /dev/null+++ b/products/business_knowledge/backend/tests/test_embeddings.py@@ -0,0 +1,256 @@+import datetime++from posthog.test.base import BaseTest+from unittest.mock import 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_EMBEDDING_DOCUMENT_TYPE,+ BK_EMBEDDING_MODEL,+ BK_EMBEDDING_PRODUCT,+)+from products.business_knowledge.backend.models import (+ KnowledgeDocument,+ KnowledgeSource,+ SafetyVerdict,+ SourceStatus,+ SourceType,+)+from products.business_knowledge.backend.temporal import coordinator+++class TestPendingEmbeddingSelection(BaseTest):+ def _safe_source(self, name: str, text: str) -> tuple[KnowledgeSource, KnowledgeDocument]:+ source = logic.create_text_source(team_id=self.team.id, created_by_id=self.user.id, name=name, text=text)+ with team_scope(self.team.id, canonical=True):+ KnowledgeDocument.objects.filter(source_id=source.id).update(safety_verdict=SafetyVerdict.SAFE)+ doc = KnowledgeDocument.objects.get(source_id=source.id)+ return source, doc++ def _set(self, doc: KnowledgeDocument, **fields: object) -> None:+ with team_scope(self.team.id, canonical=True):+ KnowledgeDocument.objects.filter(id=doc.id).update(**fields)++ def _set_source(self, source: KnowledgeSource, **fields: object) -> None:+ with team_scope(self.team.id, canonical=True):+ KnowledgeSource.objects.filter(id=source.id).update(**fields)++ def _disapprove_org(self) -> None:+ self.organization.is_ai_data_processing_approved = False+ self.organization.save()++ def test_lists_safe_unembedded_docs_with_chunks(self) -> None:+ _source, doc = self._safe_source("Refunds", "Our refund policy covers widgets and gadgets.")++ pending = logic.list_documents_pending_embedding()+ ids = {d.document_id for d in pending}+ assert doc.id in ids+ entry = next(d for d in pending if d.document_id == doc.id)+ assert entry.timestamp == doc.created_at+ assert len(entry.chunks) >= 1+ assert all(c.content for c in entry.chunks)++ @parameterized.expand(+ [+ # Only SAFE, approved, READY, live, not-yet-emitted docs are embedded.+ # Each case mutates exactly one of those preconditions and asserts the+ # doc drops out of the pending set.+ ("already_emitted", lambda t, s, d: t._set(d, embeddings_emitted_at=timezone.now())),+ ("unknown_verdict", lambda t, s, d: t._set(d, safety_verdict=SafetyVerdict.UNKNOWN)),+ ("unsafe_verdict", lambda t, s, d: t._set(d, safety_verdict=SafetyVerdict.UNSAFE)),+ ("tombstoned", lambda t, s, d: t._set(d, tombstoned_at=timezone.now())),+ ("source_not_ready", lambda t, s, d: t._set_source(s, status=SourceStatus.PROCESSING)),+ ("org_not_approved", lambda t, s, d: t._disapprove_org()),+ ]+ )+ def test_doc_excluded_from_pending(self, _name: str, mutate) -> None: # noqa: ANN001+ source, doc = self._safe_source("Refunds", "Our refund policy covers widgets and gadgets.")+ mutate(self, source, doc)+ assert doc.id not in {d.document_id for d in logic.list_documents_pending_embedding()}++ def test_respects_cap(self) -> None:+ for i in range(3):+ self._safe_source(f"src{i}", f"content number {i} about refunds")+ assert len(logic.list_documents_pending_embedding(limit=2)) == 2+++class TestMarkAndClearEmission(BaseTest):+ def _doc(self, verdict: str) -> KnowledgeDocument:+ source = logic.create_text_source(+ team_id=self.team.id, created_by_id=self.user.id, name="A", text="alpha content here"+ )+ with team_scope(self.team.id, canonical=True):+ KnowledgeDocument.objects.filter(source_id=source.id).update(safety_verdict=verdict)+ return KnowledgeDocument.objects.get(source_id=source.id)++ @parameterized.expand(+ [+ # The stamp guard is the second SAFE-only gate: even if a non-SAFE doc+ # somehow reaches mark (e.g. it flipped verdict mid-pass), it must not+ # be recorded as emitted.+ ("safe", SafetyVerdict.SAFE, True),+ ("unknown", SafetyVerdict.UNKNOWN, False),+ ("unsafe", SafetyVerdict.UNSAFE, False),+ ]+ )+ def test_mark_only_stamps_safe_docs(self, _name: str, verdict: str, should_stamp: bool) -> None:+ doc = self._doc(verdict)+ logic.mark_document_embeddings_emitted(team_id=self.team.id, document_id=doc.id)+ with team_scope(self.team.id, canonical=True):+ doc.refresh_from_db()+ assert (doc.embeddings_emitted_at is not None) is should_stamp++ def test_mark_is_idempotent(self) -> None:+ doc = self._doc(SafetyVerdict.SAFE)+ logic.mark_document_embeddings_emitted(team_id=self.team.id, document_id=doc.id)+ with team_scope(self.team.id, canonical=True):+ doc.refresh_from_db()+ first = doc.embeddings_emitted_at+ logic.mark_document_embeddings_emitted(team_id=self.team.id, document_id=doc.id)+ with team_scope(self.team.id, canonical=True):+ doc.refresh_from_db()+ assert doc.embeddings_emitted_at == first++ def test_clear_renulls(self) -> None:+ doc = self._doc(SafetyVerdict.SAFE)+ logic.mark_document_embeddings_emitted(team_id=self.team.id, document_id=doc.id)+ logic.clear_document_embeddings_emitted(team_id=self.team.id, document_id=doc.id)+ with team_scope(self.team.id, canonical=True):+ doc.refresh_from_db()+ assert doc.embeddings_emitted_at is None+++class TestContentChangeResetsEmission(BaseTest):+ def test_crawl_upsert_clears_emission_stamp(self) -> None:+ # A crawl refresh that replaces a doc's content in place (same id) must+ # clear the emission stamp so the new content re-embeds once re-classified.+ with team_scope(self.team.id, canonical=True):+ source = KnowledgeSource.objects.create(+ team=self.team,+ name="Docs",+ source_type=SourceType.URL,+ status=SourceStatus.READY,+ source_url="https://example.com",+ )+ doc = KnowledgeDocument.objects.create(+ team=self.team,+ source=source,+ stable_id="https://example.com",+ title="Old title",+ content="Original content about refunds.",+ url="https://example.com",+ content_hash="old-hash",+ safety_verdict=SafetyVerdict.SAFE,+ embeddings_emitted_at=timezone.now(),+ )++ logic._insert_document_and_chunks(+ source=source,+ team_id=self.team.id,+ title="New title",+ text="Completely new content about returns and exchanges.",+ url="https://example.com",+ etag="new-etag",+ content_hash="new-hash",+ existing_doc=doc,+ )+ doc.refresh_from_db()++ assert doc.safety_verdict == SafetyVerdict.UNKNOWN+ assert doc.embeddings_emitted_at is None+++class TestEmitOneDocument(BaseTest):+ # Tests the sync produce+stamp primitive directly. The async activity is a+ # thin gather/try-except wrapper over this; the threaded-DB visibility that+ # async activity tests need (committed transactions) isn't worth dragging in+ # for glue that just counts results.+ def _pending(self, name: str, text: str) -> tuple[KnowledgeDocument, logic.DocumentToEmbed]:+ source = logic.create_text_source(team_id=self.team.id, created_by_id=self.user.id, name=name, text=text)+ with team_scope(self.team.id, canonical=True):+ KnowledgeDocument.objects.filter(source_id=source.id).update(safety_verdict=SafetyVerdict.SAFE)+ doc = KnowledgeDocument.objects.get(source_id=source.id)+ entry = next(d for d in logic.list_documents_pending_embedding() if d.document_id == doc.id)+ return doc, entry++ def test_emits_each_chunk_and_stamps(self) -> None:+ doc, entry = self._pending("Refunds", "Our refund policy covers widgets and gadgets.")++ with patch.object(coordinator, "emit_embedding_request") as emit:+ written = coordinator._emit_one_document(entry)++ assert written == len(entry.chunks)+ assert emit.call_count == len(entry.chunks)+ emitted_doc_ids = {call.kwargs["document_id"] for call in emit.call_args_list}+ assert emitted_doc_ids == {str(c.chunk_id) for c in entry.chunks}+ kwargs = emit.call_args_list[0].kwargs+ assert kwargs["product"] == BK_EMBEDDING_PRODUCT+ assert kwargs["document_type"] == BK_EMBEDDING_DOCUMENT_TYPE+ assert kwargs["models"] == [BK_EMBEDDING_MODEL]+ assert kwargs["timestamp"] == doc.created_at # stable doc timestamp, not now()+ assert kwargs["metadata"]["document_id"] == str(doc.id)++ with team_scope(self.team.id, canonical=True):+ doc.refresh_from_db()+ assert doc.embeddings_emitted_at is not None++ def test_emit_failure_propagates_and_leaves_doc_unstamped(self) -> None:+ doc, entry = self._pending("Refunds", "Our refund policy covers widgets and gadgets.")++ with patch.object(coordinator, "emit_embedding_request", side_effect=RuntimeError("kafka down")):+ with self.assertRaises(RuntimeError):+ coordinator._emit_one_document(entry)++ with team_scope(self.team.id, canonical=True):+ doc.refresh_from_db()+ assert doc.embeddings_emitted_at is None+ # Still pending so the next pass retries the whole doc.+ assert doc.id in {d.document_id for d in logic.list_documents_pending_embedding()}+++class TestReconciliationSelection(BaseTest):+ def _emitted_doc(self, *, emitted_minutes_ago: int, verdict: str = SafetyVerdict.SAFE) -> KnowledgeDocument:+ source = logic.create_text_source(+ team_id=self.team.id, created_by_id=self.user.id, name="A", text="alpha content about refunds"+ )+ emitted_at = timezone.now() - datetime.timedelta(minutes=emitted_minutes_ago)+ with team_scope(self.team.id, canonical=True):+ KnowledgeDocument.objects.filter(source_id=source.id).update(+ safety_verdict=verdict, embeddings_emitted_at=emitted_at+ )+ return KnowledgeDocument.objects.get(source_id=source.id)++ def test_returns_old_emitted_safe_docs_with_chunk_ids(self) -> None:+ old = self._emitted_doc(emitted_minutes_ago=60 * 24)+ recent = self._emitted_doc(emitted_minutes_ago=1)++ result = logic.list_documents_for_embedding_reconciliation()+ ids = {d.document_id for d in result}+ assert old.id in ids+ assert recent.id not in ids # still within the grace window+ entry = next(d for d in result if d.document_id == old.id)+ assert len(entry.chunk_ids) >= 1++ @parameterized.expand(+ [+ ("unknown", SafetyVerdict.UNKNOWN),+ ("unsafe", SafetyVerdict.UNSAFE),+ ]+ )+ def test_excludes_non_safe_emitted(self, _name: str, verdict: str) -> None:+ # Reconciliation only re-checks docs that are still embeddable (SAFE);+ # a doc that left SAFE shouldn't be re-emitted.+ doc = self._emitted_doc(emitted_minutes_ago=60 * 24, verdict=verdict)+ assert doc.id not in {d.document_id for d in logic.list_documents_for_embedding_reconciliation()}++ def test_orders_oldest_emitted_first(self) -> None:+ older = self._emitted_doc(emitted_minutes_ago=60 * 48)+ newer = self._emitted_doc(emitted_minutes_ago=60 * 24)+ order = [d.document_id for d in logic.list_documents_for_embedding_reconciliation()]+ assert order.index(older.id) < order.index(newer.id)