Skip to content

Decompose CollectionDAO & EntityRepository; fix lineage/usage/isBot bugs - #28778

Merged
harshach merged 43 commits into
mainfrom
harshach/port-louis
Aug 28, 2026
Merged

harshach merged 43 commits into
mainfrom
harshach/port-louis

Conversation

@harshach

@harshach harshach commented Jun 6, 2026 •

Copy link
Copy Markdown
Collaborator

Describe your changes:

Fixes #28785

I decomposed the two backend "god-classes" — CollectionDAO (15,040 → 433 lines) and EntityRepository (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. CollectionDAO is now a thin composite that extends 17 same-package domain aggregator interfaces (composite-interface-inheritance — zero call-site change), and EntityRepository delegates to 7 extracted collaborators while keeping its public/protected API intact for all 81 subclasses. The whole openmetadata-service test suite passes (5,800 tests, 0 failures), and a new CollectionDAOCompositionTest guards the JDBI wiring of the inherited @CreateSqlObject accessors. Each extraction was validated against the full suite, one collaborator at a time.

Type of change:

  • Improvement
  • Bug fix

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's SqlObjectFactory discovers inherited @CreateSqlObject accessors via getMethods(), so daoCollection.xDAO() and CollectionDAO.X references 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 62 EntityUpdater subclasses / 81 repositories. EntityUpdater itself was intentionally left in place (its 62-subclass inheritance coupling warrants a separate, dedicated refactor).

Bug/perf fixes: lineage findTo/FromPipeline operator-precedence bug (the relation filter was being dropped); entity_usage(entityType, usageDate) index for UsageDAO.computePercentile; Postgres isBot generated column was reading $.deleted instead of $.isBot (bots were counted as daily-active users); getMaxLastActivityTime/user-list isBot filters now use indexed columns; removed dead, malformed EntityExtensionDAO.update. Migrations are idempotent and live under bootstrap/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

  • Added CollectionDAOCompositionTest (verifies every moved @CreateSqlObject accessor stays visible + annotated — the mechanism JDBI relies on at runtime).

Backend integration tests

  • Not applicable — no API contract changes; existing openmetadata-service suite (5,800 tests) passes green and exercises the refactored DAO/repository layer end-to-end.

Ingestion / Playwright tests

  • Not applicable (no ingestion or UI changes).

Manual testing performed

  • Validated both DB migrations on ephemeral MySQL 8.0 and Postgres 16 containers: index creation is idempotent and EXPLAIN confirms the percentile query now does an index-only scan; the Postgres isBot fix flips a bot from counted→excluded in countDailyActiveUsers.

UI screen recording / screenshots:

Not applicable.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR is linked to a GitHub issue via Fixes #28785 above.
  • For JSON Schema changes: not applicable; DB migrations added for the entity_usage index and Postgres isBot column fix.
  • I have added tests and listed them above.

🤖 Generated with Claude Code

Greptile Summary

This PR decomposes two large "god-class" interfaces — CollectionDAO (15k lines → 433) and EntityRepository (~13k → ~10k) — into 17 focused DAO aggregator interfaces and 7 EntityRepository collaborators respectively, with no public API or call-site changes. Bundled alongside the structural refactor are targeted correctness fixes found during the decomposition.

  • DAO decomposition: CollectionDAO now extends 17 domain aggregator interfaces (RdfInfraDAOs, AccessControlDAOs, CoreRelationshipDAOs, etc.); JDBI's getMethods()-based wiring is guarded by the new CollectionDAOCompositionTest.
  • Bug fixes: Postgres isBot generated column was reading $.deleted instead of $.isBot (bots wrongly counted as active users); added a (entityType, usageDate) composite index so computePercentile uses range scans instead of full-table scans; listTeamsUnderOrganization results are now filtered for soft-deleted teams before subtree traversal and userCount computation.
  • Team hierarchy batching: fetchAndSetUserCount is 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

  • The refactoring is structurally sound — the composite-interface decomposition of CollectionDAO preserves JDBI's getMethods() wiring, the EntityRepository collaborators maintain the protected API for all 81 subclasses, and the bundled bug fixes (Postgres isBot column, entity_usage index, organization team soft-delete filtering) are correct.
  • The decomposition is mechanically verified by CollectionDAOCompositionTest and exercised by the full 5,800-test suite. The bug fixes are well-scoped and independently validated. Previous reviewer-found issues (organization childrenCount, soft-deleted users in userCount, organization subtree filtering) are all addressed in follow-up commits included here. No new logic bugs were identified in this review pass.
  • TeamRepository.java and UserRepository.java contain the most behaviorally significant changes (BFS subtree walk for userCount, batch role/team resolution) and warrant a final read-through. The Postgres schemaChanges.sql migration holds an ACCESS EXCLUSIVE lock on user_entity during the ADD COLUMN rewrite — documented, but worth confirming the deployment window plan for large installations.

Important Files Changed

Filename Overview
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java Reduced from 15k lines to a thin composite interface that extends 17 aggregator interfaces; all @CreateSqlObject accessors are still visible through JDBI's getMethods() traversal, guarded by CollectionDAOCompositionTest.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CoreRelationshipDAOs.java New file housing EntityRelationshipDAO, FieldRelationshipDAO, EntityExtensionDAO, and their nested types/mappers. SQL queries are faithfully moved from CollectionDAO; findToPipeline/findFromPipeline UNION-ALL queries preserved unchanged.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TeamRepository.java Replaces recursive per-team O(n) userCount with a BFS subtree walk (discoverSubtreeTeams + batchFetchDirectUsers); soft-delete filtering now applied consistently via nonDeletedToIds and getLiveOrganizationChildIds. Previous reviewer-found bugs (organization childrenCount, soft-deleted user/team leaking into count) are addressed.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java Individual per-record Entity.getEntityReferenceById calls replaced with batchResolveRefs throughout all bulk field fetchers; getInheritedRoles now accepts pre-fetched teams instead of calling getTeams(user) per-user. batchFetchTeamsForUsers introduces a second team query when both roles and teams fields are requested.
bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql Adds entity_usage composite index and fixes the isBot generated column (was reading $.deleted instead of $.isBot). The ALTER TABLE ADD COLUMN STORED holds ACCESS EXCLUSIVE on user_entity for the full rewrite duration — correctly documented as requiring a maintenance window for large deployments.
bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql Adds entity_usage (entityType, usageDate) composite index using plain CREATE INDEX, consistent with existing MySQL migration conventions (MySQL lacks CREATE INDEX IF NOT EXISTS).
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java Adds batchResolveRefs helper for bulk entity reference lookup with EntityNotFoundException on orphaned IDs (same fail-fast contract as old per-record calls); import statements updated from CollectionDAO.* to CoreRelationshipDAOs.*.
openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/CollectionDAOCompositionTest.java New guard test verifying every @CreateSqlObject accessor remains visible and annotated through CollectionDAO.getMethods() after decomposition; also ensures no type-level JDBI configurer annotations are placed on aggregator interfaces (which Java doesn't inherit across interfaces).
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AccessControlDAOs.java New aggregator for user/team/role/policy DAOs; includes listLiveTeamsUnderOrganization and countLiveTeamsUnderOrganization queries that add the soft-delete filter (deleted = FALSE OR deleted IS NULL) to the parentless-team discovery query.

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 --|> EntityDataDAOs
Loading

Reviews (23): Last reviewed commit: "fix(review): attach orphaned javadoc; re..." | Re-trigger Greptile

…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]>
@github-actions

github-actions Bot commented Jun 6, 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 backend safe to test Add this label to run secure Github workflows on PRs labels Jun 6, 2026
harshach and others added 6 commits June 6, 2026 16:01
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]>
harshach and others added 2 commits June 6, 2026 19:07
… (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]>

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

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

  • batchFetchDirectUsers uses Include.ALL for Team→User HAS relationships. 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. Use Include.NON_DELETED to count only active memberships in userCount.

# 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

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

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

  • childrenCount for the organization team is computed from listTeamsUnderOrganization(...).size(), which counts soft-deleted teams as children (the underlying query has no deleted=false filter). This can cause childrenCount to disagree with getChildren(..., 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]>

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

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 accessors and the test can still pass as long as the remaining count stays above MIN_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]>

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

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

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

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

Comment on lines +989 to +999
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;
}

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.

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]>

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

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.

@manerow

manerow commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

CollectionDAO.EntityRelationshipRecord now actually lives in CoreRelationshipDAOs.
Java lets you use it as CollectionDAO.EntityRelationshipRecord, but not import it that way.
So every Collate import ...CollectionDAO.EntityRelationshipRecord; fails to compile.

The data-access-request-e2e check on this PR is already red for this reason
(run):

ContextPluginRepository.java:[38,52] import requires canonical name for ...CoreRelationshipDAOs.EntityRelationshipRecord
JdbcResponseCacheStore.java:[21,52]  import requires canonical name for ...CoreRelationshipDAOs.EntityExtensionDAO
JdbcResponseCacheStore.java:[22,52]  import requires canonical name for ...CoreRelationshipDAOs.ExtensionRecord
ProvenanceGrants.java:[22,52]        import requires canonical name for ...CoreRelationshipDAOs.EntityRelationshipRecord

