Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
05b5628
feat(events): add flushAndWait on Apple (tier 2)
abelonogov-ld Sep 19, 2026
5420c2c
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Sep 24, 2026
a4a1bf1
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Sep 25, 2026
41c02e1
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Sep 25, 2026
5842339
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Sep 25, 2026
c0cabc2
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Sep 25, 2026
92f17c9
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Sep 25, 2026
2f8e528
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Sep 28, 2026
86277e6
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Sep 29, 2026
7d70ae6
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Sep 29, 2026
fd1381c
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Sep 29, 2026
dc9d1e6
fix(events): answer a bounded flush about the delivery already in flight
abelonogov-ld Oct 1, 2026
6c3b8f9
shorten comments
abelonogov-ld Oct 1, 2026
57f04c3
fix(events): report a closed client and a refused in-flight delivery …
abelonogov-ld Oct 1, 2026
47700b3
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Oct 2, 2026
f11a86c
refactor(events): Name the queued delivery a pending flush and move f…
abelonogov-ld Oct 7, 2026
f14f1de
fix(events): Deliver every environment against one shared flush budget
abelonogov-ld Oct 8, 2026
3224c62
fix(events): Keep draining while a delivery is in flight
abelonogov-ld Oct 8, 2026
07f80c6
feat(events): Report a flush outcome without blocking the caller
abelonogov-ld Oct 8, 2026
63af706
test(events): Drive the background assertion from a test, and log a r…
abelonogov-ld Oct 8, 2026
3647c5e
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Oct 8, 2026
d5215f5
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Oct 9, 2026
f6cd58c
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Oct 9, 2026
a30c21e
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Oct 12, 2026
62dcebd
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Oct 12, 2026
17b141c
Run the process assertion specs only where the platform has assertions
abelonogov-ld Oct 12, 2026
e9399ab
Merge branch 'andrey/event-durability-tier1-buffer' into andrey/event…
abelonogov-ld Oct 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions LaunchDarkly.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

11 changes: 10 additions & 1 deletion LaunchDarkly/GeneratedCode/mocks.generated.swift
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,15 @@ final class EventReportingMock: EventReporting {
flushReceivedCompletion = completion
try! flushCallback?()
}

var flushReportingOutcomeCallCount = 0
var flushReportingOutcomeCallback: (() throws -> Void)?
var flushReportingOutcomeReceivedCompletion: (FlushOutcomeClosure)?
func flushReportingOutcome(completion: @escaping FlushOutcomeClosure) {
flushReportingOutcomeCallCount += 1
flushReportingOutcomeReceivedCompletion = completion
try! flushReportingOutcomeCallback?()
}
}

