From 589c01955afc89728b7a7be86f924f2d6eceb6d6 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 20:01:42 -0500 Subject: [PATCH 1/5] 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); From dc479e36186ac9a6aee580a026073123d56a41d1 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 20:02:20 -0500 Subject: [PATCH 2/5] test(sync): pin the two-place rule of the scheduler A single free place with a queued backlog starts no run until a second place frees up; the condition alone was not pinned by the latency test. Refs #178 Co-Authored-By: Claude Opus 5.5 --- tests/syncSchedule.test.mjs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/syncSchedule.test.mjs b/tests/syncSchedule.test.mjs index 1d78954..14e91df 100644 --- a/tests/syncSchedule.test.mjs +++ b/tests/syncSchedule.test.mjs @@ -225,6 +225,22 @@ test('with 300 ms per request, a 9-batch queue empties in bounded time and no ru assert.ok(maxInAnyWindow(server.requests) <= REQUEST_BUDGET, `max ${maxInAnyWindow(server.requests)} in a window`); }); +test('with a single free place, no run starts until a second one frees up', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { batches: 1 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.tracker.request(); + await clock.advance(1000); + for (let i = 1; i < REQUEST_BUDGET - 1; i++) s.tracker.request(); + s.request(); + await clock.advance(BUDGET_WINDOW_MS - 1001); + assert.equal(server.runs, 0, 'one place left: a run would only pull'); + await clock.advance(1); + assert.equal(server.runs, 1, 'the run starts once the oldest request leaves the window'); + assert.equal(server.emptyPushRuns, 0); + assert.equal(server.queue, 0); +}); + test('after a 429 with Retry-After: 20, no request before 20 s', async () => { const clock = fakeClock(); let first = true; From cc591ba85e5185657ebba1e6862bac834ada4ff2 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 20:41:32 -0500 Subject: [PATCH 3/5] fix(web): close a socket whose send throws Review of PR #183: the socket was dropped from the client set but left open, outside the heartbeat, so its page was never notified again. terminate() closes it and the page reconnects through onclose. Refs #177 Co-Authored-By: Claude Opus 5.5 --- web/src/lib/ws.test.ts | 4 +++- web/src/lib/ws.ts | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/web/src/lib/ws.test.ts b/web/src/lib/ws.test.ts index c310b71..ab0b2f7 100644 --- a/web/src/lib/ws.test.ts +++ b/web/src/lib/ws.test.ts @@ -12,6 +12,7 @@ type FakeSocket = EventEmitter & { userId: string; readyState: number; send: ReturnType; + terminate: ReturnType; }; const OPEN = 1; // WebSocket.OPEN @@ -22,7 +23,7 @@ const g = globalThis as unknown as { }; function fakeSocket(userId: string): FakeSocket { - return Object.assign(new EventEmitter(), { userId, readyState: OPEN, send: vi.fn() }); + return Object.assign(new EventEmitter(), { userId, readyState: OPEN, send: vi.fn(), terminate: vi.fn() }); } async function freshModule() { @@ -106,6 +107,7 @@ describe('notifyUserChanged', () => { ws.notifyUserChanged('user-a'); expect(() => vi.advanceTimersByTime(ws.NOTIFY_DEBOUNCE_MS)).not.toThrow(); expect(ws.getActiveConnections()).toBe(0); + expect(a.terminate).toHaveBeenCalledTimes(1); }); }); diff --git a/web/src/lib/ws.ts b/web/src/lib/ws.ts index a454e77..14734e3 100644 --- a/web/src/lib/ws.ts +++ b/web/src/lib/ws.ts @@ -171,7 +171,10 @@ export function broadcastToUser(userId: string, message: WsMessage) { try { ws.send(payload); } catch { + // Close it too: left open, it would escape the heartbeat and the page + // would never be notified again (its onclose reconnects it). clients.delete(ws); + ws.terminate(); } } } From fd509fbfac3374a21b169e8092f20a5756b9a89d Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 20:42:15 -0500 Subject: [PATCH 4/5] test(web): pin dueDate with a tag filter and a non-integer priority Review of PR #186: both behaviour changes of the shared task query were untested; removing either condition left the suite green. Refs #179 Co-Authored-By: Claude Opus 5.5 --- web/src/lib/taskQueries.test.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/web/src/lib/taskQueries.test.ts b/web/src/lib/taskQueries.test.ts index 342091e..16bfa8f 100644 --- a/web/src/lib/taskQueries.test.ts +++ b/web/src/lib/taskQueries.test.ts @@ -181,6 +181,22 @@ describe('GET /api/lists/[id]/tasks?tags=', () => { expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t2]); }); + it('applies dueDate with a tag filter', async () => { + const a = await seedAccount(); + await exec('UPDATE sl_tasks SET due_date = $1 WHERE id = $2', ['2026-01-10T00:00:00Z', a.t1]); + // t2 (blue too) has no due date: excluded by the dueDate filter + const res = await getTasks(a.userId, a.list, `?tags=${a.blue}&dueDate=2026-02-01T00:00:00Z`); + expect(res.status).toBe(200); + expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t1]); + }); + + it('ignores a non-integer priority instead of failing', async () => { + const a = await seedAccount(); + const res = await getTasks(a.userId, a.list, '?priority=abc'); + expect(res.status).toBe(200); + expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t1, a.t2, a.t3]); + }); + it('still answers 404 for a list of another account', async () => { const a = await seedAccount(); const res = await getTasks(`user-${u()}`, a.list, ''); From 706f91d234976e2eb2b16828eb620843c09d8233 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 3 Nov 2026 20:42:41 -0500 Subject: [PATCH 5/5] test(sync): let the setTagsForTask wipe guard match across lines Review of PR #187: the regex did not allow the line break between .delete(taskTags) and .where(...), so the guard could never fail. Refs #180 Co-Authored-By: Claude Opus 5.5 --- tests/smoke.test.cjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index 89603c8..39fe31e 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -444,7 +444,7 @@ check('tag links: removals written by the app, pull aligned without the outbox ( assert.match(set, /tagLinkDiff\(/, 'setTagsForTask must diff with the local links'); assert.match(set, /for \(const tagId of removed\) \{\s*writeOutboxEntry\('taskTag', taskId, 'delete', \{ tagId \}\)/); assert.match(set, /for \(const tagId of added\) \{\s*writeOutboxEntry\('taskTag', taskId, 'create', \{ tagId \}\)/); - assert.ok(!/db\.delete\(taskTags\)\.where\(eq\(taskTags\.taskId, taskId\)\)/.test(set), 'setTagsForTask must not wipe every link'); + assert.ok(!/db\s*\.delete\(taskTags\)\s*\.where\(eq\(taskTags\.taskId, taskId\)\)/.test(set), 'setTagsForTask must not wipe every link'); assert.match(fnOf(tags, 'addTagToTask'), /writeOutboxEntry\('taskTag', taskId, 'create', \{ tagId \}\)\.then\(requestSync\)/); assert.match(fnOf(tags, 'removeTagFromTask'), /writeOutboxEntry\('taskTag', taskId, 'delete', \{ tagId \}\)\.then\(requestSync\)/);