Cascading delete should remove whole master–part composites or refuse before deleting anything

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

Mantenedores costumam responder em até 5 dias

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
48/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
mysql, postgresql, python, sql
Domínio
backend, databases

Direção de pesquisa

Start with src/datajoint/table.py, especially the delete path, then inspect cascade planning in src/datajoint/diagram.py. Use the scenarios in tests/integration/test_cascade_integrity.py and tests/integration/test_cascade_delete.py to reproduce behavior before changing code. Done means deletes either remove each complete master-part set atomically or refuse before any row is deleted, with the specified transaction and concurrency cases covered.

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

Descrição

A delete has two acceptable outcomes: it removes every master row it reaches together with all of that master's part rows and their dependents, in one transaction, or it refuses before any row is deleted. No committed state holds a master with some of its parts missing. The Master-Part specification, §2.1 "Compositional Integrity", states why a pipeline author depends on this: "a dependency on the master is a dependency on all of its parts." A make() that reads a master's parts assumes the set is complete, so a delete that commits a partial set leaves downstream results computed from inputs that no longer exist, with no error and nothing on the master row to show it.

The first item is reproduced in #1760. The others were read, not run: each comes from master at b2994e5e and the docs at b68b6cc6, and each carries a sketch to turn into a failing test before the fix.

Open work this builds on: #1760 (row-level enforce), #1719 with #1728 (parts in schemas whose names contain non-word characters), #1620 (owned parts), #1637 with datajoint/datajoint-docs#249 (traversal planner, v2.4), #1496 (delete-time materialization), #1682 (the transaction stays open while the prompt waits).

