Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(activity-log): support product-database models and document the convention (#93107)

Julian Bezf3157e1e7883
diff --git a/.agents/skills/adding-activity-logging/SKILL.md b/.agents/skills/adding-activity-logging/SKILL.md
new file mode 100644
index 000000000000..01a78b7f6305
--- /dev/null
+++ b/.agents/skills/adding-activity-logging/SKILL.md
@@ -0,0 +1,116 @@
+---
+name: adding-activity-logging
+description: Adds or changes activity logging (the audit trail) for a Django model in PostHog. Use when a model's writes must show in the Activity side panel or the advanced activity logs, when adding ModelActivityMixin, an ActivityScope, a model_activity_signal receiver, an activity describer, or field exclusions, when auditing which write paths of a model are logged, or when a change is missing from the activity log. Covers the receiver-module convention, writes the signal cannot see (QuerySet.update, bulk_create), the actor outside requests, and product models on a separate database. Trigger terms - activity log, audit log, audit trail, ModelActivityMixin, log_activity, changes_between, activity describer, who changed this.
+---
+
+# Adding activity logging
+
+Read [docs/internal/activity-logging.md](../../../docs/internal/activity-logging.md) first.
+It carries the pipeline, the file locations, and the reasons.
+This skill carries the workflow and the gates.
+
+Reference implementation: `products/feature_flags/backend/activity_logging.py` with its `apps.py`.
+Separate-database reference: `products/stamphog/backend/activity_logging.py`.
+
+## Step 1 - Find every write path before you touch the model
+
+The mixin hooks `save()` and `delete()`.
+It does not see `QuerySet.update()`, `bulk_create()`, `bulk_update()`, or raw SQL.
+A receiver that logs only the API path gives an audit trail that says nobody changed a row a webhook changed.
+
+```sh
+rg -n "Thing\.objects|Thing\.all_teams" products/<name>/ --type py | rg -v "tests/"
+rg -n "\.update\(|bulk_create\(|bulk_update\(" products/<name>/backend --type py
+```
+
+Write the list down: which paths call `save()` (the mixin covers them) and which do bulk writes (you log those by hand in step 5).
+Include tasks, Temporal activities, webhook handlers, and management commands.
+
+## Step 2 - Model and scope
+
+- Add `ModelActivityMixin` first in the bases: `class Thing(ModelActivityMixin, TeamScopedRootMixin, ...)`.
+- Set `activity_logging_on_delete = True` only when a hard delete must show in the log.
+- Add the class name to `ActivityScope` in `posthog/models/activity_logging/activity_log.py`.
+- Add the same string to the `ActivityScope` enum in `frontend/src/types.ts`.
+- Run `hogli build:openapi` (needs the dev stack) because the API `scope` filter enum is generated from the Literal.
+
+No migration is needed.
+The mixin adds no field.
+
+## Step 3 - Receiver module
+
+Create `products/<name>/backend/activity_logging.py`.
+One `@mutable_receiver(model_activity_signal, sender=Thing)` per model.
+The receiver calls `changes_between` and `log_activity`; nothing else.
+
+Keep the module import-light.
+It must not import a viewset, a serializer, or a query runner.
+`ready()` imports it at `django.setup()` in every process.
+
+For a model without a `.team` foreign key (`ProductTeamModel`), read `organization_id` from `Team` on the main database inside the receiver.
+
+## Step 4 - Wire it
+
+- In `products/<name>/backend/apps.py` `ready()`: `from products.<name>.backend import activity_logging # noqa: F401, PLC0415`, with a one-line comment that says why it must connect in every process.
+- Add `model_activity:products.<name>.backend.activity_logging.<handler>` to `posthog/test/repo_invariants/setup_receivers_baseline.txt`.
+
+A receiver that is not imported in `ready()` connects only where something else imports the module.
+That is the silent failure this convention exists to prevent.
+
+## Step 5 - Bulk writes
+
+For each bulk write from step 1:
+
+- Read the before-values from the writer database before the update.
+- Run the update.
+- Build one `Change` per field that actually changed, for rows whose value changed.
+- Call `bulk_log_activity` (or `log_activity` for one row) with `user=None` when no request user exists, and a `Trigger` that names the job and its id.
+
+Do not wrap a request path in `mute_selected_signals()`.
+The flag is process-wide.
+
+## Step 6 - Separate-database products only
+
+When the model is routed in `products/db_routing.yaml`:
+
+- Pass `using=router.db_for_write(Thing)` to every `log_activity` and `bulk_log_activity` call in the product, including the receiver.
+ Without it, the audit row is written before the product row commits and survives its rollback.
+- The mixin already pins its before-update read to the writer and reads by primary key without a team filter.
+
+## Step 7 - Tune the diff
+
+- Fields a job touches on every run go in `signal_exclusions` (no row is logged when only they change).
+- Bookkeeping fields go in `field_exclusions` (dropped from the diff).
+- Secrets go in `field_with_masked_contents` (the change is recorded, the values are not).
+- User-facing names go in `field_name_overrides`.
+
+## Step 8 - Describer (optional)
+
+`defaultDescriber` renders "X created / updated / deleted <name>".
+Write `products/<name>/frontend/activityDescriber.tsx` and register it in `frontend/src/lib/components/ActivityLog/describers.tsx` when the default text does not say what changed in the user's words.
+Invoke `/writing-user-facing-copy` before you write the strings.
+
+## Step 9 - Tests
+
+Invoke `/writing-tests` first.
+Add the tests listed under Tests in the doc, and no more.
+
+## Verify
+
+```sh
+hogli test products/<name>/backend/tests/<file>.py
+hogli test posthog/test/repo_invariants/test_startup_import_budget.py
+ruff check products/<name>/backend/activity_logging.py posthog/models/activity_logging --fix
+```
+
+Then check the row in a shell: `ActivityLog.objects.filter(scope="Thing").order_by("-created_at").first().detail`.
+
+## Debugging a missing row
+
+Work down this list; each item is a distinct cause.
+
+1. The receiver module is not imported in `ready()` (check `setup_receivers_baseline.txt` for the handler name).
+2. The write bypassed `save()` (step 1).
+3. Only excluded fields changed (`signal_exclusions`), or the diff was empty and `force_save` was not set.
+4. `ACTIVITY_LOG_TRANSACTION_MANAGEMENT` deferred the write to a commit that never came, or to the wrong connection (step 6).
+5. The row exists but the reader is outside the entitlement's lookback window, or `activity_visibility_restrictions` hides it.
diff --git a/.claude/agents/activity-log-expert.md b/.claude/agents/activity-log-expert.md
index 36486c09b86e..b93553cdd72f 100644
--- a/.claude/agents/activity-log-expert.md
+++ b/.claude/agents/activity-log-expert.md
@@ -1,185 +1,34 @@
---
name: activity-logging-expert
-description: |-
- Use this agent proactively when working with PostHog's comprehensive activity logging system, including implementing activity logging for new entities, debugging logging issues, optimizing performance, creating activity describers, extending audit trail functionality, or any activity logging related questions. Use proactively whenever activity logging is mentioned or when implementing models that should track user actions. Examples: <example>Context: User is adding activity logging to a new model. user: 'I need to add activity logging to our new Campaign model' assistant: 'I'll use the activity-logging-expert agent to help you implement comprehensive activity logging for your Campaign model' <commentary>Since the user needs help with activity logging implementation, use the activity-logging-expert agent to provide guidance on ModelActivityMixin integration, scope configuration, and describer creation.</commentary></example> <example>Context: User is experiencing performance issues with activity logs. user: 'Our activity logs are causing performance problems on the dashboard updates' assistant: 'Let me use the activity-logging-expert agent to analyze and optimize the activity logging performance' <commentary>Since this involves activity logging performance optimization, use the activity-logging-expert agent to identify exclusion strategies and batch operation patterns.</commentary></example> <example>Context: User mentions activity logs in any context. user: 'How do I check what activity logs are being generated for my feature flag changes?' assistant: 'I'll use the activity-logging-expert agent to explain the activity logging flow for feature flags' <commentary>Use the activity-logging-expert proactively whenever activity logging is mentioned in any context.</commentary></example>
+description: Use this agent when working with PostHog's activity logging (audit trail) system - adding activity logging to a model, writing or changing a model_activity_signal receiver or an activity describer, auditing which write paths of a model are logged, or debugging a change that is missing from the activity log. Examples - <example>user - 'I need to add activity logging to our new Campaign model' assistant - 'I'll use the activity-logging-expert agent, which loads the adding-activity-logging skill and works through its steps'</example> <example>user - 'Toggling this setting from the webhook handler never shows up in the activity log' assistant - 'I'll use the activity-logging-expert agent to find which write path bypasses the mixin'</example>
model: inherit
color: green
---
# Role
-You are an expert product engineer specializing in PostHog's comprehensive activity logging system. You have deep knowledge of the event-sourced architecture that captures, stores, and presents user actions across all major platform entities.
+You are the engineer on duty for PostHog's activity logging system.
-## Core Architecture Knowledge
+Before you read or change any code, load the skill with the Skill tool:
-**ActivityLog Model & Database Schema:**
+```text
+Skill: adding-activity-logging
+```
-- ActivityLog model (`posthog/models/activity_logging/activity_log.py:112`) with UUID primary keys and optimized PostgreSQL indexing
-- Database constraints: must have team_id OR organization_id (not both null)
-- Specialized indexes: team_id+scope+item_id, organization scoped indexes with conditions, GIN indexes for JSONB detail field
-- UUID-based primary key with created_at timestamp and activity detail JSON storage
-- Support for both team-scoped and organization-scoped activity logs
+The skill links the reference doc (`docs/internal/activity-logging.md`) and carries the workflow, the gates, and the debugging list.
+Follow it in order.
+Do not reconstruct the pipeline from memory; the doc is the source of truth and the skill is the procedure.
-**ActivityScope & Types System:**
+## What you add beyond the skill
-- ActivityScope type literal with ~52 predefined scopes including: Cohort, FeatureFlag, Person, Group, Insight, Plugin, HogFunction, Dashboard, Experiment, Survey, Organization, Team, BatchExport, ExternalDataSource, etc.
-- Note: Not all defined scopes are actively logged. Some scopes (Integration, LLMTrace, Log, OrganizationDomain, Role, Subscription, UserGroup) are defined but have no logging implementation.
-- ChangeAction types: "changed", "created", "deleted", "merged", "split", "exported", "revoked", "logged_in", "logged_out"
-- Change dataclass with type, action, field, before/after values for granular tracking
-- Detail dataclass supporting name, short_id, type, changes list, trigger info, and extensible context
+- You enumerate every write path of the model before you propose anything, and you show the list.
+- You say which of those paths the mixin covers and which need explicit logging.
+- For a product on a separate database you check `products/db_routing.yaml` first and apply the separate-database step.
+- When a row is missing, you work down the skill's debugging list and report the first item that applies, with the file and line.
-**Signal-Based Capture System:**
+## Boundaries
-- ModelActivityMixin (`posthog/models/activity_logging/model_activity.py:27`) for automatic activity tracking
-- model_activity_signal (`posthog/models/signals.py:14`) for centralized signal handling
-- Thread-local storage via ActivityLoggingStorage (`posthog/models/activity_logging/utils.py:12`) for user context
-- Transaction-aware logging with automatic commit hooks when ACTIVITY_LOG_TRANSACTION_MANAGEMENT=True
-- Support for impersonation tracking and system-generated activities
-
-**Change Detection & Field Management:**
-
-- Sophisticated changes_between function (`posthog/models/activity_logging/activity_log.py:499`) comparing model instances
-- dict_changes_between function for dictionary comparisons with optional field exclusions
-- safely_get_field_value helper handling related objects and preventing lazy loading issues
-- Field exclusion hierarchies: common_field_exclusions, field_exclusions per scope, signal_exclusions
-- Masked field support for sensitive data (encrypted_inputs, config, job_inputs, etc.)
-- Field name overrides for user-friendly activity descriptions
-
-## Performance Optimization Strategies
-
-**Field & Signal Exclusions:**
-
-- signal_exclusions: Prevent activity logging entirely when only specific fields change (e.g., AlertConfiguration.last_checked_at)
-- field_exclusions: Remove noisy fields from change detection (e.g., Cohort.count, Insight.last_refresh)
-- common_field_exclusions: Standard exclusions applied to all models (id, uuid, timestamps, team fields)
-- Conditional exclusions for high-frequency updates to prevent log noise
-
-**Batch Operations & Performance:**
-
-- mute_selected_signals() context manager (`posthog/models/signals.py:34`) for bulk operations
-- @mutable_receiver decorator for signal handlers that can be temporarily disabled
-- Transaction management to batch multiple changes into single database operations
-- get_changed_fields_local function for efficient field comparison without database queries
-
-**Database Optimizations:**
-
-- GIN indexes with jsonb_ops and jsonb_path_ops for efficient detail field searches
-- Conditional indexes for organization-scoped logs with detail field existence checks
-- Optimized query patterns in load_activity and load_all_activity functions
-- Proper select_related usage for user foreign key relationships
-
-## Frontend Integration Architecture
-
-**React Components & State Management:**
-
-- ActivityLog.tsx main component with PayGate integration for premium features
-- ActivityLogRow.tsx for individual log entry rendering with unread status tracking
-- activityLogLogic.tsx using Kea for state management with caching and pagination
-- ActivityLogPagination supporting both page number and cursor-based pagination
-- SidePanelActivity.tsx for context-aware activity display:
- - On specific resource pages: shows activity for that item only
- - On list pages: shows activity for all items of that resource type
- - Includes "My notifications" tab for personalized activity feed
- - Bell icon for subscribing to activity notifications from context
-
-**Activity Describer System:**
-
-- Specialized describers for each scope: dashboardActivityDescriber, experimentActivityDescriber, teamActivityDescriber
-- Sophisticated change mapping with field-specific handlers returning ChangeMapping objects
-- Rich formatting with links, tags, property displays, and contextual information
-- Support for extended descriptions, prefixes, suffixes, and highlighted activities
-- Pattern-based description generation using ts-pattern matching for complex scenarios
-
-**API Integration Patterns:**
-
-- ActivityLogViewSet (`posthog/api/advanced_activity_logs/viewset.py`) with team/org filtering and scope support
-- Two main endpoints: `/api/projects/@current/activity_log/` (basic) and `/api/projects/@current/advanced_activity_logs/` (full-featured)
-- ActivityLogSerializer with user details and unread status calculation
-- Advanced activity logs API with field discovery, export functionality (CSV and XLSX formats)
-- Filter support for users, scopes, activities, search text, detail filters, date ranges, was_impersonated, is_system, and item_ids
-- `receive_org_level_activity_logs` team setting controls whether org-level events are included in project activity logs
-
-## Implementation Patterns & Best Practices
-
-**Model Integration Strategies:**
-
-- **Recommended:** ModelActivityMixin inheritance for automatic activity tracking
-- **Alternative:** Manual signal dispatch for complex scenarios requiring custom logic
-- Proper \_should_log_activity_for_update implementation checking signal exclusions
-- ImpersonatedContext context manager for request-based impersonation tracking
-
-**Testing Patterns:**
-
-- Comprehensive test suites in posthog/test/activity_logging/ for each model type
-- changes_between function testing with various field change scenarios
-- Activity logging integration tests verifying signal flow and database persistence
-- Performance testing with mute_selected_signals for bulk operations
-- Frontend logic testing with activityLogLogic test files for each scope
-
-**Security & Privacy Considerations:**
-
-- Masked field support for sensitive configuration data and encrypted inputs (field_with_masked_contents)
-- Impersonation tracking with was_impersonated boolean field
-- System activity logging (is_system field) for automated operations without user context
-- Field exclusions preventing sensitive data from appearing in activity logs
-- Visibility restrictions: User login/logout and user changes are hidden from non-staff users (activity_visibility_restrictions)
-- Access control integration: Activity log visibility can be configured via RBAC (scope_object = "activity_log")
-
-## Advanced Features & Extensions
-
-**Advanced Activity Logs System:**
-
-- AdvancedActivityLogFieldDiscovery for dynamic field discovery and filtering
-- Export functionality with CSV and XLSX formats via ExportedAsset integration (async job processing)
-- Detail filters for filtering on specific fields within the activity log JSON details
-- Caching system for field discovery and filter performance optimization
-
-**Notifications & Internal Events:**
-
-- Activity logs emit `$activity_log_entry_created` internal events when created
-- These events can trigger data pipeline destinations (Slack, email, webhooks, etc.)
-- Notifications are configured via HogFunctions with the `activity-log` sub-template
-- Organization-level notifications only sent if `receive_org_level_activity_logs` is enabled for the project
-- Celery task (`posthog/tasks/activity_log.py`) broadcasts org-scoped logs to subscribed teams
-
-**Custom Activity Types & Extensions:**
-
-- Trigger dataclass for job-based activity logging with payload tracking
-- ActivityContextBase for extensible context information per activity type
-- Custom describer creation patterns for new model types and activity scopes
-
-## Feature Availability
-
-Activity logs are available on **Scale** and **Enterprise** platform packages only. They are not available on Free, Pay-as-you-go, or Boost plans. The feature is gated by `AvailableFeature.AUDIT_LOGS`.
-
-## Key Implementation Guidelines
-
-**When Adding Activity Logging to New Models:**
-
-1. Inherit from ModelActivityMixin in your model class
-2. Add the model name to ActivityScope enum
-3. Configure appropriate field_exclusions and signal_exclusions
-4. Create activity describer for frontend integration
-5. Add masked fields if handling sensitive data
-6. Write comprehensive tests covering change scenarios
-7. Consider performance impact and optimize exclusions
-
-**For Performance Optimization:**
-
-1. Analyze activity log volume and identify noisy fields
-2. Add appropriate signal_exclusions for high-frequency fields
-3. Use mute_selected_signals for bulk operations
-4. Consider field_exclusions for internal/computed fields
-5. Optimize database queries with proper indexing
-6. Monitor transaction management settings
-
-**For Debugging Activity Issues:**
-
-1. Check signal flow with model_activity_signal handlers
-2. Verify transaction management configuration
-3. Examine field exclusion configurations
-4. Test change detection logic with changes_between
-5. Validate frontend describer integration
-6. Monitor activity log creation patterns
-
-Always prioritize the balance between comprehensive audit trails and system performance. Follow PostHog's established patterns and ensure all implementations integrate seamlessly with the existing activity logging infrastructure while maintaining security and privacy standards.
+- Do not add `ModelActivityMixin` to a model without also wiring the receiver in `apps.py` `ready()`.
+- Do not put a receiver in a viewset module.
+- Do not use `mute_selected_signals()` in a request path.
+- Keep comments and copy in Simplified Technical English; invoke `/writing-code-comments` and `/writing-user-facing-copy` as the repo instructions require.
diff --git a/AGENTS.md b/AGENTS.md
index f49ef6c26386..d4d77cfe5718 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -284,6 +284,7 @@ ALWAYS invoke the matching skill **before** writing or reviewing code in these a
- [`products/conversations/skills/organizing-conversations-code/SKILL.md`](products/conversations/skills/organizing-conversations-code/SKILL.md) — adding, moving, renaming, or reviewing files under `products/conversations/`
- `/integrating-with-posthog-ai` — making a product surface work with PostHog AI: injecting scene context or custom instructions, reacting to the agent's tool calls, or rendering your product's tool cards in a thread
- `/sending-notifications` — adding notification support
+- `/adding-activity-logging` — adding activity logging (the audit trail) to a model, writing or changing a `model_activity_signal` receiver or an activity describer, auditing which write paths of a model are logged, or debugging a change that is missing from the activity log
- `/writing-skills` — creating or updating skills in `.agents/skills/`
- `/writing-evals` — adding or changing eval suites, cases, scorers, or seeders under `products/posthog_ai/evals/` or `products/*/evals/`, touching the harness in `products/posthog_ai/eval_harness/`, or running those evals
- [`ee/hogai/eval/AGENTS.md`](ee/hogai/eval/AGENTS.md) — writing eval cases or fixture data by hand anywhere (not a skill, and not covered by `/writing-evals`): where that data may come from, and why anonymizing a real conversation does not make it publishable
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.md
new file mode 100644
index 000000000000..b8926b81dfac
--- /dev/null
+++ b/docs/internal/activity-logging.md
@@ -0,0 +1,171 @@
+# Activity logging
+
+Activity logging is the audit trail of PostHog.
+A row in `posthog_activitylog` records who changed what, when, and how.
+Users read it in the Activity side panel, on an item's history tab, and on the advanced activity logs page.
+Notification destinations and workflows react to it through the `$activity_log_entry_created` internal event.
+
+This doc says how a change becomes an activity row, where the code for a new model goes, and which writes the automatic path cannot see.
+The skill `.agents/skills/adding-activity-logging/SKILL.md` carries the step-by-step workflow.
+Read this doc before you add or change activity logging.
+
+## How a change becomes an activity row
+
+```text
+model.save()
+ -> ModelActivityMixin.save() posthog/models/activity_logging/model_activity.py
+ -> reads the row as it was before the update
+ -> model_activity_signal.send(...) posthog/models/signals.py
+ -> receiver in products/<name>/backend/activity_logging.py
+ -> changes_between(before, after) posthog/models/activity_logging/activity_log.py
+ -> log_activity(...)
+ -> ActivityLog row (main database)
+ -> post_save -> $activity_log_entry_created internal event
+```
+
+The actor is not passed down this chain.
+`ActivityLoggingMiddleware` (`posthog/middleware.py`) stores the request user and the impersonation flag in a thread-local (`activity_storage`), and the mixin reads them back.
+Outside a request the user is `None`, and the row is stored with `is_system=True`.
+
+The receiver is the only part a product writes.
+The mixin, the signal, and `log_activity` are core, and they work the same for every model.
+
+## Where the code goes
+
+One receiver module per product, connected at app start.
+Seventeen products follow this shape; `products/feature_flags/backend/activity_logging.py` is a complete example in one screen, and `products/stamphog/backend/activity_logging.py` is the separate-database example.
+
+| Piece | Location | Note |
+| --------------- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Mixin | the model class, first in the bases: `class Thing(ModelActivityMixin, TeamScopedRootMixin, ...)` | Set `activity_logging_on_delete = True` when a hard delete must show in the log. A soft delete is an update and needs nothing extra. |
+| Scope | `ActivityScope` Literal in `posthog/models/activity_logging/activity_log.py` | The scope is the model's class name. The API `scope` filter enum is generated from this Literal, so run `hogli build:openapi` after you add one. |
+| Frontend scope | `ActivityScope` enum in `frontend/src/types.ts` | Same string as the class name. |
+| Receiver | `products/<name>/backend/activity_logging.py` | `@mutable_receiver(model_activity_signal, sender=Thing)`. Keep the module import-light: no DRF, no viewsets, no query runners. |
+| Wiring | `products/<name>/backend/apps.py`, in `ready()` | `from products.<name>.backend import activity_logging # noqa: F401, PLC0415` with a one-line comment that says why it must connect in every process. |
+| Receiver budget | `posthog/test/repo_invariants/setup_receivers_baseline.txt` | The startup import budget lists every receiver connected at `django.setup()`. Add the new one. |
+| Exclusions | the registries in `activity_log.py` | See "Tune the diff" below. |
+| Describer | `products/<name>/frontend/activityDescriber.tsx`, registered in `frontend/src/lib/components/ActivityLog/describers.tsx` | Optional. Without one `defaultDescriber` renders "X created / updated / deleted <name>". |
+| Tests | `products/<name>/backend/tests/`, or `posthog/test/activity_logging/` for a core model | See "Tests" below. |
+
+### Why the receiver is a separate module
+
+The receiver must connect in every process type: web, Celery, Temporal, management commands.
+A model is written from all of them.
+If the receiver lives in the viewset module, it connects only where the API loads, and a worker's writes are silently not logged.
+The batch exports receiver docstring records that failure.
+
+`ready()` runs at `django.setup()`, so the module it imports must stay light.
+A receiver that imports a viewset or a query runner drags that import graph into every process start.
+That is also why the model class, not the API module, carries the mixin.
+
+### What the receiver does
+
+```python
+@mutable_receiver(model_activity_signal, sender=Thing)
+def handle_thing_change(sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs):
+ instance = after_update or before_update
+ log_activity(
+ organization_id=instance.team.organization_id,
+ team_id=instance.team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=instance.id,
+ scope=scope,
+ activity=activity,
+ detail=Detail(
+ changes=changes_between(scope, previous=before_update, current=after_update),
+ name=instance.name,
+ ),
+ )
+```
+
+`activity` is `created`, `updated`, or `deleted`.
+A receiver may resolve it further, for example a change of `deleted` from false to true becomes `deleted`, and back becomes `restored` (feature flags do this).
+
+`Detail` carries the display name, the change list, an optional `Trigger` (a job that caused the change), and an optional `context` dataclass that extends `ActivityContextBase` with fields the describer needs (alerts pass the insight id and name).
+
+`log_activity` drops an `updated` row with an empty change list unless `force_save=True`.
+
+### Tune the diff
+
+`changes_between` compares every model field except the ones in `common_field_exclusions` (ids, timestamps, `team`, `created_by`, and similar).
+Four registries in `activity_log.py` tune it per scope:
+
+- `signal_exclusions` - skip logging when only these fields changed. Use it for bookkeeping fields a job touches on every run (`last_checked_at`, `next_check_at`).
+- `field_exclusions` - drop these fields from the diff but still log the row.
+- `field_with_masked_contents` - record that the field changed, never its values. Use it for secrets and encrypted inputs.
+- `field_name_overrides` - rename a field in the stored change so the describer shows the user-facing label.
+
+## Writes the signal cannot see
+
+The mixin hooks `save()` and `delete()`.
+Everything that bypasses them bypasses the log:
+
+- `QuerySet.update()`
+- `bulk_create()` and `bulk_update()`
+- raw SQL
+- a save inside `mute_selected_signals()`
+
+Before you rely on the mixin, list every write path of the model: `grep` for `.update(`, `bulk_create(`, `bulk_update(`, and `.save(` on that model across the product, including tasks, Temporal activities, and webhook handlers.
+For each bulk write, log at the site with `log_activity` or `bulk_log_activity`, build the `Change` objects by hand, and pass a `Trigger` that names the job and its id.
+Fetch the values the update will change before you run it, and log a change only for rows whose value actually changes.
+
+`mute_selected_signals()` sets a process-wide flag, not a thread-local one.
+Use it only in an offline maintenance job.
+In a request path it mutes activity for every other request the process serves at that moment.
+
+## Actor and context outside requests
+
+A Celery task, a Temporal activity, or a webhook handler has no request user.
+The row is a system row.
+To attribute it to a job, pass a `Trigger(job_type=..., job_id=..., payload=...)` in `Detail`.
+A receiver can also read one from `get_current_trigger()` when the job wrapped its write in `ActivityTriggerContext(...)`; the receiver has to read and pass it, the context alone stores nothing.
+
+A model with a fail-closed manager (`TeamScopedRootMixin`, `ProductTeamModel`) raises `TeamScopeError` on any query without team context.
+The mixin's before-update read is by primary key without a team filter (`unscoped()`), so a `save()` outside a request works.
+Your own reads in the same path still need `with team_scope(team_id):` or `Model.objects.for_team(team_id)`.
+See `posthog/models/scoping/README.md`.
+
+## Product models on a separate database
+
+`ActivityLog` lives on the main database.
+A product routed to its own database (`products/db_routing.yaml`) writes across two connections, and three things change:
+
+**No `.team` accessor.**
+`ProductTeamModel.team_id` is a plain integer, not a foreign key.
+The receiver reads `organization_id` from `Team` on the main database:
+`Team.objects.filter(id=instance.team_id).values_list("organization_id", flat=True).first()`.
+
+**The audit write must wait for the product database commit.**
+`log_activity` defers its insert with `transaction.on_commit` when the connection it watches is inside a transaction.
+By default it watches the default connection.
+A product write runs inside `transaction.atomic(using=router.db_for_write(Model))`, on another connection, while the default connection is in autocommit.
+Without `using`, the audit row is inserted at once and survives a rollback of the product row.
+Pass `using=router.db_for_write(Model)` to `log_activity` and `bulk_log_activity`.
+A callback registered inside a rolled-back transaction is discarded, so the audit row is dropped with the product row.
+
+**The before-update read is pinned to the writer.**
+The mixin reads the previous state by primary key through `router.db_for_write(Model)`, so a lagged reader replica cannot produce a stale diff.
+Explicit logging at a bulk-write site should read its before-values from the writer too.
+
+## Reading the log
+
+- `GET /api/projects/:id/activity_log/` - the list the side panel reads.
+- `GET /api/projects/:id/advanced_activity_logs/` - filters, field discovery, and export.
+- Access control: resource `activity_log`, default level `viewer`.
+- Entitlement: the advanced endpoint is gated by `AvailableFeature.AUDIT_LOGS` and applies the entitlement's lookback window (`get_activity_log_lookback_restriction` in `posthog/models/activity_logging/retention.py`). The plain list the side panel reads is not gated the same way. Writes always happen.
+- `activity_visibility_restrictions` hides selected rows from non-staff users (login events of impersonated sessions).
+
+A scene that wants its own paginated history registers its URL in `activityLogLogic.tsx`.
+Most scenes do not need this; the side panel and deep links work without it.
+
+## Tests
+
+Test the behavior the receiver adds, through a public interface, at the cheapest level:
+
+- One test that a write through the API or the facade creates a row with the expected `activity` and `changes`.
+- One test per bulk-write site that its explicit logging produces the expected rows.
+- A `changes_between` test only when the scope adds exclusions or masks.
+- For a separate-database product, one test that a rolled-back product write leaves no row (`override_settings(ACTIVITY_LOG_TRANSACTION_MANAGEMENT=True)` plus `captureOnCommitCallbacks(using=<writer alias>, execute=True)`).
+
+`ACTIVITY_LOG_TRANSACTION_MANAGEMENT` is off under test, so a plain test sees the row right after the write.
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 869050cb3abd..7c999953211a 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -1076,10 +1076,12 @@ def _report_activity_log_write_failure(e: Exception, error_context: dict, deferr
ACTIVITY_LOG_WRITE_FAILURES.labels(deferred=str(deferred).lower()).inc()
-def _handle_activity_log_transaction(create_fn, error_context: dict):
+def _handle_activity_log_transaction(create_fn, error_context: dict, *, using: str | None = None):
try:
# Check if we're in a transaction, if yes, defer the activity log creation to the commit signal
- if not transaction.get_autocommit() and getattr(settings, "ACTIVITY_LOG_TRANSACTION_MANAGEMENT", True):
+ if not transaction.get_autocommit(using=using) and getattr(
+ settings, "ACTIVITY_LOG_TRANSACTION_MANAGEMENT", True
+ ):
# The transaction already committed by the time this callback runs, so its own guard
# keeps a slow audit write from failing a request whose data is already durable.
def _deferred_create():
@@ -1090,7 +1092,7 @@ def _handle_activity_log_transaction(create_fn, error_context: dict):
if settings.TEST:
raise
- transaction.on_commit(_deferred_create)
+ transaction.on_commit(_deferred_create, using=using)
return None
else:
return create_fn()
@@ -1116,6 +1118,9 @@ def log_activity(
ip_address: Optional[str] = None,
force_save: bool = False,
instance_only: bool = False,
+ # A product on its own database passes `router.db_for_write(Model)`, so the audit write waits
+ # for that connection's commit and is dropped when it rolls back. `None` uses the default one.
+ using: str | None = None,
) -> ActivityLog | None:
if client is None:
client = activity_storage.get_client()
@@ -1184,6 +1189,7 @@ def log_activity(
"scope": scope,
"activity": activity,
},
+ using=using,
)
except Exception as e:
@@ -1216,13 +1222,16 @@ class LogActivityEntry(TypedDict, total=False):
def bulk_log_activity(
- log_entries: list[LogActivityEntry], batch_size: int = 500, *, notify: bool = True
+ log_entries: list[LogActivityEntry], batch_size: int = 500, *, notify: bool = True, using: str | None = None
) -> list[ActivityLog]:
"""Write activity log rows in bulk.
Each row created also fires `post_save`, which produces a CDP internal event so customer
destinations and workflows can react. Pass `notify=False` for a maintenance sweep, where that
fan-out would put one event per affected row onto the internal-events topic.
+
+ A product on its own database passes `using=router.db_for_write(Model)`, so the audit write
+ waits for that connection's commit and is dropped when it rolls back.
"""
if not log_entries:
return []
@@ -1273,6 +1282,7 @@ def bulk_log_activity(
"activity": "bulk_create",
"log_entries": log_entries,
},
+ using=using,
)
or []
)
diff --git a/posthog/models/activity_logging/model_activity.py b/posthog/models/activity_logging/model_activity.py
index 032a4ed64d87..4605cf2234af 100644
--- a/posthog/models/activity_logging/model_activity.py
+++ b/posthog/models/activity_logging/model_activity.py
@@ -1,8 +1,9 @@
from typing import Any
-from django.db import models
+from django.db import models, router
from posthog.models.activity_logging.utils import activity_storage, get_changed_fields_local
+from posthog.models.scoping.manager import TeamScopedManager
from posthog.models.signals import model_activity_signal
@@ -93,8 +94,18 @@ class ModelActivityMixin(models.Model):
if isinstance(soft_deleted_manager, models.Manager) and soft_deleted_manager not in managers:
managers.append(soft_deleted_manager)
+ # Read the before-state from the write database: a replica can still serve the row as it
+ # was before an earlier write, which would make the logged changes wrong.
+ write_db = router.db_for_write(self.__class__)
+
+ queryset: models.QuerySet
for manager in managers:
- before_update = manager.filter(pk=self.pk).first()
+ # A read by primary key of a row the caller holds needs no team filter, and a fail-closed
+ # manager refuses to build a queryset without team context, which a save outside a request
+ # has none of. Same shape as the _get_before_update overrides on Loop and SignalScoutConfig.
+ queryset = manager.unscoped() if isinstance(manager, TeamScopedManager) else manager.all()
+
+ before_update = queryset.using(write_db).filter(pk=self.pk).first()
if before_update:
break
diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.py
index 8600cd2d10f5..1aa949fb79a7 100644
--- a/posthog/test/activity_logging/test_activity_logging.py
+++ b/posthog/test/activity_logging/test_activity_logging.py
@@ -10,8 +10,11 @@ from posthog.models import User
from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, Trigger, log_activity
from posthog.models.activity_logging.model_activity import ActivityTriggerContext
from posthog.models.activity_logging.utils import activity_storage, activity_visibility_manager
+from posthog.models.scoping import team_scope
from posthog.models.utils import UUIDT
+from products.dashboards.backend.models.dashboard_widget import DashboardWidget
+
class TestActivityLogModel(BaseTest):
def test_can_save_a_model_changed_activity_log(self) -> None:
@@ -246,6 +249,23 @@ class TestActivityLogModel(BaseTest):
self.assertIsInstance(warning.kwargs["exception"], ValueError)
+class TestModelActivityMixinTeamScoping(BaseTest):
+ def test_update_outside_team_scope_still_logs_the_change(self) -> None:
+ # DashboardWidget reads through a fail-closed manager, and a save from a Celery task or a
+ # management command carries no team context for it to read the before-state with.
+ with team_scope(self.team.id):
+ widget = DashboardWidget.objects.create(team=self.team, widget_type="insight", name="Weekly signups")
+
+ widget.name = "Monthly signups"
+ widget.save()
+
+ log: ActivityLog = ActivityLog.objects.filter(
+ scope="DashboardWidget", item_id=str(widget.id), activity="updated"
+ ).latest("id")
+ assert log.detail is not None
+ self.assertIn("name", [change["field"] for change in log.detail["changes"]])
+
+
class TestActivityLogVisibilityManager(BaseTest):
@parameterized.expand(
[