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

Open
#7,217 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
55/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
postgresql, python
Domain
backend, databases

Research direction

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.

Written by the indexing model from the issue text.

Description

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)

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.