From 589c01955afc89728b7a7be86f924f2d6eceb6d6 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 20:01:42 -0500 Subject: [PATCH] fix(sync): start a run only with room for one POST and the GET Review of PR #184: when the budget freed up one place at a time (requests spread by network latency), every place went to a pull-only run with pushBatches = 0, so a queued backlog was never sent while the device spent 6 GETs a minute. The scheduler now waits for two free places. Tests: a fake server with 300 ms per request (9-batch queue empties within 4 min, no run without a POST place), the 600 s Retry-After bound, and source guards for the `more` signal of pushChanges and the budget of initialMerge. Refs #178 Co-Authored-By: Claude Opus 5.5 --- src/services/syncSchedule.ts | 11 +++++++---- tests/smoke.test.cjs | 5 +++++ tests/syncSchedule.test.mjs | 38 ++++++++++++++++++++++++++++++++++-- 3 files changed, 48 insertions(+), 6 deletions(-) diff --git a/src/services/syncSchedule.ts b/src/services/syncSchedule.ts index e71fc4a..9e11b6a 100644 --- a/src/services/syncSchedule.ts +++ b/src/services/syncSchedule.ts @@ -30,7 +30,7 @@ export interface RequestTracker { export interface SyncRun extends RequestTracker { /** * POST batches this run may send: the remaining budget minus one place for - * the GET of the pull. The rest of the queue goes to the next run. + * the GET of the pull, at least 1. The rest of the queue goes to the next run. */ readonly pushBatches: number; /** True once a 429 suspended the scheduler: the run sends nothing more. */ @@ -125,9 +125,12 @@ export function createSyncScheduler(deps: SchedulerDeps): SyncScheduler { return; } const left = remaining(now); - if (left < 1) { - // The oldest request leaves the window first - arm(sent[0] + BUDGET_WINDOW_MS - now); + if (left < 2) { + // A run needs a place for one POST and one for the GET. Starting with a + // single place would only pull, and a queue whose places free up one by + // one would never be sent (review of PR #184). Wait until the second + // oldest request in the window leaves it. + arm(sent[sent.length - REQUEST_BUDGET + 1] + BUDGET_WINDOW_MS - now); return; } start(left); diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index b51ac94..76096f2 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -243,6 +243,11 @@ check('sync on write and every sync go through the scheduler (#178)', () => { assert.match(body, /await scheduler\.beginInitialSync\(\);\s*try \{[^]*\} finally \{\s*scheduler\.endInitialSync\(\);/, `${name} must hold the first-sync state`); } assert.equal((client.match(/pullChanges\(SYNC_EPOCH, scheduler\.tracker\)/g) || []).length, 2, 'the first-sync pulls are counted'); + // Review of PR #184: initialMerge's POST batches count against the budget, + // and pushChanges tells the scheduler when the budget left entries unsent + const merge = client.slice(client.indexOf('async function mergeLocalData('), client.indexOf('export async function initialReset(')); + assert.match(merge, /post: \(batch\) => postBatch\(batch, headers, scheduler\.tracker\),/, 'initialMerge must count its POST batches'); + assert.match(client, /return \{ more: ok && operations\.length > maxBatches \* BATCH_SIZE \};\n\}/, 'pushChanges must report an unsent queue'); }); // Tags must not go through keepLocal: the server's tag updated_at is its diff --git a/tests/syncSchedule.test.mjs b/tests/syncSchedule.test.mjs index 0a3af67..1d78954 100644 --- a/tests/syncSchedule.test.mjs +++ b/tests/syncSchedule.test.mjs @@ -12,6 +12,7 @@ import assert from 'node:assert/strict'; import { BUDGET_WINDOW_MS, DEFAULT_RETRY_AFTER_S, + MAX_RETRY_AFTER_S, REQUEST_BUDGET, createSyncScheduler, } from '../src/services/syncSchedule.ts'; @@ -50,11 +51,15 @@ async function flush() { // A server stand-in: a queue of POST batches, each run pushes up to // ctx.pushBatches of them then pulls once. Records every request time. -function fakeServer(clock, { batches = 0, status = () => 200, duration = 0 } = {}) { - const state = { queue: batches, requests: [], runs: 0, active: 0, maxActive: 0, starts: [] }; +// `latency` is the response time of each request: the requests of one run +// are then spread in time, as on a real network (review of PR #184). +function fakeServer(clock, { batches = 0, status = () => 200, duration = 0, latency = 0 } = {}) { + const state = { queue: batches, requests: [], runs: 0, active: 0, maxActive: 0, starts: [], emptyPushRuns: 0 }; + const respond = () => (latency ? new Promise((resolve) => clock.setTimer(resolve, latency)) : undefined); state.run = async (ctx) => { state.runs++; state.starts.push(clock.now()); + if (state.queue > 0 && ctx.pushBatches < 1) state.emptyPushRuns++; state.active++; state.maxActive = Math.max(state.maxActive, state.active); try { @@ -64,6 +69,7 @@ function fakeServer(clock, { batches = 0, status = () => 200, duration = 0 } = { ctx.request(); state.requests.push(clock.now()); sent++; + await respond(); const s = status('POST'); if (s === 429) { ctx.rateLimited(20); @@ -74,6 +80,7 @@ function fakeServer(clock, { batches = 0, status = () => 200, duration = 0 } = { if (ctx.isSuspended()) return { more: state.queue > 0 }; ctx.request(); state.requests.push(clock.now()); + await respond(); const s = status('GET'); if (s === 429) ctx.rateLimited(20); return { more: state.queue > 0 }; @@ -203,6 +210,21 @@ test('an unsent queue is resumed without a new request once the budget allows', assert.ok(maxInAnyWindow(server.requests) <= REQUEST_BUDGET); }); +test('with 300 ms per request, a 9-batch queue empties in bounded time and no run starts without a POST place', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { batches: 9, latency: 300 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + // The 30 s foreground interval keeps asking + for (let t = 0; t < 4 * BUDGET_WINDOW_MS; t += 30_000) { + await clock.advance(30_000); + s.request(); + } + assert.equal(server.queue, 0, `${server.queue} batch(es) still queued after 4 min (${server.runs} runs)`); + assert.equal(server.emptyPushRuns, 0, 'a run started with pushBatches = 0 while the queue was not empty'); + assert.ok(maxInAnyWindow(server.requests) <= REQUEST_BUDGET, `max ${maxInAnyWindow(server.requests)} in a window`); +}); + test('after a 429 with Retry-After: 20, no request before 20 s', async () => { const clock = fakeClock(); let first = true; @@ -249,6 +271,18 @@ test('a 429 without a readable Retry-After suspends for the default delay', asyn assert.equal(starts, 2); }); +test('a huge Retry-After is bounded to MAX_RETRY_AFTER_S', async () => { + const clock = fakeClock(); + const server = fakeServer(clock); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.tracker.rateLimited(100_000); + s.request(); + await clock.advance(MAX_RETRY_AFTER_S * 1000 - 1); + assert.equal(server.runs, 0); + await clock.advance(1); + assert.equal(server.runs, 1, 'the scheduler resumes after MAX_RETRY_AFTER_S'); +}); + test('a 429 reported outside a run (initial sync) also suspends the scheduler', async () => { const clock = fakeClock(); const server = fakeServer(clock);