Skip to content

fix: cluster node getting stuck and cluster left running in degraded mode - #4447

Merged
koladilip merged 2 commits into
developfrom
fix.corruptedCluster
Jul 4, 2025
Merged

koladilip merged 2 commits into
developfrom
fix.corruptedCluster

Conversation

@atzoum

@atzoum atzoum commented Jul 1, 2025 •

Copy link
Copy Markdown
Contributor

Description

Using ClusterManager in rudder-transformer:

  • Supports graceful shutdown of the cluster with a configurable timeout. Once the timeout expires, any remaining cluster workers are forcefully terminated.
  • Provides worker health monitoring via a ping/pong mechanism. If a stuck worker is detected, it can be restarted automatically or trigger a cluster shutdown.
  • Enables automatic worker restarts on unexpected exits, with configurable restart limits.
  • Implements proper signal handling to ensure clean shutdown triggers.
  • Offers flexible handlers for primary and worker functions.

The previous cluster management logic had several flaws that caused multiple issues:

  • It attempted to gracefully handle SIGSEGV signals. However, when a process receives SIGSEGV, it is already in an unreliable state. This often led to the worker process hanging indefinitely and consuming 100% of the cpu core.
  • There was no mechanism to detect stuck workers.
  • Stuck workers were not handled during shutdown, sometimes resulting in incomplete shutdowns.
  • After all workers were terminated, the cluster itself did not call process.exit(0), which could leave the process hanging without fully shutting down.

resolves PIPE-2194
resolves PIPE-2193

@coderabbitai

coderabbitai Bot commented Jul 1, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@atzoum has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 5 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 91203a1906672e80ba4cc42a41a1449880335d9d and 915d0bb.

📒 Files selected for processing (5)
  • .github/scripts/verifyServerStart.sh (1 hunks)
  • .github/workflows/verify-server-start.yml (1 hunks)
  • src/index.ts (3 hunks)
  • src/util/cluster.test.ts (1 hunks)
  • src/util/cluster.ts (1 hunks)

Summary by CodeRabbit

  • New Features

    • Introduced a new script to manage and verify server startup and shutdown health.
    • Added a new module for cluster management with utilities for graceful shutdown and worker lifecycle control.
    • New test suite added to ensure cluster management functions work as expected.
  • Bug Fixes

    • Improved Redis disconnection logic to prevent errors if the client is not initialized.
  • Chores

    • Updated workflow to use scripted health checks for server verification under different clustering configurations.
    • Refined signal handling for server shutdown processes.

Summary by CodeRabbit

  • New Features

    • Introduced cluster management utilities for improved server reliability and graceful shutdown.
    • Added a script to automate starting, health-checking, and gracefully stopping the server.
  • Bug Fixes

    • Improved Redis disconnection logic to prevent errors when the client is not initialized.
  • Tests

    • Added comprehensive test coverage for cluster management utilities to ensure robust process handling.
  • Chores

    • Removed legacy cluster management code and signal handling for cleaner server operation.

Summary by CodeRabbit

  • Refactor

    • Improved cluster management by adopting a new centralized approach for worker lifecycle, restarts, and shutdowns.
    • Removed manual signal handling and explicit process event listeners for shutdown events.
    • Enhanced Redis disconnection logic to prevent potential runtime errors.
  • Tests

    • Added comprehensive unit tests for cluster management, worker shutdown, and stuck worker respawn logic.

Walkthrough

The updates refactor cluster management by introducing a ClusterManager abstraction, centralizing worker lifecycle control and removing manual signal handling. The code also adds unit tests for the new cluster utilities, updates Redis disconnection logic for safety, and removes SIGSEGV signal handling from the shutdown process.

Changes

File(s) Change Summary
src/index.ts Removed all SIGSEGV signal handling from graceful shutdown logic and event listeners.
src/util/cluster.js Deleted legacy cluster management implementation using Node.js cluster module and manual signal handling.
src/util/cluster.ts Added new cluster management module with ClusterManager integration, worker shutdown, stuck worker respawn logic.
src/util/cluster.test.ts Added unit tests covering cluster start, worker shutdown, and stuck worker respawn functions.
src/util/redis/redisConnector.js Updated disconnect method to check for existence of Redis client before calling disconnect().
.github/scripts/startServer.sh Added new Bash script to start the server, verify health endpoint, and gracefully stop the server with timeout checks.
.github/workflows/verify-server-start.yml Refactored server start verification workflow to build project and run scripted healthchecks with clustering toggled.

