Skip to content

feat(ai): pluggable AiProvider seam for memory & ontology derivation - #29360

Closed
pmbrull wants to merge 7 commits into
mainfrom
pmbrull/ai-settings-llm-abstraction-v1
Closed

pmbrull wants to merge 7 commits into
mainfrom
pmbrull/ai-settings-llm-abstraction-v1

Conversation

@pmbrull

@pmbrull pmbrull commented Jun 23, 2026 •

Copy link
Copy Markdown
Member

Describe your changes:

Follow-up to #29201 (feature issue #29285) — refactor only, no separate tracking issue, no user-visible change.

I put the two LLM-backed AI steps added in #29201 — document → memory pills and memory → ontology verdict — behind a single pluggable AiProvider seam, so OSS keeps calling the LLM while a downstream distribution can drop in a different backend (e.g. an agent platform) with zero changes to OSS code. Selection is config-driven (same shape as pipelineServiceClientConfiguration.className): AiProviderHolder reads llmConfiguration.aiProviderClass from openmetadata.yaml and reflectively loads it, falling back to the built-in LlmAiProvider when unset/blank/absent; all three production call sites now build their deriver through it. Behavior is unchanged in OSS and guarded by existing tests.

Type of change:

  • Improvement

High-level design:

  • Contracts: extracted MemoryDeriver (ContextMemory + MemoryContext → MemoryDerivation) and DocumentMemoryExtractor (text → DeriveResult) interfaces from the existing concrete MemoryExtractor / ContextMemoryExtractor; the DeriveResult record moved onto the interface so no consumer is pinned to the LLM impl. The seam sits at the agent altitude (verdict in / out), not the LLM-token altitude — an agent backend is not a chat-completion client.
  • Provider seam: AiProvider vends both derivers; LlmAiProvider is the OSS default (builds the LLM-backed impls via LLMClientHolder); AiProviderHolder caches a single instance resolved from llmConfiguration.aiProviderClass (missing class → warn + OSS fallback, instantiation failure → error + OSS fallback), with setForTesting/reset test seams. Config-driven-FQCN pattern like pipelineServiceClientConfiguration.className; double-checked-locking idiom from the sibling PageContextProcessingEngineHolder. New schema field llmConfiguration.aiProviderClass (additive, optional) surfaced in conf/openmetadata.yaml as ${LLM_AI_PROVIDER_CLASS:-""}.
  • Rewire: MemoryProcessingEngine, ContextFileProcessingService, and PageContextProcessingEngineHolder now obtain their deriver from AiProviderHolder.get(). Post-condition: only LlmAiProvider constructs the OSS extractors.
  • Compatibility: no schema/DDL/API change; OSS behavior identical; AISettings enable/disable/prompt toggles remain live. A runtime swap of the LLM client still won't re-point already-built derivers — identical to pre-feat(ai): AISettings + Memory Agent deriving glossary terms and metrics #29201 behavior, deliberately out of scope here.
  • Alternatives rejected: swapping at the LLMCompletionClient (token) level — wrong altitude; subclassing the concrete extractors — fragile base class and forces the OSS constructor's dependencies on the alternate impl.

Tests:

Use cases covered

  • llmConfiguration.aiProviderClass unset: AiProviderHolder.get() returns LlmAiProvider; both AI steps call the LLM exactly as before.
  • aiProviderClass set to an on-classpath impl: that AiProvider drives both steps with no OSS edit. A configured-but-missing class warns and falls back to the LLM provider.
  • Injected provider for tests via setForTesting.

Unit tests

  • AiProviderHolderTest (4): OSS fallback when unconfigured, setForTesting injection, aiProviderClass resolution, configured-but-missing-class fallback.
  • Suites for the touched classes stay green: 38 tests, 0 failures, 0 errors (AiProviderHolderTest, MemoryExtractorTest, MemoryProcessingEngineTest, ContextMemoryExtractorTest, PageContextProcessingEngineTest, ContextFileProcessingServiceTest).

