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): add noise filters and computed fields to activity summaries (#123029)

posthog[bot]ae9b0220ced7
diff --git a/products/signals/backend/activity_summary/computed.py b/products/signals/backend/activity_summary/computed.py
new file mode 100644
index 000000000000..11b0bf42361d
--- /dev/null
+++ b/products/signals/backend/activity_summary/computed.py
@@ -0,0 +1,225 @@
+"""Exact fields of an activity summary that code computes from the window, with no model call.
+
+Consumers that need ids, such as reviewer assignment or the homepage, read these instead of the prose.
+`update_activity_summary` computes them from the full window on every successful update, after the
+filters of `render.py`, so automated activity does not reach them either.
+"""
+
+import re
+import json
+import datetime
+import dataclasses
+from collections import Counter
+from collections.abc import Iterable
+from typing import Any
+
+from posthog.dataclasses import frozen
+
+from products.signals.backend.activity_summary.render import (
+ ACTIVITY_NAME_CHARS,
+ SCENE_VIEW_TYPE,
+ ActivityItem,
+ Product,
+ TaskItem,
+ ViewItem,
+ cap_line,
+ clean_text,
+ is_auto_named,
+ person_activity,
+ scene_product,
+ scope_of,
+ scope_product,
+ task_units,
+)
+
+# Bump on any change to the shape or the meaning of a field, so a consumer can tell old rows apart.
+COMPUTED_SCHEMA_VERSION = 1
+MAX_OWNED = 20
+MAX_WATCHED = 20
+# An object opened on fewer days than this is a visit, not something the person keeps an eye on.
+MIN_WATCHED_OPEN_DAYS = 3
+# The file system refers to these by short id, the activity log by primary key.
+_SHORT_ID_SCOPES: frozenset[str] = frozenset({"Insight", "Notebook", "SessionRecordingPlaylist"})
+
+_SNAKE_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
+_TAG_SEPARATORS = re.compile(r"[\s/-]+")
+
+
+@frozen
+class OwnedObject:
+ ref: str
+ type: str
+ id: str
+ name: str
+ edit_days: int
+ last_at: str
+ created: bool
+
+
+@frozen
+class WatchedObject:
+ ref: str
+ type: str
+ id: str
+ name: str
+ open_days: int
+ last_at: str
+ not_theirs: bool
+
+
+@frozen
+class PageVisits:
+ ref: str
+ product: str
+ open_days: int
+ last_at: str
+
+
+@frozen
+class ProductSplit:
+ works_in: tuple[str, ...]
+ visits: tuple[str, ...]
+
+
+@frozen
+class ComputedFields:
+ schema_version: int
+ owned: tuple[OwnedObject, ...]
+ watched: tuple[WatchedObject, ...]
+ pages: tuple[PageVisits, ...]
+ products: ProductSplit
+ task_count: int
+
+ def as_json(self) -> dict[str, Any]:
+ # JSON has no tuples, so the stored value and this one compare equal.
+ return json.loads(json.dumps(dataclasses.asdict(self)))
+
+
+def _day(at: datetime.datetime) -> datetime.date:
+ return at.astimezone(datetime.UTC).date()
+
+
+def _snake(scope: str) -> str:
+ """The file system type of an activity log scope, such as "feature_flag" for "FeatureFlag"."""
+ return _SNAKE_BOUNDARY.sub("_", scope).lower()
+
+
+def _name(name: str) -> str:
+ return cap_line(clean_text(name, ACTIVITY_NAME_CHARS * 2), ACTIVITY_NAME_CHARS)
+
+
+def _tag_product(tag: str) -> Product | None:
+ key = _TAG_SEPARATORS.sub("_", tag.strip().lower())
+ return Product(key) if key in Product._value2member_map_ else None
+
+
+def _object_id(item: ActivityItem) -> str | None:
+ if item.scope in _SHORT_ID_SCOPES and item.short_id:
+ return item.short_id
+ return item.item_id
+
+
+def _ranked(counts: Counter[Product]) -> tuple[str, ...]:
+ return tuple(str(product) for product, _ in sorted(counts.items(), key=lambda pair: (-pair[1], pair[0])))
+
+
+def compute_fields(
+ tasks: Iterable[TaskItem], activity: Iterable[ActivityItem], views: Iterable[ViewItem]
+) -> ComputedFields:
+ """The owned and watched objects, the product pages, the products and the task count of one window.
+
+ `owned` holds the objects the person created or changed, the most edited first. `watched` holds
+ the objects opened on `MIN_WATCHED_OPEN_DAYS` or more days, the most opened first. A product is in
+ `works_in` when the person changed something in it or tagged a task with it, and in `visits` when
+ they only opened its pages or objects."""
+ kept, _ = person_activity(activity, Counter(), keep_ticket_bursts=True)
+ edits: dict[tuple[str, str], list[ActivityItem]] = {}
+ work_days: dict[Product, set[datetime.date]] = {}
+ for item in kept:
+ if (product := scope_product(item.scope)) is not None:
+ work_days.setdefault(product, set()).add(_day(item.at))
+ if object_id := _object_id(item):
+ edits.setdefault((item.scope, object_id), []).append(item)
+ work: Counter[Product] = Counter({product: len(days) for product, days in work_days.items()})
+
+ owned_ranked = sorted(
+ edits.items(),
+ key=lambda entry: (
+ -len({_day(row.at) for row in entry[1]}),
+ -max(row.at for row in entry[1]).timestamp(),
+ entry[0],
+ ),
+ )
+ owned: list[OwnedObject] = []
+ for (scope, item_id), rows in owned_ranked[:MAX_OWNED]:
+ latest = max(rows, key=lambda row: row.at)
+ owned.append(
+ OwnedObject(
+ ref=f"o{len(owned) + 1}",
+ type=_snake(scope),
+ id=item_id,
+ name=_name(latest.name or ""),
+ edit_days=len({_day(row.at) for row in rows}),
+ last_at=_day(latest.at).isoformat(),
+ created=any(row.activity == "created" for row in rows),
+ )
+ )
+
+ tasks = list(tasks)
+ for task in tasks:
+ for tag in task.tags:
+ if (product := _tag_product(tag)) is not None:
+ work[product] += 1
+
+ visit: Counter[Product] = Counter()
+ pages: dict[Product, tuple[datetime.datetime, set[datetime.date]]] = {}
+ candidates: list[ViewItem] = []
+ for view in views:
+ if view.type == SCENE_VIEW_TYPE:
+ if (product := scene_product(view.ref)) is not None:
+ at, days = pages.get(product, (view.at, set()))
+ pages[product] = (max(at, view.at), days | set(view.days))
+ continue
+ name = (view.name or "").strip()
+ if not name or is_auto_named(name):
+ continue
+ open_days = len(set(view.days))
+ if (product := scope_product(scope_of(view.type))) is not None:
+ visit[product] += open_days
+ if open_days >= MIN_WATCHED_OPEN_DAYS:
+ candidates.append(view)
+ for product, (_, days) in pages.items():
+ visit[product] += len(days)
+
+ candidates.sort(key=lambda view: (-len(set(view.days)), -view.at.timestamp(), view.type, view.ref))
+ refs = {(entry.type, entry.id): entry.ref for entry in owned}
+ watched: list[WatchedObject] = []
+ for view in candidates[:MAX_WATCHED]:
+ if (view.type, view.ref) not in refs:
+ refs[(view.type, view.ref)] = f"o{len(refs) + 1}"
+ watched.append(
+ WatchedObject(
+ ref=refs[(view.type, view.ref)],
+ type=view.type,
+ id=view.ref,
+ name=_name(view.name or ""),
+ open_days=len(set(view.days)),
+ last_at=_day(view.at).isoformat(),
+ not_theirs=view.not_theirs,
+ )
+ )
+ page_list = [
+ PageVisits(ref=f"p{index + 1}", product=str(product), open_days=len(days), last_at=_day(at).isoformat())
+ for index, (product, (at, days)) in enumerate(
+ sorted(pages.items(), key=lambda entry: (-len(entry[1][1]), -entry[1][0].timestamp(), entry[0]))
+ )
+ ]
+ visits_only = Counter({product: count for product, count in visit.items() if product not in work})
+ return ComputedFields(
+ schema_version=COMPUTED_SCHEMA_VERSION,
+ owned=tuple(owned),
+ watched=tuple(watched),
+ pages=tuple(page_list),
+ products=ProductSplit(works_in=_ranked(work), visits=_ranked(visits_only)),
+ task_count=len(task_units(tasks, Counter())),
+ )
diff --git a/products/signals/backend/activity_summary/inputs.py b/products/signals/backend/activity_summary/inputs.py
index f94771e5de24..46d20512a9d5 100644
--- a/products/signals/backend/activity_summary/inputs.py
+++ b/products/signals/backend/activity_summary/inputs.py
@@ -61,8 +61,11 @@ def user_activity(team_id: int, user_id: int, start: datetime.datetime, end: dat
.annotate(
name=KeyTextTransform("name", "detail"),
intent=KeyTextTransform("intent", KeyTransform("payload", KeyTransform("trigger", "detail"))),
+ short_id=KeyTextTransform("short_id", "detail"),
)
- .values("scope", "activity", "client", "created_at", "name", "intent", "item_id")[:MAX_ACTIVITY_ROWS_PER_PERSON]
+ .values(
+ "scope", "activity", "client", "created_at", "name", "intent", "item_id", "credential_type", "short_id"
+ )[:MAX_ACTIVITY_ROWS_PER_PERSON]
)
return [
ActivityItem(
@@ -73,6 +76,8 @@ def user_activity(team_id: int, user_id: int, start: datetime.datetime, end: dat
client=row["client"],
intent=row["intent"],
item_id=row["item_id"],
+ credential_type=row["credential_type"],
+ short_id=row["short_id"],
)
for row in rows
]
diff --git a/products/signals/backend/activity_summary/logic.py b/products/signals/backend/activity_summary/logic.py
index 7cd019195e57..84d63b3698d6 100644
--- a/products/signals/backend/activity_summary/logic.py
+++ b/products/signals/backend/activity_summary/logic.py
@@ -13,6 +13,7 @@ from django.utils import timezone
from posthog.dataclasses import frozen
from posthog.models import Team
+from products.signals.backend.activity_summary.computed import compute_fields
from products.signals.backend.activity_summary.inputs import activity_parents, user_activity, user_tasks, user_views
from products.signals.backend.activity_summary.prompt import PROMPT_VERSION, summary_text
from products.signals.backend.activity_summary.render import (
@@ -77,6 +78,7 @@ class ActivitySummaryUpdate:
latency_ms: int | None = None
error: str | None = None
inputs_used: dict[str, Any] | None = None
+ computed: dict[str, Any] | None = None
input_watermark: datetime.datetime | None = None
rebuilt: bool = False
# The pair had no generated summary before this update.
@@ -152,6 +154,7 @@ _VERSION_FIELDS = (
"render_version",
"input_watermark",
"inputs_used",
+ "computed",
"tokens_in",
"tokens_out",
"cost_usd",
@@ -264,6 +267,7 @@ def update_activity_summary(
return ActivitySummaryUpdate(status=UpdateStatus.SKIPPED_NOT_ELIGIBLE_YET)
rebuild = is_stale(stored, rebuild_before)
+ window_start = _input_start(None, now, limits.window_days)
start = _input_start(stored.input_watermark if stored and not rebuild else None, now, limits.window_days)
tasks = user_tasks(team_id, user_id, start, now)
activity = user_activity(team_id, user_id, start, now)
@@ -295,6 +299,15 @@ def update_activity_summary(
"limits": dataclasses.asdict(limits),
}
watermark = max([task.at for task in tasks] + [item.at for item in activity] + [view.at for view in views])
+ # An incremental update reads only the rows after the watermark, so the computed fields read the full window.
+ if start == window_start:
+ computed = compute_fields(tasks, activity, views).as_json()
+ else:
+ computed = compute_fields(
+ user_tasks(team_id, user_id, window_start, now),
+ user_activity(team_id, user_id, window_start, now),
+ user_views(team_id, user_id, window_start, now),
+ ).as_json()
previous = stored.summary if stored is not None and not rebuild else None
model = DEFAULT_MODEL
outcome = summarize(
@@ -317,6 +330,7 @@ def update_activity_summary(
latency_ms=outcome.latency_ms,
error=outcome.error,
inputs_used=inputs_used,
+ computed=computed if outcome.summary is not None else None,
input_watermark=watermark if outcome.summary is not None else None,
rebuilt=rebuild,
new_summary=stored is None or stored.generated_at is None,
@@ -353,6 +367,7 @@ def update_activity_summary(
"status": UserActivitySummary.Status.OK,
"summary": outcome.summary,
"summary_text": summary_text(outcome.summary),
+ "computed": computed,
"generated_at": now,
"model": model,
"prompt_version": PROMPT_VERSION,
diff --git a/products/signals/backend/activity_summary/render.py b/products/signals/backend/activity_summary/render.py
index 7c2c634d7e04..677f07a75bb3 100644
--- a/products/signals/backend/activity_summary/render.py
+++ b/products/signals/backend/activity_summary/render.py
@@ -24,7 +24,7 @@ from posthog.dataclasses import frozen
# 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 = 6
+RENDER_VERSION = 7
WINDOW_DAYS = 28
RECENCY_HALF_LIFE_DAYS = 7
@@ -97,43 +97,122 @@ _DIGIT = re.compile(r"\d")
_LETTER = re.compile(r"[A-Za-z]")
_WHITESPACE = re.compile(r"\s+")
+# Inbox onboarding creates a scout config for each canonical scout, named after its skill.
+ONBOARDING_CONFIG_SCOPES: frozenset[str] = frozenset({"SignalScoutConfig"})
+CANONICAL_SCOUT_PREFIX = "signals-scout-"
+# Personal API key changes are account housekeeping, not work in the project.
+API_KEY_SCOPES: frozenset[str] = frozenset({"PersonalAPIKey"})
+# CI writes deploy markers as annotations through a personal API key.
+ANNOTATION_SCOPE = "Annotation"
+PERSONAL_API_KEY_CREDENTIAL = "personal_api_key"
+TEAM_SCOPE = "Team"
+# Team settings rows without an intent are dropped when the person has at least this many: one change
+# can be deliberate, but repeated ones come from setup flows.
+MIN_TEAM_SETTINGS_ROWS = 2
+TICKET_SCOPE = "Ticket"
+# Changes to this many distinct tickets on one UTC day collapse to one line with a count.
+MIN_TICKET_BURST = 3
+# Changes of one kind to this many distinct objects of one type inside the window are a bulk job,
+# such as knowledge sources synced for many accounts.
+MIN_BULK_OBJECTS = 10
+BULK_WINDOW = datetime.timedelta(hours=1)
+# A task goal seen on this many distinct days is a scheduled job, not a question the person asked.
+MIN_REPEATED_TASK_DAYS = 4
+_DIGITS = re.compile(r"\d+")
+_CAMEL_WORD = re.compile(r"[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+")
+
+
+class Product(StrEnum):
+ """The fixed product keys of an activity summary. Scene views and activity scopes map to these only."""
+
+ PRODUCT_ANALYTICS = "product_analytics"
+ DASHBOARDS = "dashboards"
+ WEB_ANALYTICS = "web_analytics"
+ SESSION_REPLAY = "session_replay"
+ HEATMAPS = "heatmaps"
+ ERROR_TRACKING = "error_tracking"
+ EXPERIMENTS = "experiments"
+ FEATURE_FLAGS = "feature_flags"
+ EARLY_ACCESS_FEATURES = "early_access_features"
+ SURVEYS = "surveys"
+ PRODUCT_TOURS = "product_tours"
+ NOTEBOOKS = "notebooks"
+ COHORTS = "cohorts"
+ PERSONS = "persons"
+ DATA_MANAGEMENT = "data_management"
+ DATA_WAREHOUSE = "data_warehouse"
+ DATA_PIPELINES = "data_pipelines"
+ WORKFLOWS = "workflows"
+ AI_OBSERVABILITY = "ai_observability"
+ MCP_ANALYTICS = "mcp_analytics"
+ LOGS = "logs"
+ TRACING = "tracing"
+ ENDPOINTS = "endpoints"
+ REVENUE_ANALYTICS = "revenue_analytics"
+ CUSTOMER_ANALYTICS = "customer_analytics"
+ INBOX = "inbox"
+ CANVASES = "canvases"
+ SUPPORT = "support"
+
+
# A view log row of this type records a page, and its ref is the frontend scene id.
SCENE_VIEW_TYPE = "scene"
-# The product of each scene id prefix. A prefix matches its plural and any longer scene id of the
-# same product, such as "ErrorTrackingIssue". Other scenes, such as settings, the home page or a new
-# tab, say nothing about the work.
-_SCENE_PRODUCTS: tuple[tuple[str, str], ...] = (
- ("Insight|SavedInsight|ProductAnalytics", "Product analytics"),
- ("Dashboard", "Dashboards"),
- ("WebAnalytics", "Web analytics"),
- ("Replay|SessionRecording|SessionSummaries", "Session replay"),
- ("Heatmap", "Heatmaps"),
- ("ErrorTracking", "Error tracking"),
- ("Experiment", "Experiments"),
- ("FeatureFlag", "Feature flags"),
- ("EarlyAccessFeature", "Early access features"),
- ("Survey", "Surveys"),
- ("ProductTour", "Product tours"),
- ("Notebook", "Notebooks"),
- ("Cohort", "Cohorts"),
- ("Person|Group", "Persons and groups"),
- ("Action|EventDefinition|PropertyDefinition|DataManagement", "Data management"),
- ("SQLEditor|DataWarehouse|Sources|Models", "Data warehouse"),
- ("Pipeline|Destination|Transformation|HogFunction|BatchExport", "Data pipelines"),
- ("Workflow|Broadcast", "Workflows"),
- ("AIObservability", "AI observability"),
- ("MCPAnalytics", "MCP analytics"),
- ("Logs", "Logs"),
- ("Tracing", "Tracing"),
- ("Endpoint", "Endpoints"),
- ("RevenueAnalytics", "Revenue analytics"),
- ("CustomerAnalytics", "Customer analytics"),
- ("Inbox", "Inbox"),
- ("Canvas", "Canvases"),
+# The product of each scene id prefix, and its label in the prompt. A prefix matches its plural and any
+# longer scene id of the same product, such as "ErrorTrackingIssue". Other scenes, such as settings,
+# the home page or a new tab, say nothing about the work.
+_SCENE_PRODUCTS: tuple[tuple[str, Product, str], ...] = (
+ ("Insight|SavedInsight|ProductAnalytics", Product.PRODUCT_ANALYTICS, "Product analytics"),
+ ("Dashboard", Product.DASHBOARDS, "Dashboards"),
+ ("WebAnalytics", Product.WEB_ANALYTICS, "Web analytics"),
+ ("Replay|SessionRecording|SessionSummaries", Product.SESSION_REPLAY, "Session replay"),
+ ("Heatmap", Product.HEATMAPS, "Heatmaps"),
+ ("ErrorTracking", Product.ERROR_TRACKING, "Error tracking"),
+ ("Experiment", Product.EXPERIMENTS, "Experiments"),
+ ("FeatureFlag", Product.FEATURE_FLAGS, "Feature flags"),
+ ("EarlyAccessFeature", Product.EARLY_ACCESS_FEATURES, "Early access features"),
+ ("Survey", Product.SURVEYS, "Surveys"),
+ ("ProductTour", Product.PRODUCT_TOURS, "Product tours"),
+ ("Notebook", Product.NOTEBOOKS, "Notebooks"),
+ ("Cohort", Product.COHORTS, "Cohorts"),
+ ("Person|Group", Product.PERSONS, "Persons and groups"),
+ ("Action|EventDefinition|PropertyDefinition|DataManagement", Product.DATA_MANAGEMENT, "Data management"),
+ ("SQLEditor|DataWarehouse|Sources|Models", Product.DATA_WAREHOUSE, "Data warehouse"),
+ ("Pipeline|Destination|Transformation|HogFunction|BatchExport", Product.DATA_PIPELINES, "Data pipelines"),
+ ("Workflow|Broadcast", Product.WORKFLOWS, "Workflows"),
+ ("AIObservability", Product.AI_OBSERVABILITY, "AI observability"),
+ ("MCPAnalytics", Product.MCP_ANALYTICS, "MCP analytics"),
+ ("Logs", Product.LOGS, "Logs"),
+ ("Tracing", Product.TRACING, "Tracing"),
+ ("Endpoint", Product.ENDPOINTS, "Endpoints"),
+ ("RevenueAnalytics", Product.REVENUE_ANALYTICS, "Revenue analytics"),
+ ("CustomerAnalytics", Product.CUSTOMER_ANALYTICS, "Customer analytics"),
+ ("Inbox", Product.INBOX, "Inbox"),
+ ("Canvas", Product.CANVASES, "Canvases"),
+ ("SupportTicket", Product.SUPPORT, "Support"),
+)
+# Activity log scopes that no scene id prefix covers. A scope otherwise maps like a scene id.
+_SCOPE_PRODUCTS: tuple[tuple[str, Product], ...] = (
+ ("HogFlow", Product.WORKFLOWS),
+ ("ExternalData", Product.DATA_WAREHOUSE),
+ ("Plugin", Product.DATA_PIPELINES),
+ ("LLM|Evaluation", Product.AI_OBSERVABILITY),
+ ("Log", Product.LOGS),
+ ("Signal", Product.INBOX),
+ ("Ticket", Product.SUPPORT),
+)
+
+
+def _prefix_pattern(prefixes: str) -> re.Pattern[str]:
+ return re.compile(rf"^(?:{prefixes})s?(?:[A-Z]|$)")
+
+
+_SCENE_PATTERNS: tuple[tuple[re.Pattern[str], Product], ...] = tuple(
+ (_prefix_pattern(prefixes), product) for prefixes, product, _ in _SCENE_PRODUCTS
)
-_SCENE_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = tuple(
- (re.compile(rf"^(?:{prefixes})s?(?:[A-Z]|$)"), product) for prefixes, product in _SCENE_PRODUCTS
+_SCOPE_PATTERNS: tuple[tuple[re.Pattern[str], Product], ...] = _SCENE_PATTERNS + tuple(
+ (_prefix_pattern(prefixes), product) for prefixes, product in _SCOPE_PRODUCTS
)
+PRODUCT_LABELS: Mapping[Product, str] = {product: label for _, product, label in _SCENE_PRODUCTS}
def _limit(default: int, *, max_value: int) -> Any:
@@ -175,6 +254,13 @@ class Drop(StrEnum):
SCOUT_CLIENT = "scout_client"
AUTO_NAMED_OBJECT = "auto_named_object"
UNNAMED_OBJECT = "unnamed_object"
+ ONBOARDING_SCOUT_CONFIG = "onboarding_scout_config"
+ API_KEY_CHANGE = "api_key_change"
+ API_KEY_ANNOTATION = "api_key_annotation"
+ TEAM_SETTINGS = "team_settings"
+ BULK_SAME_TYPE = "bulk_same_type"
+ TICKET_BURST = "ticket_burst"
+ REPEATED_TASK = "repeated_task"
GENERIC_SCENE = "generic_scene"
DUPLICATE = "duplicate"
GROUPED_INTO_PARENT = "grouped_into_parent"
@@ -204,6 +290,10 @@ class ActivityItem:
client: str | None
intent: str | None = None
item_id: str | None = None
+ # The credential that authenticated the change, such as "personal_api_key". None outside a request.
+ credential_type: str | None = None
+ # The short id in the row's detail. The file system refers to some objects, such as insights, by it.
+ short_id: str | None = None
@frozen
@@ -341,8 +431,30 @@ def _templated_label(title: str) -> str | None:
return None
+def _goal_key(text: str) -> str:
+ """A task goal without its numbers and case, so the runs of one scheduled job compare equal."""
+ return _DIGITS.sub("#", text.lower())
+
+
+def _collapse_repeated(units: Sequence[Unit], drops: Counter[str]) -> list[Unit]:
+ """One line with a count for each goal seen on `MIN_REPEATED_TASK_DAYS` or more distinct days."""
+ by_goal: dict[str, list[Unit]] = {}
+ for unit in units:
+ by_goal.setdefault(_goal_key(unit.text.split(" ", 2)[-1]), []).append(unit)
+ collapsed: list[Unit] = []
+ for group in by_goal.values():
+ if len({_day(unit.at) for unit in group}) < MIN_REPEATED_TASK_DAYS:
+ collapsed.extend(group)
+ continue
+ latest = max(group, key=lambda unit: unit.at)
+ collapsed.append(Unit(at=latest.at, text=f"{latest.text} (x{len(group)})"))
+ drops[Drop.REPEATED_TASK] += len(group) - 1
+ return collapsed
+
+
def task_units(tasks: Iterable[TaskItem], drops: Counter[str], limits: RenderLimits = DEFAULT_LIMITS) -> list[Unit]:
- """One line per task, with templated titles collapsed to one line per template."""
+ """One line per task, with templated titles collapsed to one line per template and a goal repeated
+ on many days collapsed to one line with a count."""
units: list[Unit] = []
templated: dict[str, list[datetime.datetime]] = {}
for task in tasks:
@@ -364,6 +476,7 @@ def task_units(tasks: Iterable[TaskItem], drops: Counter[str], limits: RenderLim
drops[Drop.BARE_TITLE] += 1
continue
units.append(Unit(at=task.at, text=cap_line(line, limits.task_line_chars)))
+ units = _collapse_repeated(units, drops)
for label, times in templated.items():
latest = max(times)
units.append(
@@ -540,6 +653,153 @@ def _spread_across_days(
return kept + backfill
+def is_auto_named(name: str) -> bool:
+ return _AUTO_NAME.search(name) is not None
+
+
+def _has_intent(item: ActivityItem) -> bool:
+ return bool(item.intent and item.intent.strip())
+
+
+def _row_drop(item: ActivityItem) -> Drop | None:
+ """The rule that drops one activity row on its own, or None when nothing on the row says it is not the person's."""
+ name = (item.name or "").strip()
+ if item.scope in NOISY_ACTIVITY_SCOPES:
+ return Drop.NOISY_SCOPE
+ if (item.client or "").startswith(SCOUT_CLIENT_PREFIX):
+ return Drop.SCOUT_CLIENT
+ if item.scope in API_KEY_SCOPES:
+ return Drop.API_KEY_CHANGE
+ if item.scope == ANNOTATION_SCOPE and item.credential_type == PERSONAL_API_KEY_CREDENTIAL:
+ return Drop.API_KEY_ANNOTATION
+ if item.scope in ONBOARDING_CONFIG_SCOPES and name.startswith(CANONICAL_SCOUT_PREFIX) and not _has_intent(item):
+ return Drop.ONBOARDING_SCOUT_CONFIG
+ if not name:
+ return Drop.UNNAMED_OBJECT
+ if _AUTO_NAME.search(name):
+ return Drop.AUTO_NAMED_OBJECT
+ return None
+
+
+def _plural_label(scope: str, count: int) -> str:
+ """A scope in lower-case words, such as "knowledge sources" for "KnowledgeSource"."""
+ words = " ".join(word.lower() for word in _CAMEL_WORD.findall(scope))
+ return words if count == 1 else f"{words}s"
+
+
+def _object_id(item: ActivityItem) -> str:
+ return item.item_id or (item.name or "").strip()
+
+
+def _count_line(rows: Sequence[ActivityItem], text: str, limits: RenderLimits) -> _ActivityLine:
+ latest = max(row.at for row in rows)
+ line = f"- {_day(latest).isoformat()} {text}" + _intent_suffix(rows, limits.activity_intent_chars)
+ return _ActivityLine(at=latest, text=cap_line(line, limits.activity_line_chars), created=False, rows=len(rows))
+
+
+@frozen
+class _TicketBursts:
+ other_rows: list[ActivityItem]
+ lines: list[_ActivityLine]
+ burst_rows: list[ActivityItem]
+
+
+def _collapse_tickets(items: Sequence[ActivityItem], drops: Counter[str], limits: RenderLimits) -> _TicketBursts:
+ """One counted line for each UTC day and kind of change that touches `MIN_TICKET_BURST` or more tickets."""
+ groups: dict[tuple[datetime.date, str], list[ActivityItem]] = {}
+ for item in items:
+ if item.scope == TICKET_SCOPE and item.activity != "created":
+ groups.setdefault((_day(item.at), item.activity), []).append(item)
+ burst: set[int] = set()
+ lines: list[_ActivityLine] = []
+ for (_, activity), rows in groups.items():
+ tickets = len({_object_id(row) for row in rows})
+ if tickets < MIN_TICKET_BURST:
+ continue
+ burst.update(id(row) for row in rows)
+ lines.append(_count_line(rows, f"{activity} {tickets} support tickets", limits))
+ drops[Drop.TICKET_BURST] += len(rows) - 1
+ return _TicketBursts(
+ other_rows=[item for item in items if id(item) not in burst],
+ lines=lines,
+ burst_rows=[item for item in items if id(item) in burst],
+ )
+
+
+def _bulk_runs(rows: Sequence[ActivityItem]) -> list[list[ActivityItem]]:
+ """The runs of rows inside one `BULK_WINDOW` that touch `MIN_BULK_OBJECTS` or more distinct objects."""
+ ordered = sorted(rows, key=lambda row: row.at)
+ runs: list[list[ActivityItem]] = []
+ start = 0
+ while start < len(ordered):
+ end = start
+ while end < len(ordered) and ordered[end].at - ordered[start].at <= BULK_WINDOW:
+ end += 1
+ if len({_object_id(row) for row in ordered[start:end]}) >= MIN_BULK_OBJECTS:
+ runs.append(ordered[start:end])
+ start = end
+ else:
+ start += 1
+ return runs
+
+
+def _collapse_bulk(
+ items: Sequence[ActivityItem], drops: Counter[str], limits: RenderLimits
+) -> tuple[list[ActivityItem], list[_ActivityLine]]:
+ """A bulk job's rows as one counted line when an agent stated why, and dropped when nothing did.
+
+ Creates are left alone: the parent grouping already merges a dashboard built in one go."""
+ groups: dict[tuple[str, str], list[ActivityItem]] = {}
+ for item in items:
+ if item.activity != "created":
+ groups.setdefault((item.scope, item.activity), []).append(item)
+ bulk: set[int] = set()
+ lines: list[_ActivityLine] = []
+ for (scope, activity), rows in groups.items():
+ for run in _bulk_runs(rows):
+ bulk.update(id(row) for row in run)
+ if any(_has_intent(row) for row in run):
+ objects = len({_object_id(row) for row in run})
+ lines.append(_count_line(run, f"{activity} {objects} {_plural_label(scope, objects)}", limits))
+ drops[Drop.BULK_SAME_TYPE] += len(run) - 1
+ else:
+ drops[Drop.BULK_SAME_TYPE] += len(run)
+ return [item for item in items if id(item) not in bulk], lines
+
+
+def _drop_team_settings(items: Sequence[ActivityItem], drops: Counter[str]) -> list[ActivityItem]:
+ """Without the team settings rows that state no intent, when there are `MIN_TEAM_SETTINGS_ROWS` or more."""
+ unstated = [item for item in items if item.scope == TEAM_SCOPE and not _has_intent(item)]
+ if len(unstated) < MIN_TEAM_SETTINGS_ROWS:
+ return list(items)
+ drops[Drop.TEAM_SETTINGS] += len(unstated)
+ dropped = {id(item) for item in unstated}
+ return [item for item in items if id(item) not in dropped]
+
+
+def person_activity(
+ items: Iterable[ActivityItem],
+ drops: Counter[str],
+ limits: RenderLimits = DEFAULT_LIMITS,
+ keep_ticket_bursts: bool = False,
+) -> tuple[list[ActivityItem], list[_ActivityLine]]:
+ """The rows that are the person's own work, and one counted line for each ticket burst or bulk job.
+
+ The row rules run first, then the ticket bursts, so a ticket burst is not taken for a bulk job.
+ With `keep_ticket_bursts`, the rows of each ticket burst stay in the result as well: a burst is
+ one line in the prompt, but each ticket is still the person's work."""
+ kept: list[ActivityItem] = []
+ for item in items:
+ if (reason := _row_drop(item)) is not None:
+ drops[reason] += 1
+ else:
+ kept.append(item)
+ tickets = _collapse_tickets(kept, drops, limits)
+ kept, bulk_lines = _collapse_bulk(tickets.other_rows, drops, limits)
+ kept = _drop_team_settings(kept, drops)
+ return (kept + tickets.burst_rows if keep_ticket_bursts else kept), tickets.lines + bulk_lines
+
+
def activity_units(
items: Iterable[ActivityItem],
drops: Counter[str],
@@ -551,33 +811,33 @@ def activity_units(
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."""
+ kept, count_lines = person_activity(items, drops, limits)
collapsed: dict[ObjectKey, list[ActivityItem]] = {}
- for item in items:
- name = (item.name or "").strip()
- if item.scope in NOISY_ACTIVITY_SCOPES:
- drops[Drop.NOISY_SCOPE] += 1
- elif (item.client or "").startswith(SCOUT_CLIENT_PREFIX):
- drops[Drop.SCOUT_CLIENT] += 1
- elif not name:
- drops[Drop.UNNAMED_OBJECT] += 1
- elif _AUTO_NAME.search(name):
- drops[Drop.AUTO_NAMED_OBJECT] += 1
- else:
- collapsed.setdefault((item.scope, item.activity, name), []).append(item)
- lines = _lines_with_parents(collapsed, parents or {}, drops, limits)
+ for item in kept:
+ collapsed.setdefault((item.scope, item.activity, (item.name or "").strip()), []).append(item)
+ lines = _lines_with_parents(collapsed, parents or {}, drops, limits) + count_lines
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))
+ kept_lines = _spread_across_days(ranked, drops, limits)
+ return sorted((Unit(at=line.at, text=line.text) for line in kept_lines), key=lambda unit: (unit.at, unit.text))
-def scene_product(scene_id: str) -> str | None:
- for pattern, product in _SCENE_PATTERNS:
- if pattern.match(scene_id):
+def _match_product(patterns: Sequence[tuple[re.Pattern[str], Product]], name: str) -> Product | None:
+ for pattern, product in patterns:
+ if pattern.match(name):
return product
return None
-def _scope_of(view_type: str) -> str:
+def scene_product(scene_id: str) -> Product | None:
+ return _match_product(_SCENE_PATTERNS, scene_id)
+
+
+def scope_product(scope: str) -> Product | None:
+ """The product of an activity log scope, such as "FeatureFlag", or of a file system type."""
+ return _match_product(_SCOPE_PATTERNS, scope)
+
+
+def scope_of(view_type: str) -> str:
"""The activity log scope of a file system type, such as "FeatureFlag" for "feature_flag"."""
return "".join(word.capitalize() for word in view_type.split("/")[0].split("_"))
@@ -597,11 +857,10 @@ def view_units(
An object line also counts the days the person edited it, matched to their activity rows by
scope and name. These lines skip the per-day burst cap."""
edit_days: dict[tuple[str, str], set[datetime.date]] = {}
- for item in activity:
- if item.name and not (item.client or "").startswith(SCOUT_CLIENT_PREFIX):
- edit_days.setdefault((item.scope, item.name.strip()), set()).add(_day(item.at))
+ for item in person_activity(activity, Counter(), limits)[0]:
+ edit_days.setdefault((item.scope, (item.name or "").strip()), set()).add(_day(item.at))
ranked: list[tuple[int, datetime.datetime, str]] = []
- scenes: dict[str, tuple[datetime.datetime, set[datetime.date]]] = {}
+ scenes: dict[Product, tuple[datetime.datetime, set[datetime.date]]] = {}
for view in views:
if view.type == SCENE_VIEW_TYPE:
product = scene_product(view.ref)
@@ -621,14 +880,20 @@ def view_units(
opened = len(set(view.days))
name_text = cap_line(clean_text(name, ACTIVITY_NAME_CHARS * 2), ACTIVITY_NAME_CHARS)
facts = [f"opened {_days(opened)}", f"last {_day(view.at).isoformat()}"]
- if edited := len(edit_days.get((_scope_of(view.type), name), ())):
+ if edited := len(edit_days.get((scope_of(view.type), name), ())):
facts.append(f"edited {_days(edited)}")
if view.not_theirs:
facts.append("not theirs")
label = view.type.split("/")[0].replace("_", " ").capitalize()
ranked.append((opened, view.at, f'- {label} "{name_text}": {", ".join(facts)}'))
for product, (at, days) in scenes.items():
- ranked.append((len(days), at, f"- {product} pages: opened {_days(len(days))}, last {_day(at).isoformat()}"))
+ ranked.append(
+ (
+ len(days),
+ at,
+ f"- {PRODUCT_LABELS[product]} pages: opened {_days(len(days))}, last {_day(at).isoformat()}",
+ )
+ )
ranked.sort(key=lambda entry: (-entry[0], -entry[1].timestamp(), entry[2]))
if len(ranked) > limits.view_lines:
drops[Drop.SAMPLE_CAP] += len(ranked) - limits.view_lines
diff --git a/products/signals/backend/migrations/0198_useractivitysummary_computed.py b/products/signals/backend/migrations/0198_useractivitysummary_computed.py
new file mode 100644
index 000000000000..d9786a87de5a
--- /dev/null
+++ b/products/signals/backend/migrations/0198_useractivitysummary_computed.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.18 on 2026-10-24 10:45
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0197_signalscratchpad_trgm_fastupdate_off"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="useractivitysummary",
+ name="computed",
+ field=models.JSONField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="useractivitysummaryversion",
+ name="computed",
+ field=models.JSONField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index f1cfa062fe32..ad1b5ceff741 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0197_signalscratchpad_trgm_fastupdate_off
+0198_useractivitysummary_computed
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index e0f8e9a49ade..6cf3a6f76b6f 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -3895,6 +3895,10 @@ class UserActivitySummary(TeamScopedRootMixin, UUIDModel):
latency_ms = models.IntegerField(null=True, blank=True)
# Line counts per section and drop counts per filter rule of the latest update.
inputs_used = models.JSONField(default=dict, blank=True)
+ # Exact fields from `activity_summary/computed.py` over the full window of the latest good update:
+ # owned and watched objects with ids, product pages, products and the task count. Carries its own
+ # `schema_version`. Null before the first update that computed it.
+ computed = models.JSONField(null=True, blank=True)
status = models.CharField(max_length=20, choices=Status)
# One of the fixed error strings of `summaries.py`, never model output.
@@ -3944,6 +3948,8 @@ class UserActivitySummaryVersion(TeamScopedRootMixin, UUIDModel):
render_version = models.PositiveSmallIntegerField()
input_watermark = models.DateTimeField()
inputs_used = models.JSONField(default=dict, blank=True)
+ # See `UserActivitySummary.computed`. Null on versions written before the field existed.
+ computed = models.JSONField(null=True, blank=True)
tokens_in = models.IntegerField(null=True, blank=True)
tokens_out = models.IntegerField(null=True, blank=True)
cost_usd = models.FloatField(null=True, blank=True)
diff --git a/products/signals/backend/test/test_activity_summary_render.py b/products/signals/backend/test/test_activity_summary_render.py
index 5b7a020ffd58..467fed8fdcfc 100644
--- a/products/signals/backend/test/test_activity_summary_render.py
+++ b/products/signals/backend/test/test_activity_summary_render.py
@@ -9,6 +9,7 @@ import pytest
from openai import APIConnectionError
from parameterized import parameterized
+from products.signals.backend.activity_summary.computed import compute_fields
from products.signals.backend.activity_summary.prompt import (
MAX_PRODUCT_CHARS,
MAX_RECENT_SHIFT_CHARS,
@@ -67,9 +68,19 @@ def _change(
days_ago: float = 1,
intent: str | None = None,
item_id: str | None = None,
+ credential_type: str | None = None,
+ short_id: str | None = None,
) -> ActivityItem:
return ActivityItem(
- at=_at(days_ago), scope=scope, activity=activity, name=name, client=client, intent=intent, item_id=item_id
+ at=_at(days_ago),
+ scope=scope,
+ activity=activity,
+ name=name,
+ client=client,
+ intent=intent,
+ item_id=item_id,
+ credential_type=credential_type,
+ short_id=short_id,
)
@@ -120,6 +131,29 @@ def test_task_units(_name: str, task: TaskItem, expected: str | None, expected_d
assert dict(drops) == expected_drops
+ [
+ ("a goal on a few days is kept on each day", 3, 3, {}),
+ ("a goal on most days is a scheduled job", 4, 1, {Drop.REPEATED_TASK: 3}),
+ ]
+)
+def test_a_goal_repeated_on_many_days_collapses_to_one_line(
+ _name: str, days: int, expected_lines: int, expected_drops: dict[str, int]
+) -> None:
+ drops: Counter[str] = Counter()
+ tasks = [
+ _task("digest", summary=f"Goal: post the digest of {10 + day} new signups.", days_ago=1 + day)
+ for day in range(days)
+ ]
+
+ units = task_units(tasks, drops)
+
+ assert len(units) == expected_lines
+ if expected_drops:
+ assert units[0].text == f"- 2026-10-18 post the digest of 10 new signups. (x{days})"
+ assert dict(drops) == expected_drops
+
+
def test_templated_task_titles_collapse_to_one_line_with_a_count() -> None:
tasks = [_task(f"Fix failing CI checks in PR #{number}", days_ago=number) for number in (1, 2, 3)]
units = task_units(tasks, Counter())
@@ -152,6 +186,113 @@ def test_activity_units_filter_collapse_and_rank_creates_first() -> None:
}
+def _bulk(count: int, spacing_days: float, intent: str | None = None) -> list[ActivityItem]:
+ return [
+ _change(
+ "KnowledgeSource",
+ "updated",
+ f"Account {n} docs",
+ days_ago=1 - n * spacing_days,
+ item_id=str(n),
+ intent=intent if n == count - 1 else None,
+ )
+ for n in range(count)
+ ]
+
+
+ [
+ (
+ "a scout config that onboarding created is dropped",
+ [_change("SignalScoutConfig", "created", "signals-scout-error-tracking")],
+ [],
+ {Drop.ONBOARDING_SCOUT_CONFIG: 1},
+ ),
+ (
+ "a scout config the person named is kept",
+ [_change("SignalScoutConfig", "created", "checkout-watch")],
+ ['- 2026-10-18 created SignalScoutConfig "checkout-watch"'],
+ {},
+ ),
+ (
+ "a personal API key change is dropped",
+ [_change("PersonalAPIKey", "created", "CI deploy key")],
+ [],
+ {Drop.API_KEY_CHANGE: 1},
+ ),
+ (
+ "an integration with a key-like name is kept",
+ [_change("Integration", "created", "CI deploy key")],
+ ['- 2026-10-18 created Integration "CI deploy key"'],
+ {},
+ ),
+ (
+ "an annotation written through a personal API key is dropped",
+ [_change("Annotation", "created", "Deploy v1.4.2", credential_type="personal_api_key")],
+ [],
+ {Drop.API_KEY_ANNOTATION: 1},
+ ),
+ (
+ "an annotation written in the app is kept",
+ [_change("Annotation", "created", "Deploy v1.4.2", credential_type="session")],
+ ['- 2026-10-18 created Annotation "Deploy v1.4.2"'],
+ {},
+ ),
+ (
+ "repeated team settings updates without an intent are dropped",
+ [
+ _change("Team", "updated", "Default project", days_ago=1),
+ _change("Team", "updated", "Default project", days_ago=2),
+ ],
+ [],
+ {Drop.TEAM_SETTINGS: 2},
+ ),
+ (
+ "one team settings update is kept",
+ [_change("Team", "updated", "Default project")],
+ ['- 2026-10-18 updated Team "Default project"'],
+ {},
+ ),
+ (
+ "a bulk update with no intent is dropped",
+ _bulk(12, 0.001),
+ [],
+ {Drop.BULK_SAME_TYPE: 12},
+ ),
+ (
+ "a bulk update with an intent collapses to one line",
+ _bulk(12, 0.001, intent="Sync the account docs"),
+ ["- 2026-10-18 updated 12 knowledge sources (agent: Sync the account docs)"],
+ {Drop.BULK_SAME_TYPE: 11},
+ ),
+ (
+ "updates spread over the day are kept one per object",
+ _bulk(10, 0.05),
+ [f'- 2026-10-1{8 if n < 10 else 9} updated KnowledgeSource "Account {n} docs"' for n in range(10)],
+ {},
+ ),
+ (
+ "a ticket burst collapses to one line with a count",
+ [_change("Ticket", "updated", f"Ticket #{n}", days_ago=1 - n / 100, item_id=str(n)) for n in range(3)],
+ ["- 2026-10-18 updated 3 support tickets"],
+ {Drop.TICKET_BURST: 2},
+ ),
+ (
+ "two ticket updates are kept one per ticket",
+ [_change("Ticket", "updated", f"Ticket #{n}", days_ago=1 - n / 100, item_id=str(n)) for n in range(2)],
+ ['- 2026-10-18 updated Ticket "Ticket #0"', '- 2026-10-18 updated Ticket "Ticket #1"'],
+ {},
+ ),
+ ]
+)
+def test_activity_units_drop_automated_activity(
+ _name: str, items: list[ActivityItem], expected: list[str], expected_drops: dict[str, int]
+) -> None:
+ drops: Counter[str] = Counter()
+ assert [unit.text for unit in activity_units(items, drops)] == expected
+ assert dict(drops) == expected_drops
+
+
@parameterized.expand(
[
("no intent renders as before", [None], '- 2026-10-18 updated Insight "Signup funnel"'),
@@ -404,6 +545,89 @@ def test_view_units_name_products_count_edits_and_drop_what_says_nothing() -> No
assert dict(drops) == {Drop.GENERIC_SCENE: 2, Drop.AUTO_NAMED_OBJECT: 1, Drop.UNNAMED_OBJECT: 1}
+def test_compute_fields_split_owned_watched_and_visited() -> None:
+ activity = (
+ [_change("FeatureFlag", "updated", "new-checkout", days_ago=day, item_id="7") for day in (1, 2, 3)]
+ + [
+ _change("Dashboard", "created", "Growth overview", days_ago=2, item_id="9"),
+ _change("Insight", "updated", "Signup funnel", client="scout:product-analytics", item_id="1"),
+ _change("PersonalAPIKey", "created", "CI deploy key", item_id="k1"),
+ _change("Insight", "updated", "Weekly signups", item_id="42", short_id="abc"),
+ ]
+ + [_change("Ticket", "updated", f"Ticket #{n}", item_id=f"t{n}") for n in (1, 2, 3)]
+ )
+ views = [
+ _view("insight", "abc", "Weekly signups", days=4, not_theirs=True),
+ _view("insight", "def", "Churn by plan", days=2),
+ _view("scene", "Replay", days=1),
+ ]
+ tasks = [_task("why", summary="Goal: find why signups dropped.", tags=("Product analytics",))]
+
+ computed = compute_fields(tasks, activity, views).as_json()
+
+ assert computed == {
+ "schema_version": 1,
+ "owned": [
+ {
+ "ref": "o1",
+ "type": "feature_flag",
+ "id": "7",
+ "name": "new-checkout",
+ "edit_days": 3,
+ "last_at": "2026-10-18",
+ "created": False,
+ },
+ {
+ "ref": "o2",
+ "type": "insight",
+ "id": "abc",
+ "name": "Weekly signups",
+ "edit_days": 1,
+ "last_at": "2026-10-18",
+ "created": False,
+ },
+ *(
+ {
+ "ref": f"o{n + 2}",
+ "type": "ticket",
+ "id": f"t{n}",
+ "name": f"Ticket #{n}",
+ "edit_days": 1,
+ "last_at": "2026-10-18",
+ "created": False,
+ }
+ for n in (1, 2, 3)
+ ),
+ {
+ "ref": "o6",
+ "type": "dashboard",
+ "id": "9",
+ "name": "Growth overview",
+ "edit_days": 1,
+ "last_at": "2026-10-17",
+ "created": True,
+ },
+ ],
+ "watched": [
+ {
+ "ref": "o2",
+ "type": "insight",
+ "id": "abc",
+ "name": "Weekly signups",
+ "open_days": 4,
+ "last_at": "2026-10-18",
+ "not_theirs": True,
+ }
+ ],
+ "pages": [{"ref": "p1", "product": "session_replay", "open_days": 1, "last_at": "2026-10-18"}],
+ "products": {
+ "works_in": ["feature_flags", "product_analytics", "dashboards", "support"],
+ "visits": ["session_replay"],
+ },
+ "task_count": 1,
+ }
+
+
@parameterized.expand(
[
("default limits", DEFAULT_LIMITS),
@@ -423,7 +647,7 @@ def test_view_units_name_products_count_edits_and_drop_what_says_nothing() -> No
def test_build_input_stays_inside_its_bounds_for_a_very_active_person(_name: str, limits: RenderLimits) -> None:
runaway = "word " * 2000
tasks = [
- _task(runaway, summary=f"{day} {n} {runaway}", tags=(runaway,) * 20, days_ago=day + 0.01 * n)
+ _task(runaway, summary=f"{'x' * day}{'y' * n} {runaway}", tags=(runaway,) * 20, days_ago=day + 0.01 * n)
for day in range(28)
for n in range(20)
]
diff --git a/products/signals/backend/test/test_activity_summary_update.py b/products/signals/backend/test/test_activity_summary_update.py
index 67ff9e3618fd..42e11126ae9a 100644
--- a/products/signals/backend/test/test_activity_summary_update.py
+++ b/products/signals/backend/test/test_activity_summary_update.py
@@ -102,6 +102,16 @@ class TestUpdateActivitySummary(BaseTest):
assert self._versions() == [1, 2]
first = UserActivitySummaryVersion.objects.for_team(self.team.id).get(summary_row=latest, version=1)
assert (first.summary_text, first.input_watermark) == (stored.summary_text, stored.input_watermark)
+ # The second update read only the rows after the watermark, but its computed fields cover the full window.
+ assert latest.computed is not None
+ assert {entry["id"] for entry in latest.computed["owned"]} == {
+ "Funnel 0",
+ "Funnel 1",
+ "Funnel 2",
+ "Signup funnel",
+ }
+ second = UserActivitySummaryVersion.objects.for_team(self.team.id).get(summary_row=latest, version=2)
+ assert second.computed == latest.computed
def test_a_person_who_only_reads_gets_a_summary_from_what_they_opened(self) -> None:
other = User.objects.create_and_join(self.organization, "[email protected]", None)