Skip to content

feat(events): persist events to disk so they survive the process (tier 3) - #408

Merged
abelonogov-ld merged 229 commits into
andrey/event-durability-tier2-bounded-flushfrom
andrey/event-durability-tier3-persistence
Nov 21, 2026
Merged

abelonogov-ld merged 229 commits into
andrey/event-durability-tier2-bounded-flushfrom
andrey/event-durability-tier3-persistence

Conversation

@abelonogov-ld

@abelonogov-ld abelonogov-ld commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Requirements

  • I have added test coverage for new or changed functionality
  • I have followed the repository's pull request submission guidelines
  • I have validated my changes against all supported platform versions

Related issues

Tier 3 of the Event Durability spec, "Tier 3 — persistence". Stacked on #403 (tier 2) and targets that branch, so this diff shows only tier 3. It will be retargeted once the branches below it merge. The iOS counterpart is launchdarkly/ios-client-sdk#538, and both write the same on-disk format.

Opened as a draft: a multi-threading and readability review turned up items still being worked through (see Known open items).

Describe the solution you've provided

Recorded events go to an append-only log on disk rather than only an in-memory buffer, so an application that dies shortly after recording an event still reports it: the next run delivers what the previous one left behind. That covers what tier 2 cannot: SIGKILL, ANR kills, native crashes, and the system reclaiming a backgrounded process.

  • EventPersistence (new public enum) and EventProcessorBuilder.eventPersistence(...):
    • DISABLED (default): events stay in memory and the SDK does not touch the filesystem for events.
    • DEFERRED: writes happen on the SDK's commit thread, a moment after recording.
    • IMMEDIATE: track and identify write on the caller's thread before returning, so there is no window.
  • EventStore: an append-only log under the no-backup files directory, one directory per mobile key. It handles framing, capacity, torn-tail recovery of a log interrupted by a crash, and a fallback to memory when a write fails (for example, a full disk), so a disk failure never takes the application down. Each process appends to its own open-<process> log; closed ready-<payloadId> batches are shared, so a batch left by a process that never runs again is still delivered. The byte format lives in EventLogFormat and the log this process appends to in DiskEventLog, mirroring the iOS split.
  • Recording and commits (DirectEventProcessor): an evaluation appends to a pending run and updates a counter, with no encoding on the caller's thread. A commit encodes the run and its summaries together and stages them in the store. track and identify are commit points. Evaluations commit once a threshold accumulates, on flush, and before delivery.
  • Delivery reads batches oldest first. A batch keeps its payload ID across retries and process restarts, so LaunchDarkly discards a repeated delivery instead of double counting. Delivery stops at the first retryable failure, schedules a single retry instead of sleeping on the events thread, and removes a batch only once it has been accepted or permanently refused. A batch whose read fails transiently is kept for a later attempt.
  • Loss reporting: flushAsync() answers false when events the SDK accepted were lost for good: an event or summary that could not be serialized, or that was too large to store. Each loss is reported to exactly one caller, the one whose delivery closed its batch after the loss, as on iOS. Events dropped for capacity are counted in diagnostics, not reported as losses.
  • close() commits first, then delivers with what is left of one two-second budget. Neither step waits on the caller's thread past the budget, so a stalled disk write cannot become an ANR. Work that outlasts the budget finishes in the background.
  • AnalyticsEventSender posts a pre-assembled body under an explicit payload ID.
  • DEFAULT_CAPACITY goes from 100 to 2000, matching iOS, since capacity now also bounds what is held on disk.

Describe alternatives you've considered

SQLite. Measured as a store and rejected: it costs more per event than an append to a log the SDK already frames, for durability properties the log gets from write alone. See sqlite-event-persistence-findings.md in the spec folder.

Fsync on every commit. What durability is defending against is the process dying, not the device losing power. Bytes handed to the kernel survive the former, and an fsync per event would dominate the cost of track.

One shared log for all processes. That is simpler, but one process's startup recovery could rename a log another live process is still appending to. A log per process avoids that without file locks.

Additional context

Tests. 879 unit tests pass locally (testDebugUnitTest). New coverage includes EventStoreMultiProcessTest (several stores on one directory, recovery, transient read failures, events still counted against capacity while being written), DirectEventProcessorTest (commit points, retry, capacity across memory and disk, persistence failing partway through, oversized frames reported as losses, a loss reported to the right flush across a retry, close() within budget on a stalled disk write), OutboundEventBufferSerializationTest, and SameContextPerContextEventSummarizerTest.

Benchmarks. EventPersistenceBenchmark (JVM and instrumented) measures recording cost per mode. It runs only when LD_EVENT_BENCH=1, so ordinary test runs are unaffected.

Test app. Now configures EventPersistence.IMMEDIATE, so the events recorded by Eval+Kill now, which tier 2 loses, are recovered and delivered on the next launch. It also gains Over-Refresh Eval, a main-thread stress loop that compares evaluation cost while filling capacity and after it is full.

Known open items (from the threading review, to be resolved before this leaves draft):

  • flushAsync(), and so flushAndWait, does not commit on the caller's thread as flush() does, so a flushAndWait that times out can leave events only in memory, even at IMMEDIATE.
  • Batches left by a previous run are not counted against capacity until the first listing, which an offline start postpones.
  • The store and the processor both schedule commits, so a threshold commit is followed by a redundant no-op pass.

Version. EventPersistence and EventProcessorBuilder.eventPersistence have no @since tag yet; one should be added once the release version is known.

Changelog

The default capacity change gets its own changelog entry, since apps that never set it see it on upgrade.

BEGIN_COMMIT_OVERRIDE
feat(events): persist events to disk so they survive the process (tier 3)
feat(events): raise the default EventProcessorBuilder.capacity from 100 to 2000, so the in-memory event buffer can hold 20 times as many events as before, also with persistence disabled
END_COMMIT_OVERRIDE


Note

Overview
Adds Tier 3 event persistence so analytics events survive process death: recorded data is framed and written under the no-backup files directory (per mobile key), with EventPersistence (DISABLED / DEFERRED / IMMEDIATE) on EventProcessorBuilder.

DirectEventProcessor is reworked around EventCommitter + EventStore (append-only logs, DiskEventLog, BatchLocks for cross-process send vs expiry). Delivery runs on a paced scheduler with DeliveryRetryState, stable payload IDs via AnalyticsEventSender, launch delay before sending leftovers, and flushAsync() loss reporting when accepted events are dropped for good. DiagnosticReporter is split out; close() commits first then delivers within the ANR budget.

Gradle gains an opt-in LD_EVENT_BENCH instrumented benchmark path; new Android tests cover batch locks, encoding benchmarks, and null flag keys. Default event capacity moves to 1000; crash flushAndWait can bypass delivery backoff.

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

abelonogov-ld and others added 30 commits September 9, 2026 11:59
Tier 3 of the event durability spec: unrecoverable failure.

EventStore stages serialized events in memory and commits them to an append-only
log in the no-backup files directory, so events survive a process that never gets
to flush. Commit points — track, identify, an explicit flush — write on the
caller's thread before returning, and the evaluations counted since the last one
are summarized and written with them. Delivery reads closed batches back from
disk and deletes them only once LaunchDarkly has accepted them, under a payload
ID that stays the same across retries so a redelivered batch is not counted
twice. Each process of a multi-process application gets its own log.

Spec: Event Durability, "Tier 3 — unrecoverable failure"; the mechanism is
Page-Cache Event Persistence.

Co-authored-by: Cursor <cursoragent@cursor.com>
The counterpart of the iOS EventPersistenceBenchmark, covering the same
five context shapes and three privacy settings so the two platforms can
be compared rather than assumed alike. Gated on LD_EVENT_BENCH=1, which
also turns on stdout and disables up-to-date checks for the test task,
so an ordinary run skips all four and is otherwise unaffected.

The answer is that Android does not have the problem iOS had. Its
unoptimized path beats iOS's fully optimized one on every row:

  evaluation, summary only      1.87 us (iOS) ->  68 ns
  evaluation, full event       17.35 us       -> 1.51 us
  evaluation + track            38.40 us       -> 4.92 us

Cost still tracks attributes written rather than the redaction decision,
as on iOS, but at 48-59 ns per attribute against Codable's 1.14 us. So
there is no Codable-shaped overhead to remove, because there is no
Codable.

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

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/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
…y/event-durability-tier3-persistence

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

# Conflicts:
#	example/src/main/java/com/launchdarkly/example/MainActivity.java
Coming online now delivers, and the fixture brings the processor online as
it builds it, so the queued delivery could drain the store before the test
read it. The commit these cover runs offline just the same.

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
#	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
Moving these back to where tier 2 has them leaves the capacity fields and
their assignment as unchanged lines, so this branch's diff shows the commit
machinery it adds rather than a reshuffle of what it inherited.

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

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

# Conflicts:
#	example/src/main/java/com/launchdarkly/example/MainActivity.java
#	example/src/main/res/layout/activity_main.xml
…y/event-durability-tier3-persistence

* andrey/event-durability-tier2-bounded-flush:
  unserializable unit test
…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
#	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
…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
Co-authored-by: Cursor <cursoragent@cursor.com>
…y/event-durability-tier3-persistence

* andrey/event-durability-tier2-bounded-flush:
  test(fdv2): stop requiring a changeset to be the first result
…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/DirectEventProcessorTest.java
At this tier analytics go through AnalyticsEventSender, so the other
sender only ever posts diagnostics. Naming it eventSender next to
analyticsEventSender read as if it were the general-purpose one.

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

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/DirectEventProcessor.java

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

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>

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

Automated risk review (dry run): High

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

Why: This introduces on-disk event persistence (EventStore, DiskEventLog, EventDirectory) and a large rewrite of DirectEventProcessor (~17k lines across 58 files), a durability-sensitive SDK change with an unresolved Bugbot finding on close/track delivery.

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

@cursor cursor Bot added the risk:high label Nov 20, 2026
abelonogov-ld and others added 2 commits November 20, 2026 11:43
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>
@abelonogov-ld
abelonogov-ld added this pull request to stack #441 November 21, 2026 00:12
@abelonogov-ld
abelonogov-ld removed this pull request from stack #441 November 21, 2026 00:14
abelonogov-ld and others added 2 commits November 20, 2026 16:20
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.

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

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 79989ff. Configure here.

@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: high. Left a non-blocking comment. SDK rule 2: the author is not on the approved SDK team member list, so this automation cannot approve. Cursor Bugbot completed with findings that need human review, 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.

Risk: high. Left a non-blocking comment. SDK rule 2: the author is not on the approved SDK team member list, so this automation cannot approve. Cursor Bugbot completed with no findings that need human review; risk is above the low threshold, and no reviewers were assigned.

Open in Web View Automation 

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

@abelonogov-ld
abelonogov-ld added this pull request to stack #443 November 21, 2026 01:01
…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>
@abelonogov-ld
abelonogov-ld merged commit ecfbca9 into main Nov 21, 2026
7 checks passed
@abelonogov-ld
abelonogov-ld deleted the andrey/event-durability-tier3-persistence branch November 21, 2026 01:50
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.

3 participants