Skip to content

Fixes #38112: reject deleting a relationship type that is still in use - #38140

Merged
fmcardoso merged 19 commits into
mainfrom
fmcardoso/38112-relationship-type-delete-guard
Nov 19, 2026
Merged

fmcardoso merged 19 commits into
mainfrom
fmcardoso/38112-relationship-type-delete-guard

Conversation

@fmcardoso

@fmcardoso fmcardoso commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

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 400 Relationship type 'X' is not registered, and a PATCH on a type whose chain member was deleted returned 404.

  • RelationshipTypeRepository.preDelete now rejects a soft or hard delete with 400 while another type (live or soft-deleted) names the type in replacedBy, propertyChain or disjointWith, or any stored glossary term relation is stored as it. The message names those types and counts the relations.
  • Deleting one side of an unused inverse pair works (soft or hard): another type naming the deleted type as its inverse does not block; the delete clears each live partner's inverse in 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.
  • The delete is still rejected while a relation is stored as such a partner: relations are stored from the lower term id, so one authored as the deleted type from the higher id is stored as the partner, and every relation stored as the partner reads as the deleted type from its other end. Clearing the inverse would make those read as the partner at both ends.
  • Restore keeps a type's inverse only 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.
  • prepare rejects a create/update whose references name a soft-deleted type (main accepted it with 201, which led to the same broken state).
  • The deprecated settings write (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.
  • RDF import naming a soft-deleted type (on top of Fixes #38042: validate RDF inverse pairs before registration #38147's predicate-keyed registration): a predicate the import names, as an edge or a declared inverse, that only a soft-deleted type holds brings that type back instead of registering a new type beside it. Only the predicate decides, one type per predicate, never onto a predicate a live type holds. A soft-deleted type holding only the name the import would register, on another predicate, is never restored (that would move the authored edges onto its predicate): the new type is skipped with 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 of ADR:2026-11-18-rdf-import-registers-governed-inverse-components.
  • The delete guard, back-link clearing, restore rule and settings removal live in RelationshipTypeReferenceGuard; RelationshipTypeRepository delegates to it.
  • The ontology export omits an axiom whose FQN-only reference names a type that does not exist yet (the UI creates an inverse pair that way) instead of failing; an unresolved id still fails it.
  • No repair for types deleted earlier: 2.1 has not been released, so only unreleased 2.1/main builds and the 2.1.0 pre-releases can hold one; restoring the type (soft delete) or recreating it under the same name with its inverse (hard delete) makes those reads work again (verified live on main).
  • Decision record: docs/decisions/2026-11-18-a-relationship-type-in-use-cannot-be-deleted.md.

Type of change:

  • Bug fix

High-level design:

  • Rejected alternatives. Cascading (deleting or retyping relations, clearing an inverse, dropping a chain member) would drop or silently reinterpret stored relations; clearing A.inverse changes how every existing A relation reads from its target side. Tolerant readers hide the corruption and still fail on other paths (list, PATCH, export).
  • Soft-deleted referrers count, so a later restore can never bring back a reference to a missing type and restore needs no separate check. The UI already deletes with hardDelete=true.
  • Restore is refused with 400 for a live type before anything is written. The partner's link back is written in the shape of the restored type's own inverse reference (API-written references carry no name, and inverses apply to relations by name), so a restored pair reads its relations as one never deleted.
  • Deprecated settings removal runs in one transaction and detaches references among the removed types by id, FQN or name, so the delete order cannot make the second delete fail and a concurrent refusal leaves no partial removal.
  • MySQL: the relation count compares 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, because relationType takes the database character set (utf8mb3/latin1) where utf8mb4_bin is invalid.
  • A term relation naming a soft-deleted type now says Relationship type '<t>' is deleted; restore it first, as relationship-type writes do, instead of is not registered.
  • Known limit: a relation write and a type delete are each validated on their own, not locked together. Any glossary editor writing relations can race an admin's delete for as long as the writer's transaction is open; a relation that commits next to the deleted type brings back the original failure for that glossary (term reads, list, edits and export return 400) until the type is restored or recreated under its name. Recorded in the ADR.
  • Deleting an inverse pair: either side of an unused pair can be deleted directly, and the other side is left without an inverse; the deprecated settings write removes a pair in one call and clears a kept type's back-link to a removed type the same way. Writes to a relationship type (delete, restore, update) now run in one transaction with the partner updates they cause.
  • API change: 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's inverse. 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

  • Admin soft/hard deletes either side of an unused inverse pair → 200, the partner's inverse is cleared and recorded as a change event; deleting both sides in turn works
  • A pair with a relation stored as either side (authored from the lower or the higher term id) → both deletes 400, the pair and reads stay
  • A back-link plus a replacedBy reference → 400 naming only the replacedBy referrer, the pair stays
  • Restore of a deleted side links an unused partner back; when the partner names another inverse, has a relation, or is deleted, the restored type's inverse is cleared and the partner is untouched
  • A symmetric type's self-inverse never blocks its delete; restore keeps it
  • A soft-deleted type's back-link does not block the delete of its target; restoring it then drops the dangling inverse
  • Admin deletes a type stored relations use → 400; after removing the relation, the delete succeeds
  • Type referenced through propertyChain / disjointWith / replacedBy → 400 until the reference is removed
  • A soft-deleted type's reference still blocks the delete
  • Creating a type whose inverse names a soft-deleted type → 400
  • Unreferenced custom type: soft delete, restore, hard delete → 200; system type → 400
  • Deprecated settings write: an inverse pair removed together; a type an outside type references refused before saving; one side dropped while the other's inverse is cleared; a listed soft-deleted type brought back first
  • RDF import naming a soft-deleted inverse (import-created and REST-created) → 200, the type is restored under its stored id and the pair is wired
  • Types whose names differ only in case never count each other's relations (MySQL)

Unit tests

  • Added RelationshipTypeReferencesTest, RelationshipTypeRdfWriterTest; updated LegacyRelationshipTypeSynchronizerTest
  • LegacyRelationshipType*Test,RelationshipType*Test,GlossaryOntologyModelBuilderTest,GlossaryRdfImporter*Test,SoftDeletedRelationTypesTest,OntologyMigrationTest,IngestionPipelineMigrationEntryPointTest,v1125 MigrationTest — 105 run, 0 failures on the final head
  • Coverage % on changed classes — not measured

Backend integration tests

  • Added RelationshipTypeDeleteGuardIT (32 cases) and helper RelationshipTypeTestSupport; GlossaryRdfImportIT gains importRestoresASoftDeletedInverseFoundByItsPredicate (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 order
  • Final head (stacked on Fixes #38042: validate RDF inverse pairs before registration #38147 at 72c69ec), MySQL + Elasticsearch, parallel lane: RelationshipType*IT,GlossaryTermRelation*IT,GlossaryRdfImportIT,GlossaryRdfImportConcurrencyIT,GlossaryCsvRelationTypesIT — 417 run, 0 failures, 32 skipped (inherited BaseEntityIT cases), including 44 GlossaryRdfImportIT, 6 GlossaryRdfImportConcurrencyIT and 35 RelationshipTypeDeleteGuardIT cases. An earlier run of the same lane hit a MySQL deadlock (500) in GlossaryRdfImportIT's custom-property cleanup (main's code, concurrent PATCHes of the shared glossaryTerm type), twice in different tests; the rerun was clean
  • Final head, global-state lane: GlossaryOntologyExportIT,SystemResourceIT — 80 run, 0 failures
  • Final head, Postgres + OpenSearch: RelationshipTypeDeleteGuardIT,GlossaryRdfImportIT — 79 run, 0 failures
  • Regression proof: with the production change reverted, 13 of 18 guard cases fail and 2 of 4 writer unit tests fail; the 5 that pass are behaviour main already 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 merging main, 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 400 named in inverse is deleted before the importer change
  • Regression proof for the pair rule: with RelationshipTypeRepository and RelationshipTypeReferences reverted 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)
  • Regression proof for the import restore: with GlossaryRdfImporter reverted to the merge with Fixes #38042: validate RDF inverse pairs before registration #38147, both importRestoresASoftDeletedInverseFoundByItsPredicate cases fail (the import-created case skips the forward type as naming a deleted inverse; the governed case plans an alias beside the deleted type)
  • Regression proof for the review fixes: with the production and unit-test changes of 864aaa0 reverted on the final head, 7 of 39 cases fail: restoringALiveTypeIsRefusedAndChangesNothing, aRestoredApiPairReadsItsRelationsAsOneNeverDeleted, aTermRelationNamingADeletedTypeSaysToRestoreIt, both importSkipsANameHeldByADeletedTypeOnAnotherPredicate cases and both importRestoresASoftDeletedInverseFoundByItsPredicate cases (restore change event)
  • MySQL utf8mb3: on a MySQL 8.3 database with character-set-server=utf8mb3, the old relationType COLLATE utf8mb4_bin = ? fails with ERROR 1253 COLLATION 'utf8mb4_bin' is not valid for CHARACTER SET 'utf8mb3'; the new expression returns the binary-exact count (1 of cites/Cites)

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes; the existing relation-type specs delete unreferenced types only).

Visual regression baselines

  • Not applicable (no rendering change).

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 and exportOntology all returned 400; deleting a REST-created inverse returned 200 and broke exportOntology; PATCH on a type whose chain member was soft-deleted returned 404; a new type naming a soft-deleted inverse was accepted (201).

  • Same probe against this branch: every one of those deletes returns 400 naming the referencing type or counting the relations, and every read stays 200; a type naming a soft-deleted inverse is rejected with 400.
  • Pair rule, same probe on a server built from the previous commit vs this one: deleting one side of an unused API pair (soft and hard) went from 400 to 200, the partner going v0.1→v0.2 with an entityUpdated change event whose fieldsDeleted is inverse; 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 plus replacedBy returns 400 naming only the replacedBy referrer. Symmetric delete/restore stays 200. After the partner gained a relation, restoring A returned 200 with A's inverse cleared and B untouched.
  • Import naming a soft-deleted type, live on servers built from the merge with Fixes #38042: validate RDF inverse pairs before registration #38147 vs this tip: an import-created deleted inverse made the forward type be skipped with 0 relations (dry run and real) before, and now the dry run reports is deleted and would be restored leaving 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.
  • Recovery on main for 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 and PUT …/restore brings reads back.

Known follow-ups (not fixed here):

  • The relation-type settings UI does not refetch after a delete, so a partner shows its cleared inverse until reload.
  • The settings page always hard-deletes, and its confirm dialog stays open after a 400.
  • The RDF import modal shows restore notices in red as "skipped or need review".

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.md and an independent code review; findings fixed or answered in the follow-up commits

  • Decision check: docs/decisions/2026-11-18-a-relationship-type-in-use-cannot-be-deleted.md

  • I have added a test that covers the exact scenario we are fixing.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 4/5

The test must meet the repository's explicit requirement before merging; the preview mismatch is non-blocking.

Findings

  1. P2 Restore preview misses inverse conflicts. ▶
  2. P2 Test checks calls, not results. ▶

Summary

Protects relationship types from deletion while definitions or stored glossary relations still use them, and keeps inverse pairs consistent during deletion and restore.

  • Deletes keep relationship types available while saved relations or definitions use them.
  • Relationship-type writes reject references to deleted types.
  • Settings remove relationship types together after checking the whole change.
  • RDF imports restore deleted relationship types when their predicate returns.
  • Ontology export skips axioms that name a not-yet-created type by FQN.

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

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.
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.
@fmcardoso
fmcardoso changed the base branch from main to fmcardoso/38042-symmetric-inverse-partner November 18, 2026 21:19
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
@fmcardoso
fmcardoso marked this pull request as ready for review November 19, 2026 08:59
@fmcardoso
fmcardoso requested a review from a team as a code owner November 19, 2026 08:59
@fmcardoso
fmcardoso requested review from TeddyCr and removed request for a team November 19, 2026 08:59
@fmcardoso
fmcardoso added this pull request to stack #38191 November 19, 2026 09:02
Comment on lines +723 to +727
RelationshipType restored =
JsonUtils.deepCopy(type, RelationshipType.class)
.withDeleted(false)
.withInverse(relationshipTypeRepository().inverseKeptOnRestore(type));
restorableByPredicate.put(restored.getRdfPredicate().toString(), restored);

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.

P2 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.

Comment on lines +75 to +77
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"));

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.

P2 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!

Base automatically changed from fmcardoso/38042-symmetric-inverse-partner to main November 19, 2026 09:42
#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
@gitar-bot

gitar-bot Bot commented Nov 19, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 🔴 High risk 4 closed / 4 findings

The 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

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CoreRelationshipDAOs.java:1447-1455
countRelationsOfType matches rows with relationType = :relationshipTypeName. On MySQL, entity_relationship.relationType uses the database's default collation, which is case-insensitive. The 2.1.0 post-data migration hits the same problem: it converts the column and adds COLLATE utf8mb4_bin before comparing it to relationship_type_entity.name. Here is the trigger: on MySQL, a user tries to delete a custom type such as Cites that nothing uses, while glossary term relations still use another type named cites. The OR relationType = ... branch counts those rows, so the delete is wrongly rejected with "used by N glossary term relations". Postgres does not have this problem. To fix it, make the name comparison binary on MySQL (CONVERT(relationType USING utf8mb4) COLLATE utf8mb4_bin = :name, using @ConnectionAwareSqlQuery). Another option is to match on name only for rows where relationshipTypeId IS NULL.

✅ Edge Case: Settings pre-check reads stale type definitions, not the incoming ones

📄 openmetadata-service/src/main/java/org/openmetadata/service/resources/system/SystemResource.java:2019-2022 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RelationshipTypeRepository.java:270-283 📄 openmetadata-service/src/main/java/org/openmetadata/service/ontology/LegacyRelationshipTypeSynchronizer.java:49-54
requireRemovableTogether in validateGlossaryTermRelationSettingsUpdate checks references against the types already stored. But LegacyRelationshipTypeSynchronizer.synchronize upserts the kept types from the new setting before it calls deleteTogether, so the check and the real delete see different definitions. Two things go wrong:

  1. Valid writes are refused. Say one write removes partOf and also clears hasPart.inverseRelation. The pre-check still sees the stored hasPart -> partOf reference and returns 400. The delete would have passed, because hasPart is upserted without the inverse first.
  2. A refusal can still happen after the save. Say a kept type's new inverseRelation names a type removed in the same write. The pre-check passes, then the upsert adds the reference and deleteTogether refuses after the setting is already saved. That is the exact state the new comment at SystemResource.java:2019-2020 says this code prevents.

Fix: build the post-upsert view first. Map newConfig through LegacyRelationshipTypeMapper, overlay the result on listIncludingDeleted(), and check the removed types against that list. One way is to have requireRemovableTogether take the proposed types.

✅ Edge Case: Restored symmetric type keeps a self-inverse pointing at the stable id

📄 openmetadata-service/src/main/java/org/openmetadata/service/rdf/GlossaryRdfImporter.java:657-666
buildRelationType calls applyCharacteristics, which sets a symmetric type's inverse to type.getEntityReference() while the id is still RelationshipTypeIds.stableId(name). restoringSoftDeletedFirst changes the id afterwards with type.withId(storedId), but the self-inverse reference it already holds keeps the stable id. wireInversePartners skips symmetric types, and hydrate leaves references alone once they have an id. A REST-created type has a random id, so if that type is symmetric, soft-deleted, and then named by an import, the restore writes inverse.id = a UUID no record has. The validator still accepts it because isSelfReference also matches by FQN. Any later code that resolves inverse by id then gets a dangling reference. Fix: after swapping the id, rebuild the self-reference for symmetric types.

✅ Bug: Restore on an already-live type can clear its inverse while it holds relations

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RelationshipTypeRepository.java:334-348
EntityRepository.restoreLoadedEntity catches EntityNotFoundException when the type is not deleted and still calls postRestore(restoredEntity) with the live record (EntityRepository.java ~8350). Live types can hold a one-way inverse: a POST with inverse does not set the partner's back-link, which is why createInversePair needs a second PUT. So PUT /v1/relationshipTypes/restore on a live type A whose inverse B already names another type, or already has stored relations, takes the changeInverse(entity, null, …) branch and clears A's inverse. That changes how A's existing relations read from the higher term id, which is what rule 6 of the ADR forbids. The same no-op restore can also write a new inverse onto an unused partner B. The comment's argument that "a deleted type holds none" does not hold here, because the type was never deleted.

Fix: only re-link or unlink when this call actually restored the type, or at least skip both branches while relationsStoredAs(entity) > 0.

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

@fmcardoso
fmcardoso enabled stacked auto-merge (squash) November 19, 2026 09:56
@fmcardoso
fmcardoso merged commit 51d605f into main Nov 19, 2026
58 checks passed
@fmcardoso
fmcardoso deleted the fmcardoso/38112-relationship-type-delete-guard branch November 19, 2026 10:00
fmcardoso added a commit that referenced this pull request Nov 19, 2026
- 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Deleting a relationship type that is still in use breaks glossary term reads

2 participants