test(sync): close the reviewer mutation gaps of the stack

Tests for mutations that stayed green in the reviews of PRs #154 to #159,
all added at the top of the stack (decision of Max, 2026-10-24):

- route: a task sent to an archived regular list stays there; the most
  recent active inbox wins the redirect; every POST cleans the
  idempotency store (#145, #147)
- idempotency store: a refreshed key moves to the newest end (#147)
- syncRules: an unknown result status is neither marked nor counted; the
  429 retry bound fails the test instead of hanging the suite (#151)
- smoke source check of syncClient.ts wiring: `since` forwarded by the
  pull, kept rows re-queued then left untouched, local row passed to
  pulled*Values, no local tag version in any form, SYNC_EPOCH stamped
  before the full pull of initialMerge, successful batches marked even
  after a failed one, widget refreshed after marking (#149, #150, #151)

Refs #151

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-10-24 20:55:44 -04:00
commit b88ca81e07
4 changed files with 118 additions and 1 deletions

View file

@ -227,6 +227,54 @@ check('syncClient.ts passes the #151 push bounds to sendInBatches', () => {
assert.match(src, /retryAfter: parseRetryAfter\(res\.headers\.get\('Retry-After'\)\)/);
});
// Wiring of the pull (#149), the end of initialMerge (#150) and the push
// (#151) in syncClient.ts, which node cannot load: the pure rules are tested
// in tests/syncRules.test.mjs, this check locks how syncClient.ts calls them
// (reviewer mutations of PRs #157, #158 and #159 stayed green without it).
check('syncClient.ts wires the #149-#151 sync rules', () => {
const src = fs.readFileSync(path.join(__dirname, '..', 'src/services/syncClient.ts'), 'utf8');
const fn = (name) => {
const m = new RegExp(`\\n(export )?async function ${name}\\(`).exec(src);
assert.ok(m, `${name} not found`);
const rest = src.slice(m.index + 1);
const end = rest.search(/\n(export )?async function /);
return end < 0 ? rest : rest.slice(0, end);
};
// #149: the pull forwards its `since`, and keeps or rewrites each row
assert.match(fn('pullChanges'), /applyChange\(change, since\)/);
const apply = fn('applyChange');
assert.match(apply, /applyListChange\(entity_id, action, payload, since\)/);
assert.match(apply, /applyTaskChange\(entity_id, action, payload, since\)/);
for (const [name, type, values, snapshot] of [
['applyListChange', 'list', 'pulledListValues', 'listUpdatePayload'],
['applyTaskChange', 'task', 'pulledTaskValues', 'taskUpdatePayload'],
]) {
const body = fn(name);
assert.match(
body,
new RegExp(`if \\(keepLocal\\(local, payload, since\\)\\) \\{\\s*(//[^\\n]*\\s*)?await writeOutboxEntry\\('${type}', id, 'update', ${snapshot}\\(local\\)\\);\\s*return;\\s*\\}`),
`${name}: a kept row must be re-queued, then left untouched`
);
assert.match(body, new RegExp(`${values}\\(id, payload, local\\)`), `${name} must pass the local row`);
}
// Tags always take the server version (decision of Max, PR #157)
const tag = fn('applyTagChange');
assert.match(tag, /pulledTagValues\(id, payload, local\)/);
assert.ok(!/\bkeepLocal\b|writeOutboxEntry|updated_at/.test(tag), 'applyTagChange must never keep a local tag');
// #150: lastSyncAt goes back to SYNC_EPOCH before the full pull, never after
const merge = fn('initialMerge');
const stamp = merge.indexOf('setLastSyncAt(SYNC_EPOCH)');
const pull = merge.indexOf('await pullChanges(SYNC_EPOCH)');
assert.ok(stamp >= 0 && pull >= 0 && stamp < pull, 'initialMerge: setLastSyncAt(SYNC_EPOCH) then await pullChanges(SYNC_EPOCH)');
assert.ok(!/setLastSyncAt\(new Date\(/.test(merge), 'initialMerge must not stamp the device time');
// #151: the push marks the batches that succeeded even when a later one failed
const push = fn('pushChanges');
assert.match(push, /const \{ results \} = await sendInBatches\(/);
const between = push.slice(push.indexOf('await sendInBatches('), push.indexOf('classifyOutbox(unsynced, results,'));
assert.ok(!/\breturn\b|results\.length|\bok\b/.test(between), 'pushChanges must classify the results of every successful batch');
assert.match(push, /\.where\(inArray\(syncOutbox\.id, markIds\)\);\s*\/\/[^\n]*\s*syncWidgetData\(\)/);
});
// --- Build toolchain guards ---
// A blanket `npm audit fix` (PR #118) once rewrote hundreds of lock entries:
// babel-preset-expo and @expo/metro-config lost their root hoisting and a

View file

@ -302,6 +302,14 @@ test('classifyOutbox: applied and duplicate marked, recent refusal kept, old ref
assert.deepEqual(c.droppedByType, { task: 1 });
});
test('classifyOutbox: an unknown status is neither marked nor counted as a refusal', () => {
const e = entry();
const c = classifyOutbox([e], [{ idempotencyKey: e.id, status: 'queued' }], NOW);
assert.deepEqual(c.markIds, []);
assert.equal(c.keptRefusals, 0);
assert.equal(c.droppedRefusals, 0);
});
test('classifyOutbox: an entry without a result is not marked', () => {
const sent = entry();
const unsent = entry();
@ -465,6 +473,13 @@ test('sendInBatches: a 429 with retryOn429 sleeps the bounded Retry-After and re
test('sendInBatches: a 429 is resent three times at most', async () => {
const t = transport([{ status: 429, retryAfter: 1, body: null }]);
// Guard: without the bound the loop never yields to a timer, so a test
// timeout would hang the suite instead of failing it (PR #159 review).
const post = t.post;
t.post = async (batch) => {
if (t.calls.length >= 10) throw new Error('unbounded 429 retries');
return post(batch);
};
const r = await sendInBatches(keys(10), opts(t, { retryOn429: true }));
assert.equal(r.ok, false);
assert.equal(t.calls.length, 1 + MAX_429_RETRIES);

View file

@ -10,7 +10,7 @@ import type { PGlite } from 'electric-sql-pglite';
const h = await vi.hoisted(async () => {
const { PGlite } = await import('electric-sql-pglite');
return { pg: new PGlite() as PGlite, userId: '' };
return { pg: new PGlite() as PGlite, userId: '', cleanups: 0 };
});
vi.mock('@/db/client', async () => {
@ -28,6 +28,18 @@ vi.mock('@/lib/api', async (importOriginal) => ({
vi.mock('@/lib/rateLimit', () => ({ rateLimit: () => null }));
// Real idempotency store, with its cleanup counted: the route must call it (#147).
vi.mock('@/lib/idempotency', async (importOriginal) => {
const mod = await importOriginal<typeof import('@/lib/idempotency')>();
return {
...mod,
createIdempotencyStore: (opts: Parameters<typeof mod.createIdempotencyStore>[0]) => {
const store = mod.createIdempotencyStore(opts);
return { ...store, cleanup: (now: number) => { h.cleanups++; store.cleanup(now); } };
},
};
});
const { POST } = await import('./route');
type Op = [entityType: string, action: string, entityId: string, data?: Record<string, unknown>];
@ -373,6 +385,31 @@ describe('POST /api/sync: inbox merge', () => {
expect(await row('select count(*)::int c from sl_tasks where list_id=$1', [otherInbox])).toEqual({ c: 0 });
});
it('keeps a task sent to an archived regular list in that list (only an archived inbox redirects)', async () => {
const { B, N } = await merged();
await h.pg.query('update sl_lists set deleted_at = now() where id=$1', [B.list]);
const id = u();
expect(await push(B.userId, [
['task', 'create', id, { title: 'late', listId: B.list }],
['task', 'update', B.task, { listId: B.list }],
])).toEqual(['applied', 'applied']);
expect(await listOf(id)).toBe(B.list);
expect(await listOf(B.task)).toBe(B.list);
expect(await listOf(B.task)).not.toBe(N);
});
it('redirects to the most recently created active inbox when there are several', async () => {
const { B, N } = await merged();
const X = u();
await h.pg.query(
"insert into sl_lists (id, user_id, name, is_inbox, created_at) values ($1, $2, 'Inbox', true, now() + interval '1 hour')",
[X, B.userId]);
const id = u();
expect(await push(B.userId, [['task', 'create', id, { title: 'late', listId: B.inbox }]])).toEqual(['applied']);
expect(await listOf(id)).toBe(X);
expect(await listOf(id)).not.toBe(N);
});
it('(g) creates only one new inbox per request', async () => {
const { B } = await seed();
const N1 = u();
@ -476,6 +513,12 @@ describe('POST /api/sync: bounded batches (#147)', () => {
expect(res.status).toBe(400);
});
it('cleans the idempotency store on every POST', async () => {
const before = h.cleanups;
expect(await push(`user-${u()}`, [['list', 'create', u(), { name: 'L', position: 0, isInbox: false }]])).toEqual(['applied']);
expect(h.cleanups).toBe(before + 1);
});
it('skips a replayed key without an error, for its account only', async () => {
const userId = `user-${u()}`;
const [op] = listOps(1);

View file

@ -16,6 +16,17 @@ describe('createIdempotencyStore', () => {
expect(s.seen('a', 'k', T0 + 1)).toBe(true);
});
it('moves a refreshed key to the newest end, so it is evicted last', () => {
const s = createIdempotencyStore({ ttlMs: TTL, maxPerAccount: 3 });
s.remember('a', 'k1', T0);
s.remember('a', 'k2', T0);
s.remember('a', 'k3', T0);
s.remember('a', 'k1', T0 + 1);
s.remember('a', 'k4', T0 + 2);
expect(s.seen('a', 'k1', T0 + 3)).toBe(true);
expect(s.seen('a', 'k2', T0 + 3)).toBe(false);
});
it('forgets a key after the TTL', () => {
const s = store();
s.remember('a', 'k', T0);