Skip to content

fix(tiktok_audience): keep batch_data aligned with id_schema - #5519

Closed
arpl wants to merge 1 commit into
developfrom
fix/tiktok-audience-id-schema-alignment
Closed

arpl wants to merge 1 commit into
developfrom
fix/tiktok-audience-id-schema-alignment

Conversation

@arpl

@arpl arpl commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

TikTok reads each batch_data row positionally against id_schema. prepareIdentifiersPayload built the row by iterating the identifiers object and pushing only truthy values, which misaligned it in two independent ways:

  1. A missing identifier produced a shorter row, shifting every later id left. A user with only an email was sent as a one-entry row against a four-entry schema, so TikTok read the email hash as an AAID_SHA256. This is the customer report.
  2. id_schema is sorted, the row was not. The row followed the identifiers object's own key order, so even a fully populated user could be emitted out of order — AAID and PHONE silently swapped. This was not in the report and is the more insidious of the two, since nothing about the record looks wrong.

The fix walks the sorted schema instead of the object, and emits {} for any slot the user has no usable value for.

const idSchema = Object.keys(identifiers).sort();
for (const fieldName of idSchema) {
  let identifier: BatchIdentifier = {};   // holds the slot open
  if (value) { /* validate, normalize, hash */ }
  identifiersList.push(identifier);
}

Events whose slots are all placeholders still abort with No identifiers found — a row of nothing but placeholders identifies no one.

Why {} and not a reordered id_schema

Two independent confirmations that the placeholder is the contract:

  • This repo already does it correctly elsewhere. The legacy audienceList path in transform.ts maps over the schema and emits {} for a missing trait:
    destinationFields.map((f) => trait[f] ? { id: hashIdentifier(f, trait[f]), audience_ids: [audienceId] } : {})
    The two paths disagreed; the older one was right. This change makes the record path match it.
  • Segment's TikTok Audiences destination does the same, with a comment stating the rule: "Even if email and advertising_id are empty we want to include them into the array as we seek to comply with the ID Schema defined outside of this function."

What is the related Linear task?

Not yet filed — reported by Chatbooks in a shared Slack channel and triaged in #. Happy to link one before merge.

Please explain the objectives of your changes below

Restore correct identifier attribution for TikTok audiences. Any record with a missing or invalid identifier currently has its remaining ids attributed to the wrong identifier types, which corrupts audience matching silently — TikTok returns 200 either way. Customers only notice as unexplained low match rates.

The affected customer worked around it by rebuilding their connection to match on email only, which is exactly the configuration in which the bug cannot appear (a single-slot schema is always aligned). Enriching with any additional identifier re-exposes it.

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

batch_data rows now always have exactly id_schema.length entries, where previously they had only as many entries as the record had non-null identifiers. This is the fix, and it is a wire-format change for every record-path TikTok audience payload with a sparse or unsorted identifier set.

test/integrations/destinations/tiktok_audience/router/data.ts — "Native Test 18: record events: invalid identifiers" had frozen the old behaviour into its expected payload (two ids against a four-entry id_schema, i.e. the misalignment itself) and had always passed. Its fixture is updated; please sanity-check that fixture rather than assuming it was collateral damage.

Any new dependencies introduced with this change?

N/A

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

N/A — one new local type, BatchIdentifier = Identifier | IdentifierPlaceholder, so a placeholder is representable.

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

Payload size grows for sparse records (an extra {} per unfilled slot). Grouping is unchanged: it already keys on id_schema, and rows are now uniformly that length.


Verification

Unit — 12/12 in recordTransform.test.ts, including 3 new alignment cases. All three were confirmed to fail before the fix (row length 1 vs schema 4; AAID/PHONE hashes swapped), so they can actually catch a regression.

Component — 16/16 for tiktok_audience. Repo-wide tsc --noEmit, eslint and prettier clean.

End-to-end on a local stack, against the real TikTok API. Transformer built from this branch and deployed into the stack, verified the patched code was actually in the running container, then drove a real rETL sync from a warehouse source into a live TikTok audience with AAID_SHA256, EMAIL_SHA256, PHONE_SHA256 mapped and nulls seeded across every gap shape. The payload was captured off the wire between rudder-server and the transformer:

 20 ok                                    (every row length == id_schema length)
 11 ["AAID_SHA256","EMAIL_SHA256","PHONE_SHA256"]

  5  -           | EMAIL_SHA256 | -              both null
  5  -           | EMAIL_SHA256 | PHONE_SHA256   <- leading gap: the reported bug
  5  AAID_SHA256 | EMAIL_SHA256 | -              trailing gap
  5  AAID_SHA256 | EMAIL_SHA256 | PHONE_SHA256   fully populated

Sync result: 20 changed → 20 successful, 0 failed / dropped / invalid. TikTok accepted the {} placeholders.

