Skip to content

Fixes #33741: lock the data product so a concurrent assets/add cannot orphan its edge - #33762

Merged
yan-3005 merged 10 commits into
open-metadata:mainfrom
zhang-arvin:fix/om-33741-orphan-relationship
Nov 4, 2026
Merged

yan-3005 merged 10 commits into
open-metadata:mainfrom
zhang-arvin:fix/om-33741-orphan-relationship

Conversation

@zhang-arvin

@zhang-arvin zhang-arvin commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Describe your changes:

Fixes #33741

An assets/add that lands while the same data product is being hard-deleted leaves an entity_relationship HAS 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.

  • Writers lock first. Before an entity is linked to data products it does not already have, the write takes a shared lock on those rows (lockExistingIds, FOR SHARE) in the same transaction as the edge insert. If a row is gone, the write fails with dataProduct … not found. This covers asset updates (PUT/PATCH, so assets/add), single create and bulk create. Ordinary edits that don't add a data product take no new lock.
  • The delete locks first. A lockRowsForDelete hook runs first inside both cleanup transactions, a direct delete and a domain's bulk cascade. DataProductRepository overrides 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 … SELECT in bulkAssetsOperation. Since then:

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.

Type of change:

  • Bug fix

High-level design:

N/A — small change (3 files). The lock ordering is documented in the Javadoc of EntityRepository#lockDataProducts and DataProductRepository#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; flushInOneTransaction already retries deadlocks. This is reasoned, not tested.

Tests:

Use cases covered

  • Delete holding the data product mid-transaction, then assets/add for it: no edge survives.
  • assets/add holding the asset mid-transaction (edge written, not committed), then a hard delete: the delete removes the edge.
  • Recursive hard delete of the data product's domain, held between the cascade's relationship sweep and its row delete, then assets/add: no edge survives.
  • 20 and 50 parallel assets/add calls into one live data product, with and without concurrent PATCHes of the data product: all succeed, every edge lands, no deadlocks.

Unit tests

  • Not added. The fix is a database locking order, which only a real database can show. Covered by the IT below.

Backend integration tests

  • Added openmetadata-integration-tests/.../it/tests/DataProductDeleteRaceIT.java.
    • Each test holds a row lock on a separate connection to pause one request at a known point, so the two requests interleave the same way on every run.
    • It waits on the database's own lock-wait view (pg_stat_activity / innodb_trx) rather than on time.
    • It asserts on the rows left in data_product_entity and entity_relationship, not on HTTP status, since which request wins is the database's choice.
  • Fails on main:
    • Postgres: 2 of 2 fail (expected: <0> but was: <1>).
    • MySQL: 1 of 2 fails. The add-first test passes on MySQL without the fix, because there the sweep already blocks on the add's uncommitted row; it can only catch a regression on Postgres.
  • Passes with the fix:
Run Engine Result
DataProductDeleteRaceIT on final commit postgres-opensearch 2 run, 0 failures
DataProductDeleteRaceIT on final commit mysql-elasticsearch 2 run, 0 failures on the previous commit; the final commit only tightens one assertion and was not rerun on MySQL
DataProductDeleteRaceIT,DataProductResourceIT postgres-opensearch 281 run, 0 failures, 28 skipped
DataProductDeleteRaceIT,DataProductResourceIT mysql-elasticsearch 281 run, 0 failures, 28 skipped
16 classes: DataProduct*, Domain*, MultiDomainHasDomainIT, BulkAssetChangeEventUserIT, AssetsTab*, EntityHardDeletionAtomicityIT, EntityRelationshipCleanupIT, EntityUpdateLockOrderIT, EntityTransactionBoundaryIT, UnitOfWorkRollbackIT, OrphanedEntityReferenceIT mysql-elasticsearch 628 run, 0 failures, 52 skipped
OneTransactionFlushAtomicityIT cache-tests 9 run, 0 failures, 1 skipped

Not run locally: because EntityRepository changed, make java_affected selects the full IT suite (about 300 classes) and the full openmetadata-service unit 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):

  • Test addDuringDomainCascadeWritesNoEdgeForTheDeletedDataProduct, run before the fix:
    • Postgres fails with 1 orphan.
    • MySQL passes, because the old code avoided the orphan through a deadlock and retry.
  • With the fix, DataProductDeleteRaceIT,DataProductResourceIT,DomainResourceIT:
