Skip to content

feat: add alert rule test fire button - #2203

Merged
jsers merged 9 commits into
mainfrom
optimize-alert-rule-page
Jul 24, 2026
Merged

feat: add alert rule test fire button#2203
jsers merged 9 commits into
mainfrom
optimize-alert-rule-page

Conversation

@710leo

@710leo 710leo commented Jul 22, 2026

Copy link
Copy Markdown
Member
image image

Summary by CodeRabbit

  • New Features
    • Added a Test Fire action for alert rules to run a synthetic trigger or recovery event.
    • Includes severity/event-type selection, Prometheus real-series sampling (with selectable series) or mock sampling, and dry-run vs real-send.
    • Displays localized, stage-by-stage results with a detailed collapsible event panel.
  • Bug Fixes
    • Improved handling/compatibility for “notify recovered” values across boolean and numeric inputs.
    • Prevented stale datasource values from persisting when switching datasource categories.
  • Tests
    • Added unit tests covering default severity selection, PromQL selection by rule version, vector-series parsing, and notification outcome summarization.

710leo added 3 commits July 22, 2026 16:48
…ore conditions are met

Adds a 'test fire' button beside Save in FormNG. It synthesizes a test
event from the current (even unsaved) rule config — using a real
Prometheus series sample or a built-in mock — and calls the new backend
test-fire endpoint, which walks the real effective/pipeline/mute/notify/
subscribe chain and returns a per-stage report. Notifications are really
sent with a [TEST] marker unless dry-run is checked.
…sread form value

The form stores notify_recovered as the Switch boolean (converted to 0/1
only by processFormValues on save), so comparing against 1 flagged
enabled rules as disabled. Accept both the boolean and numeric forms.
…ecovery notify in test-fire

- getDefaultSeverity only looked at rule_config.queries[].severity; ES/SQL
  plugin datasources and Prometheus V2 keep severity in rule_config.triggers,
  so the default always fell back to S2 there
- render the new recover_notify_disabled notify-stage reason returned by the
  backend when the rule has recovery notification disabled
@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds an alert-rule test-fire modal with configurable event and sample settings, Prometheus series selection, API execution, staged results, localized messages, utility functions, and unit tests. The modal is integrated into the alert-rule form action area.

Changes

Alert rule test-fire

