Skip to content

fix: add mapping of event_source instead of static value - #4497

Merged
ItsSudip merged 6 commits into
developfrom
fix/tiktok_ads_v2
Aug 18, 2025
Merged

ItsSudip merged 6 commits into
developfrom
fix/tiktok_ads_v2

Conversation

@ItsSudip

@ItsSudip ItsSudip commented Jul 15, 2025 •

Copy link
Copy Markdown
Member

What are the changes introduced in this PR?

This PR enhances the TikTok Ads V2 destination integration by implementing dynamic event source mapping instead of using static values. The changes focus on improving data accuracy, enhancing batching logic, and providing comprehensive test coverage.

Core Changes

  1. Dynamic Event Source Resolution:

    • Updated getEventSource utility in src/v0/destinations/tiktok_ads/util.js to dynamically resolve event sources from message properties
    • Added support for multiple property sources: eventSource, event_source, and channel
    • Implemented validation against TikTok's supported event source values: ['web', 'app', 'offline', 'crm']
    • Added backward compatibility mapping for legacy sources (mobile → app, server/sources → offline)
  2. Enhanced Batching Logic:

    • Implemented event source-based grouping in processRouterDest function using groupByInBatches
    • Events are now grouped by event_source before batching, improving processing efficiency
    • Added forEachInBatches for better event processing and source-based grouping
  3. Mobile Advertising ID Support:

    • Enhanced hashUserField function to properly handle idfa and gaid fields
    • Added OS-specific filtering for mobile advertising identifiers
    • Improved hashing logic for mobile device IDs
  4. New Field Mappings:

    • Added comprehensive app-related fields to TikTokTrackV2.json:
      • app.app_id, app.app_name, app.app_version
    • Added advertising-related fields:
      • ad.callback, ad.campaign_id, ad.ad_id, ad.creative_id
      • ad.is_retargeting, ad.attributed, ad.attribution_type, ad.attribution_provider
  5. Comprehensive Test Coverage:

    • Added 8+ new test cases for getEventSource function covering all scenarios
    • Enhanced test data with contents_ids, num_items, and eventSource: 'app' properties
    • Added OS-specific testing for iOS/Android device ID handling
    • Updated test data from channel: 'web' to channel: 'app' in relevant test cases

What is the related Linear task?

https://linear.app/rudderstack/issue/INT-3933/investigate-hardcoded-event-source-in-tiktok-ads-v2-integration

Please explain the objectives of your changes below

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

Previous Behavior: The event source was always set to the static value 'web', regardless of the actual source of the event. This limited flexibility and did not accurately represent the true event source.

New Behavior:

  • Dynamic event source resolution based on message properties
  • Support for all TikTok-supported event source values (web, app, offline, crm)
  • Proper validation and fallback mechanisms
  • Enhanced batching with source-based grouping

Reason for Change: The static approach limited data granularity and could impact downstream analytics. The dynamic approach provides more accurate event attribution and better aligns with TikTok's requirements.

Any new dependencies introduced with this change?

No new external dependencies were introduced. The changes utilize existing utility functions from @rudderstack/integrations-lib such as groupByInBatches and forEachInBatches.

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

Modified Utilities:

  1. getEventSource function: Enhanced with comprehensive source resolution logic, validation, and backward compatibility mapping
  2. hashUserField function: Improved to handle mobile advertising IDs with OS-specific filtering
  3. processRouterDest function: Enhanced with event source-based grouping for better batching

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

Performance Improvements:

  • Event source-based grouping reduces processing overhead
  • More efficient batching logic with groupByInBatches
  • Better memory utilization through optimized event processing

Technical Considerations:

  • Maintains backward compatibility with existing integrations
  • Validates event sources against TikTok's supported values
  • Provides proper fallback mechanisms for edge cases
  • Enhanced error handling and logging for better debugging

Success Criteria

  • Only valid TikTok event source values (web, app, offline, crm) are returned
  • All new and existing tests pass (96.5% coverage on new code)
  • No regressions in related TikTok Ads functionality
  • Enhanced batching logic works correctly with event source grouping
  • Mobile advertising IDs are properly hashed and filtered based on OS
  • Backward compatibility maintained for existing integrations

Developer checklist

  • My code follows the style guidelines of this project
  • 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.
  • Code follows best practices and maintains backward compatibility
  • Test coverage is comprehensive and includes edge cases
  • Performance implications have been considered

@ItsSudip
ItsSudip requested review from a team and sivashanmukh as code owners July 15, 2025 04:39
@ItsSudip
ItsSudip requested review from a team, sandeepdsvs and vinayteki95 July 15, 2025 04:39
@coderabbitai

