Repository navigation
Fixes #33741: lock the data product so a concurrent assets/add cannot orphan its edge - #33762
Conversation
✅ PR checks passedThe linked issue has a description and all required Shipping project fields set. Thanks! |
|
Hi there 👋 Thanks for your contribution! The OpenMetadata team will review the PR shortly! Once it has been labeled as Let us know if you need any help! |
|
Thanks for the review. Two notes on the state of this PR. Expected non-blocking gatesTwo checks on fork PRs are expected to stay red here and are not related to the change:
Both behave the same way on recently merged fork PRs, e.g. #33292, #32135, #31921. Local compile status (being upfront)I could not complete a local multi-module So CI is the first full compile of these changes, and the compile job should be treated as the gate for them. What the change does
|
|
Update on the verification gaps flagged in my summary — I've now closed them locally. These changes compile and are correctly formatted. Local verification (run by the author after the PR was opened)Environment note: this machine's Homebrew JDK 21.0.12.1 is incompatible with the repo's pinned Lombok 1.18.36 ( Prerequisites installed first ( Results on this branch (
So the One caveat unchanged: This comment was generated by an AI agent (Hermes Agent). |
- DataProductOrphanRelationshipIT: import assertFalse (class did not compile) - derive the guarded-insert table name from the from-entity's own DAO (Entity.DATA_PRODUCT -> DataProductDAO.getTableName() = data_product_entity, not the naive "dataProduct_entity"); drop the now-unused EntityDAO.physicalTableName helper - CoreRelationshipDAOs.insertIfFromEntityExists (Postgres): lock the source row with FOR SHARE and recheck the source entity in the ON CONFLICT DO UPDATE path, so a concurrent uncommitted DELETE cannot resurrect the edge - DataProductRepository: let EntityNotFoundException escape the per-asset catch so a single-asset call returns 404 instead of a FAILURE bulk row (400) - CoreRelationshipDAOs.insert: remove the duplicate PostgreSQL ConnectionAwareSqlUpdate annotation - DataProductOrphanRelationshipIT: make the orphan-tolerance test actually delete the data product after attaching, and document the sequential (non-concurrent) nature of the first test
|
Thanks for the review. All six findings are addressed in 1. (P1) Missing 2. (P1) Wrong physical table name — Confirmed. 3. (P1) PostgreSQL race remains open — Confirmed, and the mechanism is as described: the plain INSERT INTO entity_relationship(...) SELECT ..., (:json :: jsonb)
FROM <fromTable> f WHERE f.id = :fromId FOR SHARE
ON CONFLICT (fromId, toId, relation, relationType) DO UPDATE SET json = EXCLUDED.json
WHERE EXISTS (SELECT 1 FROM <fromTable> f WHERE f.id = :fromId)
4. (P1) Not-found becomes bad request — Confirmed: the throw sits inside the loop 5. (P2) Duplicate PostgreSQL annotation — Confirmed. The second, byte-identical 6. (P2) Regression states are untested — Partially confirmed.
Local verification: This comment was generated by an AI agent. |
|
Hi there 👋 Thanks for your contribution! The OpenMetadata team will review the PR shortly! Once it has been labeled as Let us know if you need any help! |
|
Local compile verification update: both affected modules build clean on |
…a deleted from-entity
A concurrent assets/add racing DELETE of the same Data Product re-created the
CONTAINS edge after the delete had torn the entity down, leaving an
entity_relationship row whose fromId named nothing. That orphan is unreachable
(GET /dataProducts/{id} 404s with and without ?include=deleted) and poisons later
bulk operations over the same asset with an opaque not_found.
Make existence part of the write: the edge is now inserted by a single statement
that selects from the from-entity's own table, so the check shares the insert's
transaction and lock scope and observes a delete that commits in between. The
repository reports the dropped write so the caller answers 404 instead of
silently losing the asset, and the dropped path still evicts the entity cache.
- DataProductOrphanRelationshipIT: import assertFalse (class did not compile) - derive the guarded-insert table name from the from-entity's own DAO (Entity.DATA_PRODUCT -> DataProductDAO.getTableName() = data_product_entity, not the naive "dataProduct_entity"); drop the now-unused EntityDAO.physicalTableName helper - CoreRelationshipDAOs.insertIfFromEntityExists (Postgres): lock the source row with FOR SHARE and recheck the source entity in the ON CONFLICT DO UPDATE path, so a concurrent uncommitted DELETE cannot resurrect the edge - DataProductRepository: let EntityNotFoundException escape the per-asset catch so a single-asset call returns 404 instead of a FAILURE bulk row (400) - CoreRelationshipDAOs.insert: remove the duplicate PostgreSQL ConnectionAwareSqlUpdate annotation - DataProductOrphanRelationshipIT: make the orphan-tolerance test actually delete the data product after attaching, and document the sequential (non-concurrent) nature of the first test
889290c to
2f50ba5
Compare
|
Hi there 👋 Thanks for your contribution! The OpenMetadata team will review the PR shortly! Once it has been labeled as Let us know if you need any help! |
|
Rebased onto current |
# Conflicts: # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataProductRepository.java
open-metadata#35026 replaced bulkAssetsOperation, the only caller of addRelationshipIfFromEntityExists, so the guarded insert and its DAO statement no longer run. The INSERT ... SELECT also does not close the race on its own: the delete sweeps relationships before removing the data product row, so Postgres still writes the orphan edge. The next commit fixes the race with row locks on both sides instead.
…ts/add cannot orphan its edge A hard delete of a data product sweeps its entity_relationship rows before it deletes its own row, and an asset write only checked that the data product exists with a read the cache can answer. An assets/add landing inside the delete inserted its HAS edge after the sweep and left a row whose data product is gone. Writers now share-lock the data products an entity gains (lockExistingIds, FOR SHARE) in the same transaction as the edge insert, and fail with not-found when the row is gone. The delete takes the data product's row lock first in its cleanup transaction, so it either waits for the writer's edge to commit and sweeps it, or the writer finds the row deleted. DataProductDeleteRaceIT holds a row lock on a separate connection to stop one side mid-transaction, so both orderings run deterministically.
A domain hard delete removes its data products through bulkHardDeleteSubtree, which runs entitySpecificCleanup outside the transaction that sweeps their relationships. The FOR UPDATE taken there auto-committed before the sweep, so an assets/add could still land its edge after it (Postgres orphaned the row; MySQL only avoided it through a deadlock and retry). Add a lockRowsForDelete hook that runs first inside both cleanup transactions, the single delete and the bulk cascade, and have DataProductRepository lock its rows there with one SELECT ... IN (...) FOR UPDATE. DataProductDeleteRaceIT gains a domain-cascade case that holds the data product's entity_extension row to stop the cascade between its sweep and its row delete.
…ocking lockIdsForUpdate now takes its row locks in id order, so a direct delete and a domain cascade locking overlapping data products acquire them in the same order. lockDataProducts de-duplicates the ids, so a bulk create of many entities in one data product sends a single id instead of one copy per entity.
|
Hi there 👋 Thanks for your contribution! The OpenMetadata team will review the PR shortly! Once it has been labeled as Let us know if you need any help! |
|
Hi there 👋 Thanks for your contribution! The OpenMetadata team will review the PR shortly! Once it has been labeled as Let us know if you need any help! |
|
Hi there 👋 Thanks for your contribution! The OpenMetadata team will review the PR shortly! Once it has been labeled as Let us know if you need any help! |
yan-3005
left a comment
There was a problem hiding this comment.
Approving after local verification of the impacted tests on this PR merged with current main:
| Suite | Result |
|---|---|
ITs, mysql-elasticsearch (18 impacted classes incl. DataProductDeleteRaceIT, DataProductResourceIT, DomainResourceIT, delete-atomicity and lock-order ITs) |
Tests run: 666, Failures: 0, Errors: 0 |
ITs, postgres-opensearch (DataProductDeleteRaceIT, DataProductResourceIT, DomainResourceIT) |
Tests run: 531, Failures: 0, Errors: 0 |
ITs, cache-tests (OneTransactionFlushAtomicityIT) |
Tests run: 9, Failures: 0, Errors: 0 |
Playwright: DataProducts, Domains, DataProductAndSubdomains, DomainAdvanced, DataProductDomainMigration, EntityDomainPropagation |
117 of 118 pass |
The one Playwright failure, Domains.spec.ts:850 (domain asset count, expected 6 got 0), fails the same way on plain main (4195406575), so it is pre-existing and not caused by this change.
All three race tests (direct delete, add-first, domain cascade) pass on both engines. No open bot findings.
Resolve the EntityRepository conflict by keeping both doc comments: lockRowsForDelete's and main's shouldCleanupFqnDependents.
|
Hi there 👋 Thanks for your contribution! The OpenMetadata team will review the PR shortly! Once it has been labeled as Let us know if you need any help! |
Code Review ✅ Approved 5 closed / 5 findings🔴 High risk · Locking data-product relationship writes and hard deletes changes stored-data integrity; lock-order conflicts could deadlock requests or leave orphan edges. Adds row-level locking so a concurrent Resolved this session: the ✅ 5 closed✅ Bug: physicalTableName produces wrong table for multi-word types
✅ Bug: Test uses assertFalse without importing it
✅ Quality: Duplicate POSTGRES annotation on insert()
✅ Bug: FOR SHARE guard misses the window where delete has removed edges
✅ Bug: Blanket ENF rethrow aborts the whole bulk call on any asset's not-found
VerificationRules No rules evaluated Functional validation Not enabledAuto-approval Not enabledFor more verification details, comment OptionsDisplay: compact → Showing compact verification results. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source |
Merge commits are not allowed on this repository
|
🤖 Backport to |
|
🤖 Backport to |
… orphan its edge (2.0) (#37107) Backport of #33762. A hard delete of a data product sweeps its entity_relationship rows before deleting its own row, and writers only checked that the data product exists with a read the cache can answer, so an assets/add landing inside the delete left a HAS edge to a deleted data product. Writers now share-lock the data products an entity gains (lockExistingIds, FOR SHARE) in the same transaction as the edge insert and fail with not-found when the row is gone. On 2.0 the assets/add path is DataProductRepository.bulkAssetsOperation, which inserted edges outside any transaction; it now locks and inserts each edge inside flushInOneTransaction. A lockRowsForDelete hook runs first in both cleanup transactions (direct delete and domain cascade), and DataProductRepository locks its rows there before the relationship sweep. DataProductDeleteRaceIT holds row locks on a separate connection to fix the interleaving of delete-first, add-first (through a table PATCH on 2.0) and domain-cascade races. Co-authored-by: Ram Narayan Balaji <[email protected]>
Describe your changes:
Fixes #33741
An
assets/addthat lands while the same data product is being hard-deleted leaves anentity_relationshipHAS row whose data product no longer exists.Why it happens. The delete removes the data product's relationship rows first and its own row last, in one transaction, without locking anything. The asset write (since #35026, one PATCH per asset) only checked that the data product exists with
validateDataProducts, which can be answered from the cache. An add that lands between the delete's sweep and its commit inserts its edge after the sweep, and nothing removes it.What this changes.
lockExistingIds,FOR SHARE) in the same transaction as the edge insert. If a row is gone, the write fails withdataProduct … not found. This covers asset updates (PUT/PATCH, soassets/add), single create and bulk create. Ordinary edits that don't add a data product take no new lock.lockRowsForDeletehook runs first inside both cleanup transactions, a direct delete and a domain's bulk cascade.DataProductRepositoryoverrides it to take the row locks (SELECT … IN (…) FOR UPDATE) before the sweep. A writer-side lock alone is not enough: the sweep runs before the row delete, so it would still miss an edge committed after it.With both, the two requests serialize: either the add commits first and the delete's sweep removes its edge, or the delete commits first and the add fails with not-found.
History of this PR. @zhang-arvin opened it with a guarded
INSERT … SELECTinbulkAssetsOperation. Since then:bulkAssetsOperation(assets/add is now one PATCH per asset), so the guarded insert had no caller left.The branch now merges
main, reverts the guarded insert (189e6e55d7), and adds the row-lock fix (6cc90fce93). The orphan-edge diagnosis and the regression scenario are from the original commits.What this does not change.
assets/addcalls on the same asset; I checked 20 such assets on a live server and all accepted new adds. That is why this PR doesn't claim to fix that symptom from the issue.entity_relationshiprows (dangling Data Product edges) #33742.Type of change:
High-level design:
N/A — small change (3 files). The lock ordering is documented in the Javadoc of
EntityRepository#lockDataProductsandDataProductRepository#entitySpecificCleanup.Trade-off: the delete now locks the data product's row before its sweep, while a concurrent PATCH of the same data product writes its edges first and its row last. On MySQL those two can deadlock;
flushInOneTransactionalready retries deadlocks. This is reasoned, not tested.Tests:
Use cases covered
assets/addfor it: no edge survives.assets/addholding the asset mid-transaction (edge written, not committed), then a hard delete: the delete removes the edge.assets/add: no edge survives.assets/addcalls into one live data product, with and without concurrent PATCHes of the data product: all succeed, every edge lands, no deadlocks.Unit tests
Backend integration tests
openmetadata-integration-tests/.../it/tests/DataProductDeleteRaceIT.java.pg_stat_activity/innodb_trx) rather than on time.data_product_entityandentity_relationship, not on HTTP status, since which request wins is the database's choice.main:expected: <0> but was: <1>).DataProductDeleteRaceITon final commitDataProductDeleteRaceITon final commitDataProductDeleteRaceIT,DataProductResourceITDataProductDeleteRaceIT,DataProductResourceITDataProduct*,Domain*,MultiDomainHasDomainIT,BulkAssetChangeEventUserIT,AssetsTab*,EntityHardDeletionAtomicityIT,EntityRelationshipCleanupIT,EntityUpdateLockOrderIT,EntityTransactionBoundaryIT,UnitOfWorkRollbackIT,OrphanedEntityReferenceITOneTransactionFlushAtomicityITNot run locally: because
EntityRepositorychanged,make java_affectedselects the full IT suite (about 300 classes) and the fullopenmetadata-serviceunit suite. The unit suite runs in PR CI. For the full IT suite, I'm triggering the "Integration Tests - MySQL + Elasticsearch" workflow on this branch.Domain cascade follow-up (Greptile review, commit
15014cf362):addDuringDomainCascadeWritesNoEdgeForTheDeletedDataProduct, run before the fix:DataProductDeleteRaceIT,DataProductResourceIT,DomainResourceIT:Ingestion integration tests
Playwright (UI) tests
Manual testing performed
Standalone server on port 9595 (MySQL + Elasticsearch), auth-free. A script creates a domain and tables, then for each iteration creates a data product and fires
PUT /dataProducts/{fqn}/assets/addandDELETE /dataProducts/{id}?hardDelete=true&recursive=trueconcurrently. It then countsentity_relationshiprows from a data product that has nodata_product_entityrow.maindataProduct … not found)recordBulkAssetsChangereading the deleted data product after the asset PATCH had committed.successand every edge landed (20/20/50).UI screen recording:
Not applicable — backend-only fix.
Checklist:
Fixes <issue-number>: <short explanation>Fixes #<issue-number>above.6cc90fce93, identical tree to the reviewed8140621722) againstREVIEW.mdand fixed every 🔴 finding.assertThrows(OpenMetadataException.class, …), which also passes on a 500. It now counts thedata_product_entityrow directly.docs/decisions/record. The lock ordering is stated in the code's Javadoc, not only in this description.🤖 Generated with Claude Code


Confidence Score: 5/5
The PR appears safe to merge; no new blocking issue was found.Summary
The PR locks data products before adding asset relationships and before deleting their relationships. Both direct deletes and domain cascades take the delete-side lock inside the cleanup transaction.
Diagram
Reviews (4) · Last reviewed commit: "Order the delete-side lock and de-duplic..." · Reviewed by Greptile