fix(server): take MAX+1 positions inside the transaction that inserts

Days, todo items, packing items and bags, packing template categories and
items, collections, collection labels and road-trip vias took their next
position as MAX(...) + 1 in one statement and inserted in the next, with
any other request free to run in between: two adds at once read the same
MAX and landed on the same position (the road-trip test pinned exactly
that duplicate). The read now sits in the transaction that inserts, and
the transaction holds the connection, so the second add waits and takes
the next position. A collection label's limit and name check move into
the same transaction, so two labels of one name added at once end in one
label and a 409.

Each site gets a test that adds several rows at once and reads back one
position each.
This commit is contained in:
Maurice
2026-10-08 15:35:36 +02:00
parent e015e5e5e8
commit 9dd2e1b983
10 changed files with 137 additions and 73 deletions
@@ -146,6 +146,23 @@ describe('collections CRUD + visibility', () => {
expect((await svc.listCollections(b.id)).collections).toHaveLength(0);
});
it('COLLECTIONS-SVC-001b: lists and labels created at the same time take one position each', async () => {
const a = createUser(testDb).user;
// Without the transaction every one read the same MAX and they shared a position.
const lists = await Promise.all(['A', 'B', 'C'].map((name) => svc.createCollection(a.id, { name })));
expect(lists.map((l) => l.sort_order).sort((x, y) => x - y)).toEqual([0, 1, 2]);
const labels = await Promise.all(['Food', 'Sights', 'Bars'].map((name) => svc.createLabel(a.id, lists[0].id, name)));
expect(labels.map((l) => l.sort_order).sort((x, y) => x - y)).toEqual([0, 1, 2]);
});
it('COLLECTIONS-SVC-001c: two labels of one name created at the same time: one lands, the other is a 409', async () => {
const a = createUser(testDb).user;
const list = await svc.createCollection(a.id, { name: 'Tokyo' });
const results = await Promise.allSettled([svc.createLabel(a.id, list.id, 'Food'), svc.createLabel(a.id, list.id, 'Food')]);
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
expect(results.find((r) => r.status === 'rejected')).toMatchObject({ reason: { status: 409 } });
});
it('COLLECTIONS-SVC-002: getCollection 404 for a non-member', async () => {
const a = createUser(testDb).user;
const b = createUser(testDb).user;
@@ -241,6 +241,16 @@ describe('create (service)', () => {
expect(d2.day_number).toBe(2);
});
it('DAY-SVC-009b: days added at the same time take one day number each', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Without the transaction both read the same MAX and both became day 1.
await Promise.all([svc.create(trip.id), svc.create(trip.id), svc.create(trip.id)]);
const numbers = (testDb.prepare('SELECT day_number FROM days WHERE trip_id = ? ORDER BY day_number').all(trip.id) as { day_number: number }[])
.map((d) => d.day_number);
expect(numbers).toEqual([1, 2, 3]);
});
it('DAY-SVC-010 — returns day with empty assignments array', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
@@ -224,6 +224,22 @@ function seedTemplate(userId: number, itemNames: string[]): number {
return templateId;
}
describe('template positions', () => {
it('PACK-SVC-002b: template categories and items added at the same time take one position each', async () => {
const { user } = createUser(testDb);
const templateId = seedTemplate(user.id, ['Tent']);
// seedTemplate's own category holds position 0 and its item position 0.
const categories = await Promise.all(['Kitchen', 'Sleep', 'Clothes'].map((name) => svc.createTemplateCategory(String(templateId), name)));
const catIds = categories.map((c) => (c as { category: { id: number } }).category.id);
expect((testDb.prepare('SELECT sort_order FROM packing_template_categories WHERE template_id = ? ORDER BY sort_order').all(templateId) as { sort_order: number }[])
.map((r) => r.sort_order)).toEqual([0, 1, 2, 3]);
await Promise.all(['Stove', 'Pot', 'Lighter'].map((name) => svc.createTemplateItem(String(templateId), String(catIds[0]), name)));
expect((testDb.prepare('SELECT sort_order FROM packing_template_items WHERE category_id = ? ORDER BY sort_order').all(catIds[0]) as { sort_order: number }[])
.map((r) => r.sort_order)).toEqual([0, 1, 2]);
});
});
describe('applyTemplate', () => {
it('PACK-SVC-003: adds template items to a trip packing list', async () => {
const { user } = createUser(testDb);
@@ -332,6 +348,18 @@ describe('createBag / deleteBag', () => {
expect(bag.name).toBe('Carry-On');
});
it('PACK-SVC-005b: bags and items created at the same time take one position each', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Without the transaction every one of them read the same MAX and landed on 0.
await Promise.all(['Carry-On', 'Checked', 'Daypack'].map((name) => svc.createBag(trip.id, { name })));
await Promise.all(['Tent', 'Stove', 'Mat'].map((name) => svc.createItem(trip.id, { name }, user.id)));
const orders = (table: string) => (testDb.prepare(`SELECT sort_order FROM ${table} WHERE trip_id = ? ORDER BY sort_order`).all(trip.id) as { sort_order: number }[])
.map((r) => r.sort_order);
expect(orders('packing_bags')).toEqual([0, 1, 2]);
expect(orders('packing_items')).toEqual([0, 1, 2]);
});
it('PACK-SVC-006: deleteBag removes the bag and returns true', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
@@ -326,15 +326,11 @@ describe('RoadtripService', () => {
expect(await service.tracksForTrip(f.tripA.id)).toEqual([]);
});
// R7 (Plan 3d Task 7 whole-plan review, item 12 — flag + pin, not fix, the
// MEMBERS-SVC-018 shape): `create`'s `nextSequence` (MAX(sequence)+1) READ
// and its `insertVia` WRITE are two separate statements with no lock
// between them. Measured under real concurrency (`Promise.allSettled`, no
// mocks): both calls succeed — there is no UNIQUE constraint to lose a
// race on, unlike `trip_members` — but both land on the SAME `sequence`
// (`0`), a genuine duplicate the un-serialized read-then-write leaves
// behind. Today's actual outcome, pinned; not a fix.
it('R7: two concurrent creates on the same leg both succeed but can land on the SAME sequence (unserialized nextSequence read)', async () => {
// R7: `create`'s `nextSequence` (MAX(sequence)+1) read and its `insertVia`
// write run in one transaction, which holds the connection, so two concurrent
// creates (`Promise.allSettled`, no mocks) take one sequence each. Before,
// both landed on sequence 0.
it('R7: two concurrent creates on the same leg both succeed and take consecutive sequences', async () => {
const results = await Promise.allSettled([
service.create(f.dayA1.id, { after_order_index: 0, lat: 1, lng: 1 }),
service.create(f.dayA1.id, { after_order_index: 0, lat: 2, lng: 2 }),
@@ -342,8 +338,7 @@ describe('RoadtripService', () => {
expect(results.every((r) => r.status === 'fulfilled')).toBe(true);
const rows = await service.listForDay(f.dayA1.id);
expect(rows).toHaveLength(2);
// Both landed on the same leg, at the same sequence — the duplicate R7 flags.
expect(rows.map((r) => r.after_order_index)).toEqual([0, 0]);
expect(rows.map((r) => r.sequence)).toEqual([0, 0]);
expect(rows.map((r) => r.sequence).sort((a, b) => a - b)).toEqual([0, 1]);
});
});
@@ -128,6 +128,16 @@ describe('listItems and createItem', () => {
expect(b.sort_order).toBe(a.sort_order + 1);
});
it('TODO-SVC-006b: items created at the same time still take one position each', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Without the transaction both read the same MAX and both landed on 0.
await Promise.all(['A', 'B', 'C'].map((name) => svc.createItem(trip.id, { name })));
const orders = (testDb.prepare('SELECT sort_order FROM todo_items WHERE trip_id = ? ORDER BY sort_order').all(trip.id) as { sort_order: number }[])
.map((r) => r.sort_order);
expect(orders).toEqual([0, 1, 2]);
});
it('TODO-SVC-007: createItem stores optional fields', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);