Running the identical payload against the current published transformer image reproduces both bugs:

                     BEFORE                          AFTER
row 0  AAID_SHA256   [email protected]   <- bug      (no entry)
       EMAIL_SHA256  (no entry)                      [email protected]
row 1  AAID_SHA256   marketing@example   <- bug      (no entry)
       EMAIL_SHA256  +15551234567        <- bug      [email protected]
       PHONE_SHA256  (no entry)                      +15551234567
row 2  AAID_SHA256   +15559998888        <- bug      aaid-value-here
       PHONE_SHA256  aaid-value-here     <- bug      +15559998888

Row 2 is bug #2: all identifiers present, AAID and PHONE swapped.

Linear ticket

Resolve INT-7054

Developer checklist

  • My code follows the style guidelines of this project

  • No breaking changes are being introduced. — see changes to existing behaviour above: the emitted batch_data shape changes. That is the fix, but it is a wire-format change worth a reviewer's eyes.

  • 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? — 4 files

  • Is the PR limited to one linear task?

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

TikTok reads each batch_data row positionally against id_schema, but
prepareIdentifiersPayload built the row by iterating the identifiers object
and pushing only truthy values. Two ways that misaligns the row:

- A user missing an identifier produced a shorter row, shifting every later
  id into the wrong slot. A user with only an email was sent as a one-entry
  row against a four-entry schema, so TikTok read the email hash as an
  AAID_SHA256.
- id_schema is sorted but the row followed the identifiers object's own key
  order, so even a fully populated user could be emitted out of order.

Walk the sorted schema instead and emit `{}` for any slot the user has no
usable value for, which is how TikTok expects "this user has no such id".
Events whose slots are all placeholders still abort with "No identifiers
found" — a row of nothing but placeholders identifies no one.

Native Test 18 had frozen the old behaviour into its expected payload
(two ids against a four-entry schema); its fixture is updated to match.

Reported by Chatbooks, who worked around it by rebuilding the connection to
match on email only.

Co-Authored-By: Claude Opus 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d6d7e3b4-e7f9-420a-8917-97f816037853

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

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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

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

@arpl
arpl marked this pull request as ready for review August 25, 2026 08:16
@arpl
arpl requested review from a team as code owners August 25, 2026 08:16
@sonarqubecloud

Copy link
Copy Markdown

@codecov

codecov Bot commented Aug 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.01%. Comparing base (49ff567) to head (c274121).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #5519   +/-   ##
========================================
  Coverage    93.00%   93.01%           
========================================
  Files          719      719           
  Lines        39056    39063    +7     
  Branches      9143     9143           
========================================
+ Hits         36324    36333    +9     
+ Misses        2509     2507    -2     
  Partials       223      223           

☔ View full report in Codecov by Harness.
📢 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.

maheshkutty added a commit that referenced this pull request Aug 25, 2026
> Same change as #5519, targeted at `hotfix/tiktok_ads_id_schema`
instead of `develop`. Cherry-picked from `c2741212e` with the original
authorship and commit message intact; the tiktok_audience files are
byte-identical to that commit.

## What are the changes introduced in this PR?

TikTok reads each `batch_data` row **positionally** against `id_schema`.
`prepareIdentifiersPayload` built the row by iterating the `identifiers`
object and pushing only truthy values, which misaligned it in two
independent ways:

1. **A missing identifier produced a shorter row**, shifting every later
id left. A user with only an email was sent as a one-entry row against a
four-entry schema, so TikTok read the email hash as an `AAID_SHA256`.
This is the customer report.
2. **`id_schema` is sorted, the row was not.** The row followed the
`identifiers` object's own key order, so even a *fully populated* user
could be emitted out of order — `AAID` and `PHONE` silently swapped.
This was not in the report and is the more insidious of the two, since
nothing about the record looks wrong.

The fix walks the sorted schema instead of the object, and emits `{}`
for any slot the user has no usable value for.

```ts
const idSchema = Object.keys(identifiers).sort();
for (const fieldName of idSchema) {
  let identifier: BatchIdentifier = {};   // holds the slot open
  if (value) { /* validate, normalize, hash */ }
  identifiersList.push(identifier);
}
```

Events whose slots are *all* placeholders still abort with `No
identifiers found` — a row of nothing but placeholders identifies no
one.

### Why `{}` and not a reordered `id_schema`

Two independent confirmations that the placeholder is the contract:

- **This repo already does it correctly elsewhere.** The legacy
`audienceList` path in `transform.ts` maps over the schema and emits
`{}` for a missing trait:
  ```js
destinationFields.map((f) => trait[f] ? { id: hashIdentifier(f,
trait[f]), audience_ids: [audienceId] } : {})
  ```
The two paths disagreed; the older one was right. This change makes the
`record` path match it.
- **Segment's TikTok Audiences destination** does the same, with a
comment stating the rule: *"Even if email and advertising_id are empty
we want to include them into the array as we seek to comply with the ID
Schema defined outside of this function."*

