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): enroll accounts on a person's role edit (#105292)

Abhischekc6ba47ebd1e2
diff --git a/products/customer_analytics/backend/logic/ownership.py b/products/customer_analytics/backend/logic/ownership.py
index 4a5e07723346..b1eb55a0855d 100644
--- a/products/customer_analytics/backend/logic/ownership.py
+++ b/products/customer_analytics/backend/logic/ownership.py
@@ -72,9 +72,12 @@ def lock_definition(team_id: int, definition_id: str | UUID) -> AccountRelations
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.
+ Taking control enrolls no account at once. From then on, a person's change to a controlled
+ relationship on a linked account enrolls that account (see ``logic/relationships.py``). Reviewed
+ adoption enrolls accounts in batches. Giving control up is refused while any account is
+ enrolled, because those accounts would fall back to legacy authority at once. It is also refused
+ 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)
diff --git a/products/customer_analytics/backend/logic/relationships.py b/products/customer_analytics/backend/logic/relationships.py
index acb3ba0581c7..b9391990849f 100644
--- a/products/customer_analytics/backend/logic/relationships.py
+++ b/products/customer_analytics/backend/logic/relationships.py
@@ -3,9 +3,12 @@ Assign/end transactions for account relationships: the one write path for every
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.
+the same transaction, so a mutation without an audit record cannot commit. A person's change to a
+controlled relationship on a linked account first enrolls the account under every controlled
+definition. Accounts thus reach managed ownership without a manual adoption run. That enrollment
+locks definitions before the account. A caller that already holds either lock must therefore not
+pass a person as the actor. The Salesforce claim procedure in ``logic/ownership_claims.py`` writes
+through the public helpers here under the same lock and audit rules.
"""
import dataclasses
@@ -99,8 +102,11 @@ def assign(
) -> 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."""
+ the current holder again records no change and leaves the fence where it is. When a person does
+ this to a controlled relationship on a linked account that is not fully enrolled, the call
+ enrolls the account."""
with transaction.atomic():
+ _enroll_on_human_edit(team_id, account.id, definition.id, actor)
locked_account = _lock_or_raise(team_id, account.id)
control = ownership.control_for(locked_account, definition)
_enforce_managed_role_policy(control, actor)
@@ -154,6 +160,7 @@ def end_active(
and the confirmation is recorded, so a later automated claim cannot treat it as never reviewed.
"""
with transaction.atomic():
+ _enroll_on_human_edit(team_id, account.id, definition.id, actor)
locked_account = _lock_or_raise(team_id, account.id)
control = ownership.control_for(locked_account, definition)
_enforce_managed_role_policy(control, actor)
@@ -200,6 +207,14 @@ def end_relationship(
emit_event: bool = True,
) -> AccountRelationship:
with transaction.atomic():
+ definition_id = (
+ AccountRelationship.objects.for_team(team_id)
+ .filter(id=relationship_id, account_id=account_id, ended_at__isnull=True)
+ .values_list("definition_id", flat=True)
+ .first()
+ )
+ if definition_id is not None:
+ _enroll_on_human_edit(team_id, account_id, definition_id, actor)
locked_account = _lock_or_raise(team_id, account_id, missing_id=relationship_id)
relationship = (
AccountRelationship.objects.for_team(team_id)
@@ -300,24 +315,75 @@ def enroll(
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 _enroll_locked(team_id, locked_account, locked_definition, actor)
+
+
+def _enroll_on_human_edit(team_id: int, account_id: str | UUID, definition_id: UUID, actor: Actor) -> None:
+ """Before a person changes one of the account's controlled relationships, enroll the account
+ under every controlled definition it lacks.
+
+ Every controlled definition is enrolled, not only the edited one, because a consumer takes over
+ an account only once all its controlled relationships are managed. An account without an
+ ``external_id`` stays unenrolled, as reviewed adoption leaves it. No consumer can find such an
+ account, and enrolling it would add a managed account whose identity changes when it is linked.
+
+ Call inside the mutation's transaction, before the mutation locks the account. The definitions
+ are locked first, in id order, the order every writer takes. The first checks take no lock. An
+ edit by another writer, an edit of an uncontrolled relationship, and an edit on a fully enrolled
+ account stop there. The controlled check repeats under the definition locks, because a
+ definition can stop being controlled between the two reads. The link is read only under the
+ account lock, so an edit that races the linking of its account still sees the link. An edit on
+ an unlinked account therefore takes the definition locks before it stops. A definition that
+ becomes controlled after the first read is not enrolled here. The next edit by a person enrolls
+ it.
+ """
+ if actor.source != AccountRelationshipSource.HUMAN:
+ return
+ controlled_ids = set(ownership.controlled_definitions(team_id).values_list("id", flat=True))
+ if definition_id not in controlled_ids:
+ return
+ enrolled_ids = set(
+ AccountRelationshipControl.objects.for_team(team_id)
+ .filter(account_id=account_id)
+ .values_list("definition_id", flat=True)
+ )
+ if controlled_ids <= enrolled_ids:
+ return
+
+ definitions = [
+ definition for definition in ownership.lock_definitions(team_id, controlled_ids) if definition.is_controlled
+ ]
+ if definition_id not in {definition.id for definition in definitions}:
+ return
+ account = lock_account(team_id, account_id)
+ if account is None or not account.external_id:
+ return
+ for definition in definitions:
+ _enroll_locked(team_id, account, definition, actor)
+
+
+def _enroll_locked(
+ team_id: int, account: Account, definition: AccountRelationshipDefinition, actor: Actor
+) -> AccountRelationshipControl:
+ """Enroll under the definition and Account locks the caller holds."""
+ control = ownership.control_for(account, definition)
+ if control is not None:
return control
+ holder = active_relationships(team_id, account, definition).first()
+ holder_user = holder.user if holder is not None else None
+ control = ownership.enroll(account, definition, actor.user)
+ record_transition(
+ account=account,
+ actor=actor,
+ activity="role_enrolled",
+ definition=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:
diff --git a/products/customer_analytics/backend/management/commands/configure_account_ownership.py b/products/customer_analytics/backend/management/commands/configure_account_ownership.py
index dae1c3bf7af9..ed1a6e1ad8eb 100644
--- a/products/customer_analytics/backend/management/commands/configure_account_ownership.py
+++ b/products/customer_analytics/backend/management/commands/configure_account_ownership.py
@@ -1,6 +1,8 @@
"""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``).
+external decisions fills each of them. Taking control of a definition enrolls no account at once.
+From then on, a person's change to a controlled relationship on a linked account enrolls that
+account under every controlled definition. ``adopt_account_ownership`` enrolls accounts in reviewed
+batches. No path unenrolls an account, so control cannot end after the first enrollment.
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> \\
@@ -31,7 +33,11 @@ class Command(BaseCommand):
action="append",
default=[],
metavar="DEFINITION_ID",
- help="Let customer analytics take control of this single-holder definition per account. Repeatable.",
+ help=(
+ "Let customer analytics take control of this single-holder definition per account. A person's "
+ "change to a controlled relationship on a linked account then enrolls that account under every "
+ "controlled definition. --uncontrol is refused once any account is enrolled. Repeatable."
+ ),
)
parser.add_argument(
"--uncontrol",
diff --git a/products/customer_analytics/backend/test/test_account_ownership_commands.py b/products/customer_analytics/backend/test/test_account_ownership_commands.py
index 9840af092a34..4d0087ae92f3 100644
--- a/products/customer_analytics/backend/test/test_account_ownership_commands.py
+++ b/products/customer_analytics/backend/test/test_account_ownership_commands.py
@@ -183,12 +183,14 @@ class TestAdoptAccountOwnershipCommand(BaseTest):
self.manifest_path = Path(directory) / "manifest.json"
def _assign(self, account: Account, user: User) -> None:
+ # A person's edit would enroll the linked account, so the state a manifest reviews comes
+ # from an autonomous writer.
relationships.assign(
team_id=self.team.id,
account=account,
definition=self.ae_definition,
user=user,
- actor=relationships.Actor.human(self.user),
+ actor=relationships.Actor(source=AccountRelationshipSource.WORKFLOW),
)
def _fingerprints(self) -> dict[str, str]:
diff --git a/products/customer_analytics/backend/test/test_relationships.py b/products/customer_analytics/backend/test/test_relationships.py
index c48b6691098e..f012a5998739 100644
--- a/products/customer_analytics/backend/test/test_relationships.py
+++ b/products/customer_analytics/backend/test/test_relationships.py
@@ -1,4 +1,6 @@
from datetime import datetime, timedelta
+from typing import Any
+from uuid import UUID
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -15,14 +17,19 @@ 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.logic import ownership, relationships
from products.customer_analytics.backend.models import (
Account,
AccountRelationship,
AccountRelationshipControl,
AccountRelationshipDefinition,
)
-from products.customer_analytics.backend.test.factories import create_account, enroll_account
+from products.customer_analytics.backend.test.factories import (
+ create_account,
+ create_account_relationship,
+ create_account_relationship_definition,
+ enroll_account,
+)
class TestRelationshipLogic(BaseTest):
@@ -373,26 +380,45 @@ class TestExternalRelationshipAssignments(BaseTest):
class TestControlledRelationshipPolicy(BaseTest):
def setUp(self):
super().setUp()
+ # Without an external_id a person's edit does not enroll the account, so each test decides
+ # when enrollment happens.
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(
+ self.ae_definition = create_account_relationship_definition(
team_id=self.team.id, name="Account executive", is_controlled=True
)
self.human = relationships.Actor.human(self.user)
+ def _linked_account(self) -> Account:
+ return create_account(team_id=self.team.pk, name="Linked", external_id="org-linked")
+
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:
+ def _fence(
+ self, definition: AccountRelationshipDefinition | None = None, account: Account | None = None
+ ) -> datetime | None:
return (
AccountRelationshipControl.objects.for_team(self.team.id)
- .filter(account=self.account, definition=definition or self.ae_definition)
+ .filter(account=account or self.account, definition=definition or self.ae_definition)
.values_list("controlled_at", flat=True)
.first()
)
+ def _enrolled_definition_ids(self, account: Account) -> set[UUID]:
+ return set(
+ AccountRelationshipControl.objects.for_team(self.team.id)
+ .filter(account=account)
+ .values_list("definition_id", flat=True)
+ )
+
+ @staticmethod
+ def _context(row: ActivityLog) -> dict[str, Any]:
+ assert row.detail is not None
+ return row.detail["context"]
+
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
@@ -426,21 +452,154 @@ class TestControlledRelationshipPolicy(BaseTest):
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")
+ @parameterized.expand([source for source in AccountRelationshipSource if source != AccountRelationshipSource.HUMAN])
+ def test_autonomous_writer_may_fill_an_unmanaged_controlled_relationship_without_taking_authority(self, source):
+ account = self._linked_account()
+ create_account_relationship_definition(team_id=self.team.id, name="CSM", is_controlled=True)
+
+ rel = relationships.assign(
+ team_id=self.team.id,
+ account=account,
+ definition=self.ae_definition,
+ user=self.user,
+ actor=relationships.Actor(source=source, workflow_id="wf-1"),
)
- assert rel.source == AccountRelationshipSource.WORKFLOW
- assert self._fence() is None
+ assert rel.source == source
+ assert self._enrolled_definition_ids(account) == set()
(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
+ context = self._context(row)
+ assert context["source"] == source
+ assert context["workflow_id"] == "wf-1"
+ assert context["definition_id"] == str(self.ae_definition.id)
+ assert context["controlled_at"] is None
+
+ @parameterized.expand(["assign", "end_active", "end_relationship"])
+ def test_human_edit_enrolls_a_linked_account_under_every_controlled_definition(self, operation):
+ account = self._linked_account()
+ csm_definition = create_account_relationship_definition(team_id=self.team.id, name="CSM", is_controlled=True)
+ create_account_relationship_definition(
+ team_id=self.team.id, name="Technical account manager", is_controlled=True
+ )
+ ae_row = create_account_relationship(
+ team_id=self.team.id, account=account, definition=self.ae_definition, user=self.other_user
+ )
+ create_account_relationship(team_id=self.team.id, account=account, definition=csm_definition, user=self.user)
+
+ if operation == "assign":
+ relationships.assign(
+ team_id=self.team.id, account=account, definition=self.ae_definition, user=self.user, actor=self.human
+ )
+ elif operation == "end_active":
+ relationships.end_active(
+ team_id=self.team.id, account=account, definition=self.ae_definition, actor=self.human
+ )
+ else:
+ relationships.end_relationship(
+ team_id=self.team.id, account_id=account.id, relationship_id=str(ae_row.id), actor=self.human
+ )
+
+ roles = {
+ role.definition_name: (role.state, role.holder.user_id if role.holder else None)
+ for role in ownership.ownership_for_account(account).roles
+ }
+ assert roles == {
+ "Account executive": ("assigned", self.user.id) if operation == "assign" else ("cleared", None),
+ "CSM": ("assigned", self.user.id),
+ "Technical account manager": ("cleared", None),
+ }
+ rows = self._activity_rows()
+ change = "relationship_assigned" if operation == "assign" else "relationship_ended"
+ assert [row.activity for row in rows] == ["role_enrolled", "role_enrolled", "role_enrolled", change]
+ assert {row.user_id for row in rows} == {self.user.id}
+ enrolled_at = {self._context(row)["definition_name"]: self._context(row)["controlled_at"] for row in rows[:3]}
+ fence = self._fence(account=account)
+ assert fence is not None and fence > datetime.fromisoformat(enrolled_at["Account executive"])
+
+ @parameterized.expand(["uncontrolled_relationship", "unlinked_account"])
+ def test_human_edit_of_an_uncontrolled_relationship_or_an_unlinked_account_enrolls_nothing(self, case):
+ create_account_relationship_definition(team_id=self.team.id, name="CSM", is_controlled=True)
+ if case == "uncontrolled_relationship":
+ account = self._linked_account()
+ definition = create_account_relationship_definition(team_id=self.team.id, name="Buddy")
+ else:
+ account, definition = self.account, self.ae_definition
+
+ relationships.assign(
+ team_id=self.team.id, account=account, definition=definition, user=self.user, actor=self.human
+ )
+
+ assert self._enrolled_definition_ids(account) == set()
+
+ def test_human_edit_on_a_partly_enrolled_account_enrolls_only_the_missing_definitions(self):
+ account = self._linked_account()
+ csm_definition = create_account_relationship_definition(team_id=self.team.id, name="CSM", is_controlled=True)
+ enroll_account(account, self.ae_definition, controlled_at=timezone.now() - timedelta(days=1))
+
+ relationships.assign(
+ team_id=self.team.id, account=account, definition=self.ae_definition, user=self.user, actor=self.human
+ )
+
+ assert self._enrolled_definition_ids(account) == {self.ae_definition.id, csm_definition.id}
+ assert [(row.activity, self._context(row)["definition_name"]) for row in self._activity_rows()] == [
+ ("role_enrolled", "CSM"),
+ ("relationship_assigned", "Account executive"),
+ ]
+
+ def test_human_reassigning_the_current_holder_still_enrolls_a_linked_account(self):
+ account = self._linked_account()
+ create_account_relationship(
+ team_id=self.team.id, account=account, definition=self.ae_definition, user=self.user
+ )
+
+ relationships.assign(
+ team_id=self.team.id, account=account, definition=self.ae_definition, user=self.user, actor=self.human
+ )
+
+ assert self._enrolled_definition_ids(account) == {self.ae_definition.id}
+ assert [row.activity for row in self._activity_rows()] == ["role_enrolled"]
+
+ def test_human_edit_that_fails_rolls_back_its_enrollment(self):
+ account = self._linked_account()
+ create_account_relationship(
+ team_id=self.team.id, account=account, definition=self.ae_definition, user=self.other_user
+ )
+
+ with self.assertRaises(relationships.RelationshipOccupiedError):
+ relationships.assign(
+ team_id=self.team.id,
+ account=account,
+ definition=self.ae_definition,
+ user=self.user,
+ actor=self.human,
+ replace_active=False,
+ )
+
+ assert self._enrolled_definition_ids(account) == set()
+ assert self._activity_rows() == []
+
+ @parameterized.expand(["edited", "sibling"])
+ def test_definition_uncontrolled_after_the_unlocked_read_is_not_enrolled(self, uncontrolled):
+ account = self._linked_account()
+ csm_definition = create_account_relationship_definition(team_id=self.team.id, name="CSM", is_controlled=True)
+ both_definitions = AccountRelationshipDefinition.objects.for_team(self.team.id).filter(
+ id__in=[self.ae_definition.id, csm_definition.id]
+ )
+ stopped = self.ae_definition if uncontrolled == "edited" else csm_definition
+ ownership.set_controlled(self.team.id, stopped.id, False)
+
+ # The unlocked read still sees both definitions as controlled, as it would when a concurrent
+ # --uncontrol commits between that read and the definition locks.
+ with patch.object(ownership, "controlled_definitions", return_value=both_definitions):
+ relationships.assign(
+ team_id=self.team.id, account=account, definition=self.ae_definition, user=self.user, actor=self.human
+ )
+
+ assert self._enrolled_definition_ids(account) == (
+ set() if uncontrolled == "edited" else {self.ae_definition.id}
+ )
@parameterized.expand(["assign", "end_active", "confirm_empty", "end_relationship"])
def test_human_decision_on_a_managed_relationship_advances_the_fence(self, operation):
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 1e4aa8bc4a14..1b49f1ea4eaf 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; 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)
+ ├── (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; a person's assign or unassign under a controlled definition enrolls a linked account under every controlled definition, so a bulk or automatic write from this UI would enroll accounts in bulk)
├── (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)