Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(browser-extension): stop new turns from burning queued batches' retries (#842)

Rudy Mizrahi Celekli01b11bbce594
diff --git a/browser-extension/src/background/delivery.ts b/browser-extension/src/background/delivery.ts
index 8f027568..5f1320cb 100644
--- a/browser-extension/src/background/delivery.ts
+++ b/browser-extension/src/background/delivery.ts
@@ -19,6 +19,8 @@ interface QueueItem {
endpoint: string;
envelope: LogsEnvelope;
attempts: number;
+ /** Persisted deadline so new turns cannot consume retries before backoff. */
+ nextAttemptAt?: number;
}
async function readQueue(): Promise<QueueItem[]> {
@@ -79,10 +81,16 @@ export async function flush(): Promise<void> {
// queued by an older build, or a tampered queue, must not reach anything
// but the local collector. Such an item is dropped, not retried.
if (!isAllowedEndpoint(item.endpoint)) continue;
+ if (item.nextAttemptAt != null && item.nextAttemptAt > Date.now()) {
+ remaining.push(item);
+ anyFailed = true;
+ continue;
+ }
const ok = await post(item);
if (!ok) {
item.attempts += 1;
if (item.attempts < MAX_ATTEMPTS) {
+ item.nextAttemptAt = Date.now() + retryDelay(item.attempts);
remaining.push(item);
anyFailed = true;
} // else: give up, drop it (avoid an unbounded queue)
@@ -110,16 +118,17 @@ async function post(item: QueueItem): Promise<boolean> {
}
}
+function retryDelay(attempts: number): number {
+ return Math.min(250 * 2 ** attempts, 60_000);
+}
+
function scheduleRetry(queue: QueueItem[]): void {
- const minAttempts = Math.min(...queue.map((i) => i.attempts));
- // We compute an exponential backoff, but note MV3 clamps chrome.alarms to a
- // ~30s minimum — so in practice the first retry lands at ~30s regardless of
- // this value. That's acceptable here: the collector is a local loopback
- // endpoint that is almost always reachable, so retries are the rare path and
- // the durable queue (chrome.storage) guarantees eventual delivery. We use
- // alarms rather than setTimeout because they survive service-worker suspension.
- const backoffMs = Math.min(250 * 2 ** minAttempts, 60_000);
- ext.alarms.create(ALARM, { when: Date.now() + backoffMs });
+ // Preserve each failed batch's deadline when unrelated new turns arrive.
+ // Chrome may clamp alarm cadence, but an enqueue must never accelerate a
+ // retry or repeatedly postpone the existing earliest scheduled deadline.
+ const when = Math.min(...queue.map((item) =>
+ item.nextAttemptAt ?? Date.now() + retryDelay(item.attempts)));
+ ext.alarms.create(ALARM, { when });
}
/** Wire the alarm listener (called once from the SW entry). */
diff --git a/browser-extension/test/unit/retry-backoff.test.ts b/browser-extension/test/unit/retry-backoff.test.ts
new file mode 100644
index 00000000..1b26a473
--- /dev/null
+++ b/browser-extension/test/unit/retry-backoff.test.ts
@@ -0,0 +1,58 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+const api = vi.hoisted(() => ({ get: vi.fn(), set: vi.fn(), alarm: vi.fn() }));
+vi.mock('../../src/shared/browser.js', () => ({ ext: {
+ storage: { local: { get: api.get, set: api.set } },
+ alarms: { create: api.alarm },
+} }));
+// The persisted shape of a delivery queue item, as delivery.ts stores it.
+type StoredItem = { id: string; endpoint: string; envelope: object; attempts: number; nextAttemptAt?: number };
+let queue: StoredItem[];
+let send: ReturnType<typeof vi.fn>;
+beforeEach(() => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ vi.setSystemTime(10_000);
+ queue = [{ id: 'turn', endpoint: 'http://127.0.0.1:4318/v1/logs', envelope: {}, attempts: 1, nextAttemptAt: 11_000 }];
+ api.get.mockImplementation(async () => ({ delivery_queue: structuredClone(queue) }));
+ api.set.mockImplementation(async ({ delivery_queue }: { delivery_queue: StoredItem[] }) => { queue = structuredClone(delivery_queue); });
+ api.alarm.mockClear();
+ send = vi.fn().mockResolvedValue({ ok: false });
+ vi.stubGlobal('fetch', send);
+});
+afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });
+
+it('preserves a waiting batch and its alarm deadline across unrelated flushes', async () => {
+ const { flush } = await import('../../src/background/delivery.js');
+ await flush();
+ await flush();
+ expect(send).not.toHaveBeenCalled();
+ expect(queue[0].attempts).toBe(1);
+ expect(api.alarm).toHaveBeenLastCalledWith('beacon_flush', { when: 11_000 });
+});
+
+it('retries a due batch and persists its next exponential deadline', async () => {
+ vi.setSystemTime(11_000);
+ const { flush } = await import('../../src/background/delivery.js');
+ await flush();
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(queue[0]).toMatchObject({ attempts: 2, nextAttemptAt: 12_000 });
+});
+
+it('still delivers a legacy queue item without a persisted deadline', async () => {
+ delete queue[0].nextAttemptAt;
+ send.mockResolvedValue({ ok: true });
+ const { flush } = await import('../../src/background/delivery.js');
+ await flush();
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(queue).toEqual([]);
+});
+
+it('keeps the existing maximum attempt limit for due failures', async () => {
+ vi.setSystemTime(11_000);
+ queue[0].attempts = 5;
+ const { flush } = await import('../../src/background/delivery.js');
+ await flush();
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(queue).toEqual([]);
+});