Deletes that commit a master with some of its parts missing

  • Default part_integrity="enforce" commits a delete that removes some of a master's parts whenever the cascade also deletes other rows of the master table. Tracked in #1760.

    • Where: the check runs after the deletes and compares table names (src/datajoint/table.py:1211-1214). tests/integration/test_cascade_integrity.py:43 pins only the case where the master table loses no rows.
    • Change: before the first DELETE, refuse when a master row that stays owns a part row in the cascade, and name those master rows; remove the post-check. Compatibility: breaking for deletes that commit a partial set today, which start raising. No API change.
    • Test first: the reproduction in #1760.
  • part_integrity="cascade" extends a part to its masters once, at the first foreign key that reaches the part. Part rows reached by a later foreign key are deleted and their masters stay. No check runs in this mode (table.py:1211). #1484 made every part of a master contribute its master rows; this is one part reached by a second foreign key.

    • Where: src/datajoint/diagram.py:899-907 skips a (part, master) pair already visited (set at :835), and the master keys were read into literals at the first visit (:1149-1163). tests/integration/test_cascade_delete.py:493 gives each part one outside reference, never two.
    • Change: repeat the part-to-master step whenever a part's restriction grows, until no master gains rows, then run the row-level test of #1760 as a final assertion. Compatibility: none; the deletes affected leave partial sets today.
    • Test first (read, not run): Ext(ext_id); Master(master_id) with part P: -> master, -> Ext.proj(src="ext_id"), -> Ext.proj(dst="ext_id"); rows P(1, src=1, dst=2), P(2, src=2, dst=1); (Ext & {"ext_id": 1}).delete(prompt=False, part_integrity="cascade"). Expected: both masters deleted. By reading: both part rows are deleted and one master stays with no parts.
  • delete(transaction=False) with no transaction open commits each table's delete on its own, and the enforce refusal is raised after the rows are gone.

    • Where: table.py:1169-1180 opens a transaction only when transaction is true and never checks that one is open; connections autocommit (adapters/mysql.py:160, adapters/postgres.py:200); the per-table deletes at :1187 precede the raise at :1211-1221, which rolls back only if transaction. The same order applies after the silent downgrade inside a caller's transaction (:1172-1174). No test passes transaction=False. datajoint/datajoint-docs#312 (open) documents today's behavior: each DELETE takes effect as it runs and delete() does not roll it back. This item makes an open transaction a precondition.
    • Change: raise when transaction=False and not conn.in_transaction. With the pre-check of #1760, a refusal precedes every delete on both paths. Compatibility: deprecation path, one release of DeprecationWarning, then breaking for scripts that pass transaction=False outside a transaction.
    • Test first (read, not run): the tables of test_enforce_postcheck_raises_and_rolls_back; (Ext & {"ext_id": 1}).delete(prompt=False, transaction=False). Expected: refused, three rows in place. By reading: DataJointError is raised and the Ext row and the part row are deleted.
  • Part.delete_quick() deletes part rows with no master check, and part_integrity="ignore" is documented as an ordinary option with recommended use cases. Both leave a master with a partial set.

    • Where: Part overrides delete, drop, and alter only (src/datajoint/user_tables.py:217-262); delete_quick (table.py:1096-1111) is callable on the class (user_tables.py:52). "ignore" docstrings: table.py:1143, user_tables.py:224. tests/integration/test_cascading_delete.py:41 pins ignore.
    • Change: keep ignore as a repair that sits outside the integrity guarantees, said so in docstrings and docs, with a warning when it is used. Add Part.delete_quick that warns, and in the next minor raises unless part_integrity="ignore" is passed. The cascade is unaffected: it calls delete_quick on FreeTable objects (table.py:1187). Part.drop(part_integrity="ignore") (user_tables.py:253-254) drops the whole part table and is the recovery path #1620 names: document it as a schema change, no code change. Compatibility: none for docs and warnings; deprecation path for the raise.
    • Test first (read, not run): (Master.P & key).delete_quick(). Expected: the refusal Master.P.delete() gives. By reading: the row is deleted and the master stays.
  • The part-to-master step follows the shortest foreign-key path, which need not be the reference that makes the part belong to its master. A part that belongs through a sibling part with renamed attributes and also references a second master row gets the referenced master deleted and its own master left with a partial set.

    • Where: diagram.py:1093 (nx.shortest_path), and _edge_props returns the first of parallel foreign keys (:1189-1192); neither filters on the primary flag (src/datajoint/dependencies.py:208). The cascade spec lists the single path under Limitations. test_cascade_integrity.py:118 pins a step through a secondary -> master. #1525 proposed walking every path and was closed unmerged in favor of the 2.4 planner's lift through the part's owning attributes (#1637). Walking every path would still delete master 2 in the sketch below, so the walk has to follow the owning reference alone.
    • Change: walk only primary-key foreign keys inside the master's group, using owned_parts from #1620, and prefer the primary edge among parallel ones. Compatibility: none for parts whose primary key references the master; the pinned secondary-reference case changes with the owned-part rule of #1620, on its deprecation path.
    • Test first (read, not run): Master(master_id); part A: -> master, a : int32; part B: -> Master.A.proj(m="master_id", a_ref="a"), b : int32, ---, -> master.proj(other="master_id"); rows Master 1 and 2, A(1, 10), B(m=1, a_ref=10, b=100, other=2); (Master.B & {"b": 100}).delete(prompt=False, part_integrity="cascade"). Expected: master 1 deleted whole, master 2 kept. By reading: master 2 is deleted and master 1 keeps A(1, 10) without its B row.
  • The cascade is planned before the delete's transaction starts, so rows committed by another session between the plan and the DELETE are deleted in part. Concurrent writers only.

    • Where: table.py:1158 builds the diagram; the transaction starts at :1171. The plan reads master keys (diagram.py:1154) and a dj.Top or subquery seed (diagram.py:186-187) into literals, while part restrictions are evaluated at DELETE time.
    • Change: start the transaction, then plan, and run the row-level test immediately before the first DELETE in every mode except "ignore". This narrows the window to the transaction's isolation level; closing it needs a locking read of the restricted part rows. The prompt keeps its place before the commit, as decided on #1682 (closing comment on #1683), so the rows confirmed are the rows committed; the transaction then also stays open while the plan is built. Compatibility: none.
    • Test first (read, not run): two connections; Ext, Master.P (-> master, -> Ext), rows Master 1, P(1, 1). Connection 1 runs (Ext & {"ext_id": 1}).delete(prompt=False, part_integrity="cascade") with Diagram.cascade patched to pause on return; connection 2 commits Master 2 with P(2, 1); connection 1 resumes. Expected: master 2 deleted with its part, or the delete refused. By reading: P(2, 1) is deleted and master 2 stays.

Docs that change with this

Statements that are stale against shipped code and need no code change:

  • Cascade specification, "Forward propagation": rule F1's trigger reads parent_attrs ⊆ child_pk (cascade.md:36); the code requires the restricted attributes to be carried by the foreign key and the foreign key to lie in the child's primary key (diagram.py:943). The Diagram specification, "Restriction Propagation", repeats the old Rule 1 (diagram.md:270), and its Rule 3 says "projected (all attributes)" (:274) where the code projects to the primary key (diagram.py:964).
  • Cascade specification, "Upward propagation" and Example 2: the part-to-master walk is said to apply U1, copying the part's condition (cascade.md:82, :183-184). The code never copies on this walk (diagram.py:1132-1142, pinned by tests/integration/test_cascade_overdelete.py:215), because the copy deletes masters that have no matching part (#1591). Rewrite Example 2 with U3 at both edges.
  • Cascade specification, "Walking the FK path": intermediate parts are said to be restricted along the way (cascade.md:96); the code restores them after the walk (diagram.py:1102-1106, :1170-1178).
  • Master-Part specification, §4.5 (master-part.md:238): its contradiction with §7.4 is tracked in #1768. The rewrite says when a further round occurs: the dependents of a master pulled into the cascade include a part of another master.

Statements that change with the items above (line numbers at b68b6cc6; datajoint/datajoint-docs#312, open, edits the Data Manipulation, Delete Data, and Transactions sections named here):

  • Cascade specification, "part_integrity modes": state the rule on both sides, no part without its master and no master with a partial set (cascade.md:70). enforce refuses before any delete, per row (:74), which removes "Enforce granularity" from Limitations (:207). ignore is a repair (:75). "Cascade flow" (:66) changes with the repeated part-to-master step, and Limitations "Single FK path" (:204) with the owned-reference walk.
  • Diagram specification, "Diagram.cascade()" (diagram.md:142-150): the default preview holds the rows reached through children only, which delete() refuses when a master would keep a partial set; part_integrity="cascade" gives the rows a delete removes. Revise again if #1760 puts the refusal in the preview.
  • Master-Part specification, §4.4 "Breaking Integrity (ignore)": replace the use-case list (master-part.md:221-225) with the repair statement; an invalid trial is corrected by deleting the master and entering it again. §5.2 "Drop Part Directly": a schema change.
  • Data Manipulation specification: §4.1 and §4.6 ignore rows (data-manipulation.md:324, :398-399, :410) and §6.2 (:539-540); §4.5 "Transaction Control" (:386-387), transaction=False requires an open transaction; §4.7 "delete_quick() Method" (:413-431), never on a part table.
  • Delete Data how-to: "Transaction Handling" (delete-data.md:87-94), "Part Tables" (:108-122), "Quick Delete" (:124-131). Transactions, "Deletes are transactional too" (transactions.md:185-187): the advice becomes an enforced precondition.

Order: parts recognized in every schema, then the refusal before the first DELETE

  1. Merge #1728. Until parts are recognized in every schema, none of these checks runs there.
  2. Write the six tests from the sketches. They decide the findings made by reading.
  3. #1760: the row-level test before the first DELETE. It fixes the first item, puts the refusal ahead of every delete for transaction=False, and supplies the final assertion for cascade mode.
  4. In the same patch release: the transaction=False warning, the Part.delete_quick and ignore warnings, and the stale docs statements. Raise in the next minor.
  5. The repeated part-to-master step and the owned-reference walk, either on master or as cases for the planner when cascade() and delete() move onto it (#1637); the owned-reference walk follows #1620.
  6. Planning inside the transaction.
Linguagem predominante
Python
Estrelas
198
Forks
107
Merge médio
4d 7h
PRs com merge (30d)
12

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.