Skip to content

feat(ai): AISettings + Memory Agent deriving glossary terms and metrics - #29201

Merged
harshach merged 56 commits into
mainfrom
pmbrull/ontology-agent-memory-derivation
Jun 23, 2026
Merged

harshach merged 56 commits into
mainfrom
pmbrull/ontology-agent-memory-derivation

Conversation

@pmbrull

@pmbrull pmbrull commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

Describe your changes:

Fixes #29285

I added an AISettings configuration plane and an Ontology Agent so that knowledge "memories" (ContextMemory) automatically become curated Glossary Terms and Metrics, with the full File → Memory → Term/Metric provenance preserved and a clean ownership lifecycle. I did this so the knowledge captured from Context Center files/pages stops being a dead-end and instead feeds the governed ontology, while giving admins one place to toggle every AI feature and tune every internal LLM system prompt.

Type of change:

  • New feature

High-level design:

Two layers, schema-first (JSON Schema → generated Java/TS):

  • AISettings (config plane): a SearchSettings-style settings entity (configuration/aiSettings.json → SettingsType.AI_SETTINGS → SettingsCache seed/merge via AISettingsHandler → SystemResource GET/PUT/reset → admin UI page under Preferences → AI). It carries a master enabled kill-switch, memoryExtraction.{fromFiles,fromPages} toggles, ontologyAgent.{enabled,deriveGlossaryTerms,deriveMetrics,deletionPolicy}, and editable system prompts. The previously hardcoded extraction prompt now lives in settings (the code constant remains the cache-miss fallback). File/page extraction now additionally gate on AISettings.

  • Ontology Agent: on ContextMemory create/update, OntologyProcessingEngine (throttled, hash-gated) grounds the memory against the existing instance ontology (top-K keyword search over the glossary-term/metric indexes), then OntologyExtractor asks the LLM for a per-axis verdict and OntologyReconciler applies it: REUSE an existing entity (RELATED_TO edge, not owned), CREATE a new one (provider=automation, new DERIVED_FROM relationship, minting a glossary if none fits), or SKIP. Writes as a dedicated ontology-bot.

  • Ownership lifecycle: provider=automation = agent-owned. Adopt-on-touch flips it to user on a human PATCH of a managed field (the agent then never re-manages it). On memory delete, owned entities follow deletionPolicy (cascade/orphan/deprecate) via pre-cleanup *AdditionalChildren hooks; reused links are just dropped. Recursion is prevented by a content hash-gate (the stat stamp is updateVersion=false; the hash-gate is load-bearing).

  • Alternatives / compatibility: reuses ContextMemory rather than a new entity (consistent with the existing knowledge-pill feature); no DDL migration (generic JSON-column tables + the generic entity_relationship table; DERIVED_FROM appended last to preserve enum ordinals); no fixed default glossary (the agent picks the best existing one or mints one).

Tests:

Use cases covered

  • Admin reads/updates/resets AI settings; disabling a toggle stops the corresponding extraction/derivation.
  • Memory that maps to an existing term/metric → linked (RELATED_TO), nothing created.
  • Memory with no match → new Term (in best-fit or minted glossary) / Metric created provider=automation, linked DERIVED_FROM.
  • Deleting a memory cascades its agent-owned derivations (default policy); a human-edited derivation is released and survives the delete.

Unit tests

  • Added. Backend: AISettingsHandlerTest (3), AISettingsUtilTest (4), OntologyDerivationTest (1), OntologyExtractorTest (2), OntologyReconcilerTest (20), OntologyProcessingEngineTest (2), OntologyOwnershipTest (7). UI: AISettingsPage.test.tsx, DerivedOntologyCard.test.tsx.

Backend integration tests

  • Added in openmetadata-integration-tests/: AISettingsResourceIT (GET/PUT/reset, 3/3) and OntologyAgentIT (cascade, adopt-on-touch, provenance projections, 3/3) — both green against a real DB. These caught two critical product bugs the mocked unit tests could not: a missing SettingsType case in CollectionDAO.SettingsRowMapper (empty AISettings GET) and missing id/updatedAt on agent-created entities (NOT-NULL failure on PostgreSQL); both fixed.

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not added — UI covered by Jest component tests (AISettingsPage, DerivedOntologyCard); Playwright E2E to follow if required.

Manual testing performed

The integration tests exercise the end-to-end flows (settings round-trip, derivation, cascade, adopt-on-touch) against a real DB via Testcontainers.

UI screen recording / screenshots:

UI changes present (AISettings admin page + "Derived ontology"/"Derived from" provenance panels). Screen recording to be attached by the author (could not capture in this environment).

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: no migration needed (generic JSON-column storage + generic entity_relationship; DERIVED_FROM appended last to preserve ordinals).
  • For UI changes: screen recording/screenshots to be attached by the author.
  • I have added tests (unit / integration as applicable) and listed them above.
  • I have added tests around the new logic.

Greptile Summary

This PR introduces an AISettings configuration plane and an Ontology Agent that automatically derives Glossary Terms and Metrics from ContextMemory entries, preserving full Memory → Term/Metric provenance via DERIVED_FROM edges and a clean ownership lifecycle (provider=automation, adopt-on-touch, configurable deletion policy).

  • AISettings: a new settings entity (AI_SETTINGS type) seeded and merged at startup via SettingsCache, exposed through SystemResource GET/PUT/reset endpoints, and consumed by AISettingsUtil to gate all extraction and derivation paths.
  • Ontology Agent pipeline: OntologyProcessingEngine (debounced, hash-gated, single-threaded scheduler) → OntologyGrounding (top-K search over existing terms/metrics/glossaries) → OntologyExtractor (LLM verdict) → OntologyReconciler (REUSE/CREATE/SKIP with FQN prechecks for terms and metrics, glossary minting, retirement by deletion policy).
  • Ownership lifecycle: GlossaryTermRepository and MetricRepository gain OntologyOwnership.releaseIfHumanEdited adopt-on-touch guards; ContextMemoryRepository gains cancel + cascadeOntology hooks on soft/hard delete and a restore hook.

Confidence Score: 3/5

The new ontology pipeline has two correctness gaps in OntologyReconciler that should be addressed before merging.

Glossary minting in resolveOrMintByName lacks the collision-resistant precheck that was explicitly retrofitted onto term and metric creation in previous rounds. In a multi-node deployment, two concurrent derivation runs that both need to mint the same new glossary name will race; the loser's createInternal throws, is caught by reconcileSafely, stamps the content hash, and permanently abandons that memory's derivation with no user-visible signal. Additionally, agent-minted glossaries carry provider=AUTOMATION but are never tracked via DERIVED_FROM edges and are omitted from onMemoryDeleted, so empty agent-owned glossaries accumulate indefinitely when memories are deleted.

OntologyReconciler.java — glossary mint collision handling and retirement on memory deletion.

Important Files Changed

Filename Overview
openmetadata-service/src/main/java/org/openmetadata/service/drive/ontology/OntologyReconciler.java Core reconciliation logic — correctly handles term/metric REUSE/CREATE/SKIP verdicts with FQN prechecks and adopt-on-touch ownership, but glossary minting lacks the same collision-resistant precheck applied to terms/metrics, and agent-minted glossaries are never retired when their source memory is deleted.
openmetadata-service/src/main/java/org/openmetadata/service/drive/ontology/OntologyProcessingEngine.java Orchestrates scheduling, hash-gating, and derivation; per-axis flags (deriveGlossaryTerms/deriveMetrics) are now correctly threaded into reconcile; hash-gate recursion prevention is sound.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextMemoryRepository.java Adds ontology lifecycle hooks (schedule/cancel/cascade on create/update/delete/restore) and provenance field projections; stampOntologyStats uses ADMIN_USER_NAME instead of the ontology bot, causing misleading audit attribution.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GlossaryTermRepository.java Adds derivedFrom provenance field and adopt-on-touch ownership release; logic is correct.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/MetricRepository.java Adds derivedFrom provenance field and adopt-on-touch ownership release; mirrors GlossaryTermRepository correctly.
openmetadata-service/src/main/java/org/openmetadata/service/util/AISettingsUtil.java Stateless utility for reading AISettings from cache with safe fallback; per-axis checks and deletion policy resolution are correct.
openmetadata-service/src/main/java/org/openmetadata/service/resources/system/SystemResource.java Adds GET/PUT/reset endpoints for AISettings following the SearchSettings pattern; reset correctly replaces stored value and invalidates cache.
openmetadata-service/src/main/java/org/openmetadata/service/resources/settings/SettingsCache.java Seeds AISettings on startup with merge-into-defaults logic; handles missing stored settings and no-op updates correctly.
openmetadata-service/src/main/java/org/openmetadata/service/util/OntologyOwnership.java Correctly implements adopt-on-touch: only releases AUTOMATION-owned entities on PATCH when a managed field changes and updater is not the ontology bot.
openmetadata-service/src/main/java/org/openmetadata/service/drive/ontology/OntologyGrounding.java Keyword-searches glossary term, metric, and glossary indexes for top-K candidates; search failures are isolated per-axis.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant CM as ContextMemory (create/update)
    participant CMR as ContextMemoryRepository
    participant OPE as OntologyProcessingEngine
    participant OG as OntologyGrounding
    participant OE as OntologyExtractor (LLM)
    participant OR as OntologyReconciler
    participant GTR as GlossaryTermRepo
    participant MR as MetricRepository
    participant GR as GlossaryRepository

    CM->>CMR: postCreate / postUpdate
    CMR->>OPE: schedule(memoryId) [if agent enabled]
    Note over OPE: quiet period (5 min debounce)
    OPE->>CMR: get(memoryId)
    OPE->>OPE: hashOf(memory) — skip if unchanged
    OPE->>OG: fetchCandidates(memory)
    OG-->>OPE: OntologyContext (terms, metrics, glossaries)
    OPE->>OE: derive(memory, context)
    OE-->>OPE: OntologyDerivation (termVerdict, metricVerdict)

    alt REUSE verdict
        OPE->>OR: reconcile(...)
        OR->>GTR: addRelationship(RELATED_TO)
    else CREATE verdict
        OPE->>OR: reconcile(...)
        OR->>GR: resolveOrMintGlossary
        OR->>GTR: createInternal + addRelationship(DERIVED_FROM)
        OR->>MR: createInternal + addRelationship(DERIVED_FROM)
    else SKIP verdict
        OPE->>OR: reconcile(...)
        Note over OR: no-op (protects against LLM failure)
    end

    OPE->>CMR: stampOntologyStats(hash) → postUpdate → re-schedule
    Note over OPE: next run exits via hash-gate (unchanged)

    CM->>CMR: delete(memoryId)
    CMR->>OPE: cancel(memoryId)
    CMR->>OR: onMemoryDeleted(CASCADE/ORPHAN/DEPRECATE)
    OR->>GTR: retire owned terms
    OR->>MR: retire owned metrics
    Note over OR: ⚠ agent-minted Glossary not retired
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant CM as ContextMemory (create/update)
    participant CMR as ContextMemoryRepository
    participant OPE as OntologyProcessingEngine
    participant OG as OntologyGrounding
    participant OE as OntologyExtractor (LLM)
    participant OR as OntologyReconciler
    participant GTR as GlossaryTermRepo
    participant MR as MetricRepository
    participant GR as GlossaryRepository

    CM->>CMR: postCreate / postUpdate
    CMR->>OPE: schedule(memoryId) [if agent enabled]
    Note over OPE: quiet period (5 min debounce)
    OPE->>CMR: get(memoryId)
    OPE->>OPE: hashOf(memory) — skip if unchanged
    OPE->>OG: fetchCandidates(memory)
    OG-->>OPE: OntologyContext (terms, metrics, glossaries)
    OPE->>OE: derive(memory, context)
    OE-->>OPE: OntologyDerivation (termVerdict, metricVerdict)

    alt REUSE verdict
        OPE->>OR: reconcile(...)
        OR->>GTR: addRelationship(RELATED_TO)
    else CREATE verdict
        OPE->>OR: reconcile(...)
        OR->>GR: resolveOrMintGlossary
        OR->>GTR: createInternal + addRelationship(DERIVED_FROM)
        OR->>MR: createInternal + addRelationship(DERIVED_FROM)
    else SKIP verdict
        OPE->>OR: reconcile(...)
        Note over OR: no-op (protects against LLM failure)
    end

    OPE->>CMR: stampOntologyStats(hash) → postUpdate → re-schedule
    Note over OPE: next run exits via hash-gate (unchanged)

    CM->>CMR: delete(memoryId)
    CMR->>OPE: cancel(memoryId)
    CMR->>OR: onMemoryDeleted(CASCADE/ORPHAN/DEPRECATE)
    OR->>GTR: retire owned terms
    OR->>MR: retire owned metrics
    Note over OR: ⚠ agent-minted Glossary not retired
