Skip to content

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

Open
abelonogov-ld wants to merge 279 commits into
andrey/event-durability-tier2-bounded-flushfrom
andrey/event-durability-tier3-persistence
Open

abelonogov-ld wants to merge 279 commits into
andrey/event-durability-tier2-bounded-flushfrom
andrey/event-durability-tier3-persistence

Conversation

@abelonogov-ld

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

Copy link
Copy Markdown
Contributor

Third in the event-durability stack, on top of #536. Recorded events go to an on-disk log rather than an in-memory buffer, so an application that dies moments after recording one still reports it: the next run delivers what the last one left behind.

What changes

EventStore is a new on-disk log, with capacity, framing, interrupted-log recovery, and multi-process safety. NullEventStore stands in where the platform gave the SDK nowhere to write, which is the behaviour the SDK had before.

Recording no longer encodes on the caller's thread. An evaluation appends to a held run and updates a counter; a commit turns the whole run into bytes at once. Recording a custom or identify event is a commit point, because an application reporting something it chose to report is saying it matters more than the microseconds it costs. Evaluations commit once pendingCommitThreshold of them accumulate, when a delivery starts, or on flush.

LDConfig.eventPersistence lets the application choose whether a commit point runs on the caller's thread (.immediate), off it (.deferred), or not at all (.disabled).

Delivery sends batches oldest first and stops at the first retryable failure, so the rest keep their place in the log instead of the SDK spending the session's requests on a service that is refusing them.

Reconciling with tier 2

Tier 2 replaced the delivery gate this branch was built on, so the merge had to pick one design rather than keep both.

Coalescing comes from tier 2: flushes arriving before a delivery starts join it, one already started is never joined, and nothing holds the drain back while a retry runs. What tier 2 did not need is a way to keep an in-flight batch from being sent twice — it empties its buffer before publishing, so a second delivery finds nothing. Here a batch stays on disk until its response arrives, which is what isDelivering guarded.

batchesInFlight takes its place. A delivery claims the batches it lists and releases them once it has an answer, so a later delivery still runs and still sends what it closed for itself; only the batches already on their way are left out. A caller whose own events are all that remain unsent is answered true, which is exactly the contract tier 2 documents: an answer is about the batch the caller's own delivery took, never one an earlier delivery lost.

The loss flag is now taken once per delivery rather than once per caller, so everyone joined to it hears about a loss instead of only whoever was answered first, and a scheduled delivery with no waiters leaves it for the caller who is owed it. This branch had also fixed the duplicate event reporter independently; that now comes from #537, so the local copy is gone.

Verification

  • 824 tests pass on iOS; macOS and tvOS build. No new SwiftLint violations.
  • The in-flight claim is load-bearing: removing the filter fails 5 tests, including does not send a batch again when a delivery is asked for while one is in flight.
  • DiagnosticReporterSpec.testRetries flaked once under load and passed on re-run; it has a 0.1 s timeout and is unrelated to these changes.

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 eventCapacity 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
11.8.1 bumps version metadata and changelog; CI workflows move to actions/checkout@v7, newer Xcode/setup pins, and a Dependabot config for GitHub Actions (including v10).

The core change is replacing the in-memory EventReporter with DirectEventProcessor, an on-disk EventStore (framed logs, recovery, capacity/age limits), and supporting delivery/commit/background paths. Recorded events can survive process death when persistence is enabled; close and background flows commit and attempt delivery with clearer backoff and retry behavior.

LDConfig adds experimental eventPersistence (.disabled / .deferred / .immediate), eventCapacityBytes, eventMaxAge, and eventDeliveryDelay, and raises default eventCapacity from 100 to 2000. Flush APIs now take a timeout and return FlushResult instead of a bare Bool; Obj-C mirrors the same contract.

LDClient coordinates start() / close() so closes finish committing before a new start opens stores; multi-environment start order is primary then sorted secondaries; background event commit/delivery is centralized in BackgroundEventDelivery. Smaller fixes: WRONG_TYPE evaluation events, Date comparison workaround for a Foundation back-deploy issue, and contract harness eventFlushInterval in seconds.

