Skip to content

Fixes #35879: Preserve remaining search fields and refresh move and label copies - #36256

Merged
mohityadav766 merged 5 commits into
mainfrom
codex/search-sync-followups
Dec 2, 2026
Merged

mohityadav766 merged 5 commits into
mainfrom
codex/search-sync-followups

Conversation

@mohityadav766

@mohityadav766 mohityadav766 commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Fixes #35879

Follow-up to merged #35888. Additional paths still overwrite complete search documents with partial entities or leave copied fields stale.

Changes:

  • Container and knowledge-page moves rewrite only their own index, and only the moved entity and what sits under it at an FQN boundary. Container moves used the global alias, so another entity type holding the same FQN (services of different types may share a name) was renamed with it.
  • A team membership PATCH re-indexes the users it added or removed. User display-name changes reach query users, page editors and file lastModifiedBy.
  • A changed PUT keeps followers and votes, and resolves inherited fields once, before its search write, which its response reuses. Import PUTs keep followers and votes the same way. PATCH inheritance is unchanged.
  • Reindex reads load usageSummary for dashboards, pipelines, ML models and schemas; query users; user activity timestamps; context-file folders; context-memory source references. ML-model usage refresh reads the model as an ML model, not a chart.
  • Renaming or moving a classification, tag, glossary or term re-indexes soft-deleted descendants too. Membership re-indexing still reads non-deleted entities.
  • Copies held as a single object are relabeled as well as lists, including a subdomain's parent. Object copies are matched on the id and on its keyword sub-field, because a copy no mapping declares (a subdomain's parent) is mapped dynamically as text.
  • Query lists load users in one batch with the single read's rules (users only, not deleted) instead of re-reading each query's users in clearFields.

Regression coverage:

  • EntityUpdateSearchDocIT: PUT followers/votes, inherited domains, retained tags, and PATCH owner inheritance.
  • ReindexFieldSetSearchDocIT: usage and query users survive a rebuild from a reindex read (/v1/search/reindexEntities after deleting the doc).
  • RenameCascadeSearchIT: container moves leave siblings and other entity types with the same FQN alone; page moves; soft-deleted tags/terms.
  • TeamMembershipSearchIT for PATCH; ReferenceLabelSearchIT for query users and subdomain parent labels.
  • SearchRepositoryTest covers the Include overload of updateEntitiesByReference.

Validation on 4616c73 (main merged in 1ce632a):

  • RED first: containerMove_leavesOtherTypesWithTheSameFqnAlone fails on the global-alias rewrite (the database doc became ….archive.raw), and pipelineReindex_keepsUsage fails without usageSummary in PipelineIndex's field set (usage 0 after the rebuild). Both pass with the fixes. domainDisplayName_reachesSubdomainParent failed in both CI IT lanes on the previous head and passes now.
  • Unit tests for the touched classes: 534 tests, 0 failures (SearchRepositoryTest, SearchRepositoryBehaviorTest, SearchIndexFactoryTest, UpdateByQueryReconcilerTest, SearchClientTagScriptSeparationTest, SearchIndexReindexFieldsParityTest, ContainerRepositoryParentValidationTest, QueryRepository*Test, TeamRepositoryUnitTest, EntityLoaderIndirectionTest).
  • MySQL + Elasticsearch, parallel lane, the search ITs above plus ContainerResourceIT, QueryResourceIT, TeamResourceIT, UserResourceIT, DomainResourceIT, DataProductResourceIT, KnowledgePageHierarchyIT, TestCaseResourceIT and GlossaryTermResourceIT: 2541 tests, 194 skipped. Two failures: QueryResourceIT.test_batchFetchQueryFields found that findFromRecordsBatch passed the from and to types to the DAO swapped (fixed; rerun of QueryResourceIT, GlossaryTermResourceIT, ReindexFieldSetSearchDocIT and ReferenceLabelSearchIT: 604 tests, 0 failures), and the DataProductResourceIT test below.
  • Postgres + OpenSearch, same set on the final code: 2541 tests, 194 skipped, 1 failure, DataProductResourceIT.test_forgedDomainFqnCannotBypassTheDomainRule. It does not come from this PR: Fixes 37376: Let data products take assets from subdomains of their domain #39252 added it asserting InvalidRequestException from tables().update(), but the SDK's EntityServiceBase.update wraps every error in OpenMetadataException, so it cannot pass as written. The server returns the expected 400.
  • The full unit suite and both full IT lanes run in CI on this head.

Still outside this PR:

  • Async cascade task tracking, conflict reconciliation and retry-queue fallback.
  • Cluster-wide staged-index routing during recreate reindexing.
  • Remaining audit items: time-series DQ tag/domain/reference copies, team counts on user create/delete, and additional display-only references (including relatedTerms, role and chart/dashboard copies). These need focused follow-up validation and fixes.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 4/5

Restrict container move writes to the container index before merging.

Findings

  1. P1 Container moves rename unrelated files ▶

Summary

Preserves fields during entity updates and reindexing, refreshes team membership and copied labels, and includes deleted descendants in rename refreshes.

  • Entity updates keep their tags, votes, followers, and inherited fields in search.
  • Search rebuilds keep the usage and relationship fields their pages need.
  • Renames and moves update only the matching search records.
  • Copied labels and team membership stay current in search.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Container moves] --> B[Update matching FQN through all]
  B --> C[Container documents renamed]
  B --> D[File with matching FQN also renamed]
  D --> E[Search path differs from saved file]
Loading

Reviews (1) · Last reviewed commit: "fix(search): preserve PUT relationships ..." · Reviewed by Greptile

…search

- Moving a container or a knowledge page rewrote, by a bare text prefix, the
  FQN of every document whose FQN started with the old one: a sibling such
  as "rawdata" when "raw" moved, and documents of other types that happened
  to start the same way. The rewrite now matches the moved entity and what is
  under it, and replaces only the leading FQN segments.
- Changing a team's users through a team PATCH did not re-index those users,
  so their teams went stale in search.
- A user's display-name change now also reaches query users, knowledge page
  editors and file lastModifiedBy.
…-reading entities

A full reindex, the retry-queue replay, reindexEntities and the live
updateEntity(ref) path load each entity with its index's required field
list. Fields its repository only loads on request were missing from the
list, so the search document lost them:

- usageSummary for pipelines, dashboards, ML models and schemas. Usage
  reports re-index through updateEntity(ref), so live usage never
  reached search for these types.
- users on queries, which the Table > Queries panel reads from search.
- lastLoginTime and lastActivityTime on users, which the Online Users
  search filters on.
- folder on context files, which the Context Center Documents page
  filters on.
- primaryEntity, relatedEntities, sourceEntity and sourceFile on
  context memories, which the asset memories listing filters on.

Reporting usage for an ML model also failed with "Entity not found:
chart": mlModelEntityUsage re-read the model as a chart.
@github-actions github-actions Bot added backend safe to test Add this label to run secure Github workflows on PRs labels Oct 26, 2026
@mohityadav766 mohityadav766 self-assigned this Oct 26, 2026
@mohityadav766
mohityadav766 marked this pull request as ready for review October 26, 2026 13:39
@mohityadav766
mohityadav766 requested a review from a team as a code owner October 26, 2026 13:39
Comment on lines +798 to +805
t.field(prefixFieldCondition)
.value(FieldValue.of(oldParentFQN))))
.should(
s ->
s.prefix(
p ->
p.field(prefixFieldCondition)
.value(oldParentFQN + Entity.SEPARATOR)))

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.

P1 Container moves rename unrelated files

The boundary check still leaves the intended index restriction incomplete. ContainerRepository.updateAssetIndexes passes GLOBAL_SEARCH_ALIAS, and both Elasticsearch and OpenSearch filter only by fullyQualifiedName. Service names can repeat across service types, so a container and a file can both have svc.raw as their FQN. Moving that container also rewrites the file's search document, although its saved path never changed.

