Skip to content

fix(data-quality): stop orphan test cases from breaking search indexing - #28159

Merged
harshach merged 10 commits into
mainfrom
harshach/fix-orphan-testcase-cleanup
May 26, 2026
Merged

harshach merged 10 commits into
mainfrom
harshach/fix-orphan-testcase-cleanup

Conversation

@harshach

@harshach harshach commented May 15, 2026 •

Copy link
Copy Markdown
Collaborator

Describe your changes:

When a table is hard-deleted, the cascade table → executable test suite → test cases works in the happy path but can leave test cases orphaned (legacy data, partial cascade failure, or test cases attached only to a logical suite). The next reindex throws EntityNotFoundException("Error occurred when retrieving executable test suite for testCase ...") — and because that message doesn't match the stale-reference allow-list in ReindexingUtil.isStaleReferenceError, the indexing app surfaces it as a real failure.

This PR fixes the bug in four layers and adds a sweeper to clean up any orphans that already exist:

  1. Listing tolerance & self-healing (TestCaseRepository): setFields and getTestSuites no longer throw on missing test suites; they delete the dangling entity_relationship row inline so the next read self-heals. fetchAndSetTestSuitesData does the same for the bulk path.
  2. Cascade safety net (TableRepository.entitySpecificCleanup): finds any test case whose entityFQN matches the deleted table FQN (LIKE-escaped via the new LikeEscape helper) and any leftover table → testSuite relationship rows, and hard-deletes them through Entity.deleteEntity so time-series, resolution status, and search docs are cleaned up too.
  3. Periodic sweeper (OrphanTestCaseCleanup + DataRetention): scans test_case, parses each entityLink, looks up the target entity, and deletes the test case when the target is gone. Soft-deleted test cases are skipped.
  4. Audit trail (EntityRepository.cleanup): now threads deletedBy to a new entitySpecificCleanup(String, T) overload so cascade-deletes are credited to the real operator instead of a hard-coded "admin". The original signature still delegates, so the 9 existing overrides keep working unchanged.

Type of change:

  • Bug fix

High-level design:

  • TestCaseRepository.findExecutableTestSuiteForTestCase is the new non-throwing variant used by setFields. The throwing getTestSuite is kept because getOrCreateTestSuite still uses the exception for control flow.
  • TableRepository.deleteResidualTestCases runs after the standard deleteChildren cascade as a backstop. It uses a new CollectionDAO.TestCaseDAO.findIdsByEntityFQN SQL with ESCAPE '\' so _ and % in table FQNs don't over-match.
  • OrphanTestCaseCleanup is the complement to EntityRelationshipCleanup: that utility cleans broken rows in entity_relationship, but it can't reason about the string-based entityLink pointer. The new sweeper runs in DataRetention after the relationship pass so a recently-restored suite doesn't get its test cases wiped.
  • entitySpecificCleanup(String deletedBy, T) is additive — the default implementation delegates to the old entitySpecificCleanup(T), so AppRepository, PipelineRepository, QueryRepository, TestCaseRepository, etc. don't need changes. TableRepository opts into the new overload.

Tests:

Use cases covered

  • Hard-deleting a table cascades through to all attached test cases AND the executable test suite.
  • Listing test cases for a surviving table works correctly when a sibling table's test cases have just been wiped (no EntityNotFoundException leaking through setFields).
  • The DataRetention sweeper deletes test cases whose entityLink target is gone, but leaves soft-deleted test cases alone.
  • LIKE escaping prevents my_table from matching myXtable when searching by FQN prefix.

Unit tests

  • Added.
  • Files: openmetadata-service/src/test/java/org/openmetadata/service/util/OrphanTestCaseCleanupTest.java (4 tests), openmetadata-service/src/test/java/org/openmetadata/service/util/LikeEscapeTest.java (6 tests).

Backend integration tests

  • Added.
  • Files: openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TestCaseResourceIT.java — test_deleteTableCascadesTestSuiteAndTestCases and test_listTestCasesReturnsTestSuiteFieldAfterCascade.

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Manual testing performed

  • Confirmed the orphan pattern on a production Postgres instance running 1.12.8: 394 orphan test cases, all pointing at a single hard-deleted table.
  • Wrote and executed the SQL cleanup transaction documented in the issue, then verified the indexing app no longer surfaces the error.

UI screen recording / screenshots:

Not applicable.

Checklist:

  • I have read the CONTRIBUTING document.
  • I have commented on my code, particularly in hard-to-understand areas.
  • I have added tests (unit / integration) and listed them above.
  • I have added a test that covers the exact scenario we are fixing.

🤖 Generated with Claude Code


Summary by Gitar

  • Data Retention:
    • Added a MAX_ORPHAN_CLEANUP_ITERATIONS cap to executeOrphanCleanup to prevent infinite loops in DataRetention jobs.
  • Refactoring:
    • Cleaned up imports and static references in TestCaseResourceIT to improve code readability.
  • Database Compatibility:
    • Migrated LikeEscape and CollectionDAO from ESCAPE '\' to ESCAPE '!' to resolve MySQL string-literal conflicts and JDBI parsing issues.
    • Updated LikeEscapeTest to reflect the new bang-based escaping convention and ensure backslash literals are preserved.

This will update automatically on new commits.

Hard-deleting a table could leave test cases behind whose relationship still
pointed at the deleted executable test suite. The reindex loop then choked on
"Error occurred when retrieving executable test suite for testCase ..." because
that message doesn't match the stale-reference allow-list.