Engine Result
postgres-opensearch 523 run, 0 failures, 0 errors, 52 skipped
mysql-elasticsearch 523 run, 0 failures, 0 errors, 52 skipped; no deadlocks

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

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/add and DELETE /dataProducts/{id}?hardDelete=true&recursive=true concurrently. It then counts entity_relationship rows from a data product that has no data_product_entity row.

Build Iterations Orphaned rows
main 300 20
this PR 300 0 (25 adds rejected with dataProduct … not found)
  • Before the fix, every orphaned iteration returned 404 to the client even though its edge was saved. The 404 came from recordBulkAssetsChange reading the deleted data product after the asset PATCH had committed.
  • Fan-out with the fix: 20, 20 and 50 concurrent single-asset adds into one data product, with 0, 10 and 20 concurrent PATCHes of it.
    • Every add returned success and every edge landed (20/20/50).
    • Every PATCH returned 200.
    • The server log has no deadlock or lock-wait timeout.

UI screen recording:

Not applicable — backend-only fix.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes <issue-number>: <short explanation>
  • My PR is linked to a GitHub issue via Fixes #<issue-number> above.
  • I have commented on my code, particularly in hard-to-understand areas.
  • For JSON Schema changes: not applicable, no schema change.
  • For a UI feature or feature task: not applicable, backend-only.
  • I have added tests (unit / integration / Playwright as applicable) and listed them above.
  • Self-review: I reviewed the final diff (6cc90fce93, identical tree to the reviewed 8140621722) against REVIEW.md and fixed every 🔴 finding.
    • The review found one 🔴: the test asserted the deletion with assertThrows(OpenMetadataException.class, …), which also passes on a 500. It now counts the data_product_entity row directly.
  • Decision check: no docs/decisions/ record. The lock ordering is stated in the code's Javadoc, not only in this description.
  • I have added a test that covers the exact scenario we are fixing.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence 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.

  • Asset links and hard deletes wait on the same data-product rows.

Diagram

sequenceDiagram
  participant Writer as Asset write
  participant DB as Database
  participant Delete as Data-product delete
  Writer->>DB: Take shared data-product lock
  Writer->>DB: Insert asset relationship
  Delete->>DB: Request exclusive data-product lock
  Note over Delete,DB: Wait for writer to commit
  Writer->>DB: Commit
  DB-->>Delete: Grant exclusive lock
  Delete->>DB: Remove relationships and data-product row
  Delete->>DB: Commit
Loading

Reviews (4) · Last reviewed commit: "Order the delete-side lock and de-duplic..." · Reviewed by Greptile

@zhang-arvin
zhang-arvin requested a review from a team as a code owner September 22, 2026 05:47
@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

The linked issue has a description and all required Shipping project fields set. Thanks!

@github-actions

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@zhang-arvin

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Two notes on the state of this PR.

Expected non-blocking gates

Two checks on fork PRs are expected to stay red here and are not related to the change:

  • safe to test label / integration tests skipped — integration tests do not run for fork contributors until a maintainer adds the label.
  • PR Metadata Validation — requires Shipping-project fields that need org permissions, so a fork author cannot populate them.

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 -am compile: on this machine mvn -pl openmetadata-service -am compile fails inside openmetadata-spec with TypeTag :: UNKNOWN (the jsonschema2pojo codegen + Lombok annotation-processor interaction in reactor mode). That reproduces independently of this change — mvn -pl common compile and mvn -pl openmetadata-spec compile each pass on their own, and the failure is in codegen for the spec module, not in the files touched here.

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

entity_relationship writes for the assets path now carry their own existence proof instead of being a separate check that could itself race: the edge is inserted by a 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 committed in between. The write reports back, and the caller answers not_found rather than persisting an edge that outlives its entity.

DataProductOrphanRelationshipIT covers both halves — the racing add is rejected, and an asset left with a dangling association by a pre-fix deployment still serves reads and still accepts bulk adds for live data products.

@zhang-arvin

Copy link
Copy Markdown
Contributor Author

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 (NoSuchFieldException: com.sun.tools.javac.code.TypeTag :: UNKNOWN inside lombok.javac.JavacTreeMaker$TypeTag.typeTag). Passing -Dlombok.version=1.18.48 as a temporary, command-line-only override resolves it locally; it is not part of this PR and no pom change is included.