Target the container's write index and add a regression test with matching FQNs across entity types.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 4616c73: ContainerRepository.updateAssetIndexes now rewrites only the container write index, as page moves already do. New RenameCascadeSearchIT.containerMove_leavesOtherTypesWithTheSameFqnAlone gives a database and a container the same FQN (same-named database and storage services). On the global-alias rewrite it failed: the database doc became ….archive.raw. It passes now.

@mohityadav766 mohityadav766 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reviewed the latest head against current main, #35879 and merged #35888. Although #35879 is closed, this follow-up still contains absent fixes: PUT followers/votes and inheritance, reindex field hydration, membership refreshes and copied labels. It is not superseded by the earlier tag-preservation fix. The existing P1 about container moves targeting the global search alias remains applicable; I am not duplicating it inline. No additional substantiated finding from this static pass. The latest service-unit workflow failed, broad integration lanes were skipped, and the PR remains draft pending integration validation. Please resolve the existing index-scoping finding and validate the search/cascade cases on both engines before treating this as ready. No tests run locally.

Reviewed head: ab5f5f0dd223f4fbfb464e7d78d4075a480e6f81.

@harshach harshach left a comment

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.

Good follow-up overall, especially on the boundary-safe FQN scripts, soft-deleted cascade reindexing, and the ML model usage fix. Two blockers need to be resolved before merge: domain_index_mapping.json does not map parent (so parent.id is dynamically analyzed as text and updateReferenceCopies will match zero subdomains), and ContainerRepository.updateAssetIndexes still targets GLOBAL_SEARCH_ALIAS instead of the container index. Please also address the performance regressions flagged inline — the N+1 getQueryUsers call in QueryRepository.clearFields, duplicate parent-inheritance traversal on changed PUTs, and unguarded consolidation replays in TeamRepository.updateChangedUsers — along with extending ReindexFieldSetSearchDocIT to verify usageSummary after reindexing.

Comment on lines 10807 to 10811
if (operation.isPatch() || operation.isPut()) {
try (var ignored = phase("updateSetInheritedFields")) {
setInheritedFields(updated, operation.isPatch() ? patchFields : putFields);
}
}

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.

Calling setInheritedFields(updated, putFields) in reactUpdate causes every changed PUT (and import PUT) to traverse the parent inheritance chain twice, because applyPut (line 4848) and putForImportAndStore (line 4899) still call setInheritedFields(updated, new Fields(allowedFields)) right after update() returns. Resolve with new Fields(allowedFields) here (or track that inheritance already ran) and skip the post-update call in applyPut/putForImportAndStore when a change occurred.

Suggested change
if (operation.isPatch() || operation.isPut()) {
try (var ignored = phase("updateSetInheritedFields")) {
setInheritedFields(updated, operation.isPatch() ? patchFields : putFields);
}
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done. reactUpdate resolves a PUT with new Fields(allowedFields) and records it; applyPut and putForImportAndStore skip their call when it ran. A PUT that changed nothing still resolves in applyPut, since reactUpdate returns early there.

Comment on lines +11010 to +11013
if (operation.isPut()) {
updated.setFollowers(original.getFollowers());
updated.setVotes(original.getVotes());
}

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.

updateInternalForImport (line 11042) also runs under Operation.PUT and feeds reactUpdate() -> postUpdate() for search indexing, but still does not carry followers and votes from original. Copy them there too (or share a small helper with updateInternal) so import PUTs do not blank followers and votes in search.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done. updateInternal and updateInternalForImport share keepFieldsPutCannotChange(). The only caller of the single import path today is test-case CSV import, where followers come from the table through inheritance, so this keeps the two paths consistent rather than changing a visible result.

Comment on lines +1642 to +1649
Set<UUID> updatedUserIds =
updatedUsers.stream().map(EntityReference::getId).collect(Collectors.toSet());
reindexMembership(
updatedTeam,
Stream.concat(
addedUsers.stream().map(EntityReference::getId),
origUserIds.stream().filter(id -> !updatedUserIds.contains(id)))
.toList());

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.

Guard reindexMembership(...) with if (isIndexBaselinePass()) (matching TableRepository.java:2454): during same-session change consolidation, updateChangedUsers runs across multiple replay passes and will enqueue duplicate post-commit DB reads and bulk search writes on every pass. Also consider avoiding re-adding team.getEntityReference() on this updater path since TeamUpdater's postUpdate already re-indexes updatedTeam.

Suggested change
Set<UUID> updatedUserIds =
updatedUsers.stream().map(EntityReference::getId).collect(Collectors.toSet());
reindexMembership(
updatedTeam,
Stream.concat(
addedUsers.stream().map(EntityReference::getId),
origUserIds.stream().filter(id -> !updatedUserIds.contains(id)))
.toList());

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done. The members are re-indexed only when isIndexBaselinePass(), and the updater path re-indexes just the users; the team document is left to postUpdate. The /users endpoints, which run no updater, still re-index the team too.

"users"),
Entity.TEAM, List.of(FIELD_OWNERS, FIELD_REVIEWERS, "teams", "parents"),
Entity.DOMAIN, List.of(FIELD_DOMAINS),
Entity.DOMAIN, List.of(FIELD_DOMAINS, "parent"),

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.

Adding "parent" here will not relabel subdomain documents in Elasticsearch/OpenSearch because domain_index_mapping.json has no parent mapping (only parentId), so parent.id is dynamically mapped as analyzed text (splitting UUIDs on -). Since updateReferenceCopies queries terms on parent.id, it will match zero subdomains; add an explicit parent object mapping with id as keyword to all domain_index_mapping.json files (or also match parent.id.keyword).

Suggested change
Entity.DOMAIN, List.of(FIELD_DOMAINS, "parent"),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed on the query side, for both engines: updateReferenceCopies matches object copies on <path>.id and on <path>.id.keyword. Existing domain indexes already map parent dynamically as text, and an explicit keyword mapping would only reach indexes rebuilt after upgrading, so matching the keyword sub-field covers both. It is the fallback anyOfFieldQuery already uses for the parent.id child update. domainDisplayName_reachesSubdomainParent, which failed in both CI IT lanes, passes on MySQL/ES and Postgres/OpenSearch.

// query_search_index and Table → Queries renders the empty state.
fields.add("queryUsedIn");
// "users" is stripped from storage JSON the same way; the Queries panel lists them from here.
fields.add("users");

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.

Adding "users" to QueryIndex.getRequiredReindexFields() triggers an N+1 DB query on every query reindex batch because QueryRepository.clearFields (line 115) calls this.getQueryUsers(entity) instead of entity.getUsers(), discarding the batch result that fetchAndSetQueryUsers just loaded on line 128. Change QueryRepository.clearFields line 115 to entity.getUsers() alongside this change so bulk query reindexing stays batched.

Suggested change
fields.add("users");

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done: clearFields keeps entity.getUsers(). The batch loader returned something else than getQueryUsers (any USES source, deleted users included), which the re-read had been masking, so fetchAndSetQueryUsers now applies the single read's rules too: users only, not deleted, one relationship read and one reference read per batch. That surfaced a bug in EntityRepository.findFromRecordsBatch, which passed the from and to types to the DAO swapped; fixed, and its only other caller uses one type for both. QueryResourceIT.test_batchFetchQueryFields covers the list path.

Comment on lines +237 to +239
// usageSummary is fields-gated in these repositories. A reindex dropped it, and a live usage
// report never landed at all: UsageRepository re-reads through updateEntity(ref), which loads
// only these fields, so the doc kept no usage and the usage-based ranking boosts had nothing.

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.

Update this comment to match current UsageRepository.updateUsageInSearch: live usage reports now patch usageSummary directly via updateEntityFieldInSearch rather than calling updateEntity(ref), so this field set is what keeps usageSummary from being wiped on full reindex and reference-based rebuilds.

Suggested change
// usageSummary is fields-gated in these repositories. A reindex dropped it, and a live usage
// report never landed at all: UsageRepository re-reads through updateEntity(ref), which loads
// only these fields, so the doc kept no usage and the usage-based ranking boosts had nothing.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Updated the comment.

Comment on lines +117 to +131
private static void assertUsageReachesSearchDoc(String entityType, String index, UUID id) {
SdkClients.adminClient()
.getHttpClient()
.execute(
HttpMethod.POST,
"/v1/usage/" + entityType + "/" + id,
new DailyCount().withDate(LocalDate.now().toString()).withCount(DAILY_USAGE),
EntityUsage.class);
awaitDocAsserted(
index,
id,
doc ->
assertEquals(
DAILY_USAGE, doc.path("usageSummary").path("dailyStats").path("count").asInt()));
}

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.

Because UsageRepository.updateUsageInSearch patches usageSummary directly via updateEntityFieldInSearch without loading getRequiredReindexFields(), these three usage tests would still pass even if PipelineIndex, DashboardIndex, and MlModelIndex dropped "usageSummary" from their reindex field sets. After asserting the live usage write, delete the search doc and invoke /v1/search/reindexEntities (just as singleEntityReindex_keepsQueryUsers does) so the reindex path is actually verified.

Suggested change
private static void assertUsageReachesSearchDoc(String entityType, String index, UUID id) {
SdkClients.adminClient()
.getHttpClient()
.execute(
HttpMethod.POST,
"/v1/usage/" + entityType + "/" + id,
new DailyCount().withDate(LocalDate.now().toString()).withCount(DAILY_USAGE),
EntityUsage.class);
awaitDocAsserted(
index,
id,
doc ->
assertEquals(
DAILY_USAGE, doc.path("usageSummary").path("dailyStats").path("count").asInt()));
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done. Each usage test now deletes the doc after the live write, calls /v1/search/reindexEntities, and asserts usage again (*Reindex_keepsUsage). Without usageSummary in PipelineIndex's field set, pipelineReindex_keepsUsage fails (usage 0 after the rebuild).

…trim PUT and team overhead

- Container moves rewrite only the container index. Services of different
  types may share a name, so a database could hold the moved container's FQN
  and was renamed with it.
- The relabel query also matches an object copy's id on its keyword
  sub-field. The domain mapping has no parent, so a subdomain's parent id is
  dynamically mapped as text and the exact match found no subdomain.
- A changed PUT resolves inherited fields once, with every field, before
  indexing, and its caller no longer repeats the walk. Import PUTs keep
  followers and votes as regular PUTs do.
- A team update re-indexes the users it added or removed only on the pass
  against the stored team, and leaves the team's own document to the update.
- Query lists keep the users loaded in one batch, now read with the single
  read's rules (users only, not deleted), instead of re-reading each query's
  users in clearFields. findFromRecordsBatch passed the from and to entity
  types to the DAO swapped; its only other caller uses one type for both.
- The usage ITs rebuild the document from a reindex read: a live usage report
  patches usageSummary directly, so it never exercised the field set.
- SearchRepositoryTest stubs the overload updateEntitiesByReference delegates
  to.
@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

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

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

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

@gitar-bot

gitar-bot Bot commented Dec 2, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 🟡 Medium risk

Changes shared entity-update and search reindexing paths across multiple entity types; regressions could leave search documents stale or mislabel copied references.

Preserves search fields across entity PUT/PATCH updates, reindex reads, team membership changes, and copied labels, and limits container and knowledge-page move rewrites to their own index. No open issues found.

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

@mohityadav766
mohityadav766 merged commit 0830609 into main Dec 2, 2026
39 of 41 checks passed
@mohityadav766
mohityadav766 deleted the codex/search-sync-followups branch December 2, 2026 07:08
pmbrull added a commit that referenced this pull request Dec 3, 2026
…ompile (#39703)

#39624 backported StoredParentReferenceIT, which calls
SearchDocs.awaitDocAsserted. That helper came in on main with #36256 and
was never backported, so openmetadata-integration-tests fails to
test-compile on 2.1. Bring over just the helper.

Co-authored-by: Claude Opus 5.5 <[email protected]>
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tags and Tier disappear from search after an ingestion run that changes the table

2 participants