: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: periodically re-emit aging embeddings before TTL (#62650)
Alex V65c489517c76
diff --git a/products/business_knowledge/backend/constants.py b/products/business_knowledge/backend/constants.pyindex aef2c22b0371..91f157419144 100644--- a/products/business_knowledge/backend/constants.py+++ b/products/business_knowledge/backend/constants.py@@ -112,6 +112,29 @@ PENDING_EMBEDDING_SCAN_CAP = 50# re-checking docs whose vectors are simply still in flight through Kafka.RECONCILE_EMBEDDING_SCAN_CAP = 50RECONCILE_EMBEDDING_GRACE = datetime.timedelta(hours=2)+# Periodic TTL refresh. The shared document_embeddings table TTLs rows at+# `timestamp + 3 MONTH`, computed from the user-supplied `timestamp` we pass at+# emit time (NOT inserted_at). A SAFE doc embedded once and never re-emitted+# silently loses its vectors after ~3 months and falls back to FTS-only forever+# — the first-emission `embeddings_emitted_at IS NULL` guard means it's never+# re-emitted on its own. This window picks up docs whose last emission is older+# than ~2 months, comfortably under the 3-month TTL, so the re-emit lands a+# fresh live row before the old one expires.+#+# Unlike first emission (which passes the stable document.created_at so re-emits+# of an unchanged chunk collapse onto one sort key), the refresh MUST pass a+# fresh timestamp=now() — the TTL is on `timestamp`, so re-emitting under the+# old created_at would not reset the clock at all. The fresh-timestamp row lands+# under today's partition; the old row ages out under its own TTL. This is+# correctness-safe: the read path always re-joins to Postgres and dedups+# candidates by chunk_id, so the transient extra row can never double-count or+# surface stale content.+EMBEDDING_TTL_REFRESH_WINDOW = datetime.timedelta(days=60)+# Per coordinator pass: how many aging SAFE docs to re-emit (oldest-emitted+# first). Same memory knob as the other embedding caps — each doc loads its+# chunk content to produce to Kafka. A large refresh wave drains over many+# hourly passes instead of blowing up a single run across all teams.+REEMIT_EMBEDDING_SCAN_CAP = 50# --- Hybrid retrieval tunables (PR2 read path) ---# cosineDistance threshold: vectors above this are discarded BEFORE re-joiningdiff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.pyindex 2007a1bf1685..93ed88a0e878 100644--- a/products/business_knowledge/backend/logic.py+++ b/products/business_knowledge/backend/logic.py@@ -46,6 +46,7 @@ from .constants import (CRAWL_HARD_MAX_DEPTH,DEFAULT_CRAWL_MAX_DEPTH,DEFAULT_MAX_PAGES,+ EMBEDDING_TTL_REFRESH_WINDOW,MAX_CHUNKS_PER_TEAM,MAX_SOURCES_PER_TEAM,MAX_TEXT_SIZE_BYTES,@@ -53,6 +54,7 @@ from .constants import (PENDING_EMBEDDING_SCAN_CAP,RECONCILE_EMBEDDING_GRACE,RECONCILE_EMBEDDING_SCAN_CAP,+ REEMIT_EMBEDDING_SCAN_CAP,)from .models import (REFRESH_INTERVAL_TIMEDELTAS,@@ -2002,9 +2004,12 @@ class DocumentToEmbed:team_id: intdocument_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)`.+ # The embedding row `timestamp`. The first-emission path passes the+ # document's stable `created_at` so a re-emit of the same chunk_id collapses+ # onto one ClickHouse sort key / partition instead of duplicating under a+ # later `toDate(timestamp)`. The TTL-refresh path instead passes `now()` so+ # the re-emit resets the 3-month TTL clock (the table TTLs on `timestamp`);+ # the extra row is correctness-safe via the read-path re-join.timestamp: datetime.datetimechunks: list[ChunkToEmbed]@@ -2130,6 +2135,45 @@ def list_documents_for_embedding_reconciliation(]+def list_documents_for_embedding_refresh(+ *,+ now: datetime.datetime | None = None,+ window: datetime.timedelta = EMBEDDING_TTL_REFRESH_WINDOW,+ limit: int = REEMIT_EMBEDDING_SCAN_CAP,+) -> list[DocumentToEmbed]:+ """+ Return already-emitted SAFE docs (oldest-emitted first) whose vectors are+ aging toward the 3-month ClickHouse TTL, so their chunks can be re-emitted+ before the rows expire and the doc silently drops to FTS-only.++ The returned ``DocumentToEmbed.timestamp`` is ``now`` (NOT the doc's+ ``created_at``): the shared table TTLs on the embedding row ``timestamp``,+ so the re-emit must carry a fresh timestamp to actually reset the clock —+ re-emitting under the old ``created_at`` would land an already-/soon-expired+ row and keep losing vectors. The extra row this creates is correctness-safe:+ the read path always re-joins to Postgres and dedups candidates by chunk_id.+ Cross-team — coordinator only.+ """+ now = now or timezone.now()+ cutoff = now - window+ 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]+ )+ chunks_by_doc = _chunks_to_embed_by_document([document_id for _team_id, document_id in rows])+ return [+ DocumentToEmbed(+ team_id=team_id,+ document_id=document_id,+ timestamp=now,+ chunks=chunks_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:"""@@ -2148,6 +2192,26 @@ def mark_document_embeddings_emitted(*, team_id: int, document_id: UUID) -> None).update(embeddings_emitted_at=timezone.now(), updated_at=timezone.now())+@with_team_scope(canonical=True)+def restamp_document_embeddings_emitted(*, team_id: int, document_id: UUID) -> None:+ """+ Bump ``embeddings_emitted_at`` to now after a TTL-refresh re-emit.++ Unlike ``mark_document_embeddings_emitted`` (gated on NULL, for first+ emission), this re-stamps an ALREADY-stamped doc so it drops out of the+ refresh window for another full cycle. Still gated on the doc being SAFE+ AND already stamped: a content change that flipped it to ``unknown``+ mid-pass NULLs the stamp, and that new (unembedded) content must go through+ the normal pending-emit path rather than being re-stamped here.+ """+ KnowledgeDocument.objects.filter(+ team_id=team_id,+ id=document_id,+ safety_verdict=SafetyVerdict.SAFE,+ embeddings_emitted_at__isnull=False,+ ).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:"""diff --git a/products/business_knowledge/backend/temporal/__init__.py b/products/business_knowledge/backend/temporal/__init__.pyindex 2ffadf887d8e..c890c1bbc906 100644--- a/products/business_knowledge/backend/temporal/__init__.py+++ b/products/business_knowledge/backend/temporal/__init__.py@@ -8,6 +8,7 @@ from .coordinator import (ingest_knowledge_source_activity,list_due_refresh_sources_activity,reconcile_embeddings_activity,+ refresh_aging_embeddings_activity,refresh_knowledge_source_activity,sweep_tombstoned_documents_activity,)@@ -23,6 +24,7 @@ ACTIVITIES = [classify_pending_documents_activity,reconcile_embeddings_activity,emit_pending_embeddings_activity,+ refresh_aging_embeddings_activity,list_due_refresh_sources_activity,refresh_knowledge_source_activity,execute_refresh_knowledge_source_activity,@@ -41,6 +43,7 @@ __all__ = ["ingest_knowledge_source_activity","list_due_refresh_sources_activity","reconcile_embeddings_activity",+ "refresh_aging_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 085b474a16cb..f1e53594007b 100644--- a/products/business_knowledge/backend/temporal/coordinator.py+++ b/products/business_knowledge/backend/temporal/coordinator.py@@ -88,16 +88,10 @@ 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.- """+def _produce_document_chunks(doc: logic.DocumentToEmbed) -> None:+ """Produce every chunk of one doc to the embedding pipeline (sync Kafka+ produce). ``doc.timestamp`` is the embedding row timestamp — the stable+ ``created_at`` for first emission, or ``now()`` for a TTL refresh."""for chunk in doc.chunks:emit_embedding_request(content=chunk.content,@@ -107,16 +101,45 @@ def _emit_one_document(doc: logic.DocumentToEmbed) -> int: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)},)+++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.+ """+ _produce_document_chunks(doc)logic.mark_document_embeddings_emitted(team_id=doc.team_id, document_id=doc.document_id)return len(doc.chunks)+def _reemit_one_document(doc: logic.DocumentToEmbed) -> int:+ """+ Re-produce every chunk of an aging SAFE doc with a FRESH timestamp, then+ re-stamp ``embeddings_emitted_at``. Used by the TTL-refresh pass to keep+ vectors alive past the 3-month ClickHouse TTL.++ ``doc.timestamp`` is ``now()`` here (set by+ ``logic.list_documents_for_embedding_refresh``) so the re-emit lands a fresh+ row that resets the TTL clock; the prior row ages out under its own TTL. As+ with first emission, a produce error propagates before the re-stamp, so the+ doc keeps its old stamp and is retried on a later pass.+ """+ _produce_document_chunks(doc)+ logic.restamp_document_embeddings_emitted(team_id=doc.team_id, document_id=doc.document_id)+ return len(doc.chunks)++@activity.defnasync def emit_pending_embeddings_activity() -> dict[str, Any]:"""@@ -144,6 +167,38 @@ async def emit_pending_embeddings_activity() -> dict[str, Any]:return {"documents_embedded": documents_embedded, "chunks_emitted": chunks_emitted}+async def refresh_aging_embeddings_activity() -> dict[str, Any]:+ """+ Re-emit chunk embeddings for SAFE docs whose vectors are aging toward the+ 3-month ClickHouse TTL, so long-lived knowledge never silently loses its+ vectors and falls back to FTS-only.++ Bounded by ``REEMIT_EMBEDDING_SCAN_CAP`` (oldest-emitted docs first); a large+ refresh wave drains over many hourly passes. The re-emit uses a fresh+ timestamp=now() (the TTL is on the embedding row timestamp, so the stable+ created_at would not reset it) and re-stamps ``embeddings_emitted_at`` so the+ doc drops out of the refresh window for another cycle. Per-doc failures are+ logged and skipped without re-stamping, so they retry on a later pass.+ """+ docs = await database_sync_to_async(logic.list_documents_for_embedding_refresh, thread_sensitive=False)()+ documents_refreshed = 0+ chunks_reemitted = 0+ for doc in docs:+ try:+ written = await database_sync_to_async(_reemit_one_document, thread_sensitive=False)(doc)+ except Exception:+ logger.exception(+ "business_knowledge.embedding.refresh_failed",+ team_id=doc.team_id,+ document_id=str(doc.document_id),+ )+ continue+ documents_refreshed += 1+ chunks_reemitted += written+ return {"documents_refreshed": documents_refreshed, "chunks_reemitted": chunks_reemitted}++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 theshared ClickHouse embeddings table for this team + model. HogQL auto-scopes@@ -405,6 +460,15 @@ class BusinessKnowledgeRefreshCoordinatorWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=2),)+ # Keep long-lived vectors alive past the 3-month CH TTL by re-emitting+ # aging SAFE docs. Runs last (lowest urgency) and re-stamps with now()+ # so a refreshed doc won't be touched again for a full window.+ ttl_refreshed = await workflow.execute_activity(+ refresh_aging_embeddings_activity,+ start_to_close_timeout=timedelta(minutes=10),+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+return {"tombstoned_deleted": swept,"sources_due": len(due),@@ -417,6 +481,8 @@ class BusinessKnowledgeRefreshCoordinatorWorkflow(PostHogWorkflow):"embeddings_re_nulled": reconciled.get("re_nulled", 0),"documents_embedded": embedded.get("documents_embedded", 0),"chunks_emitted": embedded.get("chunks_emitted", 0),+ "embeddings_ttl_refreshed": ttl_refreshed.get("documents_refreshed", 0),+ "chunks_reemitted": ttl_refreshed.get("chunks_reemitted", 0),}@staticmethoddiff --git a/products/business_knowledge/backend/tests/test_embeddings.py b/products/business_knowledge/backend/tests/test_embeddings.pyindex 654bf4653397..696625130a65 100644--- a/products/business_knowledge/backend/tests/test_embeddings.py+++ b/products/business_knowledge/backend/tests/test_embeddings.py@@ -14,6 +14,7 @@ from products.business_knowledge.backend.constants import (BK_EMBEDDING_DOCUMENT_TYPE,BK_EMBEDDING_MODEL,BK_EMBEDDING_PRODUCT,+ EMBEDDING_TTL_REFRESH_WINDOW,)from products.business_knowledge.backend.models import (KnowledgeDocument,@@ -254,3 +255,151 @@ class TestReconciliationSelection(BaseTest):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)+++class TestTtlRefreshSelection(BaseTest):+ def _emitted_doc(self, *, emitted_days_ago: float, 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(days=emitted_days_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_selects_only_docs_past_the_window(self) -> None:+ window_days = EMBEDDING_TTL_REFRESH_WINDOW.days+ aging = self._emitted_doc(emitted_days_ago=window_days + 5)+ fresh = self._emitted_doc(emitted_days_ago=window_days - 5)++ ids = {d.document_id for d in logic.list_documents_for_embedding_refresh()}+ assert aging.id in ids+ assert fresh.id not in ids++ def test_never_emitted_doc_is_not_refreshed(self) -> None:+ # embeddings_emitted_at IS NULL belongs to the pending-emit path, not the+ # refresh path — refresh only re-emits docs that were already stamped.+ source = logic.create_text_source(+ team_id=self.team.id, created_by_id=self.user.id, name="A", text="alpha content about refunds"+ )+ 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)+ assert doc.id not in {d.document_id for d in logic.list_documents_for_embedding_refresh()}++ @parameterized.expand(+ [+ ("unknown", SafetyVerdict.UNKNOWN),+ ("unsafe", SafetyVerdict.UNSAFE),+ ]+ )+ def test_excludes_non_safe(self, _name: str, verdict: str) -> None:+ doc = self._emitted_doc(emitted_days_ago=EMBEDDING_TTL_REFRESH_WINDOW.days + 5, verdict=verdict)+ assert doc.id not in {d.document_id for d in logic.list_documents_for_embedding_refresh()}++ def test_uses_now_not_created_at_as_timestamp(self) -> None:+ # The TTL is on the embedding row timestamp, so the refresh must pass a+ # FRESH timestamp (now) — created_at would not reset the clock.+ doc = self._emitted_doc(emitted_days_ago=EMBEDDING_TTL_REFRESH_WINDOW.days + 5)+ entry = next(d for d in logic.list_documents_for_embedding_refresh() if d.document_id == doc.id)+ assert entry.timestamp != doc.created_at+ assert entry.timestamp > doc.created_at+ assert len(entry.chunks) >= 1++ def test_respects_cap(self) -> None:+ for _ in range(3):+ self._emitted_doc(emitted_days_ago=EMBEDDING_TTL_REFRESH_WINDOW.days + 5)+ assert len(logic.list_documents_for_embedding_refresh(limit=2)) == 2++ def test_orders_oldest_emitted_first(self) -> None:+ older = self._emitted_doc(emitted_days_ago=EMBEDDING_TTL_REFRESH_WINDOW.days + 30)+ newer = self._emitted_doc(emitted_days_ago=EMBEDDING_TTL_REFRESH_WINDOW.days + 5)+ order = [d.document_id for d in logic.list_documents_for_embedding_refresh()]+ assert order.index(older.id) < order.index(newer.id)+++class TestRestampAndReemit(BaseTest):+ def _safe_emitted_doc(self) -> KnowledgeDocument:+ source = logic.create_text_source(+ team_id=self.team.id, created_by_id=self.user.id, name="A", text="alpha content about refunds"+ )+ old_stamp = timezone.now() - EMBEDDING_TTL_REFRESH_WINDOW - datetime.timedelta(days=5)+ with team_scope(self.team.id, canonical=True):+ KnowledgeDocument.objects.filter(source_id=source.id).update(+ safety_verdict=SafetyVerdict.SAFE, embeddings_emitted_at=old_stamp+ )+ return KnowledgeDocument.objects.get(source_id=source.id)++ def test_restamp_moves_stamp_forward(self) -> None:+ doc = self._safe_emitted_doc()+ with team_scope(self.team.id, canonical=True):+ before = KnowledgeDocument.objects.get(id=doc.id).embeddings_emitted_at+ logic.restamp_document_embeddings_emitted(team_id=self.team.id, document_id=doc.id)+ with team_scope(self.team.id, canonical=True):+ after = KnowledgeDocument.objects.get(id=doc.id).embeddings_emitted_at+ assert after is not None and before is not None+ assert after > before++ @parameterized.expand(+ [+ ("unknown", SafetyVerdict.UNKNOWN),+ ("unsafe", SafetyVerdict.UNSAFE),+ ]+ )+ def test_restamp_skips_non_safe(self, _name: str, verdict: str) -> None:+ doc = self._safe_emitted_doc()+ with team_scope(self.team.id, canonical=True):+ before = KnowledgeDocument.objects.get(id=doc.id).embeddings_emitted_at+ KnowledgeDocument.objects.filter(id=doc.id).update(safety_verdict=verdict)+ logic.restamp_document_embeddings_emitted(team_id=self.team.id, document_id=doc.id)+ with team_scope(self.team.id, canonical=True):+ after = KnowledgeDocument.objects.get(id=doc.id).embeddings_emitted_at+ assert after == before++ def test_restamp_skips_renulled_doc(self) -> None:+ # A content change mid-pass NULLs the stamp; that new content must flow+ # through the pending-emit path, not be re-stamped by the refresh.+ doc = self._safe_emitted_doc()+ with team_scope(self.team.id, canonical=True):+ KnowledgeDocument.objects.filter(id=doc.id).update(embeddings_emitted_at=None)+ logic.restamp_document_embeddings_emitted(team_id=self.team.id, document_id=doc.id)+ with team_scope(self.team.id, canonical=True):+ assert KnowledgeDocument.objects.get(id=doc.id).embeddings_emitted_at is None++ def test_reemit_produces_chunks_with_fresh_timestamp_and_restamps(self) -> None:+ doc = self._safe_emitted_doc()+ entry = next(d for d in logic.list_documents_for_embedding_refresh() if d.document_id == doc.id)+ with team_scope(self.team.id, canonical=True):+ before = KnowledgeDocument.objects.get(id=doc.id).embeddings_emitted_at++ with patch.object(coordinator, "emit_embedding_request") as emit:+ written = coordinator._reemit_one_document(entry)++ assert written == len(entry.chunks)+ assert emit.call_count == len(entry.chunks)+ kwargs = emit.call_args_list[0].kwargs+ assert kwargs["timestamp"] == entry.timestamp # fresh now(), not created_at+ assert kwargs["timestamp"] != doc.created_at+ assert kwargs["metadata"]["document_id"] == str(doc.id)++ with team_scope(self.team.id, canonical=True):+ after = KnowledgeDocument.objects.get(id=doc.id).embeddings_emitted_at+ assert after is not None and before is not None+ assert after > before++ def test_reemit_failure_leaves_old_stamp(self) -> None:+ doc = self._safe_emitted_doc()+ entry = next(d for d in logic.list_documents_for_embedding_refresh() if d.document_id == doc.id)+ with team_scope(self.team.id, canonical=True):+ before = KnowledgeDocument.objects.get(id=doc.id).embeddings_emitted_at++ with patch.object(coordinator, "emit_embedding_request", side_effect=RuntimeError("kafka down")):+ with self.assertRaises(RuntimeError):+ coordinator._reemit_one_document(entry)++ with team_scope(self.team.id, canonical=True):+ after = KnowledgeDocument.objects.get(id=doc.id).embeddings_emitted_at+ # Stamp unchanged (no re-stamp), so the doc is retried on a later pass.+ assert after == before