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(home): boot project-targeted flags, fill recents and serve partial highlights (#117697)

Shy Alter64e988b21ae6
diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.py
index 9050313ef2db..073a20faf672 100644
--- a/posthog/api/file_system/test/test_file_system.py
+++ b/posthog/api/file_system/test/test_file_system.py
@@ -336,17 +336,23 @@ class TestFileSystemAPI(APIBaseTest):
self.assertEqual([listed["results"], searched["results"], counted["count"]], [[], [], 0])
self.assertEqual(retrieved.status_code, status.HTTP_404_NOT_FOUND)
- def test_recents_skip_views_of_retired_types(self) -> None:
+ @parameterized.expand([("retired_type",), ("scene",), ("deleted_object",)])
+ def test_recents_skip_views_without_an_entry(self, unlisted_view: str) -> None:
_folder, retired = self._create_retired_row_in_folder()
dashboard = Dashboard.objects.create(team=self.team, name="Viewed earlier", created_by=self.user)
entry = FileSystem.objects.create(
team=self.team, path="Viewed earlier", type="dashboard", ref=str(dashboard.id), created_by=self.user
)
+ view_type, view_ref = {
+ "retired_type": ("link", retired.ref),
+ "scene": ("scene", "ProjectHomepage"),
+ "deleted_object": ("dashboard", "999999"),
+ }[unlisted_view]
base = f"/api/projects/{self.team.id}/file_system"
self.client.post(
f"{base}/log_view/", {"type": "dashboard", "ref": entry.ref, "viewed_at": "2026-09-01T00:00:00Z"}
)
- self.client.post(f"{base}/log_view/", {"type": "link", "ref": retired.ref, "viewed_at": "2026-09-02T00:00:00Z"})
+ self.client.post(f"{base}/log_view/", {"type": view_type, "ref": view_ref, "viewed_at": "2026-09-02T00:00:00Z"})
recents = self.client.get(f"{base}/?order_by=-last_viewed_at&limit=1").json()
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 0abac3c4cc73..138755e6c207 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -812,8 +812,7 @@ class TestQueryRunner(BaseTest):
def test_cache_payload_week_interval(self):
TestQueryRunner = self.setup_test_query_runner_class()
- # set the pk directly as it affects the hash in the _cache_key call
- team = Team.objects.create(pk=42, organization=self.organization, week_start_day=WeekStartDay.MONDAY)
+ team = Team.objects.create(organization=self.organization, week_start_day=WeekStartDay.MONDAY)
runner = TestQueryRunner(query={"some_attr": "bla", "tags": {"scene": "foo", "productKey": "bar"}}, team=team)
runner.query_date_range = QueryDateRange(
team=team, date_range=None, interval=IntervalType.WEEK, now=datetime.now()
@@ -822,16 +821,24 @@ class TestQueryRunner(BaseTest):
cache_payload = runner.get_cache_payload()
assert cache_payload["week_start_day"] == WeekStartDay.MONDAY
+ def _cache_key_with_fixed_payload_team_id(self, runner: QueryRunner) -> str:
+ payload = runner.get_cache_payload()
+ payload["team_id"] = 42
+ with mock.patch.object(runner, "get_cache_payload", return_value=payload):
+ return runner.get_cache_key()
+
+ @parameterized.expand([("new_team", False), ("existing_team", True)])
@override_settings(PERSON_ON_EVENTS_OVERRIDE=False, PERSON_ON_EVENTS_V2_OVERRIDE=False)
- def test_cache_key(self):
+ def test_cache_key(self, _name: str, existing_team: bool) -> None:
TestQueryRunner = self.setup_test_query_runner_class()
- # set the pk directly as it affects the hash in the _cache_key call
- team = Team.objects.create(pk=42, organization=self.organization)
+ team = Team.objects.create(organization=self.organization)
+ if existing_team and not Team.objects.filter(pk=42).exists():
+ Team.objects.create(pk=42, organization=self.organization)
runner = TestQueryRunner(query={"some_attr": "bla"}, team=team)
- cache_key = runner.get_cache_key()
- assert cache_key == "cache_42_13361de10d0c3c79451b288eb57ca1147331e86a8b8e63a0a815adf5a2d7bcbb"
+ cache_key = self._cache_key_with_fixed_payload_team_id(runner)
+ assert cache_key == f"cache_{team.pk}_13361de10d0c3c79451b288eb57ca1147331e86a8b8e63a0a815adf5a2d7bcbb"
def test_cache_key_ignores_query_log_tags(self):
# Query log tags are metadata, so they must never partition the cache. Web
@@ -840,7 +847,7 @@ class TestQueryRunner(BaseTest):
# reading the same cache entry as the untagged one, or every preset user would
# miss the cache on every load and the warm set would double.
TestQueryRunner = self.setup_test_query_runner_class()
- team = Team.objects.create(pk=42, organization=self.organization)
+ team = Team.objects.create(organization=self.organization)
untagged = TestQueryRunner(query={"some_attr": "bla"}, team=team)
tagged = TestQueryRunner(query={"some_attr": "bla", "tags": {"presetId": "abc123"}}, team=team)
@@ -854,25 +861,24 @@ class TestQueryRunner(BaseTest):
class TestSubclassQueryRunner(TestQueryRunner): # type: ignore[misc, valid-type]
pass
- # set the pk directly as it affects the hash in the _cache_key call
- team = Team.objects.create(pk=42, organization=self.organization)
+ team = Team.objects.create(organization=self.organization)
runner = TestSubclassQueryRunner(query={"some_attr": "bla"}, team=team)
- cache_key = runner.get_cache_key()
- assert cache_key == "cache_42_9dcfced89edfbfcd1e0fd380380c7a5e4a9957386fc22172c1b83548a9af6d02"
+ cache_key = self._cache_key_with_fixed_payload_team_id(runner)
+ assert cache_key == f"cache_{team.pk}_9dcfced89edfbfcd1e0fd380380c7a5e4a9957386fc22172c1b83548a9af6d02"
@override_settings(PERSON_ON_EVENTS_OVERRIDE=False, PERSON_ON_EVENTS_V2_OVERRIDE=False)
def test_cache_key_different_timezone(self):
TestQueryRunner = self.setup_test_query_runner_class()
- team = Team.objects.create(pk=42, organization=self.organization)
+ team = Team.objects.create(organization=self.organization)
team.timezone = "Europe/Vienna"
team.save()
runner = TestQueryRunner(query={"some_attr": "bla"}, team=team)
- cache_key = runner.get_cache_key()
- assert cache_key == "cache_42_580a20072d3930f66666356574843255ba9418ff58cc0fc92d019bf8bf1cf972"
+ cache_key = self._cache_key_with_fixed_payload_team_id(runner)
+ assert cache_key == f"cache_{team.pk}_580a20072d3930f66666356574843255ba9418ff58cc0fc92d019bf8bf1cf972"
def test_query_identity_splits_the_query_from_how_it_is_answered(self) -> None:
TestQueryRunner = self.setup_test_query_runner_class()
diff --git a/posthog/models/file_system/file_system_view_log.py b/posthog/models/file_system/file_system_view_log.py
index a6348da58266..937ef3821aa0 100644
--- a/posthog/models/file_system/file_system_view_log.py
+++ b/posthog/models/file_system/file_system_view_log.py
@@ -6,7 +6,7 @@ from datetime import datetime
from typing import TYPE_CHECKING, Optional, cast
from django.db import IntegrityError, models
-from django.db.models import Q, QuerySet
+from django.db.models import Exists, OuterRef, Q, QuerySet
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.utils import timezone
@@ -152,16 +152,19 @@ def get_recent_file_system_items(
before the ``(type, ref)`` keys are matched. ``descending`` is threaded down to the view-log
query so the ``limit`` slice picks the globally oldest/newest views, not a re-sorted page.
"""
- log_rows = list(
- recent_view_logs(
- team_id=team_id,
- user_id=user_id,
- surface=surface,
- exclude_types=exclude_types,
- limit=limit,
- descending=descending,
- ).values_list("type", "ref", "viewed_at")
- )
+ entries = FileSystem.objects.filter(
+ surface_q(surface), team_id=team_id, type=OuterRef("type"), ref=OuterRef("ref")
+ ).exclude(shortcut=True)
+ log_queryset = recent_view_logs(
+ team_id=team_id,
+ user_id=user_id,
+ surface=surface,
+ exclude_types=exclude_types,
+ descending=descending,
+ ).filter(Exists(entries))
+ if limit is not None:
+ log_queryset = log_queryset[:limit]
+ log_rows = list(log_queryset.values_list("type", "ref", "viewed_at"))
if not log_rows:
return []
diff --git a/posthog/test/test_get_context_for_template.py b/posthog/test/test_get_context_for_template.py
index c92824b16e2f..c29d00aed8c6 100644
--- a/posthog/test/test_get_context_for_template.py
+++ b/posthog/test/test_get_context_for_template.py
@@ -187,6 +187,18 @@ class TestGetContextForTemplate(APIBaseTest):
app_context = actual["posthog_app_context"]
assert app_context["homepage"] == (stored_homepage or None)
+ @mock.patch("posthog.utils.posthoganalytics.get_all_flags", return_value={})
+ def test_flag_bootstrap_evaluates_with_the_project_group(self, mock_get_all_flags):
+ request = RequestFactory().get("/")
+ SessionMiddleware(lambda _request: HttpResponse()).process_request(request)
+ request.user = self.user
+
+ get_context_for_template("layout", request)
+
+ kwargs = mock_get_all_flags.call_args.kwargs
+ assert kwargs["groups"]["project"] == str(self.team.uuid)
+ assert kwargs["group_properties"]["project"]["id"] == self.team.id
+
def test_bootstraps_project_tags_into_app_context(self):
# projectLogic reads currentProject from the app context and only calls the API when it is
# absent, so tags missing here render an empty Tags field until something refetches.
diff --git a/posthog/utils.py b/posthog/utils.py
index a6b1fd69de69..99b34dbb536f 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -727,7 +727,7 @@ def _build_template_context(
if posthog_distinct_id:
groups = {}
- group_properties = {}
+ group_properties: dict[str, dict[str, str | int]] = {}
person_properties = {}
if request.user and request.user.is_authenticated:
user = cast("User", request.user)
@@ -739,6 +739,13 @@ def _build_template_context(
"name": user.organization.name,
"created_at": user.organization.created_at.isoformat(),
}
+ if user.team:
+ groups["project"] = str(user.team.uuid)
+ group_properties["project"] = {
+ "id": user.team.id,
+ "uuid": str(user.team.uuid),
+ "name": user.team.name,
+ }
with tracer.start_as_current_span("template.feature_flag_bootstrap"):
feature_flags = posthoganalytics.get_all_flags(
diff --git a/products/today/backend/logic/highlights.py b/products/today/backend/logic/highlights.py
index b4ae8ffd6ee2..24be14d50330 100644
--- a/products/today/backend/logic/highlights.py
+++ b/products/today/backend/logic/highlights.py
@@ -38,7 +38,7 @@ from .highlight_types import CACHE_SECONDS, Candidate, Context, Found, Source, p
logger = structlog.get_logger(__name__)
FAILED_CACHE_SECONDS = 60
-COMPUTING_SECONDS = 2 * 60
+COMPUTING_SECONDS = 5 * 60
START_LOCK_SECONDS = 30
MAX_ITEMS = 6
MAX_PER_FAMILY = 2
@@ -142,7 +142,12 @@ def finalize(inputs: FinalizeHighlightsInputs) -> None:
found = {result.source_name: _FOUND.validate_json(result.found) for result in inputs.results if result.found}
highlights = build_highlights(load_sources(), found, Team.objects.get(id=inputs.team_id), row.local_day)
failed = [result for result in inputs.results if result.failed]
- row.status = HighlightsStatus.FAILED if failed and len(failed) == len(inputs.results) else HighlightsStatus.READY
+ usable = bool(highlights.items or highlights.pulse)
+ row.status = (
+ HighlightsStatus.FAILED
+ if failed and len(failed) == len(inputs.results) and not usable
+ else HighlightsStatus.READY
+ )
row.content = _HIGHLIGHTS.dump_python(highlights, mode="json")
row.failed_sources = bool(failed)
row.ready_at = timezone.now()
diff --git a/products/today/backend/temporal/workflows.py b/products/today/backend/temporal/workflows.py
index 691d48ebe0be..3eb7f98b3a46 100644
--- a/products/today/backend/temporal/workflows.py
+++ b/products/today/backend/temporal/workflows.py
@@ -33,7 +33,7 @@ with temporalio.workflow.unsafe.imports_passed_through():
MARK_FAILED_TIMEOUT = timedelta(seconds=30)
SCHEDULER_TIMEOUT = timedelta(minutes=10)
-HIGHLIGHT_SOURCE_TIMEOUT = timedelta(seconds=30)
+HIGHLIGHT_SOURCE_TIMEOUT = timedelta(seconds=60)
FINALIZE_HIGHLIGHTS_TIMEOUT = timedelta(seconds=30)
diff --git a/products/today/backend/tests/test_highlights.py b/products/today/backend/tests/test_highlights.py
index 74d69868d566..198ed857fd9c 100644
--- a/products/today/backend/tests/test_highlights.py
+++ b/products/today/backend/tests/test_highlights.py
@@ -67,6 +67,7 @@ ALERT_RESULT = HighlightSourceResult(
failed=False,
)
FAILED_RESULT = HighlightSourceResult(source_name="errors", found=None, failed=True)
+PARTIAL_RESULT = HighlightSourceResult(source_name="alerts", found=ALERT_RESULT.found, failed=True)
READY_CONTENT = HIGHLIGHTS.dump_python(
contracts.Highlights(
status=HighlightsStatus.READY,
@@ -251,6 +252,7 @@ class TestFinalizeHighlights(BaseTest):
[
("one source failed", [ALERT_RESULT, FAILED_RESULT], HighlightsStatus.READY, ["alert"], False),
("every source failed", [FAILED_RESULT], HighlightsStatus.FAILED, [], True),
+ ("every source failed but one kept an item", [PARTIAL_RESULT], HighlightsStatus.READY, ["alert"], False),
]
)
def test_a_ready_computation_replaces_the_older_rows(
@@ -299,8 +301,14 @@ class TestGetHighlights(BaseTest):
0,
["k1"],
),
- ("a recent computing row", {"created_at": timedelta(minutes=1)}, HighlightsStatus.COMPUTING, 0, []),
- ("a lost computing row", {"created_at": timedelta(minutes=5)}, HighlightsStatus.COMPUTING, 1, []),
+ (
+ "a computing row inside the retry budget",
+ {"created_at": timedelta(minutes=3)},
+ HighlightsStatus.COMPUTING,
+ 0,
+ [],
+ ),
+ ("a lost computing row", {"created_at": timedelta(minutes=6)}, HighlightsStatus.COMPUTING, 1, []),
(
"a stale ready row",
{"status": HighlightsStatus.READY, "ready_at": timedelta(minutes=20)},