delete(): Ctrl-C or end of input during a delete leaves its transaction open

Aberta Para iniciantes
#1,691 0 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 6 dias

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
2/5
Tempo estimado
1-3 horas
Facilidade para iniciantes
74/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
mysql, postgresql, python
Domínio
database

Direção de pesquisa

Comece em src/datajoint/table.py em Table.delete(), lendo o bloco que abre a transação, o prompt user_choice("Commit deletes?") e o try/except Exception existente que chama cancel_transaction(). Reproduza com o snippet de builtins.input com mock patch, depois amplie o manipulador para que KeyboardInterrupt e EOFError também façam rollback quando transaction ainda for True, relançando depois. Pronto significa que conn.in_transaction é False após a interrupção e que os testes de delete existentes continuam passando.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

bug

Summary

Table.delete() with prompt=True runs the deletes inside its transaction and then asks "Commit deletes?" (src/datajoint/table.py, the user_choice("Commit deletes?", default="no") call). The question is asked after the try/except Exception that rolls the transaction back on errors. If the user presses Ctrl-C at the prompt (KeyboardInterrupt), or input ends (EOFError, for example a script run without a terminal), nothing rolls the transaction back, and the connection stays in it.

The same happens for a KeyboardInterrupt during the delete loop, with or without the prompt, since except Exception does not catch it.

Reproduced on master with MySQL 8.0 and PostgreSQL 15.

Consequences

On the same connection afterwards:

  • delete(prompt=True) raises "Delete cannot use a transaction within an ongoing transaction".
  • delete(prompt=False) joins the stale transaction (it sets transaction=False when one is open), deletes the rows, logs "Delete completed", and returns their count. Inserts join it too.
  • None of this is committed. It is lost when the connection closes or the transaction rolls back, including the rollback done by the next with conn.transaction: block, which raises "Nested connections are not supported." Nothing tells the user. An explicit conn.commit_transaction() would instead commit the delete the user never confirmed.
  • The transaction holds the locks taken by the deletes until it ends. Another session that writes those rows waits and then fails with a lock timeout (MySQL error 1205, PostgreSQL LockNotAvailable).

Reproduce

import datajoint as dj
from unittest import mock

schema = dj.Schema("delete_prompt_demo")

@schema
class Subject(dj.Manual):
    definition = """
    subject_id : int32
    """

Subject.insert([(1,), (2,), (3,)])
conn = Subject.connection

with mock.patch("builtins.input", side_effect=KeyboardInterrupt):
    try:
        (Subject & {"subject_id": 1}).delete(prompt=True)
    except KeyboardInterrupt:
        pass
print(conn.in_transaction)  # True: the transaction is still open

print((Subject & {"subject_id": 2}).delete(prompt=False))  # joins it: 1
conn.close()
conn.connect()
print(Subject.fetch("subject_id"))  # [1 2 3]: neither delete was committed

Fix

Roll back on any exit other than a confirmed commit: wrap the delete loop and the prompt in try/except BaseException (or finally) that calls cancel_transaction() when delete() opened the transaction and did not commit, then re-raises. transaction is still True at that point only when delete() opened the transaction itself, so it is the right guard.

Linguagem predominante
Python
Estrelas
198
Forks
103
Merge médio
6d 1h
PRs com merge (30d)
10

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de datajoint/datajoint-python

Todas as issues de datajoint/datajoint-python

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.