Prerequisites installed first (openmetadata-shaded-deps/{elasticsearch,opensearch}-dep and openmetadata-spec only publish usable jars in the package/install phases, so a plain compile cannot resolve them):

mvn -pl openmetadata-spec install -DskipTests -Dspotless.check.skip=true -Dlombok.version=1.18.48

Results on this branch (5ccc28e7):

Check Result
mvn -pl openmetadata-service compile BUILD SUCCESS — Compiling 2130 source files with javac [debug target 21]
mvn -pl openmetadata-service spotless:check (restricted to this PR's 4 changed Java files) BUILD SUCCESS

So the openmetadata-service sources in this PR are type-checked and format-clean. This supersedes my earlier note that the change had never been compiled.

One caveat unchanged: spotless:check over the whole module crashes in this local environment inside google-java-format (NoSuchMethodError: com.sun.tools.javac.util.Log$DeferredDiagnosticHandler.getDiagnostics()) on EntityInterfaceUtilTest.java, a file not touched by this PR — that is a tooling/JDK incompatibility here, not a formatting violation, and the module-wide check is expected to run normally on CI.

This comment was generated by an AI agent (Hermes Agent).

zhang-arvin added a commit to zhang-arvin/OpenMetadata that referenced this pull request Sep 29, 2026
- 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
@zhang-arvin

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All six findings are addressed in 889290c6 (or explicitly rebutted below).

1. (P1) Missing assertFalse import — Confirmed. import static org.junit.jupiter.api.Assertions.assertFalse; added. The test module now compiles.

2. (P1) Wrong physical table name — Confirmed. DataProductDAO.getTableName() returns the literal data_product_entity (GovernanceDAOs.java:183) while the helper produced dataProduct_entity. Fixed by taking the table name from the from-entitys own DAO, as suggested: Entity.getEntityRepository(fromEntity).getDao().getTableName(). The now-unused EntityDAO.physicalTableName` helper is deleted — leaving it would be a dead, foot-gun-shaped duplication of a mapping that is wrong for multi-word types (it was its only caller).

3. (P1) PostgreSQL race remains open — Confirmed, and the mechanism is as described: the plain EXISTS subquery neither locks the source row nor rechecks it, so a snapshot taken while the delete is uncommitted can still insert the edge. Fixed within the existing statement (no architectural change): the source row now appears as the insert`s row source with a shared lock, and the conflict path rechecks the source entity —

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)

FOR SHARE makes a concurrent uncommitted DELETE of the same entity block this statement; once the delete commits, the locked row is rechecked and gone and the statement writes 0 rows. The DO UPDATE ... WHERE clause closes the same hole on the re-insert path (an ON CONFLICT update whose source row vanished becomes a no-op). MySQL keeps the plain INSERT ... SELECT ... FROM <fromTable> form, whose statement-level locking on the source table already gives the same guarantee. No cross-table lock ordering is introduced — the lock is confined to the source entity row.

4. (P1) Not-found becomes bad request — Confirmed: the throw sits inside the loops broad catch (Exception), which turns it into a failed bulk row and, for a single asset, a FAILUREresult → HTTP 400. Fixed by letting it escape: acatch (EntityNotFoundException e) { throw e; }branch now precedes theRuleValidationExceptionandException` branches, so a single-asset call returns 404 as intended.

5. (P2) Duplicate PostgreSQL annotation — Confirmed. The second, byte-identical @ConnectionAwareSqlUpdate(connectionType = POSTGRES) block on insert() is removed, leaving the single MYSQL + POSTGRES pair.

6. (P2) Regression states are untested — Partially confirmed.

  • The second test (orphanedAssetStillServesReadsAndAcceptsBulkAddsForLiveDataProducts) did indeed never delete the data product, so it never created the dangling state its comment described. Fixed: it now attaches the asset, asserts the attachment, then deletes the data product, and only then exercises reads + bulk add against the live one — so it is a real orphan fixture now.
  • The first test is a sequential regression by design, and the rebuttal is that the concurrent interleaving cannot be forced deterministically through the public REST API — there is no hook to hold the DELETE uncommitted or to pause between the DELETE and the assets/add, and adding a test-only synchronization point to production code is not worth it. Its job is the post-condition (a rejected write leaves no edge); the concurrency dimension is covered at the SQL layer by the in-statement existence check addressed in Apply apache 2.0 license to all the files in the project #3. I added a comment stating this explicitly rather than leaving a comment that overpromises coverage.

Local verification: openmetadata-service compiles clean (mvn -pl openmetadata-service compile, all 2130 sources, BUILD SUCCESS). The integration-test module compile is running locally; the assertFalse import is the only symbol fix it needed and is verifiable statically. Note Validate PR Metadata and the integration-test lanes are expected to stay red for an external fork (Shipping project fields + safe to test label are not grantable by a fork contributor); the same pattern held for merged PRs #33292, #32135, #31921.

This comment was generated by an AI agent.

@github-actions

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@zhang-arvin

Copy link
Copy Markdown
Contributor Author

Local compile verification update: both affected modules build clean on 889290c6 — openmetadata-service (2130 sources) and openmetadata-integration-tests (test-compile produces DataProductOrphanRelationshipIT.class, confirming the assertFalse import and the reworked test cases compile). Runtime integration tests still need the safe to test lane. AI agent.

zhang-arvin and others added 2 commits October 8, 2026 14:01
…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
@zhang-arvin
zhang-arvin force-pushed the fix/om-33741-orphan-relationship branch from 889290c to 2f50ba5 Compare October 8, 2026 06:01
@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@zhang-arvin

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (new head 2f50ba516). No conflicts. The earlier review threads were addressed by the head commit fix(review): address six bot findings on #33762 — notably the missing assertFalse static import (present), the duplicated POSTGRES @ConnectionAwareSqlUpdate on insert(), and the dataProduct_entity physical-table-name mapping.

# 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.
@yan-3005 yan-3005 changed the title Fix #33741: never persist entity_relationship edges for a deleted from-entity Fixes #33741: lock the data product so a concurrent assets/add cannot orphan its edge Oct 21, 2026
@yan-3005 yan-3005 added the safe to test Add this label to run secure Github workflows on PRs label Oct 21, 2026
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.
@github-actions github-actions Bot removed the safe to test Add this label to run secure Github workflows on PRs label Oct 22, 2026
@yan-3005
yan-3005 enabled auto-merge October 22, 2026 08:00
…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.
@github-actions github-actions Bot removed the safe to test Add this label to run secure Github workflows on PRs label Oct 22, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@pmbrull
pmbrull requested a review from yan-3005 November 3, 2026 15:14
@yan-3005 yan-3005 added the safe to test Add this label to run secure Github workflows on PRs label Nov 3, 2026
@github-actions github-actions Bot removed the safe to test Add this label to run secure Github workflows on PRs label Nov 3, 2026
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@yan-3005 yan-3005 added safe to test Add this label to run secure Github workflows on PRs To release Will cherry-pick this PR into the release branch labels Nov 4, 2026
@github-actions github-actions Bot removed the safe to test Add this label to run secure Github workflows on PRs label Nov 4, 2026
@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@yan-3005 yan-3005 added safe to test Add this label to run secure Github workflows on PRs 2.1 labels Nov 4, 2026

@yan-3005 yan-3005 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@github-actions github-actions Bot removed the safe to test Add this label to run secure Github workflows on PRs label Nov 4, 2026
@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@gitar-bot

gitar-bot Bot commented Nov 4, 2026

Copy link
Copy Markdown
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 assets/add cannot leave an orphaned entity_relationship edge when its data product is hard-deleted. Writers take a shared lock before linking new data products, and the delete takes an exclusive lock before its sweep.

Resolved this session: the physicalTableName mapping for multi-word types, the missing assertFalse import in the test, the duplicate POSTGRES annotation on insert(), the FOR SHARE guard gap where a delete had already removed edges, and the blanket ENF rethrow that aborted bulk calls on any single asset's not-found. No open issues remain.

✅ 5 closed
✅ Bug: physicalTableName produces wrong table for multi-word types

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityDAO.java:86-88 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java:7641-7652 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataProductRepository.java:799-805
EntityDAO.physicalTableName maps an entity type to <type>_entity, but real table names snake-case multi-word types. For a data product fromEntity is Entity.DATA_PRODUCT = "dataProduct", so physicalTableName returns dataProduct_entity, while the actual table (DataProductDAO.getTableName()) is data_product_entity. The generated INSERT ... FROM dataProduct_entity f / WHERE EXISTS (SELECT 1 FROM dataProduct_entity f ...) references a table that does not exist, so insertIfFromEntityExists throws a SQL error and every dataProducts/{fqn}/assets/add — including the happy path — fails. The docstring's claim that this equals getTableName() holds only for single-word types. Derive the name from the from-entity's own DAO instead.

✅ Bug: Test uses assertFalse without importing it

📄 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductOrphanRelationshipIT.java:71 📄 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DataProductOrphanRelationshipIT.java:3-6
addAssetAfterDataProductDeleteIsRejectedAndWritesNoRelationship calls assertFalse(...) at line 71, but the file only statically imports assertEquals, assertNotNull, assertThrows, and assertTrue. assertFalse is unresolved, so the whole test class fails to compile and none of the three tests that verify this fix can run.

✅ Quality: Duplicate POSTGRES annotation on insert()

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CoreRelationshipDAOs.java:671-676
The PR adds a second @ConnectionAwareSqlUpdate(connectionType = POSTGRES) on insert() whose value is byte-for-byte identical to the existing POSTGRES annotation at lines 665-670. Two annotations with the same connection type are redundant at best and rely on the SQL locator silently picking one; the duplicate appears to be an accidental copy-paste and should be removed.

✅ Bug: FOR SHARE guard misses the window where delete has removed edges

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CoreRelationshipDAOs.java:688-696 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CoreRelationshipDAOs.java:709-711 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java:7652
The new Javadoc says the race is closed, but cleanupFlushBody (EntityRepository ~L5089-5132) deletes the data product's edges first with relationshipDAO().deleteAll(id, entityType) and only removes the entity row at the very end with dao.delete(id). So an assets/add that runs after deleteAll but before dao.delete still finds the data_product_entity row unlocked and visible. FOR SHARE succeeds, the new CONTAINS edge is inserted and committed, and the delete's dao.delete then goes ahead once the share lock is released, leaving the orphan edge this PR is meant to prevent. MySQL has the same gap because the source row isn't row-locked until the delete reaches it. To fix it, have the delete lock the entity row (SELECT ... FOR UPDATE) at the start of the cleanup transaction, before deleteAll, so any concurrent guarded insert waits and then sees the row is gone. You could also delete the entity row before its relationships.

✅ Bug: Blanket ENF rethrow aborts the whole bulk call on any asset's not-found

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataProductRepository.java:796-803 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataProductRepository.java:818-823
The new catch (EntityNotFoundException e) { throw e; } rethrows every not-found raised in the per-asset try block, not only the one from the guarded write. searchRepository.updateEntity(ref) (line 818) runs inline here, because @Transaction does not open a search-write deferral scope. It calls entityRepository.get(null, id, ...) with the default NON_DELETED include, while the assets were loaded with ALL. So adding or removing a soft-deleted asset, or one hard-deleted mid-request, used to give one FAILURE row. Now the whole request returns 404 and the @Transaction rolls back the other assets' edges, even though their search docs were already updated inline.

Fix: rethrow only the not-found caused by the deleted data product. Use a dedicated flag or exception type, or throw from outside the per-asset try, so other not-found errors keep being collected as failure rows.

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

@yan-3005 yan-3005 added the safe to test Add this label to run secure Github workflows on PRs label Nov 4, 2026
auto-merge was automatically disabled November 4, 2026 18:35

Merge commits are not allowed on this repository

@yan-3005
yan-3005 merged commit 0055904 into open-metadata:main Nov 4, 2026
88 of 98 checks passed
@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

🤖 Backport to 2.0 is under way. It is built from openmetadata-collate, which holds the credentials needed to open a PR here, and it will comment again with the result — nothing is needed from you unless it reports otherwise.

@gh-bot-collate

gh-bot-collate Bot commented Nov 4, 2026

Copy link
Copy Markdown

🤖 Backport to 2.0 failed. The conflict could not be resolved, so this change is not on that branch. Resolver run.

yan-3005 added a commit that referenced this pull request Nov 5, 2026
… 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

2.1 safe to test Add this label to run secure Github workflows on PRs To release Will cherry-pick this PR into the release branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Concurrent assets/add and DELETE of a Data Product orphans its entity_relationship row (unreachable, un-deletable "ghost")

3 participants