Skip to content

refactor(alerts): reduce investigation loop complexity - #100093

Merged
trunk-io[bot] merged 2 commits into
fix/alert-salvage-loop-errorfrom
posthog/refactor-alert-investigation-loop
Sep 26, 2026
Merged

trunk-io[bot] merged 2 commits into
fix/alert-salvage-loop-errorfrom
posthog/refactor-alert-investigation-loop

Conversation

@pauldambra

@pauldambra pauldambra commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

Problem

  • Alert maintainers need the anomaly investigation loop to stay easy to inspect when report recovery fails.
  • Why: dense control flow makes recovery changes harder to review safely.

Changes

How did you test this code?

  • Ran uv run pytest -q posthog/temporal/tests/ai/test_anomaly_investigation_runner.py.
  • Ran Ruff checks and hogli ci:preflight --strict after stacking.

Release status

  • No feature flag controls this change
  • This change is behind a feature flag and is not available to users
  • This change makes a previously flagged feature available to everyone

Automatic notifications

  • Publish to changelog?

Docs update

  • None. This refactor does not change a documented workflow.

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Agent: PostHog Slack app (original PR); Codex, GPT-6 (stacking pass)

  • PostHog Slack app used the anomaly-agent, writing-dataclasses, rs-trim-comments, writing-pr-descriptions, and reviewing-with-coderabbit guidance.
  • The CodeRabbit CLI was unavailable, so this PR opens without a local CodeRabbit pass.
  • The PR search found no open PR that refactors this loop.
  • This PR contains no session-derived customer data.
  • A review comment requested the separate fix in fix(alerts): salvage report when investigation loop fails #106334. Codex replayed this refactor onto that fix, using /stacking-prs and /writing-pr-descriptions.

Created with PostHog from a Slack thread

@pauldambra pauldambra self-assigned this Sep 14, 2026
@trunk-io

trunk-io Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

😎 Stack merged successfully - details.

@pauldambra
pauldambra marked this pull request as ready for review September 14, 2026 11:23
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-14T11:28:07.791560Z fd6d065 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

🤖 CI report

⚠️ Trunk lane — backend Python lane

This PR is assigned to the backend Python lane. It runs backend Python tests and may merge in parallel with PRs in other lanes.

✅ Duplication (Python) — clean

New Python code duplication introduced by this branch. Fails at 70+ tokens in app code, or 150+ tokens when both copies live in test files. Advisory while the gate proves itself: extract a shared helper instead of copying.

✅ Duplication (TypeScript) — clean

New TypeScript code duplication introduced by this branch. Fails at 70+ tokens in app code, or 150+ tokens when both copies live in test files. Advisory while the gate proves itself: extract a shared helper instead of copying.

🚨 Comment density — 12% of added code lines are comments (26 of 224)

This section warns when comments are more than 3% of the code lines a PR adds, and alerts above 6%. Before agent-assisted PRs, the typical share was about 2%. Only full-line comments count. Docstrings, generated files, snapshots, migrations, and workflow files are left out.

Comments that restate the code, record how the change came about, or narrate the next line add noise for the next reader. Keep the comments that explain a reason the code cannot show, and remove the rest. See .agents/skills/writing-code-comments/SKILL.md for the house rules.

Files with the most added comment lines:

File Comment lines Added lines
posthog/temporal/ai/anomaly_investigation/runner.py 26 224

This check does not block merging. It updates on every push and clears when the share drops.

✅ ClickHouse migration SQL — none

No ClickHouse migrations in the latest push.

pauldambra commented Sep 14, 2026 •

Copy link
Copy Markdown
Member Author

Note

🤖 Automated comment by QA Swarm — not written by a human

Multi-perspective review: router (cheap-first pass) + delegated reviewers (qa-team, paul-reviewer, xp-reviewer, security-audit as warranted)

Verdict: ✅ APPROVE (round 4 @ 4b3a448)

Two more commits landed since round 3: the defensive per-run state reset, and consolidating that state's initialization into run() alone (bare type annotations in __init__, no duplicate assignment). Router re-verified both are correct — bare annotations perform no runtime assignment, all three per-run attributes are now set in exactly one place, and every execution path still matches the original loop. No findings.

Key findings

  • None.

Convergence

  • N/A — clean round.

Reviewer summaries

Reviewer Assessment
🧭 router Low risk, high confidence. No delegation needed.
Previous rounds (3)

round 1 @ fd6d065 — ✅ APPROVE: no correctness, security, or style issue found.
round 2 @ f38efdba — 💬 APPROVE WITH NITS: one MEDIUM (LLM-invoke error path bypassed _result()) — fixed in commit 85f9d0c.
round 3 @ fa36843 — 💬 APPROVE WITH NITS: one MEDIUM (latent state-reuse hazard in _InvestigationRunner.run()) — fixed in commit 376a5f0, then further hardened in commit 4b3a448.


Automated by QA Swarm — not a human review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fd6d065d0c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@pauldambra pauldambra added the stamphog Request AI approval (no full review) label Sep 14, 2026 — with PostHog
stamphog[bot]
stamphog Bot previously approved these changes Sep 14, 2026

@stamphog stamphog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved.

Pure internal refactor extracting helper functions from a Temporal anomaly-investigation loop; tracing the diff confirms the tool-budget, retry, salvage, and fallback control flow is preserved unchanged. The two unresolved Codex comments are a style preference (class vs. functions) and a lost explanatory comment — non-substantive per the rubric, not correctness or security issues, and this is not risky territory.

  • Codex flagged (P1, unresolved): prefers the extracted loop state be encapsulated in a class per repo convention (AGENTS.md) — style preference, not a correctness issue.
  • Codex flagged (P1, unresolved): the refactor dropped an explanatory comment about why LLM finalize failures are swallowed rather than left to bubble up to Temporal retries — worth restoring for future maintainers but behavior itself is unchanged.
Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✓ no deny categories matched
size ✓ 396L, 1F substantive — within ceiling
tier ✓ T1-agent / T1d-complex (396L, 1F, single-area, refactor)
stamphog 2.0.0b4 .stamphog/policy.yml @ f38efdb · reviewed head f38efdb

@trunk-io

trunk-io Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Static Badge   Static Badge   Static Badge

View Full Report ↗︎ ⋅ Docs

@posthog

posthog Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

🦔 PostHog Review reviewed this pull request

Found 0 must fix, 1 should fix, 1 consider.

Published 2 findings (view the review).

Resolved comments: 1 fixed, 1 left for you

pauldambra added a commit that referenced this pull request Sep 14, 2026
Addresses review feedback on #100093: threading messages, report_args_history,
and tool_calls_used through several loose functions risked one path omitting
or propagating the state inconsistently. Moves the extracted operations onto a
private _InvestigationRunner class that owns that state, and restores the
comment explaining why a failed finalize call returns a fallback report
instead of raising (an exception would trigger a costly full activity retry).

Generated-By: PostHog Desktop
Task-Id: bd7e5ab4-ee17-419c-a28d-702360e9805a
@stamphog
stamphog Bot dismissed their stale review September 14, 2026 12:13

A new stamphog review started for this PR — the fresh verdict replaces this approval.

stamphog[bot]
stamphog Bot previously approved these changes Sep 14, 2026

@stamphog stamphog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved.

Internal refactor of a single Temporal worker file that preserves the LLM tool-calling/report-validation/salvage/fallback behavior verbatim (verified by diffing old vs new control flow); both prior Codex P1 concerns (extract to a class, retain retry rationale comment) are already addressed in the current head. Not risky territory (no schema, API contract, auth, billing, dependency, or CI changes), so no independent assurance is required.

Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✓ no deny categories matched
size ✓ 435L, 1F substantive — within ceiling
tier ✓ T1-agent / T1d-complex (435L, 1F, single-area, refactor)
stamphog 2.0.0b4 .stamphog/policy.yml @ b00a225 · reviewed head b00a225

@posthog

posthog Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

PostHog Review alpha 🦔 If you find any issues helpful - please reply "valid", "invalid", etc., for evaluation purposes 🙏

@posthog posthog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PostHog Review

Found 1 should fix, 1 consider.

@posthog posthog Bot removed the reviewhog label Sep 14, 2026
@stamphog
stamphog Bot dismissed their stale review September 14, 2026 12:35

A new stamphog review started for this PR — the fresh verdict replaces this approval.

stamphog[bot]
stamphog Bot previously approved these changes Sep 14, 2026

@stamphog stamphog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved.

Pure behavior-preserving refactor of one internal file; I traced both bot-flagged concerns against the diff and confirmed the precondition comment was preserved (reworded, relocated) and the salvage asymmetry the bot called out exists identically in the pre-refactor code, so it's not a regression this PR introduces. Not risky territory, so no independent assurance is required.

Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✓ no deny categories matched
size ✓ 440L, 1F substantive — within ceiling
tier ✓ T1-agent / T1d-complex (440L, 1F, single-area, refactor)
stamphog 2.0.0b4 .stamphog/policy.yml @ a1ace6f · reviewed head a1ace6f

@stamphog
stamphog Bot dismissed their stale review September 19, 2026 12:11

A new stamphog review started for this PR — the fresh verdict replaces this approval.

