Skip to content

fix(session-replay-browser): keep batches whose retries ran out on transient failures - #2216

Open
bravecod wants to merge 2 commits into
mainfrom
josephjin/src-398-keep-failed-replay-batches
Open

bravecod wants to merge 2 commits into
mainfrom
josephjin/src-398-keep-failed-replay-batches

Conversation

@bravecod

@bravecod bravecod commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Problem. When every upload attempt for a replay batch fails with a transient error, the SDK treats the batch as delivered and deletes its IndexedDB record. Transient errors here are a send timeout, 5xx, 408, 429 or 499. If the deleted batch held the initial full snapshot, the rest of the session still uploads, but the replay plays back blank: there is no snapshot to apply the later events to. The full snapshot batch is the largest one, so on a slow uplink it is also the one most likely to hit the 10s send timeout twice.

The deletion happens on two paths:

  • Web worker: sendWithRetry posted { type: 'complete' } after the last failed attempt. That is the same message a successful upload sends, so the main thread ran completeRequest → onComplete → cleanUpSessionEventsStore.
  • Main thread: handleOtherResponse called completeRequest when the retry budget ran out.

Fix. When the retry budget runs out on a transient failure, keep the stored record instead of completing it. sendStoredEvents then re-sends it on the next page load. Concretely:

  • The worker reports transient exhaustion as { type: 'complete', retryExhausted: true }.
  • The main thread routes both paths through a new keepForNextPageLoad, which logs a warning and does not call onComplete.
  • Non-retryable failures (4xx, non-WAF 413, thrown errors) still settle and delete the record, as before.

Re-sending a batch that the server did receive is safe, because the server deduplicates. The drain on load already relies on this.

Kept batches keep their device id. A stored record now also saves the device id the batch was first sent with, and sendStoredEvents re-sends with it. Without this, a batch re-sent after the device id changed (reset(), cleared cookies) would be attached to a different replay, since the replay id is session id + device id. Records without one fall back to the current device id, as before. Those are records from older SDK versions and batches promoted from another tab.

A batch is kept at most 3 times. If the endpoint keeps failing with a retryable status, kept batches must not pile up in IndexedDB and be re-sent on every page load. Each time a stored batch's retries run out, onRetryExhausted → markRetryExhausted increments a counter on its record, and on the 3rd time (MAX_RETRY_EXHAUSTED_COUNT) the record is deleted. Details:

  • Merged requests fan the callback out to every source batch, as onComplete already does.
  • Records left behind by a closed page are unaffected.
  • The in-memory store deletes the batch right away, since nothing re-reads it on a later page load.

Related fix. Each batch's store callbacks are now bound to the store its record is in. Before, after a mid-page fallback from IndexedDB to the in-memory store, a batch sent earlier would clean up the in-memory record with the same sequence id. The two stores' ids overlap, so that record was unrelated.

Tests

  • Unit tests:
    • worker: transient exhaustion, both 500s and timeouts, reports retryExhausted;
    • worker: a 400 still completes;
    • main thread: exhaustion keeps the record;
    • pending and late worker messages are both handled;
    • device id is persisted and used on re-send, with a fallback for records without one;
    • the counter keeps the record twice and drops it the 3rd time; the in-memory store drops right away;
    • merged requests fan out onRetryExhausted;
    • callbacks target the right store after a fallback to the in-memory store.
    • Coverage stays at 100%.
  • New e2e test, e2e/retry-exhausted-keep.spec.ts, run for both the main-thread and worker send paths:
    1. Every upload hangs until the retry budget is spent.
    2. The test checks that the full snapshot is still in IndexedDB.
    3. The page reloads and the network recovers.
    4. The test checks that the original full snapshot is delivered.
    5. Load 2 uses a different device id; the test checks that the load-1 full snapshot is re-sent with the original device id, and load 2's own data with the new one.
  • A second e2e test runs three page loads with every upload hanging, and checks that the load-1 batch's counter goes 1 → 2 and the batch is then dropped.
  • The new e2e test fails on main: 0 full snapshots are left in IndexedDB after retries run out. The device id assertion fails without the device id change. Both pass with this change.
  • The full session replay e2e suite passes locally. The one exception is shadow-dom.spec.ts, which is flaky on main too (2 of 20 runs failed there).

Follow-ups, not in this PR

  • Scale the send timeout with payload size.
  • EventCompressor keeps the device id it was created with, so after setSessionId(sessionId, newDeviceId) within one page, split-off batches still go out with the old device id while flushed ones use the new one. This was already the case before this PR.
  • The sendBeacon 64KB prefix trim can send a Meta event without its full snapshot; its code comment assumes the snapshot was already sent eagerly.

Checklist

  • Does your PR title have the correct title format?
  • Does your PR have a breaking change?: No

🤖 Generated with Claude Code


Note

Medium Risk
Changes core upload settlement and IndexedDB lifecycle for failed batches; wrong branching could duplicate uploads or leave stale data, though server deduplication and a 3-attempt drop cap limit exposure.

Overview
Fixes session replay losing full snapshots (blank playback) when upload retries exhaust on transient errors: the SDK no longer treats those batches as delivered and deletes their IndexedDB rows.

On the send path, transient retry exhaustion now goes through keepForNextPageLoad instead of onComplete/cleanUpSessionEventsStore — on both main-thread (handleOtherResponse) and web worker (retryExhausted: true on worker complete). Non-retryable failures still complete and remove the record as before.

Persistence is extended so retries can survive reloads: batches store deviceId and are re-sent with the original id (replay id = session + device); markRetryExhausted increments a counter and drops after MAX_RETRY_EXHAUSTED_COUNT (3) page loads of repeated failure. events-manager wires onRetryExhausted, prefers stored deviceId in sendStoredEvents, and pins the source store for cleanup when IDB falls back to memory. Coalesced flushes fan out onRetryExhausted to every merged source.

Tests: new Playwright e2e retry-exhausted-keep.spec.ts (main thread + worker, device id, eventual drop); unit tests updated across stores, manager, track destination, and worker.

Reviewed by Cursor Bugbot for commit 5a234a2. Bugbot is set up for automated code reviews on this repo. Configure here.

…ansient failures

When every upload attempt for a batch failed with a transient error (send
timeout, 5xx, 408, 429, 499), the SDK called onComplete as if the batch had
been delivered, deleting its IndexedDB record. If that batch held the initial
full snapshot, later batches uploaded normally but the replay played back
blank.

Keep the stored record instead, so sendStoredEvents re-sends it on the next
page load. The worker now reports transient exhaustion as `retryExhausted`
rather than a plain `complete`. Non-retryable failures still settle the record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@bravecod
bravecod requested a review from a team as a code owner December 1, 2026 07:17
@linear-code

linear-code Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

SRC-398

@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
packages/analytics-browser/lib/scripts/amplitude-min.js.gz 68.9 KB (0%)
packages/session-replay-browser/lib/scripts/session-replay-browser-min.js.gz 141.67 KB (+0.28% 🔺)
packages/unified/lib/scripts/amplitude-min.umd.js.gz 228.75 KB (+0.18% 🔺)
@amplitude/element-selector (gzipped esm) 3.48 KB (0%)
@amplitude/analytics-browser/lite (gzipped CDN bundle) 21.44 KB (0%)

@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Session Replay Browser E2E Results

passed  183 passed

Details

stats  183 tests across 21 suites
duration  8 minutes, 35 seconds
commit  5a234a2

@bravecod

bravecod commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@Xiaoyu-Ben-Wang

Xiaoyu-Ben-Wang commented Dec 1, 2026 •

Copy link
Copy Markdown

const sendStoredEvents = async ({ deviceId }: { deviceId: string }) => {
lastKnownDeviceId = deviceId;
const sequencesToSend = await store.getSequencesToSend();
if (!sequencesToSend?.length) {
return;
}
config.loggerProvider.log(`Draining ${sequencesToSend.length} stored sequence(s) from previous session.`);
// These persisted sequences are about to be enqueued back-to-back. Without
// coalescing they flush as N separate POSTs — a request flood on page load. Mark the
// imminent flush to merge same-identity batches (the enqueues below are synchronous, so
// the whole backlog lands in the queue before the deferred flush consumes the flag). Skip
// the single-sequence case where there's nothing to merge.
if (sequencesToSend.length > 1) {
trackDestination.markCoalesceNextFlush();
}
sequencesToSend.forEach((sequence) => {
sendEventsList({
sequenceId: sequence.sequenceId,
events: sequence.events,
sessionId: sequence.sessionId,
deviceId,
});
});
};

If a batch exhausts reloads and is saved for next time, should it also store the device id to avoid using the newest device id once it tries again on next initialization? Or will the device id be correct on the next time?

…w often it is kept

- Persist the device id a batch was first sent with on its stored record and use it when the
  batch is re-sent on a later page load, so it keeps its original replay id if the device id
  changed in between. Records without one (older SDK versions, batches promoted from another
  tab) fall back to the current device id.
- Count how many times a stored batch's retries ran out on transient failures
  (onRetryExhausted -> markRetryExhausted) and drop it after MAX_RETRY_EXHAUSTED_COUNT (3),
  so a batch the endpoint keeps rejecting is not stored and re-sent forever. Merged requests
  fan the callback out to every source batch. The in-memory store drops the batch right
  away, since nothing re-reads it on a later page load.
- Bind each batch's store callbacks to the store its record is in, so a mid-page fallback
  to the in-memory store can't clean up an unrelated record with an overlapping id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@bravecod

bravecod commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

If a batch exhausts reloads and is saved for next time, should it also store the device id to avoid using the newest device id once it tries again on next initialization?

Good catch, thanks — yes. Fixed in 5a234a2:

  • When a batch moves to sequencesToSend, its record now also stores the device id it was sent with on that page. sendStoredEvents re-sends with that id, so the batch keeps its original replay id even if the device id changed (reset(), cleared cookies).
  • Records without one fall back to the current device id, same as before. These are records written by older SDK versions, or batches promoted from another tab.
  • The e2e test now changes the device id across the reload and checks that the kept full snapshot goes out under the original one.

This gap was already there for batches left behind by a closed page. Keeping batches after retries run out just makes it more common.

While I was in here I also capped how often a batch is kept. After its retries run out on 3 page loads it's dropped, so a batch the endpoint keeps rejecting doesn't pile up in IndexedDB. Details are in the PR description.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 5a234a2. Configure here.

logIdbError(this.loggerProvider, `${STORAGE_FAILURE}: ${e as string}`, e);
this.recordFailure();
}
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing transaction rejection handler

Low Severity

markRetryExhausted opens a manual readwrite transaction and only awaits tx.done after get/put/delete. The other manual transactions in this store attach tx.done.catch immediately so an aborted commit cannot become an unhandled rejection. If get or put rejects, control jumps to the outer catch and never awaits tx.done, so that rejection is unhandled.

Fix in Cursor Fix in Web

Triggered by learned rule: IDB store tx.done.catch handlers must call recordFailure()

Reviewed by Cursor Bugbot for commit 5a234a2. Configure here.

This branch has not been deployed

No deployments
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