Layer / File(s) Summary
Test-fire data helpers and validation
src/pages/alertRules/FormNG/components/TestFireModal/utils.ts, src/pages/alertRules/FormNG/components/TestFireModal/utils.test.ts
Defines test-stage, sample-series, and notification-summary types and helpers, with tests for severity selection, PromQL extraction, vector parsing, and notification aggregation.
Test-fire execution and form integration
src/pages/alertRules/FormNG/components/TestFireModal/index.tsx, src/pages/alertRules/services.ts, src/pages/alertRules/FormNG/index.tsx
Adds modal state and execution flow, Prometheus sampling, the test-fire POST request, stale datasource response handling, deprecated datasource cleanup, and action-bar wiring.
Result rendering and localized messages
src/pages/alertRules/FormNG/components/TestFireModal/index.tsx, src/pages/alertRules/locale/*.ts
Displays staged outcomes and event details, with test-fire labels and result descriptions across supported locales.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant FormNG
  participant TestFireModal
  participant PrometheusService
  participant AlertRuleTestFireAPI
  FormNG->>TestFireModal: open with form values and business group
  TestFireModal->>PrometheusService: fetch vector-series data
  PrometheusService-->>TestFireModal: return sample series
  TestFireModal->>AlertRuleTestFireAPI: submit test-fire payload
  AlertRuleTestFireAPI-->>TestFireModal: return event and stage results
  TestFireModal-->>FormNG: render result timeline and event details
Loading

Possibly related PRs

  • n9e/fe#2144: Introduces the FormNG page composition used to integrate the test-fire modal.

Suggested reviewers: jsers

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title matches the main change: adding an alert rule test fire button and related test-fire workflow.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch optimize-alert-rule-page

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

710leo added 4 commits July 22, 2026 19:21
…re report

The backend now reports when a notify rule's own event pipeline drops the
event (so it won't be sent); render it explicitly instead of falling
through to a misleading 'not matched'.
Backend no longer emits the subscribe stage; remove it from the stage
list, renderer and locales.
…test-fire modal

- read the query expression by rule_config.version (V2 stores it in
  queries[].query, only V1 uses prom_ql), so Prometheus advanced-mode rules
  can pick a real series instead of silently falling back to mock
- guard fetchSeries with a request-id so a slow earlier response can't
  overwrite a newer one; clear series/selection up front
- reset local state on open/close so reopening never echoes stale series,
  and disable Run while series are loading

@coderabbitai coderabbitai 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/pages/alertRules/FormNG/components/TestFireModal/index.tsx (1)

179-343: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Define the alert-rule test-fire response contract before reading stage fields.

TestFireStage.data is typed as Record<string, any>, but renderStageDescription depends on backend field names such as q.promql, q.series_count, q.latest_value, tr.exp, tr.fired_groups, data.matched_datasource_ids, and data.host_count. If the /api/n9e/busi-group/${bgid}/alert-rule/test-fire response shape changes, these reads can silently render blank or fallback text instead of failing clearly. Add typed stage detail interfaces or fall back to defensive checks for the fields this UI relies on.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/pages/alertRules/FormNG/components/TestFireModal/index.tsx` around lines
179 - 343, Define typed interfaces or runtime validation for the stage detail
payloads consumed by renderStageDescription, covering fields such as
matched_datasource_ids, host_count, queries, triggers, promql, series_count,
latest_value, exp, and fired_groups. Replace the current unchecked
Record<string, any> reads with the validated or typed structures, and provide
explicit safe fallback behavior when required fields are missing or malformed.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/pages/alertRules/FormNG/components/TestFireModal/index.tsx`:
- Around line 179-343: Define typed interfaces or runtime validation for the
stage detail payloads consumed by renderStageDescription, covering fields such
as matched_datasource_ids, host_count, queries, triggers, promql, series_count,
latest_value, exp, and fired_groups. Replace the current unchecked
Record<string, any> reads with the validated or typed structures, and provide
explicit safe fallback behavior when required fields are missing or malformed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4bce72c9-78d2-48f1-8938-3647beaf04f5

📥 Commits

Reviewing files that changed from the base of the PR and between 33a2041 and d9a8091.

📒 Files selected for processing (9)
  • src/pages/alertRules/FormNG/components/TestFireModal/index.tsx
  • src/pages/alertRules/FormNG/components/TestFireModal/utils.test.ts
  • src/pages/alertRules/FormNG/components/TestFireModal/utils.ts
  • src/pages/alertRules/FormNG/index.tsx
  • src/pages/alertRules/locale/en_US.ts
  • src/pages/alertRules/locale/ja_JP.ts
  • src/pages/alertRules/locale/ru_RU.ts
  • src/pages/alertRules/locale/zh_CN.ts
  • src/pages/alertRules/locale/zh_HK.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/pages/alertRules/locale/ru_RU.ts
  • src/pages/alertRules/locale/zh_HK.ts
  • src/pages/alertRules/locale/ja_JP.ts
  • src/pages/alertRules/FormNG/components/TestFireModal/utils.ts

模拟触发弹窗的 openModal 把初始化逻辑放在 validateFields().then() 里、catch 只提示
「请先完善必填项」,导致初始化过程中的任何异常都被伪装成校验失败:用户看到必填项提示、
弹窗打不开,控制台没有线索。

改成 then(onOk, onErr) 两参形式,让校验失败与初始化异常分流,两条路径都打印原始错误。
顺带跑 prettier 修正同文件的格式。
Comment thread src/pages/alertRules/FormNG/index.tsx Outdated
// datasource_ids 是后端 DB2FE 反填的 Deprecated 展示字段(引擎只认 datasource_queries)。
// 表单里没有它的 UI 绑定,留在 values 里会在切换数据源类型后携带旧数据源 id 提交出去,
// 导致模拟触发解析到错误的数据源
delete processed.datasource_ids;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

应该在上面 processInitialValues 里处理

form.setFieldsValue(newValues);
// setFieldsValue 对数组按索引 merge,重置用的空 values:[] 盖不掉旧值
//(旧 cate 选中的数据源 id 会残留),这里对 datasource_queries 强制整体替换
form.setFields([{ name: 'datasource_queries', value: newValues.datasource_queries }]);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

还是没搞清楚这个用意,但是可以确定这个会破坏上面数据源配置保存草稿的功能

…ialValues

Move the datasource_ids cleanup from FormNG's init useEffect into the
shared DB->form transform (processInitialValues), per review feedback.
datasource_ids is a deprecated DB2FE field (engine only reads
datasource_queries) with no UI binding; stripping it at the transform
layer prevents stale datasource ids from being carried into submit /
test-fire.
@jsers
jsers merged commit dafc9dd into main Jul 24, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants