Skip to content

Fixes 27041: purge profiler data on table hard delete, and stop the orphan sweep deleting live column profiles - #31556

Merged
TeddyCr merged 13 commits into
open-metadata:mainfrom
TeddyCr:ISSUE-27041
Aug 20, 2026
Merged

TeddyCr merged 13 commits into
open-metadata:mainfrom
TeddyCr:ISSUE-27041

Conversation

@TeddyCr

@TeddyCr TeddyCr commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

Describe your changes:

Fixes #27041

I fixed two independent defects in the lifecycle of profiler_data_time_series, both rooted in the fact that the table is keyed by FQN hash, not by entity id.

(A) The filed bug — hard delete leaks profiler rows, and a re-created table inherits them.

TableRepository never touched profiler_data_time_series on delete. Nothing else in the hard-delete path does either: EntityRepository.cleanup deliberately skips time-series children and leaves them to the offline DataRetention sweep. So hard-deleting a table left every one of its table.tableProfile, table.systemProfile and table.columnProfile rows behind, and because the table is keyed by FQN hash, the next table created at the same FQN (re-ingestion, rename-and-recreate, IaC replay) silently adopted them — GET /v1/tables/{fqn}/tableProfile/latest returned the dead table's row counts and column statistics for a brand-new table.

(B) A second defect found while fixing (A) — the weekly sweep was deleting live column profiles. Please do not skim this one.

CollectionDAO.ProfilerDataTimeSeriesDAO.deleteOrphanedRecords deleted any row where NOT EXISTS (SELECT 1 FROM table_entity te WHERE te.fqnHash = profiler_data_time_series.entityFQNHash), with no extension filter. FullyQualifiedName.buildHash hashes each FQN part (MD5 hex) and joins with ., so a table's fqnHash always has exactly 4 dot-joined segments (service.database.schema.table) while a column profile's entityFQNHash has 5 or more. The two can never be equal. Every table.columnProfile row of every live, healthy table was therefore classified as an orphan and deleted on each DataRetention run — a weekly cron (0 0 * * 0). That is silent data loss of column-level profiling history, and it is arguably more severe than the filed bug.

It went unnoticed because OrphanedTimeSeriesCleanupIT.profilerDataOrphans only ever seeded a table-level row.

The fix resolves a column-profile row to its parent table by taking the first four hash segments — SUBSTRING_INDEX(entityFQNHash, '.', 4) on MySQL, four chained split_part(...) on PostgreSQL. Stripping exactly one segment would be wrong: nested/struct columns have FQNs like service.db.schema.table.parent.child, so their hashes carry 6+ segments and would still fail to match. Non-column extensions keep the previous raw-hash comparison, and genuinely orphaned rows are still swept.

This second defect was folded into this PR with the maintainer's explicit approval rather than filed separately, because it lives in the same table, is caused by the same hashing property, and the two fixes interact: (A)'s correctness depends on (B) no longer mis-classifying live rows.

Type of change:

  • Bug fix

High-level design:

(A) Where the purge runs, and the two properties that make it safe.

The purge is issued from TableRepository.postDelete, on the hard-delete branch only, through
AsyncService.executeDatabaseTask(DatabaseOperation.PROFILER_CLEANUP, …). It is one unbounded
DELETE per extension
— no batching, no iteration cap.

It does not run inside entitySpecificCleanup, which executes inside EntityRepository.cleanup's
transaction. A table with a long profiling history can own millions of profiler rows; draining them
there holds every row lock for the life of the request, and batching inside a single transaction
buys nothing — the locks are held to the end either way, so it is the same peak cost spread over
~1,700 round-trips instead of one statement.

Two ordering properties make the asynchronous purge safe, and they cover different failures:

  1. It runs after the delete has committed. A rolled-back delete therefore cannot purge a live
    table's history — those rows legitimately predate the attempt.
  2. It is bounded to profiles recorded at or before the delete (timestamp <= :deletedAt).
    profiler_data_time_series carries no table id, so a purge that lands after the FQN has been
    reused cannot otherwise tell the dead table's rows from its successor's. Everything a successor
    records happens after the delete, so the watermark makes the purge safe to run at any later
    point, and idempotent when it runs more than once.

Property 2 is what removes the need for a cap: the statement is unbounded because it no longer needs
to be bounded to be correct. An earlier revision of this PR ran the purge synchronously and capped it
at 1,001,000 rows; that cap silently truncated large tables, and truncated rows regain a live parent
if the FQN is reused — reintroducing the exact symptom of this issue at scale. Both are gone.

Why a prefix delete is required, not three exact deletes.

Table and system profiles are written under the table FQN, so an exact-match delete suffices.
Column profiles are written under each column FQN (TableRepository.addTableProfileData, and
EntityProfileRepository.addProfileData for the standalone endpoint), including nested columns.
Those rows are not enumerable from the table's current column list either — dropping a column does
not delete its profiler rows, so the only complete way to reach them is the FQN-hash prefix
'<table hash>.%'. delete_hardDeletePurgesProfilesOfDroppedColumns pins that.

(B) Why the orphan predicate resolves the parent from the outer row.

Correlating the other way — entityFQNHash LIKE te.fqnHash || '.%' — computes the LIKE pattern from
the inner row, which leaves no equijoin key, so both planners degrade to a nested loop over
table_entity for every profiler row. Resolving the parent from the outer row keeps a single
equality and preserves the hash anti-join.

Measured on a fixture reproducing the real column types, collation and indexes (5,000 tables /
105,250 profiler rows / 250 planted orphans), issuing the exact statement the DAO issues:

PostgreSQL 15 MySQL 8.4
LIKE-correlated (nested loop) 32,389 ms 75,637 ms
parent-hash equality (hash anti-join) 106 ms 247 ms

Both return the same 250 orphans, with an empty symmetric difference in both directions, on both
engines. The PostgreSQL plans are Nested Loop Anti Join with Rows Removed by Join Filter: 263,697,500 versus Hash Anti Join. Cost is O(profiler_rows × tables), so the nested-loop form
stops completing rather than merely slowing on a large catalog — which matters directly here,
because this PR ships no backfill and relies on the sweep to reclaim historical orphans.

Database migration:

Appended to bootstrap/sql/migrations/native/2.0.0/{postgres,mysql}/schemaChanges.sql.

PostgreSQL — adds idx_profiler_data_time_series_fqnhash_pattern, a text_pattern_ops index on entityFQNHash, built CONCURRENTLY so the migration takes no write lock.

Without it, the prefix delete cannot use an index. The only persistent index with entityFQNHash leading is the 1.1.5 unique constraint (entityFQNHash, extension, operation, timestamp); it uses the default operator class and the column inherits the database default collation, neither of which qualifies the planner for LIKE 'prefix%'. (1.9.9 does create idx_pdts_entityFQNHash_prefix, but the same script drops it again at the end — it is a migration-time helper, not a persistent index.) So every table hard delete cost at least one sequential scan of profiler_data_time_series, and a recursive service delete cost one per table.

Measured on postgres:15 (lc_collate=en_US.utf8, matching managed Postgres/RDS) against the real 1.1.5 DDL with 300k rows / 211 MB, issuing the exact statement the DAO issues with the prefix bound as text the way JDBC binds it:

Case Before After
Terminal statement, prefix matches nothing Parallel Seq Scan, 24.174 ms, 11112 buffers Index Scan, 0.056 ms, 3 buffers
Prefix matches 3000 rows Seq Scan, 16.579 ms, 3701 buffers Bitmap Heap Scan, 8.647 ms, 1006 buffers

Index size 2776 kB against a 211 MB table.

Why text_pattern_ops and not varchar_pattern_ops. entityFQNHash is VARCHAR(768), so varchar_pattern_ops is the type-matched choice on paper. But the planner normalises varchar LIKE text — what every JDBC setString bind produces — by casting the column, and the filter in the measured plan is literally (entityfqnhash)::text ~~ …. 1.13.0/postgres/schemaChanges.sql records this repo hitting a production environment where varchar_pattern_ops was consequently unused and the table seq-scanned, and the existing idx_*_fqnhash_pattern family settled on text_pattern_ops for that reason. To be plain: on PostgreSQL 15 both opclasses planned identically as an Index Scan in my fixture. This is a consistency-and-robustness choice across versions and environments, not a difference this benchmark demonstrates.

MySQL — deliberately statement-free, with the reasoning in the file rather than left as an unexplained empty script. profiler_data_time_series.entityFQNHash has been VARCHAR(768) CHARACTER SET ascii COLLATE ascii_bin since 1.1.5 — a binary collation — so InnoDB already answers a LIKE prefix predicate with a range scan on the leading column of the existing unique index. Adding a second index on the same leading column would be write overhead with no read benefit.

Operator runbook — interrupted CREATE INDEX CONCURRENTLY. An interrupted build leaves an INVALID index behind, and IF NOT EXISTS then no-ops against it forever. This is a known pattern-level gap shared with the 1.11.0 and 1.13.0 index migrations. The full detection query and remediation are in the migration file header; in short:

SELECT c.relname FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid
 WHERE NOT i.indisvalid AND c.relname = 'idx_profiler_data_time_series_fqnhash_pattern';
DROP INDEX CONCURRENTLY idx_profiler_data_time_series_fqnhash_pattern;
DELETE FROM server_migration_sql_logs
 WHERE version = '2.0.0' AND sqlstatement LIKE '%idx\_profiler\_data\_time\_series\_fqnhash\_pattern%' ESCAPE '\';

The version above is 2.0.0, not 2.1.1 — fcece67 moved this migration onto the 2.0 train. A
cleanup keyed on 2.1.1 matches nothing.

No data migration is included. With (B) corrected, the existing weekly sweep reclaims genuinely-orphaned historical rows on its own while preserving live column profiles.

Tests:

Use cases covered

  • Hard-deleting a table purges its table, system and column profiles; a table re-created at the same FQN starts clean instead of serving the dead table's profile.
  • Profiles recorded after the delete survive the purge — the property that makes the asynchronous purge race-free against FQN reuse.
  • Soft-deleting a table preserves all three, and GET /v1/tables/{fqn}/tableProfile/latest keeps serving them (it resolves with Include.ALL).
  • Recursively hard-deleting a database schema purges the profiler data of the tables it contained (bulk cascade path).
  • Hard delete purges the profiles of columns that were dropped from the table before the delete.
  • Hard delete drains a large column-profile history in full.
  • The weekly DataRetention orphan sweep preserves column profiles of live tables — including nested-column profiles — while still deleting rows whose parent table no longer exists.
  • The 2.0.0 migration leaves a valid prefix index on PostgreSQL; on MySQL the premises that make the statement-free script correct hold.

Unit tests

Not applicable — no unit-testable logic was added. The change is JDBI DAO SQL plus repository wiring, whose behaviour is only meaningful against a real database; asserting it with mocks would test mock wiring rather than whether rows are actually deleted. Covered by integration tests instead.

Backend integration tests

  • Added, in openmetadata-integration-tests/.

TableResourceIT.java:

Test Asserts
delete_hardDeletePurgesProfilerData 0 rows for all three extensions after hard delete; a table re-created at the same FQN returns profile == null, all columns[*].profile == null, and an empty systemProfile data array
delete_hardDeletePurgeSpareProfilesRecordedAfterTheDelete new — one row seeded before the watermark and one after; the purge removes only the earlier row, and the survivor is the later one. Seeding the future-dated row up front pins the boundary deterministically instead of racing the async purge
delete_softDeletePreservesProfilerData all three row groups still present after a soft delete, and still served by the API
delete_hardDeleteOfSchemaPurgesTableProfilerData recursive schema hard delete purges the contained table's rows (bulk cascade path)
delete_hardDeletePurgesLargeColumnProfileHistory 1001 seeded rows are drained in full by the single statement
delete_hardDeletePurgesProfilesOfDroppedColumns a column-only profile, whose column is then dropped via PUT /v1/tables, is still purged on hard delete; asserts its own precondition that dropping a column leaves the rows behind

OrphanedTimeSeriesCleanupIT.java:

Test Asserts
profilerDataOrphans after deleteOrphanedRecords, a live table's table / system / column / nested-column rows all survive, while table-level and column-level rows under a non-existent table are removed
profilerPrefixIndexIsAvailable PostgreSQL: the migration's index exists and pg_index.indisvalid. MySQL: entityFQNHash is the leading column of the unique index and its collation is ascii_bin — the two facts that make the statement-free MySQL script correct

Every assertion is a row count in profiler_data_time_series or a field of an HTTP response body — no mocks, no verify(), no Thread.sleep. The purge is now asynchronous, so the delete-path assertions await with Awaitility rather than asserting inline.

Results — MySQL 8 + Elasticsearch, run in both the isolated-tests and parallel-tests failsafe lanes (each applies the whole native migration chain from scratch against a fresh testcontainer, so this also exercises the migration end to end):

