Skip to content

test(api): fix flaky checkAlerts integration tests - #3858

Open
wrn14897 wants to merge 1 commit into
mainfrom
warren/fix-flaky-checkalerts-int-test
Open

wrn14897 wants to merge 1 commit into
mainfrom
warren/fix-flaky-checkalerts-int-test

Conversation

@wrn14897

@wrn14897 wrn14897 commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes intermittent checkAlerts.int.test.ts failures where a test finds fewer AlertHistory rows than it wrote (e.g. "expected 2, received 1").

Cause: DocumentDB's documentdb_ttl_task pg_cron job purges expired documents once a minute. The checkAlerts tests evaluate alerts at fixed 2023/2024 dates, so every history row is already past the 30-day TTL on createdAt. When a purge lands between an evaluation and its assertion, rows disappear. In recent CI runs this shows up as a retry in shard 4 (about 2 of 48 jobs) that jest.retryTimes(1) currently absorbs; any multi-step history test can be hit.

Fix:

  • docker/documentdb/entrypoint.sh: new opt-in DOCDB_DISABLE_TTL. When true, it unschedules documentdb_ttl_task on every boot. Default behavior is unchanged, so dev and e2e stacks keep TTL.
  • docker-compose.ci.yml: sets DOCDB_DISABLE_TTL: 'true' for the integration-test DB. No int test relies on TTL deletion.
  • checkAlerts.int.test.ts: reset the Slack webhook spy in the processAlert beforeEach. jest.clearAllMocks() keeps implementations, so a test that sets a persistent mockRejectedValue leaks into later tests. This doesn't happen on main today; it closes the gap (the same leak caused first-attempt failures in a downstream fork).

Test and CI only; no product code changes, so no changeset.

How to reproduce

Starting point: a worktree with Docker; yarn install and make dev-int-build once. Export the HDX_CI_* ports from scripts/slots.sh (hdx_ci_ports), start the stack with docker compose -p $HDX_CI_PROJECT -f docker-compose.ci.yml up -d --wait, and run the file from packages/api with JEST_RETRY_TIMES=0 DOTENV_CONFIG_PATH=.env.test DOTENV_CONFIG_OVERRIDE=true npx jest --config jest.int.config.js --runInBand --forceExit src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts.

On main:

  1. Make the purge frequent so it reliably overlaps a test: docker exec $HDX_CI_PROJECT-db-1 psql -h /tmp -U postgres -d postgres -c "select cron.alter_job(jobid, schedule := '1 seconds') from cron.job where jobname = 'documentdb_ttl_task'".
  2. Run the file 5 times. Locally all 5 runs failed (1 to 3 tests each, different tests every run).

On this branch:

  1. Rebuild the DB image (docker compose ... build db) and recreate the stack.
  2. select jobname from cron.job no longer lists documentdb_ttl_task, on a fresh boot and after docker restart.
  3. Run the file 5 times: 198/198 passed every run.

How to test locally or on Vercel

  1. make dev-int-build
  2. JEST_RETRY_TIMES=0 make dev-int FILE=checkAlerts.int
  3. All tests pass without retries.

References

  • Linear Issue: none
  • Related PRs: equivalent fix in the EE repo, where CI uses MongoDB (--setParameter ttlMonitorEnabled=false)

Note

Low Risk
Test and CI Docker configuration only; no application runtime or production deployment paths change.

Overview
Addresses intermittent checkAlerts integration failures where AlertHistory rows vanish between write and assert because DocumentDB’s documentdb_ttl_task cron purges “expired” docs every minute while tests use fixed 2023/2024 timestamps (already past the 30-day TTL).

CI DocumentDB: DOCDB_DISABLE_TTL is a new opt-in flag in entrypoint.sh that unschedules documentdb_ttl_task on container start when set to true; default stays unchanged for dev/e2e. docker-compose.ci.yml turns it on for the integration-test db service.

Test isolation: In the processAlert suite, the Slack postMessageToWebhook spy now calls .mockReset() in beforeEach so a prior test’s mockRejectedValue doesn’t leak after jest.clearAllMocks().

Reviewed by Cursor Bugbot for commit cc1e495. Bugbot is set up for automated code reviews on this repo. Configure here.

DocumentDB's documentdb_ttl_task pg_cron job purges expired documents
every minute. checkAlerts tests evaluate alerts at fixed 2023/2024 dates,
so their AlertHistory rows are already past the TTL; a purge landing
between an evaluation and its assertion drops rows. Add an opt-in
DOCDB_DISABLE_TTL to the DocumentDB entrypoint that unschedules the job,
and set it only in docker-compose.ci.yml.

Also reset the Slack webhook spy in the processAlert beforeEach:
clearAllMocks keeps implementations, so a persistent mockRejectedValue
would leak into later tests.
@wrn14897
wrn14897 requested a review from a team as a code owner November 30, 2026 04:27
@vercel

