Skip to content

Sumanth - #2

Merged
SumanthPuram merged 9 commits into
masterfrom
sumanth
Jul 22, 2019
Merged

SumanthPuram merged 9 commits into
masterfrom
sumanth

Conversation

@SumanthPuram

Copy link
Copy Markdown
Member

No description provided.

@SumanthPuram
SumanthPuram merged commit 30bd6cd into master Jul 22, 2019
shekhar-rudder added a commit that referenced this pull request Jul 28, 2026
…#5385)

## What are the changes introduced in this PR?

Caps how many custom-mapping evaluations run concurrently on a single
`isolated-vm` isolate and queues the excess.

`IvmScriptRunner` gains one optional knob — `maxConcurrentExecutions`.
It defaults to unlimited, so `custom_audience` and every other consumer
keep today's behaviour; only the `custom_mappings_ivm` pool opts in.

## What is the related Linear task?

Resolves INT-6832

## Please explain the objectives of your changes below

An isolate runs JS on one thread against one fixed heap. Extra
concurrency on it buys no throughput — it only keeps more
structured-clone argument copies and evaluation working sets alive on
that heap at the same time. When the total breaches `memoryLimit`, V8
disposes the **whole isolate**, so every in-flight evaluation fails at
once with a retryable 500, not just the one that tipped it. That
amplification is what surfaced as the intermittent 500 spikes on
Lovable's HTTP destination.

Nothing bounded that fan-in before this. `execute()` had
promise-coalescing on isolate *creation* only; once an isolate was warm,
unlimited calls could re-enter it. Callers actively fan out — the HTTP
destination maps headers, query params and payload as three separate
evaluations per event (`procWorkflow.yaml:39,50,59`), and `ga4_v2`
`Promise.all`s over its mapping list (`customMappingsHandler.js:110`).

Bounding admission converts "the isolate dies and takes every in-flight
event with it" into "the excess waits". Queued callers hold their args
on the Node heap, where those args already were — the queue itself costs
the isolate nothing.

This is follow-up #1 from the INT-6832 thread. Follow-up #2
(compile-caching the mapping template) is #5372; the two are independent
and can merge in either order.

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

Only the `custom_mappings_ivm` pool changes behaviour, and only past the
cap. **Nothing is ever shed** — the queue is unbounded by construction,
so an overload costs latency rather than dropped events. `acquireSlot()`
cannot reject; it only ever admits or queues.

One new tunable (falling back to unlimited — i.e. today's behaviour — if
absent or unparseable, rather than wedging the sandbox):

| Env var | Default | Rationale |
|---|---|---|
| `CUSTOM_MAPPINGS_IVM_MAX_CONCURRENT_EXECUTIONS` | 100 | Sized from
prod — see below. |

The cap alone is what protects the isolate heap, and a single-threaded
isolate drains its queue at its own throughput either way, so an
explicit queue bound would only have bought a strictly worse failure
mode (a dropped event instead of a slower one).

#### Where the cap of 100 comes from

Sized against `enterprise-eu` / `rudder-eu-central-1b`, the busiest
namespace for this pool by a wide margin (~380x `eu-central-1a`):

| Observation (7d) | Value |
|---|---|
| Peak single-pod eval rate | ~13.8k/s |
| Warm isolates per pod | 18 (cache max 20) |
| Observed heap per isolate | ~5.6 MB baseline |
| `ivm_platform_error`, `custom_mappings_ivm` | 879, **all in one hour,
all one workspace** |

That error profile is the whole argument for this PR: 879 failures
inside a single hour and zero across the rest of the week is not a
steady error rate, it is one isolate dying and taking every in-flight
evaluation with it.

An isolate runs on one thread, so sustaining ~13.8k evals/s implies a
sub-100µs evaluation, which by Little's Law puts steady-state in-flight
depth near 1. Concurrency only builds when arrivals transiently outrun
the isolate — exactly the OOM regime. So 100 sits ~100x above anything
normal traffic reaches (it will not throttle the hot workspace) and ~16x
below the ~1600-concurrency OOM onset measured in #5372. Memory agrees:
~5.9 MB of eval working set at concurrency 100, on top of the ~5.6 MB
baseline, against the 32 MB prod limit.

#### Measured under load

Verified locally against the real `http` destination path (single
process, one workspace, 6s per phase). The cap was set to **8** rather
than 100 for the run: by the Little's Law argument above, steady-state
depth sits near 1, so a laptop cannot drive an isolate to depth 100 —
lowering the cap exercises the identical code path at reachable load.
180,674 requests / 542,022 evaluations, **all HTTP 200**.

| offered concurrency | evals/s | queued/s | mean wait | in-flight depth
|
|---|---|---|---|---|
| 1 | 6,900 | 0 | — | 0.39 |
| 4 | 14,803 | 0 | — | 0.84 |
| 8 | 16,518 | 0 | — | 0.94 |
| 16 | 17,003 | 0 | — | 0.97 |
| 32 | 17,551 | 13,553 | 0.39ms | **7.84** |
| 64 | 17,509 | 17,651 | 1.11ms | **20.43** |