TableResourceIT (profiler tests)   isolated   Tests run: 6, Failures: 0, Errors: 0
OrphanedTimeSeriesCleanupIT        isolated   Tests run: 2, Failures: 0, Errors: 0
TableResourceIT (profiler tests)   parallel   Tests run: 6, Failures: 0, Errors: 0
OrphanedTimeSeriesCleanupIT        parallel   Tests run: 2, Failures: 0, Errors: 0
mvn spotless:check -pl openmetadata-service,openmetadata-integration-tests   BUILD SUCCESS

RED check on the new watermark test. Neutralising the predicate (AND timestamp <= :deletedAt → an always-true bound) and re-running delete_hardDeletePurgeSpareProfilesRecordedAfterTheDelete fails for exactly the right reason — the purge takes the successor's row too:

Purge must remove the row recorded before the delete ==> expected: <1> but was: <0>

Ingestion integration tests

Not applicable — no ingestion changes.

Playwright (UI) tests

Not applicable — no UI changes.

Manual testing performed ✅

Re-run end to end against the asynchronous design on a local Docker stack (MySQL 8 + Elasticsearch),
server built from this branch. The instance was returned to its exact starting state afterwards
(195 tables, 3 profiler rows, no leftover fixtures).

A — hard delete purges profiler data. Create service/database/schema/table with columns id and
name, then PUT /v1/tables/{id}/tableProfile with a table, column and system profile.

  1. SELECT extension, COUNT(*) … — one row per extension; GET /v1/tables/{fqn}/tableProfile/latest?includeColumnProfile=true
    returns profile.rowCount = 42 and columns[0].profile.uniqueCount = 42.
  2. DELETE /v1/tables/{id}?hardDelete=true → all three counts drain to 0.
  3. Re-create the table at the identical FQN → profile: null, every columns[*].profile null, and
    GET /v1/tables/{fqn}/systemProfile?startTs=0&endTs={now} returns "data": [].
  4. Soft-delete regression on a second table → all three rows retained and rowCount = 42 still served.
  5. Cascade regression on a third table → DELETE /v1/databaseSchemas/{id}?hardDelete=true&recursive=true
    drains its rows (the bulk path reaches postDelete per entity via bulkHardDeleteSubtree).

The purge is asynchronous, so poll rather than checking once. At 300k rows the counts were still
fully present the instant the DELETE returned. This is the one behavioural change from the previous
revision of this PR.

Scale. A single table seeded with 1,200,000 column-profile rows — deliberately above the
1,001,000 ceiling the removed cap imposed:

DELETE /v1/tables/{id}?hardDelete=true   →  200, request returned in 0.24s
[om-async-6] TableRepository - Purged 1200000 profiler row(s) for hard-deleted table …

One statement, no truncation, on the bounded AsyncService executor. Under the capped design this
would have stopped at 1,001,000 and stranded ~199,000 rows — unreclaimable by the sweep if the FQN
were reused. Timing the raw statement separately: 300,000 rows in 7.27s, so ~29s at 1.2M, all off
the request path. That delete is one transaction, so it holds those row locks for its duration; a
concurrent count over the same rows blocks until it completes.

B — the weekly sweep no longer eats live column profiles. Seeded 297,509 profiler rows across the
instance's 198 live tables (including a nested-column row, 6 hash segments) plus 500 planted orphans,
then triggered POST /v1/apps/trigger/DataRetentionApplication with -H 'Content-Type: application/json' -d '{}':

before: 297,509 rows / 500 orphans     after: 297,009 rows / 0 orphans   (2.2s)
live-table rows preserved: 297,009

Exactly the 500 orphans removed, every live row kept. Both predicates timed on that same real data,
returning the same 500 orphans:

Predicate Time
This PR (parent-hash equality) 344 ms
LIKE-correlated 6,748 ms

19.6× at only 198 tables; the gap grows with table count.

A bodyless POST /v1/apps/trigger/… returns 500, not 415. The Content-Type header and {}
body are required either way.

C — the index migration. The migration ships in 2.0.0 (moved there by fcece67); any runbook
or check referencing 2.1.1 is stale, including the server_migration_sql_logs cleanup predicate.

