Skip to content

fix(topsort): idempotent event ids, request chunking, and remove additionalAttribution - #5606

Merged
ItsSudip merged 7 commits into
rudderlabs:feat/topsort-batching-frameworkfrom
Topsort:refactor/topsort-batching-framework
Sep 25, 2026
Merged

ItsSudip merged 7 commits into
rudderlabs:feat/topsort-batching-frameworkfrom
Topsort:refactor/topsort-batching-framework

Conversation

@bernirosas

@bernirosas bernirosas commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

Three fixes to the Topsort destination, which has not been modified since it was onboarded in
#3913. We own the Topsort Events API, so where this describes API behaviour it comes from the
server implementation rather than our published docs. Each commit is self-contained and can be
reviewed independently — happy to split into separate PRs if you'd prefer.

1. fix(topsort): make event ids deterministic so retries are idempotent

Each event's id is the idempotency key — we use it to recognise a redelivery and discard it, so a
retried event must carry the same id as the first attempt. purchase.js and
impressions-and-clicks.js generated it with generateUUID() on the product-array path, so a
RudderStack retry after a 5xx or 429 re-sent the same events under new ids and we counted them
again. The single-product paths already used message.messageId and were correct, so the two paths
disagreed with each other.

Purchases now use message.messageId; impressions and clicks fanned out from properties.products
use `${message.messageId}-${index}`, since one message produces one event per product.

This commit also reshapes the per-event code into buildTopsortEvents(message, destination), which
returns the events a message maps to rather than mutating a shared finalPayloads accumulator
threaded through three modules. That is a prerequisite for commit 3, which needs a per-event
transform.

2. feat(topsort): drop the additionalAttribution mapping

We have moved away from per-event additional attribution — the products eligible for attribution on
a banner campaign are declared at campaign creation and resolved on our side. The API still accepts
the field, so nothing breaks; we would rather the destination stopped implying it is part of the
integration.

3. feat(topsort): chunk requests at the Events API per-array cap

The API binds max=50 on each of the impressions, clicks and purchases arrays independently
and rejects the whole request past that. processRouterDest merged an entire router batch into one
request with no chunking, so a large enough batch was rejected in full — and since the router
returns a single success response covering all metadata, every event in the batch was lost rather
than just the overflow. There is no per-item result array on our side, so there is no
partial-success path to fall back on.

This is easier to hit than 50 suggests: an impression or click carrying a products array fans out
to one event per product, so six input events with ten products each already produce sixty
impressions.

Ported to the native batching framework. The body is three independently capped arrays rather than
one flat array, so ChunkBatchStrategy can't express it — wrapBody receives only the bodies, not
the group key. Each payload is instead tagged with an internalGroupKey of impressions, clicks
or purchases, and a CustomBatchStrategy reads that back, chunks at MAX_BATCH_SIZE via
chunkPayloads, and wraps as {[type]: bodies}.

What is the related Linear task?

None — external contribution from Topsort. Happy to have one filed if that helps tracking.

Please explain the objectives of your changes below

The first and third are the ones that matter. Without them, retries duplicate events (inflating
impressions, clicks, purchases and attributed revenue) and sufficiently large batches are dropped
entirely under load. Both affect data our billing runs against.

processRouterDest and process remain exported and functional. They are the fallback for any
workspace not enrolled through TOPSORT_BATCHING_FRAMEWORK_ENABLED_WORKSPACE_IDS, so this can be
rolled out per workspace before GA. We have deliberately not set batching: true in
features.ts, since that would move every workspace at once — we would suggest validating against
a real workspace first, and we can supply one.

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

Three, all intentional.

  1. Event ids are derived from messageId rather than random. This is the fix. It changes the
    wire value of id for events carrying a products array, and probably warrants a release note.
  2. Impressions and clicks fanned out from a products array get distinct ids (-0, -1, …).
    Previously each got an independently random id in production; under the test mock they all got
    the same constant, which would have collided on our dedup key had it reached the API.
  3. A mixed batch now becomes up to three requests instead of one. That is the cost of making
    the per-array cap enforceable, and we think it is the right trade.

