Skip to content

chore: groupEventsByType function optimization - #4398

Merged
atzoum merged 1 commit into
developfrom
chore.groupByPerf
Jun 16, 2025
Merged

atzoum merged 1 commit into
developfrom
chore.groupByPerf

Conversation

@atzoum

@atzoum atzoum commented Jun 11, 2025 •

Copy link
Copy Markdown
Contributor

This pull request refactors the groupEventsByType function to improve performance drastically, especially with larger batch sizes, and maintain user-specific ordering. It also introduces a new benchmarking script for comparing the performance of two implementations of the groupEventsByType function.

Performance Benchmarking Enhancements:

  • Added a new benchmarking script in src/v0/util/index.groupEvents.bench.js to compare the performance of the old and new groupEventsByType implementations. It includes utilities for generating test data, running benchmarks, and analyzing results across different dataset sizes and skewed data scenarios.

Refactoring for Efficiency:

  • Refactored the groupEventsByType function in src/v0/util/index.js to improve performance and ensure user-specific ordering in batches. The new implementation uses chunk objects and a Map to track the last chunk index for each user, reducing redundant iterations and enhancing scalability.

resolves PIPE-2139

Running benchmarks with 1000 messages...

Benchmarking groupEventsByType:
groupEventsByType generated 155 batches
Average time: 0.20ms
Min time: 0.17ms
Max time: 0.29ms

Benchmarking groupEventsByTypeOld:
groupEventsByTypeOld generated 155 batches
Average time: 2.51ms
Min time: 2.17ms
Max time: 3.06ms

Comparison: groupEventsByType is 12.59x faster than groupEventsByTypeOld


===== Testing with different dataset sizes =====

Testing with 10 messages:
groupEventsByType generated 6 batches
groupEventsByTypeOld generated 6 batches
groupEventsByType: 0.00ms, groupEventsByTypeOld: 0.00ms
Speedup: 0.81x slower

Testing with 100 messages:
groupEventsByType generated 23 batches
groupEventsByTypeOld generated 23 batches
groupEventsByType: 0.02ms, groupEventsByTypeOld: 0.03ms
Speedup: 1.94x faster

Testing with 500 messages:
groupEventsByType generated 85 batches
groupEventsByTypeOld generated 85 batches
groupEventsByType: 0.09ms, groupEventsByTypeOld: 0.61ms
Speedup: 6.84x faster

Testing with 1000 messages:
groupEventsByType generated 159 batches
groupEventsByTypeOld generated 159 batches
groupEventsByType: 0.06ms, groupEventsByTypeOld: 2.54ms
Speedup: 44.83x faster

Testing with 2000 messages:
groupEventsByType generated 290 batches
groupEventsByTypeOld generated 290 batches
groupEventsByType: 0.12ms, groupEventsByTypeOld: 9.88ms
Speedup: 80.48x faster

Testing with 5000 messages:
groupEventsByType generated 721 batches
groupEventsByTypeOld generated 721 batches
groupEventsByType: 0.39ms, groupEventsByTypeOld: 44.80ms
Speedup: 113.75x faster


===== Testing with skewed data (fewer types, more duplicates) =====

Testing with 1000 skewed messages (fewer types, more duplicates):
groupEventsByType generated 116 batches
groupEventsByTypeOld generated 116 batches
groupEventsByType: 0.04ms, groupEventsByTypeOld: 1.21ms
Speedup: 29.93x faster

@atzoum
atzoum requested a review from a team as a code owner June 11, 2025 12:35
@atzoum
atzoum requested review from chandumlg and maheshkutty June 11, 2025 12:35
@coderabbitai

coderabbitai Bot commented Jun 11, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Added performance benchmarking for event grouping functionality, with detailed console output for analysis.
  • Refactor

    • Improved the logic for grouping events by message type and user to better preserve event order and enhance performance.
  • Chores

    • Updated configuration to exclude benchmark files from code coverage and static analysis reports.

Summary by CodeRabbit

  • New Features

    • Introduced a benchmarking tool to compare the performance of event grouping functions, with detailed console output for results.
  • Refactor

    • Updated event grouping logic to better preserve the order of events per user while batching by message type.
  • Chores

    • Updated coverage settings to exclude benchmark files from coverage reports and static analysis.

Walkthrough

A new benchmarking script was added to evaluate and compare two versions of the groupEventsByType function, which groups event objects by message type and user ID. The core grouping logic in groupEventsByType was completely rewritten, altering its batching strategy and event ordering. The benchmarking script generates test data, runs performance comparisons, and reports results.

