Skip to content

fix(events): back delivery off from an extended initial delay after a refusal - #425

Open
abelonogov-ld wants to merge 329 commits into
mainfrom
andrey/delivery-retry-extended-initial-delay
Open

abelonogov-ld wants to merge 329 commits into
mainfrom
andrey/delivery-retry-extended-initial-delay

Conversation

@abelonogov-ld

@abelonogov-ld abelonogov-ld commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Makes event delivery's backoff conform to RETRY 1.5.6: once an unexpected failure (a 401, 403 or other non-retryable 4xx) has been seen, the backoff is computed from a separate extended initial delay, until an accepted delivery resets it.

Stacked on #408 (tier 3).

Delivery used to reach the same first wait by keeping a 1 second base and raising the attempt count to at least 10 on a refusal (2⁹ s = 512 s). That matches RETRY's waits except for one case: a refusal after ten or more ordinary failures in a row overshot, waiting 1024 s or more rather than 512 s.

  • DeliveryRetryState binds EXTENDED_INITIAL_DELAY_MILLIS = 512 s (about 8.5 minutes, the same first wait as before) in place of ATTEMPTS_AFTER_UNEXPECTED.
  • The first refusal since a reset enters the extended regime with the attempt count at 1, as StreamingRetryState does. Later failures of either kind add 1 and keep the extended base and ceiling until a reset.
  • The extended delays are floored at the initial delay (RETRY 1.5.4.1).
  • retryDelaysForTesting takes the extended initial delay too. Each test passes the first refusal wait it got before, so no test's timing changes.
  • New tests: a refusal after 12 ordinary failures waits 512 s; extended delays bound below the initial delay are raised to it.

The waits for every sequence the existing tests cover are unchanged: 1, 2, 4… s up to the flush interval for ordinary failures; 512, 1024, 2048, then 3600 s for repeated refusals.

Tested: :launchdarkly-android-client-sdk:testDebugUnitTest, 1259 tests, 0 failures.


Note

Overview
Event delivery backoff now follows RETRY 1.5.6: the first unexpected failure (e.g. 401) switches into an extended regime with a dedicated 512 s base delay, instead of jumping the attempt counter to 10 so the first wait happened to be 512 s only when few prior failures existed.

DeliveryRetryState tracks inExtendedRegime and uses extendedInitialDelayMillis / extendedCeilingMillis for exponential backoff there; extended delays are floored at the normal initial delay. A successful delivery resets the regime. Test hooks take a fourth delay parameter.

DirectEventProcessor splits lifecycle so construction no longer reads the filesystem or schedules work—start() runs recovery from previous runs and periodic tasks once, with recovery queued first on the scheduler (supports tests that build an unstarted processor). EventProcessorBuilderImpl.build constructs the processor then calls start().

New unit tests cover refusal after many ordinary failures (still 512 s first wait), extended-delay floors, and no log recovery until start().

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

abelonogov-ld and others added 30 commits September 22, 2026 14:04
…y/event-durability-tier3-persistence

Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/OutboundEventBuffer.java
An evaluation of a tracked flag writes a summary counter and a feature
event, and a debug event alongside them when debugging is on. Those
writes took separate locks, so a close() landing between them delivered
the counter and then refused the event, reporting an evaluation that no
event describes.

Widen the lock that guarded the pending events to cover the summary
counters too, so the writes one evaluation makes are one critical
section. drain() splits into takeSummaries() and encode() so the flush
can take the run and the counters together and still encode outside the
lock.

Co-authored-by: Cursor <cursoragent@cursor.com>
…-durability-tier2-bounded-flush

Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java
…y/event-durability-tier3-persistence

Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java
#	launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/OutboundEventBuffer.java
createEventAndReset hands back a period's statistics and clears them in
the same call, so whoever builds the event owns it. It was built on the
scheduler thread and posted from the diagnostics thread, which may have
been busy with an earlier post; a transition to offline or background in
that window was noticed after the build and discarded the event. The
period's stream inits, events-in-batch count and dropped count went with
it, and dataSinceDate had already moved, so the next event described a
window beginning after the reset.