coderabbitai Bot commented Jul 15, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Dynamic event source detection and propagation across events.
    • Per-source batching for more accurate processing.
    • Payload enrichment: adds contents_ids and num_items when item data is present.
  • Bug Fixes

    • OS-aware user identifier filtering to respect platform privacy (e.g., remove incompatible IDs per OS).
  • Refactor

    • Streamlined batching and routing flow for clearer separation of test vs. regular events and deterministic result ordering.
  • Tests

    • Added coverage for event source resolution, contents enrichment, and platform-specific identifier handling.

Walkthrough

Dynamic event_source detection and per-source batching were added to the TikTok Ads transformer; payloads are enriched with content-level fields, device identifiers are sanitized based on OS, test events are separated, processed events are grouped/batched per resolved event_source, and final responses are deterministically ordered by jobId.

Changes

Cohort / File(s) Change Summary
TikTok Ads transform core
src/v0/destinations/tiktok_ads/transformV2.js
Added contents enrichment (contents_ids, num_items); OS-aware removal of device IDs (idfa, idfv, gaid); replaced hardcoded web with dynamic getEventSource(message); refactored batching (getEventChunks → separateTestEvents, added buildResponseList); changed batchEvents signature to (processedEvents, eventSource); updated processRouterDest to group by event_source, batch per group, and sort final responses by jobId. Function names/signatures updated accordingly.
Utilities
src/v0/destinations/tiktok_ads/util.js
Extended hashUserField to hash idfa and gaid; added getEventSource to resolve event source from properties.eventSource / event_source or channel with legacy mappings (mobile→app, server/sources→offline) and allowed set (web,app,offline,crm); updated exports to include getEventSource.
Utility tests
src/v0/destinations/tiktok_ads/util.test.js
Imported getEventSource; added tests for hashing idfa/gaid and arrays of phones; new test suite for getEventSource covering precedence, fallbacks, snake_case support, and legacy mappings.
Transform tests
src/v0/destinations/tiktok_ads/transformV2.test.js
Added tests verifying contents_ids/num_items enrichment, OS-specific device ID filtering (Apple vs Android), and propagation of snake_case event_source; removed an unused import.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant TransformV2
    participant Util

    Client->>TransformV2: Send event message
    TransformV2->>Util: getEventSource(message)
    Util-->>TransformV2: resolved event_source
    TransformV2->>TransformV2: Enrich properties.contents with contents_ids, num_items (if present)
    TransformV2->>TransformV2: Sanitize user IDs based on OS (remove idfa/idfv/gaid accordingly)
    TransformV2->>TransformV2: separateTestEvents(...) -> separate test vs regular events
    TransformV2->>TransformV2: Group processedEvents by event_source
    TransformV2->>TransformV2: batchEvents(processedEventsGroup, event_source) -> buildResponseList(...)
    TransformV2-->>Client: Return ordered list of batched responses + test events + errors (sorted by jobId)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~35 minutes

Possibly related PRs

Suggested labels

DO NOT MERGE

Suggested reviewers

  • sivashanmukh
  • maheshkutty
  • krishna2020
  • yashasvibajpai

Suggestions for improvement

  • Add an integration test that mixes events with multiple event_source values to validate per-source batching and final ordering.
  • Document getEventSource precedence and legacy mappings in the util file or README.
  • Add tests for malformed device ID formats and edge cases (e.g., arrays with mixed types) to ensure hashing/sanitization is robust.

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/tiktok_ads_v2

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@ItsSudip
ItsSudip changed the base branch from develop to main July 15, 2025 04:39

@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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9064e3a and 6c61d87.