Also adds shared Xcode test schemes for macOS/tvOS/watchOS tests and refreshes generated mocks.

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

@abelonogov-ld
abelonogov-ld requested a review from a team as a code owner October 8, 2026 22:44

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

abelonogov-ld and others added 6 commits October 9, 2026 21:08
A Mac runs a second instance of an application under the same process
name, so a log named for the process alone would still be shared. Where
that can happen (macOS, and iPhone or iPad applications running on a
Mac), the open log is held under a non-blocking flock. An instance that
finds the name's log locked opens one named for its process ID instead,
and recovery closes off any open log no live process holds, whatever it
is named. The kernel drops the lock when the process dies, so a crash
never leaves a stale one.

iOS, tvOS and watchOS do not lock: a suspended application holding a
lock on a file in a shared container is killed (0xdead10cc), and there a
process name is one live process.

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

Co-authored-by: Cursor <cursoragent@cursor.com>
A commit only stages events; whichever delivery runs next is what closes
them into a batch. So a flush could find everything claimed, conclude it
had nothing of its own left to send, and report success for events that
were about to fail with somebody else's delivery.

batchesInFlight becomes a map to a Claim holding the batch's outcome and
the deliveries waiting to hear it, and a DeliveryAnswer gathers this
delivery's own outcome with every claim it skipped. Only the answer
waits; the batches it closed for itself go out straight away.

The loss flag becomes a counter for the same reason. Each delivery takes
the count as it closes its batch and answers for the losses up to that
mark, so a loss reaches the caller whose delivery it happened before
rather than whichever response arrived first.

Claims also move off stateLock onto a claimLock of their own, so an
evaluating thread reading lastEventResponseDate never waits on a listing
of the store.

Co-authored-by: Cursor <cursoragent@cursor.com>
@abelonogov-ld
abelonogov-ld changed the base branch from andrey/event-durability-tier2-bounded-flush to v11 October 11, 2026 23:47
abelonogov-ld and others added 3 commits October 11, 2026 17:29
… sent twice

A write that fails partway can leave whole frames in the log while the store
keeps every byte of it in memory to deliver from there. The landed frames were
then sent twice: beside the memory copy when the log was closed this session,
or by recovery on the next launch. The log is now cut back to where the write
started before persistence is given up on.

Co-authored-by: Cursor <cursoragent@cursor.com>
…ile it writes through

DiskEventLog reads apart from diagnostic logging; the store's property becomes
diskLog. File names on disk are unchanged, so a log left by an earlier version
is still recovered.

EventLogFile was a namespace of functions over a raw descriptor, with -1
standing for closed. It is now a value owning the descriptor, with writing,
sizing, truncating and closing as its methods, and DiskEventLog holds it as an
optional. The write hook tests use takes the file rather than a descriptor.

Co-authored-by: Cursor <cursoragent@cursor.com>
@abelonogov-ld
abelonogov-ld marked this pull request as ready for review October 12, 2026 02:01

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

abelonogov-ld and others added 4 commits October 11, 2026 19:36
…oked up once

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
@abelonogov-ld
abelonogov-ld marked this pull request as draft October 12, 2026 03:56
abelonogov-ld and others added 8 commits October 11, 2026 21:17
…lainly

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
…th the protocol and null object in files of their own

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

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

Co-authored-by: Cursor <cursoragent@cursor.com>
…er, as Android has it