// MARK: - FeatureFlagCachingMock
Expand Down Expand Up @@ -437,7 +446,7 @@ final class ThrottlingMock: Throttling {

var runThrottledCallCount = 0
var runThrottledCallback: (() throws -> Void)?
var runThrottledReceivedRunClosure: RunClosure?
var runThrottledReceivedRunClosure: (RunClosure)?
func runThrottled(_ runClosure: @escaping RunClosure) {
runThrottledCallCount += 1
runThrottledReceivedRunClosure = runClosure
Expand Down
54 changes: 34 additions & 20 deletions LaunchDarkly/LaunchDarkly/LDClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ public class LDClient {

// MARK: - State Controls and Indicators

private static var instances: [String: LDClient]?
private static let instancesQueue = DispatchQueue(label: "com.launchdarkly.LDClient.instancesQueue")
static var instances: [String: LDClient]?
static let instancesQueue = DispatchQueue(label: "com.launchdarkly.LDClient.instancesQueue")

// If the SDK is provided a timeout value that exceeds this value, a warning will be logged.
private static let longTimeoutInterval: TimeInterval = 15
static let longTimeoutInterval: TimeInterval = 15

/**
Reports the online/offline state of the LDClient.
Expand Down Expand Up @@ -263,6 +263,23 @@ public class LDClient {

@objc private func didEnterBackground() {
os_log("%s", log: config.logger, type: .debug, typeName(and: #function))
// A backgrounded process is suspended once idle, so deliver inside an activity assertion. Only where suspension
// is real: macOS posts this notification whenever the application loses focus, and never suspends it for that.
#if os(iOS) || os(tvOS)
backgroundDelivery.run { [weak self] finished in
guard let self = self
else {
finished()
return
}
self.eventReporter.flushReportingOutcome { delivered in
if !delivered {
os_log("%s events did not reach LaunchDarkly before suspension", log: self.config.logger, type: .debug, self.typeName(and: #function))
}
finished()
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Do we need to put any rate limiting in place here? Could this pathway allow an SDK to make requests more rapidly than it did previously in such a way that could lead to more load on the servers?

@tanderson-ld tanderson-ld Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Matching Android is probably sufficient.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Background flush skips in-flight delivery

High Severity

Backgrounding calls flushReportingOutcome, which does not join a delivery that has already taken the store. If events are on the wire or in the retry delay, the store is empty, the new flush answers true at once, and finished() drops the assertion. The process can then suspend and kill that in-flight request. Those events are already gone from the store, so they are lost, and the “did not reach LaunchDarkly” log does not fire. That hole is widest during the retry window this change otherwise went out of its way to keep draining.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit f6cd58c. Configure here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Tier 3 (#538), which sits directly on this branch, narrows that without relying on the disk. A delivery no longer takes events out of the store: claimDeliverableBatches only marks payload IDs in batchesInFlight, and remove runs solely once LaunchDarkly has accepted or permanently refused the batch. With persistence off that batch sits in inMemoryBatches until then, so a suspension that is later resumed redelivers it. Neither branch ships on its own.

#endif
Thread.performOnMain {
runMode = .background
}
Expand All @@ -275,6 +292,9 @@ public class LDClient {
}
}

/// One assertion per client, however many times the application is backgrounded while a delivery is running.
private let backgroundDelivery: BackgroundActivity

let config: LDConfig
/// Identifies this client's environment to a hook, without handing it the mobile key that identifies the
/// environment to LaunchDarkly. Hashed once here rather than per evaluation, because a deduping hook asks for it on
Expand Down Expand Up @@ -786,23 +806,6 @@ public class LDClient {
plugin.register(client: self, metadata: environmentMetadata)
}

/**
Tells the SDK to immediately send any currently queued events to LaunchDarkly.

There should not normally be a need to call this function. While online, the LDClient automatically reports events
on an interval defined by `LDConfig.eventFlushInterval`. Note that this function does not block until events are
sent, it only triggers a background task to send events immediately.
*/
public func flush() {
LDClient.instancesQueue.sync(flags: .barrier) {
LDClient.instances?.forEach { $1.internalFlush() }
}
}

private func internalFlush() {
eventReporter.flush(completion: nil)
}

/// Static, and over a logger rather than a client, so that the event reporter can be given it while the client
/// that owns the reporter is still being built.
private static func logEventSyncComplete(_ result: SynchronizingError?, _ logger: OSLog) {
Expand Down Expand Up @@ -1027,6 +1030,7 @@ public class LDClient {
throttler = self.serviceFactory.makeThrottler(environmentReporter: environmentReporter)

config = configuration
backgroundDelivery = BackgroundActivity(reason: "LaunchDarkly event delivery", logger: configuration.logger)
context = startContext ?? LDContext()

if config.autoEnvAttributes {
Expand Down Expand Up @@ -1089,6 +1093,16 @@ public class LDClient {

extension LDClient: TypeIdentifying { }

private extension LDClient {
func onEventSyncComplete(result: SynchronizingError?) {
if let synchronizingError = result {
os_log("%s result: %s", log: config.logger, type: .debug, typeName(and: #function), String(describing: synchronizingError))
} else {
os_log("%s result: success", log: config.logger, type: .debug, typeName(and: #function))
}
}
}

#if DEBUG
extension LDClient {
func setRunMode(_ runMode: LDClientRunMode) {
Expand Down
156 changes: 156 additions & 0 deletions LaunchDarkly/LaunchDarkly/LDClientFlush.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import Foundation
import OSLog

// MARK: - Flush
extension LDClient {
/**
Tells the SDK to immediately send any currently queued events to LaunchDarkly.

There should not normally be a need to call this function. While online, the LDClient automatically reports events
on an interval defined by `LDConfig.eventFlushInterval`. Note that this function does not block until events are
sent, it only triggers a background task to send events immediately.

Because it does not wait, it cannot report how the delivery went. Use `flush(completion:)` where that matters
but blocking does not suit, or `flushAndWait` where blocking is acceptable.
*/
public func flush() {
LDClient.instancesQueue.sync(flags: .barrier) {
LDClient.instances?.forEach { $1.internalFlush() }
}
}

/**
Sends any currently queued events to LaunchDarkly and reports how the delivery went.

Like `flushAndWait`, but without blocking: the completion runs once every environment has answered. There is no
timeout, because a delivery always ends, by its own request timeouts if nothing else. This is the one to reach
for from a Swift concurrency task, where blocking is not safe.

- parameter completion: Given `true` if LaunchDarkly accepted the events, or there were none to send, and
`false` if the client is offline or closed, or any of the events were lost. See `flushAndWait` for what being
lost covers. Runs once, on a background queue that is neither the caller's thread nor the one recorded events
wait on, so it is free to record or flush again.
*/
public func flush(completion: @escaping (Bool) -> Void) {
let clients = instancesIncludingThisClient()
guard !clients.isEmpty
else {
os_log("%s called on a closed client", log: config.logger, type: .debug, self.typeName(and: #function))
completion(false)
return
}

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 completion runs on caller

Medium Severity

flush(completion:) documents that the completion always runs on a background queue, not the caller’s thread, so it is safe to record or flush again. A closed client and NullEventReporter (sendEvents false) invoke that completion synchronously on the caller instead, which can deadlock a caller that hops back onto its current queue.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d5215f5. Configure here.


let lock = UnfairLock()
/// Only to be used while holding `lock`: each environment answers from whichever thread its delivery ended on.
var delivered = true
var outstanding = clients.count

for client in clients {
client.eventReporter.flushReportingOutcome { result in
lock.lock()
delivered = delivered && result
outstanding -= 1
// Nil until the last environment answers, so the completion runs once. A reporter answering twice
// takes the count past zero rather than back to it, which cannot match again.
let outcome = outstanding == 0 ? delivered : nil
lock.unlock()

if let outcome {
completion(outcome)
}
}
}
}

/// Every environment's client, or none where this client is no longer one of them.
private func instancesIncludingThisClient() -> [LDClient] {
let clients = LDClient.instancesQueue.sync { LDClient.instances.map { Array($0.values) } } ?? []
return clients.contains { $0 === self } ? clients : []
}

/**
Sends any currently queued events to LaunchDarkly and waits up to `timeout` seconds for the result.

The timeout bounds the wait, not the delivery: an in-flight request is left to finish. Multiple environments
deliver at the same time and share the one budget, so the call takes no longer for several of them than for one.

A delivery that definitively failed is reported as a failure. Some other LaunchDarkly SDKs report that as a
success, on the grounds that the attempt is over, so an expectation carried from another platform may not hold
here.

This blocks the thread it is called on until the answer is in or the budget runs out. Where the answer is not
needed, `flush` queues the same delivery and returns at once; where it is needed but blocking does not suit,
`flush(completion:)` reports it without waiting.

Do not call this from a Swift concurrency task. Blocking there holds a thread of the cooperative pool, which
cannot grow to replace it, and enough of them will stall every other task in the process. Use
`flush(completion:)` from a task, wrapped in a continuation where you want to await it.

This is not a crash-time mechanism. It is safe to call from the main thread, but keep the budget well below
15 seconds there.

- parameter timeout: How long to wait, in seconds. Zero or less does not wait, and so reports `false`. There is
no upper limit: a delivery always ends, by its own request timeouts if nothing else, so a very long timeout
waits for that.
- returns: `true` if LaunchDarkly accepted the events, or there were none to send. `false` if the timeout expired
first, the client is offline or closed, or any of the events were lost: refused by LaunchDarkly, still failing
after one retry, or unable to be serialized. Lost events are not kept for a later flush, so calling this again
does not resend them. A refusal also stops event delivery until the client is next set online, and until then
this returns `false` even with nothing to send. A `false` because the timeout expired does not mean the events
were not sent: the delivery is left running, and may still arrive.
*/
@discardableResult
public func flushAndWait(timeout: TimeInterval) -> Bool {
if timeout > LDClient.longTimeoutInterval {
os_log("%s LDClient.flushAndWait was called with a timeout greater than %f seconds. We recommend a timeout of less than %f seconds.", log: config.logger, type: .info, self.typeName(and: #function), LDClient.longTimeoutInterval, LDClient.longTimeoutInterval)
}

let clients = instancesIncludingThisClient()
guard !clients.isEmpty
else {
// Closed, or replaced by a later start, or caught while a start is still filling the instances in. None of
// them can deliver this client's events, and saying otherwise would tell the caller they were safe.
os_log("%s called on a closed client", log: config.logger, type: .debug, self.typeName(and: #function))
return false
}
let deadline = DispatchTime.now() + max(0, timeout)
// Counts answers rather than tracking each delivery, so that a reporter answering twice costs a spare permit
// no one reads. A DispatchGroup would fit as well, but its `leave` traps without a matching `enter`, which
// turns a broken reporter into a crash in the application.
let answered = DispatchSemaphore(value: 0)
let lock = UnfairLock()
/// Only to be used while holding `lock`: each environment answers from whichever thread its delivery ended on.
var delivered = true

// Every environment is started before any of them is waited on. Each has its own event reporter, so waiting on
// one before starting the next would spend the caller's budget on deliveries that could have been running all
// along, and leave the last environment with none of it.
for client in clients {
client.eventReporter.flushReportingOutcome { result in
lock.lock()
delivered = delivered && result
lock.unlock()
answered.signal()
}
}

// Every wait is against the one deadline rather than a fresh copy of it, so the timeout the caller asked for
// is the time this call can take however many environments there are. A delivery still running when the wait
// gives up is left to finish rather than canceled: its events are already in flight, so abandoning it would
// only make losing them certain.
for _ in clients {
guard answered.wait(timeout: deadline) == .success
else { return false }
}

// The waits count answers rather than environments, so a reporter answering twice can end them while another
// environment's answer is still being written.
lock.lock()
defer { lock.unlock() }
return delivered
}

func internalFlush() {
eventReporter.flush(completion: nil)
}
}
7 changes: 6 additions & 1 deletion LaunchDarkly/LaunchDarkly/Networking/DarklyService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,12 @@ final class DarklyService: DarklyServiceProvider {
// MARK: Publish Events

func publishEventData(_ eventData: Data, _ payloadId: String, completion: ServiceCompletionHandler?) {
guard hasMobileKey(#function) else { return }
guard hasMobileKey(#function)
else {
// Answered rather than dropped: the reporter holds every later delivery until this one answers.
completion?((nil, nil, URLError(.userAuthenticationRequired), nil))
return
}
let url = config.eventsUrl.appendingPathComponent(EventRequestPath.bulk)
let headers = [HTTPHeaders.HeaderKey.eventPayloadIDHeader: payloadId].merging(httpHeaders.eventRequestHeaders) { $1 }
doPublish(url: url, headers: headers, body: eventData, completion: completion)
Expand Down
47 changes: 47 additions & 0 deletions LaunchDarkly/LaunchDarkly/ObjectiveC/ObjcLDClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -534,11 +534,58 @@ public final class ObjcLDClient: NSObject {
There should not normally be a need to call this function. While online, the LDClient automatically reports events
on an interval defined by `LDConfig.eventFlushInterval`. Note that this function does not block until events are
sent, it only triggers a background task to send events immediately.

Because it does not wait, it cannot report how the delivery went. Use `flushWithCompletion:` where that matters
but blocking does not suit, or `flushAndWait` where blocking is acceptable.
*/
@objc public func flush() {
ldClient.flush()
}

/**
Sends any currently queued events to LaunchDarkly and reports how the delivery went.

Like `flushAndWait`, but without blocking: the completion runs once every environment has answered. There is no
timeout, because a delivery always ends, by its own request timeouts if nothing else.

- parameter completion: Given `YES` if LaunchDarkly accepted the events, or there were none to send, and `NO` if
the client is offline or closed, or any of the events were lost. See `flushAndWait` for what being lost
covers. Runs once, on a background queue that is not the caller's thread.
*/
@objc public func flush(completion: @escaping (Bool) -> Void) {
ldClient.flush(completion: completion)
}

/**
Sends any currently queued events to LaunchDarkly and waits up to `timeout` seconds for the result.

The timeout bounds the wait, not the delivery: an in-flight request is left to finish. Multiple environments
deliver at the same time and share the one budget, so the call takes no longer for several of them than for one.

A delivery that definitively failed is reported as a failure. Some other LaunchDarkly SDKs report that as a
success, on the grounds that the attempt is over, so an expectation carried from another platform may not hold
here.

This blocks the thread it is called on until the answer is in or the budget runs out, so where the answer is
not needed, `flush` queues the same delivery and returns at once.

This is not a crash-time mechanism. It is safe to call from the main thread, but keep the budget well below
15 seconds there.

- parameter timeout: How long to wait, in seconds. Zero or less does not wait, and so reports `NO`. There is
no upper limit: a delivery always ends, by its own request timeouts if nothing else, so a very long timeout
waits for that.
- returns: `YES` if LaunchDarkly accepted the events, or there were none to send. `NO` if the timeout expired
first, the client is offline or closed, or any of the events were lost: refused by LaunchDarkly, still failing
after one retry, or unable to be serialized. Lost events are not kept for a later flush, so calling this again
does not resend them. A refusal also stops event delivery until the client is next set online, and until then
this returns `NO` even with nothing to send. A `NO` because the timeout expired does not mean the events were
not sent: the delivery is left running, and may still arrive.
*/
@objc public func flushAndWait(timeout: TimeInterval) -> Bool {
ldClient.flushAndWait(timeout: timeout)
}

/**
Starts the LDClient using the passed in `config` & `context`. Call this before requesting feature flag values. The LDClient will not go online until you call this method.
Starting the LDClient means setting the `config` & `context`, setting the client online if `config.startOnline` is true (the default setting), and starting event recording. The client app must start the LDClient before it will report feature flag values. If a client does not call `start`, no methods will work.
Expand Down
Loading
Loading