: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
feat(projects): let projects carry tags (#92307)
Yasen0659b35bfac4
diff --git a/ee/api/test/test_project.py b/ee/api/test/test_project.pyindex 217b444a1fc7..ab9874265462 100644--- a/ee/api/test/test_project.py+++ b/ee/api/test/test_project.py@@ -177,6 +177,7 @@ class TestProjectEnterpriseAPI(team_enterprise_api_test_factory()): # type: ign"is_demo": False,"timezone": "UTC","access_control": False,+ "tags": [],}],)diff --git a/ee/api/test/test_team.py b/ee/api/test/test_team.pyindex d83d9c324e08..f4e0f9414b76 100644--- a/ee/api/test/test_team.py+++ b/ee/api/test/test_team.py@@ -326,6 +326,7 @@ class TestTeamEnterpriseAPI(team_enterprise_api_test_factory()): # type: ignore"is_demo": False,"timezone": "UTC","access_control": False,+ "tags": [],}],)diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 212673ab965f..22eba92ebf90 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8397,9 +8397,9 @@ snapshots:scenes-app-settings-environment--settings-environment-csp-reporting--light:hash: v1.k794b7964.a842c3f0ee5a6731d1051c47f04fd6da35d42f85cc3e0ba40afba80d2ea66b91.uj0d249fCiw0N7_QZI0owaFQ77omJCKRsMDMnmJrX5kscenes-app-settings-environment--settings-environment-customization--dark:- hash: v1.k794b7964.20a4c0114ee5bc5239d8f7379d3b524fab7792f5cbe4e955af67f2b628c6740a.B2_rKR1OO-ZWVFAXJIorDCuW7DQI7cccnguK9OQ1crQ+ hash: v1.k794b7964.1a38cfe1271e4a9f6290e392d9a6f4e3cd8847fe2dcdff60bb5bd31f01f6471f.KffiFQt4EKsxI1Rbjs7yMoIbB6QRSkml34IlulQ72Zsscenes-app-settings-environment--settings-environment-customization--light:- hash: v1.k794b7964.90efacec6b8b33b059eb3574c8379b997f3774b71a6b8b5f044abacceab629d6.dE0G8aMXIav3GKTW7wwf0rXCFnhSzF2YCOLu3nRtvu8+ hash: v1.k794b7964.35c10ee15e7424fb6966da088d7edb955e71e88e87288b71cfe0be2733d2a51c.pBLStD_u8lE5z1PuMkA3GGkSoFc4YNU1y-Q6-WDsBcgscenes-app-settings-environment--settings-environment-danger-zone--dark:hash: v1.k794b7964.586910a373b9a9cf63d114f527d0bb8580033d25a81be6f830e07bf244a7c316.-ID92-MgwgAf0sdCeF84tYBSJ1RcHGOvApRVSsJNYeEscenes-app-settings-environment--settings-environment-danger-zone--light:@@ -8524,6 +8524,10 @@ snapshots:hash: v1.k794b7964.8defefc8ee81d152212ad970ee03afd0170e149183c700875620b83c94041edb.5f5prfRZbGCHJZ5SXwCfvu5BsuOjCWSch49ouOMP4iUscenes-app-settings-project--settings-project-autocapture--light:hash: v1.k794b7964.397d4848babe9a8d2fd98b15ffe998d685521cb5135ff4ad1a70951e6062ec71.HMYh2-IfWjQd_PDBPGoPGrX_LVi2OHg7wzBFzJAmslA+ scenes-app-settings-project--settings-project-customization--dark:+ hash: v1.k794b7964.1a38cfe1271e4a9f6290e392d9a6f4e3cd8847fe2dcdff60bb5bd31f01f6471f.OVv8zCjGPjX8-NsbhgGEY8SivN_0m3yn6SwTMqF6CN0+ scenes-app-settings-project--settings-project-customization--light:+ hash: v1.k794b7964.35c10ee15e7424fb6966da088d7edb955e71e88e87288b71cfe0be2733d2a51c.Lf9oEEP9gWth52aeJ2143IvfkEAylnHS6pEtzIFvmhQscenes-app-settings-project--settings-project-danger-zone--dark:hash: v1.k794b7964.d18bc16d7f8d14a2168e67a889a5229659191e35393f829ce1b5eb6c0876a269.nQC3Mf7fvxzoZTD0m9ndbrfXV9nQin3tsW49wkX6Zqkscenes-app-settings-project--settings-project-danger-zone--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 1119192d5b3f..000b3937e90e 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -616,6 +616,11 @@ export interface ProjectBackwardCompatBasicApi {readonly is_demo: booleanreadonly timezone: stringreadonly access_control: boolean+ /**+ * Labels applied to this project.+ * @items.maxLength 255+ */+ readonly tags: readonly string[]}export interface PaginatedProjectBackwardCompatBasicListApi {@@ -1817,7 +1822,10 @@ export const CookielessServerHashModeEnumApi = {} as const/**- * Mixin for serializers to add user access control fields+ * A project and its settings, including the settings that live on its passthrough Team.+ *+ * This shape is a superset of TeamSerializer's, so a request rewritten from /api/environments/+ * onto /api/projects/ never loses a field.*/export interface ProjectBackwardCompatApi {readonly id: number@@ -1834,6 +1842,11 @@ export interface ProjectBackwardCompatApi {* @nullable*/product_description?: string | null+ /**+ * Labels applied to this project. Names are trimmed and lowercased, and sending this field replaces the project's existing tags.+ * @items.maxLength 255+ */+ tags?: string[]readonly created_at: stringreadonly effective_membership_level: OrganizationMembershipLevelEnumApireadonly has_group_types: boolean@@ -2669,7 +2682,10 @@ export type PatchedProjectBackwardCompatApiProductIntentsItem = {export type PatchedProjectBackwardCompatApiManagedViewsets = { [key: string]: boolean }/**- * Mixin for serializers to add user access control fields+ * A project and its settings, including the settings that live on its passthrough Team.+ *+ * This shape is a superset of TeamSerializer's, so a request rewritten from /api/environments/+ * onto /api/projects/ never loses a field.*/export interface PatchedProjectBackwardCompatApi {readonly id?: number@@ -2686,6 +2702,11 @@ export interface PatchedProjectBackwardCompatApi {* @nullable*/product_description?: string | null+ /**+ * Labels applied to this project. Names are trimmed and lowercased, and sending this field replaces the project's existing tags.+ * @items.maxLength 255+ */+ tags?: string[]readonly created_at?: stringreadonly effective_membership_level?: OrganizationMembershipLevelEnumApireadonly has_group_types?: boolean@@ -5138,8 +5159,24 @@ export type OrganizationsProjectsListParams = {* A search term.*/search?: string+ /**+ * Comma-separated tag names to filter by, for example `production,eu-region`. Names are trimmed and lowercased before matching. At most 20 distinct tags per request.+ */+ tags?: string+ /**+ * How to combine the `tags` filter. `all` (the default) returns projects carrying every listed tag; `any` returns projects carrying at least one.+ */+ tags_match?: OrganizationsProjectsListTagsMatch}+export type OrganizationsProjectsListTagsMatch =+ (typeof OrganizationsProjectsListTagsMatch)[keyof typeof OrganizationsProjectsListTagsMatch]++export const OrganizationsProjectsListTagsMatch = {+ All: 'all',+ Any: 'any',+} as const+export type OrganizationsProjectsEventIngestionRestrictionsListParams = {/*** A search term.diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 2b9e1364ba80..9a7366f2c8bb 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -139,13 +139,7 @@ import {} from './environment/SessionRecordingSettings'import { SurveyDefaultAppearance, SurveyEnableToggle } from './environment/SurveySettings'import { TeamAccessControl } from './environment/TeamAccessControl'-import {- TeamAuthorizedURLs,- TeamBusinessModel,- TeamDisplayName,- TeamTimezone,- TeamVariables,-} from './environment/TeamSettings'+import { TeamAuthorizedURLs, TeamBusinessModel, TeamTimezone, TeamVariables } from './environment/TeamSettings'import { ProjectAccountFiltersSetting } from './environment/TestAccountFiltersConfig'import { UsageMetricsConfig } from './environment/UsageMetricsConfig'import { WebAnalyticsEnablePreAggregatedTables } from './environment/WebAnalyticsAPISetting'@@ -171,6 +165,7 @@ import { OrganizationVariables } from './organization/OrgVariables'import { EnforceVerifiedDomains } from './organization/VerifiedDomains/EnforceVerifiedDomains'import { VerifiedDomains } from './organization/VerifiedDomains/VerifiedDomains'import { ProjectDangerZone } from './project/ProjectDangerZone'+import { ProjectDetails } from './project/ProjectDetails'import { ProjectMove } from './project/ProjectMove'import { ProjectSecretAPIKeys } from './project/ProjectSecretAPIKeys'import { SettingSection } from './types'@@ -288,10 +283,10 @@ export const SETTINGS_MAP: SettingSection[] = [settings: [{id: 'display-name',- title: 'Display name',- description: 'A human-friendly name for this environment.',- component: <TeamDisplayName />,- keywords: ['name', 'rename', 'label'],+ title: 'Project details',+ description: 'Name this project and label it so you can group and find it across your organization.',+ component: <ProjectDetails />,+ keywords: ['name', 'rename', 'label', 'tag', 'tags'],},{id: 'date-and-time',diff --git a/frontend/src/scenes/settings/project/ProjectDetails.tsx b/frontend/src/scenes/settings/project/ProjectDetails.tsxnew file mode 100644index 000000000000..2a3cc27bc2c5--- /dev/null+++ b/frontend/src/scenes/settings/project/ProjectDetails.tsx@@ -0,0 +1,19 @@+import { LemonLabel } from 'lib/lemon-ui/LemonLabel'+import { TeamDisplayName } from 'scenes/settings/environment/TeamSettings'++import { ProjectTags } from './ProjectTags'++export function ProjectDetails(): JSX.Element {+ return (+ <div className="flex flex-col gap-4 max-w-160">+ <div className="flex flex-col gap-1">+ <LemonLabel>Display name</LemonLabel>+ <TeamDisplayName />+ </div>+ <div className="flex flex-col gap-1">+ <LemonLabel>Tags</LemonLabel>+ <ProjectTags />+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/settings/project/ProjectTags.tsx b/frontend/src/scenes/settings/project/ProjectTags.tsxnew file mode 100644index 000000000000..2a9248c20582--- /dev/null+++ b/frontend/src/scenes/settings/project/ProjectTags.tsx@@ -0,0 +1,40 @@+import { useActions, useValues } from 'kea'++import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'+import { useRestrictedArea, RestrictionScope } from 'lib/components/RestrictedArea'+import { TeamMembershipLevel } from 'lib/constants'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { projectLogic } from 'scenes/projectLogic'++import { tagsModel } from '~/models/tagsModel'++export function ProjectTags(): JSX.Element {+ const { currentProject, currentProjectLoading } = useValues(projectLogic)+ const { updateCurrentProject } = useActions(projectLogic)+ const { tags: tagsAvailable } = useValues(tagsModel)++ // Projects carry no resource-level access controls, so tag writes are gated by project+ // membership, which is exactly what the API's own permission check requires.+ const restrictionReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Member,+ })++ if (!currentProject) {+ return <LemonSkeleton className="w-40 h-5" />+ }++ if (restrictionReason) {+ return <ObjectTags tags={currentProject.tags ?? []} staticOnly data-attr="project-tags" />+ }++ return (+ <ObjectTags+ tags={currentProject.tags ?? []}+ tagsAvailable={tagsAvailable}+ onChange={(tags) => updateCurrentProject({ tags })}+ saving={currentProjectLoading}+ data-attr="project-tags"+ />+ )+}diff --git a/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx b/frontend/src/scenes/settings/stories/SettingsProject.stories.tsxindex 04b553ef369e..3dbfd52defe9 100644--- a/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx+++ b/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx@@ -40,6 +40,8 @@ const meta: Meta<(props: StoryProps) => JSX.Element> = {personal_github_connected: false,},'/api/users/@me/integrations/github/install_requests/': { results: [], install_url: null },+ // The tags field autocompletes from this; unmocked, its error toast lands in the snapshot.+ '/api/projects/:id/tags': ['eu-region', 'production'],},patch: {'/api/projects/:id': async ({ request }) => {@@ -65,6 +67,8 @@ export default metaexport const SettingsProjectDetails: Story = { args: { sectionId: 'project-details' } }+export const SettingsProjectCustomization: Story = { args: { sectionId: 'project-customization' } }+export const SettingsProjectDangerZone: Story = { args: { sectionId: 'project-danger-zone' } }// -- Project (legacy) --diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 5a82e6c03532..074f19c91b99 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -723,6 +723,7 @@ export interface CorrelationConfigType {export interface ProjectType extends ProjectBasicType {created_at: stringis_pending_deletion: boolean+ tags?: string[]}export interface TeamSurveyConfigType {diff --git a/posthog/api/project.py b/posthog/api/project.pyindex b995da1ae188..01bbc951e8bd 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -19,8 +19,10 @@ from rest_framework.permissions import BasePermission, IsAuthenticatedfrom posthog.schema import ProductKey+from posthog.api import project_tagsfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import ProjectBackwardCompatBasicSerializer+from posthog.api.tagged_item import TaggedItemSerializerMixin# These are imported from team.py for now. They are part of the legacy /api/environments/ surface and are# expected to move project-side (or to a neutral module) in a later PR once /api/environments/ is retired —@@ -531,10 +533,18 @@ class ProjectSerializer(serializers.ModelSerializer):class ProjectBackwardCompatSerializer(+ TaggedItemSerializerMixin,UserAccessControlSerializerMixin,ProjectBackwardCompatBasicSerializer,UserPermissionsSerializerMixin,):+ """A project and its settings, including the settings that live on its passthrough Team.++ This shape is a superset of TeamSerializer's, so a request rewritten from /api/environments/+ onto /api/projects/ never loses a field.+ """++ tags = project_tags.tags_field()effective_membership_level = serializers.SerializerMethodField() # Compat with TeamSerializerhas_group_types = serializers.SerializerMethodField() # Compat with TeamSerializergroup_types = serializers.SerializerMethodField() # Compat with TeamSerializer@@ -599,6 +609,7 @@ class ProjectBackwardCompatSerializer("organization","name","product_description",+ "tags","created_at","effective_membership_level", # Compat with TeamSerializer"has_group_types", # Compat with TeamSerializer@@ -1067,6 +1078,8 @@ class ProjectBackwardCompatSerializer():validated_data.pop(config_field, None)+ tags = validated_data.pop("tags", None) # tags are created separately below as global tag relationships+serializers.raise_errors_on_nested_writes("create", self, validated_data)request = self.context["request"]@@ -1114,9 +1127,19 @@ class ProjectBackwardCompatSerializer(detail=Detail(name=str(team.name)),)+ # Replacing tags is several inserts, deletes and an orphan cleanup. Without a transaction a+ # failure part way through leaves the project holding a mix of old and new tags.+ with transaction.atomic():+ self._attempt_set_tags(tags, project)+return projectdef update(self, instance: Project, validated_data: dict[str, Any]) -> Project:+ # Unlike the other taggable serializers, this update() never delegates to super().update():+ # the passthrough loop below setattr()s everything left in validated_data onto the Project+ # or its Team. So tags come out here and are written at the end.+ tags = validated_data.pop("tags", None)+team = instance.passthrough_teamteam_before_update = team.__dict__.copy()project_before_update = instance.__dict__.copy()@@ -1290,11 +1313,18 @@ class ProjectBackwardCompatSerializer(team,)+ # As in create(): the tag replacement is all-or-nothing.+ with transaction.atomic():+ self._attempt_set_tags(tags, instance)+return instance@extend_schema(extensions={"x-product": "core"})@extend_schema_view(+ list=extend_schema(+ parameters=project_tags.LIST_FILTER_PARAMETERS,+ ),retrieve=extend_schema(description=("Retrieve a project and its settings."),),@@ -1319,7 +1349,14 @@ class ProjectViewSet(scope_object: APIScopeObjectOrNotSupported = "project"serializer_class = ProjectBackwardCompatSerializer- queryset = Project.objects.all().select_related("organization").prefetch_related("teams")+ queryset = (+ Project.objects.all()+ .select_related("organization")+ .prefetch_related(+ "teams",+ project_tags.prefetch(),+ )+ )lookup_field = "id"ordering = "-created_by"filter_backends = [PhraseSearchFilter]@@ -1331,6 +1368,7 @@ class ProjectViewSet(queryset = queryset.filter(id__in=visible_teams_ids)if scoped_organizations := get_authenticator_scoped_organization_ids(self.request.successful_authenticator):queryset = queryset.filter(organization_id__in=scoped_organizations)+ queryset = project_tags.filter_queryset(queryset, self.request.query_params)return querysetdef get_serializer_class(self) -> type[serializers.BaseSerializer]:@@ -1342,6 +1380,26 @@ class ProjectViewSet(super().perform_create(serializer)project = cast(Project, serializer.instance)self._notify_org_admins_of_member_project_creation(project)+ if "tags" in serializer.initial_data:+ project_tags.report_change(+ user=cast(User, self.request.user),+ project=project,+ tags_before=set(),+ tags_after=project_tags.current_names(project),+ )++ def perform_update(self, serializer: serializers.BaseSerializer) -> None:+ project = cast(Project, serializer.instance)+ # Read the old names before saving: the tag write replaces the prefetch this reads from.+ tags_before = project_tags.current_names(project) if "tags" in serializer.initial_data else None+ super().perform_update(serializer)+ if tags_before is not None:+ project_tags.report_change(+ user=cast(User, self.request.user),+ project=project,+ tags_before=tags_before,+ tags_after=project_tags.current_names(project),+ )def _notify_org_admins_of_member_project_creation(self, project: Project) -> None:"""When a member (below admin) creates a project, notify org admins/owners in-app. Best-effort."""diff --git a/posthog/api/project_tags.py b/posthog/api/project_tags.pynew file mode 100644index 000000000000..1a0f0b7bb6ba--- /dev/null+++ b/posthog/api/project_tags.py@@ -0,0 +1,126 @@+"""Tagging for projects: the `tags` field, the list filter, and the analytics around both.++The pieces live here rather than in `project.py` so that module keeps to project settings.+`project.py` is the only caller.+"""++from typing import Any++from django.db.models import Prefetch, QuerySet++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter+from rest_framework import exceptions, serializers++from posthog.event_usage import report_user_action+from posthog.models.project import Project+from posthog.models.tag import tagify+from posthog.models.tagged_item import TaggedItem+from posthog.models.user import User++TAGS_HELP_TEXT = (+ "Labels applied to this project. Names are trimmed and lowercased, and sending this field "+ "replaces the project's existing tags."+)++MATCH_MODES = ("all", "any")++# "all" adds one join per tag, so an unbounded list would hand Postgres a query plan that grows+# with whatever a caller puts in the query string.+MAX_TAGS_PER_FILTER = 20++# Query parameters for the project list, declared so they reach the generated clients.+LIST_FILTER_PARAMETERS = [+ OpenApiParameter(+ name="tags",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ description=(+ "Comma-separated tag names to filter by, for example `production,eu-region`. "+ f"Names are trimmed and lowercased before matching. At most {MAX_TAGS_PER_FILTER} "+ "distinct tags per request."+ ),+ ),+ OpenApiParameter(+ name="tags_match",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ enum=list(MATCH_MODES),+ description=(+ "How to combine the `tags` filter. `all` (the default) returns projects carrying "+ "every listed tag; `any` returns projects carrying at least one."+ ),+ ),+]+++def tags_field() -> serializers.ListField:+ """The writable `tags` field shared by the project detail and list serializers."""+ return serializers.ListField(+ child=serializers.CharField(max_length=255),+ required=False,+ help_text=TAGS_HELP_TEXT,+ )+++def prefetch() -> Prefetch:+ """Load each project's tags in one query, under the attribute the serializers read."""+ return Prefetch("tagged_items", queryset=TaggedItem.objects.select_related("tag"), to_attr="prefetched_tags")+++def current_names(project: Project) -> set[str]:+ """The project's tag names, preferring the prefetch the viewset attaches."""+ if hasattr(project, "prefetched_tags"):+ return {tagged_item.tag.name for tagged_item in project.prefetched_tags}+ return set(project.tagged_items.values_list("tag__name", flat=True))+++def _parse_filter(query_params: Any) -> tuple[list[str], str] | None:+ """Read the `tags` / `tags_match` query pair, or None when no tag filter was asked for."""+ raw = query_params.get("tags")+ if not raw:+ return None+ tags = sorted({tagify(tag) for tag in raw.split(",") if tag.strip()})+ if not tags:+ return None+ if len(tags) > MAX_TAGS_PER_FILTER:+ raise exceptions.ValidationError({"tags": f"Filter by at most {MAX_TAGS_PER_FILTER} tags at a time."})+ match = query_params.get("tags_match", "all")+ if match not in MATCH_MODES:+ raise exceptions.ValidationError({"tags_match": f"Must be one of: {', '.join(MATCH_MODES)}."})+ return tags, match+++def filter_queryset(queryset: QuerySet[Project], query_params: Any) -> QuerySet[Project]:+ """Narrow projects to those carrying every requested tag, or any of them under `tags_match=any`."""+ parsed = _parse_filter(query_params)+ if parsed is None:+ return queryset+ tags, match = parsed+ if match == "any":+ return queryset.filter(tagged_items__tag__name__in=tags).distinct()+ for tag in tags:+ queryset = queryset.filter(tagged_items__tag__name=tag)+ return queryset+++def report_change(*, user: User, project: Project, tags_before: set[str], tags_after: set[str]) -> None:+ """Record a tag edit so adoption and depth of use can be measured after release."""+ added = tags_after - tags_before+ removed = tags_before - tags_after+ if not added and not removed:+ return+ report_user_action(+ user,+ "project tags updated",+ {+ "tags_count_before": len(tags_before),+ "tags_count_after": len(tags_after),+ "tags_added_count": len(added),+ "tags_removed_count": len(removed),+ "is_first_tagging": not tags_before and bool(tags_after),+ "all_tags_removed": bool(tags_before) and not tags_after,+ "organization_project_count": Project.objects.filter(organization_id=project.organization_id).count(),+ },+ team=project.passthrough_team,+ )diff --git a/posthog/api/shared.py b/posthog/api/shared.pyindex 03a3eb07e953..c928f5f8b602 100644--- a/posthog/api/shared.py+++ b/posthog/api/shared.py@@ -120,6 +120,13 @@ class ProjectBackwardCompatBasicSerializer(serializers.ModelSerializer):project_id = serializers.IntegerField(source="id", read_only=True, help_text="ID of the project this environment belongs to.")+ # Project-only: tags label a Project, which environments do not have, so this is not mirrored+ # onto TeamBasicSerializer.+ tags = serializers.ListField(+ child=serializers.CharField(max_length=255),+ read_only=True,+ help_text="Labels applied to this project.",+ )class Meta:model = Project@@ -136,8 +143,9 @@ class ProjectBackwardCompatBasicSerializer(serializers.ModelSerializer):"is_demo", # Compat with TeamSerializer"timezone", # Compat with TeamSerializer"access_control", # Compat with TeamSerializer+ "tags",)- read_only_fields = fields+ read_only_fields = tuple(field for field in fields if field != "tags")team_passthrough_fields = {"uuid","api_token",@@ -219,6 +227,17 @@ class ProjectBackwardCompatBasicSerializer(serializers.ModelSerializer):else:ret[field.field_name] = field.to_representation(attribute)+ # Tags live in a join table rather than on the model, so the loop above skips them.+ # This method does not delegate to Serializer.to_representation, so nothing else can add them.+ if instance.pk:+ ret["tags"] = (+ [tagged_item.tag.name for tagged_item in instance.prefetched_tags]+ if hasattr(instance, "prefetched_tags")+ else list(instance.tagged_items.values_list("tag__name", flat=True))+ )+ else:+ ret["tags"] = []+return retdiff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.pyindex ad34938c5154..1022b93ff889 100644--- a/posthog/api/test/test_project.py+++ b/posthog/api/test/test_project.py@@ -7,12 +7,14 @@ from rest_framework import statusfrom rest_framework.test import APIRequestFactoryfrom posthog.api.project import ProjectViewSet+from posthog.api.project_tags import MAX_TAGS_PER_FILTERfrom posthog.api.test.test_team import EnvironmentToProjectRewriteClient, team_api_test_factoryfrom posthog.constants import AvailableFeaturefrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.person.util import get_person_by_uuidfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.project import Project+from posthog.models.tag import Tagfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.test.persons import create_person, delete_person@@ -914,3 +916,92 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreself.assertEqual(response.status_code, status.HTTP_200_OK, response.json())config.refresh_from_db()self.assertEqual(config.precomputation_enabled_set_by, TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL)++ def test_tags_round_trip_and_land_in_the_project_team_namespace(self):+ # `tags` is not a Project column, so it must be pulled out before the serializer's+ # passthrough loop setattr()s everything left in validated_data onto the model.+ response = self.client.patch(+ f"/api/projects/{self.project.id}/",+ {"tags": ["Production", " EU-Region "]},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(sorted(response.json()["tags"]), ["eu-region", "production"])++ reread = self.client.get(f"/api/projects/{self.project.id}/")+ self.assertEqual(sorted(reread.json()["tags"]), ["eu-region", "production"])+ self.assertEqual(+ set(Tag.objects.filter(team_id=self.project.id).values_list("name", flat=True)),+ {"eu-region", "production"},+ )++ def test_tags_are_replaced_and_orphaned_tags_removed(self):+ self.client.patch(f"/api/projects/{self.project.id}/", {"tags": ["keep", "drop"]}, format="json")++ response = self.client.patch(f"/api/projects/{self.project.id}/", {"tags": ["keep"]}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(response.json()["tags"], ["keep"])+ self.assertEqual(set(Tag.objects.filter(team_id=self.project.id).values_list("name", flat=True)), {"keep"})++ def test_project_can_be_created_with_tags(self):+ self.organization.available_product_features = [+ {"key": AvailableFeature.ORGANIZATIONS_PROJECTS, "name": "Projects", "limit": 2}+ ]+ self.organization.save()+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ response = self.client.post("/api/projects/", {"name": "Tagged", "tags": ["production"]}, format="json")++ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ self.assertEqual(response.json()["tags"], ["production"])++ @parameterized.expand(+ [+ ("all_narrows_to_projects_carrying_every_tag", "production,eu-region", "all", {"both"}),+ ("all_is_the_default_match_mode", "production,eu-region", None, {"both"}),+ ("any_widens_to_projects_carrying_either_tag", "production,us-region", "any", {"both", "us_only"}),+ ("no_match_returns_nothing", "nonexistent", "all", set()),+ ]+ )+ def test_list_filters_projects_by_tags(self, _name, tags_param, match, expected_keys):+ both, _ = Project.objects.create_with_team(+ organization=self.organization, name="Both", initiating_user=self.user+ )+ us_only, _ = Project.objects.create_with_team(+ organization=self.organization, name="US only", initiating_user=self.user+ )+ self.client.patch(f"/api/projects/{both.id}/", {"tags": ["production", "eu-region"]}, format="json")+ self.client.patch(f"/api/projects/{us_only.id}/", {"tags": ["production", "us-region"]}, format="json")+ ids_by_key = {"both": both.id, "us_only": us_only.id}++ query = f"?tags={tags_param}" + (f"&tags_match={match}" if match else "")+ response = self.client.get(f"/api/projects/{query}")++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ returned_ids = [project["id"] for project in response.json()["results"]]+ self.assertEqual(len(returned_ids), len(set(returned_ids)), "A project matching several tags was duplicated")+ self.assertEqual(set(returned_ids), {ids_by_key[key] for key in expected_keys})++ def test_list_rows_carry_tags(self):+ self.client.patch(f"/api/projects/{self.project.id}/", {"tags": ["production"]}, format="json")++ response = self.client.get("/api/projects/")++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ rows = {project["id"]: project["tags"] for project in response.json()["results"]}+ self.assertEqual(rows[self.project.id], ["production"])++ def test_unknown_tags_match_mode_is_rejected(self):+ response = self.client.get("/api/projects/?tags=production&tags_match=either")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())++ def test_filtering_by_too_many_tags_is_rejected(self):+ # "all" joins once per tag, so an unbounded list would let a caller size the query plan.+ too_many = ",".join(f"tag-{index}" for index in range(MAX_TAGS_PER_FILTER + 1))++ response = self.client.get(f"/api/projects/?tags={too_many}")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())diff --git a/posthog/api/test/test_team_project_parity.py b/posthog/api/test/test_team_project_parity.pyindex 3461106f329c..8de004f06b50 100644--- a/posthog/api/test/test_team_project_parity.py+++ b/posthog/api/test/test_team_project_parity.py@@ -19,11 +19,15 @@ from posthog.api.team import TeamSerializer, TeamViewSet# Fields that legitimately exist only on the project surface (a genuine Project concept, not a Team field).# is_pending_deletion was added project-side on master; a project-only field is fine for the rewrite target.-PROJECT_ONLY_SERIALIZER_FIELDS = {"product_description", "is_pending_deletion"}+# `tags` labels a Project, which environments do not have, so it stays off the Team surface.+PROJECT_ONLY_SERIALIZER_FIELDS = {"product_description", "is_pending_deletion", "tags"}# Actions that legitimately exist only on the project surface (operate on the Project, not the Team).PROJECT_ONLY_ACTIONS = {"change_organization", "default_release_conditions", "default_evaluation_contexts"}+# Fields the project list carries on top of the shared basic serializer.+PROJECT_ONLY_LIST_FIELDS = {"tags"}+def _serializer_field_names(serializer_class) -> set[str]:return set(serializer_class().fields.keys())@@ -54,15 +58,24 @@ class TestTeamProjectParity(BaseTest):f"If intentional, add them to PROJECT_ONLY_SERIALIZER_FIELDS.",)- def test_list_serializers_are_identical(self):+ def test_list_serializer_is_a_superset_of_team_basic_serializer(self):team_basic_fields = _serializer_field_names(TeamBasicSerializer)project_basic_fields = _serializer_field_names(ProjectBackwardCompatBasicSerializer)++ missing_on_project = team_basic_fields - project_basic_fields+ self.assertEqual(+ missing_on_project,+ set(),+ f"/api/environments/ list rows expose fields that /api/projects/ list rows do not: "+ f"{sorted(missing_on_project)}.",+ )++ project_only = project_basic_fields - team_basic_fieldsself.assertEqual(- team_basic_fields,- project_basic_fields,- "List responses diverge between /api/environments/ and /api/projects/. "- f"Only on environments: {sorted(team_basic_fields - project_basic_fields)}; "- f"only on projects: {sorted(project_basic_fields - team_basic_fields)}.",+ project_only,+ PROJECT_ONLY_LIST_FIELDS,+ f"Unexpected project-only list fields: {sorted(project_only - PROJECT_ONLY_LIST_FIELDS)}. "+ f"If intentional, add them to PROJECT_ONLY_LIST_FIELDS.",)def test_viewset_actions_are_a_superset_of_team_viewset(self):diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 19d8e17b585e..2f6639a48ad7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -55438,6 +55438,11 @@ export namespace Schemas {readonly is_demo: boolean;readonly timezone: string;readonly access_control: boolean;+ /**+ * Labels applied to this project.+ * @items.maxLength 255+ */+ readonly tags: readonly string[];}export interface PaginatedProjectBackwardCompatBasicList {@@ -64632,7 +64637,10 @@ export namespace Schemas {}/**- * Mixin for serializers to add user access control fields+ * A project and its settings, including the settings that live on its passthrough Team.+ *+ * This shape is a superset of TeamSerializer's, so a request rewritten from /api/environments/+ * onto /api/projects/ never loses a field.*/export interface PatchedProjectBackwardCompat {readonly id?: number;@@ -64649,6 +64657,11 @@ export namespace Schemas {* @nullable*/product_description?: string | null;+ /**+ * Labels applied to this project. Names are trimmed and lowercased, and sending this field replaces the project's existing tags.+ * @items.maxLength 255+ */+ tags?: string[];readonly created_at?: string;readonly effective_membership_level?: OrganizationMembershipLevelEnum;readonly has_group_types?: boolean;@@ -69026,7 +69039,10 @@ export namespace Schemas {export type ProjectBackwardCompatManagedViewsets = {[key: string]: boolean};/**- * Mixin for serializers to add user access control fields+ * A project and its settings, including the settings that live on its passthrough Team.+ *+ * This shape is a superset of TeamSerializer's, so a request rewritten from /api/environments/+ * onto /api/projects/ never loses a field.*/export interface ProjectBackwardCompat {readonly id: number;@@ -69043,6 +69059,11 @@ export namespace Schemas {* @nullable*/product_description?: string | null;+ /**+ * Labels applied to this project. Names are trimmed and lowercased, and sending this field replaces the project's existing tags.+ * @items.maxLength 255+ */+ tags?: string[];readonly created_at: string;readonly effective_membership_level: OrganizationMembershipLevelEnum;readonly has_group_types: boolean;@@ -90483,8 +90504,24 @@ export namespace Schemas {* A search term.*/search?: string;+ /**+ * Comma-separated tag names to filter by, for example `production,eu-region`. Names are trimmed and lowercased before matching. At most 20 distinct tags per request.+ */+ tags?: string;+ /**+ * How to combine the `tags` filter. `all` (the default) returns projects carrying every listed tag; `any` returns projects carrying at least one.+ */+ tags_match?: OrganizationsProjectsListTagsMatch;};+ export type OrganizationsProjectsListTagsMatch = typeof OrganizationsProjectsListTagsMatch[keyof typeof OrganizationsProjectsListTagsMatch];+++ export const OrganizationsProjectsListTagsMatch = {+ All: 'all',+ Any: 'any',+ } as const;+export type OrganizationsProjectsEvaluationContextSuggestionsDestroyParams = {/*** Name of the evaluation context to restore to suggestions.diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.tsindex ae3f76a1578f..9dd5eef922f0 100644--- a/services/mcp/src/generated/core/api.ts+++ b/services/mcp/src/generated/core/api.ts@@ -50,6 +50,8 @@ export const organizationsProjectsPartialUpdateBodyNameMax = 200export const organizationsProjectsPartialUpdateBodyProductDescriptionMax = 1000+export const organizationsProjectsPartialUpdateBodyTagsItemMax = 255+export const organizationsProjectsPartialUpdateBodyAppUrlsItemMax = 200export const organizationsProjectsPartialUpdateBodyPersonDisplayNamePropertiesItemMax = 400@@ -113,6 +115,12 @@ export const OrganizationsProjectsPartialUpdateBody = () => zod.describe('Short description of what the project is about. This is helpful to give our AI agents context about your project.'),+ tags: zod+ .array(zod.string().max(organizationsProjectsPartialUpdateBodyTagsItemMax))+ .optional()+ .describe(+ "Labels applied to this project. Names are trimmed and lowercased, and sending this field replaces the project's existing tags."+ ),app_urls: zod.array(zod.string().max(organizationsProjectsPartialUpdateBodyAppUrlsItemMax).nullable()).optional(),@@ -2648,7 +2656,9 @@ export const OrganizationsProjectsPartialUpdateBody = () => zodonboarding_tasks: zod.unknown().optional(),web_analytics_pre_aggregated_tables_enabled: zod.boolean().nullish(),})- .describe('Mixin for serializers to add user access control fields')+ .describe(+ "A project and its settings, including the settings that live on its passthrough Team.\n\nThis shape is a superset of TeamSerializer's, so a request rewritten from \/api\/environments\/\nonto \/api\/projects\/ never loses a field."+ )export const ProductEnablementCreateParams = () => zod.object({project_id: zoddiff --git a/services/mcp/src/tools/generated/core.ts b/services/mcp/src/tools/generated/core.tsindex e59857c64179..e5ee55be871f 100644--- a/services/mcp/src/tools/generated/core.ts+++ b/services/mcp/src/tools/generated/core.ts@@ -186,6 +186,9 @@ const projectSettingsUpdate = (): ToolBase<if (params.product_description !== undefined) {body['product_description'] = params.product_description}+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }if (params.app_urls !== undefined) {body['app_urls'] = params.app_urls}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.jsonindex d910f056c279..b391b2ddbc2a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json@@ -4164,6 +4164,14 @@],"description": "Enables displaying surveys via posthog-js on allowed origins."},+ "tags": {+ "description": "Labels applied to this project. Names are trimmed and lowercased, and sending this field replaces the project's existing tags.",+ "items": {+ "maxLength": 255,+ "type": "string"+ },+ "type": "array"+ },"test_account_filters": {"description": "Filter groups that identify internal/test traffic to be excluded from insights."},