Retain deadlock: the co-occurrence flush locks entities out of id order against release_entity_postings

Aperta
#7,216 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
58/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
postgresql, python
Ambito
backend, databases

Direzione di ricerca

Read engine/memories/pg/entity_resolver.py at EntityResolver.flush_pending_stats and compare its lock order with release_entity_postings in engine/db/ops_postgresql.py. The issue’s two-session PostgreSQL 16 reproduction shows the deadlock and a sorted FOR KEY SHARE query that avoids it. Confirm the batch locks entities in ascending id order in the upsert transaction, then rerun that reproduction and check that it completes without a deadlock.

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

Descrizione

core
Bug Description

Two retains into one bank deadlock between the co-occurrence flush of one and the posting release of the other.

  • EntityResolver.flush_pending_stats (engine/memories/pg/entity_resolver.py) upserts entity_cooccurrences with executemany, sorted by (entity_id_1, entity_id_2). Each new row takes FOR KEY SHARE on both entities rows through the foreign keys. Sorted pairs do not give ascending entity ids: (a, d), (b, c) locks a, d, b, c.
  • release_entity_postings (engine/db/ops_postgresql.py), reached from a delta retain through chunk_storage.delete_chunks_by_ids → enqueue_entity_prune_candidates, takes FOR UPDATE on the same entities rows in ascending id order.

The flush holds d and waits for c; the release holds c and waits for d.

Steps to Reproduce

The two statements in two sessions, on postgres:16, with only the keys and columns they touch:

docker run -d --rm --name cooc -e POSTGRES_PASSWORD=pw postgres:16 >/dev/null; sleep 4
psql() { docker exec -i cooc psql -U postgres -q "$@"; }
psql <<'SQL'
CREATE TABLE entities (id uuid PRIMARY KEY, bank_id text, mention_count int);
CREATE TABLE entity_cooccurrences (
  entity_id_1 uuid REFERENCES entities, entity_id_2 uuid REFERENCES entities,
  cooccurrence_count int, PRIMARY KEY (entity_id_1, entity_id_2));
INSERT INTO entities SELECT ('00000000-0000-0000-0000-00000000000' || c)::uuid, 'b', 5 FROM unnest('{a,b,c,d}'::text[]) c;
SQL
a=00000000-0000-0000-0000-00000000000a b=${a%a}b c=${a%a}c d=${a%a}d
# retain 1: flush_pending_stats, pairs (a,d) then (b,c)
psql -c "BEGIN;
  INSERT INTO entity_cooccurrences VALUES ('$a','$d',1) ON CONFLICT (entity_id_1, entity_id_2) DO UPDATE SET cooccurrence_count = entity_cooccurrences.cooccurrence_count + 1;
  SELECT pg_sleep(1);
  INSERT INTO entity_cooccurrences VALUES ('$b','$c',1) ON CONFLICT (entity_id_1, entity_id_2) DO UPDATE SET cooccurrence_count = entity_cooccurrences.cooccurrence_count + 1;
  COMMIT;" &
sleep 0.3
# retain 2: release_entity_postings for c and d
psql -c "BEGIN;
  UPDATE entities e SET mention_count = GREATEST(e.mention_count - v.n, 0)
  FROM (SELECT l.id, d.n FROM entities l JOIN unnest('{$c,$d}'::uuid[], '{1,1}'::bigint[]) AS d(id, n) ON d.id = l.id
        WHERE l.bank_id = 'b' ORDER BY l.id FOR UPDATE OF l) v
  WHERE e.id = v.id;
  SELECT pg_sleep(1.5); COMMIT;" &
wait; docker rm -f cooc >/dev/null

Output: ERROR: deadlock detected ... while locking tuple (0,4) in relation "entities".

With SELECT id FROM entities WHERE id = ANY('{a,b,c,d}') ORDER BY id FOR KEY SHARE as the first statement of the flush transaction, the same script completes without a deadlock.

Expected Behavior

The flush takes its entity locks in ascending id order, as the release and restore_entity_postings do. For example, lock every entity id of the batch in one sorted FOR KEY SHARE statement, in the same transaction as the upsert.

Actual Behavior

34 deadlocks of this pair in two days in the PostgreSQL log of one bank, all between two retains:

Process A: UPDATE public.entities e SET mention_count = GREATEST(e.mention_count - v.n, 0) FROM ( SELECT l.id, d.n FROM public.entities l JOIN unnest($2::uuid[], $3::bigint[]) ... ORDER BY l.id FOR UPDATE OF l ) v WHERE e.id = v.id
Process B: INSERT INTO public.entity_cooccurrences (entity_id_1, entity_id_2, cooccurrence_count, last_cooccurred) VALUES ($1, $2, $3, $4) ON CONFLICT (entity_id_1, entity_id_2) DO UPDATE ...

The delta retain that loses fails its task:

orchestrator.py, line 4751, in _try_delta_retain
    delta_committed = await _run_delta_db_work()
orchestrator.py, line 4634, in _run_delta_db_work
    invalidated_obs = await chunk_storage.delete_chunks_by_ids(
chunk_storage.py, line 83, in delete_chunks_by_ids
    await enqueue_entity_prune_candidates(conn, bank_id, outgoing_unit_ids)
...
ops_postgresql.py, line 728, in release_entity_postings
asyncpg.exceptions.DeadlockDetectedError: deadlock detected

The worker retries the task, and the retry runs fact extraction again.

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.