: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(dashboards): isolate edits to shared text and button tiles (#107605)
Daniel Parker0c2ebfc9675f
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex 21375ca51483..4f1b5adb50a1 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -1,5 +1,6 @@import jsonimport datetime+from collections.abc import Callableimport time_machinefrom posthog.test.base import APIBaseTest, FuzzyInt, QueryMatchingTest, snapshot_postgres_queries@@ -7,6 +8,7 @@ from unittest import mockfrom unittest.mock import ANY, MagicMock, patchfrom django.core.cache import cache+from django.db import connectionfrom django.test import override_settingsfrom django.utils.timezone import now@@ -2294,14 +2296,30 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):)self.assertEqual(response["creation_mode"], "default")- def test_dashboard_duplication_does_not_duplicate_tiles_by_default(self):+ def test_dashboard_duplication_uses_copy_on_write_for_text_tiles(self) -> None:existing_dashboard = Dashboard.objects.create(team=self.team, name="existing dashboard", created_by=self.user)insight_one_id, _ = self.dashboard_api.create_insight({"dashboards": [existing_dashboard.pk], "name": "the insight"})- _, dashboard_with_tiles = self.dashboard_api.create_text_tile(existing_dashboard.id)+ _, dashboard_with_tiles = self.dashboard_api.create_text_tile(existing_dashboard.id, text="source body")+ original_text_tile = next(t for t in dashboard_with_tiles["tiles"] if t.get("text"))+ original_text = Text.objects.get(id=original_text_tile["text"]["id"])+ original_text.agent_context = "source context"+ original_text.save(update_fields=["agent_context"])+ _, dashboard_with_buttons = self.dashboard_api.create_button_tile(existing_dashboard.id)+ original_button_tile = next(t for t in dashboard_with_buttons["tiles"] if t.get("button_tile"))- _, duplicate_response = self.dashboard_api.create_dashboard(+ viewer = User.objects.create_and_join(self.organization, "[email protected]", None)+ AccessControl.objects.create(+ resource="dashboard",+ resource_id=str(existing_dashboard.id),+ team=self.team,+ access_level="viewer",+ organization_member=viewer.organization_memberships.get(organization=self.organization),+ )+ self.client.force_login(viewer)++ duplicate_id, duplicate_response = self.dashboard_api.create_dashboard({"name": "another", "use_dashboard": existing_dashboard.id})@@ -2310,9 +2328,52 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):assert insight_tile["insight"]["id"] == insight_one_idassert insight_tile["insight"]["name"] == "the insight"- original_text_tile = next(t for t in dashboard_with_tiles["tiles"] if t.get("text"))assert text_tile["text"]["id"] == original_text_tile["text"]["id"]+ invalid_text_tile = {+ **text_tile,+ "text": {**text_tile["text"], "body": "invalid update"},+ "layouts": {"sm": {"x": 0, "y": 0, "w": 0, "h": 1}},+ }+ self.dashboard_api.update_text_tile(+ duplicate_id,+ invalid_text_tile,+ expected_status=status.HTTP_400_BAD_REQUEST,+ )+ shared_tile = DashboardTile.objects.get(id=text_tile["id"])+ original_text.refresh_from_db()+ assert shared_tile.text_id == original_text.id+ assert original_text.body == "source body"++ text_tile["text"]["body"] = "duplicate body"+ text_tile["text"]["agent_context"] = "duplicate context"+ self.dashboard_api.update_text_tile(duplicate_id, text_tile)++ source_text_tile = next(+ tile for tile in self.dashboard_api.get_dashboard(existing_dashboard.id)["tiles"] if tile.get("text")+ )+ duplicate_text_tile = next(+ tile for tile in self.dashboard_api.get_dashboard(duplicate_id)["tiles"] if tile.get("text")+ )+ assert source_text_tile["text"]["id"] == original_text_tile["text"]["id"]+ assert source_text_tile["text"]["body"] == "source body"+ assert source_text_tile["text"]["agent_context"] == "source context"+ assert duplicate_text_tile["text"]["id"] != original_text_tile["text"]["id"]+ assert duplicate_text_tile["text"]["body"] == "duplicate body"+ assert duplicate_text_tile["text"]["agent_context"] == "duplicate context"++ button_tile = next(t for t in duplicate_response["tiles"] if t.get("button_tile"))+ assert button_tile["button_tile"]["id"] == original_button_tile["button_tile"]["id"]+ button_tile["button_tile"]["url"] = "https://example.com/duplicate"+ self.dashboard_api.update_dashboard(duplicate_id, {"tiles": [button_tile]})++ source_button = ButtonTile.objects.get(id=original_button_tile["button_tile"]["id"])+ duplicate_button_tile = DashboardTile.objects.get(id=button_tile["id"])+ assert source_button.url == "https://example.com"+ assert duplicate_button_tile.button_tile_id != source_button.id+ assert duplicate_button_tile.button_tile is not None+ assert duplicate_button_tile.button_tile.url == "https://example.com/duplicate"+def test_dashboard_duplication_without_tile_duplicate_excludes_soft_deleted_tiles(self):existing_dashboard = Dashboard.objects.create(team=self.team, name="existing dashboard", created_by=self.user)insight_one_id, _ = self.dashboard_api.create_insight(@@ -3041,6 +3102,39 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):dashboard = self.dashboard_api.get_dashboard(dashboard_id)assert len(dashboard["tiles"]) == 1+ def test_move_tile_foreign_team_text_is_copied_on_edit(self) -> None:+ destination_team = Team.objects.create(organization=self.organization, project=self.project)+ source_dashboard = Dashboard.objects.create(team=self.team, name="Source Dashboard")+ destination_dashboard = Dashboard.objects.create(team=destination_team, name="Destination Dashboard")+ text = Text.objects.create(body="original", team=self.team, created_by=self.user)+ tile = DashboardTile.objects.create(dashboard=source_dashboard, text=text)++ move_response = self.client.patch(+ f"/api/projects/{self.team.id}/dashboards/{source_dashboard.id}/move_tile",+ {"tile": {"id": tile.id}, "to_dashboard": destination_dashboard.id},+ )+ self.assertEqual(move_response.status_code, status.HTTP_200_OK)++ tile.refresh_from_db()+ self.assertEqual(tile.team_id, destination_team.id)+ self.assertEqual(tile.text_id, text.id, "the moved tile still points at the source team's text")++ update_response = self.client.post(+ f"/api/environments/{destination_team.id}/dashboards/{destination_dashboard.id}/update_text_tile/",+ {"tile_id": tile.id, "body": "edited from destination team"},+ content_type="application/json",+ )+ self.assertEqual(update_response.status_code, status.HTTP_200_OK)++ text.refresh_from_db()+ tile.refresh_from_db()+ self.assertEqual(text.body, "original", "the source team's text must not be mutated")+ self.assertNotEqual(tile.text_id, text.id)+ tile_text = tile.text+ assert tile_text is not None+ self.assertEqual(tile_text.team_id, destination_team.id)+ self.assertEqual(tile_text.body, "edited from destination team")+@parameterized.expand([("source",), ("target",)])def test_move_tile_respects_access_control(self, blocked_dashboard: str) -> None:self.organization.available_product_features = [@@ -3088,6 +3182,152 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):other_tile.refresh_from_db()assert other_tile.dashboard_id == other_dashboard.id+ @parameterized.expand(+ [+ ("text", "patch"),+ ("text", "update_text_tile"),+ ("button_tile", "patch"),+ ("text", "copy_tile"),+ ("text", "duplicate"),+ ]+ )+ def test_tile_mutation_rejects_move_before_lock(self, content_field: str, endpoint: str) -> None:+ dashboard = Dashboard.objects.create(team=self.team, name="Source")+ destination = Dashboard.objects.create(team=self.team, name="Destination")+ if content_field == "text":+ content: Text | ButtonTile = Text.objects.create(team=self.team, body="Original")+ content_data = {"id": content.id, "body": "Updated"}+ else:+ content = ButtonTile.objects.create(team=self.team, url="https://example.com/original", text="Original")+ content_data = {"id": str(content.id), "url": "https://example.com/updated", "text": "Updated"}+ tile = DashboardTile.objects.create(dashboard=dashboard, **{content_field: content})+ copy_destination = Dashboard.objects.create(team=self.team, name="Copy destination")+ private_text = Text.objects.create(team=self.team, body="Private content")+ dashboard_count = Dashboard.objects.count()+ moved = False++ def move_before_lock(+ execute: Callable[..., object], sql: str, params: object, many: bool, context: dict[str, object]+ ) -> object:+ nonlocal moved+ if not moved and "FOR UPDATE" in sql and DashboardTile._meta.db_table in sql:+ moved = True+ updates: dict[str, object] = {"dashboard": destination}+ if endpoint in ("copy_tile", "duplicate"):+ updates["text"] = private_text+ DashboardTile.objects.filter(pk=tile.pk).update(**updates)+ return execute(sql, params, many, context)++ with connection.execute_wrapper(move_before_lock):+ if endpoint == "patch":+ response = self.client.patch(+ f"/api/projects/{self.team.id}/dashboards/{dashboard.id}",+ {"tiles": [{"id": tile.id, content_field: content_data}]},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], content_field)+ elif endpoint == "update_text_tile":+ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{dashboard.id}/update_text_tile/",+ {"tile_id": tile.id, "body": "Updated"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ elif endpoint == "copy_tile":+ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{copy_destination.id}/copy_tile/",+ {"fromDashboardId": dashboard.id, "tileId": tile.id},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(DashboardTile.objects.filter(dashboard=copy_destination).exists())+ else:+ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/",+ {"name": "Copy", "use_dashboard": dashboard.id},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(Dashboard.objects.count(), dashboard_count)++ self.assertTrue(moved)+ content.refresh_from_db()+ self.assertEqual(content.body if isinstance(content, Text) else content.text, "Original")++ def test_update_rolls_back_earlier_tile_text_copy_when_a_later_tile_fails(self) -> None:+ dashboard = Dashboard.objects.create(team=self.team, name="Test Dashboard")+ other_dashboard = Dashboard.objects.create(team=self.team, name="Other Dashboard")+ shared_text = Text.objects.create(body="original", team=self.team, created_by=self.user)+ tile = DashboardTile.objects.create(dashboard=dashboard, text=shared_text)+ DashboardTile.objects.create(dashboard=other_dashboard, text=shared_text)++ second_text = Text.objects.create(body="second", team=self.team, created_by=self.user)+ second_tile = DashboardTile.objects.create(dashboard=dashboard, text=second_text)++ response = self.client.patch(+ f"/api/projects/{self.team.id}/dashboards/{dashboard.id}",+ {+ "tiles": [+ {"id": tile.id, "text": {"id": shared_text.id, "body": "edited before failure"}},+ # second_tile's real text is second_text, so this id mismatch fails validation+ {"id": second_tile.id, "text": {"id": shared_text.id, "body": "mismatched text id"}},+ ]+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ shared_text.refresh_from_db()+ tile.refresh_from_db()+ self.assertEqual(shared_text.body, "original")+ self.assertEqual(+ tile.text_id, shared_text.id, "the tile must still point at the shared text, not an orphaned copy"+ )++ @parameterized.expand([(False, False), (True, False), (False, True)])+ def test_update_shared_button_tile_isolates_source(self, source_deleted: bool, foreign_team: bool) -> None:+ source_team = (+ Team.objects.create(organization=self.organization, project=self.project) if foreign_team else self.team+ )+ source = Dashboard.objects.create(team=source_team, name="Source", deleted=source_deleted)+ destination = Dashboard.objects.create(team=self.team, name="Destination")+ button = ButtonTile.objects.create(+ team=source_team, url="https://example.com/source", text="Source", created_by=self.user+ )+ source_tile = DashboardTile.objects.create(dashboard=source, button_tile=button, deleted=source_deleted)+ tile = DashboardTile.objects.create(dashboard=destination, button_tile=button)+ button_count = ButtonTile.objects.count()+ tile_data = {+ "id": tile.id,+ "button_tile": {"id": str(button.id), "url": "https://example.com/edited", "text": "Edited"},+ }++ invalid_response = self.client.patch(+ f"/api/projects/{self.team.id}/dashboards/{destination.id}",+ {"tiles": [{**tile_data, "layouts": {"sm": {"x": 0, "y": 0, "w": 0, "h": 1}}}]},+ format="json",+ )+ assert invalid_response.status_code == status.HTTP_400_BAD_REQUEST+ tile.refresh_from_db()+ assert tile.button_tile_id == button.id+ assert ButtonTile.objects.count() == button_count++ response = self.client.patch(+ f"/api/projects/{self.team.id}/dashboards/{destination.id}", {"tiles": [tile_data]}, format="json"+ )+ assert response.status_code == status.HTTP_200_OK+ button.refresh_from_db()+ tile.refresh_from_db()+ source_tile.refresh_from_db()+ assert button.url == "https://example.com/source"+ assert source_tile.button_tile_id == button.id+ assert tile.button_tile_id != button.id+ assert tile.button_tile is not None+ assert tile.button_tile.team_id == destination.team_id+ assert tile.button_tile.url == "https://example.com/edited"+ assert tile.button_tile.text == "Edited"+def test_cannot_inject_insight_id_into_tile_update(self) -> None:other_org, _, other_team = Organization.objects.bootstrap(self.user, name="other org")other_insight = Insight.objects.create(team=other_team, name="secret insight")@@ -4774,14 +5014,22 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):)self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)- def test_update_text_tile_updates_body_context_and_layout(self):+ def test_update_text_tile_updates_body_context_and_layout(self) -> None:dashboard = Dashboard.objects.create(team=self.team, name="Test Dashboard")- text = Text.objects.create(body="original", team=self.team, created_by=self.user)+ source_team = Team.objects.create(organization=self.organization, project=self.project)+ source_dashboard = Dashboard.objects.create(team=source_team, name="Source Dashboard")+ text = Text.objects.create(+ body="original",+ agent_context="Original context",+ team=source_team,+ created_by=self.user,+ )tile = DashboardTile.objects.create(dashboard=dashboard,text=text,layouts={"sm": {"x": 0, "y": 0, "w": 6, "h": 1}},)+ source_tile = DashboardTile.objects.create(dashboard=source_dashboard, text=text)response = self.client.post(f"/api/environments/{self.team.pk}/dashboards/{dashboard.pk}/update_text_tile/",@@ -4801,9 +5049,17 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):text.refresh_from_db()tile.refresh_from_db()- self.assertEqual(text.body, "## Updated heading")- self.assertEqual(text.agent_context, "Use paid plan events for this metric.")- self.assertEqual(text.last_modified_by, self.user)+ source_tile.refresh_from_db()+ self.assertEqual(text.body, "original")+ self.assertEqual(text.agent_context, "Original context")+ self.assertEqual(source_tile.text_id, text.id)+ self.assertNotEqual(tile.text_id, text.id)+ tile_text = tile.text+ assert tile_text is not None+ self.assertEqual(tile_text.team_id, self.team.id)+ self.assertEqual(tile_text.body, "## Updated heading")+ self.assertEqual(tile_text.agent_context, "Use paid plan events for this metric.")+ self.assertEqual(tile_text.last_modified_by, self.user)self.assertEqual(tile.layouts["sm"], {"x": 0, "y": 5, "w": 12, "h": 2})def test_update_text_tile_leaves_omitted_fields_unchanged(self):diff --git a/posthog/api/test/dashboards/test_dashboard_tile_concurrency.py b/posthog/api/test/dashboards/test_dashboard_tile_concurrency.pynew file mode 100644index 000000000000..387ac098991a--- /dev/null+++ b/posthog/api/test/dashboards/test_dashboard_tile_concurrency.py@@ -0,0 +1,137 @@+from collections.abc import Callable+from concurrent.futures import ThreadPoolExecutor+from queue import Queue+from threading import Event+from time import monotonic++from posthog.test.base import NonAtomicAPIBaseTest++from django.db import connection, connections, transaction++from rest_framework import status+from rest_framework.test import APIClient++from products.dashboards.backend.models.dashboard import Dashboard+from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text+++class TestDashboardTileConcurrency(NonAtomicAPIBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def _request(+ self,+ dashboard: Dashboard,+ payload: dict[str, object],+ backend: Queue[int],+ *,+ text_update: bool = False,+ after_lock: Callable[[], None] | None = None,+ ) -> int:+ conn = connections["default"]+ first_lock = True++ def trace_lock(+ execute: Callable[..., object], sql: str, params: object, many: bool, context: dict[str, object]+ ) -> object:+ nonlocal first_lock+ is_first_lock = first_lock and "FOR UPDATE" in sql and DashboardTile._meta.db_table in sql+ if is_first_lock:+ first_lock = False+ with conn.cursor() as cursor:+ cursor.execute("SELECT pg_backend_pid()")+ backend.put(cursor.fetchone()[0])+ result = execute(sql, params, many, context)+ if is_first_lock and after_lock is not None:+ after_lock()+ return result++ try:+ client = APIClient()+ client.force_authenticate(self.user)+ with conn.execute_wrapper(trace_lock):+ url = f"/api/projects/{self.team.id}/dashboards/{dashboard.id}/"+ response = (+ client.post(f"{url}update_text_tile/", payload, format="json")+ if text_update+ else client.patch(url, payload, format="json")+ )+ return response.status_code+ finally:+ conn.close()++ def _wait_for_blocked_request(self, backend: int) -> None:+ deadline = monotonic() + 10+ while monotonic() < deadline:+ with connection.cursor() as cursor:+ cursor.execute("SELECT cardinality(pg_blocking_pids(%s)) > 0", [backend])+ if cursor.fetchone()[0]:+ return+ self.fail("The request did not wait for a database lock.")++ def test_waiting_text_edit_reads_content_created_by_first_edit(self) -> None:+ dashboard = Dashboard.objects.create(team=self.team, name="Destination")+ source = Dashboard.objects.create(team=self.team, name="Source")+ text = Text.objects.create(team=self.team, body="Original")+ tile = DashboardTile.objects.create(dashboard=dashboard, text=text)+ DashboardTile.objects.create(dashboard=source, text=text)+ backend: Queue[int] = Queue()++ with ThreadPoolExecutor(max_workers=1) as executor:+ with transaction.atomic():+ DashboardTile.objects.select_for_update(of=("self",)).get(pk=tile.pk)+ pending = executor.submit(+ self._request,+ dashboard,+ {"tile_id": tile.pk, "body": "Second edit"},+ backend,+ text_update=True,+ )+ self._wait_for_blocked_request(backend.get(timeout=10))+ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{dashboard.id}/update_text_tile/",+ {"tile_id": tile.pk, "body": "First edit"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(pending.result(timeout=15), status.HTTP_200_OK)++ tile.refresh_from_db()+ text.refresh_from_db()+ assert tile.text is not None+ self.assertEqual(tile.text.body, "Second edit")+ self.assertEqual(text.body, "Original")++ def test_batch_edits_with_opposite_tile_orders_both_complete(self) -> None:+ dashboard = Dashboard.objects.create(team=self.team, name="Dashboard")+ texts = [Text.objects.create(team=self.team, body=f"Original {index}") for index in range(2)]+ tiles = [DashboardTile.objects.create(dashboard=dashboard, text=text) for text in texts]+ first_locked = Event()+ release_first = Event()+ first_backend: Queue[int] = Queue()+ second_backend: Queue[int] = Queue()++ def hold_first_lock() -> None:+ first_locked.set()+ self.assertTrue(release_first.wait(timeout=10))++ def payload(order: list[DashboardTile], body: str) -> dict[str, object]:+ return {"tiles": [{"id": tile.id, "text": {"id": tile.text_id, "body": body}} for tile in order]}++ with ThreadPoolExecutor(max_workers=2) as executor:+ first = executor.submit(+ self._request, dashboard, payload(tiles, "First edit"), first_backend, after_lock=hold_first_lock+ )+ try:+ self.assertTrue(first_locked.wait(timeout=10))+ second = executor.submit(+ self._request, dashboard, payload(list(reversed(tiles)), "Second edit"), second_backend+ )+ self._wait_for_blocked_request(second_backend.get(timeout=10))+ finally:+ release_first.set()+ self.assertEqual(first.result(timeout=15), status.HTTP_200_OK)+ self.assertEqual(second.result(timeout=15), status.HTTP_200_OK)++ for text in texts:+ text.refresh_from_db()+ self.assertEqual(text.body, "Second edit")diff --git a/posthog/models/test/test_dashboard_tile_model.py b/posthog/models/test/test_dashboard_tile_model.pyindex 167cf51fd90d..8e7436954a83 100644--- a/posthog/models/test/test_dashboard_tile_model.py+++ b/posthog/models/test/test_dashboard_tile_model.py@@ -5,8 +5,10 @@ from posthog.test.base import APIBaseTestfrom django.core.exceptions import ValidationErrorfrom django.db.utils import IntegrityError+from parameterized import parameterized+from products.dashboards.backend.models.dashboard import Dashboard-from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text+from products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Textfrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.product_analytics.backend.facade.models import Insight@@ -62,3 +64,32 @@ class TestDashboardTileModel(APIBaseTest):tile = DashboardTile(dashboard=self.dashboard, insight=insight, team_id=self.team.id)tile.save()self.assertEqual(tile.team_id, self.team.id)++ @parameterized.expand(+ [(content, deleted) for content in ("text", "button_tile") for deleted in ("neither", "tile", "dashboard")]+ )+ def test_copy_uses_current_content_after_reference_changes(self, content_field: str, deleted: str) -> None:+ if content_field == "text":+ original: Text | ButtonTile = Text.objects.create(team=self.team, body="Original")+ updated: Text | ButtonTile = Text.objects.create(team=self.team, body="Updated")+ else:+ original = ButtonTile.objects.create(team=self.team, url="https://example.com/original", text="Original")+ updated = ButtonTile.objects.create(team=self.team, url="https://example.com/updated", text="Updated")+ source = DashboardTile.objects.create(dashboard=self.dashboard, **{content_field: original})+ source = DashboardTile.objects.select_related(content_field).get(pk=source.pk)+ DashboardTile.objects.filter(pk=source.pk).update(**{content_field: updated})+ if deleted == "tile":+ DashboardTile.objects.filter(pk=source.pk).update(deleted=True)+ elif deleted == "dashboard":+ Dashboard.objects.filter(pk=self.dashboard.pk).update(deleted=True)+ destination = Dashboard.objects.create(team=self.team, name="Destination")++ source.copy_to_dashboard(destination)++ copied = DashboardTile.objects.get(dashboard=destination)+ if content_field == "text":+ assert copied.text is not None+ assert copied.text.body == "Updated"+ else:+ assert copied.button_tile is not None+ assert copied.button_tile.url == "https://example.com/updated"diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 77f0f7beed00..f2e9a9b86c2f 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -1562,6 +1562,54 @@ def _tile_type_and_widget_type(tile: DashboardTile) -> tuple[str, str | None]:raise ValueError("Dashboard tile has no related content for analytics")+def _copy_text_if_shared(tile: DashboardTile) -> Text:+ # Locks the tile against a concurrent `copy_to_dashboard` adding a second reference to this+ # text, so the sharing check below can't race a duplication that hasn't committed yet.+ tile = DashboardTile.objects.select_for_update(of=("self",)).get(pk=tile.pk, dashboard_id=tile.dashboard_id)+ text = cast(Text, tile.text)+ is_shared = DashboardTile.objects_including_soft_deleted.filter(text_id=text.id).exclude(id=tile.id).exists()+ # A tile moved to another team's dashboard (`move_tile`) keeps its text reference, so a+ # sole reference can still belong to a different team than the tile.+ if not is_shared and text.team_id == tile.team_id:+ return text++ text_copy = Text.objects.create(+ body=text.body,+ agent_context=text.agent_context,+ created_by_id=text.created_by_id,+ last_modified_at=text.last_modified_at,+ last_modified_by_id=text.last_modified_by_id,+ team_id=tile.team_id,+ )+ tile.text = text_copy+ tile.save(update_fields=["text"])+ return text_copy+++def _copy_button_if_shared(tile: DashboardTile) -> ButtonTile:+ tile = DashboardTile.objects.select_for_update(of=("self",)).get(pk=tile.pk, dashboard_id=tile.dashboard_id)+ button = cast(ButtonTile, tile.button_tile)+ is_shared = (+ DashboardTile.objects_including_soft_deleted.filter(button_tile_id=button.id).exclude(id=tile.id).exists()+ )+ if not is_shared and button.team_id == tile.team_id:+ return button++ button_copy = ButtonTile.objects.create(+ url=button.url,+ text=button.text,+ placement=button.placement,+ style=button.style,+ created_by_id=button.created_by_id,+ last_modified_at=button.last_modified_at,+ last_modified_by_id=button.last_modified_by_id,+ team_id=tile.team_id,+ )+ tile.button_tile = button_copy+ tile.save(update_fields=["button_tile"])+ return button_copy++def _report_dashboard_tile_added(*,user: User,@@ -1888,7 +1936,10 @@ class DashboardSerializer(DashboardMetadataSerializer):if duplicate_tiles or existing_tile.widget_id is not None:self._deep_duplicate_tiles(dashboard, existing_tile, user_access_control)else:- existing_tile.copy_to_dashboard(dashboard)+ try:+ existing_tile.copy_to_dashboard(dashboard)+ except DjangoValidationError:+ raise serializers.ValidationError("Unable to copy tile due to invalid data.")# Manual tag creation since this create method doesn't call super()self._attempt_set_tags(tags, dashboard)@@ -2137,12 +2188,26 @@ class DashboardSerializer(DashboardMetadataSerializer):user = cast(User, self.context["request"].user)tiles = initial_data.pop("tiles", [])- for tile_data in tiles:- tile, created = self._update_tiles(instance, tile_data, user, request=self.context.get("request"))- # Text and button tiles are always added via PATCH (never during initial dashboard- # creation), so this update() method is the right place to fire the "tile added"- # event. The `created` flag from update_or_create ensures we only fire on first- # insertion, not on subsequent edits to an existing tile.+ # One transaction for the whole loop: a text copy-on-write repoints a tile's text_id,+ # so a later tile failing validation must roll that back too, or a retry with the+ # original text_id can no longer find the tile.+ tile_results: list[tuple[DashboardTile | None, bool]] = []+ with transaction.atomic():+ tile_ids = [tile["id"] for tile in tiles if tile.get("id") is not None]+ list(+ DashboardTile.objects_including_soft_deleted.select_for_update(of=("self",))+ .filter(dashboard=instance, id__in=tile_ids)+ .order_by("id")+ .values_list("id", flat=True)+ )+ for tile_data in tiles:+ tile_results.append(self._update_tiles(instance, tile_data, user, request=self.context.get("request")))++ # Text and button tiles are always added via PATCH (never during initial dashboard+ # creation), so this update() method is the right place to fire the "tile added"+ # event. The `created` flag from update_or_create ensures we only fire on first+ # insertion, not on subsequent edits to an existing tile.+ for tile, created in tile_results:if created and tile is not None and "request" in self.context:tile_type, widget_type = DashboardSerializer._tile_added_analytics_fields(tile)_report_dashboard_tile_added(@@ -2498,20 +2563,27 @@ class DashboardSerializer(DashboardMetadataSerializer):validated_data["last_modified_by"] = last_modified_byvalidated_data["last_modified_at"] = now()- existing_text_id = text_json.get("id", None)- if existing_text_id:- try:- text = Text.objects.get(id=existing_text_id, team_id=instance.team_id)- if not DashboardTile.objects.filter(dashboard=instance, text_id=existing_text_id).exists():+ with transaction.atomic():+ existing_text_id = text_json.get("id", None)+ if existing_text_id:+ tile_id = tile_data.get("id")+ if tile_id is None:raise serializers.ValidationError({"text": "Text tile not found."})- for attr, val in validated_data.items():- setattr(text, attr, val)- text.save()- except Text.DoesNotExist:- raise serializers.ValidationError({"text": "Text tile not found in this team."})- else:- text = Text.objects.create(**validated_data)- tile, created = DashboardSerializer._upsert_tile(instance, tile_data, text=text)+ try:+ existing_tile = DashboardTile.objects.select_related("text").get(+ id=tile_id,+ dashboard=instance,+ text_id=existing_text_id,+ )+ text = _copy_text_if_shared(existing_tile)+ for attr, val in validated_data.items():+ setattr(text, attr, val)+ text.save()+ except DashboardTile.DoesNotExist:+ raise serializers.ValidationError({"text": "Text tile not found."})+ else:+ text = Text.objects.create(**validated_data)+ tile, created = DashboardSerializer._upsert_tile(instance, tile_data, text=text)return tile, createdelif tile_data.get("button_tile", None):button_tile_json: dict = tile_data.get("button_tile", {})@@ -2539,20 +2611,27 @@ class DashboardSerializer(DashboardMetadataSerializer):validated_data["last_modified_by"] = last_modified_byvalidated_data["last_modified_at"] = now()- existing_button_id = button_tile_json.get("id", None)- if existing_button_id:- try:- button_tile = ButtonTile.objects.get(id=existing_button_id, team_id=instance.team_id)- if not DashboardTile.objects.filter(dashboard=instance, button_tile_id=existing_button_id).exists():+ with transaction.atomic():+ existing_button_id = button_tile_json.get("id", None)+ if existing_button_id:+ tile_id = tile_data.get("id")+ if tile_id is None:raise serializers.ValidationError({"button_tile": "Button tile not found."})- for attr, val in validated_data.items():- setattr(button_tile, attr, val)- button_tile.save()- except ButtonTile.DoesNotExist:- raise serializers.ValidationError({"button_tile": "Button tile not found in this team."})- else:- button_tile = ButtonTile.objects.create(**validated_data)- tile, created = DashboardSerializer._upsert_tile(instance, tile_data, button_tile=button_tile)+ try:+ existing_tile = DashboardTile.objects.get(+ id=tile_id,+ dashboard=instance,+ button_tile_id=existing_button_id,+ )+ button_tile = _copy_button_if_shared(existing_tile)+ for attr, val in validated_data.items():+ setattr(button_tile, attr, val)+ button_tile.save()+ except DashboardTile.DoesNotExist:+ raise serializers.ValidationError({"button_tile": "Button tile not found."})+ else:+ button_tile = ButtonTile.objects.create(**validated_data)+ tile, created = DashboardSerializer._upsert_tile(instance, tile_data, button_tile=button_tile)return tile, createdelif tile_data.get("widget", None):widget_json: dict = tile_data.get("widget", {})@@ -3498,14 +3577,17 @@ class DashboardsViewSet(user = cast(User, request.user)with transaction.atomic():- text = tile.text- if "body" in validated:- text.body = validated["body"]- if "agent_context" in validated:- text.agent_context = validated["agent_context"]- text.last_modified_by = user- text.last_modified_at = now()- text.save()+ text_fields = [field for field in ("body", "agent_context") if field in validated]+ if text_fields:+ try:+ text = _copy_text_if_shared(tile)+ except DashboardTile.DoesNotExist:+ raise exceptions.NotFound()+ for field in text_fields:+ setattr(text, field, validated[field])+ text.last_modified_by = user+ text.last_modified_at = now()+ text.save(update_fields=[*text_fields, "last_modified_by", "last_modified_at"])tile_updates: list[str] = []if "layouts" in validated:diff --git a/products/dashboards/backend/models/dashboard_tile.py b/products/dashboards/backend/models/dashboard_tile.pyindex 95e79cc205eb..95b96d844789 100644--- a/products/dashboards/backend/models/dashboard_tile.py+++ b/products/dashboards/backend/models/dashboard_tile.py@@ -235,6 +235,18 @@ class DashboardTile(models.Model):The ``copy_tile`` API still only exposes insight and text tiles; dashboard duplication uses thismethod for all tile types including buttons."""+ # An edit can replace the content reference while this copy waits for the lock.+ if self.text_id is not None or self.button_tile_id is not None:+ try:+ self.refresh_from_db(+ from_queryset=DashboardTile.objects_including_soft_deleted.filter(+ dashboard_id=self.dashboard_id+ ).select_for_update(of=("self",))+ )+ except DashboardTile.DoesNotExist:+ raise ValidationError(+ "The tile is no longer on the source dashboard. Refresh the dashboard and try again."+ )if self.insight is not None:existing = DashboardTile.objects_including_soft_deleted.filter(dashboard=dashboard, insight=self.insight