From 975d91686d6190076b067c93a4d3db37af8e48f1 Mon Sep 17 00:00:00 2001 From: Andrey Belonogov Date: Tue, 24 Nov 2026 13:22:05 -0800 Subject: [PATCH] fix(events): end an ordinary failure's wait on going online again Co-authored-by: Cursor --- .../sdk/android/DeliveryRetryState.java | 53 +++++++- .../sdk/android/DirectEventProcessor.java | 27 +++- .../sdk/android/LDClientInterface.java | 11 ++ .../sdk/android/DeliveryRetryStateTest.java | 46 +++++++ .../sdk/android/DirectEventProcessorTest.java | 128 +++++++++++++++++- 5 files changed, 255 insertions(+), 10 deletions(-) diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DeliveryRetryState.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DeliveryRetryState.java index fdb31706..83e10832 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DeliveryRetryState.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DeliveryRetryState.java @@ -7,12 +7,18 @@ * When event delivery may post again after a failure, following the SDK Retry Behavior specification as * event durability ยง9 binds it. *

- * A failure never stops delivery, it only makes the next post wait. An ordinary one, such as a 503 or no - * network, waits from a second up to the flush interval, so it is never later than the schedule already - * would be. A refusal that is unlikely to pass soon, such as a 401, waits about eight and a half minutes, - * doubling up to an hour, rather than deleting the batch: a valid key is sometimes refused for minutes - * during an incident, and every event the fleet recorded meanwhile would be lost. A {@code Retry-After} - * sets the wait instead. One accepted delivery puts everything back. + * A failure never stops delivery, it only makes the next post wait. There are two kinds of wait: + *

+ * One accepted delivery puts everything back. *

