Skip to content

Fixes #34394: Add memory lifecycle and status filtering - #34647

Merged
pmbrull merged 55 commits into
open-metadata:mainfrom
pmbrull:pmbrull/memory-lifecycle-main
Oct 5, 2026
Merged

pmbrull merged 55 commits into
open-metadata:mainfrom
pmbrull:pmbrull/memory-lifecycle-main

Conversation

@pmbrull

@pmbrull pmbrull commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Describe your changes:

Fixes #34394

Adds a lifecycle to Context Center memories. A memory that was replaced or found wrong leaves search, agent context and glossary proposals, while its own page and history stay readable. This replaces #34395, which GitHub closed when its base branch was deleted after #34541 merged; this PR targets main and builds on the shared lifecycle from #34541.

Lifecycle

  • Memories use the shared EntityStatus stages: Draft, Approved (in use), Deprecated (replaced), Rejected (invalidated) and Archived. A memory created without a stage starts Approved. Allowed moves: Draft → Approved or Archived; Approved → Archived, Deprecated or Rejected; Deprecated or Rejected → Approved or Archived; Archived → Approved.
  • A Deprecated memory requires supersededBy: another memory the editor can read that is not deleted and not itself. statusReason records why a memory reached its stage. A status change without a reason of its own clears the old one, and leaving Deprecated clears the successor. PUT keeps these fields, and a PATCH that removes the stage is rejected. Direct reads and version history keep retired states.
  • disputes records memories by other owners whose claims contradict this one. A Learning memory type and a ConversationExtraction source type support conversation capture for ai-platform#523.

Access

  • An Entity or Public memory anchored to an asset is readable only by readers of that asset: on direct reads, version history and listings. A new anchored memory created without domains takes its anchor's domain when the anchor has exactly one.
  • Search cannot check an anchor's policy per document, so ordinary search omits anchored Entity and Public memories for non-owners. Owners and admins still find them.

Search and listing

  • Ordinary lexical and vector search return Approved memories only, for admins too. Memory and chunk documents carry entityStatus and anchorId.
  • GET /v1/contextCenter/memories?statuses=Approved,Deprecated lists the chosen stages and combines with q, assets, author, sort and offset. The statuses ride on SearchListFilter through the generic search listing.
  • Vector chunks are refreshed through one decision: a content change re-embeds; a status, anchor or mapping change rewrites the stored vectors without re-embedding. Live updates also rewrite an in-flight staged reindex, so promoting it cannot bring back stale chunks.

Extraction

  • Re-extracting a file or page never rewrites or re-approves a memory outside Approved. Extraction creates every memory Approved, so Draft, Archived, Deprecated and Rejected are reviewer decisions that stand.
  • Cross-file duplicate detection searches as a synthetic admin, so it finds anchored memories and does not need a user named admin. A memory is shared with another file, through deduplication or byte-identical reuse, only when its own file is readable by everyone.

Glossary proposals and agents

  • Memories outside Approved cannot start glossary proposals. An operation in a pending draft can't be applied once none of its source memories is still Approved; terms already applied keep their provenance.
  • MCP company_context returns Approved shared file memories only. get_entity_details searches passages as the caller and falls back to the full body when search returns none.
  • AI context drops retired and hidden memories before applying its 20-memory cap.

UI

  • Context Center lists Approved memories by default, with a multi-select status filter that combines with search, asset, author and sort; the count cards follow it. Rows and details show the status, the reason and a "Superseded by" link. The link appears in view mode only and keeps the page's other URL parameters. Closing details clears only the memory URL parameter, and a slow lookup cannot reopen a closed modal.
  • The proposal action is hidden for memories outside Approved. Editing a memory keeps a type the form does not offer, such as Learning. The sidebar badge counts the Approved memories the caller can see.

Type of change:

  • New feature

