Repository navigation
Fixes #37556: Preserve memories across document lifecycle changes - #37564
Conversation
Archiving a file saves it deleted before its cleanup hook releases the file's memories. A memory that survives because another source remains is reloaded without the archived file, so the reparent update changes nothing and skips the search write, and the raw edge deletes never reindex: the Memories page kept showing the archived file as a source. The surviving branch of releaseExtractedMemory now ends with refreshSearchDocument, which dispatches a reference update so the search handler reindexes the memory from the database after commit. It runs after the edge deletes, since a caller outside a transaction dispatches at once.
Archiving a file used to hard-delete every memory only it stated and drop its links to the shared ones, so restoring it could bring nothing back. The soft-delete hook now archives instead: a memory no other live source states is soft-deleted with all its links kept, and a shared one stays live, keeps the archived file's links, and moves its anchor off it when it was the anchor. chooseAnchor prefers a live org-wide source, the current anchor first, so a restricted copy does not hide the memory from the other copies' readers. A permanent delete releases the links as before, and the release path now reads archived memories and sources too. An update would restore an archived memory, so its anchor moves by its edges alone, and a memory that only archived sources still state, including one re-extraction drops from its last live file, is archived rather than deleted. hasOtherSources counts archived sources for the same reason. Pages have no deleted field, so an article is always deleted permanently; its soft hook mirrors the file one.
The archive and release policy, the anchor ranking and the edge-only re-anchor were business logic in a repository past 1,400 lines. They now live in MemorySourceLifecycle, which uses the repository for data access and is what restore and sharing changes extend next. The file and page hooks call it directly; the repository keeps only the two delegates the reconciler calls, plus refreshSearchDocument. Behaviour is unchanged. The source-link unit tests move with the code, and the shared-file IT now pins that archiving the anchor keeps its MENTIONED_IN link, which restoring it relies on.
Restoring an archived file brought nothing back: its memories stayed in the Archive, and the shared ones it states kept hiding it as a source. The file's restore hook now has MemorySourceLifecycle undo the archive. A memory the file took to the Archive comes back through restoreEntity, with the same id, status, edits, usage and review state, and nothing is re-extracted. A shared memory that stayed live shows the file as a source again. Each one gets a fresh search document. A folder restore runs the same hook for each of its files. A person's own soft delete looked the same as the archive's, so the lifecycle now marks each memory it archives with an entity_extension row, contextMemory.archivedWithSources, written right after its delete. The memory's postDelete and postRestore hooks clear it. A memory a person deleted, or restored and deleted again, therefore stays deleted. The restored file takes the anchor back only from a source that is not org-wide, when the file is org-wide itself and had been the anchor. Archiving took its anchor edge without making it a related source, so a related file never takes the anchor. An anchor left on an archived copy moves to a live source. That edge is dropped explicitly, because after an edge-only move the stored anchor names another file. linkExtractedMemory moves into MemorySourceLifecycle unchanged, and restore reuses its related-source step.
A restored org-wide file now takes the anchor from any file that only some people may read, whether it had been the anchor or only related. Before, it took the anchor only from a file it had held it on. So when an org-wide copy and then the anchor were archived, the anchor stayed on a private copy after the copy came back, and the copy's readers lost the memory. An article or an asset anchor still never moves. Anchor moves made by MemorySourceLifecycle no longer advance a memory's content clock. They change who may read the memory, not what it says. Each source-link update the lifecycle makes now runs while a thread-local names the memory, and contentChanged skips that move. A review detected before an archive and restore can therefore still be decided after them. A person's own anchor edit still counts. The restore now decides on the memory as last committed. It locks the memory row and then reads the mark for update, so a delete clearing the mark, or a second copy being restored, waits for it. The locks hold only inside the restore's transaction, so the restore refuses to run without one.
Inside the write that turns a file from org-wide to restricted, every memory it states stops naming it among its related entities, and one it anchors moves to a live source everyone may read. With none left, the anchor stays and each restricted source whose readers would lose the memory gets a copy of its own, which takes that source's link, so toggling never copies twice. Opening the file again names it again, and a restricted anchor gives way to it as on restore. Archiving applies the same copy rule. Ports Group 2's MemorySourceDisclosure byte-identical (7992d4f), its shown-source reads and its guarded link write, so a restricted document never joins a memory's related entities. Lifecycle writes are now conditional on the memory as read, and record a restricted document by id and type alone.
…mories Amends the context-file memory reuse record after §4: the archive, its mark and restore, the anchor ranking, where a restricted document may be named, the sharing transitions and the copy rule, with the races and limits each keeps.
Extracted memories and their copies are named memory-<uuid>. A name is the memory's FQN and never changes, so naming it after its file showed that file's name to every reader of a copy the memory later moved to. A copy now takes extraction's defaults (its creator as owner, Entity visibility), and only a memory in use, under review or rejected is copied: Superseded and Deprecated carry a successor reference, and Invalidated and Archived are retired. When a document leaves those everyone may read, by restriction, archive or release, a restricted document a memory would then show takes the memory's copy instead. A re-extraction's release that a decision overtook now leaves the link, as the reconciler's other conditional writes do, instead of failing the run.
States the generated memory name, what a copy takes and which stages are copied, the shown-source copy, that a note citing a restricted file keeps naming it, the 412 window of the lifecycle writes under MySQL's snapshot reads, concurrent restrictions, and that indexing a copy embeds it.
A version keeps the links it was written with, and a memory's current readers read all of its versions. Once an org-wide file anchored a memory again, a version written while a private copy anchored it named that copy to everyone who could read the memory. - The version list, each version and a memory's last change name a file only to a caller who may read it now (ContextMemoryDocumentAccess). An article reads to everyone, and an admin reads every file. - A lifecycle write now withholds those names in the memory as it leaves it, not only as it was. The archive's soft delete and the memory's restore run as lifecycle writes too. - Linking a document reindexes the memory, because the link write indexed it with the names withheld.
An archive's hook runs after the file's soft delete has committed and outside any transaction. A decision written on a memory while its anchor moved failed the move with 412 midway: some memories had moved and others still named the archived file, which had already left the Documents list, so the person could not retry. The anchor move now reads the memory afresh and tries again, at most three times, as linking a document already did. Both share MemoryLinkWrites, the conditional, relinking writes a source lifecycle makes.
Restore ran neither copy rule, so it could cost readers a memory or name a restricted document to them: - A file shared with the private copy's owner and a colleague lost the anchor to that copy on archive and never took it back on restore, so the colleague kept getting 403. - A restricted document restored beside a still-archived org-wide one became the lone document an asset-anchored memory showed to the asset's readers. A restricted anchor now gives way to the restored document when everyone may read it, or when every reader of the anchor reads it too; otherwise the restored document gets a copy. The shown-source rule runs after it. The shown-source copy could also leave a memory linked only to archived documents on archive, or to none at all on release. Archive, release and restore now re-decide the memory's fate after the copies: one only archived documents state is archived with its mark, and one no document states is deleted.
A decision read the disputed memories as live only, so one archived with its document counted as gone: approving the review skipped it, and restoring the document brought it back Approved beside the memory that contradicts it. The decision now reads archived memories too and, while one it disputes is in the Archive, refuses with 409 and a message to restore the memory's document first. A permanently deleted disputed memory still counts as gone.
…action IT Against a real database and search index: - No version of a memory names a private copy to a reader it is hidden from once an org-wide file anchors the memory again. An admin still reads it, and no lifecycle change names it. - Restoring a file shared with the private copy's readers takes the anchor back, so a colleague reads the memory again. - Archiving an org-wide anchor anchors the memory on one private copy and leaves the other copy's reader a copy of their own. - Archiving what a table-anchored memory shows leaves the restricted document a copy and archives the memory until that document returns. - A conflict review refuses with 409 while the memory it disputes is archived, and supersedes it once its document is restored.
…endment The inline "§4 amended" block moves to the record's Amendment section, as the decision-records format asks, and now states: - history names a file only to a caller who may read it now, so the old "history written while a file was org-wide still names it" limit goes; - restore re-applies both copy rules and hands the anchor to a restored document every reader of the anchor reads; - a memory the shown-source copies leave with only archived documents is archived, and one they leave with none is deleted; - a conflict review waits with 409 while a memory it disputes is archived; - the archive's moves retry on a fresh read, while restore and a share change still fail with 412 inside their transaction; - the reuse-versus-restriction race, how Collate's reconciliation reviews an Unprocessed copy, that restore names a file again only when everyone may read it, and that only internal callers skip the Archive. CompanyContextTool now says that 2.1 pre-releases, not "before 2.1", named memories after their file: 2.0 has no extractor.
The archived-dispute check refused for any soft-deleted disputed memory. A memory a person deletes from its dialog is soft-deleted with no archive mark, and no document restore brings an unmarked memory back, so approving and rejecting its review both kept answering "restore its document". Only a disputed memory archived with its document, which carries the mark, now holds the decision with 409. One a person deleted is gone, as a permanently deleted one is, and the decision goes on without it.
A memory anchored on a table whose only document is a private file came back on the file's restore, the file took its copy, and the fate check found no document left and hard-deleted the memory it had just restored, losing its id, versions, disputes and open review. A restore, like an archive, never deletes: the memory waits in the Archive when only archived documents still state it, and otherwise stays live where it is anchored, with no document link. Only a release deletes a memory no document states any more.
The inherited GET /v1/contextCenter/memories/history returned stored snapshots unredacted. A change stored with a restricted file named in full, from a person's link edit or an admin's edit consolidated with a lifecycle move, reached the memory's later readers there. ContextMemoryResource now overrides snapshotRedaction with the document redaction, so the version list, one version and the history all redact the same way, and the explicit calls in the version endpoints go.
The reuse record's v3 amendment now says that a review waits only for a disputed memory archived with its document, that a restore or an archive never deletes a memory its copies leave with no document, and that every history read, the /history endpoint included, is redacted. It also notes that a memory anchored on an asset whose documents all turn restricted stays live on the asset with no document link, and that an archived memory keeps the id and type its archive wrote for a restricted link until it is restored.
|
Local Java test run: PASSED — details
Tests run locally
Per-class counts come from the test reports, which can credit a test to the wrong class when classes run concurrently, and keep only the last run of a nested class that several test classes inherit. The summary's step totals are Maven's own counts. Broader coverage not executed by this focused run
Why these tests
Impacted, not run locally (18)
Commandsmvn -B package -pl openmetadata-mcp,openmetadata-service -am -Dspring-boot.repackage.skip=true -Dtest=CompanyContextToolTest,ContextFileRepositoryTest,ContextMemoryBodyTextContributorTest,ContextMemoryDocumentAccessTest,ContextMemoryExtractorTest,ContextMemoryIndexTest,ContextMemoryReconcilerTest,ContextMemoryRepositoryTest,ContextMemoryResourceTest,ContextMemoryVisibilityTest,ElasticSearchEntityManagerUpdateEntityTest,GetEntityToolTest,KnowledgePageRepositoryTest,MemoryConflictResolutionTest,MemorySourceLifecycleTest,OpenSearchEntityManagerUpdateEntityTest,SearchRepositoryBehaviorTest,SearchRepositoryTest,SourceReadersTest,VectorDocBuilderTest,VectorEmbeddingHandlerTest -Dsurefire.failIfNoSpecifiedTests=false
mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=parallel -Dit.test=ContextFileIT,ContextMemoryConflictReviewIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=global-state -Dit.test=ContextMemoryExtractionIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false |
manerow
left a comment
There was a problem hiding this comment.
The lifecycle split and the redaction across REST, MCP, versions and history read well, and the tests are thorough. Requesting changes for one gap in the restricted-file guarantee, plus two robustness points inline. The first two continue Greptile's threads, which have no reply yet.
Keep source file labels out of vector text and clear old entity and chunk vectors before rebuilding a reference refresh. Lock and reread a memory while creating its source copy and moving the link, so a concurrent review cannot republish a retired claim. Archive each memory and its marker in a transaction. Continue through other memories after a failed move, and keep another document's live children independent of a source archive.
Remove legacy memory vectors through ordinary indexing even when the embedding handler could not initialize. Keep current embeddings for other entity types during reference refreshes. Keep a source restore from reviving another document's deleted child. Cover both search engines' removal instructions, a disabled handler, and child deletion alongside the archive and restore cases.
manerow
left a comment
There was a problem hiding this comment.
Thanks, the three points from my last review are fixed. One note on SearchRepository below.
Unconditional index cleanup discarded valid vectors before fingerprint reuse. Limit stale-vector removal to memory reference refreshes, preserve current fingerprints without an initialized provider, and keep unrelated entity refreshes out of synchronous embedding work.
Comments Outside DiffThese findings could not be posted inline.
|
Invalidate stale vectors in the shared index-write path so ordinary PATCHes cannot serve replaced answers after a provider failure. Preserve unchanged fingerprints and keep provider work asynchronous on edits.
Code Review ✅ Approved 🔴 High risk 1 closed / 1 findingsChanging memory lifecycle and file-sharing access could expose private document references or incorrectly archive or delete shared memories. Preserves shared memories and their source links through document archive, restore, deletion, and sharing changes, with search and vector references kept consistent with file access. Every memory index write that previously stripped its live embedding, forcing a re-embed, has been resolved. No open issues found. ✅ 1 closed✅ Performance: Every memory index write strips its live embedding, forcing a re-embed
VerificationRules No rules evaluated Functional validation Not enabledAuto-approval Not enabledFor more verification details, comment OptionsDisplay: compact → Showing compact verification results. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source |
Describe your changes
Fixes #37556
Preserve shared memories and their source links when documents are archived, restored, permanently deleted, or made private. Restoring a document brings back the memories archived with it and retains their review state and usage. Sharing changes keep current REST, MCP, historical, and search references consistent with file access.
Type of change
High-level design
MemorySourceLifecycleowns archive, restore, release, anchor selection, and source-specific copies. Each memory's archive andArchivedWithSourcesmark commit together, and a failed move is reported after the remaining memories are attempted. Source archive and restore leave other documents' child memories in their own live or deleted states.MemoryLinkWritesperforms conditional link updates and bounded fresh-read retries.MemorySourceSharingapplies the file's committed sharing state and refreshes all three kinds of dependent memory references after commit.SourceReaderscompares the readers of restricted files. A copy keeps the fact for its document's readers and starts with extraction's ownership and visibility defaults. Existing review and usage history stays on the original memory.ContextMemoryDocumentAccessredacts unreadable file labels in current REST and MCP responses and historical reads. The search index stores id/type references for restricted files. Vector text contains memory content without source-file labels. Every memory index write invalidates stale vector fields by fingerprint and preserves unchanged vectors without a provider call. Ordinary PATCHes regenerate embeddings through the asynchronous lifecycle handler; reference refreshes explicitly regenerate afterward. Cleanup also runs without an initialized embedding handler. Other entity types keep their existing refresh behavior. A sharing change also refreshes archived memories while preserving their deleted state.contextMemoryafter upgrading to refresh older source metadata. Existing pre-release names remain as recorded in the decision record.The decision is recorded through the append-only v7 amendment of ADR:2026-09-29-context-file-memory-reuse. This builds on merged #37453. The related Extract/Retry and shutdown PRs are #37479 and #37455. Collate's provider change is open-metadata/openmetadata-collate#8444.
Tests
Use cases covered
deleted=true.Unit tests
The focused run and its exact counts are recorded below.
MemoryCopyandMemoryLinkWritesare covered throughMemorySourceLifecycleTest, including copy contents, conditional writes, and retry cases. Changed-class coverage percentages have not been measured.Independent self-review at
60b6cd5636c2found no unanswered Important findings. Regressions reproduced the vector-label disclosure, stale approved copy, early archive-loop exit, unconditional vector clearing, table refresh scope, and ordinary-write invalidation gap before the fixes. Integration cases cover child restore state, legacy vector cleanup, current-vector preservation, and removal of replaced answers while embedding is unavailable. Ordinary index writes make no provider calls.Spotless,
git diff --check, decision-record validation, and Java impact ownership passed.Backend integration tests
Local Java test run: PASSED
60b6cd5636c2(baseorigin/main)--scope full).The focused integration run uses MySQL 8.3 and Elasticsearch 9.3. Broader affected coverage, including the PostgreSQL/OpenSearch and nightly lanes, remains pending for merge readiness.
Ingestion integration tests
Not applicable for this Java backend change.
Playwright tests
Not applicable for this backend change. API and search behavior is exercised by the integration tests above.
Manual testing performed
The local integration harness exercised real HTTP calls and search requests as admin and the memory owner. A separate interactive walkthrough remains pending.
UI screen recording
Not applicable for this backend change.
Checklist
REVIEW.md.

Confidence Score: 5/5
The reviewed changes appear safe to merge; no new blocking issue was established.Summary
This PR preserves memories and their source links through document archive, restore, deletion, and sharing changes.
No new actionable findings were established. The earlier file-label, retired-copy, and unchanged-vector findings are addressed in the current code. The earlier ordinary-edit finding is also addressed by the shared cleanup path. All supplied threads were unnumbered, so none require a numbered previous-finding entry.
Tests were inspected, not run during this review. The PR reports that broader affected coverage remains pending.
Diagram
%%{init: {'theme': 'neutral'}}%% flowchart TD A[Memory edit or reference refresh] --> B[Write memory search document] B --> C{Stored vector fingerprint matches?} C -->|Yes| D[Keep current vectors] C -->|No| E[Remove stale vector fields] E --> F{Embedding handler initialized?} F -->|Yes| G[Remove stale chunks] D --> H[Regenerate vectors when needed] G --> H F -->|No| I[Leave stale fields removed]Reviews (4) · Last reviewed commit: "fix(memory): invalidate replaced answer ..." · Reviewed by Greptile