Skip to content

feat(context): restore memory extraction from files and articles behind an AiProvider seam - #32524

Merged
pmbrull merged 18 commits into
mainfrom
pmbrull/yamoussoukro
Sep 9, 2026
Merged

pmbrull merged 18 commits into
mainfrom
pmbrull/yamoussoukro

Conversation

@pmbrull

@pmbrull pmbrull commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

Describe your changes:

Fixes #32523

Re-lands the Context Center knowledge-pill extraction pipeline that #30041 reverted — uploaded files and Knowledge Center articles are turned into ContextMemory pills again — without the Memory Agent, AISettings, or MCP Chat, and this time behind the pluggable engine seam that was the point of the closed #29360.

  • The seam: AiProvider → DocumentMemoryExtractor, resolved once by AiProviderHolder from llmConfiguration.aiProviderClass. Unset → the built-in LlmAiProvider (one structured completion per chunk via the shared LLMCompletionClient, so every supported provider — OpenAI/Azure, Bedrock, Google, Anthropic — works out of the box). Collate sets the class name to substitute an agent-platform engine with zero OSS changes: its implementation invokes a seeded dynamic agent on the AI platform (default graph, no skills, bot identity — the same pattern as the landing-page recommended actions), and this seam's KnowledgePill deserialization is the structural gate on whatever comes back. Resolution hardening reviewers asked for on feat(ai): pluggable AiProvider seam for memory & ontology derivation #29360 is in: a configured class that exists but does not implement AiProvider falls back cleanly (asSubclass + ClassCastException catch) instead of crashing the service, pinned by a regression test.
  • The pipeline: restored ContextProcessingEngine (hash gate — unchanged content never calls the LLM; a failed run never stamps the success hash), FileContextProcessingEngine, PageContextProcessingEngine (5-min trailing-throttle debounce for autosaves), ContextMemoryExtractor (paragraph-aligned chunking, 60K chars × 8 chunks cap), and ContextMemoryReconciler (match by normalized question; keep/update/retire — preserves pill identity, usage telemetry and embeddings; human-edited pills flip to Manual and are never touched).
  • Hardened base: the file pipeline is rebuilt on the conditional-update service from Fixed context center bugs #31118 (retry/backoff, contention requeue, RequestEntityCache hygiene), renamed back to ContextFileProcessingService, with the LLM stage riding the same conditional updates. FileContextProcessingEngine now only treats EntityNotFoundException as file-gone; infrastructure failures propagate to a Failed status instead of silently marking the file Processed.
  • Not restored: drive/memory/* (Memory Agent), AISettings (the gate is llmConfiguration.enabled alone), DERIVED_FROM projections, MCP Chat. Ontology derivation returns later through Ontology Studio change sets, per the memory & ontology plan (open-metadata/ai-platform#1107 / Fields for creating service used by Redash #523).
  • Schema/config: additive llmConfiguration.aiProviderClass + LLM_AI_PROVIDER_CLASS in conf/openmetadata.yaml; ES mappings re-add sourceFile (additive; the index-time visibility-enforcement fields are untouched). No DB migration — the entity fields were frozen by the revert and are re-activated code-only. Generated TS for llmConfiguration rides the type-generation workflow.

Type of change:

  • New feature

High-level design:

upload/save ─► ContextFileProcessingService ─► text extraction (Analyzing)
                    │                                 │
KnowledgePage hook ─► PageContextProcessingEngine ◄───┘ (ExtractingContext)
                    │
             ContextProcessingEngine.runExtraction(id)
                    │ hash gate (sourceHash)
             AiProviderHolder.get().documentExtractor()   ◄── llmConfiguration.aiProviderClass
              /                          \
   LlmAiProvider (OSS)          Collate impl → CAIP MEMORY_EXTRACTION agent
              \                          /
        candidates: [{title, question, answer, summary, memoryType}]  ← pinned boundary
                    │
             ContextMemoryReconciler (keep/update/retire by question)
                    │
             ContextMemory pills (sourceType=File/PageExtraction, sourceEntity link,
             extractionStats stamped only on success)

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR is adequately covered with tests: 42 unit tests across ContextFileProcessingServiceTest (status machine incl. LLM stage, contention, recovery), PageContextProcessingEngineTest (throttle, hash gate, blank-body retire), ContextMemoryExtractorTest (chunking, dedup, validation), ContextMemoryReconcilerTest (keep/update/retire, Manual pills), AiProviderHolderTest (fallbacks incl. the ClassCastException regression) — all green locally, plus mvn -pl openmetadata-service,openmetadata-spec spotless:apply.

…nd an AiProvider seam

Re-lands the Context Center knowledge-pill extraction pipeline (engines,
reconciler, repository hooks, list filters, search-index fields) that #30041
reverted, without the Memory Agent, AISettings, or MCP Chat. Extraction now
runs behind a pluggable AiProvider seam resolved from
llmConfiguration.aiProviderClass: OSS ships LlmAiProvider (one structured
completion via the shared LLMCompletionClient, all providers supported);
Collate can substitute an agent-platform implementation without any caller
changing. The candidate shape (KnowledgePill) is the compatibility boundary
between the two engines.

Adaptations over the reverted code:
- File pipeline rebuilt on the hardened conditional-update service (#31118):
  retry/backoff, contention requeue, RequestEntityCache hygiene now cover the
  pill stage too.
- Extraction gate is llmConfiguration.enabled alone; the AISettings toggles
  are gone.
- AiProviderHolder resolves the configured class via asSubclass and falls
  back to the built-in provider on ClassCastException instead of crashing
  (review finding on #29360), pinned by a regression test.
- FileContextProcessingEngine only treats EntityNotFoundException as
  file-gone; infrastructure failures now propagate to a Failed status instead
  of silently marking the file Processed.

Co-Authored-By: Claude Fable 5 <[email protected]>
@pmbrull
pmbrull requested a review from a team as a code owner September 3, 2026 07:18
Copilot AI lite review requested due to automatic review settings September 3, 2026 07:18

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 Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

The linked issue has a description and all required Shipping project fields set. Thanks!

@github-actions github-actions Bot added Ingestion safe to test Add this label to run secure Github workflows on PRs labels Sep 3, 2026
@github-actions

github-actions Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

✅ Generated Sources Auto-Updated

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

Copilot AI review requested due to automatic review settings September 3, 2026 07:25

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.

@pmbrull

pmbrull commented Sep 3, 2026

Copy link
Copy Markdown
Member Author

Collate-side implementation of this seam: open-metadata/openmetadata-collate#6374 (draft until this merges and the submodule pin advances).

…xt becomes context/entity

The service-layer package now matches the domain language: everything Context
Center (file/article extraction engines, the AiProvider seam, KnowledgePill)
lives under context/center, and the AI entity-prompt classes move from the
context/ root into context/entity. 'drive' was the legacy storage name; the
REST surface already says contextCenter. Mechanical move — no behavior change;
all moved-package suites green (48 tests).

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI review requested due to automatic review settings September 3, 2026 08:05

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 Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Jest test Coverage

UI tests summary

Lines Statements Branches Functions
Coverage: 70%
70.42% (95146/135107) 54.97% (56339/102472) 56.32% (18785/33352)

…nd skips cross-source duplicates

Extraction previously matched derived pills to stored ones by exact normalized
question, so a model that reworded a question between runs retired the old
pill and created a new one — losing its usageCount/lastUsedAt and its
embedding for an unchanged fact. And nothing looked beyond the source being
extracted, so one policy stated in two documents produced two pills.

Reconciliation now runs three passes: exact question match, then word-overlap
similarity for rephrasings (same gate as the server's duplicate probe —
0.6*question + 0.4*answer Jaccard at 0.85), then creation, where a
best-effort search probe checks whether another source's automated pill
already states the fact. A rephrase updates in place; a cross-source
restatement is skipped and counted.

Deliberately deterministic and lexical: the precision gate is word overlap,
so vector recall could not change an outcome, only cost more. Semantic
paraphrase and contradiction detection belong to the scheduled reconciliation
pass, not to extraction time. Manual and chat-authored memories never
suppress extraction — a user's private note must not silence a document's
knowledge — and a probe failure degrades to creating the pill.

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI review requested due to automatic review settings September 3, 2026 08:25

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.

@pmbrull

pmbrull commented Sep 3, 2026

Copy link
Copy Markdown
Member Author

Pushed two follow-ups on this branch:

1. drive/ → context/center, and the AI entity-prompt classes → context/entity. The package name now matches the domain (the REST surface already said contextCenter); service/llm stays the domain-free completion layer underneath. KnowledgePill moved with its feature. Mechanical, no behavior change.

2. Reconciliation keeps pill identity across rephrasing, and skips cross-source duplicates. Matching was exact normalized question, so a reworded question retired the old pill and created a new one — losing usageCount/lastUsedAt and the embedding for an unchanged fact. Now three passes: exact match → word-overlap similarity for rephrasings (the same gate as the server's duplicate probe: 0.6*question + 0.4*answer Jaccard at 0.85) → creation, where a best-effort search probe checks whether another source's automated pill already states the fact.

Deliberately deterministic and lexical: the precision gate is word overlap, so vector recall could not change an outcome, only cost more. Manual and chat-authored memories never suppress extraction (a user's private note must not silence a document's knowledge), and a probe failure degrades to creating the pill. Semantic paraphrase/contradiction detection stays out of extraction time — it belongs to the scheduled reconciliation pass (ai-platform#1130), whose judge agent is now seeded in openmetadata-collate#6374.

Suites green: 46 tests across ContextFileProcessingServiceTest, PageContextProcessingEngineTest, ContextMemoryExtractorTest, ContextMemoryReconcilerTest (now 9, incl. rephrase-identity and cross-source-skip), AiProviderHolderTest.

…n, redundant index put

- memoryCount was populated per-entity in setFields but never in either
  repository's setFieldsInBulk, so a list asking for it got 0/null while
  GET-by-id returned the real count. Both ContextFile and Page now fill it
  from one batched MENTIONED_IN query (MemoryCountFetcher), and Page clears
  it when unrequested like ContextFile already did.
- The page extraction throttle evicted a pending page even when the incoming
  id was already tracked, so one actively-autosaved page could repeatedly
  cost unrelated pages their run. Evict only when the page is new.
- Dropped a duplicate sourceType put in ContextMemoryIndex; the field is
  already stamped, null-safely, earlier in the same doc build.

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI review requested due to automatic review settings September 3, 2026 08: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.

Copilot AI review requested due to automatic review settings September 4, 2026 09:58

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.

Rohit0301
Rohit0301 previously approved these changes Sep 7, 2026
mohityadav766
mohityadav766 previously approved these changes Sep 7, 2026
chirag-madlani
chirag-madlani previously approved these changes Sep 7, 2026
…js/no-nested-conditional

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@github-actions

github-actions Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — manual (2026-09-07T18:17:34Z)

Blocked the queue: ui-checkstyle

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 is ineligible. To be eligible to request a review, you need a paid Copilot license, or your organization must enable Copilot code review.

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 is ineligible. To be eligible to request a review, you need a paid Copilot license, or your organization must enable Copilot code review.

@gitar-bot

gitar-bot Bot commented Sep 7, 2026

Copy link
Copy Markdown
Code Review 👍 Approved with suggestions 4 resolved / 5 findings

Restores the Context Center knowledge-pill extraction pipeline behind a pluggable AiProvider seam, with built-in LLM support and hardened file processing. The pipeline handles hash-gated extraction, reconciliation with pill identity preservation, and graceful fallbacks for misconfigured engines. Consider clarifying the documentation for memoryExtractionEnabled — the flag is independent of embeddings but still requires enabled: true, and operators setting only memoryExtractionEnabled: true may expect extraction to run when it silently won't.

💡 Quality: Docs say memoryExtractionEnabled is "Independent" but code requires enabled too

📄 conf/openmetadata.yaml:615-618 📄 openmetadata-spec/src/main/resources/json/schema/configuration/llmConfiguration.json:34-38

isMemoryExtractionEnabled() returns enabled && memoryExtractionEnabled, so extraction requires BOTH switches — confirmed by the memoryExtractionNeedsBothSwitches test. However the schema description and the conf/openmetadata.yaml comment both describe the flag as "Independent of enabled", which could lead an operator to set memoryExtractionEnabled: true with enabled: false and expect extraction to run, when it silently won't. Reword the docs to clarify extraction is an additional opt-in that still requires enabled: true (i.e. independent of embeddings but not a replacement for the LLM master switch).

✅ 4 resolved
✅ Bug: memoryCount populated on GET but omitted in list queries

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/KnowledgePageRepository.java:127-135 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/KnowledgePageRepository.java:153-167
setFields() populates memoryCount via findTo(...).size() for a single-entity GET, but the overridden setFieldsInBulk() (used by list endpoints) never handles memoryCount — it only runs fetchAndSetParents/RelatedEntities/Editors/Fields, and memoryCount is not a registered field fetcher. As a result a page listing that requests fields=memoryCount silently returns it unset (0/null) while GET-by-id returns the real count, an inconsistency the UI list views will surface. Add a bulk memoryCount fetcher (batched MENTIONED_IN count keyed by page id) invoked from setFieldsInBulk, mirroring how ContextFileRepository handles it.

✅ Edge Case: Throttle reschedule can evict an unrelated pending page

📄 openmetadata-service/src/main/java/org/openmetadata/service/drive/PageContextProcessingEngine.java:98-112
schedule() always calls evictIfFull() before pending.put(). When pending is at maxPendingPages and the incoming pageId is already pending (a reschedule during an active editing session), put() replaces the entry with no net growth, yet evictIfFull() has already dropped an unrelated page's timer. At capacity, a single actively-autosaved page can therefore repeatedly evict other pages that were waiting to extract. Only evict when the page is not already tracked (e.g. check pending.containsKey(pageId) before evicting), so a reschedule does not cost another page its pending run.

✅ Quality: Redundant sourceType put in ContextMemoryIndex

📄 openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/ContextMemoryIndex.java:57 📄 openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/ContextMemoryIndex.java:119-121
buildSearchIndexDocInternal already stamps doc.put("sourceType", ...) at line 57 before calling applyEntityReferences. The block added at lines 119-121 writes the exact same field with the same .value(), so it is a dead, redundant put. Remove it to avoid the misleading impression that the index doc needs a second sourceType assignment.

✅ Performance: Duplicate probe issues one search per new candidate

📄 openmetadata-service/src/main/java/org/openmetadata/service/context/center/ContextMemoryReconciler.java:98-105 📄 openmetadata-service/src/main/java/org/openmetadata/service/context/center/ContextMemoryReconciler.java:167-181 📄 openmetadata-service/src/main/java/org/openmetadata/service/context/center/SearchMemoryDuplicateProbe.java:31-45
duplicateElsewhere is called once for every genuinely-new candidate in Pass 3, and each call performs a synchronous SearchRepository.search round-trip. A document that yields many new pills therefore fans out into N sequential search queries per extraction run. This is best-effort background work so it is not critical, but consider batching the probe queries or bounding candidate count if extraction latency becomes a concern.

🤖 Prompt for agents
Code Review: Restores the Context Center knowledge-pill extraction pipeline behind a pluggable `AiProvider` seam, with built-in LLM support and hardened file processing. The pipeline handles hash-gated extraction, reconciliation with pill identity preservation, and graceful fallbacks for misconfigured engines. Consider clarifying the documentation for `memoryExtractionEnabled` — the flag is independent of embeddings but still requires `enabled: true`, and operators setting only `memoryExtractionEnabled: true` may expect extraction to run when it silently won't.

1. 💡 Quality: Docs say memoryExtractionEnabled is "Independent" but code requires enabled too
   Files: conf/openmetadata.yaml:615-618, openmetadata-spec/src/main/resources/json/schema/configuration/llmConfiguration.json:34-38

   `isMemoryExtractionEnabled()` returns `enabled && memoryExtractionEnabled`, so extraction requires BOTH switches — confirmed by the `memoryExtractionNeedsBothSwitches` test. However the schema description and the `conf/openmetadata.yaml` comment both describe the flag as "Independent of `enabled`", which could lead an operator to set `memoryExtractionEnabled: true` with `enabled: false` and expect extraction to run, when it silently won't. Reword the docs to clarify extraction is an additional opt-in that still requires `enabled: true` (i.e. independent of embeddings but not a replacement for the LLM master switch).

Options

Display: compact → Showing less information.

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

Compact
gitar display:verbose         

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

@github-actions

github-actions Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

⚠️ UI Checkstyle passed — lint findings in changed files

🔍 ESLint findings in this PR's files — 0 error(s), 3 warning(s)

Errors block the build. Warnings do not yet — they are rules whose backlog is still
being worked down, listed so this PR does not add to it. See docs/ui-code-quality-gate.md.

0 error(s), 3 warning(s) across 2 changed file(s).

Count Rule
1 openmetadata-imports/no-circular-imports
1 openmetadata-imports/no-rest-ui-imports
1 openmetadata-imports/no-internal-barrel-imports
All findings
Location Rule Message
🟡 src/interface/knowledge-center.interface.ts:14:1 openmetadata-imports/no-circular-imports This runtime import participates in a circular dependency. Extract the shared type/constant/utility or invert the dependency.
🟡 src/rest/contextMemoryAPI.ts:15:1 openmetadata-imports/no-rest-ui-imports REST clients must not import UI or state-layer modules. Move shared request/response types to the interface layer.
🟡 src/rest/contextMemoryAPI.ts:19:1 openmetadata-imports/no-internal-barrel-imports Import the internal module directly instead of its index barrel so unrelated siblings do not enter the bundle graph.

Fix locally (fast - only checks files changed in this branch):

make ui-checkstyle-changed

@sonarqubecloud

sonarqubecloud Bot commented Sep 7, 2026

Copy link
Copy Markdown

@sonarqubecloud

sonarqubecloud Bot commented Sep 7, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — failed_checks (2026-09-08T13:23:03Z)

Blocked the queue: playwright-summary

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.

Restore Context Center memory extraction (files + articles) behind a pluggable AiProvider seam

5 participants