High-level design:

  • Lifecycle. ContextMemoryRepository declares the memory stages through the shared EntityLifecycle, so EntityRepository validates every move. ContextMemoryLifecycle adds the memory-only rules: successor and dispute references, and clearing a stale reason or successor. Status changes are never folded into an in-session version, so history keeps each one.
  • Visibility. ContextMemoryVisibility decides REST reads in memory and delegates the anchor check to ContextMemoryAnchorAccess, a policy check on the anchor with a bounded per-request cache. ContextMemorySearchVisibility and VectorSearchQueryBuilder render the same rule as search filters and add the status constraint and the conservative anchor rule.
  • Listing. The selected statuses travel on SearchListFilter to a listWithOffset overload on the search clients; the existing overload defaults to Approved. There is no memory-specific listing method in the repository or search layers.
  • Vectors. OpenSearchVectorService.chunkRefresh chooses between no change, restamping stored vectors and re-embedding, for the live, chunk-only and staged-backfill paths. Status and anchor sit outside the content fingerprint, so changing them costs no embedding calls.
  • Migration and rollout. No SQL migration: the new fields are optional, and main's 2.1.0 migration already sets Approved on every memory and stored version without a stage, so the code assumes every memory has one. Existing search indexes need a reindex: memory documents and chunks written before entityStatus and anchorId stay out of search until restamped, out of vector search even for admins. Chunk schema version 7 upgrades older chunk mappings.
  • Known CI gap. maven-collate-ci fails while Collate still imports ContextMemoryStatus, which Fixes #34540: Support a shared lifecycle stage on entities and let active workflows own it #34541 removed; that build fails on main too.
  • Out of scope, pre-existing on main. Extraction creates memories as admin with no owner, so saving one fails on deployments without a user named admin.

Tests:

Use cases covered

  • Deprecating requires a readable, live successor; leaving Deprecated clears it; reasons are kept or cleared; moves outside the lifecycle are rejected; PUT keeps the lifecycle fields.
  • Ordinary search hides memories outside Approved, admins included, while direct reads and history keep them; the status filter combines with search and author.
  • Users who cannot read a memory's anchor do not see it on reads, versions, listings or MCP.
  • Retired memories cannot start or complete glossary proposals; a draft still applies while another source memory is Approved.
  • Re-extraction leaves memories outside Approved alone, and memories of restricted files are not reused for other files.
  • UI: default and combined status filters, status and reason badges, hidden proposal action, successor navigation, modal close behaviour, memory type kept on edit, badge count.

Unit tests

  • I added unit tests for the new/changed logic.
  • Backend: ContextMemoryLifecycleTest, ContextMemoryVisibilityTest, ContextMemoryAnchorAccessTest, ContextMemoryStatusTransitionTest, ContextMemorySchemaTest, ContextMemoryIndexTest, ContextMemoryIndexMappingTest, ContextMemorySearchVisibilityTest, VectorSearchQueryBuilderTest, VectorDocBuilderChunkTest, OpenSearchVectorServiceTest, ContextMemoryReconcilerTest, SemanticMemoryDuplicateFinderTest, FileContextProcessingEngineTest, ContextFileVisibilityTest, OntologyChangePreflightTest, OntologyMemoryDerivationServiceTest, OntologyMemoryDerivationQueueTest, AIContextBuilderTest, SearchRepositoryBehaviorTest.
  • MCP: CompanyContextToolTest, GetEntityToolTest.
  • Jest: ContextCenterMemoriesPage, CreateMemoryModal and its utils, MemoriesView, MemoryDerivedOntology.utils, useContextCenterBadges.
  • Regression tests added during review were checked to fail without their fixes.
  • Coverage %: not measured.

Backend integration tests

  • I added integration tests in openmetadata-integration-tests/ for new/changed API endpoints.
  • New: ContextMemoryLifecycleIT, ContextMemoryAnchorIT. Extended: ContextMemoryIT (version access), OntologyChangeSetIT (retired, co-sourced and deleted source memories), McpContextMemoryVisibilityIT (anchored memories).

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • I added Playwright E2E tests under openmetadata-ui/.../ui/playwright/ for UI changes.
  • New: playwright/e2e/Features/ContextCenterMemoryLifecycle.spec.ts.

Results

Run locally on 2026-10-05, integration tests against PostgreSQL and Elasticsearch containers:

Check Commit Result
Backend unit tests for memories, search, vectors, ontology, AI context and the search repository c8a71173b1 536 passed
MCP unit tests c8a71173b1 82 passed
ContextMemoryIT, ContextMemoryLifecycleIT, ContextMemoryAnchorIT, OntologyChangeSetIT, McpContextMemoryVisibilityIT, AIContextRestIT, AIContextMcpIT, PersonaAIContextIT c8a71173b1 291 run, 0 failed, 26 expected capability skips
Jest, 16 Context Center and sidebar suites c8a71173b1 112 passed
Related backend unit tests after the two review fixes 0335a6a86f 153 passed
Chromium ContextCenterMemoryLifecycle.spec.ts 8466c48d5c 3 passed
Spotless, ESLint, Prettier and organize-imports; tsc adds no errors 0335a6a86f Clean

Integration tests were not re-run on the two review-fix commits, and the Playwright spec was not re-run after the later UI changes.

mvn -pl openmetadata-service,openmetadata-mcp install -DskipTests
mvn -pl openmetadata-service test '-Dtest=ContextMemory*Test,SemanticMemoryDuplicateFinderTest,OpenSearchVectorService*Test,VectorDocBuilderChunkTest,VectorSearchQueryBuilderTest,OntologyChangePreflightTest,OntologyChangeApplicationServiceTest,OntologyMemoryDerivation*Test,EntityRepositoryEntityStatusTest,RdfOntologyContractTest,ContextMemorySearchVisibilityTest,FileContextProcessingEngineTest,ContextFileVisibilityTest,AIContextBuilderTest,SearchRepositoryBehaviorTest'
mvn -pl openmetadata-mcp test '-Dtest=GetEntityToolTest,CompanyContextToolTest,SemanticSearchToolTest'
mvn -pl openmetadata-integration-tests test '-Dtest=ContextMemoryLifecycleIT,ContextMemoryAnchorIT,OntologyChangeSetIT,ContextMemoryIT,McpContextMemoryVisibilityIT,AIContextRestIT,AIContextMcpIT,PersonaAIContextIT'
# from openmetadata-ui/src/main/resources/ui
npx jest src/components/platform/ai-shell/Sidebar src/components/ContextCenter/CreateMemoryModal src/components/ContextCenter/MemoriesView src/pages/ContextCenterPage/ContextCenterMemoriesPage

Manual testing performed

  1. Ran the OSS UI on port 3000 against a local backend on 8585 and seeded Deprecated and Rejected memories through the API (at 8466c48d5c).
  2. Checked the default Approved list, combined status, asset, author and sort filters, and the reason badges.
  3. Opened a Deprecated memory, followed "Superseded by", and closed details with Cancel, Escape and Edit; the list stayed usable.
  4. Confirmed the proposal action is hidden for retired memories.
  5. Reopened the originally reported memory link and closed it.

Live semantic search was not revalidated: the local embedding model produced 384 dimensions against a 512-dimension chunk index. Vector behaviour is covered by the Java tests.

UI screen recording / screenshots:

TODO: attach a short recording of the status filter, a Deprecated memory's details and the successor link.

Checklist:

  • I have read the CONTRIBUTING document.

  • My PR title is Fixes <issue-number>: <short explanation>

  • My PR is linked to a GitHub issue via Fixes #<issue-number> above.

  • I have commented on my code, particularly in hard-to-understand areas.

  • For JSON Schema changes: I updated the migration scripts or explained why it is not needed.

  • For UI changes: I attached a screen recording and/or screenshots above.

  • I have added tests (unit / integration / Playwright as applicable) and listed them above.

  • The issue properly describes why the new feature is needed, what's the goal, and how we are building it. Any discussion or decision-making process is reflected in the issue.

  • I have updated the documentation.

  • I have added tests around the new logic.

pmbrull and others added 30 commits October 1, 2026 17:44
Entity memories about restricted assets were visible through direct REST
reads. Check ViewBasic on the anchor for non-owners.

Search still relies on domain inheritance and search RBAC; asset policies
are not evaluated per result.
The by-name Company Context lookup omitted primaryEntity, so an anchored
memory appeared unanchored to the visibility check. Fetch the decision
fields before projecting the pill.

Query search remains governed by search RBAC and inherited domains.
History endpoints exposed earlier versions without checking the current
memory's visibility. Check the current memory before serving either
history endpoint.

Keep paging cursors when hidden memories are filtered from a list page
so callers can reach later visible rows.
Map supersession and dispute fields in every search locale and request
the relationship fields needed by memory docs during reindex.

Default an omitted status to Active on create. The generated model leaves
the schema default null, which broke lifecycle reads after regeneration.
Stamp lifecycle status on chunk docs and accept it in both vector query
builders. Non-Active transitions change the fingerprint to refresh the
filter fields; existing Active memories keep their fingerprint.
Preserve server-managed lifecycle fields on PUT so re-extraction cannot
reactivate a superseded memory or erase disputes.

Reject newly referenced memories the editor cannot read, and cache
anchor access decisions within each list page.
Search cannot evaluate an anchor's asset policy for each indexed hit.
Limit anchored Entity memories to owners and admins in lexical and vector
search; direct reads still allow asset readers.

Require an explicit unanchored marker so older documents fail closed
until reindexed. Stamp the marker on entity and chunk documents.
Keep retired memories available through direct lifecycle and version reads while excluding them from lexical, vector, and Company Context retrieval.
Allow status selection alongside search, asset, author, and sort filters while keeping ordinary search Active-only.

