Skip to content

fix: router output ordering for tiktok_ads - #4364

Closed
maheshkutty wants to merge 5 commits into
developfrom
fix.tiktok_ads_batch_ordering
Closed

maheshkutty wants to merge 5 commits into
developfrom
fix.tiktok_ads_batch_ordering

Conversation

@maheshkutty

@maheshkutty maheshkutty commented May 30, 2025 •

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

This pull request introduces a new utility function, sortBatchesByMinJobId, to ensure consistent ordering of batched requests based on the minimum jobId in their metadata. The function is integrated into multiple files, enhancing batch processing logic for TikTok Ads transformations and other utilities. Additionally, comprehensive unit tests have been added to validate its behavior across various scenarios.

Enhancements to batch processing:

  • Utility function addition: Added sortBatchesByMinJobId in src/v0/util/index.js to sort batches by the minimum jobId in their metadata, ensuring consistent ordering. This replaces inline sorting logic in multiple places. [1] [2] [3]
  • Integration in TikTok Ads transformations: Updated processRouterDest in both src/v0/destinations/tiktok_ads/transform.js and src/v0/destinations/tiktok_ads/transformV2.js to use sortBatchesByMinJobId for sorting batched responses. [1] [2]

Testing improvements:

  • Unit tests for sortBatchesByMinJobId: Added extensive test cases in src/v0/util/index.test.js to validate sorting functionality, including edge cases like empty arrays, single metadata items, and already sorted inputs.

Code cleanup:

  • Removed redundant logic: Eliminated inline sorting code in combineBatchRequestsWithSameJobIds and replaced it with the new utility function for better reusability and maintainability.

Other changes:

  • TikTok Ads integration test adjustment: Removed TikTok Ads-specific exclusion in test/integrations/component.test.ts, likely as part of broader test cleanup or updates.

What is the related Linear task?

Resolves INT-3733

Please explain the objectives of your changes below

Put down any required details on the broader aspect of your changes. If there are any dependent changes, mandatorily mention them here

Any changes to existing capabilities/behaviour, mention the reason & what are the changes ?

N/A

Any new dependencies introduced with this change?

N/A

Any new generic utility introduced or modified. Please explain the changes.

N/A

Any technical or performance related pointers to consider with the change?

N/A

@coderabbitai review


Developer checklist

  • My code follows the style guidelines of this project

  • No breaking changes are being introduced.

  • All related docs linked with the PR?

  • All changes manually tested?

  • Any documentation changes needed with this change?

  • Is the PR limited to 10 file changes?

  • Is the PR limited to one linear task?

  • Are relevant unit and component test-cases added in new readability format?

Reviewer checklist

  • Is the type of change in the PR title appropriate as per the changes?

  • Verified that there are no credentials or confidential data exposed with the changes.

@maheshkutty
maheshkutty requested review from a team and sivashanmukh as code owners May 30, 2025 10:47
@maheshkutty
maheshkutty requested review from a team, manish339k and vinayteki95 May 30, 2025 10:47
@coderabbitai

