Retain deadlock: replacing a document deletes its memory units in scan order against link inserts

Aperta
#7,217 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
55/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
postgresql, python
Ambito
backend, databases

Direzione di ricerca

Start with writes.delete_document, delete_stale_observations, bulk_insert_links, and the graph relink path identified in the issue; trace how each statement acquires locks on memory_units. Reproduce the deadlock using PostgreSQL 16 and the supplied SQL steps. Done means replacing a document and linking to its memories serialize without deadlocks, including through graph maintenance.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

core
Bug Description

A retain that replaces a document deadlocks against a concurrent writer that links new memories to that document's memories.

  • The replace path deletes the old units with writes.delete_document: DELETE FROM memory_units WHERE document_id = $1 AND bank_id = $2. The DELETE takes its row locks in scan order. The sweep before it (delete_stale_observations) locks the same rows in id order, but FOR NO KEY UPDATE, which does not conflict with FOR KEY SHARE, so it does not order the DELETE's lock.
  • Link writers (bulk_insert_links, from a retain's link phase and from the graph-maintenance relink) lock their target units with WITH locked AS (SELECT id FROM memory_units WHERE id = ANY($7::uuid[]) ORDER BY id FOR KEY SHARE) INSERT INTO memory_links .... A retain inserts semantic, temporal, causal and entity links in separate statements, so across one transaction its FOR KEY SHARE locks are not in one id order either.

A linker that holds KEY SHARE on one unit of the document and then needs another unit that the DELETE has already removed waits for the replace, while the DELETE waits for that first unit.

Steps to Reproduce

On postgres:16, with only the keys and columns the statements touch. Document X has units 1 and 2, 2 stored first, so the scan meets it first:

docker run -d --rm --name repl -e POSTGRES_PASSWORD=pw postgres:16 >/dev/null; sleep 4
psql() { docker exec -i repl psql -U postgres -q "$@"; }
u=00000000-0000-0000-0000-00000000000
psql <<SQL
CREATE TABLE memory_units (id uuid PRIMARY KEY, bank_id text, document_id text);
CREATE INDEX ON memory_units (document_id);
CREATE TABLE memory_links (from_unit_id uuid REFERENCES memory_units ON DELETE CASCADE,
  to_unit_id uuid REFERENCES memory_units ON DELETE CASCADE, PRIMARY KEY (from_unit_id, to_unit_id));
INSERT INTO memory_units VALUES ('${u}2','b','X'), ('${u}1','b','X'), ('${u}9','b','Y');
SQL
# retain R replaces X: the sweep's ordered NO KEY UPDATE pass, then delete_document
psql -c "BEGIN;
  SELECT id FROM memory_units WHERE bank_id = 'b' AND id = ANY('{${u}1,${u}2}') ORDER BY id FOR NO KEY UPDATE;
  SELECT pg_sleep(0.6);
  DELETE FROM memory_units WHERE document_id = 'X' AND bank_id = 'b';
  SELECT pg_sleep(1.5); COMMIT;" &
sleep 0.3
# retain L links Y's unit to X's units in two link statements
psql -c "BEGIN;
  WITH locked AS (SELECT id FROM memory_units WHERE id = '${u}1' FOR KEY SHARE)
  INSERT INTO memory_links SELECT '${u}9', id FROM locked;
  SELECT pg_sleep(0.6);
  WITH locked AS (SELECT id FROM memory_units WHERE id = ANY('{${u}1,${u}2}') ORDER BY id FOR KEY SHARE)
  INSERT INTO memory_links SELECT '${u}9', id FROM locked ON CONFLICT DO NOTHING;
  COMMIT;" &
wait; docker rm -f repl >/dev/null

Output: ERROR: deadlock detected ... while deleting tuple (0,2) in relation "memory_units".

Expected Behavior

Replacing a document and linking to its memories serialize instead of deadlocking. For example, a link writer locks every unit it will link to in one sorted statement before its first link insert, and the replace deletes the old units in id order with the lock mode the DELETE needs.

Actual Behavior

In two days of the PostgreSQL log of one bank: 43 deadlocks between DELETE FROM public.memory_units WHERE document_id = $1 AND bank_id = $2 and the memory_links insert, 6 between the chunk delete and the memory_links insert, 4 between DELETE FROM public.documents ... and the memory_links insert. In the worker log, 31 graph-maintenance tasks failed in two days with the same deadlock at:

graph.py, line 851, in _relink_batch
links.py, line 197, in _bulk_insert_links
ops_postgresql.py, line 402, in bulk_insert_links
asyncpg.exceptions.DeadlockDetectedError: deadlock detected

The replacing retain also waits up to HINDSIGHT_API_DB_COMMAND_TIMEOUT (60 s) on SELECT id FROM memory_units ... ORDER BY id FOR NO KEY UPDATE and fails with TimeoutError: 43 such task failures in one day.

Version

1.3.1, PostgreSQL 16 (Cloud SQL), two workers, HINDSIGHT_API_RETAIN_MAX_CONCURRENT=4.

LLM Provider

Gemini (Vertex AI)

Lingua principale
Python
Stelle
45.2k
Fork
5.9k
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di vectorize-io/hindsight

Tutte le issue di vectorize-io/hindsight

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.