Sequence Diagram(s)

sequenceDiagram
    participant Main as Main Process
    participant ClusterManager
    participant Worker
    participant MetricsServer
    participant RedisClient

    Main->>ClusterManager: Initialize with config (worker count, timeouts, etc.)
    ClusterManager->>Worker: Fork worker(s)
    Worker->>MetricsServer: Start (if Prometheus enabled)
    Worker->>AppServer: Start application server
    Note over ClusterManager, Worker: ClusterManager monitors workers

    alt Graceful Shutdown Triggered
        ClusterManager->>Worker: Invoke workerShutdownFn
        Worker->>AppServer: Close server
        Worker->>MetricsServer: Shutdown metrics client
        Worker->>RedisClient: Disconnect (if client exists)
        Worker-->>ClusterManager: Signal shutdown complete
    end

    alt Stuck Worker Detected
        ClusterManager->>Worker: Kill and respawn (up to max limit)
    end
Loading

Suggested reviewers

  • sivashanmukh
  • krishna2020
  • dhawal1248

Suggestions for improvement:

  • Consider adding integration tests to validate cluster behavior under real shutdown and restart scenarios to complement the unit tests.
  • Document the new cluster management approach and shutdown flow in the project’s developer guide for easier onboarding and maintenance.
  • Review other resource cleanup areas for similar defensive checks as added in Redis disconnection to prevent runtime errors in edge cases.
  • The new startServer.sh script could be extended with logging for better diagnostics during CI/CD runs.
✨ 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.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@codecov

codecov Bot commented Jul 1, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 94.33962% with 3 lines in your changes missing coverage. Please review.

Project coverage is 91.22%. Comparing base (0b596a0) to head (915d0bb).
Report is 5 commits behind head on develop.

Files with missing lines Patch % Lines
src/util/cluster.ts 94.11% 3 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4447      +/-   ##
===========================================
+ Coverage    91.18%   91.22%   +0.03%     
===========================================
  Files          638      639       +1     
  Lines        33532    33588      +56     
  Branches      7919     7931      +12     
===========================================
+ Hits         30577    30640      +63     
+ Misses        2716     2681      -35     
- Partials       239      267      +28     

☔ 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.corruptedCluster branch from 0a171e5 to 2c7b914 Compare July 1, 2025 13:57
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@atzoum
atzoum force-pushed the fix.corruptedCluster branch from 2c7b914 to c7aa203 Compare July 1, 2025 14:23
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@atzoum
atzoum force-pushed the fix.corruptedCluster branch from c7aa203 to 7b01629 Compare July 1, 2025 18:45
@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 July 2, 2025 10:52
@atzoum
atzoum requested review from a team and sivashanmukh as code owners July 2, 2025 10:52
@atzoum
atzoum requested a review from a team July 2, 2025 10:52
@atzoum
atzoum force-pushed the fix.corruptedCluster branch from 7b01629 to 1dcf5ab Compare July 2, 2025 10:52

@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: 3

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b8aeabb and 1dcf5abad1e20670c904dc694f8550e5b0c22a07.

⛔ 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 (4)
  • src/index.ts (2 hunks)
  • src/util/cluster.js (1 hunks)
  • src/util/cluster.test.ts (1 hunks)
  • src/util/redis/redisConnector.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/redis/redisConnector.js
  • src/util/cluster.js
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • 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: 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: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
src/util/redis/redisConnector.js (1)

129-134: Good defensive programming practice!

The added null check prevents potential runtime errors during shutdown when the Redis client might not be initialized. This is particularly important in the context of the cluster management refactor where worker shutdown can occur at various stages of the application lifecycle.

src/index.ts (1)

69-73: Correct removal of SIGSEGV from graceful shutdown signals

Removing SIGSEGV from the graceful shutdown signals is the right approach. When a segmentation fault occurs, the process is already in an unreliable state, and attempting graceful shutdown can lead to hangs and stuck workers. It's better to let the process crash immediately and rely on the cluster manager to restart it.

Also applies to: 86-91

src/util/cluster.test.ts (1)

40-45: Well-structured unit test for respawn limit logic

The test effectively verifies that the respawn function correctly enforces the maximum respawn limit by returning true for the first call and false for subsequent calls.

src/util/cluster.js (3)

8-30: Well-structured worker shutdown handler

The implementation properly sequences the shutdown steps: HTTP server → metrics client → Redis client. The 30-second timeout for graceful HTTP shutdown aligns with the overall cluster shutdown timeout pattern.


