Repository navigation
Decompose CollectionDAO & EntityRepository; fix lineage/usage/isBot bugs - #28778
Conversation
…e/usage/isBot bugs Decompose the two backend god-classes into cohesive, single-responsibility collaborators (behavior-preserving) and fix several DAO-layer perf/correctness bugs. CollectionDAO (15,040 -> 433 lines): split into 17 same-package domain aggregator interfaces it `extends` (composite-interface-inheritance, zero call-site change): RdfInfraDAOs, SearchReindexDAOs, AiGovernanceDAOs, FeedDAOs, ClassificationTagDAOs, TimeSeriesDAOs, ActivityAuditDAOs, GovernanceDAOs, EventSubscriptionDAOs, KnowledgeAssetDAOs, SystemTokenDAOs, DataAssetServiceDAOs, EntityDataDAOs, AccessControlDAOs, WorkflowDocStoreDAOs, OAuthDAOs, CoreRelationshipDAOs. Added CollectionDAOCompositionTest guarding the JDBI wiring of inherited accessors. EntityRepository (12,797 -> ~9,950 lines): extracted 7 collaborators with delegators preserving the public/protected API for 81 subclasses: EntityTaskWorkflows, EntityCacheLoaders, EntityCaches, EntityCacheInvalidator, InheritanceParentCache, BulkFieldFetcher, BulkImportService. Perf/correctness fixes: - Lineage findTo/FromPipeline operator-precedence bug (restores the relation filter) - entity_usage(entityType,usageDate) index for UsageDAO.computePercentile (2.0.0 migration) - Postgres isBot generated column read $.deleted instead of $.isBot (2.0.0 migration); bots were counted as daily-active users on Postgres - getMaxLastActivityTime / user-list isBot filters use the indexed columns - deleted dead, malformed EntityExtensionDAO.update Full openmetadata-service test suite passes (5,800 tests, 0 failures). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
✅ PR checks passedThe linked issue has a description and all required Shipping project fields set. Thanks! |
Resolve CollectionDAO.java conflict from the CollectionDAO split refactor: - Port #28752 (chunk IN-list batch queries under the DB parameter ceiling) onto the moved DAOs: EntityExtensionDAO/EntityRelationshipDAO now live in CoreRelationshipDAOs; TagUsageDAO in ClassificationTagDAOs; UsageDAO in AccessControlDAOs; DataQualityDataTimeSeriesDAO/TestCaseResultTimeSeriesDAO in TimeSeriesDAOs. EntityDAO.queryInChunks/updateInChunks (auto-merged) drive the chunking; F1 dead-code delete and P1 lineage parenthesization preserved in EntityExtensionDAO/EntityRelationshipDAO. - Add IntakeFormDAO from #27600 (ODPS/Custom Forms) to the composite CollectionDAO (accessor + interface + IntakeForm import). - Redirect InListChunkingTest imports to the new declaring interfaces. Service module compiles (main + test); InListChunkingTest (16) and CollectionDAOCompositionTest (2) pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nup (E1) A3 — getContractByEntityId full-scanned data_contract_entity filtering nested $.entity.id / $.entity.type via JSON_EXTRACT on the per-entity contract enforcement write path. Add VIRTUAL (MySQL) / STORED (Postgres) generated columns contractEntityId / contractEntityType + a composite index, and rewrite the query to seek on those columns plus the existing indexed `deleted` column. Validated on MySQL 8.0 + Postgres 16: generated columns populate, query returns only non-deleted matches, EXPLAIN shows an index seek (ref / Index Scan), and the guarded migration is idempotent. E1 — TagUsageCleanup.performCleanup walked the full tag_usage table with offset += batchSize (O(n^2) deep-offset). Switch to keyset pagination on the unique (source, tagFQNHash, targetFQNHash) key. Per-engine SQL: MySQL needs the expanded-OR form (its optimizer makes it an index range seek; a row-constructor comparison scans the whole index from the start — verified Handler_read_next), Postgres seeks optimally with the row-constructor (Index Only Scan). Validated on both engines: a batchSize=7 drive over 300 rows covers all 300 exactly once with zero duplicates. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… (C1) FieldRelationshipDAO was the one high-volume relationship DAO with no batch insert, so FeedRepository.storeMentions and TaskRepository.storeMentions fired one round trip per distinct mention. Add insertMany(List<FieldRelationship>) mirroring EntityRelationshipDAO.bulkInsertTo: a @BindBeanList multi-row VALUES with INSERT IGNORE (MySQL) / ON CONFLICT (fromFQNHash, toFQNHash, relation) DO NOTHING (Postgres), omitting the nullable json column so no per-row ::jsonb cast is needed. Both mention callers now build the bean list (pre-hashing FQNs via FullyQualifiedName.buildHash — the same hash @BindFQN applies) and issue one insertMany; empty lists are guarded so the VALUES clause is never empty. Pipeline task-owner inserts are intentionally left on the single-row path: they pass buildHash(fqn) into a @BindFQN param (a separate double-hash concern), so a bean-bound batch would change the stored hash — out of scope here. Validated on MySQL 8.0 + Postgres 16: a multi-row batch inserts all distinct rows, a follow-up batch with duplicate keys is ignored with no error, and json stays NULL — matching the single-row insert semantics. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… 2 finish) The CollectionDAO split left ~12 cross-domain row/mapper carriers (system entity/service counts + pipeline reporting trends/metrics) inside the composite, referenced as CollectionDAO.X from the aggregators and PipelineRepository — the last thing keeping CollectionDAO from being a thin accessor list. Move them into a new leaf interface SharedRowMappers and redirect all 21 references to their canonical SharedRowMappers.X name (no CollectionDAO dependency, breaking the aggregator->CollectionDAO type cycle). CollectionDAO drops 470 -> 150 lines (now just the extends clause, 4 accessors, IntakeFormDAO, AssetDAO). Pure type relocation, no behavior/SQL change; compiles main+test, CollectionDAOCompositionTest passes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…CollectionDAO/EntityRepository split The CollectionDAO/EntityRepository decomposition moved member types into aggregator interfaces and static caches into EntityCaches, but the redirect never covered the openmetadata-integration-tests module, breaking its compile: - SearchIndexRetryQueueIT imported CollectionDAO.SearchIndexRetryQueueDAO; that type now lives in SearchReindexDAOs, and a single-type import requires the canonical declaring interface (inherited member types can't be imported via a subtype). Repointed both imports to SearchReindexDAOs. - EntityCacheInvalidationIT referenced EntityRepository.CACHE_WITH_ID; that field moved to EntityCaches (static fields aren't inherited via the subclass name). The remaining "cannot find symbol: log" errors CI reported were Lombok cascade fallout from these two — they clear once the real errors are fixed. Integration -tests module now compiles (BUILD SUCCESS). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…llow-up) An adversarial audit (proven on a live MySQL container) found the E1 keyset cleanup could silently skip rows: tagFQNHash/targetFQNHash are nullable, and once the cursor lands on a NULL-hash row (MySQL sorts NULLs first, so this is reached early), every subsequent `tagFQNHash > NULL` / `= NULL` / row-constructor compare is UNKNOWN, the batch returns empty, and the scan terminates — skipping all trailing rows. The two engine forms also diverge on NULL ordering. Fix: exclude NULL hashes from the keyset scan (AND tagFQNHash IS NOT NULL AND targetFQNHash IS NOT NULL) so the cursor only ever holds real keys. This keeps the index seek (verified: MySQL type=range, Postgres Index Only Scan) and makes both engines scan an identical row set regardless of their NULL ordering. The rare malformed NULL-hash rows (no write path produces them) are swept once via a new bounded getTagUsagesWithNullHash query so the cleanup tool still sees them. Validated on MySQL 8.0 + Postgres 16: with NULL rows present, a batchSize=2 walk now covers all non-NULL rows (0 dropped, 0 dupes) and the NULL sweep catches the malformed rows; the pre-fix walk terminated early. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…mPropertyValidator An adversarial architecture review of the remaining EntityRepository clusters found the big ones (EntityUpdater, inheritance/lifecycle template hooks, CSV stubs) must stay — they are polymorphic seams 20-63 subclasses override, and extracting them would force pervasive r.hook() callbacks. The one genuinely clean, callback-free win all three reviewers named independently: the static extension/custom-property validators (~210 lines), which carry zero entity-instance state and whose siblings (validateCustomPropertyEntityReference[List]) already live in EntityUtil. Move validateExtension(Object,String), validateAndTransformExtension, validateHyperlinkUrl, getFormattedDateTimeField, validateTableType, validateEnumKeys to a new org.openmetadata.service.util.CustomPropertyValidator. EntityRepository keeps the instance validateExtension(T,boolean) create/update hook, now delegating to it. Redirected the two external callers (ColumnRepository, EntityCsv) and dropped the two now-unused static imports. EntityRepository -213 lines; pure move, no behavior change. Service (main+test) and integration-tests modules both compile. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… (A9) deleteReportDataTypeAtDate's Postgres form recomputed DATE(TO_TIMESTAMP((json->>'timestamp')::bigint/1000)) per row — non-sargable, a full seq scan across all report types. Replace both engine forms with a single half-open range over the indexed `timestamp` column: WHERE entityFQNHash = :reportDataType AND timestamp >= :startTs AND timestamp < :endTs The caller derives [startTs, endTs) from the yyyy-MM-dd date in UTC via the existing TimestampUtils helpers — matching how the date string and the Elasticsearch cleanup (doc['timestamp'].toLocalDate()) are already built, so semantics are preserved while the query becomes identical and index-backed on both engines. Container-validated on MySQL 8.0 (EXPLAIN type=range) and Postgres 16 (Index Scan using idx_report_data_ts_keyset): exactly the target UTC day is deleted; the preceding-day-23:59, next-day-00:00, and other-entity boundary rows are preserved. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ers (B4) The bulk field fetchers batched their relationship records but then resolved each EntityReference one row at a time via Entity.getEntityReferenceById — an N+1 over a page of users/teams (teams, roles, personas, default/inherited personas, domains; team users, defaultRoles, defaultPersona, parents, policies). Add a shared EntityRepository.batchResolveRefs(entityType, ids) that resolves a homogeneous id set in one getEntityReferencesByIds call and returns an id->ref map, and route all 13 single-type fetchers through it. The mixed-type owns/follows fetchers keep their per-row resolution: they resolve heterogeneous entity types with defensive per-row try/catch for dangling owned/followed entities, which a batched find() (throws on the first missing id) would regress. Full service suite green (5,892 tests, 0 failures). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 87 out of 88 changed files in this pull request and generated 4 comments.
Comments suppressed due to low confidence (1)
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TeamRepository.java:470
batchFetchDirectUsersusesInclude.ALLfor Team→UserHASrelationships. This can include soft-deleted membership edges, and the current filtering only checks whether the user entity is deleted, not whether the relationship is deleted. UseInclude.NON_DELETEDto count only active memberships inuserCount.
# Conflicts: # bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql # bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TeamRepository.java # openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/distributed/DistributedSearchIndexCoordinatorTest.java
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 89 out of 90 changed files in this pull request and generated 4 comments.
Suppressed comments (1)
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TeamRepository.java:353
childrenCountfor the organization team is computed fromlistTeamsUnderOrganization(...).size(), which counts soft-deleted teams as children (the underlying query has nodeleted=falsefilter). This can causechildrenCountto disagree withgetChildren(..., NON_DELETED)once deleted filtering is fixed.
Three review findings from PR #28778: 1. Runtime break (P1): the 680-commit merge reconciliation re-applied TagUsageDAO.getTagUsagesAfter and FieldRelationshipDAO.insertMany through a helper that truncated their leading annotations, leaving both methods without @ConnectionAwareSqlQuery/@ConnectionAwareSqlUpdate. JDBI cannot bind an implementation for either, so TagUsageCleanup and the batched mention inserts would have failed at runtime. Restored both annotation pairs (MySQL + Postgres) verbatim from the pre-merge commit. 2. Organization children ignored soft deletion: listTeamsUnderOrganization returns raw parentless-team ids without applying `deleted`, and three call sites consumed them differently — childrenCount used the unfiltered size, getChildren(teamId, include) ignored the requested Include, and only the subtree walk filtered. Consolidated all three onto getOrganizationChildren(orgId, include) / getLiveOrganizationChildIds(orgId) so the organization path matches the PARENT_OF path, which gets the same filtering from findTo. 3. Style: dropped redundant fully-qualified UsageDAO.UsageDetailsWithId and java.util.stream.Collectors references in EntityUtil (both already imported). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 89 out of 90 changed files in this pull request and generated no new comments.
Suppressed comments (1)
Previously missed (1) — in code that hasn't changed since the last review.
openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/CollectionDAOCompositionTest.java:91
- This test’s expected accessor set is derived by filtering for methods that already have @CreateSqlObject. If an accessor accidentally loses its annotation (the exact regression this guard is meant to catch), it will drop out of
accessorsand the test can still pass as long as the remaining count stays aboveMIN_EXPECTED_ACCESSORS. Consider instead deriving the candidate set from structural properties (e.g., all zero-arg DAO-accessor methods on CollectionDAO + extended interfaces) and then asserting each candidate is annotated and visible, so annotation loss fails deterministically.
… refs The previous fix made the organization branch resolve an EntityReference for every parentless team just to honour `deleted`: childrenCount called getLiveOrganizationChildIds(...).size() and the subtree seed resolved the same list. listTeamsUnderOrganization already scans team_entity with a NOT IN (subquery), so this added a full batch reference resolution on a hot read path for every organization team fetch. Push the filter into SQL instead: - TeamDAO.countLiveTeamsUnderOrganization(orgId) backs childrenCount - TeamDAO.listLiveTeamsUnderOrganization(orgId) seeds the subtree walk Both exclude soft-deleted teams with (deleted = FALSE OR deleted IS NULL), since team_entity.deleted is a nullable generated column. getChildren still resolves references through getOrganizationChildren(orgId, include) because it must return them, and it continues to honour the caller's Include. Verified locally: TeamResourceIT + UserResourceIT, 494 tests, 0 failures. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 89 out of 90 changed files in this pull request and generated no new comments.
Suppressed comments (3)
Previously missed (3) — in code that hasn't changed since the last review.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java:1451
- The inline comment is wrapped in a way that splits a single sentence across multiple one- or two-word lines ("would" / "leave a"), which hurts readability and looks accidental. Reflow the comment into normally wrapped lines so the sentence reads continuously.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContainerRepository.java:272 - This comment wrap breaks mid-sentence ("Cache" / "one"), making it hard to read and likely unintentional. Please reflow the comment so the sentence isn’t split across tiny lines.
// De-dupe service IDs before resolving them to references. In any practical paged
// listing the children are all under the same storage service, so the naive loop
// below would call getEntityReferenceById N times for the same service id —
// each call hits EntityRepository.CACHE_WITH_ID (or DB) for the full StorageService JSON. Cache
// one
// ref per unique service id and fan it back out to every child.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/PersonaRepository.java:176
- The comment is broken into two separate lines ("Passing fqn lets" on its own line) which reads like an accidental wrap. Reflow into a single coherent comment block.
# Conflicts: # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ClassificationRepository.java # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedRepository.java # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GlossaryRepository.java # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GlossaryTermRepository.java # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TagRepository.java # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TeamRepository.java # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java
| protected Map<UUID, EntityReference> batchResolveRefs(String entityType, List<UUID> ids) { | ||
| List<UUID> distinctIds = ids.stream().distinct().toList(); | ||
| Map<UUID, EntityReference> refsById = new HashMap<>(); | ||
| if (!distinctIds.isEmpty()) { | ||
| for (EntityReference ref : | ||
| Entity.getEntityReferencesByIds(entityType, distinctIds, Include.ALL)) { | ||
| refsById.put(ref.getId(), ref); | ||
| } | ||
| } | ||
| return refsById; | ||
| } |
There was a problem hiding this comment.
Valid — good catch, fixed in 2dd0070.
You're right that the two APIs have different contracts:
getEntityReferenceById -> repository.getReference(id, include) -> find(id, include) // throws
getEntityReferencesByIds -> repository.getReferences(ids, include) -> dao.findReferencesByIds(...)
// plain WHERE id IN (...) — drops missing
I confirmed against the B4 commit (3fcf3f4) that all 13 replaced call sites (8 in UserRepository, 5 in TeamRepository) previously used Entity.getEntityReferenceById(TYPE, id, Include.ALL) and added the result unconditionally — so an orphaned relationship row did fail the request before, and silently vanished after. That's a real behaviour change in a refactor documented as behaviour-preserving.
batchResolveRefs now fails fast when a requested id doesn't resolve, matching the per-record path it replaced. Include.ALL is unchanged so soft-deleted entities still resolve exactly as before — only genuinely missing ids throw. The call-site null guards are left as harmless defence-in-depth.
Verified with TeamResourceIT + UserResourceIT: 494 tests, 0 failures.
The B4 perf refactor (3fcf3f4) replaced 13 per-record Entity.getEntityReferenceById(type, id, Include.ALL) calls in UserRepository/TeamRepository with a single batched batchResolveRefs(...) lookup plus `if (ref != null)` guards at each call site. Those two APIs do not have the same contract: getEntityReferenceById -> repository.getReference(id, include) -> find(id, include) // throws EntityNotFoundException getEntityReferencesByIds -> repository.getReferences(ids, include) -> dao.findReferencesByIds(...) // plain "WHERE id IN (...)" — missing ids are dropped So an orphaned relationship row changed from failing the request to silently omitting the reference — a behaviour change in a refactor that was documented as behaviour-preserving, and one that hides data corruption rather than surfacing it. Make batchResolveRefs fail fast when a requested id does not resolve, so the batched path matches the per-record path it replaced. Include.ALL is unchanged, so soft-deleted entities still resolve exactly as before; only genuinely missing ids now throw. The call-site null guards are left in place as harmless defence-in-depth. Reported by Copilot review on PR #28778. Verified: TeamResourceIT + UserResourceIT, 494 tests, 0 failures. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 88 out of 89 changed files in this pull request and generated no new comments.
Suppressed comments (1)
Previously missed (1) — in code that hasn't changed since the last review.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java:1453
- The comment explaining why FQN is needed is currently broken across multiple short lines ("would" / "leave a"), which makes it harder to read and looks like an accidental wrap. Reflow it into complete sentences on fewer lines.
|
The (The Fix6 Collate files need their import repointed to
I'd recommend to extend it to all 6 and merge it with this PR. |
| FeedDAOs, | ||
| AiGovernanceDAOs, | ||
| SearchReindexDAOs, | ||
| RdfInfraDAOs { |
There was a problem hiding this comment.
201 files still reference these types as CollectionDAO.<Nested>, which is no longer their canonical name.
Member types are inherited by a subinterface, so CollectionDAO.EntityRelationshipObject (340 refs), CollectionDAO.EntityRelationshipRecord (128), CollectionDAO.TagUsageDAO (62) and friends all still resolve. But JLS 7.5 requires canonical names in import declarations, and the canonical name is now CoreRelationshipDAOs.EntityRelationshipObject, TimeSeriesDAOs.TestCaseDAO, etc.
That asymmetry — inline qualified references keep compiling, imports don't — is exactly why TableRepository is in this diff (three import static …CollectionDAO.ProfilerDataTimeSeriesDAO.*) while TestCaseRepository, which uses CollectionDAO.EntityRelationshipObject inline at :333/:475, isn't touched at all. Two consequences:
- Auto-import footgun. An IDE "add import" or organize-imports on any of those 201 files now emits an import that doesn't compile, and spotless won't catch or fix it.
- The decomposition doesn't reach consumers.
ReportDataRepository:40in this very PR still casts toCollectionDAO.ReportDataTimeSeriesDAOfor a type that now lives inTimeSeriesDAOs. The 10k-line file is gone, but call sites still name the facade, so the coupling that motivated the split survives at the reference level.
Suggestion: a follow-up mechanical sweep rewriting CollectionDAO.<Nested> → <OwningInterface>.<Nested> would make the new ownership boundaries real and remove the footgun. If that's deliberately out of scope for this PR, a javadoc note here saying these are inherited aliases and that imports must name the owning interface would save the next person the compile error.
Relatedly, one latent hazard this split creates that CollectionDAOCompositionTest doesn't cover: Java never inherits annotations across interfaces (@Inherited is superclass-only). Nothing is broken today — I verified no aggregator has type-level annotations — but the first time someone puts @RegisterRowMapper / @RegisterArgumentFactory at the type level on one of the 17, JDBI will silently ignore it when attaching CollectionDAO: no compile error, no test failure, just a NoSuchMapperException on one runtime path. Worth either a comment on each aggregator or extending the guard to assert type-level configurers stay on CollectionDAO itself.
There was a problem hiding this comment.
All three points check out — I verified each rather than taking them on faith:
- 202 files reference
CollectionDAO.<Nested>(EntityRelationshipObject343,EntityRelationshipRecord128,TagUsageDAO62 — your counts were essentially exact) ReportDataRepository:40does still cast toCollectionDAO.ReportDataTimeSeriesDAOfor a type that now lives inTimeSeriesDAOs- no aggregator carries a type-level annotation today, and neither does
CollectionDAO
Annotation hazard — guarded in ad3b54d. This was the one worth closing now, because it fails silently. CollectionDAOCompositionTest has a second test asserting no interface behind CollectionDAO carries a type-level JDBI configurer. It keys off the meta-annotation (@UseExtensionConfigurer, plus legacy @ConfiguringAnnotation) rather than a hardcoded @Register* list, so new configurer variants are covered automatically, and the failure message says to move it to CollectionDAO or onto the method.
Canonical-name footgun — javadoc for now. I took your out-of-scope option: CollectionDAO now documents that the nested types are inherited aliases, that JLS 7.5 makes import CollectionDAO.<Nested> uncompilable while inline references keep working, that the canonical name is the owning interface, and that spotless won't catch it.
The 202-file sweep I'd rather not do here, and I want to be straight that this is a scope call, not a disagreement — your point that the coupling survives at the reference level is correct, and the javadoc doesn't fix it, it just warns. This PR has already absorbed several large upstream merges (Conversation V2 among them) and adding a 202-file mechanical rewrite on top would make the diff materially harder to review and to bisect if something regresses. Happy to open it as a follow-up immediately after this lands — it's purely mechanical (CollectionDAO.<Nested> → <OwningInterface>.<Nested>) and much safer to review on its own.
| // Malformed rows whose hash columns are NULL cannot be keyset-ordered, so they are swept in one | ||
| // bounded query. No current write path produces NULL hashes (FullyQualifiedName.buildHash only | ||
| // returns null for null/empty FQNs), so this is expected to return nothing — but the cleanup | ||
| // tool | ||
| // exists precisely to remove malformed rows, so it must still see them. | ||
| @SqlQuery( | ||
| "SELECT source, tagFQN, tagFQNHash, targetFQNHash, labelType, state, reason, appliedAt, appliedBy, metadata " | ||
| + "FROM tag_usage WHERE tagFQNHash IS NULL OR targetFQNHash IS NULL LIMIT :limit") | ||
| @RegisterRowMapper(TagUsageObjectMapper.class) | ||
| List<TagUsageObject> getTagUsagesWithNullHash(@Bind("limit") int limit); |
There was a problem hiding this comment.
The NULL-hash sweep restores visibility, but those rows still can't be deleted — so the cleanup can never converge.
The keyset rewrite above checks out, for what it's worth: (source, tagFQNHash, targetFQNHash) is genuinely unique on both engines (tag_usage_key in bootstrap/sql/schema/mysql.sql:913, tag_usage_source_tagfqnhash_targetfqnhash_key in postgres.sql:1721), that same unique index backs the ORDER BY so the index-seek claim holds, and lastSource = -1 correctly includes source = 0 on the first page. No skipped or duplicated rows.
The issue is the premise in this comment — "the cleanup tool exists precisely to remove malformed rows, so it must still see them." Seeing them is all it gets. The delete path is keyed on the very columns that are NULL by construction here:
DELETE FROM tag_usage WHERE source = :source AND tagFQNHash = :tagFQNHash AND targetFQNHash = :targetFQNHash(ClassificationTagDAOs:1215, reached from TagUsageCleanup.deleteOrphanedTagUsages:247.) col = NULL is UNKNOWN, so for every row this sweep returns the DELETE matches zero rows, the deleted > 0 guard fails, and deletedCount silently doesn't increment. The row survives, the next run finds it again, and the operator-facing warning at TagUsageCleanup:170 — "some malformed rows may remain. Investigate and re-run cleanup" — points at a loop that structurally cannot converge.
To be explicit: the delete path is pre-existing and unchanged by this PR — I diffed it, this is not a regression you introduced. But this PR is what newly asserts the capability and builds a bounded sweep plus a cap warning premised on it, so it seems like the right moment to either:
- give the sweep a NULL-safe delete (
tagFQNHash IS NULL/IS NOT DISTINCT FROM, or delete bysource+tagFQN), or - keep the sweep report-only and say so — drop "so it must still see them", and have
processTagUsagemark NULL-hash orphans as non-deletable so the summary doesn't reportFound: Nfor rows nothing will ever remove.
Either way MAX_NULL_HASH_ROWS's warning would read better as "cannot be auto-removed" than "re-run cleanup".
There was a problem hiding this comment.
You're right, and thanks for tracing it all the way to deleteTagUsage. Fixed in ad3b54d — I took the first option (NULL-safe delete) rather than making the sweep report-only, since the sweep is worth more if the rows it finds can actually go away.
I reproduced the non-convergence on real containers before changing anything:
| equality delete | NULL-safe delete | normal row | |
|---|---|---|---|
| MySQL 8.0 | 0 rows | 1 row | intact |
| Postgres 16 | 0 rows | 1 row | intact |
Postgres was exercised through PREPARE with bound NULL params rather than SQL literals, so the CAST($n AS TEXT) is confirmed against the parameter-type inference JDBI actually hits.
The fix is a separate deleteTagUsageNullSafe (<=> on MySQL, IS NOT DISTINCT FROM on Postgres) that only NULL-hash orphans are routed through. I kept the common path on plain equality deliberately: the (source, tagFQNHash, targetFQNHash) unique index you identified serves that predicate directly, and Postgres won't use a btree index for IS NOT DISTINCT FROM — so making the single delete uniformly NULL-safe would have turned every orphan delete into a seq scan. The null-safe form still matches normal rows exactly (verified above), it's just not the indexed path.
Also fixed the two bits of prose you called out: the getTagUsagesWithNullHash comment no longer claims the tool removes rows it merely sees, and the MAX_NULL_HASH_ROWS warning now says rows beyond the cap weren't examined this run — which is accurate, and re-running now genuinely converges.
# Conflicts: # openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java
| private Map<UUID, List<EntityReference>> batchFetchTeamsForUsers(List<String> userIds) { | ||
| Map<UUID, List<EntityReference>> userToTeams = new HashMap<>(); | ||
| List<CollectionDAO.EntityRelationshipObject> teamRecords = | ||
| daoCollection | ||
| .relationshipDAO() | ||
| .findFromBatch(userIds, Relationship.HAS.ordinal(), Entity.TEAM, Include.ALL); | ||
| Map<UUID, EntityReference> teamRefsById = | ||
| batchResolveRefs( | ||
| Entity.TEAM, teamRecords.stream().map(r -> UUID.fromString(r.getFromId())).toList()); |
There was a problem hiding this comment.
I checked this one closely because the fail-fast change I just made to batchResolveRefs would turn exactly this scenario into a 500 — but the premise doesn't hold: that call does constrain fromEntity.
findFromBatch(userIds, HAS.ordinal(), Entity.TEAM, Include.ALL) resolves to the (List<String>, int, String, Include) overload, whose backing query is findFromBatchWithEntityTypeAndCondition:
SELECT fromId, toId, fromEntity, toEntity, relation, json, jsonSchema
FROM entity_relationship
WHERE toId IN (<toIds>)
AND relation = :relation
AND fromEntity = :fromEntityType -- bound to 'team'
<cond>So a Domain→User HAS edge has fromEntity = 'domain' and is filtered out in SQL; no non-team id can reach batchResolveRefs(Entity.TEAM, ...).
You're right that toEntity is unconstrained, but that can't mis-associate here: toIds are user UUIDs, and UUIDs are globally unique, so no non-user row can match toId IN (userIds). Adding the toEntity predicate would be redundant rather than corrective.
Leaving as-is. (The two other findings in these reviews were real and are fixed in f37f45a.)
| * definition) must override this (or {@link #setInheritedFields(List, Fields)}) to name the one it | ||
| * inherits from -- otherwise the ancestor fallback resolves an arbitrary CONTAINS parent. | ||
| */ | ||
| /** |
There was a problem hiding this comment.
Correct, and worse than you saw — fixed in f37f45a.
batchResolveRefs had two javadoc blocks stacked on it: the original one describing getParentReference (which it was inserted in front of), and a second one I added when making it fail-fast. So the first block documented the wrong method and getParentReference had no docs at all. Moved the parent-reference javadoc back onto getParentReference; batchResolveRefs keeps only its own.
The E1 keyset rewrite added getTagUsagesWithNullHash so malformed rows
(NULL tagFQNHash/targetFQNHash) stay visible to TagUsageCleanup, but the
delete path is keyed on exactly those columns:
DELETE FROM tag_usage WHERE source = :source
AND tagFQNHash = :tagFQNHash AND targetFQNHash = :targetFQNHash
`col = NULL` is UNKNOWN, so for every row the sweep returns the delete
matched zero rows, the `deleted > 0` guard failed, deletedCount never
incremented, and the next run found the same rows again — a loop that
structurally could not converge, under a warning telling the operator to
re-run it. The delete path itself is pre-existing, but this PR is what
asserts the capability and builds the bounded sweep on top of it.
Add deleteTagUsageNullSafe (MySQL `<=>`, Postgres IS NOT DISTINCT FROM)
and route only NULL-hash orphans through it, so the common path keeps the
plain equality predicate that the (source, tagFQNHash, targetFQNHash)
unique index serves directly — Postgres cannot use that index for
IS NOT DISTINCT FROM. Also correct the sweep comment and the cap warning,
which described re-running as the remedy for rows nothing could remove.
Validated on real containers:
MySQL 8.0 — equality delete 0 rows, NULL-safe 1 row, normal row intact
Postgres 16 — same, via PREPARE with bound NULL params (no type-inference
error from CAST($n AS TEXT)); NULL-safe also still matches
a normal row exactly
Reported by @TeddyCr on PR #28778.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| tagUsageBatch.forEach(tagUsage -> processTagUsage(tagUsage, result)); | ||
| processedCount += tagUsageBatch.size(); | ||
|
|
There was a problem hiding this comment.
Valid — fixed in f37f45a.
totalTagUsagesScanned was set once from getTotalTagUsageCount(), i.e. the row count of the table, which stopped being the scanned count as soon as the keyset scan started excluding NULL hashes and the NULL-hash sweep got a cap. It also disagreed with this class's own "Completed scanning {}" / "Scanned: {}" logs, which already print processedCount.
The result now reports processedCount, so the returned object and the logs agree. The pre-scan total is still logged, as the amount of work expected rather than performed.
Two Copilot findings on PR #28778: - EntityRepository: batchResolveRefs was inserted between getParentReference and the javadoc describing it, and the fail-fast commit then added a second javadoc directly beneath the first. batchResolveRefs carried two doc blocks, the first of them wrong, and getParentReference carried none. Move the parent-reference javadoc back onto getParentReference. - TagUsageCleanup: totalTagUsagesScanned was set once from getTotalTagUsageCount(), i.e. the row count of the table. The keyset scan deliberately excludes NULL-hash rows and the NULL-hash sweep is capped, so that number is not what the run actually walked, and it disagreed with the "Completed scanning {}" / "Scanned: {}" logs. Report processedCount instead, which is the figure those logs already print. The pre-scan total is still logged as the amount of work expected. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Code Review
|
| Compact |
|
Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source
|
CI triage
Separately:
The other 96 are Lombok cascade ( Cause is the decomposition itself: Confirmed by building Collate against this branch — compile, unit tests, and both Java integration suites green (run). That mattered because 100 is javac's default Ordering: these two checks build Collate |



Describe your changes:
Fixes #28785
I decomposed the two backend "god-classes" —
CollectionDAO(15,040 → 433 lines) andEntityRepository(12,797 → ~9,950 lines) — into cohesive, single-responsibility collaborators with no behavior change, and fixed several DAO-layer perf/correctness bugs found along the way.CollectionDAOis now a thin composite thatextends17 same-package domain aggregator interfaces (composite-interface-inheritance — zero call-site change), andEntityRepositorydelegates to 7 extracted collaborators while keeping its public/protected API intact for all 81 subclasses. The wholeopenmetadata-servicetest suite passes (5,800 tests, 0 failures), and a newCollectionDAOCompositionTestguards the JDBI wiring of the inherited@CreateSqlObjectaccessors. Each extraction was validated against the full suite, one collaborator at a time.Type of change:
High-level design:
CollectionDAO split (17 interfaces):
RdfInfraDAOs,SearchReindexDAOs,AiGovernanceDAOs,FeedDAOs,ClassificationTagDAOs,TimeSeriesDAOs,ActivityAuditDAOs,GovernanceDAOs,EventSubscriptionDAOs,KnowledgeAssetDAOs,SystemTokenDAOs,DataAssetServiceDAOs,EntityDataDAOs,AccessControlDAOs,WorkflowDocStoreDAOs,OAuthDAOs,CoreRelationshipDAOs. JDBI'sSqlObjectFactorydiscovers inherited@CreateSqlObjectaccessors viagetMethods(), sodaoCollection.xDAO()andCollectionDAO.Xreferences resolve unchanged; only member-type import statements were repointed to the new declaring interface (compiler-enforced).EntityRepository collaborators (7):
EntityTaskWorkflows,EntityCacheLoaders,EntityCaches,EntityCacheInvalidator,InheritanceParentCache,BulkFieldFetcher,BulkImportService. Each holds a back-reference to the repository where needed and is reached via thin delegators, preserving overridable hooks and the protected API for the 62EntityUpdatersubclasses / 81 repositories.EntityUpdateritself was intentionally left in place (its 62-subclass inheritance coupling warrants a separate, dedicated refactor).Bug/perf fixes: lineage
findTo/FromPipelineoperator-precedence bug (therelationfilter was being dropped);entity_usage(entityType, usageDate)index forUsageDAO.computePercentile; PostgresisBotgenerated column was reading$.deletedinstead of$.isBot(bots were counted as daily-active users);getMaxLastActivityTime/user-list isBot filters now use indexed columns; removed dead, malformedEntityExtensionDAO.update. Migrations are idempotent and live underbootstrap/sql/migrations/native/2.0.0/{mysql,postgres}/schemaChanges.sql.Backward-compat: no public API or call-site changes; cache fields/inheritance behavior preserved via delegation; DB migrations are
IF NOT EXISTS/guarded and validated on MySQL 8.0 + Postgres 16.Tests:
Unit tests
CollectionDAOCompositionTest(verifies every moved@CreateSqlObjectaccessor stays visible + annotated — the mechanism JDBI relies on at runtime).Backend integration tests
openmetadata-servicesuite (5,800 tests) passes green and exercises the refactored DAO/repository layer end-to-end.Ingestion / Playwright tests
Manual testing performed
EXPLAINconfirms the percentile query now does an index-only scan; the PostgresisBotfix flips a bot from counted→excluded incountDailyActiveUsers.UI screen recording / screenshots:
Not applicable.
Checklist:
Fixes #28785above.entity_usageindex and PostgresisBotcolumn fix.🤖 Generated with Claude Code
Greptile Summary
This PR decomposes two large "god-class" interfaces —
CollectionDAO(15k lines → 433) andEntityRepository(~13k → ~10k) — into 17 focused DAO aggregator interfaces and 7EntityRepositorycollaborators respectively, with no public API or call-site changes. Bundled alongside the structural refactor are targeted correctness fixes found during the decomposition.CollectionDAOnowextends17 domain aggregator interfaces (RdfInfraDAOs,AccessControlDAOs,CoreRelationshipDAOs, etc.); JDBI'sgetMethods()-based wiring is guarded by the newCollectionDAOCompositionTest.isBotgenerated column was reading$.deletedinstead of$.isBot(bots wrongly counted as active users); added a(entityType, usageDate)composite index socomputePercentileuses range scans instead of full-table scans;listTeamsUnderOrganizationresults are now filtered for soft-deleted teams before subtree traversal anduserCountcomputation.fetchAndSetUserCountis replaced by a BFS subtree walk with a single batch query per level (discoverSubtreeTeams+batchFetchDirectUsers), eliminating the O(n) per-team recursive queries.Confidence Score: 5/5
Important Files Changed
Class Diagram
%%{init: {'theme': 'neutral'}}%% classDiagram class CollectionDAO { <<interface>> } class RdfInfraDAOs { <<interface>> +rdfGraphDAO() +rdfTripleDAO() } class SearchReindexDAOs { <<interface>> +searchIndexMappingDAO() +indexMappingVersionDAO() } class AiGovernanceDAOs { <<interface>> +contextMemoryDAO() } class FeedDAOs { <<interface>> +conversationDAO() +announcementDAO() +suggestionDAO() } class ClassificationTagDAOs { <<interface>> +tagDAO() +classificationDAO() +tagUsageDAO() } class CoreRelationshipDAOs { <<interface>> +relationshipDAO() +fieldRelationshipDAO() +entityExtensionDAO() } class AccessControlDAOs { <<interface>> +userDAO() +teamDAO() +roleDAO() +policyDAO() } class TimeSeriesDAOs { <<interface>> +entityExtensionTimeSeriesDao() +profilerDataTimeSeriesDao() } class GovernanceDAOs { <<interface>> +kpiDAO() +workflowDefinitionDAO() } class KnowledgeAssetDAOs { <<interface>> +glossaryDAO() +glossaryTermDAO() } class DataAssetServiceDAOs { <<interface>> +databaseDAO() +tableDAO() +pipelineDAO() } class EntityDataDAOs { <<interface>> +docStoreDAO() +systemDAO() } CollectionDAO --|> RdfInfraDAOs CollectionDAO --|> SearchReindexDAOs CollectionDAO --|> AiGovernanceDAOs CollectionDAO --|> FeedDAOs CollectionDAO --|> ClassificationTagDAOs CollectionDAO --|> CoreRelationshipDAOs CollectionDAO --|> AccessControlDAOs CollectionDAO --|> TimeSeriesDAOs CollectionDAO --|> GovernanceDAOs CollectionDAO --|> KnowledgeAssetDAOs CollectionDAO --|> DataAssetServiceDAOs CollectionDAO --|> EntityDataDAOsReviews (23): Last reviewed commit: "fix(review): attach orphaned javadoc; re..." | Re-trigger Greptile