Three things the run confirms:

- **Throughput is flat from concurrency 8 onward** (~17.5k evals/s)
while offered load grows 8x. Extra concurrency bought zero throughput
and became queue depth — the premise of the PR, measured. The implied
~57µs service time is consistent with the sub-100µs figure inferred from
prod.
- **The gate is silent until it is genuinely saturated.**
`ivm_execution_queued` stayed at exactly 0 through four phases of rising
load. Past the cap, 312,295 evaluations queued and
`ivm_execution_queue_wait_count` equalled that number exactly — every
queued call was admitted, nothing lost or double-counted, and
`ivm_platform_error` stayed at 0 across all 542k evaluations.
- **In-flight depth crosses the cap where queueing starts.** Depth above
is Little's Law (throughput x residence), derived independently of the
gate's own counters, and it crosses 8 at precisely the phase where the
counter switches on.

### Any new dependencies introduced with this change?

N/A — no new packages; the gate is ~60 lines of plain promise plumbing.

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

`IvmScriptRunner` (shared by `custom_mappings` and `custom_audience`)
gains the option above, opt-in per consumer.

`prometheus.js` gains a static registration for
`ivm_execution_queue_wait` with explicit buckets — see the metrics
bullet below for why.

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

- **Slot handoff, not free-and-wake.** `release()` hands its slot
directly to the next waiter and leaves `slotsInUse` untouched.
Decrementing *and* waking a waiter would let the accounting drift and
admit past the cap. There is a regression test for exactly that — it
fails with peak 3 against a cap of 2 under the buggy variant. The
counter is named for slots *reserved*, not work in progress: a slot in
transit between a departing caller and a waiter stays counted across the
microtask gap in which neither is executing.
- **Waiters are FIFO.** `pop()` would be marginally cheaper, but it
starves the oldest waiter under sustained saturation, and nothing bounds
queue time here (`execTimeoutMs` covers evaluation only, and the queue
is unbounded). The O(n) `shift()` is a pointer memmove on a queue that
Little's Law keeps near-empty in steady state — orders of magnitude
below the ~100µs evaluation it gates.
- **Gates are per isolate** (keyed like the isolate cache, i.e. per
workspace) and dropped once fully idle, so the map stays bounded by the
live isolate set rather than every workspace ever seen. A queued caller
resolves with its own release closure and its own `cacheKey`, so it can
never bind to another tenant's isolate.
- **New metrics:** `ivm_execution_queued` (counter) and
`ivm_execution_queue_wait` (timer), both carrying the full
`(workspaceId, functionName, cache)` label set that `ivm_platform_error`
already uses, so all three join on the same series. The gate is per
isolate — i.e. per workspace — and these two are the only overload
signal there is, so "which tenant is at its cap" has to be answerable
from them. `ivm_execution_queued` is incremented **at enqueue**, so a
backlog shows up the moment it forms; the wait timer only samples on
admission and so lags a burst by however long the queue takes to drain.
`ivm_execution_queued` is the one to alert on. Cardinality is bounded by
the workspaces that actually reach the cap — rare by design, since the
cap sits far above normal traffic — not by call volume; `functionName`
is a hardcoded expression literal per call site (three exist repo-wide,
only one on a gated pool), so it adds no fan-out.
- **`ivm_execution_queue_wait` is declared statically with explicit
buckets.** Left to `prometheus.js`'s dynamic path it inherits
prom-client's default buckets, whose first boundary is 5ms — and a gated
isolate drains far faster than that. In the load run above, **99.45% of
312k observations (310,578) landed in that single first bucket**, with
the remaining 0.55% in the next and every higher bucket empty;
`histogram_quantile()` on that series interpolates inside one bucket and
cannot separate a healthy 0.4ms wait from a degraded 4ms one. The
declared buckets start at 0.5ms and run to 1s; re-measured under the
same load the distribution spans five buckets (p50 ~3.8ms, p99 ~19ms).
Declaring it also pins the label set rather than inferring it from
whichever call site observes first.
- **Metric emission ordering.** `ivm_execution_queued` is emitted before
the waiter promise is constructed, and the wait timer after `resolve()`,
so a throwing metric client can never strand a waiter in the queue
holding a slot that was handed to it and never released.
- **Out of scope, deliberately:** the code default for
`CUSTOM_MAPPINGS_IVM_MEMORY_MB` is still 16 while prod is overridden to
32 via helm — separate concern, prod already carries the bump.
`custom_audience` stays ungated; enabling it there is a one-line config
change if wanted.

@coderabbitai review

<hr>

### Developer checklist

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

- [x] **No breaking changes are being introduced.**

- [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?

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

- [x] 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.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
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]>
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.

1 participant