One bug fixed incidentally: when every event in a batch failed, processRouterDest still returned
a success response wrapping {impressions: [], clicks: [], purchases: []}, which we reject with
at least one event must be present. The framework emits no request for an empty group.

Any new dependencies introduced with this change?

N/A

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

None generic. Within the destination, utils.addFinalPayload is removed — it existed only to push
into the accumulator that no longer exists.

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

test/integrations/destinations/topsort/mocks.ts is removed and the fixtures now assert real
values.

That mock could not work. It called jest.spyOn(utils, 'generateUUID'), but the destination modules
do const { generateUUID } = require('../../util') — a CommonJS destructure copies the value at
require time, so replacing the property afterwards has no effect unless the module happens to be
loaded after the spy is installed. The full suite produces that ordering and passes; running the
destination alone does not:

$ npm run test:ts -- component --destination=topsort   # on develop
Tests:       4 failed, 9 passed, 13 total

After this PR the same command reports 13 passed, 13 total, and does so because the values are
genuinely deterministic rather than because a spy won a race.

New coverage in routerTransform.test.ts (8 tests) includes the three cases that pin the chunking
fix: 70 events of one type splitting into 50 + 20; six events carrying ten products each producing
sixty impressions across multiple requests, none over the cap; and seven events carrying eight
products each (56 impressions), where the cap falls inside a job's fan-out rather than on an
input-event boundary.

That last case is the one worth calling out. When a job's events straddle two chunks, both chunks
share its jobId, so combineBatchRequestsWithSameJobIds folds them into a single response whose
batchedRequest is an array of requests. The cap is still honoured (50 + 6) and every job is
accounted for exactly once — but it is a different response shape, and the first two cases above
happen to pick counts whose boundary lands on an input-event edge, so neither reaches it.


Developer checklist

  • My code follows the style guidelines of this project

  • No breaking changes are being introduced. — see "changes to existing behaviour"; the wire
    value of id changes for events carrying a products array. That is the fix.

  • 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? — three related fixes to one destination, one commit
    each. Glad to split them if you'd rather review separately.

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

🤖 Generated with Claude Code