(The cannot find symbol errors after those are Lombok fallout, not separate bugs.)

Fix

6 Collate files need their import repointed to CoreRelationshipDAOs.
Collate #4577 was opened for
this, went Stale, and only covers 2 of them:

File Import In #4577
collate-service/.../repository/ContextPluginRepository.java:38 EntityRelationshipRecord yes
collate-service/.../repository/AIChartRepositoryCleanupTest.java:21 EntityRelationshipRecord yes
collate-service/.../service/ai/provenance/ProvenanceGrants.java:22 EntityRelationshipRecord no
collate-service/.../service/cache/JdbcResponseCacheStore.java:21 EntityExtensionDAO no
collate-service/.../service/cache/JdbcResponseCacheStore.java:22 ExtensionRecord no
collate-integration-tests/.../cache/JdbcResponseCacheStoreIT.java:35 EntityExtensionDAO no

I'd recommend to extend it to all 6 and merge it with this PR.

manerow
manerow previously approved these changes Aug 27, 2026
FeedDAOs,
AiGovernanceDAOs,
SearchReindexDAOs,
RdfInfraDAOs {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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:

  1. 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.
  2. The decomposition doesn't reach consumers. ReportDataRepository:40 in this very PR still casts to CollectionDAO.ReportDataTimeSeriesDAO for a type that now lives in TimeSeriesDAOs. 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.

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.

All three points check out — I verified each rather than taking them on faith:

  • 202 files reference CollectionDAO.<Nested> (EntityRelationshipObject 343, EntityRelationshipRecord 128, TagUsageDAO 62 — your counts were essentially exact)
  • ReportDataRepository:40 does still cast to CollectionDAO.ReportDataTimeSeriesDAO for a type that now lives in TimeSeriesDAOs
  • 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.

Comment on lines +1203 to +1212
// 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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The 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 by source + tagFQN), or
  • keep the sweep report-only and say so — drop "so it must still see them", and have processTagUsage mark NULL-hash orphans as non-deletable so the summary doesn't report Found: N for 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".

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.

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

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

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

Comment on lines +886 to +894
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());

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.

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

Comment on lines +982 to +989
* 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.
*/
/**

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.

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]>

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

Copilot reviewed 88 out of 89 changed files in this pull request and generated 1 comment.

Comment on lines +119 to +121
tagUsageBatch.forEach(tagUsage -> processTagUsage(tagUsage, result));
processedCount += tagUsageBatch.size();

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.

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]>
@gitar-bot

gitar-bot Bot commented Aug 28, 2026

Copy link
Copy Markdown
Code Review ⚠️ Changes requested 4 resolved / 5 findings

Decomposes CollectionDAO and EntityRepository into cohesive domain-specific collaborators while fixing several persistence bugs. Access control on lineage audit fields requires hardening, as the new implementation incorrectly trusts client-provided audit timestamps and user IDs.

⚠️ Security: Lineage audit fields createdBy/updatedBy now trust client payload

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/LineageRepository.java:1752-1766 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/LineageRepository.java:169

The refactor of addLineage replaced the previously authoritative audit-field assignment with applyTemporalFields, which now derives createdBy, updatedBy, createdAt and updatedAt from the incoming request body when no prior record exists.

Previously the code unconditionally did:

lineageDetails.setCreatedBy(updatedBy);
lineageDetails.setUpdatedBy(updatedBy);
lineageDetails.setCreatedAt(currentTime);
lineageDetails.setUpdatedAt(System.currentTimeMillis());

so these fields always reflected the authenticated principal (updatedBy) and server time.

Now:

  • resolveCreatedBy returns incoming.getCreatedBy() when there is no prior record.
  • applyTemporalFields sets updatedBy to incoming.getUpdatedBy() != null ? incoming.getUpdatedBy() : fallbackUser — i.e. a client-supplied updatedBy in the LineageDetails request body overrides the authenticated user.
  • resolveUpdatedAt/resolveCreatedAt likewise honor client-supplied timestamps.

Because lineageDetails comes directly from the AddLineage request body (see addLineage), a caller can spoof the provenance/audit fields (who created/updated the lineage edge and when), and these spoofed values are persisted and propagated into the emitted ENTITY_LINEAGE_ADDED/UPDATED change events. This is an audit-integrity regression.

Suggested fix: keep the prior-record preservation behavior for consolidation, but always force updatedBy to the authenticated fallbackUser, and ignore client-supplied createdBy on initial creation (use fallbackUser). Timestamps should be server-generated.

Force updatedBy/updatedAt to the authenticated user and server time; only preserve the original createdBy from the prior record.
private static void applyTemporalFields(
    LineageDetails incoming, LineageDetails prior, String fallbackUser, long now) {
  incoming.setCreatedAt(resolveCreatedAt(incoming, prior, now));
  // Provenance must reflect the authenticated principal, never client-supplied values.
  incoming.setCreatedBy(prior != null && prior.getCreatedBy() != null ? prior.getCreatedBy() : fallbackUser);
  incoming.setUpdatedAt(now);
  incoming.setUpdatedBy(fallbackUser);
}
✅ 4 resolved
✅ Bug: isBot fix only on Postgres; confirm MySQL was already correct

📄 bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql:341-352
The PR fixes the Postgres isBot generated column (migration 1.6.3 erroneously defined it as (json ->> 'deleted')::boolean). I verified that the corresponding MySQL migration (1.6.3) defined the column correctly as GENERATED ALWAYS AS (json -> '$.isBot'), so MySQL did NOT have the bug and correctly does not receive an equivalent fix in 2.0.0/mysql/schemaChanges.sql. This is consistent and correct — flagging only as a verification note so reviewers confirm no MySQL deployment was relying on the buggy behavior. No code change needed.

✅ Quality: Composition guard test only checks a hardcoded subset of moved accessors

📄 openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/CollectionDAOCompositionTest.java:35-49
CollectionDAOCompositionTest guards that @CreateSqlObject accessors moved into the new aggregator interfaces stay visible/annotated through CollectionDAO — the mechanism JDBI relies on at runtime. However it only validates the ~35 entries hardcoded in MOVED_ACCESSOR_TO_INTERFACE, not every moved accessor across all 17 interfaces. A regression where a non-listed accessor loses its annotation or visibility would not be caught. Consider deriving the expected accessor set by reflecting over the extended interfaces (iterate the extends list and collect their @CreateSqlObject methods) so the test stays exhaustive as the interfaces evolve.

✅ Performance: Postgres isBot migration rewrites user_entity table under exclusive lock

📄 bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql:347-352
The Postgres fix does ALTER TABLE user_entity DROP COLUMN IF EXISTS isBot followed by ADD COLUMN isBot BOOLEAN GENERATED ALWAYS AS ((json ->> 'isBot')::boolean) STORED NOT NULL. Adding a STORED generated column forces a full table rewrite and takes an ACCESS EXCLUSIVE lock on user_entity for the duration, in addition to the preceding full-table UPDATE ... jsonb_set(...). On deployments with very large user_entity tables this can mean a notable maintenance-window stall. The logic is correct and idempotent; this is purely an operational heads-up. Consider documenting expected runtime / running during a maintenance window, which the PR's migration notes partially do.

✅ Bug: deleteLineageBySource omits ENTITY_LINEAGE_DELETED change events

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/LineageRepository.java:1093-1107
Both deleteLineage and deleteLineageByFQN were updated to emit an ENTITY_LINEAGE_DELETED change event after a successful delete. However, deleteLineageBySource (used by the DELETE .../lineage/{entityType}/{entityId}/{lineageSource} endpoint) deletes one or more lineage edges (deleteLineageBySourcePipeline / deleteLineageBySource) but does not emit any change event.

This is an inconsistency: consumers/alerts subscribed to lineage-deleted events will be notified for single-edge deletions but silently miss source-based bulk deletions. If lineage change events are meant to drive notifications/audit, the source-based path should emit ENTITY_LINEAGE_DELETED for each removed relation (it already loads relations for deleteLineageFromSearch).

🤖 Prompt for agents
Code Review: Decomposes CollectionDAO and EntityRepository into cohesive domain-specific collaborators while fixing several persistence bugs. Access control on lineage audit fields requires hardening, as the new implementation incorrectly trusts client-provided audit timestamps and user IDs.

1. ⚠️ Security: Lineage audit fields createdBy/updatedBy now trust client payload
   Files: openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/LineageRepository.java:1752-1766, openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/LineageRepository.java:169

   The refactor of `addLineage` replaced the previously authoritative audit-field assignment with `applyTemporalFields`, which now derives `createdBy`, `updatedBy`, `createdAt` and `updatedAt` from the incoming request body when no prior record exists.
   
   Previously the code unconditionally did:
   ```
   lineageDetails.setCreatedBy(updatedBy);
   lineageDetails.setUpdatedBy(updatedBy);
   lineageDetails.setCreatedAt(currentTime);
   lineageDetails.setUpdatedAt(System.currentTimeMillis());
   ```
   so these fields always reflected the authenticated principal (`updatedBy`) and server time.
   
   Now:
   - `resolveCreatedBy` returns `incoming.getCreatedBy()` when there is no prior record.
   - `applyTemporalFields` sets `updatedBy` to `incoming.getUpdatedBy() != null ? incoming.getUpdatedBy() : fallbackUser` — i.e. a client-supplied `updatedBy` in the `LineageDetails` request body overrides the authenticated user.
   - `resolveUpdatedAt`/`resolveCreatedAt` likewise honor client-supplied timestamps.
   
   Because `lineageDetails` comes directly from the `AddLineage` request body (see `addLineage`), a caller can spoof the provenance/audit fields (who created/updated the lineage edge and when), and these spoofed values are persisted and propagated into the emitted `ENTITY_LINEAGE_ADDED/UPDATED` change events. This is an audit-integrity regression.
   
   Suggested fix: keep the prior-record preservation behavior for consolidation, but always force `updatedBy` to the authenticated `fallbackUser`, and ignore client-supplied `createdBy` on initial creation (use `fallbackUser`). Timestamps should be server-generated.

   Fix (Force updatedBy/updatedAt to the authenticated user and server time; only preserve the original createdBy from the prior record.):
   private static void applyTemporalFields(
       LineageDetails incoming, LineageDetails prior, String fallbackUser, long now) {
     incoming.setCreatedAt(resolveCreatedAt(incoming, prior, now));
     // Provenance must reflect the authenticated principal, never client-supplied values.
     incoming.setCreatedBy(prior != null && prior.getCreatedBy() != null ? prior.getCreatedBy() : fallbackUser);
     incoming.setUpdatedAt(now);
     incoming.setUpdatedBy(fallbackUser);
   }

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

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

Copilot reviewed 88 out of 89 changed files in this pull request and generated no new comments.

@sonarqubecloud

Copy link
Copy Markdown

@harshach

Copy link
Copy Markdown
Collaborator Author

CI triage

python / Integration Tests (shard-2, 3.10) — flake, now green. SqlServerContainer missed testcontainers' 10s readiness window (Cannot run 'SELECT 1': container is not ready) in a module fixture. This PR changes zero Python files, and on this same commit py-tests (MySQL) passed all nine shards including shard-2, 3.10 while only the Postgres pipeline's copy failed — the MSSQL container is test-local and unrelated to the server's backing DB. Rerun passed; py-tests-status and Verify Expected Jobs cleared with it.

Separately: test_dynamic_sampling_mssql.py declares no wait strategy against a SQL Server 2022 image that routinely needs longer than 10s to accept connections. That's a real pre-existing flake on main, worth its own PR rather than unrelated Python churn here.

maven-collate-ci / data-access-request-e2e — real, fixed in open-metadata/openmetadata-collate#4577. Both are dispatchers for the same Collate build. Of its 100 errors, four are real:

ContextPluginRepository.java:38   import requires canonical name for ...CoreRelationshipDAOs.EntityRelationshipRecord
JdbcResponseCacheStore.java:21    ...CoreRelationshipDAOs.EntityExtensionDAO
JdbcResponseCacheStore.java:22    ...CoreRelationshipDAOs.ExtensionRecord
ProvenanceGrants.java:22          ...CoreRelationshipDAOs.EntityRelationshipRecord

The other 96 are Lombok cascade (variable log, builder(), and the giveaway method onMethod_() / location: @interface lombok.Getter), which appears once annotation processing bails after a real error.

Cause is the decomposition itself: CollectionDAO still inherits these nested types, so inline CollectionDAO.X references and daoCollection.xDAO() calls resolve unchanged, but a single-type import needs the canonical declaring name under JLS 7.5. Six such imports across five Collate files, all repointed to CoreRelationshipDAOs; a tree-wide sweep leaves none, and all 48 nested types Collate references inline resolve to one of the 17 aggregators CollectionDAO extends. This PR deletes no Java files, so import canonicality is its only source-incompatible change.

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 -Xmaxerrs, so a real error could have been truncated; none was.

Ordering: these two checks build Collate main, so they stay red until #4577 merges — and once it does, Collate main compiles against OpenMetadata main and goes red until this lands. There's no order that avoids a red window; the two need to land together.

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

backend safe to test Add this label to run secure Github workflows on PRs skip-pr-checks Bypass PR metadata validation check

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Decompose CollectionDAO & EntityRepository god-classes and fix latent DAO-layer perf/correctness bugs

6 participants