Skip to content

Add TOOLS_DOMAIN perf metrics job and Prometheus verification#60

Merged
Mehdi-Bl merged 3 commits into
mainfrom
feat/tools-domain-perf-job
Feb 11, 2026
Merged

Add TOOLS_DOMAIN perf metrics job and Prometheus verification#60
Mehdi-Bl merged 3 commits into
mainfrom
feat/tools-domain-perf-job

Conversation

@Mehdi-Bl

@Mehdi-Bl Mehdi-Bl commented Feb 11, 2026

Copy link
Copy Markdown
Contributor

Summary

  • add a pipeline that auto-resolves Pushgateway and Prometheus endpoints from
  • publish stress benchmark metrics with per-scenario deduplication to avoid Pushgateway duplicate-series rejections
  • add Prometheus verification script that validates pushed metrics are visible for the exact job/instance labels
  • wire new commands into , script runner help, and test catalog
  • add unit tests for stress metrics payload generation, perf orchestration, and Prometheus verification

Validation

  • npm run lint
  • npm test -- --runInBand
  • TOOLS_DOMAIN='.114.be.tn' make perf-test (real push + Prometheus verification)

Summary by Sourcery

Introduce an automated performance metrics pipeline that publishes deduplicated stress benchmark metrics to Pushgateway and verifies their visibility in Prometheus.

New Features:

  • Add a performance metrics job script that resolves monitoring endpoints from TOOLS_DOMAIN or explicit URLs, runs stress tests, publishes metrics, and verifies them in Prometheus.
  • Add a Prometheus verification script that queries for stress publish timestamp metrics scoped to specific job and instance labels.

Enhancements:

  • Update stress metrics publishing to include a publish timestamp metric and to emit only the latest record per scenario to avoid duplicate series.
  • Expose script helper functions for reuse and testing, and extend the script runner with new perf- and Prometheus-related commands.

Build:

  • Add Makefile targets for running the perf metrics job, generating stress metrics, and verifying Prometheus metrics.

Documentation:

  • Document new stress, metrics, Prometheus verification, and perf-test commands in the scripts README and tests catalog.

Tests:

  • Add unit tests for the perf metrics job orchestration, stress metrics payload generation and deduplication, and Prometheus verification logic.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added stress/perf commands and Makefile targets for running stress tests, metrics publishing, Prometheus verification, and a perf metrics job.
    • New end-to-end perf metrics workflow with environment-driven Pushgateway and Prometheus integration and a verification utility.
  • Tests

    • Added unit tests for perf workflow, metrics publishing, and Prometheus verification.
  • Documentation

    • Updated docs and help text to document the new testing and verification commands.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@sourcery-ai

sourcery-ai Bot commented Feb 11, 2026

Copy link
Copy Markdown

Reviewer's Guide

Adds an end-to-end performance metrics job that auto-resolves Pushgateway/Prometheus endpoints (including TOOLS_DOMAIN support), deduplicates stress metrics per scenario with a publish timestamp gauge, and introduces a Prometheus verification script plus CLI/Makefile wiring and unit tests for the new behavior.

Sequence diagram for perf-test end-to-end stress metrics publication and verification

sequenceDiagram
  actor Dev as Developer
  participant Make as Makefile_perf-test
  participant Cmd as scripts_index_js
  participant Npm as npm_runner
  participant Perf as run_perf_metrics_job_js
  participant StressTest as npm_test_stress
  participant StressMetrics as npm_stress_metrics
  participant Pub as publish_stress_metrics_js
  participant Push as Pushgateway
  participant Ver as verify_prometheus_metrics_js
  participant Prom as Prometheus

  Dev->>Make: make perf-test
  Make->>Cmd: node scripts/index.js perf-test
  Cmd->>Npm: run npm script perf:test
  Npm->>Perf: node scripts/run-perf-metrics-job.js

  Perf->>Perf: resolveMonitoringEndpoints
  Perf->>Perf: buildDefaultInstanceName
  Perf->>Perf: set env PUSHGATEWAY_URL
  Perf->>Perf: set env PROMETHEUS_URL
  Perf->>Perf: set env PUSHGATEWAY_JOB
  Perf->>Perf: set env PUSHGATEWAY_INSTANCE
  Perf->>Perf: set env STRESS_METRICS_PUBLISH_TS_SECONDS
  Perf->>Perf: set env PROMETHEUS_MIN_PUBLISH_TS_SECONDS

  Perf->>StressTest: run "npm run test:stress" with env
  StressTest-->>Perf: stress benchmarks completed

  Perf->>StressMetrics: run "npm run stress:metrics" with env
  StressMetrics->>Pub: node scripts/publish-stress-metrics.js
  Pub->>Pub: normalizeBenchmarkRecord
  Pub->>Pub: selectLatestRecordPerScenario
  Pub->>Pub: buildPrometheusPayload
  Pub->>Push: push metrics with job and instance labels
  Pub-->>Perf: return success

  Perf->>Ver: waitForStressMetrics(options)
  loop until timeout or metrics present
    Ver->>Prom: HTTP GET /api/v1/query
    Prom-->>Ver: JSON samples for publish_timestamp_seconds
    Ver->>Ver: check values against minPublishTimestampSeconds
  end
  Ver-->>Perf: verified metrics for job and instance

  Perf-->>Npm: return job result
  Npm-->>Cmd: perf:test success
  Cmd-->>Dev: "Performance metrics job completed successfully"
Loading

File-Level Changes

Change Details Files
Deduplicate stress benchmark records per scenario and include a publish timestamp metric in the Prometheus payload, exposing helpers for unit testing.
  • Extend normalized benchmark records with a millisecond capture timestamp to support ordering.
  • Add helper to pick the latest record per scenario using capture time and filename tie-breaker, and use it for metric publishing.
  • Introduce a publish timestamp gauge metric whose value is resolved from CLI options, env var, or current time.
  • Expose internal helpers and main function from the stress metrics script and guard CLI entry point for testing.
scripts/publish-stress-metrics.js
tests/unit/scripts/publish-stress-metrics.test.js
Add a Prometheus verification script that polls for a publish timestamp metric with strict job/instance label matching.
  • Normalize and validate a Prometheus base URL, including automatic https prefix and trailing-slash trimming.
  • Build label-selecting PromQL queries for both job/instance and exported_job/exported_instance variants.
  • Implement JSON HTTP query helper, extraction of numeric values, and a polling loop that waits for metrics to appear above a minimum timestamp, with timeout and configurable polling interval.
  • Export test utilities and main function with a CLI entry wrapper, and add unit tests around query building, threshold waiting, and timeout behavior.
scripts/verify-prometheus-metrics.js
tests/unit/scripts/verify-prometheus-metrics.test.js
Introduce a perf metrics orchestration script that runs stress tests, publishes metrics to Pushgateway, and verifies visibility in Prometheus using TOOLS_DOMAIN-based endpoint resolution.
  • Normalize TOOLS_DOMAIN to a bare host, derive Pushgateway/Prometheus URLs from it when explicit URLs are not provided, and fail fast if endpoints cannot be resolved.
  • Generate a default instance label from hostname and timestamp, and assemble an environment for downstream commands including strict Pushgateway mode and publish/verify timestamps.
  • Run stress tests and metrics publishing via npm scripts, then call the Prometheus verification helper with matching parameters, logging resolved endpoints and labels.
  • Export orchestration helpers for testing and add unit tests covering domain normalization, endpoint resolution, the happy-path flow, and failure when endpoints are missing.
scripts/run-perf-metrics-job.js
tests/unit/scripts/perf-metrics-job.test.js
Wire new perf and verification commands into the script runner, Makefile, npm scripts, help output, and tests catalog.
  • Add CLI cases for running stress tests, building stress metrics, verifying Prometheus, and executing the combined perf job, with success logging.
  • Expose corresponding Makefile targets that delegate to the CLI script.
  • Extend package.json scripts with prometheus:verify and perf:test commands pointing to the new node scripts.
  • Document the new commands and TOOLS_DOMAIN flow in scripts README and tests catalog, and update CLI help text sections for testing & quality.
scripts/index.js
Makefile
package.json
scripts/lib/utils.js
scripts/README.md
tests/catalog.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions

github-actions Bot commented Feb 11, 2026

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Scanned Files

None

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Review Summary by Qodo

Add TOOLS_DOMAIN perf metrics job with Prometheus verification

✨ Enhancement 🧪 Tests

Grey Divider

Walkthroughs

Description
• Add TOOLS_DOMAIN-aware perf metrics job orchestration with auto-resolved endpoints
• Implement Prometheus verification script to validate pushed metrics visibility
• Add per-scenario deduplication to prevent Pushgateway duplicate-series rejections
• Wire new commands into script runner, help text, and Makefile
• Add comprehensive unit tests for metrics, orchestration, and verification
Diagram
flowchart LR
  A["TOOLS_DOMAIN env var"] -->|normalizeToolsDomain| B["Monitoring endpoints"]
  B -->|resolveMonitoringEndpoints| C["Pushgateway + Prometheus URLs"]
  D["Stress benchmarks"] -->|normalizeBenchmarkRecord| E["Benchmark records"]
  E -->|selectLatestRecordPerScenario| F["Deduplicated records"]
  F -->|buildPrometheusPayload| G["Prometheus text format"]
  G -->|publish| C
  C -->|queryPrometheus| H["Verify metrics visible"]
  H -->|waitForStressMetrics| I["Confirmation"]
Loading

Grey Divider

File Changes

1. scripts/index.js ✨ Enhancement +25/-0

Wire perf and stress test commands

scripts/index.js


2. scripts/lib/utils.js 📝 Documentation +4/-0

Add perf metrics commands to help text

scripts/lib/utils.js


3. scripts/publish-stress-metrics.js ✨ Enhancement +98/-7

Add deduplication and publish timestamp metrics

scripts/publish-stress-metrics.js


View more (9)
4. scripts/run-perf-metrics-job.js ✨ Enhancement +143/-0

New orchestration script for TOOLS_DOMAIN perf job

scripts/run-perf-metrics-job.js


5. scripts/verify-prometheus-metrics.js ✨ Enhancement +230/-0

New Prometheus verification script with polling

scripts/verify-prometheus-metrics.js


6. tests/unit/scripts/perf-metrics-job.test.js 🧪 Tests +76/-0

Unit tests for perf metrics job orchestration

tests/unit/scripts/perf-metrics-job.test.js


7. tests/unit/scripts/publish-stress-metrics.test.js 🧪 Tests +75/-0

Unit tests for deduplication and payload generation

tests/unit/scripts/publish-stress-metrics.test.js


8. tests/unit/scripts/verify-prometheus-metrics.test.js 🧪 Tests +65/-0

Unit tests for Prometheus verification logic

tests/unit/scripts/verify-prometheus-metrics.test.js


9. Makefile ⚙️ Configuration changes +10/-1

Add perf-test, stress-metrics, prometheus-verify targets

Makefile


10. package.json ⚙️ Configuration changes +3/-1

Add prometheus:verify and perf:test npm scripts

package.json


11. scripts/README.md 📝 Documentation +4/-0

Document new perf metrics commands and usage

scripts/README.md


12. tests/catalog.md 📝 Documentation +3/-0

Document stress metrics and TOOLS_DOMAIN workflow

tests/catalog.md


Grey Divider

Qodo Logo

@coderabbitai

coderabbitai Bot commented Feb 11, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds a perf/stress metrics workflow: new Make/npm targets and CLI aliases, two new Node scripts to run and verify Prometheus-published metrics, enhancements to metrics publishing, and corresponding unit tests and docs.

Changes

Cohort / File(s) Summary
Build & CLI wiring
Makefile, package.json, scripts/index.js, scripts/lib/utils.js
Added phony Make targets and npm scripts; wired new CLI aliases to npm scripts; updated help text to document stress/perf and prometheus verification commands.
Metrics publishing
scripts/publish-stress-metrics.js
Added capturedAtMs, helpers to parse timestamps and select latest per-scenario, publish_timestamp_seconds metric, safer PUSHGATEWAY_URL handling, test exports, and main export wrapper.
Perf orchestration
scripts/run-perf-metrics-job.js
New orchestrator: resolves endpoints, builds env, runs stress and metrics scripts, waits for verification; exports runPerfMetricsJob and __testUtils.
Prometheus verification
scripts/verify-prometheus-metrics.js
New verifier: builds/promotes metric queries, polls Prometheus HTTP API with timeout/polling, parses numeric values, exposes waitForStressMetrics, main, and __testUtils.
Docs & Tests
scripts/README.md, tests/catalog.md, tests/unit/scripts/*
Documented new commands and env vars; added unit tests for perf-metrics job, publish-stress-metrics helpers, and Prometheus verification behavior.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant CLI as "Make / npm / scripts/index.js"
    participant Orchestrator as "run-perf-metrics-job"
    participant Stress as "npm run test:stress"
    participant Publish as "npm run stress:metrics / publish-stress-metrics"
    participant Pushgateway as "Pushgateway"
    participant Prometheus as "Prometheus"
    participant Verifier as "verify-prometheus-metrics"

    User->>CLI: make perf-test / npm run perf:test
    CLI->>Orchestrator: start runPerfMetricsJob
    Orchestrator->>Stress: run test:stress (env)
    Stress->>Pushgateway: push raw metrics
    Orchestrator->>Publish: run stress:metrics (env)
    Publish->>Pushgateway: publish aggregated/latest metrics
    Prometheus->>Pushgateway: scrape metrics
    Orchestrator->>Verifier: waitForStressMetrics(prometheusUrl, job, instance)
    Verifier->>Prometheus: query /api/v1/query
    Prometheus-->>Verifier: return metric values
    Verifier-->>Orchestrator: verification result
    Orchestrator-->>CLI: success / failure
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰
Hopping through logs with metrics bright,
I stamp timestamps in the quiet night.
Stress runs, Pushgateway hums a tune,
Prometheus sings by the light of the moon.
Perf-test done — carrots for the crew!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main additions: TOOLS_DOMAIN perf metrics job orchestration and Prometheus verification script, which are the core features across the multiple new files and modifications in this PR.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/tools-domain-perf-job

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 and usage tips.

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello @Mehdi-Bl, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request establishes a robust and automated pipeline for collecting, publishing, and verifying performance metrics. By introducing a unified perf-test command and dynamic endpoint resolution, it significantly streamlines the process of integrating stress benchmark results into a Prometheus monitoring system. The changes also improve data quality by ensuring only the most relevant metrics are published and validated, enhancing the overall reliability of performance monitoring.

Highlights

  • New Performance Metrics Job: Introduced a new end-to-end performance metrics job (perf-test) that orchestrates stress tests, publishes metrics to Pushgateway, and verifies their visibility in Prometheus.
  • Dynamic Endpoint Resolution: Implemented automatic resolution of Pushgateway and Prometheus endpoints based on the TOOLS_DOMAIN environment variable, simplifying configuration for different environments.
  • Stress Metrics Deduplication: Enhanced the stress metrics publishing script to deduplicate metrics per scenario, ensuring only the latest benchmark record is pushed to Pushgateway, preventing duplicate series rejections.
  • Prometheus Verification Script: Added a dedicated script (prometheus-verify) to validate that published stress metrics are correctly ingested and visible in Prometheus for specific job and instance labels.
  • Command Line Integration: Integrated the new performance-related commands (perf-test, stress-metrics, prometheus-verify) into the Makefile, package.json scripts, scripts/index.js command runner, and the help documentation.
  • Comprehensive Unit Testing: Added new unit tests for the performance orchestration logic, stress metrics payload generation (including deduplication), and Prometheus verification utilities to ensure reliability.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • Makefile
    • Added perf-test, stress-metrics, and prometheus-verify to the list of phony targets.
    • Introduced new perf-test, stress-metrics, and prometheus-verify commands, mapping them to corresponding Node.js scripts.
  • package.json
    • Added new npm scripts: prometheus:verify to run the Prometheus verification script and perf:test to execute the end-to-end performance metrics job.
  • scripts/README.md
    • Updated the script catalog to include documentation for test:stress, stress:metrics, prometheus:verify, and perf-test commands.
    • Added a note on using TOOLS_DOMAIN with make perf-test for deriving monitoring endpoints.
  • scripts/index.js
    • Implemented new command handlers for test:stress, stress:metrics, prometheus:verify, and perf-test (and their aliases), routing them to the appropriate npm scripts.
  • scripts/lib/utils.js
    • Updated the printHelp function to display descriptions for the new test:stress, stress:metrics, prometheus:verify, and perf-test commands.
  • scripts/publish-stress-metrics.js
    • Added capturedAtMs to the normalized benchmark record for more precise timestamp tracking.
    • Introduced resolvePublishTimestampSeconds to determine the metric publish timestamp from arguments, environment, or current time.
    • Implemented parseCapturedAtMs to safely extract a numeric timestamp from a record.
    • Added selectLatestRecordPerScenario to filter benchmark records, keeping only the latest entry for each unique scenario.
    • Modified buildPrometheusPayload to accept an options object and include a _publish_timestamp_seconds metric.
    • Updated the main function to use selectLatestRecordPerScenario for Prometheus payload generation and to log the number of unique scenario metric sets published.
    • Refactored the script to export its functions for unit testing, moving the main execution logic into an if (require.main === module) block.
  • scripts/run-perf-metrics-job.js
    • Added a new script to orchestrate the full performance metrics job.
    • Implemented toFiniteNumber for robust number parsing.
    • Created normalizeToolsDomain to clean and validate the TOOLS_DOMAIN environment variable.
    • Developed resolveMonitoringEndpoints to automatically determine Pushgateway and Prometheus URLs from TOOLS_DOMAIN or explicit environment variables.
    • Included buildDefaultInstanceName to generate a unique instance name for Pushgateway metrics.
    • Defined runCommand to execute shell commands with specified environment and options.
    • Implemented runPerfMetricsJob to execute stress tests, publish metrics, and then verify them in Prometheus, handling environment variables for configuration.
    • Exported internal functions for testing purposes.
  • scripts/verify-prometheus-metrics.js
    • Added a new script to verify the presence of stress metrics in Prometheus.
    • Implemented toFiniteNumber for numeric parsing.
    • Created trimTrailingSlashes and normalizeBaseUrl for URL handling.
    • Developed escapeLabelValue to properly format Prometheus label values.
    • Included buildMetricQueries to construct Prometheus queries for specific job and instance labels.
    • Implemented requestJson for making HTTP/HTTPS requests and parsing JSON responses.
    • Added extractNumericValues to parse numeric values from Prometheus query results.
    • Defined queryPrometheus to execute a Prometheus query and return numeric results.
    • Implemented sleep for asynchronous delays.
    • Created waitForStressMetrics to poll Prometheus until a matching metric with a sufficient timestamp is found or a timeout occurs.
    • Exported internal functions for testing purposes.
  • tests/catalog.md
    • Added entries for npm run prometheus:verify and npm run perf:test to the test catalog.
    • Included a description of the TOOLS_DOMAIN mode for performance testing.
  • tests/unit/scripts/perf-metrics-job.test.js
    • Added a new unit test file for scripts/run-perf-metrics-job.js.
    • Included tests for normalizeToolsDomain with various inputs.
    • Tested resolveMonitoringEndpoints to ensure correct URL derivation from TOOLS_DOMAIN.
    • Verified the end-to-end runPerfMetricsJob flow, including command execution and Prometheus verification calls.
    • Added a test case for failure when monitoring endpoints cannot be resolved.
  • tests/unit/scripts/publish-stress-metrics.test.js
    • Added a new unit test file for scripts/publish-stress-metrics.js.
    • Included a test for selectLatestRecordPerScenario to confirm correct deduplication of benchmark records.
    • Verified that buildPrometheusPayload correctly includes the publish timestamp metric.
  • tests/unit/scripts/verify-prometheus-metrics.test.js
    • Added a new unit test file for scripts/verify-prometheus-metrics.js.
    • Included a test for buildMetricQueries to ensure correct Prometheus query string generation.
    • Tested waitForStressMetrics to confirm it waits for metrics with a publish timestamp at or above a specified threshold.
    • Added a test case to verify that waitForStressMetrics correctly times out when no matching metrics are found.
Activity
  • No human activity has been recorded on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@sourcery-ai sourcery-ai 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.

Hey - I've found 1 issue, and left some high level feedback:

  • There are several small helpers that are now duplicated across scripts (e.g., toFiniteNumber, trimTrailingSlashes, numeric/time helpers); consider extracting them into a shared utility module for consistency and easier maintenance.
  • In waitForStressMetrics, the timeout error only reports that no samples matched; including which queries were attempted (job vs exported_job variants) in the error message would make diagnosing label/selector issues in Prometheus much easier.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- There are several small helpers that are now duplicated across scripts (e.g., `toFiniteNumber`, `trimTrailingSlashes`, numeric/time helpers); consider extracting them into a shared utility module for consistency and easier maintenance.
- In `waitForStressMetrics`, the timeout error only reports that no samples matched; including which queries were attempted (job vs exported_job variants) in the error message would make diagnosing label/selector issues in Prometheus much easier.

## Individual Comments

### Comment 1
<location> `scripts/verify-prometheus-metrics.js:52-61` </location>
<code_context>
+function requestJson(endpointUrl) {
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Add a request timeout when calling Prometheus to avoid hanging indefinitely on network issues.

Since this request doesn’t set a timeout, a stalled connection could cause the script to hang even if `waitForStressMetrics` times out. Please add a `request.setTimeout(...)` that aborts the request and rejects the promise so the higher-level timeout can take effect under bad network conditions.

Suggested implementation:

```javascript
const REQUEST_TIMEOUT_MS = 10000; // 10 seconds

function requestJson(endpointUrl) {

```

```javascript
    const request = client.request(
      endpointUrl,
      { method: 'GET' },
      (response) => {

```

```javascript
      (response) => {
        const responseChunks = [];

```

```javascript
        response.on('data', (chunk) => responseChunks.push(chunk));

```

```javascript
        response.on('end', () => {
          const responseBody = Buffer.concat(responseChunks).toString('utf8');

```

```javascript
    const client = endpointUrl.protocol === 'https:' ? https : http;
    const request = client.request(
      endpointUrl,
      { method: 'GET' },
      (response) => {
        const responseChunks = [];
        response.on('data', (chunk) => responseChunks.push(chunk));
        response.on('end', () => {
          const responseBody = Buffer.concat(responseChunks).toString('utf8');
        });
      }
    );

    request.setTimeout(REQUEST_TIMEOUT_MS, () => {
      request.abort();
      reject(
        new Error(
          `Request to ${endpointUrl.href} timed out after ${REQUEST_TIMEOUT_MS} ms`
        )
      );
    });

```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread scripts/verify-prometheus-metrics.js Outdated

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@scripts/verify-prometheus-metrics.js`:
- Around line 52-87: The requestJson function lacks a per-request timeout so a
hung HTTP connection can block the whole script; fix by adding a configurable
timeout (e.g., const REQUEST_TIMEOUT_MS = 30_000) and applying it to the created
request (use request.setTimeout(REQUEST_TIMEOUT_MS, () => { request.destroy(new
Error(`Request timeout after ${REQUEST_TIMEOUT_MS}ms`)) }) or pass the timeout
option) and also handle the request 'error'/'timeout' events to reject with a
clear error; update the rejection message produced by requestJson to include
that it was a timeout when applicable and ensure any response listeners are
cleaned up when aborting the request.
🧹 Nitpick comments (3)
scripts/run-perf-metrics-job.js (1)

11-14: toFiniteNumber is duplicated across three scripts.

This helper now exists in publish-stress-metrics.js, verify-prometheus-metrics.js, and this file. Consider extracting it into a shared module (e.g., scripts/lib/metric-utils.js) to keep the tooling DRY.

tests/unit/scripts/verify-prometheus-metrics.test.js (1)

20-43: Consider asserting the resolved metric value in the success test.

The test verifies result.query contains exported_job= and that queryFn was called, but doesn't assert on the returned metric values (e.g., that the resolved timestamp 1_700_000_005 is captured in the result). Adding an assertion like expect(result.values).toContain(1_700_000_005) (or equivalent for the result shape) would strengthen confidence that the return contract is correct.

tests/unit/scripts/perf-metrics-job.test.js (1)

71-75: Consider testing with a malformed TOOLS_DOMAIN (not just missing).

The fast-fail test passes an empty env, which validates the "no domain at all" path. You might also want a case where TOOLS_DOMAIN is set but invalid (e.g., { TOOLS_DOMAIN: 'http://' }) to confirm the orchestrator surfaces the normalization error rather than silently producing broken URLs. This aligns with the normalizeToolsDomain rejection test on line 12 but at the orchestration level.

Comment thread scripts/verify-prometheus-metrics.js Outdated
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Feb 11, 2026

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (3) 📎 Requirement gaps (0)

Grey Divider


Action required

✅ 1. requestJson() lacks timeout 📘 Rule violation ⛯ Reliability
Description
The Prometheus HTTP request has no socket/request timeout, so a stalled connection can hang longer
than the intended verification timeoutMs. This violates the requirement to handle external
dependency failure modes robustly.
Code

scripts/verify-prometheus-metrics.js[R52-86]

+function requestJson(endpointUrl) {
+  return new Promise((resolve, reject) => {
+    const client = endpointUrl.protocol === 'https:' ? https : http;
+    const request = client.request(
+      endpointUrl,
+      { method: 'GET' },
+      (response) => {
+        const responseChunks = [];
+        response.on('data', (chunk) => responseChunks.push(chunk));
+        response.on('end', () => {
+          const responseBody = Buffer.concat(responseChunks).toString('utf8');
+          if (!response.statusCode || response.statusCode < 200 || response.statusCode >= 300) {
+            reject(
+              new Error(
+                `Prometheus returned ${response.statusCode || 'unknown status'}${
+                  responseBody ? `: ${responseBody}` : ''
+                }`
+              )
+            );
+            return;
+          }
+
+          try {
+            resolve(JSON.parse(responseBody));
+          } catch (error) {
+            const safeMessage = error instanceof Error ? error.message : String(error);
+            reject(new Error(`Failed to parse Prometheus response: ${safeMessage}`));
+          }
+        });
+      }
+    );
+
+    request.on('error', (error) => reject(error));
+    request.end();
+  });
Evidence
Compliance requires handling external dependency failure points (timeouts/hangs). The new
requestJson() issues an HTTP(S) request and never sets a timeout/abort, meaning it can hang
indefinitely on network stalls.

Rule 3: Generic: Robust Error Handling and Edge Case Management
scripts/verify-prometheus-metrics.js[52-86]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`scripts/verify-prometheus-metrics.js` makes HTTP(S) requests without any explicit timeout/abort handling. A stalled TCP connection or slow server can cause the verification flow to hang longer than `timeoutMs`.
## Issue Context
This script is used to verify that pushed metrics appear in Prometheus. It should degrade gracefully when Prometheus is unreachable or slow.
## Fix Focus Areas
- scripts/verify-prometheus-metrics.js[52-86]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Logs print raw endpoints 📘 Rule violation ⛨ Security
Description
The perf job logs full pushgatewayUrl/prometheusUrl, which may include credentials (userinfo) or
tokens (query params) if configured that way in env. This violates secure logging requirements by
potentially exposing secrets and also produces unstructured logs.
Code

scripts/run-perf-metrics-job.js[R95-101]

+  if (toolsDomain) {
+    logger.log(`Resolved monitoring endpoints from TOOLS_DOMAIN=${toolsDomain}`);
+  }
+  logger.log(`Pushgateway endpoint: ${pushgatewayUrl}`);
+  logger.log(`Prometheus endpoint: ${prometheusUrl}`);
+  logger.log(`Pushgateway job="${jobName}" instance="${instanceName}"`);
+
Evidence
The secure logging rule forbids sensitive data in logs and expects structured logging. The added
code logs raw URLs sourced from environment variables without redaction, and uses plain string
logging.

Rule 5: Generic: Secure Logging Practices
scripts/run-perf-metrics-job.js[95-101]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The perf metrics job logs raw endpoint URLs that come from environment variables; these URLs may contain secrets (e.g., basic auth userinfo or query tokens). This creates a risk of leaking credentials into logs.
## Issue Context
`pushgatewayUrl` / `prometheusUrl` can be provided via `PUSHGATEWAY_URL` / `PROMETHEUS_URL`. Some deployments embed credentials in URLs.
## Fix Focus Areas
- scripts/run-perf-metrics-job.js[95-101]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

✅ 3. Errors expose Prometheus body 📘 Rule violation ⛨ Security
Description
On non-2xx responses, the code includes the full Prometheus response body in the thrown error, which
is printed to stderr by the CLI. This risks leaking internal implementation details in user-visible
output.
Code

scripts/verify-prometheus-metrics.js[R63-70]

+          if (!response.statusCode || response.statusCode < 200 || response.statusCode >= 300) {
+            reject(
+              new Error(
+                `Prometheus returned ${response.statusCode || 'unknown status'}${
+                  responseBody ? `: ${responseBody}` : ''
+                }`
+              )
+            );
Evidence
Secure error handling requires avoiding exposing internal details to end users. The new error
message concatenates the raw HTTP response body into the thrown error, and the CLI prints
error.message to stderr.

Rule 4: Generic: Secure Error Handling
scripts/verify-prometheus-metrics.js[63-70]
scripts/verify-prometheus-metrics.js[224-229]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The Prometheus verification script includes full HTTP response bodies in thrown errors, and the CLI prints these messages directly. This can expose internal details.
## Issue Context
Non-2xx responses may include HTML, stack traces, or other internal content. CLI output should remain generic by default.
## Fix Focus Areas
- scripts/verify-prometheus-metrics.js[63-70]
- scripts/verify-prometheus-metrics.js[224-229]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Pushgateway URL not normalized 🐞 Bug ✓ Correctness
Description
perf-test accepts PUSHGATEWAY_URL verbatim (trimmed only), but metric publishing requires an
absolute URL parseable by new URL(). A common value like pushgateway.example.internal (no
scheme) will fail at runtime with an “Invalid URL” error.
Code

scripts/run-perf-metrics-job.js[R33-38]

+function resolveMonitoringEndpoints(environment) {
+  const env = environment || process.env;
+  const toolsDomain = normalizeToolsDomain(env.TOOLS_DOMAIN || '');
+  const pushgatewayUrl = (env.PUSHGATEWAY_URL || '').trim() || (toolsDomain ? `https://pushgateway.${toolsDomain}` : '');
+  const prometheusUrl = (env.PROMETHEUS_URL || '').trim() || (toolsDomain ? `https://prometheus.${toolsDomain}` : '');
+
Evidence
resolveMonitoringEndpoints forwards PUSHGATEWAY_URL without adding a scheme, while
publish-stress-metrics uses new URL(baseUrl) which throws for URLs missing http:// or
https://. In contrast, Prometheus URL handling *does* normalize missing schemes, creating an
inconsistent UX where only Pushgateway fails on bare hosts.

scripts/run-perf-metrics-job.js[33-38]
scripts/publish-stress-metrics.js[251-256]
scripts/verify-prometheus-metrics.js[24-36]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`PUSHGATEWAY_URL` is used as-is in the perf-test flow, but publishing calls `new URL(baseUrl)` which throws if the scheme is missing. This makes `perf-test`/`stress:metrics` brittle and user-hostile for common env values like `pushgateway.my-domain`.
### Issue Context
Prometheus URL already gets scheme normalization in `verify-prometheus-metrics.js`, but Pushgateway URL does not, creating inconsistent behavior.
### Fix Focus Areas
- scripts/run-perf-metrics-job.js[33-43]
- scripts/publish-stress-metrics.js[251-256]
### Suggested approach
1. Add a small helper (either in `run-perf-metrics-job.js` or `publish-stress-metrics.js`) to normalize Pushgateway base URLs:
- trim
- if missing `http://` or `https://`, prefix `https://` (or make scheme configurable)
2. Validate early and throw an explicit error (e.g., `PUSHGATEWAY_URL must include http:// or https://`) rather than letting `new URL()` throw a generic `Invalid URL`.
3. (Optional) Update docs (`tests/catalog.md` / scripts README) to show example values with scheme.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

Comment thread scripts/verify-prometheus-metrics.js Outdated
Comment on lines +52 to +86
function requestJson(endpointUrl) {
return new Promise((resolve, reject) => {
const client = endpointUrl.protocol === 'https:' ? https : http;
const request = client.request(
endpointUrl,
{ method: 'GET' },
(response) => {
const responseChunks = [];
response.on('data', (chunk) => responseChunks.push(chunk));
response.on('end', () => {
const responseBody = Buffer.concat(responseChunks).toString('utf8');
if (!response.statusCode || response.statusCode < 200 || response.statusCode >= 300) {
reject(
new Error(
`Prometheus returned ${response.statusCode || 'unknown status'}${
responseBody ? `: ${responseBody}` : ''
}`
)
);
return;
}

try {
resolve(JSON.parse(responseBody));
} catch (error) {
const safeMessage = error instanceof Error ? error.message : String(error);
reject(new Error(`Failed to parse Prometheus response: ${safeMessage}`));
}
});
}
);

request.on('error', (error) => reject(error));
request.end();
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

1. requestjson() lacks timeout 📘 Rule violation ⛯ Reliability

The Prometheus HTTP request has no socket/request timeout, so a stalled connection can hang longer
than the intended verification timeoutMs. This violates the requirement to handle external
dependency failure modes robustly.
Agent Prompt
## Issue description
`scripts/verify-prometheus-metrics.js` makes HTTP(S) requests without any explicit timeout/abort handling. A stalled TCP connection or slow server can cause the verification flow to hang longer than `timeoutMs`.

## Issue Context
This script is used to verify that pushed metrics appear in Prometheus. It should degrade gracefully when Prometheus is unreachable or slow.

## Fix Focus Areas
- scripts/verify-prometheus-metrics.js[52-86]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +95 to +101
if (toolsDomain) {
logger.log(`Resolved monitoring endpoints from TOOLS_DOMAIN=${toolsDomain}`);
}
logger.log(`Pushgateway endpoint: ${pushgatewayUrl}`);
logger.log(`Prometheus endpoint: ${prometheusUrl}`);
logger.log(`Pushgateway job="${jobName}" instance="${instanceName}"`);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

2. Logs print raw endpoints 📘 Rule violation ⛨ Security

The perf job logs full pushgatewayUrl/prometheusUrl, which may include credentials (userinfo) or
tokens (query params) if configured that way in env. This violates secure logging requirements by
potentially exposing secrets and also produces unstructured logs.
Agent Prompt
## Issue description
The perf metrics job logs raw endpoint URLs that come from environment variables; these URLs may contain secrets (e.g., basic auth userinfo or query tokens). This creates a risk of leaking credentials into logs.

## Issue Context
`pushgatewayUrl` / `prometheusUrl` can be provided via `PUSHGATEWAY_URL` / `PROMETHEUS_URL`. Some deployments embed credentials in URLs.

## Fix Focus Areas
- scripts/run-perf-metrics-job.js[95-101]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces an automated performance metrics pipeline, including stress test execution, metric publishing to Pushgateway, and verification in Prometheus. The changes are well-structured, testable, and include comprehensive unit tests and documentation updates. I've identified a potential bug in endpoint resolution and a few areas where the code can be made more readable and maintainable. Overall, this is a solid contribution.

}

return value.slice(startIndex, endIndex);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

Using parsed.host can unintentionally include the port number from the TOOLS_DOMAIN URL. For example, if TOOLS_DOMAIN is example.com:8443, parsed.host would be example.com:8443. This would lead to incorrectly constructed URLs like https://pushgateway.example.com:8443, which is likely not the desired behavior. You should use parsed.hostname instead, which contains the host name without the port, to ensure correct endpoint resolution.

Suggested change
}
const normalizedHost = parsed.hostname.replace(/^\.+/, '').replace(/\.+$/, '').trim().toLowerCase();

async function runPerfMetricsJob(options = {}) {
const env = options.env || process.env;
const nowFn = options.nowFn || Date.now;
const hostName = options.hostName || os.hostname();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

This line is functionally correct but a bit dense and hard to read. To improve readability and maintainability, you could rewrite this to more clearly express the intent, which is to default to true unless explicitly set to false.

Suggested change
const hostName = options.hostName || os.hostname();
const strictMode = String((env.PUSHGATEWAY_STRICT || 'true').trim().toLowerCase() !== 'false');

Comment on lines +15 to +22
function trimTrailingSlashes(value) {
let lastIndex = value.length;
while (lastIndex > 0 && value[lastIndex - 1] === '/') {
lastIndex -= 1;
}

return value.slice(0, lastIndex);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

This function can be simplified and made more concise by using a regular expression to remove trailing slashes. This improves readability and is a more idiomatic way to perform this kind of string manipulation in JavaScript.

function trimTrailingSlashes(value) {
  return String(value).replace(/\/+$/, '');
}

Comment on lines +89 to +105
function extractNumericValues(resultSet) {
if (!Array.isArray(resultSet)) {
return [];
}

const values = [];
for (const resultItem of resultSet) {
if (Array.isArray(resultItem?.value) && resultItem.value.length >= 2) {
const parsedValue = toFiniteNumber(resultItem.value[1]);
if (parsedValue !== null) {
values.push(parsedValue);
}
}
}

return values;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

This function can be written more concisely using modern JavaScript functional array methods like flatMap. This would make the code more declarative and easier to read and maintain.

function extractNumericValues(resultSet) {
  return (resultSet || []).flatMap((item) => {
    const value = item?.value?.[1];
    const num = toFiniteNumber(value);
    return num === null ? [] : [num];
  });
}

@sonarqubecloud

Copy link
Copy Markdown

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@scripts/run-perf-metrics-job.js`:
- Around line 134-135: The timeout and poll interval variables (timeoutMs and
pollIntervalMs) accept negative values because toFiniteNumber returns negatives
and the `||` fallback only covers falsy zeros; change the assignment to clamp to
a positive number by validating the parsed value from
toFiniteNumber(env.PROMETHEUS_VERIFY_TIMEOUT_MS) and
toFiniteNumber(env.PROMETHEUS_VERIFY_POLL_INTERVAL_MS) and using the default
only if the parsed value is not a finite positive (> 0) number (e.g., replace
the current expressions with a small helper or inline check that uses the parsed
value if > 0, otherwise uses 60_000 and 5_000 respectively).
🧹 Nitpick comments (3)
scripts/run-perf-metrics-job.js (3)

11-14: toFiniteNumber is duplicated from verify-prometheus-metrics.js.

This identical function already exists in scripts/verify-prometheus-metrics.js (line 11). Consider extracting it into a shared utility module to avoid drift between the two copies.

#!/bin/bash
# Verify the duplication
ast-grep --pattern 'function toFiniteNumber($_) { $$$ }'

31-50: normalizeEndpointUrl and normalizeToolsDomain share similar URL-parsing boilerplate.

Both functions trim input, prepend https:// if missing, and parse with new URL(...). This is a minor duplication — could be consolidated with a shared parse step. Not urgent given the functions serve different purposes (one returns full URL, the other extracts hostname).

Also applies to: 66-81


194-200: Stack trace is discarded on failure.

Only error.message is logged. For CI debugging, the full stack can be valuable. Consider logging the stack at a debug/verbose level or when a --verbose flag is set.

Optional: include stack trace
   runPerfMetricsJob().catch((error) => {
     const safeMessage = error instanceof Error ? error.message : String(error);
     console.error(`Performance metrics job failed: ${safeMessage}`);
+    if (error instanceof Error && error.stack) {
+      console.error(error.stack);
+    }
     process.exit(1);
   });

Comment on lines +134 to +135
const timeoutMs = toFiniteNumber(env.PROMETHEUS_VERIFY_TIMEOUT_MS) || 60_000;
const pollIntervalMs = toFiniteNumber(env.PROMETHEUS_VERIFY_POLL_INTERVAL_MS) || 5_000;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Negative environment values would be accepted as valid timeouts.

toFiniteNumber converts any finite number (including negatives), and the || default fallback only triggers on 0 or null. If someone sets PROMETHEUS_VERIFY_TIMEOUT_MS=-1, it would be used as-is, which could cause unexpected behavior in the polling loop.

Proposed fix: clamp to positive values
-  const timeoutMs = toFiniteNumber(env.PROMETHEUS_VERIFY_TIMEOUT_MS) || 60_000;
-  const pollIntervalMs = toFiniteNumber(env.PROMETHEUS_VERIFY_POLL_INTERVAL_MS) || 5_000;
+  const rawTimeout = toFiniteNumber(env.PROMETHEUS_VERIFY_TIMEOUT_MS);
+  const timeoutMs = rawTimeout != null && rawTimeout > 0 ? rawTimeout : 60_000;
+  const rawPoll = toFiniteNumber(env.PROMETHEUS_VERIFY_POLL_INTERVAL_MS);
+  const pollIntervalMs = rawPoll != null && rawPoll > 0 ? rawPoll : 5_000;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const timeoutMs = toFiniteNumber(env.PROMETHEUS_VERIFY_TIMEOUT_MS) || 60_000;
const pollIntervalMs = toFiniteNumber(env.PROMETHEUS_VERIFY_POLL_INTERVAL_MS) || 5_000;
const rawTimeout = toFiniteNumber(env.PROMETHEUS_VERIFY_TIMEOUT_MS);
const timeoutMs = rawTimeout != null && rawTimeout > 0 ? rawTimeout : 60_000;
const rawPoll = toFiniteNumber(env.PROMETHEUS_VERIFY_POLL_INTERVAL_MS);
const pollIntervalMs = rawPoll != null && rawPoll > 0 ? rawPoll : 5_000;
🤖 Prompt for AI Agents
In `@scripts/run-perf-metrics-job.js` around lines 134 - 135, The timeout and poll
interval variables (timeoutMs and pollIntervalMs) accept negative values because
toFiniteNumber returns negatives and the `||` fallback only covers falsy zeros;
change the assignment to clamp to a positive number by validating the parsed
value from toFiniteNumber(env.PROMETHEUS_VERIFY_TIMEOUT_MS) and
toFiniteNumber(env.PROMETHEUS_VERIFY_POLL_INTERVAL_MS) and using the default
only if the parsed value is not a finite positive (> 0) number (e.g., replace
the current expressions with a small helper or inline check that uses the parsed
value if > 0, otherwise uses 60_000 and 5_000 respectively).

@Mehdi-Bl Mehdi-Bl merged commit 80e2363 into main Feb 11, 2026
17 checks passed
@Mehdi-Bl Mehdi-Bl deleted the feat/tools-domain-perf-job branch February 11, 2026 03:16
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.

1 participant