From 10a9419039e7179bd9d814860ad8633df38e6ace Mon Sep 17 00:00:00 2001 From: Rahul Raveendran V P Date: Fri, 27 Nov 2026 13:06:57 +0530 Subject: [PATCH 1/2] fix(analytics): avoid sending the same JavaScript-mode batch twice In JavaScript mode the event queue is shared per token, but every Mixpanel instance runs its own flush timer, and processQueue does not wait for the request it starts. Two instances for the same token (for example one created inside a component), a flush() during a timer flush, or a request slower than the flush interval all sent the same batch again before it was removed from the queue. JavaScript mode adds no $insert_id, so the duplicates were ingested. Allow one flush per token and endpoint at a time, like the native SDKs, which flush on a single worker. Related to #283 Co-Authored-By: Claude Opus 5.5 --- __tests__/core.test.js | 25 +++++++++++++++++++++++++ javascript/mixpanel-core.js | 21 ++++++++++++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/__tests__/core.test.js b/__tests__/core.test.js index ac397fb0..d341cfae 100644 --- a/__tests__/core.test.js +++ b/__tests__/core.test.js @@ -132,4 +132,29 @@ describe("MixpanelQueueManager", () => { await MixpanelCore().flush(token); expect(MixpanelNetwork.sendRequest).toHaveBeenCalledTimes(0); }); + + it("does not send the same batch twice while a request is in flight", async () => { + const queue = [data]; + MixpanelQueueManager.getQueue.mockImplementation(() => [...queue]); + MixpanelQueueManager.spliceQueue.mockImplementation(async (t, ty, start, count) => { + queue.splice(start, count); + }); + let finishRequest; + MixpanelNetwork.sendRequest.mockImplementation( + () => new Promise((resolve) => (finishRequest = resolve)) + ); + + // Two instances for the same token (e.g. a component that creates its own + // Mixpanel) flush the shared queue at the same time. + await MixpanelCore().flush("in-flight-token"); + await MixpanelCore().flush("in-flight-token"); + finishRequest(); + await new Promise(setImmediate); + + const trackCalls = MixpanelNetwork.sendRequest.mock.calls.filter( + ([args]) => args.endpoint === MixpanelType.EVENTS + ); + expect(trackCalls).toHaveLength(1); + expect(queue).toHaveLength(0); + }); }); diff --git a/javascript/mixpanel-core.js b/javascript/mixpanel-core.js index d866aa96..26890c39 100644 --- a/javascript/mixpanel-core.js +++ b/javascript/mixpanel-core.js @@ -6,6 +6,8 @@ import { MixpanelConfig } from "./mixpanel-config"; import { MixpanelPersistent } from "./mixpanel-persistent"; import { MixpanelLogger } from "./mixpanel-logger"; +const flushesInFlight = new Set(); + export const MixpanelCore = (storage) => { const mixpanelPersistent = MixpanelPersistent.getInstance(storage); const config = MixpanelConfig.getInstance(); @@ -101,10 +103,22 @@ export const MixpanelCore = (storage) => { }; const processQueue = async (token, type) => { + // The queue is shared by every instance for this token, so only one flush + // may send it at a time; otherwise the same batch is sent more than once. + const flushKey = `${token}${type}`; + if (flushesInFlight.has(flushKey)) { + MixpanelLogger.log(token, `Flush already in progress for endpoint: ${type}`); + return; + } + flushesInFlight.add(flushKey); + const done = () => flushesInFlight.delete(flushKey); + MixpanelLogger.log(token, `Processing queue for endpoint: ${type}`); const processBatch = async () => { const queue = MixpanelQueueManager.getQueue(token, type); - if (queue.length > 0) { + if (queue.length === 0) { + done(); + } else { MixpanelLogger.log(token, `[Flushing queue] endpoint: ${type}`); MixpanelLogger.log( token, @@ -126,8 +140,13 @@ export const MixpanelCore = (storage) => { const queue = MixpanelQueueManager.getQueue(token, type); if (queue.length > 0) { setTimeout(processBatch, 0); + } else { + done(); } } catch (error) { + if (error.code !== 400) { + done(); + } handleBatchError(token, error, type, processBatch); } } From 52844da743d76035da2ec268247224f3ec1b92b4 Mon Sep 17 00:00:00 2001 From: Rahul Raveendran V P Date: Fri, 27 Nov 2026 13:19:13 +0530 Subject: [PATCH 2/2] fix(analytics): recover the JavaScript-mode flush lock from stuck or failed flushes Review follow-up. React Native's Android fetch has no default timeout, so a request that never settles held the per-token flush lock for the rest of the session. A batch pending longer than sendRequest's full retry window (2 minutes, above the ~62s of backoff) now counts as stuck, and the next flush takes over. A taken-over flush stops without removing events from the queue. The batch loop now releases the lock in a finally block, so an unexpected throw (storage, logging, or the 400 path's spliceQueue) can't leave it held. The lock key also uses a separator. Related to #283 Co-Authored-By: Claude Opus 5.5 --- __tests__/core.test.js | 56 +++++++++++++++++++++ javascript/mixpanel-core.js | 97 +++++++++++++++++++++---------------- 2 files changed, 111 insertions(+), 42 deletions(-) diff --git a/__tests__/core.test.js b/__tests__/core.test.js index d341cfae..9d1a6097 100644 --- a/__tests__/core.test.js +++ b/__tests__/core.test.js @@ -38,6 +38,7 @@ jest.mock("mixpanel-react-native/javascript/mixpanel-config", () => ({ jest.mock("mixpanel-react-native/javascript/mixpanel-logger", () => ({ MixpanelLogger: { log: jest.fn(), + warn: jest.fn(), error: jest.fn(), }, })); @@ -157,4 +158,59 @@ describe("MixpanelQueueManager", () => { expect(trackCalls).toHaveLength(1); expect(queue).toHaveLength(0); }); + + describe("with an events-only queue", () => { + let queue; + // Scope the queue to one token so flush loops left running by other tests + // (e.g. "flushes the queue") can't send or remove these events. + let queueToken; + const eventSends = () => + MixpanelNetwork.sendRequest.mock.calls.filter( + ([args]) => args.token === queueToken && args.endpoint === MixpanelType.EVENTS + ).length; + + beforeEach(() => { + queue = [data]; + MixpanelQueueManager.getQueue.mockImplementation((t, ty) => + t === queueToken && ty === MixpanelType.EVENTS ? [...queue] : [] + ); + MixpanelQueueManager.spliceQueue.mockImplementation(async (t, ty, start, count) => { + queue.splice(start, count); + }); + MixpanelNetwork.sendRequest.mockResolvedValue(undefined); + }); + + it("starts a new flush when the in-flight request never settles", async () => { + queueToken = "stuck-token"; + MixpanelNetwork.sendRequest.mockImplementationOnce(() => new Promise(() => {})); + const now = jest.spyOn(Date, "now").mockReturnValue(1000); + + await MixpanelCore().flush("stuck-token"); + now.mockReturnValue(1000 + 60 * 1000); // still within the retry window + await MixpanelCore().flush("stuck-token"); + expect(eventSends()).toBe(1); + + now.mockReturnValue(1000 + 3 * 60 * 1000); + await MixpanelCore().flush("stuck-token"); + await new Promise(setImmediate); + expect(eventSends()).toBe(2); + expect(queue).toHaveLength(0); + now.mockRestore(); + }); + + it("releases the flush when processing throws unexpectedly", async () => { + queueToken = "throwing-token"; + MixpanelQueueManager.getQueue.mockImplementationOnce(() => { + throw new Error("storage failure"); + }); + + await MixpanelCore().flush("throwing-token"); + await new Promise(setImmediate); + await MixpanelCore().flush("throwing-token"); + await new Promise(setImmediate); + + expect(eventSends()).toBe(1); + expect(queue).toHaveLength(0); + }); + }); }); diff --git a/javascript/mixpanel-core.js b/javascript/mixpanel-core.js index 26890c39..0ad34152 100644 --- a/javascript/mixpanel-core.js +++ b/javascript/mixpanel-core.js @@ -6,7 +6,12 @@ import { MixpanelConfig } from "./mixpanel-config"; import { MixpanelPersistent } from "./mixpanel-persistent"; import { MixpanelLogger } from "./mixpanel-logger"; -const flushesInFlight = new Set(); +// One flush per token and endpoint at a time; the queue is shared by every +// instance for a token. A flush whose current batch has been pending longer +// than sendRequest's full retry window (~62s of backoff) is treated as stuck, +// so a request that never settles can't block flushing for the session. +const FLUSH_LOCK_STALE_MS = 2 * 60 * 1000; +const flushLocks = new Map(); export const MixpanelCore = (storage) => { const mixpanelPersistent = MixpanelPersistent.getInstance(storage); @@ -103,22 +108,36 @@ export const MixpanelCore = (storage) => { }; const processQueue = async (token, type) => { - // The queue is shared by every instance for this token, so only one flush - // may send it at a time; otherwise the same batch is sent more than once. - const flushKey = `${token}${type}`; - if (flushesInFlight.has(flushKey)) { + const flushKey = `${token}|${type}`; + const current = flushLocks.get(flushKey); + if (current && Date.now() - current.batchStartedAt < FLUSH_LOCK_STALE_MS) { MixpanelLogger.log(token, `Flush already in progress for endpoint: ${type}`); return; } - flushesInFlight.add(flushKey); - const done = () => flushesInFlight.delete(flushKey); + if (current) { + MixpanelLogger.warn( + token, + `Previous flush for endpoint ${type} appears stuck, starting a new one.` + ); + } + const lock = { batchStartedAt: Date.now() }; + flushLocks.set(flushKey, lock); MixpanelLogger.log(token, `Processing queue for endpoint: ${type}`); - const processBatch = async () => { - const queue = MixpanelQueueManager.getQueue(token, type); - if (queue.length === 0) { - done(); - } else { + drainQueue(token, type, flushKey, lock); + }; + + const drainQueue = async (token, type, flushKey, lock) => { + // A newer flush may take over a stuck lock; this loop then stops without + // touching the queue, so it can't remove events the new flush hasn't sent. + const ownsLock = () => flushLocks.get(flushKey) === lock; + try { + while (ownsLock()) { + const queue = MixpanelQueueManager.getQueue(token, type); + if (queue.length === 0) { + return; + } + lock.batchStartedAt = Date.now(); MixpanelLogger.log(token, `[Flushing queue] endpoint: ${type}`); MixpanelLogger.log( token, @@ -126,6 +145,7 @@ export const MixpanelCore = (storage) => { ); const batchSize = config.getFlushBatchSize(token); const batch = queue.slice(0, batchSize); + let removeCount = batch.length; try { await MixpanelNetwork.sendRequest({ token, @@ -135,41 +155,34 @@ export const MixpanelCore = (storage) => { useIPAddressForGeoLocation: config.getUseIpAddressForGeolocation(token), }); - await MixpanelQueueManager.spliceQueue(token, type, 0, batch.length); - // Process the next batch if there are more events in the queue - const queue = MixpanelQueueManager.getQueue(token, type); - if (queue.length > 0) { - setTimeout(processBatch, 0); - } else { - done(); - } } catch (error) { if (error.code !== 400) { - done(); + MixpanelLogger.error( + token, + `Error sending event batch from queue, error: ${error}` + ); + return; } - handleBatchError(token, error, type, processBatch); + MixpanelLogger.error( + token, + `Bad request received due to corrupted data within the batch. The corrupted data is now being removed from the queue...` + ); + // Remove the corrupted data from the queue, to avoid the data loss, only remove one event at a time + removeCount = 1; } + if (!ownsLock()) { + return; + } + await MixpanelQueueManager.spliceQueue(token, type, 0, removeCount); + // Yield before the next batch + await new Promise((resolve) => setTimeout(resolve, 0)); + } + } catch (error) { + MixpanelLogger.error(token, `Error flushing queue, error: ${error}`); + } finally { + if (ownsLock()) { + flushLocks.delete(flushKey); } - }; - - processBatch(); - }; - - const handleBatchError = (token, error, type, callback) => { - if (error.code === 400) { - MixpanelLogger.error( - token, - `Bad request received due to corrupted data within the batch. The corrupted data is now being removed from the queue...` - ); - // Remove the corrupted data from the queue, to avoid the data loss, only remove one event at a time - MixpanelQueueManager.spliceQueue(token, type, 0, 1).then(() => { - setTimeout(callback, 0); - }); - } else { - MixpanelLogger.error( - token, - `Error sending event batch from queue, error: ${error}` - ); } };