Repository navigation
Fixes #38112: reject deleting a relationship type that is still in use - #38140
Conversation
Other relationship types reference a type through inverse, replacedBy, propertyChain and disjointWith, and glossary term relations store it by name and id. Every reader resolves those against live types, but the delete only refused system types, so deleting a type in use left term reads, the term list, PATCH and the ontology export failing with 400 (the export projects every type, so one dangling reference broke it for every glossary). A soft or hard delete is now rejected with 400 while another type, live or soft-deleted, references the type or any stored relation uses it; the message names the referrers and counts the relations. Counting soft-deleted referrers keeps a later restore from dangling. A create or update that names a soft-deleted type is rejected too, since it led to the same state. Clusters that already deleted types in use are repaired by a run-once 2.1.0 data-migration step: a soft-deleted type still in use is undeleted, a hard-deleted one is recreated under its old id and name as a deprecated placeholder that points back at its inverse partner. User relations are never dropped or retyped.
An independent review of the delete guard found gaps, fixed here: - The deprecated settings write saves the setting, then hard-deletes the removed types one by one, so the guard failed it half-way and a mutual inverse pair could never be removed. The whole removal is now checked before the setting is saved, and references among the removed types do not block it. - The repair wrote fqnHash with a whole-FQN hash; it now writes through the entity DAO (update by id, insert with the per-part FQN hash). - The repair walked soft-deleted owners and could bring back a pair deleted on purpose. Demands now start from live types and stored relations and follow what each undeleted type references. - A recreated inverse copies its partner's reference shape: REST writes nameless references, which relation reads never invert, and a named back-link would have reinterpreted those relations. - The repair is a fixed point and runs on every 2.1.0 data migration, so damage a pod on the unguarded build leaves during a rolling upgrade is repaired too. - Names compare binary on MySQL in the guard and the repair. - The ontology export omits an axiom whose FQN-only reference names a type that does not exist yet (the UI creates inverse pairs that way) instead of failing; an unresolved id still fails it. Tests: the RDF-imported pair (named references, the path in the issue) in both ITs with the relation types each side reads, the settings path, @isolated on the repair IT, and unit tests for the planner fixpoint, the reference shape and the writer.
Keep a symmetric property's self-reference while leaving its named partner without an inverse. A one-way B-to-A link beside A's self-inverse changes B-authored edges to A during UUID canonicalization. Retain fresh-state partner completion, cover both UUID orderings with a three-term HTTP regression, and trim inverse-wiring comments to constraints.
2.1 has not been released to any client: installs upgrading from 2.0.x create their relationship types inside the 2.1.0 migration itself, so only unreleased 2.1/main builds and the 2.1.0 pre-releases can hold a type deleted while in use, and restoring it or recreating it under the same name through the API makes those reads work again. The repair, its planner, their tests and the v210 hooks are removed, so this change no longer touches the 2.1.0 data migration. An independent code review found three gaps in the deprecated settings path, fixed here: - Removing a type that holds a reference written by FQN before its target existed threw a NullPointerException after the setting was saved; such a reference names no removed type. - The pre-save check read stored definitions, so a write that drops one side of an inverse pair while clearing the other side's inverse was refused; it now checks against the definitions that write saves. - A listed type that was soft-deleted is brought back before the other listed types, so one naming it is not refused after the save. The settings ITs restore the shared setting in a finally block, and a new case pins the binary name match on MySQL.
Resolve inverse predicates to their governed types and prepare every new candidate before saving any pair. Skip invalid pairs together so validation cannot leave the first type pointing at an absent partner. Recheck existing claims before insertion and before partner updates, clearing our new inverse when either check loses. Preserve fresh governed fields while making the remaining non-atomic window explicit. Exercise actual symmetric wiring, record the identity-preserving rule, and cover contradictory partners, predicate reuse, and controlled concurrent claims through real HTTP integration tests.
…ionship-type-delete-guard
…tric-inverse-partner
The importer registers both halves of an owl:inverseOf pair. When one half names a soft-deleted type, that type is now written first and keeps its stored id, so the reference to it passes the soft-deleted-reference check and points at the real record. GlossaryRdfImportIT cleanup clears the inverses it created before deleting the types, since neither half of a pair can be deleted while the other names it.
Complete an existing partner with updateIfCurrent on an unchanged original, treating a stale version or a late validation failure as a lost claim that clears the new type's inverse. Resolve authored and inverse predicates against the registry and the current batch, so one predicate never gets two types. Run the same read-only validation in dry runs, limit rejection to types actually wired to an invalid one, and name every skipped type. Replace the MySQL trigger and named lock with portable JDBI gates, giving the pre-insert, post-insert, compare-and-set and partner-validation checks their own failing-without-it tests. Record the governed-predicate, skip-as-a-whole and lost-claim rules in a decision record.
Another type naming the deleted type as its inverse no longer blocks the delete: the delete clears each live partner's inverse in the same transaction, as a versioned, version-checked change of the partner with its own change event. The delete is still refused while a relation is stored as the type or as such a partner, since relations stored as the partner read as the deleted type from their other end. Restore links an unused partner back and otherwise clears the restored type's inverse, so no one-way link is left. The deprecated settings write follows the same rule.
When the partner's version comparison fails, re-read it once: accept a partner that now points at the new type, retry the conditional write once when it is still unclaimed, and clear the new inverse only when another type claimed it or it keeps changing. Concurrent imports making the same claim and unrelated partner edits no longer leave a one-way pair. Validate new definitions before wiring inverse pairs. A rejected definition no longer claims a partner that declares no inverse, so the partner pairs with the next valid claimer regardless of IRI order; a definition whose own declaration names a rejected one is still skipped with it. Move the in-batch predicate test to a unit test with an injected resolver instead of deleting the seeded skos:related row, add same-claim and unrelated-edit gate cases plus the reverse-sorted claimer variant, align the decision record with the code, and drop a redundant impact-map entry.
…e-partner' into fmcardoso/38112-relationship-type-delete-guard # Conflicts: # openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GlossaryRdfImportIT.java # openmetadata-service/src/main/java/org/openmetadata/service/rdf/GlossaryRdfImporter.java
The delete guard, the inverse back-link clearing, the restore rule and the deprecated settings removal move unchanged into RelationshipTypeReferenceGuard, which the repository delegates to. The guard also answers which inverse a type keeps when it is restored, for an RDF dry run to plan against.
A predicate the import names, as an edge or a declared inverse, that only a soft-deleted type holds now brings that type back instead of registering a new type beside it. The predicate decides, the name only when no type holds the predicate, and a type whose own predicate a live type holds is never restored. A real import restores the type before collecting definitions, so validation and wiring see a live governed type; a dry run restores nothing, reports the type, and validates and wires against it as its restore would leave it.
When a relationship type in the imported file failed validation, the real import still tried to add each edge that used it and reported "Relationship type '<t>' is not registered" per edge, while the dry run dropped those edges silently. Counts matched, but the two runs returned different messages, and the real-run wording hid the cause. Both runs now skip edges whose type was skipped as invalid before reaching the repository, with one message per edge: "Relation <t> skipped: its relationship type '<t>' was skipped as invalid".
- Compare relation type names on MySQL after converting the column to utf8mb4, as the 2.1.0 migration does, so utf8mb3 and latin1 databases can count relations. - Reject restoring a live type before anything is written, and write the restored pair's link back in the shape of the restored type's own inverse reference. - Remove types from the deprecated settings write in one transaction and detach references among them by id, FQN or name, whatever the order. - Restore an imported type only by its predicate; skip a new type whose name a deleted type holds on another predicate, and record import restores as change events. - Say a term relation's type is deleted rather than not registered. - Tighten the tests the review named.
…e-partner' into fmcardoso/38112-relationship-type-delete-guard # Conflicts: # openmetadata-service/src/main/java/org/openmetadata/service/rdf/GlossaryRdfImporter.java
| RelationshipType restored = | ||
| JsonUtils.deepCopy(type, RelationshipType.class) | ||
| .withDeleted(false) | ||
| .withInverse(relationshipTypeRepository().inverseKeptOnRestore(type)); | ||
| restorableByPredicate.put(restored.getRdfPredicate().toString(), restored); |
There was a problem hiding this comment.
Restore preview misses inverse conflicts. The dry run copies the restored type but does not apply the partner change made by
afterRestore. Start with an unused pair A/B, then soft-delete A. Import an edge using A and another using a new C that declares B as its inverse. The preview leaves B.inverse empty and accepts C/B without a conflict warning. The real import first restores A/B, then clears C.inverse because B already names A.
Apply the restore’s partner changes to the preview’s shared set of definitions before checking new pairs, and cover this three-type case.
| InOrder order = inOrder(repository); | ||
| order.verify(repository).createOrUpdate(isNull(), any(RelationshipType.class), eq(UPDATED_BY)); | ||
| order.verify(repository).deleteTogether(UPDATED_BY, Set.of("partOf", "hasPart")); |
There was a problem hiding this comment.
Test checks calls, not results. This changed test only checks that
createOrUpdate and deleteTogether were called in order. It still passes if those calls leave the removed types in place. The repository guide requires: “Assert on observable outcomes (API responses, DB state), not internal verify() calls.” Replace these call checks with assertions that the kept type remains and both removed types are gone.
Context Used: CLAUDE.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
#38147 was squash-merged into main; conflicts resolved against its PR head, so this PR's diff is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01M4KprReeYHb7DDyP4ujmSX
Code Review ✅ Approved 🔴 High risk 4 closed / 4 findingsThe delete guard and inverse-pair updates protect stored relationship integrity; inconsistency could leave glossary relations unreadable or change their interpretation. Blocks deleting a relationship type while other types or stored glossary term relations still reference it, and clears the partner's inverse when one side of an unused inverse pair is deleted. Restore and RDF import now handle soft-deleted types consistently. Approved; the MySQL case-insensitive name match, stale settings pre-check, symmetric self-inverse on restore, and restore-clearing-inverse-on-live-type issues were resolved, with no open findings. ✅ 4 closed✅ Edge Case: MySQL name match in delete guard ignores case
✅ Edge Case: Settings pre-check reads stale type definitions, not the incoming ones
✅ Edge Case: Restored symmetric type keeps a self-inverse pointing at the stable id
✅ Bug: Restore on an already-live type can clear its inverse while it holds relations
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 |
- restore links the partner back with the canonical reference - refersTo matches by id or FQN; every guard read goes through the heal, which also gives a reference stored with only a name its FQN - reads, deletes and cardinality use the live inverse; storing a relation whose declared inverse names no live type is refused in both directions - canonical reference is identity only (no displayName/description) - an id-only reference is accepted; only carried parts are compared - read heal keeps disjointWith order - amend the delete-guard record (v2)
Stacked on #38147; merge that first, then this retargets to main.
Describe your changes:
Fixes #38112
A relationship type is referenced by other types (
inverse,replacedBy,propertyChain,disjointWith) and by stored glossary term relations (relationType/relationshipTypeId). Every reader resolves those against live types, but the delete only refused system types. Deleting a type in use therefore made term reads, the term list, PATCH and the ontology export of the affected glossaries fail with 400Relationship type 'X' is not registered, and a PATCH on a type whose chain member was deleted returned 404.RelationshipTypeRepository.preDeletenow rejects a soft or hard delete with 400 while another type (live or soft-deleted) names the type inreplacedBy,propertyChainordisjointWith, or any stored glossary term relation is stored as it. The message names those types and counts the relations.inversedoes not block; the delete clears each live partner'sinversein the same transaction, as a versioned change of the partner by the deleting user with its own change event. The partner is written only if it is unchanged since the delete read it (optimistic version check), otherwise the delete returns 412 and nothing is written. A symmetric type's own inverse never blocks.inverseonly as one half of a pair: a live partner with no inverse and no stored relation is linked back (same version check); otherwise the restored type's inverse is cleared. A one-way link would read a relation authored as the restored type from the higher term id back as the partner; the restored type holds no relation, so clearing its inverse changes no reading.preparerejects a create/update whose references name a soft-deleted type (main accepted it with 201, which led to the same broken state).PUT/PATCH /v1/system/settings, which saves the setting and then deletes the removed types) checks the whole removal before saving, against the definitions that write saves; references among types removed together (an inverse pair) do not block it, and a listed soft-deleted type is brought back before the others.the name is held by a deleted relationship type on <predicate>; restore or rename it, and its relations are reported as skipped like any skipped type's. (Fixes #38042: validate RDF inverse pairs before registration #38147 alone would save the new type over the deleted one by name, re-pointing it at the authored predicate and replacing its definition.) A real import restores the type before collecting definitions, so validation and wiring see a live governed type with its stored definition, and records a restore change event; a dry run restores nothing, reports "is deleted and would be restored", and validates and wires against the type as its restore would leave it (same counts as the real import). Recorded as v3 ofADR:2026-11-18-rdf-import-registers-governed-inverse-components.RelationshipTypeReferenceGuard;RelationshipTypeRepositorydelegates to it.docs/decisions/2026-11-18-a-relationship-type-in-use-cannot-be-deleted.md.Type of change:
High-level design:
inverse, dropping a chain member) would drop or silently reinterpret stored relations; clearingA.inversechanges how every existingArelation reads from its target side. Tolerant readers hide the corruption and still fail on other paths (list, PATCH, export).hardDelete=true.CONVERT(relationType USING utf8mb4) COLLATE utf8mb4_bin, as the 2.1.0 migration does since fix(migrations): let the 2.1.0 relationship type backfill run on utf8mb3 and latin1 MySQL databases #37189, becauserelationTypetakes the database character set (utf8mb3/latin1) whereutf8mb4_binis invalid.Relationship type '<t>' is deleted; restore it first, as relationship-type writes do, instead ofis not registered.DELETE /v1/relationshipTypes/{id}(the only delete endpoint for relationship types) on a custom type that relations or other definitions use returns 400 instead of 200; deleting one side of an unused inverse pair returns 200 and clears the partner'sinverse. Unreferenced custom types and system types behave as before. The settings page already shows the server message in its error toast.Tests:
Use cases covered
inverseis cleared and recorded as a change event; deleting both sides in turn worksreplacedByreference → 400 naming only thereplacedByreferrer, the pair stayspropertyChain/disjointWith/replacedBy→ 400 until the reference is removedinversenames a soft-deleted type → 400Unit tests
RelationshipTypeReferencesTest,RelationshipTypeRdfWriterTest; updatedLegacyRelationshipTypeSynchronizerTestLegacyRelationshipType*Test,RelationshipType*Test,GlossaryOntologyModelBuilderTest,GlossaryRdfImporter*Test,SoftDeletedRelationTypesTest,OntologyMigrationTest,IngestionPipelineMigrationEntryPointTest,v1125 MigrationTest— 105 run, 0 failures on the final headBackend integration tests
RelationshipTypeDeleteGuardIT(32 cases) and helperRelationshipTypeTestSupport;GlossaryRdfImportITgainsimportRestoresASoftDeletedInverseFoundByItsPredicate(2 cases: a type an earlier import registered, and a governed type whose name differs from the IRI local name; each runs a dry run then the real import) and a cleanup that hard-deletes pairs in any orderRelationshipType*IT,GlossaryTermRelation*IT,GlossaryRdfImportIT,GlossaryRdfImportConcurrencyIT,GlossaryCsvRelationTypesIT— 417 run, 0 failures, 32 skipped (inheritedBaseEntityITcases), including 44GlossaryRdfImportIT, 6GlossaryRdfImportConcurrencyITand 35RelationshipTypeDeleteGuardITcases. An earlier run of the same lane hit a MySQL deadlock (500) inGlossaryRdfImportIT's custom-property cleanup (main's code, concurrent PATCHes of the sharedglossaryTermtype), twice in different tests; the rerun was cleanGlossaryOntologyExportIT,SystemResourceIT— 80 run, 0 failuresRelationshipTypeDeleteGuardIT,GlossaryRdfImportIT— 79 run, 0 failuresmainalready has (system types, unreferenced delete) and two settings cases that guard against this change's own regressions. Reverting only the MySQL binary name match fails the case-variant test (expected 200 but was 400). After mergingmain, its new pair tests failed in cleanup (7 of 33, 400 because the other half names the type), and the new import case failed with 400named in inverse is deletedbefore the importer changeRelationshipTypeRepositoryandRelationshipTypeReferencesreverted to the previous commit, 15 of the 32 guard cases fail (every unused-pair delete, restore and settings back-link case, plus the message checks)GlossaryRdfImporterreverted to the merge with Fixes #38042: validate RDF inverse pairs before registration #38147, bothimportRestoresASoftDeletedInverseFoundByItsPredicatecases fail (the import-created case skips the forward type as naming a deleted inverse; the governed case plans an alias beside the deleted type)restoringALiveTypeIsRefusedAndChangesNothing,aRestoredApiPairReadsItsRelationsAsOneNeverDeleted,aTermRelationNamingADeletedTypeSaysToRestoreIt, bothimportSkipsANameHeldByADeletedTypeOnAnotherPredicatecases and bothimportRestoresASoftDeletedInverseFoundByItsPredicatecases (restore change event)character-set-server=utf8mb3, the oldrelationType COLLATE utf8mb4_bin = ?fails withERROR 1253 COLLATION 'utf8mb4_bin' is not valid for CHARACTER SET 'utf8mb3'; the new expression returns the binary-exact count (1 ofcites/Cites)Ingestion integration tests
Playwright (UI) tests
Visual regression baselines
Manual testing performed
Live HTTP probe against a server built from
main(MySQL 8.3 + Elasticsearch 9.3): deleting a type used by a relation returned 200, then GET term?fields=relatedTerms, the term list, PATCH andexportOntologyall returned 400; deleting a REST-created inverse returned 200 and brokeexportOntology; PATCH on a type whose chain member was soft-deleted returned 404; a new type naming a soft-deleted inverse was accepted (201).entityUpdatedchange event whosefieldsDeletedisinverse; restoring the deleted side linked the partner back. A relation authored as A from the higher term id is stored as B, and deleting A returns 400 (its inverse 'B' is used by 1 glossary term relation). A back-link plusreplacedByreturns 400 naming only thereplacedByreferrer. Symmetric delete/restore stays 200. After the partner gained a relation, restoring A returned 200 with A's inverse cleared and B untouched.is deleted and would be restoredleaving it deleted while the real import restores it under its id, wires the pair and adds 3 relations; a deleted governed type whose name differs from the local name got an alias registered beside it before, and now it is restored and paired with no alias, dry-run counts matching the real import. Deleting one side of an unused pair on the stacked tip returns 200 and clears the partner's inverse.mainfor damage from earlier deletes: after a hard delete, POSTing the type again under its name (imported pair: with its inverse) brings every read back to 200; after a soft delete, POST returns 409 andPUT …/restorebrings reads back.Known follow-ups (not fixed here):
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: I updated the migration scripts or explained why it is not needed. (No schema change.)
For a UI feature or feature task: not applicable.
I have added tests (unit / integration / Playwright as applicable) and listed them above.
Self-review against
REVIEW.mdand an independent code review; findings fixed or answered in the follow-up commitsDecision check:
docs/decisions/2026-11-18-a-relationship-type-in-use-cannot-be-deleted.mdI have added a test that covers the exact scenario we are fixing.
🤖 Generated with Claude Code
The test must meet the repository's explicit requirement before merging; the preview mismatch is non-blocking.
Findings
Summary
Protects relationship types from deletion while definitions or stored glossary relations still use them, and keeps inverse pairs consistent during deletion and restore.
fmcardoso explicitly accepts the relation-write/delete race documented in the decision record. fmcardoso also defers repair of earlier pre-release deletions and the UI refresh, delete-dialog, and restore-notice follow-ups.
Reviews (2) · Last reviewed commit: "Merge origin/main into fmcardoso/38112-r..." · Reviewed by Greptile