Loading

Reviews (4): Last reviewed commit: "fix(ui): align AISettingsPage to codegen..." | Re-trigger Greptile


Summary by Gitar

  • Configuration plane:
    • Centralized MCP chat settings into AISettings and added McpChatServiceHolder for runtime toggling without application re-installation.
  • UI/UX enhancements:
    • Added AISettingsPage to manage memory extraction and ontology derivation toggles, including MCP chat and server configurations.
    • Implemented MemoryStatusBadge and DerivedOntologyCard to track and visualize derivation provenance and processing errors.
    • Added UI support to display derivedFrom links on Glossary Term and Metric detail pages.
  • Core logic & refactoring:
    • Renamed internal Ontology components to Memory domain for consistency.
    • Added MemoryProcessingEngine to handle debounced ontology derivation with hash-gate recursion protection.
    • Introduced MemoryReconciler to manage entity ownership lifecycles (provider=automation vs user-adopted).
  • Integration:
    • Added comprehensive integration tests (MemoryAgentIT, AISettingsResourceIT) to validate lifecycle hooks and configuration persistence.
  • Internationalization:
    • Updated localization files across 20+ languages to include new AI and memory management labels.

This will update automatically on new commits.

pmbrull and others added 22 commits June 18, 2026 15:48
…ats, AISettings schema

- Append DERIVED_FROM as last entry in entityRelationship.json enum (ordinal-safe)
- Add provider (ProviderType) field to metric.json and createMetric.json
- Add ontologyStats definition and property to contextMemory.json (OntologyStats javaType)
- Create configuration/aiSettings.json (AISettings, MemoryExtractionSettings, OntologyAgentSettings, PromptConfig, AIPrompts, AIDeletionPolicy)
- Register aiSettings in settings.json enum and config_value oneOf
- Add default seed openmetadata-service/src/main/resources/json/data/settings/aiSettings.json

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…EST branch

Implements Task 2: AISettingsHandler (validate + merge), SettingsCache
seed/merge block for aiSettings.json mirroring searchSettings, and
SystemResource PUT branch + reset extension for AI_SETTINGS.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…n reset

