Skip to content

Fixes open-metadata/openmetadata-collate#8646: a hard delete keeps the tags of entities that share its FQN - #38126

Merged
mohityadav766 merged 7 commits into
mainfrom
fix/8646-hard-delete-same-name-tag-wipe
Nov 19, 2026
Merged

mohityadav766 merged 7 commits into
mainfrom
fix/8646-hard-delete-same-name-tag-wipe

Conversation

@mohityadav766

@mohityadav766 mohityadav766 commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Describe your changes:

Fixes open-metadata/openmetadata-collate#8646

A hard delete removes the tag labels (tag_usage) and field relationships (field_relationship) at and under the deleted entity's FQN with one prefix delete on the FQN hash. Neither table records the entity type, and an FQN is unique only within a type, so the delete also removed the rows of unrelated entities. On a customer deployment running 2.0.8, hard-deleting a pipeline service that had the same name as a database service removed the tags and tiers of every table in the database service. No version or change description recorded it. The same happened:

  • to a table, when a stored procedure with the same FQN (same schema, same name) was hard-deleted;
  • to every dashboard data model of a service (FQN service.model.name), when a chart or dashboard named model was hard-deleted;
  • to a metric whose bare name is another entity's FQN (glossary.term), when that entity was deleted;
  • to a table or Drive file column, when a metric named like the column's FQN was hard-deleted (raised in review).

This PR keeps the rows of the entities a delete leaves in place:

  • FqnKeyedRowCleanup runs the FQN-prefix deletes for both the single-entity cleanup and the bulk cascade. First it looks for entities the delete leaves in place:
    • Another type's entity with the same FQN. The rows at that FQN are its rows too, and it may own rows under it, so nothing at or under the FQN is deleted.
    • A field at a free-form FQN. A metric's bare name can equal a column's FQN. If an entity whose inline fields carry tags (EntityRepository.hasTaggedFields(): tables, topics, data models, Drive files, …) sits above a free-form FQN, nothing at or under it is deleted.
    • Entities that nest under the FQN without being its descendants. Everything except their subtrees is deleted. Only types whose FQN can nest under an unrelated FQN are searched. They opt in with EntityRepository.nestsUnderUnrelatedFqns(): dashboard data models (fixed model segment), and metrics, metric groups, knowledge pages, folders and context files (bare names, dots included).
  • Recursive deletes: before the cascade, the root checks whether its prefix delete will keep rows under its FQN for an entity it leaves in place: a same-FQN entity, or an unrelated nested one. If so, its descendants remove their own rows instead of relying on the root's single prefix delete, so the deleted subtree leaves nothing behind. A dashboard service's own data models don't count, since they are its descendants (EntityRepository.fqnParentType()).
  • ADR:2026-11-18-a-hard-delete-keeps-the-rows-of-entities-that-share-its-fqn records the rule, the 100-subtree cap and the 50-FQN probe batch. ADR:2026-11-03-a-hard-delete-removes-only-rows-of-the-deleted-entity, which deferred this case, gets a v3 amendment pointing to it.

Not in this PR: the issue's second item. The async hard delete writes no entityDeleted audit entry.

Type of change:

  • Bug fix

High-level design:

  • Approach. The delete answers "does anything else hold rows here?" before its prefix delete. Two queries do it:

    • One UNION ALL over the tables of every other taggable type (hash IN (...), unique index) finds same-FQN entities.
    • One LIKE probe over the opted-in types finds nested entities.

    Both are built from Entity.getEntityRepositories(), so Collate's types are included. They run through TagUsageDAO.listEntityFqnHashes, inside the delete's transaction.

  • Components:

    • FqnKeyedRowCleanup (new) holds the probe and the deletes.
    • TagUsageDAO.deleteTagLabelsByTargetPrefixOutside and FieldRelationshipDAO.deleteAllByPrefixOutside delete everything except the kept subtrees. The existing prefix deletes are unchanged and still run when nothing is shared.
    • EntityRepository calls the new class from cleanup() and bulkCleanupReferences(). Before the cascade, deleteChildrenOf sets CASCADE_ROOT_FQN_SHARED from FqnKeyedRowCleanup.rootKeepsDescendantRows.
  • Alternatives rejected:

    • Recording the target entity type on each tag_usage row. This is exact, but it is a schema change and backfill on a large, hot table. The backfill is ambiguous for exactly the shared rows, and every tag read would have to pass the type. It stays deferred, as in the 11-03 ADR.
    • Rejecting a service whose name another service kind already uses. This breaks deployments that name their database and pipeline services after the same workspace. It also doesn't cover table/stored-procedure or chart/data-model collisions.
  • Cost and rollout:

    • Each hard delete costs two more queries, and a recursive one two more before its cascade. Descendants that remove their own rows cost two more per batch of 50.
    • No migration and no API change. Rows a past delete already removed are not restored.

Tests:

Use cases covered

  • An async recursive hard delete of a pipeline service named like a database service keeps the tags and tier of the database's tables and columns. This is the reported scenario, run through the endpoint the UI uses.
  • A hard delete of the database service keeps the same-name pipeline service's pipeline tags. A table re-created at the deleted FQN starts with no tags.
  • A hard delete of a stored procedure named like a table keeps the table's tags.
  • A hard delete of a chart named model keeps the tags of the service's data models.
  • A hard delete of a glossary keeps the tags of a metric named like one of its terms.
  • A hard delete of a database service keeps the tags of a metric named like its database (service.db), and a table re-created at the deleted FQN starts with no tags.
  • A chart re-created at the FQN of a hard-deleted chart named model starts with no tags.
  • A hard delete of a metric named like a table column's FQN, or like a Drive file column's, keeps that column's tags.
  • Existing cases still pass: a user or type named like a service, and a user named like an entity type.

Unit tests

  • I added unit tests for the new/changed logic.
  • Files added: openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/FqnKeyedRowCleanupTest.java (14 tests). Following review, it mocks none of the project's classes:
    • The rules are tested as pure functions: OwnedRows.keeping (including the 100-subtree cap), properPrefixes, outermost and outsideKeptSubtrees.
    • The probe and delete statements are tested as the SQL and bind values each dialect receives, using EntityDAOTest's JDBC harness.
    • Which rows survive is asserted in HardDeleteCleanupIT.
  • Coverage at bb7d63b219c (JaCoCo, FqnKeyedRowCleanupTest + EntityRepositoryRestoreTest): 100/129 lines of FqnKeyedRowCleanup and 130/185 (70%) of all changed lines in openmetadata-service/src/main. The uncovered lines are the probe-and-delete orchestration, EntityRepository.deleteChildrenOf and the one-line hooks. They run in HardDeleteCleanupIT, which JaCoCo does not instrument. The path that only deletes the rows at the FQN, past the 100-subtree cap, has no end-to-end test; only its decision is tested.

Backend integration tests

  • I added integration tests in openmetadata-integration-tests/.
  • Files updated: openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/HardDeleteCleanupIT.java (8 new tests).
  • RED before the fix: on main (bbc3497485c) the first 5 new tests fail, e.g. expected: <[PersonalData.Personal, Tier.Tier2]> but was: <[]>. The 3 existing tests pass.
  • RED for the second commit: with the pre-cascade check limited to same-FQN entities, as in the first commit, hardDeletingADatabaseServiceKeepsTheTagsOfAMetricNamedLikeItsDatabaseAndRemovesItsOwn fails with A table re-created at a deleted FQN must not inherit the deleted table's tags ==> expected: <[]> but was: <[PersonalData.Personal, Tier.Tier2]>.
  • RED for the review fixes:
    • With the field check disabled, hardDeletingAMetricNamedLikeAColumnKeepsTheColumnsTags fails with expected: <[PersonalData.Personal]> but was: <[]>.
    • With FileRepository.hasTaggedFields() returning false, hardDeletingAMetricNamedLikeAFileColumnKeepsTheColumnsTags fails the same way.
  • GREEN at bb7d63b219c: HardDeleteCleanupIT 11/11 on mysql-elasticsearch (block below) and 11/11 on postgres-opensearch. The head, afd3ee65134, changes only the ADR.

Local Java test run: PASSED

  • Commit: bb7d63b219c8 (base origin/main)
  • Finished: 2026-11-18 15:22 UTC · 5.5 min
  • Scope: focused; merge readiness is not established. Broader steps deferred: 11 (run --scope full).
Step Scope Classes Tests Failed Skipped Min Result
unit openmetadata-service (5 classes) 5 95 0 0 1.9 passed
integration mysql-elasticsearch · parallel 1 11 0 0 3.6 passed
  • Impacted, not run locally: 14 classes (listed in the details)
  • Details

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Visual regression baselines

  • Not applicable (no rendering change).

Manual testing performed

Ran the reported scenario in the UI against Docker builds of main and of this head; the recordings are under UI screen recording below. HardDeleteCleanupIT automates the same scenario through the async endpoint the UI uses. To reproduce by hand:

  1. Create a database service svc_a with a table, and give the table Tier.Tier2 and a classification tag.
  2. Create a pipeline service, also named svc_a.
  3. Delete the pipeline service with Hard delete and recursive (or DELETE /api/v1/services/pipelineServices/async/{id}?hardDelete=true&recursive=true).
  4. GET /api/v1/tables/name/svc_a.<db>.<schema>.<table>?fields=tags: on main it returns no tags; with this PR the tags remain.

UI screen recording:

Backend-only fix. The recordings show the reported scenario in the UI, once on main and once with this PR. Each ran against a Docker image built from its commit, with the same fixture:

  1. The database service sales_dw has the tables orders (Tier.Tier2 and PersonalData.Personal; column email tagged PII.Sensitive) and customers (Tier.Tier1 and PII.Sensitive; column email tagged PersonalData.Personal).
  2. A pipeline service is also named sales_dw. It is hard-deleted from its page (⋮ → Delete → Permanently Delete). The UI sends DELETE /api/v1/services/pipelineServices/async/{id}?hardDelete=true&recursive=true, and the reloaded list of pipeline services no longer shows it.
  3. orders and customers are opened again.

Before: main at bbc3497485c. Both tables lose their tier, their tags and their column tags.

pr38126-before-main.mp4

After: this PR at afd3ee65134. Both tables keep all of them.

pr38126-after-pr.mp4
Before the delete (same on both builds) Delete dialog
orders before the delete: Tier2 in the header, Sensitive on the email column, Personal in the Tags panel Delete dialog for the sales_dw pipeline service with Permanently Delete selected
After the delete, main After the delete, this PR
orders after the delete on main: no tier, no column tag and no table tag orders after the delete with this PR: Tier2, Sensitive and Personal are still shown
Recording setup
  • Builds: mvn -DskipTests package -pl openmetadata-dist -am on each commit (main in a scratch worktree), then docker/development/Dockerfile. In each image, the openmetadata-service and openmetadata-ui jars match that build's target/ by SHA-256.
  • Stacks: one healthy server container per image. /api/v1/system/version reported revision bbc3497485c1503bf3d1f5d248acc96427861589 and afd3ee6513402fda21620c1f5eab4ffab88ba5f2. Migrations ran from the same images, against Postgres 14 and Elasticsearch 9.3.0 on the host, with a separate database and cluster alias per server.
  • Data: no sample data. The fixture above was created through the REST API and recreated before each recording.
  • The recording script asserted each step:
    • the chips on screen before and after the delete;
    • the DELETE request the UI sent (202, hardDelete=true&recursive=true);
    • the service's 404, and its absence from the reloaded list;
    • a final GET of both tables (fields=tags,columns). On main, neither table nor email column had a tag left. With this PR, each had exactly its fixture tags, and the database service was still there.

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. — N/A, no schema change.

  • For a UI feature or feature task: as part of PR creation, I ran the PR build in Docker with sample data and embedded a verified GitHub-hosted recording plus build/health evidence above (or explained why this requirement is not applicable). — N/A, backend-only fix.

  • I have added tests (unit / integration / Playwright as applicable) and listed them above.

  • Self-review: I reviewed the final diff against REVIEW.md (the pr-checklist skill runs it) and fixed every 🔴 finding, or answered it on the line below.
    Reviewed at 9f7675dae49 by a reviewer with no context from this work. The first pass, on d78c9a13473, raised two 🔴s, both fixed in 94747c52c67:

    • The entity probe was a bare-template DAO statement (ADR:2026-11-03-dao-statements-bind-every-value; DaoStatementGuardTest). It now runs in a constant SELECT probe.hash FROM (<probes>) probe shell.
    • A root that keeps an unrelated nested entity's subtree left its cascade-covered descendants' rows behind. A new IT case covers this, and it is RED against the first commit's check.

    Later rounds, after the bot reviews on this PR:

    • 67289664d60 raised one more 🔴. Drive file columns carry tags outside ChildFieldResolver, so the field check missed them; bb7d63b219c fixes it with hasTaggedFields().
    • The other half of that 🔴 is answered in the ADR rather than fixed. An FQN built from its parents can still equal another entity's field: a test case or child container named like a column of its parent, or schema X.a.b against the task b of pipeline X.a. Telling those apart needs the target's entity type on each tag_usage row, which stays deferred.
    • The review of bb7d63b219c found no 🔴.

    Answered rather than fixed (🟡): the nestsUnderUnrelatedFqns() overrides on Folder, ContextFile, KnowledgePage and MetricGroup have no IT of their own. Each is a one-line opt-in into the same probe that the Metric and data-model cases cover. Adding cases would need the context-memory and knowledge-center setup.

  • Decision check: if this PR decides something the next contributor could undo — a schema field, REST path or format another component or repo must agree with, a new default or limit, an ordering that must hold, or a rule stated only in this description — it adds a record under docs/decisions/ (see its README.md). This description is gone from git log after the squash-merge.

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

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 5/5

The changes appear safe to merge within the documented scope.

Summary

Hard deletes now preserve tags and field relationships shared with surviving entities, including table and Drive file columns.

  • Hard deletes keep tags and field links shared by other entities.

No new actionable issues found. mohityadav766 explicitly deferred collisions between parent-built names and inline fields because an exact fix needs the entity type stored on each tag row. They also accepted omitting separate integration cases for four one-line repository opt-ins because those use the same tested checks.

Reviews (8) · Last reviewed commit: "docs(delete): state the general case a h..." · Reviewed by Greptile

tag_usage and field_relationship key their rows by FQN hash alone, so a hard
delete removed the rows of every entity at or under the deleted entity's FQN,
whatever its type. Hard-deleting a pipeline service named like a database
service removed the tags and tiers of every table in the database service.

Before its prefix delete, the cleanup now looks for entities the delete leaves
in place: a taggable entity of another type with the same FQN keeps every row
at and under it, and entities that nest under the FQN without being its
descendants keep their subtrees. When a recursive delete's root shares its FQN,
its descendants remove their own rows.
The root of a recursive hard delete keeps the rows under its FQN that an
unrelated nested entity holds, not only those of a same-FQN entity, so its
descendants now remove their own rows in both cases. A metric named like a
service's database no longer leaves the deleted tables' tags behind. Before the
cascade, nested entities of a type whose parent is the root's type (a dashboard
service's data models) do not count.

The entity probes run in a constant statement shell, since a DAO statement may
not be a bare template attribute (ADR:2026-11-03-dao-statements-bind-every-value).
A database that shares its FQN with a metric shows the metric's tags, and
reads propagate them to its tables as DERIVED labels. Rows a hard delete left
behind would be the table's own labels, so only those count.
Folders, context files and pages are not cascade-covered, so naming their
parent type had no effect. Only a dashboard service's data models need it, to
keep that service's cascade on its single prefix delete.
@mohityadav766
mohityadav766 requested a review from a team as a code owner November 18, 2026 13:51
@mohityadav766 mohityadav766 added safe to test Add this label to run secure Github workflows on PRs backend labels Nov 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

This PR cannot be merged until the following are addressed on its linked issue:

  • Linked issue open-metadata/openmetadata-collate#8646 does not exist or is not accessible.

The fields live on the linked issue in the Shipping project (open the issue → right sidebar → Projects). After you set them, re-run this check (or push a commit) — issue/project changes do not re-trigger it automatically.

Maintainers can bypass this check by adding the skip-pr-checks label.

@mohityadav766

mohityadav766 commented Nov 18, 2026 •

Copy link
Copy Markdown
Member Author

Local Java test run: PASSED — details

  • Commit: bb7d63b219c8 (base origin/main)
  • The summary is in the PR description.

Tests run locally

  • unit · openmetadata-service (5 classes): ContextFileRepositoryTest (12 passed), FqnKeyedRowCleanupTest (14 passed), KnowledgePageRepositoryTest (4 passed), MetricGroupRepositoryTest (24 passed), MetricRepositoryTest (41 passed)
  • integration · mysql-elasticsearch · parallel: HardDeleteCleanupIT (11 passed)

Broader coverage not executed by this focused run

  • mvn -B package -pl openmetadata-mcp,openmetadata-service -am -Dspring-boot.repackage.skip=true '-Dtest=org/openmetadata/DefaultOperationalConfigProviderTest.java,org/openmetadata/csv/**/*Test.java,org/openmetadata/csv/**/Test*.java,org/openmetadata/csv/**/*Tests.java,org/openmetadata/csv/**/*TestCase.java,org/openmetadata/schema/**/*Test.java,org/openmetadata/schema/**/Test*.java,org/openmetadata/schema/**/*Tests.java,org/openmetadata/schema/**/*TestCase.java,org/openmetadata/sdk/**/*Test.java,org/openmetadata/sdk/**/Test*.java,org/openmetadata/sdk/**/*Tests.java,org/openmetadata/sdk/**/*TestCase.java,org/openmetadata/service/**/*Test.java,org/openmetadata/service/**/Test*.java,org/openmetadata/service/**/*Tests.java,org/openmetadata/service/**/*TestCase.java,BasicAuthLoginServletTest,CommonUtilsAuthorizeOverwriteTest,CompanyContextToolTest,CreateEntityToolTest,CreateTestCaseToolTest,DefaultToolContextTest,FindByTagToolTest,GetConceptContextToolTest,GetEntityToolTest,McpChangeEventUtilTest,McpPendingAuthRequestRepositoryTest,McpResponseUtilsTest,McpServerRequestContextTest,McpUsageRecorderTest,OAuthHttpStatelessServerTransportProviderTest,OAuthTokenRepositoryTest,PatchEntityToolTest,PersonaSearchScopeTest,RootCauseAnalysisToolTest,SearchMetadataToolTest,SemanticSearchToolTest,UserSSOOAuthProviderTest' -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=parallel '-Dit.test=<506 classes>' -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=global-state '-Dit.test=<39 classes>' -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=rdf '-Dit.test=<37 classes>' -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Psearch-it -DdatabaseType=mysql -DsearchType=elasticsearch -Djpw.data.mode=ingest -Dit.test=GlossarySynonymNgramIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pcache-tests -DintegrationTests.lane=parallel -Dit.test=AlertStateIT,BundleWarmupCertificationIT,ContainerCacheCorrectnessIT,EntityCacheWriteOrderIT,OneTransactionFlushAtomicityIT,RelationshipCacheInvalidationIT,TagRenameCacheIT,UncachedReadIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pcache-tests -DintegrationTests.lane=global-state -Dit.test=CredentialRedisDownIT,CredentialRedisNoRoundTripIT,SessionRedisMultiNodeIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Ppostgres-opensearch -DintegrationTests.lane=parallel '-Dit.test=<72 classes>' -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Ppostgres-opensearch -DintegrationTests.lane=global-state -Dit.test=EntityShapeIT,GlossaryOntologyExportIT,OntologyConcurrentHardDeleteIT,PatchTableEmbeddingIT,TagRecognizerFeedbackIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Ppostgres-opensearch -DintegrationTests.lane=rdf -Dit.test=RdfGlossaryGraphIT,RdfSoftDeleteIT,RdfSoftDeleteReindexIT,RdfTagsTierCertificationIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Psearch-it -DdatabaseType=postgres -DsearchType=opensearch -Djpw.data.mode=ingest '-Dit.test=<31 classes>' -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
Impacted, not run locally (14)
  • RdfCatalogScaleIT → only with -DrdfCatalogScale=true, which no CI lane sets
  • ReindexBenchmarkIT → nightly: openmetadata-nightly k8s-java-it (scale-it)
  • TableTotalCountScaleIT → nightly: openmetadata-nightly k8s-java-it (scale-it)
  • GoogleSsoSignInUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • EntityLoaderSmokeUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • LongCompoundNameSearchUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • PipelineOwnerIndexUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • DistributedAutoTuneReindexUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • SearchAvailableAllKindsDuringReindexUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • SearchAvailableDuringReindexUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • SelectiveFieldReindexUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • SimpleReindexTriggerUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • GoogleSsoBootstrapUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • MockIdpSmokeUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
Commands
mvn -B package -pl openmetadata-service -am -Dspring-boot.repackage.skip=true -Dtest=ContextFileRepositoryTest,FqnKeyedRowCleanupTest,KnowledgePageRepositoryTest,MetricGroupRepositoryTest,MetricRepositoryTest -Dsurefire.failIfNoSpecifiedTests=false
mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=parallel -Dit.test=HardDeleteCleanupIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false

A metric's FQN is its bare name, so it can equal a table column's FQN, and
deleting the metric removed the column's tags. When an entity with inline fields
sits above a free-form FQN, the delete now keeps the rows at and under it.

FqnKeyedRowCleanupTest now asserts the rules as pure functions and the
statements each database receives, instead of DAO calls on mocks.
File columns carry tags outside the ChildFieldResolver registry, so the field
check missed a metric named like one. hasTaggedFields() gives the type-level
answer to taggedFieldContainers, and FileRepository overrides both. The ADR now
states what the checks cover and records the case they leave open.
A test case or child container named like a column of its parent shares that
column's FQN as well, not only names repeated across types at several levels.
@gitar-bot

gitar-bot Bot commented Nov 18, 2026

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

Changes hard-delete cleanup and cascade handling for FQN-keyed tags and relationships; mistakes could preserve deleted data or erase surviving entities’ metadata.

Hard deletes now keep tag labels and field relationships for entities that share an FQN with the deleted entity, fixing the wiped tags on same-name tables and data models. The FqnKeyedRowCleanupTest was reworked to check the rows that actually get deleted rather than mock calls, which was the only open item and is now resolved.

✅ 1 closed
✅ Quality: FqnKeyedRowCleanupTest checks mock calls instead of what gets deleted

📄 openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/FqnKeyedRowCleanupTest.java:44-58 📄 openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/FqnKeyedRowCleanupTest.java:75-89 📄 openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/FqnKeyedRowCleanupTest.java:249-263
The unit test mocks five of the project's own classes (CollectionDAO, TagUsageDAO, FieldRelationshipDAO, EntityRepository, EntityDAO) and also mocks the static Entity class. Most of its assertions are verify(...) calls on which DAO method ran. The project's testing rules call this wrong: "If a test mocks 3+ of your own classes to verify a call, it is wrong." They also say to assert outcomes you can observe and to avoid static mocking.

The probe stub found() picks its result by checking for substrings like " IN (" and "LIMIT 1)". So the tests pass even if the generated SQL is wrong on MySQL or Postgres, for example a bad UNION of parenthesised LIMIT selects or a wrong hash column. That SQL is the riskiest part of this change, and only the IT exercises it.

Fix: keep the pure-function tests (outsideKeptSubtrees, outermost, OwnedRows.keeping). Move the namesake, nested-holder and cap scenarios into HardDeleteCleanupIT, or into a DB-backed test that checks which tag_usage and field_relationship rows are left.

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

@mohityadav766 mohityadav766 added the To release Will cherry-pick this PR into the release branch label Nov 19, 2026

@ulixius9 ulixius9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed at afd3ee65134. The fix looks right to me: it checks for entities that share the FQN before the prefix delete, and one class (FqnKeyedRowCleanup) now does the cleanup for both single deletes and the bulk cascade. I traced CASCADE_ROOT_FQN_SHARED: every cascade entry point goes through deleteChildrenOf, and a nested delete() (such as the chart cleanup) saves and restores the outer value. The HardDeleteCleanupIT cases are real end-to-end tests, red on main and green here.

Before merge

  1. Validate PR Metadata fails because the job can't read the private Collate issue (GET .../openmetadata-collate/issues/8646 - 404). It needs an OSS issue linked, or a maintainer override.
  2. This PR fixes only the first of the issue's two items. The async hard delete still writes no entityDeleted audit entry. Consider Part of instead of Fixes, or a follow-up issue, so the audit gap isn't closed with it.

Non-blocking

  • nestsUnderUnrelatedFqns() is opt-in. A future type with bare-name FQNs that forgets the override brings the bug back with no failing test. Worth a guard test, or at least a line in DEVELOPER.md's add-an-entity checklist.
  • When a batch has any nested holder, ownedRows calls nestedHolderHashes for every FQN in the batch (up to 50 queries), not only for the FQNs that matched. This only matters on cascades under a shared root, so it's minor.
  • On Postgres, the LIKE probe has no text_pattern_ops index on the metric group, knowledge page, folder and context file tables, so it scans them in full (metric and data model tables have one). They're small for now.

// cleanup() prefix delete, unless the root keeps rows under its FQN for an entity the delete
// leaves in place (CASCADE_ROOT_FQN_SHARED). Types not FQN-nested under their delete root
// (e.g. flat-FQN teams) keep the per-entity path.
if (shouldCleanupFqnDependents() && !reliesOnCascadeRootFqnCleanup()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This fixes the bug, but it can make a recursive hard delete much slower when the name is shared.

Without a name clash, deleting a service runs one DELETE ... LIKE 'service.%'. That one statement removes the
tags of every database, schema, table and column under it.

With a name clash (e.g. a pipeline service and a database service both called sales), that statement is
skipped and every child deletes its own rows instead. So a service with 8,000 tables runs ~16,000 delete
statements in place of 2.

Tried it locally on Postgres (2.0.8 schema, ~130k tag rows, a database service with 8,000 tables and a pipeline
service with the same name), then hard-deleted the database service:

  • main: 2 statements, 0.3 s (but it also deletes the pipeline service's rows)
  • this PR: 16,044 statements, ~86 s, plus ~11 s for the lookups

The result was correct: all the deleted service's tags were gone and the other service's were kept. The time is
the issue, and it grows with the number of tables.

Suggestion: delete per batch of 50 children with one statement instead of one per child, e.g.

DELETE FROM tag_usage
WHERE targetfqnhash_lower IN (:h1, :h2, ... :h50)
   OR targetfqnhash_lower LIKE :h1_dot_percent OR ... OR targetfqnhash_lower LIKE :h50_dot_percent

That's 2 statements per 50 tables instead of 100.

if (keptSubtreeHashes.isEmpty()) {
daoCollection.fieldRelationshipDAO().deleteAllByPrefix(fqn, entityType);
if (taggable) {
daoCollection.tagUsageDAO().deleteTagLabelsByTargetPrefix(fqn);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The tag delete here filters on targetFQNHash. On Postgres that column has no index that suits a prefix LIKE,
so it falls back to the trigram (GIN) index, ~6 ms per delete.

tag_usage already has a pattern index for exactly this: idx_tag_usage_targetfqnhash_lower_pattern on
targetfqnhash_lower. Hashes are lowercase MD5 hex (EntityUtil.hash), so filtering on targetfqnhash_lower
returns the same rows.

Measured locally, 8,000 per-table deletes:

  • WHERE targetFQNHash = :h OR targetFQNHash LIKE 'h.%' → 46.5 s
  • WHERE targetfqnhash_lower = :h OR targetfqnhash_lower LIKE 'h.%' → 6.3 s

Suggestion: use targetfqnhash_lower in the Postgres version of deleteTagLabelsByTargetPrefix and
deleteTagLabelsByTargetPrefixOutside.

* {@link #deleteAllByPrefix} except the rows at and under the kept subtrees, which belong to
* entities a hard delete leaves in place.
*/
default void deleteAllByPrefixOutside(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The field_relationship delete (toFQNHash LIKE 'h.%' OR fromFQNHash LIKE 'h.%') can't use any index on
Postgres, so every call reads the whole table. EXPLAIN locally:

Delete on field_relationship
  -> Seq Scan on field_relationship   (Rows Removed by Filter: 39998)
Execution Time: 41 ms

On main it runs once per hard delete. With the per-child path from comment 1 it runs once per child: ~43 s for
8,000 tables locally, with only 40k lineage rows. An instance with millions of column-lineage rows reads the full
table 8,000 times, which could take hours.

Suggestion: batch it like comment 1, and/or add a text_pattern_ops index on fromFQNHash and toFQNHash in a
Postgres migration.

}

/** One probe per table for a row under any of the bound prefixes. */
static String anyUnderProbes(List<EntityTable> tables, Collection<String> bindNames) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Minor. This check (fqnHash LIKE 'h.%' LIMIT 1) now runs on every hard delete of a taggable entity.

  • metric_entity and dashboard_data_model_entity have pattern indexes, so it's fast (<1 ms locally).
  • knowledge_center, drive_folder, context_file and metric_group_entity don't, so on Postgres it reads
    each of those tables in full on every delete.

Small tables today, so fine for now, but worth a pattern index if Knowledge Center grows. The same-name check
(the IN lookup over all entity tables) was ~3 ms, no concern.

private OwnedRows ownedRows(String hash, boolean heldElsewhere, boolean mayHaveNestedHolders) {
OwnedRows owned = OwnedRows.NONE;
if (!heldElsewhere) {
owned = mayHaveNestedHolders ? OwnedRows.keeping(nestedHolderHashes(hash)) : OwnedRows.ALL;

@sonika-shah sonika-shah Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Minor. If the batch check finds any nested entity, nestedHolderHashes(hash) then runs once for every FQN in
the batch, up to 50 more queries, even for FQNs with nothing under them. Could the batch check return which hashes matched, so only those get the second lookup?

@mohityadav766
mohityadav766 merged commit ad4d5f2 into main Nov 19, 2026
72 of 83 checks passed
@mohityadav766
mohityadav766 deleted the fix/8646-hard-delete-same-name-tag-wipe branch November 19, 2026 12:49
@github-actions

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

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.

mohityadav766 added a commit that referenced this pull request Nov 19, 2026
…eps the tags of entities that share its FQN (#38126) (#38230)

Backport of #38126. tag_usage and field_relationship key their rows by FQN
hash alone, so a hard delete removed the rows of every entity at or under the
deleted entity's FQN, whatever its type. Hard-deleting a pipeline service named
like a database service removed the tags and tiers of every table in it.

Differences from main:
- The new TagUsageDAO and FieldRelationshipDAO statements live in
  CollectionDAO, where 2.0 keeps those DAOs.
- 2.0 has no ChildFieldResolver registry, so hasTaggedFields() defaults to
  false and the ten repositories that override taggedFieldContainers() return
  true.
- cleanup() runs both FQN-prefix deletes after entity_extension, the order
  2.0's bulk cascade already uses.
- No MetricGroup opt-in or impact-map entry; neither exists on 2.0.

(cherry picked from commit ad4d5f2)
yan-3005 added a commit that referenced this pull request Nov 23, 2026
The hard-delete cleanup from #38126 probes every taggable entity table in
one UNION ALL. MySQL rejects a UNION whose columns have different
collations, and an install's hash columns do not share one: most are
ascii_bin, the newer tables declare utf8mb4_0900_ai_ci, and
query_entity.fqnHash (renamed in 1.2.0 without a collation) takes the
server default. On a server whose default is not utf8mb4_0900_ai_ci,
every hard delete of a taggable entity fails with
"Illegal mix of collations for operation 'UNION'".

On MySQL each probe now selects CONVERT(hash USING utf8mb4) COLLATE
utf8mb4_bin. The WHERE clause still reads the bare column, so the lookup
keeps its index. No schema change.

(cherry picked from commit 4f9ccf8)
yan-3005 added a commit that referenced this pull request Nov 23, 2026
…FQN cleanup (#38443)

* Select FQN-cleanup probe hashes in one collation on MySQL

The hard-delete cleanup from #38126 probes every taggable entity table in
one UNION ALL. MySQL rejects a UNION whose columns have different
collations, and an install's hash columns do not share one: most are
ascii_bin, the newer tables declare utf8mb4_0900_ai_ci, and
query_entity.fqnHash (renamed in 1.2.0 without a collation) takes the
server default. On a server whose default is not utf8mb4_0900_ai_ci,
every hard delete of a taggable entity fails with
"Illegal mix of collations for operation 'UNION'".

On MySQL each probe now selects CONVERT(hash USING utf8mb4) COLLATE
utf8mb4_bin. The WHERE clause still reads the bare column, so the lookup
keeps its index. No schema change.

* Run the FQN-cleanup probes on a real MySQL with mixed hash collations

The SQL-string test cannot catch the collation error. This one starts
MySQL with utf8mb4_unicode_ci as the server default and three tables on
the collations an install mixes (ascii_bin, utf8mb4_0900_ai_ci, server
default). The bare-column union fails with 'Illegal mix of collations';
the namesake and nested probes return the hash from every table.
yan-3005 added a commit that referenced this pull request Nov 23, 2026
…s' in FQN cleanup (#38443) (#38444)

* Select FQN-cleanup probe hashes in one collation on MySQL

The hard-delete cleanup from #38126 probes every taggable entity table in
one UNION ALL. MySQL rejects a UNION whose columns have different
collations, and an install's hash columns do not share one: most are
ascii_bin, the newer tables declare utf8mb4_0900_ai_ci, and
query_entity.fqnHash (renamed in 1.2.0 without a collation) takes the
server default. On a server whose default is not utf8mb4_0900_ai_ci,
every hard delete of a taggable entity fails with
"Illegal mix of collations for operation 'UNION'".

On MySQL each probe now selects CONVERT(hash USING utf8mb4) COLLATE
utf8mb4_bin. The WHERE clause still reads the bare column, so the lookup
keeps its index. No schema change.

(cherry picked from commit 4f9ccf8)

* Run the FQN-cleanup probes on a real MySQL with mixed hash collations

The SQL-string test cannot catch the collation error. This one starts
MySQL with utf8mb4_unicode_ci as the server default and three tables on
the collations an install mixes (ascii_bin, utf8mb4_0900_ai_ci, server
default). The bare-column union fails with 'Illegal mix of collations';
the namesake and nested probes return the hash from every table.

(cherry picked from commit 5316487)
yan-3005 added a commit that referenced this pull request Nov 23, 2026
…s' (#38443, #37142) (#38442)

* fix(it): run the UI test MySQL on the shipped collation, and clean up a server that fails to start (#37142)

* fix(it): stop a containerized UI test server that fails to start, and fail fast after it

* fix(it): run the containerized UI test MySQL on the collation OpenMetadata ships with

* style(it): apply spotless

(cherry picked from commit 74b0529)

* Select FQN-cleanup probe hashes in one collation on MySQL

The hard-delete cleanup from #38126 probes every taggable entity table in
one UNION ALL. MySQL rejects a UNION whose columns have different
collations, and an install's hash columns do not share one: most are
ascii_bin, the newer tables declare utf8mb4_0900_ai_ci, and
query_entity.fqnHash (renamed in 1.2.0 without a collation) takes the
server default. On a server whose default is not utf8mb4_0900_ai_ci,
every hard delete of a taggable entity fails with
"Illegal mix of collations for operation 'UNION'".

On MySQL each probe now selects CONVERT(hash USING utf8mb4) COLLATE
utf8mb4_bin. The WHERE clause still reads the bare column, so the lookup
keeps its index. No schema change.

(cherry picked from commit 4f9ccf8)

* Run the FQN-cleanup probes on a real MySQL with mixed hash collations

The SQL-string test cannot catch the collation error. This one starts
MySQL with utf8mb4_unicode_ci as the server default and three tables on
the collations an install mixes (ascii_bin, utf8mb4_0900_ai_ci, server
default). The bare-column union fails with 'Illegal mix of collations';
the namesake and nested probes return the hash from every table.

(cherry picked from commit 5316487)

---------

Co-authored-by: Adrià Manero <adria.estivill@getcollate.io>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

4 participants