On MySQL the premises behind the statement-free script were confirmed on a migrated instance: only
the 1.1.5 unique index and combined_id_ts are present (nothing added), entityFQNHash is
varchar(768) ascii ascii_bin, server_migration_sql_logs holds 93 statements for 2.0.0 and zero
for the index, and EXPLAIN on the purge predicate gives type=range,
key=profiler_data_time_series_unique_hash_extension_ts, key_len=1796, Using where; Using index
— index-driven, not a scan.

Not verified by hand: the PostgreSQL branch (idx_profiler_data_time_series_fqnhash_pattern and
its indisvalid check) — the manual stack and the IT runs were both MySQL. It is covered by
OrphanedTimeSeriesCleanupIT.profilerPrefixIndexIsAvailable on a Postgres CI lane.

Residual risk:

Stated plainly rather than hedged, so reviewers can weigh them:

  • A crash between the delete committing and the purge completing loses that purge. AsyncService is an in-process executor, so a server restart in that window drops the task. If the table is not re-created, the weekly orphan sweep reclaims the rows normally. If it is re-created at the same FQN before the sweep runs, the leftovers regain a live parent and the sweep can never reclaim them — only age-based retention (profileDataRetentionPeriod, default 1440 days) will. The window is the seconds between commit and drain, versus the permanent leak this PR replaces. A durable queue (background_jobs) would close it; that was judged not worth the machinery for a window this narrow, given the watermark already makes a late purge harmless.
  • The watermark uses the profile's logical timestamp, not the row's write time. So it mis-classifies only if a successor table records a profile backdated to before its predecessor's deletion — a PUT .../tableProfile backfill with an explicit historical timestamp, or clock skew — and the purge is still pending. Closing this fully would need a write-time column on a very large table, which is not worth the migration.
  • A retention behaviour change for dropped columns. The sweep is table-granular: it can tell whether a column row's parent table exists, but not whether that specific column still does. table.columnProfile rows for columns dropped from a still-live table are therefore retained until age-based retention removes them. Before this PR they were deleted weekly — but only as collateral damage of defect (B), which deleted every live column's profiles along with them. The trade-off is deliberate.
  • The interrupted-CONCURRENTLY runbook is documented, not automated. Same gap as 1.11.0 and 1.13.0.
  • Historical rows stranded by pre-upgrade hard deletes are not back-filled. The corrected weekly sweep reclaims them, which can take up to a week — except where a table was already re-created at that FQN before upgrading, where the same permanence described above applies.

UI screen recording / screenshots:

Not applicable — no UI changes.

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: N/A — no schema change. A database migration is included (2.0.0) and is described above.
  • For UI changes: N/A — no UI changes.
  • I have added tests (unit / integration / Playwright as applicable) and listed them above.
  • I have added a test that covers the exact scenario we are fixing, with the issue number referenced in this PR and in the migration file header.

🤖 Generated with Claude Code

Greptile Summary

The PR asynchronously purges profiler history after table hard deletion and corrects orphan cleanup so live column profiles resolve to their parent table.

  • Adds timestamp-bounded cleanup for table, system, and nested column profiles.
  • Changes orphan detection to compare profiler rows with the parent table hash.
  • Adds PostgreSQL prefix-index migration support and integration coverage for both database engines.

Confidence Score: 4/5

The PR does not yet appear safe to merge because a recreated table can still lose backdated successor profiles to the predecessor's delayed purge.

The purge identifies ownership using a reused FQN and the profile's caller-controlled logical timestamp, so a valid historical profile written by the successor before cleanup runs remains indistinguishable from predecessor data and is deleted.

Files Needing Attention: openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java, openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java

Important Files Changed

Filename Overview
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java Schedules profiler cleanup after hard-delete processing, but the detached purge still relies on a caller-controlled logical timestamp to distinguish a recreated table.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java Adds profiler purge statements and parent-table hash orphan detection; the outstanding timestamp ownership limitation remains.
bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql Adds the PostgreSQL pattern-operator index needed by column-profile prefix deletion.
openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TableResourceIT.java Covers hard/soft deletion, recursive deletion, large histories, dropped columns, and the post-watermark successor case.
openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OrphanedTimeSeriesCleanupIT.java Verifies preservation of live table, system, column, and nested-column profiles while deleting genuine orphans.

Sequence Diagram

