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 updated_at to SignalScoutRun (#102999)

posthog[bot]02717c851d95
diff --git a/products/signals/backend/migrations/0144_signalscoutrun_updated_at.py b/products/signals/backend/migrations/0144_signalscoutrun_updated_at.py
new file mode 100644
index 000000000000..5568aca41d06
--- /dev/null
+++ b/products/signals/backend/migrations/0144_signalscoutrun_updated_at.py
@@ -0,0 +1,31 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0143_scout_emission_confidence_nullable"),
+ ]
+
+ operations = [
+ # Hand-written `ADD COLUMN` rather than the `AddField` SQL: `auto_now` gives the field an
+ # effective default, so Django would stamp every existing row with the migration's own
+ # timestamp. A run that settled last month did not change at deploy time, so the rows the
+ # column never observed stay NULL and a reader that wants one timestamp per row takes
+ # `coalesce(updated_at, created_at)`. No default and no backfill keeps the ALTER
+ # metadata-only. `IF NOT EXISTS` so a `bin/migrate` retry is a no-op.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddField(
+ model_name="signalscoutrun",
+ name="updated_at",
+ field=models.DateTimeField(auto_now=True, null=True),
+ ),
+ ],
+ database_operations=[
+ migrations.RunSQL(
+ sql='ALTER TABLE "signals_signalscoutrun" ADD COLUMN IF NOT EXISTS "updated_at" timestamptz NULL;',
+ reverse_sql='ALTER TABLE "signals_signalscoutrun" DROP COLUMN IF EXISTS "updated_at";',
+ ),
+ ],
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 847e18f9c327..d76a43c65386 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0143_scout_emission_confidence_nullable
+0144_signalscoutrun_updated_at
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 84028be6be05..55a2ec3a6d30 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -2622,6 +2622,12 @@ class SignalScoutRun(TeamScopedRootMixin, UUIDModel):
# Nullable with a `{}` db_default so the AddField stays non-blocking on the populated table.
metadata = models.JSONField(null=True, blank=True, default=dict, db_default={})
created_at = models.DateTimeField(auto_now_add=True)
+ # Last touch on the row. The `summary`, the emit and edit tallies, and `metadata` all land after
+ # the row is created, so a reader keyed on `created_at` alone never sees a settled run. Nullable
+ # with no backfill so the AddField stays non-blocking on the populated table: the rows the column
+ # never observed read NULL, and a reader that wants one timestamp per row takes
+ # `coalesce(updated_at, created_at)`.
+ updated_at = models.DateTimeField(auto_now=True, null=True)
class Meta:
verbose_name = "Signal scout run"
@@ -2647,6 +2653,13 @@ class SignalScoutRun(TeamScopedRootMixin, UUIDModel):
GinIndex(fields=["edited_report_ids"], name="signal_scout_run_edited_idx"),
]
+ def save(self, *args: Any, update_fields: Any = None, **kwargs: Any) -> None:
+ # `auto_now` only fires for the fields a narrowed write names, and every post-create writer
+ # on this row narrows. Widening here rather than at each call site keeps a new writer honest.
+ if update_fields is not None:
+ update_fields = [*update_fields, "updated_at"]
+ super().save(*args, update_fields=update_fields, **kwargs)
+
class SignalScoutEmission(TeamScopedRootMixin, UUIDModel):
"""One persisted row per finding a scout run emitted to the inbox.
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 37d1d7db6348..4356f764d528 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -1583,8 +1583,11 @@ def _capture_run_finished(
def _finalize_run_row(*, run_id: Any, team_id: int, summary: str) -> None:
# Targeted UPDATE rather than `.save()` — the row's other fields are untouched
- # by the agent's close-out, and `update()` skips the full model refresh.
- SignalScoutRun.objects.unscoped().filter(team_id=team_id, id=run_id).update(summary=summary)
+ # by the agent's close-out, and `update()` skips the full model refresh. `updated_at` is stamped
+ # by hand because `auto_now` runs in `save()`, which this path deliberately skips.
+ SignalScoutRun.objects.unscoped().filter(team_id=team_id, id=run_id).update(
+ summary=summary, updated_at=timezone.now()
+ )
# Stamped here rather than at each emit/edit site so the flags are computed once, from the
# run's settled output, in the same hop that persists the close-out. Best-effort inside, so
# a stamp failure never costs the summary write that already landed above.
diff --git a/products/signals/backend/test/test_signal_scout_models.py b/products/signals/backend/test/test_signal_scout_models.py
index a23837fb8501..2620b4d959da 100644
--- a/products/signals/backend/test/test_signal_scout_models.py
+++ b/products/signals/backend/test/test_signal_scout_models.py
@@ -1,5 +1,6 @@
import uuid
from contextlib import AbstractContextManager
+from datetime import datetime, timedelta
from typing import TYPE_CHECKING
import pytest
@@ -15,6 +16,7 @@ from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.scoping import team_scope
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun, SignalScratchpad
+from products.signals.backend.scout_harness.runner import _finalize_run_row
from products.signals.backend.scout_harness.tools.emit import _record_emit
if TYPE_CHECKING:
@@ -252,6 +254,51 @@ class TestSignalScoutModels(_ScoutTeamScopedTestMixin, BaseTest):
assert loaded.scout_config_id is None
assert loaded.team_id == self.team.id
+ def _run_with_stale_updated_at(self) -> tuple[SignalScoutRun, datetime]:
+ # `updated_at` an hour in the past, so a write that advances it is visible whatever
+ # the clock resolution.
+ run = SignalScoutRun.objects.create(
+ task_run=self._make_task_run(),
+ team=self.team,
+ skill_name="signals-scout-errors",
+ skill_version=1,
+ )
+ stale = timezone.now() - timedelta(hours=1)
+ SignalScoutRun.all_teams.filter(pk=run.pk).update(updated_at=stale)
+ return run, stale
+
+ def test_narrowed_write_advances_updated_at(self) -> None:
+ # Every post-create writer on this row saves with `update_fields`, which skips `auto_now`
+ # unless the model widens the field list.
+ run, stale = self._run_with_stale_updated_at()
+
+ _record_emit(
+ run_id=run.id,
+ finding_id="finding-1",
+ description="A finding",
+ confidence=0.8,
+ severity="P1",
+ source_id=f"run:{run.id}:finding:finding-1",
+ tags=[],
+ )
+
+ run.refresh_from_db()
+ assert run.emitted_count == 1
+ assert run.updated_at is not None and run.updated_at > stale
+
+ def test_summary_write_advances_updated_at(self) -> None:
+ # The close-out summary lands as a targeted `.update()`, which no `save()` override can reach.
+ run, stale = self._run_with_stale_updated_at()
+
+ # The derived-metadata stamp saves the same row moments later, so it would advance
+ # `updated_at` on its own and hide a summary write that carries no timestamp.
+ with patch("products.signals.backend.scout_harness.runner.stamp_derived_metadata"):
+ _finalize_run_row(run_id=run.id, team_id=self.team.id, summary="Nothing to report.")
+
+ run.refresh_from_db()
+ assert run.summary == "Nothing to report."
+ assert run.updated_at is not None and run.updated_at > stale
+
def test_signal_scratchpad_round_trip(self) -> None:
run = SignalScoutRun.objects.create(
task_run=self._make_task_run(),