bernirosas and others added 3 commits September 22, 2026 15:25
`id` is the idempotency key on every Topsort event -- the server stores it as
`external_id` and the v2 models call it out explicitly ("ensures the event
reporting is idempotent in case there is a network issue and the request is
retried").

The product-array paths in purchase.js and impressions-and-clicks.js called
`generateUUID()` (with the entropy cache disabled), so a RudderStack retry on
5xx/429 re-sent the same events under fresh ids -- duplicating impressions,
clicks and purchases, and overcharging vendors. The single-product paths
already used `message.messageId` and were correct.

- purchases: id = message.messageId
- impressions/clicks fanned out from properties.products:
  id = `${message.messageId}-${index}`, since one message produces one event
  per product and messageId alone would repeat across them
- drop generateUUID from this destination

Also reshapes processEvent into `buildTopsortEvents`, which returns the events a
message maps to instead of mutating a shared `finalPayloads` accumulator. This
is a prerequisite for the batching framework port, which needs a per-event
transform. `processRouterDest` and `process` are re-expressed on top of it with
no behaviour change.

The destination's component tests asserted the mocked constant
`test-id-123-123-123`, repeated across distinct fanned-out impressions. That
mock never worked: mocks.ts spied on `utils.generateUUID` while the modules
destructure it at require time, so the spy only bit when the destination
happened to be loaded after it. Running `--destination=topsort` in isolation
failed 4 tests on develop. Fixtures now assert the real deterministic ids and
mocks.ts is removed.

INTE-3438
INTE-3440

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
We no longer use per-event `additionalAttribution`. Banner attribution comes
from the `product_ids` declared at campaign creation and is resolved
server-side, so there is nothing for the marketplace to send per event.

`/v2/events` still accepts the field -- this is a deliberate choice not to
surface it, not a reaction to an API change. Any marketplace currently sending
`properties.additionalAttribution` will stop having it forwarded, which is
intended.

Fixtures keep `properties.additionalAttribution` in their input payloads and
drop it from the expected output, so the suite now pins the new behaviour: the
field can be sent and is ignored.

INTE-3445

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The Events API binds `max=50` on each of the impressions, clicks and purchases
arrays independently and rejects the whole request past that.
`processRouterDest` merged an entire router batch into a single request with no
chunking, so a large enough batch was rejected in full -- and because the
router returns one success response covering all metadata, every event in the
batch was lost rather than just the overflow.

This is easier to hit than 50 suggests: an impression or click carrying a
`products` array fans out to one event per product, so six input events with
ten products each already produce sixty impressions.

Ports the destination to the native batching framework. The body is three
independently capped arrays rather than one flat array, so `ChunkBatchStrategy`
cannot express it -- `wrapBody` receives only the bodies, not the group key.
Instead each payload is tagged with `internalGroupKey` of impressions, clicks
or purchases, and a `CustomBatchStrategy` reads that back, chunks at
MAX_BATCH_SIZE via `chunkPayloads` and wraps as `{[type]: bodies}`.

A mixed batch therefore becomes up to three requests instead of one. That is
the cost of making the per-array cap enforceable.

Also resolves the empty-request bug: when every event in a batch failed,
`processRouterDest` still returned a success response wrapping
`{impressions: [], clicks: [], purchases: []}`, which the API rejects with
"at least one event must be present". The framework emits no request for an
empty group.

`processRouterDest` and `process` stay exported and working -- they remain the
fallback for any workspace not enrolled via
TOPSORT_BATCHING_FRAMEWORK_ENABLED_WORKSPACE_IDS. No `features.ts` change,
since `batching: true` would mean GA for every workspace at once.

INTE-3437
INTE-3439
INTE-3442

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@contributor-support

Copy link
Copy Markdown

Thank you @bernirosas for contributing this PR.
Please sign the Contributor License Agreement (CLA) before merging.

@coderabbitai

coderabbitai Bot commented Sep 23, 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: Advanced

Run ID: ebf863b5-f81f-4c15-8e02-b5fa677e06f9

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.

bernirosas and others added 3 commits September 23, 2026 13:01
The two chunking tests both used counts whose 50th event landed exactly on an
input-event boundary (5 x 10 products), so neither exercised a job whose
fanned-out products straddle two chunks. That is the case where the framework's
combineBatchRequestsWithSameJobIds folds both requests back into one response
and `batchedRequest` becomes an array — a shape `bodiesOf` read as
`undefined`, so the helper would have masked a regression rather than catching
it.

Flatten that shape in the helper and add 7 x 8 products, where the boundary
falls mid-job. Behaviour was already correct (50 + 6, cap respected); this pins
it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
validateEvent is only called by processEvent in the same module; routerTransform
reaches the same checks through the Zod input schema and imports only
buildTopsortEvents. Exporting it widened the module surface for no caller.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@bernirosas
bernirosas marked this pull request as ready for review September 23, 2026 17:27
@bernirosas
bernirosas requested review from a team as code owners September 23, 2026 17:27
@ItsSudip
ItsSudip changed the base branch from develop to feat/topsort-batching-framework September 25, 2026 09:26
@ItsSudip
ItsSudip merged commit 7e04af5 into rudderlabs:feat/topsort-batching-framework Sep 25, 2026
16 of 24 checks passed
@codecov

codecov Bot commented Sep 25, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.14815% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 93.03%. Comparing base (9a78786) to head (eda34d9).
⚠️ Report is 13 commits behind head on feat/topsort-batching-framework.

Files with missing lines Patch % Lines
src/v0/destinations/topsort/transform.js 91.66% 1 Missing ⚠️
Additional details and impacted files
@@                         Coverage Diff                         @@
##           feat/topsort-batching-framework    #5606      +/-   ##
===================================================================
+ Coverage                            93.01%   93.03%   +0.01%     
===================================================================
  Files                                  729      731       +2     
  Lines                                39440    39440              
  Branches                              9200     9249      +49     
===================================================================
+ Hits                                 36687    36692       +5     
+ Misses                                2554     2549       -5     
  Partials                               199      199              

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

ItsSudip added a commit that referenced this pull request Sep 28, 2026
)

