Repository navigation
fix(topsort): idempotent event ids, request chunking, and remove additionalAttribution - #5606
Conversation
`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]>
|
Thank you @bernirosas for contributing this PR. |
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
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. Comment |
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]>
7e04af5
into
rudderlabs:feat/topsort-batching-framework
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
) ## 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)
## 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]>
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 idempotentEach event's
idis the idempotency key — we use it to recognise a redelivery and discard it, so aretried event must carry the same
idas the first attempt.purchase.jsandimpressions-and-clicks.jsgenerated it withgenerateUUID()on the product-array path, so aRudderStack 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.messageIdand were correct, so the two pathsdisagreed with each other.
Purchases now use
message.messageId; impressions and clicks fanned out fromproperties.productsuse
`${message.messageId}-${index}`, since one message produces one event per product.This commit also reshapes the per-event code into
buildTopsortEvents(message, destination), whichreturns the events a message maps to rather than mutating a shared
finalPayloadsaccumulatorthreaded through three modules. That is a prerequisite for commit 3, which needs a per-event
transform.
2.
feat(topsort): drop the additionalAttribution mappingWe 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 capThe API binds
max=50on each of theimpressions,clicksandpurchasesarrays independentlyand rejects the whole request past that.
processRouterDestmerged an entire router batch into onerequest 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
productsarray fans outto 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
ChunkBatchStrategycan't express it —wrapBodyreceives only the bodies, notthe group key. Each payload is instead tagged with an
internalGroupKeyofimpressions,clicksor
purchases, and aCustomBatchStrategyreads that back, chunks atMAX_BATCH_SIZEviachunkPayloads, 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.
processRouterDestandprocessremain exported and functional. They are the fallback for anyworkspace not enrolled through
TOPSORT_BATCHING_FRAMEWORK_ENABLED_WORKSPACE_IDS, so this can berolled out per workspace before GA. We have deliberately not set
batching: trueinfeatures.ts, since that would move every workspace at once — we would suggest validating againsta real workspace first, and we can supply one.
Any changes to existing capabilities/behaviour, mention the reason & what are the changes?
Three, all intentional.
messageIdrather than random. This is the fix. It changes thewire value of
idfor events carrying aproductsarray, and probably warrants a release note.productsarray 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.
the per-array cap enforceable, and we think it is the right trade.
One bug fixed incidentally: when every event in a batch failed,
processRouterDeststill returneda success response wrapping
{impressions: [], clicks: [], purchases: []}, which we reject withat 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.addFinalPayloadis removed — it existed only to pushinto the accumulator that no longer exists.
Any technical or performance related pointers to consider with the change?
test/integrations/destinations/topsort/mocks.tsis removed and the fixtures now assert realvalues.
That mock could not work. It called
jest.spyOn(utils, 'generateUUID'), but the destination modulesdo
const { generateUUID } = require('../../util')— a CommonJS destructure copies the value atrequire 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:
After this PR the same command reports
13 passed, 13 total, and does so because the values aregenuinely deterministic rather than because a spy won a race.
New coverage in
routerTransform.test.ts(8 tests) includes the three cases that pin the chunkingfix: 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
combineBatchRequestsWithSameJobIdsfolds them into a single response whosebatchedRequestis an array of requests. The cap is still honoured (50 + 6) and every job isaccounted 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
idchanges for events carrying aproductsarray. 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