Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(signals): claim supersede marker before slow edit side effects (#92751)

posthog[bot]b50b2a3ed12c
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
index 97eb05236cf4..3e2158581027 100644
--- a/products/signals/backend/scout_harness/tools/report.py
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -1390,6 +1390,56 @@ def _do_edit_report(
attribution=attribution,
author=run.skill_name,
)
+ charts_set = len(charts) if charts is not None and charts_changed else None
+ prompts_set = len(suggested_prompts) if suggested_prompts is not None and prompts_changed else None
+ changed = (
+ bool(updated_fields or note_appended or reviewers_set) or charts_set is not None or prompts_set is not None
+ )
+ # Enqueue the edited report's Slack delivery as the first post-commit step — before the slower
+ # side effects below (repository inference, autostart) and the tally writes further down. An
+ # earlier delivery of the same report may still be building its message, and it reads the report's
+ # latest-delivery marker to decide whether to yield to this edit. Claiming that marker here, right
+ # after the content commits, keeps the window in which the edit is visible but the marker is not as
+ # short as one status read. If the slow work ran first, that earlier delivery could read the freshly
+ # committed edit, still find no marker, and post the edited report — the same content this edit's
+ # own delivery then posts a second time.
+ if changed:
+ # Mirror emit's surfaced gate: an edit to a suppressed / never-surfaced report must not push
+ # its content to a configured destination. The delivery worker re-checks status at send time
+ # (the report can be suppressed after enqueue), so this mainly keeps the two paths symmetric
+ # and skips queueing work that would no-op.
+ #
+ # The edit has already committed, so a transient failure on this read must not fail the call or
+ # skip the side effects below (repository inference, autostart, the tally) — same best-effort
+ # posture as the title read further down. Degrade to None, which the `is not None` guard treats
+ # as "don't enqueue"; the delivery is best-effort and `queue_configured_scout_slack_delivery`
+ # swallows its own failures anyway.
+ try:
+ report_status = get_scout_report_status(team_id=team.id, report_id=report_id)
+ except Exception:
+ logger.warning(
+ "signals_scout.edit_report: failed to read report status for slack delivery",
+ extra={"team_id": team.id, "report_id": report_id},
+ )
+ report_status = None
+ # Suggested questions live in the inbox, nowhere in the Slack message, so an edit that
+ # touched only them has nothing to say in the channel — delivering it would post the report
+ # a second time byte for byte.
+ prompts_only = prompts_set is not None and not (
+ updated_fields or note_appended or reviewers_set or charts_set is not None
+ )
+ if report_status is not None and _surfaced(report_status) and not prompts_only:
+ # A note-only edit leaves the title, summary and charts the Slack report message shows
+ # unchanged, so re-posting it would duplicate the message already in the channel.
+ # Deliver the note itself instead; any edit that rewrote the content re-posts the
+ # report as before.
+ note_only = note_appended and not updated_fields and not charts_changed
+ queue_configured_scout_slack_delivery(
+ run_id=run.id,
+ output_type="report",
+ output_id=report_id,
+ edit_note=append_note if note_only else None,
+ )
# A rewrite can move the report onto a different repository, and an inferred target is only ever a
# reading of that text. Outside the transaction above for the same reason autostart is: it reads
# the team's GitHub repo cache, which has no business holding the content write open.
@@ -1397,15 +1447,24 @@ def _do_edit_report(
# Ordered before autostart, because one edit can both rewrite the content and add a qualifying
# reviewer. Autostart reads the selection as it stands and is idempotent, so running it first
# would open the task against the repository the rewrite just replaced, with no second chance.
+ #
+ # Best-effort like autostart below: the Slack delivery was already enqueued above, so a raise here
+ # must not fail the already-committed edit. A failure returned to the agent triggers a retry, and a
+ # retry carrying reviewers or a note enqueues a second full delivery — the duplicate this reorder
+ # exists to prevent. Swallow and log; a stale inferred repo is corrected by the next edit.
if updated_fields:
- _refresh_inferred_repository(team_id=team.id, report_id=report_id, attribution=attribution)
+ try:
+ _refresh_inferred_repository(team_id=team.id, report_id=report_id, attribution=attribution)
+ except Exception:
+ logger.exception(
+ "signals_scout.edit_report: inferred repository refresh failed",
+ extra={"team_id": team.id, "report_id": report_id},
+ )
# Re-run autostart only when reviewers changed: it's idempotent (a report with an implementation
# task already started no-ops), but a report that was missing a qualifying reviewer can now open a
# draft PR. Fired outside any txn since it spawns a Task — mirrors emit's post-commit hand-off.
if reviewers_set:
async_to_sync(_maybe_autostart_report)(team_id=team.id, report_id=report_id)
- charts_set = len(charts) if charts is not None and charts_changed else None
- prompts_set = len(suggested_prompts) if suggested_prompts is not None and prompts_changed else None
logger.info(
"signals_scout.edit_report: edited",
extra={
@@ -1443,35 +1502,14 @@ def _do_edit_report(
)
# Record the edit on the run tally only when something actually changed — a no-op edit (e.g. a
# title rewrite to its current value, or re-sending the charts already stored) must not claim the
- # run touched the report, or notify its destination a second time about nothing.
- if result.changed:
+ # run touched the report, or notify its destination a second time about nothing. The Slack
+ # delivery for this edit was already enqueued above, before the autostart side effect, so a prior
+ # in-flight delivery sees the supersede marker rather than posting the edit a second time.
+ if changed:
record_report_edit(team_id=team.id, run_id=run.id, report_id=report_id)
# Also link the run itself on the report's work log (deduped), so the editing scout's
# transcript is reachable from the report — not just the run-side `edited_report_ids` tally.
record_scout_run_task_artefact(team_id=team.id, report_id=report_id, run=run, task_id=attribution.task_id)
- # Mirror emit's surfaced gate: an edit to a suppressed / never-surfaced report must not push
- # its content to a configured destination. The delivery worker re-checks status at send time
- # (the report can be suppressed after enqueue), so this mainly keeps the two paths symmetric
- # and skips queueing work that would no-op.
- report_status = get_scout_report_status(team_id=team.id, report_id=report_id)
- # Suggested questions live in the inbox, nowhere in the Slack message, so an edit that
- # touched only them has nothing to say in the channel — delivering it would post the report
- # a second time byte for byte.
- prompts_only = prompts_set is not None and not (
- updated_fields or note_appended or reviewers_set or charts_set is not None
- )
- if report_status is not None and _surfaced(report_status) and not prompts_only:
- # A note-only edit leaves the title, summary and charts the Slack report message shows
- # unchanged, so re-posting it would duplicate the message already in the channel.
- # Deliver the note itself instead; any edit that rewrote the content re-posts the
- # report as before.
- note_only = note_appended and not updated_fields and not charts_changed
- queue_configured_scout_slack_delivery(
- run_id=run.id,
- output_type="report",
- output_id=report_id,
- edit_note=append_note if note_only else None,
- )
return result
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index 2f8651424523..a77d4d862e0b 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -433,6 +433,113 @@ class TestScoutReportAPI(APIBaseTest):
autostart.assert_awaited_once()
assert repository_at_autostart == ["acme/gadgets"]
+ def test_content_edit_queues_slack_delivery_before_the_autostart_side_effect(self) -> None:
+ # A prior delivery of the same report may still be building its Slack message; it reads the
+ # report's latest-delivery marker to decide whether to yield to this edit. The edit claims
+ # that marker when it queues its own delivery, so the queue call must run before the slow
+ # post-commit side effects (repository inference, autostart). Otherwise the prior delivery can
+ # read the freshly committed edit, still find no marker, and post the edited report a second
+ # time — the same content this edit's own delivery then posts again.
+ run = _make_run(self.team)
+ # Emit before the destination is set, so only the edit below queues a delivery.
+ with _safe_judge(), patch(EMBED_PATH), patch(CONNECTED_REPOS_PATH, return_value=_CONNECTED_REPOS):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ config = run.scout_config
+ assert config is not None
+ config.output_destinations = {"slack": {"integration_id": 17, "channel": "CSCOUTS|#scout-findings"}}
+ config.save(update_fields=["output_destinations"])
+
+ queued_output_ids: list[str] = []
+ queued_before_autostart: list[bool] = []
+
+ def _record_queue(**kwargs) -> None:
+ queued_output_ids.append(kwargs["output_id"])
+
+ async def _record_autostart(**kwargs) -> None:
+ queued_before_autostart.append(bool(queued_output_ids))
+
+ with (
+ patch(CONNECTED_REPOS_PATH, return_value=_CONNECTED_REPOS),
+ patch(
+ "products.signals.backend.scout_harness.tools.report.queue_configured_scout_slack_delivery",
+ side_effect=_record_queue,
+ ),
+ patch(AUTOSTART_PATH, new=AsyncMock(side_effect=_record_autostart)),
+ ):
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={
+ "report_id": created["report_id"],
+ "summary": "Rewritten summary",
+ "suggested_reviewers": [{"github_login": "octocat"}],
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ # The reviewer change ran autostart, and the delivery was already queued by the time it did.
+ assert queued_output_ids == [created["report_id"]]
+ assert queued_before_autostart == [True]
+
+ def test_content_edit_survives_a_slack_status_read_failure(self) -> None:
+ # The status read that gates the Slack delivery runs after the edit has committed. A transient
+ # failure there must not fail the call or skip the side effects below it (autostart, the tally):
+ # only the delivery enqueue is best-effort. Degrade to skipping the enqueue and carry on.
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(CONNECTED_REPOS_PATH, return_value=_CONNECTED_REPOS):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ report_id = created["report_id"]
+ with (
+ patch(CONNECTED_REPOS_PATH, return_value=_CONNECTED_REPOS),
+ patch(
+ "products.signals.backend.scout_harness.tools.report.get_scout_report_status",
+ side_effect=RuntimeError("db unavailable"),
+ ),
+ patch("products.signals.backend.scout_harness.tools.report.queue_configured_scout_slack_delivery") as queue,
+ patch(AUTOSTART_PATH, new=AsyncMock()) as autostart,
+ ):
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={
+ "report_id": report_id,
+ "summary": "Rewritten summary",
+ "suggested_reviewers": [{"github_login": "octocat"}],
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ # The read failed, so the delivery is skipped, but autostart and the run tally still ran.
+ queue.assert_not_called()
+ autostart.assert_awaited_once()
+ run.refresh_from_db()
+ assert run.edited_report_ids == [report_id]
+
+ def test_content_edit_survives_an_inferred_repository_refresh_failure(self) -> None:
+ # Repository inference runs after the Slack delivery is already enqueued. If it raises, failing
+ # the already-committed, already-enqueued edit would return an error the agent retries — and a
+ # retry can enqueue a second full delivery. The refresh is best-effort: swallow, keep the edit
+ # successful, and let the tally still run.
+ run = _make_run(self.team)
+ with _safe_judge(), patch(EMBED_PATH), patch(CONNECTED_REPOS_PATH, return_value=_CONNECTED_REPOS):
+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ report_id = created["report_id"]
+ with (
+ patch(
+ "products.signals.backend.scout_harness.tools.report._refresh_inferred_repository",
+ side_effect=RuntimeError("repo cache unavailable"),
+ ),
+ patch("products.signals.backend.scout_harness.tools.report.queue_configured_scout_slack_delivery") as queue,
+ ):
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": report_id, "summary": "Rewritten summary"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ # The delivery was accepted before the refresh raised, and the tally still recorded the edit.
+ queue.assert_called_once()
+ run.refresh_from_db()
+ assert run.edited_report_ids == [report_id]
+
def test_emit_report_writes_autostart_artefacts(self) -> None:
# The autostart inputs the scout supplies become the same artefacts a pipeline report carries,
# which is what `maybe_autostart_from_report_artefacts` reads to open a draft PR. Repo is normalized.