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(signals): group activity summary insights by dashboard and spread days (#121341)

posthog[bot]cf0ca472f7a8
diff --git a/products/dashboards/backend/facade/api.py b/products/dashboards/backend/facade/api.py
index ad0fef74df14..4e0079c324fb 100644
--- a/products/dashboards/backend/facade/api.py
+++ b/products/dashboards/backend/facade/api.py
@@ -194,6 +194,23 @@ def dashboard_refs(dashboard_ids: Sequence[int]) -> tuple[DashboardRef, ...]:
return _refs_in_given_order(dashboard_ids)
+def dashboards_by_insight(insight_ids: Collection[int], *, team_id: int) -> dict[int, tuple[DashboardRef, ...]]:
+ """The listed dashboards each insight of this team sits on, oldest tile first, in one query.
+
+ Deleted tiles, dashboards and insights do not count. An insight on no such dashboard has no key.
+ """
+ rows = (
+ DashboardTile.objects.filter(dashboard__team_id=team_id, insight_id__in=insight_ids, insight__deleted=False)
+ .exclude(dashboard__creation_mode=Dashboard.CreationMode.UNLISTED)
+ .order_by("insight_id", "id")
+ .values_list("insight_id", "dashboard_id", "dashboard__name")
+ )
+ refs: dict[int, list[DashboardRef]] = {}
+ for insight_id, dashboard_id, name in rows:
+ refs.setdefault(insight_id, []).append(DashboardRef(id=dashboard_id, name=name))
+ return {insight_id: tuple(dashboards) for insight_id, dashboards in refs.items()}
+
+
def unknown_dashboard_ids(dashboard_ids: Collection[int], *, team_id: int) -> list[int]:
"""Which of these ids are not a live dashboard of this team, in the order they were given.
diff --git a/products/dashboards/backend/test/test_insight_tile_facade.py b/products/dashboards/backend/test/test_insight_tile_facade.py
index d519aa8a6cc0..ea046c66cdee 100644
--- a/products/dashboards/backend/test/test_insight_tile_facade.py
+++ b/products/dashboards/backend/test/test_insight_tile_facade.py
@@ -4,8 +4,10 @@ from parameterized import parameterized
from posthog.models.team import Team
-from products.dashboards.backend.facade.api import unknown_dashboard_ids
+from products.dashboards.backend.facade.api import DashboardRef, dashboards_by_insight, unknown_dashboard_ids
from products.dashboards.backend.models.dashboard import Dashboard
+from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.facade.models import Insight
class TestUnknownDashboardIds(APIBaseTest):
@@ -36,3 +38,30 @@ class TestUnknownDashboardIds(APIBaseTest):
def test_reports_a_repeated_unknown_id_once(self) -> None:
assert unknown_dashboard_ids([9_999_999, 9_999_999], team_id=self.team.id) == [9_999_999]
+
+
+class TestDashboardsByInsight(APIBaseTest):
+ def test_maps_live_insights_to_their_listed_live_dashboards_in_tile_order(self) -> None:
+ insight = Insight.objects.create(team=self.team, name="Signup funnel")
+ deleted_insight = Insight.objects.create(team=self.team, name="gone", deleted=True)
+ first = Dashboard.objects.create(team=self.team, name="Growth overview")
+ second = Dashboard.objects.create(team=self.team, name="Quality review")
+ for dashboard in (
+ second,
+ first,
+ Dashboard.objects.create(team=self.team, name="gone", deleted=True),
+ Dashboard.objects.create(team=self.team, name="embedded", creation_mode="unlisted"),
+ ):
+ DashboardTile.objects.create(dashboard=dashboard, insight=insight)
+ hidden_tile = Dashboard.objects.create(team=self.team, name="tile removed")
+ DashboardTile.objects.create(dashboard=hidden_tile, insight=insight, deleted=True)
+ DashboardTile.objects.create(dashboard=first, insight=deleted_insight)
+ other_team = Team.objects.create(organization=self.organization)
+
+ assert dashboards_by_insight([insight.id, deleted_insight.id], team_id=self.team.id) == {
+ insight.id: (
+ DashboardRef(id=second.id, name="Quality review"),
+ DashboardRef(id=first.id, name="Growth overview"),
+ )
+ }
+ assert dashboards_by_insight([insight.id], team_id=other_team.id) == {}
diff --git a/products/signals/backend/activity_summary/inputs.py b/products/signals/backend/activity_summary/inputs.py
index 286f9db98c0b..80c3e449a239 100644
--- a/products/signals/backend/activity_summary/inputs.py
+++ b/products/signals/backend/activity_summary/inputs.py
@@ -1,11 +1,13 @@
"""Read one user's own tasks and activity log rows in one project, from in-region Postgres."""
import datetime
+from collections.abc import Iterable
from django.db.models.fields.json import KeyTextTransform, KeyTransform
from posthog.models import ActivityLog
+from products.dashboards.backend.facade.api import dashboards_by_insight
from products.signals.backend.activity_summary.render import (
MAX_ACTIVITY_ROWS_PER_PERSON,
MAX_TASKS_PER_PERSON,
@@ -13,6 +15,8 @@ from products.signals.backend.activity_summary.render import (
SANDBOX_PROMPT_TITLE_PREFIX,
SCOUT_CLIENT_PREFIX,
ActivityItem,
+ Parent,
+ ParentLookup,
TaskItem,
)
from products.tasks.backend.facade.user_task_summaries import list_user_task_summaries
@@ -54,7 +58,7 @@ def user_activity(team_id: int, user_id: int, start: datetime.datetime, end: dat
name=KeyTextTransform("name", "detail"),
intent=KeyTextTransform("intent", KeyTransform("payload", KeyTransform("trigger", "detail"))),
)
- .values("scope", "activity", "client", "created_at", "name", "intent")[:MAX_ACTIVITY_ROWS_PER_PERSON]
+ .values("scope", "activity", "client", "created_at", "name", "intent", "item_id")[:MAX_ACTIVITY_ROWS_PER_PERSON]
)
return [
ActivityItem(
@@ -64,6 +68,24 @@ def user_activity(team_id: int, user_id: int, start: datetime.datetime, end: dat
name=row["name"],
client=row["client"],
intent=row["intent"],
+ item_id=row["item_id"],
)
for row in rows
]
+
+
+def activity_parents(team_id: int, activity: Iterable[ActivityItem]) -> ParentLookup:
+ """The dashboards that the insights in these rows sit on, in one query."""
+ insight_ids = {
+ int(item.item_id)
+ for item in activity
+ if item.scope == "Insight" and item.item_id and item.item_id.isascii() and item.item_id.isdigit()
+ }
+ if not insight_ids:
+ return {}
+ return {
+ ("Insight", str(insight_id)): tuple(
+ Parent(scope="Dashboard", item_id=str(dashboard.id), name=dashboard.name or "") for dashboard in dashboards
+ )
+ for insight_id, dashboards in dashboards_by_insight(insight_ids, team_id=team_id).items()
+ }
diff --git a/products/signals/backend/activity_summary/logic.py b/products/signals/backend/activity_summary/logic.py
index 8380ce2160ce..3e011fe3a75c 100644
--- a/products/signals/backend/activity_summary/logic.py
+++ b/products/signals/backend/activity_summary/logic.py
@@ -12,7 +12,7 @@ from django.utils import timezone
from posthog.dataclasses import frozen
from posthog.models import Team
-from products.signals.backend.activity_summary.inputs import user_activity, user_tasks
+from products.signals.backend.activity_summary.inputs import activity_parents, user_activity, user_tasks
from products.signals.backend.activity_summary.prompt import PROMPT_VERSION, summary_text
from products.signals.backend.activity_summary.render import (
DEFAULT_LIMITS,
@@ -171,7 +171,12 @@ def update_activity_summary(
tasks = user_tasks(team_id, user_id, start, now)
activity = user_activity(team_id, user_id, start, now)
rendered = build_input(
- tasks, activity, as_of=now, seed=sampling_seed(now.date().isoformat(), team_id, user_id), limits=limits
+ tasks,
+ activity,
+ as_of=now,
+ seed=sampling_seed(now.date().isoformat(), team_id, user_id),
+ limits=limits,
+ parents=activity_parents(team_id, activity),
)
if rendered is None or rendered.units < min_units:
if not dry_run:
diff --git a/products/signals/backend/activity_summary/prompt.py b/products/signals/backend/activity_summary/prompt.py
index a76e36b04f4d..3e1e7447176e 100644
--- a/products/signals/backend/activity_summary/prompt.py
+++ b/products/signals/backend/activity_summary/prompt.py
@@ -9,12 +9,13 @@ import json
import datetime
from typing import Any
-PROMPT_VERSION = 2
+from products.signals.backend.activity_summary.render import SUMMARY_MAX_WORDS, cap_line
+
+PROMPT_VERSION = 3
-SUMMARY_MAX_WORDS = 60
MAX_FOCUS_AREAS = 6
MAX_PRODUCTS = 10
-# Per-field caps, so one runaway field cannot make the stored summary large.
+# Per-field caps, so one runaway field cannot make the stored summary large. A cut ends at a word boundary.
MAX_TOPIC_CHARS = 80
MAX_PRODUCT_CHARS = 40
MAX_RECENT_SHIFT_CHARS = 300
@@ -97,7 +98,7 @@ def _clean(value: Any, max_chars: int | None = None) -> str | None:
text = " ".join(value.split())
if text.lower() in _NULL_STRINGS:
return None
- return text[:max_chars].strip() if max_chars is not None else text
+ return cap_line(text, max_chars) if max_chars is not None else text
def cap_words(text: str, max_words: int = SUMMARY_MAX_WORDS) -> str:
diff --git a/products/signals/backend/activity_summary/render.py b/products/signals/backend/activity_summary/render.py
index 30f1d27db8c4..3c12c100f4b7 100644
--- a/products/signals/backend/activity_summary/render.py
+++ b/products/signals/backend/activity_summary/render.py
@@ -15,18 +15,19 @@ import hashlib
import datetime
import dataclasses
from collections import Counter
-from collections.abc import Iterable, Sequence
+from collections.abc import Iterable, Mapping, Sequence
from enum import StrEnum
from typing import Any
from urllib.parse import urlsplit
from posthog.dataclasses import frozen
-from products.signals.backend.activity_summary.prompt import SUMMARY_MAX_WORDS
+# Words of the stored summary. It lives here and not in `prompt`, because `prompt` imports from this module.
+SUMMARY_MAX_WORDS = 60
# Bump on any code change to the filters, the default caps, the sampling or the rendered layout, so summaries
# stay comparable. Limits from the flag payload go into `inputs_used` instead.
-RENDER_VERSION = 4
+RENDER_VERSION = 5
WINDOW_DAYS = 28
RECENCY_HALF_LIFE_DAYS = 7
@@ -41,6 +42,9 @@ MAX_ACTIVITY_ROWS_PER_PERSON = 1000
MAX_UNITS_PER_DAY = 3
TASK_LINES = 12
ACTIVITY_LINES = 15
+# Activity lines one UTC day may keep while other days have lines to show. A third of the section
+# leaves a busy day several lines and the rest of the window most of the slots.
+MAX_ACTIVITY_LINES_PER_DAY = 5
# Per-line caps, so one runaway title or intent cannot take the budget. With the default caps a full
# prompt section stays under SECTIONS_MAX_CHARS; the hard stop is the backstop when the caps change.
TASK_LINE_CHARS = 260
@@ -104,6 +108,7 @@ class RenderLimits:
window_days: int = _limit(WINDOW_DAYS, max_value=90)
task_lines: int = _limit(TASK_LINES, max_value=50)
activity_lines: int = _limit(ACTIVITY_LINES, max_value=50)
+ max_activity_lines_per_day: int = _limit(MAX_ACTIVITY_LINES_PER_DAY, max_value=50)
max_units_per_day: int = _limit(MAX_UNITS_PER_DAY, max_value=20)
sections_max_chars: int = _limit(SECTIONS_MAX_CHARS, max_value=32000)
task_line_chars: int = _limit(TASK_LINE_CHARS, max_value=1000)
@@ -128,6 +133,7 @@ class Drop(StrEnum):
AUTO_NAMED_OBJECT = "auto_named_object"
UNNAMED_OBJECT = "unnamed_object"
DUPLICATE = "duplicate"
+ GROUPED_INTO_PARENT = "grouped_into_parent"
BURST_CAP = "burst_cap"
SAMPLE_CAP = "sample_cap"
SECTIONS_BUDGET = "sections_budget"
@@ -153,6 +159,20 @@ class ActivityItem:
name: str | None
client: str | None
intent: str | None = None
+ item_id: str | None = None
+
+
+@frozen
+class Parent:
+ """An object that holds another, such as the dashboard an insight sits on."""
+
+ scope: str
+ item_id: str
+ name: str
+
+
+# Parents of an object in preference order, keyed by the object's (scope, item_id).
+ParentLookup = Mapping[tuple[str, str], Sequence[Parent]]
@frozen
@@ -163,6 +183,16 @@ class Unit:
text: str
+@frozen
+class _ActivityLine:
+ """A rendered activity line with the fields that rank it."""
+
+ at: datetime.datetime
+ text: str
+ created: bool
+ rows: int
+
+
@frozen
class RenderedInput:
text: str
@@ -285,15 +315,183 @@ def task_units(tasks: Iterable[TaskItem], drops: Counter[str], limits: RenderLim
return units
+ObjectKey = tuple[str, str, str]
+
+
+def _intent_suffix(rows: Iterable[ActivityItem], max_chars: int) -> str:
+ intents = [row for row in rows if row.intent and row.intent.strip()]
+ if not intents:
+ return ""
+ intent = max(intents, key=lambda row: row.at).intent or ""
+ intent_text = cap_line(clean_text(intent, max_chars * 2), max_chars)
+ return f" (agent: {intent_text})" if intent_text else ""
+
+
+def _display_name(name: str) -> str:
+ return cap_line(clean_text(name, ACTIVITY_NAME_CHARS * 2), ACTIVITY_NAME_CHARS)
+
+
+def _quoted_names(names: Sequence[str], max_chars: int) -> str:
+ """Quoted names joined by commas, as many as fit in `max_chars`, with "…" for the rest."""
+ text = ", ".join(f'"{name}"' for name in names)
+ if len(text) <= max_chars:
+ return text
+ text = ""
+ for name in names:
+ part = f'"{name}"' if not text else f', "{name}"'
+ if len(text) + len(part) + len(", …") > max_chars:
+ break
+ text += part
+ return f"{text}, …" if text else "…"
+
+
+def _usable_parents(parents: Sequence[Parent]) -> list[Parent]:
+ """Parents with a name worth showing: a scheduled job's auto-named object says nothing."""
+ usable: list[Parent] = []
+ for parent in parents:
+ name = parent.name.strip()
+ if name and not _AUTO_NAME.search(name) and parent not in usable:
+ usable.append(parent)
+ return usable
+
+
+def _object_line(
+ scope: str, activity: str, name: str, rows: Sequence[ActivityItem], context: str, limits: RenderLimits
+) -> _ActivityLine:
+ latest = max(row.at for row in rows)
+ count = f" (x{len(rows)})" if len(rows) > 1 else ""
+ line = f'- {_day(latest).isoformat()} {activity} {scope} "{_display_name(name)}"{context}{count}'
+ return _ActivityLine(
+ at=latest,
+ text=cap_line(line + _intent_suffix(rows, limits.activity_intent_chars), limits.activity_line_chars),
+ created=activity == "created",
+ rows=len(rows),
+ )
+
+
+def _group_line(
+ parent: Parent,
+ own: Sequence[ObjectKey],
+ children: Sequence[ObjectKey],
+ collapsed: Mapping[ObjectKey, list[ActivityItem]],
+ limits: RenderLimits,
+) -> _ActivityLine:
+ """One line for a parent and the children merged into it, children ranked like lines."""
+ rows = [row for key in (*own, *children) for row in collapsed[key]]
+ latest = max(row.at for row in rows)
+ ranked_children = sorted(
+ children,
+ key=lambda key: (
+ key[1] != "created",
+ -len(collapsed[key]),
+ -max(row.at for row in collapsed[key]).timestamp(),
+ key[2],
+ ),
+ )
+ names = list(dict.fromkeys(_display_name(key[2]) for key in ranked_children))
+ counts = Counter(scope for scope, _ in dict.fromkeys((key[0], key[2]) for key in children))
+ child_text = ", ".join(f"{count} {scope}{'s' if count != 1 else ''}" for scope, count in sorted(counts.items()))
+ parent_text = f'{parent.scope} "{_display_name(parent.name)}"'
+ if any(key[1] == "created" for key in own):
+ head = f"created {parent_text} with {child_text}: "
+ else:
+ activities = sorted({key[1] for key in children}, key=lambda activity: (activity != "created", activity))
+ head = f"{' and '.join(activities)} {child_text} on {parent_text}: "
+ head = f"- {_day(latest).isoformat()} {head}"
+ intent = _intent_suffix(rows, limits.activity_intent_chars)
+ line = head + _quoted_names(names, limits.activity_line_chars - len(head) - len(intent)) + intent
+ return _ActivityLine(
+ at=latest,
+ text=cap_line(line, limits.activity_line_chars),
+ created=any(row.activity == "created" for row in rows),
+ rows=len(rows),
+ )
+
+
+def _lines_with_parents(
+ collapsed: Mapping[ObjectKey, list[ActivityItem]], parents: ParentLookup, drops: Counter[str], limits: RenderLimits
+) -> list[_ActivityLine]:
+ """One line per object, with the objects that share a parent merged into one line for the parent.
+
+ The parent's own rows merge into its line. An object whose parent holds no other changed object
+ keeps its own line and names the parent."""
+ child_parents: dict[ObjectKey, list[Parent]] = {}
+ for key, rows in collapsed.items():
+ found = [parent for row in rows if row.item_id for parent in parents.get((row.scope, row.item_id), ())]
+ if usable := _usable_parents(found):
+ child_parents[key] = usable
+ by_identity = {(parent.scope, parent.item_id): parent for usable in child_parents.values() for parent in usable}
+ own: dict[Parent, list[ObjectKey]] = {}
+ for key, rows in collapsed.items():
+ identities = dict.fromkeys((row.scope, row.item_id) for row in rows if row.item_id)
+ for identity in identities:
+ if (parent := by_identity.get(identity)) is not None:
+ own.setdefault(parent, []).append(key)
+ # Each child picks the parent that holds the most changed objects, so a group forms where the work was.
+ weight = Counter(parent for usable in child_parents.values() for parent in usable)
+ weight.update({parent: len(keys) for parent, keys in own.items()})
+ chosen: dict[Parent, list[ObjectKey]] = {}
+ for key, usable in child_parents.items():
+ chosen.setdefault(max(usable, key=lambda parent: weight[parent]), []).append(key)
+
+ lines: list[_ActivityLine] = []
+ merged: set[ObjectKey] = set()
+ for parent, children in chosen.items():
+ parent_own = [key for key in own.get(parent, []) if key not in child_parents]
+ distinct_children = {(key[0], key[2]) for key in children}
+ if len(distinct_children) < 2 and not parent_own:
+ continue
+ lines.append(_group_line(parent, parent_own, children, collapsed, limits))
+ merged.update(parent_own, children)
+ drops[Drop.GROUPED_INTO_PARENT] += len(parent_own) + len(children) - 1
+ for key, rows in collapsed.items():
+ if key in merged:
+ continue
+ context = ""
+ if key in child_parents:
+ usable = child_parents[key]
+ parent = max(usable, key=lambda parent: weight[parent])
+ more = f" (+{len(usable) - 1} more)" if len(usable) > 1 else ""
+ context = f' on {parent.scope} "{_display_name(parent.name)}"{more}'
+ lines.append(_object_line(*key, rows, context, limits))
+ return lines
+
+
+def _spread_across_days(
+ ranked: Sequence[_ActivityLine], drops: Counter[str], limits: RenderLimits
+) -> list[_ActivityLine]:
+ """The first `limits.activity_lines` lines in rank order, at most `limits.max_activity_lines_per_day` from one UTC day.
+
+ Lines over a day's cap fill the slots that no other day takes, so a single busy day still shows."""
+ kept: list[_ActivityLine] = []
+ deferred: list[_ActivityLine] = []
+ per_day: Counter[datetime.date] = Counter()
+ for line in ranked:
+ if per_day[_day(line.at)] >= limits.max_activity_lines_per_day:
+ deferred.append(line)
+ elif len(kept) < limits.activity_lines:
+ per_day[_day(line.at)] += 1
+ kept.append(line)
+ else:
+ drops[Drop.SAMPLE_CAP] += 1
+ backfill = deferred[: limits.activity_lines - len(kept)]
+ if len(deferred) > len(backfill):
+ drops[Drop.BURST_CAP] += len(deferred) - len(backfill)
+ return kept + backfill
+
+
def activity_units(
- items: Iterable[ActivityItem], drops: Counter[str], limits: RenderLimits = DEFAULT_LIMITS
+ items: Iterable[ActivityItem],
+ drops: Counter[str],
+ parents: ParentLookup | None = None,
+ limits: RenderLimits = DEFAULT_LIMITS,
) -> list[Unit]:
- """Changes collapsed to one line per object, creates first, then the most changed, then the newest.
+ """Changes collapsed to one line per object, or per parent, creates first, then the most changed, then the newest.
- A line carries the newest agent intent of its rows. Lines are already collapsed per object, so
- they skip the per-day burst cap: a busy day of changes to different objects lands on one date
- and the cap would keep only a few of them."""
- collapsed: dict[tuple[str, str, str], list[ActivityItem]] = {}
+ A line carries the newest agent intent of its rows. A day keeps at most `limits.max_activity_lines_per_day`
+ lines while other days have lines left, not the `MAX_UNITS_PER_DAY` of tasks: lines are already
+ collapsed per object, and a busy day of changes to different objects is more than three things."""
+ collapsed: dict[ObjectKey, list[ActivityItem]] = {}
for item in items:
name = (item.name or "").strip()
if item.scope in NOISY_ACTIVITY_SCOPES:
@@ -306,30 +504,10 @@ def activity_units(
drops[Drop.AUTO_NAMED_OBJECT] += 1
else:
collapsed.setdefault((item.scope, item.activity, name), []).append(item)
- ranked = sorted(
- collapsed.items(),
- key=lambda entry: (
- entry[0][1] != "created",
- -len(entry[1]),
- -max(row.at for row in entry[1]).timestamp(),
- ),
- )
- if len(ranked) > limits.activity_lines:
- drops[Drop.SAMPLE_CAP] += len(ranked) - limits.activity_lines
- units: list[Unit] = []
- for (scope, activity, name), rows in ranked[: limits.activity_lines]:
- latest = max(row.at for row in rows)
- count = f" (x{len(rows)})" if len(rows) > 1 else ""
- name_text = cap_line(clean_text(name, ACTIVITY_NAME_CHARS * 2), ACTIVITY_NAME_CHARS)
- line = f'- {_day(latest).isoformat()} {activity} {scope} "{name_text}"{count}'
- intents = [row for row in rows if row.intent and row.intent.strip()]
- if intents:
- intent = max(intents, key=lambda row: row.at).intent or ""
- intent_text = cap_line(clean_text(intent, limits.activity_intent_chars * 2), limits.activity_intent_chars)
- if intent_text:
- line += f" (agent: {intent_text})"
- units.append(Unit(at=latest, text=cap_line(line, limits.activity_line_chars)))
- return sorted(units, key=lambda unit: (unit.at, unit.text))
+ lines = _lines_with_parents(collapsed, parents or {}, drops, limits)
+ ranked = sorted(lines, key=lambda line: (not line.created, -line.rows, -line.at.timestamp(), line.text))
+ kept = _spread_across_days(ranked, drops, limits)
+ return sorted((Unit(at=line.at, text=line.text) for line in kept), key=lambda unit: (unit.at, unit.text))
def dedupe_latest(units: Iterable[Unit], drops: Counter[str]) -> list[Unit]:
@@ -408,16 +586,19 @@ def build_input(
as_of: datetime.datetime,
seed: int,
limits: RenderLimits = DEFAULT_LIMITS,
+ parents: ParentLookup | None = None,
) -> RenderedInput | None:
"""The rendered input of one (project, person) pair, or None when nothing survives the filters.
Order: the named filters, then the burst cap, then the recency-weighted sample, then the hard
- budget, so the sample is drawn from clean units only."""
+ budget, so the sample is drawn from clean units only. `parents` groups activity lines under the
+ objects that hold them."""
drops: Counter[str] = Counter()
task_pool = burst_cap(dedupe_latest(task_units(tasks, drops, limits), drops), drops, limits.max_units_per_day)
- activity_lines = activity_units(activity, drops, limits)
- # Only `activity_units` has counted a sample cap drop so far.
- activity_pool = len(activity_lines) + drops[Drop.SAMPLE_CAP]
+ capped_before = drops[Drop.SAMPLE_CAP] + drops[Drop.BURST_CAP]
+ activity_lines = activity_units(activity, drops, parents, limits)
+ # Lines that `activity_units` dropped for its line cap or its per-day cap.
+ activity_pool = len(activity_lines) + drops[Drop.SAMPLE_CAP] + drops[Drop.BURST_CAP] - capped_before
if not task_pool and not activity_lines:
return None
chosen_tasks = sample_units(task_pool, limit=limits.task_lines, as_of=as_of, seed=seed)
diff --git a/products/signals/backend/activity_summary/summaries.py b/products/signals/backend/activity_summary/summaries.py
index 5e47873eb3b8..b47d584f41a0 100644
--- a/products/signals/backend/activity_summary/summaries.py
+++ b/products/signals/backend/activity_summary/summaries.py
@@ -16,13 +16,12 @@ from posthog.llm.gateway_client import build_openai_client, trace_id_from_seed
from products.signals.backend.activity_summary.prompt import (
RESPONSE_FORMAT,
- SUMMARY_MAX_WORDS,
MalformedSummaryError,
normalize_summary,
system_prompt,
user_message,
)
-from products.signals.backend.activity_summary.render import MAX_COMPLETION_TOKENS
+from products.signals.backend.activity_summary.render import MAX_COMPLETION_TOKENS, SUMMARY_MAX_WORDS
AI_PRODUCT = "activity_summary"
# Not a person: the gateway attributes every call to the pipeline.
diff --git a/products/signals/backend/test/test_activity_summary_render.py b/products/signals/backend/test/test_activity_summary_render.py
index e7add5b02aa5..2ef7afa7d3a3 100644
--- a/products/signals/backend/test/test_activity_summary_render.py
+++ b/products/signals/backend/test/test_activity_summary_render.py
@@ -20,13 +20,17 @@ from products.signals.backend.activity_summary.prompt import (
)
from products.signals.backend.activity_summary.render import (
ACTIVITY_HEADER,
+ ACTIVITY_LINE_CHARS,
+ ACTIVITY_LINES,
DEFAULT_LIMITS,
+ MAX_ACTIVITY_LINES_PER_DAY,
MAX_COMPLETION_TOKENS,
MAX_UNITS_PER_DAY,
TASK_LINES,
TASKS_HEADER,
ActivityItem,
Drop,
+ Parent,
RenderLimits,
TaskItem,
Unit,
@@ -59,8 +63,15 @@ def _change(
client: str | None = None,
days_ago: float = 1,
intent: str | None = None,
+ item_id: str | None = None,
) -> ActivityItem:
- return ActivityItem(at=_at(days_ago), scope=scope, activity=activity, name=name, client=client, intent=intent)
+ return ActivityItem(
+ at=_at(days_ago), scope=scope, activity=activity, name=name, client=client, intent=intent, item_id=item_id
+ )
+
+
+QUALITY = Parent(scope="Dashboard", item_id="10", name="Quality review")
+GROWTH = Parent(scope="Dashboard", item_id="11", name="Growth overview")
@parameterized.expand(
@@ -159,6 +170,111 @@ def test_activity_units_render_the_agent_intent(_name: str, intents: list[str |
assert [unit.text for unit in activity_units(items, Counter())] == [expected]
+ [
+ (
+ "insights on one dashboard merge with the dashboard's created row",
+ [
+ _change("Dashboard", "created", "Quality review", days_ago=3, item_id="10"),
+ _change("Insight", "created", "Records judged per day", days_ago=2.9, item_id="1"),
+ _change("Insight", "created", "Suggestion defect rates", days_ago=2.8, item_id="2"),
+ _change("Insight", "updated", "Suggestion defect rates", days_ago=2.7, item_id="2"),
+ _change("Insight", "created", "Unplaced funnel", days_ago=1, item_id="3"),
+ ],
+ {("Insight", "1"): (QUALITY,), ("Insight", "2"): (QUALITY,)},
+ [
+ '- 2026-10-16 created Dashboard "Quality review" with 2 Insights: '
+ '"Suggestion defect rates", "Records judged per day"',
+ '- 2026-10-18 created Insight "Unplaced funnel"',
+ ],
+ {Drop.GROUPED_INTO_PARENT: 3},
+ ),
+ (
+ "insights on a dashboard the person did not create group under it",
+ [
+ _change("Insight", "created", "Records judged per day", item_id="1"),
+ _change("Insight", "updated", "Suggestion defect rates", item_id="2"),
+ ],
+ {("Insight", "1"): (QUALITY,), ("Insight", "2"): (QUALITY,)},
+ [
+ '- 2026-10-18 created and updated 2 Insights on Dashboard "Quality review": '
+ '"Records judged per day", "Suggestion defect rates"'
+ ],
+ {Drop.GROUPED_INTO_PARENT: 1},
+ ),
+ (
+ "a lone insight names its dashboard and how many more it sits on",
+ [_change("Insight", "created", "Signup funnel", item_id="1")],
+ {("Insight", "1"): (GROWTH, QUALITY)},
+ ['- 2026-10-18 created Insight "Signup funnel" on Dashboard "Growth overview" (+1 more)'],
+ {},
+ ),
+ (
+ "an insight joins the dashboard that holds the other changed insights",
+ [
+ _change("Insight", "created", "Signup funnel", item_id="1"),
+ _change("Insight", "created", "Defect rates", item_id="2"),
+ ],
+ {("Insight", "1"): (GROWTH, QUALITY), ("Insight", "2"): (QUALITY,)},
+ ['- 2026-10-18 created 2 Insights on Dashboard "Quality review": "Defect rates", "Signup funnel"'],
+ {Drop.GROUPED_INTO_PARENT: 1},
+ ),
+ (
+ "an auto-named dashboard gives no context",
+ [_change("Insight", "created", "Signup funnel", item_id="1")],
+ {("Insight", "1"): (Parent(scope="Dashboard", item_id="12", name="Daily report 2026-10-18"),)},
+ ['- 2026-10-18 created Insight "Signup funnel"'],
+ {},
+ ),
+ ]
+)
+def test_activity_units_group_children_under_their_parent(
+ _name: str,
+ items: list[ActivityItem],
+ parents: dict[tuple[str, str], tuple[Parent, ...]],
+ expected: list[str],
+ expected_drops: dict[str, int],
+) -> None:
+ drops: Counter[str] = Counter()
+ assert [unit.text for unit in activity_units(items, drops, parents)] == expected
+ assert dict(drops) == expected_drops
+
+
+def test_a_group_line_lists_the_names_that_fit_and_marks_the_rest() -> None:
+ items = [
+ _change(
+ "Insight", "created", f"Insight number {n} with a fairly long name", days_ago=1 + n / 100, item_id=str(n)
+ )
+ for n in range(12)
+ ]
+ parents = {("Insight", str(n)): (QUALITY,) for n in range(12)}
+
+ [unit] = activity_units(items, Counter(), parents)
+
+ assert unit.text.startswith('- 2026-10-18 created 12 Insights on Dashboard "Quality review": "Insight number 0')
+ assert unit.text.endswith('", …')
+ assert len(unit.text) <= ACTIVITY_LINE_CHARS
+
+
+ [
+ ("other days take the slots a burst would fill", 12, MAX_ACTIVITY_LINES_PER_DAY),
+ ("a burst fills the slots no other day takes", 3, ACTIVITY_LINES - 3),
+ ("a lone busy day still fills the section", 0, ACTIVITY_LINES),
+ ]
+)
+def test_activity_units_spread_a_burst_across_days(_name: str, older_days: int, expected_burst_lines: int) -> None:
+ drops: Counter[str] = Counter()
+ burst = [_change("Insight", "created", f"Burst {n}", days_ago=1 - n / 1000) for n in range(ACTIVITY_LINES + 5)]
+ older = [_change("Notebook", "updated", f"Older {day}", days_ago=day) for day in range(2, 2 + older_days)]
+
+ units = activity_units(burst + older, drops)
+
+ assert len(units) == ACTIVITY_LINES
+ assert sum(1 for unit in units if "Burst" in unit.text) == expected_burst_lines
+ assert drops[Drop.BURST_CAP] + drops[Drop.SAMPLE_CAP] == len(burst) + len(older) - ACTIVITY_LINES
+
+
def test_burst_cap_keeps_the_newest_units_of_a_day() -> None:
drops: Counter[str] = Counter()
units = [Unit(at=_at(1, minutes=minute), text=f"unit {minute}") for minute in range(MAX_UNITS_PER_DAY + 2)]
@@ -348,19 +464,31 @@ def _answer(**overrides: Any) -> str:
{"focus_areas": []},
),
(
- "topic, product and recent_shift are cut to their caps",
+ "topic, product and recent_shift are cut at a word boundary inside their caps",
_answer(
- focus_areas=[{"topic": "t" * 500, "strength": "high", "last_seen": "2026-10-17"}],
- products=["p" * 500],
- recent_shift="s" * 2000,
+ focus_areas=[{"topic": "adoption " * 50, "strength": "high", "last_seen": "2026-10-17"}],
+ products=["analytics " * 50],
+ recent_shift="shift " * 400,
),
True,
{
- "focus_areas": [{"topic": "t" * MAX_TOPIC_CHARS, "strength": "high", "last_seen": "2026-10-17"}],
- "products": ["p" * MAX_PRODUCT_CHARS],
- "recent_shift": "s" * MAX_RECENT_SHIFT_CHARS,
+ "focus_areas": [
+ {
+ "topic": " ".join(["adoption"] * ((MAX_TOPIC_CHARS - 1) // 9)) + "…",
+ "strength": "high",
+ "last_seen": "2026-10-17",
+ }
+ ],
+ "products": [" ".join(["analytics"] * ((MAX_PRODUCT_CHARS - 1) // 10)) + "…"],
+ "recent_shift": " ".join(["shift"] * ((MAX_RECENT_SHIFT_CHARS - 1) // 6)) + "…",
},
),
+ (
+ "one long word is cut and marked",
+ _answer(products=["p" * 500]),
+ False,
+ {"products": ["p" * (MAX_PRODUCT_CHARS - 1) + "…"]},
+ ),
]
)
def test_normalize_summary(_name: str, content: str, had_previous: bool, expected: dict[str, Any]) -> None:
diff --git a/products/signals/backend/test/test_activity_summary_update.py b/products/signals/backend/test/test_activity_summary_update.py
index 57ff9d937513..f88ecb4a22dc 100644
--- a/products/signals/backend/test/test_activity_summary_update.py
+++ b/products/signals/backend/test/test_activity_summary_update.py
@@ -10,6 +10,9 @@ from parameterized import parameterized
from posthog.models import ActivityLog
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.facade.models import Insight
from products.signals.backend.activity_summary.inputs import user_activity
from products.signals.backend.activity_summary.logic import ActivitySummaryUpdate, UpdateStatus, update_activity_summary
from products.signals.backend.activity_summary.render import RenderLimits
@@ -41,11 +44,9 @@ class TestUpdateActivitySummary(BaseTest):
organization_id=self.organization.id,
user=self.user,
scope=scope,
- activity="created",
- item_id=name,
detail=detail,
created_at=NOW - datetime.timedelta(days=days_ago),
- **overrides,
+ **{"activity": "created", "item_id": name, **overrides},
)
def _changes(self, count: int, *, days_ago: float = 1) -> None:
@@ -102,6 +103,23 @@ class TestUpdateActivitySummary(BaseTest):
assert stored.inputs_used["activity_lines"] == 3
assert stored.inputs_used["limits"]["max_completion_tokens"] == 1234
+ def test_insights_on_a_dashboard_render_as_one_line_for_the_dashboard(self) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, name="Quality review")
+ self._change("Quality review", days_ago=1.2, scope="Dashboard", item_id=str(dashboard.id))
+ for index, name in enumerate(["Records judged per day", "Suggestion defect rates"]):
+ insight = Insight.objects.create(team=self.team, name=name)
+ DashboardTile.objects.create(dashboard=dashboard, insight=insight)
+ self._change(name, days_ago=1.1 - index / 100, item_id=str(insight.id))
+
+ result = self._update(FakeLLM([ANSWER]), dry_run=True, min_units=1)
+
+ assert result.rendered_input is not None and result.inputs_used is not None
+ assert result.rendered_input.splitlines()[1:] == [
+ '- 2026-10-18 created Dashboard "Quality review" with 2 Insights: '
+ '"Suggestion defect rates", "Records judged per day"'
+ ]
+ assert result.inputs_used["drops"] == {"grouped_into_parent": 2}
+
def test_a_failed_update_keeps_the_stored_summary_and_watermark(self) -> None:
self._changes(3, days_ago=2)
self._update(FakeLLM([ANSWER]))