Skip to content

fix: metrics aggregator stops collecting metrics - #4441

Merged
atzoum merged 3 commits into
developfrom
fix.metricsAggregator
Jul 1, 2025
Merged

atzoum merged 3 commits into
developfrom
fix.metricsAggregator

Conversation

@atzoum

@atzoum atzoum commented Jun 30, 2025 •

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

There were a number of issues with the current metrics aggregator implementation that this pull request is fixing:

  • If the running request didn't complete for whatever reason, aggregator was being stuck not trying to aggregate anymore. Now we are using a configurable METRICS_AGGREGATOR_REQUEST_TIMEOUT_SECONDS=10, after which a new aggregation request will be allowed.
  • In case of worker errors the aggregator's state could become corrupted, since it could associate old responses with newer requests. Now we're using a requestId so that aggregator ignores responses for previous request ids.
  • A lot of error conditions were being unhandled, e.g. an error while sending to a worker or the aggregator thread, or trying to send to a disconnected worker.
  • Worker thread wasn't being monitored for errors/exits. Now we are recreating the worker thread if it exits unexpectedly.

Additionally, bumping prom-client to latest version:

After all these changes, it is still possible for metrics aggregation to fail continuously, e.g. in case there is a stuck (busy) worker. This scenario however should be handled through a future change, where we'll be introducing a cluster manager which is going to be able to detect stuck workers not responding to ping requests and restart them or even shutdown the pod.

resolves INT-3872

@coderabbitai

coderabbitai Bot commented Jun 30, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Added a configurable request timeout to prevent indefinite waiting during metric aggregation.
    • Introduced improved request tracking and response validation for more robust metric aggregation.
    • Enabled automatic diagnostic report generation on receiving a specific signal to aid in debugging.
  • Bug Fixes

    • Improved error handling and resilience when communicating between processes and threads.
  • Chores

    • Excluded a utility file from code analysis to streamline quality checks.

Summary by CodeRabbit

  • New Features

    • Added a configurable request timeout to prevent hanging metric aggregation requests.
    • Improved request tracking with unique request IDs for each aggregation request.
    • Enhanced worker management with automatic restarts and safer shutdown procedures.
  • Bug Fixes

    • Enhanced error handling and resilience when communicating between threads and processes.
    • Prevented race conditions and stale responses by correlating requests and responses using unique IDs.
    • Ensured only connected workers are used for metric aggregation, skipping disconnected ones.
    • Improved handling of concurrent requests by rejecting overlapping aggregation attempts.
  • Chores

    • Added detailed logging for request tracking, error cases, and worker lifecycle events.
    • Excluded src/util/worker.js from SonarQube analysis.
    • Enabled Node.js diagnostic reporting on SIGUSR2 signal for better debugging.

Walkthrough

The changes implement a request ID mechanism and timeout handling in the MetricsAggregator class to improve the robustness of metric aggregation across worker threads. The update also enhances error handling, ensures only connected workers are used, synchronizes request/response pairs using request IDs, and adds worker lifecycle event handling including automatic restarts. Worker responses now include the request ID for accurate correlation. Additionally, src/util/worker.js is excluded from SonarQube analysis, and Node.js diagnostic reporting on SIGUSR2 is enabled in the cluster management.

Changes

File(s) Change Summary
src/util/metricsAggregator.js Added request ID tracking, timeout handling, concurrency checks, error resilience, improved worker communication, lifecycle event handling, and safer shutdown.
src/util/worker.js Modified message handler to include request ID in aggregation responses for accurate correlation.
sonar-project.properties Excluded src/util/worker.js from SonarQube analysis.
src/util/cluster.js Enabled Node.js diagnostic reporting on SIGUSR2 signal.

Suggestions for Improvements

  • Consider extracting repeated logging logic into utility functions for consistency and easier maintenance.
  • Add unit tests to cover edge cases such as timeouts, worker disconnections, invalid request IDs, and concurrent request rejection.
  • Document the request ID mechanism, timeout handling, and worker restart strategies in code comments or developer documentation for clarity.
  • Evaluate if the default timeout duration (10 seconds) suits all deployment environments and make it easily configurable.
  • Monitor the performance impact of frequent worker restarts and consider exponential backoff or alerting for persistent failures.

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 276deaf and 63cfb12.

⛔ Files ignored due to path filters (2)
  • package-lock.json is excluded by !**/package-lock.json, !**/*.json
  • package.json is excluded by !**/*.json
📒 Files selected for processing (1)
  • src/util/cluster.js (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/util/cluster.js
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov

codecov Bot commented Jun 30, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 92.00000% with 6 lines in your changes missing coverage. Please review.

Project coverage is 91.18%. Comparing base (bca73c4) to head (63cfb12).
Report is 9 commits behind head on develop.

Files with missing lines Patch % Lines
src/util/metricsAggregator.js 92.00% 5 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4441      +/-   ##
===========================================
+ Coverage    91.14%   91.18%   +0.04%     
===========================================
  Files          638      638              
  Lines        33484    33539      +55     
  Branches      7903     7918      +15     
===========================================
+ Hits         30519    30584      +65     
+ Misses        2726     2686      -40     
- Partials       239      269      +30     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@atzoum
atzoum force-pushed the fix.metricsAggregator branch 3 times, most recently from 0102fbc to 2068d78 Compare June 30, 2025 08:18
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@atzoum
atzoum marked this pull request as ready for review June 30, 2025 08:37
@atzoum
atzoum requested review from a team as code owners June 30, 2025 08:37

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/util/metricsAggregator.js (2)

15-17: Consider adding validation for the parsed timeout value.

The current implementation could result in NaN if the environment variable contains an invalid value.

-  requestTimeout: process.env.METRICS_AGGREGATOR_REQUEST_TIMEOUT_SECONDS
-    ? parseInt(process.env.METRICS_AGGREGATOR_REQUEST_TIMEOUT_SECONDS, 10) * 1000
-    : 10 * 1000, // default to 10 seconds
+  requestTimeout: (() => {
+    const envValue = process.env.METRICS_AGGREGATOR_REQUEST_TIMEOUT_SECONDS;
+    if (envValue) {
+      const parsed = parseInt(envValue, 10);
+      return isNaN(parsed) ? 10 * 1000 : parsed * 1000;
+    }
+    return 10 * 1000; // default to 10 seconds
+  })(),

103-137: Consider adding tests for error handling paths.

Static analysis indicates several error handling paths lack test coverage. While these can be challenging to test, consider adding tests for critical scenarios:

  • Worker thread exit and restart
  • Request timeout handling
  • Disconnected worker handling
  • Message sending failures

Would you like me to help generate unit tests for these error scenarios?

Also applies to: 209-213, 225-226, 250-251

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa8e0c4 and 2068d78d3b04650c85763f6d88053fd61d3c11f2.

⛔ Files ignored due to path filters (1)
  • test/__tests__/metricsAggregator.test.js is excluded by !**/test/**
📒 Files selected for processing (2)
  • src/util/metricsAggregator.js (6 hunks)
  • src/util/worker.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.js`: Focus on ESLint errors (max 3) and warnings (max 5).

**/*.js: Focus on ESLint errors (max 3) and warnings (max 5).

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • src/util/worker.js
  • src/util/metricsAggregator.js
🧠 Learnings (2)
src/util/worker.js (2)
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.
src/util/metricsAggregator.js (2)
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.
🧬 Code Graph Analysis (2)
src/util/worker.js (1)
src/util/metricsAggregator.js (1)
  • MESSAGE_TYPES (6-12)
src/util/metricsAggregator.js (3)
src/util/prometheus.js (1)
  • logger (2-2)
src/util/cluster.js (2)
  • logger (3-3)
  • cluster (1-1)
src/routes/metricsRouter.js (1)
  • logger (2-2)
🪛 GitHub Check: codecov/patch
src/util/metricsAggregator.js

[warning] 16-16: src/util/metricsAggregator.js#L16
Added line #L16 was not covered by tests


[warning] 58-58: src/util/metricsAggregator.js#L58
Added line #L58 was not covered by tests


[warning] 104-104: src/util/metricsAggregator.js#L104
Added line #L104 was not covered by tests


[warning] 107-107: src/util/metricsAggregator.js#L107
Added line #L107 was not covered by tests


[warning] 110-111: src/util/metricsAggregator.js#L110-L111
Added lines #L110 - L111 were not covered by tests


[warning] 114-114: src/util/metricsAggregator.js#L114
Added line #L114 was not covered by tests


[warning] 126-126: src/util/metricsAggregator.js#L126
Added line #L126 was not covered by tests


[warning] 128-128: src/util/metricsAggregator.js#L128
Added line #L128 was not covered by tests


[warning] 209-209: src/util/metricsAggregator.js#L209
Added line #L209 was not covered by tests


[warning] 212-213: src/util/metricsAggregator.js#L212-L213
Added lines #L212 - L213 were not covered by tests


[warning] 225-226: src/util/metricsAggregator.js#L225-L226
Added lines #L225 - L226 were not covered by tests


[warning] 250-251: src/util/metricsAggregator.js#L250-L251
Added lines #L250 - L251 were not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Run Ingestion Service Test / ingestion-service-test
🔇 Additional comments (3)
src/util/worker.js (1)

10-20: LGTM! Request ID propagation is correctly implemented.

The addition of requestId to both success and error responses enables proper request-response correlation between the master and worker threads.

src/util/metricsAggregator.js (2)

103-137: Excellent implementation of worker thread resilience and request tracking.

The addition of requestId validation, error handling, and automatic worker thread restart significantly improves the robustness of the metrics aggregator. The shuttingDown flag appropriately suppresses logs during graceful shutdown.


169-180: Move the pending requests reset to avoid potential race condition.

The pendingMetricRequests reset should happen before setting up the timeout to ensure accurate counting.

+      this.pendingMetricRequests = 0; // Reset pending requests count
       // Add timeout to prevent hanging forever
       this.currentTimeout = setTimeout(() => {
         if (this.requestId === currentRequestId && this.resolveFunc) {
           logger.error(
             `[MetricsAggregator] Request (id: ${this.requestId}) timed out after ${config.requestTimeout / 1000} seconds (pending requests: ${this.pendingMetricRequests})`,
           );
           this.rejectFunc(new Error('Metrics request timed out'));
           this.resetAggregator();
         }
       }, config.requestTimeout);

-      this.pendingMetricRequests = 0; // Reset pending requests count
⛔ Skipped due to learnings
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.

@atzoum
atzoum force-pushed the fix.metricsAggregator branch from 2068d78 to 66ea030 Compare June 30, 2025 09:05
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@atzoum
atzoum force-pushed the fix.metricsAggregator branch from 66ea030 to 595b99d Compare June 30, 2025 09:27

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/util/metricsAggregator.js (2)

154-154: Fix typo in comment.

The comment contains a grammatical error.

-    // We dont support concurrent /metrics requests.
+    // We don't support concurrent /metrics requests.

169-178: Consider extracting timeout logic for better testability.

While the current timeout implementation is correct, extracting it into a separate method could improve testability and readability.

+  setupRequestTimeout(currentRequestId) {
+    this.currentTimeout = setTimeout(() => {
+      if (this.requestId === currentRequestId && this.resolveFunc) {
+        logger.error(
+          `[MetricsAggregator] Request (id: ${this.requestId}) timed out after ${config.requestTimeout / 1000} seconds (pending requests: ${this.pendingMetricRequests})`
+        );
+        this.rejectFunc(new Error('Metrics request timed out'));
+        this.resetAggregator();
+      }
+    }, config.requestTimeout);
+  }

Then in aggregateMetrics:

-      // Add timeout to prevent hanging forever
-      this.currentTimeout = setTimeout(() => {
-        if (this.requestId === currentRequestId && this.resolveFunc) {
-          logger.error(
-            `[MetricsAggregator] Request (id: ${this.requestId}) timed out after ${config.requestTimeout / 1000} seconds (pending requests: ${this.pendingMetricRequests})`,
-          );
-          this.rejectFunc(new Error('Metrics request timed out'));
-          this.resetAggregator();
-        }
-      }, config.requestTimeout);
+      this.setupRequestTimeout(currentRequestId);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 66ea030da0c6ac4b24cf1e8dd9e7df66c8f5aca7 and 595b99d44ba4be6ea7e233b9f8697041f45dbd1e.

⛔ Files ignored due to path filters (1)
  • test/__tests__/metricsAggregator.test.js is excluded by !**/test/**
📒 Files selected for processing (2)
  • src/util/metricsAggregator.js (6 hunks)
  • src/util/worker.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/util/worker.js
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.js`: Focus on ESLint errors (max 3) and warnings (max 5).

**/*.js: Focus on ESLint errors (max 3) and warnings (max 5).

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • src/util/metricsAggregator.js
🧠 Learnings (1)
src/util/metricsAggregator.js (1)
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
🧬 Code Graph Analysis (1)
src/util/metricsAggregator.js (2)
src/util/prometheus.js (1)
  • logger (2-2)
src/util/cluster.js (2)
  • logger (3-3)
  • cluster (1-1)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (5)
src/util/metricsAggregator.js (5)

182-197: Excellent improvement in worker communication reliability.

The addition of connection checks and error handling for worker communication significantly improves robustness. This prevents attempts to send messages to disconnected workers and properly handles send failures.


201-215: Well-implemented error handling for worker thread communication.

The try-catch block properly handles postMessage failures and maintains consistent error handling patterns by calling rejectFunc and resetAggregator.


217-227: Robust request ID validation prevents state corruption.

The validation logic correctly handles both stale responses and responses received after a request has been completed or timed out. This is crucial for maintaining aggregator state integrity.


123-137: Effective worker thread lifecycle management.

The error and exit event handlers provide automatic recovery from worker failures. The shuttingDown flag prevents unnecessary logging during planned shutdown, and automatic worker restart ensures continued operation.


163-178: No race condition here—Node.js is single-threaded
In Node.js the assignment to currentRequestId and the call to setTimeout run back-to-back in the same tick, so there’s no opportunity for another invocation of resetAggregator() to slip in between. The timeout will always reference the correct ID.

If you’d like to make this explicit, you can add a brief comment above the block:

// In Node.js’s single-threaded event loop, these two lines execute atomically
const currentRequestId = this.requestId;
…

but no code changes are required.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@atzoum
atzoum force-pushed the fix.metricsAggregator branch from 595b99d to 276deaf Compare June 30, 2025 10:09
@atzoum
atzoum requested a review from sivashanmukh as a code owner June 30, 2025 10:09
@atzoum
atzoum requested a review from a team June 30, 2025 10:09

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/util/metricsAggregator.js (2)

115-115: Fix typo in log message.

There's a typo in the log message: "reseting" should be "resetting".

-        `[MetricsAggregator] Periodic reset interval of ${intervalSeconds} seconds expired, reseting metrics`,
+        `[MetricsAggregator] Periodic reset interval of ${intervalSeconds} seconds expired, resetting metrics`,

161-161: Fix grammatical error in comment.

The comment has a grammatical error: "We dont support" should be "We don't support".

-    // We dont support concurrent /metrics requests.
+    // We don't support concurrent /metrics requests.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 595b99d44ba4be6ea7e233b9f8697041f45dbd1e and 276deaf.

⛔ Files ignored due to path filters (1)
  • test/__tests__/metricsAggregator.test.js is excluded by !**/test/**
📒 Files selected for processing (3)
  • sonar-project.properties (1 hunks)
  • src/util/metricsAggregator.js (5 hunks)
  • src/util/worker.js (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • sonar-project.properties
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/util/worker.js
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.js`: Focus on ESLint errors (max 3) and warnings (max 5).

**/*.js: Focus on ESLint errors (max 3) and warnings (max 5).

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • src/util/metricsAggregator.js
🧠 Learnings (1)
src/util/metricsAggregator.js (1)
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (10)
src/util/metricsAggregator.js (10)

15-17: LGTM: Configurable timeout implementation.

The configurable timeout with a reasonable default of 10 seconds is well-implemented. The parseInt usage with radix 10 and fallback to default values follows best practices.


32-32: LGTM: Request ID mechanism for preventing race conditions.

The addition of requestId and currentTimeout properties provides an effective mechanism to track and invalidate stale requests, preventing state corruption from overlapping requests.

Also applies to: 35-35


51-69: LGTM: Robust request ID validation in worker thread responses.

The implementation correctly validates request IDs, ignores stale responses, and handles errors appropriately. The early returns prevent unnecessary processing of outdated responses.


130-144: LGTM: Comprehensive worker thread lifecycle management.

The error and exit event handlers provide robust worker thread management. The shuttingDown flag prevents unnecessary error logging during shutdown, and the automatic restart logic ensures service continuity.


176-185: LGTM: Well-implemented timeout mechanism.

The timeout implementation correctly prevents hanging requests by checking both the request ID and active request state. The timeout duration is configurable and the cleanup logic is sound.


189-203: LGTM: Defensive programming for worker communication.

The addition of connection state checking and try-catch blocks around worker communication prevents errors from disconnected workers and provides appropriate error logging.


208-222: LGTM: Enhanced error handling for worker thread communication.

The try-catch block around postMessage with proper error handling and aggregator reset prevents the system from getting stuck when worker thread communication fails.


224-246: LGTM: Comprehensive response validation.

The handleMetricsResponse method now properly validates request IDs, checks for active requests, and handles errors gracefully. This prevents processing of stale or unexpected responses.


256-268: LGTM: Improved error handling in reset operations.

The addition of connection checking and try-catch blocks around reset operations makes the system more resilient to worker communication failures.


272-272: LGTM: Graceful shutdown flag implementation.

The shuttingDown flag provides a clean way to suppress error logging during shutdown, preventing unnecessary log noise.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@atzoum atzoum changed the title fix: metrics aggregator stops responding fix: metrics aggregator stops working Jun 30, 2025
@atzoum atzoum changed the title fix: metrics aggregator stops working fix: metrics aggregator stops collecting metrics Jun 30, 2025
koladilip
koladilip previously approved these changes Jun 30, 2025
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@atzoum
atzoum requested a review from koladilip June 30, 2025 18:49
dhawal1248
dhawal1248 previously approved these changes Jul 1, 2025
koladilip
koladilip previously approved these changes Jul 1, 2025
@atzoum
atzoum dismissed stale reviews from koladilip and dhawal1248 via 63cfb12 July 1, 2025 06:47
@atzoum
atzoum requested review from dhawal1248 and koladilip July 1, 2025 06:47
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@sonarqubecloud

sonarqubecloud Bot commented Jul 1, 2025

Copy link
Copy Markdown

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.

4 participants