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(tags): add generic pointer columns to tagged items (#101560)

Yasend24e32b17690
diff --git a/posthog/api/tagged_item.py b/posthog/api/tagged_item.py
index 6b9571dd302e..8d7707c59e10 100644
--- a/posthog/api/tagged_item.py
+++ b/posthog/api/tagged_item.py
@@ -34,7 +34,8 @@ def set_tags_on_object(tags: list[str], obj: Any) -> list[TaggedItem]:
for tag in deduped_tags:
tag_instance, _ = Tag.objects.get_or_create(name=tag, team_id=obj.team_id)
- tagged_item_instance, _ = obj.tagged_items.get_or_create(tag_id=tag_instance.id)
+ # The instance, not the id, so TaggedItem.save() reads the team without re-fetching.
+ tagged_item_instance, _ = obj.tagged_items.get_or_create(tag=tag_instance)
tagged_item_objects.append(tagged_item_instance)
# Delete tags that are missing (use individual deletes to trigger activity logging)
diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
index cacfdd733ba8..b04fa9194dbc 100644
--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
@@ -1761,6 +1761,10 @@
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
"posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id",
"posthog_tag"."id",
"posthog_tag"."name",
"posthog_tag"."team_id"
@@ -2449,6 +2453,10 @@
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
"posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id",
"posthog_tag"."id",
"posthog_tag"."name",
"posthog_tag"."team_id"
@@ -4065,6 +4073,10 @@
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
"posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id",
"posthog_tag"."id",
"posthog_tag"."name",
"posthog_tag"."team_id"
@@ -7433,6 +7445,10 @@
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
"posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id",
"posthog_tag"."id",
"posthog_tag"."name",
"posthog_tag"."team_id"
@@ -8117,6 +8133,10 @@
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
"posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id",
"posthog_tag"."id",
"posthog_tag"."name",
"posthog_tag"."team_id"
@@ -12901,6 +12921,10 @@
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
"posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id",
"posthog_tag"."id",
"posthog_tag"."name",
"posthog_tag"."team_id"
@@ -16348,6 +16372,10 @@
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
"posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id",
"posthog_tag"."id",
"posthog_tag"."name",
"posthog_tag"."team_id"
diff --git a/posthog/migrations/1363_taggeditem_generic_columns.py b/posthog/migrations/1363_taggeditem_generic_columns.py
new file mode 100644
index 000000000000..16d4ed9f0434
--- /dev/null
+++ b/posthog/migrations/1363_taggeditem_generic_columns.py
@@ -0,0 +1,49 @@
+# Generated by Django 5.2.17 on 2026-09-16 10:03
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("contenttypes", "0002_remove_content_type_name"),
+ ("posthog", "1362_identity_provider_oidc"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="taggeditem",
+ name="content_type",
+ field=models.ForeignKey(
+ blank=True,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.PROTECT,
+ related_name="+",
+ to="contenttypes.contenttype",
+ ),
+ ),
+ migrations.AddField(
+ model_name="taggeditem",
+ name="object_id",
+ field=models.IntegerField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="taggeditem",
+ name="object_uuid",
+ field=models.UUIDField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="taggeditem",
+ name="team",
+ field=models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 0baf18c70334..7177ef01da8e 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1362_identity_provider_oidc
+1363_taggeditem_generic_columns
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 5456b01279a7..5bd4c7dad616 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -577,6 +577,8 @@ field_exclusions: dict[AuditableScope, list[str]] = {
"ReplayScanner": [*replay_scanner_machine_fields, "observations", "backfills", "prompt_suggestions", "alerts"],
"VisionAlertConfiguration": [*vision_alert_machine_fields, "events", "matches"],
"DataQualityCheckSchedule": ["subject_type", "subject_uuid", "next_run_at", "last_run_at", "last_suite_run"],
+ # The generic pointer mirrors whichever per-model foreign key is set, so it is never a user edit.
+ "TaggedItem": ["content_type", "object_id", "object_uuid", "team"],
"StamphogRepoConfig": [
# Reverse relation to the repo's review history. The diff would read every pull request row
# on each settings toggle, and none of it is configuration.
diff --git a/posthog/models/activity_logging/tag_utils.py b/posthog/models/activity_logging/tag_utils.py
index 618bc91a099d..cc7ec2efd14d 100644
--- a/posthog/models/activity_logging/tag_utils.py
+++ b/posthog/models/activity_logging/tag_utils.py
@@ -1,5 +1,4 @@
from posthog.dataclasses import frozen
-from posthog.models.tagged_item import RELATED_OBJECTS
@frozen
@@ -10,26 +9,21 @@ class RelatedObjectInfo:
def get_tagged_item_related_object_info(tagged_item) -> RelatedObjectInfo:
- related_object_type = None
- related_object_id = None
- related_object_name = None
+ related_obj = tagged_item.content_object
+ if related_obj is None:
+ return RelatedObjectInfo(type=None, id=None, name=None)
+
+ related_object_type = tagged_item.related_object_type
- for field_name in RELATED_OBJECTS:
- related_obj = getattr(tagged_item, field_name, None)
- if related_obj:
- related_object_type = field_name
-
- if field_name == "insight" and hasattr(related_obj, "short_id"):
- related_object_id = str(related_obj.short_id)
- else:
- related_object_id = str(related_obj.id)
-
- if hasattr(related_obj, "name"):
- related_object_name = related_obj.name
- elif hasattr(related_obj, "title"):
- related_object_name = related_obj.title
- elif hasattr(related_obj, "label"):
- related_object_name = related_obj.label
+ if related_object_type == "insight" and hasattr(related_obj, "short_id"):
+ related_object_id = str(related_obj.short_id)
+ else:
+ related_object_id = str(related_obj.id)
+
+ related_object_name = None
+ for attribute in ("name", "title", "label"):
+ if hasattr(related_obj, attribute):
+ related_object_name = getattr(related_obj, attribute)
break
return RelatedObjectInfo(type=related_object_type, id=related_object_id, name=related_object_name)
diff --git a/posthog/models/tagged_item.py b/posthog/models/tagged_item.py
index c4c90e175e24..3ef95e283754 100644
--- a/posthog/models/tagged_item.py
+++ b/posthog/models/tagged_item.py
@@ -1,9 +1,16 @@
+from collections.abc import Iterable
+from typing import Any
+
from django.core.exceptions import ValidationError
from django.db import models
from posthog.models.activity_logging.model_activity import ModelActivityMixin, get_current_user, get_was_impersonated
+from posthog.models.tag import Tag
+from posthog.models.tagged_item_registry import content_type_for_entry, legacy_field_for, taggable_for_legacy_field
from posthog.models.utils import UUIDTModel, build_partial_uniqueness_constraint, build_unique_relationship_check
+GENERIC_POINTER_FIELDS = ("content_type", "object_id", "object_uuid", "team")
+
RELATED_OBJECTS = (
"dashboard",
"insight",
@@ -21,6 +28,41 @@ RELATED_OBJECTS = (
)
+class TaggedItemQuerySet(models.QuerySet):
+ """Ways of selecting tagged items by what they tag, without naming a column.
+
+ Every method here still reads the per-model foreign keys. They exist so that call sites
+ stop spelling those column names, and so the switch to the generic pointer is a change
+ inside these methods rather than across the codebase.
+ """
+
+ def for_model(self, model: type[models.Model]) -> "TaggedItemQuerySet":
+ """Rows tagging any instance of this model."""
+ # nosemgrep: orm-field-injection -- the name comes from the closed TAGGABLE_MODELS registry, never from input
+ return self.filter(**{f"{legacy_field_for(model)}__isnull": False})
+
+ def for_object(self, obj: models.Model) -> "TaggedItemQuerySet":
+ """Rows tagging this exact instance."""
+ # nosemgrep: orm-field-injection -- the name comes from the closed TAGGABLE_MODELS registry, never from input
+ return self.filter(**{f"{legacy_field_for(type(obj))}_id": obj.pk})
+
+ def for_objects(self, model: type[models.Model], pks: Iterable[Any]) -> "TaggedItemQuerySet":
+ """Rows tagging any of these instances of one model."""
+ # nosemgrep: orm-field-injection -- the name comes from the closed TAGGABLE_MODELS registry, never from input
+ return self.filter(**{f"{legacy_field_for(model)}_id__in": pks})
+
+ def bulk_create(self, objs: Iterable["TaggedItem"], *args: Any, **kwargs: Any) -> list["TaggedItem"]:
+ """Fill the generic pointer on each row, because bulk_create never calls save()."""
+ objs = list(objs)
+ uncached_tag_ids = {obj.tag_id for obj in objs if not TaggedItem.tag.is_cached(obj)}
+ tags = Tag.objects.in_bulk(uncached_tag_ids) if uncached_tag_ids else {}
+ for obj in objs:
+ if obj.tag_id in tags:
+ obj.tag = tags[obj.tag_id]
+ obj.sync_generic_columns()
+ return super().bulk_create(objs, *args, **kwargs)
+
+
class TaggedItem(ModelActivityMixin, UUIDTModel):
"""
Taggable describes global tag-object relationships.
@@ -139,6 +181,31 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):
db_constraint=False,
)
+ # db_index=False on both keys below: Django would build that index non-concurrently
+ # inside the AddField transaction, locking the table.
+ content_type = models.ForeignKey(
+ "contenttypes.ContentType",
+ # A model moving between apps deletes the stale ContentType row, and CASCADE there
+ # would take every tag on that model with it.
+ on_delete=models.PROTECT,
+ null=True,
+ blank=True,
+ related_name="+",
+ db_index=False,
+ )
+ object_id = models.IntegerField(null=True, blank=True)
+ object_uuid = models.UUIDField(null=True, blank=True)
+ team = models.ForeignKey(
+ "posthog.Team",
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ related_name="+",
+ # posthog_team is read on nearly every request, so an inline constraint would lock it.
+ db_constraint=False,
+ db_index=False,
+ )
+
class Meta:
unique_together = ("tag", *RELATED_OBJECTS)
# Make sure to add new key to uniqueness constraint when extending tag functionality to new model
@@ -160,8 +227,53 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):
if sum(map(bool, [getattr(self, o_field) for o_field in RELATED_OBJECTS])) != 1:
raise ValidationError("Exactly one object field must be set.")
+ objects = TaggedItemQuerySet.as_manager()
+
+ @property
+ def related_object_type(self) -> str | None:
+ """Which kind of object this row tags, as the string activity-log rows already hold.
+
+ Activity-log rows persist this value and the frontend describer switches on it, so it
+ stays the old foreign key name rather than becoming a content-type model name.
+ """
+ for legacy_field in RELATED_OBJECTS:
+ if getattr(self, f"{legacy_field}_id", None) is not None:
+ return legacy_field
+ return None
+
+ @property
+ def content_object(self) -> models.Model | None:
+ """The object this row tags."""
+ legacy_field = self.related_object_type
+ return getattr(self, legacy_field) if legacy_field else None
+
+ def sync_generic_columns(self) -> None:
+ """Fill the generic pointer from whichever per-model foreign key is set.
+
+ Reads `<field>_id` rather than `<field>`, so it resolves the target without loading it.
+ """
+ self.content_type = None
+ self.object_id = None
+ self.object_uuid = None
+ for legacy_field in RELATED_OBJECTS:
+ related_id = getattr(self, f"{legacy_field}_id", None)
+ if related_id is None:
+ continue
+
+ entry = taggable_for_legacy_field(legacy_field)
+ if entry is None:
+ continue
+
+ self.content_type = content_type_for_entry(entry)
+ setattr(self, entry.object_field, related_id)
+ self.team_id = self.tag.team_id
+ return
+
def save(self, *args, **kwargs):
self.full_clean()
+ self.sync_generic_columns()
+ if kwargs.get("update_fields"):
+ kwargs["update_fields"] = {*kwargs["update_fields"], *GENERIC_POINTER_FIELDS}
return super().save(*args, **kwargs)
def __str__(self) -> str:
diff --git a/posthog/models/tagged_item_registry.py b/posthog/models/tagged_item_registry.py
new file mode 100644
index 000000000000..a77cc6c990bb
--- /dev/null
+++ b/posthog/models/tagged_item_registry.py
@@ -0,0 +1,135 @@
+"""Which models may carry tags, and how each one is addressed on a TaggedItem row.
+
+TaggedItem points at its object with two typed columns, `object_id` for integer-keyed
+models and `object_uuid` for UUID-keyed ones, rather than the single text column a
+textbook generic relation uses. Postgres has to cast a join column when the two sides
+differ in type, and Django puts that cast on the TaggedItem side, which makes the index
+on the object column unusable for every `tagged_items__...` lookup. Two typed columns
+keep both joins cast-free.
+
+`object_id` is a plain integer even though `Project.id` is a bigint. Project ids are
+drawn from `posthog_team_id_seq`, an integer sequence, so they always fit. Only Project
+pays for the mismatch, with a widening cast that cannot fail. Sizing the column to bigint
+instead would move the cast onto every other integer-keyed model, and make it a narrowing
+cast that can overflow.
+
+This module holds no Django model imports, so it is safe to import from anywhere,
+including `posthog/models/tagged_item.py` itself.
+"""
+
+from __future__ import annotations
+
+from django.apps import apps
+from django.contrib.contenttypes.models import ContentType
+from django.db import models
+
+from posthog.dataclasses import frozen
+
+OBJECT_ID = "object_id"
+OBJECT_UUID = "object_uuid"
+
+
+@frozen
+class TaggableModel:
+ """One taggable model, and the three things tag code needs to know about it."""
+
+ model_label: str
+ """Django `app_label.ModelName`, resolved lazily so this module imports no models."""
+
+ legacy_field: str
+ """The pre-generic-relation foreign key name on TaggedItem.
+
+ This string is also persisted in activity-log rows as `related_object_type`, and the
+ frontend describer switches on it, so it must keep its exact spelling even after the
+ foreign key column is gone.
+ """
+
+ object_field: str
+ """Which typed column on TaggedItem holds this model's primary key."""
+
+
+TAGGABLE_MODELS: tuple[TaggableModel, ...] = (
+ TaggableModel(model_label="dashboards.Dashboard", legacy_field="dashboard", object_field=OBJECT_ID),
+ TaggableModel(model_label="product_analytics.Insight", legacy_field="insight", object_field=OBJECT_ID),
+ TaggableModel(
+ model_label="event_definitions.EventDefinition", legacy_field="event_definition", object_field=OBJECT_UUID
+ ),
+ TaggableModel(
+ model_label="event_definitions.PropertyDefinition", legacy_field="property_definition", object_field=OBJECT_UUID
+ ),
+ TaggableModel(model_label="actions.Action", legacy_field="action", object_field=OBJECT_ID),
+ TaggableModel(model_label="feature_flags.FeatureFlag", legacy_field="feature_flag", object_field=OBJECT_ID),
+ TaggableModel(
+ model_label="experiments.ExperimentSavedMetric",
+ legacy_field="experiment_saved_metric",
+ object_field=OBJECT_ID,
+ ),
+ TaggableModel(model_label="conversations.Ticket", legacy_field="ticket", object_field=OBJECT_UUID),
+ TaggableModel(model_label="customer_analytics.Account", legacy_field="account", object_field=OBJECT_UUID),
+ TaggableModel(model_label="endpoints.Endpoint", legacy_field="endpoint", object_field=OBJECT_UUID),
+ TaggableModel(model_label="replay_vision.ReplayScanner", legacy_field="replay_scanner", object_field=OBJECT_UUID),
+ TaggableModel(model_label="posthog.Project", legacy_field="project", object_field=OBJECT_ID),
+ TaggableModel(model_label="experiments.Experiment", legacy_field="experiment", object_field=OBJECT_ID),
+)
+
+_BY_LABEL: dict[str, TaggableModel] = {entry.model_label: entry for entry in TAGGABLE_MODELS}
+_BY_LEGACY_FIELD: dict[str, TaggableModel] = {entry.legacy_field: entry for entry in TAGGABLE_MODELS}
+
+
+class NotTaggableError(ValueError):
+ """Raised when tag code is handed a model that the registry does not list."""
+
+
+def taggable_for(model: type[models.Model]) -> TaggableModel | None:
+ """The registry entry for a model, or None when the model is not taggable.
+
+ A multi-table-inheritance child resolves to its registered base. `EnterpriseEventDefinition`
+ therefore answers with the `EventDefinition` entry. Django resolves a generic relation's
+ content type from the instance's own class, so without this every enterprise definition
+ would tag itself under a second content type and its tags would stop matching the ones
+ written through the base model's API.
+ """
+ for klass in model.__mro__:
+ meta = getattr(klass, "_meta", None)
+ entry = _BY_LABEL.get(getattr(meta, "label", ""))
+ if entry is not None:
+ return entry
+ return None
+
+
+def require_taggable(model: type[models.Model]) -> TaggableModel:
+ """The registry entry for a model, raising when it is not taggable."""
+ entry = taggable_for(model)
+ if entry is None:
+ raise NotTaggableError(f"{model._meta.label} is not a taggable model. Add it to TAGGABLE_MODELS.")
+ return entry
+
+
+def taggable_for_legacy_field(legacy_field: str) -> TaggableModel | None:
+ """The registry entry for a pre-generic-relation foreign key name."""
+ return _BY_LEGACY_FIELD.get(legacy_field)
+
+
+def base_model_for(model: type[models.Model]) -> type[models.Model]:
+ """The registered base model a taggable model resolves to."""
+ return apps.get_model(require_taggable(model).model_label)
+
+
+def content_type_for(model: type[models.Model]) -> ContentType:
+ """The content type a tag on this model is stored under, always the registered base."""
+ return content_type_for_entry(require_taggable(model))
+
+
+def content_type_for_entry(entry: TaggableModel) -> ContentType:
+ """The content type for a registry entry, without needing the model class in hand."""
+ return ContentType.objects.get_for_model(apps.get_model(entry.model_label))
+
+
+def object_column_for(model: type[models.Model]) -> str:
+ """Which typed column on TaggedItem holds this model's primary key."""
+ return require_taggable(model).object_field
+
+
+def legacy_field_for(model: type[models.Model]) -> str:
+ """The activity-log `related_object_type` string for this model."""
+ return require_taggable(model).legacy_field
diff --git a/posthog/models/test/test_tagged_item_model.py b/posthog/models/test/test_tagged_item_model.py
index 7b0542695877..091eb5fbb58a 100644
--- a/posthog/models/test/test_tagged_item_model.py
+++ b/posthog/models/test/test_tagged_item_model.py
@@ -1,12 +1,14 @@
from posthog.test.base import BaseTest
+from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
-from posthog.models import Tag, TaggedItem
+from posthog.models import Tag, TaggedItem, Team
from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.event_definitions.backend.models import EventDefinition
from products.product_analytics.backend.facade.models import Insight
@@ -83,3 +85,140 @@ class TestTaggedItem(BaseTest):
TaggedItem.objects.create(action_id=action.id, tag_id=tag.id)
with self.assertRaises(ValidationError):
TaggedItem.objects.create(action_id=action.id, tag_id=tag.id)
+
+
+class TestTaggedItemGenericColumns(BaseTest):
+ """The generic pointer is filled from whichever per-model foreign key is set.
+
+ Both shapes are written until the migration finishes, so these assert the new columns
+ agree with the old ones rather than replace them.
+ """
+
+ def test_integer_keyed_object_fills_object_id(self):
+ dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
+ tag = Tag.objects.create(name="tag", team_id=self.team.id)
+
+ tagged_item = TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)
+
+ tagged_item.refresh_from_db()
+ assert tagged_item.object_id == dashboard.id
+ assert tagged_item.object_uuid is None
+ assert tagged_item.content_type == ContentType.objects.get_for_model(Dashboard)
+ assert tagged_item.team_id == tag.team_id
+
+ def test_uuid_keyed_object_fills_object_uuid(self):
+ event_definition = EventDefinition.objects.create(team=self.team, name="event")
+ tag = Tag.objects.create(name="tag", team_id=self.team.id)
+
+ tagged_item = TaggedItem.objects.create(event_definition_id=event_definition.id, tag_id=tag.id)
+
+ tagged_item.refresh_from_db()
+ assert tagged_item.object_uuid == event_definition.id
+ assert tagged_item.object_id is None
+ assert tagged_item.content_type == ContentType.objects.get_for_model(EventDefinition)
+ assert tagged_item.team_id == tag.team_id
+
+ def test_enterprise_definition_stores_the_base_content_type(self):
+ """An enterprise definition must not create a second content type for its tags."""
+ try:
+ from ee.models import EnterpriseEventDefinition
+ except ImportError:
+ self.skipTest("needs the ee app")
+
+ event_definition = EnterpriseEventDefinition.objects.create(team=self.team, name="enterprise event")
+ tag = Tag.objects.create(name="tag", team_id=self.team.id)
+
+ tagged_item = TaggedItem.objects.create(event_definition_id=event_definition.id, tag_id=tag.id)
+
+ tagged_item.refresh_from_db()
+ assert tagged_item.content_type == ContentType.objects.get_for_model(EventDefinition)
+ assert tagged_item.content_type != ContentType.objects.get_for_model(EnterpriseEventDefinition)
+ assert tagged_item.object_uuid == event_definition.id
+
+ def test_bulk_create_fills_the_generic_columns(self):
+ """bulk_create never calls save(), and the Zendesk import writes ticket tags through it."""
+ dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
+ event_definition = EventDefinition.objects.create(team=self.team, name="event")
+ tag = Tag.objects.create(name="tag", team_id=self.team.id)
+
+ TaggedItem.objects.bulk_create(
+ [TaggedItem(tag=tag, dashboard=dashboard), TaggedItem(tag=tag, event_definition=event_definition)]
+ )
+
+ by_type = {item.related_object_type: item for item in TaggedItem.objects.filter(tag=tag)}
+ assert by_type["dashboard"].object_id == dashboard.id
+ assert by_type["dashboard"].content_type == ContentType.objects.get_for_model(Dashboard)
+ assert by_type["event_definition"].object_uuid == event_definition.id
+ assert by_type["event_definition"].content_type == ContentType.objects.get_for_model(EventDefinition)
+ assert all(item.team_id == tag.team_id for item in by_type.values())
+
+ def test_bulk_create_loads_uncached_tags_once(self):
+ dashboards = [Dashboard.objects.create(team_id=self.team.id, name=f"dashboard {i}") for i in range(3)]
+ tag = Tag.objects.create(name="tag", team_id=self.team.id)
+ rows = [TaggedItem(tag_id=tag.id, dashboard=dashboard) for dashboard in dashboards]
+ ContentType.objects.get_for_model(Dashboard)
+
+ with self.assertNumQueries(2):
+ TaggedItem.objects.bulk_create(rows)
+
+ assert all(row.team_id == tag.team_id for row in rows)
+
+ def test_retargeting_a_row_clears_the_other_object_column(self):
+ dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
+ event_definition = EventDefinition.objects.create(team=self.team, name="event")
+ tag = Tag.objects.create(name="tag", team_id=self.team.id)
+ tagged_item = TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)
+
+ tagged_item.dashboard = None
+ tagged_item.event_definition = event_definition
+ tagged_item.sync_generic_columns()
+
+ assert tagged_item.object_id is None
+ assert tagged_item.object_uuid == event_definition.id
+ assert tagged_item.content_type == ContentType.objects.get_for_model(EventDefinition)
+
+ def test_save_with_update_fields_persists_the_generic_columns(self):
+ dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
+ tag = Tag.objects.create(name="tag", team_id=self.team.id)
+ tagged_item = TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)
+ TaggedItem.objects.filter(pk=tagged_item.pk).update(content_type=None, object_id=None, team=None)
+
+ tagged_item = TaggedItem.objects.get(pk=tagged_item.pk)
+ tagged_item.save(update_fields=["tag"])
+
+ tagged_item.refresh_from_db()
+ assert tagged_item.object_id == dashboard.id
+ assert tagged_item.content_type == ContentType.objects.get_for_model(Dashboard)
+ assert tagged_item.team_id == tag.team_id
+
+ def test_team_follows_the_tag(self):
+ dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ tagged_item = TaggedItem.objects.create(
+ dashboard_id=dashboard.id, tag=Tag.objects.create(name="tag", team_id=self.team.id)
+ )
+
+ tagged_item.tag = Tag.objects.create(name="tag", team_id=other_team.id)
+ tagged_item.sync_generic_columns()
+
+ assert tagged_item.team_id == other_team.id
+
+ def test_helpers_report_the_tagged_object(self):
+ insight = Insight.objects.create(filters={"events": [{"id": "$pageview"}]}, team_id=self.team.id)
+ tag = Tag.objects.create(name="tag", team_id=self.team.id)
+
+ tagged_item = TaggedItem.objects.create(insight_id=insight.id, tag_id=tag.id)
+
+ assert tagged_item.related_object_type == "insight"
+ assert tagged_item.content_object == insight
+
+ def test_queryset_helpers_select_by_object(self):
+ dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
+ other_dashboard = Dashboard.objects.create(team_id=self.team.id, name="other dashboard")
+ tag = Tag.objects.create(name="tag", team_id=self.team.id)
+ tagged_item = TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)
+ TaggedItem.objects.create(dashboard_id=other_dashboard.id, tag_id=tag.id)
+
+ assert list(TaggedItem.objects.for_object(dashboard)) == [tagged_item]
+ assert TaggedItem.objects.for_model(Dashboard).count() == 2
+ assert list(TaggedItem.objects.for_objects(Dashboard, [dashboard.id])) == [tagged_item]
diff --git a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
index 76659c3a842f..d360708058ad 100644
--- a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
+++ b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
@@ -302,7 +302,11 @@
"posthog_taggeditem"."endpoint_id",
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id"
+ "posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id"
FROM "posthog_taggeditem"
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
@@ -323,7 +327,11 @@
"posthog_taggeditem"."endpoint_id",
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id"
+ "posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id"
FROM "posthog_taggeditem"
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
@@ -1227,7 +1235,11 @@
"posthog_taggeditem"."endpoint_id",
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id"
+ "posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id"
FROM "posthog_taggeditem"
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
@@ -1248,7 +1260,11 @@
"posthog_taggeditem"."endpoint_id",
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id"
+ "posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id"
FROM "posthog_taggeditem"
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
diff --git a/posthog/test/repo_invariants/test_taggable_registry.py b/posthog/test/repo_invariants/test_taggable_registry.py
new file mode 100644
index 000000000000..2eb441396155
--- /dev/null
+++ b/posthog/test/repo_invariants/test_taggable_registry.py
@@ -0,0 +1,79 @@
+import pytest
+
+from django.apps import apps
+from django.db import models
+
+from posthog.models.tagged_item import RELATED_OBJECTS, TaggedItem
+from posthog.models.tagged_item_registry import (
+ OBJECT_ID,
+ OBJECT_UUID,
+ TAGGABLE_MODELS,
+ TaggableModel,
+ base_model_for,
+ taggable_for,
+)
+
+INTEGER_FIELDS = (models.AutoField, models.IntegerField, models.BigAutoField, models.BigIntegerField)
+
+
+def _model_for(entry: TaggableModel) -> type[models.Model]:
+ return apps.get_model(entry.model_label)
+
+
+def test_registry_matches_the_foreign_key_fields() -> None:
+ assert {entry.legacy_field for entry in TAGGABLE_MODELS} == set(RELATED_OBJECTS)
+
+
+def test_registry_entries_are_unique() -> None:
+ labels = [entry.model_label for entry in TAGGABLE_MODELS]
+ legacy_fields = [entry.legacy_field for entry in TAGGABLE_MODELS]
+ assert len(set(labels)) == len(labels)
+ assert len(set(legacy_fields)) == len(legacy_fields)
+
+
[email protected]("entry", TAGGABLE_MODELS, ids=lambda entry: entry.legacy_field)
+def test_object_column_matches_the_primary_key_type(entry: TaggableModel) -> None:
+ """A mismatch here would make Postgres cast the object column and stop using its index."""
+ primary_key = _model_for(entry)._meta.pk
+ assert primary_key is not None
+
+ if entry.object_field == OBJECT_UUID:
+ assert isinstance(primary_key, models.UUIDField), (
+ f"{entry.model_label} has a {type(primary_key).__name__} primary key, so it belongs on {OBJECT_ID}"
+ )
+ else:
+ assert isinstance(primary_key, INTEGER_FIELDS), (
+ f"{entry.model_label} has a {type(primary_key).__name__} primary key, so it belongs on {OBJECT_UUID}"
+ )
+
+
[email protected]("entry", TAGGABLE_MODELS, ids=lambda entry: entry.legacy_field)
+def test_registry_points_at_the_same_model_as_the_foreign_key(entry: TaggableModel) -> None:
+ assert TaggedItem._meta.get_field(entry.legacy_field).related_model is _model_for(entry)
+
+
[email protected]("entry", TAGGABLE_MODELS, ids=lambda entry: entry.legacy_field)
+def test_object_column_holds_the_primary_key_range(entry: TaggableModel) -> None:
+ """`object_id` is a plain integer, so a bigint-keyed model must still fit inside it."""
+ if entry.object_field != OBJECT_ID:
+ return
+ assert isinstance(TaggedItem._meta.get_field(OBJECT_ID), models.IntegerField)
+
+
+def test_inherited_models_resolve_to_their_registered_base() -> None:
+ """Django reads a generic relation's content type off the instance's own class.
+
+ Without this resolution an enterprise definition would store its tags under a second
+ content type, and they would stop matching the tags written through the base model.
+ """
+ if not apps.is_installed("ee"):
+ pytest.skip("needs the ee app")
+ enterprise_event_definition = apps.get_model("ee.EnterpriseEventDefinition")
+ enterprise_property_definition = apps.get_model("ee.EnterprisePropertyDefinition")
+
+ assert base_model_for(enterprise_event_definition) is apps.get_model("event_definitions.EventDefinition")
+ assert base_model_for(enterprise_property_definition) is apps.get_model("event_definitions.PropertyDefinition")
+
+
+def test_unregistered_models_are_not_taggable() -> None:
+ assert taggable_for(apps.get_model("posthog.Team")) is None
diff --git a/products/actions/backend/api/test/__snapshots__/test_action.ambr b/products/actions/backend/api/test/__snapshots__/test_action.ambr
index 1404a7c56e5c..cbf52b699080 100644
--- a/products/actions/backend/api/test/__snapshots__/test_action.ambr
+++ b/products/actions/backend/api/test/__snapshots__/test_action.ambr
@@ -478,6 +478,10 @@
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
"posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id",
"posthog_tag"."id",
"posthog_tag"."name",
"posthog_tag"."team_id"
@@ -1111,6 +1115,10 @@
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
"posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id",
"posthog_tag"."id",
"posthog_tag"."name",
"posthog_tag"."team_id"
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
index 3c2085c9a418..a3fec10ac71d 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
@@ -800,6 +800,10 @@
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
"posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id",
"posthog_tag"."id",
"posthog_tag"."name",
"posthog_tag"."team_id"
diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
index d919437f91d3..12335fb84870 100644
--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
@@ -1309,7 +1309,11 @@
"posthog_taggeditem"."endpoint_id",
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id"
+ "posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id"
FROM "posthog_taggeditem"
WHERE "posthog_taggeditem"."insight_id" IN (1,
2,
@@ -1335,6 +1339,10 @@
"posthog_taggeditem"."replay_scanner_id",
"posthog_taggeditem"."project_id",
"posthog_taggeditem"."experiment_id",
+ "posthog_taggeditem"."content_type_id",
+ "posthog_taggeditem"."object_id",
+ "posthog_taggeditem"."object_uuid",
+ "posthog_taggeditem"."team_id",
"posthog_tag"."id",
"posthog_tag"."name",
"posthog_tag"."team_id"