: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(streamlit-apps): log activity from the model save under the team's organization (#114487)
Julian Bezfa8a15d83dbf
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 9b1878c041b7..eda104ff2af6 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -597,6 +597,9 @@ signal_exclusions: dict[ActivityScope, list[str]] = {"Subscription": ["next_delivery_date",],+ # The facade logs a version change as `uploaded_version` or `activated_version` at the write+ # site, so the save that only moves the active version must not add an `updated` row.+ "StreamlitApp": ["active_version", "updated_at"],# `last_run_at` is written by the scout coordinator on every tick (~every 15 min per scout),# and the failure streak by the runner on every run outcome. When those are the only# change, suppress the activity signal entirely so run bookkeeping never spams the audit@@ -720,6 +723,12 @@ field_exclusions: dict[AuditableScope, list[str]] = {# on each settings toggle, and none of it is configuration."pull_requests",],+ "StreamlitApp": [+ # Reverse relations. Version uploads and activations log their own rows, and a version's+ # str() includes the app name, so a rename would show a false versions change.+ "versions",+ "sandbox",+ ],"HogFlow": [# System-maintained skip-forward map for deleted steps, refreshed as a side effect of graph# writes — bookkeeping, not a user edit, so keep it out of change diffs.diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex 86babdb66707..31dd903a77c9 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -51,6 +51,7 @@ model_activity:products.review_hog.backend.activity_logging.handle_review_reposimodel_activity:products.signals.backend.activity_logging.handle_signal_scout_config_changemodel_activity:products.signals.backend.activity_logging.handle_signal_team_config_changemodel_activity:products.stamphog.backend.activity_logging.handle_stamphog_repo_config_change+model_activity:products.streamlit_apps.backend.activity_logging.handle_streamlit_app_changemodel_activity:products.tasks.backend.activity_logging.handle_loop_changemodel_activity:products.tracing.backend.activity_logging.handle_traces_retention_rule_activitymodel_activity:products.warehouse_sources.backend.activity_logging.handle_external_data_schema_changediff --git a/products/streamlit_apps/backend/activity_logging.py b/products/streamlit_apps/backend/activity_logging.pynew file mode 100644index 000000000000..c706033b9e51--- /dev/null+++ b/products/streamlit_apps/backend/activity_logging.py@@ -0,0 +1,55 @@+"""Activity-log receiver for streamlit apps.++The module stays import-light because `apps.py` imports it at `ready()`.+A version upload or activation is not logged here: the field change alone cannot tell an upload+from a rollback to the newest version, so the facade logs those at the write site.+"""++from typing import TYPE_CHECKING, Any++from posthog.models.activity_logging.activity_log import AuditableScope, Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver++from products.streamlit_apps.backend.models import StreamlitApp++if TYPE_CHECKING:+ from posthog.models.user import User+++def _was_soft_deleted(before_update: StreamlitApp | None, after_update: StreamlitApp | None) -> bool:+ return before_update is not None and after_update is not None and after_update.deleted and not before_update.deleted+++@mutable_receiver(model_activity_signal, sender=StreamlitApp)+def handle_streamlit_app_change(+ sender: type[StreamlitApp],+ scope: AuditableScope,+ before_update: StreamlitApp | None,+ after_update: StreamlitApp | None,+ activity: str,+ user: "User | None",+ was_impersonated: bool = False,+ **kwargs: Any,+) -> None:+ app = after_update or before_update+ if app is None:+ return++ if _was_soft_deleted(before_update, after_update):+ activity = "deleted"++ if activity == "updated":+ detail = Detail(changes=changes_between(scope, previous=before_update, current=after_update), name=app.name)+ else:+ detail = Detail(name=app.name)++ log_activity(+ organization_id=app.team.organization_id,+ team_id=app.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=str(app.id),+ scope=scope,+ activity=activity,+ detail=detail,+ )diff --git a/products/streamlit_apps/backend/apps.py b/products/streamlit_apps/backend/apps.pyindex a228a9cf8289..cac145041149 100644--- a/products/streamlit_apps/backend/apps.py+++ b/products/streamlit_apps/backend/apps.py@@ -5,3 +5,8 @@ class StreamlitAppsConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "products.streamlit_apps.backend"label = "streamlit_apps"++ def ready(self) -> None:+ # Apps are written from web requests and from Celery tasks, so the activity-log receiver+ # must connect in every process, not only where the API module loads.+ from products.streamlit_apps.backend import activity_logging # noqa: F401, PLC0415diff --git a/products/streamlit_apps/backend/facade/api.py b/products/streamlit_apps/backend/facade/api.pyindex bcc72b960c58..b0160cd2ee09 100644--- a/products/streamlit_apps/backend/facade/api.py+++ b/products/streamlit_apps/backend/facade/api.py@@ -11,7 +11,8 @@ from django.utils import timezoneimport structlog-from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity+from posthog.models.activity_logging.activity_log import Detail, log_activity+from posthog.models.activity_logging.model_activity import get_was_impersonatedfrom posthog.models.user import Userfrom posthog.storage import object_storage@@ -298,9 +299,7 @@ def get_app(team_id: int, short_id: str) -> contracts.AppContract:return _app_to_contract(_get_app(team_id, short_id))-def create_app(- team_id: int, user: User, data: contracts.CreateAppInput, was_impersonated: bool-) -> contracts.AppContract:+def create_app(team_id: int, user: User, data: contracts.CreateAppInput) -> contracts.AppContract:_validate_resource_bounds(data.cpu_cores, data.memory_gb)app = StreamlitApp.objects.for_team(team_id).create(@@ -312,25 +311,11 @@ def create_app(memory_gb=data.memory_gb,)- log_activity(- organization_id=user.current_organization_id,- team_id=team_id,- user=user,- was_impersonated=was_impersonated,- item_id=str(app.id),- scope="StreamlitApp",- activity="created",- detail=Detail(name=app.name),- )-return _app_to_contract(app)-def update_app(- team_id: int, short_id: str, user: User, data: contracts.UpdateAppInput, was_impersonated: bool-) -> contracts.AppContract:+def update_app(team_id: int, short_id: str, data: contracts.UpdateAppInput) -> contracts.AppContract:app = _get_app(team_id, short_id)- before_update = StreamlitApp.objects.for_team(team_id).get(pk=app.pk)_validate_resource_bounds(data.cpu_cores, data.memory_gb)@@ -344,23 +329,10 @@ def update_app(app.memory_gb = data.memory_gbapp.save()- changes = changes_between("StreamlitApp", previous=before_update, current=app)- if changes:- log_activity(- organization_id=user.current_organization_id,- team_id=team_id,- user=user,- was_impersonated=was_impersonated,- item_id=str(app.id),- scope="StreamlitApp",- activity="updated",- detail=Detail(changes=changes, name=app.name),- )-return _app_to_contract(app)-def delete_app(team_id: int, short_id: str, user: User, was_impersonated: bool) -> None:+def delete_app(team_id: int, short_id: str) -> None:app = _get_app(team_id, short_id)try:@@ -372,17 +344,6 @@ def delete_app(team_id: int, short_id: str, user: User, was_impersonated: bool)app.deleted_at = timezone.now()app.save(update_fields=["deleted", "deleted_at", "updated_at"])- log_activity(- organization_id=user.current_organization_id,- team_id=team_id,- user=user,- was_impersonated=was_impersonated,- item_id=str(app.id),- scope="StreamlitApp",- activity="deleted",- detail=Detail(name=app.name),- )-# --- Version API ---@@ -399,11 +360,25 @@ def upload_version(user: User,file_content: bytes,declared_size: int | None,- was_impersonated: bool,) -> contracts.AppVersionContract:app = _get_app(team_id, short_id)check_zip_size(declared_size)- return _store_version(app, user, file_content, was_impersonated)+ return _store_version(app, user, file_content)+++def _log_version_activity(app: StreamlitApp, user: User, activity: str, version_number: int) -> None:+ # The model signal skips saves that only move the active version (see `signal_exclusions`):+ # the field change cannot tell an upload from a rollback, so this site names the activity.+ log_activity(+ organization_id=app.team.organization_id,+ team_id=app.team_id,+ user=user,+ was_impersonated=get_was_impersonated(),+ item_id=str(app.id),+ scope="StreamlitApp",+ activity=activity,+ detail=Detail(name=f"{app.name} v{version_number}"),+ )def _active_version_number(app: StreamlitApp) -> int:@@ -420,7 +395,6 @@ def _store_version(app: StreamlitApp,user: User,file_content: bytes,- was_impersonated: bool,expected_active_version_id: uuid.UUID | None = None,) -> contracts.AppVersionContract:"""Validate, store, and activate a version zip.@@ -482,17 +456,7 @@ def _store_version(raise_get_sandbox_and_stop_if_live(app)-- log_activity(- organization_id=user.current_organization_id,- team_id=app.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=str(app.id),- scope="StreamlitApp",- activity="uploaded_version",- detail=Detail(name=f"{app.name} v{next_version_number}"),- )+ _log_version_activity(app, user, "uploaded_version", next_version_number)return _version_to_contract(version)@@ -502,7 +466,6 @@ def create_version_from_source(short_id: str,user: User,data: contracts.CreateVersionFromSourceInput,- was_impersonated: bool,) -> contracts.AppVersionContract:"""Create and activate a version from free-text source plus optional extra files.@@ -518,7 +481,6 @@ def create_version_from_source(user=user,file_content=file_content,declared_size=len(file_content),- was_impersonated=was_impersonated,)@@ -553,7 +515,6 @@ def edit_version_source(short_id: str,user: User,data: contracts.EditVersionSourceInput,- was_impersonated: bool,) -> contracts.AppVersionContract:"""Create and activate a version from exact edits against ``data.base_version``.@@ -576,12 +537,10 @@ def edit_version_source(delete_files=data.delete_files,)check_zip_size(len(file_content))- return _store_version(app, user, file_content, was_impersonated, expected_active_version_id=base.id)+ return _store_version(app, user, file_content, expected_active_version_id=base.id)-def activate_version(- team_id: int, short_id: str, user: User, version_number: int, was_impersonated: bool-) -> contracts.AppVersionContract:+def activate_version(team_id: int, short_id: str, user: User, version_number: int) -> contracts.AppVersionContract:app = _get_app(team_id, short_id)try:version = app.versions.get(version_number=version_number)@@ -592,17 +551,7 @@ def activate_version(app.save(update_fields=["active_version", "updated_at"])_get_sandbox_and_stop_if_live(app)-- log_activity(- organization_id=user.current_organization_id,- team_id=team_id,- user=user,- was_impersonated=was_impersonated,- item_id=str(app.id),- scope="StreamlitApp",- activity="activated_version",- detail=Detail(name=f"{app.name} v{version_number}"),- )+ _log_version_activity(app, user, "activated_version", version_number)return _version_to_contract(version)diff --git a/products/streamlit_apps/backend/models.py b/products/streamlit_apps/backend/models.pyindex b554aaa5b2b9..a196ceca7ab4 100644--- a/products/streamlit_apps/backend/models.py+++ b/products/streamlit_apps/backend/models.py@@ -2,6 +2,7 @@ import uuidfrom django.db import models+from posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.utils import generate_short_id@@ -11,7 +12,7 @@ MIN_MEMORY_GB = 0.5MAX_MEMORY_GB = 16.0-class StreamlitApp(TeamScopedRootMixin):+class StreamlitApp(ModelActivityMixin, TeamScopedRootMixin):# `objects` (TeamScopedManager) inherited from TeamScopedRootMixin is fail-closed for# explicit user code. `all_teams` is the unscoped sibling for Django framework internals# (related-object access, prefetch_related, DRF class-body querysets) — Meta'sdiff --git a/products/streamlit_apps/backend/presentation/views.py b/products/streamlit_apps/backend/presentation/views.pyindex 49f39e0e4917..c315276cb0c0 100644--- a/products/streamlit_apps/backend/presentation/views.py+++ b/products/streamlit_apps/backend/presentation/views.py@@ -4,7 +4,6 @@ from django.core.cache import cacheimport structlogfrom drf_spectacular.utils import OpenApiResponse, extend_schema-from loginas.utils import is_impersonated_sessionfrom rest_framework import status, viewsetsfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -109,7 +108,6 @@ class StreamlitAppViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):team_id=self.team_id,user=cast(User, request.user),data=request.validated_data,- was_impersonated=is_impersonated_session(request),)except ValueError as e:return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)@@ -128,9 +126,7 @@ class StreamlitAppViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):app = api.update_app(team_id=self.team_id,short_id=short_id,- user=cast(User, request.user),data=request.validated_data,- was_impersonated=is_impersonated_session(request),)except api.AppNotFoundError:return Response(status=status.HTTP_404_NOT_FOUND)@@ -157,12 +153,7 @@ class StreamlitAppViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@extend_schema(summary="Delete a streamlit app", request=None, responses={204: None})def destroy(self, request: Request, short_id: str, **kwargs: Any) -> Response:try:- api.delete_app(- team_id=self.team_id,- short_id=short_id,- user=cast(User, request.user),- was_impersonated=is_impersonated_session(request),- )+ api.delete_app(team_id=self.team_id, short_id=short_id)except api.AppNotFoundError:return Response(status=status.HTTP_404_NOT_FOUND)return Response(status=status.HTTP_204_NO_CONTENT)@@ -206,7 +197,6 @@ class StreamlitAppViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):user=cast(User, request.user),file_content=file_content,declared_size=zip_file.size,- was_impersonated=is_impersonated_session(request),)except api.AppNotFoundError:return Response(status=status.HTTP_404_NOT_FOUND)@@ -239,7 +229,6 @@ class StreamlitAppViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):short_id=short_id,user=cast(User, request.user),data=request.validated_data,- was_impersonated=is_impersonated_session(request),)except api.AppNotFoundError:return Response(status=status.HTTP_404_NOT_FOUND)@@ -300,7 +289,6 @@ class StreamlitAppViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):short_id=short_id,user=cast(User, request.user),data=request.validated_data,- was_impersonated=is_impersonated_session(request),)except api.AppNotFoundError:return Response(status=status.HTTP_404_NOT_FOUND)@@ -342,7 +330,6 @@ class StreamlitAppViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):short_id=short_id,user=cast(User, request.user),version_number=version_number,- was_impersonated=is_impersonated_session(request),)except api.AppNotFoundError:return Response(status=status.HTTP_404_NOT_FOUND)diff --git a/products/streamlit_apps/backend/tests/test_presentation.py b/products/streamlit_apps/backend/tests/test_presentation.pyindex 4578b9b08807..41fed97bb3b4 100644--- a/products/streamlit_apps/backend/tests/test_presentation.py+++ b/products/streamlit_apps/backend/tests/test_presentation.py@@ -14,9 +14,13 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from posthog.models import Organization, OrganizationMembership+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.scoping import team_scope+from products.streamlit_apps.backend.facade import api as streamlit_apifrom products.streamlit_apps.backend.facade.api import MAX_FILE_COUNT+from products.streamlit_apps.backend.facade.contracts import UpdateAppInputfrom products.streamlit_apps.backend.models import StreamlitApp, StreamlitAppSandbox, StreamlitAppVersionfrom products.streamlit_apps.backend.presentation.serializers import (CreateVersionFromSourceInputSerializer,@@ -471,6 +475,76 @@ class TestStreamlitAppVersionAPI(_StreamlitAppsFlagMixin, APIBaseTest):mock_storage_write.assert_not_called()+class TestStreamlitAppActivityLog(_StreamlitAppsFlagMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ other_organization = Organization.objects.create(name="Other org")+ OrganizationMembership.objects.create(organization=other_organization, user=self.user)+ self.user.current_organization = other_organization+ self.user.save()+ self.app = StreamlitApp.objects.create(team=self.team, name="Test App", created_by=self.user)+ self.version = StreamlitAppVersion.objects.create(+ app=self.app, version_number=1, zip_file="test/v1.zip", zip_hash="abc", created_by=self.user+ )++ def _new_rows(self, after_id: int) -> list[ActivityLog]:+ return list(ActivityLog.objects.filter(scope="StreamlitApp", id__gt=after_id).order_by("id"))++ @parameterized.expand(+ [+ ("create", "post", "", {"name": "New App"}, "created", "New App", None),+ ("update", "patch", "{short_id}/", {"name": "Renamed"}, "updated", "Renamed", "name"),+ ("delete", "delete", "{short_id}/", None, "deleted", "Test App", None),+ (+ "activate_version",+ "post",+ "{short_id}/activate_version/",+ {"version_number": 1},+ "activated_version",+ "Test App v1",+ None,+ ),+ (+ "create_version_from_source",+ "post",+ "{short_id}/create_version_from_source/",+ {"source": "import streamlit as st"},+ "uploaded_version",+ "Test App v2",+ None,+ ),+ ]+ )+ @patch("posthog.storage.object_storage.write")+ def test_write_logs_one_row_under_the_team_organization(+ self, _name, method, path, data, expected_activity, expected_name, expected_changed_field, _mock_write+ ):+ last_id = ActivityLog.objects.order_by("-id").values_list("id", flat=True).first() or 0+ url = f"/api/projects/{self.team.id}/streamlit_apps/{path.format(short_id=self.app.short_id)}"++ response = getattr(self.client, method)(url, data=data, format="json")++ assert response.status_code < 300, response.content+ rows = self._new_rows(last_id)+ assert [row.activity for row in rows] == [expected_activity]+ row = rows[0]+ assert row.organization_id == self.team.organization_id+ assert row.user_id == self.user.id+ assert row.detail is not None+ assert row.detail["name"] == expected_name+ changed_fields = [change["field"] for change in row.detail["changes"] or []]+ assert changed_fields == ([] if expected_changed_field is None else [expected_changed_field])++ def test_write_outside_a_request_logs_a_system_row(self):+ last_id = ActivityLog.objects.order_by("-id").values_list("id", flat=True).first() or 0++ streamlit_api.update_app(self.team.id, self.app.short_id, UpdateAppInput(name="Renamed by a job"))++ rows = self._new_rows(last_id)+ assert [(row.activity, row.user_id, row.is_system) for row in rows] == [("updated", None, True)]+ assert rows[0].organization_id == self.team.organization_id++class TestStreamlitAppSandboxControlAPI(_StreamlitAppsFlagMixin, APIBaseTest):def _url(self, short_id: str, suffix: str = "") -> str:base = f"/api/projects/{self.team.id}/streamlit_apps/{short_id}"