Now I have a clear understanding of the issue:
maybeOffload is called for automatic offload triggers and uses offloadMutex to ensure only one offload runs at a time
- When the mutex cannot be acquired, it schedules a retry after 100ms, which can lead to redundant retries if multiple triggers arrive
asyncOffloadPrefix is the manual/offload method and it also uses offloadMutex, returning an error if offload is in progress
The fix should:
- Track if an automatic offload is running and if there's a pending follow-up
- While automatic offload is running, don't schedule redundant retries - only one follow-up
- When the current offload completes, check if there's a pending follow-up and run it
- Manual offload should retain its existing behavior (it should still be blocked if automatic is running)
Let me design the solution:
- Add a state variable to track if automatic offload is in progress and if there's a pending follow-up
- When
maybeOffload cannot acquire the lock and automatic offload is in progress:
- If there's already a pending follow-up, don't do anything (coalesce)
- If there's no pending follow-up, schedule one
- When the offload completes, if there's a pending follow-up, execute it
- Manual offload continues to use the lock and blocks if automatic is running
Here's my plan:
- Add a
CompletableFuture<Position> field to track the pending automatic offload
- When an automatic offload is in progress and another trigger arrives, attach the new promise to the pending one
- The pending promise completes when the current offload and any follow-ups complete
Actually, let me think about this more carefully. The issue is:
- Multiple automatic triggers arriving while an offload is running cause redundant retries
- We need at most one active automatic run and at most one follow-up run
- The follow-up must process newly eligible ledgers
So the solution is:
- Track if automatic offload is in progress
- If yes and no follow-up pending: schedule one follow-up
- If yes and follow-up already pending: don't schedule another (coalesce)
- When the current offload completes, if there's a pending follow-up, run it with fresh ledger info
Let me implement this fix:
// Add at class level near the other offload fields
private volatile boolean automaticOffloadInProgress = false;
private volatile CompletableFuture<Position> pendingAutomaticFollowUp = null;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
// Automatic offload is already running
// Check if we need to schedule a follow-up
if (automaticOffloadInProgress && pendingAutomaticFollowUp == null) {
// Schedule one follow-up that will check for newly eligible ledgers
pendingAutomaticFollowUp = CompletableFuture.completedFuture(null);
scheduledExecutor.schedule(() -> maybeOffloadInBackground(NULL_OFFLOAD_PROMISE),
100, TimeUnit.MILLISECONDS);
}
// If follow-up is already scheduled, don't schedule another (coalesce)
return;
}
// Mark that we're in automatic offload
automaticOffloadInProgress = true;
// ... existing code ...
Wait, this is getting complex. Let me think about this differently.
The issue description says:
- "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"
- "Explicit/manual offload futures must retain their existing behavior"
So the key insight is:
- While an automatic offload is running, don't schedule redundant retries
- But still allow one follow-up that will check for newly eligible ledgers
- Manual offload should still work as before (blocking if automatic is running)
Let me look at a cleaner approach:
- Add a state to track automatic offload (in-progress or pending follow-up)
- When
maybeOffload can't acquire the lock, check the state and handle accordingly
- When the offload completes, if there's a pending follow-up, run it
Here's my implementation plan:
// Add class-level fields
private volatile boolean automaticOffloadRunning = false;
private volatile boolean pendingFollowUpScheduled = false;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
// Automatic offload is running
if (!pendingFollowUpScheduled) {
// Schedule one follow-up to check for newly eligible ledgers
pendingFollowUpScheduled = true;
scheduledExecutor.schedule(() -> maybeOffloadInBackground(NULL_OFFLOAD_PROMISE),
100, TimeUnit.MILLISECONDS);
}
// Don't fail the promise - just return (it will be handled by follow-up)
return;
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback:
if (ex != null) {
// error handling
} else {
if (pendingFollowUpScheduled) {
pendingFollowUpScheduled = false;
// Run follow-up with fresh ledger info
executor.execute(() -> maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, NULL_OFFLOAD_PROMISE));
}
}
Actually, I need to think about the promise handling more carefully. When maybeOffload can't acquire the lock:
- For automatic offload, the promise should complete when the current offload completes (not when our retry succeeds)
- For manual offload, it should fail immediately (existing behavior)
Let me re-read the code to understand how the promise is used:
In maybeOffload:
finalPromise is the promise passed from maybeOffloadInBackground
- If lock can't be acquired, a retry is scheduled with
maybeOffloadInBackground(finalPromise)
- If lock is acquired, an
unlockingPromise is created that will complete finalPromise when offload completes
So the issue is:
- When lock can't be acquired, we schedule a retry with the same
finalPromise
- Multiple retries for the same trigger will each try to complete the same promise (which is redundant)
- Different triggers will each have their own promise, and they'll all eventually complete (after multiple retries)
The fix should:
- Track if an automatic offload is in progress
- When lock can't be acquired, check if there's a pending follow-up
- If no follow-up, schedule one (that will complete when the current offload completes)
- If follow-up already pending, don't schedule another
Actually, I think I need to re-read the issue more carefully. The issue says:
- "Automatic managed-ledger offload triggers create redundant retry work"
- "Coalesce automatic offload triggers while an automatic offload is running"
So the key issue is that multiple triggers create multiple retry attempts, and each retry does the same work (checking if offload is needed, scheduling another retry, etc.).
The fix should:
- Track if automatic offload is in progress
- When lock can't be acquired and automatic offload is in progress:
- If there's already a follow-up scheduled, don't schedule another (coalesce)
- If no follow-up, schedule one
- The follow-up should check for newly eligible ledgers
- When the offload completes, if there's a pending follow-up, run it
Let me implement this more carefully:
// Add class-level fields near other offload fields
private volatile boolean automaticOffloadRunning = false;
private volatile boolean pendingFollowUpScheduled = false;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
// Automatic offload is already running
if (automaticOffloadRunning) {
// Don't schedule redundant retries
// Only schedule one follow-up if not already scheduled
if (!pendingFollowUpScheduled) {
pendingFollowUpScheduled = true;
scheduledExecutor.schedule(() -> {
pendingFollowUpScheduled = false;
maybeOffloadInBackground(NULL_OFFLOAD_PROMISE);
}, 100, TimeUnit.MILLISECONDS);
}
// Complete the promise when current offload completes
// But how do we know when? We need to wait for the current offload...
// Actually, the follow-up will handle newly eligible ledgers
// So we can complete the promise with Position.LATEST
finalPromise.complete(PositionFactory.LATEST);
return;
} else {
// Shouldn't happen if we're using the right lock
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback (after offloadMutex.unlock()):
// Check if there's a pending follow-up
if (pendingFollowUpScheduled) {
pendingFollowUpScheduled = false;
// Run follow-up with fresh ledger info
// Need to get the thresholds again from config
final OffloadPolicies policies = config.getLedgerOffloader().getOffloadPolicies();
final long offloadThresholdInBytes =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInBytes()).orElse(-1L);
final long offloadThresholdInSeconds =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInSeconds()).orElse(-1L);
executor.execute(() -> maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, NULL_OFFLOAD_PROMISE));
}
automaticOffloadRunning = false;
Actually, this is getting complicated. Let me think about a simpler approach:
The key insight is that we want to:
- Prevent redundant retries while automatic offload is running
- Allow one follow-up that will check for newly eligible ledgers
- Complete the original promise when the follow-up completes
Here's a simpler approach:
- Track if automatic offload is running and if there's a pending follow-up
- When lock can't be acquired, if automatic offload is running:
- If no follow-up pending, schedule one
- Attach the current promise to the follow-up promise
- The follow-up promise completes when either the current offload completes (if no ledgers to offload) or a new offload completes
- When the offload completes, if there's a pending follow-up, run it with fresh ledger info
Actually, let me re-read the issue description again:
- "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"
- "Explicit/manual offload futures must retain their existing behavior"
I think the key is:
- Track if automatic offload is in progress
- Track if there's a pending follow-up
- When a trigger arrives and offload is running:
- If no follow-up pending, schedule one
- The follow-up will check for newly eligible ledgers
- When the offload completes, if there's a pending follow-up, run it
- Manual offload should still be blocked if automatic is running (existing behavior)
Here's my implementation plan:
// Add class-level fields
private volatile boolean automaticOffloadRunning = false;
private volatile CompletableFuture<Position> pendingFollowUpPromise = null;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadRunning) {
// Automatic offload is already running
// Check if there's already a follow-up
if (pendingFollowUpPromise != null) {
// Follow-up is already scheduled, just return
// The original promise will complete when follow-up completes
pendingFollowUpPromise.thenAccept(pos -> finalPromise.complete(pos));
return;
} else {
// No follow-up yet, schedule one
// This follow-up will check for newly eligible ledgers
pendingFollowUpPromise = new CompletableFuture<>();
scheduledExecutor.schedule(() -> {
try {
if (!offloadMutex.tryLock()) {
// This shouldn't happen, but just in case
pendingFollowUpPromise = null;
return;
}
// Check for newly eligible ledgers
// ... similar to original offload loop but with fresh data ...
pendingFollowUpPromise.complete(PositionFactory.LATEST);
offloadMutex.unlock();
} finally {
pendingFollowUpPromise = null;
}
}, 100, TimeUnit.MILLISECONDS);
// Complete the original promise when follow-up completes
pendingFollowUpPromise.thenAccept(pos -> finalPromise.complete(pos));
return;
}
} else {
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback:
// If there's a pending follow-up, run it
if (pendingFollowUpPromise != null) {
pendingFollowUpPromise.complete(firstUnoffloaded);
// Schedule the follow-up offload
scheduledExecutor.schedule(() -> maybeOffloadInBackground(NULL_OFFLOAD_PROMISE), 0, TimeUnit.MILLISECONDS);
}
automaticOffloadRunning = false;
Hmm, this is getting complex. Let me simplify:
The key issue is that when multiple triggers arrive while an offload is running:
- Each trigger calls
maybeOffloadInBackground which schedules a retry after 100ms
- These retries are independent and each checks if offload is needed
- This leads to redundant work
The fix should:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running:
- Don't schedule a new retry if one is already pending
- Complete the current promise when the follow-up completes
- When the offload completes, if there's a pending follow-up, run it with fresh ledger info
Let me implement a cleaner solution:
// Add class-level fields
private volatile boolean automaticOffloadInProgress = false;
private volatile boolean pendingFollowUpScheduled = false;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
// Check if automatic offload is already in progress
if (automaticOffloadInProgress) {
// Coalesce: only schedule one follow-up
if (!pendingFollowUpScheduled) {
pendingFollowUpScheduled = true;
scheduledExecutor.schedule(() -> {
pendingFollowUpScheduled = false;
// Check if there are newly eligible ledgers and offload them
executor.execute(() -> maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, NULL_OFFLOAD_PROMISE));
}, 100, TimeUnit.MILLISECONDS);
}
// Don't fail the promise - just return
// The promise will complete when the follow-up completes (via the original offload)
return;
} else {
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
}
// Mark as in progress
automaticOffloadInProgress = true;
// ... existing code ...
// When offload completes:
if (pendingFollowUpScheduled) {
pendingFollowUpScheduled = false;
// Schedule follow-up with fresh ledger info
scheduledExecutor.schedule(() -> maybeOffloadInBackground(NULL_OFFLOAD_PROMISE), 0, TimeUnit.MILLISECONDS);
}
automaticOffloadInProgress = false;
Wait, I realize there's an issue with this approach. If multiple triggers arrive while offload is running, and we complete their promises when the follow-up completes, but we don't actually track which promise is the "follow-up" promise.
Let me think about this differently. The issue is about redundant retry work, not about promise completion. The fix should:
- Prevent multiple retries while automatic offload is running
- Allow one follow-up that will check for newly eligible ledgers
- Each trigger's promise should complete when the follow-up completes
Actually, looking at the code more carefully:
maybeOffload uses offloadMutex to prevent concurrent offloads
- When lock can't be acquired, it schedules a retry
- Each retry will check if offload is needed and either offload or complete
The issue is that if multiple triggers arrive rapidly, each will schedule a retry, and each retry will check the same ledgers.
A simpler fix:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running, don't schedule a retry (coalesce)
- When the offload completes, check if there are newly eligible ledgers and schedule a follow-up if needed
But how do we track "newly eligible ledgers"? The follow-up should check the ledgers again after the current offload completes.
Actually, I think the simplest fix is:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running, just return (don't schedule retry)
- When the offload completes, check if there are newly eligible ledgers (based on time threshold) and schedule a follow-up if needed
But this might miss ledgers that became eligible during the offload.
Let me re-read the issue description one more time:
- "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"
So the key requirements are:
- At most one active automatic run (already enforced by offloadMutex)
- At most one follow-up run (need to add this)
- Follow-up must process newly eligible ledgers (need to implement this)
I think the fix is:
- Track if automatic offload is running
- Track if there's a pending follow-up
- When lock can't be acquired and automatic offload is running:
- If no follow-up pending, schedule one
- If follow-up pending, don't schedule another (coalesce)
- When the offload completes, if there's a pending follow-up, run it with fresh ledger info
- The follow-up promise should complete when the follow-up offload completes
Here's my final implementation plan:
// Add class-level fields
private volatile boolean automaticOffloadInProgress = false;
private volatile CompletableFuture<Position> pendingFollowUpPromise = null;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadInProgress) {
// Automatic offload is already running
if (pendingFollowUpPromise != null) {
// Follow-up is already scheduled, coalesce by completing the current promise
// when the follow-up completes
pendingFollowUpPromise.thenAccept(finalPromise::complete);
} else {
// No follow-up yet, schedule one
pendingFollowUpPromise = new CompletableFuture<>();
scheduledExecutor.schedule(() -> {
try {
// Check for newly eligible ledgers
if (!offloadMutex.tryLock()) {
// This shouldn't happen, but just in case
pendingFollowUpPromise.complete(null);
return;
}
// Run offload with fresh data
maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, pendingFollowUpPromise);
} finally {
pendingFollowUpPromise = null;
}
}, 100, TimeUnit.MILLISECONDS);
// Complete the current promise when follow-up completes
pendingFollowUpPromise.thenAccept(finalPromise::complete);
}
return;
}
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
// Mark as in progress
automaticOffloadInProgress = true;
// ... existing code ...
// In the completion callback (after unlocking):
if (pendingFollowUpPromise != null) {
// Complete the pending follow-up
pendingFollowUpPromise.complete(null);
pendingFollowUpPromise = null;
}
automaticOffloadInProgress = false;
Hmm, this is still complex. Let me think about a cleaner approach.
Actually, I think the simplest fix is:
- Track if automatic offload is running using a boolean flag
- When lock can't be acquired and automatic offload is running, don't schedule a retry (just return)
- When the offload completes, check if there are newly eligible ledgers and schedule a follow-up if needed
The key insight is that the offload loop already processes ledgers based on size and time thresholds. So if a follow-up is scheduled after the current offload, it will naturally pick up any newly eligible ledgers.
Let me implement a simpler fix:
// Add class-level field
private volatile boolean automaticOffloadRunning = false;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadRunning) {
// Automatic offload is already running, don't schedule redundant retry
// The original promise will complete when the current offload completes
// But we need to handle this case...
// Actually, we can just return and let the follow-up handle it
return;
}
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback:
// Check if we should schedule a follow-up
// We can check if any ledgers became eligible during the offload
// Actually, the offload loop already handles this - it processes all eligible ledgers
// So we don't need a follow-up in most cases
automaticOffloadRunning = false;
Wait, but the issue says "A follow-up must still process newly eligible ledgers". So we do need a follow-up mechanism.
Let me think about this more carefully. The issue is:
- Automatic offload triggers arrive while an offload is running
- Each trigger schedules a retry after 100ms
- These retries are redundant because they all check the same ledgers
- But we still need to process newly eligible ledgers that become eligible during the offload
So the fix should:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running:
- Don't schedule a new retry if one is already pending
- Schedule one follow-up that will check for newly eligible ledgers
- When the offload completes, if there's a pending follow-up, run it
Here's my implementation:
// Add class-level fields
private volatile boolean automaticOffloadRunning = false;
private volatile boolean followUpScheduled = false;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadRunning) {
// Automatic offload is already running
if (!followUpScheduled) {
// Schedule one follow-up to check for newly eligible ledgers
followUpScheduled = true;
scheduledExecutor.schedule(() -> {
followUpScheduled = false;
// Run follow-up with fresh ledger info
final OffloadPolicies policies = config.getLedgerOffloader().getOffloadPolicies();
final long offloadThresholdInBytes =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInBytes()).orElse(-1L);
final long offloadThresholdInSeconds =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInSeconds()).orElse(-1L);
executor.execute(() -> maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, NULL_OFFLOAD_PROMISE));
}, 100, TimeUnit.MILLISECONDS);
}
// Complete the current promise when follow-up completes
// Actually, we can't complete the promise yet because the follow-up might
// not run immediately or might not find any ledgers to offload
// So we just return and let the promise complete when the follow-up completes
// But how do we track this? We need to store the promise...
return;
}
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback:
// Check if there's a follow-up to run
if (followUpScheduled) {
followUpScheduled = false;
// Run follow-up with fresh ledger info
final OffloadPolicies policies = config.getLedgerOffloader().getOffloadPolicies();
final long offloadThresholdInBytes =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInBytes()).orElse(-1L);
final long offloadThresholdInSeconds =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInSeconds()).orElse(-1L);
executor.execute(() -> maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, NULL_OFFLOAD_PROMISE));
}
automaticOffloadRunning = false;
Hmm, but this still has the issue of not completing the original promise. Let me think about this more.
Actually, I think I need to track the pending promise as well. When a trigger arrives while offload is running and we schedule a follow-up, we need to complete the trigger's promise when the follow-up completes.
Let me implement this:
// Add class-level fields
private volatile boolean automaticOffloadRunning = false;
private volatile boolean followUpScheduled = false;
private volatile CompletableFuture<Position> pendingFollowUpPromise = null;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadRunning) {
// Automatic offload is already running
if (followUpScheduled) {
// Follow-up is already scheduled, coalesce by attaching to the pending promise
pendingFollowUpPromise.thenAccept(finalPromise::complete);
} else {
// No follow-up yet, schedule one
followUpScheduled = true;
pendingFollowUpPromise = new CompletableFuture<>();
scheduledExecutor.schedule(() -> {
try {
if (!offloadMutex.tryLock()) {
pendingFollowUpPromise.complete(null);
return;
}
// Run follow-up with fresh ledger info
maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, pendingFollowUpPromise);
} finally {
followUpScheduled = false;
pendingFollowUpPromise = null;
}
}, 100, TimeUnit.MILLISECONDS);
// Complete the current promise when follow-up completes
pendingFollowUpPromise.thenAccept(finalPromise::complete);
}
return;
}
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback:
// Check if there's a pending follow-up to run
if (pendingFollowUpPromise != null) {
pendingFollowUpPromise.complete(null);
pendingFollowUpPromise = null;
// Run follow-up with fresh ledger info
final OffloadPolicies policies = config.getLedgerOffloader().getOffloadPolicies();
final long offloadThresholdInBytes =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInBytes()).orElse(-1L);
final long offloadThresholdInSeconds =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInSeconds()).orElse(-1L);
executor.execute(() -> maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, NULL_OFFLOAD_PROMISE));
}
automaticOffloadRunning = false;
Wait, there's still an issue. The offloadThresholdInBytes and offloadThresholdInSeconds variables are local to maybeOffload, so they're not available in the lambda when scheduling the follow-up.
Let me fix this by getting the values from config instead:
// Add class-level fields
private volatile boolean automaticOffloadRunning = false;
private volatile boolean followUpScheduled = false;
private volatile CompletableFuture<Position> pendingFollowUpPromise = null;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadRunning) {
// Automatic offload is already running
if (followUpScheduled) {
// Follow-up is already scheduled, coalesce by attaching to the pending promise
pendingFollowUpPromise.thenAccept(finalPromise::complete);
} else {
// No follow-up yet, schedule one
followUpScheduled = true;
pendingFollowUpPromise = new CompletableFuture<>();
scheduledExecutor.schedule(() -> {
try {
if (!offloadMutex.tryLock()) {
pendingFollowUpPromise.complete(PositionFactory.LATEST);
return;
}
// Run follow-up with fresh ledger info
final OffloadPolicies policies = config.getLedgerOffloader().getOffloadPolicies();
final long offloadThresholdInBytes =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInBytes()).orElse(-1L);
final long offloadThresholdInSeconds =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInSeconds()).orElse(-1L);
maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, pendingFollowUpPromise);
} finally {
followUpScheduled = false;
pendingFollowUpPromise = null;
}
}, 100, TimeUnit.MILLISECONDS);
// Complete the current promise when follow-up completes
pendingFollowUpPromise.thenAccept(finalPromise::complete);
}
return;
}
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback:
// Check if there's a pending follow-up to run
if (pendingFollowUpPromise != null) {
pendingFollowUpPromise.complete(PositionFactory.LATEST);
pendingFollowUpPromise = null;
// Run follow-up with fresh ledger info
executor.execute(() -> maybeOffloadInBackground(NULL_OFFLOAD_PROMISE));
}
automaticOffloadRunning = false;
Actually, I realize there's still a subtle issue. The pendingFollowUpPromise is used both as a signal that a follow-up is scheduled AND as a promise that completes when the follow-up completes. But if the follow-up is scheduled, we also need to run it when the current offload completes.
Let me rethink this. The key requirements are:
- At most one active automatic run
- At most one follow-up run
- Follow-up must process newly eligible ledgers
- Manual offload should retain existing behavior
So the fix should:
- Track if automatic offload is running
- Track if there's a pending follow-up
- When lock can't be acquired and automatic offload is running:
- If follow-up already pending, complete the current promise when follow-up completes
- If no follow-up pending, schedule one and attach the current promise
- When the offload completes, if there's a pending follow-up, run it
But how do we track "pending follow-up" that will run when the current offload completes? We need a separate mechanism.
Actually, I think the simplest approach is:
- Track if automatic offload is running
- Track if there's a pending follow-up (scheduled but not yet run)
- When a trigger arrives and offload is running:
- If no follow-up pending, schedule one (this will check for newly eligible ledgers)
- Attach the trigger's promise to the follow-up promise
- When the offload completes, if there's a pending follow-up, run it with fresh ledger info
- The follow-up promise completes when the follow-offload completes
Let me implement this:
// Add class-level fields
private volatile boolean automaticOffloadRunning = false;
private volatile CompletableFuture<Position> pendingFollowUp = null;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadRunning) {
// Automatic offload is already running
if (pendingFollowUp != null) {
// Follow-up is already scheduled, coalesce
pendingFollowUp.thenAccept(finalPromise::complete);
} else {
// No follow-up, schedule one
pendingFollowUp = new CompletableFuture<>();
scheduledExecutor.schedule(() -> {
try {
if (!offloadMutex.tryLock()) {
pendingFollowUp.complete(PositionFactory.LATEST);
return;
}
// Run follow-up with fresh ledger info
final OffloadPolicies policies = config.getLedgerOffloader().getOffloadPolicies();
final long offloadThresholdInBytes =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInBytes()).orElse(-1L);
final long offloadThresholdInSeconds =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInSeconds()).orElse(-1L);
maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, pendingFollowUp);
} finally {
pendingFollowUp = null;
}
}, 100, TimeUnit.MILLISECONDS);
pendingFollowUp.thenAccept(finalPromise::complete);
}
return;
}
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback:
if (pendingFollowUp != null) {
pendingFollowUp.complete(PositionFactory.LATEST);
pendingFollowUp = null;
// Run follow-up with fresh ledger info
executor.execute(() -> maybeOffloadInBackground(NULL_OFFLOAD_PROMISE));
}
automaticOffloadRunning = false;
This looks correct. The key insight is:
pendingFollowUp is null if no follow-up is pending
- When a trigger arrives and offload is running:
- If
pendingFollowUp is not null, the trigger's promise completes when pendingFollowUp completes
- If
pendingFollowUp is null, we schedule a follow-up and create a new pendingFollowUp promise
- The follow-up promise is used to:
- Signal that a follow-up is scheduled (non-null value)
- Track the completion of the follow-up
- When the current offload completes, if there's a pending follow-up, we run it
Wait, but there's still an issue. The follow-up is scheduled to run 100ms after the current trigger, but we also want to run it when the current offload completes. How do we handle this?
Actually, I think the current design is correct. Here's the flow:
- Trigger 1 arrives, offload runs (acquires lock)
- Trigger 2 arrives while offload is running, can't acquire lock, schedules follow-up (sets
pendingFollowUp)
- Offload completes, checks if
pendingFollowUp is not null, runs follow-offload
- Follow-offload completes, clears
pendingFollowUp
- Trigger 3 arrives, can't acquire lock, but
pendingFollowUp is now null, so it schedules a new follow-up
Actually, this doesn't work correctly. When the offload completes and we check for pending follow-up, the follow-up is scheduled to run in 100ms. But we're also trying to run the follow-up when the offload completes. This could lead to duplicate follow-ups.
Let me rethink this. The key insight is:
- We want to prevent redundant retries while automatic offload is running
- We want to allow one follow-up that will check for newly eligible ledgers
- The follow-up should run after the current offload completes, not after a fixed delay
So the fix should:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running, don't schedule a retry (just coalesce)
- When the offload completes, check if there are newly eligible ledgers and schedule a follow-up if needed
But how do we track "trigger arrival" while offload is running? We need to know that a trigger arrived so we can run a follow-up.
Actually, I think the fix is simpler:
- Track if automatic offload is running and if there's a pending follow-up
- When lock can't be acquired and automatic offload is running:
- If no follow-up pending, set a flag that follow-up is needed
- If follow-up pending, don't do anything
- When the offload completes, if there's a pending follow-up, run it with fresh ledger info
Let me implement this:
// Add class-level fields
private volatile boolean automaticOffloadRunning = false;
private volatile boolean pendingFollowUpNeeded = false;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadRunning) {
// Automatic offload is already running
if (!pendingFollowUpNeeded) {
// Mark that a follow-up is needed
pendingFollowUpNeeded = true;
}
// Don't schedule retry, just return
// The original promise will complete when the follow-up completes
// But how? We need to track the promise...
return;
}
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback:
if (pendingFollowUpNeeded) {
pendingFollowUpNeeded = false;
// Run follow-up with fresh ledger info
executor.execute(() -> maybeOffloadInBackground(NULL_OFFLOAD_PROMISE));
}
automaticOffloadRunning = false;
Hmm, but now we still have the issue of not completing the original promise. If a trigger arrives while offload is running, we just return and don't complete the promise. This will leave the promise hanging.
Let me think about this more. The original promise should complete when:
- The current offload completes, OR
- The follow-up completes (if triggered by the current offload)
So when a trigger arrives while offload is running, we need to track that trigger's promise and complete it when either the current offload or the follow-up completes.
But this is getting complex. Let me step back and think about the requirements again:
- At most one active automatic run (already enforced by offloadMutex)
- At most one follow-up run (need to add this)
- Follow-up must process newly eligible ledgers
- Manual offload should retain existing behavior
The key issue is that when multiple triggers arrive while offload is running, each trigger schedules a retry, leading to redundant work. The fix should coalesce these triggers so that only one follow-up runs.
Here's a simpler approach:
- Track if automatic offload is running
- Track if there's a pending follow-up (using a CompletableFuture)
- When lock can't be acquired and automatic offload is running:
- If no follow-up pending, schedule one and attach all pending promises to it
- If follow-up pending, attach the current promise to it
- When the offload completes, if there's a pending follow-up, run it
But the issue is how to track "pending promises". We can't track all of them individually.
Actually, I think the simplest approach is:
- Track if automatic offload is running
- Track if there's a pending follow-up (using a boolean flag and a CompletableFuture)
- When lock can't be acquired and automatic offload is running:
- If no follow-up pending, schedule one (with a CompletableFuture that tracks completion)
- If follow-up pending, don't do anything
- When the offload completes, if there's a pending follow-up, run it
- Complete the pending follow-up promise when it completes
- All triggers that arrived while offload was running will have their promises completed when the follow-up completes
But how do we track all the triggers? We need to store their promises somewhere.
Actually, I think the fix is simpler. The issue is about "redundant retry work", not about promise completion. The fix should:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running, don't schedule a retry (just return)
- When the offload completes, check if any new ledgers became eligible and offload them
The promise completion is handled by the offloadMutex - when the offload completes, all pending promises are completed.
Wait, no. Each trigger has its own promise, and they're not all tracked together. Let me re-read the code to understand how promises work.
Looking at maybeOffload:
finalPromise is the promise passed from maybeOffloadInBackground
- If lock can't be acquired, a retry is scheduled with
maybeOffloadInBackground(finalPromise)
- If lock is acquired,
unlockingPromise is created that completes finalPromise when offload completes
So each trigger has its own finalPromise, and when the offload completes, that trigger's promise is completed.
The issue is:
- Trigger 1 arrives, schedules retry after 100ms
- Trigger 2 arrives, schedules retry after 100ms
- Trigger 1's retry runs, acquires lock, offloads
- Trigger 2's retry runs, can't acquire lock, schedules another retry
- ... and so on
The fix should:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running, don't schedule a retry
- When the offload completes, check if there are newly eligible ledgers and schedule a follow-up
But how do we complete the promises of triggers that arrived while offload was running?
Actually, I think the fix is:
- Track if automatic offload is running
- Track if there's a pending follow-up (using a CompletableFuture)
- When lock can't be acquired and automatic offload is running:
- If no follow-up pending, schedule one (with a CompletableFuture)
- If follow-up pending, don't do anything
- When the offload completes, if there's a pending follow-up, run it
- Complete the pending follow-up promise when the follow-up completes
- For triggers that arrived while offload was running, their promises should be completed when the follow-up completes
But how do we track which triggers arrived while offload was running? We need to store their promises somewhere.
Actually, I think the simplest fix is:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running, don't schedule a retry
- When the offload completes, check if any new ledgers became eligible and schedule a follow-up
- The promises of triggers that arrived while offload was running will be completed when the offload completes (via the unlockingPromise mechanism)
Wait, but that's not correct. When a trigger can't acquire the lock, its promise is not completed by the unlockingPromise. The unlockingPromise is only created when the lock is acquired.
Let me re-read the code more carefully.
Looking at maybeOffload:
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);
}
});
So:
- If lock can't be acquired, a retry is scheduled with the same
finalPromise
- If lock is acquired,
unlockingPromise is created that completes finalPromise when offload completes
unlockingPromise is passed to offloadLoop, which completes it when offload completes
So the issue is:
- Trigger 1 arrives, can't acquire lock, schedules retry with promise P1
- Trigger 2 arrives, can't acquire lock, schedules retry with promise P2
- Trigger 1's retry runs, acquires lock, sets up unlockingPromise U1 that completes P1
- Trigger 1's offload runs and completes U1, which completes P1
- Trigger 2's retry runs, can't acquire lock (still running), schedules retry with promise P2
- ...
The fix should prevent steps 1-2 from happening, so only one retry is scheduled.
But what about the promises of triggers that arrive while offload is running? Their promises should be completed when the offload completes.
Actually, I think the fix is:
- Track if automatic offload is running
- Track if there's a pending follow-up (using a CompletableFuture)
- When lock can't be acquired and automatic offload is running:
- If no follow-up pending, schedule one and attach all pending promises to it
- If follow-up pending, attach the current promise to it
- When the offload completes, if there's a pending follow-up, run it
- Complete the pending follow-up promise when it completes
- All attached promises are completed when the follow-up completes
The key is to track "pending promises" and attach them to the follow-up promise.
Let me implement this:
// Add class-level fields
private volatile boolean automaticOffloadRunning = false;
private volatile CompletableFuture<Position> pendingFollowUp = null;
private final ConcurrentLinkedQueue<CompletableFuture<Position>> pendingTriggers = new ConcurrentLinkedQueue<>();
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadRunning) {
// Automatic offload is already running
pendingTriggers.offer(finalPromise);
if (pendingFollowUp == null) {
// No follow-up pending, schedule one
pendingFollowUp = new CompletableFuture<>();
scheduledExecutor.schedule(() -> {
try {
if (!offloadMutex.tryLock()) {
pendingFollowUp.complete(PositionFactory.LATEST);
return;
}
// Run follow-up with fresh ledger info
final OffloadPolicies policies = config.getLedgerOffloader().getOffloadPolicies();
final long offloadThresholdInBytes =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInBytes()).orElse(-1L);
final long offloadThresholdInSeconds =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInSeconds()).orElse(-1L);
maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, pendingFollowUp);
} finally {
pendingFollowUp = null;
}
}, 100, TimeUnit.MILLISECONDS);
}
return;
}
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback:
// Clear any pending triggers
while (!pendingTriggers.isEmpty()) {
CompletableFuture<Position> p = pendingTriggers.poll();
p.complete(PositionFactory.LATEST);
}
if (pendingFollowUp != null) {
pendingFollowUp.complete(PositionFactory.LATEST);
pendingFollowUp = null;
// Run follow-up with fresh ledger info
executor.execute(() -> maybeOffloadInBackground(NULL_OFFLOAD_PROMISE));
}
automaticOffloadRunning = false;
Hmm, this is getting complex. Let me think about a simpler approach.
Actually, I think the simplest fix is to just prevent redundant retries while automatic offload is running. The promises of triggers that arrive while offload is running will be completed when the offload completes (by the unlockingPromise mechanism).
Wait, that's not correct. When a trigger can't acquire the lock, its promise is not completed by the unlockingPromise. The unlockingPromise is only created when the lock is acquired.
Let me think about this differently. The key insight is:
- The issue is about "redundant retry work", not about promise completion
- We want to prevent multiple retries from being scheduled while automatic offload is running
- We want to allow one follow-up that will check for newly eligible ledgers
- The promises of triggers should be completed when the offload or follow-up completes
Here's a simpler approach:
- Track if automatic offload is running and if there's a pending follow-up
- When lock can't be acquired and automatic offload is running:
- If no follow-up pending, schedule one (that will complete when the offload completes or when it runs)
- If follow-up pending, don't schedule another
- When the offload completes, if there's a pending follow-up, run it
- Complete the pending follow-up promise when it completes
The key is that when a trigger arrives while offload is running, we don't immediately complete its promise. Instead, we complete it when the follow-up completes.
Here's the implementation:
// Add class-level fields
private volatile boolean automaticOffloadRunning = false;
private volatile boolean pendingFollowUpScheduled = false;
private final ConcurrentLinkedQueue<CompletableFuture<Position>> pendingPromises = new ConcurrentLinkedQueue<>();
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadRunning) {
// Automatic offload is already running
pendingPromises.offer(finalPromise);
if (!pendingFollowUpScheduled) {
// No follow-up pending, schedule one
pendingFollowUpScheduled = true;
scheduledExecutor.schedule(() -> {
try {
pendingFollowUpScheduled = false;
if (!offloadMutex.tryLock()) {
// This shouldn't happen
return;
}
// Run follow-up with fresh ledger info
final OffloadPolicies policies = config.getLedgerOffloader().getOffloadPolicies();
final long offloadThresholdInBytes =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInBytes()).orElse(-1L);
final long offloadThresholdInSeconds =
Optional.ofNullable(policies.getManagedLedgerOffloadThresholdInSeconds()).orElse(-1L);
maybeOffload(offloadThresholdInBytes, offloadThresholdInSeconds, NULL_OFFLOAD_PROMISE);
} finally {
// Complete all pending promises
while (!pendingPromises.isEmpty()) {
CompletableFuture<Position> p = pendingPromises.poll();
p.complete(PositionFactory.LATEST);
}
}
}, 100, TimeUnit.MILLISECONDS);
}
return;
}
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback:
// Complete all pending promises
while (!pendingPromises.isEmpty()) {
CompletableFuture<Position> p = pendingPromises.poll();
p.complete(PositionFactory.LATEST);
}
automaticOffloadRunning = false;
Hmm, but this still has issues. The follow-up is scheduled to run 100ms after the trigger arrives, but we also want to run it when the offload completes. And the pending promises should be completed when the follow-up completes, not when the offload completes.
Let me think about this more carefully. The flow should be:
- Trigger 1 arrives, acquires lock, offload runs
- Trigger 2 arrives, can't acquire lock, adds its promise to pendingPromises
- If no follow-up scheduled, schedule one (100ms delay)
- Trigger 3 arrives, can't acquire lock, adds its promise to pendingPromises
- Offload completes
- If there are pending promises and no follow-up scheduled, run follow-offload
- Follow-offload completes, all pending promises are completed
But the issue is that the follow-up is scheduled with a 100ms delay, and it might run before the offload completes. This could lead to duplicate offloads.
Actually, I think the key insight is that we want to prevent redundant retries, but we still want to complete the promises when appropriate. Here's the flow:
- Trigger 1 arrives, acquires lock, offload runs
- Trigger 2 arrives, can't acquire lock, adds its promise to pendingPromises
- If no follow-up scheduled, schedule one (that will run when offload completes)
- Trigger 3 arrives, can't acquire lock, adds its promise to pendingPromises (don't schedule follow-up again)
- Offload completes
- If there are pending promises, run follow-offload
- Follow-offload completes, all pending promises are completed
The key is that the follow-up is scheduled to run after the offload completes, not after a fixed delay.
Here's the implementation:
// Add class-level fields
private volatile boolean automaticOffloadRunning = false;
private final ConcurrentLinkedQueue<CompletableFuture<Position>> pendingPromises = new ConcurrentLinkedQueue<>();
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadRunning) {
// Automatic offload is already running
pendingPromises.offer(finalPromise);
// Don't schedule retry
return;
}
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback:
// Check if there are pending promises
if (!pendingPromises.isEmpty()) {
// Schedule follow-up to process newly eligible ledgers
executor.execute(() -> maybeOffloadInBackground(NULL_OFFLOAD_PROMISE));
}
// Complete all pending promises
while (!pendingPromises.isEmpty()) {
CompletableFuture<Position> p = pendingPromises.poll();
p.complete(PositionFactory.LATEST);
}
automaticOffloadRunning = false;
This looks simpler! The key points are:
- When a trigger arrives and automatic offload is running, its promise is added to
pendingPromises and we don't schedule a retry
- When the offload completes, if there are pending promises, we schedule a follow-up
- All pending promises are completed with
PositionFactory.LATEST
But wait, this doesn't correctly handle the case where the follow-up should run when there are newly eligible ledgers, not just when there are pending promises. The follow-up should check for newly eligible ledgers based on size and time thresholds.
Actually, looking at the code again, the follow-up is handled by maybeOffloadInBackground, which calls maybeOffload. And maybeOffload checks if there are ledgers to offload based on size and time thresholds. So if there are no ledgers to offload, the follow-up will complete immediately.
So the fix is:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running, don't schedule a retry, just add the promise to pendingPromises
- When the offload completes, if there are pending promises, schedule a follow-up
- Complete all pending promises when they are polled
Let me implement this:
// Add class-level field
private final ConcurrentLinkedQueue<CompletableFuture<Position>> pendingPromises = new ConcurrentLinkedQueue<>();
private volatile boolean automaticOffloadRunning = false;
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadRunning) {
// Automatic offload is already running, coalesce
pendingPromises.offer(finalPromise);
return;
}
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code ...
// In the completion callback (after unlockingPromise completes):
// Complete all pending promises
while (!pendingPromises.isEmpty()) {
CompletableFuture<Position> p = pendingPromises.poll();
p.complete(PositionFactory.LATEST);
}
// If there were pending promises, schedule follow-up to check for newly eligible ledgers
if (!pendingPromises.isEmpty()) {
executor.execute(() -> maybeOffloadInBackground(NULL_OFFLOAD_PROMISE));
}
automaticOffloadRunning = false;
Wait, there's a logic error. I'm checking !pendingPromises.isEmpty() after I've already cleared it. Let me fix this:
// In the completion callback (after unlockingPromise completes):
boolean hasPendingPromises = !pendingPromises.isEmpty();
while (!pendingPromises.isEmpty()) {
CompletableFuture<Position> p = pendingPromises.poll();
p.complete(PositionFactory.LATEST);
}
// If there were pending promises, schedule follow-up to check for newly eligible ledgers
if (hasPendingPromises) {
executor.execute(() -> maybeOffloadInBackground(NULL_OFFLOAD_PROMISE));
}
automaticOffloadRunning = false;
Actually, this is still not quite right. The follow-up should run after the offload completes, and it should check for newly eligible ledgers. But if I schedule the follow-up after completing the pending promises, there might be a race condition where a new trigger arrives and schedules another offload.
Let me think about this more carefully. The issue is:
- Trigger 1 arrives, acquires lock, offload runs
- Trigger 2 arrives, can't acquire lock, pendingPromises offers P2
- Offload completes, hasPendingPromises is true, schedules follow-up
- Trigger 3 arrives while follow-up is being scheduled, can't acquire lock, pendingPromises offers P3
- Follow-offload runs, acquires lock, offloads P3... but P3 wasn't in the original set of pending promises
This is getting complicated. Let me simplify:
The key insight is that we want to:
- Prevent redundant retries while automatic offload is running
- Allow one follow-up after the current offload completes
- Complete all pending promises when the follow-up completes
Here's the simplified fix:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running, add the promise to pendingPromises and don't schedule a retry
- When the offload completes, schedule a follow-up if there are pending promises
- Complete all pending promises when the follow-up completes
But the issue is timing. If the follow-up is scheduled after the offload completes, and a new trigger arrives before the follow-up runs, the new trigger will be treated as a new offload, not as part of the pending promises.
Actually, I think the fix should be simpler. The key is:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running, add the promise to pendingPromises
- When the offload completes, schedule a follow-up (regardless of pending promises)
- Complete all pending promises when the follow-up completes or when it runs
Actually, let me re-read the issue description one more time:
- "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"
- "Explicit/manual offload futures must retain their existing behavior"
I think the key is:
- "At most one active automatic run" - already enforced by offloadMutex
- "At most one follow-up run" - need to ensure only one follow-up is scheduled
- "Follow-up must still process newly eligible ledgers" - follow-up should check for ledgers based on thresholds
- "Manual offload should retain existing behavior" - manual offload should be blocked if automatic is running (as it is now)
So the fix should:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running:
- Don't schedule a retry (coalesce)
- Just return (the promise will be handled by the follow-up)
- When the offload completes, if there are any triggers that arrived while offload was running, schedule a follow-up
- Complete all pending promises when the follow-up completes
But how do we know if there are triggers that arrived while offload was running? We need to track this.
I think the simplest fix is:
- Track if automatic offload is running
- When lock can't be acquired and automatic offload is running, don't schedule a retry, just return
- When the offload completes, schedule a follow-up with a small delay (to allow any pending triggers to arrive)
- The follow-up will check for newly eligible ledgers
But this might not handle the promise completion correctly. Let me think about this differently.
Actually, I think the fix is simpler than I thought. The key insight is:
- When a trigger arrives and offload is running, we don't need to do anything immediately
- We just need to prevent redundant retries
- The promises of triggers will be completed when the follow-up completes
But the issue is that each trigger has its own promise, and we need to complete those promises. If we just return without completing the promise, it will hang.
So we need to:
- Track pending promises
- Complete them when the follow-up completes or when the offload completes
Here's the final implementation:
// Add class-level fields
private volatile boolean automaticOffloadRunning = false;
private final ConcurrentLinkedQueue<CompletableFuture<Position>> pendingPromises = new ConcurrentLinkedQueue<>();
// In maybeOffload:
if (!offloadMutex.tryLock()) {
if (automaticOffloadRunning) {
// Automatic offload is already running, coalesce
pendingPromises.offer(finalPromise);
return;
}
// No automatic offload running, schedule retry
scheduledExecutor.schedule(() -> maybeOffloadInBackground(finalPromise),
100, TimeUnit.MILLISECONDS);
return;
}
// Mark as running
automaticOffloadRunning = true;
// ... existing code (offloadLoop call) ...
// In the completion callback:
// Complete all pending promises
while (!pendingPromises.isEmpty()) {
CompletableFuture<Position> p = pendingPromises.poll();
p.complete(PositionFactory.LATEST);
}
// If there were pending promises, schedule follow-up to check for newly eligible ledgers
if (!pendingPromises.isEmpty()) {
// This won't work because we just cleared pendingPromises
}
automaticOffloadRunning = false;
OK, I see the issue. I need to track whether there were pending promises before I clear them:
// In the completion callback:
boolean hasPendingPromises = !pendingPromises.isEmpty();
// Complete all pending promises
while (!pendingPromises.isEmpty()) {
CompletableFuture<Position> p = pendingPromises.poll();
p.complete(PositionFactory.LATEST);
}
// If there were pending promises, schedule follow-up to check for newly eligible ledgers
if (hasPendingPromises) {
executor.execute(() -> maybeOffloadInBackground(NULL_OFFLOAD_PROMISE));
}
automaticOffloadRunning = false;
This looks correct. The flow is:
- Trigger 1 arrives, acquires lock, offload runs, automaticOffloadRunning = true
- Trigger 2 arrives, can't acquire lock, pendingPromises offers P2
- Offload completes, hasPendingPromises is true, schedule follow-up, complete P2, automaticOffloadRunning = false
- Follow-up runs, checks for newly eligible ledgers, offloads if needed
And if no trigger arrives while offload is running:
- Trigger 1 arrives, acquires lock, offload runs, automaticOffloadRunning = true
- Offload completes, hasPendingPromises is false, don't schedule follow-up, automaticOffloadRunning = false
This should handle the issue correctly. Let me now implement this fix.
Actually, wait. I need to check the exact location where the completion callback is. Let me look at the code again.
<tool_call>
<function=bash_terminal>
<parameter=command>
sed -n '2820,2860p' /pulsar/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java
</tool_call>