Repository navigation
feat(events): add flushAndWait with a bounded timeout (tier 2) - #403
Conversation
Tier 2 of the event durability spec: recoverable failure. flushAndWait(timeout) delivers what has been recorded and reports whether it got there inside the budget, so an application that knows it is about to go away — backgrounding, or an uncaught exception handler on its way out — gets an answer instead of a fire-and-forget flush. Delivery now reports its outcome so the bounded call can tell delivered from not. Spec: Event Durability, "Tier 2 — recoverable failure", §10. Co-authored-by: Cursor <[email protected]>
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush Co-authored-by: Cursor <[email protected]> # Conflicts: # launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush Co-authored-by: Cursor <[email protected]> # Conflicts: # launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush Co-authored-by: Cursor <[email protected]> # Conflicts: # example/src/main/java/com/launchdarkly/example/MainActivity.java # example/src/main/res/layout/activity_main.xml
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush * andrey/event-durability-tier1-buffer: unserializable unit test
…-durability-tier2-bounded-flush Co-authored-by: Cursor <[email protected]> # Conflicts: # launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush * andrey/event-durability-tier1-buffer: test(fdv2): stop requiring a changeset to be the first result
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush Co-authored-by: Cursor <[email protected]> # Conflicts: # launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java
…-durability-tier2-bounded-flush Co-authored-by: Cursor <[email protected]>
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush Co-authored-by: Cursor <[email protected]> # Conflicts: # launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush Co-authored-by: Cursor <[email protected]> # Conflicts: # launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush * andrey/event-durability-tier1-buffer: Document that close() discards events held while offline
…-durability-tier2-bounded-flush Co-authored-by: Cursor <[email protected]> # Conflicts: # launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java
…-durability-tier2-bounded-flush
Co-authored-by: Cursor <[email protected]>
…d delivery Co-authored-by: Cursor <[email protected]>
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: c50db314-b25e-498e-aa0a-cb4c844f579d) |
…allel environments Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
…and use American spelling Co-authored-by: Cursor <[email protected]>
I added similar unit tests for tier-2 but they don't account the case of restoring connection. It is part of tier-3 |
|
Similar tests are |
…et is read as a bound Co-authored-by: Cursor <[email protected]>
|
bugbot review |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 7457a26. Configure here.
…-durability-tier2-bounded-flush
Co-authored-by: Cursor <[email protected]>
…-durability-tier2-bounded-flush
…-durability-tier2-bounded-flush
…er 1) (#397) **Requirements** - [x] I have added test coverage for new or changed functionality - [x] I have followed the repository's [pull request submission guidelines](../blob/main/CONTRIBUTING.md#submitting-pull-requests) - [ ] I have validated my changes against all supported platform versions **Related issues** Fixes #281. `DefaultEventProcessor.close()` waited with no limit for its final flush, which on a slow network blocked the calling thread long enough to trigger an ANR. `DirectEventProcessor.close()` waits at most two seconds for that delivery and then lets it finish in the background. Tier 1 of the Event Durability spec, "Tier 1 — the buffer". Tier 2 is stacked on this branch as #403; tier 3 will follow. **Describe the solution you've provided** `DirectEventProcessor` takes over from java-sdk-internal's `DefaultEventProcessor` in `ComponentsImpl`, and `OutboundEventBuffer` replaces the bounded queue that used to sit between the calling thread and the summarizer. That queue is the problem this tier removes. An evaluation handed its event to an `ArrayBlockingQueue` and a dispatcher thread summarized it on the far side, so a burst of evaluations of untracked flags could fill the queue and displace the `track` and `identify` events an application actually asked to send. Summarizing on the recording thread means an evaluation of an untracked flag costs a counter increment and can never displace anything, because it never occupies a slot in the first place. `OutboundEventBuffer` holds in full only the events that have to be sent one by one. It reuses java-sdk-internal's `EventOutputFormatter` and summarizer implementations rather than reimplementing them, so there stays exactly one definition of what an event looks like on the wire. Two smaller changes ride along, both prerequisites rather than additions: - java-sdk-internal moves to 1.12.0, which makes the summarizer and formatter types public so the buffer can use them from its own package. - Diagnostic events are no longer sent while the SDK is offline or the application is backgrounded. **Describe alternatives you've considered** *Reuse `DefaultEventProcessor` and raise its queue capacity.* This moves the threshold without removing it. The displacement is a property of having a bounded handoff between the caller and the summarizer at all, and a render loop re-evaluating a tracked flag will reach any capacity you pick. *Keep the buffer inside java-sdk-internal's package* to reach its package-private types. This worked, but it relied on a split package, which breaks Java modules and needed a Javadoc exclusion to build at all. Making the types public upstream was the durable fix, and is why the dependency bump is here. **Additional context** *Naming.* `DirectEventProcessor` and `OutboundEventBuffer` rather than an `Android` prefix: that prefix in this package is reserved for adapters over Android OS APIs, such as `AndroidPlatformState` and `AndroidTaskExecutor`, and neither of these classes touches one. "Direct" names the contrast with `DefaultEventProcessor` — nothing sits between the caller and the summarizer. `DefaultEventProcessor` was unavailable as a name because java-sdk-internal already exports it and this package imports from it. *Tests.* `DirectEventProcessorTest`, `EventProcessorBufferingTest` and `EventProcessorPrivacyTest` share an `EventProcessorTestBase`, adding 22 tests across buffering, capacity, private-attribute redaction and diagnostics. The full unit suite is 752 tests, all passing locally. *Platform validation.* The requirements box above is left unchecked deliberately. Behaviour is covered by the unit suite, but performance was measured on one physical device rather than across the supported API range. *Example app.* Gains an "Eval+track+kill" button that evaluates a flag, tracks an event, flushes, and then kills the process five seconds later. That is the reproduction for the loss this work addresses, and it still loses the events on this tier — tier 3 is what makes them survive. Its `LDClient.init` call also moves off the deprecated three-argument overload. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Overview** > Replaces the SDK’s **java-sdk-internal `DefaultEventProcessor` wrapper** with **`DirectEventProcessor`** and **`OutboundEventBuffer`**, so **flag evaluations are summarized on the calling thread** and **event-buffer capacity applies only to full-fidelity events** (track/identify/custom/feature), avoiding bursts of untracked evaluations crowding out events an app asked to send. > > **`DirectEventProcessor`** handles flush scheduling, offline/background behavior (including **no diagnostic posts while offline or backgrounded**), atomic record/flush handoff, bounded **`close()`** (2s wait then background finish), and a **dedicated diagnostics posting thread** separate from analytics delivery. **`OutboundEventBuffer`** reuses internal summarizers/formatters for wire-compatible payloads and bounds per-context summary cardinality. > > Config/docs tweaks: **`capacity` below 1 is clamped to 1**, diagnostics report the effective capacity, and **`EventProcessor.close()`** is documented as discarding buffered events when offline. **`LDClient.init(..., timeout)`** replaces Future-based waiting in the sample **`MainActivity`**; dexcount moves off **`example`** to a new **`:test-app`** QA harness (including **Eval+track+kill** for event-loss reproduction). > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 36f60c8. 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 <[email protected]> Co-authored-by: Todd Anderson <[email protected]>
…r 3) (#408) **Requirements** - [x] I have added test coverage for new or changed functionality - [x] I have followed the repository's [pull request submission guidelines](../blob/main/CONTRIBUTING.md#submitting-pull-requests) - [ ] 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](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 1000, 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. <!-- CURSOR_SUMMARY --> --- > [!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. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9524e93. 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 <[email protected]> Co-authored-by: abelonogov <[email protected]>
Requirements
Related issues
Tier 2 of the Event Durability spec, "Tier 2 — recoverable failure" (§10). Stacked on #397 (tier 1), and targets that branch so this diff shows only tier 2. It is small and self-contained, so it can be reviewed in parallel with #397. It will be retargeted to
mainonce #397 merges.Describe the solution you've provided
A new public method,
LDClientInterface.flushAndWait(long timeout, TimeUnit unit). It sends what has been recorded and returns whether the events were delivered within the timeout.flush()is fire-and-forget, so an application that knows it is about to lose the chance to send (an uncaught exception handler, a move to the background) had no way to give its events that chance and find out whether it worked.flushAndWaitgives it both, with a bound the caller chooses.EventProcessorgainsblockingFlush(long, TimeUnit)as a default method, so custom implementations written before it still compile. The default falls back to the unboundedblockingFlush()and returns true.DirectEventProcessorimplements it. Delivery now reports its outcome: true if the events were accepted or there was nothing to send, false if offline, closed, or the send failed. If the timeout expires, the delivery is left running rather than cancelled, because the buffer has already been drained into the payload and interrupting it would only make the loss certain.LDClient.flushAndWaitshares one budget across them rather than giving each a fresh copy, so the timeout is the most the call can take.Describe alternatives you've considered
Make
flush()return aFuture. That changes the signature of an existing public method, and aFuturestill leaves the caller to pick a timeout and interpret the exceptions. A boolean with the timeout in the call is the shape a crash handler actually needs.Cancel the delivery on timeout. It frees the thread sooner but guarantees the events are lost, since they are no longer in the buffer. Letting it finish in the background gives them the best chance at no cost to the caller, who has already stopped waiting.
Additional context
Tests. Four new tests in
DirectEventProcessorTestcover delivered events, nothing to send, offline, and the timeout expiring first. The full unit suite and the instrumented suite (126 tests on an emulator) pass locally.Test app. Gains two controls that show what this tier can and cannot do:
FlushOnCrashHandlercallsflushAndWaitwith a two-second budget before handing the crash on, so the events are delivered.SIGKILL. Nothing can run, so the events are lost. That is the gap tier 3 (on-disk persistence) closes.Version. The new methods are marked
@since 5.17.0; adjust if the release lands under a different version.Note
Overview
Adds
LDClientInterface.flushAndWait(timeout, unit), which flushes pending analytics events and returns whether delivery completed within the caller’s budget—aimed at last-chance sends (crash handlers, shutdown, background transitions).DirectEventProcessornow exposesflushAsync()with delivery coalescing (concurrent flushes share one in-flight post), outcome reporting (offline, HTTP failure, partial serialization drops, events lost by an earlier undelivered run), and leaves timed-out deliveries running rather than canceling them.OutboundEventBuffer.PayloadgainsisComplete()so a successful HTTP response still counts as failure when events were dropped on encode.LDClient.flushAndWaitstarts async flushes for all configured environments in parallel and waits on a single shared deadline.LDCrashHandler(experimental) wraps the default uncaught-exception handler and callsflushAndWaitbefore delegating to the prior handler.EventProcessor.flushAsync()is added with a default that bridges legacyblockingFlushviaLDFutures.fromBlockingCall.Unit, instrumentation, and test-app controls (Eval+Crash now vs Eval+Kill now) cover success, timeout, multi-env, closed client, and crash-path delivery.
Reviewed by Cursor Bugbot for commit 1d976b5. Bugbot is set up for automated code reviews on this repo. Configure here.