Skip to content

Fixes #34394: Isolate context memory lifecycle statuses - #34785

Merged
pmbrull merged 10 commits into
mainfrom
pmbrull/memory-retirement-statuses
Oct 8, 2026
Merged

pmbrull merged 10 commits into
mainfrom
pmbrull/memory-retirement-statuses

Conversation

@pmbrull

@pmbrull pmbrull commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

Describe your changes:

Fixes #34394

Give context memories their own generated ContextMemoryStatus enum, including Superseded and Invalidated, following the revised lifecycle design. Other entities retain the shared EntityStatus vocabulary. The initial memory lifecycle PR, #34717, has merged; this follow-up is based on current main.

Type of change:

  • Breaking change (generic Java status contract and separate generated memory enum)

High-level design:

  • Add entity/context/contextMemoryStatus.json and reference it from both the memory and create-memory schemas. Retain Unprocessed and legacy Deprecated/Rejected values for stored memories and version history. Superseded and Invalidated are absent from type/status.json.
  • Make EntityInterface<S extends Enum<S>> generic. Generated memories implement EntityInterface<ContextMemoryStatus>; existing entities keep EntityInterface<EntityStatus>. Most of the 619 changed files are the one-time generic migration and generated models, including shared status-description regeneration.
  • Use EntityLifecycle<S> and a policy-provided EntityStatusAdapter<S> at common repository boundaries. Validate that each graph covers exactly its generated schema vocabulary and that its adapter matches the entity's declared enum.
  • Declare memory initialization and transitions with ContextMemoryStatus. Retirement requires a reason; supersession additionally requires a live, readable successor and rejects self-references and cycles. Restoration clears stale successor/reason metadata. Ordinary search, grounding, and ontology proposals continue to require Approved memories.
  • Keep lifecycle discovery's JSON shape using string codes, with an optional entity/search-index scope. SQL filters resolve against the relevant entity's policy. Workflow writes resolve the target's generated enum and pass through repository lifecycle constraints.
  • Generic search selectors discover the selected types' vocabulary. Workflow writes offer the intersection of target vocabularies and guard failed/stale discovery and invalid selections. Memory controls derive options from their generated enum, falling back to wire codes for untranslated future values. Autocomplete keeps one discovery promise per selector instance, shares concurrent loads, and clears failed loads for retry.
  • Future memory vocabulary changes require memory schemas and policy changes followed by regeneration. Extending the shared enum would expose memory-only values to unrelated entities; using untyped statuses throughout would lose the generated enum contract. The generic contract plus adapters retains type checks while supporting specialized policies.

Compatibility and migration: Java clients/plugins implementing or consuming EntityInterface must rebuild with the generic contract; memory callers must use ContextMemoryStatus. Regenerate Java, Python, and TypeScript models together. Existing supported memory wire values and stored JSON remain readable, so no database migration is required. In Review remains a general-entity status and is not a memory lifecycle stage.

Tests:

Use cases covered

  • Independent memory/general vocabularies, complete policy graphs, mismatched adapters, invalid status values, initialization, and legacy/null statuses.
  • New and legacy retirement, successor validation, restoration, PUT preservation, workflow writes, and trusted-search visibility.
  • Entity-scoped discovery and aliases, SQL filtering, general-entity lifecycle behavior, mixed workflow targets, discovery errors, and out-of-order responses.
  • Memory status/text/author/sort combinations, Unprocessed defaults, retirement badges/reasons, successor navigation, and proposal restrictions.
  • Concurrent autocomplete loads, reuse across later keystrokes, and recovery after a failed request. The two new regressions failed before the fix and pass with it.