Preserve lifecycle fields on omitted-status PUT and prevent non-Active memories from proposing glossary terms. Extend API and UI coverage for these behaviors.
Reconcile Public memory visibility and index fields after the parent PR landed. Cover retired memory behavior in Playwright and align the deleted-source glossary expectation.

Refs open-metadata#34394
…es and let active workflows own it

Every entity type whose schema declares entityStatus now gets its lifecycle
stage rules from EntityRepository instead of a schema default, so they live in
one place:

- A new entity starts in its type's stage: Draft for domains, data products,
  glossaries, articles, ontology axioms, data contracts and AI assets;
  Approved for assets that come from the data infrastructure. Metrics and
  glossary terms start Draft only when they have reviewers.
- A PUT, bulk upsert or CSV import whose request carries no stage keeps the
  stage the entity is in instead of resetting it.
- While a deployed, unsuspended governance workflow sets an entity type's
  stage, only that workflow (acting as the governance bot) may change it.
  A direct change is rejected with 403, and a create that asks for a stage the
  workflow owns starts in the type's own stage. The workflow's trigger filter
  decides which entities it owns; suspending it releases them.
- GET /v1/metadata/types/lifecycleStages lists the stages and, per entity
  type, the workflows that own its stage.
- Context memories move from their own Draft/Active/Archived status onto
  entityStatus. The 2.1.0 migration converts stored memories and their
  version history (Active becomes Approved).
- The approval-task closing, in-review delete and reviewer rules that seven
  repositories each duplicated are shared now, with per-type flags keeping
  each rule on the entity types that had it.
- A consolidated update no longer re-validates a stage change that an earlier
  version made, such as a workflow approving on the user's behalf.
- createOntologyAxiom no longer requires entityStatus, and DataProduct
  lifecycleStage is deprecated in favor of entityStatus.

BaseEntityIT checks the stage rules for every entity type; types without a
lifecycle (users, teams, test suites, ...) opt out.
The repositories' stage rules reached the active workflows through a static
EntityStatusWorkflows lookup, so no unit test could put an entity under an
owning workflow. EntityRepository now takes a StageOwnership, with the active
workflows as its default, and the create-time stage assignment and the
updater's stage check are package-private instead of being reached through
reflection.

New tests cover a create that asks for a workflow-owned stage, the workflow
creating and moving an entity in that stage, types whose stage no workflow
owns, approval and rejection by reviewers and reviewing teams, sending an
entity in review back to Draft, session consolidation, memory transitions
through the updater, and glossary terms inheriting reviewers. Line and branch
coverage of the repositories' stage code goes from 66% and 58% to 91% each.
Every type with entityStatus draws its stages from one vocabulary, but a type
can now declare its own lifecycle in its repository: the stages it uses,
including stages only it has, and the moves between them. Types that declare
none keep the general lifecycle, any move between today's seven stages, so
nothing changes for them, Metric included. A stage added to the vocabulary
later is outside the general lifecycle, so only the types that declare it can
use it.

EntityRepository rejects with 400 a create in a stage outside the type's
lifecycle and a stage change the lifecycle has no move for, for direct edits,
imports and workflows alike. Context memories are the first type to declare
one (Draft, Approved, Archived), replacing their own transition table and
validators. GET /v1/metadata/types/lifecycleStages now reports each type's
stages and transitions, and BaseEntityIT checks that every type rejects a move
outside its lifecycle.
… made dead

main's 2.1.0 postDataMigration sets entityStatus to Approved on every
context memory and version row that lacks one, and every create path
assigns the initial stage, so a memory without a stage can no longer
exist. Remove effectiveStatus and the updater's legacy branches, compare
statuses directly as main did, let the shared entityStatus index field
carry the stage, and delete the tests that built such rows by hand.
Deduplicating a fact, or reusing the memories of a byte-identical file,
links the existing memory to the new source but leaves it anchored to
its own file. Since anchors now gate reads, a memory from a private or
shared file would stay hidden from readers of the new file. Reuse only
memories whose anchor file everyone can read; the new file extracts its
own otherwise.
The status filter had its own method on the resource, repository,
search repository, search client interface, both clients and both
managers. Carry the selected statuses on SearchListFilter instead: the
resource uses the generic listInternalFromSearch, SearchRepository hands
them to a listWithOffset overload, and the existing overload defaults to
the searchable statuses.
The live, chunk-only and staged-backfill paths each repeated the check
for when a memory's chunks must be rewritten, and no test caught the
status or anchor restamp being dropped. They now share chunkRefresh,
which is tested directly.