Move the build onto the posting thread, behind the suspension check, so
a transition leaves the counters where they are for the next period to
carry. The init event keeps its check, having nothing to consume.

Co-authored-by: Cursor <cursoragent@cursor.com>
…y/event-durability-tier3-persistence

Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java
The normalization said `>= 0`, so a capacity of nought stayed nought. On main
that threw from `new ArrayBlockingQueue<>(0)` at construction; with the pending
list there is nothing to throw, so it became a silent refusal of every event.

Worse than it sounds, because the same number is the buffer's context limit and
only the processor was normalizing it: at nought neither full events nor
summaries survived, and at -5 the processor allowed one event while the buffer
refused to summarize at all. So the fix is one normalization in ComponentsImpl
feeding both, with the processor keeping its own guard for direct construction.

Co-authored-by: Cursor <cursoragent@cursor.com>
…ing the server

describeConfiguration was sending the raw capacity, so a client configured with
nought told the service nought while running at one. It now shares the one
normalization with the buffer and the processor.

The race test was flaking about one run in six. Not the processor: the test
server records a request body with a single unlooped read, so a body past one
socket read's worth comes back truncated, at a point that moves between runs.
Thirty events instead of a hundred and fifty stays clear of it, and the test
still fails on every un-fixed run.

Co-authored-by: Cursor <cursoragent@cursor.com>
…y/event-durability-tier3-persistence

Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/ComponentsImpl.java
Three components bound themselves by this number and each was normalizing it,
or not. Clamping in the setter makes the field valid by construction, which is
what the sibling setter for the diagnostic interval already does, and leaves
every consumer -- the buffer, the processor, the diagnostic description -- to
just use it.

Co-authored-by: Cursor <cursoragent@cursor.com>
…y/event-durability-tier3-persistence

Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/ComponentsImpl.java
The two init tests asserted nothing. One asked a foreground processor to go to
the foreground, which setInBackground returns from before reaching any decision;
the other waited for the init event before going offline, so the only thing
stopping a second one was that the first had already gone. Each was held up by
the guard the other claimed to cover, and both passed with every guard deleted.

Coming to the foreground now goes through the background first, and waits for
the diagnostics thread to come free -- while the first init is still posting,
the claim is taken and the transition is turned away before it decides anything.
The offline one builds a processor that never comes online, then brings it
online to show the silence was the offline state and not a dead fixture.

Two new ones. A must-shut-down response has to stop recording and delivery for
good, which nothing exercised. And a flush running against four recorders has to
keep each evaluation in one payload: close() delivers once, so it can catch an
evaluation being stranded but never one being split across two deliveries.
Eight trials, because a single one catches a split lock about two times in three.

Co-authored-by: Cursor <cursoragent@cursor.com>
…-durability-tier2-bounded-flush

Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java
…y/event-durability-tier3-persistence

aFlushNeverSplitsAnEvaluationAcrossTwoPayloads is left behind at tier 2. It
reads each payload as it went out, which says something only where a payload is
the run taken straight from the pending list; here a delivery reads the store,
so a counter and its event can land in one payload or two for reasons that have
nothing to do with the lock. Confirmed by narrowing the lock and watching it
pass five times out of five. A comment in its place says where it went.

Co-authored-by: Cursor <cursoragent@cursor.com>
The MalformedJsonException in aContextAlreadyBeingCountedKeepsCountingOnceTheLimitIsReached
is not a serialization race: recording is sequential on the test thread and the payload is a
deterministic ~28 KB. The test-helpers HTTP server reads request bodies with a single unlooped
read, so larger bodies can be truncated depending on the machine. Fill the summarizer to a
limit of 10 contexts instead of 100 so each flush stays well under that size.

Co-authored-by: Cursor <cursoragent@cursor.com>
Offline means the application told the SDK to stay off the network, and closing does not revoke
that, so the final delivery in close() is skipped and held events are dropped. DefaultEventProcessor
behaved the same way (its FLUSH is a no-op while offline); the comments and the EventProcessor
javadoc promised more than either implementation did. Add a test pinning the behavior.

Co-authored-by: Cursor <cursoragent@cursor.com>
…-durability-tier2-bounded-flush

* andrey/event-durability-tier1-buffer:
  Document that close() discards events held while offline
…y/event-durability-tier3-persistence

* andrey/event-durability-tier2-bounded-flush:
  Document that close() discards events held while offline
…n reconnect

The SDK builds the event processor offline and turns it on once initialization is done. Coming online
used to deliver immediately, meant for the end of an outage, but it also fired on that first transition
at startup and sent the initial identify alone before anything else was recorded. DefaultEventProcessor
never did that, and the contract tests expect the first payload to wait for a flush.

The immediate delivery existed only because cancelling the periodic flush for an outage restarted its
interval on every reconnect. The flush task now stays scheduled regardless of the offline state (a run
while offline does nothing), so the interval is never restarted and what an outage buffered goes out at
the first run after it ends. No transition needs special handling.

Co-authored-by: Cursor <cursoragent@cursor.com>
…-durability-tier2-bounded-flush

Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java
…y/event-durability-tier3-persistence

Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java
#	launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/EventProcessorTestBase.java
…rent constructor

The context limit moved to the fourth parameter; the androidTest copy of the benchmark was never
compiled by the unit-test runs and kept the old order.

Co-authored-by: Cursor <cursoragent@cursor.com>
A commit takes the pending run under recordLock and encodes it outside, so until it is staged the run
is in neither pending nor the store. The capacity check counted only those two, so an event recorded in
that window was accepted past capacity; LDClientEventTest.testEventBufferFillsUp saw two identifies
with a capacity of one once startup stopped delivering the first one alone. EventStore is no longer
final so the test can pause a commit mid-staging.

Co-authored-by: Cursor <cursoragent@cursor.com>
With DEFERRED persistence, flush() and blockingFlush() now write on the
events thread instead of the calling thread. The event store finds its
directory and process name the first time it needs them, on the events
thread, not while LDClient.init builds it. close() writes on the events
thread and only falls back to the caller's thread if that thread doesn't
get to the write within the close budget. commit() returns before taking
the I/O lock when persistence is off. The IMMEDIATE and flush() javadocs
now say which thread does the write.

Co-authored-by: Cursor <cursoragent@cursor.com>
updateScheduledTasks no longer returns early once the processor is
closed. The closed flag now gates only starting work, so cancelling
always happens, and close() cancels its tasks by calling
updateScheduledTasks under stateLock instead of repeating the cancel
calls itself.

Co-authored-by: Cursor <cursoragent@cursor.com>
abelonogov-ld and others added 8 commits October 31, 2026 08:16
…ler's thread

Co-authored-by: Cursor <cursoragent@cursor.com>
…rites everything before it returns

Co-authored-by: Cursor <cursoragent@cursor.com>
…ence

The caller's thread encodes and writes the one event, without waiting for a
commit in progress; the held evaluations and the summaries are left to a commit
queued on the commit executor in the same call. The summarizer's counters are
still taken at each track or identify, so its contexts are cleared as before.

Co-authored-by: Cursor <cursoragent@cursor.com>
… reserved place

A track or identify at immediate persistence committed the store, which wrote
whatever a commit in flight had staged so far, up to megabytes of a run or a
split summary, on the application thread. It now writes just its own frame and
leaves the rest to the commit that staged it.

It is also reserved where it is admitted, so a recording on another thread
cannot take its place while it is encoded and have it refused as a loss. A
commit now releases only its own unused reservations rather than all of them.

Co-authored-by: Cursor <cursoragent@cursor.com>
A summary too large for one log frame is refused whole by the store,
logged, and counted as lost, so the flush that committed it answers
false. Reaching that takes one context evaluating dozens of the largest
JSON flags between two commits, which did not justify the packing and
halving that split it.

Co-authored-by: Cursor <cursoragent@cursor.com>
…e again

Writing only the tracked event left the evaluations before it to a commit
queued on the commit executor, so a kill straight after the track, which is
what immediate persistence is for, could take those exposures with it. With the
summary split gone, the commit costs the caller a normal encode of the held run
and the summaries, so the track commits it again before returning.

This reverts 19afcec and 1200025.

Co-authored-by: Cursor <cursoragent@cursor.com>
…rsistence again"

This reverts commit a65c588, which moves to a
PR of its own.

Co-authored-by: Cursor <cursoragent@cursor.com>
RETRY 1.5.6 makes the extended initial delay the base of the backoff once
an unexpected failure is seen. Delivery reached the same first wait by
raising the attempt count to at least 10 on a 1 s base, which a refusal
after ten or more ordinary failures overshot. Bind the extended initial
delay to 512 s, start the count at 1 on the first refusal since a reset,
and floor the extended delays at the initial delay (RETRY 1.5.4.1).

Matches the iOS change.

Co-authored-by: Cursor <cursoragent@cursor.com>
abelonogov-ld and others added 6 commits November 12, 2026 12:24
The constructor queued the recovery of what a previous run left and scheduled
the periodic flush and the diagnostics, so building a processor was enough to
start work on the events thread. The constructor now only sets fields, and
start() does that work. EventProcessorBuilderImpl.build calls it straight
after the constructor, before anything else can use the processor, so the
recovery is still the first task on the events thread and every delivery
queued after it waits for it.

Tests start each processor they build, as the builder does, and a new one
checks that a processor not yet started leaves a previous run's log alone.

Co-authored-by: Cursor <cursoragent@cursor.com>
Each environment now has the whole `capacityBytes`, like `capacity`,
rather than an equal share of it. This follows the review on iOS
([ios-client-sdk#538](launchdarkly/ios-client-sdk#538 (comment))),
which makes the same change.

Stacked on #408 (tier 3).

- **An equal share is too small where there are many environments.**
Some customers configure 7, which at the default left each under 3 MiB.
- **Adding an environment no longer shrinks the others.** A share was
fixed when the store was built, so a directory within its old share
could be over its new one, and new events were refused until delivery or
expiry drained it.
- **The disk the SDK may use now grows with the environments**: up to 20
MiB each at the default. Ordinary traffic reaches `capacity` (2000
events) long before that; only unusually large events, or summaries
piling up through a long outage, get near it.
- **`ComponentsImpl.shareOfCapacityBytes` is gone**; the store gets
`capacityBytes` as it is, and already reads zero or less as the default.
The `EventProcessorBuilder.capacityBytes` docs say it is for each
environment.

Test: `theByteCapacityIsSharedEquallyByTheConfiguredEnvironments`
becomes
`eachEnvironmentHasTheWholeByteCapacityHoweverManyAreConfigured`: with
seven environments and a 2,400-byte capacity, an 850-byte event is
delivered, where the old split's 342 bytes would have refused it.

`./gradlew :launchdarkly-android-client-sdk:testDebugUnitTest`: 1257
tests, 0 failures (25 skipped).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Overview**
> **Persisted event byte limits are now per environment**, matching
`capacity(int)` and the iOS client change, instead of splitting
`capacityBytes` evenly across all configured mobile keys.
> 
> `ComponentsImpl` drops `shareOfCapacityBytes` and passes the
configured `capacityBytes` straight into `EventStore.create`.
**`EventProcessorBuilder` docs** are updated to state each secondary
environment gets the full limit, so adding environments no longer
shrinks others and apps with many envs (e.g. seven) aren’t stuck with
tiny per-env quotas.
> 
> The unit test is renamed and asserts that with seven environments and
a 2,400-byte limit, an ~850-byte custom event still flushes—behavior
that would fail under the old equal-share rule.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a809095. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Cursor <cursoragent@cursor.com>
Changes `EventProcessorBuilder.DEFAULT_MAX_AGE_MILLIS` from 7 days to 24
hours. Persisted events that have not been delivered within 24 hours are
discarded and counted as dropped, and so is what the SDK stored for a
mobile key the application stopped using. Applications can still call
`maxAgeMillis(long)` to keep events longer. It has no effect where
`eventPersistence` is `DISABLED`.

Stacked on #408 (tier 3).

- `DEFAULT_MAX_AGE_MILLIS` is now `24L * 60 * 60 * 1000`, with its
Javadoc updated.
- `EventStoreBoundsTest.keepsABatchYoungerThanTheMaximumAge` aged its
batch by 6 days, which is now past the default; it ages it by 12 hours.
The tests that age by 8 days still exceed the maximum age and are
unchanged.

iOS counterpart: launchdarkly/ios-client-sdk#549.

Tested: `:launchdarkly-android-client-sdk:testDebugUnitTest`, 1257
tests, 0 failures.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Overview**
> **Shortens the default retention window** for persisted analytics
events from **7 days to 24 hours** by updating
`EventProcessorBuilder.DEFAULT_MAX_AGE_MILLIS` and its Javadoc.
> 
> When event persistence is enabled, undelivered batches older than the
default max age are discarded (and counted as dropped); apps can still
override via `maxAgeMillis(long)`. The change has **no effect** when
`eventPersistence` is `DISABLED`.
> 
> `EventStoreBoundsTest.keepsABatchYoungerThanTheMaximumAge` now ages a
batch by **12 hours** instead of 6 days so it still falls under the new
default.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
057a2ef. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Cursor <cursoragent@cursor.com>
The unknown-flag de-duplication set added in 68d3dbf is backed by a
ConcurrentHashMap, which rejects null, so variation(null, ...) threw a
NullPointerException on the caller's thread. A null key now skips the
de-duplication and returns the default, as it did before.

Co-authored-by: Cursor <cursoragent@cursor.com>
@cursor cursor Bot added the risk:medium label Nov 21, 2026

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

Risk: medium.

Automated risk review (dry run): Medium

This PR would not be automatically approved. Human approval required.

Why: DeliveryRetryState changes event-delivery backoff after unexpected refusals, and DirectEventProcessor moves recovery, flush, and diagnostics out of the constructor into start(). That is a moderate event-pipeline behavior change with tests, so it is not Low. Human review is needed and no reviewers were assigned.

If you disagree with this review, share this PR in #feedback-agent-approvals or submit a changes-requested review explaining why.

Open in Web View Automation 

Sent by Cursor Approval Agent: Dry-Run PR Approver

abelonogov-ld and others added 5 commits November 20, 2026 16:18
…ty-tier1-buffer

Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	launchdarkly-android-client-sdk/build.gradle
#	launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/ComponentsImpl.java
#	shared-test-code/build.gradle
Persisted batches are posted by AnalyticsEventSender, which ignored EventProcessorBuilder.enableCompression, so only diagnostic events were compressed. The batch on disk stays plain JSON; each attempt compresses it, and one that cannot be compressed goes uncompressed.

Co-authored-by: Cursor <cursoragent@cursor.com>

@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 comment

Risk: medium. SDK rule 2 (Approve only PRs opened by an SDK team member) decides this result: the PR is not eligible for automatic approval. Cursor Bugbot completed with no findings, but risk is above the low threshold, so human review is needed and no reviewers were assigned.

Open in Web View Automation 

Sent by Cursor Approval Agent: SDK - Pull Request Router and Approver

@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 comment

Risk: medium. SDK rule 2 (Approve only PRs opened by an SDK team member) decides this result: the PR is not eligible for automatic approval. Cursor Bugbot completed with no findings, but risk is above the low threshold, so human review is needed and no reviewers were assigned.

Open in Web View Automation 

Sent by Cursor Approval Agent: SDK - Pull Request Router and Approver

abelonogov-ld and others added 2 commits November 20, 2026 17:19
…o be discarded

sdk-test-harness v2.46.0 added "events/delivery retry/payload is discarded if the
retry also fails". With persistence, a batch whose retry fails is kept and posted
again later (DeliveryRetryState: a failure never stops delivery), so the next post
repeats the payload instead of carrying only the later event. The other delivery
retry tests pass.

Co-authored-by: Cursor <cursoragent@cursor.com>

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

Risk: medium. SDK rule 2 (Approve only PRs opened by an SDK team member) decides this result: the PR is not eligible for automatic approval. Cursor Bugbot completed with no findings, but risk is above the low threshold, so human review is needed and no reviewers were assigned.

Open in Web View Automation 

Sent by Cursor Approval Agent: SDK - Pull Request Router and Approver

Base automatically changed from andrey/event-durability-tier3-persistence to main November 21, 2026 01:50

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant