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.

perf(signals): speed up scout scratchpad search (#116753)

posthog[bot]a682b1d20582
diff --git a/products/signals/backend/migrations/0184_signalscratchpad_search_trgm_indexes.py b/products/signals/backend/migrations/0184_signalscratchpad_search_trgm_indexes.py
new file mode 100644
index 000000000000..30704b28f46e
--- /dev/null
+++ b/products/signals/backend/migrations/0184_signalscratchpad_search_trgm_indexes.py
@@ -0,0 +1,24 @@
+from django.contrib.postgres.indexes import GinIndex, OpClass
+from django.db import migrations
+from django.db.models.functions import Upper
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # Concurrent index builds can't run in a transaction.
+ atomic = False
+
+ dependencies = [("signals", "0183_spend_accounting_failures")]
+
+ # The posthog app migrations already install pg_trgm.
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="signalscratchpad",
+ index=GinIndex(OpClass(Upper("content"), name="gin_trgm_ops"), name="signal_scratchpad_content_trgm"),
+ ),
+ SafeAddIndexConcurrently(
+ model_name="signalscratchpad",
+ index=GinIndex(OpClass(Upper("key"), name="gin_trgm_ops"), name="signal_scratchpad_key_trgm"),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 0c0d24b36c9d..a615c56cf0ed 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0183_spend_accounting_failures
+0184_signalscratchpad_search_trgm_indexes
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index f4ce7aeb470b..4504dea13a73 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -3381,6 +3381,10 @@ class SignalScratchpad(TeamScopedRootMixin, UUIDModel):
name="signal_scratchpad_key_like_idx",
opclasses=["int4_ops", "varchar_pattern_ops"],
),
+ # Back the `text` search. On UPPER(...) because icontains compiles to
+ # UPPER(col::text) LIKE UPPER(pattern) on Postgres.
+ GinIndex(OpClass(Upper("content"), name="gin_trgm_ops"), name="signal_scratchpad_content_trgm"),
+ GinIndex(OpClass(Upper("key"), name="gin_trgm_ops"), name="signal_scratchpad_key_trgm"),
]
diff --git a/products/signals/backend/scout_harness/tools/scratchpad.py b/products/signals/backend/scout_harness/tools/scratchpad.py
index eeb8db580632..5e2793669abb 100644
--- a/products/signals/backend/scout_harness/tools/scratchpad.py
+++ b/products/signals/backend/scout_harness/tools/scratchpad.py
@@ -48,6 +48,20 @@ MAX_SCRATCHPAD_KEY_LENGTH = 300
# runaway write can't bloat the scratchpad or a later prompt. Generous for prose.
MAX_SCRATCHPAD_CONTENT_LENGTH = 50_000
+# The columns `_to_entry` reads, joined run and task run included. Both joined rows also carry
+# unbounded text and JSON columns, and a search must not fetch them.
+_ENTRY_FIELDS = (
+ "team_id",
+ "key",
+ "content",
+ "created_at",
+ "updated_at",
+ "expires_at",
+ "created_by_identity",
+ "created_by_run__skill_name",
+ "created_by_run__task_run__task_id",
+)
+
class InvalidScratchpadError(ValueError):
"""The agent tried to write a memory with invalid shape (empty key, oversized, etc)."""
@@ -121,7 +135,11 @@ def search_scratchpad(
clamped_limit = _clamp_search_limit(limit)
# Join the creating run (and its task_run) so per-row skill/url resolution in `_to_entry`
# stays a single query rather than an N+1 across the result window.
- qs = SignalScratchpad.objects.filter(team_id=team_id).select_related("created_by_run", "created_by_run__task_run")
+ qs = (
+ SignalScratchpad.objects.filter(team_id=team_id)
+ .select_related("created_by_run", "created_by_run__task_run")
+ .only(*_ENTRY_FIELDS)
+ )
qs = _project_content_in_sql(qs, keys_only=keys_only, content_max_chars=content_max_chars)
if key:
qs = qs.filter(key=key)
@@ -157,8 +175,10 @@ def search_scratchpad_naming(
return []
boundary = "[^A-Za-z0-9_-]"
pattern = f"(^|{boundary})({'|'.join(re.escape(term) for term in wanted)})({boundary}|$)"
- qs = SignalScratchpad.objects.filter(team_id=team_id, key__startswith=key_prefix).select_related(
- "created_by_run", "created_by_run__task_run"
+ qs = (
+ SignalScratchpad.objects.filter(team_id=team_id, key__startswith=key_prefix)
+ .select_related("created_by_run", "created_by_run__task_run")
+ .only(*_ENTRY_FIELDS)
)
qs = _project_content_in_sql(qs, keys_only=True, content_max_chars=None)
qs = qs.filter(Q(content__iregex=pattern) | Q(key__iregex=pattern))
diff --git a/products/signals/backend/test/test_scout_harness_tools.py b/products/signals/backend/test/test_scout_harness_tools.py
index 95c81b1e76d5..0d69c319397d 100644
--- a/products/signals/backend/test/test_scout_harness_tools.py
+++ b/products/signals/backend/test/test_scout_harness_tools.py
@@ -95,6 +95,7 @@ from products.signals.backend.scout_harness.tools.runs import (
from products.signals.backend.scout_harness.tools.scratchpad import (
MAX_SCRATCHPAD_CONTENT_LENGTH,
MAX_SCRATCHPAD_SEARCH_LIMIT,
+ search_scratchpad_naming,
)
from products.signals.backend.scout_report.judge import (
_chart_signal,
@@ -708,6 +709,31 @@ class TestForget(BaseTest):
class TestSearchScratchpad(BaseTest):
+ @parameterized.expand(
+ [
+ ("search", lambda team_id: search_scratchpad(team_id=team_id, text="shared")),
+ (
+ "naming",
+ lambda team_id: search_scratchpad_naming(team_id=team_id, key_prefix="person:", terms=["shared"]),
+ ),
+ ]
+ )
+ def test_resolves_attribution_in_one_query_without_heavy_joined_columns(self, _name: str, search) -> None:
+ for i in range(2):
+ remember(
+ team_id=self.team.id, key=f"person:{i}", content="shared login", run_id=str(_create_run(self.team).id)
+ )
+
+ with CaptureQueriesContext(connection) as queries:
+ entries = search(self.team.id)
+
+ assert len(entries) == 2
+ assert all(e.created_by_skill == "signals-scout-errors" and e.created_by_run_url for e in entries)
+ assert len(queries.captured_queries) == 1
+ sql = queries.captured_queries[0]["sql"]
+ for column in ("summary", "metadata", "state", "output", "artifacts", "imported_mcp_servers"):
+ assert f'."{column}"' not in sql
+
def test_returns_all_team_entries(self) -> None:
SignalScratchpad.objects.create(team=self.team, key="a", content="alpha")
SignalScratchpad.objects.create(team=self.team, key="b", content="beta")