Four layers of the fix:
1. TestCaseRepository.setFields / getTestSuites now tolerate hard-deleted suites
   and self-heal orphan relationship rows on the next read instead of throwing.
2. TableRepository.entitySpecificCleanup is a safety net for the cascade: it
   finds test cases by entityFQN (LIKE-escaped) and any leftover table->suite
   relationships, deleting them through the standard path so time-series,
   resolution status, and search docs are also cleaned up.
3. New OrphanTestCaseCleanup is wired into DataRetention to sweep test cases
   whose entityLink target is gone (the entity-relationship cleaner can't reason
   about string-based entityLink pointers). Skips soft-deleted test cases.
4. EntityRepository.cleanup now threads deletedBy through to a new
   entitySpecificCleanup(String, T) overload so cascade-deletes are credited to
   the actual operator instead of a hard-coded "admin"; the original signature
   still delegates so the nine existing overrides keep working unchanged.

Tests: 6 LikeEscapeTest + 4 OrphanTestCaseCleanupTest unit tests, plus two new
integration tests in TestCaseResourceIT covering the cascade and post-cascade
listing.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 15, 2026 20:03
@github-actions github-actions Bot added backend safe to test Add this label to run secure Github workflows on PRs labels May 15, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

1. Fix offset pagination bug: each successful delete shifts subsequent rows
   backward, so advancing the offset by the full batchSize skipped exactly that
   many rows. Now advance by batchSize - deletedInBatch so one run completes
   cleanup instead of needing repeated passes.
2. Narrow EntityLink.parse catch from Exception to IllegalArgumentException so
   only genuinely malformed links lead to deletion; any unexpected runtime
   error skips the row to avoid accidental data loss from a future parser bug.
3. Replace fully-qualified JsonUtils reference with a proper import.

New unit test verifies the offset is advanced by survivors, not the batch size.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@github-actions

github-actions Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

🟡 Playwright Results — all passed (10 flaky)

✅ 4247 passed · ❌ 0 failed · 🟡 10 flaky · ⏭️ 87 skipped

Shard Passed Failed Flaky Skipped
✅ Shard 1 299 0 0 4
🟡 Shard 2 804 0 1 8
🟡 Shard 3 791 0 5 8
✅ Shard 4 845 0 0 12
✅ Shard 5 719 0 0 47
🟡 Shard 6 789 0 4 8
🟡 10 flaky test(s) (passed on retry)
  • Features/Glossary/GlossaryMiscOperations.spec.ts › should delete glossary and remove tags from assets (shard 2, 1 retry)
  • Features/KnowledgeCenterTextEditor.spec.ts › Rich Text Editor - Text Formatting (shard 3, 1 retry)
  • Features/KnowledgeCenterTextEditor.spec.ts › Rich Text Editor - Text Formatting (shard 3, 1 retry)
  • Features/KnowledgeCenterTextEditor.spec.ts › Rich Text Editor - Text Formatting (shard 3, 1 retry)
  • Features/RestoreEntityInheritedFields.spec.ts › Validate restore with Inherited domain and data products assigned (shard 3, 1 retry)
  • Features/RTL.spec.ts › Verify Following widget functionality (shard 3, 1 retry)
  • Pages/GlossaryImportExport.spec.ts › Glossary CSV import preserves typed relations (shard 6, 1 retry)
  • Pages/Lineage/LineageFilters.spec.ts › Verify lineage schema filter selection (shard 6, 1 retry)
  • Pages/ServiceEntity.spec.ts › Tier Add, Update and Remove (shard 6, 1 retry)
  • Pages/UserDetails.spec.ts › Admin user can edit teams from the user profile (shard 6, 1 retry)

📦 Download artifacts

How to debug locally
# Download playwright-test-results-<shard> artifact and unzip
npx playwright show-trace path/to/trace.zip    # view trace

Copilot AI review requested due to automatic review settings May 17, 2026 19:28

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

DataRetention.executeOrphanCleanup: replace `while(true)` with a
1000-iteration cap (10M rows at BATCH_SIZE=10k) so a delete query that
always returns non-zero (e.g., rows blocked by FK constraints) can't
spin forever and block the rest of the DataRetention job. Warns when
the cap is hit so remaining work is visible; surviving rows are picked
up on the next scheduled run.

TestCaseResourceIT.test_recursiveHardDeleteCascadesPastResolutionStatusChildren:
replace inline FQNs with imports for CreateTestCaseResolutionStatus and
TestCaseResolutionStatusTypes, matching project convention.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@sonarqubecloud

Copy link
Copy Markdown

@harshach
harshach merged commit 1d4834d into main May 26, 2026
95 of 97 checks passed
@harshach
harshach deleted the harshach/fix-orphan-testcase-cleanup branch May 26, 2026 16:08
@github-actions

Copy link
Copy Markdown
Contributor

Failed to cherry-pick changes to the 1.13 branch.
Please cherry-pick the changes manually.
You can find more details here.

@github-actions

Copy link
Copy Markdown
Contributor

Failed to cherry-pick changes to the 1.12.9 branch.
Please cherry-pick the changes manually.
You can find more details here.

This branch was previously deployed

1 inactive deployment
test — b971b365 Deployed May 26, 2026 by mohityadav766 via playwright-ci-postgresql (3, 6) #48617
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.

3 participants