: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
fix(business-knowledge): release stuck sources and strip NUL bytes (#116084)
John C. Waters1933f5984dd2
diff --git a/products/business_knowledge/backend/api/views.py b/products/business_knowledge/backend/api/views.pyindex 88f75a0fe0e8..0cfbb6719534 100644--- a/products/business_knowledge/backend/api/views.py+++ b/products/business_knowledge/backend/api/views.py@@ -232,7 +232,11 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# mypy can't resolve Temporal's start_workflow overloads for string-named workflows.async_to_sync(client.start_workflow)( # type: ignore[misc]"business-knowledge-ingest-source", # type: ignore[arg-type]- IngestSourceInputs(team_id=self.team_id, source_id=str(source.id)), # type: ignore[arg-type]+ IngestSourceInputs( # type: ignore[arg-type]+ team_id=self.team_id,+ source_id=str(source.id),+ claim_id=str(source.processing_claim_id) if source.processing_claim_id else None,+ ),id=f"business-knowledge-ingest-{source.id}",task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,)@@ -452,7 +456,11 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):client = sync_connect()async_to_sync(client.start_workflow)( # type: ignore[misc]"business-knowledge-refresh-source", # type: ignore[arg-type]- RefreshSourceInputs(team_id=self.team_id, source_id=str(source.id)), # type: ignore[arg-type]+ RefreshSourceInputs( # type: ignore[arg-type]+ team_id=self.team_id,+ source_id=str(source.id),+ claim_id=str(source.processing_claim_id) if source.processing_claim_id else None,+ ),id=f"business-knowledge-refresh-{source.id}",task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,)diff --git a/products/business_knowledge/backend/html_parse.py b/products/business_knowledge/backend/html_parse.pyindex b95bbc4c091c..690b022b2404 100644--- a/products/business_knowledge/backend/html_parse.py+++ b/products/business_knowledge/backend/html_parse.py@@ -157,4 +157,5 @@ def parse_html(body: bytes, url: str, content_type: str | None = None) -> tuple[except Exception: # noqa: BLE001pass- return title, text+ # Postgres text fields reject NUL, and the bs4 fallback keeps them from bodies that are not HTML.+ return title.replace("\x00", ""), text.replace("\x00", "")diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.pyindex cbc5ec3ae70c..12979ba9eb81 100644--- a/products/business_knowledge/backend/logic.py+++ b/products/business_knowledge/backend/logic.py@@ -145,6 +145,10 @@ class SourceBusyError(Exception):"""A refresh is already running for this source."""+class SourceClaimLostError(Exception):+ """The run's PROCESSING claim was released or taken over, so it must not write."""++class GeneratedSourceReadOnlyError(Exception):"""A system-managed source cannot be changed through user mutation paths."""@@ -1275,6 +1279,7 @@ def _validate_url(url: str) -> str:_PROCESSING_STALENESS_MINUTES = 10+_FAILED_PROCESSING_MESSAGE = "Processing stopped before it finished. You can retry via refresh."def _resolve_crawl_config(raw: dict | None) -> discover.CrawlConfig:@@ -1429,10 +1434,24 @@ def claim_url_source(crawl_config=crawl_config or {},refresh_interval=refresh_interval or RefreshInterval.MANUAL,always_include=always_include,+ processing_claim_id=uuid.uuid4(),)return source+def _lock_claimed_source(source: KnowledgeSource, team_id: int) -> KnowledgeSource:+ """+ Lock the source row and confirm `source`'s run still holds the PROCESSING claim.++ Call inside `transaction.atomic()` before each write, so a timed-out run whose thread keeps going+ cannot write after `release_failed_source` or the stale sweep ended its claim.+ """+ fresh = KnowledgeSource.objects.select_for_update().get(id=source.id, team_id=team_id)+ if fresh.status != SourceStatus.PROCESSING or fresh.processing_claim_id != source.processing_claim_id:+ raise SourceClaimLostError(f"Source {source.id} is no longer claimed by this run.")+ return fresh++def _ingest_url_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeSource | None:"""Fetch + parse + chunk a single-URL source that's already claimed PROCESSING.@@ -1447,7 +1466,7 @@ def _ingest_url_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeSouresult, title, text = _fetch_and_parse(normalized, etag=None)except (InvalidUrlError, UrlFetchFailedError, EmptyContentError) as exc:with transaction.atomic():- fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ fresh = _lock_claimed_source(source, team_id)now = timezone.now()fresh.status = SourceStatus.ERRORfresh.error_message = str(exc)@@ -1469,6 +1488,7 @@ def _ingest_url_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeSoucontent_hash = sha256_of(text)try:with transaction.atomic():+ _lock_claimed_source(source, team_id)_replace_source_content(source=source,team_id=team_id,@@ -1495,7 +1515,7 @@ def _ingest_url_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeSou)except QuotaExceededError:with transaction.atomic():- fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ fresh = _lock_claimed_source(source, team_id)fresh.status = SourceStatus.ERRORfresh.error_message = "Quota exceeded"fresh.last_refresh_at = timezone.now()@@ -1534,8 +1554,12 @@ def create_url_source(return _ingest_url_source(source=source, team_id=team_id) or source+def _is_claimed_by_another_run(source: KnowledgeSource, claim_id: UUID | None) -> bool:+ return claim_id is not None and source.processing_claim_id != claim_id++@with_team_scope(canonical=True)-def ingest_source(*, source_id: UUID, team_id: int) -> KnowledgeSource | None:+def ingest_source(*, source_id: UUID, team_id: int, claim_id: UUID | None = None) -> KnowledgeSource | None:"""Background ingestion entry point for a freshly-claimed PROCESSING source.@@ -1548,21 +1572,28 @@ def ingest_source(*, source_id: UUID, team_id: int) -> KnowledgeSource | None:source = KnowledgeSource.objects.get(id=source_id, team_id=team_id)except KnowledgeSource.DoesNotExist:return None+ if _is_claimed_by_another_run(source, claim_id):+ return sourceif source.source_type != SourceType.URL or not source.source_url:return source- if source.crawl_mode and source.crawl_mode != CrawlMode.SINGLE:- return _ingest_crawl_source(source=source, team_id=team_id)- return _ingest_url_source(source=source, team_id=team_id)+ try:+ if source.crawl_mode and source.crawl_mode != CrawlMode.SINGLE:+ return _ingest_crawl_source(source=source, team_id=team_id)+ return _ingest_url_source(source=source, team_id=team_id)+ except SourceClaimLostError:+ logger.info("business_knowledge.ingest.claim_lost", source_id=str(source.id))+ return get_for_team(source.id, team_id)@with_team_scope(canonical=True)-def claim_refresh_source(*, source_id: UUID, team_id: int) -> KnowledgeSource:+def claim_refresh_source(*, source_id: UUID, team_id: int, claim_id: UUID | None = None) -> KnowledgeSource:"""Mark a URL source PROCESSING so a background worker can refresh it.Acquires the per-team advisory lock and enforces the single-PROCESSINGinvariant. Raises `SourceBusyError` / `InvalidUrlError` synchronously sothe API can return 409 / 400 before kicking off the workflow.+ A retry that passes the `claim_id` already on the row gets the row back instead of `SourceBusyError`."""try:existing_source = KnowledgeSource.objects.only("is_generated").get(id=source_id, team_id=team_id)@@ -1571,42 +1602,31 @@ def claim_refresh_source(*, source_id: UUID, team_id: int) -> KnowledgeSource:_ensure_user_managed_source(existing_source)with transaction.atomic():+ _acquire_source_quota_lock(team_id)+ source = KnowledgeSource.objects.select_for_update().get(id=source_id, team_id=team_id)+ if claim_id is not None and source.status == SourceStatus.PROCESSING and source.processing_claim_id == claim_id:+ return source_check_source_quota_locked(team_id, reject_if_processing=True)- try:- source = KnowledgeSource.objects.select_for_update().get(id=source_id, team_id=team_id)- except KnowledgeSource.DoesNotExist:- raise+ source.refresh_from_db()_ensure_user_managed_source(source)if source.source_type != SourceType.URL or not source.source_url:raise InvalidUrlError("Only URL sources can be refreshed.")if source.status == SourceStatus.PROCESSING:raise SourceBusyError("This source is already refreshing.")source.status = SourceStatus.PROCESSING- source.save(update_fields=["status", "updated_at"])+ source.processing_claim_id = claim_id or uuid.uuid4()+ source.save(update_fields=["status", "processing_claim_id", "updated_at"])return source-@with_team_scope(canonical=True)-def execute_refresh_source(*, source_id: UUID, team_id: int) -> KnowledgeSource | None:- """- Actually re-fetch + rebuild a source that's already claimed PROCESSING.-- Called from a Temporal activity or as an inline fallback. The claim must- have happened beforehand via `claim_refresh_source`.- """- try:- source = KnowledgeSource.objects.get(id=source_id, team_id=team_id)- except KnowledgeSource.DoesNotExist:- return None-- _ensure_user_managed_source(source)+def _refresh_claimed_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeSource | None:try:if source.crawl_mode and source.crawl_mode != CrawlMode.SINGLE:return _refresh_crawl_source(source=source, team_id=team_id)return _refresh_single_source(source=source, team_id=team_id)except QuotaExceededError:with transaction.atomic():- fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ fresh = _lock_claimed_source(source, team_id)fresh.status = SourceStatus.READY if fresh.documents.exists() else SourceStatus.ERRORfresh.last_refresh_at = timezone.now()fresh.last_refresh_status = RefreshStatus.ERROR@@ -1626,6 +1646,65 @@ def execute_refresh_source(*, source_id: UUID, team_id: int) -> KnowledgeSourceraise+@with_team_scope(canonical=True)+def execute_refresh_source(*, source_id: UUID, team_id: int, claim_id: UUID | None = None) -> KnowledgeSource | None:+ """+ Actually re-fetch + rebuild a source that's already claimed PROCESSING.++ Called from a Temporal activity or as an inline fallback. The claim must+ have happened beforehand via `claim_refresh_source`.+ """+ try:+ source = KnowledgeSource.objects.get(id=source_id, team_id=team_id)+ except KnowledgeSource.DoesNotExist:+ return None+ if _is_claimed_by_another_run(source, claim_id):+ return source++ _ensure_user_managed_source(source)+ try:+ return _refresh_claimed_source(source=source, team_id=team_id)+ except SourceClaimLostError:+ logger.info("business_knowledge.refresh.claim_lost", source_id=str(source.id))+ return get_for_team(source.id, team_id)+++@with_team_scope(canonical=True)+def release_failed_source(*, source_id: UUID, team_id: int, claim_id: UUID | None, discard_documents: bool) -> None:+ """+ Move a source out of PROCESSING once its ingest or refresh activity is out of retries.++ A worker shutdown or heartbeat timeout skips the activity's own error handling, so the workflow calls this.+ `discard_documents` drops the partial index an unfinished ingest committed, so it never turns searchable.+ Only the run holding `claim_id` may release: after the stale sweep, a newer run can own the same row.+ """+ with transaction.atomic():+ source = KnowledgeSource.objects.select_for_update().filter(id=source_id, team_id=team_id).first()+ if source is None or source.status != SourceStatus.PROCESSING:+ return+ if source.processing_claim_id != claim_id:+ return+ if discard_documents:+ _delete_crawl_documents(source=source, team_id=team_id)+ has_live_documents = source.documents.filter(tombstoned_at__isnull=True).exists()+ source.status = SourceStatus.READY if has_live_documents else SourceStatus.ERROR+ source.last_refresh_at = timezone.now()+ source.last_refresh_status = RefreshStatus.ERROR+ source.last_refresh_error = _FAILED_PROCESSING_MESSAGE+ if source.status == SourceStatus.ERROR:+ source.error_message = _FAILED_PROCESSING_MESSAGE+ source.save(+ update_fields=[+ "status",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "error_message",+ "updated_at",+ ]+ )++@with_team_scope(canonical=True)def refresh_source(*, source_id: UUID, team_id: int) -> KnowledgeSource | None:"""@@ -1647,7 +1726,7 @@ def _refresh_single_source(*, source: KnowledgeSource, team_id: int) -> Knowledgresult, title, text = _fetch_and_parse(normalized, etag=source.last_etag or None)except (InvalidUrlError, UrlFetchFailedError, EmptyContentError) as exc:with transaction.atomic():- fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ fresh = _lock_claimed_source(source, team_id)# Leave existing chunks intact so queries keep working even while# refresh is broken — that's why last_refresh_status is separate.fresh.status = SourceStatus.READY if fresh.documents.exists() else SourceStatus.ERROR@@ -1670,7 +1749,7 @@ def _refresh_single_source(*, source: KnowledgeSource, team_id: int) -> Knowledgif result.status == 304:with transaction.atomic():- fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ fresh = _lock_claimed_source(source, team_id)fresh.status = SourceStatus.READYfresh.last_refresh_at = timezone.now()fresh.last_refresh_status = RefreshStatus.NOT_MODIFIED@@ -1693,7 +1772,7 @@ def _refresh_single_source(*, source: KnowledgeSource, team_id: int) -> Knowledgnew_hash = sha256_of(text)with transaction.atomic():- fresh = KnowledgeSource.objects.select_for_update().get(id=source.id, team_id=team_id)+ fresh = _lock_claimed_source(source, team_id)existing_doc = (KnowledgeDocument.objects.filter(team_id=team_id, source_id=fresh.id).order_by("created_at").first())@@ -1867,7 +1946,7 @@ def _ingest_crawl_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeSdef _mark_error(error_msg: str) -> KnowledgeSource:with transaction.atomic():- fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ fresh = _lock_claimed_source(source, team_id)now = timezone.now()fresh.status = SourceStatus.ERRORfresh.error_message = error_msg@@ -1938,6 +2017,7 @@ def _ingest_crawl_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeSreturn _mark_error(f"Crawl would exceed the {MAX_CHUNKS_PER_TEAM} chunk cap.")with transaction.atomic():+ _lock_claimed_source(source, team_id)for outcome in ok_outcomes:_insert_document_and_chunks(source=source,@@ -1956,6 +2036,8 @@ def _ingest_crawl_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeS_delete_crawl_documents(source=source, team_id=team_id)_mark_error(f"Crawl exceeded the {MAX_CHUNKS_PER_TEAM} chunk cap.")raise+ except SourceClaimLostError:+ raiseexcept Exception:_delete_crawl_documents(source=source, team_id=team_id)raise@@ -1963,24 +2045,27 @@ def _ingest_crawl_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeSif not written_any:return _mark_error(first_error or "All pages failed to fetch.")- source.status = SourceStatus.READY- source.last_refresh_at = timezone.now()- source.last_refresh_status = RefreshStatus.SUCCESS- source.last_refresh_error = ""- source.save(- update_fields=[- "status",- "last_refresh_at",- "last_refresh_status",- "last_refresh_error",- "updated_at",- ]- )+ with transaction.atomic():+ fresh = _lock_claimed_source(source, team_id)+ fresh.status = SourceStatus.READY+ fresh.last_refresh_at = timezone.now()+ fresh.last_refresh_status = RefreshStatus.SUCCESS+ fresh.last_refresh_error = ""+ fresh.save(+ update_fields=[+ "status",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "updated_at",+ ]+ )return get_for_team(source.id, team_id) or sourcedef _delete_crawl_documents(*, source: KnowledgeSource, team_id: int) -> None:with transaction.atomic():+ _lock_claimed_source(source, team_id)KnowledgeChunk.objects.filter(team_id=team_id, source_id=source.id).delete()KnowledgeDocument.objects.filter(team_id=team_id, source_id=source.id).delete()@@ -2012,7 +2097,7 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledgeraise UrlFetchFailedError(str(exc)) from excexcept (InvalidUrlError, UrlFetchFailedError) as exc:with transaction.atomic():- fresh = KnowledgeSource.objects.get(id=source.id, team_id=team_id)+ fresh = _lock_claimed_source(source, team_id)fresh.status = SourceStatus.READY if fresh.documents.exists() else SourceStatus.ERRORfresh.last_refresh_at = timezone.now()fresh.last_refresh_status = RefreshStatus.ERROR@@ -2080,6 +2165,7 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledge# case the page comes back soon).if vanished_ids:with transaction.atomic():+ _lock_claimed_source(source, team_id)now = timezone.now()KnowledgeChunk.objects.filter(team_id=team_id, document_id__in=vanished_ids).delete()KnowledgeDocument.objects.filter(team_id=team_id, id__in=vanished_ids, tombstoned_at__isnull=True).update(@@ -2091,7 +2177,7 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledgeoutcomes = crawl.iter_fetch(safe_urls, etag_for=_etag_for, prefetched=discovery.prefetched)for batch in batched(outcomes, CRAWL_WRITE_BATCH_SIZE, strict=False):with transaction.atomic():- fresh = KnowledgeSource.objects.select_for_update().get(id=source.id, team_id=team_id)+ fresh = _lock_claimed_source(source, team_id)for outcome in batch:existing = existing_by_url.pop(outcome.url, None)if outcome.status == "not_modified":@@ -2149,7 +2235,7 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledgeelse:error_msg = first_error or "All pages failed to fetch."with transaction.atomic():- fresh = KnowledgeSource.objects.select_for_update().get(id=source.id, team_id=team_id)+ fresh = _lock_claimed_source(source, team_id)now = timezone.now()fresh.last_refresh_at = nowfresh.last_refresh_status = RefreshStatus.ERROR@@ -2173,7 +2259,7 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledgereturn get_for_team(source.id, team_id) or freshwith transaction.atomic():- fresh = KnowledgeSource.objects.select_for_update().get(id=source.id, team_id=team_id)+ fresh = _lock_claimed_source(source, team_id)fresh.status = SourceStatus.READYfresh.last_refresh_at = timezone.now()fresh.last_refresh_status = RefreshStatus.SUCCESS if any_changes else RefreshStatus.NOT_MODIFIEDdiff --git a/products/business_knowledge/backend/migrations/0023_knowledgesource_processing_claim_id.py b/products/business_knowledge/backend/migrations/0023_knowledgesource_processing_claim_id.pynew file mode 100644index 000000000000..d5cedcfde56b--- /dev/null+++ b/products/business_knowledge/backend/migrations/0023_knowledgesource_processing_claim_id.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.18 on 2026-10-14 12:59++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("business_knowledge", "0022_playground_chat_sandbox_task"),+ ]++ operations = [+ migrations.AddField(+ model_name="knowledgesource",+ name="processing_claim_id",+ field=models.UUIDField(+ blank=True,+ help_text="Token of the run that last claimed this source PROCESSING, so a stale run cannot release a newer claim.",+ null=True,+ ),+ ),+ ]diff --git a/products/business_knowledge/backend/migrations/max_migration.txt b/products/business_knowledge/backend/migrations/max_migration.txtindex ccdc8236269b..31b7ebe8d4b6 100644--- a/products/business_knowledge/backend/migrations/max_migration.txt+++ b/products/business_knowledge/backend/migrations/max_migration.txt@@ -1 +1 @@-0022_playground_chat_sandbox_task+0023_knowledgesource_processing_claim_iddiff --git a/products/business_knowledge/backend/models/knowledge_source.py b/products/business_knowledge/backend/models/knowledge_source.pyindex f8f6750480c8..ce1b7e804f43 100644--- a/products/business_knowledge/backend/models/knowledge_source.py+++ b/products/business_knowledge/backend/models/knowledge_source.py@@ -26,6 +26,11 @@ class KnowledgeSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields,status = models.CharField(max_length=16, choices=SourceStatus.choices, default=SourceStatus.PENDING)# Human-facing failure reason. Empty when status != ERROR.error_message = models.TextField(blank=True, default="")+ processing_claim_id = models.UUIDField(+ null=True,+ blank=True,+ help_text="Token of the run that last claimed this source PROCESSING, so a stale run cannot release a newer claim.",+ )# --- Stage 2a: URL-source fields (all nullable — additive, text sources# leave them empty) ---diff --git a/products/business_knowledge/backend/temporal/__init__.py b/products/business_knowledge/backend/temporal/__init__.pyindex f6df24435cb8..021d4a76166f 100644--- a/products/business_knowledge/backend/temporal/__init__.py+++ b/products/business_knowledge/backend/temporal/__init__.py@@ -3,6 +3,7 @@ from .coordinator import (BusinessKnowledgeRefreshCoordinatorWorkflow,BusinessKnowledgeRefreshCoordinatorWorkflowV2,BusinessKnowledgeRefreshSourceWorkflow,+ claim_refresh_source_activity,classify_pending_documents_activity,emit_pending_embeddings_activity,execute_refresh_knowledge_source_activity,@@ -11,6 +12,7 @@ from .coordinator import (reconcile_embeddings_activity,refresh_aging_embeddings_activity,refresh_knowledge_source_activity,+ release_failed_source_activity,sweep_tombstoned_documents_activity,)from .learning.activities.analyze import analyze_learning_evidence_activity@@ -35,8 +37,10 @@ ACTIVITIES = [refresh_aging_embeddings_activity,list_due_refresh_sources_activity,refresh_knowledge_source_activity,+ claim_refresh_source_activity,execute_refresh_knowledge_source_activity,ingest_knowledge_source_activity,+ release_failed_source_activity,collect_learning_evidence_activity,analyze_learning_evidence_activity,]@@ -50,6 +54,7 @@ __all__ = ["BusinessKnowledgeRefreshCoordinatorWorkflow","BusinessKnowledgeRefreshCoordinatorWorkflowV2","BusinessKnowledgeRefreshSourceWorkflow",+ "claim_refresh_source_activity","classify_pending_documents_activity","collect_learning_evidence_activity","analyze_learning_evidence_activity",@@ -60,5 +65,6 @@ __all__ = ["reconcile_embeddings_activity","refresh_aging_embeddings_activity","refresh_knowledge_source_activity",+ "release_failed_source_activity","sweep_tombstoned_documents_activity",]diff --git a/products/business_knowledge/backend/temporal/coordinator.py b/products/business_knowledge/backend/temporal/coordinator.pyindex bb6f3cdbfdb6..3a4b3ec1feff 100644--- a/products/business_knowledge/backend/temporal/coordinator.py+++ b/products/business_knowledge/backend/temporal/coordinator.py@@ -13,7 +13,7 @@ Refresh runs *before* classification so that documents whose content changedduring the refresh (reset to ``unknown``) get classified in the same pass —otherwise they'd be searchable as ``unknown`` until the next hourly run.-Per-source refresh reuses the shipped, idempotent `logic.refresh_source`; the+Per-source refresh reuses `logic.claim_refresh_source` + `execute_refresh_source`; theexisting per-team advisory lock ("one PROCESSING source per team") plus theschedule's SKIP overlap policy prevent concurrent double-refresh, so there isno bespoke concurrency cap here.@@ -31,6 +31,7 @@ from uuid import UUIDimport structlogfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy+from temporalio.exceptions import ActivityErrorfrom posthog.hogql import astfrom posthog.hogql.query import execute_hogql_query@@ -52,7 +53,7 @@ from ..constants import (MAX_URLS_PER_SOURCE,PENDING_EMBEDDING_SCAN_CAP,)-from ..models import SafetyVerdict+from ..models import KnowledgeSource, SafetyVerdictlogger = structlog.get_logger(__name__)@@ -74,12 +75,22 @@ REFRESH_COORDINATOR_WORKFLOW_V2 = "business-knowledge-refresh-coordinator-v2"class RefreshSourceInputs:team_id: intsource_id: str+ claim_id: str | None = None@dataclasses.dataclass(frozen=True)class IngestSourceInputs:team_id: intsource_id: str+ claim_id: str | None = None++[email protected](frozen=True)+class ReleaseFailedSourceInputs:+ team_id: int+ source_id: str+ discard_documents: bool+ claim_id: str | None = None@activity.defn@@ -376,6 +387,65 @@ def _crawl_activity_timeouts() -> tuple[timedelta, timedelta | None]:return timedelta(minutes=10), None+def _parse_claim_id(claim_id: str | None) -> UUID | None:+ return UUID(claim_id) if claim_id else None+++# Pre-patch histories never released failed sources and refreshed due sources in one activity; replay must match.+_RELEASE_FAILED_SOURCE_PATCH = "bk-release-failed-source"+++async def _release_failed_source(inputs: ReleaseFailedSourceInputs) -> None:+ if not workflow.patched(_RELEASE_FAILED_SOURCE_PATCH):+ return+ await workflow.execute_activity(+ release_failed_source_activity,+ inputs,+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+++async def _refresh_due_source(+ inputs: RefreshSourceInputs, *, start_to_close: timedelta, heartbeat: timedelta | None+) -> dict[str, Any]:+ if not workflow.patched(_RELEASE_FAILED_SOURCE_PATCH):+ return await workflow.execute_activity(+ refresh_knowledge_source_activity,+ inputs,+ start_to_close_timeout=start_to_close,+ heartbeat_timeout=heartbeat,+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+ inputs = dataclasses.replace(inputs, claim_id=str(workflow.uuid4()))+ claimed = await workflow.execute_activity(+ claim_refresh_source_activity,+ inputs,+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ if claimed.get("status") != "ok":+ return claimed+ try:+ return await workflow.execute_activity(+ execute_refresh_knowledge_source_activity,+ inputs,+ start_to_close_timeout=start_to_close,+ heartbeat_timeout=heartbeat,+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+ except ActivityError:+ await _release_failed_source(+ ReleaseFailedSourceInputs(+ team_id=inputs.team_id,+ source_id=inputs.source_id,+ discard_documents=False,+ claim_id=inputs.claim_id,+ )+ )+ raise++@activity.defnasync def refresh_knowledge_source_activity(inputs: RefreshSourceInputs) -> dict[str, Any]:"""@@ -404,17 +474,40 @@ async def refresh_knowledge_source_activity(inputs: RefreshSourceInputs) -> dictreturn {"status": "ok"}+async def claim_refresh_source_activity(inputs: RefreshSourceInputs) -> dict[str, Any]:+ """+ Claim half of a coordinator refresh. Its execute half then retries without+ re-claiming, so the per-team busy check cannot skip a retry.+ """+ log = logger.bind(team_id=inputs.team_id, source_id=inputs.source_id)+ try:+ await database_sync_to_async(logic.claim_refresh_source, thread_sensitive=False)(+ source_id=UUID(inputs.source_id),+ team_id=inputs.team_id,+ claim_id=_parse_claim_id(inputs.claim_id),+ )+ except logic.SourceBusyError:+ return {"status": "skipped", "reason": "busy"}+ except KnowledgeSource.DoesNotExist:+ return {"status": "skipped", "reason": "missing"}+ except (logic.InvalidUrlError, logic.QuotaExceededError) as exc:+ log.info("business_knowledge.refresh.recorded_failure", error_type=type(exc).__name__)+ return {"status": "error", "reason": type(exc).__name__}+ return {"status": "ok"}++@activity.defnasync def execute_refresh_knowledge_source_activity(inputs: RefreshSourceInputs) -> dict[str, Any]:"""Execute the fetch+rebuild half of a refresh for a source already claimed- PROCESSING. Used by the ad-hoc refresh workflow (user clicks "Re-fetch").+ PROCESSING. Used by the ad-hoc refresh workflow (user clicks "Re-fetch") and the coordinator."""log = logger.bind(team_id=inputs.team_id, source_id=inputs.source_id)async with Heartbeater():try:await database_sync_to_async(logic.execute_refresh_source, thread_sensitive=False)(- source_id=UUID(inputs.source_id), team_id=inputs.team_id+ source_id=UUID(inputs.source_id), team_id=inputs.team_id, claim_id=_parse_claim_id(inputs.claim_id))except (logic.InvalidUrlError,@@ -427,6 +520,22 @@ async def execute_refresh_knowledge_source_activity(inputs: RefreshSourceInputs)return {"status": "ok"}+async def release_failed_source_activity(inputs: ReleaseFailedSourceInputs) -> None:+ logger.warning(+ "business_knowledge.processing.released_after_failure",+ team_id=inputs.team_id,+ source_id=inputs.source_id,+ discard_documents=inputs.discard_documents,+ )+ await database_sync_to_async(logic.release_failed_source, thread_sensitive=False)(+ source_id=UUID(inputs.source_id),+ team_id=inputs.team_id,+ claim_id=_parse_claim_id(inputs.claim_id),+ discard_documents=inputs.discard_documents,+ )++@activity.defnasync def ingest_knowledge_source_activity(inputs: IngestSourceInputs) -> dict[str, Any]:"""@@ -441,7 +550,7 @@ async def ingest_knowledge_source_activity(inputs: IngestSourceInputs) -> dict[sasync with Heartbeater():try:await database_sync_to_async(logic.ingest_source, thread_sensitive=False)(- source_id=UUID(inputs.source_id), team_id=inputs.team_id+ source_id=UUID(inputs.source_id), team_id=inputs.team_id, claim_id=_parse_claim_id(inputs.claim_id))except (logic.InvalidUrlError,@@ -459,13 +568,24 @@ class BusinessKnowledgeIngestSourceWorkflow(PostHogWorkflow):@workflow.runasync def run(self, inputs: IngestSourceInputs) -> dict[str, Any]:start_to_close, heartbeat = _crawl_activity_timeouts()- return await workflow.execute_activity(- ingest_knowledge_source_activity,- inputs,- start_to_close_timeout=start_to_close,- heartbeat_timeout=heartbeat,- retry_policy=RetryPolicy(maximum_attempts=2),- )+ try:+ return await workflow.execute_activity(+ ingest_knowledge_source_activity,+ inputs,+ start_to_close_timeout=start_to_close,+ heartbeat_timeout=heartbeat,+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+ except ActivityError:+ await _release_failed_source(+ ReleaseFailedSourceInputs(+ team_id=inputs.team_id,+ source_id=inputs.source_id,+ discard_documents=True,+ claim_id=inputs.claim_id,+ )+ )+ raise@staticmethoddef parse_inputs(inputs: list[str]) -> IngestSourceInputs:@@ -480,13 +600,24 @@ class BusinessKnowledgeRefreshSourceWorkflow(PostHogWorkflow):@workflow.runasync def run(self, inputs: RefreshSourceInputs) -> dict[str, Any]:start_to_close, heartbeat = _crawl_activity_timeouts()- return await workflow.execute_activity(- execute_refresh_knowledge_source_activity,- inputs,- start_to_close_timeout=start_to_close,- heartbeat_timeout=heartbeat,- retry_policy=RetryPolicy(maximum_attempts=2),- )+ try:+ return await workflow.execute_activity(+ execute_refresh_knowledge_source_activity,+ inputs,+ start_to_close_timeout=start_to_close,+ heartbeat_timeout=heartbeat,+ retry_policy=RetryPolicy(maximum_attempts=2),+ )+ except ActivityError:+ await _release_failed_source(+ ReleaseFailedSourceInputs(+ team_id=inputs.team_id,+ source_id=inputs.source_id,+ discard_documents=False,+ claim_id=inputs.claim_id,+ )+ )+ raise@staticmethoddef parse_inputs(inputs: list[str]) -> RefreshSourceInputs:@@ -610,16 +741,7 @@ async def _run_refresh_coordinator(*, drain_index_queues: bool) -> dict[str, Anystart_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- ),+ *(_refresh_due_source(inputs, start_to_close=start_to_close, heartbeat=heartbeat) for inputs in batch),return_exceptions=True,)for result in results:diff --git a/products/business_knowledge/backend/tests/test_crawl_ingest.py b/products/business_knowledge/backend/tests/test_crawl_ingest.pyindex 2f842baf613b..4778d2608fad 100644--- a/products/business_knowledge/backend/tests/test_crawl_ingest.py+++ b/products/business_knowledge/backend/tests/test_crawl_ingest.py@@ -20,6 +20,7 @@ Design notes:test patches the narrowest layer it needs."""+import uuidfrom collections.abc import Iterator, Mappingfrom typing import Any@@ -32,7 +33,15 @@ from parameterized import parameterizedfrom products.business_knowledge.backend import crawl, discover, logic, url_fetchfrom products.business_knowledge.backend.logic import create_crawl_source, ingest_source, refresh_source-from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource, SourceStatus+from products.business_knowledge.backend.models import (+ KnowledgeChunk,+ KnowledgeDocument,+ KnowledgeSource,+ RefreshStatus,+ SourceStatus,+)++_CURRENT_CLAIM_ID = uuid.UUID("00000000-0000-0000-0000-00000000000a")def _sitemap_xml(urls: list[str]) -> str:@@ -474,7 +483,15 @@ class TestCreateCrawlSource(APIBaseTest):chunks_before if expected_docs else 0)- def test_ingest_of_a_finished_source_keeps_its_rows(self) -> None:+ @parameterized.expand(+ [+ ("finished_source", SourceStatus.READY, None),+ ("source_a_newer_run_claimed", SourceStatus.PROCESSING, uuid.UUID("00000000-0000-0000-0000-00000000000b")),+ ]+ )+ def test_ingest_leaves_rows_of_a_source_it_does_not_own(+ self, _name: str, status_before: str, ingest_claim_id: uuid.UUID | None+ ) -> None:urls = ["https://example.com/a"]behaviours = {url: _ok(url, f"<html><body>Body of {url}.</body></html>".encode()) for url in urls}with (@@ -490,12 +507,15 @@ class TestCreateCrawlSource(APIBaseTest):crawl_config={"max_pages": 10},)chunks_before = KnowledgeChunk.objects.unscoped().filter(source=source).count()+ KnowledgeSource.objects.unscoped().filter(id=source.id).update(+ status=status_before, processing_claim_id=_CURRENT_CLAIM_ID+ )with patch.object(discover, "_http_get_text", side_effect=AssertionError("must not rediscover")):- again = ingest_source(source_id=source.id, team_id=self.team.id)+ again = ingest_source(source_id=source.id, team_id=self.team.id, claim_id=ingest_claim_id)assert again is not None- assert again.status == SourceStatus.READY+ assert again.status == status_beforeassert KnowledgeChunk.objects.unscoped().filter(source=source).count() == chunks_beforedef test_zero_safe_urls_returns_error_source(self) -> None:@@ -622,6 +642,168 @@ class TestRefreshCrawlSource(APIBaseTest):assert "updated" in doc_a.contentassert doc_b.content_hash == b_hash_before+ def test_refresh_stores_a_text_page_whose_body_has_nul_bytes(self) -> None:+ source = self._seed(["https://example.com/a"])+ sitemap = _sitemap_xml(["https://example.com/a", "https://example.com/notes.txt"])+ behaviours = {+ "https://example.com/a": _ok(+ "https://example.com/a", b"<html><body>body of https://example.com/a</body></html>"+ ),+ "https://example.com/notes.txt": url_fetch.FetchResult(+ status=200,+ body=b"Release notes \x00for the docs.",+ content_type="text/plain",+ etag=None,+ final_url="https://example.com/notes.txt",+ ),+ }+ with (+ patch.object(discover, "_http_get_text", return_value=sitemap),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ ):+ refresh_source(source_id=source.id, team_id=self.team.id)++ source.refresh_from_db()+ assert source.status == SourceStatus.READY+ assert source.last_refresh_status == RefreshStatus.SUCCESS+ notes = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/notes.txt")+ assert notes.content == "Release notes for the docs."++ @parameterized.expand(+ [+ (+ "refresh_keeps_written_documents_searchable",+ False,+ SourceStatus.PROCESSING,+ _CURRENT_CLAIM_ID,+ SourceStatus.READY,+ RefreshStatus.ERROR,+ True,+ ),+ (+ "unfinished_ingest_discards_partial_documents",+ True,+ SourceStatus.PROCESSING,+ _CURRENT_CLAIM_ID,+ SourceStatus.ERROR,+ RefreshStatus.ERROR,+ False,+ ),+ (+ "source_another_run_finished_is_left_alone",+ True,+ SourceStatus.READY,+ _CURRENT_CLAIM_ID,+ SourceStatus.READY,+ RefreshStatus.SUCCESS,+ True,+ ),+ (+ "superseded_run_cannot_release_a_newer_claim",+ True,+ SourceStatus.PROCESSING,+ uuid.UUID("00000000-0000-0000-0000-00000000000b"),+ SourceStatus.PROCESSING,+ RefreshStatus.SUCCESS,+ True,+ ),+ ]+ )+ def test_release_failed_source(+ self,+ _name: str,+ discard_documents: bool,+ status_before: str,+ released_claim_id: uuid.UUID,+ expected_status: str,+ expected_refresh_status: str,+ expect_documents_left: bool,+ ) -> None:+ source = self._seed(["https://example.com/a"])+ KnowledgeSource.objects.unscoped().filter(id=source.id).update(+ status=status_before, processing_claim_id=_CURRENT_CLAIM_ID+ )++ logic.release_failed_source(+ source_id=source.id,+ team_id=self.team.id,+ claim_id=released_claim_id,+ discard_documents=discard_documents,+ )++ source.refresh_from_db()+ assert source.status == expected_status+ assert source.last_refresh_status == expected_refresh_status+ assert KnowledgeDocument.objects.unscoped().filter(source=source).exists() == expect_documents_left++ def test_release_failed_source_with_only_tombstoned_documents_becomes_error(self) -> None:+ from django.utils import timezone++ source = self._seed(["https://example.com/a"])+ KnowledgeSource.objects.unscoped().filter(id=source.id).update(+ status=SourceStatus.PROCESSING, processing_claim_id=_CURRENT_CLAIM_ID+ )+ KnowledgeDocument.objects.unscoped().filter(source=source).update(tombstoned_at=timezone.now())++ logic.release_failed_source(+ source_id=source.id, team_id=self.team.id, claim_id=_CURRENT_CLAIM_ID, discard_documents=False+ )++ source.refresh_from_db()+ assert source.status == SourceStatus.ERROR+ assert source.last_refresh_status == RefreshStatus.ERROR++ @parameterized.expand(+ [+ ("ingest", True, SourceStatus.ERROR, False),+ ("refresh", False, SourceStatus.READY, True),+ ]+ )+ def test_run_released_while_fetching_writes_nothing_after_the_release(+ self, _name: str, is_ingest: bool, expected_status: str, expect_documents_left: bool+ ) -> None:+ urls = ["https://example.com/a"]+ source = self._seed(urls)+ KnowledgeSource.objects.unscoped().filter(id=source.id).update(+ status=SourceStatus.PROCESSING, processing_claim_id=_CURRENT_CLAIM_ID+ )+ real_iter_fetch = crawl.iter_fetch++ def iter_fetch_released_by_the_workflow(*args: Any, **kwargs: Any) -> Iterator[crawl.CrawlOutcome]:+ logic.release_failed_source(+ source_id=source.id, team_id=self.team.id, claim_id=_CURRENT_CLAIM_ID, discard_documents=is_ingest+ )+ yield from real_iter_fetch(*args, **kwargs)++ behaviours = {url: _ok(url, b"<html><body>Changed body.</body></html>") for url in urls}+ run = logic.ingest_source if is_ingest else logic.execute_refresh_source+ with (+ patch.object(discover, "_http_get_text", return_value=_sitemap_xml(urls)),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ patch.object(crawl, "iter_fetch", side_effect=iter_fetch_released_by_the_workflow),+ ):+ run(source_id=source.id, team_id=self.team.id, claim_id=_CURRENT_CLAIM_ID)++ source.refresh_from_db()+ assert source.status == expected_status+ assert source.last_refresh_status == RefreshStatus.ERROR+ assert KnowledgeDocument.objects.unscoped().filter(source=source).exists() == expect_documents_left+ assert not KnowledgeDocument.objects.unscoped().filter(source=source, content__contains="Changed").exists()++ def test_claim_refresh_retry_with_its_own_claim_id_continues_and_another_stays_busy(self) -> None:+ source = self._seed(["https://example.com/a"])++ logic.claim_refresh_source(source_id=source.id, team_id=self.team.id, claim_id=_CURRENT_CLAIM_ID)+ logic.claim_refresh_source(source_id=source.id, team_id=self.team.id, claim_id=_CURRENT_CLAIM_ID)+ with self.assertRaises(logic.SourceBusyError):+ logic.claim_refresh_source(+ source_id=source.id, team_id=self.team.id, claim_id=uuid.UUID("00000000-0000-0000-0000-00000000000b")+ )++ source.refresh_from_db()+ assert source.status == SourceStatus.PROCESSING+ assert source.processing_claim_id == _CURRENT_CLAIM_ID+def test_vanished_url_is_tombstoned(self) -> None:source = self._seed(["https://example.com/a", "https://example.com/b"])doc_b = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/b")diff --git a/products/business_knowledge/backend/tests/test_refresh_coordinator.py b/products/business_knowledge/backend/tests/test_refresh_coordinator.pyindex 54cca933467a..e651d7150227 100644--- a/products/business_knowledge/backend/tests/test_refresh_coordinator.py+++ b/products/business_knowledge/backend/tests/test_refresh_coordinator.py@@ -5,14 +5,23 @@ from typing import TypedDictimport pytestfrom temporalio import activity+from temporalio.client import WorkflowFailureError+from temporalio.exceptions import ApplicationErrorfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker+from posthog.temporal.common.base import PostHogWorkflow+from products.business_knowledge.backend.temporal.coordinator import (_CLASSIFY_CHUNK_SIZE,_CLASSIFY_DRAIN_MAX_CHUNKS,_EMBED_CHUNK_SIZE,+ BusinessKnowledgeIngestSourceWorkflow,BusinessKnowledgeRefreshCoordinatorWorkflowV2,+ BusinessKnowledgeRefreshSourceWorkflow,+ IngestSourceInputs,+ RefreshSourceInputs,+ ReleaseFailedSourceInputs,)@@ -173,3 +182,140 @@ async def test_index_drain_stops_at_the_chunk_ceiling() -> None:assert embed_calls == _CLASSIFY_DRAIN_MAX_CHUNKSassert result["documents_classified"] == _CLASSIFY_CHUNK_SIZE * _CLASSIFY_DRAIN_MAX_CHUNKSassert result["documents_embedded"] == _EMBED_CHUNK_SIZE * _CLASSIFY_DRAIN_MAX_CHUNKS+++ "workflow_class, inputs, failing_activity_name, expected_discard_documents",+ [+ (+ BusinessKnowledgeRefreshSourceWorkflow,+ RefreshSourceInputs(team_id=1, source_id="source-1", claim_id="claim-1"),+ "execute_refresh_knowledge_source_activity",+ False,+ ),+ (+ BusinessKnowledgeIngestSourceWorkflow,+ IngestSourceInputs(team_id=1, source_id="source-1", claim_id="claim-1"),+ "ingest_knowledge_source_activity",+ True,+ ),+ ],+)+async def test_source_workflow_releases_the_source_when_its_activity_fails(+ workflow_class: type[PostHogWorkflow],+ inputs: RefreshSourceInputs | IngestSourceInputs,+ failing_activity_name: str,+ expected_discard_documents: bool,+) -> None:+ logging.getLogger("temporalio.activity").setLevel(logging.INFO)+ logging.getLogger("temporalio.workflow").setLevel(logging.INFO)++ released: list[ReleaseFailedSourceInputs] = []++ @activity.defn(name=failing_activity_name)+ async def failing(_inputs: RefreshSourceInputs) -> dict[str, str]:+ raise ApplicationError("text fields cannot contain NUL (0x00) bytes", non_retryable=True)++ @activity.defn(name="release_failed_source_activity")+ async def release(released_inputs: ReleaseFailedSourceInputs) -> None:+ released.append(released_inputs)++ async with await WorkflowEnvironment.start_time_skipping() as environment:+ async with Worker(+ environment.client,+ task_queue="bk-source-release-test",+ workflows=[workflow_class],+ activities=[failing, release],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ with pytest.raises(WorkflowFailureError):+ await environment.client.execute_workflow(+ workflow_class.get_name(),+ inputs,+ id="bk-source-release-test",+ task_queue="bk-source-release-test",+ execution_timeout=timedelta(minutes=2),+ )++ assert released == [+ ReleaseFailedSourceInputs(+ team_id=1, source_id="source-1", discard_documents=expected_discard_documents, claim_id="claim-1"+ )+ ]+++async def test_coordinator_releases_only_the_source_whose_refresh_failed() -> None:+ logging.getLogger("temporalio.activity").setLevel(logging.INFO)+ logging.getLogger("temporalio.workflow").setLevel(logging.INFO)++ released: list[ReleaseFailedSourceInputs] = []+ execute_attempts_by_source_id: dict[str, int] = {}+ claim_ids_by_source_id: dict[str, str | None] = {}++ @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 [(1, "broken", "broken.example.com"), (1, "healthy", "healthy.example.com")]++ @activity.defn(name="claim_refresh_source_activity")+ async def claim(inputs: RefreshSourceInputs) -> dict[str, str]:+ claim_ids_by_source_id[inputs.source_id] = inputs.claim_id+ return {"status": "ok"}++ @activity.defn(name="execute_refresh_knowledge_source_activity")+ async def execute(inputs: RefreshSourceInputs) -> dict[str, str]:+ execute_attempts_by_source_id[inputs.source_id] = execute_attempts_by_source_id.get(inputs.source_id, 0) + 1+ if inputs.source_id == "broken":+ raise ApplicationError("text fields cannot contain NUL (0x00) bytes")+ return {"status": "ok"}++ @activity.defn(name="release_failed_source_activity")+ async def release(released_inputs: ReleaseFailedSourceInputs) -> None:+ released.append(released_inputs)++ @activity.defn(name="classify_pending_documents_activity")+ async def classify(_exclude_ids: list[str]) -> _ClassifyStub:+ 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]:+ 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-release-test",+ workflows=[BusinessKnowledgeRefreshCoordinatorWorkflowV2],+ activities=[sweep, list_due, claim, execute, release, classify, reconcile, emit, refresh_aging],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ result = await environment.client.execute_workflow(+ BusinessKnowledgeRefreshCoordinatorWorkflowV2.run,+ id="bk-refresh-coordinator-release-test",+ task_queue="bk-refresh-coordinator-release-test",+ execution_timeout=timedelta(minutes=2),+ )++ assert released == [+ ReleaseFailedSourceInputs(+ team_id=1, source_id="broken", discard_documents=False, claim_id=claim_ids_by_source_id["broken"]+ )+ ]+ assert claim_ids_by_source_id["broken"] is not None+ assert claim_ids_by_source_id["broken"] != claim_ids_by_source_id["healthy"]+ assert execute_attempts_by_source_id == {"broken": 2, "healthy": 1}+ assert result["sources_failed"] == 1+ assert result["sources_refreshed"] == 1