Now I understand the issue. The problem is in the maybeOffload method at line 2836-2838. When offloadMutex.tryLock() fails (meaning an automatic offload is already running), it schedules a new retry after 100ms via maybeOffloadInBackground. If multiple triggers come in during that time, each one will schedule its own retry.
The issue states:
- There must be at most one active automatic run and at most one follow-up run when additional triggers arrive.
- A follow-up must still process newly eligible ledgers.
- Explicit/manual offload futures must retain their existing behavior.
The key distinction is:
- Automatic offload: Called via
maybeOffloadInBackground → maybeOffload. If already running, should coalesce into one follow-up trigger.
- Manual/explicit offload: Called via
asyncOffloadPrefix → ledgersOffload. These already throw OffloadInProgressException when the mutex is locked, and this behavior should be retained.
The fix should modify the automatic offload logic to:
- Track if an automatic offload is in progress
- If an automatic offload is already running, schedule at most one follow-up trigger
- When the current automatic offload completes, if there's a pending follow-up, execute it
Let me think about the implementation approach:
- We could add a field to track if an automatic offload is in progress
- When
maybeOffload fails to acquire the lock, instead of immediately scheduling a new retry, we should only schedule one if we haven't already scheduled a follow-up
- When the offload completes (via the unlockingPromise callback), we should check if there's a pending follow-up and schedule it
Let me look at the code structure more carefully:
Current flow:
maybeOffloadInBackground(promise) → executor.execute(() → maybeOffload(...))
→ tryLock() succeeds → offloadLoop() → unlock via callback
→ tryLock() fails → schedule(maybeOffloadInBackground, 100ms)
The problem: Each failed tryLock schedules a new retry, so if N triggers come in while an offload is running, we get N retries.
Solution approach:
- Add a flag
autoOffloadInProgress to track when an automatic offload is running
- Add a flag
autoOffloadFollowupScheduled to track when a follow-up has been scheduled
- When
maybeOffload can't acquire the lock and we're in an auto-offload, set autoOffloadFollowupScheduled = true and don't schedule anything new (the follow-up will be triggered when current offload completes)
- When the current offload completes, check if
autoOffloadFollowupScheduled is true, and if so, schedule the follow-up
Actually, let me re-read the requirement more carefully:
- "at most one active automatic run" - OK, mutex already handles this
- "at most one follow-up run when additional triggers arrive" - This means we need to coalesce follow-ups
- "A follow-up must still process newly eligible ledgers" - The follow-up should check for new eligible ledgers
- "explicit/manual offload futures must retain their existing behavior" - Manual offloads should still fail with OffloadInProgressException
Wait, there's a subtle point here. The offloadMutex is shared between automatic and manual offloads. So if an automatic offload is running, manual offloads will also fail (which is the expected behavior based on the tests we saw).
Let me think about the fix more carefully. The key issue is that maybeOffload schedules a new retry every time it fails to acquire the lock. This creates redundant work.
The fix should be:
- Track when an automatic offload is in progress using a state variable
- When
maybeOffload fails to acquire the lock, only schedule ONE follow-up (not one per trigger)
- When the automatic offload completes, if there's a pending follow-up scheduled, run it
- Manual offloads should continue to fail with
OffloadInProgressException
Let me implement this. I need to add:
- A state field to track automatic offload status (e.g.,
autoOffloadState)
- Logic to coalesce multiple triggers into one follow-up
Here's my plan:
// State to track automatic offload runs
private volatile AutoOffloadState autoOffloadState = AutoOffloadState.Idle;
enum AutoOffloadState {
Idle, // No automatic offload running, no follow-up scheduled
Running, // Automatic offload is running
FollowUpScheduled // Offload is running, but a follow-up is scheduled
}
When maybeOffload is called:
- If state is Idle, set to Running, try to acquire lock
- Success: proceed with offload
- Failure: set to Idle (someone else will handle it)
- If state is Running, set to FollowUpScheduled and return (don't schedule anything new)
- If state is FollowUpScheduled, just return (already have a scheduled follow-up)
When offload completes:
- If state is FollowUpScheduled, reset to Idle and schedule a new offload
- If state is Running, reset to Idle
Actually, I realize this is more nuanced because the offloadMutex handles the locking. Let me reconsider...
The offloadMutex is already shared between auto and manual offloads. The issue is specifically with automatic offload triggering. When multiple automatic triggers come in:
- Trigger 1: tries to lock, succeeds → starts offload → sets
autoOffloadState = Running
- Trigger 2: tries to lock, fails → schedules retry in 100ms
- Trigger 3: tries to lock, fails → schedules retry in 100ms
- ... more triggers ...
The fix should make it so that triggers 2, 3, etc. only schedule at most ONE follow-up.
Let me reconsider the implementation:
- Add
autoOffloadScheduled flag (boolean)
- In
maybeOffload, when we can't acquire the lock:
- If not already scheduled, set
autoOffloadScheduled = true and schedule a follow-up
- If already scheduled, just return (follow-up will run anyway)
- When the follow-up runs (before trying to acquire the lock), if
autoOffloadScheduled = true, continue; otherwise, reset state if needed
- When offload completes (success or failure), reset
autoOffloadScheduled = false
Actually, let me think about this differently. The issue is simpler than I thought:
When maybeOffload fails to acquire offloadMutex, it should:
- Only schedule ONE follow-up, not one per trigger
- That follow-up should run regardless of whether there are still triggers coming
The simplest fix: track whether a follow-up has been scheduled. If yes, don't schedule another one.
Let me look at the code more carefully to understand the state management:
private void maybeOffload(...) {
if (!offloadMutex.tryLock()) {
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise), 100, TimeUnit.MILLISECONDS);
return;
}
// ... proceed with offload
// When done, offloadMutex.unlock() is called in the callback
}
The fix:
private volatile boolean autoOffloadFollowupScheduled = false;
private void maybeOffload(...) {
if (!offloadMutex.tryLock()) {
if (!autoOffloadFollowupScheduled) {
autoOffloadFollowupScheduled = true;
scheduledExecutor.schedule(() -> {
autoOffloadFollowupScheduled = false;
maybeOffloadInBackground(finalPromise);
}, 100, TimeUnit.MILLISECONDS);
}
return;
}
// ... proceed with offload, when done:
// In the unlock callback, reset autoOffloadFollowupScheduled = false
}
Wait, but we also need to handle the case where the follow-up itself might fail to acquire the lock (e.g., if a manual offload started). Let me think about this...
Actually, let me re-read the issue requirements:
- "There must be at most one active automatic run and at most one follow-up run when additional triggers arrive."
- "A follow-up must still process newly eligible ledgers"
So the behavior should be:
- If automatic offload is running, don't start another one
- Schedule at most one follow-up that will run after the current offload completes (or after 100ms if none is running but the follow-up itself failed to acquire)
- Manual offloads should still behave as before
Let me look at this from a different angle. The key insight is:
- When an automatic offload is running, we want to coalesce all subsequent triggers into ONE follow-up
- That follow-up should run after the current offload finishes (or after a short delay)
The cleanest approach:
- Add
autoOffloadScheduled flag
- In
maybeOffload, when lock fails and !autoOffloadScheduled:
- Set
autoOffloadScheduled = true
- Schedule a follow-up that will:
- Reset
autoOffloadScheduled = false
- Call
maybeOffloadInBackground which will re-evaluate and potentially start a new offload
- When offload completes, if
autoOffloadScheduled, don't do anything special (the follow-up will handle it)
- Actually, we should reset
autoOffloadScheduled when the offload completes, so that subsequent triggers can schedule new follow-ups
Let me look at how to implement this. The maybeOffload method handles the locking and unlocking. When the lock is acquired, we call offloadLoop which eventually completes the promise. The promise completion triggers the unlock.
Here's my refined plan:
// Flag to track if a follow-up has been scheduled
private volatile boolean autoOffloadFollowupScheduled = false;
// When maybeOffload fails to acquire the lock
if (!offloadMutex.tryLock()) {
if (!autoOffloadFollowupScheduled) {
autoOffloadFollowupScheduled = true;
scheduledExecutor.schedule(() -> {
autoOffloadFollowupScheduled = false;
maybeOffloadInBackground(finalPromise);
}, 100, TimeUnit.MILLISECONDS);
}
return;
}
// When offload completes (in the unlockingPromise callback)
unlockingPromise.whenComplete((res, ex) -> {
offloadMutex.unlock();
// If a follow-up was scheduled while we were offloading, don't reset the flag
// The scheduled task will pick it up
// If no follow-up was scheduled, we can reset it (already false if never set)
});
Hmm, but there's a race condition here. The follow-up might run before the offload completes, or after. Let me think about this more carefully...
Actually, I think the simpler approach is better:
- When
maybeOffload can't acquire the lock, only schedule a follow-up if one isn't already scheduled
- The follow-up schedules itself via
maybeOffloadInBackground
- When
maybeOffload successfully acquires the lock and completes, reset the flag
Let me also consider: what happens if the offload takes a long time and many triggers come in? We only want ONE follow-up scheduled, not one per trigger.
Here's my implementation plan:
private volatile boolean autoOffloadPending = false;
private void maybeOffload(...) {
// ... validation checks ...
if (!offloadMutex.tryLock()) {
if (!autoOffloadPending) {
autoOffloadPending = true;
scheduledExecutor.schedule(() -> {
autoOffloadPending = false;
maybeOffloadInBackground(finalPromise);
}, 100, TimeUnit.MILLISECONDS);
}
return;
}
// ... proceed with offload
// When offloadLoop completes:
unlockingPromise.whenComplete((res, ex) -> {
offloadMutex.unlock();
// Reset the flag - it will be set again if new triggers come in
autoOffloadPending = false;
// ... rest of completion logic
});
}
Wait, there's still a race. If the offload completes and we reset autoOffloadPending = false, but a follow-up was already scheduled, the follow-up might see autoOffloadPending = false and schedule ANOTHER follow-up, leading to multiple retries.
Let me think about this differently. The key property we want is:
- At most one pending follow-up at any time
So the follow-up should NOT reset the flag. Only the offload itself should reset the flag when it completes.
But then, what if the follow-up runs BEFORE the offload completes? That shouldn't happen because:
- The follow-up is scheduled via
scheduledExecutor.schedule(..., 100ms)
- The offload typically takes much longer than 100ms
- If the offload completes in less than 100ms, the follow-up will try to acquire the lock and fail (because the lock was already released by the offload completion)
Actually, wait. If the offload completes in less than 100ms:
offloadMutex.unlock() is called
- 100ms later, the follow-up runs and calls
maybeOffloadInBackground
maybeOffload tries to acquire the lock, which should succeed (since offload already completed)
- A new offload might start if there are eligible ledgers
This is actually correct behavior! The follow-up should check for eligible ledgers after the current offload completes.
But what if the offload completes, and THEN new triggers come in? The autoOffloadPending flag should be reset so new triggers can schedule follow-ups.
OK here's my final design:
private volatile boolean autoOffloadPending = false;
private void maybeOffload(...) {
// ... validation checks ...
if (!offloadMutex.tryLock()) {
if (!autoOffloadPending) {
autoOffloadPending = true;
scheduledExecutor.schedule(() -> {
autoOffloadPending = false;
maybeOffloadInBackground(finalPromise);
}, 100, TimeUnit.MILLISECONDS);
}
return;
}
// ... proceed with offload ...
// When offload completes (in the callback)
unlockingPromise.whenComplete((res, ex) -> {
offloadMutex.unlock();
autoOffloadPending = false; // Reset so future triggers can schedule
// ... rest of completion logic
});
}
This ensures:
- Only one follow-up is scheduled at a time
- When the offload completes,
autoOffloadPending is reset
- When the follow-up runs, it resets the flag before proceeding
- The follow-up will re-evaluate which ledgers to offload (since it calls
maybeOffloadInBackground again)
Wait, there's still a subtle issue. If the offload completes AND a follow-up is scheduled:
- Offload completes, unlocks mutex, resets
autoOffloadPending = false
- Follow-up runs, resets
autoOffloadPending = false (no-op since already false)
- Follow-up calls
maybeOffloadInBackground, which may start a new offload
This is correct! But there's a race: between step 1 and 2, a new trigger might come in and set autoOffloadPending = true, and then step 2 resets it. But this is fine because:
- Step 3 will try to acquire the lock. If the offload already unlocked, the follow-up can start a new offload.
- If a new trigger comes in during this window, it might see
autoOffloadPending = false and schedule its own follow-up.
Hmm, this could lead to multiple follow-ups if triggers are very frequent. Let me reconsider...
Actually, let me think about this more carefully. The scenario is:
- Offload is running
- Trigger A arrives, can't acquire lock, schedules follow-up F1, sets
autoOffloadPending = true
- Trigger B arrives, can't acquire lock, sees
autoOffloadPending = true, doesn't schedule anything
- Offload completes, resets
autoOffloadPending = false
- F1 runs 100ms later, resets
autoOffloadPending = false, calls maybeOffloadInBackground
maybeOffloadInBackground calls maybeOffload, tries to acquire lock (succeeds), runs new offload
This looks correct!
But what about:
- Offload is running
- Trigger A arrives, can't acquire lock, schedules follow-up F1, sets
autoOffloadPending = true
- Offload completes, resets
autoOffloadPending = false
- F1 runs 100ms later, resets
autoOffloadPending = false, calls maybeOffloadInBackground
maybeOffloadInBackground calls maybeOffload, tries to acquire lock (succeeds), runs new offload
This also looks correct!
And what about:
- Offload is running
- Trigger A arrives, can't acquire lock, schedules follow-up F1, sets
autoOffloadPending = true
- New Trigger B arrives, can't acquire lock, sees
autoOffloadPending = true, doesn't schedule anything
Also correct!
What about the race between offload completion and follow-up execution?
- Offload is running
- Trigger A arrives, can't acquire lock, schedules follow-up F1, sets
autoOffloadPending = true
- Offload completes, resets
autoOffloadPending = false (time: 0ms)
- F1 runs 100ms later, resets
autoOffloadPending = false, calls maybeOffloadInBackground
Still correct! The follow-up runs after the offload completes and checks for new ledgers.
OK, I think my design is correct. Let me implement it.
Actually wait, I need to reconsider one more thing. Looking at the code:
if (!offloadMutex.tryLock()) {
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise), 100, TimeUnit.MILLISECONDS);
return;
}
The finalPromise is the promise passed to this specific invocation of maybeOffload. When we schedule a follow-up, we're essentially deferring this promise to a later time. The follow-up will call maybeOffloadInBackground(finalPromise) which will pass the same finalPromise to a new maybeOffload invocation.
So the flow is:
maybeOffloadInBackground(finalPromise) is called
- It executes
maybeOffload(..., finalPromise) on the executor
- If lock fails, it schedules
maybeOffloadInBackground(finalPromise) to run in 100ms
- The follow-up will try again, and if successful, will resolve
finalPromise
This is correct behavior. Each trigger's promise will be resolved when the offload eventually completes.
But wait, there's another consideration. Each trigger creates a new finalPromise. If triggers come in frequently, we might have multiple pending promises. The follow-up only resolves one of them?
No, looking at the code again:
if (!offloadMutex.tryLock()) {
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise), 100, TimeUnit.MILLISECONDS);
return;
}
CompletableFuture<Position> unlockingPromise = new CompletableFuture<>();
unlockingPromise.whenComplete((res, ex) -> {
offloadMutex.unlock();
if (ex != null) {
finalPromise.completeExceptionally(ex);
} else {
finalPromise.complete(res);
}
});
When the lock is acquired, we create a new unlockingPromise that will eventually resolve the finalPromise. The unlockingPromise is used for the actual offload, and when it completes, we unlock and resolve finalPromise.
So each trigger has its own finalPromise, and only the one that actually acquires the lock will be resolved. The others will just be rescheduled until one succeeds.
But with my fix, only ONE follow-up is scheduled, which means only ONE trigger's promise will eventually be resolved (by the follow-up). This could be a problem if other triggers' promises are never resolved.
Hmm, but actually, looking at how maybeOffloadInBackground is used:
public void maybeOffloadInBackground(CompletableFuture<Position> promise) {
// ...
executor.execute(() -> maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, promise));
}
And it's called from various places:
- From
ManagedLedgerFactoryImpl.open() with NULL_OFFLOAD_PROMISE
- Probably from other places too
Let me check where maybeOffloadInBackground is called:
grep -rn "maybeOffloadInBackground" /pulsar --include="*.java"
I should verify this. But even if there are multiple callers with different promises, the key insight is:
- Each caller has its own promise
- If the caller's tryLock fails, the promise is deferred
- The deferred call will eventually resolve the promise when offload completes
With my fix, at most one follow-up is scheduled. This means if multiple triggers come in, only one follow-up will run. The promise associated with that follow-up will be resolved. Other triggers' promises... hmm, this could be an issue.
Wait, let me re-read the code. When maybeOffload fails to acquire the lock, it schedules a follow-up. The follow-up calls maybeOffloadInBackground(finalPromise), which creates a new maybeOffload invocation with the same finalPromise. If this new invocation succeeds, the promise is resolved. If it fails again (e.g., because a manual offload started), it schedules another follow-up...
So the current behavior is:
- Each failed trigger schedules its own retry
- Multiple retries can run concurrently (in a sense, as they're scheduled at different times)
With my fix:
- At most one retry is scheduled
- When the retry runs, it might succeed or fail again
- If it fails again, it schedules another retry (but only if
autoOffloadPending is not already set)
Actually, I think the key issue is: are the finalPromises from multiple triggers independent? Looking at how maybeOffloadInBackground is called:
// Line 1971
maybeOffloadInBackground(NULL_OFFLOAD_PROMISE);
And NULL_OFFLOAD_PROMISE is:
public static final CompletableFuture<Position> NULL_OFFLOAD_PROMISE = CompletableFuture
So there's at least one shared promise. If multiple calls use the same promise, then coalescing follow-ups makes sense.
But even if they use different promises, the key is that maybeOffload is meant to be idempotent - it checks for eligible ledgers each time. So if we coalesce follow-ups, the follow-up will process any newly eligible ledgers.
Actually, I think I'm overcomplicating this. Let me re-read the issue description:
"Coalesce automatic offload triggers while an automatic offload is running. There must be at most one active automatic run and at most one follow-up run when additional triggers arrive. A follow-up must still process newly eligible ledgers, and explicit/manual offload futures must retain their existing behavior."
The key points:
- At most one active automatic run - already handled by mutex
- At most one follow-up run when additional triggers arrive - this is what we need to fix
- A follow-up must still process newly eligible ledgers - the follow-up should re-check ledgers
- Explicit/manual offload futures must retain their existing behavior - this is about
asyncOffloadPrefix, not maybeOffload
So my fix is correct. Let me implement it.
Actually, I realize there's one more thing to consider. The issue says "at most one follow-up run when additional triggers arrive". This could mean:
- Option A: At most one follow-up scheduled at a time (what I've been thinking)
- Option B: At most one follow-up that runs after the current offload completes
I think Option A is what we want. The follow-up runs, processes newly eligible ledgers, and if it needs to (e.g., can't acquire lock because of a manual offload), it can schedule another follow-up (but only one).
OK, let me implement this now. I'll add a field autoOffloadPending to track whether a follow-up is already scheduled, and modify the maybeOffload method to only schedule a follow-up if one isn't already pending.
Let me first look at the full file structure to understand where to add the field:
<tool_call>
<function=bash_terminal>
<parameter=command>
head -400 /pulsar/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java | tail -200
</tool_call>