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(billing): fill salesforce account hosting region from billing (#105875)

Abhischek70a430b0423a
diff --git a/ee/billing/salesforce_enrichment/constants.py b/ee/billing/salesforce_enrichment/constants.py
index 6a71e046ce6f..2fe144800f90 100644
--- a/ee/billing/salesforce_enrichment/constants.py
+++ b/ee/billing/salesforce_enrichment/constants.py
@@ -131,6 +131,9 @@ POSTHOG_ORG_ID_FIELD = "Posthog_Org_ID__c"
POSTHOG_USAGE_ENRICHMENT_BATCH_SIZE = 100
POSTHOG_FETCH_MAPPINGS_PAGE_SIZE = 10_000 # Page size for fetching org mappings, kept under Temporal's 4 MB gRPC limit
+POSTHOG_ORG_REGION_FIELD = "Posthog_Org_Region__c"
+ORG_REGION_BY_LICENSE_ID: dict[int, str] = {1: "EU", 2: "US"}
+
# Salesforce field mappings for PostHog usage signals
# Format: internal_field_name -> salesforce_custom_field_name
POSTHOG_USAGE_FIELD_MAPPINGS = {
diff --git a/ee/billing/salesforce_enrichment/org_regions.py b/ee/billing/salesforce_enrichment/org_regions.py
new file mode 100644
index 000000000000..542e7f7ee071
--- /dev/null
+++ b/ee/billing/salesforce_enrichment/org_regions.py
@@ -0,0 +1,66 @@
+"""Hosting region of PostHog organizations, read from billing licenses in the duckgres DWH."""
+
+import uuid
+from collections import defaultdict
+from collections.abc import Iterable
+from itertools import batched
+
+from psycopg import sql
+
+from .constants import ORG_REGION_BY_LICENSE_ID
+from .duckgres_client import duckgres_cursor
+
+_LOOKUP_CHUNK_SIZE = 1_000
+_STATEMENT_TIMEOUT_MS = 60 * 1000
+
+# Each ID gets its own scalar placeholder, because duckgres accepts scalar binds
+# (the Stripe query uses them) while array binds are unverified. The ID is read
+# back as text, so the rows hold strings whatever the column type is.
+_FETCH_QUERY = sql.SQL(
+ "SELECT CAST(organization_id AS VARCHAR) AS organization_id, license_id "
+ "FROM ducklake.billing_public.billing_customer "
+ "WHERE CAST(organization_id AS VARCHAR) IN ({placeholders})"
+)
+
+
+def normalize_org_id(org_id: str | None) -> str:
+ return (org_id or "").strip().lower()
+
+
+def _is_canonical_uuid(value: str) -> bool:
+ try:
+ return str(uuid.UUID(value)) == value
+ except ValueError:
+ return False
+
+
+def fetch_org_regions(org_ids: Iterable[str]) -> dict[str, str]:
+ """Map organization IDs, normalized, to "US" or "EU" by their billing license.
+
+ An organization gets no entry when it has no billing customer, when its license
+ names no region, or when its customers name different regions. A missing region
+ is never defaulted.
+ """
+ # A Salesforce stamp that is not a canonical UUID cannot match a billing customer.
+ # Leaving it out keeps one malformed stamp from failing a query and costing the
+ # whole page its regions.
+ lookup_ids = sorted({org_id for org_id in map(normalize_org_id, org_ids) if _is_canonical_uuid(org_id)})
+ if not lookup_ids:
+ return {}
+
+ regions_found: dict[str, set[str | None]] = defaultdict(set)
+ with duckgres_cursor() as cur:
+ cur.execute(sql.SQL("SET LOCAL statement_timeout = {}").format(sql.Literal(_STATEMENT_TIMEOUT_MS)))
+ for chunk in batched(lookup_ids, _LOOKUP_CHUNK_SIZE, strict=False):
+ placeholders = sql.SQL(", ").join([sql.Placeholder()] * len(chunk))
+ cur.execute(_FETCH_QUERY.format(placeholders=placeholders), list(chunk))
+ for row in cur.fetchall():
+ region = ORG_REGION_BY_LICENSE_ID.get(row["license_id"])
+ regions_found[normalize_org_id(row["organization_id"])].add(region)
+
+ regions: dict[str, str] = {}
+ for org_id, found in regions_found.items():
+ region = next(iter(found)) if len(found) == 1 else None
+ if region is not None:
+ regions[org_id] = region
+ return regions
diff --git a/ee/billing/test/test_org_regions.py b/ee/billing/test/test_org_regions.py
new file mode 100644
index 000000000000..aed74a7766d7
--- /dev/null
+++ b/ee/billing/test/test_org_regions.py
@@ -0,0 +1,44 @@
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from ee.billing.salesforce_enrichment.org_regions import fetch_org_regions
+
+EU_ORG = "00000000-0000-4000-8000-000000000001"
+US_ORG = "00000000-0000-4000-8000-000000000002"
+OTHER_LICENSE_ORG = "00000000-0000-4000-8000-000000000003"
+NO_LICENSE_ORG = "00000000-0000-4000-8000-000000000004"
+CONFLICT_ORG = "00000000-0000-4000-8000-000000000005"
+PARTLY_UNKNOWN_ORG = "00000000-0000-4000-8000-000000000006"
+
+
+class TestFetchOrgRegions(SimpleTestCase):
+ @patch("ee.billing.salesforce_enrichment.org_regions.duckgres_cursor")
+ def test_maps_licenses_to_regions_and_never_defaults(self, mock_cursor_ctx):
+ mock_cursor = MagicMock()
+ mock_cursor.fetchall.return_value = [
+ {"organization_id": EU_ORG, "license_id": 1},
+ {"organization_id": US_ORG, "license_id": 2},
+ {"organization_id": OTHER_LICENSE_ORG, "license_id": 3},
+ {"organization_id": NO_LICENSE_ORG, "license_id": None},
+ {"organization_id": CONFLICT_ORG, "license_id": 1},
+ {"organization_id": CONFLICT_ORG, "license_id": 2},
+ {"organization_id": PARTLY_UNKNOWN_ORG, "license_id": 2},
+ {"organization_id": PARTLY_UNKNOWN_ORG, "license_id": 3},
+ ]
+ mock_cursor_ctx.return_value.__enter__.return_value = mock_cursor
+
+ regions = fetch_org_regions(
+ [
+ f" {EU_ORG.upper()} ",
+ US_ORG,
+ OTHER_LICENSE_ORG,
+ NO_LICENSE_ORG,
+ CONFLICT_ORG,
+ PARTLY_UNKNOWN_ORG,
+ "00000000-0000-4000-8000-000000000007",
+ "not-a-uuid",
+ ]
+ )
+
+ assert regions == {EU_ORG: "EU", US_ORG: "US"}
diff --git a/posthog/temporal/salesforce_enrichment/usage_workflow.py b/posthog/temporal/salesforce_enrichment/usage_workflow.py
index 10b6fdb02d9a..7e83da073890 100644
--- a/posthog/temporal/salesforce_enrichment/usage_workflow.py
+++ b/posthog/temporal/salesforce_enrichment/usage_workflow.py
@@ -1,19 +1,23 @@
"""Salesforce usage enrichment workflow - enriches accounts with PostHog usage signals."""
+import enum
import json
import time
import asyncio
import datetime as dt
import dataclasses
+from collections import Counter
from itertools import batched
-from typing import Any
+from typing import TYPE_CHECKING, Any
from django.db import close_old_connections
+from simple_salesforce.format import format_soql
from temporalio import activity, workflow
from temporalio.common import RetryPolicy
from temporalio.exceptions import ActivityError, ApplicationError
+from posthog.dataclasses import frozen
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger
@@ -22,10 +26,12 @@ from ee.billing.salesforce_enrichment.constants import (
ORG_MAPPINGS_CACHE_MISSING_ERROR_TYPE,
POSTHOG_FETCH_MAPPINGS_PAGE_SIZE,
POSTHOG_ORG_ID_FIELD,
+ POSTHOG_ORG_REGION_FIELD,
POSTHOG_USAGE_ENRICHMENT_BATCH_SIZE,
POSTHOG_USAGE_FIELD_MAPPINGS,
SALESFORCE_UPDATE_BATCH_SIZE,
)
+from ee.billing.salesforce_enrichment.org_regions import fetch_org_regions, normalize_org_id
from ee.billing.salesforce_enrichment.redis_cache import (
OrgMappingsCacheMissingError,
get_cached_org_mappings_count,
@@ -35,13 +41,16 @@ from ee.billing.salesforce_enrichment.redis_cache import (
from ee.billing.salesforce_enrichment.salesforce_client import get_salesforce_client
from ee.billing.salesforce_enrichment.usage_signals import UsageSignals, aggregate_usage_signals_for_orgs
+if TYPE_CHECKING:
+ from simple_salesforce import Salesforce
+
LOGGER = get_logger(__name__)
# Fields from POSTHOG_USAGE_FIELD_MAPPINGS that are handled specially (not simple attribute->field copy)
_SPECIAL_FIELDS = frozenset({"products_activated_7d", "products_activated_30d"})
[email protected](frozen=False)
class UsageEnrichmentState:
"""Continue-As-New state carried across workflow executions."""
@@ -50,6 +59,8 @@ class UsageEnrichmentState:
total_updated: int = 0
error_count: int = 0
errors: list[str] = dataclasses.field(default_factory=list)
+ regions_filled: int = 0
+ regions_replaced: int = 0
@dataclasses.dataclass
@@ -62,7 +73,7 @@ class UsageEnrichmentInputs:
state: UsageEnrichmentState | None = None # Continue-As-New state
[email protected](frozen=True)
class UsageEnrichmentResult:
"""Result of the usage enrichment workflow."""
@@ -70,6 +81,8 @@ class UsageEnrichmentResult:
total_orgs_updated: int
error_count: int
errors: list[str]
+ regions_filled: int
+ regions_replaced: int
def prepare_salesforce_update_record(salesforce_account_id: str, signals: UsageSignals) -> dict[str, Any]:
@@ -91,6 +104,194 @@ def prepare_salesforce_update_record(salesforce_account_id: str, signals: UsageS
return record
+class OrgRegionOutcome(enum.StrEnum):
+ FILL = "fill"
+ MATCHES = "matches"
+ REPLACE = "replace"
+ RESTAMPED = "restamped"
+
+
+@frozen
+class SalesforceAccountRegion:
+ """Values an Account carries when it is re-read just before its batch is written."""
+
+ posthog_org_id: str | None
+ region: str | None
+
+
+def decide_org_region(org_id: str, billing_region: str, current: SalesforceAccountRegion | None) -> OrgRegionOutcome:
+ """Decide whether billing's region may be written onto the Account mapped to ``org_id``.
+
+ ``current`` is read just before the write, because the cached mapping can be hours old.
+ Billing's license is the authoritative source, so it fills an empty region and replaces
+ a different one, such as an interim value copied from Vitally. It writes only onto an
+ Account that still carries ``org_id``. The read and the Bulk API write are separate calls
+ with no conditional update between them, so a restamp that lands in that gap can take
+ the old organization's region until the next run replaces it.
+ """
+ if current is None or normalize_org_id(current.posthog_org_id) != normalize_org_id(org_id):
+ return OrgRegionOutcome.RESTAMPED
+ if not current.region:
+ return OrgRegionOutcome.FILL
+ if current.region == billing_region:
+ return OrgRegionOutcome.MATCHES
+ return OrgRegionOutcome.REPLACE
+
+
+def org_region_field_is_writable(sf: "Salesforce") -> bool:
+ describe = sf.restful("sobjects/Account/describe") or {}
+ return any(
+ field["name"] == POSTHOG_ORG_REGION_FIELD and field["updateable"] for field in describe.get("fields", [])
+ )
+
+
+async def _fetch_billing_regions(sf: "Salesforce", org_ids: list[str]) -> dict[str, str]:
+ """Return billing's region per normalized organization ID, or an empty map while Salesforce cannot take it.
+
+ Salesforce rejects a whole record that names a missing or read-only field, so
+ sending the region before the field is deployed and granted to this integration
+ user would also drop the usage fields of every Account that has no region yet.
+ """
+ logger = LOGGER.bind()
+ try:
+ if not await asyncio.to_thread(org_region_field_is_writable, sf):
+ logger.warning("salesforce_org_region_field_not_writable", field=POSTHOG_ORG_REGION_FIELD)
+ return {}
+ return await asyncio.to_thread(fetch_org_regions, org_ids)
+ except Exception:
+ logger.exception("org_region_lookup_failed", org_count=len(org_ids))
+ return {}
+
+
+def read_account_regions(sf: "Salesforce", account_ids: list[str]) -> dict[str, SalesforceAccountRegion]:
+ # The field names are trusted constants; simple_salesforce quotes the IN values.
+ query = format_soql(
+ f"SELECT Id, {POSTHOG_ORG_ID_FIELD}, {POSTHOG_ORG_REGION_FIELD} FROM Account WHERE Id IN {{}}",
+ account_ids,
+ )
+ # Index instead of .get(): a missing key means the query and the field disagree, so
+ # the read fails and the batch skips regions instead of deciding on a guessed value.
+ return {
+ record["Id"]: SalesforceAccountRegion(
+ posthog_org_id=record[POSTHOG_ORG_ID_FIELD], region=record[POSTHOG_ORG_REGION_FIELD]
+ )
+ for record in sf.query_all(query).get("records", [])
+ }
+
+
+@frozen
+class _RegionDecision:
+ outcome: OrgRegionOutcome
+ previous_region: str | None
+
+
+async def _add_org_regions(
+ sf: "Salesforce",
+ records: list[dict[str, Any]],
+ org_by_account_id: dict[str, str],
+ billing_regions: dict[str, str],
+) -> dict[str, _RegionDecision]:
+ """Add billing's region to each update record whose Account may take it, and return the decision per Account."""
+ logger = LOGGER.bind()
+ region_by_account_id: dict[str, str] = {}
+ for record in records:
+ billing_region = billing_regions.get(normalize_org_id(org_by_account_id[record["Id"]]))
+ if billing_region is not None:
+ region_by_account_id[record["Id"]] = billing_region
+ if not region_by_account_id:
+ return {}
+
+ try:
+ current_by_account_id = await asyncio.to_thread(read_account_regions, sf, list(region_by_account_id))
+ except Exception:
+ logger.exception("salesforce_account_regions_read_failed", account_count=len(region_by_account_id))
+ return {}
+
+ decisions: dict[str, _RegionDecision] = {}
+ for record in records:
+ account_id = record["Id"]
+ billing_region = region_by_account_id.get(account_id)
+ if billing_region is None:
+ continue
+ current = current_by_account_id.get(account_id)
+ outcome = decide_org_region(org_by_account_id[account_id], billing_region, current)
+ decisions[account_id] = _RegionDecision(outcome=outcome, previous_region=current.region if current else None)
+ if outcome in (OrgRegionOutcome.FILL, OrgRegionOutcome.REPLACE):
+ record[POSTHOG_ORG_REGION_FIELD] = billing_region
+ return decisions
+
+
+@frozen
+class _AccountUpdateCounts:
+ updated: int
+ regions_filled: int
+ regions_replaced: int
+ error: str | None = None
+
+
+async def _update_accounts(
+ sf: "Salesforce", records: list[dict[str, Any]], region_decisions: dict[str, _RegionDecision]
+) -> _AccountUpdateCounts:
+ """Send one Bulk API batch and count the Accounts it updated.
+
+ Salesforce rejects a whole record when one of its values fails, for example a picklist
+ value that the Account's record type does not allow. A rejected record that carries the
+ region is sent again without it, so a region problem never also drops the usage fields.
+ """
+ logger = LOGGER.bind()
+ updated = 0
+ regions_filled = 0
+ regions_replaced = 0
+ resend: list[dict[str, Any]] = []
+ response = await asyncio.to_thread(sf.bulk.Account.update, records) # type: ignore[union-attr,arg-type]
+ # Bulk API results come back in input order, and a failed result can have no id.
+ for record, result in zip(records, response, strict=True):
+ if result.get("success"):
+ updated += 1
+ decision = region_decisions.get(record["Id"])
+ if decision is None:
+ continue
+ if decision.outcome is OrgRegionOutcome.FILL:
+ regions_filled += 1
+ elif decision.outcome is OrgRegionOutcome.REPLACE:
+ regions_replaced += 1
+ logger.info(
+ "salesforce_org_region_replaced",
+ account_id=record["Id"],
+ previous_region=decision.previous_region,
+ billing_region=record[POSTHOG_ORG_REGION_FIELD],
+ )
+ continue
+ logger.warning("salesforce_account_update_failed", account_id=record["Id"], errors=result.get("errors"))
+ if POSTHOG_ORG_REGION_FIELD in record:
+ resend.append({field: value for field, value in record.items() if field != POSTHOG_ORG_REGION_FIELD})
+
+ error = None
+ if resend:
+ try:
+ retry_response = await asyncio.to_thread(sf.bulk.Account.update, resend) # type: ignore[union-attr,arg-type]
+ except Exception as e:
+ # The first attempt's updates are already written, so a failed resend is reported
+ # beside their counts instead of raised over them.
+ logger.exception("salesforce_account_resend_failed", account_count=len(resend))
+ error = f"Failed to resend {len(resend)} Accounts without the region: {e!s}"
+ else:
+ rejected = 0
+ for record, result in zip(resend, retry_response, strict=True):
+ if result.get("success"):
+ updated += 1
+ else:
+ rejected += 1
+ logger.warning(
+ "salesforce_account_update_failed", account_id=record["Id"], errors=result.get("errors")
+ )
+ if rejected:
+ error = f"Salesforce rejected {rejected} Accounts again when resent without the region"
+ return _AccountUpdateCounts(
+ updated=updated, regions_filled=regions_filled, regions_replaced=regions_replaced, error=error
+ )
+
+
@activity.defn
async def cache_org_mappings_activity(force_rebuild: bool = False) -> dict[str, Any]:
"""Cache all Salesforce org mappings in Redis (reuses existing cache if available).
@@ -130,7 +331,7 @@ async def cache_org_mappings_activity(force_rebuild: bool = False) -> dict[str,
return {"success": True, "total_mappings": len(mappings)}
[email protected](frozen=True)
class EnrichPageResult:
"""Result of enriching one page of org mappings."""
@@ -138,6 +339,8 @@ class EnrichPageResult:
processed: int
updated: int
errors: list[str]
+ regions_filled: int = 0
+ regions_replaced: int = 0
@activity.defn
@@ -174,6 +377,7 @@ async def enrich_org_page_activity(offset: int, limit: int, batch_size: int) ->
return EnrichPageResult(page_size=0, processed=0, updated=0, errors=[])
org_to_sf = {m["posthog_org_id"]: m["salesforce_account_id"] for m in cached_mappings}
+ org_by_account_id = {account_id: org_id for org_id, account_id in org_to_sf.items()}
all_org_ids = list(org_to_sf.keys())
total_orgs = len(all_org_ids)
@@ -186,8 +390,12 @@ async def enrich_org_page_activity(offset: int, limit: int, batch_size: int) ->
total_processed = 0
total_updated = 0
+ regions_filled = 0
+ regions_replaced = 0
+ region_outcome_counts: Counter[OrgRegionOutcome] = Counter()
errors: list[str] = []
sf = get_salesforce_client()
+ billing_regions = await _fetch_billing_regions(sf, all_org_ids)
for batch_tuple in batched(all_org_ids, batch_size, strict=False):
batch_org_ids = list(batch_tuple)
@@ -204,16 +412,15 @@ async def enrich_org_page_activity(offset: int, limit: int, batch_size: int) ->
if update_records:
for sf_batch in batched(update_records, SALESFORCE_UPDATE_BATCH_SIZE, strict=False):
- response = await asyncio.to_thread(sf.bulk.Account.update, list(sf_batch)) # type: ignore[union-attr,arg-type]
- for result in response:
- if result.get("success"):
- total_updated += 1
- else:
- logger.warning(
- "salesforce_account_update_failed",
- account_id=result.get("id"),
- errors=result.get("errors"),
- )
+ batch_records = list(sf_batch)
+ region_decisions = await _add_org_regions(sf, batch_records, org_by_account_id, billing_regions)
+ region_outcome_counts.update(decision.outcome for decision in region_decisions.values())
+ counts = await _update_accounts(sf, batch_records, region_decisions)
+ total_updated += counts.updated
+ regions_filled += counts.regions_filled
+ regions_replaced += counts.regions_replaced
+ if counts.error:
+ errors.append(counts.error)
total_processed += len(batch_org_ids)
heartbeater.details = (total_processed, total_orgs, total_updated)
@@ -229,6 +436,10 @@ async def enrich_org_page_activity(offset: int, limit: int, batch_size: int) ->
page_size=len(all_org_ids),
processed=total_processed,
updated=total_updated,
+ billing_regions=len(billing_regions),
+ region_outcomes=dict(region_outcome_counts),
+ regions_filled=regions_filled,
+ regions_replaced=regions_replaced,
error_count=len(errors),
)
@@ -237,6 +448,8 @@ async def enrich_org_page_activity(offset: int, limit: int, batch_size: int) ->
processed=total_processed,
updated=total_updated,
errors=errors,
+ regions_filled=regions_filled,
+ regions_replaced=regions_replaced,
)
@@ -338,6 +551,8 @@ class SalesforceUsageEnrichmentWorkflow(PostHogWorkflow):
state.total_processed += page_result.processed
state.total_updated += page_result.updated
+ state.regions_filled += page_result.regions_filled
+ state.regions_replaced += page_result.regions_replaced
state.error_count += len(page_result.errors)
# Cap stored errors to avoid unbounded growth across Continue-As-New executions
if len(state.errors) < 10:
@@ -389,5 +604,7 @@ class SalesforceUsageEnrichmentWorkflow(PostHogWorkflow):
total_orgs_updated=state.total_updated,
error_count=state.error_count,
errors=state.errors[:10],
+ regions_filled=state.regions_filled,
+ regions_replaced=state.regions_replaced,
)
)
diff --git a/posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py b/posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py
index 08fb591ef47f..d0d92189ab88 100644
--- a/posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py
+++ b/posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py
@@ -3,16 +3,20 @@ import json
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
-from django.test import TestCase
+from django.test import SimpleTestCase, TestCase
+from parameterized import parameterized
from temporalio.exceptions import ActivityError, ApplicationError
from posthog.temporal.salesforce_enrichment.usage_workflow import (
EnrichPageResult,
+ OrgRegionOutcome,
+ SalesforceAccountRegion,
SalesforceUsageEnrichmentWorkflow,
UsageEnrichmentInputs,
UsageEnrichmentState,
cache_org_mappings_activity,
+ decide_org_region,
enrich_org_page_activity,
prepare_salesforce_update_record,
)
@@ -109,6 +113,46 @@ class TestPrepareSalesforceUpdateRecord(TestCase):
assert record["posthog_total_events_30d__c"] == 0
+class TestDecideOrgRegion(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "fills_empty_region",
+ "US",
+ SalesforceAccountRegion(posthog_org_id="org-a", region=None),
+ OrgRegionOutcome.FILL,
+ ),
+ (
+ "fills_when_stamp_differs_only_in_case_and_spaces",
+ "EU",
+ SalesforceAccountRegion(posthog_org_id=" ORG-A ", region=None),
+ OrgRegionOutcome.FILL,
+ ),
+ (
+ "keeps_matching_region",
+ "US",
+ SalesforceAccountRegion(posthog_org_id="org-a", region="US"),
+ OrgRegionOutcome.MATCHES,
+ ),
+ (
+ "replaces_a_different_region",
+ "US",
+ SalesforceAccountRegion(posthog_org_id="org-a", region="EU"),
+ OrgRegionOutcome.REPLACE,
+ ),
+ (
+ "skips_account_restamped_since_cache",
+ "US",
+ SalesforceAccountRegion(posthog_org_id="org-b", region=None),
+ OrgRegionOutcome.RESTAMPED,
+ ),
+ ("skips_account_gone_since_cache", "US", None, OrgRegionOutcome.RESTAMPED),
+ ]
+ )
+ def test_decide_org_region(self, _name, billing_region, current, expected):
+ assert decide_org_region("org-a", billing_region, current) == expected
+
+
class TestWorkflowParseInputs(TestCase):
def test_parse_inputs_valid_json(self):
inputs = SalesforceUsageEnrichmentWorkflow.parse_inputs(['{"batch_size": 50}'])
@@ -139,6 +183,7 @@ class TestWorkflowParseInputs(TestCase):
WORKFLOW_MODULE = "posthog.temporal.salesforce_enrichment.usage_workflow"
+NOT_SENT = "<not sent>"
def _cache_missing_activity_error() -> ActivityError:
@@ -221,6 +266,11 @@ class TestCacheOrgMappingsActivity(TestCase):
class TestEnrichOrgPageActivity(TestCase):
+ def setUp(self):
+ regions_patcher = patch(f"{WORKFLOW_MODULE}.fetch_org_regions", return_value={})
+ regions_patcher.start()
+ self.addCleanup(regions_patcher.stop)
+
@pytest.mark.asyncio
@patch(f"{WORKFLOW_MODULE}.Heartbeater")
@patch(f"{WORKFLOW_MODULE}.get_salesforce_client")
@@ -248,6 +298,149 @@ class TestEnrichOrgPageActivity(TestCase):
assert result.errors == []
mock_get_page.assert_called_once_with(0, 10000)
+ @parameterized.expand(
+ [
+ ("fills_empty_and_replaces_different", None, "US", "EU", 1, 1),
+ ("field_not_writable_yet", "field_not_writable", NOT_SENT, NOT_SENT, 0, 0),
+ ("billing_lookup_fails", "billing_lookup", NOT_SENT, NOT_SENT, 0, 0),
+ ("account_reread_fails", "account_reread", NOT_SENT, NOT_SENT, 0, 0),
+ ]
+ )
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.Heartbeater")
+ @patch(f"{WORKFLOW_MODULE}.fetch_org_regions", return_value={"uuid-1": "US", "uuid-2": "EU"})
+ @patch(f"{WORKFLOW_MODULE}.get_salesforce_client")
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.close_old_connections")
+ async def test_writes_billing_region_and_never_blocks_usage(
+ self,
+ _name,
+ failure,
+ expected_empty_region,
+ expected_different_region,
+ expected_filled,
+ expected_replaced,
+ _mock_close,
+ mock_get_page,
+ mock_sf_client,
+ mock_regions,
+ _mock_heartbeat,
+ ):
+ mock_get_page.return_value = [
+ {"salesforce_account_id": "001ABC", "posthog_org_id": "uuid-1"},
+ {"salesforce_account_id": "001DEF", "posthog_org_id": "uuid-2"},
+ {"salesforce_account_id": "001GHI", "posthog_org_id": "uuid-3"},
+ ]
+ if failure == "billing_lookup":
+ mock_regions.side_effect = Exception("duckgres unavailable")
+
+ mock_sf = MagicMock()
+ mock_sf.restful.return_value = {
+ "fields": [{"name": "Posthog_Org_Region__c", "updateable": failure != "field_not_writable"}]
+ }
+ if failure == "account_reread":
+ mock_sf.query_all.side_effect = Exception("Salesforce query failed")
+ mock_sf.query_all.return_value = {
+ "records": [
+ {"Id": "001ABC", "Posthog_Org_ID__c": "uuid-1", "Posthog_Org_Region__c": None},
+ {"Id": "001DEF", "Posthog_Org_ID__c": "uuid-2", "Posthog_Org_Region__c": "US"},
+ ]
+ }
+ mock_sf.bulk.Account.update.return_value = [
+ {"id": "001ABC", "success": True},
+ {"id": "001DEF", "success": True},
+ {"id": "001GHI", "success": True},
+ ]
+ mock_sf_client.return_value = mock_sf
+
+ with patch(f"{WORKFLOW_MODULE}.asyncio.to_thread", side_effect=mock_to_thread):
+ result = await enrich_org_page_activity(0, 10000, 100)
+
+ sent = {record["Id"]: record for record in mock_sf.bulk.Account.update.call_args[0][0]}
+ assert sent["001ABC"].get("Posthog_Org_Region__c", NOT_SENT) == expected_empty_region
+ assert sent["001DEF"].get("Posthog_Org_Region__c", NOT_SENT) == expected_different_region
+ assert "Posthog_Org_Region__c" not in sent["001GHI"]
+ assert result.updated == 3
+ assert result.regions_filled == expected_filled
+ assert result.regions_replaced == expected_replaced
+
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.Heartbeater")
+ @patch(f"{WORKFLOW_MODULE}.fetch_org_regions", return_value={"uuid-1": "US"})
+ @patch(f"{WORKFLOW_MODULE}.get_salesforce_client")
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.close_old_connections")
+ async def test_resends_usage_without_region_when_salesforce_rejects_the_record(
+ self, _mock_close, mock_get_page, mock_sf_client, _mock_regions, _mock_heartbeat
+ ):
+ mock_get_page.return_value = [{"salesforce_account_id": "001ABC", "posthog_org_id": "uuid-1"}]
+
+ mock_sf = MagicMock()
+ mock_sf.restful.return_value = {"fields": [{"name": "Posthog_Org_Region__c", "updateable": True}]}
+ mock_sf.query_all.return_value = {
+ "records": [{"Id": "001ABC", "Posthog_Org_ID__c": "uuid-1", "Posthog_Org_Region__c": None}]
+ }
+ mock_sf.bulk.Account.update.side_effect = [
+ [{"id": None, "success": False, "errors": ["bad value for restricted picklist field"]}],
+ [{"id": "001ABC", "success": True}],
+ ]
+ mock_sf_client.return_value = mock_sf
+
+ with patch(f"{WORKFLOW_MODULE}.asyncio.to_thread", side_effect=mock_to_thread):
+ result = await enrich_org_page_activity(0, 10000, 100)
+
+ first_attempt, resend = (call.args[0] for call in mock_sf.bulk.Account.update.call_args_list)
+ assert first_attempt[0]["Posthog_Org_Region__c"] == "US"
+ assert "Posthog_Org_Region__c" not in resend[0]
+ assert resend[0]["posthog_total_events_7d__c"] == 0
+ assert result.updated == 1
+ assert result.regions_filled == 0
+
+ @parameterized.expand(
+ [
+ ("resend_raises", Exception("Salesforce timed out"), "Salesforce timed out"),
+ ("resend_rejected", [{"id": None, "success": False, "errors": ["still bad"]}], "rejected 1 Accounts"),
+ ]
+ )
+ @pytest.mark.asyncio
+ @patch(f"{WORKFLOW_MODULE}.Heartbeater")
+ @patch(f"{WORKFLOW_MODULE}.fetch_org_regions", return_value={"uuid-1": "US"})
+ @patch(f"{WORKFLOW_MODULE}.get_salesforce_client")
+ @patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
+ @patch(f"{WORKFLOW_MODULE}.close_old_connections")
+ async def test_keeps_batch_counts_and_reports_a_failed_resend(
+ self,
+ _name,
+ resend_outcome,
+ expected_error,
+ _mock_close,
+ mock_get_page,
+ mock_sf_client,
+ _mock_regions,
+ _mock_heartbeat,
+ ):
+ mock_get_page.return_value = [
+ {"salesforce_account_id": "001ABC", "posthog_org_id": "uuid-1"},
+ {"salesforce_account_id": "001DEF", "posthog_org_id": "uuid-2"},
+ ]
+
+ mock_sf = MagicMock()
+ mock_sf.restful.return_value = {"fields": [{"name": "Posthog_Org_Region__c", "updateable": True}]}
+ mock_sf.query_all.return_value = {
+ "records": [{"Id": "001ABC", "Posthog_Org_ID__c": "uuid-1", "Posthog_Org_Region__c": None}]
+ }
+ first_attempt = [{"id": None, "success": False, "errors": ["bad value"]}, {"id": "001DEF", "success": True}]
+ mock_sf.bulk.Account.update.side_effect = [first_attempt, resend_outcome]
+ mock_sf_client.return_value = mock_sf
+
+ with patch(f"{WORKFLOW_MODULE}.asyncio.to_thread", side_effect=mock_to_thread):
+ result = await enrich_org_page_activity(0, 10000, 100)
+
+ assert result.processed == 2
+ assert result.updated == 1
+ assert len(result.errors) == 1
+ assert expected_error in result.errors[0]
+
@pytest.mark.asyncio
@patch(f"{WORKFLOW_MODULE}.Heartbeater")
@patch(f"{WORKFLOW_MODULE}.get_org_mappings_page", new_callable=AsyncMock)
@@ -367,18 +560,24 @@ class TestProductionModeContinueAsNew(TestCase):
@patch(f"{WORKFLOW_MODULE}.workflow")
async def test_returns_result_on_last_page(self, mock_workflow):
mock_workflow.execute_activity = AsyncMock(
- return_value=EnrichPageResult(page_size=5000, processed=5000, updated=4800, errors=[]),
+ return_value=EnrichPageResult(
+ page_size=5000, processed=5000, updated=4800, errors=[], regions_filled=40, regions_replaced=1
+ ),
)
mock_workflow.continue_as_new = MagicMock()
wf = SalesforceUsageEnrichmentWorkflow()
- state = UsageEnrichmentState(page_offset=10000, total_processed=10000, total_updated=9500)
+ state = UsageEnrichmentState(
+ page_offset=10000, total_processed=10000, total_updated=9500, regions_filled=60, regions_replaced=2
+ )
inputs = UsageEnrichmentInputs(batch_size=100, state=state)
result = await wf._run_production_mode(inputs)
mock_workflow.continue_as_new.assert_not_called()
assert result["total_orgs_processed"] == 15000
assert result["total_orgs_updated"] == 14300
+ assert result["regions_filled"] == 100
+ assert result["regions_replaced"] == 3
@pytest.mark.asyncio
@patch(f"{WORKFLOW_MODULE}.workflow")