coderabbitai Bot commented May 30, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • test/integrations/destinations/tiktok_ads/router/data.ts is excluded by !**/test/**

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Summary by CodeRabbit

  • Bug Fixes
    • Improved the ordering of processed event batches for TikTok Ads to ensure events are sorted by job ID, preventing potential out-of-order issues.
  • New Features
    • Introduced enhanced sorting for event batches based on job ID to provide more consistent and reliable event processing.
  • Tests
    • Added comprehensive tests to verify correct sorting of event batches by job ID.

Summary by CodeRabbit

  • New Features

    • Responses for TikTok Ads destinations are now sorted by job ID to ensure correct event order.
  • Bug Fixes

    • Resolved potential issues with out-of-order events in TikTok Ads integrations.
  • Tests

    • Added comprehensive tests to verify correct sorting of event batches by job ID.

Walkthrough

This change introduces a new utility function, sortBatchesByMinJobId, to consistently sort batched response arrays by the minimum jobId in their metadata. The function is applied in both TikTok Ads destination modules and replaces manual sorting logic. Comprehensive unit tests for the utility are also added.

Changes

File(s) Change Summary
src/v0/destinations/tiktok_ads/transform.js, Updated processRouterDest to return responses sorted by min job ID using the new utility.
src/v0/destinations/tiktok_ads/transformV2.js
src/v0/util/index.js Added sortBatchesByMinJobId utility; refactored batch sorting logic to use this helper.
src/v0/util/index.test.js Added extensive unit tests for sortBatchesByMinJobId, covering multiple edge and normal cases.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant TikTokTransform
    participant Util

    Caller->>TikTokTransform: processRouterDest(...)
    TikTokTransform->>Util: sortBatchesByMinJobId([batched, track, error])
    Util-->>TikTokTransform: Sorted array by min jobId
    TikTokTransform-->>Caller: Sorted combined response
Loading

Possibly related PRs

  • rudderlabs/rudder-transformer#4359: Both PRs address sorting batches by minimum job ID in batch processing utilities, focusing on consistent ordering and improved sorting logic.

Suggested reviewers

  • sivashanmukh
  • krishna2020
  • vinayteki95

Suggestions for improvement:

  • Consider documenting the expected structure of batch objects and their metadata to aid future maintainers in understanding sorting criteria.
  • Evaluate performance implications if batch sizes grow large; optimizing the sorting logic or caching minimum job IDs could improve efficiency.
  • Add integration tests to verify end-to-end correctness of event ordering in the full TikTok Ads pipeline.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 43c1056 and ddae63500ca6464ca26c55367a464f105d685d63.

⛔ Files ignored due to path filters (5)
  • test/integrations/component.test.ts is excluded by !**/test/**
  • test/integrations/destinations/tiktok_ads/common.ts is excluded by !**/test/**
  • test/integrations/destinations/tiktok_ads/dataDelivery/data.ts is excluded by !**/test/**
  • test/integrations/destinations/tiktok_ads/processor/data.ts is excluded by !**/test/**
  • test/integrations/destinations/tiktok_ads/router/data.ts is excluded by !**/test/**
📒 Files selected for processing (4)
  • src/v0/destinations/tiktok_ads/transform.js (2 hunks)
  • src/v0/destinations/tiktok_ads/transformV2.js (2 hunks)
  • src/v0/util/index.js (3 hunks)
  • src/v0/util/index.test.js (2 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.test.js
  • src/v0/destinations/tiktok_ads/transformV2.js
  • src/v0/destinations/tiktok_ads/transform.js
  • src/v0/util/index.js
🧬 Code Graph Analysis (2)
src/v0/destinations/tiktok_ads/transformV2.js (1)
src/v0/util/index.js (1)
  • sortBatchesByMinJobId (2236-2241)
src/v0/destinations/tiktok_ads/transform.js (2)
src/v0/util/index.js (1)
  • sortBatchesByMinJobId (2236-2241)
src/v0/destinations/tiktok_ads/transformV2.js (3)
  • batchedResponseList (751-751)
  • trackResponseList (723-723)
  • errorRespList (725-725)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
src/v0/util/index.js (2)

2291-2291: Good refactoring to use the centralized utility.

The replacement of manual sorting logic with the new utility function improves code maintainability and follows the DRY principle.


2549-2549: Export is correctly added.

The function is properly exported and maintains alphabetical ordering in the exports list.

src/v0/destinations/tiktok_ads/transformV2.js (2)

18-18: Import statement is correctly added.

The import of sortBatchesByMinJobId utility function is properly included.


761-763: Excellent use of the sorting utility with clear documentation.

The replacement of manual array concatenation with sorted results addresses the router output ordering issue effectively. The comments clearly explain the purpose and the specific case where testEventCode properties can cause out-of-order events.

src/v0/destinations/tiktok_ads/transform.js (2)

23-23: Import statement is correctly added.

The import of sortBatchesByMinJobId utility function maintains consistency with the transformV2.js implementation.


286-286: Consistent implementation across transform versions.

The usage of sortBatchesByMinJobId ensures the same ordering behavior as transformV2.js, maintaining consistency across both TikTok Ads transform implementations. This addresses the router output ordering issue mentioned in the PR objectives.

Comment thread src/v0/util/index.js Resolved
Comment thread src/v0/util/index.test.js Outdated
Comment on lines 1410 to 1476

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.

💡 Verification agent

🧩 Analysis chain

Comprehensive test coverage with one logical inconsistency to address.

The test suite provides excellent coverage for the sortEventsBasedMetadataJobId function, including edge cases like empty arrays, negative jobIds, and mixed data types. However, there's a logical inconsistency in the non-numeric jobIds test case.

Issue with non-numeric jobIds test logic:

    it('should handle batches with non-numeric jobIds gracefully (NaN)', () => {
      const input = [
        { metadata: [{ jobId: 'a' }] },
        { metadata: [{ jobId: 2 }] },
        { metadata: [{ jobId: 1 }] },
      ];
-      // Math.min('a') is NaN, so those batches will be sorted to the end
+      // Math.min('a') is NaN, so those batches will be sorted to the end
      const expected = [
-        { metadata: [{ jobId: 'a' }] },
         { metadata: [{ jobId: 1 }] },
         { metadata: [{ jobId: 2 }] },
+        { metadata: [{ jobId: 'a' }] },
      ];
      expect(sortEventsBasedMetadataJobId(input)).toEqual(expected);
    });

The comment correctly states that NaN values should be sorted to the end, but the expected output places the non-numeric jobId first. This contradicts standard sorting behavior where NaN values typically sort last.

Please verify the actual behavior of the sortEventsBasedMetadataJobId function with this test case:


🏁 Script executed:

#!/bin/bash
# Description: Verify the sorting behavior with non-numeric jobIds
# Expected: Non-numeric jobIds (NaN) should sort to the end, not the beginning

# Search for the actual implementation of sortEventsBasedMetadataJobId
rg -A 20 "sortEventsBasedMetadataJobId.*=" --type js

Length of output: 1375


To confirm how non-numeric jobId values are treated in the actual comparator, let’s inspect the implementation of sortEventsBasedMetadataJobId:


🏁 Script executed:

#!/bin/bash
# Locate the implementation of sortEventsBasedMetadataJobId
rg -A 20 'sortEventsBasedMetadataJobId' --type js

Length of output: 8892


Let’s inspect the actual implementation to see how it handles NaN from Math.min:


🏁 Script executed:

#!/bin/bash
# Locate implementation in the utility module
rg -A20 'sortEventsBasedMetadataJobId' -g 'src/v0/util/index.js'

Length of output: 62


To locate the actual implementation and see how it handles NaN, let’s first list all files in the util folder and then search within the index file(s):


🏁 Script executed:

#!/bin/bash
# 1. List all files in src/v0/util to identify the index file extension
find src/v0/util -maxdepth 1 -type f

# 2. Search for the function definition in any index.* file
rg -A20 'sortEventsBasedMetadataJobId' src/v0/util/index.*

Length of output: 9198


Let’s pinpoint where and how sortEventsBasedMetadataJobId is defined and exported in src/v0/util/index.js:


🏁 Script executed:

#!/bin/bash
# 1. Show the exports block to confirm it's being exported
grep -n -C3 "module\\.exports" src/v0/util/index.js

# 2. Search for the function definition anywhere in util
rg -n "sortEventsBasedMetadataJobId" src/v0/util

Length of output: 1283


Incorrect assumption in non-numeric case—update comment or implementation

The current test for non-numeric jobId values actually reflects the implementation’s behavior: since Math.min('a') yields NaN, comparisons against numbers also yield NaN and V8’s stable sort leaves that batch in its original position (first). You have two options:

• If you intend to keep this behavior, update the inline comment to say “batches with non-numeric jobId will remain in original order (so ‘a’ stays first),” instead of “sorted to the end.”
• If you want truly to push non-numeric IDs to the end, change the comparator in sortEventsBasedMetadataJobId to treat NaN as Infinity (e.g. const min = Number.isNaN(rawMin) ? Infinity : rawMin;).

Either way, the test’s expected array (['a', 1, 2]) is correct given the code; only the comment (or the comparator) needs adjustment.

📝 Committable suggestion

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

Suggested change
describe('sortEventsBasedMetadataJobId', () => {
it('should sort batches by the minimum jobId in each batch (ascending)', () => {
const input = [
{ metadata: [{ jobId: 3 }, { jobId: 4 }] },
{ metadata: [{ jobId: 1 }, { jobId: 5 }] },
{ metadata: [{ jobId: 2 }] },
];
const expected = [
{ metadata: [{ jobId: 1 }, { jobId: 5 }] },
{ metadata: [{ jobId: 2 }] },
{ metadata: [{ jobId: 3 }, { jobId: 4 }] },
];
expect(sortEventsBasedMetadataJobId(input)).toEqual(expected);
});
it('should handle batches with single metadata item', () => {
const input = [
{ metadata: [{ jobId: 10 }] },
{ metadata: [{ jobId: 2 }] },
{ metadata: [{ jobId: 5 }] },
];
const expected = [
{ metadata: [{ jobId: 2 }] },
{ metadata: [{ jobId: 5 }] },
{ metadata: [{ jobId: 10 }] },
];
expect(sortEventsBasedMetadataJobId(input)).toEqual(expected);
});
it('should handle batches with multiple metadata items and unordered jobIds', () => {
const input = [
{ metadata: [{ jobId: 8 }, { jobId: 3 }] },
{ metadata: [{ jobId: 2 }, { jobId: 7 }] },
{ metadata: [{ jobId: 5 }, { jobId: 9 }] },
];
const expected = [
{ metadata: [{ jobId: 2 }, { jobId: 7 }] },
{ metadata: [{ jobId: 5 }, { jobId: 9 }] },
{ metadata: [{ jobId: 8 }, { jobId: 3 }] },
];
// Note: The function sorts by the minimum jobId in each batch, so batch 3's min is 3, batch 1's min is 2, batch 2's min is 5
// So after sorting: batch 1 (min 2), batch 3 (min 3), batch 2 (min 5)
// But the expected output should be sorted by min jobId: 2, 3, 5
// Let's fix the expected accordingly:
const sortedExpected = [
{ metadata: [{ jobId: 2 }, { jobId: 7 }] },
{ metadata: [{ jobId: 8 }, { jobId: 3 }] },
{ metadata: [{ jobId: 5 }, { jobId: 9 }] },
];
expect(sortEventsBasedMetadataJobId(input)).toEqual(sortedExpected);
});
it('should handle empty input array', () => {
expect(sortEventsBasedMetadataJobId([])).toEqual([]);
});
it('should handle batches with empty metadata arrays', () => {
const input = [{ metadata: [] }, { metadata: [{ jobId: 2 }] }, { metadata: [] }];
// Math.min(...[]) is Infinity, so batches with empty metadata will be sorted to the end
const expected = [{ metadata: [{ jobId: 2 }] }, { metadata: [] }, { metadata: [] }];
expect(sortEventsBasedMetadataJobId(input)).toEqual(expected);
});
it('should not mutate the original array order if already sorted', () => {
const input = [
{ metadata: [{ jobId: 1 }] },
{ metadata: [{ jobId: 2 }] },
{ metadata: [{ jobId: 3 }] },
];
const expected = [
{ metadata: [{ jobId: 1 }] },
{ metadata: [{ jobId: 2 }] },
{ metadata: [{ jobId: 3 }] },
];
expect(sortEventsBasedMetadataJobId(input)).toEqual(expected);
});
it('should handle negative jobIds', () => {
const input = [
{ metadata: [{ jobId: -5 }, { jobId: 2 }] },
{ metadata: [{ jobId: 0 }] },
{ metadata: [{ jobId: -1 }] },
];
const expected = [
{ metadata: [{ jobId: -5 }, { jobId: 2 }] },
{ metadata: [{ jobId: -1 }] },
{ metadata: [{ jobId: 0 }] },
];
expect(sortEventsBasedMetadataJobId(input)).toEqual(expected);
});
it('should handle batches with non-numeric jobIds gracefully (NaN)', () => {
const input = [
{ metadata: [{ jobId: 'a' }] },
{ metadata: [{ jobId: 2 }] },
{ metadata: [{ jobId: 1 }] },
];
// Math.min('a') is NaN, so those batches will be sorted to the end
const expected = [
{ metadata: [{ jobId: 'a' }] },
{ metadata: [{ jobId: 1 }] },
{ metadata: [{ jobId: 2 }] },
];
expect(sortEventsBasedMetadataJobId(input)).toEqual(expected);
});
});
});
it('should handle batches with non-numeric jobIds gracefully (NaN)', () => {
const input = [
{ metadata: [{ jobId: 'a' }] },
{ metadata: [{ jobId: 2 }] },
{ metadata: [{ jobId: 1 }] },
];
// Math.min('a') is NaN, so those batches will be sorted to the end
const expected = [
{ metadata: [{ jobId: 1 }] },
{ metadata: [{ jobId: 2 }] },
{ metadata: [{ jobId: 'a' }] },
];
expect(sortEventsBasedMetadataJobId(input)).toEqual(expected);
});
🤖 Prompt for AI Agents
In src/v0/util/index.test.js around lines 1410 to 1517, the test case for
batches with non-numeric jobIds has a misleading comment stating that such
batches will be sorted to the end, but the expected output actually keeps them
in their original position. To fix this, update the inline comment to accurately
reflect the current behavior of the function, stating that batches with
non-numeric jobIds remain in their original order rather than being sorted to
the end. Alternatively, if you want to change the behavior to push non-numeric
jobIds to the end, modify the comparator in the sortEventsBasedMetadataJobId
function to treat NaN as Infinity. For now, just correct the comment to match
the existing expected output.

@maheshkutty
maheshkutty force-pushed the fix.tiktok_ads_batch_ordering branch from ddae635 to 9487d78 Compare May 30, 2025 10:54
@codecov

codecov Bot commented May 30, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91.14%. Comparing base (4f48250) to head (61268a3).
Report is 27 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #4364   +/-   ##
========================================
  Coverage    91.13%   91.14%           
========================================
  Files          638      638           
  Lines        33476    33477    +1     
  Branches      7904     7904           
========================================
+ Hits         30509    30513    +4     
+ Misses        2728     2725    -3     
  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.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

2 similar comments
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@maheshkutty
maheshkutty force-pushed the fix.tiktok_ads_batch_ordering branch from d70a152 to 3348ace Compare May 30, 2025 14:04
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

ItsSudip
ItsSudip previously approved these changes Jun 2, 2025
Comment thread src/v0/util/index.test.js Resolved
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

ItsSudip
ItsSudip previously approved these changes Jun 5, 2025
@maheshkutty
maheshkutty force-pushed the fix.tiktok_ads_batch_ordering branch from 9171692 to ca76ecf Compare June 6, 2025 04:40
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@maheshkutty
maheshkutty force-pushed the fix.tiktok_ads_batch_ordering branch from ca76ecf to f71f756 Compare June 10, 2025 06:13
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@sonarqubecloud

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.

3 participants