32-50: Clean implementation of respawn limit logic

Excellent use of closure pattern to maintain respawn counter state. The function generator approach provides a clean API for the ClusterManager while encapsulating the respawn tracking logic.


66-89: Robust configuration with sensible defaults

The environment variable parsing is well-implemented with appropriate defaults and clear documentation. The configuration parameters comprehensively address the cluster management requirements outlined in the PR objectives.

Comment thread src/util/cluster.test.ts Resolved
Comment thread src/util/cluster.test.ts Resolved
Comment thread src/util/cluster.js Resolved
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

Comment thread src/util/cluster.js Resolved
Comment thread src/util/cluster.js Resolved
Comment thread src/util/cluster.js Resolved
utsabc
utsabc previously approved these changes Jul 2, 2025
@atzoum
atzoum force-pushed the fix.corruptedCluster branch 2 times, most recently from 9d7c791 to 91203a1 Compare July 3, 2025 09:44

@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: 2

🧹 Nitpick comments (4)
.github/scripts/startServer.sh (2)

24-36: Graceful shutdown should wait on the child

After sending SIGINT you loop until /health fails, but never wait on the PID. Use wait to avoid leaving a zombie and to propagate the exit code.

-kill -SIGINT $NODE_PID
+kill -SIGINT "$NODE_PID"
+wait "$NODE_PID" 2>/dev/null || true

Optionally drop the second curl-polling loop and rely solely on wait.


38-39: Missing trap for early exits

If the script itself is terminated (e.g., CI timeout) the child keeps running. Add a trap so the child is always cleaned up:

trap 'kill -SIGINT "$NODE_PID" 2>/dev/null || true' EXIT
.github/workflows/verify-server-start.yml (2)

29-32: Trailing spaces – YAML lint fails pipeline

Lines 29, 34 and 39 contain stray spaces flagged by yamllint. Remove them to keep the workflow green.

-      - name: Install Dependencies␠
+      - name: Install Dependencies
 ...
-        run: npm run build␠
+        run: npm run build

40-47: Parameter duplication – use a reusable matrix

The two nearly-identical steps differ only in env vars. Consider a job / matrix strategy to avoid duplication and make it easy to add more scenarios.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9d7c79146499f0d499b2b72c1a88520c03a71a83 and 91203a1906672e80ba4cc42a41a1449880335d9d.

📒 Files selected for processing (3)
  • .github/scripts/startServer.sh (1 hunks)
  • .github/workflows/verify-server-start.yml (1 hunks)
  • src/index.ts (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/index.ts
🧰 Additional context used
🪛 YAMLlint (1.37.1)
.github/workflows/verify-server-start.yml

[error] 29-29: trailing spaces

(trailing-spaces)


[error] 34-34: trailing spaces

(trailing-spaces)


[error] 39-39: trailing spaces

(trailing-spaces)

🪛 Shellcheck (0.10.0)
.github/scripts/startServer.sh

[warning] 30-30: i appears unused. Verify use (or export if used externally).

(SC2034)

⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Code Coverage
  • 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: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
.github/scripts/startServer.sh (2)

7-16: Unused loop counter & missing strict mode

i is never referenced – shellcheck rightly warns (SC2034).
Also add set -euo pipefail to abort fast on any error and catch unset vars.

+# Exit on error, unset vars, or pipe failure
+set -euo pipefail
 ...
-for i in $(seq 1 $timeout); do
+for _ in $(seq 1 "$timeout"); do

[ suggest_essential_refactor ]


18-22: Race condition & brittle kill

If the node process dies before this point, kill $NODE_PID will exit non-zero and mask the real failure. Add || true, and use wait to collect exit status.

-  kill $NODE_PID
+  kill "$NODE_PID" 2>/dev/null || true
+  wait "$NODE_PID" 2>/dev/null || true

[ suggest_essential_refactor ]

Comment thread .github/scripts/startServer.sh Resolved
@atzoum
atzoum force-pushed the fix.corruptedCluster branch from 91203a1 to 2a74cd2 Compare July 3, 2025 09:51
@atzoum
atzoum force-pushed the fix.corruptedCluster branch from 2a74cd2 to 915d0bb Compare July 3, 2025 09:53
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@sonarqubecloud

sonarqubecloud Bot commented Jul 3, 2025

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
E Maintainability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

@atzoum
atzoum requested review from koladilip and utsabc July 3, 2025 10:12
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