Backend integration tests

  • Not applicable (internal refactor; no new/changed API endpoint).

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Manual testing performed

Consolidated mvn -pl openmetadata-service test over the six touched test classes on the final commit: 37 run / 0 failed.

UI screen recording / screenshots:

Not applicable.

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: additive optional field aiProviderClass on llmConfiguration; no migration needed (generic config schema). Generated llmConfiguration.ts updated (CI's TypeScript Type Generation will normalize if needed).
  • For UI changes: not applicable (no UI changes).
  • I have added tests (unit) and listed them above.
  • I have added tests around the new logic.

🤖 Generated with Claude Code

Greptile Summary

This PR adds a configurable AI provider seam for Context Center derivation. The main changes are:

  • A new AiProvider interface with LLM-backed default implementation.
  • Lazy provider selection through llmConfiguration.aiProviderClass.
  • File, page, and memory processing rewired to use the provider seam.
  • Optional schema and generated TypeScript config updates.

Confidence Score: 4/5

This is close, but the provider fallback should be fixed before merging.

  • A configured class that exists but is not an AiProvider can still throw during lazy setup.
  • The affected path can break file, page, or memory derivation instead of falling back to the built-in provider.
  • The rest of the provider seam is a contained refactor.

openmetadata-service/src/main/java/org/openmetadata/service/drive/AiProviderHolder.java

Important Files Changed

Filename Overview
openmetadata-service/src/main/java/org/openmetadata/service/drive/AiProviderHolder.java Adds lazy provider resolution and fallback handling, but wrong-type configured classes can still escape the fallback path.
openmetadata-service/src/test/java/org/openmetadata/service/drive/AiProviderHolderTest.java Adds coverage for provider selection and missing-class fallback.

Reviews (4): Last reviewed commit: "Merge branch 'main' into pmbrull/ai-sett..." | Re-trigger Greptile

Greptile also left 1 inline comment on this PR.

Context used (3)

  • Context used - CLAUDE.md (source)
  • Context used - openmetadata-ui-core-components/CLAUDE.md (source)
  • Context used - AGENTS.md (source)

Copilot AI review requested due to automatic review settings June 23, 2026 12:12

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

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

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

  • No GitHub issue is linked. Link an issue in the Development section of the PR (or add Fixes #12345 to the description). For a same-org cross-repo issue, add Fixes open-metadata/<repo>#123 to the description.

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

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

@github-actions github-actions Bot added Ingestion safe to test Add this label to run secure Github workflows on PRs labels Jun 23, 2026
Comment on lines +57 to +59
} catch (ClassNotFoundException notOnClasspath) {
resolved = new LlmAiProvider();
} catch (ReflectiveOperationException badProvider) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 ClassCastException escapes the fallback handler

If a class named by the system property exists on the classpath but does not implement AiProvider, the (AiProvider) cast on line 55 throws a ClassCastException. That is a RuntimeException, not a ReflectiveOperationException, so neither catch block intercepts it — the exception propagates unchecked through build() → get() → every AiProviderHolder.get() call site, crashing the service at startup instead of logging the error and falling back to LlmAiProvider. The second catch block's intent ("on the classpath but could not be instantiated") clearly covers this case, so adding ClassCastException (or widening the second catch to Exception) makes the behaviour consistent with the stated contract.

Suggested change
} catch (ClassNotFoundException notOnClasspath) {
resolved = new LlmAiProvider();
} catch (ReflectiveOperationException badProvider) {
} catch (ClassNotFoundException notOnClasspath) {
resolved = new LlmAiProvider();
} catch (ClassCastException | ReflectiveOperationException badProvider) {

Replace the hardcoded DEFAULT_PROVIDER_CLASS constant and the
openmetadata.ai.provider.class system property with a config-driven seam:
AiProviderHolder reads llmConfiguration.aiProviderClass (openmetadata.yaml)
via LlmConfigHolder. Unset/blank/absent class falls back to the built-in
LlmAiProvider. Mirrors pipelineServiceClientConfiguration.className.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@pmbrull
pmbrull requested a review from a team as a code owner June 23, 2026 12:53
Comment on lines +67 to +81
private static AiProvider resolveConfigured(final String className) {
AiProvider resolved;
try {
final Class<?> clazz = Class.forName(className);
resolved = (AiProvider) clazz.getDeclaredConstructor().newInstance();
LOG.info("Using AI provider: {}", className);
} catch (ClassNotFoundException notOnClasspath) {
LOG.warn(
"Configured aiProviderClass '{}' is not on the classpath; using the built-in LLM provider",
className);
resolved = new LlmAiProvider();
} catch (ReflectiveOperationException badProvider) {
LOG.error(
"Configured aiProviderClass '{}' could not be instantiated; using the built-in LLM provider",
className,

@gitar-bot gitar-bot Bot Jun 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Bug: Misconfigured non-AiProvider class crashes startup instead of falling back

In resolveConfigured, the cast (AiProvider) clazz.getDeclaredConstructor().newInstance() (line 71) throws ClassCastException when the configured aiProviderClass names a class that exists on the classpath but does not implement AiProvider. ClassCastException is an unchecked RuntimeException, so it is caught by neither catch (ClassNotFoundException ...) nor catch (ReflectiveOperationException ...). The exception propagates out of build() (which is called lazily from get()), defeating the graceful-fallback contract now stated in the Javadoc and warn/error messages ("using the built-in LLM provider"). A distribution that wires in a wrong class name in llmConfiguration.aiProviderClass would crash the service rather than degrade to the OSS LlmAiProvider. The error-handling block around this cast is modified in this commit, so the fallback guarantee should cover this case too.

Use asSubclass for an early, descriptive failure and also catch ClassCastException so a wrong-type class falls back gracefully. Add a regression test covering a classpath class that does not implement AiProvider.:

private static AiProvider resolveConfigured(final String className) {
    AiProvider resolved;
    try {
      final Class<? extends AiProvider> clazz =
          Class.forName(className).asSubclass(AiProvider.class);
      resolved = clazz.getDeclaredConstructor().newInstance();
      LOG.info("Using AI provider: {}", className);
    } catch (ClassNotFoundException notOnClasspath) {
      LOG.warn(
          "Configured aiProviderClass '{}' is not on the classpath; using the built-in LLM provider",
          className);
      resolved = new LlmAiProvider();
    } catch (ReflectiveOperationException | ClassCastException badProvider) {
      LOG.error(
          "Configured aiProviderClass '{}' could not be instantiated; using the built-in LLM provider",
          className,
          badProvider);
      resolved = new LlmAiProvider();
    }
    return resolved;
  }

Was this helpful? React with 👍 / 👎

@github-actions

Copy link
Copy Markdown
Contributor

✅ TypeScript Types Auto-Updated

The generated TypeScript types have been automatically updated based on JSON schema changes in this PR.

Copilot AI review requested due to automatic review settings June 23, 2026 12:59
@pmbrull
pmbrull removed the request for review from Copilot June 23, 2026 12:59
@github-actions

github-actions Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Jest test Coverage

UI tests summary

Lines Statements Branches Functions
Coverage: 63%
63.78% (72754/114067) 46.92% (42362/90269) 48.22% (13029/27018)

@github-actions

github-actions Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

🟡 Playwright Results — all passed (19 flaky)

✅ 4093 passed · ❌ 0 failed · 🟡 19 flaky · ⏭️ 22 skipped

Shard Passed Failed Flaky Skipped
🟡 Shard 2 815 0 8 4
✅ Shard 3 816 0 0 12
🟡 Shard 4 820 0 1 5
✅ Shard 5 831 0 0 0
🟡 Shard 6 811 0 10 1
🟡 19 flaky test(s) (passed on retry)
  • Features/ContextCenterArticles.spec.ts › Article listing search filters, clears, and shows empty state (shard 2, 1 retry)
  • Features/ContextCenterArticles.spec.ts › Article list cards, recently viewed widget, and pagination work (shard 2, 1 retry)
  • Features/ContextCenterMemories.spec.ts › clearing search restores the unfiltered list (shard 2, 1 retry)
  • Features/ContextCenterMemories.spec.ts › clicking a memory row adds ?memory= param to the URL (shard 2, 1 retry)
  • Features/ContextCenterMemories.spec.ts › copy link button copies URL containing the ?memory= param (shard 2, 1 retry)
  • Features/ContextCenterMemories.spec.ts › editing visibility from Shared to Private saves and updates the badge (shard 2, 1 retry)
  • Features/DataQuality/TestCaseImportExportBasic.spec.ts › should show validation errors for invalid CSV (shard 2, 1 retry)
  • Features/Glossary/GlossaryP3Tests.spec.ts › should handle multiple rapid API calls (shard 2, 1 retry)
  • Pages/DataContractsSemanticRules.spec.ts › Validate Description Rule Is_Set (shard 4, 1 retry)
  • Pages/ExplorePageRightPanel.spec.ts › Should verify deleted user not visible in owner selection for table (shard 6, 1 retry)
  • Pages/GlossaryImportExport.spec.ts › Import validation - missing required fields (shard 6, 1 retry)
  • Pages/GlossaryImportExport.spec.ts › Import partial success - some terms pass, some fail (shard 6, 1 retry)
  • Pages/GlossaryTermRightPanel.spec.ts › Should edit tags from glossary term assets context (shard 6, 1 retry)
  • Pages/GlossaryTermRightPanel.spec.ts › Should edit owners from glossary term assets context (shard 6, 1 retry)
  • Pages/Lineage/LineageFilters.spec.ts › Verify Impact Analysis service filter selection (shard 6, 1 retry)
  • Pages/Lineage/LineageRightPanel.spec.ts › Verify custom properties tab is NOT visible for pipelineService in platform lineage (shard 6, 1 retry)
  • Pages/Lineage/LineageRightPanel.spec.ts › Verify custom properties tab is NOT visible for apiService in platform lineage (shard 6, 1 retry)
  • Pages/TagPageRightPanel.spec.ts › Should open right panel when clicking asset in tag assets page (shard 6, 1 retry)
  • Pages/UserDetails.spec.ts › Admin user can get all the roles hierarchy and edit roles (shard 6, 1 retry)

📦 Download artifacts

How to debug locally
# Download playwright-test-results-<shard> artifact and unzip
npx playwright show-trace path/to/trace.zip    # view trace

Copilot AI review requested due to automatic review settings July 8, 2026 05:55
@gitar-bot

gitar-bot Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Code Review ⚠️ Changes requested 0 resolved / 1 findings

Introduces an AiProvider seam to decouple AI backends, but a ClassCastException in the provider resolution logic causes an unhandled crash if a misconfigured class is specified.

⚠️ Bug: Misconfigured non-AiProvider class crashes startup instead of falling back

📄 openmetadata-service/src/main/java/org/openmetadata/service/drive/AiProviderHolder.java:67-81

In resolveConfigured, the cast (AiProvider) clazz.getDeclaredConstructor().newInstance() (line 71) throws ClassCastException when the configured aiProviderClass names a class that exists on the classpath but does not implement AiProvider. ClassCastException is an unchecked RuntimeException, so it is caught by neither catch (ClassNotFoundException ...) nor catch (ReflectiveOperationException ...). The exception propagates out of build() (which is called lazily from get()), defeating the graceful-fallback contract now stated in the Javadoc and warn/error messages ("using the built-in LLM provider"). A distribution that wires in a wrong class name in llmConfiguration.aiProviderClass would crash the service rather than degrade to the OSS LlmAiProvider. The error-handling block around this cast is modified in this commit, so the fallback guarantee should cover this case too.

Use asSubclass for an early, descriptive failure and also catch ClassCastException so a wrong-type class falls back gracefully. Add a regression test covering a classpath class that does not implement AiProvider.
private static AiProvider resolveConfigured(final String className) {
    AiProvider resolved;
    try {
      final Class<? extends AiProvider> clazz =
          Class.forName(className).asSubclass(AiProvider.class);
      resolved = clazz.getDeclaredConstructor().newInstance();
      LOG.info("Using AI provider: {}", className);
    } catch (ClassNotFoundException notOnClasspath) {
      LOG.warn(
          "Configured aiProviderClass '{}' is not on the classpath; using the built-in LLM provider",
          className);
      resolved = new LlmAiProvider();
    } catch (ReflectiveOperationException | ClassCastException badProvider) {
      LOG.error(
          "Configured aiProviderClass '{}' could not be instantiated; using the built-in LLM provider",
          className,
          badProvider);
      resolved = new LlmAiProvider();
    }
    return resolved;
  }
🤖 Prompt for agents
Code Review: Introduces an AiProvider seam to decouple AI backends, but a ClassCastException in the provider resolution logic causes an unhandled crash if a misconfigured class is specified.

1. ⚠️ Bug: Misconfigured non-AiProvider class crashes startup instead of falling back
   Files: openmetadata-service/src/main/java/org/openmetadata/service/drive/AiProviderHolder.java:67-81

   In `resolveConfigured`, the cast `(AiProvider) clazz.getDeclaredConstructor().newInstance()` (line 71) throws `ClassCastException` when the configured `aiProviderClass` names a class that exists on the classpath but does not implement `AiProvider`. `ClassCastException` is an unchecked `RuntimeException`, so it is caught by neither `catch (ClassNotFoundException ...)` nor `catch (ReflectiveOperationException ...)`. The exception propagates out of `build()` (which is called lazily from `get()`), defeating the graceful-fallback contract now stated in the Javadoc and warn/error messages ("using the built-in LLM provider"). A distribution that wires in a wrong class name in `llmConfiguration.aiProviderClass` would crash the service rather than degrade to the OSS `LlmAiProvider`. The error-handling block around this cast is modified in this commit, so the fallback guarantee should cover this case too.

   Fix (Use asSubclass for an early, descriptive failure and also catch ClassCastException so a wrong-type class falls back gracefully. Add a regression test covering a classpath class that does not implement AiProvider.):
   private static AiProvider resolveConfigured(final String className) {
       AiProvider resolved;
       try {
         final Class<? extends AiProvider> clazz =
             Class.forName(className).asSubclass(AiProvider.class);
         resolved = clazz.getDeclaredConstructor().newInstance();
         LOG.info("Using AI provider: {}", className);
       } catch (ClassNotFoundException notOnClasspath) {
         LOG.warn(
             "Configured aiProviderClass '{}' is not on the classpath; using the built-in LLM provider",
             className);
         resolved = new LlmAiProvider();
       } catch (ReflectiveOperationException | ClassCastException badProvider) {
         LOG.error(
             "Configured aiProviderClass '{}' could not be instantiated; using the built-in LLM provider",
             className,
             badProvider);
         resolved = new LlmAiProvider();
       }
       return resolved;
     }

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

Comment on lines +70 to +72
final Class<?> clazz = Class.forName(className);
resolved = (AiProvider) clazz.getDeclaredConstructor().newInstance();
LOG.info("Using AI provider: {}", className);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Wrong type still escapes
When aiProviderClass names an existing class with a no-arg constructor that does not implement AiProvider, construction succeeds and this cast throws ClassCastException. That exception is not handled by the fallback block, so AiProviderHolder.get() can still fail instead of returning LlmAiProvider. A configuration mistake such as LLM_AI_PROVIDER_CLASS=java.lang.String can break the lazy file, page, or memory deriver setup.

Suggested change
final Class<?> clazz = Class.forName(className);
resolved = (AiProvider) clazz.getDeclaredConstructor().newInstance();
LOG.info("Using AI provider: {}", className);
final Class<?> clazz = Class.forName(className);
resolved = AiProvider.class.cast(clazz.getDeclaredConstructor().newInstance());
LOG.info("Using AI provider: {}", className);

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.

Pull request overview

Copilot reviewed 18 out of 19 changed files in this pull request and generated 1 comment.

Comment on lines +69 to +84
try {
final Class<?> clazz = Class.forName(className);
resolved = (AiProvider) clazz.getDeclaredConstructor().newInstance();
LOG.info("Using AI provider: {}", className);
} catch (ClassNotFoundException notOnClasspath) {
LOG.warn(
"Configured aiProviderClass '{}' is not on the classpath; using the built-in LLM provider",
className);
resolved = new LlmAiProvider();
} catch (ReflectiveOperationException badProvider) {
LOG.error(
"Configured aiProviderClass '{}' could not be instantiated; using the built-in LLM provider",
className,
badProvider);
resolved = new LlmAiProvider();
}
@sonarqubecloud

sonarqubecloud Bot commented Jul 8, 2026

Copy link
Copy Markdown

@sonarqubecloud

sonarqubecloud Bot commented Jul 8, 2026

Copy link
Copy Markdown

@pmbrull
pmbrull marked this pull request as draft July 10, 2026 11:22
@pmbrull pmbrull closed this Aug 25, 2026
timothybrush pushed a commit to timothybrush/OpenMetadata that referenced this pull request Sep 9, 2026
…nd an AiProvider seam (open-metadata#32524)

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

Re-lands the Context Center knowledge-pill extraction pipeline (engines,
reconciler, repository hooks, list filters, search-index fields) that open-metadata#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 (open-metadata#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 open-metadata#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]>

* Update generated TypeScript types and dereferenced schemas

* refactor(context): drive/ becomes context/center, entity-prompt context 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]>

* feat(context): reconciliation keeps pill identity across rephrasing and 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]>

* fix(context): review findings — batched memoryCount, throttle eviction, 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]>

* feat(context): memory extraction gets its own switch, independent of llmConfiguration.enabled

llmConfiguration.enabled turns on embeddings, Ontology Studio AI and every
other completion feature, so a deployment that enabled LLM features for
semantic search was also, silently, asking every upload and article edit to
spend model calls deriving knowledge pills.

Extraction now needs llmConfiguration.memoryExtractionEnabled as well
(LLMClientHolder.isMemoryExtractionEnabled = enabled AND extraction flag).
Off by default in OpenMetadata: extraction here is unmetered, so it is opt-in
and a large upload cannot become unbounded model spend on a self-hosted
deployment without someone asking for it. Ontology Studio AI and the RDF
endpoints keep reading isEnabled — this switch is extraction's alone.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Update generated TypeScript types and dereferenced schemas

* feat(context): restore the extracted-memories panel and status badges

The revert in open-metadata#30041 removed the UI half of knowledge-pill extraction while
this branch restored the backend. The memory -> source link survived (the view
modal renders sourceEntity), but the source -> memories direction did not, so
an article or file had no way to show what was derived from it.

Restores the deleted components as they were and re-wires their call sites:

- ExtractedMemoriesCard: lists a source's pills via
  GET /contextCenter/memories?sourceEntityId=..., opens each in the view modal
- ArticleStatusBadge / DocumentStatusBadge: extraction status, with the
  processing error (or partial chunk coverage) as a tooltip
- KnowledgePageDetailRightPanel: status row + collapsible memories card
- DocumentPreviewPanel: status row, processing-error row, memories card
- DocumentsView: "N memories" in the file row, status badge in the actions
- ContextMemoryListParams regains sourceFileId/sourceEntityId; KnowledgePage
  regains processingStatus/processingError

DocumentPreviewPanel also regains tw:min-h-0: the memories card is shrink-0,
so without it the flex child cannot shrink to the scroll container and the
panel body stops scrolling.

MemoryStatusBadge and DerivedOntologyCard are deliberately not restored. Both
render MemoryProcessingStatus, which tracks the Memory/Ontology Agent
derivation rather than pill extraction, and nothing in the service stamps it
on this branch — they would render nothing. The schema enum stays frozen, so
reviving them needs no schema change.

Tests: ExtractedMemoriesCard and KnowledgePageDetailRightPanel had no coverage
before and now do (fetch params, empty/error states, view modal, owner-based
delete permission, status row gating); DocumentPreviewPanel gains the status,
memories and error-row cases; the playwright spec regains its Status
assertion.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(context): stamp Processing when an article extraction run starts

PageProcessingStatus has always declared Processing, but nothing wrote it:
the pipeline went Queued -> Processed/Failed. Because the throttle coalesces
autosaves over a five-minute quiet period, the UI badge sat on Queued for
minutes and then jumped straight to Processed, with no way to tell a run in
flight from one still waiting.

Adds ContextProcessingEngine.markProcessing(UUID) -- a no-op by default,
called from runExtraction after the shouldProcess hash gate rather than at the
top, so an unchanged-content skip stays a single write instead of two.
PageContextProcessingEngine overrides it to stamp Processing.

FileContextProcessingEngine deliberately does not override it:
ContextFileProcessingService already owns the file status flow
(Uploaded -> Analyzing -> ExtractingContext -> Processed/Failed/Unsupported).

Cost is one extra version-free page write plus a reindex per real run, and
none per skip. Known gap, matching the in-memory throttle's existing
behaviour for Queued: a JVM death between the Processing stamp and the
terminal stamp leaves the article on Processing until its next body edit
re-arms the run.

The test helper that captured the single page write now captures all of them
and asserts on the last, since a real run writes twice.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(context): a deleted source leaves no knowledge pills behind

Hard-deleting a Context Center file left its pills in the database forever as
soft-deleted rows. A hard delete runs the soft-delete pass first, which
soft-deleted the pills; the hard pass then looked them up through
deleteExtractedMemories, whose findTo used the default Include.NON_DELETED and
so could not see the rows its own soft pass had just hidden. The result was
invisible tombstones that still held their FQNs and their search and vector
index entries -- exactly what the reconciler's deleteRetired comment argues
against.

deleteExtractedMemories now looks up with Include.ALL and always hard-deletes,
so both delete paths converge on the same outcome: no memories. A pill is
derived data, regenerable from its source, so it should not outlive the source
in any form. This also makes the behaviour consistent for pages, which cannot
soft-delete at all (page.json has no `deleted` property, so
supportsSoftDelete is false) and therefore only ever reached the hard hook.

restoreExtractedMemories and both restoreAdditionalChildren overrides are
removed: with the pills hard-deleted there is nothing left to un-delete. A
restored source is expected to re-derive its pills rather than resurrect
tombstones.

Covered by three ITs in ContextFileIT. They create pills through
POST /contextCenter/memories with sourceEntity set, which writes the same
MENTIONED_IN edge extraction does, so the cascade is exercised without a model
call.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(context): article extraction no longer deletes relatedEntities

Every extraction stamp silently wiped an article's related data assets and
bumped its version. PageContextProcessingEngine.getPage loaded the page with
getFields(""), which leaves the relationship-backed fields null; relatedEntities
is in KNOWLEDGE_UPDATE_FIELDS, so the updater read that null as a removal and
deleted the HAS rows. The article's own version history recorded it as
`fieldsDeleted: relatedEntities` on the first stamp of every run.

Loading getPutFields() instead makes the stamp a real read-modify-write, so
relatedEntities, parent and children round-trip untouched. This also removes the
version churn the surrounding comments say machine extraction avoids: the churn
was never processingStatus (already recorded with updateVersion=false), it was
the relationship deletion riding along with it.

FileContextProcessingEngine keeps getFields(""), which is correct there:
ContextFileRepository declares no patch/put fields, so a file has no
updater-managed relationship to lose. Confirmed against a running instance --
a file's folder survives extraction.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(context): the duplicate probe can actually return a hit

Cross-source dedup never fired. The probe passed the candidate's title,
question and answer joined as one query string, and the search layer applies
AND semantics to a bare query -- so every word had to occur in a single stored
memory. Any one non-matching token returned zero hits, which made
duplicateElsewhere unreachable and the "two documents stating one policy yield
one pill" guarantee false. Measured on a running instance with two identical
uploads: all seven pill pairs score 1.000 against the 0.85 gate, and the run
still logged `0 duplicates skipped`.

  q="Tier B Vendor Requirements"             -> 5 hits
  q="Tier B Vendor Requirements zzzqqqxyz"   -> 0 hits
  q=<the probe's own query>                  -> 0 hits

The query is now an OR of the candidate's distinct words, restoring
should-style recall. Precision is unaffected: the reconciler re-scores every
hit through the same deterministic Jaccard gate.

Recall draws on title and question only. The answer's generic prose dilutes
ranking -- including it, an exact duplicate placed 7th of the 10 hits fetched
and on a larger corpus would fall out of the window; title plus question ranks
that duplicate 2nd, which also matches the gate's own weighting of question
over answer. Tokenizing on non-word characters replaces the old operator
blacklist and is strictly safer: every clause is now a \w+ run, so candidate
text can neither break the query nor smuggle in a lucene operator.

The outage was invisible because the probe logs its failures at debug and
ContextMemoryReconcilerTest supplies a fake probe, so nothing exercised the
real query. New tests pin its shape, which is the whole of the defect.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(context): a rephrased question keeps its pill instead of churning it

Reconciliation matched a derived pill to a stored one using
DUPLICATE_THRESHOLD, the same 0.85 bar used to suppress a duplicate from
another source. That conflates two different questions. Suppressing a
duplicate means "another source already states this" and should demand
near-verbatim agreement; keeping identity means "the model rephrased my fact",
where 0.85 is far too strict -- so a single reworded question orphaned the
pill, and re-extraction deleted and recreated most of a document's pills,
losing their usageCount/lastUsedAt along the way.

Measured on a running instance: editing one number in a seven-pill article
produced 6 created, 1 updated, 1 kept, 5 deleted. Scoring each stored pill
against its best new match gives

  0.85 -> 2 of 7 keep identity
  0.70 -> 4 of 7
  0.50 -> 6 of 7

The seventh scores 0.175 because the model genuinely dropped that fact, so
retiring it is correct and 6 is the ceiling. Splitting out IDENTITY_THRESHOLD
at 0.5 reaches it with a wide margin over the true non-match (0.539 vs 0.175).
DUPLICATE_THRESHOLD stays at 0.85 for cross-source suppression.

The loose bar is safe because removeMostSimilar already claims the best match
above the bar rather than the first, so a weaker candidate cannot take a pill a
closer one should own -- now stated in its contract, since the bar no longer
makes a wrong match implausible on its own. Both measured pairs are covered by
tests.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(ui): extract nested ternary in ExtractedMemoriesCard to fix sonarjs/no-nested-conditional

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

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Rohit0301 <[email protected]>
Co-authored-by: Rohit Jain <[email protected]>

This branch was previously deployed

1 inactive deployment
test — a014ee2e Deployed Jul 8, 2026 by pmbrull via playwright-ci-postgresql (6, 6) #55264
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.

2 participants