vercel Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
hyperdx-oss Ready Ready Preview Nov 30, 2026 4:30am UTC
hyperdx-storybook Ready Ready Preview Nov 30, 2026 4:30am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 30, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: cc1e495

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions github-actions Bot added the review/tier-2 Low risk — AI review + quick human skim label Nov 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔵 Tier 2 — Low Risk

Small, isolated change with no API route or data model modifications.

Why this tier:

  • Standard feature/fix — introduces new logic or modifies core functionality

Review process: AI review + quick human skim (target: 5–15 min). Reviewer validates AI assessment and checks for domain-specific concerns.
SLA: Resolve within 4 business hours.

Stats
  • Production files changed: 2
  • Production lines changed: 8 (+ 3 in test files, excluded from tier calculation)
  • Branch: warren/fix-flaky-checkalerts-int-test
  • Author: wrn14897

To override this classification, remove the review/tier-2 label and apply a different review/tier-* label. Manual overrides are preserved on subsequent pushes.

@github-actions

Copy link
Copy Markdown
Contributor

Duplicate code analysis

No new duplicate code introduced by this PR.


jscpd compared this branch against origin/main
across app, api and common-utils. Only new clones are listed; the codebase
currently holds 108 in total (1.10%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

jest
.spyOn(slack, 'postMessageToWebhook')
.mockReset()
.mockResolvedValueOnce(fromAny(null));

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.

🟡 P2 — After mockReset(), calls past the first one go to the real Slack webhook

Use .mockReset().mockResolvedValue(fromAny(null)) so every call in a test gets a default stub, not just the first. Why: the repo uses Jest 30 (packages/api/package.json), where mockReset() on a spyOn puts back the original function. The beforeEach then stubs only one call with mockResolvedValueOnce, so any later call runs the real postMessageToWebhook (packages/api/src/utils/slack.ts:13). That sends a real IncomingWebhook.send to https://hooks.slack.com/services/123. Before this PR, those calls were usually caught by a stub some earlier test had left behind with mockResolvedValue (e.g. lines 3081 and 8096). Now they reliably make real network calls. Example: the group-by skip test at ~7257/7278 expects 4 Slack calls and stubs none itself. Its calls 2–4 now reach the network, which makes the suite slower and dependent on the network — the kind of flakiness this PR is meant to remove.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

@github-actions

Copy link
Copy Markdown
Contributor

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

1 finding(s): 🔴 0 P0/P1 · 🟡 1 P2 · 🔵 0 P3

1 posted as inline comment(s) on the changed lines.


Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

@github-actions

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. This is a well-scoped test/CI-infra change (DocumentDB entrypoint, CI compose, one Jest beforeEach). The missing changeset flagged by changeset-bot is a false positive — AGENTS.md rule #7 exempts test/CI/tooling changes, so no changeset is required.

🟡 P2 — recommended

  • docker/documentdb/entrypoint.sh:48 — The WHERE jobname = 'documentdb_ttl_task' unschedule returns zero rows (and never calls cron.unschedule) if the job is not yet registered when the query runs; documentdb.enableBackgroundWorkerJobs = true means the TTL job is scheduled asynchronously by the background worker, so on a fresh boot ON_ERROR_STOP cannot catch the zero-row match and TTL can silently stay active, reintroducing the flakiness intermittently.
    • Fix: After unscheduling, verify no documentdb_ttl_task row remains in cron.job and fail loudly (or poll until the job appears before unscheduling) so an ineffective disable surfaces as a hard error instead of silent, recurring flakiness.
    • correctness-reviewer, reliability-reviewer
🔵 P3 nitpicks (2)
  • packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts:11977 — The same spyOn(slack,'postMessageToWebhook').mockResolvedValueOnce(...) + afterEach clearAllMocks() pattern exists without the new .mockReset() in the Alert Templates (:1363) and processAlert with materialized views (:11977) blocks; they are not flaky today only because neither installs a persistent/rejecting webhook mock.

    • Fix: Add .mockReset() to those two sibling beforeEach blocks (or centralize the webhook-spy setup) so the isolation guard is consistent.
  • docker/documentdb/entrypoint.sh:47 — The guard [ "${DOCDB_DISABLE_TTL:-false}" = true ] activates only for the exact string true; values like 1, TRUE, or yes silently no-op with no feedback.

    • Fix: Document the exact-true contract in the inline comment, or normalize the value before comparing.

Reviewers (5): correctness, testing, reliability, maintainability, project-standards.

Testing gaps:

  • No assertion that documentdb_ttl_task is actually gone after container start, so the silent no-op failure mode above would go undetected.
  • Disabling TTL in CI removes integration coverage of the purge path (acceptable — purge is pg_cron/DocumentDB behavior, not ClickStack code, and the flag is opt-in/CI-only).

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

@github-actions

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 479 passed • 1 skipped • 1126s

Status Count
✅ Passed 479
❌ Failed 0
⚠️ Flaky 12
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — cc1e4959 Deployed Nov 30, 2026 by vercel[bot]
Preview – hyperdx-storybook — cc1e4959 Deployed Nov 30, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review/tier-2 Low risk — AI review + quick human skim

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant