Repository navigation
fix: metrics aggregator stops collecting metrics - #4441
Conversation
Summary by CodeRabbit
Summary by CodeRabbit
WalkthroughThe changes implement a request ID mechanism and timeout handling in the Changes
Suggestions for Improvements
📜 Recent review detailsConfiguration used: .coderabbit.yaml ⛔ Files ignored due to path filters (2)
📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (9)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
Documentation and Community
|
Codecov ReportAttention: Patch coverage is
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. 🚀 New features to boost your workflow:
|
|
Allure Test reports for this run are available at:
|
0102fbc to
2068d78
Compare
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
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
NaNif 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.jsis 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.jssrc/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
requestIdto 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
pendingMetricRequestsreset 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.
2068d78 to
66ea030
Compare
|
Allure Test reports for this run are available at:
|
66ea030 to
595b99d
Compare
There was a problem hiding this comment.
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.jsis 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
postMessagefailures and maintains consistent error handling patterns by callingrejectFuncandresetAggregator.
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
shuttingDownflag 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 tocurrentRequestIdand the call tosetTimeoutrun back-to-back in the same tick, so there’s no opportunity for another invocation ofresetAggregator()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.
|
Allure Test reports for this run are available at:
|
595b99d to
276deaf
Compare
There was a problem hiding this comment.
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.jsis 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
requestIdandcurrentTimeoutproperties 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
shuttingDownflag 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
postMessagewith proper error handling and aggregator reset prevents the system from getting stuck when worker thread communication fails.
224-246: LGTM: Comprehensive response validation.The
handleMetricsResponsemethod 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
shuttingDownflag provides a clean way to suppress error logging during shutdown, preventing unnecessary log noise.
|
Allure Test reports for this run are available at:
|
|
Allure Test reports for this run are available at:
|
|
Allure Test reports for this run are available at:
|
|



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:
METRICS_AGGREGATOR_REQUEST_TIMEOUT_SECONDS=10, after which a new aggregation request will be allowed.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