Co-authored-by: Cursor <cursoragent@cursor.com>
… cannot open room under capacity

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
…ract test service (#560)

<!-- TERMAG_PR_BODY_BEGIN -->
The contract test service set `LDConfig.eventFlushInterval` to the
harness's `flushIntervalMs` value without converting it.
`eventFlushInterval` is a `TimeInterval` in seconds, so a 1000 ms
interval became 1000 seconds and the SDK never flushed on its own during
a test. The service now divides by 1000, the same way it converts
`startWaitTimeMs`. This is a test-service change only. The harness's
automatic flush tests (sdk-test-harness#669) configure a 1 s interval
and fail without it. Other tests are unaffected: the harness default of
1,000,000 ms and the 60 s delivery cooldown interval both stay far
longer than any test.

Testing: not built here, because this box has no Xcode; CI builds the
service and runs the current v2 contract tests.
<!-- TERMAG_PR_BODY_END -->

<!-- termag: box=i-099691946751009d8 project=appease-ai-feverish-2 -->
<sub>Opened from termag</sub>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Overview**
> The contract test service was assigning the harness’s
**`flushIntervalMs`** directly to **`LDConfig.eventFlushInterval`**,
which is a **`TimeInterval` in seconds**. A 1 s harness setting became
1000 s, so automatic flush behavior in tests never matched intent.
> 
> **`SdkController`** now sets **`eventFlushInterval = flushIntervalMs /
1_000`**, matching how **`startWaitTimeMs`** is converted for client
startup. This is a test-service-only mapping fix; it unblocks harness
automatic flush scenarios that rely on short intervals.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7219798. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
abelonogov-ld added a commit to launchdarkly/android-client-sdk that referenced this pull request Nov 20, 2026
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>
abelonogov-ld and others added 3 commits November 20, 2026 11:46
Changes the default `LDConfig.eventMaxAge` 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 set
`eventMaxAge` to keep events longer. It has no effect where
`eventPersistence` is `.disabled`.

Stacked on #538 (tier 3).

- `LDConfig.Defaults.eventMaxAge` is now `24 * 60 * 60`, and the docs on
`LDConfig.eventMaxAge` and `ObjcLDConfig.eventMaxAge` say so.
- `LDConfigSpec` asserts the new default.
- Three `EventStoreSpec` tests that age a batch by 6 days or 1 day and
expect it to be kept now age it by 12 hours. The tests that age by 8 or
30 days still exceed the maximum age and are unchanged.

Android counterpart: launchdarkly/android-client-sdk#424.

Tested: `LaunchDarklyTests` on Mac Catalyst, 1233 tests, 0 failures.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Overview**
> **Changes the default `LDConfig.eventMaxAge` from 7 days to 24
hours**, so persisted analytics events (and stale on-disk data for
unused mobile keys) are discarded sooner unless the app sets a higher
value. This only applies when `eventPersistence` is enabled.
> 
> Updates `LDConfig.Defaults.eventMaxAge`, public and Objective-C
(`ObjcLDConfig`) docstrings, `LDConfigSpec` default expectations, and
`EventStoreSpec` expiry tests that previously aged batches by 6 days or
1 day now use **12 hours** (`0.5` days) so they still sit under the new
ceiling.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c5ae219. 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>
…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, 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: high. Cursor Bugbot did not complete successfully on this head, so this run is not approved. SDK Approval Policy rule 2 (approve only PRs opened by an SDK team member) also withholds approval; 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 added a commit to launchdarkly/android-client-sdk that referenced this pull request Nov 21, 2026
…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 <cursoragent@cursor.com>
Co-authored-by: abelonogov <abelonogov@abelonogovs-MacBook-Pro.local>
abelonogov-ld and others added 4 commits November 23, 2026 09:17
… by name (#572)

**Requirements**

- [x] I have added test coverage for new or changed functionality
- [x] I have followed the repository's [pull request submission
guidelines](../blob/v11/CONTRIBUTING.md#submitting-pull-requests)
- [ ] I have validated my changes against all supported platform
versions

**Related issues**

Found while hardening the Observability and Session Replay plugins
(`swift-launchdarkly-observability`) for apps configured with
`LDConfig.secondaryMobileKeys`.

**Describe the solution you've provided**

`LDClient.start` created one client per environment, and registered
every plugin with it, by iterating a `[String: String]` dictionary of
environment names to mobile keys. Swift seeds dictionary hashing per
process, so that order changed from launch to launch, and the primary
environment was often not the first one visited.

A plugin that keeps a single instance — such as the Observability
plugin, which publishes one pipeline and rejects later registrations —
therefore attached to whichever environment happened to come first,
which could be a secondary one. Its telemetry then went to the wrong
environment, on some launches and not others.

`start` now builds an ordered list: the primary environment first, then
the secondary environments sorted by name. Clients are created, and
plugins registered with them, in that order on every launch. Nothing
else about startup changes; the completion still fires once every client
has started.

This is defensive: plugins should still check which client they are
registered with (the Observability plugin is getting that check
separately), but a stable, primary-first order removes the
launch-to-launch nondeterminism for any plugin that does not.

**Describe alternatives you've considered**

- Leaving the order unspecified and relying on plugins alone. Each
plugin author would have to know that the order is random, and any that
does not would misbehave intermittently.
- Exposing the environment name in `EnvironmentMetadata`, so that
`getHooks` could tell a secondary environment apart. Worth doing
separately; it is an API addition, while this change is not.

**Additional context**

`testEnvironmentsAreStartedPrimaryFirstThenSecondariesByName` records
the order of `getHooks` and `register` calls across a primary and five
secondaries, and checks that the first client registered is the one
`LDClient.get()` returns. Against the previous code it fails (a
secondary was registered first); with this change it passes, along with
the rest of `LDClientPluginsSpec` and `LDClientSpec` on the iOS
simulator.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Overview**
> **`LDClient.start`** no longer walks a `[String: String]` dictionary
of environment names to mobile keys when creating clients and
registering plugins. It builds a fixed **`environments`** list—the
primary key first, then secondaries sorted by name—so creation and
plugin **`register` / `getHooks`** calls happen in the same order on
every launch.
> 
> This removes launch-to-launch nondeterminism that could register
single-instance plugins (e.g. Observability) with a secondary client
first and send telemetry to the wrong environment.
> 
> Tests add
**`testEnvironmentsAreStartedPrimaryFirstThenSecondariesByName`** and
extend **`StubPlugin`** with an **`onGetHooks`** hook to assert ordering
across six environments.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e338a16. 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>
## Summary

Replaces the one `Date <= Date` comparison in the SDK
(`FeatureFlag.shouldCreateDebugEvents`) with a comparison of the two
dates' `timeIntervalSinceReferenceDate` values. Behavior is unchanged.
The SDK no longer references Foundation's back-deployed `Date <=`
operator, which crashes on some iOS 27.2 beta builds.

Reported through customer support: an App Store app built with Xcode
27.2 crashed on 183 devices in two weeks with a jump to address `0x0`
inside `static Date.<= infix`, called from
`FeatureFlag.shouldCreateDebugEvents` via `LDClient.stringVariation`.

## Root cause (Apple, not the SDK)

- The Xcode 27.2 SDKs declare Foundation's `Date <=` and `Date >=` as
`@backDeployed(before: iOS 27.2)`. Apple added the operators to fix NaN
handling: [swift-foundation
#2223](swiftlang/swift-foundation#2223),
back-deployed on the release branch in [swift-foundation
#2230](swiftlang/swift-foundation#2230).
- An app built with that SDK weak-imports the OS symbol and calls it
whenever the device reports 27.2 or later.
- iOS 27.2 developer beta 1 (24B5084k) and beta 2 (24B5089g) shipped a
Foundation that did not export the symbol, so the call lands at address
0. Foundation gained the exports in beta 3 (24B5099f) and every later
build, confirmed from Apple's own binaries in the [ipsw-diffs Foundation
diff](https://github.com/ipsw-diffs/ios-27/blob/main/diffs/27_2_24B5089g_vs_27_2_24B5099f/DYLIBS/System/Library/Frameworks/Foundation.framework/Foundation.md).
- Builds made with Xcode 27.1 or earlier inline the operator and cannot
hit this. The same crash was reported against other libraries, for
example [swift-institute/Issues
#140](swift-institute/Issues#140) and
[urbanairship/ios-library
#467](urbanairship/ios-library#467).

This comparison has been in the SDK unchanged since 2022 and is the only
`<=` or `>=` between two Dates in the codebase.

## Why this is equivalent

Apple's new operator is implemented as
`lhs.timeIntervalSinceReferenceDate <=
rhs.timeIntervalSinceReferenceDate` ([Date.swift at the shipped
commit](https://github.com/swiftlang/swift-foundation/blob/0babce77c/Sources/FoundationEssentials/Date.swift),
line 202), and `timeIntervalSinceReferenceDate` is a direct read of the
stored Double. The pre-27.2 behavior was the standard library's
Comparable default, `!(rhs < lhs)`, over the same Double. The two differ
only for NaN, which no date in this SDK can be. This change matches
both.

## Testing

Done:
- `swift build` passes.
- `FeatureFlagSpec` on an iPhone 16 simulator (iOS 18.6): 17 tests, 0
failures, including `testShouldCreateDebugEvents`.
- SwiftLint clean.

In progress, will be posted here when complete:
- Reproduce the crash on an iOS 27.2 beta 2 (24B5089g) simulator with
the SDK built by Xcode 27.2 on `v11` without this change, then show it
passes with this change.
- `nm -m` on the built framework: the weak import of
`$s10Foundation4DateV2leoiySbAC_ACtFZ` is present before this change and
absent after it.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Overview**
> Fixes crashes on some **iOS 27.2 beta** devices when apps are built
with **Xcode 27.2**: `FeatureFlag.shouldCreateDebugEvents` no longer
calls Foundation’s back-deployed `Date <=` operator (which can resolve
to a null symbol and jump to `0x0` on certain 27.2 betas).
> 
> The method now compares `timeIntervalSinceReferenceDate` on the two
dates instead, preserving the same debug-event gating logic used from
`stringVariation` / event reporting. Inline comments document that this
is a platform/SDK linkage workaround, not a behavioral SDK change.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0ce78ac. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
🤖 I have created a release *beep* *boop*
---


##
[11.8.1](11.8.0...11.8.1)
(2026-11-23)


### Bug Fixes

* avoid Foundation's back-deployed Date comparison operators
([#575](#575))
([1e18137](1e18137))
* Record no variation and a WRONG_TYPE reason in events when a typed
evaluation has the wrong type
([#554](#554))
([d76e12e](d76e12e))
* Start the primary environment first, then secondary environments by
name ([#572](#572))
([30856c4](30856c4))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Overview**
> **Release 11.8.1** bumps the SDK version from `11.8.0` to `11.8.1`
across packaging and metadata (Release Please manifest,
`LaunchDarkly.podspec`, Xcode `MARKETING_VERSION` / dylib versions,
`ReportingConsts.sdkVersion`, and README SPM pin).
> 
> The changelog for this patch documents three **bug fixes** shipped in
the release:
> 
> **Debug events on newer Apple SDKs:**
`FeatureFlag.shouldCreateDebugEvents` no longer compares `Date` values
with `<=` / `>=`. It uses `timeIntervalSinceReferenceDate` instead,
avoiding crashes when Foundation’s back-deployed Date operators are
missing on some iOS 27.2 beta builds.
> 
> **Typed evaluation analytics:** When a flag value cannot be decoded to
the requested type, evaluations now emit **`WRONG_TYPE`** with **no
variation index** in both the returned detail and recorded flag events
(via `withEvaluationResult(variation: nil, …)`).
> 
> **Multi-environment startup order:** `LDClient.start` initializes the
**primary** environment first, then **secondary** environments in
**stable alphabetical order by name**, so client creation and plugin
registration are deterministic across launches.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4ad6acb. 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: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: LaunchDarklyReleaseBot <LaunchDarklyReleaseBot@launchdarkly.com>
abelonogov-ld and others added 4 commits November 24, 2026 13:05
Co-authored-by: Cursor <cursoragent@cursor.com>
…pend on

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

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 Bugbot comment from a previous run.

}
config.eventFlushInterval = 5
expect(DirectEventProcessor.flushInterval(config: config)) == 5
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Flush interval unit test never runs

Low Severity

testFlushIntervalFallsBackToTheDefaultWhereNotAPositiveFiniteNumber is never called from spec(), and this project uses Quick 4, which does not discover test* methods on a QuickSpec. Unlike testRecordFlagEvaluationEvents, which spec() invokes, this method never executes, so a regression in DirectEventProcessor.flushInterval would not be caught here.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ed7f671. 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.

Risk: high. Cursor Bugbot completed unsuccessfully with unresolved findings, so this run is not approved. SDK Approval Policy rule 2 (allowed PR authors) and the low-risk approval threshold also withhold approval; 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

At .immediate each environment's identify event is written to disk inside internalIdentify, so holding instancesQueue across it kept the backgrounding observer on the main thread waiting behind those writes. Copy the clients under the barrier and identify each outside it. internalIdentify now also runs on internalSetOnlineQueue, so that a setOnline or close on the same client still lands wholly before or after it, as the barrier ensured.

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 Bugbot comment from a previous run.


LDClient.instancesQueue.sync(flags: .barrier) {
LDClient.instances?.forEach { _, instance in
dispatch.enter()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Identify races with client close

Medium Severity

Copying clients off instancesQueue lets identify and close run on the same client at once. internalSetOnlineQueue only covers internalSetOnline(false), not flushAtClose, so refuseRecordings can already be set before identify writes. The identify event is then dropped, and a new flag synchronizer can still be taken online while close is flushing.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 98cfbf7. 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.

Risk: high. SDK approval policy rule 2 blocks auto-approval because the PR author is not on the allowed-approver list, and Cursor Bugbot completed unsuccessfully on this head. 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

A delivery marked a loss reported as soon as it answered any waiter, including one that had given up at its deadline and one that tells nobody, the backgrounding delivery. The next flush then reported success after events were lost for good. Every waiter on the delivery is still told, but the loss is marked heard only where one passed the answer on, so a flush that timed out or a backgrounding leaves it for the next caller. The backgrounding log no longer says that refused events remain on disk.

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

Giving up on the disk takes the log's events back into memory and cuts the log to its header. At close that leaves
them to the closing delivery alone, which posts nothing offline and is cut short when the process ends, while in the
log they were recovered at the next launch.

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 Bugbot comment from a previous run.

self.markEventsLostHeard(upTo: lossMark)
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Queued delivery can report an already-heard loss

Medium Severity

runDelivery snapshots an unheard loss, starts the next delivery, then marks that loss heard only after waiters run on a global queue. A delivery already queued behind it can finish in that window, see the same mark, and report the earlier loss as its own. A later flush can then get false for events it did not drop, which breaks the contract that an answer is only about the batch that caller’s delivery took.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b3347e2. Configure here.

abelonogov-ld and others added 2 commits November 24, 2026 20:15
A failed write leaves the store holding its log for the next close to move into a batch, and closing the client skipped
the store once it had stopped persisting. The log stayed open in this process, so a client started in its place could
not recover it, and its events waited for the next launch.

Co-authored-by: Cursor <cursoragent@cursor.com>
A delivery looked at its loss, started the next delivery, and marked the loss heard only once its callers' completions
had run. A next delivery with nothing to send could end first and tell the same loss again. A delivery now claims the
loss before the next starts, as Android does, and gives it back for the next caller where none of its callers heard it.
Each waiter takes the outcome where the delivery ends, which settles whether it heard, and passes it on elsewhere.

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 1 potential issue.

There are 11 total unresolved issues (including 10 from previous reviews).

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 8043396. Configure here.

reportedLostEvents = mark
return true
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Offline flush swallows owed event loss

Medium Severity

claimEventsLost returns an owed loss even when the delivery aborted offline with lossMark 0. Waiters of that abort still count as having heard it, so lossOwed is cleared. A later successful flush then reports success, and the application never learns that events were lost after a timeout or a backgrounding that told nobody.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 8043396. 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants