fix(sync): lock the task row first in every link write

764d833 made link creates lock the task row before inserting, but link
removals (POST /api/sync taskTag delete, DELETE /api/tasks/[id]/tags/
[tagId]) still deleted the link before touching the task. With the link
already present, a create and a removal took the two locks in opposite
orders and Postgres aborted one (40P01).

lockTaskForLinks (lib/taskDelete.ts) states one rule: every transaction
that writes an sl_task_tags link for a task locks that task's row first,
FOR NO KEY UPDATE. The four link paths now call it; deleteTask already
starts with the task row update. REVIEW.md gets the rule. A tag delete
keeps its tag-first order (left as is by the review).

Replayed on a real Postgres (embedded-postgres, outside the repo), link
removal against a create of the same existing link: old order -> one
40P01 in each order; task row first -> both applied. Earlier scenarios
(two creates, link vs task delete) unchanged.

Refs #196

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-11-08 12:38:07 -05:00
commit 46d29241a2
5 changed files with 32 additions and 17 deletions

View file

@ -114,7 +114,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
- Une suppression côté serveur est un soft-delete (`deletedAt`), relayé à l'app par le pull. — `web/src/app/api/sync/route.ts`
- Le pull garde le `createdAt` local d'une ligne existante, et le `calendarEventId` d'une tâche (colonne absente du serveur). — `src/services/syncRules.ts` (`pulled*Values`), #149
- Dans un pull depuis `SYNC_EPOCH` (première sync, ou après une déconnexion qui remet `lastSyncAt` à null), une liste ou une tâche locale strictement plus récente que le serveur est gardée et remise dans l'outbox (`queueOutboxEntry`, action `update`, écrite même sync éteinte : la première sync tourne avant l'activation, #165). Jamais une étiquette : l'app ne garde pas de date de modification pour les étiquettes, donc un renommage hors connexion d'étiquette reste perdu face au serveur (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149, #181
- Une étiquette a un `updatedAt` serveur (migration `0003_tag_updated_at`, rempli par `created_at` pour les lignes existantes) : `GET /api/sync` la tire sur `updatedAt >= since` et renvoie `updated_at` = `updatedAt`. Toute écriture d'une étiquette (`PUT`/`DELETE /api/tags/[id]`, `tag update`/`tag delete` de `POST /api/sync`) avance `updatedAt`. La suppression d'une étiquette retire ses liens `sl_task_tags` et avance `updatedAt` des tâches touchées dans la même transaction, pour que l'app réaligne leurs liens. La suppression d'une tâche (`task delete` de `POST /api/sync`, `DELETE /api/tasks/[id]`) passe par `deleteTask` : dans une transaction, la tâche et ses sous-tâches actives du même compte, sur un seul niveau, reçoivent `deletedAt`, et les liens de la tâche et de ses sous-tâches sont retirés. Un lien créé vers une tâche ou une étiquette supprimée n'est jamais écrit : `taskTag create` répond `applied`, `POST /api/tasks/[id]/tags` écarte les étiquettes supprimées et répond 404 pour une tâche supprimée ; la vérification se fait dans la transaction de l'écriture (`FOR SHARE`). La sonde attend 0 au contrôle 3 (`lien_tache_supprimee`). — `web/src/db/schema.ts`, `web/src/app/api/sync/route.ts`, `web/src/app/api/tags/[id]/route.ts`, `web/src/lib/taskDelete.ts`, `web/src/app/api/tasks/[id]/route.ts`, `web/src/app/api/tasks/[id]/tags/route.ts`, `web/src/db/migrations/0004_cleanup_deleted_task_links.sql`, `web/src/app/api/sync/route.test.ts`, #181, #196
- Une étiquette a un `updatedAt` serveur (migration `0003_tag_updated_at`, rempli par `created_at` pour les lignes existantes) : `GET /api/sync` la tire sur `updatedAt >= since` et renvoie `updated_at` = `updatedAt`. Toute écriture d'une étiquette (`PUT`/`DELETE /api/tags/[id]`, `tag update`/`tag delete` de `POST /api/sync`) avance `updatedAt`. La suppression d'une étiquette retire ses liens `sl_task_tags` et avance `updatedAt` des tâches touchées dans la même transaction, pour que l'app réaligne leurs liens. La suppression d'une tâche (`task delete` de `POST /api/sync`, `DELETE /api/tasks/[id]`) passe par `deleteTask` : dans une transaction, la tâche et ses sous-tâches actives du même compte, sur un seul niveau, reçoivent `deletedAt`, et les liens de la tâche et de ses sous-tâches sont retirés. Un lien créé vers une tâche ou une étiquette supprimée n'est jamais écrit : `taskTag create` répond `applied`, `POST /api/tasks/[id]/tags` écarte les étiquettes supprimées et répond 404 pour une tâche supprimée ; la vérification se fait dans la transaction de l'écriture. Toute transaction qui écrit un lien `sl_task_tags` pour une tâche verrouille d'abord la ligne de cette tâche (`lockTaskForLinks`, `FOR NO KEY UPDATE`), avant toute autre ligne : un autre ordre fait s'interbloquer deux écritures simultanées (`40P01`), ce qu'aucun test PGlite ne voit (une seule connexion). La sonde attend 0 au contrôle 3 (`lien_tache_supprimee`). — `web/src/db/schema.ts`, `web/src/app/api/sync/route.ts`, `web/src/app/api/tags/[id]/route.ts`, `web/src/lib/taskDelete.ts`, `web/src/app/api/tasks/[id]/route.ts`, `web/src/app/api/tasks/[id]/tags/route.ts`, `web/src/app/api/tasks/[id]/tags/[tagId]/route.ts`, `web/src/db/migrations/0004_cleanup_deleted_task_links.sql`, `web/src/app/api/sync/route.test.ts`, #181, #196
- Après la fusion de la première sync, `initialMerge` tire tout le serveur depuis `SYNC_EPOCH` ; `lastSyncAt` est posé à cette date avant le pull, pour qu'un pull raté se rejoue au `fullSync` suivant (#150). — `src/services/syncClient.ts`, `src/services/syncRules.ts` (`mergeTaskData`)
- Une suppression serveur s'applique toujours, même sur une ligne locale plus récente : le protocole n'a pas de restauration. — `src/services/syncClient.ts`, #149
- `src/services/syncRules.ts` reste sans import, pour que `tests/syncRules.test.mjs` le charge par le type stripping de Node (check smoke `syncRules.ts stays import-free`). `src/services/syncSchedule.ts` et `src/services/syncTrigger.ts` suivent la même règle pour `tests/syncSchedule.test.mjs`, et `src/services/syncSocket.ts` pour `tests/syncSocket.test.mjs` (check smoke `syncSchedule.ts, syncTrigger.ts and syncSocket.ts stay import-free`). — `tests/smoke.test.cjs`, `tests/syncRules.test.mjs`, `tests/syncSchedule.test.mjs`, `tests/syncSocket.test.mjs`, #149, #178, #175

View file

@ -7,7 +7,7 @@ import { rateLimit } from '@/lib/rateLimit';
import { syncPushSchema, type SyncOperation } from '@/lib/validators';
import { createIdempotencyStore } from '@/lib/idempotency';
import { notifyUserChanged } from '@/lib/ws';
import { deleteTask } from '@/lib/taskDelete';
import { deleteTask, lockTaskForLinks } from '@/lib/taskDelete';
import {
listCreateData,
listUpdateData,
@ -368,15 +368,14 @@ async function processOperation(op: SyncOperation, userId: string, ctx: RequestC
// A link change moves the task's updatedAt: GET /api/sync then sends
// the task with the whole set of its links (#180)
await db.transaction(async (tx) => {
if (action !== 'create' && action !== 'delete') return;
// Task row first, for both actions (lock rule in lib/taskDelete.ts)
const task = await lockTaskForLinks(tx, entityId);
if (action === 'create') {
// A link to a deleted task or tag (a device offline while it was
// deleted elsewhere) is dropped without a refusal: `applied`, nothing
// written (#196). The row locks wait for a concurrent delete, which
// updates these rows, so the check cannot miss it. The task row takes
// FOR NO KEY UPDATE, the lock of the updatedAt write below: FOR SHARE
// would deadlock two link writes on the same task.
const [task] = await tx.select({ deletedAt: slTasks.deletedAt }).from(slTasks)
.where(eq(slTasks.id, entityId)).for('no key update');
// written (#196). The row locks wait for a concurrent delete, so the
// check cannot miss it.
const [tag] = await tx.select({ deletedAt: slTags.deletedAt }).from(slTags)
.where(eq(slTags.id, tagId)).for('share');
if (task?.deletedAt || tag?.deletedAt) return;
@ -386,8 +385,6 @@ async function processOperation(op: SyncOperation, userId: string, ctx: RequestC
} else if (action === 'delete') {
await tx.delete(slTaskTags)
.where(and(eq(slTaskTags.taskId, entityId), eq(slTaskTags.tagId, tagId)));
} else {
return;
}
await tx.update(slTasks)
.set({ updatedAt: now })

View file

@ -5,6 +5,7 @@ import { eq, and } from 'drizzle-orm';
import { requireAuth } from '@/lib/api';
import { rateLimit } from '@/lib/rateLimit';
import { notifyUserChanged } from '@/lib/ws';
import { lockTaskForLinks } from '@/lib/taskDelete';
export async function DELETE(
_request: Request,
@ -28,8 +29,10 @@ export async function DELETE(
}
// Remove the link and move the task's updatedAt: GET /api/sync then sends
// the task with the whole set of its links, without this one (#180)
// the task with the whole set of its links, without this one (#180). Task
// row first (lock rule in lib/taskDelete.ts, #196).
await db.transaction(async (tx) => {
await lockTaskForLinks(tx, taskId);
await tx
.delete(slTaskTags)
.where(and(eq(slTaskTags.taskId, taskId), eq(slTaskTags.tagId, tagId)));

View file

@ -6,6 +6,7 @@ import { requireAuth, parseBody } from '@/lib/api';
import { rateLimit } from '@/lib/rateLimit';
import { notifyUserChanged } from '@/lib/ws';
import { assignTagsSchema } from '@/lib/validators';
import { lockTaskForLinks } from '@/lib/taskDelete';
export async function POST(
request: Request,
@ -45,13 +46,11 @@ export async function POST(
// then sends the task with the whole set of its links (#180). Deleted tags
// are dropped from the insert without an error, and with none left nothing
// is written (#196). The row locks wait for a concurrent delete of the task
// or a tag, which updates these rows, so a row deleted meanwhile is seen.
// The task row takes FOR NO KEY UPDATE, the lock of the updatedAt write
// below: FOR SHARE would deadlock two link writes on the same task.
// or a tag, so a row deleted meanwhile is seen. Task row first (lock rule in
// lib/taskDelete.ts).
const written = await db.transaction(async (tx) => {
const [live] = await tx.select({ id: slTasks.id }).from(slTasks)
.where(and(eq(slTasks.id, taskId), isNull(slTasks.deletedAt))).for('no key update');
if (!live) return false;
const live = await lockTaskForLinks(tx, taskId);
if (!live || live.deletedAt) return false;
const liveTags = await tx.select({ id: slTags.id }).from(slTags)
.where(and(inArray(slTags.id, body.data.tagIds), isNull(slTags.deletedAt))).for('share');
if (liveTags.length === 0) return false;

View file

@ -2,6 +2,22 @@ import { db } from '@/db/client';
import { slTasks, slTaskTags } from '@/db/schema';
import { eq, and, or, isNull, inArray } from 'drizzle-orm';
type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
// Lock rule for sl_task_tags (#196): every transaction that writes a link for
// a task locks that task's row first, FOR NO KEY UPDATE (the lock its
// updatedAt write takes anyway). Writers then queue on the task row in one
// order and cannot deadlock each other: two link creates, a create and a
// delete of the same link, or a link write and deleteTask (whose first
// statement updates the task row). The lock also waits for a concurrent
// delete, so the deletedAt it returns is current. A tag delete still takes the
// tag first, then the linked tasks; that rarer order is left as is.
export async function lockTaskForLinks(tx: Tx, taskId: string) {
const [task] = await tx.select({ deletedAt: slTasks.deletedAt }).from(slTasks)
.where(eq(slTasks.id, taskId)).for('no key update');
return task;
}
// Soft-delete a task with its subtasks and drop every tag link they hold, in
// one transaction (#196). Shared by POST /api/sync `task delete` and
// DELETE /api/tasks/[id], so that both paths stay the same.