* One per event processor, so each environment backs off on its own. Held only in memory, so a new run of * the application posts at once. @@ -40,6 +46,10 @@ final class DeliveryRetryState { private long maxDelayMillis; private boolean waiting; private long nextAttemptNanos; + // A refusal since the last accepted delivery, which keeps the extended ceiling. + private boolean refused; + // The wait is a Retry-After's. A refusal's is marked by refused. + private boolean serverDirectedWait; /** * @param flushIntervalMillis the normal ceiling; never below the initial delay, so a short interval does @@ -69,6 +79,32 @@ synchronized void recordSuccess() { attempts = 0; maxDelayMillis = normalCeilingMillis; waiting = false; + refused = false; + serverDirectedWait = false; + } + + /** + * Going online again: + *

+ * The attempt count stays either way, as only an accepted delivery puts it back. + * + * @return true when a post has failed since the last accepted one and no wait holds the next back any + * more, so a delivery may go now rather than at the next flush interval + */ + synchronized boolean endOrdinaryWait() { + if (attempts == 0) { + return false; + } + if (remainingWaitNanos() > 0 && (refused || serverDirectedWait)) { + return false; + } + waiting = false; + return true; } /** @@ -82,9 +118,11 @@ synchronized long recordFailure(boolean unexpected, long retryAfterMillis) { if (unexpected) { attempts = Math.max(attempts + 1, ATTEMPTS_AFTER_UNEXPECTED); maxDelayMillis = extendedCeilingMillis; + refused = true; } else { attempts++; } + serverDirectedWait = retryAfterMillis >= 0; long waitMillis; if (retryAfterMillis >= 0) { // Every instance hears the same value at the same moment, so it is jittered to keep them from @@ -106,7 +144,7 @@ synchronized long recordFailure(boolean unexpected, long retryAfterMillis) { * not a step of the backoff. It leaves the attempt count and the ceiling as they were, so a caller * flushing through a refusal several times does not push flush, the periodic delivery and the retry out * to the hour. A {@code Retry-After} can still make the wait longer, never shorter. Once the wait has run - * out it is an ordinary failure. + * out it is the next step of the backoff. * * @param unexpected as {@link #recordFailure} * @param retryAfterMillis as {@link #recordFailure} @@ -124,6 +162,7 @@ synchronized void recordFailureDuringWait(boolean unexpected, long retryAfterMil long asked = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(waitMillis); if (asked - nextAttemptNanos > 0) { nextAttemptNanos = asked; + serverDirectedWait = true; } } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java index 7126c0f9..530e4122 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java @@ -151,6 +151,13 @@ static final class Pacing { */ private volatile boolean launchGateOpen; + /** + * Whether going online again ended an ordinary failure's wait while the gate was still closed, which owes + * the delivery it would have submitted to the gate opening. Ending the wait is not undone, and nothing + * else would deliver before the next flush interval. Guarded by {@link #stateLock}. + */ + private boolean deliveryOwedAtGate; + /** Set once, under {@link #stateLock}, when the SDK first goes online; the gate counts from then. */ private volatile boolean wentOnline; private volatile long wentOnlineNanos; @@ -436,6 +443,16 @@ public void setOffline(boolean offline) { return; } updateScheduledTasks(inBackground.get(), offline); + // Going online again keeps to the flush interval, with one exception: when the last post had an + // ordinary failure, such as no network, its wait ends and a delivery goes now. A wait the service + // set, with a Retry-After or a refusal, stands. + if (!offline && !closed.get() && retryState.endOrdinaryWait()) { + if (launchGateOpen) { + deliveryScheduler.submit(this::deliverPayload); + } else { + deliveryOwedAtGate = true; + } + } } deliveryScheduler.wakePacedDelivery(); } @@ -1080,8 +1097,14 @@ private void updateScheduledTasks(boolean inBackground, boolean offline) { // Events a previous run left on disk have already waited out a whole process, so they do not // wait out an interval as well, only the launch gate. An application that dies within one interval // of every start would otherwise never deliver them. - if (!stopped && !offline && launchGateOpen && hasEventsFromPreviousRun.compareAndSet(true, false)) { - deliveryScheduler.submit(this::deliverPayload); + if (!stopped && !offline && launchGateOpen) { + // One delivery covers both: it sends what a previous run left first. Offline, going online again + // asks anew. + boolean previousRun = hasEventsFromPreviousRun.compareAndSet(true, false); + if (previousRun || deliveryOwedAtGate) { + deliveryOwedAtGate = false; + deliveryScheduler.submit(this::deliverPayload); + } } diagnostics.setMode(!stopped && !offline && !inBackground, launchGateOpen); } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDClientInterface.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDClientInterface.java index 34304ea3..f108b0d6 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDClientInterface.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDClientInterface.java @@ -59,6 +59,17 @@ public interface LDClientInterface extends Closeable { * Restores network connectivity for the client, if the client was previously in offline mode. * This operation may be throttled if it is called too frequently. *

+ * If a delivery of events failed, going online again: + *

+ *

* Note: The client automatically monitors the device's network connectivity and app foreground * status, so calling setOffline() or setOnline() is normally * unnecessary in most situations. diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DeliveryRetryStateTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DeliveryRetryStateTest.java index 33a838f5..337a4dba 100644 --- a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DeliveryRetryStateTest.java +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DeliveryRetryStateTest.java @@ -1,6 +1,7 @@ package com.launchdarkly.sdk.android; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -117,6 +118,51 @@ public void aFailureDuringAWaitThatHasRunOutIsAnOrdinaryOne() throws Interrupted assertTrue(quick.remainingWaitNanos() > TimeUnit.MILLISECONDS.toNanos(20)); } + @Test + public void goingOnlineEndsAnOrdinaryFailuresWaitButKeepsTheCount() { + assertFalse(state.endOrdinaryWait()); + state.recordFailure(false, -1); + state.recordFailure(false, -1); + + assertTrue(state.endOrdinaryWait()); + assertEquals(0, state.remainingWaitNanos()); + assertEquals(4 * SECOND, state.recordFailure(false, -1)); + } + + @Test + public void goingOnlineKeepsTheServicesWait() { + DeliveryRetryState refused = new DeliveryRetryState(FLUSH_INTERVAL); + refused.recordFailure(true, -1); + assertFalse(refused.endOrdinaryWait()); + assertTrue(refused.remainingWaitNanos() > TimeUnit.SECONDS.toNanos(500)); + + DeliveryRetryState directed = new DeliveryRetryState(FLUSH_INTERVAL); + directed.recordFailure(false, 10 * SECOND); + assertFalse(directed.endOrdinaryWait()); + assertTrue(directed.remainingWaitNanos() > TimeUnit.SECONDS.toNanos(4)); + + DeliveryRetryState lengthened = new DeliveryRetryState(SECOND, FLUSH_INTERVAL, TimeUnit.HOURS.toMillis(1), + new FixedRandom(0)); + lengthened.recordFailure(false, -1); + lengthened.recordFailureDuringWait(false, 10 * SECOND); + assertFalse(lengthened.endOrdinaryWait()); + } + + @Test + public void goingOnlineAfterTheServicesWaitRanOutLetsADeliveryGo() throws InterruptedException { + DeliveryRetryState quick = new DeliveryRetryState(20, 20, 20, new Random()); + quick.recordFailure(true, -1); + Thread.sleep(40); + assertTrue(quick.endOrdinaryWait()); + } + + @Test + public void goingOnlineAfterAnAcceptedDeliveryHasNothingToSend() { + state.recordFailure(false, -1); + state.recordSuccess(); + assertFalse(state.endOrdinaryWait()); + } + @Test public void theWaitRunsOut() throws InterruptedException { DeliveryRetryState quick = new DeliveryRetryState(20, 20, 20, new Random()); diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java index a00ac2c8..0917a16f 100644 --- a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java @@ -3342,6 +3342,115 @@ public void refusedFlushesBypassingTheBackoffDoNotLengthenIt() throws Exception } } + @Test + public void goingOnlineAgainAfterAnOrdinaryFailurePostsAtOnceRatherThanSittingOutTheRestOfItsWait() + throws Exception { + ScheduledExecutorService scheduler = EventUtil.makeEventsTaskExecutor(); + ExecutorService diagnosticExecutor = EventUtil.makeDiagnosticsTaskExecutor(); + diagnosticExecutors.add(diagnosticExecutor); + EventStore store = EventStore.create(eventsDirectory.getRoot(), MOBILE_KEY, DEFAULT_CAPACITY, + persistence() != EventPersistence.DISABLED, logging.logger); + try (HttpServer server = HttpServer.start(Handlers.sequential( + Handlers.status(503), Handlers.status(503), Handlers.status(202)))) { + DirectEventProcessor eventProcessor = makeEventProcessor(new StubEventSender(), server.getUri(), + null, NO_PERIODIC_FLUSH_MILLIS, 60_000, DirectEventProcessor.DEFAULT_CLOSE_BUDGET_MILLIS, + scheduler, diagnosticExecutor, store, DEFAULT_CAPACITY); + try { + eventProcessor.setOffline(false); + eventProcessor.recordCustomEvent(CONTEXT, "held", LDValue.ofNull(), null); + assertFalse(awaitFlush(eventProcessor, 10, TimeUnit.SECONDS)); + server.getRecorder().requireRequest(1, TimeUnit.SECONDS); + server.getRecorder().requireRequest(1, TimeUnit.SECONDS); + // Failures while the network was going, which leave about sixteen seconds to wait. + for (int i = 0; i < 3; i++) { + lastRetryState.recordFailure(false, -1); + } + + eventProcessor.setOffline(true); + eventProcessor.setOffline(false); + + assertTrue(server.getRecorder().requireRequest(2, TimeUnit.SECONDS).getBody() + .contains("\"key\":\"held\"")); + } finally { + eventProcessor.close(); + scheduler.shutdownNow(); + } + } + } + + @Test + public void goingOnlineAgainBeforeTheLaunchGateOpensPostsAsItOpens() throws Exception { + assumePersisting(); + ScheduledExecutorService scheduler = EventUtil.makeEventsTaskExecutor(); + ExecutorService diagnosticExecutor = EventUtil.makeDiagnosticsTaskExecutor(); + diagnosticExecutors.add(diagnosticExecutor); + EventStore store = EventStore.create(eventsDirectory.newFolder(), MOBILE_KEY, DEFAULT_CAPACITY, true, + logging.logger); + try (HttpServer server = HttpServer.start(Handlers.sequential( + Handlers.status(503), Handlers.status(503), Handlers.status(202)))) { + DirectEventProcessor eventProcessor = makeEventProcessor(new StubEventSender(), server.getUri(), + null, NO_PERIODIC_FLUSH_MILLIS, 60_000, DirectEventProcessor.DEFAULT_CLOSE_BUDGET_MILLIS, + scheduler, diagnosticExecutor, store, DEFAULT_CAPACITY, false, + new DirectEventProcessor.Pacing(4_000, 0)); + try { + eventProcessor.setOffline(false); + eventProcessor.recordCustomEvent(CONTEXT, "held", LDValue.ofNull(), null); + // A flush does not wait for the gate. + assertFalse(awaitFlush(eventProcessor, 10, TimeUnit.SECONDS)); + server.getRecorder().requireRequest(1, TimeUnit.SECONDS); + server.getRecorder().requireRequest(1, TimeUnit.SECONDS); + for (int i = 0; i < 3; i++) { + lastRetryState.recordFailure(false, -1); + } + + eventProcessor.setOffline(true); + eventProcessor.setOffline(false); + + server.getRecorder().requireNoRequests(1_500, TimeUnit.MILLISECONDS); + assertTrue(server.getRecorder().requireRequest(5, TimeUnit.SECONDS).getBody() + .contains("\"key\":\"held\"")); + } finally { + eventProcessor.close(); + scheduler.shutdownNow(); + } + } + } + + @Test + public void goingOnlineAgainKeepsToTheWaitARefusalOrARetryAfterSet() throws Exception { + Handler[] refusals = { + Handlers.status(401), + Handlers.all(Handlers.header("Retry-After", "30"), Handlers.status(503)) + }; + for (Handler refusal : refusals) { + ScheduledExecutorService scheduler = EventUtil.makeEventsTaskExecutor(); + ExecutorService diagnosticExecutor = EventUtil.makeDiagnosticsTaskExecutor(); + diagnosticExecutors.add(diagnosticExecutor); + EventStore store = EventStore.create(eventsDirectory.newFolder(), MOBILE_KEY, DEFAULT_CAPACITY, + persistence() != EventPersistence.DISABLED, logging.logger); + try (HttpServer server = HttpServer.start(Handlers.sequential(refusal, Handlers.status(202)))) { + DirectEventProcessor eventProcessor = makeEventProcessor(new StubEventSender(), + server.getUri(), null, NO_PERIODIC_FLUSH_MILLIS, 60_000, + DirectEventProcessor.DEFAULT_CLOSE_BUDGET_MILLIS, scheduler, diagnosticExecutor, store, + DEFAULT_CAPACITY); + try { + eventProcessor.setOffline(false); + eventProcessor.recordCustomEvent(CONTEXT, "refused", LDValue.ofNull(), null); + assertFalse(awaitFlush(eventProcessor, 10, TimeUnit.SECONDS)); + server.getRecorder().requireRequest(1, TimeUnit.SECONDS); + + eventProcessor.setOffline(true); + eventProcessor.setOffline(false); + + server.getRecorder().requireNoRequests(1_500, TimeUnit.MILLISECONDS); + } finally { + eventProcessor.close(); + scheduler.shutdownNow(); + } + } + } + } + @Test public void dataTooDeeplyNestedToEncodeCostsOnlyItsOwnEvent() throws Exception { LDValue nested = LDValue.of(1); @@ -4825,6 +4934,23 @@ private DirectEventProcessor makeEventProcessor(EventSender diagnosticSender, EventStore store, int capacity, boolean commitOnCallerThread) { + return makeEventProcessor(diagnosticSender, eventsUri, diagnosticStore, flushIntervalMillis, + diagnosticIntervalMillis, closeBudgetMillis, scheduler, diagnosticExecutor, store, + capacity, commitOnCallerThread, DirectEventProcessor.Pacing.NONE); + } + + private DirectEventProcessor makeEventProcessor(EventSender diagnosticSender, + URI eventsUri, + DiagnosticStore diagnosticStore, + long flushIntervalMillis, + long diagnosticIntervalMillis, + long closeBudgetMillis, + ScheduledExecutorService scheduler, + ExecutorService diagnosticExecutor, + EventStore store, + int capacity, + boolean commitOnCallerThread, + DirectEventProcessor.Pacing pacing) { ExecutorService commitExecutor = EventUtil.makeEventsCommitExecutor(); diagnosticExecutors.add(commitExecutor); lastCommitExecutor = commitExecutor; @@ -4845,7 +4971,7 @@ private DirectEventProcessor makeEventProcessor(EventSender diagnosticSender, flushIntervalMillis, diagnosticIntervalMillis, closeBudgetMillis, - DirectEventProcessor.Pacing.NONE, + pacing, false, true, // initiallyOffline, as the SDK builds it scheduler,