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

Open
#7,216 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
58/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
postgresql, python
Domain
backend, databases

Research direction

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.

Written by the indexing model from the issue text.

Description

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)

Dominant language
Python
Stars
45.2k
Forks
5.9k
PR merge metrics
No merged PRs in 30d

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from vectorize-io/hindsight

All issues in vectorize-io/hindsight

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.