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(business-knowledge): drain indexing in chunks of 50 (#114405)

Alex Ve213b529ebed
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index 18fd29d093f6..8ea71b7dc325 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -2914,6 +2914,7 @@ def list_due_refresh_sources(
def list_documents_pending_classification(
*,
limit: int = PENDING_CLASSIFICATION_SCAN_CAP,
+ exclude_ids: list[UUID] | None = None,
) -> list[PendingDocument]:
"""
Return documents whose ``safety_verdict`` is still ``unknown``.
@@ -2936,15 +2937,18 @@ def list_documents_pending_classification(
# into memory per doc at CLASSIFY_MAX_TOTAL_CHARS + 1 — the classifier
# fails closed on anything longer than the cap, and the +1 lets it detect
# that the content was truncated here without a second Length() round-trip.
+ pending = KnowledgeDocument.objects.unscoped().filter(
+ safety_verdict=SafetyVerdict.UNKNOWN,
+ tombstoned_at__isnull=True,
+ classification_attempts__lt=CLASSIFY_MAX_ATTEMPTS,
+ team__organization__is_ai_data_processing_approved=True,
+ )
+ # Empty NOT IN is invalid SQL. Skip the clause when this run has tried nothing yet.
+ if exclude_ids:
+ pending = pending.exclude(id__in=exclude_ids)
rows = (
- KnowledgeDocument.objects.unscoped()
- .filter(
- safety_verdict=SafetyVerdict.UNKNOWN,
- tombstoned_at__isnull=True,
- classification_attempts__lt=CLASSIFY_MAX_ATTEMPTS,
- team__organization__is_ai_data_processing_approved=True,
- )
- .annotate(content_capped=Substr("content", 1, CLASSIFY_MAX_TOTAL_CHARS + 1))
+ pending.annotate(content_capped=Substr("content", 1, CLASSIFY_MAX_TOTAL_CHARS + 1))
+ .order_by("classification_attempts", "id")
.values_list("team_id", "id", "source_id", "source__source_type", "content_capped", "content_hash")[:limit]
)
return [
@@ -3134,6 +3138,9 @@ def list_documents_pending_embedding(*, limit: int = PENDING_EMBEDDING_SCAN_CAP)
rows = list(
_embeddable_documents_qs()
.filter(embeddings_emitted_at__isnull=True)
+ # Stable id order so a doc stamped by this chunk is not selected again,
+ # and the next chunk continues past it.
+ .order_by("id")
.values_list("team_id", "id", "source_id", "source__source_type", "created_at")[:limit]
)
chunks_by_doc = _chunks_to_embed_by_document([document_id for _team_id, document_id, *_rest in rows])
diff --git a/products/business_knowledge/backend/temporal/__init__.py b/products/business_knowledge/backend/temporal/__init__.py
index d09fc76f45fb..f6df24435cb8 100644
--- a/products/business_knowledge/backend/temporal/__init__.py
+++ b/products/business_knowledge/backend/temporal/__init__.py
@@ -1,6 +1,7 @@
from .coordinator import (
BusinessKnowledgeIngestSourceWorkflow,
BusinessKnowledgeRefreshCoordinatorWorkflow,
+ BusinessKnowledgeRefreshCoordinatorWorkflowV2,
BusinessKnowledgeRefreshSourceWorkflow,
classify_pending_documents_activity,
emit_pending_embeddings_activity,
@@ -19,6 +20,7 @@ from .learning.workflow import BusinessKnowledgeLearningWorkflow
WORKFLOWS = [
BusinessKnowledgeRefreshCoordinatorWorkflow,
+ BusinessKnowledgeRefreshCoordinatorWorkflowV2,
BusinessKnowledgeIngestSourceWorkflow,
BusinessKnowledgeRefreshSourceWorkflow,
BusinessKnowledgeLearningCoordinatorWorkflow,
@@ -46,6 +48,7 @@ __all__ = [
"BusinessKnowledgeLearningCoordinatorWorkflow",
"BusinessKnowledgeLearningWorkflow",
"BusinessKnowledgeRefreshCoordinatorWorkflow",
+ "BusinessKnowledgeRefreshCoordinatorWorkflowV2",
"BusinessKnowledgeRefreshSourceWorkflow",
"classify_pending_documents_activity",
"collect_learning_evidence_activity",
diff --git a/products/business_knowledge/backend/temporal/coordinator.py b/products/business_knowledge/backend/temporal/coordinator.py
index 7dfa86afc9a4..bb6f3cdbfdb6 100644
--- a/products/business_knowledge/backend/temporal/coordinator.py
+++ b/products/business_knowledge/backend/temporal/coordinator.py
@@ -6,7 +6,8 @@ One global hourly Temporal schedule drives this single coordinator workflow
1. sweeps tombstoned documents past their grace period,
2. refreshes every URL source whose auto-refresh interval is due,
- 3. classifies any documents still awaiting a safety verdict.
+ 3. classifies documents still awaiting a safety verdict, then emits embeddings,
+ repeating in memory-sized chunks until each queue is empty.
Refresh runs *before* classification so that documents whose content changed
during the refresh (reset to ``unknown``) get classified in the same pass —
@@ -22,8 +23,9 @@ import json
import asyncio
import dataclasses
from collections import defaultdict
+from collections.abc import Awaitable, Callable
from datetime import timedelta
-from typing import Any
+from typing import Any, TypeVar
from uuid import UUID
import structlog
@@ -35,13 +37,21 @@ from posthog.hogql.query import execute_hogql_query
from posthog.api.embedding_worker import emit_embedding_request
from posthog.clickhouse.client.connection import ClickHouseUser, Workload
+from posthog.dataclasses import frozen
from posthog.models.team import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater
from .. import llm_telemetry, logic, safety
-from ..constants import BK_EMBEDDING_DOCUMENT_TYPE, BK_EMBEDDING_MODEL, BK_EMBEDDING_PRODUCT, BK_EMBEDDING_RENDERING
+from ..constants import (
+ BK_EMBEDDING_DOCUMENT_TYPE,
+ BK_EMBEDDING_MODEL,
+ BK_EMBEDDING_PRODUCT,
+ BK_EMBEDDING_RENDERING,
+ MAX_URLS_PER_SOURCE,
+ PENDING_EMBEDDING_SCAN_CAP,
+)
from ..models import SafetyVerdict
logger = structlog.get_logger(__name__)
@@ -50,6 +60,15 @@ logger = structlog.get_logger(__name__)
# Bounded so a large backlog can't flood the shared worker queue.
MAX_CONCURRENT_REFRESHES = 25
+_CLASSIFY_CHUNK_SIZE = logic.PENDING_CLASSIFICATION_SCAN_CAP
+_EMBED_CHUNK_SIZE = PENDING_EMBEDDING_SCAN_CAP
+_CLASSIFY_DRAIN_MAX_CHUNKS = max(1, MAX_URLS_PER_SOURCE // _CLASSIFY_CHUNK_SIZE)
+_EMBED_DRAIN_MAX_CHUNKS = max(1, MAX_URLS_PER_SOURCE // _EMBED_CHUNK_SIZE)
+
+# A new name, because a mismatched replay fails the workflow task and this
+# schedule's stable id plus SKIP overlap then blocks later hours.
+REFRESH_COORDINATOR_WORKFLOW_V2 = "business-knowledge-refresh-coordinator-v2"
+
@dataclasses.dataclass(frozen=True)
class RefreshSourceInputs:
@@ -70,11 +89,21 @@ async def sweep_tombstoned_documents_activity() -> int:
@activity.defn
-async def classify_pending_documents_activity() -> dict[str, Any]:
- """Classify documents whose safety verdict is still unknown."""
- docs = await database_sync_to_async(logic.list_documents_pending_classification, thread_sensitive=False)()
+async def classify_pending_documents_activity(exclude_ids: list[str] | None = None) -> dict[str, Any]:
+ """Classify documents whose safety verdict is still unknown.
+
+ ``exclude_ids`` are documents this coordinator run already tried. One run
+ must not spend the hourly retry budget on the same page.
+ """
+
+ def _list() -> list[logic.PendingDocument]:
+ parsed = [UUID(value) for value in exclude_ids] if exclude_ids else None
+ return logic.list_documents_pending_classification(exclude_ids=parsed)
+
+ docs = await database_sync_to_async(_list, thread_sensitive=False)()
+ tried_ids = [str(doc.document_id) for doc in docs]
if not docs:
- return {"classified": 0, "unsafe": 0}
+ return {"classified": 0, "unsafe": 0, "scanned": 0, "tried_ids": tried_ids}
async with Heartbeater():
results = await safety.classify_documents(docs)
for result in results:
@@ -86,7 +115,7 @@ async def classify_pending_documents_activity() -> dict[str, Any]:
content_hash=result.content_hash,
)
unsafe = sum(1 for r in results if r.verdict == SafetyVerdict.UNSAFE)
- return {"classified": len(results), "unsafe": unsafe}
+ return {"classified": len(results), "unsafe": unsafe, "scanned": len(docs), "tried_ids": tried_ids}
def _produce_document_chunks(doc: logic.DocumentToEmbed) -> None:
@@ -168,9 +197,10 @@ 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.
+ One chunk, bounded by ``PENDING_EMBEDDING_SCAN_CAP``. The coordinator calls
+ this again while the chunk comes back full and at least one doc was stamped.
+ Per-doc failures are logged and skipped without stamping, so they stay
+ queued. A chunk that stamps nothing is not retried in this run.
"""
docs = await database_sync_to_async(logic.list_documents_pending_embedding, thread_sensitive=False)()
documents_embedded = 0
@@ -187,7 +217,11 @@ async def emit_pending_embeddings_activity() -> dict[str, Any]:
continue
documents_embedded += 1
chunks_emitted += written
- return {"documents_embedded": documents_embedded, "chunks_emitted": chunks_emitted}
+ return {
+ "documents_embedded": documents_embedded,
+ "chunks_emitted": chunks_emitted,
+ "scanned": len(docs),
+ }
@activity.defn
@@ -460,49 +494,157 @@ class BusinessKnowledgeRefreshSourceWorkflow(PostHogWorkflow):
return RefreshSourceInputs(**loaded)
[email protected](name="business-knowledge-refresh-coordinator")
-class BusinessKnowledgeRefreshCoordinatorWorkflow(PostHogWorkflow):
- @workflow.run
- async def run(self) -> dict[str, Any]:
- swept = await workflow.execute_activity(
- sweep_tombstoned_documents_activity,
- start_to_close_timeout=timedelta(minutes=5),
- retry_policy=RetryPolicy(maximum_attempts=3),
- )
+_ChunkT = TypeVar("_ChunkT")
+
+
+def _embed_chunk_has_more(batch: dict[str, int], *, chunk_size: int) -> bool:
+ scanned = batch["scanned"]
+ return scanned >= chunk_size and batch["documents_embedded"] > 0
+
+
+@frozen
+class _IndexDrainTotals:
+ classified: int
+ unsafe: int
+ documents_embedded: int
+ chunks_emitted: int
- # Refresh *before* classify: refreshed docs whose content changed are
- # reset to `unknown`, so running classification second picks them up in
- # the same pass instead of leaving them searchable until the next run.
- due: list[tuple[int, str, str]] = await workflow.execute_activity(
- list_due_refresh_sources_activity,
- start_to_close_timeout=timedelta(minutes=2),
- retry_policy=RetryPolicy(maximum_attempts=3),
+
+async def _take_index_chunk(
+ activity_fn: Callable[..., Awaitable[_ChunkT]],
+ *,
+ start_to_close: timedelta,
+ retry: RetryPolicy,
+ heartbeat: timedelta | None = None,
+ arg: list[str] | None = None,
+) -> _ChunkT:
+ if arg is None:
+ return await workflow.execute_activity(
+ activity_fn,
+ start_to_close_timeout=start_to_close,
+ heartbeat_timeout=heartbeat,
+ retry_policy=retry,
)
+ return await workflow.execute_activity(
+ activity_fn,
+ arg,
+ start_to_close_timeout=start_to_close,
+ heartbeat_timeout=heartbeat,
+ retry_policy=retry,
+ )
- refreshed = skipped = failed = 0
- start_to_close, heartbeat = _crawl_activity_timeouts()
- for batch in _host_serialized_batches(due, MAX_CONCURRENT_REFRESHES):
- results = await asyncio.gather(
- *(
- workflow.execute_activity(
- refresh_knowledge_source_activity,
- inputs,
- start_to_close_timeout=start_to_close,
- heartbeat_timeout=heartbeat,
- retry_policy=RetryPolicy(maximum_attempts=2),
- )
- for inputs in batch
- ),
- return_exceptions=True,
+
+async def _drain_index_queues() -> _IndexDrainTotals:
+ # Alternate the two chunks so a doc classified in this iteration can be
+ # embedded before the rest of the backlog is classified.
+ classified_count = 0
+ unsafe_count = 0
+ embedded_count = 0
+ chunks_emitted = 0
+ classify_more = True
+ embed_more = True
+ embed_blocked = False
+ tried_ids: list[str] = []
+ classify_retry = RetryPolicy(maximum_attempts=2)
+ embed_retry = RetryPolicy(maximum_attempts=2)
+ for _ in range(max(_CLASSIFY_DRAIN_MAX_CHUNKS, _EMBED_DRAIN_MAX_CHUNKS)):
+ classify_scanned = 0
+ if classify_more:
+ classified = await _take_index_chunk(
+ classify_pending_documents_activity,
+ start_to_close=timedelta(minutes=30),
+ heartbeat=timedelta(minutes=5),
+ retry=classify_retry,
+ arg=tried_ids,
+ )
+ classified_count += int(classified["classified"])
+ unsafe_count += int(classified["unsafe"])
+ classify_scanned = int(classified["scanned"])
+ classify_more = classify_scanned >= _CLASSIFY_CHUNK_SIZE
+ tried_ids.extend(str(document_id) for document_id in classified["tried_ids"])
+ if not embed_blocked and (embed_more or classify_scanned > 0):
+ embedded = await _take_index_chunk(
+ emit_pending_embeddings_activity,
+ start_to_close=timedelta(minutes=10),
+ retry=embed_retry,
)
- for result in results:
- if isinstance(result, BaseException):
- failed += 1
- elif result.get("status") == "ok":
- refreshed += 1
- else:
- skipped += 1
+ embedded_counts = {
+ "documents_embedded": int(embedded["documents_embedded"]),
+ "chunks_emitted": int(embedded["chunks_emitted"]),
+ "scanned": int(embedded["scanned"]),
+ }
+ embedded_count += embedded_counts["documents_embedded"]
+ chunks_emitted += embedded_counts["chunks_emitted"]
+ if embedded_counts["scanned"] >= _EMBED_CHUNK_SIZE and embedded_counts["documents_embedded"] == 0:
+ embed_blocked = True
+ embed_more = False
+ else:
+ embed_more = _embed_chunk_has_more(embedded_counts, chunk_size=_EMBED_CHUNK_SIZE)
+ if not classify_more and not embed_more:
+ break
+ return _IndexDrainTotals(
+ classified=classified_count,
+ unsafe=unsafe_count,
+ documents_embedded=embedded_count,
+ chunks_emitted=chunks_emitted,
+ )
+
+async def _run_refresh_coordinator(*, drain_index_queues: bool) -> dict[str, Any]:
+ swept = await workflow.execute_activity(
+ sweep_tombstoned_documents_activity,
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ # Refresh *before* classify: refreshed docs whose content changed are
+ # reset to `unknown`, so running classification second picks them up in
+ # the same pass instead of leaving them searchable until the next run.
+ due: list[tuple[int, str, str]] = await workflow.execute_activity(
+ list_due_refresh_sources_activity,
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ refreshed = skipped = failed = 0
+ start_to_close, heartbeat = _crawl_activity_timeouts()
+ for batch in _host_serialized_batches(due, MAX_CONCURRENT_REFRESHES):
+ results = await asyncio.gather(
+ *(
+ workflow.execute_activity(
+ refresh_knowledge_source_activity,
+ inputs,
+ start_to_close_timeout=start_to_close,
+ heartbeat_timeout=heartbeat,
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ for inputs in batch
+ ),
+ return_exceptions=True,
+ )
+ for result in results:
+ if isinstance(result, BaseException):
+ failed += 1
+ elif result.get("status") == "ok":
+ refreshed += 1
+ else:
+ skipped += 1
+
+ if drain_index_queues:
+ # Un-stamp lost vectors before the first emit chunk, so that chunk can
+ # re-produce them. Classify and embed then alternate inside the drain.
+ reconciled = await workflow.execute_activity(
+ reconcile_embeddings_activity,
+ start_to_close_timeout=timedelta(minutes=10),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ drained = await _drain_index_queues()
+ classified = {"classified": drained.classified, "unsafe": drained.unsafe}
+ embedded = {
+ "documents_embedded": drained.documents_embedded,
+ "chunks_emitted": drained.chunks_emitted,
+ }
+ else:
classified = await workflow.execute_activity(
classify_pending_documents_activity,
start_to_close_timeout=timedelta(minutes=30),
@@ -525,33 +667,55 @@ 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),
- )
+ # 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),
- "sources_refreshed": refreshed,
- "sources_skipped": skipped,
- "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),
- "embeddings_ttl_refreshed": ttl_refreshed.get("documents_refreshed", 0),
- "chunks_reemitted": ttl_refreshed.get("chunks_reemitted", 0),
- }
+ return {
+ "tombstoned_deleted": swept,
+ "sources_due": len(due),
+ "sources_refreshed": refreshed,
+ "sources_skipped": skipped,
+ "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),
+ "embeddings_ttl_refreshed": ttl_refreshed.get("documents_refreshed", 0),
+ "chunks_reemitted": ttl_refreshed.get("chunks_reemitted", 0),
+ }
+
+
+def _parse_coordinator_inputs(inputs: list[str]) -> None:
+ # The coordinator takes no inputs; tolerate any payload from manual triggers.
+ _ = json.loads(inputs[0]) if inputs else None
+ return None
+
+
[email protected](name="business-knowledge-refresh-coordinator")
+class BusinessKnowledgeRefreshCoordinatorWorkflow(PostHogWorkflow):
+ @workflow.run
+ async def run(self) -> dict[str, Any]:
+ return await _run_refresh_coordinator(drain_index_queues=False)
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> None:
+ return _parse_coordinator_inputs(inputs)
+
+
[email protected](name=REFRESH_COORDINATOR_WORKFLOW_V2)
+class BusinessKnowledgeRefreshCoordinatorWorkflowV2(PostHogWorkflow):
+ @workflow.run
+ async def run(self) -> dict[str, Any]:
+ return await _run_refresh_coordinator(drain_index_queues=True)
@staticmethod
def parse_inputs(inputs: list[str]) -> None:
- # The coordinator takes no inputs; tolerate any payload from manual triggers.
- _ = json.loads(inputs[0]) if inputs else None
- return None
+ return _parse_coordinator_inputs(inputs)
diff --git a/products/business_knowledge/backend/temporal/schedule.py b/products/business_knowledge/backend/temporal/schedule.py
index 4675096a9f7d..1073836ed319 100644
--- a/products/business_knowledge/backend/temporal/schedule.py
+++ b/products/business_knowledge/backend/temporal/schedule.py
@@ -18,6 +18,7 @@ from temporalio.client import (
from posthog.scheduling.jitter import deterministic_offset
from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+from .coordinator import REFRESH_COORDINATOR_WORKFLOW_V2
from .learning.constants import LEARNING_COORDINATOR_INTERVAL_MINUTES
from .learning.schemas import LearningCoordinatorInput
@@ -31,7 +32,7 @@ async def create_business_knowledge_refresh_coordinator_schedule(client: Client)
"""Create or update the single global coordinator schedule (idempotent)."""
coordinator_schedule = Schedule(
action=ScheduleActionStartWorkflow(
- "business-knowledge-refresh-coordinator",
+ REFRESH_COORDINATOR_WORKFLOW_V2,
id=SCHEDULE_ID,
task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
),
diff --git a/products/business_knowledge/backend/tests/test_content_safety.py b/products/business_knowledge/backend/tests/test_content_safety.py
index 09272f05cba0..970303950653 100644
--- a/products/business_knowledge/backend/tests/test_content_safety.py
+++ b/products/business_knowledge/backend/tests/test_content_safety.py
@@ -138,6 +138,12 @@ class TestSafetyFilteringAndClassification(BaseTest):
assert doc.classification_attempts == 1
# Still searchable-excluded.
assert logic.search_knowledge(self.team.id, "alpha") == []
+ # The next chunk must take a doc that has not been tried yet.
+ _fresh_source, fresh = self._ready_unknown_source("B", "beta content here")
+ pending = logic.list_documents_pending_classification(limit=1)
+ assert pending[0].document_id == fresh.id
+ excluded = logic.list_documents_pending_classification(limit=1, exclude_ids=[fresh.id])
+ assert excluded[0].document_id == doc.id
def test_pending_classification_skips_docs_past_attempt_cap(self) -> None:
_source, doc = self._ready_unknown_source("A", "alpha content here")
diff --git a/products/business_knowledge/backend/tests/test_refresh_coordinator.py b/products/business_knowledge/backend/tests/test_refresh_coordinator.py
new file mode 100644
index 000000000000..54cca933467a
--- /dev/null
+++ b/products/business_knowledge/backend/tests/test_refresh_coordinator.py
@@ -0,0 +1,175 @@
+import logging
+from datetime import timedelta
+from typing import TypedDict
+
+import pytest
+
+from temporalio import activity
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from products.business_knowledge.backend.temporal.coordinator import (
+ _CLASSIFY_CHUNK_SIZE,
+ _CLASSIFY_DRAIN_MAX_CHUNKS,
+ _EMBED_CHUNK_SIZE,
+ BusinessKnowledgeRefreshCoordinatorWorkflowV2,
+)
+
+
+class _ClassifyStub(TypedDict):
+ classified: int
+ unsafe: int
+ scanned: int
+ tried_ids: list[str]
+
+
+async def test_coordinator_keeps_taking_index_chunks_until_the_queue_is_short() -> None:
+ # A wedged workflow task retries forever at INFO. Fail the run instead.
+ logging.getLogger("temporalio.activity").setLevel(logging.INFO)
+ logging.getLogger("temporalio.workflow").setLevel(logging.INFO)
+
+ classify_script: list[_ClassifyStub] = [
+ {
+ "classified": _CLASSIFY_CHUNK_SIZE,
+ "unsafe": 1,
+ "scanned": _CLASSIFY_CHUNK_SIZE,
+ "tried_ids": ["doc-1"],
+ },
+ {
+ "classified": _CLASSIFY_CHUNK_SIZE,
+ "unsafe": 0,
+ "scanned": _CLASSIFY_CHUNK_SIZE,
+ "tried_ids": ["doc-2"],
+ },
+ {"classified": 3, "unsafe": 0, "scanned": 3, "tried_ids": ["doc-3"]},
+ ]
+ embed_script = [
+ {
+ "documents_embedded": _EMBED_CHUNK_SIZE,
+ "chunks_emitted": _EMBED_CHUNK_SIZE * 2,
+ "scanned": _EMBED_CHUNK_SIZE,
+ },
+ {"documents_embedded": 0, "chunks_emitted": 0, "scanned": _EMBED_CHUNK_SIZE},
+ ]
+ calls: list[str] = []
+ classify_excludes: list[list[str]] = []
+
+ @activity.defn(name="sweep_tombstoned_documents_activity")
+ async def sweep() -> int:
+ return 0
+
+ @activity.defn(name="list_due_refresh_sources_activity")
+ async def list_due() -> list[tuple[int, str, str]]:
+ return []
+
+ @activity.defn(name="classify_pending_documents_activity")
+ async def classify(exclude_ids: list[str]) -> _ClassifyStub:
+ calls.append("classify")
+ classify_excludes.append(exclude_ids)
+ if classify_script:
+ return classify_script.pop(0)
+ return {"classified": 0, "unsafe": 0, "scanned": 0, "tried_ids": []}
+
+ @activity.defn(name="reconcile_embeddings_activity")
+ async def reconcile() -> dict[str, int]:
+ return {"reconciled": 0, "re_nulled": 0}
+
+ @activity.defn(name="emit_pending_embeddings_activity")
+ async def emit() -> dict[str, int]:
+ calls.append("emit")
+ if embed_script:
+ return embed_script.pop(0)
+ return {"documents_embedded": 0, "chunks_emitted": 0, "scanned": 0}
+
+ @activity.defn(name="refresh_aging_embeddings_activity")
+ async def refresh_aging() -> dict[str, int]:
+ return {"documents_refreshed": 0, "chunks_reemitted": 0}
+
+ async with await WorkflowEnvironment.start_time_skipping() as environment:
+ async with Worker(
+ environment.client,
+ task_queue="bk-refresh-coordinator-test",
+ workflows=[BusinessKnowledgeRefreshCoordinatorWorkflowV2],
+ activities=[sweep, list_due, classify, reconcile, emit, refresh_aging],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ result = await environment.client.execute_workflow(
+ BusinessKnowledgeRefreshCoordinatorWorkflowV2.run,
+ id="bk-refresh-coordinator-drain-test",
+ task_queue="bk-refresh-coordinator-test",
+ execution_timeout=timedelta(minutes=2),
+ )
+
+ assert calls == ["classify", "emit", "classify", "emit", "classify"]
+ assert classify_excludes == [[], ["doc-1"], ["doc-1", "doc-2"]]
+ assert result["documents_classified"] == _CLASSIFY_CHUNK_SIZE * 2 + 3
+ assert result["documents_unsafe"] == 1
+ assert result["documents_embedded"] == _EMBED_CHUNK_SIZE
+ assert result["chunks_emitted"] == _EMBED_CHUNK_SIZE * 2
+
+
+async def test_index_drain_stops_at_the_chunk_ceiling() -> None:
+ logging.getLogger("temporalio.activity").setLevel(logging.INFO)
+ logging.getLogger("temporalio.workflow").setLevel(logging.INFO)
+
+ classify_calls = 0
+ embed_calls = 0
+
+ @activity.defn(name="sweep_tombstoned_documents_activity")
+ async def sweep() -> int:
+ return 0
+
+ @activity.defn(name="list_due_refresh_sources_activity")
+ async def list_due() -> list[tuple[int, str, str]]:
+ return []
+
+ @activity.defn(name="classify_pending_documents_activity")
+ async def classify(_exclude_ids: list[str]) -> _ClassifyStub:
+ nonlocal classify_calls
+ classify_calls += 1
+ return {
+ "classified": _CLASSIFY_CHUNK_SIZE,
+ "unsafe": 0,
+ "scanned": _CLASSIFY_CHUNK_SIZE,
+ "tried_ids": [f"doc-{classify_calls}"],
+ }
+
+ @activity.defn(name="reconcile_embeddings_activity")
+ async def reconcile() -> dict[str, int]:
+ return {"reconciled": 0, "re_nulled": 0}
+
+ @activity.defn(name="emit_pending_embeddings_activity")
+ async def emit() -> dict[str, int]:
+ nonlocal embed_calls
+ embed_calls += 1
+ return {
+ "documents_embedded": _EMBED_CHUNK_SIZE,
+ "chunks_emitted": _EMBED_CHUNK_SIZE,
+ "scanned": _EMBED_CHUNK_SIZE,
+ }
+
+ @activity.defn(name="refresh_aging_embeddings_activity")
+ async def refresh_aging() -> dict[str, int]:
+ return {"documents_refreshed": 0, "chunks_reemitted": 0}
+
+ async with await WorkflowEnvironment.start_time_skipping() as environment:
+ async with Worker(
+ environment.client,
+ task_queue="bk-refresh-coordinator-ceiling-test",
+ workflows=[BusinessKnowledgeRefreshCoordinatorWorkflowV2],
+ activities=[sweep, list_due, classify, reconcile, emit, refresh_aging],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ result = await environment.client.execute_workflow(
+ BusinessKnowledgeRefreshCoordinatorWorkflowV2.run,
+ id="bk-refresh-coordinator-ceiling-test",
+ task_queue="bk-refresh-coordinator-ceiling-test",
+ execution_timeout=timedelta(minutes=2),
+ )
+
+ assert classify_calls == _CLASSIFY_DRAIN_MAX_CHUNKS
+ assert embed_calls == _CLASSIFY_DRAIN_MAX_CHUNKS
+ assert result["documents_classified"] == _CLASSIFY_CHUNK_SIZE * _CLASSIFY_DRAIN_MAX_CHUNKS
+ assert result["documents_embedded"] == _EMBED_CHUNK_SIZE * _CLASSIFY_DRAIN_MAX_CHUNKS