Skip to content

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

feat(flags): return who made each flag edit from the edit history read (#123624)

Gustavo H. Strassburger12a7c0bdc60b
diff --git a/products/feature_flags/backend/activity_logging.py b/products/feature_flags/backend/activity_logging.py
index 6e652adc64d4..6268a24022ca 100644
--- a/products/feature_flags/backend/activity_logging.py
+++ b/products/feature_flags/backend/activity_logging.py
@@ -1,6 +1,7 @@
from posthog.models.activity_logging.activity_log import Detail, Trigger, changes_between, log_activity
from posthog.models.signals import model_activity_signal, mutable_receiver
+from products.feature_flags.backend.facade.enums import SCHEDULED_CHANGE_JOB_TYPE
from products.feature_flags.backend.models.feature_flag import FeatureFlag
# Lives here, not in api/feature_flag.py, so it can wire at AppConfig.ready() without dragging that
@@ -31,7 +32,7 @@ def handle_feature_flag_change(
trigger = getattr(after_update, "_activity_trigger", None)
if is_scheduled_change and trigger is None:
trigger = Trigger(
- job_type="scheduled_change",
+ job_type=SCHEDULED_CHANGE_JOB_TYPE,
job_id=str(scheduled_change_id),
payload={"scheduled_change_id": scheduled_change_id},
)
diff --git a/products/feature_flags/backend/facade/edit_history.py b/products/feature_flags/backend/facade/edit_history.py
index 1d678fef94da..a5f376a1bf7f 100644
--- a/products/feature_flags/backend/facade/edit_history.py
+++ b/products/feature_flags/backend/facade/edit_history.py
@@ -5,15 +5,17 @@ flag-level aggregation, and the bucketing settings. Pass them to ``facade.edits`
"""
from datetime import datetime
+from enum import StrEnum
from typing import Any
from django.db.models import F, Func, JSONField, Q, Value
from django.db.models.fields.json import KT
from posthog.dataclasses import frozen
-from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.activity_logging.activity_log import AGENT_TRIGGER_JOB_TYPE, ActivityLog
from products.feature_flags.backend.facade.edits import BucketingSetting
+from products.feature_flags.backend.facade.enums import SCHEDULED_CHANGE_JOB_TYPE
# The activity log fields of a flag save that can change who gets which value.
_FILTERS = "filters"
@@ -57,11 +59,36 @@ class FlagEditSide:
}
+class FlagEditAuthor(StrEnum):
+ """
+ Who made a flag edit. An edit that another product triggers, such as an experiment exposure freeze, keeps the
+ author of the action that caused it. Read `FlagEdit.job_type` to find those edits. When an agent causes such an
+ edit, the author is PERSON, because `log_activity` adds the agent trigger only when the product sets no trigger.
+ """
+
+ # A user saved the flag, and no agent or scheduled change acted for them. A save outside a request that sets no
+ # trigger also reads as PERSON, because the row records the flag's last modifier.
+ PERSON = "person"
+ # An agent saved the flag for a user. The agent trigger comes from a server-set task id or from the intent
+ # header that agent clients such as the MCP server send, so the caller can claim it.
+ AGENT = "agent"
+ # A scheduled change applied the edit.
+ SCHEDULED_CHANGE = "scheduled_change"
+ # PostHog saved the flag outside a user request.
+ SYSTEM = "system"
+
+
@frozen
class FlagEdit:
changed_at: datetime
# The `job_type` of the activity log trigger, or None when the trigger has no job type.
job_type: str | None
+ author: FlagEditAuthor
+ # The user on the activity log row, which is the flag's last modifier at save time. An agent and a scheduled
+ # change carry one too, so read `author` to learn who made the edit. None when that user was deleted.
+ user_id: int | None
+ # True when a staff member made the edit while impersonating the user in `user_id`.
+ was_impersonated: bool
before: FlagEditSide
after: FlagEditSide
@@ -92,12 +119,15 @@ def flag_edits_since(*, team_id: int, feature_flag_id: int, since: datetime, lim
**{f"before_{setting}": _changed(field, "before") for setting, field in _SETTING_FIELDS.items()},
**{f"after_{setting}": _changed(field, "after") for setting, field in _SETTING_FIELDS.items()},
)
- .values("created_at", "job_type", *_PROJECTED)[:limit]
+ .values("created_at", "job_type", "is_system", "user_id", "was_impersonated", *_PROJECTED)[:limit]
)
return tuple(
FlagEdit(
changed_at=row["created_at"],
job_type=row["job_type"],
+ author=_author(job_type=row["job_type"], is_system=row["is_system"], user_id=row["user_id"]),
+ user_id=row["user_id"],
+ was_impersonated=bool(row["was_impersonated"]),
before=_side(row, "before"),
after=_side(row, "after"),
)
@@ -105,6 +135,19 @@ def flag_edits_since(*, team_id: int, feature_flag_id: int, since: datetime, lim
)
+def _author(*, job_type: str | None, is_system: bool | None, user_id: int | None) -> FlagEditAuthor:
+ # Check the trigger before the user, because an agent and a scheduled change save the flag as a user.
+ if job_type == AGENT_TRIGGER_JOB_TYPE:
+ return FlagEditAuthor.AGENT
+ if job_type == SCHEDULED_CHANGE_JOB_TYPE:
+ return FlagEditAuthor.SCHEDULED_CHANGE
+ # Deleting a user sets the user column to NULL on their rows, so the user column decides only when `is_system`
+ # is unset.
+ if is_system or (is_system is None and user_id is None):
+ return FlagEditAuthor.SYSTEM
+ return FlagEditAuthor.PERSON
+
+
def _side(row: dict[str, Any], side: str) -> FlagEditSide:
return FlagEditSide(
variants=row[f"{side}_variants"],
diff --git a/products/feature_flags/backend/facade/enums.py b/products/feature_flags/backend/facade/enums.py
index 2e0582255383..e667b3701f89 100644
--- a/products/feature_flags/backend/facade/enums.py
+++ b/products/feature_flags/backend/facade/enums.py
@@ -22,3 +22,7 @@ class FlagEvaluationsMode(LabeledIntEnum):
# the ingestion allowlist still writes to events. INGESTION_FLAG_EVALUATIONS_ONLY_DISABLED makes
# ingestion treat this mode as READ_FLAG_EVALUATIONS for every organization.
FLAG_EVALUATIONS_ONLY = 2, "Flag evaluations only"
+
+
+# The activity log trigger `job_type` of a flag save that a scheduled change applies.
+SCHEDULED_CHANGE_JOB_TYPE = "scheduled_change"
diff --git a/products/feature_flags/backend/test/test_facade_edit_history.py b/products/feature_flags/backend/test/test_facade_edit_history.py
new file mode 100644
index 000000000000..f41c1edc49e4
--- /dev/null
+++ b/products/feature_flags/backend/test/test_facade_edit_history.py
@@ -0,0 +1,61 @@
+from datetime import timedelta
+from typing import Any
+
+from posthog.test.base import BaseTest
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.activity_logging.activity_log import ActivityLog
+
+from products.feature_flags.backend.facade.edit_history import FlagEditAuthor, flag_edits_since
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+class TestFlagEditsSince(BaseTest):
+ @parameterized.expand(
+ [
+ ("person", True, False, None, False, FlagEditAuthor.PERSON),
+ ("agent", True, False, "agent", False, FlagEditAuthor.AGENT),
+ ("scheduled_change", True, False, "scheduled_change", False, FlagEditAuthor.SCHEDULED_CHANGE),
+ ("system", False, True, None, False, FlagEditAuthor.SYSTEM),
+ ("deleted_user", False, False, None, False, FlagEditAuthor.PERSON),
+ ("legacy_row_without_a_user", False, None, None, None, FlagEditAuthor.SYSTEM),
+ ("exposure_freeze_by_a_person", True, False, "experiment_exposure_frozen", False, FlagEditAuthor.PERSON),
+ ("impersonated", True, False, None, True, FlagEditAuthor.PERSON),
+ ]
+ )
+ def test_author(
+ self,
+ _name: str,
+ has_user: bool,
+ is_system: bool | None,
+ job_type: str | None,
+ was_impersonated: bool | None,
+ expected: FlagEditAuthor,
+ ) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="authored")
+ detail: dict[str, Any] = {
+ "changes": [{"type": "FeatureFlag", "action": "changed", "field": "key", "before": "a", "after": "b"}]
+ }
+ if job_type:
+ detail["trigger"] = {"job_type": job_type, "job_id": "1", "payload": {}}
+ ActivityLog.objects.create(
+ team_id=self.team.id,
+ scope="FeatureFlag",
+ item_id=str(flag.id),
+ activity="updated",
+ user=self.user if has_user else None,
+ is_system=is_system,
+ was_impersonated=was_impersonated,
+ detail=detail,
+ )
+
+ (edit,) = flag_edits_since(
+ team_id=self.team.id, feature_flag_id=flag.id, since=timezone.now() - timedelta(days=1), limit=2
+ )
+
+ assert edit.author == expected
+ assert edit.user_id == (self.user.id if has_user else None)
+ assert edit.was_impersonated == bool(was_impersonated)