sequenceDiagram
  participant Client
  participant TableRepo as TableRepository
  participant Async as AsyncService
  participant DB
  Client->>TableRepo: Hard-delete table
  TableRepo->>DB: Delete table entity
  TableRepo->>Async: Queue profiler purge(FQN, deletedAt)
  TableRepo-->>Client: Delete response
  Async->>DB: "Delete table/system rows <= deletedAt"
  Async->>DB: "Delete column-prefix rows <= deletedAt"
Loading

Reviews (7): Last reviewed commit: "refactor(profiler): collapse the orphan ..." | Re-trigger Greptile

Context used:

TeddyCr and others added 5 commits August 14, 2026 10:04
profiler_data_time_series is keyed by FQN hash rather than by table id,
so rows survived a hard delete and were silently adopted by the next
table created at the same FQN — a re-ingested table served the dead
table's row counts and column statistics.

TableRepository.entitySpecificCleanup now deletes the table's
table.tableProfile and table.systemProfile rows (keyed by the table FQN)
and purges table.columnProfile rows, which are keyed by each (possibly
nested) column FQN and therefore need a descendant sweep.

EntityTimeSeriesDAO gains deleteDescendants(entityFQN, extension),
backed by a dialect-aware prefix DELETE that runs in bounded batches
(1000 rows per statement, 1000 batches per call) so the purge can never
issue an unbounded DELETE.

The hook only runs on the hard-delete branch, so soft-deleted tables
keep serving their profiles; the bulk cascade routes through the same
hook, so a recursive schema/database/service hard delete is covered too.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…olumn profiles

ProfilerDataTimeSeriesDAO.deleteOrphanedRecords compared every
profiler_data_time_series row against table_entity.fqnHash with no
extension filter. FullyQualifiedName.buildHash hashes each FQN part and
joins with '.', so a column profile's entityFQNHash carries at least one
more segment than a table's four-segment fqnHash and could never match.
Every table.columnProfile row of every live table was therefore
classified as an orphan and deleted on each weekly DataRetention run.

Column-profile rows now resolve to their parent table by taking the
first four hash segments — SUBSTRING_INDEX on MySQL, chained split_part
on PostgreSQL — which also covers nested columns. Other extensions keep
the previous raw-hash comparison, and genuine orphans are still swept.

OrphanedTimeSeriesCleanupIT.profilerDataOrphans previously seeded only a
table-level row, which is why this went unnoticed; it now covers all
three extensions plus a nested-column row and an orphaned column row.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Review follow-ups on the table hard-delete purge.

Signal cap exhaustion. deleteDescendants returned only a row total, so
"drained" and "stopped at the 1,000,000-row cap" were indistinguishable,
and the outcome was logged at DEBUG. It now returns a DescendantPurge
record and TableRepository logs at INFO, or WARN when the cap truncated
the purge. That case matters: if the table is re-created at the same FQN
the leftovers regain a live parent, so the orphan sweep will never
reclaim them and only age-based retention will.

Skip the purge when there is nothing to purge. The descendant delete
matches an FQN-hash prefix, which PostgreSQL cannot serve from the
b-tree index under the default collation, so it scans
profiler_data_time_series. A recursive service hard delete issued one
scan per table, profiled or not. The purge now runs only when the
indexed table-level deletes removed rows or an indexed exact-hash probe
over the table's columns finds one, so a never-profiled table costs
nothing. EntityTimeSeriesDAO.delete returns its row count for this;
every existing caller discards it.

The new IT seeds one more row than a single batch and writes no
table-level profile, so it pins both the drain loop and the probe.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…he gate

The gate added in the previous commit skipped the descendant purge unless
the table had table-level profiler rows or one of its *current* columns
had a profile. Dropping a column does not delete its profiler rows, so a
table whose only rows belonged to a since-dropped column satisfied
neither signal and was never purged — re-ingesting at the same FQN
resurfaced the dead table's profile for that column, which is the bug
this issue is about. The purge is unconditional again.

The gate existed to avoid a sequential scan, so remove the reason for it
instead. Migration 2.1.1 adds a text_pattern_ops index on
profiler_data_time_series(entityFQNHash), built CONCURRENTLY. Measured on
postgres:15 with en_US.utf8 and 300k rows, the terminal batch of every
purge goes from a 24.174 ms parallel seq scan over 11112 buffers to a
0.056 ms index scan over 3. text_pattern_ops rather than
varchar_pattern_ops because JDBC binds the prefix as text and the planner
compares (entityfqnhash)::text, which the varchar opclass need not match
— the same reasoning 1.13.0 recorded for the fqnHash index family. The
MySQL script is deliberately statement-free: entityFQNHash is ascii_bin
and already leads the unique index, and an IT now pins both that premise
and the Postgres index rather than leaving them as assertions.