## What are the changes introduced in this PR?

Moves the Topsort destination fully onto the batching framework and
makes it router-only.

- Registers `TOPSORT: { routerTransform: true, batching: true,
transformerProxy: true }` in `src/features.ts`, so the destination is GA
on the framework for every workspace.
- Removes the legacy `process` / `processRouterDest` transform
(`transform.js`, `purchase.js`, `impressions-and-clicks.js`, `utils.js`,
`config.js`) and the processor test fixtures.
- Converts the destination to TypeScript: `config.ts`, `types.ts`,
`utils.ts` (`buildTopsortEvents`) and `routerTransform.ts`.
- Requires `messageId` in the input schema. Event ids are derived from
it (`<messageId>` or `<messageId>-<index>` for fanned-out products), so
an event without one now fails on its own instead of being sent with an
`undefined` id.
- Sends impressions, clicks and purchases in one request. Each array is
capped at 50 independently, and a new request starts only when the array
an event belongs in is full. Empty arrays are omitted from the body.
- Adds `delivery.ts`: a 400 from the Events API rejects the whole
request, so every job is retried on its own with `dontBatch: true`; a
job that was already sent alone is aborted. Other statuses keep the
framework default. Failure reasons are built from Topsort's `[{ errCode,
message }]` error array.

## What is the related Linear task?

Resolves INT-7228

## Please explain the objectives of your changes below

Follow-up to #5606 (merged into `feat/topsort-batching-framework`).

**Dependent change:** rudder-integrations-config must set
`transformAtV1: "router"` for Topsort before this is released
(rudderlabs/rudder-integrations-config#2763).
This PR removes the processor `process` transform, which Topsort uses
while its definition is on `processor`.

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

- Topsort is router-only; the processor route
(`/v0/destinations/topsort`) is no longer supported.
- Events of different types share a request instead of being sent per
type.
- A message without `messageId` fails with `message.messageId:
Required`.
- A 400 from Topsort retries each job alone (`dontBatch`) instead of
aborting the batch.

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

Combining event types reduces the number of requests for mixed traffic
by up to 3×. A rejected batch costs one extra request per job when it is
retried with `dontBatch`.

<hr>

### Developer checklist

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

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@ItsSudip ItsSudip mentioned this pull request Sep 28, 2026
3 of 10 tasks
ItsSudip added a commit that referenced this pull request Sep 28, 2026
## What are the changes introduced in this PR?

Merges the Topsort feature branch into `develop`. It contains:

- #5606 (contributed by Topsort): deterministic event ids so retries are
idempotent (`<messageId>`, or `<messageId>-<index>` for events fanned
out from `properties.products`), removal of the `additionalAttribution`
mapping, and chunking at the Events API's per-array cap of 50.
- #5618: moves Topsort fully onto the batching framework.
- Registers `TOPSORT: { routerTransform: true, batching: true,
transformerProxy: true }` in `src/features.ts`.
- Removes the legacy `process` / `processRouterDest` transform and the
processor test fixtures; the destination is router-only.
  - Converts the destination to TypeScript.
  - Requires `messageId` in the input schema.
- Sends impressions, clicks and purchases in one request, each array
capped at 50.
- Adds `delivery.ts`: a 400 from the Events API retries each job on its
own with `dontBatch: true`; a job already sent alone is aborted.

## What is the related Linear task?

Resolves INT-7228

## Please explain the objectives of your changes below

**Dependent change:** rudder-integrations-config #2763 (`transformAtV1:
"router"` for Topsort) is merged. It must be released before this PR,
because this PR removes the processor `process` transform.

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

- Topsort is router-only; the processor route
(`/v0/destinations/topsort`) is no longer supported.
- The `id` sent for events carrying a `products` array changes to
`<messageId>-<index>`.
- `additionalAttribution` is no longer mapped.
- Events of different types share a request.
- A message without `messageId` fails with `message.messageId:
Required`.
- A 400 from Topsort retries each job alone (`dontBatch`) instead of
aborting the batch.

### 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

<hr>

### Developer checklist

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

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

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

2 participants