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 accepted salesforce claims (#106047)

Abhischek856142cbdabe
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 6c37f20e7f9f..7696646a7710 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -623,7 +623,6 @@ OwnershipClaimOutcome = Literal["accepted", "already_applied", "cleared", "not_h
OwnershipClaimReason = Literal[
"account_not_found",
"binding_changed",
- "role_not_managed",
"identity_mismatch",
"assignee_not_member",
"role_occupied",
@@ -658,8 +657,8 @@ class OwnershipClaimDecision:
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."""
+ read. Refusals are not stored, so every sweep evaluates the Task again, and a refusal turns into an
+ acceptance once its cause is gone."""
outcome: OwnershipClaimOutcome
reason: OwnershipClaimReason | None
diff --git a/products/customer_analytics/backend/logic/ownership.py b/products/customer_analytics/backend/logic/ownership.py
index b1eb55a0855d..7602bf2bbb24 100644
--- a/products/customer_analytics/backend/logic/ownership.py
+++ b/products/customer_analytics/backend/logic/ownership.py
@@ -73,11 +73,11 @@ def set_controlled(team_id: int, definition_id: UUID, controlled: bool) -> Accou
"""Let customer analytics take control of the definition per account, or stop it.
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.
+ relationship on a linked account enrolls that account (see ``logic/relationships.py``), and so
+ does an accepted Salesforce claim (see ``logic/ownership_claims.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)
@@ -115,16 +115,19 @@ def control_for(account: Account, definition: AccountRelationshipDefinition) ->
def enroll(
- account: Account, definition: AccountRelationshipDefinition, created_by: User | None
+ account: Account,
+ definition: AccountRelationshipDefinition,
+ created_by: User | None,
+ controlled_at: datetime | None = None,
) -> AccountRelationshipControl:
- """Create the control row, timed by the database clock like every later advance. Call under the
- definition and Account locks."""
+ """Create the control row, timed by the database clock like every later advance unless the caller
+ names the instant control starts from. 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(),
+ controlled_at=controlled_at if controlled_at is not None else Now(),
)
control.refresh_from_db(fields=["controlled_at"])
return control
@@ -258,13 +261,6 @@ def canonical_digest(payload: dict) -> str:
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;
diff --git a/products/customer_analytics/backend/logic/ownership_claims.py b/products/customer_analytics/backend/logic/ownership_claims.py
index 09613267579f..2902d034c405 100644
--- a/products/customer_analytics/backend/logic/ownership_claims.py
+++ b/products/customer_analytics/backend/logic/ownership_claims.py
@@ -8,7 +8,7 @@ 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``).
+- ``region``: the PostHog cloud 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.
@@ -90,6 +90,14 @@ DECISION_COLUMNS = (
"source_releaser_id",
)
+# One project's accounts include organizations hosted in either cloud, so a claim may name either
+# region, whichever instance runs the sweep.
+CLOUD_REGIONS = frozenset({"us", "eu"})
+
+# The fence of a relationship a claim enrolls without deciding it, when no writer ever changed it.
+# No earlier decision exists to protect, so any claim for it can pass.
+NO_PRIOR_CHANGE = datetime(1970, 1, 1, tzinfo=UTC)
+
class ClaimSourceMisconfigured(Exception):
"""The claim binding cannot be made or used: no such definition or view, a definition that is not
@@ -217,12 +225,11 @@ def _refuse_saved_queries(view_name: str, context: HogQLContext) -> None:
)
-def _binding_changed(team_id: int, definition: AccountRelationshipDefinition) -> bool:
- """Lock the definition and tell whether its binding moved after the sweep read the view: to another
- definition, to a newly pinned text, or with claims switched off. Rows read under the old binding
- must not apply, and a claim under the old definition would leave the Task unable to fill the new
- one. Call inside ``transaction.atomic()``, before locking the account."""
- current = ownership.lock_definition(team_id, definition.id)
+def _binding_changed(current: AccountRelationshipDefinition | None, definition: AccountRelationshipDefinition) -> bool:
+ """Whether the binding moved after the sweep read the view: to another definition, to a newly
+ pinned text, or with claims switched off. Rows read under the old binding must not apply, and a
+ claim under the old definition would leave the Task unable to fill the new one. ``current`` is the
+ definition read under its lock, or None when it is gone or no longer controlled."""
return (
current is None
or not current.claims_enabled
@@ -535,20 +542,33 @@ def claim(
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.
+ changed hands. A new Task may fill the relationship only when it is empty, the assignee is a
+ member, the region is a cloud region, and the allocation is later than the control timestamp,
+ the last human decision, by more than the clock-skew allowance. On an account not yet enrolled
+ under the definition, the fence is the relationship's last change by any writer. An accepted claim
+ enrolls the account under every controlled definition it lacks, as a person's edit does, because a
+ consumer takes over an account only once all its controlled relationships are managed. Control of
+ the claimed relationship starts at the claim's allocation time; a sibling's starts at its own last
+ change. A refusal enrolls nothing, because enrollment hands the account to consumers for good.
+ Every refusal is returned as an outcome for the reconciler to record.
+
+ A claim or a release never moves an existing 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.
- if _binding_changed(team.id, definition):
+ # Definitions before the account, in id order, the order every writer takes. Every
+ # controlled definition is locked because an accepted claim may enroll the account under
+ # all of them. The view was read before this transaction, so the binding is checked again.
+ controlled_ids = set(ownership.controlled_definitions(team.id).values_list("id", flat=True))
+ controlled = {
+ locked_definition.id: locked_definition
+ for locked_definition in ownership.lock_definitions(team.id, controlled_ids | {definition.id})
+ if locked_definition.is_controlled
+ }
+ current = controlled.get(definition.id)
+ if current is None or _binding_changed(current, definition):
return _claim_result("blocked", "binding_changed")
try:
locked_account = _lock_account_by_external_id(team.id, decision.organization_id)
@@ -562,10 +582,7 @@ def claim(
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):
+ if decision.region not in CLOUD_REGIONS:
return _claim_result("blocked", "identity_mismatch")
membership = (
OrganizationMembership.objects.select_related("user")
@@ -575,18 +592,36 @@ def claim(
if membership is None:
return _claim_result("blocked", "assignee_not_member")
- holder = relationships.active_relationships(team.id, locked_account, definition).first()
+ holder = relationships.active_relationships(team.id, locked_account, current).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)
+ control = ownership.control_for(locked_account, current)
+ rejection = ownership.allocation_rejection(
+ decision.allocated_at,
+ control.controlled_at
+ if control is not None
+ else relationships.last_change_at(team.id, locked_account, current),
+ )
if rejection is not None:
return _claim_result("rejected", rejection)
+ controls = {
+ definition_id: relationships.enroll_locked(
+ team.id,
+ locked_account,
+ controlled_definition,
+ actor,
+ controlled_at=decision.allocated_at
+ if definition_id == current.id
+ else relationships.last_change_at(team.id, locked_account, controlled_definition) or NO_PRIOR_CHANGE,
+ )
+ for definition_id, controlled_definition in controlled.items()
+ }
+ fence = controls[current.id].controlled_at
relationship = AccountRelationship.objects.for_team(team.id).create(
team_id=team.id,
account=locked_account,
- definition=definition,
+ definition=current,
user=membership.user,
source=actor.source,
source_ref=decision.source_ref,
@@ -595,7 +630,7 @@ def claim(
account=locked_account,
actor=actor,
activity="role_claimed",
- definition=definition,
+ definition=current,
relationship=relationship,
previous_user=None,
current_user=membership.user,
@@ -622,7 +657,7 @@ def release(
return _claim_result("not_held", None)
with transaction.atomic():
# Definition before account, and the binding checked again, as for a claim.
- if _binding_changed(team.id, definition):
+ if _binding_changed(ownership.lock_definition(team.id, definition.id), definition):
return _claim_result("blocked", "binding_changed")
# 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
diff --git a/products/customer_analytics/backend/logic/relationships.py b/products/customer_analytics/backend/logic/relationships.py
index b9391990849f..5f859ac5014e 100644
--- a/products/customer_analytics/backend/logic/relationships.py
+++ b/products/customer_analytics/backend/logic/relationships.py
@@ -5,10 +5,11 @@ Account row, applies the controlled-relationship policy, advances the control ti
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. 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.
+definition. The enrollment for a person's edit locks definitions before the account, so a caller
+that already holds either lock must not pass a person as the actor. An accepted Salesforce claim
+enrolls the account in the same way, under locks the claim procedure in
+``logic/ownership_claims.py`` takes itself, and writes through the public helpers here under the
+same lock and audit rules. Accounts thus reach managed ownership without a manual adoption run.
"""
import dataclasses
@@ -16,7 +17,7 @@ from datetime import datetime
from uuid import UUID
from django.db import transaction
-from django.db.models import QuerySet
+from django.db.models import Max, QuerySet
from django.db.models.signals import post_save
from django.utils import timezone
@@ -315,7 +316,7 @@ 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)
- return _enroll_locked(team_id, locked_account, locked_definition, actor)
+ 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:
@@ -359,19 +360,24 @@ def _enroll_on_human_edit(team_id: int, account_id: str | UUID, definition_id: U
if account is None or not account.external_id:
return
for definition in definitions:
- _enroll_locked(team_id, account, definition, actor)
+ enroll_locked(team_id, account, definition, actor)
-def _enroll_locked(
- team_id: int, account: Account, definition: AccountRelationshipDefinition, actor: Actor
+def enroll_locked(
+ team_id: int,
+ account: Account,
+ definition: AccountRelationshipDefinition,
+ actor: Actor,
+ controlled_at: datetime | None = None,
) -> AccountRelationshipControl:
- """Enroll under the definition and Account locks the caller holds."""
+ """Enroll under the definition and Account locks the caller holds. ``controlled_at`` is the
+ instant control starts from when it is not the database clock's now."""
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)
+ control = ownership.enroll(account, definition, actor.user, controlled_at)
record_transition(
account=account,
actor=actor,
@@ -458,6 +464,17 @@ def active_relationships(
)
+def last_change_at(team_id: int, account: Account, definition: AccountRelationshipDefinition) -> datetime | None:
+ """When any writer last assigned or ended the relationship on the account, or None when it never
+ had one."""
+ latest = (
+ AccountRelationship.objects.for_team(team_id)
+ .filter(account=account, definition=definition)
+ .aggregate(started=Max("started_at"), ended=Max("ended_at"))
+ )
+ return max((value for value in latest.values() if value is not None), default=None)
+
+
def _enforce_managed_role_policy(control: AccountRelationshipControl | None, actor: Actor) -> None:
"""Only a person may change a relationship the account manages.
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 4af924ab2dfe..8cd68fb5faec 100644
--- a/products/customer_analytics/backend/management/commands/configure_account_ownership.py
+++ b/products/customer_analytics/backend/management/commands/configure_account_ownership.py
@@ -1,8 +1,9 @@
"""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 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.
+From then on, a person's change to a controlled relationship on a linked account, or an accepted
+Salesforce claim on it, 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.
Binding a claim view pins its SQL, switches its claims off and prints the SHA-256 of that text.
Enable claims in a separate call, after checking that the digest matches the SQL you reviewed, for
@@ -41,8 +42,9 @@ class Command(BaseCommand):
metavar="DEFINITION_ID",
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."
+ "change to a controlled relationship on a linked account, or an accepted Salesforce claim on it, "
+ "then enrolls that account under every controlled definition. --uncontrol is refused once any "
+ "account is enrolled. Repeatable."
),
)
parser.add_argument(
diff --git a/products/customer_analytics/backend/models/relationship.py b/products/customer_analytics/backend/models/relationship.py
index 793b67185be2..0af64cdffb40 100644
--- a/products/customer_analytics/backend/models/relationship.py
+++ b/products/customer_analytics/backend/models/relationship.py
@@ -110,9 +110,10 @@ class AccountRelationshipControl(TeamScopedRootMixin, UUIDModel, CreatedMetaFiel
"""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.
+ the relationship rows say. ``controlled_at`` is the last decision a person took on the relationship
+ here or, before any, the start of control: the enrollment, the allocation time of the Salesforce
+ claim that enrolled the account, or for a sibling that claim enrolled, the sibling's own last change.
+ 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="+")
diff --git a/products/customer_analytics/backend/test/test_ownership_claims.py b/products/customer_analytics/backend/test/test_ownership_claims.py
index 65d5f02866c2..3c3db743ce77 100644
--- a/products/customer_analytics/backend/test/test_ownership_claims.py
+++ b/products/customer_analytics/backend/test/test_ownership_claims.py
@@ -30,7 +30,8 @@ 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.facade.enums import AccountRelationshipSource
+from products.customer_analytics.backend.logic import ownership, ownership_claims, relationships
from products.customer_analytics.backend.logic.ownership_claims import DECISION_COLUMNS
from products.customer_analytics.backend.models import (
AccountRelationship,
@@ -51,6 +52,7 @@ from products.customer_analytics.backend.temporal.ownership_claims import (
)
from products.customer_analytics.backend.test.factories import (
create_account,
+ create_account_relationship_definition,
create_saved_query,
enroll_account,
saved_query_columns,
@@ -58,6 +60,7 @@ from products.customer_analytics.backend.test.factories import (
FENCE = datetime(2026, 1, 1, tzinfo=UTC)
TASK = "example-salesforce-task-17"
+WORKFLOW = relationships.Actor(source=AccountRelationshipSource.WORKFLOW, workflow_id="example-workflow")
class TestOwnershipClaims(BaseTest):
@@ -133,6 +136,13 @@ class TestOwnershipClaims(BaseTest):
.first()
)
+ def _controls(self) -> dict[str, datetime]:
+ return dict(
+ AccountRelationshipControl.objects.for_team(self.team.id)
+ .filter(account=self.account)
+ .values_list("definition__name", "controlled_at")
+ )
+
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
@@ -176,16 +186,22 @@ class TestOwnershipClaims(BaseTest):
("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"),
+ ("unknown_region", "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),
+ ("the_other_cloud_region", "accepted", None),
+ ("unenrolled_and_occupied", "rejected", "role_occupied"),
+ ("unenrolled_and_allocated_in_the_future", "rejected", "future_allocation"),
+ ("unenrolled_and_allocated_before_a_clear_made_while_unlinked", "rejected", "stale_allocation"),
]
)
def test_claim_decision_outcome(self, case, outcome, reason):
overrides: dict[str, Any] = {}
+ if case.startswith("unenrolled"):
+ self.control.delete()
+ create_account_relationship_definition(team_id=self.team.id, name="CSM", is_controlled=True)
if case == "occupied_by_another_user":
self._assign_by_human(self._create_user("[email protected]"))
elif case == "occupied_by_the_same_user":
@@ -194,23 +210,38 @@ class TestOwnershipClaims(BaseTest):
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":
+ elif case == "unenrolled_and_occupied":
+ relationships.assign(
+ team_id=self.team.id,
+ account=self.account,
+ definition=self.ae_definition,
+ user=self._create_user("[email protected]"),
+ actor=WORKFLOW,
+ )
+ elif case == "unenrolled_and_allocated_before_a_clear_made_while_unlinked":
+ self.account.external_id = None
+ self.account.save(update_fields=["external_id"])
+ self._assign_by_human(self._create_user("[email protected]"))
+ self._clear_by_human()
+ self.account.external_id = "org-1"
+ self.account.save(update_fields=["external_id"])
+ elif case in ("allocated_in_the_future", "unenrolled_and_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":
+ elif case == "unknown_region":
+ overrides["region"] = "apac"
+ elif case == "the_other_cloud_region":
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()
+ controls_before = self._controls()
with override_settings(CLOUD_DEPLOYMENT="US"):
result = self._claim(**overrides)
@@ -219,9 +250,75 @@ class TestOwnershipClaims(BaseTest):
if outcome == "accepted":
return
assert self._active_ae() == holder_before
- assert self._fence() == fence_before
+ assert self._controls() == controls_before
+ assert not ActivityLog.objects.filter(team_id=self.team.id, activity="role_enrolled").exists()
assert not AccountRelationship.objects.for_team(self.team.id).filter(source="salesforce_claim").exists()
+ @parameterized.expand([("unenrolled", {"Account executive", "CSM"}), ("enrolled_under_ae_only", {"CSM"})])
+ def test_an_accepted_claim_enrolls_every_controlled_definition_the_account_lacks(
+ self, case: str, newly_enrolled: set[str]
+ ) -> None:
+ if case == "unenrolled":
+ self.control.delete()
+ 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="Buddy")
+ csm = self._create_user("[email protected]")
+ relationships.assign(
+ team_id=self.team.id, account=self.account, definition=csm_definition, user=csm, actor=WORKFLOW
+ )
+
+ result = self._claim()
+
+ assert result.outcome == "accepted"
+ controls = self._controls()
+ csm_row = AccountRelationship.objects.for_team(self.team.id).get(
+ account=self.account, definition=csm_definition
+ )
+ assert controls == {
+ "Account executive": FENCE if case == "enrolled_under_ae_only" else self._decision().allocated_at,
+ "CSM": csm_row.started_at,
+ }
+ assert result.controlled_at == controls["Account executive"]
+ rows = ActivityLog.objects.filter(team_id=self.team.id, activity__in=["role_enrolled", "role_claimed"])
+ contexts = {
+ (row.activity, row.detail["context"]["definition_name"]): (row.user_id, row.detail["context"])
+ for row in rows
+ if row.detail
+ }
+ assert set(contexts) == {("role_enrolled", name) for name in newly_enrolled} | {
+ ("role_claimed", "Account executive")
+ }
+ assert {(user_id, context["source"]) for user_id, context in contexts.values()} == {(None, "salesforce_claim")}
+ claimed = contexts[("role_claimed", "Account executive")][1]
+ assert datetime.fromisoformat(claimed["controlled_at"]) == controls["Account executive"]
+ roles = {
+ role.definition_name: (role.state, role.holder.user_id if role.holder else None)
+ for role in ownership.ownership_for_account(self.account).roles
+ }
+ assert roles == {"Account executive": ("assigned", self.user.id), "CSM": ("assigned", csm.id)}
+
+ def test_a_task_allocated_before_the_sweep_claims_an_unenrolled_account_after_an_earlier_release(self) -> None:
+ self.control.delete()
+ first = self._claim()
+ self._release_claim()
+
+ second = self._claim(source_ref="example-salesforce-task-18", allocated_at=datetime(2026, 1, 2, 1, tzinfo=UTC))
+
+ assert (first.outcome, second.outcome) == ("accepted", "accepted")
+ holder = self._active_ae()
+ assert holder is not None and holder.source_ref == "example-salesforce-task-18"
+
+ def test_a_sibling_task_allocated_before_an_enrolling_claim_still_claims_the_sibling(self) -> None:
+ self.control.delete()
+ csm_definition, _ = self._claim_bound_definition("CSM", "csm_decisions")
+
+ ae = self._claim(allocated_at=datetime(2026, 1, 2, 1, tzinfo=UTC))
+ csm = ownership_claims.claim(
+ team=self.team, definition=csm_definition, decision=self._decision(source_ref="example-salesforce-task-18")
+ )
+
+ assert (ae.outcome, csm.outcome) == ("accepted", "accepted")
+
def test_release_ends_only_the_relationship_the_task_claimed(self):
claimed = self._claim()
fence_after_claim = self._fence()