capReached no longer false-positives when the subtree size is an exact
multiple of the batch size, and the cap warning states its consequence
conditionally, since the orphan sweep does drain the remainder when the
table is not re-created.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ng test

The pre-purge existence probe was removed when the gate was withdrawn,
but the batching test still described it. The javadoc told a future
reader the test pins a probe that no longer exists, and the assertion
that no table-level profile row had been written was that probe's
precondition — vacuous now that deleteDescendants is unconditional.

Comments and one dead assertion only; the test's behaviour, and the
seeding at one row beyond a batch that makes it load-bearing, are
unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@TeddyCr
TeddyCr requested a review from a team as a code owner August 14, 2026 17:22
Copilot AI lite review requested due to automatic review settings August 14, 2026 17:22
@github-actions

github-actions Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

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

@github-actions github-actions Bot added Ingestion safe to test Add this label to run secure Github workflows on PRs labels Aug 14, 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.

Pull request overview

Fixes profiler-data lifecycle defects for tables by (1) purging profiler_data_time_series on table hard delete (preventing stale profiles from resurfacing on re-creation at the same FQN) and (2) correcting the DataRetention orphan sweep so it no longer deletes live column profiles that cannot match table_entity.fqnHash due to hash-segment length differences.

Changes:

  • Wire hard-delete-only profiler purge into TableRepository.entitySpecificCleanup, including descendant (column) profile deletion.
  • Add bounded, batched descendant deletion support to EntityTimeSeriesDAO via hash-prefix deletes.
  • Fix ProfilerDataTimeSeriesDAO.deleteOrphanedRecords to resolve column-profile rows to their parent table hash (first 4 hash segments).
  • Add/extend integration tests covering hard/soft delete behaviors, cascade deletes, batching, orphan sweep correctness, and migration/index premises; add Postgres pattern index migration (MySQL intentionally statement-free).

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java Add hard-delete-only cleanup to purge table/system profiles and descendant column profiles, plus operational logging.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityTimeSeriesDAO.java Introduce bounded batched hash-prefix deletes and DescendantPurge result for descendant purges.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java Fix orphan sweep predicate to preserve live column profiles by matching against parent table hash.
openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TableResourceIT.java Add integration coverage for hard vs soft delete profiler preservation/purge, cascade deletion, batching, and dropped-column history purge.
openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OrphanedTimeSeriesCleanupIT.java Expand orphan cleanup test coverage to include all profiler extensions (incl. nested columns) and verify Postgres/MySQL indexing premises.
bootstrap/sql/migrations/native/2.1.1/postgres/schemaChanges.sql Add text_pattern_ops index to support LIKE '<hash>.%' prefix scans for hard-delete descendant purges on Postgres.
bootstrap/sql/migrations/native/2.1.1/mysql/schemaChanges.sql Document why no MySQL schema change is needed (existing collation + unique index supports prefix range scans).

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI review requested due to automatic review settings August 18, 2026 17:41

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 was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added safe to test Add this label to run secure Github workflows on PRs and removed safe to test Add this label to run secure Github workflows on PRs labels Aug 18, 2026
Copilot AI review requested due to automatic review settings August 19, 2026 15:54

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 was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added safe to test Add this label to run secure Github workflows on PRs and removed safe to test Add this label to run secure Github workflows on PRs labels Aug 19, 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 was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added safe to test Add this label to run secure Github workflows on PRs and removed safe to test Add this label to run secure Github workflows on PRs labels Aug 19, 2026
…portable form

The MySQL and Postgres variants existed only because Postgres has no
SUBSTRING_INDEX -- split_part returns a single field, so the same extraction took
four calls and three concatenations. Neither is needed. Every hash segment is MD5
hex, so a table fqnHash is always exactly four 32-char segments plus three dots =
131 characters, and LEFT(entityFQNHash, 131) yields the parent table hash on both
engines.

The CASE went with them. Extracting the parent is a no-op for table-level rows,
which are already 131 characters, so branching on the extension was dead weight;
the predicate no longer references TABLE_COLUMN_PROFILE_EXTENSION at all.