⛔ Files ignored due to path filters (1)
  • test/integrations/destinations/tiktok_ads/router/data.ts is excluded by !**/test/**
📒 Files selected for processing (3)
  • src/v0/destinations/tiktok_ads/transformV2.js (4 hunks)
  • src/v0/destinations/tiktok_ads/util.js (1 hunks)
  • src/v0/destinations/tiktok_ads/util.test.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

Instructions used from:

Sources:
⚙️ CodeRabbit Configuration File

🧠 Learnings (4)
📓 Common learnings
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4380
File: src/v0/destinations/google_adwords_remarketing_lists/config.js:3-5
Timestamp: 2025-06-04T07:24:58.591Z
Learning: User maheshkutty prefers to handle Google Ads API version upgrades for different destinations in separate pull requests rather than bundling multiple destinations together in a single PR.
Learnt from: krishna2020
PR: rudderlabs/rudder-transformer#4178
File: src/sources/shopify/transform.js:37-45
Timestamp: 2025-03-21T12:32:28.443Z
Learning: The getBodyFromV2SpecPayload function in Shopify source transformation throws an error if request is not defined, making additional null checks in getEventFromV2Request function unnecessary.
src/v0/destinations/tiktok_ads/util.test.js (1)
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2024-07-27T07:02:57.329Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.
src/v0/destinations/tiktok_ads/transformV2.js (5)
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
Learnt from: krishna2020
PR: rudderlabs/rudder-transformer#4178
File: src/sources/shopify/transform.js:37-45
Timestamp: 2025-03-21T12:32:28.443Z
Learning: The getBodyFromV2SpecPayload function in Shopify source transformation throws an error if request is not defined, making additional null checks in getEventFromV2Request function unnecessary.
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4380
File: src/v0/destinations/google_adwords_remarketing_lists/config.js:3-5
Timestamp: 2025-06-04T07:24:58.591Z
Learning: User maheshkutty prefers to handle Google Ads API version upgrades for different destinations in separate pull requests rather than bundling multiple destinations together in a single PR.
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4364
File: src/v0/util/index.js:2220-2242
Timestamp: 2025-06-02T06:25:17.338Z
Learning: In the rudderlabs/rudder-transformer codebase, jobId values are guaranteed by system contract to always be valid numbers and never undefined or infinite. Additional validation for these edge cases in sorting functions like sortBatchesByMinJobId is not necessary.
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.
src/v0/destinations/tiktok_ads/util.js (2)
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.
Learnt from: krishna2020
PR: rudderlabs/rudder-transformer#4178
File: src/sources/shopify/transform.js:37-45
Timestamp: 2025-03-21T12:32:28.443Z
Learning: The getBodyFromV2SpecPayload function in Shopify source transformation throws an error if request is not defined, making additional null checks in getEventFromV2Request function unnecessary.
🧬 Code Graph Analysis (2)
src/v0/destinations/tiktok_ads/util.test.js (1)
src/v0/destinations/tiktok_ads/util.js (2)
  • message (11-11)
  • getEventSource (70-86)
src/v0/destinations/tiktok_ads/util.js (1)
src/v0/destinations/tiktok_ads/transformV2.js (1)
  • eventSource (686-686)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
src/v0/destinations/tiktok_ads/util.js (1)

64-86: Well-implemented utility function with proper fallback logic.

The getEventSource function correctly implements the precedence hierarchy (eventSource → channel → default) and includes appropriate null safety checks. The documentation clearly references the TikTok Business API documentation and the logic aligns with the supported event sources.

src/v0/destinations/tiktok_ads/util.test.js (1)

176-209: Comprehensive test coverage for the getEventSource utility.

The test suite effectively covers all critical scenarios including valid inputs, fallback behavior, edge cases, and precedence logic. The test cases are well-structured and provide good validation for the utility function.

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

134-134: Correct implementation for single event transformation.

The integration of getEventSource(message) properly replaces the hardcoded 'web' value with dynamic event source determination.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@codecov

codecov Bot commented Jul 15, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.27586% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 91.80%. Comparing base (a0d4325) to head (3645d8c).
⚠️ Report is 35 commits behind head on develop.

Files with missing lines Patch % Lines
src/v0/destinations/tiktok_ads/transformV2.js 97.43% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #4497   +/-   ##
========================================
  Coverage    91.79%   91.80%           
========================================
  Files          642      642           
  Lines        33889    33920   +31     
  Branches      8028     8039   +11     
========================================
+ Hits         31110    31141   +31     
- Misses        2527     2549   +22     
+ Partials       252      230   -22     

☔ 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

Copy link
Copy Markdown
Contributor

base branch main?

@ItsSudip

Copy link
Copy Markdown
Member Author

base branch main?

I did it intentionally. We might need to do a hotfix.

Comment thread src/v0/destinations/tiktok_ads/util.js Resolved
@ItsSudip
ItsSudip changed the base branch from main to hotfix/15th.July July 15, 2025 07:14
@ItsSudip ItsSudip changed the title fix: add mapping of event_source instead of static fix: add mapping of event_source instead of static value Jul 15, 2025
krishna2020
krishna2020 previously approved these changes Jul 15, 2025
Comment thread src/v0/destinations/tiktok_ads/util.js Resolved
@ItsSudip
ItsSudip changed the base branch from hotfix/15th.July to develop July 15, 2025 10:57
@ItsSudip
ItsSudip dismissed krishna2020’s stale review July 15, 2025 10:57

The base branch was changed.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

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

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

@ItsSudip
ItsSudip force-pushed the fix/tiktok_ads_v2 branch from 94bc5be to fbe12e7 Compare July 23, 2025 07:18
@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:

@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

♻️ Duplicate comments (1)
src/v0/destinations/tiktok_ads/transformV2.js (1)

798-805: Earlier “last-write-wins” event_source issue fixed by per-source grouping

Grouping by event_source and passing it into batchEvents resolves the overwrite bug previously noted. Nice improvement.

Also applies to: 723-766

🧹 Nitpick comments (3)
src/v0/destinations/tiktok_ads/transformV2.js (3)

85-96: Harden OS checks to avoid type errors and improve robustness

Good OS-aware filtering. Minor safety: guard toLowerCase with a type check to avoid errors if os isn’t a string.

-  if (isDefinedAndNotNull(os) && payload.user) {
-    if (isAppleFamily(os)) {
+  if (isDefinedAndNotNull(os) && payload.user) {
+    if (isAppleFamily(os)) {
       delete payload.user.gaid;
-    } else if (os.toLowerCase() === 'android') {
+    } else if (typeof os === 'string' && os.toLowerCase() === 'android') {
       delete payload.user.idfa;
       delete payload.user.idfv;
     }
   }

768-805: Typo and iteration style in grouping by event_source

  • Rename pocessedEventsGroups → processedEventsGroups.
  • Use Object.entries for clarity and fewer lookups.
-  const pocessedEventsGroups = await groupByInBatches(
+  const processedEventsGroups = await groupByInBatches(
     processedEvents,
     (event) => event.message[0].body.JSON.event_source,
   );

-  Object.keys(pocessedEventsGroups).forEach((eventSource) => {
-    batchedResponseList.push(...batchEvents(pocessedEventsGroups[eventSource], eventSource));
-  });
+  for (const [eventSource, group] of Object.entries(processedEventsGroups)) {
+    batchedResponseList.push(...batchEvents(group, eventSource));
+  }

445-457: Docstring typos and clarity

Minor typos: “proecessedEvents” → “processedEvents”, “metadat” → “metadata”. Consider tightening the description.

- * This clubs proecessedEvents request body and metadat based upon maxBatchSize
+ * This batches processedEvents (body and metadata) up to maxBatchSize
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between acf1d7b02845bdc8da2ddad01dedd94b54cb3762 and 691785a3ec24827fcf5ba7fa21e3fea9df269346.

📒 Files selected for processing (1)
  • src/v0/destinations/tiktok_ads/transformV2.js (11 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit Configuration File

Focus on ESLint errors (max 3) and warnings (max 5).

Files:

  • src/v0/destinations/tiktok_ads/transformV2.js
🧠 Learnings (4)
📓 Common learnings
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4497
File: src/v0/destinations/tiktok_ads/transformV2.js:686-691
Timestamp: 2025-07-15T06:27:07.528Z
Learning: For TikTok Ads destination in src/v0/destinations/tiktok_ads/transformV2.js, there are plans for a future enhancement to group events by eventSource when batching to ensure all events in a batch have the same event_source value, as acknowledged by ItsSudip in PR #4497.
📚 Learning: 2025-07-15T06:27:07.528Z
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4497
File: src/v0/destinations/tiktok_ads/transformV2.js:686-691
Timestamp: 2025-07-15T06:27:07.528Z
Learning: For TikTok Ads destination in src/v0/destinations/tiktok_ads/transformV2.js, there are plans for a future enhancement to group events by eventSource when batching to ensure all events in a batch have the same event_source value, as acknowledged by ItsSudip in PR #4497.

Applied to files:

  • src/v0/destinations/tiktok_ads/transformV2.js
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.

Applied to files:

  • src/v0/destinations/tiktok_ads/transformV2.js
📚 Learning: 2025-06-04T07:24:58.591Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4380
File: src/v0/destinations/google_adwords_remarketing_lists/config.js:3-5
Timestamp: 2025-06-04T07:24:58.591Z
Learning: User maheshkutty prefers to handle Google Ads API version upgrades for different destinations in separate pull requests rather than bundling multiple destinations together in a single PR.

Applied to files:

  • src/v0/destinations/tiktok_ads/transformV2.js
🧬 Code Graph Analysis (1)
src/v0/destinations/tiktok_ads/transformV2.js (3)
src/v0/destinations/tiktok_ads/util.js (2)
  • message (11-11)
  • getEventSource (78-111)
src/v0/destinations/tiktok_ads/config.js (1)
  • PARTNER_NAME (18-18)
src/v0/util/index.js (8)
  • payload (1080-1080)
  • get (14-14)
  • message (1162-1162)
  • message (1196-1196)
  • getSuccessRespEvents (499-511)
  • metadata (959-971)
  • metadata (1986-1986)
  • sortBatchesByMinJobId (2274-2279)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (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 (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
src/v0/destinations/tiktok_ads/transformV2.js (5)

4-10: Imports updated appropriately for new batching and OS logic

The added utilities (groupByInBatches, get) and isAppleFamily/getEventSource support the new behavior. No issues.

Also applies to: 25-27


166-170: Dynamic event_source via getEventSource — LGTM

Correctly derives supported values with sensible defaults; matches PR goals.


436-443: Helper wrapper for batched responses — LGTM

buildResponseList composes batch responses correctly with batched=true.


409-420: Batch request builder — LGTM

Correct headers, endpoint, and body assignment for TikTok batch track API.


808-809: No action needed: error responses already use metadata arrays
I’ve confirmed that handleRtTfSingleEventError calls getErrorRespEvents([input.metadata], …), so every entry in errorRespList has its metadata wrapped in an array as expected. The final sortBatchesByMinJobId call can safely assume metadata is always an array.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/v0/destinations/tiktok_ads/transformV2.js (1)

422-434: Fix array passing issue for test events.

The code passes the entire message array to getSuccessRespEvents instead of the single request object, which could cause downstream issues.

Apply this fix:

   if (event.message[0].body.JSON.test_event_code) {
-    const { metadata, destination, message } = event;
-    processedTestEvents.push(getSuccessRespEvents(message, [metadata], destination));
+    const { metadata, destination } = event;
+    processedTestEvents.push(getSuccessRespEvents(event.message[0], [metadata], destination));
   } else {
🧹 Nitpick comments (1)
src/v0/destinations/tiktok_ads/transformV2.js (1)

723-766: Consider safer optional chaining and cleaner iteration pattern.

The current implementation uses unsafe optional chaining and could benefit from more defensive programming.

Consider this safer approach:

-  processedEvents.forEach((event) => {
-    const eventData = event.message[0]?.body.JSON.data;
-    // eslint-disable-next-line no-unsafe-optional-chaining, unicorn/consistent-destructuring
-    if (eventData?.length + data.length > config.maxBatchSizeV2) {
+  for (const event of processedEvents) {
+    const eventData = event.message[0]?.body?.JSON?.data;
+    const eventLen = Array.isArray(eventData) ? eventData.length : 0;
+    if (eventLen + data.length > config.maxBatchSizeV2) {
       responseLists.push(
         buildResponseList({
           event: {
             event_source_id: pixelCode,
             event_source: eventSource,
             partner_name: PARTNER_NAME,
             data: [...data],
           },
           metadata: [...metadata],
           destination,
         }),
       );
       data = [];
       metadata = [];
     }
-    data.push(...eventData);
+    if (eventLen) data.push(...eventData);
     metadata.push(event.metadata);
-  });
+  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6ce55bac1648fb37e14f8aaf93da26a9e62a66de and a5e4405728c6701e315961879d776297b1325d2d.

⛔ Files ignored due to path filters (3)
  • src/v0/destinations/tiktok_ads/data/TikTokTrackV2.json is excluded by !**/*.json
  • 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/transformV2.js (11 hunks)
  • src/v0/destinations/tiktok_ads/transformV2.test.js (1 hunks)
  • src/v0/destinations/tiktok_ads/util.js (2 hunks)
  • src/v0/destinations/tiktok_ads/util.test.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/v0/destinations/tiktok_ads/util.js
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit Configuration File

Focus on ESLint errors (max 3) and warnings (max 5).

Files:

  • src/v0/destinations/tiktok_ads/transformV2.test.js
  • src/v0/destinations/tiktok_ads/transformV2.js
  • src/v0/destinations/tiktok_ads/util.test.js
🧠 Learnings (5)
📓 Common learnings
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4497
File: src/v0/destinations/tiktok_ads/transformV2.js:686-691
Timestamp: 2025-07-15T06:27:07.528Z
Learning: For TikTok Ads destination in src/v0/destinations/tiktok_ads/transformV2.js, there are plans for a future enhancement to group events by eventSource when batching to ensure all events in a batch have the same event_source value, as acknowledged by ItsSudip in PR #4497.
📚 Learning: 2025-07-15T06:27:07.528Z
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4497
File: src/v0/destinations/tiktok_ads/transformV2.js:686-691
Timestamp: 2025-07-15T06:27:07.528Z
Learning: For TikTok Ads destination in src/v0/destinations/tiktok_ads/transformV2.js, there are plans for a future enhancement to group events by eventSource when batching to ensure all events in a batch have the same event_source value, as acknowledged by ItsSudip in PR #4497.

Applied to files:

  • src/v0/destinations/tiktok_ads/transformV2.test.js
  • src/v0/destinations/tiktok_ads/transformV2.js
  • src/v0/destinations/tiktok_ads/util.test.js
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` is used by both Mixpanel and Google AdWords Offline Conversions destinations in production. The function assumes metadata is always an array in multiple operations (forEach, filter, sort, map) and needs defensive programming to handle non-array metadata cases to prevent runtime errors.

Applied to files:

  • src/v0/destinations/tiktok_ads/transformV2.js
📚 Learning: 2025-06-04T07:24:58.591Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4380
File: src/v0/destinations/google_adwords_remarketing_lists/config.js:3-5
Timestamp: 2025-06-04T07:24:58.591Z
Learning: User maheshkutty prefers to handle Google Ads API version upgrades for different destinations in separate pull requests rather than bundling multiple destinations together in a single PR.

Applied to files:

  • src/v0/destinations/tiktok_ads/transformV2.js
📚 Learning: 2025-05-29T13:29:39.436Z
Learnt from: maheshkutty
PR: rudderlabs/rudder-transformer#4359
File: src/v0/util/index.js:2272-2272
Timestamp: 2025-05-29T13:29:39.436Z
Learning: The `combineBatchRequestsWithSameJobIds` function in `src/v0/util/index.js` assumes metadata is always an array throughout its implementation, but defensive programming should be added to handle cases where metadata might not be an array type to prevent runtime errors.

Applied to files:

  • src/v0/destinations/tiktok_ads/transformV2.js
🧬 Code Graph Analysis (3)
src/v0/destinations/tiktok_ads/transformV2.test.js (3)
src/v0/destinations/tiktok_ads/util.js (1)
  • message (11-11)
src/v0/destinations/tiktok_ads/transformV2.js (4)
  • config (28-28)
  • config (30-36)
  • trackResponseBuilder (108-173)
  • data (725-725)
src/v0/destinations/tiktok_ads/transform.js (1)
  • trackResponseBuilder (132-161)
src/v0/destinations/tiktok_ads/transformV2.js (2)
src/v0/destinations/tiktok_ads/util.js (2)
  • message (11-11)
  • getEventSource (78-111)
src/v0/util/index.js (7)
  • get (14-14)
  • message (1162-1162)
  • message (1196-1196)
  • getSuccessRespEvents (499-511)
  • metadata (959-971)
  • metadata (1986-1986)
  • sortBatchesByMinJobId (2274-2279)
src/v0/destinations/tiktok_ads/util.test.js (1)
src/v0/destinations/tiktok_ads/util.js (2)
  • hashUserField (37-70)
  • getEventSource (78-111)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (11)
src/v0/destinations/tiktok_ads/util.test.js (3)

175-185: LGTM! Comprehensive testing for device ID hashing.

The test correctly verifies that both idfa and gaid fields are hashed when present, ensuring data privacy for mobile device identifiers.


187-196: LGTM! Good coverage for array phone number hashing.

The test properly validates the array handling logic for phone numbers, which aligns with the existing external_id array test pattern.


199-243: Well-structured test suite for getEventSource utility.

The test suite provides excellent coverage of the event source resolution logic, including:

  • Priority order validation (eventSource > event_source > channel)
  • Fallback to "web" for invalid/missing values
  • Backward compatibility mappings (mobile → app)
  • Snake_case support
src/v0/destinations/tiktok_ads/transformV2.test.js (4)

144-166: Excellent test for content enrichment feature.

The test effectively validates the new contents_ids and num_items fields are correctly populated from product data.


168-188: Good OS-specific privacy handling test for iOS.

The test correctly verifies that gaid is removed for Apple devices while idfa remains defined.


190-211: Proper Android privacy test coverage.

The test validates that idfa and idfv are removed for Android while gaid remains defined.


213-231: Good validation of snake_case event_source support.

The test confirms that event_source in snake_case format is properly recognized and used.

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

64-74: LGTM! Content enrichment implementation is correct.

The implementation properly extracts content_id values and only adds contents_ids and num_items when valid IDs are present, addressing the previous review comment about aligning these fields.


85-95: Well-implemented OS-based privacy filtering.

The code correctly removes device identifiers based on the operating system to comply with platform-specific privacy requirements.


166-166: Good integration of dynamic event source resolution.

Using getEventSource(message) instead of a hardcoded value provides proper flexibility for event source determination.


797-805: Excellent implementation of event source-based batching!

The implementation properly groups events by event_source before batching, which aligns with the acknowledged future enhancement plan from the previous review. This ensures all events in a batch have the same event source value.

Sudip Paul and others added 6 commits August 16, 2025 10:16
… batching logic with grouping (#4501)

* feat: enable group by event_source before batching

* feat: add missing parameter for app event_source

* chore: refactor test cases

* chore: revert unwanted changes to test cases

---------

Co-authored-by: Sudip Paul <[email protected]>
* feat: add missing parameters and refactor code

* chore: fix as per cursor review

* chore: add test cases to increase coverage

* feat: add support of mapping to consider default eventSource

---------

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
src/v0/destinations/tiktok_ads/util.js (2)

61-67: Normalize and consistently hash mobile IDs (IDFA/GAID).

Lowercasing the hex after hashing IDFA while not doing the same for GAID is inconsistent and not equivalent to normalizing inputs pre-hash. To avoid discrepancies across clients and align with common partner requirements, normalize inputs before hashing (strip hyphens and lowercase), and keep output casing consistent.

Apply this diff:

-  if (idfa) {
-    updatedUser.idfa = hashString(idfa).toString().toLowerCase();
-  }
-
-  if (gaid) {
-    updatedUser.gaid = hashString(gaid).toString();
-  }
+  if (idfa) {
+    const normalizedIdfa = idfa.toString().replace(/-/g, '').toLowerCase();
+    updatedUser.idfa = hashString(normalizedIdfa).toString();
+  }
+
+  if (gaid) {
+    const normalizedGaid = gaid.toString().replace(/-/g, '').toLowerCase();
+    updatedUser.gaid = hashString(normalizedGaid).toString();
+  }

78-111: Make event source resolution case-insensitive and whitespace-tolerant.

Inputs like " Mobile " or "APP" should resolve correctly. Normalizing strings reduces edge cases and support burden.

Apply this diff:

 const getEventSource = ({ properties, channel }) => {
   const supportedSources = ['web', 'app', 'offline', 'crm'];

   // Mapping for backward compatibility and new mappings
   const sourceMapping = {
     web: 'web',
     mobile: 'app',
     server: 'offline',
     sources: 'offline',
   };

   const { eventSource, event_source: eventSourceV2 } = properties || {};

   // Helper function to resolve source with mapping
-  const resolveSource = (source) => {
-    if (!source) return null;
-
-    // First check if it's a direct supported source
-    if (supportedSources.includes(source)) {
-      return source;
-    }
-
-    // Then check if it needs mapping
-    if (sourceMapping[source]) {
-      return sourceMapping[source];
-    }
-
-    return null;
-  };
+  const normalize = (val) => (typeof val === 'string' ? val.trim().toLowerCase() : val);
+  const resolveSource = (source) => {
+    const s = normalize(source);
+    if (!s) return null;
+    if (supportedSources.includes(s)) {
+      return s;
+    }
+    if (sourceMapping[s]) {
+      return sourceMapping[s];
+    }
+    return null;
+  };

   return (
     resolveSource(eventSource) || resolveSource(eventSourceV2) || resolveSource(channel) || 'web'
   );
 };
src/v0/destinations/tiktok_ads/util.test.js (2)

175-197: Expand assertions to validate normalization behavior (if adopted).

Current tests ensure idfa/gaid are hashed. If we normalize inputs pre-hash (strip hyphens + lowercase), add assertions to lock in that behavior and prevent regressions.

Example additions:

it('normalizes IDFA/GAID before hashing (strip hyphens, lowercase)', () => {
  const user = {
    idfa: 'AEBE52E7-03EE-455A-B3C4-E57283966239',
    gaid: '38400000-8CF0-11BD-B23E-10B96E40000D',
  };
  const hashedUser = hashUserField(user);
  // compute expected hashes inline if you have a local hasher util exposed to tests,
  // otherwise at least assert lowercase hex format:
  expect(/^[a-f0-9]{64}$/.test(hashedUser.idfa)).toBe(true);
  expect(/^[a-f0-9]{64}$/.test(hashedUser.gaid)).toBe(true);
});

199-244: Add test cases for mappings and input normalization in getEventSource.

You’ve covered core paths. Consider adding:

  • Mapping checks: 'server' and 'sources' → 'offline'
  • Channel mapping for 'mobile' → 'app'
  • Case/whitespace normalization: ' APP ', 'Mobile', ' CRM ' resolve as expected

Proposed additions:

it('maps eventSource="server" to "offline"', () => {
  expect(getEventSource({ properties: { eventSource: 'server' } })).toBe('offline');
});

it('maps channel="sources" to "offline" when properties are absent', () => {
  expect(getEventSource({ properties: {}, channel: 'sources' })).toBe('offline');
});

it('maps channel="mobile" to "app" when eventSource missing', () => {
  expect(getEventSource({ properties: {}, channel: 'mobile' })).toBe('app');
});

// If input normalization is adopted:
it('is case-insensitive and trims whitespace', () => {
  expect(getEventSource({ properties: { eventSource: ' APP ' }, channel: 'WEB' })).toBe('app');
  expect(getEventSource({ properties: {}, channel: ' CRM ' })).toBe('crm');
});
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a5e4405728c6701e315961879d776297b1325d2d and 3645d8c.

⛔ Files ignored due to path filters (3)
  • src/v0/destinations/tiktok_ads/data/TikTokTrackV2.json is excluded by !**/*.json
  • 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/transformV2.js (11 hunks)
  • src/v0/destinations/tiktok_ads/transformV2.test.js (1 hunks)
  • src/v0/destinations/tiktok_ads/util.js (2 hunks)
  • src/v0/destinations/tiktok_ads/util.test.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/v0/destinations/tiktok_ads/transformV2.test.js
  • src/v0/destinations/tiktok_ads/transformV2.js
🧰 Additional context used
📓 Path-based instructions (1)
**/*.js

⚙️ CodeRabbit Configuration File

Focus on ESLint errors (max 3) and warnings (max 5).

Files:

  • src/v0/destinations/tiktok_ads/util.js
  • src/v0/destinations/tiktok_ads/util.test.js
🧠 Learnings (2)
📓 Common learnings
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4497
File: src/v0/destinations/tiktok_ads/transformV2.js:686-691
Timestamp: 2025-07-15T06:27:07.528Z
Learning: For TikTok Ads destination in src/v0/destinations/tiktok_ads/transformV2.js, there are plans for a future enhancement to group events by eventSource when batching to ensure all events in a batch have the same event_source value, as acknowledged by ItsSudip in PR #4497.
📚 Learning: 2025-07-15T06:27:07.528Z
Learnt from: ItsSudip
PR: rudderlabs/rudder-transformer#4497
File: src/v0/destinations/tiktok_ads/transformV2.js:686-691
Timestamp: 2025-07-15T06:27:07.528Z
Learning: For TikTok Ads destination in src/v0/destinations/tiktok_ads/transformV2.js, there are plans for a future enhancement to group events by eventSource when batching to ensure all events in a batch have the same event_source value, as acknowledged by ItsSudip in PR #4497.

Applied to files:

  • src/v0/destinations/tiktok_ads/util.js
  • src/v0/destinations/tiktok_ads/util.test.js
🧬 Code Graph Analysis (2)
src/v0/destinations/tiktok_ads/util.js (3)
src/v0/destinations/tiktok_ads/transformV2.js (1)
  • externalId (77-77)
src/v0/util/index.js (1)
  • externalId (1527-1527)
src/v0/destinations/tiktok_ads/transform.js (1)
  • externalId (76-76)
src/v0/destinations/tiktok_ads/util.test.js (2)
src/v0/destinations/tiktok_ads/util.js (4)
  • require (1-1)
  • hashUserField (37-70)
  • message (11-11)
  • getEventSource (78-111)
src/v0/destinations/tiktok_ads/transformV2.js (5)
  • require (4-10)
  • require (11-11)
  • require (12-26)
  • require (27-27)
  • require (37-37)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • 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: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
src/v0/destinations/tiktok_ads/util.js (2)

40-40: Good addition: IDFA/GAID included in hashing scope.

Including idfa and gaid in the destructuring is aligned with the PR goal to hash mobile identifiers. No issues here.


113-113: Export update looks correct.

Exporting getEventSource alongside existing utilities is consistent with its usage in transformV2. No concerns.

src/v0/destinations/tiktok_ads/util.test.js (1)

1-1: Import update is correct.

Tests now cover getEventSource from util.js as expected.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@sonarqubecloud

Copy link
Copy Markdown

@ItsSudip
ItsSudip merged commit d4f20b6 into develop Aug 18, 2025
@ItsSudip
ItsSudip deleted the fix/tiktok_ads_v2 branch August 18, 2025 06:23
@ItsSudip
ItsSudip restored the fix/tiktok_ads_v2 branch August 22, 2025 07:15
@devops-github-rudderstack
devops-github-rudderstack deleted the fix/tiktok_ads_v2 branch November 17, 2025 01:31
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