## What is the related Linear task?

Not yet filed — reported by Chatbooks in a shared Slack channel and
triaged in #<internal thread>. Happy to link one before merge.

## Please explain the objectives of your changes below

Restore correct identifier attribution for TikTok audiences. Any record
with a missing or invalid identifier currently has its remaining ids
attributed to the wrong identifier types, which corrupts audience
matching silently — TikTok returns `200` either way. Customers only
notice as unexplained low match rates.

The affected customer worked around it by rebuilding their connection to
match on email only, which is exactly the configuration in which the bug
cannot appear (a single-slot schema is always aligned). Enriching with
any additional identifier re-exposes it.

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

`batch_data` rows now always have exactly `id_schema.length` entries,
where previously they had only as many entries as the record had
non-null identifiers. This is the fix, and it is a wire-format change
for every `record`-path TikTok audience payload with a sparse or
unsorted identifier set.

`test/integrations/destinations/tiktok_audience/router/data.ts` —
**"Native Test 18: record events: invalid identifiers"** had frozen the
old behaviour into its expected payload (two ids against a four-entry
`id_schema`, i.e. the misalignment itself) and had always passed. Its
fixture is updated; please sanity-check that fixture rather than
assuming it was collateral damage.

### Any new dependencies introduced with this change?

N/A

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

N/A — one new local type, `BatchIdentifier = Identifier |
IdentifierPlaceholder`, so a placeholder is representable.

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

Payload size grows for sparse records (an extra `{}` per unfilled slot).
Grouping is unchanged: it already keys on `id_schema`, and rows are now
uniformly that length.

<hr>

## Verification

**Unit** — 12/12 in `recordTransform.test.ts`, including 3 new alignment
cases. All three were confirmed to **fail before the fix** (row length 1
vs schema 4; AAID/PHONE hashes swapped), so they can actually catch a
regression.

**Component** — 16/16 for `tiktok_audience`. Repo-wide `tsc --noEmit`,
eslint and prettier clean.

**End-to-end on a local stack, against the real TikTok API.**
Transformer built from this branch and deployed into the stack, verified
the patched code was actually in the running container, then drove a
real rETL sync from a warehouse source into a live TikTok audience with
`AAID_SHA256`, `EMAIL_SHA256`, `PHONE_SHA256` mapped and nulls seeded
across every gap shape. The payload was captured off the wire between
rudder-server and the transformer:

```
 20 ok                                    (every row length == id_schema length)
 11 ["AAID_SHA256","EMAIL_SHA256","PHONE_SHA256"]

  5  -           | EMAIL_SHA256 | -              both null
  5  -           | EMAIL_SHA256 | PHONE_SHA256   <- leading gap: the reported bug
  5  AAID_SHA256 | EMAIL_SHA256 | -              trailing gap
  5  AAID_SHA256 | EMAIL_SHA256 | PHONE_SHA256   fully populated
```

Sync result: **20 changed → 20 successful, 0 failed / dropped /
invalid.** TikTok accepted the `{}` placeholders.

Running the identical payload against the current published transformer
image reproduces both bugs:

```
                     BEFORE                          AFTER
row 0  AAID_SHA256   [email protected]   <- bug      (no entry)
       EMAIL_SHA256  (no entry)                      [email protected]
row 1  AAID_SHA256   marketing@example   <- bug      (no entry)
       EMAIL_SHA256  +15551234567        <- bug      [email protected]
       PHONE_SHA256  (no entry)                      +15551234567
row 2  AAID_SHA256   +15559998888        <- bug      aaid-value-here
       PHONE_SHA256  aaid-value-here     <- bug      +15559998888
```

Row 2 is bug #2: all identifiers present, `AAID` and `PHONE` swapped.

## Linear ticket 
[Resolve
INT-7054](https://linear.app/rudderstack/issue/INT-7054/fix-tiktok-audience-identifier-schema-alignment)

### Developer checklist

- [x] My code follows the style guidelines of this project

- [ ] **No breaking changes are being introduced.** — see *changes to
existing behaviour* above: the emitted `batch_data` shape changes. That
is the fix, but it is a wire-format change worth a reviewer's eyes.

- [x] All related docs linked with the PR?

- [x] All changes manually tested?

- [ ] Any documentation changes needed with this change?

- [x] Is the PR limited to 10 file changes? — 4 files

- [x] Is the PR limited to one linear task?

- [x] Are relevant unit and component test-cases added in **new
readability format**?

Co-authored-by: Aris Plakias <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
@maheshkutty

Copy link
Copy Markdown
Contributor

going via hotfix
#5520

@github-actions
github-actions Bot deleted the fix/tiktok-audience-id-schema-alignment branch November 26, 2026 01:04
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.

2 participants