Live updates also rewrite an in-flight staged generation, as deletes
already do, so a recreate that copied a memory before its status or
anchor changed cannot promote the stale chunks.
get_entity_details searched a knowledge item's chunks without a
subject, so restricted, anchored or retired memories the caller may read
returned no passages at all. Search as the caller, and return the full
body when search still withholds every chunk.
Retired memories stay attached to their asset, and the builder capped
the attached pills before filtering by status and visibility, so they
could push Approved pills out of the context. Load a bounded batch,
filter it, then cap; visibility is decided once for the batch. Only
Approved pills are active now that every memory carries a stage.
…rams

- The sidebar badge counted memories through the database list, which
  includes every status and other users' private memories. It now asks
  for Approved memories through search, like the page's default view.
- The successor link replaced the whole query string. It now keeps the
  Context Center's other parameters.
Copilot AI balanced review requested due to automatic review settings October 5, 2026 14:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@github-actions github-actions Bot added safe to test Add this label to run secure Github workflows on PRs and removed safe to test Add this label to run secure Github workflows on PRs labels Oct 5, 2026
Re-extraction still re-approved Archived and Draft pills. Extraction
creates every pill Approved, and no engine path archives one (a pill the
source drops is deleted), so any other stage is a reviewer's decision.
Only Approved pills are engine-managed now, which also makes the
re-approval branch in applyDerived unreachable, so it is removed.
The duplicate finder searched as the user named admin, which
deployments with other admin principals do not have, so the lookup threw
and aborted reconciliation. Search as a synthetic admin instead, as
EntityUpdater does for system writes. It carries an id, since search
treats a subject without one as anonymous and would hide every anchored
memory again.
Copilot AI balanced review requested due to automatic review settings October 5, 2026 14:33

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.

@gitar-bot

gitar-bot Bot commented Oct 5, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 2 closed / 2 findings

🔴 High risk · Memory anchor access rules now govern direct reads and search visibility

Adds memory lifecycle and status filtering using the shared EntityStatus vocabulary (Draft, Approved, Deprecated, Rejected, Archived) with validation for successor references, search visibility rules, and anchor access controls. Resolved duplicate finder failures when no literal "admin" user exists and re-extraction now correctly preserves Archived and Draft memory states instead of re-approving them. No issues remain.

✅ 2 closed
✅ Bug: Duplicate finder fails when no user is literally named "admin"

📄 openmetadata-service/src/main/java/org/openmetadata/service/context/center/SemanticMemoryDuplicateFinder.java:63-68 📄 openmetadata-service/src/main/java/org/openmetadata/service/context/center/SemanticMemoryDuplicateFinder.java:95-107
The default constructor now resolves SubjectContext.getSubjectContext(Entity.ADMIN_USER_NAME). That call loads a real User record through SubjectCache.getUserContext, and on a cache miss it falls back to Entity.getEntityByName. Elsewhere in the codebase "admin" is only used as an updatedBy label, but here the user has to exist. Deployments that set authorizerConfiguration.adminPrincipals (AUTHORIZER_ADMIN_PRINCIPALS, default [admin]) to real SSO principals have no admin user, so the lookup throws EntityNotFoundException. searchSubject.get() runs before the try/catch in candidates(), so the exception escapes findEquivalent and aborts ContextMemoryReconciler.reconcile for every file that still has unmatched derived pills. Fix: build a synthetic admin subject that doesn't depend on that user (the unit test already does this), or catch the failed lookup and fall back to a bot principal.

✅ Bug: Re-extraction still re-approves Archived (and Draft) pills

📄 openmetadata-service/src/main/java/org/openmetadata/service/context/center/ContextMemoryReconciler.java:39-40 📄 openmetadata-service/src/main/java/org/openmetadata/service/context/center/ContextMemoryReconciler.java:262-268
isEngineManaged excludes only DEPRECATED and REJECTED. A pill a reviewer moved to Archived (allowed from Approved by ContextMemoryRepository.LIFECYCLE) or to Draft still counts as engine-managed. On the next re-extraction, applyDerived sees effectiveStatus != APPROVED, treats that as a change, and calls updated.setEntityStatus(EntityStatus.APPROVED). That quietly reverses a human decision and puts the memory back into search, which is the bug this commit set out to fix for retired pills. Fix: treat only legacy-null or APPROVED pills as engine-managed, i.e. any explicit non-Approved stage counts as a human verdict.

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

@sonarqubecloud

sonarqubecloud Bot commented Oct 5, 2026

Copy link
Copy Markdown

@sonarqubecloud

sonarqubecloud Bot commented Oct 5, 2026

Copy link
Copy Markdown

This branch was previously deployed

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add OSS memory lifecycle and Context Center status filtering

4 participants