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.

fix(bk): use fresh embedding timestamp for old docs on first emit (#63173)

Alex Va8eb45e1724d
diff --git a/products/business_knowledge/backend/constants.py b/products/business_knowledge/backend/constants.py
index 91f157419144..5deffafd7573 100644
--- a/products/business_knowledge/backend/constants.py
+++ b/products/business_knowledge/backend/constants.py
@@ -121,15 +121,26 @@ RECONCILE_EMBEDDING_GRACE = datetime.timedelta(hours=2)
# 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.
+# Both the TTL-refresh path and the first-emission path for OLD docs (created_at
+# older than EMBEDDING_STABLE_TS_MAX_AGE) use timestamp=now() — the TTL is on
+# `timestamp`, so emitting under an old created_at would land an expired or
+# soon-to-expire row. Young docs still use the stable created_at for sort-key
+# dedup. The fresh-timestamp row lands under today's partition; any prior 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 a transient extra
+# row can never double-count or surface stale content.
EMBEDDING_TTL_REFRESH_WINDOW = datetime.timedelta(days=60)
+# The shared embeddings table TTLs rows at `timestamp + 3 MONTH` (see
+# error_tracking's indexed_embedding.py — the table definition is the source of
+# truth; this mirrors it for arithmetic).
+BK_EMBEDDING_TABLE_TTL = datetime.timedelta(days=90)
+# Max document age at first emit for which the stable created_at timestamp is
+# safe. The invariant: the row must survive until the refresh cron re-emits at
+# emitted_at + EMBEDDING_TTL_REFRESH_WINDOW, i.e. created_at + TTL must exceed
+# that — so created_at can be at most TTL - REFRESH_WINDOW old. Older docs
+# (incl. re-nulled in-place crawl docs, late-SAFE classifications, and backfill)
+# must emit with now() or they'd lose vectors before the refresh cron fires.
+EMBEDDING_STABLE_TS_MAX_AGE = BK_EMBEDDING_TABLE_TTL - EMBEDDING_TTL_REFRESH_WINDOW
# 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
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index 05e798359933..3ed8829cec6f 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -48,6 +48,7 @@ from .constants import (
CRAWL_HARD_MAX_DEPTH,
DEFAULT_CRAWL_MAX_DEPTH,
DEFAULT_MAX_PAGES,
+ EMBEDDING_STABLE_TS_MAX_AGE,
EMBEDDING_TTL_REFRESH_WINDOW,
MAX_CHUNKS_PER_TEAM,
MAX_SOURCES_PER_TEAM,
@@ -2028,12 +2029,13 @@ class DocumentToEmbed:
team_id: int
document_id: UUID
- # 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.
+ # The embedding row `timestamp`. Young docs use the 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)`.
+ # Old docs (created_at older than EMBEDDING_STABLE_TS_MAX_AGE) and the
+ # TTL-refresh path use `now()` so the row survives until the refresh cron
+ # fires, instead of expiring under `TTL timestamp + 3 MONTH` first. The
+ # extra row is correctness-safe via the read-path re-join.
timestamp: datetime.datetime
chunks: list[ChunkToEmbed]
@@ -2106,7 +2108,18 @@ def list_documents_pending_embedding(*, limit: int = PENDING_EMBEDDING_SCAN_CAP)
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.
- """
+
+ Timestamp strategy: young docs use the stable ``created_at`` so a re-emit
+ collapses onto one ClickHouse sort key. Old docs (``created_at`` older than
+ ``EMBEDDING_STABLE_TS_MAX_AGE``) use ``now()``: a stable timestamp is only
+ safe if the row survives until the TTL-refresh cron re-emits the doc at
+ ``emitted_at + EMBEDDING_TTL_REFRESH_WINDOW`` — beyond the max age the row
+ would expire first (in the worst case it lands already expired,
+ reconciliation re-nulls it, and the next pass re-emits with ``created_at``
+ again: a token-burning loop while the doc silently serves FTS-only forever).
+ """
+ now = timezone.now()
+ ttl_cutoff = now - EMBEDDING_STABLE_TS_MAX_AGE
rows = list(
_embeddable_documents_qs()
.filter(embeddings_emitted_at__isnull=True)
@@ -2117,7 +2130,7 @@ def list_documents_pending_embedding(*, limit: int = PENDING_EMBEDDING_SCAN_CAP)
DocumentToEmbed(
team_id=team_id,
document_id=document_id,
- timestamp=created_at,
+ timestamp=now if created_at < ttl_cutoff else created_at,
chunks=chunks_by_doc.get(document_id, []),
)
for team_id, document_id, created_at in rows
diff --git a/products/business_knowledge/backend/temporal/coordinator.py b/products/business_knowledge/backend/temporal/coordinator.py
index f1e53594007b..ed950c0e3f38 100644
--- a/products/business_knowledge/backend/temporal/coordinator.py
+++ b/products/business_knowledge/backend/temporal/coordinator.py
@@ -91,7 +91,9 @@ async def classify_pending_documents_activity() -> dict[str, Any]:
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."""
+ ``created_at`` for young first emissions, ``now()`` for old first emissions
+ (docs whose ``created_at`` is past the TTL refresh window), or ``now()``
+ for TTL refreshes."""
for chunk in doc.chunks:
emit_embedding_request(
content=chunk.content,
@@ -116,7 +118,7 @@ def _emit_one_document(doc: logic.DocumentToEmbed) -> int:
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.
+ (chunk_id, timestamp) via ReplacingMergeTree.
"""
_produce_document_chunks(doc)
logic.mark_document_embeddings_emitted(team_id=doc.team_id, document_id=doc.document_id)
diff --git a/products/business_knowledge/backend/tests/test_embeddings.py b/products/business_knowledge/backend/tests/test_embeddings.py
index 696625130a65..79096f77c252 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_STABLE_TS_MAX_AGE,
EMBEDDING_TTL_REFRESH_WINDOW,
)
from products.business_knowledge.backend.models import (
@@ -53,10 +54,33 @@ class TestPendingEmbeddingSelection(BaseTest):
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)
+ # Young doc: uses the stable created_at timestamp for sort-key dedup.
assert entry.timestamp == doc.created_at
assert len(entry.chunks) >= 1
assert all(c.content for c in entry.chunks)
+ def test_old_doc_uses_fresh_timestamp(self) -> None:
+ _source, doc = self._safe_source("Refunds", "Our refund policy covers widgets and gadgets.")
+ # Past the stable-timestamp max age (TTL - refresh window): the row
+ # would expire before the refresh cron re-emits, so now() must be used.
+ old_created = timezone.now() - EMBEDDING_STABLE_TS_MAX_AGE - datetime.timedelta(days=10)
+ self._set(doc, created_at=old_created)
+
+ before = timezone.now()
+ pending = logic.list_documents_pending_embedding()
+ entry = next(d for d in pending if d.document_id == doc.id)
+ assert entry.timestamp >= before
+
+ def test_doc_within_max_age_keeps_created_at(self) -> None:
+ _source, doc = self._safe_source("Refunds", "Our refund policy covers widgets and gadgets.")
+ # Just inside the max age: stable created_at is still safe (the row
+ # outlives the refresh cron's next pass) and keeps sort-key dedup.
+ recent_created = timezone.now() - EMBEDDING_STABLE_TS_MAX_AGE + datetime.timedelta(days=1)
+ self._set(doc, created_at=recent_created)
+
+ entry = next(d for d in logic.list_documents_pending_embedding() if d.document_id == doc.id)
+ assert entry.timestamp == recent_created
+
@parameterized.expand(
[
# Only SAFE, approved, READY, live, not-yet-emitted docs are embedded.
@@ -201,6 +225,20 @@ class TestEmitOneDocument(BaseTest):
doc.refresh_from_db()
assert doc.embeddings_emitted_at is not None
+ def test_emits_old_doc_with_fresh_timestamp(self) -> None:
+ doc, entry = self._pending("Refunds", "Our refund policy covers widgets and gadgets.")
+ old_created = timezone.now() - EMBEDDING_STABLE_TS_MAX_AGE - datetime.timedelta(days=10)
+ with team_scope(self.team.id, canonical=True):
+ KnowledgeDocument.objects.filter(id=doc.id).update(created_at=old_created, embeddings_emitted_at=None)
+ before = timezone.now()
+ entry = next(d for d in logic.list_documents_pending_embedding() if d.document_id == doc.id)
+
+ with patch.object(coordinator, "emit_embedding_request") as emit:
+ coordinator._emit_one_document(entry)
+
+ kwargs = emit.call_args_list[0].kwargs
+ assert kwargs["timestamp"] >= before
+
def test_emit_failure_propagates_and_leaves_doc_unstamped(self) -> None:
doc, entry = self._pending("Refunds", "Our refund policy covers widgets and gadgets.")