stamphog[bot]
stamphog Bot previously approved these changes Sep 19, 2026

@stamphog stamphog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved.

Verified line-by-line that the refactor is behaviorally identical to the prior inline loop — extracted helpers and a stateful runner class reproduce every branch (tool-budget finalize, retry, salvage, fallback) exactly, including the pre-existing salvage asymmetry a bot flagged, which is unchanged from master and already triaged as out-of-scope. Tests/mypy/CI checks reported passing and an independent bot review approved twice with no outstanding correctness issues.

Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✓ no deny categories matched
size ✓ 428L, 1F substantive — within ceiling
tier ✓ T1-agent / T1d-complex (428L, 1F, single-area, refactor)
stamphog 2.0.0 .stamphog/policy.yml @ f07517e · reviewed head f07517e

@stamphog
stamphog Bot dismissed their stale review September 19, 2026 12:29

A new stamphog review started for this PR — the fresh verdict replaces this approval.

stamphog[bot]
stamphog Bot previously approved these changes Sep 19, 2026

@stamphog stamphog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved.

Pure internal refactor of the anomaly-investigation loop into a class with helper methods; comparing old and new code shows behavior is preserved and the one real behavior bug reviewers found (tool_calls_used defaulting to 0 on the LLM-invoke-failure path) is already fixed by routing all returns through the new _result() helper. The remaining flagged issue (salvage-vs-fallback asymmetry) is unchanged from master, explicitly disclosed as preserved behavior, and the reviewer/author thread already agreed to fix it in a separate stacked PR rather than block this one — no unresolved regression, and the PR was covered by three rounds of automated review plus targeted unit tests.

  • Pre-existing (not introduced here) asymmetry: the loop's LLM-invoke-failure path returns a bare fallback report without consulting report_args_history for salvage, unlike the tool-budget-exhaustion path — author and reviewer agreed to address this in a follow-up stacked PR rather than in this refactor.
Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✓ no deny categories matched
size ✓ 425L, 1F substantive — within ceiling
tier ✓ T1-agent / T1d-complex (425L, 1F, single-area, refactor)
stamphog 2.0.0 .stamphog/policy.yml @ 85f9d0c · reviewed head 85f9d0c

@stamphog
stamphog Bot dismissed their stale review September 19, 2026 12:36

A new stamphog review started for this PR — the fresh verdict replaces this approval.

stamphog[bot]
stamphog Bot previously approved these changes Sep 19, 2026

@stamphog stamphog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved.

Pure internal refactor of the anomaly-investigation loop into a class-based structure, verified line-by-line to preserve prior control flow (retry, salvage, fallback, tool budget) exactly; it doesn't touch schemas, APIs, deps, CI, or auth. The one flagged asymmetry (LLM-invoke-failure path skipping salvage) is confirmed pre-existing on master, not introduced here, and was already surfaced by an automated reviewer and explicitly deferred to a follow-up human decision, which the author acknowledged.

  • Pre-existing, non-regressing asymmetry: run()'s LLM tool-call invoke failure path returns a bare fallback report without consulting report_args_history, unlike the budget-finalize failure path which salvages. Already flagged by @PostHog[bot] and escalated separately for a human policy decision on verdict handling; not a blocker for this refactor PR but worth a prompt follow-up.
Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✓ no deny categories matched
size ✓ 427L, 1F substantive — within ceiling
tier ✓ T1-agent / T1d-complex (427L, 1F, single-area, refactor)
stamphog 2.0.0 .stamphog/policy.yml @ fa36843 · reviewed head fa36843

@stamphog
stamphog Bot dismissed their stale review September 19, 2026 12:47

A new stamphog review started for this PR — the fresh verdict replaces this approval.

stamphog[bot]
stamphog Bot previously approved these changes Sep 19, 2026

@stamphog stamphog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved.

Careful line-by-line comparison confirms this is a faithful extract-to-class refactor of the anomaly investigation loop with no behavioral changes; the one outstanding defect (salvage-path asymmetry) is pre-existing on master, not introduced by this diff, and was already triaged separately by the bot reviewer as out-of-scope for this PR. A prior latent state-reuse concern raised by the QA swarm review has since been fixed (tool_calls_used and report_args_history are both reset together).

Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✓ no deny categories matched
size ✓ 429L, 1F substantive — within ceiling
tier ✓ T1-agent / T1d-complex (429L, 1F, single-area, refactor)
stamphog 2.0.0 .stamphog/policy.yml @ 376a5f0 · reviewed head 376a5f0

@pauldambra
pauldambra force-pushed the posthog/refactor-alert-investigation-loop branch from be3d01c to 3efe755 Compare September 24, 2026 22:21
@stamphog
stamphog Bot dismissed their stale review September 24, 2026 22:22

