Retain deadlock: the co-occurrence flush locks entities out of id order against release_entity_postings
Nobody has claimed this yet.
Assessment
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Newbie friendliness
- 58/100
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
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) upsertsentity_cooccurrenceswithexecutemany, sorted by(entity_id_1, entity_id_2). Each new row takesFOR KEY SHAREon bothentitiesrows through the foreign keys. Sorted pairs do not give ascending entity ids:(a, d), (b, c)locksa, d, b, c.release_entity_postings(engine/db/ops_postgresql.py), reached from a delta retain throughchunk_storage.delete_chunks_by_ids→enqueue_entity_prune_candidates, takesFOR UPDATEon the sameentitiesrows 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
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from vectorize-io/hindsight
-
core
Difficulty 2/5 1-3 hours Newbie friendliness 70/100
vectorize-io/hindsight#7254 ·
-
Control Plane shows different calendar dates for the same occurrence in Constellation and TimelineOpencore
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
vectorize-io/hindsight#7240 · 1 comment ·
-
core
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
vectorize-io/hindsight#7233 ·
-
core
Difficulty 2/5 1-3 hours Newbie friendliness 79/100
vectorize-io/hindsight#7231 ·
-
core
Difficulty 2/5 1-3 hours Newbie friendliness 83/100
vectorize-io/hindsight#7228 · 1 comment ·
All issues in vectorize-io/hindsight
Similar issues
-
Test: to_hijri() accepts datetime.datetime and uses only the date partPossibly taken A pull request linked to this issue is open or already merged. Opengood first issue
Difficulty 1/5 Under an hour Newbie friendliness 95/100
omarelshamy25x/shamy-hijri#63 · 3 comments ·
Maintainers usually reply within 1 day
-
polish
Difficulty 2/5 1-3 hours Newbie friendliness 84/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
521xueweihan/HelloGitHub#4729 ·
-
[Bug]: Score parser reads parts of scientific notation as valid scoresPossibly taken @AshutoshSingh840 claimed this today. Open
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
UKGovernmentBEIS/control-arena#992 ·
Maintainers usually reply within 3 days
-
Difficulty 1/5 Under an hour Newbie friendliness 92/100
mvalentsev/awesome-free-ai-coding#70 ·
Maintainers usually reply within 1 day