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-logs): apply retention and visibility rules to SQL access (#82573)

Yasen5a2f01761080
diff --git a/ee/hogai/context/activity_log/context.py b/ee/hogai/context/activity_log/context.py
index 3b89d3659eb0..da59acc4c9be 100644
--- a/ee/hogai/context/activity_log/context.py
+++ b/ee/hogai/context/activity_log/context.py
@@ -5,7 +5,6 @@ from typing import Any, cast
from django.db.models import QuerySet
-from posthog.api.advanced_activity_logs.utils import get_activity_log_lookback_restriction
from posthog.api.advanced_activity_logs.viewset import apply_organization_scoped_filter
from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import (
@@ -14,6 +13,7 @@ from posthog.models.activity_logging.activity_log import (
apply_activity_visibility_restrictions,
field_name_overrides,
)
+from posthog.models.activity_logging.retention import get_activity_log_lookback_restriction
from posthog.sync import database_sync_to_async
from ee.hogai.context.activity_log.prompts import (
diff --git a/posthog/api/advanced_activity_logs/constants.py b/posthog/api/advanced_activity_logs/constants.py
index 52ff7d5f0995..b4028fcba30d 100644
--- a/posthog/api/advanced_activity_logs/constants.py
+++ b/posthog/api/advanced_activity_logs/constants.py
@@ -3,6 +3,3 @@ BATCH_SIZE = 10000
SAMPLING_PERCENTAGE = 10
CACHE_TTL_SECONDS = 12 * 60 * 60 # 12 hours
CACHE_KEY_PREFIX = "activity_log:details_fields"
-# Fallbacks need to be kept in sync with the smallest AUDIT_LOG feature limits in billing
-ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_LIMIT = 2
-ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_UNIT = "months"
diff --git a/posthog/api/advanced_activity_logs/utils.py b/posthog/api/advanced_activity_logs/utils.py
deleted file mode 100644
index 414b8f666d01..000000000000
--- a/posthog/api/advanced_activity_logs/utils.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from datetime import datetime, timedelta
-from typing import Optional
-
-from django.utils import timezone
-
-from posthog.constants import AvailableFeature
-from posthog.models import Organization
-
-from .constants import ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_LIMIT, ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_UNIT
-
-
-def get_activity_log_lookback_restriction(organization: Organization) -> Optional[datetime]:
- """Get the lookback restriction date based on the AUDIT_LOGS feature."""
- audit_log_feature = organization.get_available_feature(AvailableFeature.AUDIT_LOGS)
-
- if not audit_log_feature:
- return None
-
- limit = audit_log_feature.get("limit")
- unit = audit_log_feature.get("unit")
-
- if limit is None or unit is None:
- limit = ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_LIMIT
- unit = ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_UNIT
-
- unit_lower = unit.lower()
- if unit_lower in ("day", "days"):
- delta = timedelta(days=limit)
- elif unit_lower in ("month", "months"):
- delta = timedelta(days=limit * 30)
- elif unit_lower in ("year", "years"):
- delta = timedelta(days=limit * 365)
- else:
- raise ValueError(f"Invalid unit: {unit}")
-
- return timezone.now() - delta
diff --git a/posthog/api/advanced_activity_logs/viewset.py b/posthog/api/advanced_activity_logs/viewset.py
index 698f6b7da938..33ad89235876 100644
--- a/posthog/api/advanced_activity_logs/viewset.py
+++ b/posthog/api/advanced_activity_logs/viewset.py
@@ -27,6 +27,7 @@ from posthog.models.activity_logging.activity_log import (
ActivityScope,
apply_activity_visibility_restrictions,
)
+from posthog.models.activity_logging.retention import get_activity_log_lookback_restriction
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.user import User
from posthog.permissions import PremiumFeaturePermission
@@ -38,7 +39,6 @@ from products.exports.backend.source_authentication import get_export_source_aut
from .field_discovery import AdvancedActivityLogFieldDiscovery
from .filters import AdvancedActivityLogFilterManager, validate_detail_filters
from .ocsf import ActivityLogOCSFSerializer
-from .utils import get_activity_log_lookback_restriction
ACTIVITY_LOG_ORDERING_DESCENDING = "-created_at"
ACTIVITY_LOG_ORDERING_ASCENDING = "created_at"
diff --git a/posthog/hogql/context.py b/posthog/hogql/context.py
index 51614a05534f..a6d2c58dde4c 100644
--- a/posthog/hogql/context.py
+++ b/posthog/hogql/context.py
@@ -1,4 +1,5 @@
from dataclasses import dataclass, field
+from datetime import datetime
from functools import cached_property
from typing import TYPE_CHECKING, Any, Literal, Optional
@@ -40,6 +41,8 @@ class HogQLFieldAccess:
sql: str
+# Mutable by design, because the resolver and the printers accumulate into it as they walk a query:
+# bound values, notices, warnings, and the lazily-resolved retention floors below.
@dataclass(frozen=False)
class HogQLContext:
"""Context given to a HogQL expression printer"""
@@ -151,6 +154,13 @@ class HogQLContext:
# HogQLQueryModifier, so a query can't disable enforcement.
apply_events_retention_floor: bool = True
+ # Entitlement-derived floors for federated tables that declare a `retention_field`, keyed by
+ # Postgres table name so two such tables can never share one window. Resolved lazily by the
+ # ClickHouse printer the first time each table is printed, so a query that reads none of them
+ # never pays the organization load. A stored None means "resolved, no restriction", which is why
+ # membership rather than truthiness decides whether the lookup already ran.
+ postgres_retention_starts: dict[str, Optional[datetime]] = field(default_factory=dict, compare=False, repr=False)
+
def __post_init__(self):
if self.team:
self.team_id = self.team.id
diff --git a/posthog/hogql/database/models.py b/posthog/hogql/database/models.py
index 81726d0ece3f..9079821ada98 100644
--- a/posthog/hogql/database/models.py
+++ b/posthog/hogql/database/models.py
@@ -242,7 +242,12 @@ class Table(FieldOrTable):
def to_printed_hogql(self) -> str:
raise NotImplementedError("Table.to_printed_hogql not overridden")
- def get_predicates(self) -> list[Expr]:
+ def get_predicates(self, context: Optional["HogQLContext"] = None) -> list[Expr]:
+ """Predicates the printer ANDs onto every scan of this table.
+
+ `context` lets a table shape them per query — a predicate referencing another table has to
+ know whether that table is in this caller's schema, since access control may have removed it.
+ """
return []
def avoid_asterisk_fields(self) -> list[str]:
diff --git a/posthog/hogql/database/postgres_table.py b/posthog/hogql/database/postgres_table.py
index 0534cc83c778..d6e4f2daa160 100644
--- a/posthog/hogql/database/postgres_table.py
+++ b/posthog/hogql/database/postgres_table.py
@@ -1,5 +1,6 @@
+from datetime import datetime
from functools import cache
-from typing import Optional, cast
+from typing import TYPE_CHECKING, Optional, cast
from django.conf import settings
@@ -14,6 +15,9 @@ from posthog.person_db_router import PERSONS_DB_MODELS
from posthog.persons_db import persons_db_url
from posthog.scopes import APIScopeObject
+if TYPE_CHECKING:
+ from posthog.models.team.team import Team
+
@cache
def _pk_column_for_pg_table(postgres_table_name: str) -> Optional[str]:
@@ -107,11 +111,24 @@ class PostgresTable(FunctionCallTable):
# different space than this table's ids, so its rows can't be narrowed to a grant and
# resource-level access is required to query it at all.
resource_level_access_only: bool = False
+ # Column the entitlement-derived retention floor filters on, for tables whose rows are only
+ # readable back as far as the organization's plan allows. The floor is pushed into the federated
+ # read next to the team guard (see ClickHousePrinter._print_table_ref), so it prunes in Postgres
+ # rather than after the rows have been copied out. None means the table has no retention window.
+ retention_field: Optional[str] = None
predicates: list[Expr] = []
- def get_predicates(self) -> list[Expr]:
+ def get_predicates(self, context: Optional[HogQLContext] = None) -> list[Expr]:
return self.predicates
+ def retention_start(self, team: Optional["Team"], team_id: Optional[int]) -> Optional[datetime]:
+ """Oldest `retention_field` value this team may read, or None when unrestricted.
+
+ Each table owns its own window, so two tables that declare `retention_field` can never end
+ up sharing one. Tables with no window inherit this default and are never floored.
+ """
+ return None
+
@property
def primary_key(self) -> Optional[str]:
return _pk_column_for_pg_table(self.postgres_table_name)
diff --git a/posthog/hogql/database/schema/activity_log_visibility.py b/posthog/hogql/database/schema/activity_log_visibility.py
new file mode 100644
index 000000000000..bfd7653ce65c
--- /dev/null
+++ b/posthog/hogql/database/schema/activity_log_visibility.py
@@ -0,0 +1,92 @@
+import json
+import hashlib
+from functools import lru_cache
+
+from posthog.hogql import ast
+from posthog.hogql.base import Expr
+from posthog.hogql.parser import parse_expr
+
+# Scopes whose rows the REST viewsets restrict per user, which a static predicate cannot express.
+#
+# `restrict_loop_activity` allows the loops a user may see, computed from live per-loop visibility
+# and object-level RBAC. There is no `system.loops` table to defer that decision to, so SQL drops
+# every Loop row rather than guess. `restrict_canvas_activity` has the same shape, but
+# `system.canvases` already exposes exactly the canvases a caller may read, so Canvas rows defer to
+# it. That table is stricter than the viewset — public channels only, and no soft-deleted rows — so
+# SQL hides a superset of what REST hides, never less. Deferring to it makes activity-log rows depend
+# on the caller's canvas grants, so a read of this table also partitions the query cache on `canvas`
+# (see `_TRANSITIVE_SYSTEM_TABLE_SCOPES`) — a cache hit returns before these predicates ever print.
+CANVASES_TABLE = "system.canvases"
+_LOOP_ROWS_HIDDEN = "NOT (scope = 'Loop')"
+_CANVAS_ROWS_HIDDEN = "NOT (scope = 'Canvas')"
+_CANVAS_ROWS_LIMITED_TO_READABLE_CANVASES = (
+ f"NOT (scope = 'Canvas' AND item_id NOT IN (SELECT id FROM {CANVASES_TABLE}))"
+)
+
+# Bumped whenever the compilation shape changes in a way the hashed inputs below cannot see, e.g. a rule
+# key starting to matter, or a predicate gaining a clause that reads a new column.
+_POLICY_SHAPE = 1
+
+
+@lru_cache(maxsize=1)
+def activity_log_visibility_policy_version() -> str:
+ """Fingerprint of the rules this module compiles, for the query cache key.
+
+ Nothing else in the key tracks them, and a cache hit returns before they print, so a result stored
+ under the previous rules would keep serving the rows the current ones hide.
+ `HogQLQueryRunner.get_cache_payload` folds this into the key of every query reading the table, so a
+ rule change retires those results. Hashing the inputs rather than hand-bumping a version means
+ editing the shared rule list is enough; nobody has to remember the second step.
+ """
+ # Deferred to keep the ORM off this module's import path, as elsewhere in the schema layer.
+ from posthog.models.activity_logging.activity_log import activity_visibility_restrictions # noqa: PLC0415
+
+ material = json.dumps(
+ {
+ "shape": _POLICY_SHAPE,
+ "rules": [[rule["scope"], sorted(rule["activities"])] for rule in activity_visibility_restrictions],
+ "scope_predicates": [_LOOP_ROWS_HIDDEN, _CANVAS_ROWS_HIDDEN, _CANVAS_ROWS_LIMITED_TO_READABLE_CANVASES],
+ },
+ sort_keys=True,
+ )
+ return hashlib.sha256(material.encode()).hexdigest()[:16]
+
+
+@lru_cache(maxsize=2)
+def activity_visibility_predicates(canvases_readable: bool) -> tuple[Expr, ...]:
+ """HogQL form of the activity-log visibility rules, for the federated `system.activity_logs` read.
+
+ A second compiler over the same rule list that `ActivityLogVisibilityManager.build_exclusion_query`
+ compiles to a Django Q, plus the per-user scope rules above that the list cannot hold. Together
+ these hide at least what the REST viewsets hide. They are deliberately not an exact port: every
+ difference below over-hides, so a row readable here is readable through the API too.
+
+ - `allow_staff` is ignored. This table is the customer's surface, so restricted rows stay hidden
+ on it unconditionally.
+ - `exclude_when` is ignored, so a rule matches on (scope, activity) alone. The only rule using it
+ keys on `was_impersonated`, and exposing that column would itself disclose the impersonation the
+ rule exists to hide. Over-excluding costs nothing: login rows carry `team_id=None` (see
+ `log_login_activity`), so the mandatory team guard already puts them out of reach.
+ - Loop rows are dropped outright, and Canvas rows follow `system.canvases`, per the note above.
+
+ `canvases_readable` says whether `system.canvases` is in the caller's schema. When the canvas
+ resource is denied outright the table is removed (see `_apply_system_table_access`), and a
+ predicate referencing it would raise rather than filter — so Canvas rows are dropped instead,
+ which is what a caller who may read no canvas would see anyway.
+ """
+ # Deferred to keep the ORM off this module's import path, as elsewhere in the schema layer.
+ from posthog.models.activity_logging.activity_log import activity_visibility_restrictions # noqa: PLC0415
+
+ compiled = [
+ parse_expr(
+ "NOT (scope = {scope} AND activity IN {activities})",
+ {
+ "scope": ast.Constant(value=rule["scope"]),
+ "activities": ast.Constant(value=list(rule["activities"])),
+ },
+ )
+ for rule in activity_visibility_restrictions
+ ]
+ compiled.append(parse_expr(_LOOP_ROWS_HIDDEN))
+ compiled.append(parse_expr(_CANVAS_ROWS_LIMITED_TO_READABLE_CANVASES if canvases_readable else _CANVAS_ROWS_HIDDEN))
+ return tuple(compiled)
diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.py
index 352895d5e65e..0695f8f33ad4 100644
--- a/posthog/hogql/database/schema/system.py
+++ b/posthog/hogql/database/schema/system.py
@@ -1,4 +1,6 @@
+from datetime import datetime
from functools import lru_cache
+from typing import TYPE_CHECKING, Optional
from posthog.hogql import ast
from posthog.hogql.base import Expr
@@ -25,6 +27,7 @@ from posthog.hogql.database.models import (
UUIDDatabaseField,
)
from posthog.hogql.database.postgres_table import PostgresTable
+from posthog.hogql.database.schema.activity_log_visibility import CANVASES_TABLE, activity_visibility_predicates
from posthog.hogql.database.schema.information_schema import information_schema_node
from posthog.hogql.errors import ResolutionError
from posthog.hogql.parser import parse_expr, parse_select
@@ -32,6 +35,9 @@ from posthog.hogql.parser import parse_expr, parse_select
from posthog.constants import AvailableFeature
from posthog.scopes import APIScopeObject
+if TYPE_CHECKING:
+ from posthog.models.team.team import Team
+
from products.customer_analytics.backend.facade.hogql import (
account_channel_summaries,
account_custom_property_values,
@@ -1318,12 +1324,33 @@ file_system: PostgresTable = PostgresTable(
},
)
-activity_logs: PostgresTable = PostgresTable(
+
+class _ActivityLogsTable(PostgresTable):
+ """Compiles its visibility rules on first use rather than at import: the rule list lives under
+ `posthog.models`, and this module keeps the ORM off its import path."""
+
+ def get_predicates(self, context: Optional[HogQLContext] = None) -> list[Expr]:
+ # The Canvas rule reads `system.canvases`, which access control removes from the schema for a
+ # caller denied the canvas resource; without the table it drops Canvas rows instead.
+ canvases_readable = (
+ context is not None and context.database is not None and context.database.has_table(CANVASES_TABLE)
+ )
+ return list(activity_visibility_predicates(canvases_readable))
+
+ def retention_start(self, team: Optional["Team"], team_id: Optional[int]) -> Optional[datetime]:
+ from posthog.models.activity_logging.retention import activity_log_retention_start_for_team # noqa: PLC0415
+
+ return activity_log_retention_start_for_team(team, team_id)
+
+
+activity_logs: _ActivityLogsTable = _ActivityLogsTable(
name="activity_logs",
postgres_table_name="posthog_activitylog",
access_scope="activity_log",
# Matches `premium_feature_on_cloud` on the REST activity-log viewsets, which gate the same rows.
required_feature_on_cloud=AvailableFeature.AUDIT_LOGS,
+ # Same lookback the REST viewsets apply, so the SQL surface can't read past the plan's window.
+ retention_field="created_at",
description="Audit trail of changes to objects (insights, flags, dashboards, etc.); one row per logged activity.",
fields={
"id": StringDatabaseField(name="id", description="Activity log entry UUID."),
diff --git a/posthog/hogql/database/test/test_activity_logs_restrictions.py b/posthog/hogql/database/test/test_activity_logs_restrictions.py
new file mode 100644
index 000000000000..84dcea6a30a8
--- /dev/null
+++ b/posthog/hogql/database/test/test_activity_logs_restrictions.py
@@ -0,0 +1,284 @@
+from datetime import timedelta
+from typing import Literal
+
+from freezegun import freeze_time
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.schema import HogQLQuery
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.database.models import (
+ DANGEROUS_NoTeamIdCheckTable,
+ DateTimeDatabaseField,
+ IntegerDatabaseField,
+ TableNode,
+)
+from posthog.hogql.database.postgres_table import PostgresTable
+from posthog.hogql.database.schema.activity_log_visibility import activity_log_visibility_policy_version
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.query import create_default_modifiers_for_team
+
+from posthog.constants import AvailableFeature
+from posthog.hogql_queries.query_runner import get_query_runner
+from posthog.models.activity_logging.activity_log import activity_visibility_restrictions
+from posthog.models.activity_logging.retention import get_activity_log_lookback_restriction
+from posthog.models.organization import OrganizationMembership
+
+from products.access_control.backend.models.access_control import AccessControl
+
+# The SQL surface must hide what the REST viewsets hide: rows past the plan's retention window, and
+# rows the visibility rules restrict. Both are printed guards, so the printed SQL is the assertion.
+
+
+class TestActivityLogsSqlRestrictions(BaseTest):
+ def _set_audit_logs_feature(self, **feature) -> None:
+ self.organization.available_product_features = [{"key": "audit_logs", "name": "Audit logs", **feature}]
+ self.organization.save()
+
+ def _context(self) -> HogQLContext:
+ return HogQLContext(
+ team=self.team,
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ database=Database.create_for(team=self.team, user=self.user),
+ modifiers=create_default_modifiers_for_team(self.team),
+ )
+
+ def _print(
+ self,
+ query: str = "SELECT id FROM system.activity_logs",
+ dialect: Literal["hogql", "clickhouse"] = "clickhouse",
+ ) -> tuple[str, dict]:
+ context = self._context()
+ sql = prepare_and_print_ast(parse_select(query), context, dialect=dialect)[0]
+ return sql, context.values
+
+ def _floor(self, values: dict):
+ return next(v for v in values.values() if hasattr(v, "year"))
+
+ def test_retention_floor_is_pushed_into_the_federated_read(self):
+ # Next to the team guard inside the wrap, so Postgres prunes on (team_id, -created_at)
+ # instead of copying the rows out for ClickHouse to filter.
+ self._set_audit_logs_feature(limit=30, unit="days")
+
+ sql, _ = self._print()
+
+ self.assertIn(f"WHERE team_id = {self.team.pk} AND created_at >= %(", sql)
+
+ @parameterized.expand(
+ [
+ ("days", {"limit": 30, "unit": "days"}),
+ ("months", {"limit": 6, "unit": "months"}),
+ ("no limits, falls back", {}),
+ ]
+ )
+ def test_retention_window_matches_the_rest_surface(self, _name: str, feature: dict):
+ # One definition behind both surfaces: drift here means SQL shows rows the API hides.
+ self._set_audit_logs_feature(**feature)
+
+ _, values = self._print()
+
+ expected = get_activity_log_lookback_restriction(self.organization)
+ assert expected is not None
+ self.assertAlmostEqual(self._floor(values).timestamp(), expected.timestamp(), delta=60)
+
+ def test_no_floor_without_the_entitlement(self):
+ self.organization.available_product_features = []
+ self.organization.save()
+
+ sql, values = self._print()
+
+ self.assertIn(f"WHERE team_id = {self.team.pk})", sql)
+ self.assertEqual([v for v in values.values() if hasattr(v, "year")], [])
+
+ def test_joined_activity_logs_keep_the_federated_guard(self):
+ # A joined federated table lost its team wrap whenever it declared predicates, which made
+ # ClickHouse copy the whole table out of Postgres before filtering.
+ self._set_audit_logs_feature(limit=30, unit="days")
+
+ sql, _ = self._print(
+ "SELECT a.id FROM system.activity_logs AS a "
+ "JOIN system.insights AS i ON a.item_id = toString(i.id) LIMIT 10"
+ )
+
+ self.assertIn(f"WHERE team_id = {self.team.pk} AND created_at >= %(", sql)
+
+ @parameterized.expand([(rule["scope"], rule["activities"]) for rule in activity_visibility_restrictions])
+ def test_every_visibility_rule_reaches_the_query(self, scope: str, activities: list[str]):
+ # Fails when a rule is added to the shared list but only one compiler covers it.
+ self._set_audit_logs_feature(limit=30, unit="days")
+
+ _, values = self._print()
+
+ bound = list(values.values())
+ self.assertIn(scope, bound)
+ self.assertIn(activities, bound)
+
+ def test_loop_rows_are_hidden_entirely(self):
+ # The viewset allows loops per user from live RBAC. No system.loops table exists to defer
+ # that to, so SQL drops the scope rather than leak another user's personal loop config.
+ self._set_audit_logs_feature(limit=30, unit="days")
+
+ hogql, _ = self._print(dialect="hogql")
+
+ self.assertIn("NOT(equals(scope, 'Loop'))", hogql)
+
+ def test_canvas_rows_are_limited_to_readable_canvases(self):
+ # system.canvases carries its own access control, so Canvas rows defer to it instead of
+ # being dropped. That table is stricter than the viewset, so this over-hides, never under.
+ self._set_audit_logs_feature(limit=30, unit="days")
+
+ hogql, _ = self._print(dialect="hogql")
+
+ self.assertIn("NOT(and(equals(scope, 'Canvas'), notIn(item_id, (SELECT id FROM canvases", hogql)
+ # The canvases subquery keeps that table's own guards, so its access control carries over.
+ self.assertIn("_task_public_channels", hogql)
+
+ def test_canvas_rows_are_dropped_when_the_canvases_table_is_denied(self):
+ # Denying the canvas resource removes system.canvases from the schema, so a rule referencing it
+ # would raise TableAccessDeniedError and take the whole audit trail down with it. Such a caller
+ # may read no canvas at all, so the rows go instead.
+ self.organization.available_product_features = [
+ {"key": "audit_logs", "name": "Audit logs", "limit": 30, "unit": "days"},
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": "Access control"},
+ ]
+ self.organization.save()
+ # Object and resource access control only applies to non-admins.
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ AccessControl.objects.create(team=self.team, resource="canvas", access_level="none")
+
+ hogql, _ = self._print(dialect="hogql")
+
+ self.assertIn("NOT(equals(scope, 'Canvas'))", hogql)
+ self.assertNotIn("canvases", hogql)
+
+ def test_printing_a_query_without_activity_logs_costs_no_extra_query(self):
+ # The organization load is lazy: an ordinary HogQL query must not pay a Postgres round trip.
+ # Print once first, so the process-global primary-key cache is warm either way and this does
+ # not depend on some earlier test in the file having warmed it.
+ prepare_and_print_ast(parse_select("SELECT id FROM system.insights"), self._context(), dialect="clickhouse")
+
+ context = self._context()
+ select = parse_select("SELECT id FROM system.insights")
+
+ with self.assertNumQueries(0):
+ prepare_and_print_ast(select, context, dialect="clickhouse")
+
+ def test_floor_survives_when_the_pushdown_wrap_does_not_apply(self):
+ # The wrap in _print_table_ref is an optimization with its own preconditions. Enforcement
+ # must not ride on it, so a table that skips the wrap still gets the floor in its WHERE.
+ floor = timezone.now() - timedelta(days=30)
+
+ class _UnwrappedTable(PostgresTable, DANGEROUS_NoTeamIdCheckTable):
+ def retention_start(self, team, team_id):
+ return floor
+
+ context = self._context()
+ assert context.database is not None
+ context.database.tables.add_child(
+ TableNode(
+ name="unwrapped",
+ table=_UnwrappedTable(
+ name="unwrapped",
+ postgres_table_name="some_unwrapped_table",
+ retention_field="created_at",
+ fields={
+ "id": IntegerDatabaseField(name="id"),
+ "created_at": DateTimeDatabaseField(name="created_at"),
+ },
+ ),
+ )
+ )
+
+ sql = prepare_and_print_ast(parse_select("SELECT id FROM unwrapped"), context, dialect="clickhouse")[0]
+
+ self.assertNotIn("(SELECT * FROM postgresql(", sql)
+ self.assertIn("greaterOrEquals(unwrapped.created_at, toDateTime64(", sql)
+ self.assertIn(floor.strftime("%Y-%m-%d"), sql)
+
+
+class TestActivityLogsCacheKey(BaseTest):
+ def _payload(self, **feature) -> dict:
+ self.organization.available_product_features = [{"key": "audit_logs", "name": "Audit logs", **feature}]
+ self.organization.save()
+ runner = get_query_runner(
+ HogQLQuery(query="SELECT id FROM system.activity_logs"), team=self.team, user=self.user
+ )
+ return runner.get_cache_payload()
+
+ def test_cache_key_varies_with_the_retention_window(self):
+ # A cache hit returns before the printer applies the floor, so without this a result cached
+ # on a longer plan keeps serving rows the organization is no longer entitled to read.
+ with freeze_time("2026-08-14T10:30:00Z"):
+ wide = self._payload(limit=365, unit="days")
+ narrow = self._payload(limit=30, unit="days")
+
+ self.assertNotEqual(wide["activity_log_retention_floor_hour"], narrow["activity_log_retention_floor_hour"])
+
+ def test_cache_key_omits_the_floor_without_the_entitlement(self):
+ self.organization.available_product_features = []
+ self.organization.save()
+ runner = get_query_runner(
+ HogQLQuery(query="SELECT id FROM system.activity_logs"), team=self.team, user=self.user
+ )
+
+ self.assertNotIn("activity_log_retention_floor_hour", runner.get_cache_payload())
+
+ @parameterized.expand(
+ [
+ ("reads the table", "SELECT id FROM system.activity_logs", True),
+ ("reads another table", "SELECT id FROM system.insights", False),
+ ]
+ )
+ def test_cache_key_carries_the_visibility_policy_version(self, _name: str, query: str, expected: bool):
+ # The visibility rules are printed guards, so nothing else in the key tracks them: without this, a
+ # result stored under the previous rules keeps serving the rows the current ones hide. Changing the
+ # rules retires those results, so the fingerprint has to reach every query reading the table.
+ runner = get_query_runner(HogQLQuery(query=query), team=self.team, user=self.user)
+
+ payload = runner.get_cache_payload()
+
+ self.assertEqual("activity_log_visibility_policy" in payload, expected)
+
+ def test_the_visibility_policy_version_tracks_the_rule_list(self):
+ # The fingerprint exists so that editing the shared rule list is enough to retire the results the
+ # previous rules produced. One that ignored the list would keep serving rows the new rules hide.
+ self.addCleanup(activity_log_visibility_policy_version.cache_clear)
+ before = activity_log_visibility_policy_version()
+
+ activity_log_visibility_policy_version.cache_clear()
+ with patch(
+ "posthog.models.activity_logging.activity_log.activity_visibility_restrictions",
+ [*activity_visibility_restrictions, {"scope": "Insight", "activities": ["deleted"]}],
+ ):
+ after = activity_log_visibility_policy_version()
+
+ self.assertNotEqual(before, after)
+
+ def test_cache_key_follows_the_floor_as_it_moves(self):
+ # A cache-only request returns a stored result however stale it is, so a result stored inside the
+ # window would keep serving its rows after they fall outside it. Keying on the window rather than
+ # on the floor would miss that, because the window does not change as the clock moves.
+ self.organization.available_product_features = [
+ {"key": "audit_logs", "name": "Audit logs", "limit": 30, "unit": "days"}
+ ]
+ self.organization.save()
+
+ with freeze_time("2026-08-14T10:30:00Z"):
+ earlier = get_query_runner(
+ HogQLQuery(query="SELECT id FROM system.activity_logs"), team=self.team, user=self.user
+ ).get_cache_key()
+ with freeze_time("2026-08-14T11:30:00Z"):
+ later = get_query_runner(
+ HogQLQuery(query="SELECT id FROM system.activity_logs"), team=self.team, user=self.user
+ ).get_cache_key()
+
+ self.assertNotEqual(earlier, later)
diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.py
index 7970b5caa6c7..edd4816eb729 100644
--- a/posthog/hogql/printer/base.py
+++ b/posthog/hogql/printer/base.py
@@ -520,7 +520,7 @@ class BasePrinter(Visitor[str]):
node_type: ast.TableOrSelectType | None,
) -> list[ast.Expr]:
"""Return predicate expressions from the table definition, resolved against the table's type."""
- predicates = table_type.table.get_predicates()
+ predicates = table_type.table.get_predicates(self.context)
if not predicates or node_type is None:
return []
@@ -546,6 +546,15 @@ class BasePrinter(Visitor[str]):
default no-op — the HogQL and warehouse dialects don't enforce events retention."""
return None
+ def _postgres_retention_floor(
+ self,
+ table_type: ast.TableType | ast.LazyTableType,
+ node_type: ast.TableOrSelectType | None,
+ ) -> ast.Expr | None:
+ """Floor a federated table declaring a `retention_field` to its entitlement window. Overridden
+ by the ClickHouse dialect; default no-op — only that dialect reads these tables."""
+ return None
+
def _print_table_ref(self, table_type: ast.TableType | ast.LazyTableType, node: ast.JoinExpr) -> str:
"""Print a table reference. Fail-fast by default: each dialect must override.
@@ -617,6 +626,9 @@ class BasePrinter(Visitor[str]):
retention_floor = self._events_retention_floor(table_type, node.type)
if retention_floor is not None:
predicate_exprs = [*predicate_exprs, retention_floor]
+ postgres_floor = self._postgres_retention_floor(table_type, node.type)
+ if postgres_floor is not None:
+ predicate_exprs = [*predicate_exprs, postgres_floor]
for pred in predicate_exprs:
if is_left_join and node.constraint is not None:
if on_clause_guard is None:
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index 39a3a8c84a57..4ecb2fe16f41 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -1,6 +1,6 @@
import re
from datetime import date, datetime
-from typing import ClassVar, cast
+from typing import TYPE_CHECKING, ClassVar, Optional, cast
from uuid import UUID
from django.conf import settings as django_settings
@@ -44,6 +44,9 @@ from posthog.exchange_rate_constants import EXCHANGE_RATE_DECIMAL_PRECISION, EXC
from posthog.uuidt import UUIDT
from posthog.week_start_day import WeekStartDay
+if TYPE_CHECKING:
+ from posthog.hogql.database.postgres_table import PostgresTable
+
def _table_filter_type(table_type: ast.TableOrSelectType) -> ast.TableOrSelectType:
if isinstance(table_type, ast.ColumnAliasedTableType):
@@ -1029,7 +1032,11 @@ class ClickHousePrinter(BasePrinter):
# both exist at runtime (customer_analytics _AccountScopedPostgresTable).
and not isinstance(table, DANGEROUS_NoTeamIdCheckTable) # type: ignore[unreachable]
and "team_id" in table.fields
- and not table.get_predicates()
+ # A table declaring a retention floor still gets the wrap, because the floor is the
+ # filter that has to reach Postgres: it is indexed there, and the rows it prunes are
+ # the ones the organization is not entitled to read at all. Its other predicates stay
+ # in the enclosing select and run in ClickHouse over the already-bounded row set.
+ and (table.retention_field is not None or not table.get_predicates(self.context))
and self.context.team_id is not None
):
# The HogQL `team_id` field may map to a differently named DB column (e.g.
@@ -1037,10 +1044,65 @@ class ClickHousePrinter(BasePrinter):
# the HogQL name. Skip the wrap when the field isn't a plain column.
team_id_column = getattr(table.fields["team_id"], "name", None)
if team_id_column:
- sql = f"(SELECT * FROM {sql} WHERE {team_id_column} = {int(self.context.team_id)})"
+ conditions = [f"{team_id_column} = {int(self.context.team_id)}"]
+ retention_start = self._postgres_retention_start(table)
+ if retention_start is not None:
+ conditions.append(f"{table.retention_field} >= {self.context.add_value(retention_start)}")
+ sql = f"(SELECT * FROM {sql} WHERE {' AND '.join(conditions)})"
return sql
+ def _postgres_retention_start(self, table: "PostgresTable") -> Optional[datetime]:
+ """Oldest row timestamp the organization may read from a retention-bearing federated table.
+
+ Resolved once per table per query, and only when that table is actually printed, so ordinary
+ queries never pay the organization load. Each table computes its own window, so the memo is
+ keyed by Postgres table name rather than shared.
+ """
+ if table.retention_field is None:
+ return None
+
+ memo = self.context.postgres_retention_starts
+ if table.postgres_table_name not in memo:
+ memo[table.postgres_table_name] = table.retention_start(self.context.team, self.context.team_id)
+
+ return memo[table.postgres_table_name]
+
+ def _postgres_retention_floor(
+ self,
+ table_type: ast.TableType | ast.LazyTableType,
+ node_type: ast.TableOrSelectType | None,
+ ) -> ast.Expr | None:
+ """Floor a retention-bearing federated scan, as a predicate in the enclosing select.
+
+ The wrap in `_print_table_ref` repeats this so Postgres prunes on its own index, but that
+ wrap is an optimization with its own preconditions. Enforcement cannot ride on it, so the
+ floor is emitted here too and survives when the wrap does not apply. Prints as a literal
+ rather than `now() - interval`, which would not survive the trip into Postgres.
+ """
+ from posthog.hogql.database.postgres_table import PostgresTable # noqa: PLC0415
+
+ if node_type is None or not isinstance(table_type, ast.TableType):
+ return None
+ table = table_type.table
+ if not isinstance(table, PostgresTable) or table.retention_field is None:
+ return None
+
+ retention_start = self._postgres_retention_start(table)
+ if retention_start is None:
+ return None
+
+ field_table_type = _table_filter_type(node_type)
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(
+ chain=[table.retention_field],
+ type=ast.FieldType(name=table.retention_field, table_type=field_table_type),
+ ),
+ right=ast.Constant(value=retention_start),
+ type=ast.BooleanType(),
+ )
+
def _print_select_columns(self, columns):
def _alias_from_column_type(column: ast.Expr) -> str | None:
column_type = getattr(column, "type", None)
diff --git a/posthog/hogql_queries/access_controlled_resources.py b/posthog/hogql_queries/access_controlled_resources.py
index e86a68468d2b..1af97749b225 100644
--- a/posthog/hogql_queries/access_controlled_resources.py
+++ b/posthog/hogql_queries/access_controlled_resources.py
@@ -46,6 +46,15 @@ _DATA_QUALITY_INFORMATION_SCHEMA_TABLES = frozenset(
_ACCOUNT_COMMUNICATION_LAZY_FIELDS = frozenset({"email_threads", "support_tickets"})
+# Scopes a system table's rows depend on beyond its own `access_scope`, because its visibility rules
+# read another access-controlled table. `system.activity_logs` limits Canvas rows to the canvases in
+# `system.canvases` (see activity_log_visibility.py), so its rows follow the caller's Canvas grants:
+# without partitioning on `canvas` too, two users with identical activity-log access but different
+# Canvas grants share one cache key, and the narrower one is served the wider one's Canvas rows.
+_TRANSITIVE_SYSTEM_TABLE_SCOPES: dict[str, frozenset[str]] = {
+ "system.activity_logs": frozenset({"canvas"}),
+}
+
def queried_access_controlled_resources(query, team: "Team") -> Optional[set[str]]:
"""The set of access-control scope names a query reads, e.g. "notebook", "warehouse_table".
@@ -111,6 +120,9 @@ def queried_access_controlled_resources(query, team: "Team") -> Optional[set[str
):
scopes.add("ticket")
+ for name in table_names:
+ scopes |= _TRANSITIVE_SYSTEM_TABLE_SCOPES.get(name, frozenset())
+
# The catalog-enriched information_schema tables aren't PostgresTables, so they're absent from
# `access_controlled_system_tables()`; gate them explicitly on `data_catalog` read access.
if table_names & _DATA_CATALOG_INFORMATION_SCHEMA_TABLES:
diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.py
index dcbfd27e1f47..c510e475a2fc 100644
--- a/posthog/hogql_queries/hogql_query_runner.py
+++ b/posthog/hogql_queries/hogql_query_runner.py
@@ -1,5 +1,6 @@
from collections.abc import Callable
from datetime import datetime
+from functools import cached_property
from typing import Any, Optional, cast
from posthog.schema import (
@@ -15,6 +16,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.database.schema.activity_log_visibility import activity_log_visibility_policy_version
from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR, get_direct_connection_source
from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.filters import replace_filters
@@ -32,11 +34,13 @@ from posthog.event_usage import AnalyticsProps
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode
from posthog.models import User
+from posthog.models.activity_logging.retention import get_activity_log_lookback_restriction
from products.managed_warehouse.backend.facade import query_labels as managed_warehouse_query_labels
from products.warehouse_sources.backend.facade.types import ManagedWarehouseSQLMode
_INFORMATION_SCHEMA_PREFIX = "system.information_schema."
+_ACTIVITY_LOGS_TABLE = "system.activity_logs"
class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
@@ -89,6 +93,24 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
# Old workers preferred query modifiers while new workers prefer the constructor override.
# Keep their cached results apart during a rolling deploy.
payload["hogql_modifier_precedence"] = "runner"
+
+ # Both activity-log guards print into the query, so a cache lookup returns before either runs.
+ # `requires_fresh_calculation` below keeps a stored result from being served in every mode that may
+ # calculate. CACHE_ONLY_NEVER_CALCULATE is the mode it cannot reach: that one returns a stored
+ # result however stale it is, so the key carries what the guards depend on.
+ if _ACTIVITY_LOGS_TABLE in self._queried_table_names:
+ # Nothing else in the key tracks the visibility rules. Varying on their fingerprint means a
+ # result stored under the previous rules stops being served once they change.
+ payload["activity_log_visibility_policy"] = activity_log_visibility_policy_version()
+
+ # The retention floor moves with the clock, so a result stored inside the window would outlive
+ # it. Bucketing by the hour bounds a cache-only read to rows at most an hour past the floor,
+ # rather than for as long as the entry lives, and a downgrade moves the floor by days, so this
+ # covers a plan change too.
+ floor = get_activity_log_lookback_restriction(self.team.organization)
+ if floor is not None:
+ payload["activity_log_retention_floor_hour"] = floor.strftime("%Y-%m-%dT%H")
+
return payload
def query_status_labels(self) -> list[str] | None:
@@ -125,13 +147,34 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
# acceptance, source certification). A cached row keeps reporting the pre-change status after a
# catalog write, so recompute these queries rather than trust the query cache. Cheap to detect:
# the schema metadata itself is fast to compute. External-connection queries never touch it.
+ #
+ # system.activity_logs is floored to the organization's retention window, which moves with the
+ # clock, so a stored row outlives the entitlement that let it be read. Recompute rather than
+ # serve one back.
+ table_names = self._queried_table_names
+ return any(name.lower().startswith(_INFORMATION_SCHEMA_PREFIX) for name in table_names) or (
+ _ACTIVITY_LOGS_TABLE in table_names
+ )
+
+ @cached_property
+ def _queried_table_names(self) -> set[str]:
+ """Tables this query names, or empty when it is unparseable or reads an external connection.
+
+ Names only, so a table reached through a saved view is absent: the resolver inlines the view's
+ definition after the cache lookup. The printed guards still apply on that path, so what a read
+ through a view misses is the cache partitioning, not the enforcement. Following view definitions
+ here would put a saved-query lookup in front of every HogQL query's cache key, and the rest of
+ the fingerprinting in `queried_access_controlled_resources` stops at the same boundary.
+
+ Cached because the freshness check and the cache key both need it, and neither rewrites the query
+ text (dashboard filters and variables are applied at `to_query` time).
+ """
if self.query.connectionId:
- return False
+ return set()
try:
- table_names = get_table_names(parse_select(self.query.query))
+ return set(get_table_names(parse_select(self.query.query)))
except Exception:
- return False
- return any(name.lower().startswith(_INFORMATION_SCHEMA_PREFIX) for name in table_names)
+ return set()
def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
values: Optional[dict[str, ast.Expr]] = (
diff --git a/posthog/hogql_queries/test/test_access_controlled_resources.py b/posthog/hogql_queries/test/test_access_controlled_resources.py
index 227e85314742..3de1e1ae6726 100644
--- a/posthog/hogql_queries/test/test_access_controlled_resources.py
+++ b/posthog/hogql_queries/test/test_access_controlled_resources.py
@@ -77,6 +77,9 @@ class TestQueriedAccessControlledResources(BaseTest):
{"account", "ticket"},
),
("account_non_communication_lazy_join", "select meetings.count from system.accounts", {"account"}),
+ # Activity-log rows for canvases are limited to the canvases in `system.canvases`, so the
+ # rows follow the caller's canvas grants as well as their activity-log access.
+ ("activity_logs", "select * from system.activity_logs", {"activity_log", "canvas"}),
("no_access_controlled_table", "select 1", set()),
("events_table", "select * from events", set()),
# Catalog-enriched information_schema tables partition the cache by data_catalog access AND
diff --git a/posthog/hogql_queries/test/test_hogql_query_runner.py b/posthog/hogql_queries/test/test_hogql_query_runner.py
index 05374fc31202..3cee2b739a45 100644
--- a/posthog/hogql_queries/test/test_hogql_query_runner.py
+++ b/posthog/hogql_queries/test/test_hogql_query_runner.py
@@ -190,6 +190,9 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):
("tables", "select * from system.information_schema.tables", True),
("relationships", "select * from system.information_schema.relationships", True),
("columns", "select * from system.information_schema.columns", True),
+ # system.activity_logs is floored to the plan's retention window, which moves with the clock,
+ # so a stored row outlives the entitlement that let it be read.
+ ("activity_logs", "select * from system.activity_logs", True),
("other_system_table", "select id, name from system.insights", False),
("events", "select count(event) from events", False),
("unparseable", "INVALID SQL SYNTAX", False),
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 3a6819e1497c..4384c14b970e 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -1533,6 +1533,28 @@ class TestQueryRunnerAccessControlFingerprint(BaseTest):
payload = HogQLQueryRunner(query=query, team=self.team, user=self.user).get_cache_payload()
assert "restricted_objects" not in payload # notebook object deny doesn't touch a surveys query
+ def test_canvas_object_deny_partitions_an_activity_logs_query(self):
+ # `system.activity_logs` limits Canvas rows to the canvases in `system.canvases`, so two users
+ # with identical activity-log access but different canvas grants must land in different cache
+ # entries - otherwise the restricted one replays the other's Canvas activity rows on a hit.
+ other_user = self._create_user("[email protected]")
+ other_membership = other_user.organization_memberships.get(organization=self.organization)
+ canvas_id = "018f0000-0000-0000-0000-0000000000ca"
+ self._ac(
+ resource="canvas",
+ resource_id=canvas_id,
+ access_level="none",
+ organization_member=other_membership,
+ )
+
+ query = {"kind": "HogQLQuery", "query": "select * from system.activity_logs"}
+ unrestricted = HogQLQueryRunner(query=query, team=self.team, user=self.user)
+ restricted = HogQLQueryRunner(query=query, team=self.team, user=other_user)
+
+ assert "restricted_objects" not in unrestricted.get_cache_payload()
+ assert restricted.get_cache_payload()["restricted_objects"] == {"canvas": [canvas_id]}
+ assert restricted.get_cache_key() != unrestricted.get_cache_key()
+
def test_object_grants_under_a_denied_resource_partition_cache(self):
# Both users are denied notebooks at the resource level and see only what they were granted,
# so neither has a deny set to partition on - without the allowlist in the fingerprint they
diff --git a/posthog/models/activity_logging/retention.py b/posthog/models/activity_logging/retention.py
new file mode 100644
index 000000000000..7e6e193a6c7e
--- /dev/null
+++ b/posthog/models/activity_logging/retention.py
@@ -0,0 +1,88 @@
+from datetime import datetime, timedelta
+from typing import TYPE_CHECKING, Optional
+
+from django.utils import timezone
+
+import structlog
+
+from posthog.constants import AvailableFeature
+
+logger = structlog.get_logger(__name__)
+
+if TYPE_CHECKING:
+ from posthog.models.organization import Organization
+ from posthog.models.team.team import Team
+
+# Smallest window billing sells: Boost gets 7 days, Scale 2 months, Enterprise 60 months. Only those
+# packages carry the feature at all, so this fallback is reached by an entitled organization whose
+# entitlement is malformed, never by one that bought no activity logs. Falling back to the smallest
+# window keeps such an organization inside what any plan grants rather than above it.
+ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_LIMIT = 7
+ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_UNIT = "days"
+
+
+def _lookback_window(organization: "Organization") -> Optional[timedelta]:
+ """How far back the organization may read activity logs, or None when unrestricted."""
+ audit_log_feature = organization.get_available_feature(AvailableFeature.AUDIT_LOGS)
+
+ if not audit_log_feature:
+ return None
+
+ limit = audit_log_feature.get("limit")
+ unit = audit_log_feature.get("unit")
+
+ if limit is None or unit is None:
+ logger.warning(
+ "activity_log_retention.entitlement_missing_window",
+ organization_id=str(organization.id),
+ limit=limit,
+ unit=unit,
+ )
+ limit = ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_LIMIT
+ unit = ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_UNIT
+
+ unit_lower = unit.lower()
+ if unit_lower in ("day", "days"):
+ return timedelta(days=limit)
+ elif unit_lower in ("month", "months"):
+ return timedelta(days=limit * 30)
+ elif unit_lower in ("year", "years"):
+ return timedelta(days=limit * 365)
+
+ # Both surfaces that read this run outside HogQL's error handling — the printer and
+ # `HogQLQueryRunner.get_cache_payload` — so raising here would 500 every query naming
+ # system.activity_logs rather than surface a query error. Fall back to the smallest window
+ # instead: a unit billing has not used before must not widen what anyone can read.
+ logger.warning(
+ "activity_log_retention.entitlement_unknown_unit",
+ organization_id=str(organization.id),
+ limit=limit,
+ unit=unit,
+ )
+ return timedelta(days=ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_LIMIT)
+
+
+def get_activity_log_lookback_restriction(organization: "Organization") -> Optional[datetime]:
+ """Get the lookback restriction date based on the AUDIT_LOGS feature."""
+ window = _lookback_window(organization)
+ return None if window is None else timezone.now() - window
+
+
+def activity_log_retention_start_for_team(team: Optional["Team"], team_id: Optional[int]) -> Optional[datetime]:
+ """Oldest `created_at` a team may read activity logs back to, or None if unrestricted.
+
+ Wraps `get_activity_log_lookback_restriction` for callers that hold a team rather than an
+ organization, so the SQL surface and the REST viewsets derive the window from one place.
+ Resolved lazily by the printer, and only for a query that actually reads a retention-bearing
+ table, so ordinary queries never pay the organization load.
+ """
+ from posthog.models.team.team import Team # noqa: PLC0415 (avoids a models import cycle)
+
+ if team is None:
+ if team_id is None:
+ return None
+ team = Team.objects.filter(id=team_id).select_related("organization").first()
+ if team is None:
+ return None
+
+ return get_activity_log_lookback_restriction(team.organization)
diff --git a/posthog/test/activity_logging/test_retention.py b/posthog/test/activity_logging/test_retention.py
new file mode 100644
index 000000000000..ccaa0f01ef97
--- /dev/null
+++ b/posthog/test/activity_logging/test_retention.py
@@ -0,0 +1,42 @@
+from datetime import datetime, timedelta
+
+from freezegun import freeze_time
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.models.activity_logging.retention import get_activity_log_lookback_restriction
+from posthog.models.organization import Organization
+
+NOW = datetime(2026, 6, 1, 12, 0, 0)
+
+
+class TestActivityLogLookbackWindow(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("boost", {"limit": 7, "unit": "days"}, 7),
+ ("scale", {"limit": 2, "unit": "months"}, 60),
+ ("enterprise", {"limit": 60, "unit": "months"}, 1800),
+ ("singular unit", {"limit": 1, "unit": "year"}, 365),
+ # Billing sent the feature without a window. Falling back to anything wider than the
+ # smallest plan would read a Boost organization past what it bought.
+ ("no window falls back to the smallest plan", {}, 7),
+ # An unrecognized unit must not raise: both readers run outside HogQL's error handling,
+ # so raising 500s every query naming system.activity_logs instead of restricting it.
+ ("unknown unit falls back to the smallest plan", {"limit": 3, "unit": "weeks"}, 7),
+ ]
+ )
+ def test_window_for_entitlement(self, _name: str, feature: dict, expected_days: int):
+ organization = Organization(available_product_features=[{"key": "audit_logs", **feature}])
+
+ with freeze_time(NOW):
+ restriction = get_activity_log_lookback_restriction(organization)
+
+ assert restriction is not None
+ self.assertEqual(NOW - restriction.replace(tzinfo=None), timedelta(days=expected_days))
+
+ def test_no_entitlement_is_unrestricted(self):
+ organization = Organization(available_product_features=[])
+
+ self.assertIsNone(get_activity_log_lookback_restriction(organization))
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 03f8eb44ae50..bede22c9e082 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -1387,7 +1387,7 @@
2 posthog/dags/person_overrides.py
2 posthog/dags/scripts/extract_reconciliation_results.py
2 posthog/helpers/email_utils.py
-2 posthog/hogql/context.py
+1 posthog/hogql/context.py
2 posthog/hogql/database/models.py
2 posthog/management/commands/generate_test_events.py
2 posthog/management/migration_analysis/models.py