A new stamphog review started for this PR — the fresh verdict replaces this approval.

@pauldambra
pauldambra changed the base branch from master to fix/alert-salvage-loop-error September 24, 2026 22:22
stamphog[bot]

This comment was marked as outdated.

@pauldambra
pauldambra force-pushed the posthog/refactor-alert-investigation-loop branch from 3efe755 to 3f05401 Compare September 24, 2026 22:32
@stamphog
stamphog Bot dismissed their stale review September 24, 2026 22:32

A new stamphog review started for this PR — the fresh verdict replaces this approval.

stamphog[bot]

This comment was marked as outdated.

@pauldambra
pauldambra force-pushed the posthog/refactor-alert-investigation-loop branch from 3f05401 to 553cded Compare September 24, 2026 23:11
@stamphog
stamphog Bot dismissed their stale review September 24, 2026 23:11

A new stamphog review started for this PR — the fresh verdict replaces this approval.

stamphog[bot]

This comment was marked as outdated.

@stamphog
stamphog Bot dismissed their stale review September 24, 2026 23:26

A new stamphog review started for this PR — the fresh verdict replaces this approval.

stamphog[bot]

This comment was marked as outdated.

@pauldambra
pauldambra force-pushed the posthog/refactor-alert-investigation-loop branch from 0593fe1 to bcf35a6 Compare September 25, 2026 00:04
@stamphog
stamphog Bot dismissed their stale review September 25, 2026 00:04

A new stamphog review started for this PR — the fresh verdict replaces this approval.

stamphog[bot]

This comment was marked as outdated.

@posthog

posthog Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

🚨 This push destroyed the test runs of 12 other PRs

The SQL insight value (pauldambra pushed to this PR while it was being tested in the Trunk merge queue.

That push threw this PR out of the queue and killed the test run of every PR queued behind it. All 12 of them now have to run the full test suite again, from scratch:

#88545, #100269, #103522, #104360, #105695, #106067, #106303, #106321, #106330, #106331, #106376, #106388

Once a PR enters the merge queue it is finished. Do not touch it again. Let it merge. If something still has to change, put it on a new branch and open a new PR.

A push from a local checkout is blocked before this can happen, but only when the Trunk CLI is logged in. Run trunk login once to turn that guard on.

@pauldambra
pauldambra force-pushed the posthog/refactor-alert-investigation-loop branch from bcf35a6 to 009c948 Compare September 25, 2026 09:12
@stamphog
stamphog Bot dismissed their stale review September 25, 2026 09:12

A new stamphog review started for this PR — the fresh verdict replaces this approval.

stamphog[bot]

This comment was marked as outdated.

@pauldambra
pauldambra force-pushed the posthog/refactor-alert-investigation-loop branch from 009c948 to d8e9988 Compare September 25, 2026 09:15
@stamphog
stamphog Bot dismissed their stale review September 25, 2026 09:15

A new stamphog review started for this PR — the fresh verdict replaces this approval.

@stamphog stamphog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved.

Line-by-line diff comparison shows the new _InvestigationRunner class preserves the original loop's control flow (budget-exhaustion finalize retry, tool-call handling, salvage/fallback paths) exactly — it's a mechanical extraction into helpers/methods, not a behavior change. It's internal alert-investigation tooling, not risky territory, and it already has tests plus multiple automated review passes (Codex, CodeRabbit, an internal QA bot that iterated 4 rounds and caught/fixed two real bugs along the way) converging clean with only a cosmetic nitpick outstanding.

Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✓ no deny categories matched
size ✓ 452L, 1F substantive — within ceiling
tier ✓ T1-agent / T1d-complex (452L, 1F, single-area, refactor)
stamphog 2.1.0 .stamphog/policy.yml @ d8e9988 · reviewed head d8e9988

@pauldambra
pauldambra force-pushed the posthog/refactor-alert-investigation-loop branch from d8e9988 to 60c58bf Compare September 25, 2026 09:34
@trunk-io
trunk-io Bot merged commit a9b9147 into master Sep 26, 2026
241 checks passed
@trunk-io
trunk-io Bot deleted the posthog/refactor-alert-investigation-loop branch September 26, 2026 17:06
@deployment-status-posthog

deployment-status-posthog Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

Deploy status

Environment Status Deployed At Workflow
dev ✅ Deployed 2026-09-26 17:22 UTC Run
prod-us ✅ Deployed 2026-09-26 17:34 UTC Run
prod-eu ✅ Deployed 2026-09-26 17:33 UTC Run

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stamphog Request AI approval (no full review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant