Repository navigation
feat(events): persist events to disk so they survive the process (tier 3) - #408
Conversation
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
…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
…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
…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
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>
There was a problem hiding this comment.
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.
Sent by Cursor Approval Agent: Dry-Run PR Approver
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>
…y/event-durability-tier3-persistence
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>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
❌ 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.
There was a problem hiding this comment.
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.
Sent by Cursor Approval Agent: SDK - Pull Request Router and Approver
There was a problem hiding this 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 no findings that need human review; risk is above the low threshold, and no reviewers were assigned.
Sent by Cursor Approval Agent: SDK - Pull Request Router and Approver
…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>



Requirements
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) andEventProcessorBuilder.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:trackandidentifywrite 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 ownopen-<process>log; closedready-<payloadId>batches are shared, so a batch left by a process that never runs again is still delivered. The byte format lives inEventLogFormatand the log this process appends to inDiskEventLog, mirroring the iOS split.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.trackandidentifyare commit points. Evaluations commit once a threshold accumulates, on flush, and before delivery.flushAsync()answersfalsewhen 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.AnalyticsEventSenderposts a pre-assembled body under an explicit payload ID.DEFAULT_CAPACITYgoes 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
writealone. Seesqlite-event-persistence-findings.mdin 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 includesEventStoreMultiProcessTest(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, andSameContextPerContextEventSummarizerTest.Benchmarks.
EventPersistenceBenchmark(JVM and instrumented) measures recording cost per mode. It runs only whenLD_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 soflushAndWait, does not commit on the caller's thread asflush()does, so aflushAndWaitthat times out can leave events only in memory, even atIMMEDIATE.Version.
EventPersistenceandEventProcessorBuilder.eventPersistencehave no@sincetag 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.capacityfrom 100 to 2000, so the in-memory event buffer can hold 20 times as many events as before, also with persistence disabledEND_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) onEventProcessorBuilder.DirectEventProcessoris reworked aroundEventCommitter+EventStore(append-only logs,DiskEventLog,BatchLocksfor cross-process send vs expiry). Delivery runs on a paced scheduler withDeliveryRetryState, stable payload IDs viaAnalyticsEventSender, launch delay before sending leftovers, andflushAsync()loss reporting when accepted events are dropped for good.DiagnosticReporteris split out;close()commits first then delivers within the ANR budget.Gradle gains an opt-in
LD_EVENT_BENCHinstrumented benchmark path; new Android tests cover batch locks, encoding benchmarks, and null flag keys. Default event capacity moves to 1000; crashflushAndWaitcan bypass delivery backoff.Reviewed by Cursor Bugbot for commit 9524e93. Bugbot is set up for automated code reviews on this repo. Configure here.