Unit tests

  • Added/updated tests for the changed logic.
  • Merge-resolution verification: 359 service tests passed. Command: mvn -B -pl openmetadata-service install -Dtest='ContextMemory*Test,EntityLifecycleTest,EntityStatusAdapterTest,EntityFieldUtilsTest,ListFilterTest,Recipient*Test,*MessageDecoratorTest,SubscriptionUtilTest,SearchDocFieldValidationTest,SearchIndexTest,SearchIndexPrefetchTest'.
  • Fresh coverage run: 111 passed, using mvn -B -pl openmetadata-service jacoco:prepare-agent test jacoco:report -Dtest='ContextMemoryLifecycleTest,ContextMemoryRepositoryTest,EntityLifecycleTest,EntityStatusAdapterTest,EntityFieldUtilsTest,ListFilterTest' -Djacoco.append=false.
  • Service test files under openmetadata-service/src/test/java/org/openmetadata/service/: governance/EntityStatusAdapterTest.java, governance/EntityLifecycleTest.java, jdbi3/ContextMemoryLifecycleTest.java, jdbi3/ContextMemoryRepositoryTest.java, jdbi3/ListFilterTest.java, util/EntityFieldUtilsTest.java, and the memory schema/transition/visibility regressions under resources/context/ and search/.
  • JaCoCo whole-class line coverage: EntityStatusAdapter 97.3%, EntityLifecycle 90.2%, ContextMemoryLifecycle 94.5%, EntityFieldUtils 91.5%. The 90% whole-class target is not met by large existing classes: ContextMemoryRepository 13.2% and ListFilter 51.8% in this focused unit run; real REST tests cover their lifecycle/filter behavior.
  • Merge-resolution UI verification: 173 passed in 12 suites on 25832d9ec89. After the autocomplete fix, 108 passed in 3 status/search suites, plus 4 workflow-form tests passed. Commands from the UI root: yarn test src/utils/governance/lifecycle/LifecycleStatus.utils.test.ts src/utils/AdvancedSearchClassBase.test.ts src/utils/JSONLogicSearchClassBase.test.ts --watchAll=false --runInBand --coverage --collectCoverageFrom=src/utils/governance/lifecycle/LifecycleStatus.utils.ts, and yarn test src/components/WorkflowDefinitions/WorkflowBuilder/forms/SetActionForm.test.tsx --watchAll=false --runInBand.
  • LifecycleStatus.utils.ts has 100% line coverage. Previously measured whole-component coverage for the existing SetActionForm is 62.2%; its new status loading, failure, race, and invalid-save behavior is exercised through real UI components.
  • Before the main merge, the broader generic-contract validation also passed 731 service, 277 SDK, 62 operator, and 710 MCP tests. Client tests used -Djunit.version=5.11.4 for an existing SDK JUnit/Platform mismatch; no dependency files were changed for that workaround.

Backend integration tests

  • Added/updated API integration coverage.
  • 256 passed, 26 skipped after merging main, against real PostgreSQL and Elasticsearch: mvn -B -pl openmetadata-integration-tests test -Dtest='ContextMemoryIT,ContextMemoryAnchorIT,ContextMemoryLifecycleIT,OntologyChangeSetIT,McpContextMemoryVisibilityIT,EntityLifecycleStagesIT' -DdatabaseType=postgres -DdatabaseImage=postgres:15 -DsearchType=elasticsearch -DsearchImage=docker.elastic.co/elasticsearch/elasticsearch:9.3.0 (fixed JUnit parallelism of 4, maximum pool size 8).
  • Files: openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/{ContextMemoryIT,ContextMemoryAnchorIT,ContextMemoryLifecycleIT,EntityLifecycleStagesIT}.java, plus OntologyChangeSetIT.java and mcp/McpContextMemoryVisibilityIT.java.
  • Skips cover unsupported inherited entity operations/history cases. All 600 integration-test source files compile.

Ingestion integration tests

  • Not applicable: no tracked ingestion or connector changes.
  • Regenerated Python models and smoke-tested serialization of new/legacy memory values, rejection of memory In Review, and exclusion of memory-only retirement values from the shared enum.

Playwright (UI) tests

  • Updated openmetadata-ui/src/main/resources/ui/playwright/e2e/Features/ContextCenterMemoryLifecycle.spec.ts.

Focused lifecycle run: 4 passed, 0 failed, 0 skipped, 0 retries on 8fe51588022, using Chromium, the current Vite UI, and an isolated PostgreSQL/Elasticsearch-backed server. A separate browser capture scenario also passed and produced the recording below.

The branch-wide make playwright_affected plan selects 414 specs, including broad shared infrastructure and generated-model impacts. That full selection was not run locally. The focused memory spec was run through make playwright_affected_run with a local config; the wrapper could not write its results block because the overridden JSON reporter emitted to stdout. The actual browser result is four passes. Full mapped-suite verification remains outstanding for the merge queue.

Manual testing performed

Inspected the browser captures after the automated flows. Reproduction steps:

  1. Sign in as admin and open Context Center → Memories.
  2. Create approved memories for the original, replacement, and invalidated guidance. PATCH the original to Superseded with supersededBy and a reason, and the invalidated guidance to Invalidated with a reason.
  3. Add Superseded/Invalidated to the status filter and combine it with text search, Created by me, and Most Used sorting.
  4. Open both retired memories: verify the status/reason and absence of proposal actions. Follow the superseded memory's successor link and verify its Approved status.
  5. Confirm Unprocessed memories appear by default and also cannot propose ontology terms.

Static checks and known limitations

  • Schema/model regeneration, Java Spotless, changed-file organize-imports/ESLint/Prettier, UI licenses, locale synchronization, app-doc generation, Playwright lint, and impact-map verification passed. The latest commit passed all applicable pre-commit hooks.
  • Earlier full UI/Playwright typechecks reproduced main-branch baseline failures (571 UI and 137 Playwright diagnostics in that comparison); they are not presented as clean checks. The global CSS token audit reports 88 errors and 47 warnings in files identical to current main. No CSS/LESS changes are included in this PR.
  • CI is still running; readiness for review does not claim the full merge-queue suite has passed.

UI screen recording / screenshots:

The recording is stored on a separate branch for review artifacts and embedded below; it adds no binary file to this PR's code diff.

Memory lifecycle recording: status filtering, retirement reasons, and successor navigation

Superseded memory: retirement reason and successor

Invalidated memory: retirement reason

Checklist:

  • I have read CONTRIBUTING.md.
  • My PR title is Fixes <issue-number>: <short explanation>.
  • My PR is linked to a GitHub issue via Fixes #34394 above.
  • Hard-to-understand status adapter boundaries and lifecycle constraints have explanatory comments.
  • For JSON Schema changes: regeneration and the reason no database migration is needed are documented above.
  • For UI changes: the screen recording and screenshots are attached above.
  • I have added tests and listed their actual results and limitations above.
  • I have added the Backward-Incompatible-Change label.
  • N/A: connector documentation and ingestion integration tests.

pmbrull and others added 6 commits October 6, 2026 08:22
New memories must await processing before they ground agent responses.
Keep approved edits trusted until explicitly requeued.

BREAKING CHANGE: memory creation without entityStatus starts Unprocessed
instead of Approved. Trusted producers can still set Approved explicitly.
Existing statuses and PUT requests that omit the stage are preserved.

Fixes #34710
Match the overview to the Memories page default status filter.
Approve cited fixtures and keep higher-use pending memories excluded.
Seed and clean dashboard fixtures so navigation works independently.
@github-actions github-actions Bot added Ingestion safe to test Add this label to run secure Github workflows on PRs labels Oct 6, 2026
Give memories their own generated enum and validate lifecycle policies
against their schemas. Resolve discovery, filters and workflow writes
using the target entity vocabulary.

BREAKING CHANGE: EntityInterface requires a status enum type parameter.
Regenerate Java clients and parameterize custom implementations.
@pmbrull pmbrull changed the title Fixes #34394: Add Superseded and Invalidated memory statuses Fixes #34394: Isolate context memory lifecycle statuses Oct 6, 2026
@gitar-bot

gitar-bot Bot commented Oct 7, 2026

Copy link
Copy Markdown
Code Review 👍 Approved with suggestions 0 closed / 1 findings

🔴 High risk · The generic status contract breaks Java clients while changing memory lifecycle behavior.

Isolates context memory lifecycle to a separate ContextMemoryStatus vocabulary with Superseded and Invalidated states, while preserving EntityStatus for general entities. Comprehensive test coverage across unit, integration, and Playwright tests demonstrates correct policy enforcement, discovery scoping, and UI behavior. Consider memoising lifecycle discovery requests in the status autocomplete to avoid re-fetching on every keystroke.

💡 Performance: Status autocomplete re-fetches lifecycle discovery on every keystroke

📄 openmetadata-ui/src/main/resources/ui/src/utils/governance/lifecycle/LifecycleStatus.utils.ts:58-72 📄 openmetadata-ui/src/main/resources/ui/src/utils/AdvancedSearchClassBase.ts:1079-1081 📄 openmetadata-ui/src/main/resources/ui/src/utils/JSONLogicSearchClassBase.ts:705-711

lifecycleStatusAutocomplete calls fetchLifecycleStatuses → GET /metadata/types/lifecycleStages on every asyncFetch call. Both search builders now set useAsyncSearch: true, so the query builder calls asyncFetch again each time the user types in the status select or opens it. The vocabulary for a fixed set of entity types doesn't change during a session, so each keystroke sends a request whose response is the same, and filtering is already done on the client. Fetch it once per closure, memoising the promise and dropping it on rejection so a failed load can be retried, then filter locally.

Memoise the discovery promise per autocomplete instance and drop it if it fails
export const lifecycleStatusAutocomplete = (
  entityTypes: readonly string[]
): NonNullable<SelectFieldSettings['asyncFetch']> => {
  let statuses: Promise<string[]> | undefined;

  return async (search) => {
    statuses ??= fetchLifecycleStatuses(entityTypes).catch((error) => {
      statuses = undefined;
      throw error;
    });
    const query = (
      Array.isArray(search) ? search.join(',') : search ?? ''
    ).toLowerCase();

    return {
      values: (await statuses)
        .filter((status) => status.toLowerCase().includes(query))
        .map((status) => ({ value: status, title: status })),
      hasMore: false,
    };
  };
};
🤖 Prompt for agents
Code Review: Isolates context memory lifecycle to a separate `ContextMemoryStatus` vocabulary with `Superseded` and `Invalidated` states, while preserving `EntityStatus` for general entities. Comprehensive test coverage across unit, integration, and Playwright tests demonstrates correct policy enforcement, discovery scoping, and UI behavior. Consider memoising lifecycle discovery requests in the status autocomplete to avoid re-fetching on every keystroke.

1. 💡 Performance: Status autocomplete re-fetches lifecycle discovery on every keystroke
   Files: openmetadata-ui/src/main/resources/ui/src/utils/governance/lifecycle/LifecycleStatus.utils.ts:58-72, openmetadata-ui/src/main/resources/ui/src/utils/AdvancedSearchClassBase.ts:1079-1081, openmetadata-ui/src/main/resources/ui/src/utils/JSONLogicSearchClassBase.ts:705-711

   `lifecycleStatusAutocomplete` calls `fetchLifecycleStatuses` → `GET /metadata/types/lifecycleStages` on every `asyncFetch` call. Both search builders now set `useAsyncSearch: true`, so the query builder calls `asyncFetch` again each time the user types in the status select or opens it. The vocabulary for a fixed set of entity types doesn't change during a session, so each keystroke sends a request whose response is the same, and filtering is already done on the client. Fetch it once per closure, memoising the promise and dropping it on rejection so a failed load can be retried, then filter locally.

   Fix (Memoise the discovery promise per autocomplete instance and drop it if it fails):
   export const lifecycleStatusAutocomplete = (
     entityTypes: readonly string[]
   ): NonNullable<SelectFieldSettings['asyncFetch']> => {
     let statuses: Promise<string[]> | undefined;
   
     return async (search) => {
       statuses ??= fetchLifecycleStatuses(entityTypes).catch((error) => {
         statuses = undefined;
         throw error;
       });
       const query = (
         Array.isArray(search) ? search.join(',') : search ?? ''
       ).toLowerCase();
   
       return {
         values: (await statuses)
           .filter((status) => status.toLowerCase().includes(query))
           .map((status) => ({ value: status, title: status })),
         hasMore: false,
       };
     };
   };

Review coverage

📋 Rules No rules evaluated

🧪 Functional validation Not enabled · Set up

🤖 Auto-approval Not enabled · Set up

Options

Display: compact → Counting what did not apply, without listing it.

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

@pmbrull
pmbrull marked this pull request as ready for review October 7, 2026 08:54
Copilot AI balanced review requested due to automatic review settings October 7, 2026 08:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

✅ Generated Sources Auto-Updated

The generated TypeScript types (src/generated/) and dereferenced JSON
schemas (src/jsons/, public/jsons/) have been automatically updated
based on JSON schema changes in this PR.

Copilot AI balanced review requested due to automatic review settings October 7, 2026 09:00

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Jest test Coverage

UI tests summary

Lines Statements Branches Functions
Coverage: 75%
75.87% (117851/155322) 61.74% (72678/117708) 63.08% (24244/38430)

@sonarqubecloud

sonarqubecloud Bot commented Oct 7, 2026

Copy link
Copy Markdown

@pmbrull
pmbrull added this pull request to the merge queue Oct 8, 2026
Merged via the queue into main with commit 5eee26c Oct 8, 2026
122 of 126 checks passed
@pmbrull
pmbrull deleted the pmbrull/memory-retirement-statuses branch October 8, 2026 08:59
pmbrull added a commit that referenced this pull request Oct 8, 2026
Main moved ContextMemory.entityStatus to ContextMemoryStatus (#34785), so the
approved-memory check in ConceptContextBuilder no longer compiled after merging main.
@pmbrull pmbrull mentioned this pull request Oct 8, 2026
6 tasks done
timothybrush pushed a commit to timothybrush/OpenMetadata that referenced this pull request Oct 10, 2026
…ta#34863)

* feat(ai): resolve concept context bindings

Keep glossary definitions on their columns and resolve bounded concept context through REST and MCP.

Refs open-metadata#34861
Refs open-metadata/ai-platform#1586

* feat(ai): bind concepts to every data asset and report table row counts

- Glossary bindings now search the data-asset alias instead of the table
  index, excluding column, glossary term, tag and article documents, and
  resolve field-level bindings through ChildFieldResolver (data model and
  container columns, topic/API schema fields, search index fields, ML
  features, pipeline tasks).
- Metric expressions resolve SQL identifiers against any column-bearing
  asset (table, dashboard data model, container, worksheet).
- Context memories attached to a metric share its APPLIED_TO edge; they are
  no longer reported as bindings or counted in totals.
- ConceptBinding.rowCount carries the bound table's latest profiled row
  count, gated by VIEW_DATA_PROFILE like the column profile. Markdown
  renders it in a "Bound Profiles" table; counts print as integers.
- Bindings without stored samples omit sampleValues instead of returning [].
- ConceptContextIT covers non-table bindings, memory evidence vs bindings,
  nested and asset-level bindings, per-asset caps, alias/ambiguity
  resolution, related metrics, draft evidence and long-query excerpts,
  Markdown sections, MCP errors and row counts.

* fix(ai): bound concept candidate scan, match structured column paths, scope alias handling to ORDER BY

- Stop scanning concept candidates after 500 assets; mark the context truncated and
  treat totals as lower bounds. A capped metric scan resolves no columns, since
  unscanned assets could make them ambiguous.
- Compare SQL identifier components against structured field paths so a quoted
  "amount.cents" column and a nested amount.cents field stay distinct.
- Only ORDER BY resolves bare names to projection aliases; WHERE, GROUP BY and
  HAVING keep the input column binding.

* chore(playwright): auto-refresh impact-map.generated.json

* Update generated TypeScript types and dereferenced schemas

* fix(ai): use ContextMemoryStatus for concept evidence memories

Main moved ContextMemory.entityStatus to ContextMemoryStatus (open-metadata#34785), so the
approved-memory check in ConceptContextBuilder no longer compiled after merging main.

* perf(ai): resolve each column glossary term once per table context

Load and authorize each distinct column glossary term once instead of once per
column. Each column still gets its own KnowledgeItem, because the knowledge
budget trims items in place.

* fix(ai): address concept context review findings

- Mask PII.Sensitive saved-query SQL in concept evidence the same way the
  query listing does (owners and tags are now loaded for the decision).
- Keep column and nested-column glossary terms in the attached-knowledge
  batch; only the single-asset envelope is limited to asset-level terms.
- Attach stored profiles and samples to top-level columns only, so a nested
  amount.cents field no longer borrows a top-level "amount.cents" column's
  values.
- Bind columns named in JOIN ... ON predicates.

* fix(ai): match concept tags by filter, not query text

A glossary term's context found its tagged assets with the query
`** AND (tags.tagFQN:"<fqn>")` on the data-asset alias. The data-asset
query builder also runs that text through a multi_match over every
search field, so a long FQN overflowed OpenSearch's 1024-clause limit:
20 of 24 shards failed and the context returned 500
(GlossaryTermResourceIT.get_entityAiContext_200_OK in the
postgres-opensearch merge-queue lane; Elasticsearch allows more clauses).

Match the tag with a term filter under a match-all query, so the clause
count no longer depends on the FQN. tagSearchRequest now takes the
entity types to exclude, so Mode B's glossary routing gets the same fix.

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
sonika-shah added a commit that referenced this pull request Oct 11, 2026
Main now builds the generic list and count conditions through
ListFilter.getConditionForEntity(table) (#34785). Use the same entry point in the
task search overrides so their page and the count can't drift apart.
Chronillogical-Potato pushed a commit to Chronillogical-Potato/OpenMetadata that referenced this pull request Oct 12, 2026
…ty (open-metadata#34819)

* feat(api): search tasks about an entity and filter mentions by entity

The entity Activity feed lists the tasks about one entity through GET
/v1/tasks?aboutEntity=…, which had no search, and its Mentions view needs
the mentions about that entity only.

- GET /v1/tasks takes `q`, the same task search the scoped task lists use
  (name, displayName, payload reason, about displayName / FQN). The five
  `q` parameters share one description constant.
- GET /v1/activity/mentions takes an optional `entityLink`; it matches the
  entity the way /v1/activity/about does (aboutFqnHash of the link's entity)
  and is authorized like /about. The mention subquery, domain filter and
  ordering are shared constants across the four MySQL/Postgres variants.

* feat(api): list an entity's field conversations with includeFields

* fix(api): an empty mentions entityLink means none; cover its authorization

* perf(tasks): filter before sorting when a task list has a free-text search

A free-text `q` can't narrow rows through an index, so the name-ordered page walked
task_entity_name_index and checked every task until it filled a page. With `q`, the
task list now selects rows through the other filters (e.g. aboutEntity) and sorts only
those: MySQL ignores the name index, Postgres materializes the matches first.

Postgres also gets a text_pattern_ops index on task_entity.aboutfqnhash: the plain btree
can't serve the aboutEntity `LIKE 'hash.%'` prefix under a non-C collation, so every
aboutEntity list and count seq-scanned the table.

EXPLAIN ANALYZE on 1M tasks (page query, old -> new):
- MySQL, service-level aboutEntity + q: ~27s -> ~0.3s; one table + q: ~1ms -> <0.1ms
- Postgres, one table + q: ~900ms -> 0.2ms; service + q: ~380ms -> ~110ms
- q with no other filter: ~25s/12s -> one full pass (~7s/2s); no index can serve it

* fix(tasks): build the search page's condition with getConditionForEntity

Main now builds the generic list and count conditions through
ListFilter.getConditionForEntity(table) (open-metadata#34785). Use the same entry point in the
task search overrides so their page and the count can't drift apart.

* style: spotless

---------

Co-authored-by: sonika-shah <58761340+sonika-shah@users.noreply.github.com>

This branch was previously deployed

1 inactive deployment
test — cfdae7fa Deployed Oct 7, 2026 by pmbrull via RDF Playwright execution #26103
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Backward-Incompatible-Change Ingestion safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add OSS memory lifecycle and Context Center status filtering

4 participants