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(customer-analytics): make CA the authority for AE and CSM ownership (#100044)

Abhischekfe91b52b0cf8
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.yml
index ab4ddf9f25e1..eb1adaf2b717 100644
--- a/.github/workflows/container-images-cd.yml
+++ b/.github/workflows/container-images-cd.yml
@@ -478,6 +478,7 @@ jobs:
- 'products/signals/skills/**'
- 'products/review_hog/backend/**'
- 'products/business_knowledge/backend/**'
+ - 'products/customer_analytics/backend/**'
- 'posthog/temporal/common/**'
- 'posthog/management/commands/start_temporal_worker.py'
- pyproject.toml
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 491bcd2bfb5a..1505b7923fc6 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -58,6 +58,7 @@ rules:
|Account
|AccountChannelSummary
|AccountRelationship
+ |AccountRelationshipControl
|AccountRelationshipDefinition
|AccountTrackRuleRun
|Action
@@ -477,6 +478,7 @@ rules:
|Account
|AccountChannelSummary
|AccountRelationship
+ |AccountRelationshipControl
|AccountRelationshipDefinition
|AccountTrackRuleRun
|Action
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 357e948ae37a..75f1349c8c5a 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -987,6 +987,16 @@ class TeamCustomerAnalyticsConfigSerializer(serializers.ModelSerializer, UserAcc
"account_group_type_index",
]
+ def update(
+ self, instance: TeamCustomerAnalyticsConfig, validated_data: dict[str, Any]
+ ) -> TeamCustomerAnalyticsConfig:
+ for attr, value in validated_data.items():
+ setattr(instance, attr, value)
+ # The account track rules on this row are written by their own path, so a settings save must
+ # not carry a stale copy of them back to the database.
+ instance.save(update_fields=list(validated_data))
+ return instance
+
@staticmethod
def validate_account_group_type_index(value):
return validate_group_type_index("account_group_type_index", value)
diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.py
index 59a948c4f6fa..c14173566249 100644
--- a/posthog/api/test/test_project.py
+++ b/posthog/api/test/test_project.py
@@ -11,6 +11,7 @@ from rest_framework.test import APIRequestFactory
from posthog.api.project import ProjectViewSet
from posthog.api.project_tags import MAX_TAGS_PER_FILTER
+from posthog.api.team import TeamCustomerAnalyticsConfigSerializer
from posthog.api.test.test_team import EnvironmentToProjectRewriteClient, team_api_test_factory
from posthog.constants import AvailableFeature
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -19,9 +20,11 @@ from posthog.models.person.util import get_person_by_uuid
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.project import Project
from posthog.models.tag import Tag
+from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.test.persons import create_person, delete_person
+from products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfig
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
@@ -1056,6 +1059,22 @@ class TestProjectAPI(team_api_test_factory()): # type: ignore
self.team.refresh_from_db()
self.assertEqual(self.team.customer_analytics_config.activity_event, "$pageview")
+ def test_customer_analytics_config_save_keeps_track_rules_written_meanwhile(self):
+ config = get_or_create_team_extension(self.team, TeamCustomerAnalyticsConfig)
+ serializer = TeamCustomerAnalyticsConfigSerializer(config, data={"activity_event": "$pageview"}, partial=True)
+ self.assertTrue(serializer.is_valid(), serializer.errors)
+ enabled_at = timezone.now()
+ rules = {**config.account_track_rules, "written": "meanwhile"}
+ TeamCustomerAnalyticsConfig.objects.filter(pk=config.pk).update(
+ account_track_rules=rules, account_track_rules_enabled_at=enabled_at
+ )
+
+ serializer.save()
+
+ config.refresh_from_db()
+ self.assertEqual(config.activity_event, "$pageview")
+ self.assertEqual((config.account_track_rules, config.account_track_rules_enabled_at), (rules, enabled_at))
+
def test_settings_as_of_action_available_on_projects(self):
# This action previously existed only on /api/environments/ — it must now work on /api/projects/ too.
# NOTE: we pass a `scope` filter on purpose. The unscoped snapshot path has a pre-existing bug on the
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 9056f0b67527..b0f8185f60c8 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -90,6 +90,7 @@ from products.conversations.backend.temporal.schedule import create_support_repl
from products.customer_analytics.backend.facade.temporal import (
create_account_track_rule_coordinator_schedule,
create_calendar_sync_coordinator_schedule,
+ create_ownership_claims_coordinator_schedule,
)
from products.data_quality.backend.facade.temporal import (
create_cleanup_data_quality_check_runs_schedule,
@@ -944,6 +945,7 @@ schedules = [
create_channel_summary_coordinator_schedule,
create_account_track_rule_coordinator_schedule,
create_calendar_sync_coordinator_schedule,
+ create_ownership_claims_coordinator_schedule,
create_replay_vision_reconciler_schedule,
create_replay_vision_estimates_schedule,
create_replay_vision_search_suggestions_schedule,
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 46dcf1134f85..278837362ddd 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -97,7 +97,7 @@ from products.customer_analytics.backend.facade.contracts import (
InvalidCustomPropertyOptions as InvalidCustomPropertyOptions,
)
from products.customer_analytics.backend.facade.email_matching import schedule_email_thread_link_recalculation
-from products.customer_analytics.backend.facade.enums import AccountPropertyPinKind
+from products.customer_analytics.backend.facade.enums import AccountPropertyPinKind, AccountRelationshipSource
from products.customer_analytics.backend.logic import (
account_presence as _account_presence_logic,
account_track_rules as _account_track_rules_logic,
@@ -106,6 +106,7 @@ from products.customer_analytics.backend.logic import (
custom_property_values as _custom_property_values_logic,
customer_tasks as _customer_tasks_logic,
feature_requests as _feature_requests_logic,
+ ownership as _ownership,
relationships as _relationships_logic,
user_customer_analytics_config as _user_customer_analytics_config_logic,
)
@@ -139,6 +140,7 @@ from products.customer_analytics.backend.models import (
Account,
AccountChannelSummary,
AccountRelationship,
+ AccountRelationshipControl,
AccountRelationshipDefinition,
Announcement,
CustomerJourney,
@@ -441,11 +443,20 @@ def _to_external_account(account: Account) -> contracts.ExternalAccount:
``custom_properties`` includes every team definition keyed by name, with the
account's active value (scalar) or ``None`` when unset, so workflow result
paths are deterministic regardless of whether the property has been set.
+
+ ``relationships`` lists active assignments to current members of the team's
+ organization, as the list route does, so a holder who left is not named here
+ while the ``ownership`` block withholds their email.
"""
relationships: dict[str, list[dict]] = {}
for relationship in (
AccountRelationship.objects.for_team(account.team_id)
- .filter(account=account, ended_at__isnull=True, user__isnull=False)
+ .filter(
+ account=account,
+ ended_at__isnull=True,
+ user__isnull=False,
+ user__organization_membership__organization_id=account.team.organization_id,
+ )
.select_related("definition", "user")
.order_by("definition__name", "user__email")
):
@@ -473,6 +484,7 @@ def _to_external_account(account: Account) -> contracts.ExternalAccount:
churned_at=account.churned_at,
ignored_at=account.ignored_at,
properties=account.properties.model_dump(mode="json"),
+ ownership=_ownership.ownership_for_account(account),
tags=sorted(account.tagged_items.values_list("tag__name", flat=True)),
relationships=relationships,
custom_properties=custom_properties,
@@ -595,6 +607,7 @@ def list_external_accounts(
limit: int = 100,
assigned_only: bool = False,
include_ignored: bool = False,
+ managed_only: bool = False,
) -> contracts.ExternalAccountListPage:
"""Page through the team's accounts for the external API, ordered by id.
@@ -603,9 +616,13 @@ def list_external_accounts(
it. Only active relationship assignments to current members of the team's
organization are exposed. With ``assigned_only``, only accounts holding at
least one such assignment are returned; a consumer reconciling by absence
- still sees the complete assigned set. Assignments mirror the single-account
- endpoint's ``relationships`` shape (keyed by definition name), with the
- user's current display name added.
+ still sees the complete assigned set. With ``managed_only``, only accounts
+ where customer analytics holds authority over at least one controlled
+ relationship are returned, cleared ones and ignored accounts included, so
+ an ownership poller reads its whole cohort without paging through unmanaged
+ accounts and never mistakes an ignored account for a missing one.
+ Assignments mirror the single-account endpoint's ``relationships`` shape
+ (keyed by definition name), with the user's current display name added.
"""
active_relationships = AccountRelationship.objects.for_team(team_id).filter(
ended_at__isnull=True,
@@ -613,16 +630,21 @@ def list_external_accounts(
user__organization_membership__organization_id=organization_id,
)
queryset = Account.objects.for_team(team_id).filter(external_id__isnull=False).exclude(external_id="")
- if not include_ignored:
+ if not include_ignored and not managed_only:
queryset = queryset.filter(ignored_at__isnull=True)
queryset = queryset.order_by("id")
if assigned_only:
queryset = queryset.filter(Exists(active_relationships.filter(account=OuterRef("pk"))))
+ if managed_only:
+ queryset = queryset.filter(
+ Exists(AccountRelationshipControl.objects.for_team(team_id).filter(account=OuterRef("pk")))
+ )
if cursor:
queryset = queryset.filter(id__gt=cursor)
page_accounts = list(queryset[: limit + 1])
accounts = page_accounts[:limit]
+ ownership_by_account = _ownership.ownership_for_accounts(team_id, organization_id, accounts)
relationships_by_account: dict[UUID, dict[str, list[contracts.ExternalAccountAssignment]]] = {}
for relationship in (
@@ -648,6 +670,7 @@ def list_external_accounts(
name=account.name,
churned_at=account.churned_at,
ignored_at=account.ignored_at,
+ ownership=ownership_by_account[account.id],
relationships=relationships_by_account.get(account.id, {}),
)
for account in accounts
@@ -684,7 +707,9 @@ def _apply_external_relationship_assignments(
active assignment). Each non-None user id is resolved against an
``OrganizationMembership`` in the account's org so assignees are always trusted.
Everything is validated before the first write — the caller's ``atomic()`` block
- returns (commits) on an error result rather than rolling back.
+ returns (commits) on an error result rather than rolling back. A workflow is an
+ autonomous writer, so a controlled relationship the account manages raises
+ ``ManagedRolePolicyError`` from the relationship service and rolls the block back.
"""
keys_to_ids: dict[str, UUID] = {}
for key in assignments:
@@ -726,22 +751,15 @@ def _apply_external_relationship_assignments(
)
resolved.append((definition, membership.user))
+ actor = _relationships_logic.Actor(source=AccountRelationshipSource.WORKFLOW, workflow_id=workflow_id)
for definition, assignee in resolved:
if assignee is None:
_relationships_logic.end_active(
- team_id=account.team_id,
- account=account,
- definition=definition,
- workflow_id=workflow_id,
+ team_id=account.team_id, account=account, definition=definition, actor=actor
)
else:
_relationships_logic.assign(
- team_id=account.team_id,
- account=account,
- definition=definition,
- user=assignee,
- created_by=None,
- workflow_id=workflow_id,
+ team_id=account.team_id, account=account, definition=definition, user=assignee, actor=actor
)
return None
@@ -787,6 +805,8 @@ def update_external_account(
_apply_external_tags(account, tags, tags_mode, workflow_id=workflow_id)
if churned_at_provided:
update_account(account, churned_at=churned_at)
+ except _relationships_logic.ManagedRolePolicyError:
+ return contracts.ExternalAccountUpdateResult(error=contracts.ExternalAccountUpdateError.ROLE_MANAGED)
except Exception as e:
capture_exception(e, {"team_id": team_id, "external_id": external_id, "account_id": str(account.id)})
return contracts.ExternalAccountUpdateResult(error=contracts.ExternalAccountUpdateError.UPDATE_FAILED)
@@ -3606,17 +3626,29 @@ def delete_account_for_view(
) -> None:
account = _get_account_for_detail(team_id, account_id)
_enforce_object_access(account, user_access_control, required_level)
- _log_activity_swallowing(
- instance=account,
- scope="Account",
- activity="deleted",
- name=account.name,
- organization_id=organization_id,
- team_id=team_id,
- user=user,
- was_impersonated=was_impersonated,
- )
with transaction.atomic():
+ # Authority is checked under the same account lock enrollment and claims take, so an account
+ # that became managed a moment ago cannot be deleted on a stale read. The definitions its rows
+ # sit under are locked too, so none can become controlled before the cascade runs.
+ locked, definitions = _relationships_logic.lock_account_and_its_definitions(team_id, account.id)
+ if locked is None:
+ raise Account.DoesNotExist
+ is_managed = AccountRelationshipControl.objects.for_team(team_id).filter(account=locked).exists()
+ # The cascade would take relationship rows with it, so rows under a controlled definition
+ # refuse the account's deletion the way they refuse their own.
+ has_controlled_history = any(definition.is_controlled for definition in definitions)
+ if is_managed or has_controlled_history:
+ raise AccountOwnershipManagedError(account_id)
+ _log_activity_swallowing(
+ instance=account,
+ scope="Account",
+ activity="deleted",
+ name=account.name,
+ organization_id=organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ )
# Streams referencing this account must be captured before the delete cascades
# their membership rows away, then resynced so the account's group key doesn't
# linger in a Slack destination filter.
@@ -4529,6 +4561,33 @@ class AccountRelationshipDefinitionConflictError(Exception):
"""Raised when a relationship definition violates the per-team unique name constraint."""
+class AccountRelationshipDefinitionControlledError(Exception):
+ """The definition is controlled, so it can be neither deleted nor made multi-holder until control
+ ends."""
+
+
+class AccountRelationshipProtectedError(Exception):
+ """The relationship row belongs to a controlled definition's history and cannot be hard-deleted."""
+
+
+class AccountOwnershipManagedError(Exception):
+ """The account manages a controlled relationship or carries relationship rows under a controlled
+ definition, so it cannot be deleted."""
+
+
+class AccountRelationshipRoleManagedError(Exception):
+ """An agent acting for a person reached a controlled relationship the account manages; only the
+ person may change it."""
+
+
+def _project_api_actor(user: "User | None", via_agent: bool) -> _relationships_logic.Actor:
+ """A person's own request, or an agent acting for them through the MCP server. An agent counts
+ as an autonomous writer, like the in-app AI tool, so it cannot transfer or clear a managed
+ relationship."""
+ source = AccountRelationshipSource.AI if via_agent else AccountRelationshipSource.HUMAN
+ return _relationships_logic.Actor(source=source, user=user)
+
+
def _to_account_relationship_definition(
definition: AccountRelationshipDefinition,
) -> contracts.AccountRelationshipDefinition:
@@ -4537,6 +4596,7 @@ def _to_account_relationship_definition(
name=definition.name,
description=definition.description,
is_single_holder=definition.is_single_holder,
+ is_controlled=definition.is_controlled,
)
@@ -4548,6 +4608,7 @@ def _to_account_relationship(relationship: AccountRelationship) -> contracts.Acc
user=contracts.AccountAssignment(id=user.id, email=user.email) if user is not None else None,
started_at=relationship.started_at,
ended_at=relationship.ended_at,
+ source=cast(contracts.RelationshipSourceValue | None, relationship.source),
)
@@ -4592,28 +4653,47 @@ def get_account_relationship_definition(
return _to_account_relationship_definition(definition)
+_DEFINITION_EDITABLE_FIELDS = frozenset({"name", "description", "is_single_holder"})
+
+
def update_account_relationship_definition(
*, team_id: int, definition_id: str | UUID, fields: dict[str, Any]
) -> contracts.AccountRelationshipDefinition | None:
- definition = AccountRelationshipDefinition.objects.for_team(team_id).filter(id=definition_id).first()
- if definition is None:
- return None
- for attr, value in fields.items():
- setattr(definition, attr, value)
- try:
- definition.save()
- except IntegrityError:
- raise AccountRelationshipDefinitionConflictError(
- "A relationship definition with this name already exists for this team."
- )
+ """Rename or describe a definition, or change its cardinality. Whether it is controlled is not an
+ edit: it changes only through ``ownership.set_controlled``, which holds the guards."""
+ unexpected = set(fields) - _DEFINITION_EDITABLE_FIELDS
+ if unexpected:
+ raise ValueError(f"Fields cannot be edited here: {', '.join(sorted(unexpected))}")
+ with transaction.atomic():
+ # The definition lock keeps control from starting between this check and the save.
+ definition = _ownership.lock_definition(team_id, definition_id)
+ if definition is None:
+ return None
+ if fields.get("is_single_holder") is False and definition.is_controlled:
+ raise AccountRelationshipDefinitionControlledError(str(definition_id))
+ for attr, value in fields.items():
+ setattr(definition, attr, value)
+ try:
+ definition.save(update_fields=[*fields, "updated_at"])
+ except IntegrityError:
+ raise AccountRelationshipDefinitionConflictError(
+ "A relationship definition with this name already exists for this team."
+ )
return _to_account_relationship_definition(definition)
def delete_account_relationship_definition(*, team_id: int, definition_id: str | UUID) -> bool:
"""Hard-deletes the definition and (by cascade) its assignment history. Returns False when
- no definition matches the id for this team (→ 404)."""
- deleted, _ = AccountRelationshipDefinition.objects.for_team(team_id).filter(id=definition_id).delete()
- return deleted > 0
+ no definition matches the id for this team (→ 404). A controlled definition raises instead."""
+ with transaction.atomic():
+ # Locked, so control cannot start between the check and the delete.
+ definition = _ownership.lock_definition(team_id, definition_id)
+ if definition is None:
+ return False
+ if definition.is_controlled:
+ raise AccountRelationshipDefinitionControlledError(str(definition_id))
+ definition.delete()
+ return True
def list_account_relationships(
@@ -4640,14 +4720,21 @@ class AccountRelationshipAssigneeNotInOrganization(Exception):
def assign_account_relationship(
- *, team_id: int, account_id: str | UUID, definition_id: str | UUID, user_id: int, created_by: "User"
+ *,
+ team_id: int,
+ account_id: str | UUID,
+ definition_id: str | UUID,
+ user_id: int,
+ created_by: "User",
+ via_agent: bool = False,
) -> contracts.AccountRelationship:
"""Assign a user to an account relationship. Single-holder definitions hand off — the
previous active assignment is ended in the same transaction. Idempotent when the user
already actively holds the relationship.
Raises ``Account_DoesNotExist`` (→ 404), ``AccountRelationshipDefinitionNotFound`` and
- ``AccountRelationshipAssigneeNotInOrganization`` (→ 400).
+ ``AccountRelationshipAssigneeNotInOrganization`` (→ 400), and ``AccountRelationshipRoleManagedError``
+ (→ 409) when an agent acting for the user reaches a controlled relationship the account manages.
"""
account = Account.objects.for_team(team_id).select_related("team").get(id=account_id)
definition = AccountRelationshipDefinition.objects.for_team(team_id).filter(id=definition_id).first()
@@ -4660,9 +4747,16 @@ def assign_account_relationship(
)
if membership is None:
raise AccountRelationshipAssigneeNotInOrganization(str(user_id))
- relationship = _relationships_logic.assign(
- team_id=team_id, account=account, definition=definition, user=membership.user, created_by=created_by
- )
+ try:
+ relationship = _relationships_logic.assign(
+ team_id=team_id,
+ account=account,
+ definition=definition,
+ user=membership.user,
+ actor=_project_api_actor(created_by, via_agent),
+ )
+ except _relationships_logic.ManagedRolePolicyError:
+ raise AccountRelationshipRoleManagedError(str(definition_id))
return _to_account_relationship(relationship)
@@ -4672,6 +4766,7 @@ def end_account_relationship(
account_id: str | UUID,
relationship_id: str | UUID,
actor: "User | None" = None,
+ via_agent: bool = False,
) -> contracts.AccountRelationship | None:
"""End an active assignment. Returns None when no active assignment matches this account
(missing, another account's, or already ended) — mapped to 404."""
@@ -4680,10 +4775,12 @@ def end_account_relationship(
team_id=team_id,
account_id=account_id,
relationship_id=str(relationship_id),
- actor=actor,
+ actor=_project_api_actor(actor, via_agent),
)
except _relationships_logic.AccountRelationshipNotFound:
return None
+ except _relationships_logic.ManagedRolePolicyError:
+ raise AccountRelationshipRoleManagedError(str(relationship_id))
return _to_account_relationship(relationship)
@@ -4693,16 +4790,19 @@ def delete_account_relationship(
account_id: str | UUID,
relationship_id: str | UUID,
actor: "User | None" = None,
+ via_agent: bool = False,
) -> bool:
try:
_relationships_logic.delete_relationship(
team_id=team_id,
account_id=account_id,
relationship_id=str(relationship_id),
- actor=actor,
+ actor=_project_api_actor(actor, via_agent),
)
except _relationships_logic.AccountRelationshipNotFound:
return False
+ except _relationships_logic.ProtectedRelationshipHistoryError:
+ raise AccountRelationshipProtectedError(str(relationship_id))
return True
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index a6d86de7f463..28261399e4a2 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -50,6 +50,7 @@ class AccountRelationshipDefinition:
name: str = ""
description: str | None = None
is_single_holder: bool = True
+ is_controlled: bool = False
@dataclass(frozen=True)
@@ -63,15 +64,20 @@ class UserCustomerAnalyticsConfig:
pinned_properties: list[PinnedAccountProperty] = field(default_factory=list)
+RelationshipSourceValue = Literal["human", "workflow", "ai", "salesforce_claim", "migration"]
+
+
@dataclass(frozen=True)
class AccountRelationship:
- """One assignment of a user to an account relationship, with its effective range."""
+ """One assignment of a user to an account relationship, with its effective range and which kind
+ of writer started it (None on rows written before provenance was recorded)."""
id: UUID
definition: AccountRelationshipDefinition
user: AccountAssignment | None
started_at: datetime
ended_at: datetime | None
+ source: RelationshipSourceValue | None = None
@dataclass(frozen=True)
@@ -541,11 +547,110 @@ class ExternalAccount:
churned_at: datetime | None
ignored_at: datetime | None
properties: dict
+ ownership: "ExternalAccountOwnership"
tags: list[str] = field(default_factory=list)
relationships: dict[str, list[dict]] = field(default_factory=dict)
custom_properties: dict[str, float | bool | str | None] = field(default_factory=dict)
+@dataclass(frozen=True)
+class ExternalAccountOwnershipHolder:
+ """The user holding a controlled relationship, with the checks a consumer needs before projecting them."""
+
+ user_id: int
+ email: str | None
+ name: str | None
+ is_organization_member: bool
+ is_active: bool
+
+
+OwnershipRoleStateValue = Literal["unmanaged", "assigned", "cleared", "blocked"]
+OwnershipRoleDiagnosticValue = Literal[
+ "holder_missing",
+ "holder_inactive",
+ "holder_not_in_organization",
+ "multiple_active_holders",
+]
+
+
+@dataclass(frozen=True)
+class ExternalAccountRoleOwnership:
+ """One controlled relationship on one account.
+
+ ``state`` is what the consumer may act on: ``unmanaged`` keeps legacy authority whatever the
+ rows say, ``assigned`` and ``cleared`` are authoritative, and ``blocked`` means the holder
+ cannot be projected and the consumer keeps its last applied value. ``diagnostics`` explain a
+ block and are informational on an unmanaged role.
+ """
+
+ definition_id: UUID
+ definition_name: str
+ state: OwnershipRoleStateValue
+ controlled_at: datetime | None
+ relationship_id: UUID | None
+ holder: ExternalAccountOwnershipHolder | None
+ diagnostics: list[OwnershipRoleDiagnosticValue] = field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class ExternalAccountOwnership:
+ """Canonical identity plus every controlled relationship of the team, on the external wire
+ shape. Consumers map ``definition_id`` to the roles they project."""
+
+ account_id: str
+ external_id: str | None
+ region: str | None
+ roles: list[ExternalAccountRoleOwnership]
+
+
+OwnershipClaimOutcome = Literal["accepted", "already_applied", "cleared", "not_held", "rejected", "blocked"]
+OwnershipClaimReason = Literal[
+ "account_not_found",
+ "binding_changed",
+ "role_not_managed",
+ "identity_mismatch",
+ "assignee_not_member",
+ "role_occupied",
+ "stale_allocation",
+ "future_allocation",
+]
+
+
+@dataclass(frozen=True)
+class OwnershipClaimDecision:
+ """An eligible initial allocation as frozen on a Salesforce Task, read from the warehouse.
+
+ The Task id (``source_ref``) is the idempotency key. A Task that has since been disqualified
+ carries ``released_at`` and who released it; that row withdraws the same Task's claim.
+ """
+
+ source_ref: str
+ organization_id: str
+ region: str
+ assignee_user_id: int
+ source_assignee_id: str
+ allocated_at: datetime
+ released_at: datetime | None = None
+ source_releaser_id: str | None = None
+
+ @property
+ def is_release(self) -> bool:
+ return self.released_at is not None
+
+
+@dataclass(frozen=True)
+class OwnershipClaimResult:
+ """What customer analytics did with a decision. ``rejected`` and ``blocked`` carry a reason;
+ ``blocked`` means the decision may apply after review, ``rejected`` that it does not apply as
+ read. Refusals are not stored, so every sweep evaluates the Task again; in practice only an
+ allocation that was still in the future can turn into an acceptance."""
+
+ outcome: OwnershipClaimOutcome
+ reason: OwnershipClaimReason | None
+ relationship_id: UUID | None
+ controlled_at: datetime | None
+
+
@dataclass(frozen=True)
class ExternalAccountAssignment:
"""An active relationship assignment on the external list wire shape.
@@ -569,6 +674,7 @@ class ExternalAccountListItem:
name: str
churned_at: datetime | None
ignored_at: datetime | None
+ ownership: ExternalAccountOwnership
relationships: dict[str, list[ExternalAccountAssignment]] = field(default_factory=dict)
@@ -588,6 +694,7 @@ class ExternalAccountUpdateError(Enum):
NOT_FOUND = "not_found"
USER_NOT_IN_ORGANIZATION = "user_not_in_organization"
RELATIONSHIP_DEFINITION_NOT_FOUND = "relationship_definition_not_found"
+ ROLE_MANAGED = "role_managed"
INVALID_PROPERTIES = "invalid_properties"
UPDATE_FAILED = "update_failed"
diff --git a/products/customer_analytics/backend/facade/enums.py b/products/customer_analytics/backend/facade/enums.py
index 46c05aa6eb8f..c392566dfa5d 100644
--- a/products/customer_analytics/backend/facade/enums.py
+++ b/products/customer_analytics/backend/facade/enums.py
@@ -1,6 +1,46 @@
from enum import Enum
+from django.db import models
+
class AccountPropertyPinKind(str, Enum):
CUSTOM_PROPERTY = "custom_property"
RELATIONSHIP = "relationship"
+
+
+class AccountRelationshipSource(models.TextChoices):
+ """Which kind of writer created or ended a relationship row. Rows written before provenance
+ was recorded carry NULL."""
+
+ HUMAN = "human", "Human"
+ WORKFLOW = "workflow", "Workflow"
+ AI = "ai", "AI"
+ SALESFORCE_CLAIM = "salesforce_claim", "Salesforce claim"
+ MIGRATION = "migration", "Migration"
+
+
+class OwnershipRoleState(models.TextChoices):
+ """What a consumer may conclude about a controlled relationship on one account."""
+
+ # No control row: legacy authority holds, whatever the relationship rows say.
+ UNMANAGED = "unmanaged", "Unmanaged"
+ ASSIGNED = "assigned", "Assigned"
+ # Managed with no active holder: an explicit decision that the role is empty.
+ CLEARED = "cleared", "Cleared"
+ # Managed, but the holder cannot be projected; consumers keep their last applied value.
+ BLOCKED = "blocked", "Blocked"
+
+
+class OwnershipRoleDiagnostic(models.TextChoices):
+ HOLDER_MISSING = "holder_missing", "The active relationship has no user"
+ HOLDER_INACTIVE = "holder_inactive", "The holder's user account is deactivated"
+ HOLDER_NOT_IN_ORGANIZATION = "holder_not_in_organization", "The holder is not a member of the organization"
+ MULTIPLE_ACTIVE_HOLDERS = "multiple_active_holders", "More than one active relationship holds the role"
+
+
+__all__ = [
+ "AccountPropertyPinKind",
+ "AccountRelationshipSource",
+ "OwnershipRoleDiagnostic",
+ "OwnershipRoleState",
+]
diff --git a/products/customer_analytics/backend/facade/temporal.py b/products/customer_analytics/backend/facade/temporal.py
index 08da88800f36..d61e48b859c1 100644
--- a/products/customer_analytics/backend/facade/temporal.py
+++ b/products/customer_analytics/backend/facade/temporal.py
@@ -12,6 +12,7 @@ from products.customer_analytics.backend.temporal.account_track_rules import (
create_account_track_rule_coordinator_schedule,
)
from products.customer_analytics.backend.temporal.calendar_sync import create_calendar_sync_coordinator_schedule
+from products.customer_analytics.backend.temporal.ownership_claims import create_ownership_claims_coordinator_schedule
__all__ = [
"ACCOUNT_PROPERTY_SYNC_ACTIVITIES",
@@ -21,5 +22,6 @@ __all__ = [
"AccountPropertySyncInput",
"create_account_track_rule_coordinator_schedule",
"create_calendar_sync_coordinator_schedule",
+ "create_ownership_claims_coordinator_schedule",
"stage_warehouse_account_property_files_activity",
]
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_account_audience.py b/products/customer_analytics/backend/hogql_queries/test/test_account_audience.py
index 5f8bfcc88016..6ab4ebb166ff 100644
--- a/products/customer_analytics/backend/hogql_queries/test/test_account_audience.py
+++ b/products/customer_analytics/backend/hogql_queries/test/test_account_audience.py
@@ -81,7 +81,11 @@ class TestAccountAudience(ClickhouseTestMixin, NonAtomicBaseTest):
team_id=self.team.id, name="CSM"
)
relationships_logic.assign(
- team_id=self.team.id, account=assigned, definition=definition, user=holder, created_by=holder
+ team_id=self.team.id,
+ account=assigned,
+ definition=definition,
+ user=holder,
+ actor=relationships_logic.Actor.human(holder),
)
assert self._list(AccountAudienceFilters(assignment_status="all")) == ["assigned", "unassigned"]
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
index c5960ab952e3..5b78d848a53e 100644
--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
@@ -155,7 +155,11 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
team_id=self.team.id, name=definition_name
)
return relationships_logic.assign(
- team_id=self.team.id, account=account, definition=definition, user=user, created_by=user
+ team_id=self.team.id,
+ account=account,
+ definition=definition,
+ user=user,
+ actor=relationships_logic.Actor.human(user),
)
def test_all_roles_unassigned(self):
@@ -165,7 +169,10 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
previously_assigned = create_account(team_id=self.team.id, name="Previously assigned")
rel = self._assign(previously_assigned, holder)
relationships_logic.end_relationship(
- team_id=self.team.id, account_id=str(previously_assigned.id), relationship_id=str(rel.id)
+ team_id=self.team.id,
+ account_id=str(previously_assigned.id),
+ relationship_id=str(rel.id),
+ actor=relationships_logic.Actor.human(),
)
never_assigned = create_account(team_id=self.team.id, name="Never assigned")
@@ -220,7 +227,10 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
account = create_account(team_id=self.team.id, name="Handed off")
rel = self._assign(account, holder)
relationships_logic.end_relationship(
- team_id=self.team.id, account_id=str(account.id), relationship_id=str(rel.id)
+ team_id=self.team.id,
+ account_id=str(account.id),
+ relationship_id=str(rel.id),
+ actor=relationships_logic.Actor.human(),
)
self.assertEqual(self._ids(assignedToUserIds=[holder.id]), [])
@@ -277,7 +287,11 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
team_id=other_team.id, name="CSM"
)
relationships_logic.assign(
- team_id=other_team.id, account=theirs, definition=their_definition, user=holder, created_by=holder
+ team_id=other_team.id,
+ account=theirs,
+ definition=their_definition,
+ user=holder,
+ actor=relationships_logic.Actor.human(holder),
)
mine = create_account(team_id=self.team.id, name="Mine")
self._assign(mine, holder)
diff --git a/products/customer_analytics/backend/logic/ownership.py b/products/customer_analytics/backend/logic/ownership.py
new file mode 100644
index 000000000000..4a5e07723346
--- /dev/null
+++ b/products/customer_analytics/backend/logic/ownership.py
@@ -0,0 +1,273 @@
+"""
+Controlled relationships on accounts: which relationship definitions customer analytics may take
+control of for a team, which accounts each is controlled on, the per-(account, definition) control
+timestamp that fences automated claims, and the ownership block the external API exposes.
+Per-account mutations reach this module from ``logic/relationships.py`` under the Account row lock.
+Whether a definition is controlled at all changes only through ``set_controlled``, under the
+definition lock.
+"""
+
+import json
+import hashlib
+from collections import defaultdict
+from collections.abc import Collection, Sequence
+from datetime import datetime, timedelta
+from typing import cast
+from uuid import UUID
+
+from django.db import transaction
+from django.db.models import F, QuerySet
+from django.db.models.functions import Greatest, Now
+from django.utils import timezone
+
+from posthog.models.organization import OrganizationMembership
+from posthog.models.user import User
+from posthog.utils import get_instance_region
+
+from products.customer_analytics.backend.facade import contracts
+from products.customer_analytics.backend.facade.enums import OwnershipRoleDiagnostic
+from products.customer_analytics.backend.models import (
+ Account,
+ AccountRelationship,
+ AccountRelationshipControl,
+ AccountRelationshipDefinition,
+)
+
+# An automated claim must be later than the fence by more than this, so a clock difference between
+# the allocation source and this database cannot make a stale decision look fresh.
+CLAIM_CLOCK_SKEW_TOLERANCE = timedelta(minutes=5)
+
+
+class InvalidControlChangeError(Exception):
+ """The definition cannot take or give up control: wrong team, multi-holder, accounts still
+ enrolled under it, or a claim view bound to it."""
+
+
+def controlled_definitions(team_id: int) -> QuerySet[AccountRelationshipDefinition]:
+ return AccountRelationshipDefinition.objects.for_team(team_id).filter(is_controlled=True).order_by("name")
+
+
+def lock_definitions(team_id: int, definition_ids: Collection[str | UUID]) -> list[AccountRelationshipDefinition]:
+ """The definitions, read under their row locks and taken in id order so two callers with
+ overlapping sets never wait on each other; call inside ``transaction.atomic()``.
+
+ Enrollment and control changes take this lock so ``is_controlled`` cannot flip between a check
+ and the write that relied on it. ``no_key`` keeps it compatible with the ``FOR KEY SHARE`` lock a
+ relationship insert takes on its definition, so a writer holding the account lock never waits on
+ this one and the two cannot deadlock."""
+ return list(
+ AccountRelationshipDefinition.objects.for_team(team_id)
+ .select_for_update(no_key=True)
+ .filter(id__in=definition_ids)
+ .order_by("id")
+ )
+
+
+def lock_definition(team_id: int, definition_id: str | UUID) -> AccountRelationshipDefinition | None:
+ """One definition under its row lock, or None where the team has no such definition."""
+ locked = lock_definitions(team_id, [definition_id])
+ return locked[0] if locked else None
+
+
+def set_controlled(team_id: int, definition_id: UUID, controlled: bool) -> AccountRelationshipDefinition:
+ """Let customer analytics take control of the definition per account, or stop it.
+
+ Taking control enrolls no account. Giving it up is refused while any account is enrolled, because
+ those accounts would fall back to legacy authority at once, and while a claim view is bound to the
+ definition, because a claim can only fill a controlled relationship.
+ """
+ with transaction.atomic():
+ definition = lock_definition(team_id, definition_id)
+ if definition is None:
+ raise InvalidControlChangeError(f"No relationship definition {definition_id} in this project")
+ if definition.is_controlled == controlled:
+ return definition
+ if controlled and not definition.is_single_holder:
+ raise InvalidControlChangeError(
+ f"{definition.name} allows several holders; a controlled relationship needs one"
+ )
+ if not controlled:
+ enrolled = AccountRelationshipControl.objects.for_team(team_id).filter(definition=definition).count()
+ if enrolled:
+ raise InvalidControlChangeError(
+ f"{enrolled} account(s) are enrolled under {definition.name}; control cannot end while they are"
+ )
+ if definition.claim_saved_query_id is not None:
+ raise InvalidControlChangeError(f"{definition.name} has a claim view bound; clear that binding first")
+ definition.is_controlled = controlled
+ definition.save(update_fields=["is_controlled", "updated_at"])
+ return definition
+
+
+def control_for(account: Account, definition: AccountRelationshipDefinition) -> AccountRelationshipControl | None:
+ """The account's control row for the definition, or None while the relationship is unmanaged
+ there. The row's presence is authoritative, not the caller's copy of ``is_controlled``, which was
+ read before the account lock and may predate an enrollment that has since committed. Read it under
+ the Account lock when the caller will act on it."""
+ return (
+ AccountRelationshipControl.objects.for_team(account.team_id)
+ .filter(account=account, definition=definition)
+ .first()
+ )
+
+
+def enroll(
+ account: Account, definition: AccountRelationshipDefinition, created_by: User | None
+) -> AccountRelationshipControl:
+ """Create the control row, timed by the database clock like every later advance. Call under the
+ definition and Account locks."""
+ control = AccountRelationshipControl.objects.for_team(account.team_id).create(
+ team_id=account.team_id,
+ account=account,
+ definition=definition,
+ created_by=created_by,
+ controlled_at=Now(),
+ )
+ control.refresh_from_db(fields=["controlled_at"])
+ return control
+
+
+def advance(control: AccountRelationshipControl) -> datetime:
+ """Record a new decision on the controlled relationship and return its instant.
+
+ Call while holding the Account row lock. The value comes from the database clock and is
+ strictly later than the previous one, so two decisions in quick succession never share a fence
+ and a claim can never be exactly equal to it.
+ """
+ queryset = AccountRelationshipControl.objects.for_team(control.team_id).filter(pk=control.pk)
+ queryset.update(controlled_at=Greatest(Now(), F("controlled_at") + timedelta(microseconds=1)))
+ control.controlled_at = queryset.values_list("controlled_at", flat=True).get()
+ return control.controlled_at
+
+
+def ownership_for_accounts(
+ team_id: int, organization_id: UUID, accounts: Sequence[Account]
+) -> dict[UUID, contracts.ExternalAccountOwnership]:
+ """The ownership block for each account, read in one pass so a page of the external list costs
+ a fixed number of queries."""
+ definitions = list(controlled_definitions(team_id))
+ controls: dict[tuple[UUID, UUID], AccountRelationshipControl] = {}
+ active_by_account_and_definition: dict[tuple[UUID, UUID], list[AccountRelationship]] = defaultdict(list)
+ if definitions and accounts:
+ for control in AccountRelationshipControl.objects.for_team(team_id).filter(
+ account__in=accounts, definition__in=definitions
+ ):
+ controls[(control.account_id, control.definition_id)] = control
+ for relationship in (
+ AccountRelationship.objects.for_team(team_id)
+ .filter(account__in=accounts, definition__in=definitions, ended_at__isnull=True)
+ .select_related("user")
+ .order_by("started_at")
+ ):
+ active_by_account_and_definition[(relationship.account_id, relationship.definition_id)].append(relationship)
+ holder_user_ids = {
+ relationship.user_id
+ for rows in active_by_account_and_definition.values()
+ for relationship in rows
+ if relationship.user_id is not None
+ }
+ member_user_ids = set(
+ OrganizationMembership.objects.filter(organization_id=organization_id, user_id__in=holder_user_ids).values_list(
+ "user_id", flat=True
+ )
+ )
+ region = get_instance_region()
+ return {
+ account.id: contracts.ExternalAccountOwnership(
+ account_id=str(account.id),
+ external_id=account.external_id,
+ region=region.lower() if region else None,
+ roles=[
+ _role_ownership(
+ definition,
+ controls.get((account.id, definition.id)),
+ active_by_account_and_definition.get((account.id, definition.id), []),
+ member_user_ids,
+ )
+ for definition in definitions
+ ],
+ )
+ for account in accounts
+ }
+
+
+def ownership_for_account(account: Account) -> contracts.ExternalAccountOwnership:
+ return ownership_for_accounts(account.team_id, account.team.organization_id, [account])[account.id]
+
+
+def _role_ownership(
+ definition: AccountRelationshipDefinition,
+ control: AccountRelationshipControl | None,
+ active: list[AccountRelationship],
+ member_user_ids: set[int],
+) -> contracts.ExternalAccountRoleOwnership:
+ diagnostics: list[OwnershipRoleDiagnostic] = []
+ if len(active) > 1:
+ diagnostics.append(OwnershipRoleDiagnostic.MULTIPLE_ACTIVE_HOLDERS)
+
+ relationship = active[0] if active else None
+ holder = None
+ if relationship is not None:
+ user = relationship.user
+ if user is None:
+ diagnostics.append(OwnershipRoleDiagnostic.HOLDER_MISSING)
+ else:
+ is_member = user.id in member_user_ids
+ if not user.is_active:
+ diagnostics.append(OwnershipRoleDiagnostic.HOLDER_INACTIVE)
+ if not is_member:
+ diagnostics.append(OwnershipRoleDiagnostic.HOLDER_NOT_IN_ORGANIZATION)
+ # The single-account route also answers to the team token, so a holder outside the
+ # organization is identified by id only, as the `relationships` field already does.
+ holder = contracts.ExternalAccountOwnershipHolder(
+ user_id=user.id,
+ email=user.email if is_member else None,
+ name=(f"{user.first_name} {user.last_name}".strip() or None) if is_member else None,
+ is_organization_member=is_member,
+ is_active=user.is_active,
+ )
+
+ state: contracts.OwnershipRoleStateValue
+ if control is None:
+ state = "unmanaged"
+ elif diagnostics:
+ state = "blocked"
+ elif relationship is None:
+ state = "cleared"
+ else:
+ state = "assigned"
+
+ return contracts.ExternalAccountRoleOwnership(
+ definition_id=definition.id,
+ definition_name=definition.name,
+ state=state,
+ controlled_at=control.controlled_at if control is not None else None,
+ relationship_id=relationship.id if relationship is not None else None,
+ holder=holder,
+ diagnostics=[cast(contracts.OwnershipRoleDiagnosticValue, str(diagnostic)) for diagnostic in diagnostics],
+ )
+
+
+def canonical_digest(payload: dict) -> str:
+ """SHA-256 of a payload serialized key-order-independently, so the same facts always digest the
+ same. Every value must be JSON-serializable."""
+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
+ return hashlib.sha256(canonical.encode()).hexdigest()
+
+
+def region_matches(region: str) -> bool:
+ """A self-hosted or test instance has no region to check against; cloud instances require the
+ decision to name theirs."""
+ instance_region = get_instance_region()
+ return instance_region is None or region == instance_region.lower()
+
+
+def allocation_rejection(allocated_at: datetime, fence: datetime | None) -> contracts.OwnershipClaimReason | None:
+ """Why the allocation time cannot be trusted, or None when it can. It must be later than the fence
+ by more than the clock-skew allowance and no further in the future than that same allowance;
+ equal or uncertain ordering is rejected, because waiting cannot make the same decision newer."""
+ if allocated_at > timezone.now() + CLAIM_CLOCK_SKEW_TOLERANCE:
+ return "future_allocation"
+ if fence is not None and allocated_at <= fence + CLAIM_CLOCK_SKEW_TOLERANCE:
+ return "stale_allocation"
+ return None
diff --git a/products/customer_analytics/backend/logic/ownership_adoption.py b/products/customer_analytics/backend/logic/ownership_adoption.py
new file mode 100644
index 000000000000..8a8f7b728fbd
--- /dev/null
+++ b/products/customer_analytics/backend/logic/ownership_adoption.py
@@ -0,0 +1,202 @@
+"""
+Reviewed adoption of controlled relationships from a private manifest. Each proposal names the
+account, the definition, the state a reviewer settled on and a fingerprint of the relationship's
+state when they reviewed it. A proposal is applied only under the Account lock and only while the
+fingerprint still matches, so any decision taken in customer analytics after the review wins over
+the manifest.
+"""
+
+from collections.abc import Sequence
+from typing import Literal
+from uuid import UUID
+
+from django.db import transaction
+from django.db.models import Max
+
+from posthog.dataclasses import frozen
+from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.organization import OrganizationMembership
+
+from products.customer_analytics.backend.facade.enums import AccountRelationshipSource
+from products.customer_analytics.backend.logic import ownership, relationships
+from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinition
+
+ProposedState = Literal["assigned", "empty"]
+Disposition = Literal["would_apply", "applied", "already_applied", "fingerprint_changed", "conflict", "invalid"]
+
+
+@frozen
+class RoleProposal:
+ account_id: UUID
+ definition_id: UUID
+ state: ProposedState
+ expected_fingerprint: str
+ user_id: int | None = None
+
+ def __post_init__(self) -> None:
+ if self.state not in ("assigned", "empty"):
+ raise ValueError(f"unknown state {self.state!r}; expected 'assigned' or 'empty'")
+ if (self.state == "assigned") != (self.user_id is not None):
+ raise ValueError("an assigned proposal names a user_id and an empty one does not")
+
+
+@frozen
+class ProposalOutcome:
+ proposal: RoleProposal
+ disposition: Disposition
+ detail: str | None = None
+
+
+@frozen
+class RoleFingerprint:
+ account_id: UUID
+ external_id: str | None
+ definition_id: UUID
+ definition_name: str
+ fingerprint: str
+ managed: bool
+ holder_user_id: int | None
+
+
+def parse_manifest(raw: dict) -> list[RoleProposal]:
+ return [
+ RoleProposal(
+ account_id=UUID(entry["account_id"]),
+ definition_id=UUID(entry["definition_id"]),
+ state=entry["state"],
+ expected_fingerprint=entry["expected_fingerprint"],
+ user_id=entry.get("user_id"),
+ )
+ for entry in raw["proposals"]
+ ]
+
+
+def export_fingerprints(team_id: int) -> list[RoleFingerprint]:
+ """The current fingerprint of every controlled relationship on every account, for a manifest
+ builder to embed as the precondition of its proposals."""
+ definitions = list(ownership.controlled_definitions(team_id))
+ rows: list[RoleFingerprint] = []
+ for account in Account.objects.for_team(team_id).order_by("id").iterator():
+ for definition in definitions:
+ holder = relationships.active_relationships(team_id, account, definition).first()
+ rows.append(
+ RoleFingerprint(
+ account_id=account.id,
+ external_id=account.external_id,
+ definition_id=definition.id,
+ definition_name=definition.name,
+ fingerprint=fingerprint(team_id, account, definition),
+ managed=ownership.control_for(account, definition) is not None,
+ holder_user_id=holder.user_id if holder is not None else None,
+ )
+ )
+ return rows
+
+
+def review(team_id: int, proposals: Sequence[RoleProposal], *, apply: bool) -> list[ProposalOutcome]:
+ """Check every proposal against the live relationship state and, with ``apply``, adopt the ones
+ that still hold. Each proposal is its own transaction, so one conflict never rolls back the
+ others."""
+ return [_review_one(team_id, proposal, apply=apply) for proposal in proposals]
+
+
+def fingerprint(team_id: int, account: Account, definition: AccountRelationshipDefinition) -> str:
+ """SHA-256 of everything a reviewer's decision rested on: identity, fence, the active holder
+ rows, the last transition and the latest audit entry for the account under the definition."""
+ active = list(
+ AccountRelationship.objects.for_team(team_id)
+ .filter(account=account, definition=definition, ended_at__isnull=True)
+ .order_by("started_at")
+ .values_list("id", "user_id", "started_at")
+ )
+ last_ended_at = (
+ AccountRelationship.objects.for_team(team_id)
+ .filter(account=account, definition=definition)
+ .aggregate(value=Max("ended_at"))["value"]
+ )
+ latest_activity_id = (
+ ActivityLog.objects.filter(
+ team_id=team_id,
+ scope=relationships.ACTIVITY_SCOPE,
+ item_id=str(account.id),
+ detail__context__definition_id=str(definition.id),
+ )
+ .order_by("-created_at", "-id")
+ .values_list("id", flat=True)
+ .first()
+ )
+ control = ownership.control_for(account, definition)
+ return ownership.canonical_digest(
+ {
+ "account_id": str(account.id),
+ "external_id": account.external_id,
+ "definition_id": str(definition.id),
+ "controlled_at": control.controlled_at.isoformat() if control is not None else None,
+ "active": [[str(row_id), user_id, started_at.isoformat()] for row_id, user_id, started_at in active],
+ "last_ended_at": last_ended_at.isoformat() if last_ended_at else None,
+ "latest_activity_id": str(latest_activity_id) if latest_activity_id else None,
+ }
+ )
+
+
+def _outcome(proposal: RoleProposal, disposition: Disposition, detail: str | None = None) -> ProposalOutcome:
+ return ProposalOutcome(proposal=proposal, disposition=disposition, detail=detail)
+
+
+def _review_one(team_id: int, proposal: RoleProposal, *, apply: bool) -> ProposalOutcome:
+ with transaction.atomic():
+ # The definition lock comes before the account lock, the order enrollment takes, and it
+ # holds `is_controlled` still until the proposal is applied or refused.
+ definition = ownership.lock_definition(team_id, proposal.definition_id)
+ if definition is None or not definition.is_controlled:
+ return _outcome(proposal, "invalid", "definition_not_controlled")
+ account = relationships.lock_account(team_id, proposal.account_id)
+ if account is None:
+ return _outcome(proposal, "invalid", "account_not_found")
+ if not account.external_id:
+ return _outcome(proposal, "invalid", "account_not_linked")
+ holder = relationships.active_relationships(team_id, account, definition).first()
+ wanted_user_id = proposal.user_id if proposal.state == "assigned" else None
+ # A row whose user was deleted still occupies the relationship, so it matches neither an
+ # empty proposal nor an assigned one; it needs a person's decision.
+ state_matches = (
+ holder is None if wanted_user_id is None else holder is not None and holder.user_id == wanted_user_id
+ )
+ if ownership.control_for(account, definition) is not None:
+ if state_matches:
+ return _outcome(proposal, "already_applied")
+ # A managed relationship already carries a decision; the manifest cannot overrule it.
+ return _outcome(proposal, "conflict", "role_managed")
+ if fingerprint(team_id, account, definition) != proposal.expected_fingerprint:
+ return _outcome(proposal, "fingerprint_changed")
+ if holder is not None and not state_matches:
+ return _outcome(
+ proposal, "conflict", f"held_by_user_{holder.user_id}" if holder.user_id else "held_by_deleted_user"
+ )
+
+ membership = None
+ if wanted_user_id is not None and holder is None:
+ membership = (
+ OrganizationMembership.objects.select_related("user")
+ .filter(organization_id=account.team.organization_id, user_id=wanted_user_id, user__is_active=True)
+ .first()
+ )
+ if membership is None:
+ return _outcome(proposal, "invalid", "user_not_member")
+ if not apply:
+ return _outcome(proposal, "would_apply")
+
+ actor = relationships.Actor(source=AccountRelationshipSource.MIGRATION)
+ if membership is not None:
+ # The relationship is unmanaged here, so the migration source is allowed to fill it.
+ relationships.assign(
+ team_id=team_id,
+ account=account,
+ definition=definition,
+ user=membership.user,
+ actor=actor,
+ emit_event=False,
+ replace_active=False,
+ )
+ relationships.enroll(team_id=team_id, account=account, definition=definition, actor=actor)
+ return _outcome(proposal, "applied")
diff --git a/products/customer_analytics/backend/logic/ownership_claims.py b/products/customer_analytics/backend/logic/ownership_claims.py
new file mode 100644
index 000000000000..73a9a8ce75db
--- /dev/null
+++ b/products/customer_analytics/backend/logic/ownership_claims.py
@@ -0,0 +1,569 @@
+"""
+Pull-based delivery of Salesforce Task decisions into controlled relationships.
+
+A controlled relationship definition binds the warehouse view whose rows fill it
+(``AccountRelationshipDefinition.claim_saved_query``, read while ``claims_enabled``), so a project can
+feed as many relationships as it has views. Each view maps the frozen decision fields on Salesforce
+Tasks onto one row per Task with these columns:
+
+- ``task_id``: the Task id; the idempotency key of the decision.
+- ``organization_id``: the PostHog organization the Task's account is linked to.
+- ``region``: the PostHog region the organization lives in (``us``, ``eu``).
+- ``assignee_user_id``: PostHog user id of the allocated holder.
+- ``source_assignee_id``: Salesforce user id of the same person.
+- ``allocated_at``: when the eligible allocation was made at the source; never a delivery time.
+- ``released_at``: when the Task was disqualified, or null while the allocation stands.
+- ``source_releaser_id``: Salesforce user id of whoever disqualified the Task, or null.
+
+Each run reads every row with a usable ``task_id``, in pages ordered by that id, and applies it: a
+row without ``released_at`` claims the relationship, one with it withdraws that same Task's claim.
+Both are idempotent, so rereading a Task costs one lookup and changes nothing; the view is expected
+to keep only recent Tasks. A Task listed more than once is not applied at all, so a view must
+express a release by setting ``released_at`` on the Task's one row, never by adding a second row.
+Paging compares the id as text, so a row whose ``task_id`` is null or empty is not read and reaches
+no outcome count; it carries no idempotency key, so no run could apply it safely. Timestamps without
+a timezone are read as UTC, which is how Salesforce records them. Nothing is written back to
+Salesforce: accepted and released claims are visible on the account's relationships and audit trail,
+and every outcome is counted and logged here.
+"""
+
+from collections import Counter
+from collections.abc import Callable
+from datetime import UTC, datetime
+from decimal import Decimal
+from typing import Any
+from uuid import UUID
+
+from django.db import IntegrityError, transaction
+from django.db.models import Q
+
+import structlog
+
+from posthog.hogql import ast
+from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.dataclasses import frozen
+from posthog.errors import ExposedCHQueryError
+from posthog.exceptions_capture import capture_exception
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team import Team
+
+from products.customer_analytics.backend.facade import contracts
+from products.customer_analytics.backend.facade.enums import AccountRelationshipSource
+from products.customer_analytics.backend.logic import ownership, relationships
+from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinition
+from products.data_modeling.backend.facade import api as data_modeling_facade
+
+logger = structlog.get_logger(__name__)
+
+DECISION_COLUMNS = (
+ "task_id",
+ "organization_id",
+ "region",
+ "assignee_user_id",
+ "source_assignee_id",
+ "allocated_at",
+ "released_at",
+ "source_releaser_id",
+)
+
+
+class ClaimSourceMisconfigured(Exception):
+ """The claim binding cannot be made or used: no such definition or view, a definition that is not
+ controlled, or a view that does not answer one of the documented decision columns."""
+
+
+class SweepStopped(Exception):
+ """The caller asked the sweep to stop, which it does between two pages or two decisions."""
+
+
+def _never() -> bool:
+ return False
+
+
+@frozen
+class ClaimReconciliation:
+ team_id: int
+ decisions: int
+ outcomes: dict[str, int]
+ skipped: bool = False
+
+
+def check_decision_columns(view_name: str, columns: dict[str, str]) -> None:
+ """Raise unless the view answers every documented decision column."""
+ missing = [column for column in DECISION_COLUMNS if column not in columns]
+ if missing:
+ raise ClaimSourceMisconfigured(f"View {view_name} has no column(s): {', '.join(missing)}")
+
+
+DECISION_PAGE_SIZE = 1000
+# A run holds every row of the view before it applies the first decision, on a worker it shares with
+# other products. The view is expected to hold recent Tasks only, so a read past this ceiling is a
+# view to narrow rather than a sweep to attempt.
+MAX_DECISION_ROWS = MAX_SELECT_RETURNED_ROWS
+
+
+# The definitions a sweep fills. The coordinator wakes the teams that have one and the sweep reads
+# them, so both ask the same question here.
+CLAIM_BOUND = Q(is_controlled=True, claims_enabled=True, claim_saved_query__isnull=False)
+
+
+def list_ownership_claim_team_ids() -> list[int]:
+ """Every team with at least one definition the sweep fills; the coordinator reads this across
+ teams, which is why the query is unscoped."""
+ return list(
+ AccountRelationshipDefinition.objects.unscoped()
+ .filter(CLAIM_BOUND)
+ .order_by("team_id")
+ .values_list("team_id", flat=True)
+ .distinct()
+ )
+
+
+def claim_bound_definitions(team_id: int) -> list[AccountRelationshipDefinition]:
+ return list(
+ AccountRelationshipDefinition.objects.for_team(team_id)
+ .filter(CLAIM_BOUND)
+ .select_related("claim_saved_query")
+ .order_by("name")
+ )
+
+
+def _locked_definition(team_id: int, definition_id: UUID) -> AccountRelationshipDefinition:
+ """The definition under its row lock; call inside ``transaction.atomic()``."""
+ definition = ownership.lock_definition(team_id, definition_id)
+ if definition is None:
+ raise ClaimSourceMisconfigured(f"No relationship definition {definition_id} in this project")
+ return definition
+
+
+def bind_claim_view(team_id: int, definition_id: UUID, saved_query_id: UUID | None) -> AccountRelationshipDefinition:
+ """Bind the warehouse view whose rows fill the definition, or unbind it with None, which also
+ switches its sweep off. Only a controlled definition can take a view, because a claim fills only
+ a managed relationship; the view must answer every decision column; and a view feeds one
+ definition, because a Task id is unique per team and a second definition would only ever see
+ ``already_applied``."""
+ with transaction.atomic():
+ definition = _locked_definition(team_id, definition_id)
+ if saved_query_id is not None:
+ if not definition.is_controlled:
+ raise ClaimSourceMisconfigured(
+ f"{definition.name} is not controlled; a claim can only fill a controlled relationship"
+ )
+ view = data_modeling_facade.get_saved_query_summary(team_id, saved_query_id)
+ if view is None:
+ raise ClaimSourceMisconfigured(f"No warehouse view {saved_query_id} in this project")
+ check_decision_columns(view.name, data_modeling_facade.get_saved_query_columns(team_id, saved_query_id))
+ elsewhere = (
+ AccountRelationshipDefinition.objects.for_team(team_id)
+ .filter(claim_saved_query_id=saved_query_id)
+ .exclude(id=definition.id)
+ .first()
+ )
+ if elsewhere is not None:
+ raise ClaimSourceMisconfigured(
+ f"View {view.name} already fills {elsewhere.name}; a view feeds one definition"
+ )
+ definition.claim_saved_query_id = saved_query_id
+ if saved_query_id is None:
+ definition.claims_enabled = False
+ definition.save(update_fields=["claim_saved_query", "claims_enabled", "updated_at"])
+ return definition
+
+
+def set_claims_enabled(team_id: int, definition_id: UUID, enabled: bool) -> AccountRelationshipDefinition:
+ """Switch the sweep for the definition's view. Enabling needs a bound view, so an enabled
+ definition always names what the sweep reads."""
+ with transaction.atomic():
+ definition = _locked_definition(team_id, definition_id)
+ if enabled and definition.claim_saved_query_id is None:
+ raise ClaimSourceMisconfigured(
+ f"{definition.name} has no claim view bound; bind one before enabling claims"
+ )
+ definition.claims_enabled = enabled
+ definition.save(update_fields=["claims_enabled", "updated_at"])
+ return definition
+
+
+def reconcile_ownership_claims(team: Team, *, should_stop: Callable[[], bool] = _never) -> ClaimReconciliation:
+ """Read every view bound to one of the project's definitions and apply the decisions in it to
+ that definition. A project with nothing bound is skipped, so the scheduled sweep can run for every
+ team, and a view that cannot be read is counted as ``misconfigured`` while the others still run.
+ Callers must not run two sweeps for one team at once: an older read could apply a claim that
+ a newer read has already seen released. The schedule guarantees this through a fixed workflow id
+ per team, a single attempt per sweep, and ``should_stop``, which a timed-out activity sets so its
+ thread stops between two pages or two decisions; at most the one decision already in flight can
+ still commit beside the next sweep, and the tick after that repairs it."""
+ bound: list[tuple[AccountRelationshipDefinition, Any]] = []
+ for definition in claim_bound_definitions(team.id):
+ view = definition.claim_saved_query
+ if view is None:
+ continue
+ if view.deleted:
+ logger.warning(
+ "ownership_claims.view_deleted", team_id=team.id, definition_id=str(definition.id), view_id=str(view.id)
+ )
+ continue
+ bound.append((definition, view))
+ if not bound:
+ return ClaimReconciliation(team_id=team.id, decisions=0, outcomes={}, skipped=True)
+ decisions = 0
+ outcomes: Counter[str] = Counter()
+ for definition, view in bound:
+ # One unusable view must not stop the project's other definitions: it is counted, reported,
+ # and read again next tick. A stop request is a different exception and still ends the sweep.
+ try:
+ check_decision_columns(view.name, data_modeling_facade.get_saved_query_columns(team.id, view.id))
+ rows = _read_decision_rows(team, view.name, should_stop)
+ except ClaimSourceMisconfigured as error:
+ capture_exception(error, {"team_id": team.id, "definition_id": str(definition.id)})
+ logger.warning(
+ "ownership_claims.view_misconfigured",
+ team_id=team.id,
+ definition_id=str(definition.id),
+ view_id=str(view.id),
+ error=str(error),
+ )
+ outcomes["misconfigured"] += 1
+ continue
+ decisions += len(rows)
+ outcomes.update(_apply_rows(team, definition, rows, should_stop))
+ return ClaimReconciliation(team_id=team.id, decisions=decisions, outcomes=dict(outcomes))
+
+
+def _apply_rows(
+ team: Team, definition: AccountRelationshipDefinition, rows: list[dict[str, Any]], should_stop: Callable[[], bool]
+) -> dict[str, int]:
+ outcomes: Counter[str] = Counter()
+ for decision in _decisions_by_task(rows, outcomes):
+ if should_stop():
+ raise SweepStopped()
+ # A collision on the per-source reference index is one decision an overlapping sweep accepted
+ # first, so it is counted and the run goes on. Every refusal is an outcome, so anything else that raises is
+ # the infrastructure or a bug, never one bad decision: it ends the sweep, and the next tick
+ # reads the view again.
+ try:
+ if decision.is_release:
+ result = release(team=team, decision=decision)
+ else:
+ result = claim(team=team, definition=definition, decision=decision)
+ except IntegrityError as error:
+ capture_exception(error, {"team_id": team.id, "source_ref": decision.source_ref})
+ outcomes["error"] += 1
+ continue
+ if result.reason == "binding_changed":
+ # The view's rows now belong to another definition, or to none; the next tick reads them
+ # under the binding of that moment.
+ outcomes["binding_changed"] += 1
+ break
+ outcome = result.outcome if result.reason is None else f"{result.outcome}:{result.reason}"
+ outcomes[outcome] += 1
+ logger.info(
+ "ownership_claims.decision",
+ team_id=team.id,
+ source_ref=decision.source_ref,
+ release=decision.is_release,
+ outcome=result.outcome,
+ reason=result.reason,
+ )
+ return dict(outcomes)
+
+
+def _decisions_by_task(rows: list[dict[str, Any]], outcomes: Counter[str]) -> list[contracts.OwnershipClaimDecision]:
+ """One decision per Task. The view promises one row per Task, so a Task listed more than once is
+ counted and not applied at all, whether or not each of its rows is otherwise valid: the rows could
+ disagree, and applying either could be wrong."""
+ listings = Counter(_task_id(row) for row in rows)
+ duplicated = {task_id for task_id, count in listings.items() if task_id is not None and count > 1}
+ if duplicated:
+ # Incrementing by zero would still list "duplicate" among a clean run's outcomes.
+ outcomes["duplicate"] += len(duplicated)
+ decisions: list[contracts.OwnershipClaimDecision] = []
+ for row in rows:
+ if _task_id(row) in duplicated:
+ continue
+ decision = _decision_from_row(row)
+ if decision is None:
+ outcomes["invalid"] += 1
+ else:
+ decisions.append(decision)
+ return decisions
+
+
+def _task_id(row: dict[str, Any]) -> str | None:
+ try:
+ return _identifier(row["task_id"])
+ except ValueError:
+ return None
+
+
+def _read_decision_rows(team: Team, view_name: str, should_stop: Callable[[], bool]) -> list[dict[str, Any]]:
+ """Every row of the view, keyed by column name, paged on ``task_id`` so a view of any size is read
+ to the end. The view runs as a userless system read, so user-scoped warehouse access control is
+ bypassed; tenant isolation still holds through the team."""
+ rows: list[dict[str, Any]] = []
+ cursor = ""
+ with tags_context(product=Product.CUSTOMER_ANALYTICS, feature=Feature.ACCOUNTS, team_id=team.pk):
+ while True:
+ if should_stop():
+ raise SweepStopped()
+ query = ast.SelectQuery(
+ select=[ast.Field(chain=[column]) for column in DECISION_COLUMNS],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[view_name])),
+ where=ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt,
+ left=ast.Call(name="toString", args=[ast.Field(chain=["task_id"])]),
+ right=ast.Constant(value=cursor),
+ ),
+ order_by=[
+ ast.OrderExpr(expr=ast.Call(name="toString", args=[ast.Field(chain=["task_id"])]), order="ASC")
+ ],
+ limit=ast.Constant(value=DECISION_PAGE_SIZE),
+ )
+ try:
+ response = execute_hogql_query(
+ query, team=team, workload=Workload.OFFLINE, bypass_warehouse_access_control=True
+ )
+ except (ExposedHogQLError, ExposedCHQueryError) as error:
+ # A view whose SQL no longer resolves (a dropped source table, a renamed column) is
+ # the view's fault and is reported as such; infrastructure failures still propagate.
+ raise ClaimSourceMisconfigured(f"View {view_name} cannot be read: {error}") from error
+ page = response.results or []
+ if len(page) < DECISION_PAGE_SIZE:
+ rows.extend(dict(zip(DECISION_COLUMNS, row)) for row in page)
+ return rows
+ # A full page can end between two rows of one Task, and the next page starts after the
+ # cursor, so the last Task is handed back to the next page unless it fills this one alone.
+ last = str(page[-1][0])
+ kept = [row for row in page if str(row[0]) != last] or page
+ rows.extend(dict(zip(DECISION_COLUMNS, row)) for row in kept)
+ if len(rows) > MAX_DECISION_ROWS:
+ raise ClaimSourceMisconfigured(
+ f"View {view_name} holds more than {MAX_DECISION_ROWS} rows; narrow it to recent Tasks"
+ )
+ next_cursor = str(kept[-1][0])
+ if next_cursor <= cursor:
+ # The page filter compares toString(task_id) in ClickHouse while the cursor is the
+ # Python str() of the value; a column type where the two disagree would return the
+ # same page forever.
+ raise ClaimSourceMisconfigured(f"View {view_name} column task_id does not page as text")
+ cursor = next_cursor
+
+
+def _decision_from_row(row: dict[str, Any]) -> contracts.OwnershipClaimDecision | None:
+ """The decision the row carries, or None when the view shaped it badly, so a single malformed
+ row is counted rather than applied. Identifiers must be present and non-blank: a null Task id
+ would otherwise give unrelated rows one idempotency key."""
+ try:
+ return contracts.OwnershipClaimDecision(
+ source_ref=_identifier(row["task_id"]),
+ organization_id=_identifier(row["organization_id"]),
+ region=_identifier(row["region"]).lower(),
+ assignee_user_id=_user_id(row["assignee_user_id"]),
+ source_assignee_id=_identifier(row["source_assignee_id"]),
+ allocated_at=_as_datetime(row["allocated_at"]),
+ released_at=_as_datetime(row["released_at"]) if row["released_at"] is not None else None,
+ source_releaser_id=_identifier(row["source_releaser_id"])
+ if row["source_releaser_id"] is not None
+ else None,
+ )
+ except (TypeError, ValueError) as error:
+ logger.warning("ownership_claims.invalid_row", task_id=row.get("task_id"), error=str(error))
+ return None
+
+
+def _identifier(value: object) -> str:
+ if value is None or not str(value).strip():
+ raise ValueError("identifier is missing")
+ return str(value).strip()
+
+
+def _user_id(value: object) -> int:
+ # A warehouse column with decimal places is read as Decimal, which has no is_integer(), so a
+ # fractional value would reach int() and truncate onto another user's id.
+ if (
+ isinstance(value, bool)
+ or (isinstance(value, float) and not value.is_integer())
+ or (isinstance(value, Decimal) and not (value.is_finite() and value == value.to_integral_value()))
+ ):
+ raise ValueError(f"user id is not integral: {value!r}")
+ return int(value) # type: ignore[call-overload]
+
+
+def _as_datetime(value: object) -> datetime:
+ parsed = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+
+
+def claim(
+ *, team: Team, definition: AccountRelationshipDefinition, decision: contracts.OwnershipClaimDecision
+) -> contracts.OwnershipClaimResult:
+ """Apply an initial allocation frozen on a Salesforce Task to the definition whose view listed it.
+
+ Under the Account lock, an accepted claim for the same Task is recognized first, so a Task read
+ again on a later run is answered with the original decision even after the relationship has
+ changed hands. A new Task may fill the relationship only when the account manages it, it is
+ empty, the assignee is a member, and the allocation is later than the control timestamp, the
+ last human decision, by more than the clock-skew allowance. Every refusal is returned as an
+ outcome for the reconciler to record.
+
+ Neither a claim nor a release moves the control timestamp. Both carry Salesforce's decision time
+ and are processed later, so moving it to the processing instant would fence out a Task allocated
+ between the source event and this sweep.
+ """
+ actor = relationships.Actor(source=AccountRelationshipSource.SALESFORCE_CLAIM)
+ with transaction.atomic():
+ # Definition before account, the order every writer takes. The view was read before this
+ # transaction, so the binding is checked again here: an operator may have moved the view
+ # to another definition or switched its sweep off in between, and a claim under the old
+ # definition would leave the Task unable to fill the new one.
+ current = ownership.lock_definition(team.id, definition.id)
+ if (
+ current is None
+ or not current.claims_enabled
+ or current.claim_saved_query_id != definition.claim_saved_query_id
+ ):
+ return _claim_result("blocked", "binding_changed")
+ try:
+ locked_account = _lock_account_by_external_id(team.id, decision.organization_id)
+ except AmbiguousAccountIdentity:
+ return _claim_result("blocked", "identity_mismatch")
+ if locked_account is None:
+ return _claim_result("blocked", "account_not_found")
+ accepted = _accepted_claim(team.id, decision.source_ref)
+ if accepted is not None:
+ if accepted.account_id != locked_account.id:
+ return _claim_result("blocked", "identity_mismatch", accepted)
+ return _claim_result("already_applied", None, accepted)
+
+ control = ownership.control_for(locked_account, definition)
+ if control is None:
+ return _claim_result("blocked", "role_not_managed")
+ if not ownership.region_matches(decision.region):
+ return _claim_result("blocked", "identity_mismatch")
+ membership = (
+ OrganizationMembership.objects.select_related("user")
+ .filter(organization_id=team.organization_id, user_id=decision.assignee_user_id, user__is_active=True)
+ .first()
+ )
+ if membership is None:
+ return _claim_result("blocked", "assignee_not_member")
+
+ holder = relationships.active_relationships(team.id, locked_account, definition).first()
+ if holder is not None:
+ return _claim_result("rejected", "role_occupied", holder)
+ fence = control.controlled_at
+ rejection = ownership.allocation_rejection(decision.allocated_at, fence)
+ if rejection is not None:
+ return _claim_result("rejected", rejection)
+
+ relationship = AccountRelationship.objects.for_team(team.id).create(
+ team_id=team.id,
+ account=locked_account,
+ definition=definition,
+ user=membership.user,
+ source=actor.source,
+ source_ref=decision.source_ref,
+ )
+ relationships.record_transition(
+ account=locked_account,
+ actor=actor,
+ activity="role_claimed",
+ definition=definition,
+ relationship=relationship,
+ previous_user=None,
+ current_user=membership.user,
+ controlled_at=fence,
+ source_actor_id=decision.source_assignee_id,
+ source_decided_at=decision.allocated_at,
+ emit_event=True,
+ )
+ return _claim_result("accepted", None, relationship, fence)
+
+
+def release(*, team: Team, decision: contracts.OwnershipClaimDecision) -> contracts.OwnershipClaimResult:
+ """End the relationship that this Task's accepted claim created, and nothing else.
+
+ A release needs no time fence: identity to the Task's own claim is the guard, so it cannot clear
+ a holder assigned by a person or by another Task. Once a person has transferred or cleared the
+ relationship, the Task no longer holds it and the release is a no-op.
+ """
+ actor = relationships.Actor(source=AccountRelationshipSource.SALESFORCE_CLAIM)
+ held = _accepted_claim(team.id, decision.source_ref)
+ if held is None:
+ return _claim_result("not_held", None)
+ with transaction.atomic():
+ # The claim names the account to lock, and is then read again under that lock: a person may
+ # have ended it in between, which is exactly what makes the release a no-op. An account
+ # deleted in between takes its claim row with it, so the account check only completes the type.
+ locked_account = relationships.lock_account(team.id, held.account_id)
+ accepted = _accepted_claim(team.id, decision.source_ref)
+ if locked_account is None or accepted is None or accepted.ended_at is not None:
+ return _claim_result("not_held", None, accepted)
+
+ relationships.end_rows(team.id, [accepted])
+ control = ownership.control_for(locked_account, accepted.definition)
+ controlled_at = control.controlled_at if control is not None else None
+ relationships.record_transition(
+ account=locked_account,
+ actor=actor,
+ activity="role_released",
+ definition=accepted.definition,
+ relationship=accepted,
+ previous_user=accepted.user,
+ current_user=None,
+ controlled_at=controlled_at,
+ source_actor_id=decision.source_releaser_id,
+ source_decided_at=decision.released_at,
+ emit_event=True,
+ )
+ return _claim_result("cleared", None, accepted, controlled_at)
+
+
+def _accepted_claim(team_id: int, source_ref: str) -> AccountRelationship | None:
+ return (
+ AccountRelationship.objects.for_team(team_id)
+ .select_related("definition", "user")
+ .filter(source=AccountRelationshipSource.SALESFORCE_CLAIM, source_ref=source_ref)
+ .first()
+ )
+
+
+class AmbiguousAccountIdentity(Exception):
+ """More than one account of the team carries the external id, differing only by case."""
+
+
+def _lock_account_by_external_id(team_id: int, external_id: str) -> Account | None:
+ """Lock the account linked to the organization. The link is read again under the lock, because
+ an account update between the lookup and the lock could have moved it to another organization.
+
+ The unique constraint on external ids is case-sensitive while this lookup is not, so two
+ accounts that differ only by case are refused rather than resolved to whichever sorts first.
+ """
+ account_ids = list(
+ Account.objects.for_team(team_id).filter(external_id__iexact=external_id).values_list("id", flat=True)[:2]
+ )
+ if len(account_ids) > 1:
+ raise AmbiguousAccountIdentity(external_id)
+ locked = relationships.lock_account(team_id, account_ids[0]) if account_ids else None
+ if locked is None or (locked.external_id or "").lower() != external_id.lower():
+ return None
+ return locked
+
+
+def _claim_result(
+ outcome: contracts.OwnershipClaimOutcome,
+ reason: contracts.OwnershipClaimReason | None,
+ relationship: AccountRelationship | None = None,
+ controlled_at: datetime | None = None,
+) -> contracts.OwnershipClaimResult:
+ return contracts.OwnershipClaimResult(
+ outcome=outcome,
+ reason=reason,
+ relationship_id=relationship.id if relationship is not None else None,
+ controlled_at=controlled_at,
+ )
diff --git a/products/customer_analytics/backend/logic/ownership_test.py b/products/customer_analytics/backend/logic/ownership_test.py
new file mode 100644
index 000000000000..a5544fa52d2d
--- /dev/null
+++ b/products/customer_analytics/backend/logic/ownership_test.py
@@ -0,0 +1,24 @@
+from typing import get_args
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.customer_analytics.backend.facade import contracts
+from products.customer_analytics.backend.facade.enums import (
+ AccountRelationshipSource,
+ OwnershipRoleDiagnostic,
+ OwnershipRoleState,
+)
+
+
+class TestOwnershipVocabulary(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (OwnershipRoleState, contracts.OwnershipRoleStateValue),
+ (AccountRelationshipSource, contracts.RelationshipSourceValue),
+ (OwnershipRoleDiagnostic, contracts.OwnershipRoleDiagnosticValue),
+ ]
+ )
+ def test_wire_enum_and_contract_literal_agree(self, choices, literal):
+ assert set(choices.values) == set(get_args(literal))
diff --git a/products/customer_analytics/backend/logic/relationships.py b/products/customer_analytics/backend/logic/relationships.py
index edbb4361768b..acb3ba0581c7 100644
--- a/products/customer_analytics/backend/logic/relationships.py
+++ b/products/customer_analytics/backend/logic/relationships.py
@@ -1,63 +1,142 @@
"""
-Assign/end transactions for account relationships. Called by the facade and
-product-internal account writers only.
+Assign/end transactions for account relationships: the one write path for every relationship
+writer (UI API, external API, AI tool, workflows, management commands). Each mutation locks the
+Account row, applies the controlled-relationship policy, advances the control timestamp when
+customer analytics controls that relationship on the account, and writes its activity row inside
+the same transaction, so a mutation without an audit record cannot commit. The Salesforce claim
+procedure in ``logic/ownership_claims.py`` writes through the public helpers here under the same
+lock and audit rules.
"""
+import dataclasses
+from datetime import datetime
from uuid import UUID
from django.db import transaction
+from django.db.models import QuerySet
+from django.db.models.signals import post_save
from django.utils import timezone
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
+from posthog.models.activity_logging.activity_log import ActivityContextBase, ActivityLog, Change, Detail, log_activity
+from posthog.models.activity_logging.utils import activity_storage
from posthog.models.user import User
from products.customer_analytics.backend.events import emit_account_relationship_changed
-from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinition
+from products.customer_analytics.backend.facade.enums import AccountRelationshipSource
+from products.customer_analytics.backend.logic import ownership
+from products.customer_analytics.backend.models import (
+ Account,
+ AccountRelationship,
+ AccountRelationshipControl,
+ AccountRelationshipDefinition,
+)
+
+ACTIVITY_SCOPE = "Account"
class AccountRelationshipNotFound(Exception):
pass
+class ManagedRolePolicyError(Exception):
+ """An autonomous writer tried to change a controlled relationship that customer analytics manages
+ on the account."""
+
+
+class ProtectedRelationshipHistoryError(Exception):
+ """A row under a controlled definition cannot be hard-deleted; end it instead."""
+
+
+class RelationshipOccupiedError(Exception):
+ """The single-holder relationship already has a different active holder and the caller asked
+ not to replace one."""
+
+
+@frozen
+class Actor:
+ """Who performs a relationship mutation and through which kind of writer."""
+
+ source: AccountRelationshipSource
+ user: User | None = None
+ workflow_id: str | None = None
+
+ @classmethod
+ def human(cls, user: User | None = None) -> "Actor":
+ return cls(source=AccountRelationshipSource.HUMAN, user=user)
+
+
[email protected](frozen=True)
+class AccountRelationshipActivityContext(ActivityContextBase):
+ """Provenance stored beside the change so a reader can tell which writer acted, through which
+ reference, and where the control timestamp stood afterwards (null where the relationship is not
+ managed on the account)."""
+
+ relationship_id: str | None
+ definition_id: str
+ definition_name: str
+ source: str
+ source_ref: str | None
+ workflow_id: str | None
+ previous_user_id: int | None
+ current_user_id: int | None
+ controlled_at: str | None
+ # For a Salesforce decision: who decided at the source and when, as the Task recorded it.
+ source_actor_id: str | None = None
+ source_decided_at: str | None = None
+
+
def assign(
*,
team_id: int,
account: Account,
definition: AccountRelationshipDefinition,
user: User,
- created_by: User | None,
- workflow_id: str | None = None,
+ actor: Actor,
emit_event: bool = True,
+ replace_active: bool = True,
) -> AccountRelationship:
+ """Assign the user. A single-holder definition hands off from the previous holder in the same
+ transaction unless ``replace_active`` is False, in which case an occupied role raises. Assigning
+ the current holder again is a no-op that records nothing."""
with transaction.atomic():
- # Serializes concurrent assigns for this definition; prevents double-insert races.
- AccountRelationshipDefinition.objects.for_team(team_id).select_for_update().get(id=definition.id)
- active = list(
- AccountRelationship.objects.for_team(team_id)
- .filter(account=account, definition=definition, ended_at__isnull=True)
- .select_related("user")
- )
+ locked_account = _lock_or_raise(team_id, account.id)
+ control = ownership.control_for(locked_account, definition)
+ _enforce_managed_role_policy(control, actor)
+ # A controlled definition is single-holder by invariant, and the caller's copy of the
+ # definition may predate control starting, so a managed relationship always hands off.
+ single_holder = definition.is_single_holder or control is not None
+ active = list(active_relationships(team_id, locked_account, definition))
existing = next((rel for rel in active if rel.user_id == user.id), None)
if existing is not None:
return existing
+ if active and single_holder and not replace_active:
+ raise RelationshipOccupiedError(str(definition.id))
- previous_user = active[0].user if definition.is_single_holder and active else None
- if definition.is_single_holder:
- for relationship in active:
- relationship.ended_at = timezone.now()
- relationship.save(update_fields=["ended_at"])
+ previous_user = active[0].user if single_holder and active else None
+ if single_holder:
+ end_rows(team_id, active)
relationship = AccountRelationship.objects.for_team(team_id).create(
- team_id=team_id, account=account, definition=definition, user=user, created_by=created_by
+ team_id=team_id,
+ account=locked_account,
+ definition=definition,
+ user=user,
+ created_by=actor.user,
+ source=actor.source,
+ )
+ controlled_at = _advance_if_managed(control)
+ record_transition(
+ account=locked_account,
+ actor=actor,
+ activity="relationship_assigned",
+ definition=definition,
+ relationship=relationship,
+ previous_user=previous_user,
+ current_user=user,
+ controlled_at=controlled_at,
+ emit_event=emit_event,
)
- if emit_event:
- _schedule_relationship_changed_event(
- account=account,
- definition=definition,
- previous_user=previous_user,
- current_user=user,
- actor=created_by,
- workflow_id=workflow_id,
- )
return relationship
@@ -66,35 +145,50 @@ def end_active(
team_id: int,
account: Account,
definition: AccountRelationshipDefinition,
- actor: User | None = None,
- workflow_id: str | None = None,
+ actor: Actor,
emit_event: bool = True,
) -> int:
+ """End every active assignment of the definition on the account and return how many ended.
+
+ On a managed relationship, clearing an already-empty one is still a decision: the fence advances
+ and the confirmation is recorded, so a later automated claim cannot treat it as never reviewed.
+ """
with transaction.atomic():
- active = list(
- AccountRelationship.objects.for_team(team_id)
- .select_related("user")
- .select_for_update(of=("self",))
- .filter(account=account, definition=definition, ended_at__isnull=True)
- )
+ locked_account = _lock_or_raise(team_id, account.id)
+ control = ownership.control_for(locked_account, definition)
+ _enforce_managed_role_policy(control, actor)
+ active = list(active_relationships(team_id, locked_account, definition))
+ if not active and control is None:
+ return 0
+
+ end_rows(team_id, active)
+ controlled_at = _advance_if_managed(control)
if not active:
+ record_transition(
+ account=locked_account,
+ actor=actor,
+ activity="role_confirmed_empty",
+ definition=definition,
+ relationship=None,
+ previous_user=None,
+ current_user=None,
+ controlled_at=controlled_at,
+ emit_event=False,
+ )
return 0
- updated = (
- AccountRelationship.objects.for_team(team_id)
- .filter(id__in=[rel.id for rel in active])
- .update(ended_at=timezone.now())
- )
- if emit_event:
- for relationship in active:
- _schedule_relationship_changed_event(
- account=account,
- definition=definition,
- previous_user=relationship.user,
- current_user=None,
- actor=actor,
- workflow_id=workflow_id,
- )
- return updated
+ for relationship in active:
+ record_transition(
+ account=locked_account,
+ actor=actor,
+ activity="relationship_ended",
+ definition=definition,
+ relationship=relationship,
+ previous_user=relationship.user,
+ current_user=None,
+ controlled_at=controlled_at,
+ emit_event=emit_event,
+ )
+ return len(active)
def end_relationship(
@@ -102,32 +196,36 @@ def end_relationship(
team_id: int,
account_id: str | UUID,
relationship_id: str,
- actor: User | None = None,
- workflow_id: str | None = None,
+ actor: Actor,
emit_event: bool = True,
) -> AccountRelationship:
with transaction.atomic():
- # Serializes concurrent ends of the same row, matching assign's locking contract.
+ locked_account = _lock_or_raise(team_id, account_id, missing_id=relationship_id)
relationship = (
AccountRelationship.objects.for_team(team_id)
- .select_related("definition", "user", "account__team")
- .select_for_update(of=("self",))
- .filter(id=relationship_id, account_id=account_id, ended_at__isnull=True)
+ .select_related("definition", "user")
+ .filter(id=relationship_id, account=locked_account, ended_at__isnull=True)
.first()
)
if relationship is None:
raise AccountRelationshipNotFound(relationship_id)
- relationship.ended_at = timezone.now()
- relationship.save(update_fields=["ended_at"])
- if emit_event:
- _schedule_relationship_changed_event(
- account=relationship.account,
- definition=relationship.definition,
- previous_user=relationship.user,
- current_user=None,
- actor=actor,
- workflow_id=workflow_id,
- )
+ relationship.account = locked_account
+ control = ownership.control_for(locked_account, relationship.definition)
+ _enforce_managed_role_policy(control, actor)
+
+ end_rows(team_id, [relationship])
+ controlled_at = _advance_if_managed(control)
+ record_transition(
+ account=locked_account,
+ actor=actor,
+ activity="relationship_ended",
+ definition=relationship.definition,
+ relationship=relationship,
+ previous_user=relationship.user,
+ current_user=None,
+ controlled_at=controlled_at,
+ emit_event=emit_event,
+ )
return relationship
@@ -136,29 +234,254 @@ def delete_relationship(
team_id: int,
account_id: str | UUID,
relationship_id: str,
- actor: User | None = None,
+ actor: Actor,
) -> None:
+ """Hard-delete one relationship row, active or ended. Rows under a controlled definition are
+ history other systems replay against and are refused."""
with transaction.atomic():
- relationship = (
+ definition_id = (
AccountRelationship.objects.for_team(team_id)
- .select_related("definition", "user", "account__team")
- .select_for_update(of=("self",))
.filter(id=relationship_id, account_id=account_id)
+ .values_list("definition_id", flat=True)
.first()
)
- if relationship is None:
+ if definition_id is None:
+ raise AccountRelationshipNotFound(relationship_id)
+ # Definition before account, the order every writer takes, so control cannot start between
+ # the check below and the delete.
+ definition = ownership.lock_definition(team_id, definition_id)
+ locked_account = _lock_or_raise(team_id, account_id, missing_id=relationship_id)
+ relationship = (
+ AccountRelationship.objects.for_team(team_id)
+ .select_related("user")
+ .filter(id=relationship_id, account=locked_account)
+ .first()
+ )
+ if relationship is None or definition is None:
raise AccountRelationshipNotFound(relationship_id)
+ if definition.is_controlled:
+ raise ProtectedRelationshipHistoryError(relationship_id)
+
was_active = relationship.ended_at is None
+ deleted_id = str(relationship.id)
relationship.delete()
- if was_active:
- _schedule_relationship_changed_event(
- account=relationship.account,
- definition=relationship.definition,
- previous_user=relationship.user,
- current_user=None,
- actor=actor,
- workflow_id=None,
- )
+ record_transition(
+ account=locked_account,
+ actor=actor,
+ activity="relationship_deleted",
+ definition=definition,
+ relationship=None,
+ relationship_id=deleted_id,
+ previous_user=relationship.user,
+ current_user=None,
+ controlled_at=None,
+ emit_event=was_active,
+ )
+
+
+class DefinitionNotControlledError(Exception):
+ """The definition is not one customer analytics may take control of, so no account can be
+ enrolled under it."""
+
+
+def enroll(
+ *, team_id: int, account: Account, definition: AccountRelationshipDefinition, actor: Actor
+) -> AccountRelationshipControl:
+ """Take authority over the relationship on this account and return the control row.
+
+ The current holder, if any, is kept: enrollment records that the relationship's state has been
+ reviewed, so enrolling an empty relationship confirms it empty. Enrolling twice is a no-op that
+ keeps the existing fence.
+ """
+ with transaction.atomic():
+ # Definition before account, the order every writer takes, so `is_controlled` cannot flip
+ # between the check below and the insert of the control row.
+ locked_definition = ownership.lock_definition(team_id, definition.id)
+ if locked_definition is None or not locked_definition.is_controlled:
+ raise DefinitionNotControlledError(str(definition.id))
+ locked_account = _lock_or_raise(team_id, account.id)
+ control = ownership.control_for(locked_account, locked_definition)
+ if control is not None:
+ return control
+ holder = active_relationships(team_id, locked_account, locked_definition).first()
+ holder_user = holder.user if holder is not None else None
+ control = ownership.enroll(locked_account, locked_definition, actor.user)
+ record_transition(
+ account=locked_account,
+ actor=actor,
+ activity="role_enrolled",
+ definition=locked_definition,
+ relationship=holder,
+ previous_user=holder_user,
+ current_user=holder_user,
+ controlled_at=control.controlled_at,
+ emit_event=False,
+ )
+ return control
+
+
+def end_rows(team_id: int, rows: list[AccountRelationship]) -> None:
+ if not rows:
+ return
+ ended_at = timezone.now()
+ AccountRelationship.objects.for_team(team_id).filter(id__in=[row.id for row in rows]).update(ended_at=ended_at)
+ for row in rows:
+ row.ended_at = ended_at
+
+
+def lock_account(team_id: int, account_id: str | UUID) -> Account | None:
+ """Serialize every relationship mutation on the account; call inside ``transaction.atomic()``.
+ Locks only the account row: the joined team row is read, not locked, so a hot parent row is
+ never held."""
+ return (
+ Account.objects.for_team(team_id)
+ .select_related("team")
+ .select_for_update(of=("self",))
+ .filter(id=account_id)
+ .first()
+ )
+
+
+class _DefinitionSetChanged(Exception):
+ pass
+
+
+def lock_account_and_its_definitions(
+ team_id: int, account_id: str | UUID
+) -> tuple[Account | None, list[AccountRelationshipDefinition]]:
+ """Lock the account and every definition it holds relationship rows under, definitions first
+ and by id, the order every other writer takes, so no definition can become controlled while the
+ account's rows are judged. Call inside ``transaction.atomic()``.
+
+ A row assigned between the snapshot of definition ids and the account lock would sit under an
+ unlocked definition. Rolling the savepoint back releases the locks taken so far, and the snapshot
+ is taken again; once the account lock is held no more rows can appear.
+ """
+ rows = AccountRelationship.objects.for_team(team_id).filter(account_id=account_id)
+ for _ in range(3):
+ definition_ids = set(rows.values_list("definition_id", flat=True))
+ try:
+ with transaction.atomic():
+ definitions = ownership.lock_definitions(team_id, definition_ids)
+ account = lock_account(team_id, account_id)
+ if account is not None and not set(rows.values_list("definition_id", flat=True)) <= definition_ids:
+ raise _DefinitionSetChanged()
+ return account, definitions
+ except _DefinitionSetChanged:
+ continue
+ raise RuntimeError(f"Relationships kept being added to account {account_id} while it was being locked")
+
+
+def _lock_or_raise(team_id: int, account_id: str | UUID, *, missing_id: str | None = None) -> Account:
+ """Lock the account for the caller's transaction, or report what the caller was asked about as
+ not found: the account itself, or ``missing_id`` where the caller named a relationship."""
+ account = lock_account(team_id, account_id)
+ if account is None:
+ raise AccountRelationshipNotFound(missing_id or str(account_id))
+ return account
+
+
+def active_relationships(
+ team_id: int, account: Account, definition: AccountRelationshipDefinition
+) -> QuerySet[AccountRelationship]:
+ return (
+ AccountRelationship.objects.for_team(team_id)
+ .filter(account=account, definition=definition, ended_at__isnull=True)
+ .select_related("user")
+ .order_by("started_at")
+ )
+
+
+def _enforce_managed_role_policy(control: AccountRelationshipControl | None, actor: Actor) -> None:
+ """Only a person may change a relationship the account manages.
+
+ Transfers and clears of managed relationships are human acts. An autonomous writer may still
+ fill or change a relationship the account does not manage. Reviewed adoption reaches a managed
+ relationship only through ``enroll``, which is the act of taking it over. A new kind of writer
+ must be authorized here explicitly before it can alter a reviewed decision. That is why the
+ check names the one allowed source rather than the refused ones.
+ """
+ if control is not None and actor.source != AccountRelationshipSource.HUMAN:
+ raise ManagedRolePolicyError(
+ f"A {actor.source} writer cannot change a controlled relationship on an account where it is managed"
+ )
+
+
+def _advance_if_managed(control: AccountRelationshipControl | None) -> datetime | None:
+ return ownership.advance(control) if control is not None else None
+
+
+def record_transition(
+ *,
+ account: Account,
+ actor: Actor,
+ activity: str,
+ definition: AccountRelationshipDefinition,
+ relationship: AccountRelationship | None,
+ previous_user: User | None,
+ current_user: User | None,
+ controlled_at: datetime | None,
+ emit_event: bool,
+ relationship_id: str | None = None,
+ source_actor_id: str | None = None,
+ source_decided_at: datetime | None = None,
+) -> None:
+ """Audit the change and, with ``emit_event``, announce it to consumers once the caller commits.
+
+ The audit row is written now, inside the caller's transaction. ``log_activity`` on its own would
+ defer the insert to after commit and drop it on failure, which would let a role change commit
+ without a record of who made it.
+ """
+ context = AccountRelationshipActivityContext(
+ relationship_id=str(relationship.id) if relationship is not None else relationship_id,
+ definition_id=str(definition.id),
+ definition_name=definition.name,
+ source=str(actor.source),
+ source_ref=relationship.source_ref if relationship is not None else None,
+ workflow_id=actor.workflow_id,
+ previous_user_id=previous_user.id if previous_user is not None else None,
+ current_user_id=current_user.id if current_user is not None else None,
+ controlled_at=controlled_at.isoformat() if controlled_at is not None else None,
+ source_actor_id=source_actor_id,
+ source_decided_at=source_decided_at.isoformat() if source_decided_at is not None else None,
+ )
+ entry = log_activity(
+ organization_id=account.team.organization_id,
+ team_id=account.team_id,
+ user=actor.user,
+ was_impersonated=activity_storage.get_was_impersonated(),
+ item_id=account.id,
+ scope=ACTIVITY_SCOPE,
+ activity=activity,
+ detail=Detail(
+ name=account.name,
+ changes=[
+ Change(
+ type=ACTIVITY_SCOPE,
+ action="changed",
+ field=definition.name,
+ before=previous_user.email if previous_user is not None else None,
+ after=current_user.email if current_user is not None else None,
+ )
+ ],
+ context=context,
+ ),
+ instance_only=True,
+ )
+ if entry is None:
+ raise RuntimeError("Account relationship activity entry could not be built")
+ # bulk_create skips post_save, whose receiver publishes the entry to Kafka at once; the publish
+ # waits for the commit so a rolled-back mutation never announces itself.
+ ActivityLog.objects.bulk_create([entry])
+ transaction.on_commit(lambda: post_save.send(sender=ActivityLog, instance=entry, created=True))
+ if emit_event:
+ _schedule_relationship_changed_event(
+ account=account,
+ definition=definition,
+ previous_user=previous_user,
+ current_user=current_user,
+ actor=actor,
+ )
def _schedule_relationship_changed_event(
@@ -167,8 +490,7 @@ def _schedule_relationship_changed_event(
definition: AccountRelationshipDefinition,
previous_user: User | None,
current_user: User | None,
- actor: User | None,
- workflow_id: str | None,
+ actor: Actor,
) -> None:
"""Emit only after the relationship write commits, without failing the write on capture errors."""
@@ -179,8 +501,8 @@ def _schedule_relationship_changed_event(
definition=definition,
previous_user=previous_user,
current_user=current_user,
- actor=actor,
- workflow_id=workflow_id,
+ actor=actor.user,
+ workflow_id=actor.workflow_id,
)
except Exception as error:
capture_exception(error)
diff --git a/products/customer_analytics/backend/management/commands/adopt_account_ownership.py b/products/customer_analytics/backend/management/commands/adopt_account_ownership.py
new file mode 100644
index 000000000000..d3fcc0b8cd5f
--- /dev/null
+++ b/products/customer_analytics/backend/management/commands/adopt_account_ownership.py
@@ -0,0 +1,77 @@
+"""Reviewed adoption of controlled relationships from a private manifest.
+
+Export the current fingerprints, build the manifest outside the repository, preview it, then apply
+it. A proposal applies only while its fingerprint still matches, so anything decided in customer
+analytics after the review is kept.
+
+ python manage.py adopt_account_ownership --team-id 2 --export-fingerprints > fingerprints.json
+ python manage.py adopt_account_ownership --team-id 2 --manifest manifest.json
+ python manage.py adopt_account_ownership --team-id 2 --manifest manifest.json --apply
+
+The manifest is JSON: ``{"proposals": [{"account_id", "definition_id", "state": "assigned" | "empty",
+"user_id" (assigned only), "expected_fingerprint"}]}``.
+"""
+
+import json
+from collections import Counter
+from pathlib import Path
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+
+from posthog.models.team import Team
+
+from products.customer_analytics.backend.logic import ownership_adoption
+
+
+class Command(BaseCommand):
+ help = "Preview or apply reviewed adoption of controlled relationships for one project from a manifest."
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, required=True)
+ mode = parser.add_mutually_exclusive_group(required=True)
+ mode.add_argument(
+ "--export-fingerprints", action="store_true", help="Print current relationship fingerprints as JSON."
+ )
+ mode.add_argument("--manifest", type=Path, help="Manifest of reviewed proposals to preview or apply.")
+ parser.add_argument("--apply", action="store_true", help="Apply the proposals that still hold.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ if not Team.objects.filter(id=options["team_id"]).exists():
+ raise CommandError(f"No team {options['team_id']}")
+ if options["export_fingerprints"]:
+ self._export(options["team_id"])
+ return
+ self._review(options["team_id"], options["manifest"], apply=options["apply"])
+
+ def _export(self, team_id: int) -> None:
+ rows = [
+ {
+ "account_id": str(row.account_id),
+ "external_id": row.external_id,
+ "definition_id": str(row.definition_id),
+ "definition_name": row.definition_name,
+ "fingerprint": row.fingerprint,
+ "managed": row.managed,
+ "holder_user_id": row.holder_user_id,
+ }
+ for row in ownership_adoption.export_fingerprints(team_id)
+ ]
+ self.stdout.write(json.dumps({"team_id": team_id, "relationships": rows}, indent=2))
+
+ def _review(self, team_id: int, manifest_path: Path, *, apply: bool) -> None:
+ try:
+ proposals = ownership_adoption.parse_manifest(json.loads(manifest_path.read_text()))
+ except (OSError, ValueError, KeyError, TypeError) as error:
+ raise CommandError(f"Could not read the manifest: {error}")
+
+ outcomes = ownership_adoption.review(team_id, proposals, apply=apply)
+ for outcome in outcomes:
+ detail = f" ({outcome.detail})" if outcome.detail else ""
+ self.stdout.write(
+ f"{outcome.proposal.account_id} {outcome.proposal.definition_id} {outcome.proposal.state}: "
+ f"{outcome.disposition}{detail}"
+ )
+ counts = Counter(outcome.disposition for outcome in outcomes)
+ summary = ", ".join(f"{disposition}={count}" for disposition, count in sorted(counts.items()))
+ self.stdout.write(f"{'applied' if apply else 'preview'}: {summary or 'no proposals'}")
diff --git a/products/customer_analytics/backend/management/commands/backfill_account_relationships.py b/products/customer_analytics/backend/management/commands/backfill_account_relationships.py
index 2408b38cfc0e..53c2ddd61665 100644
--- a/products/customer_analytics/backend/management/commands/backfill_account_relationships.py
+++ b/products/customer_analytics/backend/management/commands/backfill_account_relationships.py
@@ -16,10 +16,10 @@ Idempotent. Run once per environment, with --dry-run first:
from typing import Any
from django.core.management.base import BaseCommand
-from django.db import transaction
from posthog.models import User
+from products.customer_analytics.backend.facade.enums import AccountRelationshipSource
from products.customer_analytics.backend.logic import relationships as relationships_logic
from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinition
@@ -99,21 +99,23 @@ class Command(BaseCommand):
if definition is None:
continue
# The relationships table has been authoritative since the cutover deploy, so only
- # fill gaps and never overwrite an assignment made after it. The check runs under
- # assign's definition lock, or a concurrent assign landing between check and assign
- # would be replaced by the stale JSON holder.
- with transaction.atomic():
- AccountRelationshipDefinition.objects.for_team(team_id).select_for_update().get(id=definition.id)
- if _has_active_holder(team_id, account, definition):
- continue
+ # fill gaps and never overwrite an assignment made after it. A role customer
+ # analytics manages is refused by the relationship service, because its emptiness
+ # is a reviewed decision.
+ if _has_active_holder(team_id, account, definition):
+ continue
+ try:
relationships_logic.assign(
team_id=team_id,
account=account,
definition=definition,
user=user,
- created_by=None,
+ actor=relationships_logic.Actor(source=AccountRelationshipSource.MIGRATION),
emit_event=False,
+ replace_active=False,
)
+ except (relationships_logic.RelationshipOccupiedError, relationships_logic.ManagedRolePolicyError):
+ continue
assigned += 1
return assigned
diff --git a/products/customer_analytics/backend/management/commands/configure_account_ownership.py b/products/customer_analytics/backend/management/commands/configure_account_ownership.py
new file mode 100644
index 000000000000..dae1c3bf7af9
--- /dev/null
+++ b/products/customer_analytics/backend/management/commands/configure_account_ownership.py
@@ -0,0 +1,151 @@
+"""Choose which relationship definitions customer analytics may control and which warehouse view of
+external decisions fills each of them. Taking control of a definition enrolls no account (see
+``adopt_account_ownership``).
+
+ python manage.py configure_account_ownership --team-id 2 --control <definition uuid>
+ python manage.py configure_account_ownership --team-id 2 --claim-view <definition uuid> <view uuid> \\
+ --claims <definition uuid> enabled
+"""
+
+from typing import Any
+from uuid import UUID
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+from django.db import transaction
+from django.db.models import Q
+
+from posthog.models.team import Team
+
+from products.customer_analytics.backend.logic import ownership, ownership_claims
+from products.customer_analytics.backend.models import AccountRelationshipDefinition
+
+
+class Command(BaseCommand):
+ help = "Choose the controlled relationship definitions of a project and the claim view each one reads."
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, required=True)
+ parser.add_argument(
+ "--control",
+ type=UUID,
+ action="append",
+ default=[],
+ metavar="DEFINITION_ID",
+ help="Let customer analytics take control of this single-holder definition per account. Repeatable.",
+ )
+ parser.add_argument(
+ "--uncontrol",
+ type=UUID,
+ action="append",
+ default=[],
+ metavar="DEFINITION_ID",
+ help="Stop controlling this definition; refused while any account is enrolled under it. Repeatable.",
+ )
+ parser.add_argument(
+ "--claim-view",
+ nargs=2,
+ action="append",
+ default=[],
+ metavar=("DEFINITION_ID", "SAVED_QUERY_ID"),
+ help=(
+ "Bind the warehouse view of decisions that fill this controlled definition; see "
+ "logic/ownership_claims.py. Repeatable."
+ ),
+ )
+ parser.add_argument(
+ "--clear-claim-view",
+ type=UUID,
+ action="append",
+ default=[],
+ metavar="DEFINITION_ID",
+ help="Unbind the definition's claim view, which also switches its sweep off. Repeatable.",
+ )
+ parser.add_argument(
+ "--claims",
+ nargs=2,
+ action="append",
+ default=[],
+ metavar=("DEFINITION_ID", "enabled|disabled"),
+ help="Switch the sweep on or off for this definition's view. Repeatable.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ team = Team.objects.filter(id=options["team_id"]).first()
+ if team is None:
+ raise CommandError(f"No team {options['team_id']}")
+ claim_views = self._one_per_definition(
+ [(self._uuid(definition_id), self._uuid(view_id)) for definition_id, view_id in options["claim_view"]],
+ "--claim-view",
+ )
+ switches = self._one_per_definition(
+ [(self._uuid(definition_id), self._switch(state)) for definition_id, state in options["claims"]], "--claims"
+ )
+ contradicted = set(options["clear_claim_view"]) & {definition_id for definition_id, _ in claim_views}
+ if contradicted:
+ raise CommandError(
+ f"--claim-view and --clear-claim-view both name {', '.join(str(d) for d in sorted(contradicted))}"
+ )
+
+ # One transaction, so a refused change leaves the configuration as it was. Every definition
+ # the call touches is locked first, by id, so two concurrent calls take their locks in one
+ # order. Control starts before views are bound and ends after they are cleared, so one call
+ # can move a view from one definition to another.
+ try:
+ with transaction.atomic():
+ referenced = {
+ *options["control"],
+ *options["uncontrol"],
+ *options["clear_claim_view"],
+ *(definition_id for definition_id, _ in claim_views),
+ *(definition_id for definition_id, _ in switches),
+ }
+ ownership.lock_definitions(team.id, sorted(referenced))
+ for definition_id in options["control"]:
+ ownership.set_controlled(team.id, definition_id, True)
+ for definition_id in options["clear_claim_view"]:
+ ownership_claims.bind_claim_view(team.id, definition_id, None)
+ for definition_id, view_id in claim_views:
+ ownership_claims.bind_claim_view(team.id, definition_id, view_id)
+ for definition_id, enabled in switches:
+ ownership_claims.set_claims_enabled(team.id, definition_id, enabled)
+ for definition_id in options["uncontrol"]:
+ ownership.set_controlled(team.id, definition_id, False)
+ except (ownership.InvalidControlChangeError, ownership_claims.ClaimSourceMisconfigured) as error:
+ raise CommandError(str(error))
+
+ # Every definition with any ownership state, so nothing controlled or bound goes unlisted.
+ listed = (
+ AccountRelationshipDefinition.objects.for_team(team.id)
+ .filter(Q(is_controlled=True) | Q(claims_enabled=True) | Q(claim_saved_query__isnull=False))
+ .order_by("name")
+ )
+ for definition in listed:
+ self.stdout.write(
+ f"team {team.id}: {definition.name} ({definition.id}) "
+ f"controlled={'yes' if definition.is_controlled else 'no'} "
+ f"claims={'enabled' if definition.claims_enabled else 'disabled'} "
+ f"claim_view={definition.claim_saved_query_id or '<unset>'}"
+ )
+
+ @staticmethod
+ def _one_per_definition(pairs: list[tuple[UUID, Any]], flag: str) -> list[tuple[UUID, Any]]:
+ """Refuse a definition named twice with different values, which would otherwise resolve by order."""
+ seen: dict[UUID, Any] = {}
+ for definition_id, value in pairs:
+ if definition_id in seen and seen[definition_id] != value:
+ raise CommandError(f"{flag} names {definition_id} twice with different values")
+ seen[definition_id] = value
+ return list(seen.items())
+
+ @staticmethod
+ def _uuid(value: str) -> UUID:
+ try:
+ return UUID(value)
+ except ValueError:
+ raise CommandError(f"{value} is not a UUID")
+
+ @staticmethod
+ def _switch(value: str) -> bool:
+ if value not in ("enabled", "disabled"):
+ raise CommandError(f"--claims takes enabled or disabled, not {value}")
+ return value == "enabled"
diff --git a/products/customer_analytics/backend/management/commands/reconcile_ownership_claims.py b/products/customer_analytics/backend/management/commands/reconcile_ownership_claims.py
new file mode 100644
index 000000000000..56133937a785
--- /dev/null
+++ b/products/customer_analytics/backend/management/commands/reconcile_ownership_claims.py
@@ -0,0 +1,35 @@
+"""Apply the Salesforce Task decisions in the views bound to a project's controlled relationships
+once, and print what happened. The Temporal schedule in ``temporal/ownership_claims.py`` does the
+same for every project on a timer. Do not run this while that schedule is sweeping the same project:
+of two sweeps at once, the older read can apply a claim the newer one has already seen released.
+
+ python manage.py reconcile_ownership_claims --team-id 2
+"""
+
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+
+from posthog.models.team import Team
+
+from products.customer_analytics.backend.logic.ownership_claims import reconcile_ownership_claims
+
+
+class Command(BaseCommand):
+ help = "Apply the Salesforce Task ownership decisions in the views bound to a project's controlled relationships."
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, required=True)
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ team = Team.objects.filter(id=options["team_id"]).first()
+ if team is None:
+ raise CommandError(f"No team {options['team_id']}")
+ result = reconcile_ownership_claims(team)
+ if result.skipped:
+ self.stdout.write(
+ "skipped: no controlled relationship in this project has a live claim view bound with claims enabled"
+ )
+ return
+ summary = ", ".join(f"{outcome}={count}" for outcome, count in sorted(result.outcomes.items()))
+ self.stdout.write(f"{result.decisions} row(s) read: {summary or 'none'}")
diff --git a/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py b/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py
index 101341ffeb2a..6c735473d28d 100644
--- a/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py
+++ b/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py
@@ -29,6 +29,7 @@ from posthog.models.scoping import team_scope
from posthog.persons_db import persons_db_connection
from products.customer_analytics.backend.facade.api import create_account
+from products.customer_analytics.backend.facade.enums import AccountRelationshipSource
from products.customer_analytics.backend.logic import relationships as relationships_logic
from products.customer_analytics.backend.models.account import Account, AccountProperties
from products.customer_analytics.backend.models.relationship import AccountRelationshipDefinition
@@ -207,7 +208,7 @@ class Command(BaseCommand):
account=account,
definition=definition,
user=user_pool[(index + offset) % len(user_pool)],
- created_by=creator,
+ actor=relationships_logic.Actor(source=AccountRelationshipSource.MIGRATION, user=creator),
emit_event=False,
)
diff --git a/products/customer_analytics/backend/max_tools.py b/products/customer_analytics/backend/max_tools.py
index ea4883c6ca25..f3311992870d 100644
--- a/products/customer_analytics/backend/max_tools.py
+++ b/products/customer_analytics/backend/max_tools.py
@@ -19,6 +19,7 @@ from products.customer_analytics.backend.facade.api import (
create_account,
update_account,
)
+from products.customer_analytics.backend.facade.enums import AccountRelationshipSource
from products.customer_analytics.backend.logic import relationships as relationships_logic
from products.customer_analytics.backend.models import Account, AccountRelationshipDefinition
from products.notebooks.backend.facade.content import build_markdown_notebook_content, is_markdown_notebook_content
@@ -122,7 +123,9 @@ UPSERT_ACCOUNT_TOOL_DESCRIPTION = dedent("""
# Relationships
Pass `relationships` to assign users to the account's relationships (CSM, Account executive, or
any definition the team has created), keyed by definition name: the value is the PostHog user id,
- or null to end the current assignment. Only the named definitions are changed.
+ or null to end the current assignment. Only the named definitions are changed. A controlled
+ relationship that Customer analytics manages for the account cannot be changed through this
+ tool; the change is made from the account page.
# Tags
Pass `tags` to set the account's tags. On update this REPLACES the existing tag set.
@@ -333,22 +336,26 @@ class UpsertAccountTool(MaxTool):
missing = sorted(user_ids - memberships.keys())
if missing:
raise RelationshipAssignmentError(f"User {missing[0]} is not a member of this organization.")
- for name, user_id in assignments.items():
- definition = definitions[name]
- if user_id is None:
- relationships_logic.end_active(
+ actor = relationships_logic.Actor(source=AccountRelationshipSource.AI, user=self._user)
+ try:
+ for name, user_id in assignments.items():
+ definition = definitions[name]
+ if user_id is None:
+ relationships_logic.end_active(
+ team_id=self._team.id, account=account, definition=definition, actor=actor
+ )
+ continue
+ relationships_logic.assign(
team_id=self._team.id,
account=account,
definition=definition,
- actor=self._user,
+ user=memberships[user_id].user,
+ actor=actor,
)
- continue
- relationships_logic.assign(
- team_id=self._team.id,
- account=account,
- definition=definition,
- user=memberships[user_id].user,
- created_by=self._user,
+ except relationships_logic.ManagedRolePolicyError:
+ raise RelationshipAssignmentError(
+ "This relationship is controlled in Customer analytics and is changed from the account page, "
+ "not through this tool."
)
diff --git a/products/customer_analytics/backend/migrations/0053_ownership_authority.py b/products/customer_analytics/backend/migrations/0053_ownership_authority.py
new file mode 100644
index 000000000000..caacb17b800a
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0053_ownership_authority.py
@@ -0,0 +1,127 @@
+# Generated by Django 5.2.17 on 2026-09-15 09:30
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ (
+ "customer_analytics",
+ "0052_alter_account_team_alter_accountchannelsummary_team_and_more",
+ ),
+ ("data_modeling", "0039_datamodelingjob_manually_triggered_by"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="accountrelationshipdefinition",
+ name="is_controlled",
+ field=models.BooleanField(
+ db_default=False,
+ default=False,
+ help_text="Whether customer analytics can take control of this relationship per account. Rows under a controlled definition cannot be deleted. On an account where control has started, only a person can change the relationship and an empty relationship is a deliberate decision.",
+ ),
+ ),
+ migrations.AddField(
+ model_name="accountrelationship",
+ name="source",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("human", "Human"),
+ ("workflow", "Workflow"),
+ ("ai", "AI"),
+ ("salesforce_claim", "Salesforce claim"),
+ ("migration", "Migration"),
+ ],
+ max_length=32,
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="accountrelationship",
+ name="source_ref",
+ field=models.CharField(blank=True, max_length=400, null=True),
+ ),
+ migrations.AddField(
+ model_name="accountrelationshipdefinition",
+ name="claim_saved_query",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.RESTRICT,
+ related_name="+",
+ to="data_modeling.datawarehousesavedquery",
+ ),
+ ),
+ migrations.AddField(
+ model_name="accountrelationshipdefinition",
+ name="claims_enabled",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ migrations.CreateModel(
+ name="AccountRelationshipControl",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("controlled_at", models.DateTimeField()),
+ (
+ "account",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="relationship_controls",
+ to="customer_analytics.account",
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "definition",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.RESTRICT,
+ related_name="controls",
+ to="customer_analytics.accountrelationshipdefinition",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("team", "account", "definition"),
+ name="unique_relationship_control_per_account",
+ ),
+ ],
+ },
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/0054_source_ref_unique_index.py b/products/customer_analytics/backend/migrations/0054_source_ref_unique_index.py
new file mode 100644
index 000000000000..7bde6b36ce0a
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0054_source_ref_unique_index.py
@@ -0,0 +1,50 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import CreateIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # CONCURRENTLY can't run inside a transaction.
+ atomic = False
+
+ dependencies = [
+ ("customer_analytics", "0053_ownership_authority"),
+ ]
+
+ operations = [
+ # Built concurrently so the relationship table stays writable while the index is created. The
+ # next migration attaches it as the constraint Django's state declares.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="unique_relationship_per_source_ref",
+ table_name="customer_analytics_accountrelationship",
+ columns="(team_id, source, source_ref)",
+ unique=True,
+ ),
+ ],
+ ),
+ # A conditional UniqueConstraint is an index to Django, so the state matches the index as built.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddConstraint(
+ model_name="accountrelationshipdefinition",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("claim_saved_query__isnull", False)),
+ fields=("team", "claim_saved_query"),
+ name="unique_claim_view_per_definition",
+ ),
+ ),
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="unique_claim_view_per_definition",
+ table_name="customer_analytics_accountrelationshipdefinition",
+ columns="(team_id, claim_saved_query_id)",
+ unique=True,
+ where="WHERE claim_saved_query_id IS NOT NULL",
+ ),
+ ],
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/0055_source_ref_unique_constraint.py b/products/customer_analytics/backend/migrations/0055_source_ref_unique_constraint.py
new file mode 100644
index 000000000000..5252c0b1ae16
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0055_source_ref_unique_constraint.py
@@ -0,0 +1,47 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0054_source_ref_unique_index"),
+ ]
+
+ operations = [
+ # Django drops an unconditional UniqueConstraint with DROP CONSTRAINT, so the index built by
+ # the previous migration is attached as a table constraint to match the state declared here.
+ # The concurrent build leaves lock_timeout at zero for the session, so the attachment, which
+ # takes a brief ACCESS EXCLUSIVE lock, restores a bound for its own transaction. The guard
+ # keeps a bin/migrate retry from failing on a constraint that already exists.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddConstraint(
+ model_name="accountrelationship",
+ constraint=models.UniqueConstraint(
+ fields=("team", "source", "source_ref"),
+ name="unique_relationship_per_source_ref",
+ ),
+ ),
+ ],
+ database_operations=[
+ migrations.RunSQL(
+ sql="""
+ SET LOCAL lock_timeout = '20s';
+ DO $$
+ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint WHERE conname = 'unique_relationship_per_source_ref'
+ ) THEN
+ ALTER TABLE "customer_analytics_accountrelationship"
+ ADD CONSTRAINT "unique_relationship_per_source_ref"
+ UNIQUE USING INDEX "unique_relationship_per_source_ref"; -- existing-table-constraint-ignore
+ END IF;
+ END $$;
+ """,
+ reverse_sql="""
+ ALTER TABLE "customer_analytics_accountrelationship"
+ DROP CONSTRAINT IF EXISTS "unique_relationship_per_source_ref";
+ """,
+ ),
+ ],
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index f8a0535aaf6c..6fd67a338d12 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0052_alter_account_team_alter_accountchannelsummary_team_and_more
+0055_source_ref_unique_constraint
diff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.py
index 48d839d4be7b..ff6c9fb64916 100644
--- a/products/customer_analytics/backend/models/__init__.py
+++ b/products/customer_analytics/backend/models/__init__.py
@@ -31,7 +31,7 @@ from .feature_request import (
FeatureRequestStatus,
)
from .meeting import Meeting, MeetingParticipant, MeetingResponseStatus, MeetingStatus
-from .relationship import AccountRelationship, AccountRelationshipDefinition
+from .relationship import AccountRelationship, AccountRelationshipControl, AccountRelationshipDefinition
from .team_customer_analytics_config import TeamCustomerAnalyticsConfig
from .user_customer_analytics_config import UserCustomerAnalyticsConfig
@@ -45,6 +45,7 @@ __all__ = [
"AccountTrackRuleRunStatus",
"AccountTrackRuleRunTrigger",
"AccountRelationship",
+ "AccountRelationshipControl",
"AccountRelationshipDefinition",
"Announcement",
"AnnouncementDelivery",
diff --git a/products/customer_analytics/backend/models/relationship.py b/products/customer_analytics/backend/models/relationship.py
index 66b771fa6cc2..2c9887d946f1 100644
--- a/products/customer_analytics/backend/models/relationship.py
+++ b/products/customer_analytics/backend/models/relationship.py
@@ -5,6 +5,8 @@ from django.utils import timezone
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
+from products.customer_analytics.backend.facade.enums import AccountRelationshipSource
+
class AccountRelationshipDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
@@ -22,6 +24,24 @@ class AccountRelationshipDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaF
default=True,
help_text="Whether only one user can hold this relationship per account at a time, e.g. a single CSM per account.",
)
+ is_controlled = models.BooleanField(
+ default=False,
+ db_default=False,
+ help_text=(
+ "Whether customer analytics can take control of this relationship per account. Rows under a controlled "
+ "definition cannot be deleted. On an account where control has started, only a person can change the "
+ "relationship and an empty relationship is a deliberate decision."
+ ),
+ )
+ # The warehouse view of external decisions that fill this relationship, and whether the sweep reads
+ # it. The view maps the source's frozen fields onto the columns `logic/ownership_claims.py`
+ # documents, so source field names stay out of this codebase. Only a controlled definition can
+ # bind one, because a claim fills only a managed relationship. RESTRICT keeps a bound view from
+ # being hard-deleted underneath the sweep, which would leave claims enabled with nothing to read.
+ claim_saved_query = models.ForeignKey(
+ "data_modeling.DataWarehouseSavedQuery", on_delete=models.RESTRICT, null=True, blank=True, related_name="+"
+ )
+ claims_enabled = models.BooleanField(default=False, db_default=False)
class Meta:
constraints = [
@@ -29,6 +49,13 @@ class AccountRelationshipDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaF
fields=["team", "name"],
name="unique_relationship_definition_name",
),
+ # A Task id is unique per team, so a view read into two definitions would fill only the
+ # first and answer `already_applied` for the second without a trace.
+ models.UniqueConstraint(
+ fields=["team", "claim_saved_query"],
+ condition=Q(claim_saved_query__isnull=False),
+ name="unique_claim_view_per_definition",
+ ),
]
@@ -48,6 +75,12 @@ class AccountRelationship(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):
started_at = models.DateTimeField(default=timezone.now)
ended_at = models.DateTimeField(null=True, blank=True)
+ source = models.CharField(max_length=32, choices=AccountRelationshipSource.choices, null=True, blank=True)
+ # The id of the external record that decided this row, when an integration wrote it (for a
+ # Salesforce claim, the Task id). Unique per team and source, so an integration that reads the
+ # same record again finds this row, ended or not, instead of writing a second one.
+ source_ref = models.CharField(max_length=400, null=True, blank=True)
+
class Meta:
indexes = [
models.Index(
@@ -61,3 +94,41 @@ class AccountRelationship(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):
name="idx_active_rel_by_user",
),
]
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team", "source", "source_ref"],
+ name="unique_relationship_per_source_ref",
+ ),
+ ]
+
+
+class AccountRelationshipControl(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):
+ """Customer analytics holds authority over one controlled relationship on one account.
+
+ The row exists from enrollment on; its absence means the relationship is unmanaged there, whatever
+ the relationship rows say. ``controlled_at`` is the enrollment or the last decision a person took on
+ the relationship here, and it is the fence an automated claim must be newer than. Automated writers
+ never move it.
+ """
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+"
+ )
+ account = models.ForeignKey(
+ "customer_analytics.Account", on_delete=models.CASCADE, related_name="relationship_controls"
+ )
+ # RESTRICT keeps a controlled definition deletable only once no account is enrolled under it,
+ # while a team deletion still cascades through both rows.
+ definition = models.ForeignKey(
+ "customer_analytics.AccountRelationshipDefinition", on_delete=models.RESTRICT, related_name="controls"
+ )
+ controlled_at = models.DateTimeField()
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team", "account", "definition"],
+ name="unique_relationship_control_per_account",
+ ),
+ ]
diff --git a/products/customer_analytics/backend/presentation/views/account_actions.py b/products/customer_analytics/backend/presentation/views/account_actions.py
index d8a7caaf2d7a..dce2021a7b89 100644
--- a/products/customer_analytics/backend/presentation/views/account_actions.py
+++ b/products/customer_analytics/backend/presentation/views/account_actions.py
@@ -21,6 +21,9 @@ from products.customer_analytics.backend.facade import (
api as facade,
contracts,
)
+from products.customer_analytics.backend.presentation.views.ownership_serializers import (
+ ExternalAccountOwnershipSerializer,
+)
ACCOUNT_ACTION_AUTH_COUNTER = Counter(
"posthog_customer_analytics_account_action_auth_total",
@@ -56,6 +59,7 @@ def _external_account_body(account: contracts.ExternalAccount) -> dict[str, Any]
"churned_at": account.churned_at,
"ignored_at": account.ignored_at,
"properties": account.properties,
+ "ownership": ExternalAccountOwnershipSerializer(account.ownership).data,
"tags": account.tags,
"relationships": account.relationships,
"custom_properties": account.custom_properties,
@@ -68,6 +72,10 @@ _UPDATE_ERROR_RESPONSES = {
"Invalid account properties",
status.HTTP_400_BAD_REQUEST,
),
+ contracts.ExternalAccountUpdateError.ROLE_MANAGED: (
+ "This relationship is controlled in Customer analytics and can't be changed by a workflow",
+ status.HTTP_409_CONFLICT,
+ ),
# A server fault (the facade's blanket except), not a client error: 500 keeps the CDP
# fetch layer retrying instead of failing the workflow permanently.
contracts.ExternalAccountUpdateError.UPDATE_FAILED: (
diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.py
index 8c7fa590f9a3..efd40ebb698a 100644
--- a/products/customer_analytics/backend/presentation/views/external.py
+++ b/products/customer_analytics/backend/presentation/views/external.py
@@ -56,6 +56,9 @@ from products.customer_analytics.backend.presentation.views.account_actions impo
handle_account_set_properties,
handle_account_update,
)
+from products.customer_analytics.backend.presentation.views.ownership_serializers import (
+ ExternalAccountOwnershipSerializer,
+)
logger = structlog.get_logger(__name__)
@@ -172,10 +175,8 @@ def _authenticate_psak_team(request: Request) -> tuple[Team, None] | tuple[None,
psak = authenticator.project_secret_api_key
key_scopes = set(get_authenticator_scopes(authenticator) or [])
- valid_scopes = {
- EXTERNAL_ACCOUNT_READ_SCOPE,
- EXTERNAL_ACCOUNT_READ_SCOPE.replace(":read", ":write"),
- }
+ # A key that may write accounts may read them too; the reverse does not hold.
+ valid_scopes = {EXTERNAL_ACCOUNT_READ_SCOPE, "account:write"}
if "*" not in key_scopes and key_scopes.isdisjoint(valid_scopes):
return None, Response(
{"error": f"API key missing required scope '{EXTERNAL_ACCOUNT_READ_SCOPE}'"},
@@ -219,6 +220,9 @@ class ExternalAccountSerializer(serializers.Serializer):
child=serializers.JSONField(help_text="Property value: a string or null."),
help_text="Typed account properties: external-system ids. Role assignments live under `relationships`.",
)
+ ownership = ExternalAccountOwnershipSerializer(
+ help_text="Authority state of each relationship the project controls."
+ )
tags = serializers.ListField(
child=serializers.CharField(), help_text="Tag names on the account, sorted alphabetically."
)
@@ -288,9 +292,9 @@ class ExternalAccountView(APIView):
},
summary="Get an external customer analytics account",
description=(
- "Fetch one account by external ID with its properties, tags, active relationship assignments "
- "and custom property values. Accepts the team secret API token or a project secret API key with "
- "the `account:read` scope."
+ "Fetch one account by external ID with its properties, controlled relationship ownership, tags, active "
+ "relationship assignments and custom property values. Accepts the team secret API token or a "
+ "project secret API key with the `account:read` scope."
),
)
def get(self, request: Request) -> Response:
@@ -363,6 +367,16 @@ class ExternalAccountListQuerySerializer(serializers.Serializer):
default=False,
help_text="Include ignored accounts. Ignored accounts are hidden by default.",
)
+ managed_only = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "When true, return only accounts where customer analytics holds authority over at least one "
+ "controlled relationship, including accounts whose managed relationships are cleared and "
+ "accounts that are ignored. Authority does not end when an account is ignored, so "
+ "`include_ignored` is implied."
+ ),
+ )
def validate_limit(self, value: int) -> int:
return max(1, min(value, EXTERNAL_ACCOUNT_LIST_MAX_LIMIT))
@@ -397,6 +411,9 @@ class ExternalAccountListItemSerializer(serializers.Serializer):
allow_null=True,
help_text="When Track Rules ignored the account, or null if it is tracked.",
)
+ ownership = ExternalAccountOwnershipSerializer(
+ help_text="Authority state of each relationship the project controls."
+ )
relationships = serializers.DictField(
child=ExternalAccountListAssignmentSerializer(many=True),
help_text=(
@@ -465,9 +482,11 @@ class ExternalAccountListView(APIView):
},
summary="List external customer analytics accounts",
description=(
- "List tracked accounts with external IDs, lifecycle timestamps, and active relationship assignments. "
- "Set `include_ignored=true` to include ignored accounts. Requires a project secret API key with the "
- "`account:read` scope."
+ "List tracked accounts with external IDs, lifecycle timestamps, controlled relationship "
+ "ownership, and active relationship assignments. Set `include_ignored=true` to include "
+ "ignored accounts and `managed_only=true` to read only the accounts customer analytics "
+ "holds ownership authority for. Requires a project secret API key with the `account:read` "
+ "scope."
),
)
def get(self, request: Request) -> Response:
@@ -489,6 +508,7 @@ class ExternalAccountListView(APIView):
limit=query_data["limit"],
assigned_only=query_data["assigned_only"],
include_ignored=query_data["include_ignored"],
+ managed_only=query_data["managed_only"],
)
return Response(ExternalAccountListPageSerializer(page).data)
diff --git a/products/customer_analytics/backend/presentation/views/ownership_serializers.py b/products/customer_analytics/backend/presentation/views/ownership_serializers.py
new file mode 100644
index 000000000000..597544b6eafb
--- /dev/null
+++ b/products/customer_analytics/backend/presentation/views/ownership_serializers.py
@@ -0,0 +1,68 @@
+"""
+Response serializers for the ``ownership`` block on the external account routes. Kept apart from
+``external.py`` because ``account_actions.py`` renders the single-account body by hand and needs
+the same shape without importing the views.
+"""
+
+from rest_framework import serializers
+
+from products.customer_analytics.backend.facade.enums import OwnershipRoleDiagnostic, OwnershipRoleState
+
+
+class ExternalAccountOwnershipHolderSerializer(serializers.Serializer):
+ user_id = serializers.IntegerField(help_text="PostHog user id of the holder.")
+ email = serializers.CharField(
+ allow_null=True, help_text="Current email address of the holder; null for a holder outside the organization."
+ )
+ name = serializers.CharField(
+ allow_null=True, help_text="Current display name of the holder; null when unset or outside the organization."
+ )
+ is_organization_member = serializers.BooleanField(
+ help_text="Whether the holder is currently a member of the project's organization."
+ )
+ is_active = serializers.BooleanField(help_text="Whether the holder's PostHog user account is active.")
+
+
+class ExternalAccountRoleOwnershipSerializer(serializers.Serializer):
+ definition_id = serializers.UUIDField(
+ help_text="The controlled relationship definition. Map it to the role you project; it does not change."
+ )
+ definition_name = serializers.CharField(help_text="Current name of the relationship definition.")
+ state = serializers.ChoiceField(
+ choices=OwnershipRoleState.choices,
+ help_text=(
+ "`unmanaged`: customer analytics does not hold authority over this relationship on this account; "
+ "the holder, if any, is a legacy assignment. `assigned`: the holder is authoritative. "
+ "`cleared`: the relationship is authoritatively empty. `blocked`: the relationship is managed but its "
+ "holder cannot be projected; see `diagnostics` and keep the last applied value."
+ ),
+ )
+ controlled_at = serializers.DateTimeField(
+ allow_null=True,
+ help_text="When customer analytics last decided this relationship on this account; null while unmanaged.",
+ )
+ relationship_id = serializers.UUIDField(
+ allow_null=True, help_text="The active relationship holding the role, or null when empty."
+ )
+ holder = ExternalAccountOwnershipHolderSerializer(allow_null=True, help_text="The current holder, or null.")
+ diagnostics = serializers.ListField(
+ child=serializers.ChoiceField(choices=OwnershipRoleDiagnostic.choices),
+ help_text="Why a managed relationship is blocked. Informational on an unmanaged one.",
+ )
+
+
+class ExternalAccountOwnershipSerializer(serializers.Serializer):
+ account_id = serializers.CharField(help_text="Account UUID, the canonical identity within this project.")
+ external_id = serializers.CharField(
+ allow_null=True, help_text="External account key: the group key the account is linked to."
+ )
+ region = serializers.CharField(
+ allow_null=True, help_text="Region of this PostHog instance (`us`, `eu`), or null when self-hosted."
+ )
+ roles = ExternalAccountRoleOwnershipSerializer(
+ many=True,
+ help_text=(
+ "One entry per controlled relationship definition of the project, in name order, whether or not this "
+ "account is managed under it. Empty when the project controls no relationship."
+ ),
+ )
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 7174eb85399f..a331197bdd2e 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -78,7 +78,7 @@ from products.customer_analytics.backend.facade.contracts import (
MeetingParticipantView,
MeetingView,
)
-from products.customer_analytics.backend.facade.enums import AccountPropertyPinKind
+from products.customer_analytics.backend.facade.enums import AccountPropertyPinKind, AccountRelationshipSource
class AccountTrackRuleFieldSerializer(serializers.Serializer):
@@ -2048,11 +2048,20 @@ class AccountRelationshipDefinitionSerializer(DataclassSerializer):
default=True,
help_text="Whether only one user can hold this relationship per account at a time, e.g. a single CSM per account.",
)
+ is_controlled = serializers.BooleanField(
+ read_only=True,
+ help_text=(
+ "Whether customer analytics can take control of this relationship per account. Rows under a controlled "
+ "relationship can't be deleted. On an account where control has started, only a person can change the "
+ "relationship and an empty relationship is a deliberate decision. Set by project operators, not through "
+ "this API."
+ ),
+ )
class Meta:
dataclass = AccountRelationshipDefinition
ref_name = "AccountRelationshipDefinition"
- fields = ["id", "name", "description", "is_single_holder"]
+ fields = ["id", "name", "description", "is_single_holder", "is_controlled"]
class AccountAssignmentSerializer(DataclassSerializer):
@@ -2081,11 +2090,19 @@ class AccountRelationshipSerializer(DataclassSerializer):
ended_at = serializers.DateTimeField(
read_only=True, allow_null=True, help_text="When this assignment ended; null while it is active."
)
+ # The wire field is named `source`. DRF pops declared fields off the class, so only the stubs
+ # see a clash with `Field.source`.
+ source = serializers.ChoiceField( # type: ignore[assignment]
+ choices=AccountRelationshipSource.choices,
+ read_only=True,
+ allow_null=True,
+ help_text="Which kind of writer made this assignment; null on rows older than provenance tracking.",
+ )
class Meta:
dataclass = AccountRelationship
ref_name = "AccountRelationship"
- fields = ["id", "definition", "user", "started_at", "ended_at"]
+ fields = ["id", "definition", "user", "started_at", "ended_at", "source"]
class AccountRelationshipWriteSerializer(serializers.Serializer):
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 29da19a290f6..8325baa5107c 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -38,7 +38,7 @@ from rest_framework.throttling import UserRateThrottle
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.tagged_item import TaggedItemViewSetMixin
-from posthog.auth import SessionAuthentication
+from posthog.auth import SessionAuthentication, is_mcp_request
from posthog.cdp.services.icons import CDPIconsService
from posthog.event_usage import report_user_action
from posthog.exceptions import Conflict
@@ -1213,6 +1213,8 @@ class AccountRelationshipDefinitionViewSet(
)
except api.AccountRelationshipDefinitionConflictError as e:
raise Conflict(str(e))
+ except api.AccountRelationshipDefinitionControlledError:
+ raise Conflict("This relationship is controlled and must stay single-holder.")
if definition is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(AccountRelationshipDefinitionSerializer(instance=definition).data)
@@ -1222,7 +1224,11 @@ class AccountRelationshipDefinitionViewSet(
return self.update(request, *args, **kwargs)
def destroy(self, request: Request, *args, **kwargs) -> Response:
- if not api.delete_account_relationship_definition(team_id=self.team_id, definition_id=self.kwargs["pk"]):
+ try:
+ deleted = api.delete_account_relationship_definition(team_id=self.team_id, definition_id=self.kwargs["pk"])
+ except api.AccountRelationshipDefinitionControlledError:
+ raise Conflict("This relationship is controlled and can't be deleted while it is.")
+ if not deleted:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(status=status.HTTP_204_NO_CONTENT)
@@ -2059,6 +2065,11 @@ class AccountViewSet(
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
except api.ResourceForbiddenError:
raise PermissionDenied()
+ except api.AccountOwnershipManagedError:
+ raise Conflict(
+ "This account has a controlled relationship, or history under one, so it can't be deleted. "
+ "Ignore the account to hide it instead."
+ )
return Response(status=status.HTTP_204_NO_CONTENT)
@@ -2366,6 +2377,11 @@ class AccountRelationshipDeletePermission(BasePermission):
return request.method != "DELETE" or TeamMemberStrictManagementPermission().has_permission(request, view)
+_AGENT_ROLE_MANAGED = (
+ "This relationship is controlled here and can't be changed by an agent. Change it from the account page."
+)
+
+
@extend_schema(
tags=["customer_analytics"],
parameters=[
@@ -2425,6 +2441,7 @@ class AccountRelationshipViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
definition_id=write.validated_data["definition"],
user_id=write.validated_data["user"],
created_by=cast(User, request.user),
+ via_agent=is_mcp_request(request),
)
except api.Account_DoesNotExist:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
@@ -2432,6 +2449,8 @@ class AccountRelationshipViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
raise ValidationError({"definition": "Relationship definition not found."})
except api.AccountRelationshipAssigneeNotInOrganization:
raise ValidationError({"user": "User is not a member of this organization."})
+ except api.AccountRelationshipRoleManagedError:
+ raise Conflict(_AGENT_ROLE_MANAGED)
return Response(AccountRelationshipSerializer(relationship).data, status=status.HTTP_201_CREATED)
@extend_schema(request=None, responses={200: AccountRelationshipSerializer})
@@ -2440,12 +2459,16 @@ class AccountRelationshipViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
account_id = self._accessible_account_id()
if account_id is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
- relationship = api.end_account_relationship(
- team_id=self.team_id,
- account_id=account_id,
- relationship_id=self.kwargs["pk"],
- actor=cast(User, request.user),
- )
+ try:
+ relationship = api.end_account_relationship(
+ team_id=self.team_id,
+ account_id=account_id,
+ relationship_id=self.kwargs["pk"],
+ actor=cast(User, request.user),
+ via_agent=is_mcp_request(request),
+ )
+ except api.AccountRelationshipRoleManagedError:
+ raise Conflict(_AGENT_ROLE_MANAGED)
if relationship is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(AccountRelationshipSerializer(relationship).data)
@@ -2457,12 +2480,16 @@ class AccountRelationshipViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
)
if account_id is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
- deleted = api.delete_account_relationship(
- team_id=self.team_id,
- account_id=account_id,
- relationship_id=self.kwargs["pk"],
- actor=cast(User, request.user),
- )
+ try:
+ deleted = api.delete_account_relationship(
+ team_id=self.team_id,
+ account_id=account_id,
+ relationship_id=self.kwargs["pk"],
+ actor=cast(User, request.user),
+ via_agent=is_mcp_request(request),
+ )
+ except api.AccountRelationshipProtectedError:
+ raise Conflict("The history of a controlled relationship can't be deleted. End the assignment instead.")
if not deleted:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/products/customer_analytics/backend/temporal/__init__.py b/products/customer_analytics/backend/temporal/__init__.py
index dff926a7251d..9d5703141314 100644
--- a/products/customer_analytics/backend/temporal/__init__.py
+++ b/products/customer_analytics/backend/temporal/__init__.py
@@ -16,6 +16,12 @@ from products.customer_analytics.backend.temporal.calendar_sync import (
calendar_sync_integration_activity,
google_account_email_backfill_activity,
)
+from products.customer_analytics.backend.temporal.ownership_claims import (
+ OwnershipClaimsCoordinatorWorkflow,
+ OwnershipClaimsSweepWorkflow,
+ ownership_claims_collect_teams_activity,
+ ownership_claims_sweep_activity,
+)
WORKFLOWS = [
AccountTrackRuleCoordinatorWorkflow,
@@ -23,6 +29,8 @@ WORKFLOWS = [
CalendarSyncCoordinatorWorkflow,
CalendarSyncWorkflow,
GoogleAccountBackfillWorkflow,
+ OwnershipClaimsCoordinatorWorkflow,
+ OwnershipClaimsSweepWorkflow,
]
ACTIVITIES = [
account_track_rule_collect_configs_activity,
@@ -34,4 +42,6 @@ ACTIVITIES = [
calendar_sync_collect_integrations_activity,
calendar_sync_integration_activity,
google_account_email_backfill_activity,
+ ownership_claims_collect_teams_activity,
+ ownership_claims_sweep_activity,
]
diff --git a/products/customer_analytics/backend/temporal/ownership_claims.py b/products/customer_analytics/backend/temporal/ownership_claims.py
new file mode 100644
index 000000000000..51ea45155e77
--- /dev/null
+++ b/products/customer_analytics/backend/temporal/ownership_claims.py
@@ -0,0 +1,207 @@
+"""Scheduled delivery of Salesforce Task decisions into account ownership: a coordinator on a
+Temporal schedule starts one sweep child workflow per project with claims on. The decision contract
+and the sweep itself are documented in ``logic/ownership_claims.py``."""
+
+from __future__ import annotations
+
+import json
+
+from temporalio import activity, workflow
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleIntervalSpec,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleSpec,
+ ScheduleState,
+)
+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
+from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError
+
+with workflow.unsafe.imports_passed_through():
+ import threading
+ from collections.abc import Callable
+ from datetime import timedelta
+
+ from django.conf import settings
+
+ from posthog.dataclasses import frozen
+ from posthog.models.scoping import team_scope
+ from posthog.models.team import Team
+ from posthog.sync import database_sync_to_async
+ from posthog.temporal.common.heartbeat import Heartbeater
+ from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+
+ from products.customer_analytics.backend.logic.ownership_claims import (
+ ClaimReconciliation,
+ list_ownership_claim_team_ids,
+ reconcile_ownership_claims,
+ )
+
+OWNERSHIP_CLAIMS_COORDINATOR_WORKFLOW_NAME = "customer-analytics-ownership-claims-coordinator"
+OWNERSHIP_CLAIMS_COORDINATOR_SCHEDULE_ID = "customer-analytics-ownership-claims-coordinator-schedule"
+OWNERSHIP_CLAIMS_SWEEP_WORKFLOW_NAME = "customer-analytics-ownership-claims-sweep"
+# Every sweep reads each bound view to the end, so the cadence trades delivery latency against
+# repeated reads of views that have not changed since the last tick.
+OWNERSHIP_CLAIMS_INTERVAL = timedelta(minutes=15)
+# The coordinator abandons its children, so its own budget is the collect activity's three attempts
+# of two minutes plus queue wait. It must stay under the interval: an exception that is not a
+# FailureError fails the workflow task, which the server retries without limit, and the SKIP policy
+# then drops every later tick for as long as that run stays open.
+OWNERSHIP_CLAIMS_COORDINATOR_EXECUTION_TIMEOUT = timedelta(minutes=10)
+# A sweep holds its project's fixed child id until it closes, and every later tick skips a project
+# whose child is still open. The activity's own timeouts bound a sweep that runs, so this bound is
+# only for one that never runs: no worker polls its task, or the task fails on every attempt. It
+# stays far above the interval on purpose, because a bound near the activity's would also end a
+# sweep that is merely waiting behind other products on the shared queue.
+OWNERSHIP_CLAIMS_SWEEP_EXECUTION_TIMEOUT = timedelta(hours=24)
+
+
+@frozen
+class OwnershipClaimsCoordinatorInput:
+ pass
+
+
+@frozen
+class OwnershipClaimsSweepInput:
+ team_id: int
+
+
+@frozen
+class OwnershipClaimsProjects:
+ team_ids: tuple[int, ...]
+
+
+@frozen
+class OwnershipClaimsCoordinatorOutput:
+ enabled_teams: int
+ started_children: int
+ overlapping_children: int
+
+
+def ownership_claims_workflow_id(team_id: int) -> str:
+ return f"customer-analytics-ownership-claims-{team_id}"
+
+
+async def ownership_claims_collect_teams_activity(_input: OwnershipClaimsCoordinatorInput) -> OwnershipClaimsProjects:
+ team_ids = await database_sync_to_async(list_ownership_claim_team_ids, thread_sensitive=False)()
+ return OwnershipClaimsProjects(team_ids=tuple(team_ids))
+
+
+def _sweep(input: OwnershipClaimsSweepInput, should_stop: Callable[[], bool]) -> ClaimReconciliation:
+ try:
+ team = Team.objects.get(id=input.team_id)
+ with team_scope(team.id):
+ return reconcile_ownership_claims(team, should_stop=should_stop)
+ except Team.DoesNotExist as error:
+ # A deleted project does not heal by retrying; the next tick lists the projects again.
+ raise ApplicationError(str(error), non_retryable=True) from error
+
+
+async def ownership_claims_sweep_activity(input: OwnershipClaimsSweepInput) -> ClaimReconciliation:
+ stop = threading.Event()
+ async with Heartbeater():
+ try:
+ return await database_sync_to_async(_sweep, thread_sensitive=False)(input, stop.is_set)
+ finally:
+ # A timed-out or cancelled activity leaves its thread running. The flag makes the thread
+ # stop between two pages or two decisions, so at most the one decision already in flight
+ # can still commit beside the sweep the next tick starts; the tick after that repairs it.
+ stop.set()
+
+
[email protected](name=OWNERSHIP_CLAIMS_SWEEP_WORKFLOW_NAME)
+class OwnershipClaimsSweepWorkflow:
+ """One project's sweep. Decision rows never cross the activity boundary; only the outcome
+ counts return. Start it through the coordinator only: a direct start under another workflow id
+ can run beside the sweep already running for the project."""
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> OwnershipClaimsSweepInput:
+ return OwnershipClaimsSweepInput(**json.loads(inputs[0]))
+
+ @workflow.run
+ async def run(self, input: OwnershipClaimsSweepInput) -> ClaimReconciliation:
+ # A retried attempt could run beside the thread of an attempt that timed out, and an older
+ # read can apply a claim a newer read has already seen released. The next tick is the retry.
+ return await workflow.execute_activity(
+ ownership_claims_sweep_activity,
+ input,
+ start_to_close_timeout=timedelta(minutes=30),
+ heartbeat_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+
+
[email protected](name=OWNERSHIP_CLAIMS_COORDINATOR_WORKFLOW_NAME)
+class OwnershipClaimsCoordinatorWorkflow:
+ """Starts one sweep child per project with claims on. Child ids are fixed per project, so a
+ sweep still running at the next tick is left alone rather than started twice: an older read
+ could otherwise apply a claim that a newer read has already seen released. ALLOW_DUPLICATE lets
+ the next tick start a fresh sweep once the previous one has closed."""
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> OwnershipClaimsCoordinatorInput:
+ if not inputs:
+ return OwnershipClaimsCoordinatorInput()
+ return OwnershipClaimsCoordinatorInput(**json.loads(inputs[0]))
+
+ @workflow.run
+ async def run(self, input: OwnershipClaimsCoordinatorInput) -> OwnershipClaimsCoordinatorOutput:
+ projects = await workflow.execute_activity(
+ ownership_claims_collect_teams_activity,
+ input,
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ started = 0
+ overlapping = 0
+ for team_id in projects.team_ids:
+ try:
+ await workflow.start_child_workflow(
+ OwnershipClaimsSweepWorkflow.run,
+ OwnershipClaimsSweepInput(team_id=team_id),
+ id=ownership_claims_workflow_id(team_id),
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,
+ execution_timeout=OWNERSHIP_CLAIMS_SWEEP_EXECUTION_TIMEOUT,
+ )
+ started += 1
+ except WorkflowAlreadyStartedError:
+ overlapping += 1
+ return OwnershipClaimsCoordinatorOutput(
+ enabled_teams=len(projects.team_ids), started_children=started, overlapping_children=overlapping
+ )
+
+
+def _build_ownership_claims_coordinator_schedule(state: ScheduleState) -> Schedule:
+ return Schedule(
+ action=ScheduleActionStartWorkflow(
+ OWNERSHIP_CLAIMS_COORDINATOR_WORKFLOW_NAME,
+ OwnershipClaimsCoordinatorInput(),
+ id=OWNERSHIP_CLAIMS_COORDINATOR_WORKFLOW_NAME,
+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
+ execution_timeout=OWNERSHIP_CLAIMS_COORDINATOR_EXECUTION_TIMEOUT,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ ),
+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=OWNERSHIP_CLAIMS_INTERVAL)]),
+ state=state,
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+
+
+async def create_ownership_claims_coordinator_schedule(client: Client) -> None:
+ if await a_schedule_exists(client, OWNERSHIP_CLAIMS_COORDINATOR_SCHEDULE_ID):
+ # Every worker start runs this update, so it must carry an operator's pause rather than
+ # replace it with the default running state.
+ description = await client.get_schedule_handle(OWNERSHIP_CLAIMS_COORDINATOR_SCHEDULE_ID).describe()
+ schedule = _build_ownership_claims_coordinator_schedule(description.schedule.state)
+ await a_update_schedule(client, OWNERSHIP_CLAIMS_COORDINATOR_SCHEDULE_ID, schedule)
+ return
+
+ schedule = _build_ownership_claims_coordinator_schedule(ScheduleState())
+ await a_create_schedule(client, OWNERSHIP_CLAIMS_COORDINATOR_SCHEDULE_ID, schedule, trigger_immediately=False)
diff --git a/products/customer_analytics/backend/test/factories.py b/products/customer_analytics/backend/test/factories.py
index e8b701afe19d..648767bd028c 100644
--- a/products/customer_analytics/backend/test/factories.py
+++ b/products/customer_analytics/backend/test/factories.py
@@ -1,7 +1,8 @@
+from collections.abc import Iterable
from datetime import datetime
from typing import Any
-from django.apps import apps
+from django.utils import timezone
from posthog.models import User
@@ -9,6 +10,7 @@ from products.customer_analytics.backend.models import (
Account,
AccountChannelSummary,
AccountRelationship,
+ AccountRelationshipControl,
AccountRelationshipDefinition,
CustomerTask,
CustomPropertyDefinition,
@@ -22,6 +24,7 @@ from products.customer_analytics.backend.models import (
FeatureRequestProductAreaLink,
Meeting,
)
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
def create_account(*, team_id: int, name: str = "Acme Corp", **kwargs: Any) -> Account:
@@ -56,6 +59,16 @@ def create_account_relationship(
)
+def enroll_account(
+ account: Account, definition: AccountRelationshipDefinition, *, controlled_at: datetime | None = None
+) -> AccountRelationshipControl:
+ """A control row written directly, for tests that need a known fence rather than the audited
+ enrollment path."""
+ return AccountRelationshipControl.objects.for_team(account.team_id).create(
+ team_id=account.team_id, account=account, definition=definition, controlled_at=controlled_at or timezone.now()
+ )
+
+
def create_customer_task(*, team_id: int, name: str = "Review account", **kwargs: Any) -> CustomerTask:
return CustomerTask.objects.for_team(team_id).create(team_id=team_id, name=name, **kwargs)
@@ -142,14 +155,15 @@ def create_custom_property_definition(
def create_saved_query(
*, team_id: int, name: str = "enriched_users", is_materialized: bool = True, **kwargs: Any
-) -> Any:
+) -> DataWarehouseSavedQuery:
"""Create a data-warehouse view for tests. Materialized by default, which is what a view-backed
- property source binds to.
-
- Resolved with ``apps.get_model`` because customer_analytics does not depend on data_modeling; the
- production code reaches the same model the same way.
- """
- saved_query_model = apps.get_model("data_modeling", "DataWarehouseSavedQuery")
- return saved_query_model.objects.create(
+ property source binds to."""
+ return DataWarehouseSavedQuery.objects.create(
team_id=team_id, name=name, query={"query": "select 1"}, is_materialized=is_materialized, **kwargs
)
+
+
+def saved_query_columns(names: Iterable[str]) -> dict[str, dict[str, str]]:
+ """Columns in the shape data_modeling stores after a run. Its facade drops a column with no
+ ``clickhouse`` type, so a bare ``{}`` entry would read back as missing."""
+ return {name: {"clickhouse": "String"} for name in names}
diff --git a/products/customer_analytics/backend/test/test_account_ownership_commands.py b/products/customer_analytics/backend/test/test_account_ownership_commands.py
new file mode 100644
index 000000000000..9840af092a34
--- /dev/null
+++ b/products/customer_analytics/backend/test/test_account_ownership_commands.py
@@ -0,0 +1,329 @@
+import json
+import shutil
+import tempfile
+from io import StringIO
+from pathlib import Path
+from typing import Any
+from uuid import UUID
+
+from posthog.test.base import BaseTest
+
+from django.core.management import CommandError, call_command
+
+from parameterized import parameterized
+
+from posthog.models import Team, User
+from posthog.models.activity_logging.activity_log import ActivityLog
+
+from products.customer_analytics.backend.facade.enums import AccountRelationshipSource
+from products.customer_analytics.backend.logic import ownership, relationships
+from products.customer_analytics.backend.logic.ownership_claims import DECISION_COLUMNS
+from products.customer_analytics.backend.models import (
+ Account,
+ AccountRelationship,
+ AccountRelationshipControl,
+ AccountRelationshipDefinition,
+)
+from products.customer_analytics.backend.test.factories import (
+ create_account,
+ create_saved_query,
+ enroll_account,
+ saved_query_columns,
+)
+
+
+class TestConfigureAccountOwnershipCommand(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.ae_definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="Account executive"
+ )
+
+ def _configure(self, *args) -> str:
+ out = StringIO()
+ call_command("configure_account_ownership", "--team-id", str(self.team.id), *args, stdout=out)
+ return out.getvalue()
+
+ def _state(self, definition: AccountRelationshipDefinition) -> tuple[bool, bool, UUID | None]:
+ definition.refresh_from_db()
+ return (definition.is_controlled, definition.claims_enabled, definition.claim_saved_query_id)
+
+ def _decision_view(self, team_id: int) -> Any:
+ return create_saved_query(
+ team_id=team_id, name="ownership_decisions", columns=saved_query_columns(DECISION_COLUMNS)
+ )
+
+ def test_controls_definitions_and_binds_claim_views(self):
+ view = self._decision_view(self.team.id)
+ definition_id = str(self.ae_definition.id)
+
+ self._configure(
+ "--control",
+ definition_id,
+ "--claim-view",
+ definition_id,
+ str(view.id),
+ "--claims",
+ definition_id,
+ "enabled",
+ )
+
+ assert self._state(self.ae_definition) == (True, True, view.id)
+
+ self._configure("--clear-claim-view", definition_id, "--uncontrol", definition_id)
+
+ assert self._state(self.ae_definition) == (False, False, None)
+
+ def test_rejects_a_view_without_the_decision_columns(self):
+ view = create_saved_query(team_id=self.team.id, name="partial", columns=saved_query_columns(["task_id"]))
+
+ with self.assertRaises(CommandError):
+ self._configure(
+ "--control", str(self.ae_definition.id), "--claim-view", str(self.ae_definition.id), str(view.id)
+ )
+
+ assert self._state(self.ae_definition) == (False, False, None)
+
+ def test_control_cannot_end_while_accounts_are_enrolled(self):
+ self._configure("--control", str(self.ae_definition.id))
+ enroll_account(create_account(team_id=self.team.id, name="Managed", external_id="org-1"), self.ae_definition)
+
+ with self.assertRaises(CommandError):
+ self._configure("--uncontrol", str(self.ae_definition.id))
+
+ assert self._state(self.ae_definition)[0] is True
+
+ @parameterized.expand(
+ [
+ ("binding_a_view_to_an_uncontrolled_definition", False, False),
+ ("uncontrolling_a_definition_with_a_view", True, True),
+ ("enabling_claims_without_a_view", True, False),
+ ("binding_a_view_of_another_team", True, False),
+ ("binding_a_view_that_fills_another_definition", True, False),
+ ("binding_and_clearing_in_one_call", True, False),
+ ("naming_a_definition_twice_with_different_views", True, False),
+ ]
+ )
+ def test_a_claim_view_binding_is_refused(self, case, controlled, bound):
+ view = self._decision_view(self.team.id)
+ definition_id = str(self.ae_definition.id)
+ if controlled:
+ self._configure("--control", definition_id)
+ if case == "binding_a_view_to_an_uncontrolled_definition":
+ args = ["--claim-view", definition_id, str(view.id)]
+ elif case == "uncontrolling_a_definition_with_a_view":
+ self._configure("--claim-view", definition_id, str(view.id))
+ args = ["--uncontrol", definition_id]
+ elif case == "enabling_claims_without_a_view":
+ args = ["--claims", definition_id, "enabled"]
+ elif case == "binding_a_view_of_another_team":
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ args = ["--claim-view", definition_id, str(self._decision_view(other_team.id).id)]
+ elif case == "binding_a_view_that_fills_another_definition":
+ AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="CSM", is_controlled=True, claim_saved_query=view
+ )
+ args = ["--claim-view", definition_id, str(view.id)]
+ elif case == "naming_a_definition_twice_with_different_views":
+ other = create_saved_query(
+ team_id=self.team.id, name="other_decisions", columns=saved_query_columns(DECISION_COLUMNS)
+ )
+ args = ["--claim-view", definition_id, str(view.id), "--claim-view", definition_id, str(other.id)]
+ else:
+ args = ["--claim-view", definition_id, str(view.id), "--clear-claim-view", definition_id]
+
+ with self.assertRaises(CommandError):
+ self._configure(*args)
+
+ assert self._state(self.ae_definition) == (controlled, False, view.id if bound else None)
+
+ def test_a_view_moves_between_definitions_in_one_call(self):
+ view = self._decision_view(self.team.id)
+ csm_definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="CSM"
+ )
+ ae_id, csm_id = str(self.ae_definition.id), str(csm_definition.id)
+ self._configure("--control", ae_id, "--control", csm_id, "--claim-view", ae_id, str(view.id))
+
+ self._configure("--clear-claim-view", ae_id, "--claim-view", csm_id, str(view.id))
+
+ assert self._state(self.ae_definition) == (True, False, None)
+ assert self._state(csm_definition) == (True, False, view.id)
+
+ @parameterized.expand(["other_team", "multi_holder"])
+ def test_rejects_an_unusable_definition(self, case):
+ if case == "other_team":
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ definition = AccountRelationshipDefinition.objects.for_team(other_team.id).create(
+ team_id=other_team.id, name="AE"
+ )
+ else:
+ definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="FDE", is_single_holder=False
+ )
+
+ with self.assertRaises(CommandError):
+ self._configure("--control", str(definition.id))
+
+ assert self._state(definition)[0] is False
+
+
+class TestAdoptAccountOwnershipCommand(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.other_user = self._create_user("[email protected]")
+ self.ae_definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="Account executive", is_controlled=True
+ )
+ self.empty = create_account(team_id=self.team.id, name="Empty", external_id="org-empty")
+ self.held = create_account(team_id=self.team.id, name="Held", external_id="org-held")
+ self._assign(self.held, self.other_user)
+ directory = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, directory, ignore_errors=True)
+ self.manifest_path = Path(directory) / "manifest.json"
+
+ def _assign(self, account: Account, user: User) -> None:
+ relationships.assign(
+ team_id=self.team.id,
+ account=account,
+ definition=self.ae_definition,
+ user=user,
+ actor=relationships.Actor.human(self.user),
+ )
+
+ def _fingerprints(self) -> dict[str, str]:
+ out = StringIO()
+ call_command("adopt_account_ownership", "--team-id", str(self.team.id), "--export-fingerprints", stdout=out)
+ rows = json.loads(out.getvalue())["relationships"]
+ assert {row["definition_id"] for row in rows} == {str(self.ae_definition.id)}
+ return {row["account_id"]: row["fingerprint"] for row in rows}
+
+ def _write_manifest(self, proposals: list[dict]) -> None:
+ self.manifest_path.write_text(json.dumps({"proposals": proposals}))
+
+ def _run(self, *args) -> str:
+ out = StringIO()
+ call_command(
+ "adopt_account_ownership",
+ "--team-id",
+ str(self.team.id),
+ "--manifest",
+ str(self.manifest_path),
+ *args,
+ stdout=out,
+ )
+ return out.getvalue()
+
+ def _proposals(self) -> list[dict]:
+ fingerprints = self._fingerprints()
+ return [
+ {
+ "account_id": str(self.empty.id),
+ "definition_id": str(self.ae_definition.id),
+ "state": "assigned",
+ "user_id": self.user.id,
+ "expected_fingerprint": fingerprints[str(self.empty.id)],
+ },
+ {
+ "account_id": str(self.held.id),
+ "definition_id": str(self.ae_definition.id),
+ "state": "assigned",
+ "user_id": self.other_user.id,
+ "expected_fingerprint": fingerprints[str(self.held.id)],
+ },
+ ]
+
+ def _fence(self, account: Account):
+ return (
+ AccountRelationshipControl.objects.for_team(self.team.id)
+ .filter(account=account, definition=self.ae_definition)
+ .values_list("controlled_at", flat=True)
+ .first()
+ )
+
+ def test_preview_changes_nothing_and_apply_adopts_once(self):
+ self._write_manifest(self._proposals())
+
+ preview = self._run()
+
+ assert "preview: would_apply=2" in preview
+ assert self._fence(self.empty) is None
+ assert not AccountRelationship.objects.for_team(self.team.id).filter(account=self.empty).exists()
+
+ applied = self._run("--apply")
+
+ assert "applied: applied=2" in applied
+ seeded = AccountRelationship.objects.for_team(self.team.id).get(account=self.empty, ended_at__isnull=True)
+ assert (seeded.user_id, seeded.source) == (self.user.id, AccountRelationshipSource.MIGRATION)
+ assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.held).count() == 1
+ assert self._fence(self.empty) is not None and self._fence(self.held) is not None
+ assert ActivityLog.objects.filter(team_id=self.team.id, activity="role_enrolled").count() == 2
+
+ rerun = self._run("--apply")
+
+ assert "applied: already_applied=2" in rerun
+ assert ActivityLog.objects.filter(team_id=self.team.id, activity="role_enrolled").count() == 2
+
+ def test_empty_proposal_confirms_an_empty_relationship(self):
+ fingerprints = self._fingerprints()
+ self._write_manifest(
+ [
+ {
+ "account_id": str(self.empty.id),
+ "definition_id": str(self.ae_definition.id),
+ "state": "empty",
+ "expected_fingerprint": fingerprints[str(self.empty.id)],
+ }
+ ]
+ )
+
+ self._run("--apply")
+
+ assert self._fence(self.empty) is not None
+ assert not AccountRelationship.objects.for_team(self.team.id).filter(account=self.empty).exists()
+
+ @parameterized.expand(
+ [
+ "changed_after_review",
+ "held_by_someone_else",
+ "held_by_deleted_user",
+ "empty_over_deleted_user_row",
+ "definition_not_controlled",
+ "already_managed",
+ ]
+ )
+ def test_proposal_that_no_longer_holds_is_skipped(self, case):
+ for_empty, for_held = self._proposals()
+ if case == "definition_not_controlled":
+ ownership.set_controlled(self.team.id, self.ae_definition.id, False)
+ proposal, expected = for_empty, "invalid (definition_not_controlled)"
+ elif case == "already_managed":
+ enroll_account(self.held, self.ae_definition)
+ for_held["user_id"] = self.user.id
+ proposal, expected = for_held, "conflict (role_managed)"
+ elif case == "changed_after_review":
+ self._assign(self.empty, self.other_user)
+ proposal, expected = for_empty, "fingerprint_changed"
+ elif case in ("held_by_deleted_user", "empty_over_deleted_user_row"):
+ AccountRelationship.objects.for_team(self.team.id).filter(account=self.held).update(user=None)
+ if case == "held_by_deleted_user":
+ for_held["user_id"] = self.user.id
+ else:
+ for_held["state"] = "empty"
+ del for_held["user_id"]
+ for_held["expected_fingerprint"] = self._fingerprints()[str(self.held.id)]
+ proposal, expected = for_held, "conflict (held_by_deleted_user)"
+ else:
+ for_held["user_id"] = self.user.id
+ for_held["expected_fingerprint"] = self._fingerprints()[str(self.held.id)]
+ proposal, expected = for_held, f"conflict (held_by_user_{self.other_user.id})"
+ self._write_manifest([proposal])
+ fence_before = self._fence(self.held)
+
+ output = self._run("--apply")
+
+ assert expected in output
+ assert self._fence(self.empty) is None and self._fence(self.held) == fence_before
+ holder = AccountRelationship.objects.for_team(self.team.id).get(account=self.held, ended_at__isnull=True)
+ deleted_user_cases = ("held_by_deleted_user", "empty_over_deleted_user_row")
+ assert holder.user_id == (None if case in deleted_user_cases else self.other_user.id)
diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.py
index e4e5697a81ad..8bd0d0ee1d9c 100644
--- a/products/customer_analytics/backend/test/test_external.py
+++ b/products/customer_analytics/backend/test/test_external.py
@@ -6,6 +6,7 @@ from unittest.mock import patch
from django.apps import apps
from django.core.cache import cache
+from django.test import override_settings
from parameterized import parameterized
from rest_framework import status
@@ -26,7 +27,11 @@ from products.customer_analytics.backend.models import (
DisplayType,
)
from products.customer_analytics.backend.models.account import AccountProperties
-from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition
+from products.customer_analytics.backend.test.factories import (
+ create_account,
+ create_custom_property_definition,
+ enroll_account,
+)
_SYNC_EXECUTE = "products.customer_analytics.backend.logic.custom_property_sync.execute_hogql_query"
@@ -195,6 +200,76 @@ class TestExternalAccountAPI(APIBaseTest):
{"CSM": [{"user_id": self.user.id, "email": self.user.email}]},
)
+ def _control_csm(self) -> None:
+ self.csm_definition.is_controlled = True
+ self.csm_definition.save(update_fields=["is_controlled"])
+
+ def _manage_csm(self) -> None:
+ enroll_account(self.account, self.csm_definition, controlled_at=datetime(2026, 1, 1, tzinfo=UTC))
+
+ @parameterized.expand(
+ [
+ ("not_controlled", False, False, "member", None, []),
+ ("unmanaged_controlled", True, False, None, "unmanaged", []),
+ ("unmanaged_with_legacy_holder", True, False, "member", "unmanaged", []),
+ ("assigned", True, True, "member", "assigned", []),
+ ("cleared", True, True, None, "cleared", []),
+ ("blocked_non_member", True, True, "outsider", "blocked", ["holder_not_in_organization"]),
+ ("blocked_inactive", True, True, "inactive", "blocked", ["holder_inactive"]),
+ ]
+ )
+ def test_get_account_ownership_state(self, _name, controlled, managed, holder_kind, state, diagnostics):
+ if controlled:
+ self._control_csm()
+ if managed:
+ self._manage_csm()
+ holder = None
+ if holder_kind == "member":
+ holder = self.user
+ elif holder_kind == "outsider":
+ holder = User.objects.create_user("[email protected]", None, "")
+ elif holder_kind == "inactive":
+ holder = self._create_user("[email protected]", is_active=False)
+ relationship = self._assign_csm(holder) if holder is not None else None
+
+ response = self._get()
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ payload = response.json()
+ listed = (
+ {}
+ if holder is None or holder_kind == "outsider"
+ else {"CSM": [{"user_id": holder.id, "email": holder.email}]}
+ )
+ self.assertEqual(payload["relationships"], listed)
+ roles = payload["ownership"]["roles"]
+ if not controlled:
+ self.assertEqual(roles, [])
+ return
+ (csm,) = roles
+ self.assertEqual(csm["state"], state)
+ self.assertEqual(csm["diagnostics"], diagnostics)
+ self.assertEqual((csm["definition_id"], csm["definition_name"]), (self.csm_key, "CSM"))
+ self.assertEqual(csm["controlled_at"], "2026-01-01T00:00:00Z" if managed else None)
+ self.assertEqual(csm["relationship_id"], str(relationship.id) if relationship else None)
+ if holder is None:
+ self.assertIsNone(csm["holder"])
+ return
+ self.assertEqual(csm["holder"]["user_id"], holder.id)
+ self.assertEqual(csm["holder"]["is_organization_member"], holder_kind != "outsider")
+ self.assertEqual(csm["holder"]["is_active"], holder_kind != "inactive")
+ self.assertEqual(csm["holder"]["email"], None if holder_kind == "outsider" else holder.email)
+
+ def test_get_account_ownership_identity(self):
+ with override_settings(CLOUD_DEPLOYMENT="US"):
+ response = self._get()
+
+ ownership = response.json()["ownership"]
+ self.assertEqual(ownership["account_id"], str(self.account.id))
+ self.assertEqual(ownership["external_id"], "acme-1")
+ self.assertEqual(ownership["region"], "us")
+ self.assertEqual(ownership["roles"], [])
+
def test_get_account_returns_custom_properties(self):
plan = create_custom_property_definition(team_id=self.team.id, name="Plan", display_type=DisplayType.TEXT)
create_custom_property_definition(team_id=self.team.id, name="Seats", display_type=DisplayType.NUMBER)
@@ -272,6 +347,16 @@ class TestExternalAccountAPI(APIBaseTest):
)
self.assertEqual(self._active_csm_user_ids(), [self.user.id])
+ def test_patch_cannot_change_a_managed_controlled_relationship(self):
+ self._assign_csm(self.user)
+ self._control_csm()
+ self._manage_csm()
+
+ response = self._patch({"external_id": "acme-1", "relationships": {self.csm_key: None}})
+
+ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT, response.json())
+ self.assertEqual(self._active_csm_user_ids(), [self.user.id])
+
def test_patch_null_ends_active_assignment(self):
self._assign_csm(self.user)
diff --git a/products/customer_analytics/backend/test/test_external_list.py b/products/customer_analytics/backend/test/test_external_list.py
index 1d901f30d05a..e5d15862ca61 100644
--- a/products/customer_analytics/backend/test/test_external_list.py
+++ b/products/customer_analytics/backend/test/test_external_list.py
@@ -6,6 +6,8 @@ from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.core.cache import cache
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
from rest_framework import status
@@ -15,8 +17,9 @@ from posthog.models import Organization, OrganizationMembership, Team, User
from posthog.models.utils import generate_random_token_secret
from posthog.test.api_keys import create_project_secret_api_key
+from products.customer_analytics.backend.facade import api as facade
from products.customer_analytics.backend.models import AccountRelationship, AccountRelationshipDefinition
-from products.customer_analytics.backend.test.factories import create_account
+from products.customer_analytics.backend.test.factories import create_account, enroll_account
ENDED_AT = datetime(2026, 1, 1, tzinfo=UTC)
@@ -45,6 +48,11 @@ class TestExternalAccountListAPI(APIBaseTest):
team_id=self.team.id, name=name, **kwargs
)
+ def _enrolled_account(self, *, name, external_id, definition, **kwargs):
+ account = create_account(team_id=self.team.id, name=name, external_id=external_id, **kwargs)
+ enroll_account(account, definition, controlled_at=ENDED_AT)
+ return account
+
def _assign(self, account, user, definition=None, ended_at=None):
return AccountRelationship.objects.for_team(self.team.id).create(
team_id=self.team.id,
@@ -222,18 +230,9 @@ class TestExternalAccountListAPI(APIBaseTest):
response = self._get()
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(
- response.json()["results"],
- [
- {
- "external_id": "org-1",
- "name": "Acme",
- "churned_at": None,
- "ignored_at": None,
- "relationships": {},
- }
- ],
- )
+ (row,) = response.json()["results"]
+ self.assertEqual(row["external_id"], "org-1")
+ self.assertEqual(row["relationships"], {})
def test_omits_ended_and_userless_assignments(self):
account = create_account(team_id=self.team.id, name="Acme", external_id="org-1")
@@ -283,6 +282,52 @@ class TestExternalAccountListAPI(APIBaseTest):
names = [row["name"] for row in response.json()["results"]]
self.assertEqual(names, ["Listed"])
+ def test_managed_only_returns_managed_accounts_including_cleared_roles(self):
+ self.csm_definition.is_controlled = True
+ self.csm_definition.save(update_fields=["is_controlled"])
+ onboarding_definition = self._create_definition("Onboarding manager", is_controlled=True)
+ assigned = self._enrolled_account(name="Assigned", external_id="assigned", definition=self.csm_definition)
+ self._assign(assigned, self.user)
+ self._enrolled_account(name="Cleared", external_id="cleared", definition=self.csm_definition)
+ self._enrolled_account(
+ name="Ignored", external_id="ignored", definition=self.csm_definition, ignored_at=ENDED_AT
+ )
+ self._enrolled_account(name="Onboarding", external_id="onboarding", definition=onboarding_definition)
+ legacy = create_account(team_id=self.team.id, name="Legacy", external_id="legacy")
+ self._assign(legacy, self.user)
+
+ response = self._get({"managed_only": "true"})
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ by_external_id = {
+ row["external_id"]: {role["definition_name"]: role for role in row["ownership"]["roles"]}
+ for row in response.json()["results"]
+ }
+ self.assertEqual(set(by_external_id), {"assigned", "cleared", "ignored", "onboarding"})
+ self.assertEqual(by_external_id["assigned"]["CSM"]["state"], "assigned")
+ self.assertEqual(by_external_id["assigned"]["CSM"]["holder"]["email"], self.user.email)
+ self.assertEqual(by_external_id["assigned"]["Onboarding manager"]["state"], "unmanaged")
+ self.assertEqual(by_external_id["cleared"]["CSM"]["state"], "cleared")
+ self.assertIsNone(by_external_id["cleared"]["CSM"]["holder"])
+ self.assertEqual(by_external_id["onboarding"]["Onboarding manager"]["state"], "cleared")
+ self.assertEqual(by_external_id["onboarding"]["CSM"]["state"], "unmanaged")
+
+ def test_ownership_block_costs_a_fixed_number_of_queries(self):
+ definitions = [self._create_definition(name, is_controlled=True) for name in ("AE", "Onboarding", "Support")]
+ accounts = [create_account(team_id=self.team.id, name=f"Account {i}", external_id=f"org-{i}") for i in range(3)]
+ for account in accounts:
+ for definition in definitions:
+ enroll_account(account, definition, controlled_at=ENDED_AT)
+ self._assign(account, self.user, definition=definition)
+
+ with CaptureQueriesContext(connection) as one_account:
+ facade.list_external_accounts(self.team.id, organization_id=self.organization.id, limit=1)
+ with CaptureQueriesContext(connection) as three_accounts:
+ page = facade.list_external_accounts(self.team.id, organization_id=self.organization.id, limit=3)
+
+ self.assertEqual(len(three_accounts.captured_queries), len(one_account.captured_queries))
+ self.assertEqual({len(item.ownership.roles) for item in page.results}, {3})
+
def test_assigned_only_filters_to_accounts_with_an_active_assignment(self):
assigned = create_account(team_id=self.team.id, name="Assigned", external_id="org-1")
self._assign(assigned, self.user)
diff --git a/products/customer_analytics/backend/test/test_ownership_claims.py b/products/customer_analytics/backend/test/test_ownership_claims.py
new file mode 100644
index 000000000000..6fa35c056858
--- /dev/null
+++ b/products/customer_analytics/backend/test/test_ownership_claims.py
@@ -0,0 +1,634 @@
+from dataclasses import replace
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.db import IntegrityError, OperationalError, transaction
+from django.db.models.deletion import RestrictedError
+from django.test import override_settings
+from django.utils import timezone
+
+from parameterized import parameterized
+from temporalio.client import ScheduleOverlapPolicy, ScheduleState
+from temporalio.common import WorkflowIDReusePolicy
+from temporalio.exceptions import WorkflowAlreadyStartedError
+from temporalio.workflow import ParentClosePolicy
+
+from posthog.hogql.errors import QueryError
+
+from posthog.models import User
+from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.team import Team
+
+from products.customer_analytics.backend.facade import contracts
+from products.customer_analytics.backend.logic import ownership_claims, relationships
+from products.customer_analytics.backend.logic.ownership_claims import DECISION_COLUMNS
+from products.customer_analytics.backend.models import (
+ AccountRelationship,
+ AccountRelationshipControl,
+ AccountRelationshipDefinition,
+)
+from products.customer_analytics.backend.temporal.ownership_claims import (
+ OWNERSHIP_CLAIMS_COORDINATOR_EXECUTION_TIMEOUT,
+ OWNERSHIP_CLAIMS_COORDINATOR_SCHEDULE_ID,
+ OWNERSHIP_CLAIMS_INTERVAL,
+ OWNERSHIP_CLAIMS_SWEEP_EXECUTION_TIMEOUT,
+ OwnershipClaimsCoordinatorInput,
+ OwnershipClaimsCoordinatorOutput,
+ OwnershipClaimsCoordinatorWorkflow,
+ OwnershipClaimsProjects,
+ create_ownership_claims_coordinator_schedule,
+ ownership_claims_workflow_id,
+)
+from products.customer_analytics.backend.test.factories import (
+ create_account,
+ create_saved_query,
+ enroll_account,
+ saved_query_columns,
+)
+
+FENCE = datetime(2026, 1, 1, tzinfo=UTC)
+TASK = "example-salesforce-task-17"
+
+
+class TestOwnershipClaims(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.ae_definition, self.view = self._claim_bound_definition("Account executive", "ownership_decisions")
+ self.account = create_account(team_id=self.team.id, name="Acme Corp", external_id="org-1")
+ self.control = enroll_account(self.account, self.ae_definition, controlled_at=FENCE)
+ self.human = relationships.Actor.human(self.user)
+
+ def _claim_bound_definition(self, name: str, view_name: str) -> tuple[AccountRelationshipDefinition, Any]:
+ view = create_saved_query(team_id=self.team.id, name=view_name, columns=saved_query_columns(DECISION_COLUMNS))
+ definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name=name, is_controlled=True, claims_enabled=True, claim_saved_query=view
+ )
+ return definition, view
+
+ def _decision(self, **overrides) -> contracts.OwnershipClaimDecision:
+ base = contracts.OwnershipClaimDecision(
+ source_ref=TASK,
+ organization_id="org-1",
+ region="us",
+ assignee_user_id=self.user.id,
+ source_assignee_id="example-salesforce-user-17",
+ allocated_at=datetime(2026, 1, 2, tzinfo=UTC),
+ )
+ return replace(base, **overrides)
+
+ def _release(self, **overrides) -> contracts.OwnershipClaimDecision:
+ return self._decision(
+ released_at=datetime(2026, 1, 3, tzinfo=UTC), source_releaser_id="example-salesforce-user-99", **overrides
+ )
+
+ def _claim(self, **overrides) -> contracts.OwnershipClaimResult:
+ return ownership_claims.claim(
+ team=self.team, definition=self.ae_definition, decision=self._decision(**overrides)
+ )
+
+ def _release_claim(self, **overrides) -> contracts.OwnershipClaimResult:
+ return ownership_claims.release(team=self.team, decision=self._release(**overrides))
+
+ def _active_ae(self) -> AccountRelationship | None:
+ return (
+ AccountRelationship.objects.for_team(self.team.id)
+ .filter(account=self.account, definition=self.ae_definition, ended_at__isnull=True)
+ .first()
+ )
+
+ def _fence(self) -> datetime | None:
+ return (
+ AccountRelationshipControl.objects.for_team(self.team.id)
+ .filter(account=self.account, definition=self.ae_definition)
+ .values_list("controlled_at", flat=True)
+ .first()
+ )
+
+ def _assign_by_human(self, user: User) -> AccountRelationship:
+ return relationships.assign(
+ team_id=self.team.id, account=self.account, definition=self.ae_definition, user=user, actor=self.human
+ )
+
+ def _clear_by_human(self) -> None:
+ relationships.end_active(
+ team_id=self.team.id, account=self.account, definition=self.ae_definition, actor=self.human
+ )
+
+ def test_claim_fills_an_empty_managed_role(self):
+ result = self._claim()
+
+ assert result.outcome == "accepted"
+ holder = self._active_ae()
+ assert holder is not None and result.relationship_id == holder.id
+ assert (holder.user_id, holder.source, holder.source_ref) == (self.user.id, "salesforce_claim", TASK)
+ assert self._fence() == FENCE and result.controlled_at == FENCE
+ activity = ActivityLog.objects.get(team_id=self.team.id, scope="Account", activity="role_claimed")
+ assert activity.is_system
+ assert activity.detail is not None
+ assert activity.detail["context"]["source_ref"] == TASK
+ assert activity.detail["context"]["source_actor_id"] == "example-salesforce-user-17"
+
+ def test_rereading_an_accepted_task_answers_the_original_decision_after_a_human_clear(self):
+ first = self._claim()
+ self._clear_by_human()
+ fence = self._fence()
+
+ again = self._claim()
+
+ assert (again.outcome, again.relationship_id) == ("already_applied", first.relationship_id)
+ assert self._active_ae() is None
+ assert self._fence() == fence
+ assert AccountRelationship.objects.for_team(self.team.id).filter(source_ref=TASK).count() == 1
+
+ @parameterized.expand(
+ [
+ ("occupied_by_another_user", "rejected", "role_occupied"),
+ ("occupied_by_the_same_user", "rejected", "role_occupied"),
+ ("allocated_within_the_skew_allowance", "rejected", "stale_allocation"),
+ ("allocated_before_a_human_clear", "rejected", "stale_allocation"),
+ ("allocated_in_the_future", "rejected", "future_allocation"),
+ ("role_not_managed", "blocked", "role_not_managed"),
+ ("unknown_organization", "blocked", "account_not_found"),
+ ("region_mismatch", "blocked", "identity_mismatch"),
+ ("two_accounts_differ_only_by_case", "blocked", "identity_mismatch"),
+ ("assignee_not_a_member", "blocked", "assignee_not_member"),
+ ("different_case_is_the_same_identity", "accepted", None),
+ ]
+ )
+ def test_claim_decision_outcome(self, case, outcome, reason):
+ overrides: dict[str, Any] = {}
+ if case == "occupied_by_another_user":
+ self._assign_by_human(self._create_user("[email protected]"))
+ elif case == "occupied_by_the_same_user":
+ self._assign_by_human(self.user)
+ elif case == "allocated_within_the_skew_allowance":
+ overrides["allocated_at"] = datetime(2026, 1, 1, 0, 4, 59, tzinfo=UTC)
+ elif case == "allocated_before_a_human_clear":
+ self._clear_by_human()
+ elif case == "allocated_in_the_future":
+ overrides["allocated_at"] = timezone.now() + timedelta(days=1)
+ elif case == "role_not_managed":
+ self.control.delete()
+ elif case == "unknown_organization":
+ overrides["organization_id"] = "org-2"
+ elif case == "two_accounts_differ_only_by_case":
+ shadow = create_account(team_id=self.team.id, name="Shadow", external_id="ORG-1")
+ enroll_account(shadow, self.ae_definition, controlled_at=FENCE)
+ elif case == "region_mismatch":
+ overrides["region"] = "eu"
+ elif case == "assignee_not_a_member":
+ overrides["assignee_user_id"] = User.objects.create_user("[email protected]", None, "").id
+ elif case == "different_case_is_the_same_identity":
+ overrides["organization_id"] = "ORG-1"
+ holder_before = self._active_ae()
+ fence_before = self._fence()
+
+ with override_settings(CLOUD_DEPLOYMENT="US"):
+ result = self._claim(**overrides)
+
+ assert (result.outcome, result.reason) == (outcome, reason)
+ if outcome == "accepted":
+ return
+ assert self._active_ae() == holder_before
+ assert self._fence() == fence_before
+ assert not AccountRelationship.objects.for_team(self.team.id).filter(source="salesforce_claim").exists()
+
+ def test_release_ends_only_the_relationship_the_task_claimed(self):
+ claimed = self._claim()
+ fence_after_claim = self._fence()
+
+ released = self._release_claim()
+
+ assert (released.outcome, released.relationship_id) == ("cleared", claimed.relationship_id)
+ assert self._active_ae() is None
+ fence = self._fence()
+ assert fence == fence_after_claim == FENCE
+ activity = ActivityLog.objects.get(team_id=self.team.id, activity="role_released")
+ assert activity.detail is not None
+ assert activity.detail["context"]["source_actor_id"] == "example-salesforce-user-99"
+ assert activity.detail["context"]["source_decided_at"] == "2026-01-03T00:00:00+00:00"
+
+ repeated = self._release_claim()
+
+ assert repeated.outcome == "not_held"
+ assert self._fence() == fence
+ assert ActivityLog.objects.filter(team_id=self.team.id, activity="role_released").count() == 1
+
+ def test_a_task_allocated_after_a_release_is_accepted_when_the_release_was_processed_later(self):
+ self._claim()
+ self._release_claim()
+
+ result = self._claim(source_ref="task-2", allocated_at=datetime(2026, 1, 3, 0, 10, tzinfo=UTC))
+
+ assert result.outcome == "accepted"
+ holder = self._active_ae()
+ assert holder is not None and holder.source_ref == "task-2"
+
+ @parameterized.expand(["after_a_human_transfer", "after_a_human_clear"])
+ def test_release_after_a_human_decision_is_not_held(self, decision):
+ self._claim()
+ if decision == "after_a_human_transfer":
+ self._assign_by_human(self._create_user("[email protected]"))
+ else:
+ self._clear_by_human()
+ holder_before = self._active_ae()
+ fence_before = self._fence()
+
+ released = self._release_claim()
+
+ assert released.outcome == "not_held"
+ assert self._active_ae() == holder_before
+ assert self._fence() == fence_before
+
+ def test_release_ends_its_own_row_when_another_definition_takes_claims_too(self):
+ first = self._claim()
+ csm_definition, _ = self._claim_bound_definition("CSM", "csm_decisions")
+ enroll_account(self.account, csm_definition, controlled_at=FENCE)
+ second = ownership_claims.claim(
+ team=self.team, definition=csm_definition, decision=self._decision(source_ref="task-2")
+ )
+
+ released = self._release_claim()
+
+ assert (released.outcome, released.relationship_id) == ("cleared", first.relationship_id)
+ assert self._active_ae() is None
+ csm_holder = AccountRelationship.objects.for_team(self.team.id).get(
+ definition=csm_definition, ended_at__isnull=True
+ )
+ assert csm_holder.id == second.relationship_id
+ fences = AccountRelationshipControl.objects.for_team(self.team.id).filter(account=self.account)
+ assert set(fences.values_list("controlled_at", flat=True)) == {FENCE}
+
+ def test_a_source_reference_is_unique_per_team_and_source_in_the_database(self):
+ self._claim()
+
+ AccountRelationship.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ account=self.account,
+ definition=self.ae_definition,
+ source="workflow",
+ source_ref=TASK,
+ )
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ AccountRelationship.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ account=self.account,
+ definition=self.ae_definition,
+ source="salesforce_claim",
+ source_ref=TASK,
+ )
+
+ def test_release_of_an_undelivered_claim_is_not_held(self):
+ released = self._release_claim()
+
+ assert (released.outcome, released.relationship_id) == ("not_held", None)
+
+ def _view_rows(self, *decisions):
+ return [
+ [
+ decision.source_ref,
+ decision.organization_id,
+ decision.region,
+ decision.assignee_user_id,
+ decision.source_assignee_id,
+ decision.allocated_at,
+ decision.released_at,
+ decision.source_releaser_id,
+ ]
+ for decision in decisions
+ ]
+
+ def test_reconciliation_applies_every_row_and_counts_outcomes(self):
+ rows = self._view_rows(self._decision(), self._release(source_ref="never-delivered"))
+ rows.append([TASK + "-bad", "org-1", "us", "not-a-user-id", "x", FENCE, None, None])
+ rows.append([None, "org-1", "us", self.user.id, "x", FENCE, None, None])
+ rows.append([TASK + "-fractional", "org-1", "us", self.user.id + 0.5, "x", FENCE, None, None])
+ rows.append([TASK + "-decimal", "org-1", "us", Decimal(f"{self.user.id}.5"), "x", FENCE, None, None])
+
+ with patch.object(ownership_claims, "execute_hogql_query", return_value=SimpleNamespace(results=rows)) as read:
+ result = ownership_claims.reconcile_ownership_claims(self.team)
+
+ assert read.call_count == 1
+ assert (result.decisions, result.outcomes) == (6, {"accepted": 1, "not_held": 1, "invalid": 4})
+ holder = self._active_ae()
+ assert holder is not None and holder.source_ref == TASK
+
+ @parameterized.expand(["valid_sibling", "invalid_sibling"])
+ def test_a_task_listed_more_than_once_is_not_applied(self, sibling):
+ rows = self._view_rows(self._decision(), self._release())
+ if sibling == "invalid_sibling":
+ rows[1][DECISION_COLUMNS.index("allocated_at")] = "not-a-timestamp"
+
+ with patch.object(ownership_claims, "execute_hogql_query", return_value=SimpleNamespace(results=rows)):
+ result = ownership_claims.reconcile_ownership_claims(self.team)
+
+ assert result.outcomes == {"duplicate": 1}
+ assert self._active_ae() is None
+
+ def test_a_timestamp_without_a_timezone_is_read_as_utc(self):
+ rows = self._view_rows(self._decision())
+ rows[0][5] = "2026-01-02T00:00:00"
+
+ with patch.object(ownership_claims, "execute_hogql_query", return_value=SimpleNamespace(results=rows)):
+ result = ownership_claims.reconcile_ownership_claims(self.team)
+
+ assert result.outcomes == {"accepted": 1}
+
+ @parameterized.expand([("distinct_tasks", [0, 1, 2], 0), ("a_task_split_across_pages", [0, 1, 1, 2], 1)])
+ def test_the_view_is_read_to_the_end_in_pages(self, _name, task_indexes, duplicates):
+ all_rows = self._view_rows(
+ *(self._decision(source_ref=f"task-{index}", organization_id="org-none") for index in task_indexes)
+ )
+
+ def read_after_cursor(query, **_kwargs):
+ after = [row for row in all_rows if str(row[0]) > query.where.right.value]
+ return SimpleNamespace(results=after[: query.limit.value])
+
+ with (
+ patch.object(ownership_claims, "DECISION_PAGE_SIZE", 2),
+ patch.object(ownership_claims, "execute_hogql_query", side_effect=read_after_cursor) as read,
+ ):
+ result = ownership_claims.reconcile_ownership_claims(self.team)
+
+ assert read.call_count == 3
+ assert result.decisions == len(task_indexes)
+ assert result.outcomes.get("duplicate", 0) == duplicates
+
+ def test_a_view_whose_task_id_does_not_page_as_text_is_reported(self):
+ rows = self._view_rows(self._decision(source_ref="task-0"), self._decision(source_ref="task-1"))
+
+ with (
+ patch.object(ownership_claims, "DECISION_PAGE_SIZE", 2),
+ patch.object(ownership_claims, "execute_hogql_query", return_value=SimpleNamespace(results=rows)),
+ ):
+ result = ownership_claims.reconcile_ownership_claims(self.team)
+
+ assert result.outcomes == {"misconfigured": 1}
+
+ def test_a_view_past_the_row_ceiling_is_refused_before_anything_is_applied(self):
+ all_rows = self._view_rows(*(self._decision(source_ref=f"task-{index}") for index in range(4)))
+
+ def read_after_cursor(query, **_kwargs):
+ after = [row for row in all_rows if str(row[0]) > query.where.right.value]
+ return SimpleNamespace(results=after[: query.limit.value])
+
+ with (
+ patch.object(ownership_claims, "DECISION_PAGE_SIZE", 2),
+ patch.object(ownership_claims, "MAX_DECISION_ROWS", 1),
+ patch.object(ownership_claims, "execute_hogql_query", side_effect=read_after_cursor),
+ ):
+ result = ownership_claims.reconcile_ownership_claims(self.team)
+
+ assert result.outcomes == {"misconfigured": 1}
+ assert self._active_ae() is None
+
+ def test_a_sweep_stops_between_decisions_when_asked(self):
+ rows = self._view_rows(self._decision(source_ref="task-0"), self._decision(source_ref="task-1"))
+ checks = iter([False, False, True])
+
+ with (
+ patch.object(ownership_claims, "execute_hogql_query", return_value=SimpleNamespace(results=rows)),
+ self.assertRaises(ownership_claims.SweepStopped),
+ ):
+ ownership_claims.reconcile_ownership_claims(self.team, should_stop=lambda: next(checks))
+
+ claimed = AccountRelationship.objects.for_team(self.team.id).filter(source_ref__in=["task-0", "task-1"])
+ assert claimed.count() == 1
+
+ def _claim_raising_on_first_task(self, error):
+ real_claim = ownership_claims.claim
+
+ def claim(*, team, definition, decision):
+ if decision.source_ref == "boom":
+ raise error
+ return real_claim(team=team, definition=definition, decision=decision)
+
+ return claim
+
+ def test_reconciliation_counts_a_collision_with_an_overlapping_sweep_and_continues(self):
+ rows = self._view_rows(self._decision(source_ref="boom"), self._decision())
+ claim = self._claim_raising_on_first_task(IntegrityError("unique_relationship_per_source_ref"))
+
+ with (
+ patch.object(ownership_claims, "execute_hogql_query", return_value=SimpleNamespace(results=rows)),
+ patch.object(ownership_claims, "claim", side_effect=claim),
+ patch.object(ownership_claims, "capture_exception") as captured,
+ ):
+ result = ownership_claims.reconcile_ownership_claims(self.team)
+
+ assert result.outcomes == {"error": 1, "accepted": 1}
+ captured.assert_called_once()
+ assert self._active_ae() is not None
+
+ def test_a_failing_dependency_ends_the_sweep_instead_of_counting_every_row(self):
+ rows = self._view_rows(self._decision(source_ref="boom"), self._decision())
+ claim = self._claim_raising_on_first_task(OperationalError("connection already closed"))
+
+ with (
+ patch.object(ownership_claims, "execute_hogql_query", return_value=SimpleNamespace(results=rows)),
+ patch.object(ownership_claims, "claim", side_effect=claim) as claimed,
+ self.assertRaises(OperationalError),
+ ):
+ ownership_claims.reconcile_ownership_claims(self.team)
+
+ assert claimed.call_count == 1
+ assert self._active_ae() is None
+
+ def test_rereading_an_accepted_task_under_another_organization_is_blocked(self):
+ self._claim()
+ other = create_account(team_id=self.team.id, name="Other", external_id="org-2")
+ enroll_account(other, self.ae_definition, controlled_at=FENCE)
+
+ moved = self._claim(organization_id="org-2")
+
+ assert (moved.outcome, moved.reason) == ("blocked", "identity_mismatch")
+ assert AccountRelationship.objects.for_team(self.team.id).filter(source_ref=TASK).count() == 1
+
+ @parameterized.expand(["claims_disabled", "no_view_bound", "view_deleted"])
+ def test_reconciliation_skips_a_project_that_is_not_set_up(self, case):
+ if case == "claims_disabled":
+ self.ae_definition.claims_enabled = False
+ self.ae_definition.save(update_fields=["claims_enabled"])
+ elif case == "no_view_bound":
+ self.ae_definition.claim_saved_query = None
+ self.ae_definition.save(update_fields=["claim_saved_query"])
+ else:
+ self.view.soft_delete()
+
+ with patch.object(ownership_claims, "execute_hogql_query") as read:
+ result = ownership_claims.reconcile_ownership_claims(self.team)
+
+ assert result.skipped is True
+ read.assert_not_called()
+
+ @parameterized.expand(["missing_columns", "query_error"])
+ def test_one_unusable_view_is_counted_and_the_others_still_run(self, fault):
+ if fault == "missing_columns":
+ self.view.columns = saved_query_columns(["task_id"])
+ self.view.save(update_fields=["columns"])
+ csm_definition, _ = self._claim_bound_definition("CSM", "csm_decisions")
+ enroll_account(self.account, csm_definition, controlled_at=FENCE)
+ rows = self._view_rows(self._decision(source_ref="task-csm"))
+
+ def read_view(query, **_kwargs):
+ if query.select_from.table.chain[0] == self.view.name:
+ raise QueryError("Unknown table 'salesforce_task'")
+ return SimpleNamespace(results=rows)
+
+ with (
+ patch.object(ownership_claims, "execute_hogql_query", side_effect=read_view) as read,
+ patch.object(ownership_claims, "capture_exception") as captured,
+ ):
+ result = ownership_claims.reconcile_ownership_claims(self.team)
+
+ assert (result.decisions, result.outcomes, result.skipped) == (1, {"misconfigured": 1, "accepted": 1}, False)
+ assert read.call_count == (1 if fault == "missing_columns" else 2)
+ captured.assert_called_once()
+ holder = AccountRelationship.objects.for_team(self.team.id).get(account=self.account, ended_at__isnull=True)
+ assert (holder.definition_id, holder.source_ref) == (csm_definition.id, "task-csm")
+
+ def test_a_view_moved_mid_sweep_is_applied_under_its_new_definition_next_tick(self):
+ csm_definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="CSM", is_controlled=True
+ )
+ enroll_account(self.account, csm_definition, controlled_at=FENCE)
+ rows = self._view_rows(self._decision(source_ref="task-moved"))
+
+ def move_view_then_answer(query, **_kwargs):
+ ownership_claims.bind_claim_view(self.team.id, self.ae_definition.id, None)
+ ownership_claims.bind_claim_view(self.team.id, csm_definition.id, self.view.id)
+ ownership_claims.set_claims_enabled(self.team.id, csm_definition.id, True)
+ return SimpleNamespace(results=rows)
+
+ with patch.object(ownership_claims, "execute_hogql_query", side_effect=move_view_then_answer):
+ during_move = ownership_claims.reconcile_ownership_claims(self.team)
+ with patch.object(ownership_claims, "execute_hogql_query", return_value=SimpleNamespace(results=rows)):
+ next_tick = ownership_claims.reconcile_ownership_claims(self.team)
+
+ assert during_move.outcomes == {"binding_changed": 1}
+ assert next_tick.outcomes == {"accepted": 1}
+ holder = AccountRelationship.objects.for_team(self.team.id).get(account=self.account, ended_at__isnull=True)
+ assert (holder.definition_id, holder.source_ref) == (csm_definition.id, "task-moved")
+
+ def test_a_bound_view_cannot_be_hard_deleted(self):
+ with self.assertRaises(RestrictedError):
+ self.view.delete()
+
+ def test_only_projects_with_claims_on_and_a_view_bound_are_swept(self):
+ claims_off = Team.objects.create(organization=self.organization, name="claims off")
+ AccountRelationshipDefinition.objects.for_team(claims_off.id).create(
+ team_id=claims_off.id,
+ name="AE",
+ is_controlled=True,
+ claim_saved_query=create_saved_query(
+ team_id=claims_off.id, name="decisions", columns=saved_query_columns(DECISION_COLUMNS)
+ ),
+ )
+ no_view = Team.objects.create(organization=self.organization, name="no view")
+ AccountRelationshipDefinition.objects.for_team(no_view.id).create(
+ team_id=no_view.id, name="AE", is_controlled=True, claims_enabled=True
+ )
+ self._claim_bound_definition("CSM", "csm_decisions")
+
+ assert ownership_claims.list_ownership_claim_team_ids() == [self.team.id]
+
+ def test_each_claim_bound_definition_reads_its_own_view(self):
+ csm_definition, csm_view = self._claim_bound_definition("CSM", "csm_decisions")
+ enroll_account(self.account, csm_definition, controlled_at=FENCE)
+ rows_by_view = {
+ self.view.name: self._view_rows(self._decision(source_ref="task-ae")),
+ csm_view.name: self._view_rows(self._decision(source_ref="task-csm")),
+ }
+
+ def read_view(query, **_kwargs):
+ return SimpleNamespace(results=rows_by_view[query.select_from.table.chain[0]])
+
+ with patch.object(ownership_claims, "execute_hogql_query", side_effect=read_view):
+ result = ownership_claims.reconcile_ownership_claims(self.team)
+
+ assert (result.decisions, result.outcomes) == (2, {"accepted": 2})
+ holders = AccountRelationship.objects.for_team(self.team.id).filter(account=self.account, ended_at__isnull=True)
+ assert {holder.definition_id: holder.source_ref for holder in holders} == {
+ self.ae_definition.id: "task-ae",
+ csm_definition.id: "task-csm",
+ }
+
+
+async def test_coordinator_starts_one_sweep_per_project_and_leaves_a_running_one_alone() -> None:
+ team_ids = (11, 22, 33)
+ start_child_workflow = AsyncMock(
+ side_effect=[None, WorkflowAlreadyStartedError(ownership_claims_workflow_id(22), "sweep"), None]
+ )
+ with (
+ patch(
+ "products.customer_analytics.backend.temporal.ownership_claims.workflow.execute_activity",
+ AsyncMock(return_value=OwnershipClaimsProjects(team_ids=team_ids)),
+ ),
+ patch(
+ "products.customer_analytics.backend.temporal.ownership_claims.workflow.start_child_workflow",
+ start_child_workflow,
+ ),
+ ):
+ result = await OwnershipClaimsCoordinatorWorkflow().run(OwnershipClaimsCoordinatorInput())
+
+ assert result == OwnershipClaimsCoordinatorOutput(enabled_teams=3, started_children=2, overlapping_children=1)
+ assert [call.kwargs["id"] for call in start_child_workflow.await_args_list] == [
+ ownership_claims_workflow_id(team_id) for team_id in team_ids
+ ]
+ for call in start_child_workflow.await_args_list:
+ assert call.kwargs["id_reuse_policy"] == WorkflowIDReusePolicy.ALLOW_DUPLICATE
+ assert call.kwargs["parent_close_policy"] == ParentClosePolicy.ABANDON
+ # Without a bound, a child that never runs holds its project's id and skips every later tick.
+ assert call.kwargs["execution_timeout"] == OWNERSHIP_CLAIMS_SWEEP_EXECUTION_TIMEOUT
+
+
+async def test_a_coordinator_run_expires_before_the_next_tick() -> None:
+ client = MagicMock()
+ with (
+ patch(
+ "products.customer_analytics.backend.temporal.ownership_claims.a_schedule_exists",
+ new=AsyncMock(return_value=False),
+ ),
+ patch(
+ "products.customer_analytics.backend.temporal.ownership_claims.a_create_schedule", new=AsyncMock()
+ ) as create_schedule,
+ ):
+ await create_ownership_claims_coordinator_schedule(client)
+
+ assert create_schedule.await_args is not None
+ schedule = create_schedule.await_args.args[2]
+ assert schedule.policy.overlap == ScheduleOverlapPolicy.SKIP
+ assert schedule.action.execution_timeout == OWNERSHIP_CLAIMS_COORDINATOR_EXECUTION_TIMEOUT
+ assert OWNERSHIP_CLAIMS_COORDINATOR_EXECUTION_TIMEOUT < OWNERSHIP_CLAIMS_INTERVAL
+
+
+async def test_schedule_update_keeps_an_operator_pause() -> None:
+ paused = ScheduleState(paused=True, note="Repairing the bound view.")
+ client = MagicMock()
+ client.get_schedule_handle.return_value.describe = AsyncMock(
+ return_value=SimpleNamespace(schedule=SimpleNamespace(state=paused))
+ )
+ with (
+ patch(
+ "products.customer_analytics.backend.temporal.ownership_claims.a_schedule_exists",
+ new=AsyncMock(return_value=True),
+ ),
+ patch(
+ "products.customer_analytics.backend.temporal.ownership_claims.a_update_schedule", new=AsyncMock()
+ ) as update_schedule,
+ ):
+ await create_ownership_claims_coordinator_schedule(client)
+
+ assert update_schedule.await_args is not None
+ _, schedule_id, schedule = update_schedule.await_args.args
+ assert schedule_id == OWNERSHIP_CLAIMS_COORDINATOR_SCHEDULE_ID
+ assert schedule.state == paused
diff --git a/products/customer_analytics/backend/test/test_relationships.py b/products/customer_analytics/backend/test/test_relationships.py
index 95350340323b..c48b6691098e 100644
--- a/products/customer_analytics/backend/test/test_relationships.py
+++ b/products/customer_analytics/backend/test/test_relationships.py
@@ -1,13 +1,28 @@
+from datetime import datetime, timedelta
+
from posthog.test.base import BaseTest
+from unittest.mock import patch
from django.core.management import call_command
+from django.db import transaction
+from django.utils import timezone
+
+from parameterized import parameterized
from posthog.models import Team, User
+from posthog.models.activity_logging.activity_log import ActivityLog
+from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.customer_analytics.backend.facade import api as facade
+from products.customer_analytics.backend.facade.enums import AccountRelationshipSource
from products.customer_analytics.backend.logic import relationships
-from products.customer_analytics.backend.models import AccountRelationship, AccountRelationshipDefinition
-from products.customer_analytics.backend.test.factories import create_account
+from products.customer_analytics.backend.models import (
+ Account,
+ AccountRelationship,
+ AccountRelationshipControl,
+ AccountRelationshipDefinition,
+)
+from products.customer_analytics.backend.test.factories import create_account, enroll_account
class TestRelationshipLogic(BaseTest):
@@ -26,26 +41,25 @@ class TestRelationshipLogic(BaseTest):
account=self.account, ended_at__isnull=True, **filters
)
+ def _assign(self, definition: AccountRelationshipDefinition, user: User | None = None) -> AccountRelationship:
+ return relationships.assign(
+ team_id=self.team.id,
+ account=self.account,
+ definition=definition,
+ user=user or self.user,
+ actor=relationships.Actor.human(self.user),
+ )
+
def test_assign_creates_active_row(self):
definition = self._create_definition()
- rel = relationships.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
- )
+ rel = self._assign(definition)
assert rel.ended_at is None
assert rel.user == self.user
def test_reassign_single_holder_closes_previous_and_keeps_history(self):
definition = self._create_definition()
- first = relationships.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
- )
- second = relationships.assign(
- team_id=self.team.id,
- account=self.account,
- definition=definition,
- user=self.other_user,
- created_by=self.user,
- )
+ first = self._assign(definition)
+ second = self._assign(definition, self.other_user)
first.refresh_from_db()
assert first.ended_at is not None
assert second.ended_at is None
@@ -53,35 +67,24 @@ class TestRelationshipLogic(BaseTest):
def test_assign_same_user_is_noop(self):
definition = self._create_definition()
- first = relationships.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
- )
- second = relationships.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
- )
+ first = self._assign(definition)
+ second = self._assign(definition)
assert first.id == second.id
def test_multi_holder_allows_concurrent_assignees(self):
definition = self._create_definition(name="FDE", is_single_holder=False)
- relationships.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
- )
- relationships.assign(
- team_id=self.team.id,
- account=self.account,
- definition=definition,
- user=self.other_user,
- created_by=self.user,
- )
+ self._assign(definition)
+ self._assign(definition, self.other_user)
assert self._get_active_rows_for_account(definition=definition).count() == 2
def test_end_relationship_sets_ended_at(self):
definition = self._create_definition()
- rel = relationships.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
- )
+ rel = self._assign(definition)
ended = relationships.end_relationship(
- team_id=self.team.id, account_id=self.account.id, relationship_id=str(rel.id)
+ team_id=self.team.id,
+ account_id=self.account.id,
+ relationship_id=str(rel.id),
+ actor=relationships.Actor.human(),
)
assert ended.ended_at is not None
@@ -131,7 +134,11 @@ class TestBackfillAccountRelationshipsCommand(BaseTest):
team_id=self.team.id, name="CSM"
)
relationships.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=other_user, created_by=None
+ team_id=self.team.id,
+ account=self.account,
+ definition=definition,
+ user=other_user,
+ actor=relationships.Actor.human(),
)
call_command("backfill_account_relationships")
rows = self._active_rows()
@@ -141,6 +148,17 @@ class TestBackfillAccountRelationshipsCommand(BaseTest):
assert row.user_id == other_user.id
assert "csm" not in self._refreshed_properties()
+ def test_backfill_leaves_a_managed_relationship_alone(self):
+ definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="CSM", is_controlled=True
+ )
+ enroll_account(self.account, definition)
+
+ call_command("backfill_account_relationships")
+
+ assert self._active_rows().count() == 0
+ assert "csm" not in self._refreshed_properties()
+
def test_backfill_dry_run_changes_nothing(self):
call_command("backfill_account_relationships", "--dry-run")
assert self._active_rows().count() == 0
@@ -211,7 +229,7 @@ class TestRelationshipFacade(BaseTest):
account=self.account,
definition=model_definition,
user=self.user,
- created_by=self.user,
+ actor=relationships.Actor.human(self.user),
)
assert facade.delete_account_relationship_definition(team_id=self.team.id, definition_id=definition.id)
assert AccountRelationship.objects.for_team(self.team.id).count() == 0
@@ -227,9 +245,14 @@ class TestRelationshipFacade(BaseTest):
account=self.account,
definition=model_definition,
user=self.user,
- created_by=self.user,
+ actor=relationships.Actor.human(self.user),
+ )
+ relationships.end_relationship(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ relationship_id=str(rel.id),
+ actor=relationships.Actor.human(),
)
- relationships.end_relationship(team_id=self.team.id, account_id=self.account.id, relationship_id=str(rel.id))
assert facade.list_account_relationships(team_id=self.team.id, account_id=self.account.id) == []
history = facade.list_account_relationships(
team_id=self.team.id, account_id=self.account.id, include_history=True
@@ -345,3 +368,245 @@ class TestExternalRelationshipAssignments(BaseTest):
row = rows.first()
assert row is not None
assert row.user_id == self.user.id
+
+
+class TestControlledRelationshipPolicy(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.account = create_account(team_id=self.team.pk, name="Acme")
+ self.other_user = self._create_user("[email protected]")
+ self.ae_definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="Account executive", is_controlled=True
+ )
+ self.human = relationships.Actor.human(self.user)
+
+ def _manage_ae(self) -> datetime:
+ controlled_at = timezone.now() - timedelta(days=1)
+ enroll_account(self.account, self.ae_definition, controlled_at=controlled_at)
+ return controlled_at
+
+ def _fence(self, definition: AccountRelationshipDefinition | None = None) -> datetime | None:
+ return (
+ AccountRelationshipControl.objects.for_team(self.team.id)
+ .filter(account=self.account, definition=definition or self.ae_definition)
+ .values_list("controlled_at", flat=True)
+ .first()
+ )
+
+ def _assign(self, user: User, actor: relationships.Actor) -> AccountRelationship:
+ return relationships.assign(
+ team_id=self.team.id, account=self.account, definition=self.ae_definition, user=user, actor=actor
+ )
+
+ def _activity_rows(self) -> list[ActivityLog]:
+ return list(ActivityLog.objects.filter(team_id=self.team.id, scope="Account").order_by("created_at"))
+
+ @parameterized.expand(
+ [
+ (source, operation)
+ for source in AccountRelationshipSource
+ if source != AccountRelationshipSource.HUMAN
+ for operation in ("assign", "end_active")
+ ]
+ )
+ def test_autonomous_writer_cannot_change_a_managed_relationship(self, source, operation):
+ self._assign(self.other_user, self.human)
+ fence = self._manage_ae()
+ actor = relationships.Actor(source=source)
+
+ with self.assertRaises(relationships.ManagedRolePolicyError):
+ if operation == "assign":
+ self._assign(self.user, actor)
+ else:
+ relationships.end_active(
+ team_id=self.team.id, account=self.account, definition=self.ae_definition, actor=actor
+ )
+
+ holder = AccountRelationship.objects.for_team(self.team.id).get(account=self.account, ended_at__isnull=True)
+ assert holder.user_id == self.other_user.id
+ assert self._fence() == fence
+
+ def test_autonomous_writer_may_fill_an_unmanaged_controlled_relationship_without_taking_authority(self):
+ rel = self._assign(
+ self.user, relationships.Actor(source=AccountRelationshipSource.WORKFLOW, workflow_id="wf-1")
+ )
+
+ assert rel.source == AccountRelationshipSource.WORKFLOW
+ assert self._fence() is None
+ (row,) = self._activity_rows()
+ assert row.activity == "relationship_assigned"
+ assert row.is_system is True
+ assert row.detail is not None
+ assert row.detail["context"]["source"] == "workflow"
+ assert row.detail["context"]["workflow_id"] == "wf-1"
+ assert row.detail["context"]["definition_id"] == str(self.ae_definition.id)
+ assert row.detail["context"]["controlled_at"] is None
+
+ @parameterized.expand(["assign", "end_active", "confirm_empty", "end_relationship"])
+ def test_human_decision_on_a_managed_relationship_advances_the_fence(self, operation):
+ if operation != "confirm_empty":
+ rel = self._assign(self.other_user, self.human)
+ fence = self._manage_ae()
+
+ if operation == "assign":
+ self._assign(self.user, self.human)
+ elif operation == "end_active" or operation == "confirm_empty":
+ relationships.end_active(
+ team_id=self.team.id, account=self.account, definition=self.ae_definition, actor=self.human
+ )
+ else:
+ relationships.end_relationship(
+ team_id=self.team.id, account_id=self.account.id, relationship_id=str(rel.id), actor=self.human
+ )
+
+ advanced = self._fence()
+ assert advanced is not None and advanced > fence
+ last = self._activity_rows()[-1]
+ assert last.detail is not None
+ assert last.detail["context"]["controlled_at"] == advanced.isoformat()
+
+ def test_enroll_refuses_a_definition_that_is_not_controlled(self):
+ plain = AccountRelationshipDefinition.objects.for_team(self.team.id).create(team_id=self.team.id, name="Buddy")
+
+ with self.assertRaises(relationships.DefinitionNotControlledError):
+ relationships.enroll(team_id=self.team.id, account=self.account, definition=plain, actor=self.human)
+
+ assert self._fence(plain) is None
+
+ def test_enrolling_twice_keeps_the_first_fence(self):
+ first = relationships.enroll(
+ team_id=self.team.id, account=self.account, definition=self.ae_definition, actor=self.human
+ )
+
+ again = relationships.enroll(
+ team_id=self.team.id, account=self.account, definition=self.ae_definition, actor=self.human
+ )
+
+ assert (again.id, again.controlled_at) == (first.id, first.controlled_at)
+ assert ActivityLog.objects.filter(team_id=self.team.id, activity="role_enrolled").count() == 1
+
+ def test_a_decision_on_one_controlled_relationship_leaves_another_fence_alone(self):
+ csm_definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="CSM", is_controlled=True
+ )
+ ae_fence = self._manage_ae()
+ csm_fence = timezone.now() - timedelta(days=2)
+ enroll_account(self.account, csm_definition, controlled_at=csm_fence)
+
+ self._assign(self.user, self.human)
+
+ advanced = self._fence()
+ assert advanced is not None and advanced > ae_fence
+ assert self._fence(csm_definition) == csm_fence
+
+ def test_confirming_an_empty_managed_relationship_is_recorded_as_a_decision(self):
+ self._manage_ae()
+
+ ended = relationships.end_active(
+ team_id=self.team.id, account=self.account, definition=self.ae_definition, actor=self.human
+ )
+
+ assert ended == 0
+ (row,) = self._activity_rows()
+ assert row.activity == "role_confirmed_empty"
+ assert row.user_id == self.user.id
+ assert row.detail is not None
+ assert row.detail["changes"] == [
+ {"type": "Account", "action": "changed", "field": "Account executive", "before": None, "after": None}
+ ]
+
+ def test_reassigning_the_current_holder_is_not_a_new_decision(self):
+ self._assign(self.user, self.human)
+ fence = self._manage_ae()
+
+ self._assign(self.user, self.human)
+
+ assert self._fence() == fence
+ assert len(self._activity_rows()) == 1
+
+ def test_activity_write_failure_rolls_back_the_mutation(self):
+ fence = self._manage_ae()
+
+ with patch.object(ActivityLog.objects, "bulk_create", side_effect=RuntimeError("audit store down")):
+ with self.assertRaises(RuntimeError):
+ self._assign(self.user, self.human)
+
+ assert not AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).exists()
+ assert self._fence() == fence
+
+ def test_rollback_after_the_audit_row_is_written_leaves_no_row_and_publishes_nothing(self):
+ with self.captureOnCommitCallbacks(execute=True) as callbacks:
+ with self.assertRaises(RuntimeError):
+ with transaction.atomic():
+ self._assign(self.user, self.human)
+ raise RuntimeError("a later step in the same transaction failed")
+
+ assert not ActivityLog.objects.filter(team_id=self.team.id, scope="Account").exists()
+ assert callbacks == []
+
+ def test_controlled_history_cannot_be_hard_deleted(self):
+ rel = self._assign(self.user, self.human)
+
+ with self.assertRaises(relationships.ProtectedRelationshipHistoryError):
+ relationships.delete_relationship(
+ team_id=self.team.id, account_id=self.account.id, relationship_id=str(rel.id), actor=self.human
+ )
+
+ assert AccountRelationship.objects.for_team(self.team.id).filter(id=rel.id).exists()
+
+ def test_controlled_definition_cannot_be_deleted_or_loosened_through_the_facade(self):
+ with self.assertRaises(facade.AccountRelationshipDefinitionControlledError):
+ facade.delete_account_relationship_definition(team_id=self.team.id, definition_id=self.ae_definition.id)
+ with self.assertRaises(facade.AccountRelationshipDefinitionControlledError):
+ facade.update_account_relationship_definition(
+ team_id=self.team.id, definition_id=self.ae_definition.id, fields={"is_single_holder": False}
+ )
+ with self.assertRaises(ValueError):
+ facade.update_account_relationship_definition(
+ team_id=self.team.id, definition_id=self.ae_definition.id, fields={"is_controlled": False}
+ )
+ self.ae_definition.refresh_from_db()
+ assert (self.ae_definition.is_controlled, self.ae_definition.is_single_holder) == (True, True)
+
+ def test_assign_on_a_managed_relationship_hands_off_even_with_a_stale_definition_copy(self):
+ self._assign(self.other_user, self.human)
+ self._manage_ae()
+ stale = AccountRelationshipDefinition.objects.for_team(self.team.id).get(id=self.ae_definition.id)
+ stale.is_single_holder = False
+ stale.is_controlled = False
+
+ relationships.assign(
+ team_id=self.team.id, account=self.account, definition=stale, user=self.user, actor=self.human
+ )
+
+ holders = AccountRelationship.objects.for_team(self.team.id).filter(account=self.account, ended_at__isnull=True)
+ assert [holder.user_id for holder in holders] == [self.user.id]
+
+ def test_team_deletion_cascades_through_controls(self):
+ self._manage_ae()
+
+ self.team.delete()
+
+ assert not AccountRelationshipControl.objects.unscoped().filter(definition_id=self.ae_definition.id).exists()
+ assert not AccountRelationshipDefinition.objects.unscoped().filter(id=self.ae_definition.id).exists()
+
+ @parameterized.expand(["enrolled", "history_under_a_controlled_definition"])
+ def test_account_with_controlled_authority_or_history_cannot_be_deleted(self, case):
+ if case == "enrolled":
+ self._manage_ae()
+ else:
+ self._assign(self.other_user, self.human)
+
+ with self.assertRaises(facade.AccountOwnershipManagedError):
+ facade.delete_account_for_view(
+ team_id=self.team.id,
+ account_id=str(self.account.id),
+ user_access_control=UserAccessControl(user=self.user, team=self.team),
+ required_level=None,
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+
+ assert Account.objects.for_team(self.team.id).filter(id=self.account.id).exists()
+ assert not any(row.activity == "deleted" for row in self._activity_rows())
diff --git a/products/customer_analytics/backend/test/test_upsert_account.py b/products/customer_analytics/backend/test/test_upsert_account.py
index 1b7989dad5b6..037cf600b24c 100644
--- a/products/customer_analytics/backend/test/test_upsert_account.py
+++ b/products/customer_analytics/backend/test/test_upsert_account.py
@@ -1,4 +1,6 @@
import uuid
+from datetime import UTC, datetime
+from typing import Any
import pytest
from posthog.test.base import BaseTest
@@ -15,6 +17,7 @@ from products.customer_analytics.backend.max_tools import (
UpsertAccountTool,
)
from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinition
+from products.customer_analytics.backend.test.factories import enroll_account
class TestUpsertAccountTool(BaseTest):
@@ -31,8 +34,10 @@ class TestUpsertAccountTool(BaseTest):
)()
@sync_to_async
- def _create_definition(self, name: str = "CSM") -> AccountRelationshipDefinition:
- return AccountRelationshipDefinition.objects.for_team(self.team.id).create(team_id=self.team.id, name=name)
+ def _create_definition(self, name: str = "CSM", **kwargs: Any) -> AccountRelationshipDefinition:
+ return AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name=name, **kwargs
+ )
async def _active_holder_ids(self, account: Account) -> set[int]:
return await sync_to_async(
@@ -108,6 +113,21 @@ class TestUpsertAccountTool(BaseTest):
)
assert await self._active_holder_ids(account) == set()
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_update_cannot_change_a_managed_controlled_relationship(self):
+ definition = await self._create_definition("CSM", is_controlled=True)
+ account = await sync_to_async(Account.objects.unscoped().create)(team=self.team, name="Acme")
+ await sync_to_async(enroll_account)(account, definition, controlled_at=datetime(2026, 1, 1, tzinfo=UTC))
+
+ content, artifact = await self._tool()._arun_impl(
+ action=UpdateAccountAction(account_id=str(account.id), relationships={"CSM": self.user.id})
+ )
+
+ assert artifact["error"] == "invalid_relationship_assignment"
+ assert "controlled in Customer analytics" in content
+ assert await self._active_holder_ids(account) == set()
+
@pytest.mark.django_db
@pytest.mark.asyncio
async def test_create_with_unknown_relationship_name_persists_nothing(self):
diff --git a/products/customer_analytics/backend/test/test_usage_spike_notifications.py b/products/customer_analytics/backend/test/test_usage_spike_notifications.py
index 8de2f66bd50c..127d31fb7618 100644
--- a/products/customer_analytics/backend/test/test_usage_spike_notifications.py
+++ b/products/customer_analytics/backend/test/test_usage_spike_notifications.py
@@ -41,7 +41,7 @@ class TestNotifyManagersOfUsageSpike(BaseTest):
account=account,
definition=definition,
user=user,
- created_by=None,
+ actor=relationships_logic.Actor.human(),
)
def _notify_managers(self, *, team_id: int | None = None, **kwargs):
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index d889930acdb8..57876d094e25 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -13,6 +13,7 @@ from parameterized import parameterized
from redis.exceptions import RedisError
from rest_framework import status
+from posthog.auth import MCP_USER_AGENT_MARKER
from posthog.constants import AvailableFeature
from posthog.models import Tag, TaggedItem
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -35,7 +36,10 @@ from products.conversations.backend.models import (
EmailThreadParticipantKind,
)
from products.conversations.backend.models.ticket import Ticket
-from products.customer_analytics.backend.logic import relationships as relationships_logic
+from products.customer_analytics.backend.logic import (
+ ownership,
+ relationships as relationships_logic,
+)
from products.customer_analytics.backend.models import (
Account,
AccountRelationship,
@@ -50,7 +54,11 @@ from products.customer_analytics.backend.models import (
MeetingParticipant,
TargetType,
)
-from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition
+from products.customer_analytics.backend.test.factories import (
+ create_account,
+ create_custom_property_definition,
+ enroll_account,
+)
from products.notebooks.backend.facade.content import build_markdown_notebook_content
from products.notebooks.backend.models import Notebook, ResourceNotebook
from products.product_analytics.backend.facade.models import Insight
@@ -2951,7 +2959,11 @@ class TestAccountRelationshipDefinitionViewSet(APIBaseTest):
# nosemgrep: idor-lookup-without-team (test setup)
definition = AccountRelationshipDefinition.objects.unscoped().get(id=definition_id)
relationships_logic.assign(
- team_id=self.team.id, account=account, definition=definition, user=self.user, created_by=self.user
+ team_id=self.team.id,
+ account=account,
+ definition=definition,
+ user=self.user,
+ actor=relationships_logic.Actor.human(self.user),
)
response = self.client.delete(f"{self.endpoint_base}{definition_id}/")
@@ -2991,19 +3003,30 @@ class TestAccountRelationshipViewSet(APIBaseTest):
team_id=self.team.id, name=name, created_by=self.user
)
- def test_lists_active_relationships_by_default(self):
- csm = self._create_relationship_definition("CSM")
- fde = self._create_relationship_definition("FDE")
- active = relationships_logic.assign(
- team_id=self.team.id, account=self.account, definition=csm, user=self.user, created_by=self.user
- )
- ended = relationships_logic.assign(
- team_id=self.team.id, account=self.account, definition=fde, user=self.user, created_by=self.user
+ def _assign(self, definition, user=None) -> AccountRelationship:
+ return relationships_logic.assign(
+ team_id=self.team.id,
+ account=self.account,
+ definition=definition,
+ user=user or self.user,
+ actor=relationships_logic.Actor.human(self.user),
)
+
+ def _end(self, relationship: AccountRelationship) -> None:
relationships_logic.end_relationship(
- team_id=self.team.id, account_id=self.account.id, relationship_id=str(ended.id)
+ team_id=self.team.id,
+ account_id=self.account.id,
+ relationship_id=str(relationship.id),
+ actor=relationships_logic.Actor.human(),
)
+ def test_lists_active_relationships_by_default(self):
+ csm = self._create_relationship_definition("CSM")
+ fde = self._create_relationship_definition("FDE")
+ active = self._assign(csm)
+ ended = self._assign(fde)
+ self._end(ended)
+
response = self.client.get(self.endpoint)
self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
@@ -3017,12 +3040,8 @@ class TestAccountRelationshipViewSet(APIBaseTest):
def test_include_history_returns_full_timeline(self):
definition = self._create_relationship_definition()
successor = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
- relationships_logic.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
- )
- relationships_logic.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=successor, created_by=self.user
- )
+ self._assign(definition)
+ self._assign(definition, successor)
response = self.client.get(f"{self.endpoint}?include_history=true")
@@ -3056,6 +3075,30 @@ class TestAccountRelationshipViewSet(APIBaseTest):
self.assertIsNotNone(ended.json()["ended_at"])
self.assertEqual([], self.client.get(self.endpoint).json())
+ @parameterized.expand([("agent", True, status.HTTP_409_CONFLICT), ("person", False, status.HTTP_201_CREATED)])
+ def test_only_a_person_can_change_a_managed_role_with_a_personal_key(self, _name, via_agent, expected):
+ definition = self._create_relationship_definition("Account executive")
+ ownership.set_controlled(self.team.id, definition.id, True)
+ enroll_account(self.account, definition)
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="agent",
+ user=self.user,
+ secure_value=hash_key_value(value),
+ scopes=["account:write"],
+ scoped_teams=[],
+ scoped_organizations=[],
+ )
+ user_agent = f"cursor/1.0 {MCP_USER_AGENT_MARKER}" if via_agent else "curl/8.0"
+
+ response = self.client.post(
+ self.endpoint,
+ {"definition": str(definition.id), "user": self.user.id},
+ headers={"authorization": f"Bearer {value}", "user-agent": user_agent},
+ )
+
+ self.assertEqual(expected, response.status_code, response.json())
+
def test_assign_with_unknown_definition_returns_400(self):
response = self.client.post(
self.endpoint, {"definition": "00000000-0000-0000-0000-000000000000", "user": self.user.id}
@@ -3079,12 +3122,8 @@ class TestAccountRelationshipViewSet(APIBaseTest):
def test_end_already_ended_relationship_returns_404(self):
definition = self._create_relationship_definition()
- rel = relationships_logic.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
- )
- relationships_logic.end_relationship(
- team_id=self.team.id, account_id=self.account.id, relationship_id=str(rel.id)
- )
+ rel = self._assign(definition)
+ self._end(rel)
response = self.client.post(f"{self.endpoint}{rel.id}/end/")
@@ -3096,24 +3135,23 @@ class TestAccountRelationshipViewSet(APIBaseTest):
level=OrganizationMembership.Level.ADMIN
)
definition = self._create_relationship_definition()
- relationship = relationships_logic.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
- )
+ relationship = self._assign(definition)
if ended:
- relationships_logic.end_relationship(
- team_id=self.team.id, account_id=self.account.id, relationship_id=str(relationship.id)
- )
+ self._end(relationship)
response = self.client.delete(f"{self.endpoint}{relationship.id}/")
self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code)
+ self.assertTrue(
+ ActivityLog.objects.filter(
+ team_id=self.team.id, activity="relationship_deleted", detail__context__source="human"
+ ).exists()
+ )
self.assertFalse(AccountRelationship.objects.for_team(self.team.id).filter(id=relationship.id).exists())
def test_non_admin_cannot_hard_delete_relationship(self):
definition = self._create_relationship_definition()
- relationship = relationships_logic.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
- )
+ relationship = self._assign(definition)
member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
self.client.force_login(member)
@@ -3129,9 +3167,7 @@ class TestAccountRelationshipViewSet(APIBaseTest):
]
self.organization.save()
definition = self._create_relationship_definition()
- relationship = relationships_logic.assign(
- team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
- )
+ relationship = self._assign(definition)
account_viewer = User.objects.create_and_join(
self.organization, "[email protected]", "testtest"
)
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 3d77bf5e5c84..ceb8a880de22 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -29,7 +29,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc
└── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Feature requests/Usage/Spend/Opportunities/Conversations/Meetings/Event stream)
├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)
├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId; supports bulk email copy; staff get a compact, region-aware admin link)
- ├── (relationships) AccountRelationshipsExpansion (accountRelationshipsLogic, keyed by accountId — full assignment timeline, paginated; assign/unassign controls + definition filter, admin-only hard-delete controls with confirmation, current assignments sorted on top)
+ ├── (relationships) AccountRelationshipsExpansion (accountRelationshipsLogic, keyed by accountId — full assignment timeline, paginated; assign/unassign controls + definition filter, admin-only hard-delete controls with confirmation, current assignments sorted on top; each row shows which kind of writer made it (`source`: person, workflow, AI, Salesforce, migration), the backend refuses a hard delete of any row under a controlled definition, and refuses an autonomous edit only where the account is enrolled under that definition)
├── (feature requests) AccountFeatureRequestsExpansion (accountFeatureRequestsLogic, keyed by accountId — linked requests and link-existing flow)
├── (usage) AccountBillingExpansion kind="usage" (accountBillingLogic — a saved billing-usage insight)
├── (spend) AccountBillingExpansion kind="spend" (accountBillingLogic — saved billing-spend insights)
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountPinnedPropertiesExpansion.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountPinnedPropertiesExpansion.test.tsx
index 7c55a7299753..a742c1303795 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountPinnedPropertiesExpansion.test.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountPinnedPropertiesExpansion.test.tsx
@@ -51,6 +51,7 @@ const relationshipDefinition: AccountRelationshipDefinitionApi = {
id: 'relationship-1',
name: 'CSM',
is_single_holder: true,
+ is_controlled: false,
}
const members = [
{ id: 1, email: '[email protected]', first_name: '' },
@@ -86,6 +87,7 @@ function createAssignment(userId: number): AccountRelationshipApi {
user: members.find(({ id }) => id === userId)!,
started_at: '2026-01-01T00:00:00Z',
ended_at: null,
+ source: null,
}
}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx
index 83d0a77420c3..0d4b22c7c8cd 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx
@@ -14,12 +14,23 @@ import {
import { MemberSelect } from 'lib/components/MemberSelect'
import { TZLabel } from 'lib/components/TZLabel'
-import type { AccountRelationshipApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import type {
+ AccountRelationshipApi,
+ AccountRelationshipSourceEnumApi,
+} from 'products/customer_analytics/frontend/generated/api.schemas'
import { accountRelationshipsLogic } from './accountRelationshipsLogic'
const PAGE_SIZE = 10
+const SOURCE_LABELS: Record<AccountRelationshipSourceEnumApi, string> = {
+ human: 'Person',
+ workflow: 'Workflow',
+ ai: 'AI',
+ salesforce_claim: 'Salesforce',
+ migration: 'Migration',
+}
+
export function AccountRelationshipsExpansion({
accountId,
embedded = true,
@@ -69,6 +80,17 @@ export function AccountRelationshipsExpansion({
<span className="text-muted italic">Deleted user</span>
),
},
+ {
+ title: 'Assigned by',
+ key: 'source',
+ width: 110,
+ render: (_, relationship) =>
+ relationship.source ? (
+ SOURCE_LABELS[relationship.source]
+ ) : (
+ <span className="text-muted">Not recorded</span>
+ ),
+ },
{
title: 'Started',
key: 'started_at',
@@ -78,7 +100,7 @@ export function AccountRelationshipsExpansion({
{
title: 'Ended',
key: 'ended_at',
- width: 140,
+ width: 160,
render: (_, relationship) =>
relationship.ended_at ? (
<TZLabel time={relationship.ended_at} />
diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts
index a3d82e1b413c..74914eb256ae 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts
@@ -19,12 +19,19 @@ import { accountRelationshipsLogic } from './accountRelationshipsLogic'
const RELATIONSHIPS_URL = '/api/projects/:team_id/accounts/:account_id/relationships/'
const RELATIONSHIP_URL = '/api/projects/:team_id/accounts/:account_id/relationships/:id/'
-const CSM: AccountRelationshipDefinitionApi = { id: 'def-1', name: 'CSM', description: null, is_single_holder: true }
+const CSM: AccountRelationshipDefinitionApi = {
+ id: 'def-1',
+ name: 'CSM',
+ description: null,
+ is_single_holder: true,
+ is_controlled: false,
+}
const AE: AccountRelationshipDefinitionApi = {
id: 'def-2',
name: 'Account executive',
description: null,
is_single_holder: true,
+ is_controlled: false,
}
const buildRelationship = (overrides: Partial<AccountRelationshipApi> = {}): AccountRelationshipApi => ({
@@ -33,6 +40,7 @@ const buildRelationship = (overrides: Partial<AccountRelationshipApi> = {}): Acc
user: { id: 1, email: '[email protected]' },
started_at: '2026-01-01T00:00:00Z',
ended_at: null,
+ source: null,
...overrides,
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
index 7ba702c6272f..3ea65539ff72 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
@@ -48,6 +48,7 @@ const relationshipDefinition = (
name,
description: null,
is_single_holder: true,
+ is_controlled: false,
...overrides,
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index e28eb52716ae..0df46141626d 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -124,9 +124,15 @@ const ACCOUNT_FILTERS = [
const CUSTOM_TILES = [{ id: 'tile-1', label: 'Accounts', metric: { type: 'count' as const } }]
const DEFINITIONS: AccountRelationshipDefinitionApi[] = [
- { id: CSM_DEFINITION_ID, name: 'CSM', description: null, is_single_holder: true },
- { id: AE_DEFINITION_ID, name: 'Account executive', description: null, is_single_holder: true },
- { id: OWNER_DEFINITION_ID, name: 'Account owner', description: null, is_single_holder: true },
+ { id: CSM_DEFINITION_ID, name: 'CSM', description: null, is_single_holder: true, is_controlled: false },
+ {
+ id: AE_DEFINITION_ID,
+ name: 'Account executive',
+ description: null,
+ is_single_holder: true,
+ is_controlled: false,
+ },
+ { id: OWNER_DEFINITION_ID, name: 'Account owner', description: null, is_single_holder: true, is_controlled: false },
]
const buildRelationship = (overrides: Partial<AccountRelationshipApi> = {}): AccountRelationshipApi => ({
@@ -135,6 +141,7 @@ const buildRelationship = (overrides: Partial<AccountRelationshipApi> = {}): Acc
user: { id: 42, email: '[email protected]' },
started_at: '2026-01-01T00:00:00Z',
ended_at: null,
+ source: null,
...overrides,
})
@@ -725,7 +732,13 @@ describe('accountsLogic', () => {
const config = accountsColumnConfigLogic.findMounted()!
config.actions.loadRelationshipDefinitionsSuccess([
...DEFINITIONS,
- { id: 'def-os', name: 'Onboarding specialist', description: null, is_single_holder: true },
+ {
+ id: 'def-os',
+ name: 'Onboarding specialist',
+ description: null,
+ is_single_holder: true,
+ is_controlled: false,
+ },
])
expect(config.values.selectColumns).toEqual([
...ACCOUNTS_DEFAULT_COLUMNS,
@@ -741,7 +754,13 @@ describe('accountsLogic', () => {
config.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])
config.actions.loadRelationshipDefinitionsSuccess([
...DEFINITIONS,
- { id: 'def-os', name: 'Onboarding specialist', description: null, is_single_holder: true },
+ {
+ id: 'def-os',
+ name: 'Onboarding specialist',
+ description: null,
+ is_single_holder: true,
+ is_controlled: false,
+ },
])
expect(config.values.selectColumns).toEqual([ACCOUNTS_NAME_COLUMN, 'csm'])
})
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index cd1bc29a2b6e..80b53711fba9 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -29,6 +29,101 @@ export type ExternalAccountApiRelationships = { [key: string]: ExternalAccountAs
*/
export type ExternalAccountApiCustomProperties = { [key: string]: unknown }
+/**
+ * * `unmanaged` - Unmanaged
+ * * `assigned` - Assigned
+ * * `cleared` - Cleared
+ * * `blocked` - Blocked
+ */
+export type OwnershipRoleStateEnumApi = (typeof OwnershipRoleStateEnumApi)[keyof typeof OwnershipRoleStateEnumApi]
+
+export const OwnershipRoleStateEnumApi = {
+ Unmanaged: 'unmanaged',
+ Assigned: 'assigned',
+ Cleared: 'cleared',
+ Blocked: 'blocked',
+} as const
+
+export interface ExternalAccountOwnershipHolderApi {
+ /** PostHog user id of the holder. */
+ user_id: number
+ /**
+ * Current email address of the holder; null for a holder outside the organization.
+ * @nullable
+ */
+ email: string | null
+ /**
+ * Current display name of the holder; null when unset or outside the organization.
+ * @nullable
+ */
+ name: string | null
+ /** Whether the holder is currently a member of the project's organization. */
+ is_organization_member: boolean
+ /** Whether the holder's PostHog user account is active. */
+ is_active: boolean
+}
+
+/**
+ * * `holder_missing` - The active relationship has no user
+ * * `holder_inactive` - The holder's user account is deactivated
+ * * `holder_not_in_organization` - The holder is not a member of the organization
+ * * `multiple_active_holders` - More than one active relationship holds the role
+ */
+export type OwnershipRoleDiagnosticEnumApi =
+ (typeof OwnershipRoleDiagnosticEnumApi)[keyof typeof OwnershipRoleDiagnosticEnumApi]
+
+export const OwnershipRoleDiagnosticEnumApi = {
+ HolderMissing: 'holder_missing',
+ HolderInactive: 'holder_inactive',
+ HolderNotInOrganization: 'holder_not_in_organization',
+ MultipleActiveHolders: 'multiple_active_holders',
+} as const
+
+export interface ExternalAccountRoleOwnershipApi {
+ /** The controlled relationship definition. Map it to the role you project; it does not change. */
+ definition_id: string
+ /** Current name of the relationship definition. */
+ definition_name: string
+ /** `unmanaged`: customer analytics does not hold authority over this relationship on this account; the holder, if any, is a legacy assignment. `assigned`: the holder is authoritative. `cleared`: the relationship is authoritatively empty. `blocked`: the relationship is managed but its holder cannot be projected; see `diagnostics` and keep the last applied value.
+ *
+ * * `unmanaged` - Unmanaged
+ * * `assigned` - Assigned
+ * * `cleared` - Cleared
+ * * `blocked` - Blocked */
+ state: OwnershipRoleStateEnumApi
+ /**
+ * When customer analytics last decided this relationship on this account; null while unmanaged.
+ * @nullable
+ */
+ controlled_at: string | null
+ /**
+ * The active relationship holding the role, or null when empty.
+ * @nullable
+ */
+ relationship_id: string | null
+ /** The current holder, or null. */
+ holder: ExternalAccountOwnershipHolderApi | null
+ /** Why a managed relationship is blocked. Informational on an unmanaged one. */
+ diagnostics: OwnershipRoleDiagnosticEnumApi[]
+}
+
+export interface ExternalAccountOwnershipApi {
+ /** Account UUID, the canonical identity within this project. */
+ account_id: string
+ /**
+ * External account key: the group key the account is linked to.
+ * @nullable
+ */
+ external_id: string | null
+ /**
+ * Region of this PostHog instance (`us`, `eu`), or null when self-hosted.
+ * @nullable
+ */
+ region: string | null
+ /** One entry per controlled relationship definition of the project, in name order, whether or not this account is managed under it. Empty when the project controls no relationship. */
+ roles: ExternalAccountRoleOwnershipApi[]
+}
+
export interface ExternalAccountApi {
/** Account UUID. */
id: string
@@ -51,6 +146,8 @@ export interface ExternalAccountApi {
ignored_at: string | null
/** Typed account properties: external-system ids. Role assignments live under `relationships`. */
properties: ExternalAccountApiProperties
+ /** Authority state of each relationship the project controls. */
+ ownership: ExternalAccountOwnershipApi
/** Tag names on the account, sorted alphabetically. */
tags: string[]
/** Active relationship assignments keyed by definition name (e.g. 'CSM'). Definitions with no active assignment are omitted. */
@@ -96,6 +193,8 @@ export interface ExternalAccountListItemApi {
* @nullable
*/
ignored_at: string | null
+ /** Authority state of each relationship the project controls. */
+ ownership: ExternalAccountOwnershipApi
/** Active relationship assignments to current organization members, keyed by relationship definition name (e.g. 'CSM', 'Account executive'). Definitions with no active assignment are omitted. */
relationships: ExternalAccountListItemApiRelationships
}
@@ -232,6 +331,8 @@ export interface AccountRelationshipDefinitionApi {
description?: string | null
/** Whether only one user can hold this relationship per account at a time, e.g. a single CSM per account. */
is_single_holder?: boolean
+ /** Whether customer analytics can take control of this relationship per account. Rows under a controlled relationship can't be deleted. On an account where control has started, only a person can change the relationship and an empty relationship is a deliberate decision. Set by project operators, not through this API. */
+ readonly is_controlled: boolean
}
export interface PaginatedAccountRelationshipDefinitionListApi {
@@ -261,6 +362,8 @@ export interface PatchedAccountRelationshipDefinitionApi {
description?: string | null
/** Whether only one user can hold this relationship per account at a time, e.g. a single CSM per account. */
is_single_holder?: boolean
+ /** Whether customer analytics can take control of this relationship per account. Rows under a controlled relationship can't be deleted. On an account where control has started, only a person can change the relationship and an empty relationship is a deliberate decision. Set by project operators, not through this API. */
+ readonly is_controlled?: boolean
}
/**
@@ -567,6 +670,24 @@ export interface AccountAssignmentApi {
readonly email: string
}
+/**
+ * * `human` - Human
+ * * `workflow` - Workflow
+ * * `ai` - AI
+ * * `salesforce_claim` - Salesforce claim
+ * * `migration` - Migration
+ */
+export type AccountRelationshipSourceEnumApi =
+ (typeof AccountRelationshipSourceEnumApi)[keyof typeof AccountRelationshipSourceEnumApi]
+
+export const AccountRelationshipSourceEnumApi = {
+ Human: 'human',
+ Workflow: 'workflow',
+ Ai: 'ai',
+ SalesforceClaim: 'salesforce_claim',
+ Migration: 'migration',
+} as const
+
/**
* One assignment of a user to an account relationship, with its effective range.
*/
@@ -584,6 +705,14 @@ export interface AccountRelationshipApi {
* @nullable
*/
readonly ended_at: string | null
+ /** Which kind of writer made this assignment; null on rows older than provenance tracking.
+ *
+ * * `human` - Human
+ * * `workflow` - Workflow
+ * * `ai` - AI
+ * * `salesforce_claim` - Salesforce claim
+ * * `migration` - Migration */
+ readonly source: AccountRelationshipSourceEnumApi | null
}
/**
@@ -4127,6 +4256,10 @@ export type CustomerAnalyticsExternalAccountsRetrieveParams = {
* Maximum number of accounts to return. Values below 1 are clamped to 1; values above 100 are clamped to 100.
*/
limit?: number
+ /**
+ * When true, return only accounts where customer analytics holds authority over at least one controlled relationship, including accounts whose managed relationships are cleared and accounts that are ignored. Authority does not end when an account is ignored, so `include_ignored` is implied.
+ */
+ managed_only?: boolean
}
export type AccountNotesListParams = {
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index c1bd889c4c0b..13c65b95e5a6 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -155,7 +155,7 @@ export const getCustomerAnalyticsExternalAccountRetrieveUrl = (
}
/**
- * Fetch one account by external ID with its properties, tags, active relationship assignments and custom property values. Accepts the team secret API token or a project secret API key with the `account:read` scope.
+ * Fetch one account by external ID with its properties, controlled relationship ownership, tags, active relationship assignments and custom property values. Accepts the team secret API token or a project secret API key with the `account:read` scope.
* @summary Get an external customer analytics account
*/
export const customerAnalyticsExternalAccountRetrieve = async (
@@ -187,7 +187,7 @@ export const getCustomerAnalyticsExternalAccountsRetrieveUrl = (
}
/**
- * List tracked accounts with external IDs, lifecycle timestamps, and active relationship assignments. Set `include_ignored=true` to include ignored accounts. Requires a project secret API key with the `account:read` scope.
+ * List tracked accounts with external IDs, lifecycle timestamps, controlled relationship ownership, and active relationship assignments. Set `include_ignored=true` to include ignored accounts and `managed_only=true` to read only the accounts customer analytics holds ownership authority for. Requires a project secret API key with the `account:read` scope.
* @summary List external customer analytics accounts
*/
export const customerAnalyticsExternalAccountsRetrieve = async (
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.ts
index 8d88740ddd79..15e6760aadf8 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.ts
@@ -52,6 +52,7 @@ const buildRelationship = (
name: 'CSM',
description: null,
is_single_holder: true,
+ is_controlled: false,
...overrides,
})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.test.ts
index 9b4899e3aae8..1e46f8989d90 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.test.ts
@@ -41,6 +41,7 @@ const relationshipDefinition: AccountRelationshipDefinitionApi = {
id: 'relationship-1',
name: 'Account team',
is_single_holder: false,
+ is_controlled: false,
}
const VALUES_URL = '/api/projects/:project_id/accounts/:account_id/custom_property_values/'
const RELATIONSHIPS_URL = '/api/projects/:project_id/accounts/:account_id/relationships/'
@@ -56,6 +57,7 @@ describe('accountSidebarPropertiesLogic', () => {
user: { id, email: `member${id}@example.com` },
started_at: '2026-01-01T00:00:00Z',
ended_at: null,
+ source: null,
})
const mount = async (): Promise<void> => {
logic = accountSidebarPropertiesLogic({ projectId: 1, accountId: 'account-1' })
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyComponents.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyComponents.stories.tsx
index 3997e495fc14..9b4cc7ab863d 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyComponents.stories.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyComponents.stories.tsx
@@ -79,6 +79,7 @@ function relationshipProperty(
name,
description: null,
is_single_holder: isSingleHolder,
+ is_controlled: false,
}
return { key: `relationship:${id}`, kind: 'relationship', definition, members }
}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/relationshipDefinitionsLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/relationshipDefinitionsLogic.test.ts
index 54e9fe8af631..aa460629aab8 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/relationshipDefinitionsLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/relationshipDefinitionsLogic.test.ts
@@ -21,6 +21,7 @@ const buildDefinition = (
name: 'CSM',
description: null,
is_single_holder: true,
+ is_controlled: false,
...overrides,
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9b6b43f788de..f43731cbd2cf 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -897,8 +897,28 @@ export namespace Schemas {
description?: string | null;
/** Whether only one user can hold this relationship per account at a time, e.g. a single CSM per account. */
is_single_holder?: boolean;
+ /** Whether customer analytics can take control of this relationship per account. Rows under a controlled relationship can't be deleted. On an account where control has started, only a person can change the relationship and an empty relationship is a deliberate decision. Set by project operators, not through this API. */
+ readonly is_controlled: boolean;
}
+ /**
+ * * `human` - Human
+ * * `workflow` - Workflow
+ * * `ai` - AI
+ * * `salesforce_claim` - Salesforce claim
+ * * `migration` - Migration
+ */
+ export type AccountRelationshipSourceEnum = typeof AccountRelationshipSourceEnum[keyof typeof AccountRelationshipSourceEnum];
+
+
+ export const AccountRelationshipSourceEnum = {
+ Human: 'human',
+ Workflow: 'workflow',
+ Ai: 'ai',
+ SalesforceClaim: 'salesforce_claim',
+ Migration: 'migration',
+ } as const;
+
/**
* One assignment of a user to an account relationship, with its effective range.
*/
@@ -916,6 +936,14 @@ export namespace Schemas {
* @nullable
*/
readonly ended_at: string | null;
+ /** Which kind of writer made this assignment; null on rows older than provenance tracking.
+ *
+ * * `human` - Human
+ * * `workflow` - Workflow
+ * * `ai` - AI
+ * * `salesforce_claim` - Salesforce claim
+ * * `migration` - Migration */
+ readonly source: AccountRelationshipSourceEnum | null;
}
/**
@@ -38463,6 +38491,102 @@ export namespace Schemas {
*/
export type ExternalAccountCustomProperties = {[key: string]: unknown};
+ /**
+ * * `unmanaged` - Unmanaged
+ * * `assigned` - Assigned
+ * * `cleared` - Cleared
+ * * `blocked` - Blocked
+ */
+ export type OwnershipRoleStateEnum = typeof OwnershipRoleStateEnum[keyof typeof OwnershipRoleStateEnum];
+
+
+ export const OwnershipRoleStateEnum = {
+ Unmanaged: 'unmanaged',
+ Assigned: 'assigned',
+ Cleared: 'cleared',
+ Blocked: 'blocked',
+ } as const;
+
+ export interface ExternalAccountOwnershipHolder {
+ /** PostHog user id of the holder. */
+ user_id: number;
+ /**
+ * Current email address of the holder; null for a holder outside the organization.
+ * @nullable
+ */
+ email: string | null;
+ /**
+ * Current display name of the holder; null when unset or outside the organization.
+ * @nullable
+ */
+ name: string | null;
+ /** Whether the holder is currently a member of the project's organization. */
+ is_organization_member: boolean;
+ /** Whether the holder's PostHog user account is active. */
+ is_active: boolean;
+ }
+
+ /**
+ * * `holder_missing` - The active relationship has no user
+ * * `holder_inactive` - The holder's user account is deactivated
+ * * `holder_not_in_organization` - The holder is not a member of the organization
+ * * `multiple_active_holders` - More than one active relationship holds the role
+ */
+ export type OwnershipRoleDiagnosticEnum = typeof OwnershipRoleDiagnosticEnum[keyof typeof OwnershipRoleDiagnosticEnum];
+
+
+ export const OwnershipRoleDiagnosticEnum = {
+ HolderMissing: 'holder_missing',
+ HolderInactive: 'holder_inactive',
+ HolderNotInOrganization: 'holder_not_in_organization',
+ MultipleActiveHolders: 'multiple_active_holders',
+ } as const;
+
+ export interface ExternalAccountRoleOwnership {
+ /** The controlled relationship definition. Map it to the role you project; it does not change. */
+ definition_id: string;
+ /** Current name of the relationship definition. */
+ definition_name: string;
+ /** `unmanaged`: customer analytics does not hold authority over this relationship on this account; the holder, if any, is a legacy assignment. `assigned`: the holder is authoritative. `cleared`: the relationship is authoritatively empty. `blocked`: the relationship is managed but its holder cannot be projected; see `diagnostics` and keep the last applied value.
+ *
+ * * `unmanaged` - Unmanaged
+ * * `assigned` - Assigned
+ * * `cleared` - Cleared
+ * * `blocked` - Blocked */
+ state: OwnershipRoleStateEnum;
+ /**
+ * When customer analytics last decided this relationship on this account; null while unmanaged.
+ * @nullable
+ */
+ controlled_at: string | null;
+ /**
+ * The active relationship holding the role, or null when empty.
+ * @nullable
+ */
+ relationship_id: string | null;
+ /** The current holder, or null. */
+ holder: ExternalAccountOwnershipHolder | null;
+ /** Why a managed relationship is blocked. Informational on an unmanaged one. */
+ diagnostics: OwnershipRoleDiagnosticEnum[];
+ }
+
+ export interface ExternalAccountOwnership {
+ /** Account UUID, the canonical identity within this project. */
+ account_id: string;
+ /**
+ * External account key: the group key the account is linked to.
+ * @nullable
+ */
+ external_id: string | null;
+ /**
+ * Region of this PostHog instance (`us`, `eu`), or null when self-hosted.
+ * @nullable
+ */
+ region: string | null;
+ /** One entry per controlled relationship definition of the project, in name order, whether or not this account is managed under it. Empty when the project controls no relationship. */
+ roles: ExternalAccountRoleOwnership[];
+ }
+
export interface ExternalAccount {
/** Account UUID. */
id: string;
@@ -38485,6 +38609,8 @@ export namespace Schemas {
ignored_at: string | null;
/** Typed account properties: external-system ids. Role assignments live under `relationships`. */
properties: ExternalAccountProperties;
+ /** Authority state of each relationship the project controls. */
+ ownership: ExternalAccountOwnership;
/** Tag names on the account, sorted alphabetically. */
tags: string[];
/** Active relationship assignments keyed by definition name (e.g. 'CSM'). Definitions with no active assignment are omitted. */
@@ -38530,6 +38656,8 @@ export namespace Schemas {
* @nullable
*/
ignored_at: string | null;
+ /** Authority state of each relationship the project controls. */
+ ownership: ExternalAccountOwnership;
/** Active relationship assignments to current organization members, keyed by relationship definition name (e.g. 'CSM', 'Account executive'). Definitions with no active assignment are omitted. */
relationships: ExternalAccountListItemRelationships;
}
@@ -64866,6 +64994,8 @@ export namespace Schemas {
description?: string | null;
/** Whether only one user can hold this relationship per account at a time, e.g. a single CSM per account. */
is_single_holder?: boolean;
+ /** Whether customer analytics can take control of this relationship per account. Rows under a controlled relationship can't be deleted. On an account where control has started, only a person can change the relationship and an empty relationship is a deliberate decision. Set by project operators, not through this API. */
+ readonly is_controlled?: boolean;
}
/**
@@ -97376,6 +97506,10 @@ export namespace Schemas {
* Maximum number of accounts to return. Values below 1 are clamped to 1; values above 100 are clamped to 100.
*/
limit?: number;
+ /**
+ * When true, return only accounts where customer analytics holds authority over at least one controlled relationship, including accounts whose managed relationships are cleared and accounts that are ignored. Authority does not end when an account is ignored, so `include_ignored` is implied.
+ */
+ managed_only?: boolean;
};
export type FeatureFlagsStaffCacheListParams = {
diff --git a/tach.toml b/tach.toml
index 1f8b42569871..394d773c5fe3 100644
--- a/tach.toml
+++ b/tach.toml
@@ -890,6 +890,7 @@ depends_on = [
"posthog",
"products.cdp",
"products.conversations",
+ "products.data_modeling",
"products.data_warehouse",
"products.notebooks",
"products.notifications",