Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,13 @@ static final class Pacing {
*/
private long claimedLostEvents;

/**
* Whether a loss was claimed for a caller who stopped waiting before the answer reporting it came, so
* that the next delivery a caller waits on reports it instead. Set from that caller's thread, or the
* thread that answers, and taken on the scheduler thread.
*/
private final AtomicBoolean lossOwed = new AtomicBoolean(false);

/**
* How many refusals of the payload in a row drop a batch: a 400, 413, 415 or 422, in any mix
* ({@link LDUtil#isEventPayloadRefused}). Each says the service will not take this body, which posting
Expand Down Expand Up @@ -401,11 +408,13 @@ private void reportDiscarded(int events) {
* Runs on the scheduler thread.
*
* @param mark the loss count as of the close of that delivery's batch
* @return true if a loss at or before the mark belonged to no earlier delivery a caller waited on
* @return true if a loss at or before the mark belonged to no earlier delivery a caller waited on, or
* one was claimed for a caller who stopped waiting before it heard of it
*/
private boolean claimEventsLost(long mark) {
boolean owed = lossOwed.getAndSet(false);
if (mark <= claimedLostEvents) {
return false;
return owed;
}
claimedLostEvents = mark;
return true;
Expand Down Expand Up @@ -510,7 +519,7 @@ private Future<Boolean> queueDelivery(boolean answersACaller, boolean bypassBack
* on had passed them, because a delivery that finds nothing to send is not evidence that everything
* recorded arrived.
*/
private void runDelivery(LDAwaitFuture<Boolean> result, EventDeliveryScheduler.Joined joined) {
private void runDelivery(EventDeliveryScheduler.RequestedAnswer result, EventDeliveryScheduler.Joined joined) {
DeliveryOutcome outcome;
try {
outcome = commitAndDeliverReportingOutcome(deliveryScheduler.requestedRun(joined.bypassesBackoff));
Expand All @@ -522,6 +531,12 @@ private void runDelivery(LDAwaitFuture<Boolean> result, EventDeliveryScheduler.J
}
// Claimed before the next delivery can run, however long this one's retry takes to answer.
boolean lostEvents = joined.answersACaller && claimEventsLost(outcome.lostEventsMark);
if (lostEvents) {
// Claimed for this delivery's callers, a loss a caller does not stay to hear of is not heard
// of at all unless the next delivery reports it too. Two callers joined to this one may then
// both hear of it, which is the safe direction.
result.lossUnheard = () -> lossOwed.set(true);
}
if (outcome.retry == null) {
answer(result, outcome.delivered, lostEvents);
} else {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.launchdarkly.sdk.android;

import androidx.annotation.NonNull;

import com.launchdarkly.logging.LDLogger;

import java.util.concurrent.Callable;
Expand All @@ -8,6 +10,7 @@
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
* Puts the event processor's deliveries on its scheduler thread, one at a time, and decides when that thread
Expand All @@ -21,7 +24,46 @@
final class EventDeliveryScheduler {
/** A requested delivery, given the future its callers wait on and who joined it by the time it began. */
interface RequestedDelivery {
void run(LDAwaitFuture<Boolean> result, Joined joined);
void run(RequestedAnswer result, Joined joined);
}

/**
* What a requested delivery answers its callers. Where the answer reports events lost for good, a caller
* whose wait times out or is interrupted before it comes leaves the loss for the next caller to hear about.
*/
static final class RequestedAnswer extends LDAwaitFuture<Boolean> {
/** Set by the delivery before it answers, where the answer reports a loss: what leaves it unheard. */
volatile Runnable lossUnheard;

@Override
public Boolean get() throws ExecutionException, InterruptedException {
try {
return super.get();
} catch (InterruptedException e) {
stoppedWaiting();
throw e;
}
}

@Override
public Boolean get(long timeout, @NonNull TimeUnit unit)
throws ExecutionException, TimeoutException, InterruptedException {
try {
return super.get(timeout, unit);
} catch (TimeoutException | InterruptedException e) {
stoppedWaiting();
throw e;
}
}

private void stoppedWaiting() {
addListener(() -> {
Runnable unheard = lossUnheard;
if (unheard != null) {
unheard.run();
}
});
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Timed-out loss missed during retry

High Severity

A timed-out flush still fails to report a claimed loss when that delivery is waiting on a retry. lossUnheard is assigned at pass end, but stoppedWaiting only runs it when the future later completes. The scheduler is free during the retry delay, so the next flushAndWait can claim nothing, miss lossOwed, and return true after events were already lost. That is the durability miss this change set out to close.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c9022ad. Configure here.

}

/** Who joined a requested delivery by the time it began. */
Expand Down Expand Up @@ -79,7 +121,7 @@ private Joined(boolean answersACaller, boolean bypassesBackoff) {
* on instead of queuing another. Null while nothing is queued, and cleared again as the queued
* delivery begins, which is the point past which it can no longer speak for what is recorded.
*/
private LDAwaitFuture<Boolean> pendingFlush;
private RequestedAnswer pendingFlush;

/**
* Whether a caller who is there to hear the outcome is waiting on {@link #pendingFlush}, as opposed to only
Expand Down Expand Up @@ -154,14 +196,14 @@ private EventDeliveryRun newRun(boolean throughTheBackoff, boolean paced) {
* @return what the delivery answers, or false at once if it is shutting down and nothing will be sent
*/
Future<Boolean> queue(boolean answersACaller, boolean bypassBackoff, RequestedDelivery delivery) {
LDAwaitFuture<Boolean> result;
RequestedAnswer result;
synchronized (flushLock) {
if (pendingFlush != null) {
pendingFlushAnswersACaller |= answersACaller;
pendingFlushBypassesBackoff |= bypassBackoff;
return pendingFlush;
}
LDAwaitFuture<Boolean> queued = new LDAwaitFuture<>();
RequestedAnswer queued = new RequestedAnswer();
if (submit(() -> delivery.run(queued, begin(queued))) == null) {
return new LDSuccessFuture<>(false);
}
Expand All @@ -182,7 +224,7 @@ Future<Boolean> queue(boolean answersACaller, boolean bypassBackoff, RequestedDe
*
* @return who joined it
*/
private Joined begin(LDAwaitFuture<Boolean> result) {
private Joined begin(RequestedAnswer result) {
synchronized (flushLock) {
if (pendingFlush != result) {
return Joined.NOBODY;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,38 @@ public void aLossADeliveryNobodyWaitedOnPassedIsToldToTheNextFlush() throws Exce
}
}

@Test
public void aLossClaimedForAFlushThatStoppedWaitingIsToldToTheNextFlush() throws Exception {
Semaphore letFirstResponseFinish = new Semaphore(0);
try (HttpServer server = HttpServer.start(Handlers.sequential(
Handlers.all(Handlers.waitFor(letFirstResponseFinish), Handlers.status(202)),
Handlers.status(202)))) {
EventProcessor eventProcessor = makeEventProcessor(server, DEFAULT_CAPACITY);
try {
eventProcessor.recordCustomEvent(CONTEXT, "poison", LDValue.ofNull(), Double.NaN);
eventProcessor.recordCustomEvent(CONTEXT, "kept", LDValue.ofNull(), null);

// The delivery loses the poison event, and answers only once its caller has stopped waiting,
// as a flushAndWait that times out does.
Future<Boolean> first = eventProcessor.flushAsync();
server.getRecorder().requireRequest(5, TimeUnit.SECONDS);
try {
first.get(100, TimeUnit.MILLISECONDS);
fail("expected the wait to time out");
} catch (TimeoutException expected) {
// The caller gives up here, before it hears of the loss.
}
letFirstResponseFinish.release();

assertFalse(awaitFlush(eventProcessor, 5, TimeUnit.SECONDS));
assertTrue(awaitFlush(eventProcessor, 5, TimeUnit.SECONDS));
} finally {
letFirstResponseFinish.release(Integer.MAX_VALUE);
eventProcessor.close();
}
}
}

@Test
public void aFailedDeliveryIsRetriedOnceUnderTheSamePayloadId() throws Exception {
try (HttpServer server = HttpServer.start(Handlers.sequential(Handlers.status(503),
Expand Down