- loadDefaultAiSettings now declares throws IOException instead of
  swallowing it with an empty AISettings fallback; call sites in
  createOrUpdateSetting and resetSettingToDefault wrap with try/catch
  and re-throw as SystemSettingsException (matching the searchSettings
  error-handling pattern)
- resetSettingToDefault refactored to if/else-if/else with a single
  trailing return, eliminating the two early returns
- AISettingsHandlerTest: add incomingNullReturnsDefaults and
  nullNestedDefaultInheritsIncoming tests covering null-guard branches

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… extraction prompt

- Add AISettingsUtil: cache-backed AISettings accessor (never null, fails open)
  with isFileExtractionEnabled, isPageExtractionEnabled, isOntologyAgentEnabled,
  memoryExtractionPrompt, ontologyAgentPrompt helpers
- ContextMemoryExtractor.callLlm resolves the system prompt from AISettings at
  runtime, falling back to the SYSTEM_PROMPT constant
- ContextFileProcessingService.process and fileStatusAfterText gate on
  AISettingsUtil.isFileExtractionEnabled in addition to LLMClientHolder.isEnabled
- KnowledgePageRepository.schedulePillExtraction gates on
  AISettingsUtil.isPageExtractionEnabled in addition to LLMClientHolder.isEnabled
- TDD: AISettingsUtilTest written first (RED), then implementation (GREEN)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add OntologyDerivation, OntologyVerdict (Jackson record DTOs with @JsonProperty on every component and @JsonIgnoreProperties), and OntologyAction constants (REUSE/CREATE/SKIP) as the anti-corruption boundary between untrusted LLM JSON and the domain model. Mirrors the KnowledgePill pattern. Covered by OntologyDerivationTest (lenient parse, unknown-field tolerance).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Add OntologyContext/OntologyCandidate records, OntologyExtractor (calls LLM via completeStructured, returns SKIP/SKIP on empty result), OntologyPromptBuilder (renders memory + candidate lists), and OntologyGrounding (keyword-searches glossary-term/metric/glossary indexes via Entity.getSearchRepository, caps at 20, fails-safe per axis). Covered by OntologyExtractorTest (mocked LLM, two cases: verdict passthrough + empty-→SKIP/SKIP).

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

Replace raw "_score"/"desc" with SearchConstants.DEFAULT_SORT_FIELD/DEFAULT_SORT_ORDER,
remove local FIELD_NAME/FIELD_DESCRIPTION in favour of Entity constants, dedupe
nullToEmpty via StringUtils.defaultString, extract renderMemory() so build() fits 15
lines, use CommonUtil.nullOrEmpty for the candidates guard, and replace raw "CREATE"/"SKIP"
string literals in tests with OntologyAction constants.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…retire/cascade)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e-derive, no-op on all-SKIP

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adds OntologyProcessingEngine: a trailing-throttle debounce (mirroring
PageContextProcessingEngine) that collapses rapid memory edits into one
derivation run, protected by a SHA-256 content hash-gate so unchanged
memories are never re-derived. stampOntologyStats persists via
recordChange(updateVersion=false) in ContextMemoryUpdater, exactly
mirroring KnowledgePageRepository.recordExtractionStats, so no version
churn occurs and no postUpdate event fires for the stats field.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nts, dedup scheduler

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

postCreate/postUpdate schedule the OntologyProcessingEngine (gated on
AISettingsUtil.isOntologyAgentEnabled). softDelete/hardDelete/restore
AdditionalChildren fire in-edge-window so DERIVED_FROM edges exist when
OntologyReconciler.onMemoryDeleted/onMemoryRestored run. Extracted
AISettingsUtil.deletionPolicy() to remove duplication between the engine
and the repository. Added OntologyReconciler.onMemoryRestored which
restores CASCADE-soft-deleted automation-owned entities (Include.ALL
query; ORPHAN/DEPRECATE-released entities correctly excluded because
their DERIVED_FROM edges were dropped at delete time). Three new unit
tests cover: owned restore, human-adopted skip, orphan-released skip.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adds the ontology-bot principal seed files (bot + botUser JSON, auto-loaded
by BotResource.initialize at startup), the OntologyOwnership utility class
(centralized ONTOLOGY_BOT_NAME constant + releaseIfHumanEdited guard), and
wires the guard into the entitySpecificUpdate of GlossaryTermUpdater,
MetricUpdater and GlossaryUpdater so a human PATCH that changes an
agent-managed field flips provider AUTOMATION → USER permanently.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Adds the AISettingsPage under Settings > Preferences with master enable
toggle, memory-extraction and ontology-agent toggles, a deletion-policy
Select, and two system-prompt Textareas. Registers the route, menu item,
and all i18n keys (synced to all 17 locales).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Replace raw string literals ('cascade'/'orphan'/'deprecate') in
DELETION_POLICY_OPTIONS with i18n labelKey fields; add new keys
label.cascade / label.deprecate / label.orphan to en-us.json (alphabetical)
and sync all 17 other locales via yarn i18n.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Add three read-only derived fields (non-default, resolved at read, never
persisted) to expose File→Memory→Term/Metric provenance:

- ContextMemory.derivedEntities (entityReferenceList): terms+metrics
  created by the Ontology Agent via DERIVED_FROM edges
  (findFrom(memory, CONTEXT_MEMORY, DERIVED_FROM, GLOSSARY_TERM/METRIC))
- ContextMemory.reusedEntities (entityReferenceList): terms+metrics
  reused via RELATED_TO edges
  (findTo(memory, CONTEXT_MEMORY, RELATED_TO, GLOSSARY_TERM/METRIC))
- GlossaryTerm.derivedFrom (entityReference): memory that created the term
  (findTo(term, GLOSSARY_TERM, DERIVED_FROM, CONTEXT_MEMORY))
- Metric.derivedFrom (entityReference): memory that created the metric
  (findTo(metric, METRIC, DERIVED_FROM, CONTEXT_MEMORY))

Edge directions verified against OntologyReconciler Task-6 code:
addDerivedFromEdge stores from=entity→to=memory; reuse() stores
from=memory→to=entity for RELATED_TO.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
AISettingsResourceIT: deterministic GET/PUT/reset tests for /system/settings/aiSettings
covering default values (enabled=true, deletionPolicy=cascade), PUT persistence, and reset.

OntologyAgentIT: deterministic lifecycle tests seeding DERIVED_FROM edges via in-process
repository to replicate the reconciler's CREATE path, then driving cascade delete,
adopt-on-touch (provider flip), and derivedFrom/derivedEntities projection fields through
the public REST API without any LLM dependency.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- Add derivedEntities/reusedEntities to ContextMemory generated type
- Add derivedFrom to GlossaryTerm and Metric generated types
- Add DERIVED_FROM/DERIVED_ENTITIES/REUSED_ENTITIES to TabSpecificField enum
- Add getContextMemoryById to contextMemoryAPI
- Create DerivedOntologyCard component (+ interface + test): fetches
  derivedEntities/reusedEntities from a memory and renders linked lists
- Embed DerivedOntologyCard into CreateMemoryModal view-only mode so
  every memory's derived/reused ontology is visible when viewing a memory
- Add derivedFrom field to GLOSSARY_TERM_DEFAULT_FIELDS and METRIC_DEFAULT_FIELDS
- Add "Derived from memory" link in GlossaryTermsV1 and MetricDetails when
  derivedFrom is present on the entity
- Add i18n keys: label.derived-from-memory, label.derived-ontology,
  label.reused, message.no-derived-ontology (synced to 19 locales)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ttings returns defaults

CollectionDAO$SettingsRowMapper.getSettings lacked an AI_SETTINGS case in its
switch, causing every getConfigWithKey("aiSettings") call to throw
IllegalArgumentException (swallowed, returning null) → HTTP 204 on every GET.
Added the missing case so aiSettings rows deserialise to AISettings.

Also fixed resetSettingToDefault for AI_SETTINGS: it was returning defaults
without persisting them to the DB (unlike the equivalent searchSettings reset
path which calls systemRepository.createOrUpdate). Now it persists first.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…edAt so cascade, adopt-on-touch, and projection ITs all pass

The test helper createAutomationTerm used create-via-REST + termRepo.update to
set provider=AUTOMATION, but the EntityRepository update framework only writes to
DB when entityChanged=true; provider is not tracked by recordChange so the write
was silently no-op'd. Term stayed provider=null in the DB, causing:
- Scenario A timeout: isAutomationOwned read null, cascade skipped the term
- Scenario B: assertEquals(USER, null) failed at assertion after human PATCH
- Scenario C: cascade skipped term, glossary.delete failed with "glossary is not empty"

Fix: replace the two-step seed with termRepo.createInternal() directly, mirroring
OntologyReconciler.createTerm exactly. Also fixed the reconciler itself: createTerm,
createMetric, and resolveOrMintGlossary all called createInternal without setting id
or updatedAt; PostgreSQL GENERATED columns extract both from the stored JSON with
NOT NULL constraints, so omitting them would cause constraint failures in production.

Result: OntologyAgentIT 3/3 GREEN; OntologyReconcilerTest 20/20 + OntologyOwnershipTest
7/7 no regression.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ontext spec

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@pmbrull
pmbrull requested a review from a team as a code owner June 18, 2026 19:44
Copilot AI review requested due to automatic review settings June 18, 2026 19:44
@github-actions

github-actions Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

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

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 Ingestion safe to test Add this label to run secure Github workflows on PRs labels Jun 18, 2026
@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.

siddhant1 and others added 3 commits June 22, 2026 16:11
…TL (#29268)

The SSO Session Renewal suite swaps the server to a short SAML JWT TTL before
logging in. At 10s, on a loaded CI runner the initial app bootstrap
(loggedInUser, config, permissions) outran that window, so the first
/permissions fetch 401'd mid-load; the silent refresh succeeded but the
bootstrap request was not retried, leaving the app wedged on the global loading
spinner. dropdown-profile never rendered and the renewal tests timed out,
exhausting all retries on the 2026-06-22 nightly (run 27929661599).

- Raise SHORT_ACCESS_TTL_SECONDS 10 -> 30 so the token outlives bootstrap. 30s
  stays under EXPIRY_THRESHOLD_MILLES (60s), so the proactive-renewal timer
  still fires immediately and the refresh-on-expiry behavior under test is
  unchanged.
- Wait for dropdown-profile at the end of loginViaSaml so login is only "done"
  once the app shell has rendered, making any future bootstrap hang fail in
  beforeAll with a clear cause instead of mid-test.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
- AISettings.spec: MCP Server section now exposes only Enable + Origin Header
  URI (path/originValidation removed), so assert/fill the origin header instead
  of the removed mcp-server-path field.
- McpChat.spec: enable MCP Chat via aiSettings.mcpChat.enabled (PUT
  /system/settings) and reset it afterwards, instead of installing the retired
  McpChatApplication app (which now 404s).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@pmbrull
pmbrull requested a review from a team as a code owner June 22, 2026 14:12
Copilot AI review requested due to automatic review settings June 22, 2026 14: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.

@pmbrull pmbrull changed the title feat(ai): AISettings + Ontology Agent deriving glossary terms and metrics feat(ai): AISettings + Memory Agent deriving glossary terms and metrics Jun 22, 2026
@sonarqubecloud

Copy link
Copy Markdown

@sonarqubecloud

Copy link
Copy Markdown

@harshach
harshach merged commit 9870104 into main Jun 23, 2026
59 of 62 checks passed
@harshach
harshach deleted the pmbrull/ontology-agent-memory-derivation branch June 23, 2026 03:04
@gitar-bot

gitar-bot Bot commented Jun 23, 2026

Copy link
Copy Markdown
Code Review 👍 Approved with suggestions 12 resolved / 13 findings

Introduces an AISettings configuration plane and Ontology Agent to automate glossary and metric derivation from context memories. Addressing the remaining concerns about glossary minting race conditions and orphaned glossaries upon memory deletion is recommended.

💡 Bug: McpChatServiceHolder.initialize closes service used by in-flight chats

📄 openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/McpChatServiceHolder.java:31-45 📄 openmetadata-service/src/main/java/org/openmetadata/service/resources/mcpclient/McpClientResource.java:316-324

McpChatServiceHolder.initialize() (called on every AI-settings PUT/reset via reinitMcpChatServiceIfNeeded) calls closeQuietly(instance) on the previous McpClientService and swaps in a new one. A concurrent request that already obtained the old reference via getService()->McpChatServiceHolder.get() may continue to use a now-closed service (e.g., a streaming chat in McpClientResource.chatStream), potentially causing runtime errors mid-conversation when an admin saves settings. Since instance/enabled are read separately, getService() can also briefly observe enabled=true while the new instance is being built. The null-check downstream mitigates the latter, but in-flight requests against the closed instance are not guarded. This is a low-probability concurrency edge during settings changes; consider deferring close until outstanding requests drain or making the service resilient to close-during-use.

✅ 12 resolved
✅ Bug: Possible NPE when LLM returns null verdict list

📄 openmetadata-service/src/main/java/org/openmetadata/service/drive/ontology/OntologyExtractor.java:40-50
OntologyExtractor.derive calls verdicts.isEmpty() on the result of llmClient.completeStructured(...) without a null check. If the client can return null (e.g. on a malformed/empty completion) rather than an empty list, this throws NPE. The exception is caught only by runScheduled's broad catch and logged, so the memory is never stamped and the run repeats on each edit. Guard with nullOrEmpty(verdicts) and fall back to empty().

✅ Bug: deriveGlossaryTerms/deriveMetrics toggles have no effect

📄 openmetadata-service/src/main/java/org/openmetadata/service/drive/ontology/OntologyReconciler.java:100-114 📄 openmetadata-service/src/main/java/org/openmetadata/service/resources/system/AISettingsHandler.java:61-65 📄 openmetadata-service/src/main/java/org/openmetadata/service/util/AISettingsUtil.java:48-52 📄 openmetadata-service/src/main/java/org/openmetadata/service/drive/ontology/OntologyProcessingEngine.java:175-189 📄 openmetadata-service/src/main/java/org/openmetadata/service/resources/system/AISettingsHandler.java:55-69
The ontologyAgent.deriveGlossaryTerms and ontologyAgent.deriveMetrics settings are surfaced in the schema (aiSettings.json), persisted, merged (AISettingsHandler), and exposed as UI toggles (AISettingsPage.tsx), but they are never read by the derivation pipeline. A grep shows getDeriveGlossaryTerms()/getDeriveMetrics() are referenced only inside AISettingsHandler.mergeAgent. OntologyProcessingEngine, OntologyExtractor, and OntologyReconciler gate only on AISettingsUtil.isOntologyAgentEnabled (master enabled + ontologyAgent.enabled). As a result, disabling deriveGlossaryTerms or deriveMetrics does NOT stop the agent from creating glossary terms / metrics — both axes are always reconciled. This directly contradicts the PR description ("disabling a toggle stops the corresponding extraction/derivation") and leaves admins unable to limit the agent to one axis. Recommend gating applyTermAxis/applyMetricAxis (or the extractor prompt) on these flags.

✅ Edge Case: Glossary minted with unvalidated LLM-supplied name

📄 openmetadata-service/src/main/java/org/openmetadata/service/drive/ontology/OntologyReconciler.java:151-165
OntologyReconciler.resolveOrMintGlossary mints a new Glossary using verdict.newGlossaryName() / verdict.newGlossaryDescription() directly from the LLM, with no null/blank validation. Similarly createTerm/createMetric build entities with verdict.name() unchecked. If the LLM emits a CREATE verdict with no targetFqn glossary match and a null/blank newGlossaryName (or a null entity name), createInternal will fail validation, the exception propagates out of reconcile, the memory is never stamped with ontologyStats, and every subsequent edit re-triggers the same failing derivation. Recommend validating these fields and treating a CREATE verdict with insufficient data as SKIP (logged) rather than letting it throw.

✅ Quality: derivedFrom link ignores memory id, points to generic list

📄 openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryTerms/GlossaryTermsV1.component.tsx:303-314 📄 openmetadata-ui/src/main/resources/ui/src/components/Metric/MetricDetails/MetricDetails.tsx:331-342
In both GlossaryTermsV1 and MetricDetails the new "Derived from memory" link routes to ROUTES.CONTEXT_CENTER_MEMORIES (the generic memories list) regardless of which memory the entity was derived from. The derivedFrom reference (with its id/fqn) is available but not used to deep-link to the specific source memory, so the provenance link does not actually navigate users to the originating memory. Consider building a per-memory route from glossaryTerm.derivedFrom/metricDetails.derivedFrom.

✅ Quality: Hardcoded Tailwind colors instead of design tokens

📄 openmetadata-ui/src/main/resources/ui/src/components/ContextCenter/DerivedOntologyCard/DerivedOntologyCard.component.tsx:58-67 📄 openmetadata-ui/src/main/resources/ui/src/components/ContextCenter/DerivedOntologyCard/DerivedOntologyCard.component.tsx:129-143 📄 openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryTerms/GlossaryTermsV1.component.tsx:305-310 📄 openmetadata-ui/src/main/resources/ui/src/components/Metric/MetricDetails/MetricDetails.tsx:333-338 📄 openmetadata-ui/src/main/resources/ui/src/components/ContextCenter/DerivedOntologyCard/DerivedOntologyCard.component.tsx:130-144 📄 openmetadata-ui/src/main/resources/ui/src/components/Glossary/GlossaryTerms/GlossaryTermsV1.component.tsx:305-312
New UI components hardcode palette colors/spacing via Tailwind utility classes (e.g. tw:text-gray-500, tw:text-gray-400, tw:text-brand-600) rather than referencing the project's CSS custom-property design tokens, which the repository frontend guidelines require ("Reference CSS custom properties/tokens; never hardcode colors/spacing"). This appears in the new DerivedOntologyCard and the derived-from links in GlossaryTermsV1 / MetricDetails. Recommend mapping these to the shared token classes used elsewhere.

...and 7 more resolved from earlier reviews

🤖 Prompt for agents
Code Review: Introduces an AISettings configuration plane and Ontology Agent to automate glossary and metric derivation from context memories. Addressing the remaining concerns about glossary minting race conditions and orphaned glossaries upon memory deletion is recommended.

1. 💡 Bug: McpChatServiceHolder.initialize closes service used by in-flight chats
   Files: openmetadata-service/src/main/java/org/openmetadata/service/mcpclient/McpChatServiceHolder.java:31-45, openmetadata-service/src/main/java/org/openmetadata/service/resources/mcpclient/McpClientResource.java:316-324

   McpChatServiceHolder.initialize() (called on every AI-settings PUT/reset via reinitMcpChatServiceIfNeeded) calls closeQuietly(instance) on the previous McpClientService and swaps in a new one. A concurrent request that already obtained the old reference via getService()->McpChatServiceHolder.get() may continue to use a now-closed service (e.g., a streaming chat in McpClientResource.chatStream), potentially causing runtime errors mid-conversation when an admin saves settings. Since instance/enabled are read separately, getService() can also briefly observe enabled=true while the new instance is being built. The null-check downstream mitigates the latter, but in-flight requests against the closed instance are not guarded. This is a low-probability concurrency edge during settings changes; consider deferring close until outstanding requests drain or making the service resilient to close-during-use.

Options

Display: compact → Showing less information.

Comment with these commands to change:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar

harshach added a commit that referenced this pull request Jun 24, 2026
The CollectionDAO decomposition moved SettingsRowMapper into
SystemTokenDAOs.java. Upstream #29201 later added
`case AI_SETTINGS -> readValue(json, AISettings.class)` to the original
switch in CollectionDAO.java; the --ours merge resolution for that file
silently dropped the addition and it was never ported to the relocated
mapper. The switch therefore fell through to
`default -> throw IllegalArgumentException("Invalid Settings Type aiSettings")`
at runtime — a runtime-only drop the green cross-module compile could not catch.

SettingsCache.initialize() reads AI_SETTINGS outside its try block (whose
catch is IOException-only), so once an aiSettings row exists the throw
aborts the whole initializer, leaving later settings unseeded. This broke
AISettingsResourceIT, McpChatResourceIT (503 "MCP Chat is not enabled" +
Jackson "No content to map"), and CompanyContextPipelineIT (memory agent
silently disabled).

Restore the AI_SETTINGS case and its import. Verified by an exhaustive
content sweep of the split (all switch case-labels, all 2021 SQL fragments,
all method names) that AI_SETTINGS was the only unintended drop.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
pmbrull added a commit that referenced this pull request Jul 15, 2026
…s/Memory Agent (#30041)

* revert(ai): remove AISettings + Memory/Ontology Agent (#29201)

Removes the AISettings config plane and the Memory/Ontology Agent that
derived glossary terms and metrics from ContextMemory. Keeps the
ContextMemory entity (schemas frozen), CreateContextMemoryTool, and the
Persona AI Context feature that reads ContextMemory. Restores the base
McpApplication files #29201 had refactored away.

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

* revert(context): remove page knowledge-pill extraction (#29119)

Reverts the Context Center *page* extraction pipeline (generic
ContextProcessingEngine + File/Page engines, ContextMemoryReconciler,
sourceEntity generalization, ExtractedMemoriesCard UI). Keeps the frozen
ContextMemory/ContextFile/Page schemas, file-side sourceFile handling
(removed later with #28973), and all follow-on work (pinning, pagination,
attachment widget, ui-core-components migration).

This reverts commit 506c8c9.

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

* chore(ai): keep metric.json/createMetric.json schema frozen

Extends the D1 schema-freeze decision to the Metric schema: the AI revert
(#29201) removed the Memory/Ontology Agent *code* that populated Metric's
'derivedFrom'/'provider', but the JSON schema fields are left intact (inert)
so re-introducing the feature later needs no schema change. Verified the
service compiles with the fields present and unused.

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

* revert(context-center): remove file knowledge-pill extraction (#28973)

Removes the file extraction pipeline (ContextFileProcessingService,
ContextMemoryExtractor, the LLM completion-client layer, KnowledgePill,
DocumentStatusBadge UI) and restores the pre-#28973 ContextFileExtractionService
stub. Keeps the 3 MCP context tools (Get/Search/CreateContextMemory), the
object-storage upload + /system/validate stack (D3), and the frozen
ContextMemory/ContextFile schemas (D1).

This reverts commit 03530b2.

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

* revert(mcp): remove MCP Chat client, conversation tracking, chat UI (#26343, #29169)

Removes the MCP Chat feature: chat client service (mcpclient/*), the chat
LLM-client layer (clients/llm/* except LlmConfigHolder), McpConversation/
McpMessage entities+repos+resource+schemas, McpChatApplication, the chat UI
(McpChatPage, /mcp-chat routes) and its playwright spec (#29169), and the
mcp_conversation/mcp_message tables.

KEPT (now load-bearing for semantic-search embeddings, not chat):
llmConfiguration.json + LlmConfigHolder + OpenMetadataApplicationConfig.
llmConfiguration — the vector-embedding stack (SystemRepository, the
*EmbeddingClient family, OpenSearchBulkSink, #29678 AI Context Platform)
depends on it, so a wholesale revert would break semantic search.

Follow-up UI reconciliation (package.json deps, locale keys, ApplicationsProvider,
generated TS) lands in the codegen/i18n commit.

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

* revert(ui): reconcile MCP-chat/AI UI removal + checkstyle

Finalizes the UI side of the reverts: removes the residual MCP-chat route,
plugin, and provider state; reverse-applies #26343's UI wiring (sidebar,
constants, ApplicationsClassBase); restores getContextMemoryById (still used
by the surviving memories page); fixes the DocumentPreviewPanel status-row
JSX left by the badge removal; and runs the organize-imports + eslint +
prettier sequence. Locale files and orphaned i18n keys are intentionally left
in place (harmless, re-introduction-friendly, in-sync).

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

* Update generated TypeScript types

* fix(revert): keep full objectStorage config for file upload

The extraction revert (#28973) over-reverted objectStorage down to a NOOP
stub, but file upload (ContextFile) survives and needs the full
s3/azure/env-overridable config (D3). Restore it to main's version. Net conf
diff is now only the llmConfiguration comment, updated to reference its
surviving consumer (semantic-search embeddings) instead of the removed
extraction/MCP-chat.

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

* minor fix

* lint fix

* fixed playwright test

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Rohit0301 <[email protected]>

This branch was previously deployed

1 inactive deployment
test — 4f3b452e Deployed Jun 22, 2026 by pmbrull via playwright-ci-postgresql (5, 6) #52424
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.

Memory Agent & AI Settings