Verified on a fixture with the real column types, collation and indexes (5,000
tables / 105,250 rows / 250 planted orphans): LEFT(hash,131) differs from the
previous extraction on zero rows on either engine, and the sweep returns the same
250 orphans. Timed as the identical query, MySQL 8 goes 89.9ms -> 32.1ms and
Postgres 15 36.3ms -> 46.5ms; both keep the Hash Anti Join, so this is a
readability change rather than a performance one. Running the exact statements
JDBI emits deletes 250 on both -- MySQL 8 accepts a table alias alongside LIMIT
in a single-table DELETE, which is what lets the predicate be shared.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings August 19, 2026 18:56

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 was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added safe to test Add this label to run secure Github workflows on PRs and removed safe to test Add this label to run secure Github workflows on PRs labels Aug 19, 2026
// table_entity per profiler row: 32s vs 106ms on Postgres 15, 76s vs 247ms on MySQL 8 over 5k
// tables / 105k rows. 1.9.9/postgres/postDataMigrationSQLScript.sql resolves the same parent
// for the same reason, noting it is "much faster than LIKE".
String PARENT_TABLE_HASH = "LEFT(pdts.entityFQNHash, 131)";

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This relies on the hash function being constant (i.e. each segment of the fqn is an MD5 hash separated by dots.)

@gitar-bot

gitar-bot Bot commented Aug 20, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 3 resolved / 3 findings

Asynchronous profiler data purging on table hard delete and optimized orphan cleanup predicates for live column profiles. No issues found.

✅ 3 resolved
✅ Performance: Table/system profile purge issues one unbounded DELETE

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java:1738-1745 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityTimeSeriesDAO.java:620-622
In deleteProfilerData, table and system profiles are removed with the plain profilerDao.delete(tableFqn, ...), which is a single DELETE ... WHERE entityFQNHash = :h AND extension = :e with no LIMIT. Column profiles were deliberately switched to bounded batching (deleteDescendants) precisely so one hard delete can't issue an unbounded DELETE or hold a connection indefinitely, but table.systemProfile is written once per DML operation and can accumulate to very high volume for a busy table, so its purge can still be a single large statement — contradicting the PR's stated bounded-batching goal. Consider draining these two extensions in bounded batches too (e.g. an exact-match variant of the batch delete) if high-volume system-profile histories are a concern.

✅ Performance: Orphan sweep predicate is non-sargable, regressing weekly cleanup

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java:10329-10343
deleteOrphanedRecords was changed from te.fqnHash = <computed parent hash> (an equality that can seek the table_entity.fqnHash index / plan as an anti-join) to te.fqnHash = pdts.entityFQNHash OR (extension = 'table.columnProfile' AND pdts.entityFQNHash LIKE te.fqnHash || '.%'). For column-profile rows the equality never matches, so evaluation falls to the LIKE te.fqnHash || '.%' branch whose pattern prefix is the indexed column itself — this is non-sargable and forces a full scan of table_entity per candidate row, making the NOT EXISTS roughly O(rows_scanned x table_entity). On large deployments the weekly DataRetention sweep can become extremely slow or time out, whereas the prior computed-parent-hash form was index-friendly. Consider restoring the computed-parent-hash equality (SUBSTRING_INDEX / chained split_part) so the anti-join stays sargable, while keeping the nested-column handling.

✅ Bug: Async profiler purge can delete a re-created table's live profiles

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java:1731-1745 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java:10193-10207
Moving the purge from the synchronous delete path into postDelete -> AsyncService.execute(() -> deleteProfilerDataSafely(table)) opens a TOCTOU race. profiler_data_time_series is keyed by FQN hash, and the async task deletes every row matching the table FQN / <tablehash>.% regardless of which table_entity currently owns them. If a table is hard-deleted and then re-created at the same FQN (re-ingestion, rename-and-recreate, IaC replay — the exact scenarios this PR targets) and new profiles are written before the queued async purge runs, the purge deletes the NEW table's freshly written profiler rows. The old synchronous purge completed before delete returned, so re-creation always happened after the purge. Consider keeping the purge synchronous within the delete path, or scoping the delete to rows older than the delete timestamp / re-checking the parent table is still absent before deleting.

Options

Display: compact → Showing less information.

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

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Ingestion safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Hard delete of Table does not clean up profiler data from profiler_data_time_series — stale profiles resurface on re-creation

3 participants