Changes

File(s) Change Summary
src/v0/util/index.groupEvents.bench.js Added benchmarking script with old and new grouping functions, test data generators, and performance measurement.
src/v0/util/index.js Completely rewrote groupEventsByType to change batching logic, event ordering, and improve control flow.
codecov.yml Updated to exclude benchmark files (**/*.bench.js, **/*.bench.ts) from coverage reports.
sonar-project.properties Updated to exclude benchmark files (**/*.bench.js) from SonarQube analysis.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant groupEventsByType
    participant UserMap
    participant Batches

    Caller->>groupEventsByType: Call with events[]
    groupEventsByType->>UserMap: Track last batch index per user
    loop For each event in events[]
        groupEventsByType->>Batches: Try to place event in existing batch by type and user order
        alt No suitable batch found
            groupEventsByType->>Batches: Create new batch for message type
        end
        groupEventsByType->>UserMap: Update user's last batch index
    end
    groupEventsByType-->>Caller: Return array of batches
Loading

Suggestions for Improvements

  • Add unit tests to verify the correctness of the new batching logic beyond performance benchmarking.
  • Extend the benchmarking script to export results in a machine-readable format (e.g., JSON or CSV) for automated performance regression tracking.
  • Document the new batching semantics clearly in the function's JSDoc, especially regarding user event ordering and batch creation rules.
  • Consider measuring memory usage alongside execution time, as the new approach may have different space complexity characteristics.
  • Explore parallelizing the benchmarking runs to reduce total test execution time, especially for large datasets.
✨ 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.

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

🧹 Nitpick comments (1)
src/v0/util/index.groupEvents.bench.js (1)

81-103: Consider adding output validation between implementations.

While the benchmark logs batch counts, it doesn't verify that both implementations produce equivalent results. Add a comparison to ensure correctness.

Add result validation after the warm-up run:

 function runBenchmark(fn, input, iterations = 5) {
   // Warm-up run
-  fn(input);
+  const warmupResult = fn(input);
+  
+  // Store the warm-up result for validation (if needed)
+  const expectedBatchCount = warmupResult.length;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7b7129e and 87e16599ad4c2feb07eb2840281782808203d641.

📒 Files selected for processing (2)
  • src/v0/util/index.groupEvents.bench.js (1 hunks)
  • src/v0/util/index.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).

  • src/v0/util/index.js
  • src/v0/util/index.groupEvents.bench.js
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • 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: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (4)
src/v0/util/index.js (2)

2063-2071: Excellent optimization with improved algorithm design!

The new implementation efficiently groups events while preserving user-specific ordering. The chunk-based approach with Map tracking is a significant improvement over the previous array mutation strategy.


2078-2111: Well-designed algorithm that maintains event ordering constraints.

The implementation correctly ensures that events from the same user are placed in chunks that respect their original order. The use of minChunkIndex to track the last chunk position for each user is elegant and efficient.

src/v0/util/index.groupEvents.bench.js (2)

38-78: Good test data coverage with diverse scenarios.

The test data generation functions effectively create both uniform and skewed distributions, which helps validate the performance characteristics under different conditions.


105-162: Comprehensive benchmark coverage across various scenarios.

The benchmark effectively tests performance across different dataset sizes and distributions, providing valuable insights into the optimization's impact.

Comment thread src/v0/util/index.groupEvents.bench.js Resolved
Comment thread src/v0/util/index.groupEvents.bench.js Outdated

Check failure

Code scanning / CodeQL

Insecure randomness

This uses a cryptographically insecure random number generated at [Math.random()](1) in a security context.

Copilot Autofix

AI over 1 year ago

To address the issue, we will replace the use of Math.random() with a cryptographically secure random number generator. In Node.js, the crypto module provides the crypto.randomInt function, which generates cryptographically secure random integers. This function will be used to replace the insecure random number generation in the generateTestData and generateSkewedData functions.

Suggested changeset 1
src/v0/util/index.groupEvents.bench.js

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/v0/util/index.groupEvents.bench.js b/src/v0/util/index.groupEvents.bench.js
--- a/src/v0/util/index.groupEvents.bench.js
+++ b/src/v0/util/index.groupEvents.bench.js
@@ -2,2 +2,3 @@
 const { performance } = require('perf_hooks');
+const crypto = require('crypto');
 // Import the util module
@@ -43,4 +44,4 @@
   return Array.from({ length: count }, () => {
-    const messageType = messageTypes[Math.floor(Math.random() * messageTypes.length)];
-    const userId = userIds[Math.floor(Math.random() * userIds.length)];
+    const messageType = messageTypes[crypto.randomInt(0, messageTypes.length)];
+    const userId = userIds[crypto.randomInt(0, userIds.length)];
 
@@ -64,4 +65,4 @@
   return Array.from({ length: count }, () => {
-    const messageType = messageTypes[Math.floor(Math.random() * messageTypes.length)];
-    const userId = userIds[Math.floor(Math.random() * userIds.length)];
+    const messageType = messageTypes[crypto.randomInt(0, messageTypes.length)];
+    const userId = userIds[crypto.randomInt(0, userIds.length)];
 
EOF
@@ -2,2 +2,3 @@
const { performance } = require('perf_hooks');
const crypto = require('crypto');
// Import the util module
@@ -43,4 +44,4 @@
return Array.from({ length: count }, () => {
const messageType = messageTypes[Math.floor(Math.random() * messageTypes.length)];
const userId = userIds[Math.floor(Math.random() * userIds.length)];
const messageType = messageTypes[crypto.randomInt(0, messageTypes.length)];
const userId = userIds[crypto.randomInt(0, userIds.length)];

@@ -64,4 +65,4 @@
return Array.from({ length: count }, () => {
const messageType = messageTypes[Math.floor(Math.random() * messageTypes.length)];
const userId = userIds[Math.floor(Math.random() * userIds.length)];
const messageType = messageTypes[crypto.randomInt(0, messageTypes.length)];
const userId = userIds[crypto.randomInt(0, userIds.length)];

Copilot is powered by AI and may make mistakes. Always verify output.
Comment thread src/v0/util/index.groupEvents.bench.js Outdated

Check failure

Code scanning / CodeQL

Insecure randomness

This uses a cryptographically insecure random number generated at [Math.random()](1) in a security context.

Copilot Autofix

AI over 1 year ago

To fix the issue, replace the use of Math.random() with a cryptographically secure random number generator. For Node.js, the crypto module provides the crypto.randomInt function, which can generate secure random integers. This ensures that the generated random values are unpredictable and suitable for security-sensitive contexts.

The changes will involve:

  1. Importing the crypto module.
  2. Replacing Math.random() with crypto.randomInt for generating random indices for messageTypes and userIds.
  3. Ensuring the functionality remains unchanged while improving security.
Suggested changeset 1
src/v0/util/index.groupEvents.bench.js

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/v0/util/index.groupEvents.bench.js b/src/v0/util/index.groupEvents.bench.js
--- a/src/v0/util/index.groupEvents.bench.js
+++ b/src/v0/util/index.groupEvents.bench.js
@@ -2,3 +2,3 @@
 const { performance } = require('perf_hooks');
-// Import the util module
+const crypto = require('crypto'); // Import crypto for secure randomness
 const { groupEventsByType } = require('./index');
@@ -43,4 +43,4 @@
   return Array.from({ length: count }, () => {
-    const messageType = messageTypes[Math.floor(Math.random() * messageTypes.length)];
-    const userId = userIds[Math.floor(Math.random() * userIds.length)];
+    const messageType = messageTypes[crypto.randomInt(0, messageTypes.length)];
+    const userId = userIds[crypto.randomInt(0, userIds.length)];
 
@@ -64,4 +64,4 @@
   return Array.from({ length: count }, () => {
-    const messageType = messageTypes[Math.floor(Math.random() * messageTypes.length)];
-    const userId = userIds[Math.floor(Math.random() * userIds.length)];
+    const messageType = messageTypes[crypto.randomInt(0, messageTypes.length)];
+    const userId = userIds[crypto.randomInt(0, userIds.length)];
 
EOF
@@ -2,3 +2,3 @@
const { performance } = require('perf_hooks');
// Import the util module
const crypto = require('crypto'); // Import crypto for secure randomness
const { groupEventsByType } = require('./index');
@@ -43,4 +43,4 @@
return Array.from({ length: count }, () => {
const messageType = messageTypes[Math.floor(Math.random() * messageTypes.length)];
const userId = userIds[Math.floor(Math.random() * userIds.length)];
const messageType = messageTypes[crypto.randomInt(0, messageTypes.length)];
const userId = userIds[crypto.randomInt(0, userIds.length)];

@@ -64,4 +64,4 @@
return Array.from({ length: count }, () => {
const messageType = messageTypes[Math.floor(Math.random() * messageTypes.length)];
const userId = userIds[Math.floor(Math.random() * userIds.length)];
const messageType = messageTypes[crypto.randomInt(0, messageTypes.length)];
const userId = userIds[crypto.randomInt(0, userIds.length)];

Copilot is powered by AI and may make mistakes. Always verify output.
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@codecov

codecov Bot commented Jun 11, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91.13%. Comparing base (1e5b3f0) to head (eac8c6f).
Report is 24 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #4398   +/-   ##
========================================
  Coverage    91.13%   91.13%           
========================================
  Files          638      638           
  Lines        33476    33478    +2     
  Branches      7897     7900    +3     
========================================
+ Hits         30509    30511    +2     
  Misses        2728     2728           
  Partials       239      239           

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

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

LGTM, sonar issues are coming because of bench.js, we may ignore these files or we can remove it from code as we got results.

@atzoum
atzoum force-pushed the chore.groupByPerf branch from 87e1659 to bb289d2 Compare June 11, 2025 13:05
@atzoum
atzoum requested a review from sivashanmukh as a code owner June 11, 2025 13:05
@atzoum
atzoum requested review from a team and koladilip June 11, 2025 13:05
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

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

♻️ Duplicate comments (1)
src/v0/util/index.groupEvents.bench.js (1)

14-16: ⚠️ Potential issue

Benchmark mutates its own input – results are still skewed

currentInputsArray = inputs; keeps a reference to the original array; shift() empties it, so only the first iteration measures real work.

-  let currentInputsArray = inputs;
+  let currentInputsArray = [...inputs]; // clone to keep original intact

Without this fix, timing for iterations > 1 is meaningless.

🧹 Nitpick comments (3)
src/v0/util/index.js (1)

2091-2097: Minor performance tweak – stop scanning once first match fails

The inner for keeps checking chunks even after finding that chunks[i].type !== messageType.
Since chunks are appended in order, the first non-matching type after a run of matching types is a natural break-point:

-    for (let i = minChunkIndex; i < chunks.length; i += 1) {
-      if (chunks[i].type === messageType) {
-        targetChunkIndex = i;
-        break;
-      }
+    for (let i = minChunkIndex; i < chunks.length && chunks[i].type === messageType; i += 1) {
+      targetChunkIndex = i;
+      break;
     }

Optional, but shaves a few cycles on large datasets.

src/v0/util/index.groupEvents.bench.js (2)

43-57: Use deterministic data generation for reproducible benchmarks

Math.random() makes it impossible to reproduce results and is flagged as insecure randomness.
Seeded RNGs (e.g., seedrandom) or fixed fixture datasets will yield stable, reviewable numbers.

-  return Array.from({ length: count }, () => {
+  const rng = () => (seed * 9301 + 49297) % 233280 / 233280; // tiny LCG
+  return Array.from({ length: count }, () => {
     const messageType = messageTypes[Math.floor(rng() * messageTypes.length)];
     const userId = userIds[Math.floor(rng() * userIds.length)];

81-104: Minor nit – avoid re-assigning result inside loop

The only use of result is for result.length after the loop.
Capture once and drop the redundant variable for clarity.

-  let result;
+  let resultLength = 0;
...
-    result = fn([...input]);
+    resultLength = fn([...input]).length;
...
-  return { average, min, max, times, resultLength: result.length };
+  return { average, min, max, times, resultLength };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 87e16599ad4c2feb07eb2840281782808203d641 and bb289d285088cf95597601d54099fd5d4ae28c4d.

📒 Files selected for processing (3)
  • codecov.yml (1 hunks)
  • src/v0/util/index.groupEvents.bench.js (1 hunks)
  • src/v0/util/index.js (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • codecov.yml
🧰 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).

  • src/v0/util/index.js
  • src/v0/util/index.groupEvents.bench.js
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • 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)
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
src/v0/util/index.js (1)

2082-2088:

Details

❓ Verification inconclusive

userId may be undefined, collapsing multiple users into one bucket

const { userId } = input.metadata; assumes every metadata object carries a userId.
When it is missing, Map is keyed with undefined, so all such events are considered the same user, breaking ordering guarantees and inflating batch count.

-    const { userId } = input.metadata;
+    const userId = input?.metadata?.userId ?? Symbol(); // fall back to a unique key

At minimum, add a defensive check and log to avoid silent corruption.


To verify whether input.metadata (and thus userId) can ever be missing, let’s inspect the surrounding implementation in src/v0/util/index.js. Running a quick snippet extraction around lines 2082–2088:


🏁 Script executed:

#!/bin/bash
# Dump lines 2050–2150 to see function context around userLastChunkIndex usage
sed -n '2050,2150p' src/v0/util/index.js

Length of output: 3478


Let’s locate where groupEventsByType is invoked to see what shape of metadata gets passed in:


🏁 Script executed:

#!/bin/bash
# Find all call sites of groupEventsByType
rg --color=never -n "groupEventsByType" .

Length of output: 2414


🏁 Script executed:

#!/bin/bash
# Inspect test cases for groupEventsByType to see how metadata.userId is treated
rg --color=never -n -A5 -B2 "groupEventsByType" src/v0/util/index.test.js

Length of output: 373


Ensure userId is always defined to maintain correct bucketing
Currently const { userId } = input.metadata; assumes every event’s metadata has a userId. If userId is ever undefined, all such events collapse into the same bucket (keyed by undefined), breaking per‐user ordering and inflating batch counts. Please add a defensive fallback and log any missing IDs, for example:

-  const { userId } = input.metadata;
+  const userId = input?.metadata?.userId ?? (() => {
+    console.warn('groupEventsByType: missing userId, using unique fallback:', input);
+    return Symbol();
+  })();

• Verify that no call site can pass in an event whose metadata.userId is missing.
• Consider adding a unit test for a missing userId scenario.

Comment thread src/v0/util/index.js Resolved
@atzoum
atzoum force-pushed the chore.groupByPerf branch from bb289d2 to b4bdc28 Compare June 11, 2025 13:38
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

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

♻️ Duplicate comments (2)
src/v0/util/index.js (1)

2071-2074: ⚠️ Potential issue

Guard clause still too permissive – use Array.isArray

!inputs will let objects through and the subsequent forEach will explode. We already raised this on a prior commit – please tighten the check:

-  if (!inputs || inputs.length === 0) {
+  if (!Array.isArray(inputs) || inputs.length === 0) {
     return [];
   }
src/v0/util/index.groupEvents.bench.js (1)

14-16: 🛠️ Refactor suggestion

Input mutation skews benchmarks (repeat from earlier review)

groupEventsByTypeOld mutates currentInputsArray via shift(). Although you clone the array in runBenchmark, callers that reuse the same data elsewhere will still get surprised.

Refactor to work on a shallow copy:

-  let currentInputsArray = inputs;
+  let currentInputsArray = [...inputs];
🧹 Nitpick comments (2)
src/v0/util/index.js (1)

2091-2096: Minor performance nit – avoid repeated linear scans

Iterating from minChunkIndex to chunks.length for every event makes worst-case complexity O(n²).
A second Map keyed by messageType → array of chunk indices (or the last chunk) would let you find the candidate chunk in O(1).

Not blocking, but consider if batch sizes can grow large.

src/v0/util/index.groupEvents.bench.js (1)

38-57: Security tooling warning – Math.random() for test data

Math.random() is fine for benchmark generation, but note that GitHub’s code-scanning flags it as “insecure randomness”. No action needed for perf tests, just documenting why it’s acceptable here avoids future noise.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bb289d285088cf95597601d54099fd5d4ae28c4d and b4bdc28a86ba4b62c9d62734027cb631616a9418.

📒 Files selected for processing (4)
  • codecov.yml (1 hunks)
  • sonar-project.properties (1 hunks)
  • src/v0/util/index.groupEvents.bench.js (1 hunks)
  • src/v0/util/index.js (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • sonar-project.properties
  • codecov.yml
🧰 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).

  • src/v0/util/index.js
  • src/v0/util/index.groupEvents.bench.js
🧬 Code Graph Analysis (1)
src/v0/util/index.groupEvents.bench.js (1)
src/v0/util/index.js (11)
  • require (19-19)
  • require (21-27)
  • require (29-29)
  • require (31-31)
  • require (34-34)
  • require (36-36)
  • require (37-40)
  • require (41-41)
  • require (42-42)
  • i (1427-1427)
  • i (1511-1511)
⏰ 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 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: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
src/v0/util/index.js (1)

2115-2117: LGTM on concise return

The final mapping to extract inputs keeps the public API unchanged and is clear.

Comment thread src/v0/util/index.js Resolved
@atzoum
atzoum force-pushed the chore.groupByPerf branch from b4bdc28 to eac8c6f Compare June 12, 2025 05:47
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

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

♻️ Duplicate comments (1)
src/v0/util/index.js (1)

2081-2084: ⚠️ Potential issue

userId can be undefined – previous warning still unresolved

You’re still destructuring const { userId } = input.metadata; without a fallback.
When metadata.userId is undefined (common for many call-sites), all such events collapse into the same “undefined” bucket, breaking the per-user ordering guarantee you’re optimising for.

- const { userId } = input.metadata;
+ // fall back to message-level identifiers or throw if ordering must be strict
+ const userId =
+   input?.metadata?.userId ??
+   input?.message?.userId ??
+   input?.message?.anonymousId ??
+   '__no_user__';

At minimum, log/throw when no identifier is found.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b4bdc28a86ba4b62c9d62734027cb631616a9418 and eac8c6f.

📒 Files selected for processing (4)
  • codecov.yml (1 hunks)
  • sonar-project.properties (1 hunks)
  • src/v0/util/index.groupEvents.bench.js (1 hunks)
  • src/v0/util/index.js (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • codecov.yml
🚧 Files skipped from review as they are similar to previous changes (2)
  • sonar-project.properties
  • src/v0/util/index.groupEvents.bench.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).

  • src/v0/util/index.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 (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
src/v0/util/index.js (1)

2071-2073: Guard clause looks solid
The early-return now validates that inputs is an array and non-empty, preventing the accidental forEach crash we called out in an earlier review.

Comment thread src/v0/util/index.js Resolved
@sonarqubecloud

Copy link
Copy Markdown

@atzoum
atzoum enabled auto-merge (squash) June 12, 2025 14:03
@atzoum
atzoum merged commit 9332c75 into develop Jun 16, 2025
@atzoum
atzoum deleted the chore.groupByPerf branch June 16, 2025 13:02
koladilip added a commit that referenced this pull request Jun 30, 2025
* fix: handle empty oauth secret for multiple destination (#4295)

* fix: handle empty oauth secret for multiple destination

* fix: test

* fix: add validation for other field

* chore: add missing test

* chore: add more test

* chore: change test

* chore: misc

* feat: implement hasDynamicConfig flag support (#4321)

* feat: implement hasDynamicConfig flag support in routerTransform flow

This implements support for the hasDynamicConfig flag in the routerTransform flow to fix
the issue where events with dynamic configuration were being mixed up during transformation.
The implementation includes:

1. Added a new hasDynamicConfig flag to the Destination type in controlPlaneConfig.ts to indicate
 whether a destination's configuration contains dynamic config patterns
2. Modified the dynamicConfigParser.ts to respect the hasDynamicConfig flag:
   - Skip processing when hasDynamicConfig is explicitly false
   - Process events when hasDynamicConfig is true or undefined (for backward compatibility)
3. Enhanced groupRouterTransformEvents function in src/v0/util/index.js to:
   - Group events by destination config when hasDynamicConfig is true or undefined
   - Use fast-json-stable-stringify to ensure consistent grouping of configs with different key orders
   - Maintain backward compatibility with older server versions where the flag might not be present
4. Added comprehensive test cases for:
   - Testing behavior with hasDynamicConfig=false
   - Testing behavior with hasDynamicConfig=true
   - Testing backward compatibility with hasDynamicConfig=undefined
   - Testing mixed hasDynamicConfig flags in a batch
   - Testing configs with different key orders

This implementation resolves INT-3633 by ensuring that events with dynamic configuration are properly
 grouped and processed in the routerTransform flow, preventing event mix-up issues.

Dependencies:
- Added fast-json-stable-stringify package to ensure consistent JSON string representation regardless of key order

* fix: add hasDynamicConfig flag support in routerTransform flow

* test: add hasDynamicConfig flag to test files

fix tests

* refactor: optimize dynamicConfigParser to avoid deep cloning entire event

* fix: restore unset functionality in dynamic config parser

- Add unset-value import to properly remove extracted fields from events
- Restore unset() call after extracting dynamic config values to prevent downstream issues
- Change from shallow to deep cloning to avoid modifying original events during unset operations
- Add comprehensive test to verify unset functionality works correctly
- Add shouldGroupByDestinationConfig method to JavaScript dynamic config module
- Update groupRouterTransformEvents to use shouldGroupByDestinationConfig function
- Add environment variable tests for USE_HAS_DYNAMIC_CONFIG_FLAG in router grouping logic

This ensures that fields used in dynamic config templates (e.g., {{ message.traits.appId || 'default' }})
are properly removed from events after extraction, preventing potential conflicts in destination processing.

* refactor: optimize dynamic config parser and consolidate utilities

- Move utility functions from dynamicConfig.js to utils.js for better organization
- Optimize DynamicConfigParser with pre-compiled regex patterns and efficient loops
- Replace deep cloning with selective cloning for better performance
- Remove standalone dynamicConfig.js and dynamicConfig.test.js files
- Update imports and references across affected modules

* fix: ensure consistent ordering in batch processing for google adwords offline conversions (#4359)

- Add sorting by jobId to removeDuplicateMetadata function
- Sort final batch results by minimum jobId for consistent ordering
- Re-enable router output assertion for google_adwords_offline_conversions tests
- Update test data ordering to match new consistent batch processing behavior
- Fix unit test expectations to match new sorted metadata order

* chore: add concurrent requests and memory fencing middlewares (#4358)

* chore: migrate tiktok_ads to new test (#4342)

* chore: migrate tiktok_ads to new test

* chore: review comments

* chore: review comments

* chore: review comments

* chore: review comments

* chore: rebase

* chore: introduce deep freeze to compaction middlewares (#4365)

* feat: implement rudder-test destination with migrated tests (#4352)

- Add rudder-test destination for platform testing and development
- Implement TypeScript destination with router-only transformation
- Support Record v2 events with echo response pattern
- Add context-based test behavior control via testBehavior field
- Migrate tests to new format using migration script
- Optimize tests with generateMetadata utility and common destination
- Enable Zod validation and enhanced Allure reporting
- Add npm script 'rudder-tests' for convenient test execution
- Update README.md with comprehensive destination documentation

The rudder-test destination provides a controlled testing environment
without external dependencies, ideal for platform feature testing,
development workflows, and CI/CD reliability.

refactor: reduce code duplication in rudder_test destination

- Extract common validation and request building logic to utils.ts
- Add processor transformation function alongside existing router function
- Create comprehensive component tests for both processor and router
- Implement shared utilities for message validation, request config building, and test behavior handling
- Maintain different error handling patterns for processor (throws) vs router (returns error objects)
- Add 6 test cases covering success scenarios, error responses, and validation failures

refactor: improve type safety in rudder_test utils

- Replace 'any' types with specific Metadata and RudderTestDestination types
- Import proper types from '../../../types' for better type safety
- Enhance IntelliSense support and compile-time error detection
- Address coderabbitai bot feedback on PR #4352

feat: enhance rudder_test destination with comprehensive dynamic config testing

- Modified rudder_test destination to actually use resolved dynamic config values
- Added endpoint and apiKey resolution from destination config in utils.ts
- Updated transform.ts to pass destination config to utility functions
- Enhanced type definitions to support RudderTestConfig interface

- Added multi-event test cases for both processor and router
- Tests validate multiple events with different dynamic config values resolve correctly
- Added mixed destination ID scenarios (different hasDynamicConfig flags)
- Added compaction tests with multiple events and dynamic config
- All 20 tests now pass and actually validate dynamic config resolution

These tests will surface thread safety issues and shared state problems
in dynamic config processing by testing scenarios where multiple events
have different template variable values that must resolve independently.

docs: update rudder_test destination documentation with dynamic config features

- Added dynamic config resolution capabilities to feature list
- Updated implementation details to reflect both processor and router support
- Added comprehensive test coverage information (20 test cases)
- Included dynamic config examples with template syntax
- Added multi-event testing and thread safety testing use cases
- Updated key files list to include utils.ts and enhanced type definitions
- Corrected architecture description from router-only to dual implementation

* chore: sfmc ai generated docs (#4328)

* chore: sfmc ai generated docs

* chore: sfmc api section in docs

* chore: separate out transformer logic from main doc

* chore: vdm-v2 related faulty docs fix

* Revert "Revert "Merge branch 'develop' into main""

This reverts commit af6e580.

* fix: klaviyo error logging

* chore: optimize usage of deepFreeze in compaction middlewares (#4374)

* chore: use batch processing in transformations (#4363)

* feat: use account information on zoho (#4361)

* chore: new way of creating release

* fix: deep freeze in compaction middleware

- Add test behaviors in rudder_test transform to mutate and replace destination config
- Add router and processor component tests for both property mutation and config
  reference replacement in compacted payload flow
- Assert correct error handling and status codes when mutation is attempted on frozen config
- Ensures immutability of config is enforced and covered in both flows
- Remove unneccessary clonedeep in router transform flow by fixing code

* chore: add safe batch processing to avoid blocking in highly batched destinations

* chore: add batching in mp and source transformations

* fix(marketo): remove auth key from logs

* feat: testing tool (#4391)

* feat: testing tool

* chore: changes

* chore: code structure

* fix: eslint

* chore: review comments

* chore: review comment

* feat: add server request creation flow

* chore: bluecore add internal doc and migrate test (#4353)

* fix: blucore optin event mapping

* fix: review comments

* chore: add subscription event

* chore: add subscription event

* fix: reviews comments

* chore: blucore add internal doc and migrate test

* chore: misc

* chore: misc

* fix: readme

* chore: update docs

* fix(bluecore): address PR #4353 reviewer feedback and API documentation corrections

✅ Complete reviewer feedback resolution:
- Removed all 16 'NEEDS REVIEW' placeholders with concrete information
- Removed AI-generated optimization recommendations section
- Simplified repetitive business logic content by creating detailed businesslogic.md
- Updated documentation structure to follow rs-ai repository standards

🔧 API Documentation Corrections:
- Corrected API type from 'Transactional API' to 'Events API' throughout documentation
- Updated endpoint information to reflect actual implementation: https://api.bluecore.app/api/track/mobile/v1
- Fixed authentication method documentation (namespace token in payload vs Bearer header)
- Updated rate limiting information to reflect Events API (removed incorrect Transactional API limits)
- Updated References section with official Events API documentation link

📚 Documentation Structure Improvements:
- Created comprehensive businesslogic.md with detailed field mappings and transformation flows
- Streamlined main README by removing repetitive sections and adding cross-references
- Consolidated error handling, testing, and performance sections
- Updated RETL documentation for consistency

🔍 Code Analysis Verification:
- Verified endpoint match between code implementation and documentation
- Confirmed authentication method matches actual implementation
- Validated all API references against official Bluecore Events API documentation

Files modified:
- src/cdk/v2/destinations/bluecore/README.md (extensive updates)
- src/cdk/v2/destinations/bluecore/docs/businesslogic.md (created)
- src/cdk/v2/destinations/bluecore/docs/retl.md (updated)

The documentation now accurately reflects the actual Bluecore Events API implementation
and provides reliable information for users integrating with Bluecore through RudderStack.

* chore: docs

* chore: review comments

* fix: review comments

* fix: review comments

* fix: review comments

* chore: improve release check reliability

* fix: ensure the testing tool is cross-platform compatible (#4401)

* fix: make testing tool compatible with cross plateform

* fix: review comments

* fix: review comments

* chore: update klaviyo version to 2024-10-15, remove config restricted changes (#4387)

* chore: criteo audience api version upgrade (#4382)

* chore: criteo audience api version upgrade

* chore: add destination integration doc

* chore: resolving comments

* chore: groupEventsByType function optimization (#4398)

* fix: rt event ordering for hs (#4397)

* fix: router output ordering for tiktok_ads

* fix: test

* fix: test

* fix: test

* fix: rt event ordering for hs

* test: configure batch processing defaults for component tests

* fix: test folder structure for destinations (#4414)

* feat: update workflow to raise pr for dedicated transformer from operator (#4413)

* feat: update workflow to raise pr for dedicated transformer from operator

* Update .github/workflows/prepare-for-prod-dt-deploy.yml

Co-authored-by: Krishna Chaitanya <[email protected]>

* chore: revert rollback changes

---------

Co-authored-by: Sudip Paul <[email protected]>
Co-authored-by: Krishna Chaitanya <[email protected]>

* chore: remove broken workflow to updating dedicated deployment (#4418)

chore: remove broken updating dedicated deployment workflow

Co-authored-by: Sudip Paul <[email protected]>

* chore: update node version to 20.19.2 (#4416)

* chore(mailchimp): add router test with inputs contains different destnations (#4419)

* chore(mailchimp): add router test with inputs contains different destinations

* chore: misc

* chore(release): 1.103.0

* fix: enhance config object in ga4 v2 instead of mutating it (#4436)

* fix: enhance config object in ga4v2 instead of mutation

* chore: update changelog

---------

Co-authored-by: Utsab Chowdhury <[email protected]>
Co-authored-by: Mahesh Kutty <[email protected]>
Co-authored-by: Dilip Kola <[email protected]>
Co-authored-by: Aris Tzoumas <[email protected]>
Co-authored-by: Vinay Teki <[email protected]>
Co-authored-by: Sudip Paul <[email protected]>
Co-authored-by: Dilip Kola <[email protected]>
Co-authored-by: Yashasvi Bajpai <[email protected]>
Co-authored-by: Manish Kumar <[email protected]>
Co-authored-by: Sudip Paul <[email protected]>
Co-authored-by: Krishna Chaitanya <[email protected]>
Co-authored-by: GitHub Actions <[email protected]>
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.

5 participants