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.

fix(customer-analytics): serialize custom property writes (#113510)

Arthur Moreira de Deusce2c4ca655b1
diff --git a/docs/internal/customer-analytics/account-sidebar.md b/docs/internal/customer-analytics/account-sidebar.md
index a6109eab3b9f..c4d425dd0f43 100644
--- a/docs/internal/customer-analytics/account-sidebar.md
+++ b/docs/internal/customer-analytics/account-sidebar.md
@@ -47,6 +47,11 @@ null for that property. The sidebar then displays "Not set". The clear preserves
and emits a property-change event. Repeated nulls do not emit another change event.
Missing source rows or columns leave saved values unchanged.
+Sets and clears for the same account and custom property share a PostgreSQL transaction lock,
+including when no active value exists. Sync checks for unchanged values use the same lock.
+The lock lasts until the outer transaction commits or rolls back. Different account/property keys remain independent.
+Bulk syncs commit each property separately. This prevents write collisions, but does not coalesce sync jobs or order source snapshots by freshness.
+
Relationship editors support single and multiple holders. Removing a holder ends the
assignment without deleting its history. Multi-holder changes retain unchanged holders.
Relationship saves apply the edits relative to the assignments shown when editing began.
diff --git a/products/customer_analytics/backend/logic/custom_property_values.py b/products/customer_analytics/backend/logic/custom_property_values.py
index e787a8f2c721..8cc1091acdd8 100644
--- a/products/customer_analytics/backend/logic/custom_property_values.py
+++ b/products/customer_analytics/backend/logic/custom_property_values.py
@@ -6,17 +6,19 @@ Called by facade/api.py. Do not call from outside this module.
"""
import math
-from collections.abc import Callable
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
from datetime import UTC, date, datetime, timedelta
from typing import Any
from uuid import UUID
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
-from django.db import IntegrityError, transaction
+from django.db import IntegrityError, connections, router, transaction
from django.utils import timezone
from posthog.exceptions_capture import capture_exception
+from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.models.user import User
from products.customer_analytics.backend.events import emit_account_custom_property_changed
@@ -65,6 +67,25 @@ class CustomPropertyValueConflict(Exception):
"""
+@contextmanager
+def _guard_value(*, team_id: int, account_id: str | UUID, definition_id: str | UUID) -> Iterator[str]:
+ using = router.db_for_write(CustomPropertyValue)
+ canonical_team_id = resolve_effective_team_id(team_id)
+ key = f"account-custom-property:{canonical_team_id}:{UUID(str(account_id))}:{UUID(str(definition_id))}"
+ with transaction.atomic(using=using):
+ with connections[using].cursor() as cursor:
+ # Row locks cannot protect a value that is absent or has been replaced.
+ cursor.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", [key])
+ yield using
+
+
+def _parse_definition_id(identifier: str) -> UUID:
+ try:
+ return UUID(identifier)
+ except ValueError as exc:
+ raise CustomPropertyDefinitionNotFound(identifier) from exc
+
+
def set_custom_property_value(
*,
team_id: int,
@@ -122,7 +143,9 @@ def set_account_custom_properties_by_id(
"""
_assert_account_in_team(team_id=team_id, account_id=account_id)
rows: list[CustomPropertyValue] = []
- for definition_id, value in properties.items():
+ # Outer batch transactions retain these locks until commit, so use a consistent order.
+ for definition_id in sorted(properties, key=_parse_definition_id):
+ value = properties[definition_id]
try:
definition = CustomPropertyDefinition.objects.for_team(team_id).get(id=definition_id)
except (CustomPropertyDefinition.DoesNotExist, ValidationError) as exc:
@@ -174,22 +197,24 @@ def record_last_slack_message_at(*, team_id: int, account_id: str | UUID, timest
defaults={"display_type": DisplayType.DATETIME},
)
for _attempt in range(_LAST_SLACK_MESSAGE_WRITE_ATTEMPTS):
- current = (
- CustomPropertyValue.objects.for_team(team_id)
- .filter(account_id=account_id, definition_id=definition.id, is_deleted=False)
- .values_list("value_datetime", flat=True)
- .first()
- )
- if current is not None and timestamp - current < MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES:
- return False
try:
- _set_value(
- team_id=team_id,
- account_id=account_id,
- definition=definition,
- value=timestamp,
- created_by_id=None,
- )
+ with _guard_value(team_id=team_id, account_id=account_id, definition_id=definition.id) as using:
+ current = (
+ CustomPropertyValue.objects.for_team(team_id)
+ .using(using)
+ .filter(account_id=account_id, definition_id=definition.id, is_deleted=False)
+ .values_list("value_datetime", flat=True)
+ .first()
+ )
+ if current is not None and timestamp - current < MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES:
+ return False
+ _set_value(
+ team_id=team_id,
+ account_id=account_id,
+ definition=definition,
+ value=timestamp,
+ created_by_id=None,
+ )
except CustomPropertyValueConflict:
continue
return True
@@ -203,22 +228,24 @@ def set_synced_custom_property_value(
if value is None:
return _clear_value(team_id=team_id, account_id=account_id, definition=definition)
_, coerced = _coerce_to_column(definition, value)
- current = (
- CustomPropertyValue.objects.for_team(team_id)
- .filter(account_id=account_id, definition_id=definition.id, is_deleted=False)
- .first()
- )
- if current is not None:
- current.definition = definition
- if value_of(current) == coerced:
- return False
- _set_value(
- team_id=team_id,
- account_id=account_id,
- definition=definition,
- value=value,
- created_by_id=None,
- )
+ with _guard_value(team_id=team_id, account_id=account_id, definition_id=definition.id) as using:
+ current = (
+ CustomPropertyValue.objects.for_team(team_id)
+ .using(using)
+ .filter(account_id=account_id, definition_id=definition.id, is_deleted=False)
+ .first()
+ )
+ if current is not None:
+ current.definition = definition
+ if value_of(current) == coerced:
+ return False
+ _set_value(
+ team_id=team_id,
+ account_id=account_id,
+ definition=definition,
+ value=value,
+ created_by_id=None,
+ )
return True
@@ -235,18 +262,24 @@ def _set_value(
"""Coerce `value` and atomically supersede the account's active row for `definition`."""
column, coerced = _coerce_to_column(definition, value)
try:
- with transaction.atomic():
- active_rows = CustomPropertyValue.objects.for_team(team_id).filter(
- account_id=account_id, definition_id=definition.id, is_deleted=False
+ with _guard_value(team_id=team_id, account_id=account_id, definition_id=definition.id) as using:
+ active_rows = (
+ CustomPropertyValue.objects.for_team(team_id)
+ .using(using)
+ .filter(account_id=account_id, definition_id=definition.id, is_deleted=False)
)
previous_row = active_rows.first()
active_rows.update(is_deleted=True)
- row = CustomPropertyValue.objects.for_team(team_id).create(
- team_id=team_id,
- account_id=account_id,
- definition_id=definition.id,
- created_by_id=created_by_id,
- **{column: coerced},
+ row = (
+ CustomPropertyValue.objects.for_team(team_id)
+ .using(using)
+ .create(
+ team_id=team_id,
+ account_id=account_id,
+ definition_id=definition.id,
+ created_by_id=created_by_id,
+ **{column: coerced},
+ )
)
_schedule_value_changed_event(
team_id=team_id,
@@ -256,6 +289,7 @@ def _set_value(
current_value=coerced,
actor=actor,
workflow_id=workflow_id,
+ using=using,
)
except IntegrityError as exc:
if _is_active_value_conflict(exc):
@@ -275,9 +309,11 @@ def _clear_value(
actor: User | None = None,
workflow_id: str | None = None,
) -> bool:
- with transaction.atomic():
- active_rows = CustomPropertyValue.objects.for_team(team_id).filter(
- account_id=account_id, definition_id=definition.id, is_deleted=False
+ with _guard_value(team_id=team_id, account_id=account_id, definition_id=definition.id) as using:
+ active_rows = (
+ CustomPropertyValue.objects.for_team(team_id)
+ .using(using)
+ .filter(account_id=account_id, definition_id=definition.id, is_deleted=False)
)
previous_row = active_rows.first()
if previous_row is None:
@@ -295,6 +331,7 @@ def _clear_value(
current_value=None,
actor=actor,
workflow_id=workflow_id,
+ using=using,
)
return True
@@ -308,6 +345,7 @@ def _schedule_value_changed_event(
current_value: CoercedValue | None,
actor: User | None,
workflow_id: str | None,
+ using: str,
) -> None:
"""Emit $account_custom_property_changed post-commit when the stored value actually changes.
@@ -321,7 +359,7 @@ def _schedule_value_changed_event(
previous_value = value_of(previous_row)
if previous_value == current_value:
return
- account = Account.objects.for_team(team_id).select_related("team").get(id=account_id)
+ account = Account.objects.for_team(team_id).using(using).select_related("team").get(id=account_id)
def emit() -> None:
try:
@@ -336,7 +374,7 @@ def _schedule_value_changed_event(
except Exception as e:
capture_exception(e)
- transaction.on_commit(emit)
+ transaction.on_commit(emit, using=using)
def _is_active_value_conflict(exc: IntegrityError) -> bool:
diff --git a/products/customer_analytics/backend/test/test_custom_property_value_concurrency.py b/products/customer_analytics/backend/test/test_custom_property_value_concurrency.py
new file mode 100644
index 000000000000..0260b3fab3e8
--- /dev/null
+++ b/products/customer_analytics/backend/test/test_custom_property_value_concurrency.py
@@ -0,0 +1,281 @@
+from collections.abc import Callable
+from concurrent.futures import Future, ThreadPoolExecutor
+from datetime import UTC, datetime
+from queue import Queue
+from time import monotonic
+
+from posthog.test.base import NonAtomicBaseTest
+from unittest.mock import patch
+
+from django.db import connection, transaction
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.customer_analytics.backend.logic.custom_property_values import (
+ MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES,
+ record_last_slack_message_at,
+ set_account_custom_properties_by_id,
+ set_custom_property_value,
+ set_synced_custom_property_value,
+)
+from products.customer_analytics.backend.models import Account, CustomPropertyDefinition, CustomPropertyValue
+from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition
+
+LOGIC_MODULE = "products.customer_analytics.backend.logic.custom_property_values"
+_WAIT_TIMEOUT_SECONDS = 10
+
+
+class TestCustomPropertyValueConcurrency(NonAtomicBaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.account = create_account(team_id=self.team.id)
+ self.definition = create_custom_property_definition(team_id=self.team.id)
+ self.worker_pids: Queue[int] = Queue()
+ event_patch = patch(f"{LOGIC_MODULE}.emit_account_custom_property_changed")
+ self.value_changed = event_patch.start()
+ self.addCleanup(event_patch.stop)
+
+ def _set(
+ self,
+ value: str,
+ *,
+ account: Account | None = None,
+ definition: CustomPropertyDefinition | None = None,
+ team_id: int | None = None,
+ ) -> CustomPropertyValue:
+ return set_custom_property_value(
+ team_id=team_id if team_id is not None else self.team.id,
+ account_id=str((account or self.account).id).upper(),
+ definition_id=(definition or self.definition).id,
+ value=value,
+ )
+
+ def _write(self, operation: str, value: str) -> object:
+ if operation == "set":
+ return self._set(value)
+ return set_account_custom_properties_by_id(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ properties={str(self.definition.id): None},
+ )
+
+ def _start_write(self, executor: ThreadPoolExecutor, write: Callable[[], object]) -> Future[object]:
+ def run() -> object:
+ try:
+ with connection.cursor() as cursor:
+ cursor.execute("SET statement_timeout = '15s'")
+ cursor.execute("SELECT pg_backend_pid()")
+ self.worker_pids.put(cursor.fetchone()[0])
+ return write()
+ finally:
+ connection.close()
+
+ return executor.submit(run)
+
+ def _assert_write_waits(self, future: Future[object]) -> None:
+ worker_pid = self.worker_pids.get(timeout=_WAIT_TIMEOUT_SECONDS)
+ deadline = monotonic() + _WAIT_TIMEOUT_SECONDS
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT pg_backend_pid()")
+ holder_pid = cursor.fetchone()[0]
+ while monotonic() < deadline:
+ if future.done():
+ future.result()
+ self.fail("The competing write finished before the holder transaction ended")
+ cursor.execute("SELECT %s = ANY(pg_blocking_pids(%s))", [holder_pid, worker_pid])
+ if cursor.fetchone()[0]:
+ return
+ self.fail("The competing write did not wait for the holder transaction")
+
+ @parameterized.expand(
+ [
+ ("first_insert", None, "set", "set", "second", 2),
+ ("replacement", "initial", "set", "set", "second", 3),
+ ("set_then_clear", "initial", "set", "clear", None, 2),
+ ("clear_then_set", "initial", "clear", "set", "second", 2),
+ ("absent_clear_then_set", None, "clear", "set", "second", 1),
+ ("clear_then_clear", "initial", "clear", "clear", None, 1),
+ ]
+ )
+ def test_same_key_writes_wait_for_commit_and_preserve_history(
+ self,
+ _name: str,
+ initial: str | None,
+ first_operation: str,
+ second_operation: str,
+ expected: str | None,
+ history_count: int,
+ ) -> None:
+ if initial is not None:
+ self._set(initial)
+ self.value_changed.reset_mock()
+
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ with transaction.atomic():
+ self._write(first_operation, "first")
+ future = self._start_write(executor, lambda: self._write(second_operation, "second"))
+ self._assert_write_waits(future)
+ future.result(timeout=_WAIT_TIMEOUT_SECONDS)
+
+ rows = CustomPropertyValue.objects.for_team(self.team.id).filter(
+ account=self.account, definition=self.definition
+ )
+ self.assertEqual(rows.count(), history_count)
+ self.assertEqual(
+ list(rows.filter(is_deleted=False).values_list("value_str", flat=True)), [expected] if expected else []
+ )
+ expected_events: list[tuple[str | None, str | None]] = []
+ previous = initial
+ for operation, value in [(first_operation, "first"), (second_operation, "second")]:
+ current = value if operation == "set" else None
+ if previous != current:
+ expected_events.append((previous, current))
+ previous = current
+ self.assertCountEqual(
+ [
+ (call.kwargs["previous_value"], call.kwargs["current_value"])
+ for call in self.value_changed.call_args_list
+ ],
+ expected_events,
+ )
+
+ @parameterized.expand([("same_value", "enterprise", False, 2), ("previous_value", "starter", True, 3)])
+ def test_sync_checks_current_value_after_the_competing_write_commits(
+ self, _name: str, value: str, changed: bool, history_count: int
+ ) -> None:
+ self._set("starter")
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ with transaction.atomic():
+ self._set("enterprise")
+ future = self._start_write(
+ executor,
+ lambda: set_synced_custom_property_value(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ definition=self.definition,
+ value=value,
+ ),
+ )
+ self._assert_write_waits(future)
+ self.assertIs(future.result(timeout=_WAIT_TIMEOUT_SECONDS), changed)
+
+ rows = CustomPropertyValue.objects.for_team(self.team.id).filter(
+ account=self.account, definition=self.definition
+ )
+ self.assertEqual(rows.count(), history_count)
+ self.assertEqual(rows.get(is_deleted=False).value_str, value)
+
+ def test_rollback_releases_the_key_without_history_or_events_from_the_failed_write(self) -> None:
+ self._set("initial")
+ self.value_changed.reset_mock()
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ with transaction.atomic():
+ self._set("rolled back")
+ future = self._start_write(executor, lambda: self._set("accepted"))
+ self._assert_write_waits(future)
+ transaction.set_rollback(True)
+ future.result(timeout=_WAIT_TIMEOUT_SECONDS)
+
+ rows = CustomPropertyValue.objects.for_team(self.team.id).filter(
+ account=self.account, definition=self.definition
+ )
+ self.assertCountEqual(rows.values_list("value_str", flat=True), ["initial", "accepted"])
+ self.assertEqual(rows.get(is_deleted=False).value_str, "accepted")
+ self.value_changed.assert_called_once()
+ self.assertEqual(self.value_changed.call_args.kwargs["previous_value"], "initial")
+ self.assertEqual(self.value_changed.call_args.kwargs["current_value"], "accepted")
+
+ @parameterized.expand([("account",), ("definition",)])
+ def test_other_keys_do_not_wait_for_the_holder_transaction(self, different_key: str) -> None:
+ account = create_account(team_id=self.team.id) if different_key == "account" else self.account
+ definition = (
+ create_custom_property_definition(team_id=self.team.id, name="Other")
+ if different_key == "definition"
+ else self.definition
+ )
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ with transaction.atomic():
+ self._set("first")
+ future = self._start_write(
+ executor, lambda: self._set("second", account=account, definition=definition)
+ )
+ future.result(timeout=_WAIT_TIMEOUT_SECONDS)
+ self.assertEqual(
+ CustomPropertyValue.objects.for_team(self.team.id)
+ .get(account=account, definition=definition, is_deleted=False)
+ .value_str,
+ "second",
+ )
+
+ def test_environment_and_parent_writes_share_the_same_key(self) -> None:
+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="Environment")
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ with transaction.atomic():
+ self._set("first")
+ future = self._start_write(executor, lambda: self._set("second", team_id=environment.id))
+ self._assert_write_waits(future)
+ future.result(timeout=_WAIT_TIMEOUT_SECONDS)
+ self.assertEqual(
+ CustomPropertyValue.objects.for_team(self.team.id)
+ .get(account=self.account, definition=self.definition, is_deleted=False)
+ .value_str,
+ "second",
+ )
+
+ def test_reversed_batches_acquire_keys_in_the_same_order(self) -> None:
+ other = create_custom_property_definition(team_id=self.team.id, name="Other")
+ lower, higher = sorted([self.definition, other], key=lambda definition: definition.id)
+
+ def write_batch() -> object:
+ with transaction.atomic():
+ return set_account_custom_properties_by_id(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ properties={higher.id.hex.upper(): "second", str(lower.id): "second"},
+ )
+
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ with transaction.atomic():
+ with connection.cursor() as cursor:
+ cursor.execute("SET LOCAL statement_timeout = '15s'")
+ self._set("first", definition=lower)
+ future = self._start_write(executor, write_batch)
+ self._assert_write_waits(future)
+ self._set("first", definition=higher)
+ future.result(timeout=_WAIT_TIMEOUT_SECONDS)
+ self.assertEqual(
+ list(
+ CustomPropertyValue.objects.for_team(self.team.id)
+ .filter(account=self.account, is_deleted=False)
+ .values_list("value_str", flat=True)
+ ),
+ ["second", "second"],
+ )
+
+ def test_slack_timestamp_check_sees_the_committed_newer_value(self) -> None:
+ initial = datetime(2026, 1, 1, tzinfo=UTC)
+ record_last_slack_message_at(team_id=self.team.id, account_id=self.account.id, timestamp=initial)
+ newer = initial + 2 * MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ with transaction.atomic():
+ record_last_slack_message_at(team_id=self.team.id, account_id=self.account.id, timestamp=newer)
+ future = self._start_write(
+ executor,
+ lambda: record_last_slack_message_at(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ timestamp=initial + MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES,
+ ),
+ )
+ self._assert_write_waits(future)
+ self.assertIs(future.result(timeout=_WAIT_TIMEOUT_SECONDS), False)
+ self.assertEqual(
+ CustomPropertyValue.objects.for_team(self.team.id)
+ .get(account=self.account, is_deleted=False)
+ .value_datetime,
+ newer,
+ )
diff --git a/products/customer_analytics/backend/test/test_custom_property_values.py b/products/customer_analytics/backend/test/test_custom_property_values.py
index e563df06401d..6820788bc547 100644
--- a/products/customer_analytics/backend/test/test_custom_property_values.py
+++ b/products/customer_analytics/backend/test/test_custom_property_values.py
@@ -256,7 +256,7 @@ class TestSetCustomPropertyValue(BaseTest):
@patch(f"{LOGIC_MODULE}.CustomPropertyValue")
def test_losing_the_active_value_race_surfaces_as_a_conflict(self, mock_value_model):
definition = self._create_property_definition()
- mock_value_model.objects.for_team.return_value.create.side_effect = IntegrityError(
+ mock_value_model.objects.for_team.return_value.using.return_value.create.side_effect = IntegrityError(
f'duplicate key value violates unique constraint "{ACTIVE_VALUE_CONSTRAINT_NAME}"'
)
@@ -266,7 +266,7 @@ class TestSetCustomPropertyValue(BaseTest):
@patch(f"{LOGIC_MODULE}.CustomPropertyValue")
def test_other_integrity_errors_are_not_masked_as_conflicts(self, mock_value_model):
definition = self._create_property_definition()
- mock_value_model.objects.for_team.return_value.create.side_effect = IntegrityError(
+ mock_value_model.objects.for_team.return_value.using.return_value.create.side_effect = IntegrityError(
'new row violates check constraint "custom_property_value_exactly_one_value"'
)
@@ -276,7 +276,7 @@ class TestSetCustomPropertyValue(BaseTest):
@patch(f"{LOGIC_MODULE}.CustomPropertyValue")
def test_losing_the_active_value_clear_race_surfaces_as_a_conflict(self, mock_value_model):
definition = self._create_property_definition()
- active_rows = mock_value_model.objects.for_team.return_value.filter.return_value
+ active_rows = mock_value_model.objects.for_team.return_value.using.return_value.filter.return_value
active_rows.first.return_value = MagicMock(id=uuid4())
active_rows.filter.return_value.update.return_value = 0
@@ -308,13 +308,13 @@ class TestSetAccountCustomPropertiesById(BaseTest):
(seats.id, None, 42.0),
}
- def test_unknown_id_raises_carrying_the_id(self):
- missing = uuid4()
+ @parameterized.expand([("unknown", str(uuid4())), ("malformed", "not-a-uuid")])
+ def test_unknown_id_raises_carrying_the_id(self, _name: str, missing: str) -> None:
with pytest.raises(CustomPropertyDefinitionNotFound) as exc_info:
set_account_custom_properties_by_id(
- team_id=self.team.id, account_id=self.account.id, properties={str(missing): "x"}
+ team_id=self.team.id, account_id=self.account.id, properties={missing: "x"}
)
- assert exc_info.value.identifier == str(missing)
+ assert exc_info.value.identifier == missing
def test_invalid_value_raises_carrying_the_id(self):
seats = create_custom_property_definition(team_id=self.team.id, name="Seats", display_type=DisplayType.NUMBER)
@@ -510,36 +510,6 @@ class TestRecordLastSlackMessageAt(BaseTest):
assert self._record(later) is True
assert mock_set_value.call_count == 2
- @patch(f"{LOGIC_MODULE}._set_value")
- def test_a_rival_storing_a_newer_value_stops_the_retry(self, mock_set_value):
- # The rival's value lands before the retry re-reads, so the retry must skip rather than
- # drag the stored value back to this older message.
- newer = self.at + 2 * MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES
-
- def store_newer_then_conflict(**kwargs):
- self._set_active_value(newer)
- raise CustomPropertyValueConflict("rival won the active row")
-
- mock_set_value.side_effect = store_newer_then_conflict
-
- assert self._record(self.at + MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES) is False
- assert self._active_values() == [newer]
- # The retry re-read the rival's value and skipped, rather than writing again.
- assert mock_set_value.call_count == 1
-
- def _set_active_value(self, timestamp: datetime) -> None:
- """Store a value the way a rival task would. Writes through the ORM, not the logic's own
- write path — this test doubles that path, so going through it would store nothing."""
- definition = CustomPropertyDefinition.objects.for_team(self.team.id).get(name=CANONICAL_LAST_SLACK_MESSAGE_AT)
- rows = CustomPropertyValue.objects.for_team(self.team.id)
- rows.filter(account_id=self.account.id, definition_id=definition.id, is_deleted=False).update(is_deleted=True)
- rows.create(
- team_id=self.team.id,
- account_id=self.account.id,
- definition_id=definition.id,
- value_datetime=timestamp,
- )
-
def test_a_conflicting_definition_type_rejects_the_write(self):
create_custom_property_definition(
team_id=self.team.id, name=CANONICAL_LAST_SLACK_MESSAGE_AT, display_type=DisplayType.TEXT